istereo

changeset 26:862a3329a8f0

wohooo, added a shitload of code from zlib/libpng/libjpeg. When the good lord was raining shared libraries the iphone held a fucking umbrella...
author John Tsiombikas <nuclear@mutantstargoat.com>
date Thu, 08 Sep 2011 06:28:38 +0300
parents 206348366635
children fd39c0198935
files Makefile libs/Makefile libs/imago2/conv.c libs/imago2/file_jpeg.c libs/imago2/file_png.c libs/imago2/file_ppm.c libs/imago2/ftype_module.c libs/imago2/ftype_module.h libs/imago2/imago2.c libs/imago2/imago2.h libs/imago2/modules.c libs/libjpeg/cderror.h libs/libjpeg/jcapimin.c libs/libjpeg/jcapistd.c libs/libjpeg/jccoefct.c libs/libjpeg/jccolor.c libs/libjpeg/jcdctmgr.c libs/libjpeg/jchuff.c libs/libjpeg/jchuff.h libs/libjpeg/jcinit.c libs/libjpeg/jcmainct.c libs/libjpeg/jcmarker.c libs/libjpeg/jcmaster.c libs/libjpeg/jcomapi.c libs/libjpeg/jconfig.h libs/libjpeg/jcparam.c libs/libjpeg/jcphuff.c libs/libjpeg/jcprepct.c libs/libjpeg/jcsample.c libs/libjpeg/jctrans.c libs/libjpeg/jdapimin.c libs/libjpeg/jdapistd.c libs/libjpeg/jdatadst.c libs/libjpeg/jdatasrc.c libs/libjpeg/jdcoefct.c libs/libjpeg/jdcolor.c libs/libjpeg/jdct.h libs/libjpeg/jddctmgr.c libs/libjpeg/jdhuff.c libs/libjpeg/jdhuff.h libs/libjpeg/jdinput.c libs/libjpeg/jdmainct.c libs/libjpeg/jdmarker.c libs/libjpeg/jdmaster.c libs/libjpeg/jdmerge.c libs/libjpeg/jdphuff.c libs/libjpeg/jdpostct.c libs/libjpeg/jdsample.c libs/libjpeg/jdtrans.c libs/libjpeg/jerror.c libs/libjpeg/jerror.h libs/libjpeg/jfdctflt.c libs/libjpeg/jfdctfst.c libs/libjpeg/jfdctint.c libs/libjpeg/jidctflt.c libs/libjpeg/jidctfst.c libs/libjpeg/jidctint.c libs/libjpeg/jidctred.c libs/libjpeg/jinclude.h libs/libjpeg/jmemmgr.c libs/libjpeg/jmemnobs.c libs/libjpeg/jmemsys.h libs/libjpeg/jmorecfg.h libs/libjpeg/jpegint.h libs/libjpeg/jpeglib.h libs/libjpeg/jquant1.c libs/libjpeg/jquant2.c libs/libjpeg/jutils.c libs/libjpeg/jversion.h libs/libpng/png.c libs/libpng/png.h libs/libpng/pngconf.h libs/libpng/pngerror.c libs/libpng/pnggccrd.c libs/libpng/pngget.c libs/libpng/pngmem.c libs/libpng/pngpread.c libs/libpng/pngread.c libs/libpng/pngrio.c libs/libpng/pngrtran.c libs/libpng/pngrutil.c libs/libpng/pngset.c libs/libpng/pngtrans.c libs/libpng/pngvcrd.c libs/libpng/pngwio.c libs/libpng/pngwrite.c libs/libpng/pngwtran.c libs/libpng/pngwutil.c libs/zlib/adler32.c libs/zlib/compress.c libs/zlib/crc32.c libs/zlib/crc32.h libs/zlib/deflate.c libs/zlib/deflate.h libs/zlib/gzio.c libs/zlib/infback.c libs/zlib/inffast.c libs/zlib/inffast.h libs/zlib/inffixed.h libs/zlib/inflate.c libs/zlib/inflate.h libs/zlib/inftrees.c libs/zlib/inftrees.h libs/zlib/trees.c libs/zlib/trees.h libs/zlib/uncompr.c libs/zlib/zconf.h libs/zlib/zlib.h libs/zlib/zutil.c libs/zlib/zutil.h src/istereo.c src/tex.c
diffstat 112 files changed, 62060 insertions(+), 47 deletions(-) [+]
line diff
     1.1 --- a/Makefile	Thu Sep 08 04:23:56 2011 +0300
     1.2 +++ b/Makefile	Thu Sep 08 06:28:38 2011 +0300
     1.3 @@ -1,14 +1,28 @@
     1.4  src = $(wildcard src/*.c)
     1.5 +
     1.6  obj = $(src:.c=.o)
     1.7 +dep = $(obj:.o=.d)
     1.8  bin = test
     1.9  
    1.10  CC = gcc
    1.11 -CFLAGS = -pedantic -Wall -g
    1.12 +CFLAGS = -pedantic -Wall -g $(incdir)
    1.13  LDFLAGS = -lGL -lGLU -lglut -lGLEW -lm
    1.14  
    1.15 +include libs/Makefile
    1.16 +
    1.17  $(bin): $(obj)
    1.18  	$(CC) -o $@ $(obj) $(LDFLAGS)
    1.19  
    1.20 +-include $(dep)
    1.21 +
    1.22 +%.d: %.c
    1.23 +	@$(CPP) $(CFLAGS) -MM -MT $(@:.d=.o) $< >$@
    1.24 +
    1.25 +
    1.26  .PHONY: clean
    1.27  clean:
    1.28  	rm -f $(obj) $(bin)
    1.29 +
    1.30 +.PHONY: cleandep
    1.31 +cleandep:
    1.32 +	rm -f $(dep)
     2.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.2 +++ b/libs/Makefile	Thu Sep 08 06:28:38 2011 +0300
     2.3 @@ -0,0 +1,6 @@
     2.4 +src += $(wildcard libs/zlib/*.c) \
     2.5 +	   $(wildcard libs/libpng/*.c) \
     2.6 +	   $(wildcard libs/libjpeg/*.c) \
     2.7 +	   $(wildcard libs/imago2/*.c)
     2.8 +
     2.9 +incdir += -Ilibs/imago2 -Ilibs/zlib -Ilibs/libpng -Ilibs/libjpeg
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/libs/imago2/conv.c	Thu Sep 08 06:28:38 2011 +0300
     3.3 @@ -0,0 +1,251 @@
     3.4 +/*
     3.5 +libimago - a multi-format image file input/output library.
     3.6 +Copyright (C) 2010 John Tsiombikas <nuclear@member.fsf.org>
     3.7 +
     3.8 +This program is free software: you can redistribute it and/or modify
     3.9 +it under the terms of the GNU Lesser General Public License as published
    3.10 +by the Free Software Foundation, either version 3 of the License, or
    3.11 +(at your option) any later version.
    3.12 +
    3.13 +This program is distributed in the hope that it will be useful,
    3.14 +but WITHOUT ANY WARRANTY; without even the implied warranty of
    3.15 +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    3.16 +GNU Lesser General Public License for more details.
    3.17 +
    3.18 +You should have received a copy of the GNU Lesser General Public License
    3.19 +along with this program.  If not, see <http://www.gnu.org/licenses/>.
    3.20 +*/
    3.21 +#include <string.h>
    3.22 +#include "imago2.h"
    3.23 +
    3.24 +/* pixel-format conversions are sub-optimal at the moment to avoid
    3.25 + * writing a lot of code. optimize at some point ?
    3.26 + */
    3.27 +
    3.28 +#define CLAMP(x, a, b)	((x) < (a) ? (a) : ((x) > (b) ? (b) : (x)))
    3.29 +
    3.30 +struct pixel {
    3.31 +	float r, g, b, a;
    3.32 +};
    3.33 +
    3.34 +static void unpack_grey8(struct pixel *unp, void *pptr, int count);
    3.35 +static void unpack_rgb24(struct pixel *unp, void *pptr, int count);
    3.36 +static void unpack_rgba32(struct pixel *unp, void *pptr, int count);
    3.37 +static void unpack_greyf(struct pixel *unp, void *pptr, int count);
    3.38 +static void unpack_rgbf(struct pixel *unp, void *pptr, int count);
    3.39 +static void unpack_rgbaf(struct pixel *unp, void *pptr, int count);
    3.40 +
    3.41 +static void pack_grey8(void *pptr, struct pixel *unp, int count);
    3.42 +static void pack_rgb24(void *pptr, struct pixel *unp, int count);
    3.43 +static void pack_rgba32(void *pptr, struct pixel *unp, int count);
    3.44 +static void pack_greyf(void *pptr, struct pixel *unp, int count);
    3.45 +static void pack_rgbf(void *pptr, struct pixel *unp, int count);
    3.46 +static void pack_rgbaf(void *pptr, struct pixel *unp, int count);
    3.47 +
    3.48 +/* XXX keep in sync with enum img_fmt at imago2.h */
    3.49 +static void (*unpack[])(struct pixel*, void*, int) = {
    3.50 +	unpack_grey8,
    3.51 +	unpack_rgb24,
    3.52 +	unpack_rgba32,
    3.53 +	unpack_greyf,
    3.54 +	unpack_rgbf,
    3.55 +	unpack_rgbaf
    3.56 +};
    3.57 +
    3.58 +/* XXX keep in sync with enum img_fmt at imago2.h */
    3.59 +static void (*pack[])(void*, struct pixel*, int) = {
    3.60 +	pack_grey8,
    3.61 +	pack_rgb24,
    3.62 +	pack_rgba32,
    3.63 +	pack_greyf,
    3.64 +	pack_rgbf,
    3.65 +	pack_rgbaf
    3.66 +};
    3.67 +
    3.68 +
    3.69 +int img_convert(struct img_pixmap *img, enum img_fmt tofmt)
    3.70 +{
    3.71 +	struct pixel pbuf[8];
    3.72 +	int bufsz = (img->width & 7) == 0 ? 8 : ((img->width & 3) == 0 ? 4 : 1);
    3.73 +	int i, num_pix = img->width * img->height;
    3.74 +	int num_iter = num_pix / bufsz;
    3.75 +	char *sptr, *dptr;
    3.76 +	struct img_pixmap nimg;
    3.77 +
    3.78 +	if(img->fmt == tofmt) {
    3.79 +		return 0;	/* nothing to do */
    3.80 +	}
    3.81 +
    3.82 +	img_init(&nimg);
    3.83 +	if(img_set_pixels(&nimg, img->width, img->height, tofmt, 0) == -1) {
    3.84 +		img_destroy(&nimg);
    3.85 +		return -1;
    3.86 +	}
    3.87 +
    3.88 +	sptr = img->pixels;
    3.89 +	dptr = nimg.pixels;
    3.90 +
    3.91 +	for(i=0; i<num_iter; i++) {
    3.92 +		unpack[img->fmt](pbuf, sptr, bufsz);
    3.93 +		pack[tofmt](dptr, pbuf, bufsz);
    3.94 +
    3.95 +		sptr += bufsz * img->pixelsz;
    3.96 +		dptr += bufsz * nimg.pixelsz;
    3.97 +	}
    3.98 +
    3.99 +	img_copy(img, &nimg);
   3.100 +	img_destroy(&nimg);
   3.101 +	return 0;
   3.102 +}
   3.103 +
   3.104 +/* the following functions *could* benefit from SIMD */
   3.105 +
   3.106 +static void unpack_grey8(struct pixel *unp, void *pptr, int count)
   3.107 +{
   3.108 +	int i;
   3.109 +	unsigned char *pix = pptr;
   3.110 +
   3.111 +	for(i=0; i<count; i++) {
   3.112 +		unp->r = unp->g = unp->b = (float)*pix++ / 255.0;
   3.113 +		unp->a = 1.0;
   3.114 +		unp++;
   3.115 +	}
   3.116 +}
   3.117 +
   3.118 +static void unpack_rgb24(struct pixel *unp, void *pptr, int count)
   3.119 +{
   3.120 +	int i;
   3.121 +	unsigned char *pix = pptr;
   3.122 +
   3.123 +	for(i=0; i<count; i++) {
   3.124 +		unp->r = (float)*pix++ / 255.0;
   3.125 +		unp->g = (float)*pix++ / 255.0;
   3.126 +		unp->b = (float)*pix++ / 255.0;
   3.127 +		unp->a = 1.0;
   3.128 +		unp++;
   3.129 +	}
   3.130 +}
   3.131 +
   3.132 +static void unpack_rgba32(struct pixel *unp, void *pptr, int count)
   3.133 +{
   3.134 +	memcpy(unp, pptr, count * sizeof *unp);
   3.135 +}
   3.136 +
   3.137 +static void unpack_greyf(struct pixel *unp, void *pptr, int count)
   3.138 +{
   3.139 +	int i;
   3.140 +	float *pix = pptr;
   3.141 +
   3.142 +	for(i=0; i<count; i++) {
   3.143 +		unp->r = unp->g = unp->b = *pix++;
   3.144 +		unp->a = 1.0;
   3.145 +		unp++;
   3.146 +	}
   3.147 +}
   3.148 +
   3.149 +static void unpack_rgbf(struct pixel *unp, void *pptr, int count)
   3.150 +{
   3.151 +	int i;
   3.152 +	float *pix = pptr;
   3.153 +
   3.154 +	for(i=0; i<count; i++) {
   3.155 +		unp->r = *pix++;
   3.156 +		unp->g = *pix++;
   3.157 +		unp->b = *pix++;
   3.158 +		unp->a = 1.0;
   3.159 +		unp++;
   3.160 +	}
   3.161 +}
   3.162 +
   3.163 +static void unpack_rgbaf(struct pixel *unp, void *pptr, int count)
   3.164 +{
   3.165 +	int i;
   3.166 +	float *pix = pptr;
   3.167 +
   3.168 +	for(i=0; i<count; i++) {
   3.169 +		unp->r = *pix++;
   3.170 +		unp->g = *pix++;
   3.171 +		unp->b = *pix++;
   3.172 +		unp->a = *pix++;
   3.173 +		unp++;
   3.174 +	}
   3.175 +}
   3.176 +
   3.177 +
   3.178 +static void pack_grey8(void *pptr, struct pixel *unp, int count)
   3.179 +{
   3.180 +	int i;
   3.181 +	unsigned char *pix = pptr;
   3.182 +
   3.183 +	for(i=0; i<count; i++) {
   3.184 +		int lum = (int)(255.0 * (unp->r + unp->g + unp->b) / 3.0);
   3.185 +		*pix++ = CLAMP(lum, 0, 255);
   3.186 +		unp++;
   3.187 +	}
   3.188 +}
   3.189 +
   3.190 +static void pack_rgb24(void *pptr, struct pixel *unp, int count)
   3.191 +{
   3.192 +	int i;
   3.193 +	unsigned char *pix = pptr;
   3.194 +
   3.195 +	for(i=0; i<count; i++) {
   3.196 +		int r = (int)(unp->r * 255.0);
   3.197 +		int g = (int)(unp->g * 255.0);
   3.198 +		int b = (int)(unp->b * 255.0);
   3.199 +
   3.200 +		*pix++ = CLAMP(r, 0, 255);
   3.201 +		*pix++ = CLAMP(g, 0, 255);
   3.202 +		*pix++ = CLAMP(b, 0, 255);
   3.203 +		unp++;
   3.204 +	}
   3.205 +}
   3.206 +
   3.207 +static void pack_rgba32(void *pptr, struct pixel *unp, int count)
   3.208 +{
   3.209 +	int i;
   3.210 +	unsigned char *pix = pptr;
   3.211 +
   3.212 +	for(i=0; i<count; i++) {
   3.213 +		int r = (int)(unp->r * 255.0);
   3.214 +		int g = (int)(unp->g * 255.0);
   3.215 +		int b = (int)(unp->b * 255.0);
   3.216 +		int a = (int)(unp->a * 255.0);
   3.217 +
   3.218 +		*pix++ = CLAMP(r, 0, 255);
   3.219 +		*pix++ = CLAMP(g, 0, 255);
   3.220 +		*pix++ = CLAMP(b, 0, 255);
   3.221 +		*pix++ = CLAMP(a, 0, 255);
   3.222 +		unp++;
   3.223 +	}
   3.224 +}
   3.225 +
   3.226 +static void pack_greyf(void *pptr, struct pixel *unp, int count)
   3.227 +{
   3.228 +	int i;
   3.229 +	float *pix = pptr;
   3.230 +
   3.231 +	for(i=0; i<count; i++) {
   3.232 +		*pix++ = (unp->r + unp->g + unp->b) / 3.0;
   3.233 +		unp++;
   3.234 +	}
   3.235 +}
   3.236 +
   3.237 +static void pack_rgbf(void *pptr, struct pixel *unp, int count)
   3.238 +{
   3.239 +	int i;
   3.240 +	float *pix = pptr;
   3.241 +
   3.242 +	for(i=0; i<count; i++) {
   3.243 +		*pix++ = unp->r;
   3.244 +		*pix++ = unp->g;
   3.245 +		*pix++ = unp->b;
   3.246 +		unp++;
   3.247 +	}
   3.248 +}
   3.249 +
   3.250 +static void pack_rgbaf(void *pptr, struct pixel *unp, int count)
   3.251 +{
   3.252 +	memcpy(pptr, unp, count * sizeof *unp);
   3.253 +}
   3.254 +
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/libs/imago2/file_jpeg.c	Thu Sep 08 06:28:38 2011 +0300
     4.3 @@ -0,0 +1,291 @@
     4.4 +/*
     4.5 +libimago - a multi-format image file input/output library.
     4.6 +Copyright (C) 2010 John Tsiombikas <nuclear@member.fsf.org>
     4.7 +
     4.8 +This program is free software: you can redistribute it and/or modify
     4.9 +it under the terms of the GNU Lesser General Public License as published
    4.10 +by the Free Software Foundation, either version 3 of the License, or
    4.11 +(at your option) any later version.
    4.12 +
    4.13 +This program is distributed in the hope that it will be useful,
    4.14 +but WITHOUT ANY WARRANTY; without even the implied warranty of
    4.15 +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    4.16 +GNU Lesser General Public License for more details.
    4.17 +
    4.18 +You should have received a copy of the GNU Lesser General Public License
    4.19 +along with this program.  If not, see <http://www.gnu.org/licenses/>.
    4.20 +*/
    4.21 +
    4.22 +/* -- JPEG module -- */
    4.23 +
    4.24 +#include <stdio.h>
    4.25 +#include <stdlib.h>
    4.26 +#include <string.h>
    4.27 +
    4.28 +#ifdef WIN32
    4.29 +#include <windows.h>
    4.30 +#define HAVE_BOOLEAN
    4.31 +#endif
    4.32 +
    4.33 +#include <jpeglib.h>
    4.34 +#include "imago2.h"
    4.35 +#include "ftype_module.h"
    4.36 +
    4.37 +#define INPUT_BUF_SIZE	512
    4.38 +#define OUTPUT_BUF_SIZE	512
    4.39 +
    4.40 +/* data source manager: adapted from jdatasrc.c */
    4.41 +struct src_mgr {
    4.42 +	struct jpeg_source_mgr pub;
    4.43 +
    4.44 +	struct img_io *io;
    4.45 +	unsigned char buffer[INPUT_BUF_SIZE];
    4.46 +	int start_of_file;
    4.47 +};
    4.48 +
    4.49 +/* data destination manager: adapted from jdatadst.c */
    4.50 +struct dst_mgr {
    4.51 +	struct jpeg_destination_mgr pub;
    4.52 +
    4.53 +	struct img_io *io;
    4.54 +	unsigned char buffer[OUTPUT_BUF_SIZE];
    4.55 +};
    4.56 +
    4.57 +static int check(struct img_io *io);
    4.58 +static int read(struct img_pixmap *img, struct img_io *io);
    4.59 +static int write(struct img_pixmap *img, struct img_io *io);
    4.60 +
    4.61 +/* read source functions */
    4.62 +static void init_source(j_decompress_ptr jd);
    4.63 +static int fill_input_buffer(j_decompress_ptr jd);
    4.64 +static void skip_input_data(j_decompress_ptr jd, long num_bytes);
    4.65 +static void term_source(j_decompress_ptr jd);
    4.66 +
    4.67 +/* write destination functions */
    4.68 +static void init_destination(j_compress_ptr jc);
    4.69 +static int empty_output_buffer(j_compress_ptr jc);
    4.70 +static void term_destination(j_compress_ptr jc);
    4.71 +
    4.72 +int img_register_jpeg(void)
    4.73 +{
    4.74 +	static struct ftype_module mod = {".jpg", check, read, write};
    4.75 +	return img_register_module(&mod);
    4.76 +}
    4.77 +
    4.78 +
    4.79 +static int check(struct img_io *io)
    4.80 +{
    4.81 +	unsigned char sig[10];
    4.82 +
    4.83 +	long pos = io->seek(0, SEEK_CUR, io->uptr);
    4.84 +
    4.85 +	if(io->read(sig, 10, io->uptr) < 10) {
    4.86 +		io->seek(pos, SEEK_SET, io->uptr);
    4.87 +		return -1;
    4.88 +	}
    4.89 +
    4.90 +	if(memcmp(sig, "\xff\xd8\xff\xe0", 4) != 0 || memcmp(sig + 6, "JFIF", 4) != 0) {
    4.91 +		io->seek(pos, SEEK_SET, io->uptr);
    4.92 +		return -1;
    4.93 +	}
    4.94 +	io->seek(pos, SEEK_SET, io->uptr);
    4.95 +	return 0;
    4.96 +}
    4.97 +
    4.98 +static int read(struct img_pixmap *img, struct img_io *io)
    4.99 +{
   4.100 +	int i, nlines = 0;
   4.101 +	struct jpeg_decompress_struct cinfo;
   4.102 +	struct jpeg_error_mgr jerr;
   4.103 +	struct src_mgr src;
   4.104 +	unsigned char **scanlines;
   4.105 +
   4.106 +	cinfo.err = jpeg_std_error(&jerr);	/* XXX change... */
   4.107 +	jpeg_create_decompress(&cinfo);
   4.108 +
   4.109 +	src.pub.init_source = init_source;
   4.110 +	src.pub.fill_input_buffer = fill_input_buffer;
   4.111 +	src.pub.skip_input_data = skip_input_data;
   4.112 +	src.pub.resync_to_restart = jpeg_resync_to_restart;
   4.113 +	src.pub.term_source = term_source;
   4.114 +	src.pub.next_input_byte = 0;
   4.115 +	src.pub.bytes_in_buffer = 0;
   4.116 +	src.io = io;
   4.117 +	cinfo.src = (struct jpeg_source_mgr*)&src;
   4.118 +
   4.119 +	jpeg_read_header(&cinfo, 1);
   4.120 +	cinfo.out_color_space = JCS_RGB;
   4.121 +
   4.122 +	if(img_set_pixels(img, cinfo.image_width, cinfo.image_height, IMG_FMT_RGB24, 0) == -1) {
   4.123 +		jpeg_destroy_decompress(&cinfo);
   4.124 +		return -1;
   4.125 +	}
   4.126 +
   4.127 +	if(!(scanlines = malloc(img->height * sizeof *scanlines))) {
   4.128 +		jpeg_destroy_decompress(&cinfo);
   4.129 +		return -1;
   4.130 +	}
   4.131 +	scanlines[0] = img->pixels;
   4.132 +	for(i=1; i<img->height; i++) {
   4.133 +		scanlines[i] = scanlines[i - 1] + img->width * img->pixelsz;
   4.134 +	}
   4.135 +
   4.136 +	jpeg_start_decompress(&cinfo);
   4.137 +	while(nlines < img->height) {
   4.138 +		int res = jpeg_read_scanlines(&cinfo, scanlines + nlines, img->height - nlines);
   4.139 +		nlines += res;
   4.140 +	}
   4.141 +	jpeg_finish_decompress(&cinfo);
   4.142 +	jpeg_destroy_decompress(&cinfo);
   4.143 +
   4.144 +	free(scanlines);
   4.145 +	return 0;
   4.146 +}
   4.147 +
   4.148 +static int write(struct img_pixmap *img, struct img_io *io)
   4.149 +{
   4.150 +	int i, nlines = 0;
   4.151 +	struct jpeg_compress_struct cinfo;
   4.152 +	struct jpeg_error_mgr jerr;
   4.153 +	struct dst_mgr dest;
   4.154 +	struct img_pixmap tmpimg;
   4.155 +	unsigned char **scanlines;
   4.156 +
   4.157 +	img_init(&tmpimg);
   4.158 +
   4.159 +	if(img->fmt != IMG_FMT_RGB24) {
   4.160 +		if(img_copy(&tmpimg, img) == -1) {
   4.161 +			return -1;
   4.162 +		}
   4.163 +		if(img_convert(&tmpimg, IMG_FMT_RGB24) == -1) {
   4.164 +			img_destroy(&tmpimg);
   4.165 +			return -1;
   4.166 +		}
   4.167 +		img = &tmpimg;
   4.168 +	}
   4.169 +
   4.170 +	if(!(scanlines = malloc(img->height * sizeof *scanlines))) {
   4.171 +		img_destroy(&tmpimg);
   4.172 +		return -1;
   4.173 +	}
   4.174 +	scanlines[0] = img->pixels;
   4.175 +	for(i=1; i<img->height; i++) {
   4.176 +		scanlines[i] = scanlines[i - 1] + img->width * img->pixelsz;
   4.177 +	}
   4.178 +
   4.179 +	cinfo.err = jpeg_std_error(&jerr);	/* XXX */
   4.180 +	jpeg_create_compress(&cinfo);
   4.181 +
   4.182 +	dest.pub.init_destination = init_destination;
   4.183 +	dest.pub.empty_output_buffer = empty_output_buffer;
   4.184 +	dest.pub.term_destination = term_destination;
   4.185 +	dest.io = io;
   4.186 +	cinfo.dest = (struct jpeg_destination_mgr*)&dest;
   4.187 +
   4.188 +	cinfo.image_width = img->width;
   4.189 +	cinfo.image_height = img->height;
   4.190 +	cinfo.input_components = 3;
   4.191 +	cinfo.in_color_space = JCS_RGB;
   4.192 +
   4.193 +	jpeg_set_defaults(&cinfo);
   4.194 +
   4.195 +	jpeg_start_compress(&cinfo, 1);
   4.196 +	while(nlines < img->height) {
   4.197 +		int res = jpeg_write_scanlines(&cinfo, scanlines + nlines, img->height - nlines);
   4.198 +		nlines += res;
   4.199 +	}
   4.200 +	jpeg_finish_compress(&cinfo);
   4.201 +	jpeg_destroy_compress(&cinfo);
   4.202 +
   4.203 +	free(scanlines);
   4.204 +	img_destroy(&tmpimg);
   4.205 +	return 0;
   4.206 +}
   4.207 +
   4.208 +/* -- read source functions --
   4.209 + * the following functions are adapted from jdatasrc.c in jpeglib
   4.210 + */
   4.211 +static void init_source(j_decompress_ptr jd)
   4.212 +{
   4.213 +	struct src_mgr *src = (struct src_mgr*)jd->src;
   4.214 +	src->start_of_file = 1;
   4.215 +}
   4.216 +
   4.217 +static int fill_input_buffer(j_decompress_ptr jd)
   4.218 +{
   4.219 +	struct src_mgr *src = (struct src_mgr*)jd->src;
   4.220 +	size_t nbytes;
   4.221 +
   4.222 +	nbytes = src->io->read(src->buffer, INPUT_BUF_SIZE, src->io->uptr);
   4.223 +
   4.224 +	if(nbytes <= 0) {
   4.225 +		if(src->start_of_file) {
   4.226 +			return 0;
   4.227 +		}
   4.228 +		/* insert a fake EOI marker */
   4.229 +		src->buffer[0] = 0xff;
   4.230 +		src->buffer[1] = JPEG_EOI;
   4.231 +		nbytes = 2;
   4.232 +	}
   4.233 +
   4.234 +	src->pub.next_input_byte = src->buffer;
   4.235 +	src->pub.bytes_in_buffer = nbytes;
   4.236 +	src->start_of_file = 0;
   4.237 +	return 1;
   4.238 +}
   4.239 +
   4.240 +static void skip_input_data(j_decompress_ptr jd, long num_bytes)
   4.241 +{
   4.242 +	struct src_mgr *src = (struct src_mgr*)jd->src;
   4.243 +
   4.244 +	if(num_bytes > 0) {
   4.245 +		while(num_bytes > (long)src->pub.bytes_in_buffer) {
   4.246 +			num_bytes -= (long)src->pub.bytes_in_buffer;
   4.247 +			fill_input_buffer(jd);
   4.248 +		}
   4.249 +		src->pub.next_input_byte += (size_t)num_bytes;
   4.250 +		src->pub.bytes_in_buffer -= (size_t)num_bytes;
   4.251 +	}
   4.252 +}
   4.253 +
   4.254 +static void term_source(j_decompress_ptr jd)
   4.255 +{
   4.256 +	/* nothing to see here, move along */
   4.257 +}
   4.258 +
   4.259 +
   4.260 +/* -- write destination functions --
   4.261 + * the following functions are adapted from jdatadst.c in jpeglib
   4.262 + */
   4.263 +static void init_destination(j_compress_ptr jc)
   4.264 +{
   4.265 +	struct dst_mgr *dest = (struct dst_mgr*)jc->dest;
   4.266 +
   4.267 +	dest->pub.next_output_byte = dest->buffer;
   4.268 +	dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
   4.269 +}
   4.270 +
   4.271 +static int empty_output_buffer(j_compress_ptr jc)
   4.272 +{
   4.273 +	struct dst_mgr *dest = (struct dst_mgr*)jc->dest;
   4.274 +
   4.275 +	if(dest->io->write(dest->buffer, OUTPUT_BUF_SIZE, dest->io->uptr) != OUTPUT_BUF_SIZE) {
   4.276 +		return 0;
   4.277 +	}
   4.278 +
   4.279 +	dest->pub.next_output_byte = dest->buffer;
   4.280 +	dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
   4.281 +	return 1;
   4.282 +}
   4.283 +
   4.284 +static void term_destination(j_compress_ptr jc)
   4.285 +{
   4.286 +	struct dst_mgr *dest = (struct dst_mgr*)jc->dest;
   4.287 +	size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
   4.288 +
   4.289 +	/* write any remaining data in the buffer */
   4.290 +	if(datacount > 0) {
   4.291 +		dest->io->write(dest->buffer, datacount, dest->io->uptr);
   4.292 +	}
   4.293 +	/* XXX flush? ... */
   4.294 +}
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/libs/imago2/file_png.c	Thu Sep 08 06:28:38 2011 +0300
     5.3 @@ -0,0 +1,244 @@
     5.4 +/*
     5.5 +libimago - a multi-format image file input/output library.
     5.6 +Copyright (C) 2010 John Tsiombikas <nuclear@member.fsf.org>
     5.7 +
     5.8 +This program is free software: you can redistribute it and/or modify
     5.9 +it under the terms of the GNU Lesser General Public License as published
    5.10 +by the Free Software Foundation, either version 3 of the License, or
    5.11 +(at your option) any later version.
    5.12 +
    5.13 +This program is distributed in the hope that it will be useful,
    5.14 +but WITHOUT ANY WARRANTY; without even the implied warranty of
    5.15 +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    5.16 +GNU Lesser General Public License for more details.
    5.17 +
    5.18 +You should have received a copy of the GNU Lesser General Public License
    5.19 +along with this program.  If not, see <http://www.gnu.org/licenses/>.
    5.20 +*/
    5.21 +
    5.22 +/* -- PNG module -- */
    5.23 +
    5.24 +#include <stdlib.h>
    5.25 +#include <png.h>
    5.26 +#include "imago2.h"
    5.27 +#include "ftype_module.h"
    5.28 +
    5.29 +static int check_file(struct img_io *io);
    5.30 +static int read_file(struct img_pixmap *img, struct img_io *io);
    5.31 +static int write_file(struct img_pixmap *img, struct img_io *io);
    5.32 +
    5.33 +static void read_func(png_struct *png, unsigned char *data, size_t len);
    5.34 +static void write_func(png_struct *png, unsigned char *data, size_t len);
    5.35 +static void flush_func(png_struct *png);
    5.36 +
    5.37 +static int png_type_to_fmt(int color_type, int channel_bits);
    5.38 +static int fmt_to_png_type(enum img_fmt fmt);
    5.39 +
    5.40 +
    5.41 +int img_register_png(void)
    5.42 +{
    5.43 +	static struct ftype_module mod = {".png", check_file, read_file, write_file};
    5.44 +	return img_register_module(&mod);
    5.45 +}
    5.46 +
    5.47 +static int check_file(struct img_io *io)
    5.48 +{
    5.49 +	unsigned char sig[8];
    5.50 +	int res;
    5.51 +	long pos = io->seek(0, SEEK_CUR, io->uptr);
    5.52 +
    5.53 +	if(io->read(sig, 8, io->uptr) < 8) {
    5.54 +		io->seek(pos, SEEK_SET, io->uptr);
    5.55 +		return -1;
    5.56 +	}
    5.57 +
    5.58 +	res = png_sig_cmp(sig, 0, 8) == 0 ? 0 : -1;
    5.59 +	io->seek(pos, SEEK_SET, io->uptr);
    5.60 +	return res;
    5.61 +}
    5.62 +
    5.63 +static int read_file(struct img_pixmap *img, struct img_io *io)
    5.64 +{
    5.65 +	png_struct *png;
    5.66 +	png_info *info;
    5.67 +	unsigned char **lineptr, *dest;
    5.68 +	int i, channel_bits, color_type, ilace_type, compression, filtering, fmt;
    5.69 +	unsigned long xsz, ysz;
    5.70 +
    5.71 +	if(!(png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0))) {
    5.72 +		return -1;
    5.73 +	}
    5.74 +
    5.75 +	if(!(info = png_create_info_struct(png))) {
    5.76 +		png_destroy_read_struct(&png, 0, 0);
    5.77 +		return -1;
    5.78 +	}
    5.79 +
    5.80 +	if(setjmp(png_jmpbuf(png))) {
    5.81 +		png_destroy_read_struct(&png, &info, 0);
    5.82 +		return -1;
    5.83 +	}
    5.84 +
    5.85 +	png_set_read_fn(png, io, read_func);
    5.86 +	png_set_sig_bytes(png, 0);
    5.87 +	png_read_png(png, info, 0, 0);
    5.88 +
    5.89 +	png_get_IHDR(png, info, &xsz, &ysz, &channel_bits, &color_type, &ilace_type,
    5.90 +			&compression, &filtering);
    5.91 +	if((fmt = png_type_to_fmt(color_type, channel_bits)) == -1) {
    5.92 +		png_destroy_read_struct(&png, &info, 0);
    5.93 +		return -1;
    5.94 +	}
    5.95 +
    5.96 +	if(img_set_pixels(img, xsz, ysz, fmt, 0) == -1) {
    5.97 +		png_destroy_read_struct(&png, &info, 0);
    5.98 +		return -1;
    5.99 +	}
   5.100 +
   5.101 +	lineptr = (unsigned char**)png_get_rows(png, info);
   5.102 +
   5.103 +	dest = img->pixels;
   5.104 +	for(i=0; i<ysz; i++) {
   5.105 +		memcpy(dest, lineptr[i], xsz * img->pixelsz);
   5.106 +		dest += xsz * img->pixelsz;
   5.107 +	}
   5.108 +	png_destroy_read_struct(&png, &info, 0);
   5.109 +	return 0;
   5.110 +}
   5.111 +
   5.112 +
   5.113 +static int write_file(struct img_pixmap *img, struct img_io *io)
   5.114 +{
   5.115 +	png_struct *png;
   5.116 +	png_info *info;
   5.117 +	png_text txt;
   5.118 +	struct img_pixmap tmpimg;
   5.119 +	unsigned char **rows;
   5.120 +	unsigned char *pixptr;
   5.121 +	int i, coltype;
   5.122 +
   5.123 +	img_init(&tmpimg);
   5.124 +
   5.125 +	if(!(png = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0))) {
   5.126 +		return -1;
   5.127 +	}
   5.128 +	if(!(info = png_create_info_struct(png))) {
   5.129 +		png_destroy_write_struct(&png, 0);
   5.130 +		return -1;
   5.131 +	}
   5.132 +
   5.133 +	/* if the input image is floating-point, we need to convert it to integer */
   5.134 +	if(img_is_float(img)) {
   5.135 +		if(img_copy(&tmpimg, img) == -1) {
   5.136 +			return -1;
   5.137 +		}
   5.138 +		if(img_to_integer(&tmpimg) == -1) {
   5.139 +			img_destroy(&tmpimg);
   5.140 +			return -1;
   5.141 +		}
   5.142 +		img = &tmpimg;
   5.143 +	}
   5.144 +
   5.145 +	txt.compression = PNG_TEXT_COMPRESSION_NONE;
   5.146 +	txt.key = "Software";
   5.147 +	txt.text = "libimago2";
   5.148 +	txt.text_length = 0;
   5.149 +
   5.150 +	if(setjmp(png_jmpbuf(png))) {
   5.151 +		png_destroy_write_struct(&png, &info);
   5.152 +		img_destroy(&tmpimg);
   5.153 +		return -1;
   5.154 +	}
   5.155 +	png_set_write_fn(png, io, write_func, flush_func);
   5.156 +
   5.157 +	coltype = fmt_to_png_type(img->fmt);
   5.158 +	png_set_IHDR(png, info, img->width, img->height, 8, coltype, PNG_INTERLACE_NONE,
   5.159 +			PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
   5.160 +	png_set_text(png, info, &txt, 1);
   5.161 +
   5.162 +	if(!(rows = malloc(img->height * sizeof *rows))) {
   5.163 +		png_destroy_write_struct(&png, &info);
   5.164 +		img_destroy(&tmpimg);
   5.165 +		return -1;
   5.166 +	}
   5.167 +
   5.168 +	pixptr = img->pixels;
   5.169 +	for(i=0; i<img->height; i++) {
   5.170 +		rows[i] = pixptr;
   5.171 +		pixptr += img->width * img->pixelsz;
   5.172 +	}
   5.173 +	png_set_rows(png, info, rows);
   5.174 +
   5.175 +	png_write_png(png, info, 0, 0);
   5.176 +	png_write_end(png, info);
   5.177 +	png_destroy_write_struct(&png, &info);
   5.178 +
   5.179 +	free(rows);
   5.180 +
   5.181 +	img_destroy(&tmpimg);
   5.182 +	return 0;
   5.183 +}
   5.184 +
   5.185 +static void read_func(png_struct *png, unsigned char *data, size_t len)
   5.186 +{
   5.187 +	struct img_io *io = (struct img_io*)png_get_io_ptr(png);
   5.188 +
   5.189 +	if(io->read(data, len, io->uptr) == -1) {
   5.190 +		longjmp(png_jmpbuf(png), 1);
   5.191 +	}
   5.192 +}
   5.193 +
   5.194 +static void write_func(png_struct *png, unsigned char *data, size_t len)
   5.195 +{
   5.196 +	struct img_io *io = (struct img_io*)png_get_io_ptr(png);
   5.197 +
   5.198 +	if(io->write(data, len, io->uptr) == -1) {
   5.199 +		longjmp(png_jmpbuf(png), 1);
   5.200 +	}
   5.201 +}
   5.202 +
   5.203 +static void flush_func(png_struct *png)
   5.204 +{
   5.205 +	/* XXX does it matter that we can't flush? */
   5.206 +}
   5.207 +
   5.208 +static int png_type_to_fmt(int color_type, int channel_bits)
   5.209 +{
   5.210 +	/* we don't support non-8bit-per-channel images yet */
   5.211 +	if(channel_bits > 8) {
   5.212 +		return -1;
   5.213 +	}
   5.214 +
   5.215 +	switch(color_type) {
   5.216 +	case PNG_COLOR_TYPE_RGB:
   5.217 +		return IMG_FMT_RGB24;
   5.218 +
   5.219 +	case PNG_COLOR_TYPE_RGB_ALPHA:
   5.220 +		return IMG_FMT_RGBA32;
   5.221 +
   5.222 +	case PNG_COLOR_TYPE_GRAY:
   5.223 +		return IMG_FMT_GREY8;
   5.224 +
   5.225 +	default:
   5.226 +		break;
   5.227 +	}
   5.228 +	return -1;
   5.229 +}
   5.230 +
   5.231 +static int fmt_to_png_type(enum img_fmt fmt)
   5.232 +{
   5.233 +	switch(fmt) {
   5.234 +	case IMG_FMT_GREY8:
   5.235 +		return PNG_COLOR_TYPE_GRAY;
   5.236 +
   5.237 +	case IMG_FMT_RGB24:
   5.238 +		return PNG_COLOR_TYPE_RGB;
   5.239 +
   5.240 +	case IMG_FMT_RGBA32:
   5.241 +		return PNG_COLOR_TYPE_RGBA;
   5.242 +
   5.243 +	default:
   5.244 +		break;
   5.245 +	}
   5.246 +	return -1;
   5.247 +}
     6.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     6.2 +++ b/libs/imago2/file_ppm.c	Thu Sep 08 06:28:38 2011 +0300
     6.3 @@ -0,0 +1,153 @@
     6.4 +/*
     6.5 +libimago - a multi-format image file input/output library.
     6.6 +Copyright (C) 2010 John Tsiombikas <nuclear@member.fsf.org>
     6.7 +
     6.8 +This program is free software: you can redistribute it and/or modify
     6.9 +it under the terms of the GNU Lesser General Public License as published
    6.10 +by the Free Software Foundation, either version 3 of the License, or
    6.11 +(at your option) any later version.
    6.12 +
    6.13 +This program is distributed in the hope that it will be useful,
    6.14 +but WITHOUT ANY WARRANTY; without even the implied warranty of
    6.15 +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    6.16 +GNU Lesser General Public License for more details.
    6.17 +
    6.18 +You should have received a copy of the GNU Lesser General Public License
    6.19 +along with this program.  If not, see <http://www.gnu.org/licenses/>.
    6.20 +*/
    6.21 +
    6.22 +/* -- Portable Pixmap (PPM) module -- */
    6.23 +
    6.24 +#include <string.h>
    6.25 +#include "imago2.h"
    6.26 +#include "ftype_module.h"
    6.27 +
    6.28 +static int check(struct img_io *io);
    6.29 +static int read(struct img_pixmap *img, struct img_io *io);
    6.30 +static int write(struct img_pixmap *img, struct img_io *io);
    6.31 +
    6.32 +int img_register_ppm(void)
    6.33 +{
    6.34 +	static struct ftype_module mod = {".ppm", check, read, write};
    6.35 +	return img_register_module(&mod);
    6.36 +}
    6.37 +
    6.38 +
    6.39 +static int check(struct img_io *io)
    6.40 +{
    6.41 +	char id[2];
    6.42 +	int res = -1;
    6.43 +	long pos = io->seek(0, SEEK_CUR, io->uptr);
    6.44 +
    6.45 +	if(io->read(id, 2, io->uptr) < 2) {
    6.46 +		io->seek(pos, SEEK_SET, io->uptr);
    6.47 +		return -1;
    6.48 +	}
    6.49 +
    6.50 +	if(id[0] == 'P' && (id[1] == '6' || id[1] == '3')) {
    6.51 +		res = 0;
    6.52 +	}
    6.53 +	io->seek(pos, SEEK_SET, io->uptr);
    6.54 +	return res;
    6.55 +}
    6.56 +
    6.57 +static int iofgetc(struct img_io *io)
    6.58 +{
    6.59 +	char c;
    6.60 +	return io->read(&c, 1, io->uptr) < 1 ? -1 : c;
    6.61 +}
    6.62 +
    6.63 +static char *iofgets(char *buf, int size, struct img_io *io)
    6.64 +{
    6.65 +	int c;
    6.66 +	char *ptr = buf;
    6.67 +
    6.68 +	while(--size > 0 && (c = iofgetc(io)) != -1) {
    6.69 +		*ptr++ = c;
    6.70 +		if(c == '\n') break;
    6.71 +	}
    6.72 +	*ptr = 0;
    6.73 +
    6.74 +	return ptr == buf ? 0 : buf;
    6.75 +}
    6.76 +
    6.77 +/* TODO: implement P3 reading */
    6.78 +static int read(struct img_pixmap *img, struct img_io *io)
    6.79 +{
    6.80 +	char buf[256];
    6.81 +	int xsz, ysz, maxval, got_hdrlines = 1;
    6.82 +
    6.83 +	if(!iofgets(buf, sizeof buf, io)) {
    6.84 +		return -1;
    6.85 +	}
    6.86 +	if(!(buf[0] == 'P' && (buf[1] == '6' || buf[1] == '3'))) {
    6.87 +		return -1;
    6.88 +	}
    6.89 +
    6.90 +	while(got_hdrlines < 3 && iofgets(buf, sizeof buf, io)) {
    6.91 +		if(buf[0] == '#') continue;
    6.92 +
    6.93 +		switch(got_hdrlines) {
    6.94 +		case 1:
    6.95 +			if(sscanf(buf, "%d %d\n", &xsz, &ysz) < 2) {
    6.96 +				return -1;
    6.97 +			}
    6.98 +			break;
    6.99 +
   6.100 +		case 2:
   6.101 +			if(sscanf(buf, "%d\n", &maxval) < 1) {
   6.102 +				return -1;
   6.103 +			}
   6.104 +		default:
   6.105 +			break;
   6.106 +		}
   6.107 +		got_hdrlines++;
   6.108 +	}
   6.109 +
   6.110 +	if(xsz < 1 || ysz < 1 || maxval != 255) {
   6.111 +		return -1;
   6.112 +	}
   6.113 +
   6.114 +	if(img_set_pixels(img, xsz, ysz, IMG_FMT_RGB24, 0) == -1) {
   6.115 +		return -1;
   6.116 +	}
   6.117 +
   6.118 +	if(io->read(img->pixels, xsz * ysz * 3, io->uptr) < xsz * ysz * 3) {
   6.119 +		return -1;
   6.120 +	}
   6.121 +	return 0;
   6.122 +}
   6.123 +
   6.124 +static int write(struct img_pixmap *img, struct img_io *io)
   6.125 +{
   6.126 +	int sz;
   6.127 +	char buf[256];
   6.128 +	struct img_pixmap tmpimg;
   6.129 +
   6.130 +	img_init(&tmpimg);
   6.131 +
   6.132 +	if(img->fmt != IMG_FMT_RGB24) {
   6.133 +		if(img_copy(&tmpimg, img) == -1) {
   6.134 +			return -1;
   6.135 +		}
   6.136 +		if(img_convert(&tmpimg, IMG_FMT_RGB24) == -1) {
   6.137 +			return -1;
   6.138 +		}
   6.139 +		img = &tmpimg;
   6.140 +	}
   6.141 +
   6.142 +	sprintf(buf, "P6\n#written by libimago2\n%d %d\n255\n", img->width, img->height);
   6.143 +	if(io->write(buf, strlen(buf), io->uptr) < strlen(buf)) {
   6.144 +		img_destroy(&tmpimg);
   6.145 +		return -1;
   6.146 +	}
   6.147 +
   6.148 +	sz = img->width * img->height * 3;
   6.149 +	if(io->write(img->pixels, sz, io->uptr) < sz) {
   6.150 +		img_destroy(&tmpimg);
   6.151 +		return -1;
   6.152 +	}
   6.153 +
   6.154 +	img_destroy(&tmpimg);
   6.155 +	return 0;
   6.156 +}
     7.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     7.2 +++ b/libs/imago2/ftype_module.c	Thu Sep 08 06:28:38 2011 +0300
     7.3 @@ -0,0 +1,118 @@
     7.4 +/*
     7.5 +libimago - a multi-format image file input/output library.
     7.6 +Copyright (C) 2010 John Tsiombikas <nuclear@member.fsf.org>
     7.7 +
     7.8 +This program is free software: you can redistribute it and/or modify
     7.9 +it under the terms of the GNU Lesser General Public License as published
    7.10 +by the Free Software Foundation, either version 3 of the License, or
    7.11 +(at your option) any later version.
    7.12 +
    7.13 +This program is distributed in the hope that it will be useful,
    7.14 +but WITHOUT ANY WARRANTY; without even the implied warranty of
    7.15 +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    7.16 +GNU Lesser General Public License for more details.
    7.17 +
    7.18 +You should have received a copy of the GNU Lesser General Public License
    7.19 +along with this program.  If not, see <http://www.gnu.org/licenses/>.
    7.20 +*/
    7.21 +
    7.22 +#include <stdlib.h>
    7.23 +#include <string.h>
    7.24 +#include "ftype_module.h"
    7.25 +
    7.26 +static struct list_node {
    7.27 +	struct ftype_module *module;
    7.28 +	struct list_node *next;
    7.29 +} *modules;
    7.30 +
    7.31 +/* defined in modules.c which is generated by configure */
    7.32 +void img_modules_init();
    7.33 +
    7.34 +static int done_init;
    7.35 +
    7.36 +int img_register_module(struct ftype_module *mod)
    7.37 +{
    7.38 +	struct list_node *node;
    7.39 +
    7.40 +	if(!(node = malloc(sizeof *node))) {
    7.41 +		return -1;
    7.42 +	}
    7.43 +
    7.44 +	node->module = mod;
    7.45 +	node->next = modules;
    7.46 +	modules = node;
    7.47 +	return 0;
    7.48 +}
    7.49 +
    7.50 +struct ftype_module *img_find_format_module(struct img_io *io)
    7.51 +{
    7.52 +	struct list_node *node;
    7.53 +
    7.54 +	if(!done_init) {
    7.55 +		img_modules_init();
    7.56 +		done_init = 1;
    7.57 +	}
    7.58 +
    7.59 +	node = modules;
    7.60 +	while(node) {
    7.61 +		if(node->module->check(io) != -1) {
    7.62 +			return node->module;
    7.63 +		}
    7.64 +		node = node->next;
    7.65 +	}
    7.66 +	return 0;
    7.67 +}
    7.68 +
    7.69 +struct ftype_module *img_guess_format(const char *fname)
    7.70 +{
    7.71 +	struct list_node *node;
    7.72 +	char *suffix;
    7.73 +	int suffix_len;
    7.74 +
    7.75 +	if(!done_init) {
    7.76 +		img_modules_init();
    7.77 +		done_init = 1;
    7.78 +	}
    7.79 +
    7.80 +	if(!(suffix = strrchr(fname, '.'))) {
    7.81 +		return 0;	/* no suffix, can't guess ... */
    7.82 +	}
    7.83 +	suffix_len = strlen(suffix);
    7.84 +
    7.85 +	node = modules;
    7.86 +	while(node) {
    7.87 +		char *suflist = node->module->suffix;
    7.88 +		char *start, *end;
    7.89 +
    7.90 +		while(*suflist) {
    7.91 +			if(!(start = strstr(suflist, suffix))) {
    7.92 +				break;
    7.93 +			}
    7.94 +			end = start + suffix_len;
    7.95 +
    7.96 +			if(*end == ':' || *end == 0) {
    7.97 +				return node->module;	/* found it */
    7.98 +			}
    7.99 +			suflist = end;
   7.100 +		}
   7.101 +
   7.102 +		node = node->next;
   7.103 +	}
   7.104 +	return 0;
   7.105 +}
   7.106 +
   7.107 +struct ftype_module *img_get_module(int idx)
   7.108 +{
   7.109 +	struct list_node *node;
   7.110 +
   7.111 +	if(!done_init) {
   7.112 +		img_modules_init();
   7.113 +		done_init = 1;
   7.114 +	}
   7.115 +
   7.116 +	node = modules;
   7.117 +	while(node && idx--) {
   7.118 +		node = node->next;
   7.119 +	}
   7.120 +	return node->module;
   7.121 +}
     8.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     8.2 +++ b/libs/imago2/ftype_module.h	Thu Sep 08 06:28:38 2011 +0300
     8.3 @@ -0,0 +1,39 @@
     8.4 +/*
     8.5 +libimago - a multi-format image file input/output library.
     8.6 +Copyright (C) 2010 John Tsiombikas <nuclear@member.fsf.org>
     8.7 +
     8.8 +This program is free software: you can redistribute it and/or modify
     8.9 +it under the terms of the GNU Lesser General Public License as published
    8.10 +by the Free Software Foundation, either version 3 of the License, or
    8.11 +(at your option) any later version.
    8.12 +
    8.13 +This program is distributed in the hope that it will be useful,
    8.14 +but WITHOUT ANY WARRANTY; without even the implied warranty of
    8.15 +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    8.16 +GNU Lesser General Public License for more details.
    8.17 +
    8.18 +You should have received a copy of the GNU Lesser General Public License
    8.19 +along with this program.  If not, see <http://www.gnu.org/licenses/>.
    8.20 +*/
    8.21 +
    8.22 +#ifndef FTYPE_MODULE_H_
    8.23 +#define FTYPE_MODULE_H_
    8.24 +
    8.25 +#include "imago2.h"
    8.26 +
    8.27 +struct ftype_module {
    8.28 +	char *suffix;	/* used for format autodetection during saving only */
    8.29 +
    8.30 +	int (*check)(struct img_io *io);
    8.31 +	int (*read)(struct img_pixmap *img, struct img_io *io);
    8.32 +	int (*write)(struct img_pixmap *img, struct img_io *io);
    8.33 +};
    8.34 +
    8.35 +int img_register_module(struct ftype_module *mod);
    8.36 +
    8.37 +struct ftype_module *img_find_format_module(struct img_io *io);
    8.38 +struct ftype_module *img_guess_format(const char *fname);
    8.39 +struct ftype_module *img_get_module(int idx);
    8.40 +
    8.41 +
    8.42 +#endif	/* FTYPE_MODULE_H_ */
     9.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     9.2 +++ b/libs/imago2/imago2.c	Thu Sep 08 06:28:38 2011 +0300
     9.3 @@ -0,0 +1,343 @@
     9.4 +/*
     9.5 +libimago - a multi-format image file input/output library.
     9.6 +Copyright (C) 2010 John Tsiombikas <nuclear@member.fsf.org>
     9.7 +
     9.8 +This program is free software: you can redistribute it and/or modify
     9.9 +it under the terms of the GNU Lesser General Public License as published
    9.10 +by the Free Software Foundation, either version 3 of the License, or
    9.11 +(at your option) any later version.
    9.12 +
    9.13 +This program is distributed in the hope that it will be useful,
    9.14 +but WITHOUT ANY WARRANTY; without even the implied warranty of
    9.15 +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    9.16 +GNU Lesser General Public License for more details.
    9.17 +
    9.18 +You should have received a copy of the GNU Lesser General Public License
    9.19 +along with this program.  If not, see <http://www.gnu.org/licenses/>.
    9.20 +*/
    9.21 +
    9.22 +#include <stdio.h>
    9.23 +#include <stdlib.h>
    9.24 +#include <string.h>
    9.25 +#include "imago2.h"
    9.26 +#include "ftype_module.h"
    9.27 +
    9.28 +static int pixel_size(enum img_fmt fmt);
    9.29 +static size_t def_read(void *buf, size_t bytes, void *uptr);
    9.30 +static size_t def_write(void *buf, size_t bytes, void *uptr);
    9.31 +static long def_seek(long offset, int whence, void *uptr);
    9.32 +
    9.33 +
    9.34 +void img_init(struct img_pixmap *img)
    9.35 +{
    9.36 +	img->pixels = 0;
    9.37 +	img->width = img->height = 0;
    9.38 +	img->fmt = IMG_FMT_RGBA32;
    9.39 +	img->pixelsz = pixel_size(img->fmt);
    9.40 +	img->name = 0;
    9.41 +}
    9.42 +
    9.43 +
    9.44 +void img_destroy(struct img_pixmap *img)
    9.45 +{
    9.46 +	free(img->pixels);
    9.47 +	img->pixels = 0;	/* just in case... */
    9.48 +	img->width = img->height = 0xbadbeef;
    9.49 +	free(img->name);
    9.50 +}
    9.51 +
    9.52 +struct img_pixmap *img_create(void)
    9.53 +{
    9.54 +	struct img_pixmap *p;
    9.55 +
    9.56 +	if(!(p = malloc(sizeof *p))) {
    9.57 +		return 0;
    9.58 +	}
    9.59 +	img_init(p);
    9.60 +	return p;
    9.61 +}
    9.62 +
    9.63 +void img_free(struct img_pixmap *img)
    9.64 +{
    9.65 +	img_destroy(img);
    9.66 +	free(img);
    9.67 +}
    9.68 +
    9.69 +int img_set_name(struct img_pixmap *img, const char *name)
    9.70 +{
    9.71 +	char *tmp;
    9.72 +
    9.73 +	if(!(tmp = malloc(strlen(name) + 1))) {
    9.74 +		return -1;
    9.75 +	}
    9.76 +	strcpy(tmp, name);
    9.77 +	img->name = tmp;
    9.78 +	return 0;
    9.79 +}
    9.80 +
    9.81 +int img_set_format(struct img_pixmap *img, enum img_fmt fmt)
    9.82 +{
    9.83 +	if(img->pixels) {
    9.84 +		return img_convert(img, fmt);
    9.85 +	}
    9.86 +	img->fmt = fmt;
    9.87 +	return 0;
    9.88 +}
    9.89 +
    9.90 +int img_copy(struct img_pixmap *dest, struct img_pixmap *src)
    9.91 +{
    9.92 +	return img_set_pixels(dest, src->width, src->height, src->fmt, src->pixels);
    9.93 +}
    9.94 +
    9.95 +int img_set_pixels(struct img_pixmap *img, int w, int h, enum img_fmt fmt, void *pix)
    9.96 +{
    9.97 +	void *newpix;
    9.98 +	int pixsz = pixel_size(fmt);
    9.99 +
   9.100 +	if(!(newpix = malloc(w * h * pixsz))) {
   9.101 +		return -1;
   9.102 +	}
   9.103 +
   9.104 +	if(pix) {
   9.105 +		memcpy(newpix, pix, w * h * pixsz);
   9.106 +	} else {
   9.107 +		memset(newpix, 0, w * h * pixsz);
   9.108 +	}
   9.109 +
   9.110 +	free(img->pixels);
   9.111 +	img->pixels = newpix;
   9.112 +	img->width = w;
   9.113 +	img->height = h;
   9.114 +	img->pixelsz = pixsz;
   9.115 +	img->fmt = fmt;
   9.116 +	return 0;
   9.117 +}
   9.118 +
   9.119 +void *img_load_pixels(const char *fname, int *xsz, int *ysz, enum img_fmt fmt)
   9.120 +{
   9.121 +	struct img_pixmap img;
   9.122 +
   9.123 +	img_init(&img);
   9.124 +
   9.125 +	if(img_load(&img, fname) == -1) {
   9.126 +		return 0;
   9.127 +	}
   9.128 +	if(img.fmt != fmt) {
   9.129 +		if(img_convert(&img, fmt) == -1) {
   9.130 +			img_destroy(&img);
   9.131 +			return 0;
   9.132 +		}
   9.133 +	}
   9.134 +
   9.135 +	*xsz = img.width;
   9.136 +	*ysz = img.height;
   9.137 +	return img.pixels;
   9.138 +}
   9.139 +
   9.140 +int img_save_pixels(const char *fname, void *pix, int xsz, int ysz, enum img_fmt fmt)
   9.141 +{
   9.142 +	struct img_pixmap img;
   9.143 +
   9.144 +	img_init(&img);
   9.145 +	img.fmt = fmt;
   9.146 +	img.name = (char*)fname;
   9.147 +	img.width = xsz;
   9.148 +	img.height = ysz;
   9.149 +	img.pixels = pix;
   9.150 +
   9.151 +	return img_save(&img, fname);
   9.152 +}
   9.153 +
   9.154 +void img_free_pixels(void *pix)
   9.155 +{
   9.156 +	free(pix);
   9.157 +}
   9.158 +
   9.159 +int img_load(struct img_pixmap *img, const char *fname)
   9.160 +{
   9.161 +	int res;
   9.162 +	FILE *fp;
   9.163 +
   9.164 +	if(!(fp = fopen(fname, "rb"))) {
   9.165 +		return -1;
   9.166 +	}
   9.167 +	res = img_read_file(img, fp);
   9.168 +	fclose(fp);
   9.169 +	return res;
   9.170 +}
   9.171 +
   9.172 +/* TODO implement filetype selection */
   9.173 +int img_save(struct img_pixmap *img, const char *fname)
   9.174 +{
   9.175 +	int res;
   9.176 +	FILE *fp;
   9.177 +
   9.178 +	img_set_name(img, fname);
   9.179 +
   9.180 +	if(!(fp = fopen(fname, "wb"))) {
   9.181 +		return -1;
   9.182 +	}
   9.183 +	res = img_write_file(img, fp);
   9.184 +	fclose(fp);
   9.185 +	return res;
   9.186 +}
   9.187 +
   9.188 +int img_read_file(struct img_pixmap *img, FILE *fp)
   9.189 +{
   9.190 +	struct img_io io = {0, def_read, def_write, def_seek};
   9.191 +
   9.192 +	io.uptr = fp;
   9.193 +	return img_read(img, &io);
   9.194 +}
   9.195 +
   9.196 +int img_write_file(struct img_pixmap *img, FILE *fp)
   9.197 +{
   9.198 +	struct img_io io = {0, def_read, def_write, def_seek};
   9.199 +
   9.200 +	io.uptr = fp;
   9.201 +	return img_write(img, &io);
   9.202 +}
   9.203 +
   9.204 +int img_read(struct img_pixmap *img, struct img_io *io)
   9.205 +{
   9.206 +	struct ftype_module *mod;
   9.207 +
   9.208 +	if((mod = img_find_format_module(io))) {
   9.209 +		return mod->read(img, io);
   9.210 +	}
   9.211 +	return -1;
   9.212 +}
   9.213 +
   9.214 +int img_write(struct img_pixmap *img, struct img_io *io)
   9.215 +{
   9.216 +	struct ftype_module *mod;
   9.217 +
   9.218 +	if(!img->name || !(mod = img_guess_format(img->name))) {
   9.219 +		/* TODO throw some sort of warning? */
   9.220 +		/* TODO implement some sort of module priority or let the user specify? */
   9.221 +		if(!(mod = img_get_module(0))) {
   9.222 +			return -1;
   9.223 +		}
   9.224 +	}
   9.225 +
   9.226 +	return mod->write(img, io);
   9.227 +}
   9.228 +
   9.229 +int img_to_float(struct img_pixmap *img)
   9.230 +{
   9.231 +	enum img_fmt targ_fmt;
   9.232 +
   9.233 +	switch(img->fmt) {
   9.234 +	case IMG_FMT_GREY8:
   9.235 +		targ_fmt = IMG_FMT_GREYF;
   9.236 +		break;
   9.237 +
   9.238 +	case IMG_FMT_RGB24:
   9.239 +		targ_fmt = IMG_FMT_RGBF;
   9.240 +		break;
   9.241 +
   9.242 +	case IMG_FMT_RGBA32:
   9.243 +		targ_fmt = IMG_FMT_RGBAF;
   9.244 +		break;
   9.245 +
   9.246 +	default:
   9.247 +		return 0;	/* already float */
   9.248 +	}
   9.249 +
   9.250 +	return img_convert(img, targ_fmt);
   9.251 +}
   9.252 +
   9.253 +int img_to_integer(struct img_pixmap *img)
   9.254 +{
   9.255 +	enum img_fmt targ_fmt;
   9.256 +
   9.257 +	switch(img->fmt) {
   9.258 +	case IMG_FMT_GREYF:
   9.259 +		targ_fmt = IMG_FMT_GREY8;
   9.260 +		break;
   9.261 +
   9.262 +	case IMG_FMT_RGBF:
   9.263 +		targ_fmt = IMG_FMT_RGB24;
   9.264 +		break;
   9.265 +
   9.266 +	case IMG_FMT_RGBAF:
   9.267 +		targ_fmt = IMG_FMT_RGBA32;
   9.268 +		break;
   9.269 +
   9.270 +	default:
   9.271 +		return 0;	/* already integer */
   9.272 +	}
   9.273 +
   9.274 +	return img_convert(img, targ_fmt);
   9.275 +}
   9.276 +
   9.277 +int img_is_float(struct img_pixmap *img)
   9.278 +{
   9.279 +	return img->fmt >= IMG_FMT_GREYF && img->fmt <= IMG_FMT_RGBAF;
   9.280 +}
   9.281 +
   9.282 +int img_has_alpha(struct img_pixmap *img)
   9.283 +{
   9.284 +	return img->fmt >= IMG_FMT_GREY8 && img->fmt <= IMG_FMT_RGBA32;
   9.285 +}
   9.286 +
   9.287 +void img_io_set_user_data(struct img_io *io, void *uptr)
   9.288 +{
   9.289 +	io->uptr = uptr;
   9.290 +}
   9.291 +
   9.292 +void img_io_set_read_func(struct img_io *io, size_t (*read)(void*, size_t, void*))
   9.293 +{
   9.294 +	io->read = read;
   9.295 +}
   9.296 +
   9.297 +void img_io_set_write_func(struct img_io *io, size_t (*write)(void*, size_t, void*))
   9.298 +{
   9.299 +	io->write = write;
   9.300 +}
   9.301 +
   9.302 +void img_io_set_seek_func(struct img_io *io, long (*seek)(long, int, void*))
   9.303 +{
   9.304 +	io->seek = seek;
   9.305 +}
   9.306 +
   9.307 +
   9.308 +static int pixel_size(enum img_fmt fmt)
   9.309 +{
   9.310 +	switch(fmt) {
   9.311 +	case IMG_FMT_GREY8:
   9.312 +		return 1;
   9.313 +	case IMG_FMT_RGB24:
   9.314 +		return 3;
   9.315 +	case IMG_FMT_RGBA32:
   9.316 +		return 4;
   9.317 +	case IMG_FMT_GREYF:
   9.318 +		return sizeof(float);
   9.319 +	case IMG_FMT_RGBF:
   9.320 +		return 3 * sizeof(float);
   9.321 +	case IMG_FMT_RGBAF:
   9.322 +		return 4 * sizeof(float);
   9.323 +	default:
   9.324 +		break;
   9.325 +	}
   9.326 +	return 0;
   9.327 +}
   9.328 +
   9.329 +static size_t def_read(void *buf, size_t bytes, void *uptr)
   9.330 +{
   9.331 +	return uptr ? fread(buf, 1, bytes, uptr) : 0;
   9.332 +}
   9.333 +
   9.334 +static size_t def_write(void *buf, size_t bytes, void *uptr)
   9.335 +{
   9.336 +	return uptr ? fwrite(buf, 1, bytes, uptr) : 0;
   9.337 +}
   9.338 +
   9.339 +static long def_seek(long offset, int whence, void *uptr)
   9.340 +{
   9.341 +	if(!uptr || fseek(uptr, offset, whence) == -1) {
   9.342 +		return -1;
   9.343 +	}
   9.344 +	return ftell(uptr);
   9.345 +}
   9.346 +
    10.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    10.2 +++ b/libs/imago2/imago2.h	Thu Sep 08 06:28:38 2011 +0300
    10.3 @@ -0,0 +1,185 @@
    10.4 +/*
    10.5 +libimago - a multi-format image file input/output library.
    10.6 +Copyright (C) 2010 John Tsiombikas <nuclear@member.fsf.org>
    10.7 +
    10.8 +This program is free software: you can redistribute it and/or modify
    10.9 +it under the terms of the GNU Lesser General Public License as published
   10.10 +by the Free Software Foundation, either version 3 of the License, or
   10.11 +(at your option) any later version.
   10.12 +
   10.13 +This program is distributed in the hope that it will be useful,
   10.14 +but WITHOUT ANY WARRANTY; without even the implied warranty of
   10.15 +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   10.16 +GNU Lesser General Public License for more details.
   10.17 +
   10.18 +You should have received a copy of the GNU Lesser General Public License
   10.19 +along with this program.  If not, see <http://www.gnu.org/licenses/>.
   10.20 +*/
   10.21 +
   10.22 +#ifndef IMAGO2_H_
   10.23 +#define IMAGO2_H_
   10.24 +
   10.25 +#include <stdio.h>
   10.26 +
   10.27 +#ifdef __cplusplus
   10.28 +#define IMG_OPTARG(arg, val)	arg = val
   10.29 +#else
   10.30 +#define IMG_OPTARG(arg, val)	arg
   10.31 +#endif
   10.32 +
   10.33 +/* XXX if you change this make sure to also change pack/unpack arrays in conv.c */
   10.34 +enum img_fmt {
   10.35 +	IMG_FMT_GREY8,
   10.36 +	IMG_FMT_RGB24,
   10.37 +	IMG_FMT_RGBA32,
   10.38 +	IMG_FMT_GREYF,
   10.39 +	IMG_FMT_RGBF,
   10.40 +	IMG_FMT_RGBAF,
   10.41 +
   10.42 +	NUM_IMG_FMT
   10.43 +};
   10.44 +
   10.45 +struct img_pixmap {
   10.46 +	void *pixels;
   10.47 +	int width, height;
   10.48 +	enum img_fmt fmt;
   10.49 +	int pixelsz;
   10.50 +	char *name;
   10.51 +};
   10.52 +
   10.53 +struct img_io {
   10.54 +	void *uptr;	/* user-data */
   10.55 +
   10.56 +	size_t (*read)(void *buf, size_t bytes, void *uptr);
   10.57 +	size_t (*write)(void *buf, size_t bytes, void *uptr);
   10.58 +	long (*seek)(long offs, int whence, void *uptr);
   10.59 +};
   10.60 +
   10.61 +#ifdef __cplusplus
   10.62 +extern "C" {
   10.63 +#endif
   10.64 +
   10.65 +/* initialize the img_pixmap structure */
   10.66 +void img_init(struct img_pixmap *img);
   10.67 +/* destroys the img_pixmap structure, freeing the pixel buffer (if available)
   10.68 + * and any other memory held by the pixmap.
   10.69 + */
   10.70 +void img_destroy(struct img_pixmap *img);
   10.71 +
   10.72 +/* convenience function that allocates an img_pixmap struct and then initializes it.
   10.73 + * returns null if the malloc fails.
   10.74 + */
   10.75 +struct img_pixmap *img_create(void);
   10.76 +/* frees a pixmap previously allocated with img_create (free followed by img_destroy) */
   10.77 +void img_free(struct img_pixmap *img);
   10.78 +
   10.79 +int img_set_name(struct img_pixmap *img, const char *name);
   10.80 +
   10.81 +/* set the image pixel format */
   10.82 +int img_set_format(struct img_pixmap *img, enum img_fmt fmt);
   10.83 +
   10.84 +/* copies one pixmap to another.
   10.85 + * equivalent to: img_set_pixels(dest, src->width, src->height, src->fmt, src->pixels)
   10.86 + */
   10.87 +int img_copy(struct img_pixmap *dest, struct img_pixmap *src);
   10.88 +
   10.89 +/* allocates a pixel buffer of the specified dimensions and format, and copies the
   10.90 + * pixels given through the pix pointer into it.
   10.91 + * the pix pointer can be null, in which case there's no copy, just allocation.
   10.92 + *
   10.93 + * C++: fmt and pix have default parameters IMG_FMT_RGBA32 and null respectively.
   10.94 + */
   10.95 +int img_set_pixels(struct img_pixmap *img, int w, int h, IMG_OPTARG(enum img_fmt fmt, IMG_FMT_RGBA32), IMG_OPTARG(void *pix, 0));
   10.96 +
   10.97 +/* Simplified image loading
   10.98 + * Loads the specified file, and returns a pointer to an array of pixels of the
   10.99 + * requested pixel format. The width and height of the image are returned through
  10.100 + * the xsz and ysz pointers.
  10.101 + * If the image cannot be loaded, the function returns null.
  10.102 + *
  10.103 + * C++: the format argument is optional and defaults to IMG_FMT_RGBA32
  10.104 + */
  10.105 +void *img_load_pixels(const char *fname, int *xsz, int *ysz, IMG_OPTARG(enum img_fmt fmt, IMG_FMT_RGBA32));
  10.106 +
  10.107 +/* Simplified image saving
  10.108 + * Reads an array of pixels supplied through the pix pointer, of dimensions xsz
  10.109 + * and ysz, and pixel-format fmt, and saves it to a file.
  10.110 + * The output filetype is guessed by the filename suffix.
  10.111 + *
  10.112 + * C++: the format argument is optional and defaults to IMG_FMT_RGBA32
  10.113 + */
  10.114 +int img_save_pixels(const char *fname, void *pix, int xsz, int ysz, IMG_OPTARG(enum img_fmt fmt, IMG_FMT_RGBA32));
  10.115 +
  10.116 +/* Frees the memory allocated by img_load_pixels */
  10.117 +void img_free_pixels(void *pix);
  10.118 +
  10.119 +/* Loads an image file into the supplied pixmap */
  10.120 +int img_load(struct img_pixmap *img, const char *fname);
  10.121 +/* Saves the supplied pixmap to a file. The output filetype is guessed by the filename suffix */
  10.122 +int img_save(struct img_pixmap *img, const char *fname);
  10.123 +
  10.124 +/* Reads an image from an open FILE* into the supplied pixmap */
  10.125 +int img_read_file(struct img_pixmap *img, FILE *fp);
  10.126 +/* Writes the supplied pixmap to an open FILE* */
  10.127 +int img_write_file(struct img_pixmap *img, FILE *fp);
  10.128 +
  10.129 +/* Reads an image using user-defined file-i/o functions (see img_io_set_*) */
  10.130 +int img_read(struct img_pixmap *img, struct img_io *io);
  10.131 +/* Writes an image using user-defined file-i/o functions (see img_io_set_*) */
  10.132 +int img_write(struct img_pixmap *img, struct img_io *io);
  10.133 +
  10.134 +/* Converts an image to the specified pixel format */
  10.135 +int img_convert(struct img_pixmap *img, enum img_fmt tofmt);
  10.136 +
  10.137 +/* Converts an image from an integer pixel format to the corresponding floating point one */
  10.138 +int img_to_float(struct img_pixmap *img);
  10.139 +/* Converts an image from a floating point pixel format to the corresponding integer one */
  10.140 +int img_to_integer(struct img_pixmap *img);
  10.141 +
  10.142 +/* Returns non-zero (true) if the supplied image is in a floating point pixel format */
  10.143 +int img_is_float(struct img_pixmap *img);
  10.144 +/* Returns non-zero (true) if the supplied image has an alpha channel */
  10.145 +int img_has_alpha(struct img_pixmap *img);
  10.146 +
  10.147 +
  10.148 +/* These functions can be used to fill an img_io struct before it's passed to
  10.149 + * one of the user-defined i/o image reading/writing functions (img_read/img_write).
  10.150 + *
  10.151 + * User-defined i/o functions:
  10.152 + *
  10.153 + * - size_t read_func(void *buffer, size_t bytes, void *user_ptr)
  10.154 + * Must try to fill the buffer with the specified number of bytes, and return
  10.155 + * the number of bytes actually read.
  10.156 + *
  10.157 + * - size_t write_func(void *buffer, size_t bytes, void *user_ptr)
  10.158 + * Must write the specified number of bytes from the supplied buffer and return
  10.159 + * the number of bytes actually written.
  10.160 + *
  10.161 + * - long seek_func(long offset, int whence, void *user_ptr)
  10.162 + * Must seek offset bytes from: the beginning of the file if whence is SEEK_SET,
  10.163 + * the current position if whence is SEEK_CUR, or the end of the file if whence is
  10.164 + * SEEK_END, and return the resulting file offset from the beginning of the file.
  10.165 + * (i.e. seek_func(0, SEEK_CUR, user_ptr); must be equivalent to an ftell).
  10.166 + *
  10.167 + * All three functions get the user-data pointer set through img_io_set_user_data
  10.168 + * as their last argument.
  10.169 + *
  10.170 + * Note: obviously you don't need to set a write function if you're only going
  10.171 + * to call img_read, or the read and seek function if you're only going to call
  10.172 + * img_write.
  10.173 + *
  10.174 + * Note: if the user-supplied write function is buffered, make sure to flush
  10.175 + * (or close the file) after img_write returns.
  10.176 + */
  10.177 +void img_io_set_user_data(struct img_io *io, void *uptr);
  10.178 +void img_io_set_read_func(struct img_io *io, size_t (*read)(void*, size_t, void*));
  10.179 +void img_io_set_write_func(struct img_io *io, size_t (*write)(void*, size_t, void*));
  10.180 +void img_io_set_seek_func(struct img_io *io, long (*seek)(long, int, void*));
  10.181 +
  10.182 +
  10.183 +#ifdef __cplusplus
  10.184 +}
  10.185 +#endif
  10.186 +
  10.187 +
  10.188 +#endif	/* IMAGO_H_ */
    11.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    11.2 +++ b/libs/imago2/modules.c	Thu Sep 08 06:28:38 2011 +0300
    11.3 @@ -0,0 +1,11 @@
    11.4 +/* this file is generated by ./configure, do not edit */
    11.5 +int img_register_jpeg();
    11.6 +int img_register_png();
    11.7 +int img_register_ppm();
    11.8 +
    11.9 +void img_modules_init(void)
   11.10 +{
   11.11 +	img_register_jpeg();
   11.12 +	img_register_png();
   11.13 +	img_register_ppm();
   11.14 +}
    12.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    12.2 +++ b/libs/libjpeg/cderror.h	Thu Sep 08 06:28:38 2011 +0300
    12.3 @@ -0,0 +1,132 @@
    12.4 +/*
    12.5 + * cderror.h
    12.6 + *
    12.7 + * Copyright (C) 1994-1997, Thomas G. Lane.
    12.8 + * This file is part of the Independent JPEG Group's software.
    12.9 + * For conditions of distribution and use, see the accompanying README file.
   12.10 + *
   12.11 + * This file defines the error and message codes for the cjpeg/djpeg
   12.12 + * applications.  These strings are not needed as part of the JPEG library
   12.13 + * proper.
   12.14 + * Edit this file to add new codes, or to translate the message strings to
   12.15 + * some other language.
   12.16 + */
   12.17 +
   12.18 +/*
   12.19 + * To define the enum list of message codes, include this file without
   12.20 + * defining macro JMESSAGE.  To create a message string table, include it
   12.21 + * again with a suitable JMESSAGE definition (see jerror.c for an example).
   12.22 + */
   12.23 +#ifndef JMESSAGE
   12.24 +#ifndef CDERROR_H
   12.25 +#define CDERROR_H
   12.26 +/* First time through, define the enum list */
   12.27 +#define JMAKE_ENUM_LIST
   12.28 +#else
   12.29 +/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
   12.30 +#define JMESSAGE(code,string)
   12.31 +#endif /* CDERROR_H */
   12.32 +#endif /* JMESSAGE */
   12.33 +
   12.34 +#ifdef JMAKE_ENUM_LIST
   12.35 +
   12.36 +typedef enum {
   12.37 +
   12.38 +#define JMESSAGE(code,string)	code ,
   12.39 +
   12.40 +#endif /* JMAKE_ENUM_LIST */
   12.41 +
   12.42 +JMESSAGE(JMSG_FIRSTADDONCODE=1000, NULL) /* Must be first entry! */
   12.43 +
   12.44 +#ifdef BMP_SUPPORTED
   12.45 +JMESSAGE(JERR_BMP_BADCMAP, "Unsupported BMP colormap format")
   12.46 +JMESSAGE(JERR_BMP_BADDEPTH, "Only 8- and 24-bit BMP files are supported")
   12.47 +JMESSAGE(JERR_BMP_BADHEADER, "Invalid BMP file: bad header length")
   12.48 +JMESSAGE(JERR_BMP_BADPLANES, "Invalid BMP file: biPlanes not equal to 1")
   12.49 +JMESSAGE(JERR_BMP_COLORSPACE, "BMP output must be grayscale or RGB")
   12.50 +JMESSAGE(JERR_BMP_COMPRESSED, "Sorry, compressed BMPs not yet supported")
   12.51 +JMESSAGE(JERR_BMP_NOT, "Not a BMP file - does not start with BM")
   12.52 +JMESSAGE(JTRC_BMP, "%ux%u 24-bit BMP image")
   12.53 +JMESSAGE(JTRC_BMP_MAPPED, "%ux%u 8-bit colormapped BMP image")
   12.54 +JMESSAGE(JTRC_BMP_OS2, "%ux%u 24-bit OS2 BMP image")
   12.55 +JMESSAGE(JTRC_BMP_OS2_MAPPED, "%ux%u 8-bit colormapped OS2 BMP image")
   12.56 +#endif /* BMP_SUPPORTED */
   12.57 +
   12.58 +#ifdef GIF_SUPPORTED
   12.59 +JMESSAGE(JERR_GIF_BUG, "GIF output got confused")
   12.60 +JMESSAGE(JERR_GIF_CODESIZE, "Bogus GIF codesize %d")
   12.61 +JMESSAGE(JERR_GIF_COLORSPACE, "GIF output must be grayscale or RGB")
   12.62 +JMESSAGE(JERR_GIF_IMAGENOTFOUND, "Too few images in GIF file")
   12.63 +JMESSAGE(JERR_GIF_NOT, "Not a GIF file")
   12.64 +JMESSAGE(JTRC_GIF, "%ux%ux%d GIF image")
   12.65 +JMESSAGE(JTRC_GIF_BADVERSION,
   12.66 +	 "Warning: unexpected GIF version number '%c%c%c'")
   12.67 +JMESSAGE(JTRC_GIF_EXTENSION, "Ignoring GIF extension block of type 0x%02x")
   12.68 +JMESSAGE(JTRC_GIF_NONSQUARE, "Caution: nonsquare pixels in input")
   12.69 +JMESSAGE(JWRN_GIF_BADDATA, "Corrupt data in GIF file")
   12.70 +JMESSAGE(JWRN_GIF_CHAR, "Bogus char 0x%02x in GIF file, ignoring")
   12.71 +JMESSAGE(JWRN_GIF_ENDCODE, "Premature end of GIF image")
   12.72 +JMESSAGE(JWRN_GIF_NOMOREDATA, "Ran out of GIF bits")
   12.73 +#endif /* GIF_SUPPORTED */
   12.74 +
   12.75 +#ifdef PPM_SUPPORTED
   12.76 +JMESSAGE(JERR_PPM_COLORSPACE, "PPM output must be grayscale or RGB")
   12.77 +JMESSAGE(JERR_PPM_NONNUMERIC, "Nonnumeric data in PPM file")
   12.78 +JMESSAGE(JERR_PPM_NOT, "Not a PPM/PGM file")
   12.79 +JMESSAGE(JTRC_PGM, "%ux%u PGM image")
   12.80 +JMESSAGE(JTRC_PGM_TEXT, "%ux%u text PGM image")
   12.81 +JMESSAGE(JTRC_PPM, "%ux%u PPM image")
   12.82 +JMESSAGE(JTRC_PPM_TEXT, "%ux%u text PPM image")
   12.83 +#endif /* PPM_SUPPORTED */
   12.84 +
   12.85 +#ifdef RLE_SUPPORTED
   12.86 +JMESSAGE(JERR_RLE_BADERROR, "Bogus error code from RLE library")
   12.87 +JMESSAGE(JERR_RLE_COLORSPACE, "RLE output must be grayscale or RGB")
   12.88 +JMESSAGE(JERR_RLE_DIMENSIONS, "Image dimensions (%ux%u) too large for RLE")
   12.89 +JMESSAGE(JERR_RLE_EMPTY, "Empty RLE file")
   12.90 +JMESSAGE(JERR_RLE_EOF, "Premature EOF in RLE header")
   12.91 +JMESSAGE(JERR_RLE_MEM, "Insufficient memory for RLE header")
   12.92 +JMESSAGE(JERR_RLE_NOT, "Not an RLE file")
   12.93 +JMESSAGE(JERR_RLE_TOOMANYCHANNELS, "Cannot handle %d output channels for RLE")
   12.94 +JMESSAGE(JERR_RLE_UNSUPPORTED, "Cannot handle this RLE setup")
   12.95 +JMESSAGE(JTRC_RLE, "%ux%u full-color RLE file")
   12.96 +JMESSAGE(JTRC_RLE_FULLMAP, "%ux%u full-color RLE file with map of length %d")
   12.97 +JMESSAGE(JTRC_RLE_GRAY, "%ux%u grayscale RLE file")
   12.98 +JMESSAGE(JTRC_RLE_MAPGRAY, "%ux%u grayscale RLE file with map of length %d")
   12.99 +JMESSAGE(JTRC_RLE_MAPPED, "%ux%u colormapped RLE file with map of length %d")
  12.100 +#endif /* RLE_SUPPORTED */
  12.101 +
  12.102 +#ifdef TARGA_SUPPORTED
  12.103 +JMESSAGE(JERR_TGA_BADCMAP, "Unsupported Targa colormap format")
  12.104 +JMESSAGE(JERR_TGA_BADPARMS, "Invalid or unsupported Targa file")
  12.105 +JMESSAGE(JERR_TGA_COLORSPACE, "Targa output must be grayscale or RGB")
  12.106 +JMESSAGE(JTRC_TGA, "%ux%u RGB Targa image")
  12.107 +JMESSAGE(JTRC_TGA_GRAY, "%ux%u grayscale Targa image")
  12.108 +JMESSAGE(JTRC_TGA_MAPPED, "%ux%u colormapped Targa image")
  12.109 +#else
  12.110 +JMESSAGE(JERR_TGA_NOTCOMP, "Targa support was not compiled")
  12.111 +#endif /* TARGA_SUPPORTED */
  12.112 +
  12.113 +JMESSAGE(JERR_BAD_CMAP_FILE,
  12.114 +	 "Color map file is invalid or of unsupported format")
  12.115 +JMESSAGE(JERR_TOO_MANY_COLORS,
  12.116 +	 "Output file format cannot handle %d colormap entries")
  12.117 +JMESSAGE(JERR_UNGETC_FAILED, "ungetc failed")
  12.118 +#ifdef TARGA_SUPPORTED
  12.119 +JMESSAGE(JERR_UNKNOWN_FORMAT,
  12.120 +	 "Unrecognized input file format --- perhaps you need -targa")
  12.121 +#else
  12.122 +JMESSAGE(JERR_UNKNOWN_FORMAT, "Unrecognized input file format")
  12.123 +#endif
  12.124 +JMESSAGE(JERR_UNSUPPORTED_FORMAT, "Unsupported output file format")
  12.125 +
  12.126 +#ifdef JMAKE_ENUM_LIST
  12.127 +
  12.128 +  JMSG_LASTADDONCODE
  12.129 +} ADDON_MESSAGE_CODE;
  12.130 +
  12.131 +#undef JMAKE_ENUM_LIST
  12.132 +#endif /* JMAKE_ENUM_LIST */
  12.133 +
  12.134 +/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  12.135 +#undef JMESSAGE
    13.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    13.2 +++ b/libs/libjpeg/jcapimin.c	Thu Sep 08 06:28:38 2011 +0300
    13.3 @@ -0,0 +1,280 @@
    13.4 +/*
    13.5 + * jcapimin.c
    13.6 + *
    13.7 + * Copyright (C) 1994-1998, Thomas G. Lane.
    13.8 + * This file is part of the Independent JPEG Group's software.
    13.9 + * For conditions of distribution and use, see the accompanying README file.
   13.10 + *
   13.11 + * This file contains application interface code for the compression half
   13.12 + * of the JPEG library.  These are the "minimum" API routines that may be
   13.13 + * needed in either the normal full-compression case or the transcoding-only
   13.14 + * case.
   13.15 + *
   13.16 + * Most of the routines intended to be called directly by an application
   13.17 + * are in this file or in jcapistd.c.  But also see jcparam.c for
   13.18 + * parameter-setup helper routines, jcomapi.c for routines shared by
   13.19 + * compression and decompression, and jctrans.c for the transcoding case.
   13.20 + */
   13.21 +
   13.22 +#define JPEG_INTERNALS
   13.23 +#include "jinclude.h"
   13.24 +#include "jpeglib.h"
   13.25 +
   13.26 +
   13.27 +/*
   13.28 + * Initialization of a JPEG compression object.
   13.29 + * The error manager must already be set up (in case memory manager fails).
   13.30 + */
   13.31 +
   13.32 +GLOBAL(void)
   13.33 +jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
   13.34 +{
   13.35 +  int i;
   13.36 +
   13.37 +  /* Guard against version mismatches between library and caller. */
   13.38 +  cinfo->mem = NULL;		/* so jpeg_destroy knows mem mgr not called */
   13.39 +  if (version != JPEG_LIB_VERSION)
   13.40 +    ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
   13.41 +  if (structsize != SIZEOF(struct jpeg_compress_struct))
   13.42 +    ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE, 
   13.43 +	     (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
   13.44 +
   13.45 +  /* For debugging purposes, we zero the whole master structure.
   13.46 +   * But the application has already set the err pointer, and may have set
   13.47 +   * client_data, so we have to save and restore those fields.
   13.48 +   * Note: if application hasn't set client_data, tools like Purify may
   13.49 +   * complain here.
   13.50 +   */
   13.51 +  {
   13.52 +    struct jpeg_error_mgr * err = cinfo->err;
   13.53 +    void * client_data = cinfo->client_data; /* ignore Purify complaint here */
   13.54 +    MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
   13.55 +    cinfo->err = err;
   13.56 +    cinfo->client_data = client_data;
   13.57 +  }
   13.58 +  cinfo->is_decompressor = FALSE;
   13.59 +
   13.60 +  /* Initialize a memory manager instance for this object */
   13.61 +  jinit_memory_mgr((j_common_ptr) cinfo);
   13.62 +
   13.63 +  /* Zero out pointers to permanent structures. */
   13.64 +  cinfo->progress = NULL;
   13.65 +  cinfo->dest = NULL;
   13.66 +
   13.67 +  cinfo->comp_info = NULL;
   13.68 +
   13.69 +  for (i = 0; i < NUM_QUANT_TBLS; i++)
   13.70 +    cinfo->quant_tbl_ptrs[i] = NULL;
   13.71 +
   13.72 +  for (i = 0; i < NUM_HUFF_TBLS; i++) {
   13.73 +    cinfo->dc_huff_tbl_ptrs[i] = NULL;
   13.74 +    cinfo->ac_huff_tbl_ptrs[i] = NULL;
   13.75 +  }
   13.76 +
   13.77 +  cinfo->script_space = NULL;
   13.78 +
   13.79 +  cinfo->input_gamma = 1.0;	/* in case application forgets */
   13.80 +
   13.81 +  /* OK, I'm ready */
   13.82 +  cinfo->global_state = CSTATE_START;
   13.83 +}
   13.84 +
   13.85 +
   13.86 +/*
   13.87 + * Destruction of a JPEG compression object
   13.88 + */
   13.89 +
   13.90 +GLOBAL(void)
   13.91 +jpeg_destroy_compress (j_compress_ptr cinfo)
   13.92 +{
   13.93 +  jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
   13.94 +}
   13.95 +
   13.96 +
   13.97 +/*
   13.98 + * Abort processing of a JPEG compression operation,
   13.99 + * but don't destroy the object itself.
  13.100 + */
  13.101 +
  13.102 +GLOBAL(void)
  13.103 +jpeg_abort_compress (j_compress_ptr cinfo)
  13.104 +{
  13.105 +  jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  13.106 +}
  13.107 +
  13.108 +
  13.109 +/*
  13.110 + * Forcibly suppress or un-suppress all quantization and Huffman tables.
  13.111 + * Marks all currently defined tables as already written (if suppress)
  13.112 + * or not written (if !suppress).  This will control whether they get emitted
  13.113 + * by a subsequent jpeg_start_compress call.
  13.114 + *
  13.115 + * This routine is exported for use by applications that want to produce
  13.116 + * abbreviated JPEG datastreams.  It logically belongs in jcparam.c, but
  13.117 + * since it is called by jpeg_start_compress, we put it here --- otherwise
  13.118 + * jcparam.o would be linked whether the application used it or not.
  13.119 + */
  13.120 +
  13.121 +GLOBAL(void)
  13.122 +jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  13.123 +{
  13.124 +  int i;
  13.125 +  JQUANT_TBL * qtbl;
  13.126 +  JHUFF_TBL * htbl;
  13.127 +
  13.128 +  for (i = 0; i < NUM_QUANT_TBLS; i++) {
  13.129 +    if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  13.130 +      qtbl->sent_table = suppress;
  13.131 +  }
  13.132 +
  13.133 +  for (i = 0; i < NUM_HUFF_TBLS; i++) {
  13.134 +    if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  13.135 +      htbl->sent_table = suppress;
  13.136 +    if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  13.137 +      htbl->sent_table = suppress;
  13.138 +  }
  13.139 +}
  13.140 +
  13.141 +
  13.142 +/*
  13.143 + * Finish JPEG compression.
  13.144 + *
  13.145 + * If a multipass operating mode was selected, this may do a great deal of
  13.146 + * work including most of the actual output.
  13.147 + */
  13.148 +
  13.149 +GLOBAL(void)
  13.150 +jpeg_finish_compress (j_compress_ptr cinfo)
  13.151 +{
  13.152 +  JDIMENSION iMCU_row;
  13.153 +
  13.154 +  if (cinfo->global_state == CSTATE_SCANNING ||
  13.155 +      cinfo->global_state == CSTATE_RAW_OK) {
  13.156 +    /* Terminate first pass */
  13.157 +    if (cinfo->next_scanline < cinfo->image_height)
  13.158 +      ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  13.159 +    (*cinfo->master->finish_pass) (cinfo);
  13.160 +  } else if (cinfo->global_state != CSTATE_WRCOEFS)
  13.161 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  13.162 +  /* Perform any remaining passes */
  13.163 +  while (! cinfo->master->is_last_pass) {
  13.164 +    (*cinfo->master->prepare_for_pass) (cinfo);
  13.165 +    for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  13.166 +      if (cinfo->progress != NULL) {
  13.167 +	cinfo->progress->pass_counter = (long) iMCU_row;
  13.168 +	cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  13.169 +	(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  13.170 +      }
  13.171 +      /* We bypass the main controller and invoke coef controller directly;
  13.172 +       * all work is being done from the coefficient buffer.
  13.173 +       */
  13.174 +      if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  13.175 +	ERREXIT(cinfo, JERR_CANT_SUSPEND);
  13.176 +    }
  13.177 +    (*cinfo->master->finish_pass) (cinfo);
  13.178 +  }
  13.179 +  /* Write EOI, do final cleanup */
  13.180 +  (*cinfo->marker->write_file_trailer) (cinfo);
  13.181 +  (*cinfo->dest->term_destination) (cinfo);
  13.182 +  /* We can use jpeg_abort to release memory and reset global_state */
  13.183 +  jpeg_abort((j_common_ptr) cinfo);
  13.184 +}
  13.185 +
  13.186 +
  13.187 +/*
  13.188 + * Write a special marker.
  13.189 + * This is only recommended for writing COM or APPn markers.
  13.190 + * Must be called after jpeg_start_compress() and before
  13.191 + * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  13.192 + */
  13.193 +
  13.194 +GLOBAL(void)
  13.195 +jpeg_write_marker (j_compress_ptr cinfo, int marker,
  13.196 +		   const JOCTET *dataptr, unsigned int datalen)
  13.197 +{
  13.198 +  JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  13.199 +
  13.200 +  if (cinfo->next_scanline != 0 ||
  13.201 +      (cinfo->global_state != CSTATE_SCANNING &&
  13.202 +       cinfo->global_state != CSTATE_RAW_OK &&
  13.203 +       cinfo->global_state != CSTATE_WRCOEFS))
  13.204 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  13.205 +
  13.206 +  (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  13.207 +  write_marker_byte = cinfo->marker->write_marker_byte;	/* copy for speed */
  13.208 +  while (datalen--) {
  13.209 +    (*write_marker_byte) (cinfo, *dataptr);
  13.210 +    dataptr++;
  13.211 +  }
  13.212 +}
  13.213 +
  13.214 +/* Same, but piecemeal. */
  13.215 +
  13.216 +GLOBAL(void)
  13.217 +jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  13.218 +{
  13.219 +  if (cinfo->next_scanline != 0 ||
  13.220 +      (cinfo->global_state != CSTATE_SCANNING &&
  13.221 +       cinfo->global_state != CSTATE_RAW_OK &&
  13.222 +       cinfo->global_state != CSTATE_WRCOEFS))
  13.223 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  13.224 +
  13.225 +  (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  13.226 +}
  13.227 +
  13.228 +GLOBAL(void)
  13.229 +jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  13.230 +{
  13.231 +  (*cinfo->marker->write_marker_byte) (cinfo, val);
  13.232 +}
  13.233 +
  13.234 +
  13.235 +/*
  13.236 + * Alternate compression function: just write an abbreviated table file.
  13.237 + * Before calling this, all parameters and a data destination must be set up.
  13.238 + *
  13.239 + * To produce a pair of files containing abbreviated tables and abbreviated
  13.240 + * image data, one would proceed as follows:
  13.241 + *
  13.242 + *		initialize JPEG object
  13.243 + *		set JPEG parameters
  13.244 + *		set destination to table file
  13.245 + *		jpeg_write_tables(cinfo);
  13.246 + *		set destination to image file
  13.247 + *		jpeg_start_compress(cinfo, FALSE);
  13.248 + *		write data...
  13.249 + *		jpeg_finish_compress(cinfo);
  13.250 + *
  13.251 + * jpeg_write_tables has the side effect of marking all tables written
  13.252 + * (same as jpeg_suppress_tables(..., TRUE)).  Thus a subsequent start_compress
  13.253 + * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  13.254 + */
  13.255 +
  13.256 +GLOBAL(void)
  13.257 +jpeg_write_tables (j_compress_ptr cinfo)
  13.258 +{
  13.259 +  if (cinfo->global_state != CSTATE_START)
  13.260 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  13.261 +
  13.262 +  /* (Re)initialize error mgr and destination modules */
  13.263 +  (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  13.264 +  (*cinfo->dest->init_destination) (cinfo);
  13.265 +  /* Initialize the marker writer ... bit of a crock to do it here. */
  13.266 +  jinit_marker_writer(cinfo);
  13.267 +  /* Write them tables! */
  13.268 +  (*cinfo->marker->write_tables_only) (cinfo);
  13.269 +  /* And clean up. */
  13.270 +  (*cinfo->dest->term_destination) (cinfo);
  13.271 +  /*
  13.272 +   * In library releases up through v6a, we called jpeg_abort() here to free
  13.273 +   * any working memory allocated by the destination manager and marker
  13.274 +   * writer.  Some applications had a problem with that: they allocated space
  13.275 +   * of their own from the library memory manager, and didn't want it to go
  13.276 +   * away during write_tables.  So now we do nothing.  This will cause a
  13.277 +   * memory leak if an app calls write_tables repeatedly without doing a full
  13.278 +   * compression cycle or otherwise resetting the JPEG object.  However, that
  13.279 +   * seems less bad than unexpectedly freeing memory in the normal case.
  13.280 +   * An app that prefers the old behavior can call jpeg_abort for itself after
  13.281 +   * each call to jpeg_write_tables().
  13.282 +   */
  13.283 +}
    14.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    14.2 +++ b/libs/libjpeg/jcapistd.c	Thu Sep 08 06:28:38 2011 +0300
    14.3 @@ -0,0 +1,161 @@
    14.4 +/*
    14.5 + * jcapistd.c
    14.6 + *
    14.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    14.8 + * This file is part of the Independent JPEG Group's software.
    14.9 + * For conditions of distribution and use, see the accompanying README file.
   14.10 + *
   14.11 + * This file contains application interface code for the compression half
   14.12 + * of the JPEG library.  These are the "standard" API routines that are
   14.13 + * used in the normal full-compression case.  They are not used by a
   14.14 + * transcoding-only application.  Note that if an application links in
   14.15 + * jpeg_start_compress, it will end up linking in the entire compressor.
   14.16 + * We thus must separate this file from jcapimin.c to avoid linking the
   14.17 + * whole compression library into a transcoder.
   14.18 + */
   14.19 +
   14.20 +#define JPEG_INTERNALS
   14.21 +#include "jinclude.h"
   14.22 +#include "jpeglib.h"
   14.23 +
   14.24 +
   14.25 +/*
   14.26 + * Compression initialization.
   14.27 + * Before calling this, all parameters and a data destination must be set up.
   14.28 + *
   14.29 + * We require a write_all_tables parameter as a failsafe check when writing
   14.30 + * multiple datastreams from the same compression object.  Since prior runs
   14.31 + * will have left all the tables marked sent_table=TRUE, a subsequent run
   14.32 + * would emit an abbreviated stream (no tables) by default.  This may be what
   14.33 + * is wanted, but for safety's sake it should not be the default behavior:
   14.34 + * programmers should have to make a deliberate choice to emit abbreviated
   14.35 + * images.  Therefore the documentation and examples should encourage people
   14.36 + * to pass write_all_tables=TRUE; then it will take active thought to do the
   14.37 + * wrong thing.
   14.38 + */
   14.39 +
   14.40 +GLOBAL(void)
   14.41 +jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
   14.42 +{
   14.43 +  if (cinfo->global_state != CSTATE_START)
   14.44 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
   14.45 +
   14.46 +  if (write_all_tables)
   14.47 +    jpeg_suppress_tables(cinfo, FALSE);	/* mark all tables to be written */
   14.48 +
   14.49 +  /* (Re)initialize error mgr and destination modules */
   14.50 +  (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
   14.51 +  (*cinfo->dest->init_destination) (cinfo);
   14.52 +  /* Perform master selection of active modules */
   14.53 +  jinit_compress_master(cinfo);
   14.54 +  /* Set up for the first pass */
   14.55 +  (*cinfo->master->prepare_for_pass) (cinfo);
   14.56 +  /* Ready for application to drive first pass through jpeg_write_scanlines
   14.57 +   * or jpeg_write_raw_data.
   14.58 +   */
   14.59 +  cinfo->next_scanline = 0;
   14.60 +  cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
   14.61 +}
   14.62 +
   14.63 +
   14.64 +/*
   14.65 + * Write some scanlines of data to the JPEG compressor.
   14.66 + *
   14.67 + * The return value will be the number of lines actually written.
   14.68 + * This should be less than the supplied num_lines only in case that
   14.69 + * the data destination module has requested suspension of the compressor,
   14.70 + * or if more than image_height scanlines are passed in.
   14.71 + *
   14.72 + * Note: we warn about excess calls to jpeg_write_scanlines() since
   14.73 + * this likely signals an application programmer error.  However,
   14.74 + * excess scanlines passed in the last valid call are *silently* ignored,
   14.75 + * so that the application need not adjust num_lines for end-of-image
   14.76 + * when using a multiple-scanline buffer.
   14.77 + */
   14.78 +
   14.79 +GLOBAL(JDIMENSION)
   14.80 +jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
   14.81 +		      JDIMENSION num_lines)
   14.82 +{
   14.83 +  JDIMENSION row_ctr, rows_left;
   14.84 +
   14.85 +  if (cinfo->global_state != CSTATE_SCANNING)
   14.86 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
   14.87 +  if (cinfo->next_scanline >= cinfo->image_height)
   14.88 +    WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
   14.89 +
   14.90 +  /* Call progress monitor hook if present */
   14.91 +  if (cinfo->progress != NULL) {
   14.92 +    cinfo->progress->pass_counter = (long) cinfo->next_scanline;
   14.93 +    cinfo->progress->pass_limit = (long) cinfo->image_height;
   14.94 +    (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
   14.95 +  }
   14.96 +
   14.97 +  /* Give master control module another chance if this is first call to
   14.98 +   * jpeg_write_scanlines.  This lets output of the frame/scan headers be
   14.99 +   * delayed so that application can write COM, etc, markers between
  14.100 +   * jpeg_start_compress and jpeg_write_scanlines.
  14.101 +   */
  14.102 +  if (cinfo->master->call_pass_startup)
  14.103 +    (*cinfo->master->pass_startup) (cinfo);
  14.104 +
  14.105 +  /* Ignore any extra scanlines at bottom of image. */
  14.106 +  rows_left = cinfo->image_height - cinfo->next_scanline;
  14.107 +  if (num_lines > rows_left)
  14.108 +    num_lines = rows_left;
  14.109 +
  14.110 +  row_ctr = 0;
  14.111 +  (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  14.112 +  cinfo->next_scanline += row_ctr;
  14.113 +  return row_ctr;
  14.114 +}
  14.115 +
  14.116 +
  14.117 +/*
  14.118 + * Alternate entry point to write raw data.
  14.119 + * Processes exactly one iMCU row per call, unless suspended.
  14.120 + */
  14.121 +
  14.122 +GLOBAL(JDIMENSION)
  14.123 +jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  14.124 +		     JDIMENSION num_lines)
  14.125 +{
  14.126 +  JDIMENSION lines_per_iMCU_row;
  14.127 +
  14.128 +  if (cinfo->global_state != CSTATE_RAW_OK)
  14.129 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  14.130 +  if (cinfo->next_scanline >= cinfo->image_height) {
  14.131 +    WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  14.132 +    return 0;
  14.133 +  }
  14.134 +
  14.135 +  /* Call progress monitor hook if present */
  14.136 +  if (cinfo->progress != NULL) {
  14.137 +    cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  14.138 +    cinfo->progress->pass_limit = (long) cinfo->image_height;
  14.139 +    (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  14.140 +  }
  14.141 +
  14.142 +  /* Give master control module another chance if this is first call to
  14.143 +   * jpeg_write_raw_data.  This lets output of the frame/scan headers be
  14.144 +   * delayed so that application can write COM, etc, markers between
  14.145 +   * jpeg_start_compress and jpeg_write_raw_data.
  14.146 +   */
  14.147 +  if (cinfo->master->call_pass_startup)
  14.148 +    (*cinfo->master->pass_startup) (cinfo);
  14.149 +
  14.150 +  /* Verify that at least one iMCU row has been passed. */
  14.151 +  lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  14.152 +  if (num_lines < lines_per_iMCU_row)
  14.153 +    ERREXIT(cinfo, JERR_BUFFER_SIZE);
  14.154 +
  14.155 +  /* Directly compress the row. */
  14.156 +  if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  14.157 +    /* If compressor did not consume the whole row, suspend processing. */
  14.158 +    return 0;
  14.159 +  }
  14.160 +
  14.161 +  /* OK, we processed one iMCU row. */
  14.162 +  cinfo->next_scanline += lines_per_iMCU_row;
  14.163 +  return lines_per_iMCU_row;
  14.164 +}
    15.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    15.2 +++ b/libs/libjpeg/jccoefct.c	Thu Sep 08 06:28:38 2011 +0300
    15.3 @@ -0,0 +1,449 @@
    15.4 +/*
    15.5 + * jccoefct.c
    15.6 + *
    15.7 + * Copyright (C) 1994-1997, Thomas G. Lane.
    15.8 + * This file is part of the Independent JPEG Group's software.
    15.9 + * For conditions of distribution and use, see the accompanying README file.
   15.10 + *
   15.11 + * This file contains the coefficient buffer controller for compression.
   15.12 + * This controller is the top level of the JPEG compressor proper.
   15.13 + * The coefficient buffer lies between forward-DCT and entropy encoding steps.
   15.14 + */
   15.15 +
   15.16 +#define JPEG_INTERNALS
   15.17 +#include "jinclude.h"
   15.18 +#include "jpeglib.h"
   15.19 +
   15.20 +
   15.21 +/* We use a full-image coefficient buffer when doing Huffman optimization,
   15.22 + * and also for writing multiple-scan JPEG files.  In all cases, the DCT
   15.23 + * step is run during the first pass, and subsequent passes need only read
   15.24 + * the buffered coefficients.
   15.25 + */
   15.26 +#ifdef ENTROPY_OPT_SUPPORTED
   15.27 +#define FULL_COEF_BUFFER_SUPPORTED
   15.28 +#else
   15.29 +#ifdef C_MULTISCAN_FILES_SUPPORTED
   15.30 +#define FULL_COEF_BUFFER_SUPPORTED
   15.31 +#endif
   15.32 +#endif
   15.33 +
   15.34 +
   15.35 +/* Private buffer controller object */
   15.36 +
   15.37 +typedef struct {
   15.38 +  struct jpeg_c_coef_controller pub; /* public fields */
   15.39 +
   15.40 +  JDIMENSION iMCU_row_num;	/* iMCU row # within image */
   15.41 +  JDIMENSION mcu_ctr;		/* counts MCUs processed in current row */
   15.42 +  int MCU_vert_offset;		/* counts MCU rows within iMCU row */
   15.43 +  int MCU_rows_per_iMCU_row;	/* number of such rows needed */
   15.44 +
   15.45 +  /* For single-pass compression, it's sufficient to buffer just one MCU
   15.46 +   * (although this may prove a bit slow in practice).  We allocate a
   15.47 +   * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
   15.48 +   * MCU constructed and sent.  (On 80x86, the workspace is FAR even though
   15.49 +   * it's not really very big; this is to keep the module interfaces unchanged
   15.50 +   * when a large coefficient buffer is necessary.)
   15.51 +   * In multi-pass modes, this array points to the current MCU's blocks
   15.52 +   * within the virtual arrays.
   15.53 +   */
   15.54 +  JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
   15.55 +
   15.56 +  /* In multi-pass modes, we need a virtual block array for each component. */
   15.57 +  jvirt_barray_ptr whole_image[MAX_COMPONENTS];
   15.58 +} my_coef_controller;
   15.59 +
   15.60 +typedef my_coef_controller * my_coef_ptr;
   15.61 +
   15.62 +
   15.63 +/* Forward declarations */
   15.64 +METHODDEF(boolean) compress_data
   15.65 +    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
   15.66 +#ifdef FULL_COEF_BUFFER_SUPPORTED
   15.67 +METHODDEF(boolean) compress_first_pass
   15.68 +    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
   15.69 +METHODDEF(boolean) compress_output
   15.70 +    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
   15.71 +#endif
   15.72 +
   15.73 +
   15.74 +LOCAL(void)
   15.75 +start_iMCU_row (j_compress_ptr cinfo)
   15.76 +/* Reset within-iMCU-row counters for a new row */
   15.77 +{
   15.78 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
   15.79 +
   15.80 +  /* In an interleaved scan, an MCU row is the same as an iMCU row.
   15.81 +   * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
   15.82 +   * But at the bottom of the image, process only what's left.
   15.83 +   */
   15.84 +  if (cinfo->comps_in_scan > 1) {
   15.85 +    coef->MCU_rows_per_iMCU_row = 1;
   15.86 +  } else {
   15.87 +    if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
   15.88 +      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
   15.89 +    else
   15.90 +      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
   15.91 +  }
   15.92 +
   15.93 +  coef->mcu_ctr = 0;
   15.94 +  coef->MCU_vert_offset = 0;
   15.95 +}
   15.96 +
   15.97 +
   15.98 +/*
   15.99 + * Initialize for a processing pass.
  15.100 + */
  15.101 +
  15.102 +METHODDEF(void)
  15.103 +start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  15.104 +{
  15.105 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  15.106 +
  15.107 +  coef->iMCU_row_num = 0;
  15.108 +  start_iMCU_row(cinfo);
  15.109 +
  15.110 +  switch (pass_mode) {
  15.111 +  case JBUF_PASS_THRU:
  15.112 +    if (coef->whole_image[0] != NULL)
  15.113 +      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  15.114 +    coef->pub.compress_data = compress_data;
  15.115 +    break;
  15.116 +#ifdef FULL_COEF_BUFFER_SUPPORTED
  15.117 +  case JBUF_SAVE_AND_PASS:
  15.118 +    if (coef->whole_image[0] == NULL)
  15.119 +      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  15.120 +    coef->pub.compress_data = compress_first_pass;
  15.121 +    break;
  15.122 +  case JBUF_CRANK_DEST:
  15.123 +    if (coef->whole_image[0] == NULL)
  15.124 +      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  15.125 +    coef->pub.compress_data = compress_output;
  15.126 +    break;
  15.127 +#endif
  15.128 +  default:
  15.129 +    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  15.130 +    break;
  15.131 +  }
  15.132 +}
  15.133 +
  15.134 +
  15.135 +/*
  15.136 + * Process some data in the single-pass case.
  15.137 + * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  15.138 + * per call, ie, v_samp_factor block rows for each component in the image.
  15.139 + * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  15.140 + *
  15.141 + * NB: input_buf contains a plane for each component in image,
  15.142 + * which we index according to the component's SOF position.
  15.143 + */
  15.144 +
  15.145 +METHODDEF(boolean)
  15.146 +compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  15.147 +{
  15.148 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  15.149 +  JDIMENSION MCU_col_num;	/* index of current MCU within row */
  15.150 +  JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  15.151 +  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  15.152 +  int blkn, bi, ci, yindex, yoffset, blockcnt;
  15.153 +  JDIMENSION ypos, xpos;
  15.154 +  jpeg_component_info *compptr;
  15.155 +
  15.156 +  /* Loop to write as much as one whole iMCU row */
  15.157 +  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  15.158 +       yoffset++) {
  15.159 +    for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  15.160 +	 MCU_col_num++) {
  15.161 +      /* Determine where data comes from in input_buf and do the DCT thing.
  15.162 +       * Each call on forward_DCT processes a horizontal row of DCT blocks
  15.163 +       * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  15.164 +       * sequentially.  Dummy blocks at the right or bottom edge are filled in
  15.165 +       * specially.  The data in them does not matter for image reconstruction,
  15.166 +       * so we fill them with values that will encode to the smallest amount of
  15.167 +       * data, viz: all zeroes in the AC entries, DC entries equal to previous
  15.168 +       * block's DC value.  (Thanks to Thomas Kinsman for this idea.)
  15.169 +       */
  15.170 +      blkn = 0;
  15.171 +      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  15.172 +	compptr = cinfo->cur_comp_info[ci];
  15.173 +	blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  15.174 +						: compptr->last_col_width;
  15.175 +	xpos = MCU_col_num * compptr->MCU_sample_width;
  15.176 +	ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  15.177 +	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  15.178 +	  if (coef->iMCU_row_num < last_iMCU_row ||
  15.179 +	      yoffset+yindex < compptr->last_row_height) {
  15.180 +	    (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  15.181 +					 input_buf[compptr->component_index],
  15.182 +					 coef->MCU_buffer[blkn],
  15.183 +					 ypos, xpos, (JDIMENSION) blockcnt);
  15.184 +	    if (blockcnt < compptr->MCU_width) {
  15.185 +	      /* Create some dummy blocks at the right edge of the image. */
  15.186 +	      jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  15.187 +			(compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  15.188 +	      for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  15.189 +		coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  15.190 +	      }
  15.191 +	    }
  15.192 +	  } else {
  15.193 +	    /* Create a row of dummy blocks at the bottom of the image. */
  15.194 +	    jzero_far((void FAR *) coef->MCU_buffer[blkn],
  15.195 +		      compptr->MCU_width * SIZEOF(JBLOCK));
  15.196 +	    for (bi = 0; bi < compptr->MCU_width; bi++) {
  15.197 +	      coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  15.198 +	    }
  15.199 +	  }
  15.200 +	  blkn += compptr->MCU_width;
  15.201 +	  ypos += DCTSIZE;
  15.202 +	}
  15.203 +      }
  15.204 +      /* Try to write the MCU.  In event of a suspension failure, we will
  15.205 +       * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  15.206 +       */
  15.207 +      if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  15.208 +	/* Suspension forced; update state counters and exit */
  15.209 +	coef->MCU_vert_offset = yoffset;
  15.210 +	coef->mcu_ctr = MCU_col_num;
  15.211 +	return FALSE;
  15.212 +      }
  15.213 +    }
  15.214 +    /* Completed an MCU row, but perhaps not an iMCU row */
  15.215 +    coef->mcu_ctr = 0;
  15.216 +  }
  15.217 +  /* Completed the iMCU row, advance counters for next one */
  15.218 +  coef->iMCU_row_num++;
  15.219 +  start_iMCU_row(cinfo);
  15.220 +  return TRUE;
  15.221 +}
  15.222 +
  15.223 +
  15.224 +#ifdef FULL_COEF_BUFFER_SUPPORTED
  15.225 +
  15.226 +/*
  15.227 + * Process some data in the first pass of a multi-pass case.
  15.228 + * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  15.229 + * per call, ie, v_samp_factor block rows for each component in the image.
  15.230 + * This amount of data is read from the source buffer, DCT'd and quantized,
  15.231 + * and saved into the virtual arrays.  We also generate suitable dummy blocks
  15.232 + * as needed at the right and lower edges.  (The dummy blocks are constructed
  15.233 + * in the virtual arrays, which have been padded appropriately.)  This makes
  15.234 + * it possible for subsequent passes not to worry about real vs. dummy blocks.
  15.235 + *
  15.236 + * We must also emit the data to the entropy encoder.  This is conveniently
  15.237 + * done by calling compress_output() after we've loaded the current strip
  15.238 + * of the virtual arrays.
  15.239 + *
  15.240 + * NB: input_buf contains a plane for each component in image.  All
  15.241 + * components are DCT'd and loaded into the virtual arrays in this pass.
  15.242 + * However, it may be that only a subset of the components are emitted to
  15.243 + * the entropy encoder during this first pass; be careful about looking
  15.244 + * at the scan-dependent variables (MCU dimensions, etc).
  15.245 + */
  15.246 +
  15.247 +METHODDEF(boolean)
  15.248 +compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  15.249 +{
  15.250 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  15.251 +  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  15.252 +  JDIMENSION blocks_across, MCUs_across, MCUindex;
  15.253 +  int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  15.254 +  JCOEF lastDC;
  15.255 +  jpeg_component_info *compptr;
  15.256 +  JBLOCKARRAY buffer;
  15.257 +  JBLOCKROW thisblockrow, lastblockrow;
  15.258 +
  15.259 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  15.260 +       ci++, compptr++) {
  15.261 +    /* Align the virtual buffer for this component. */
  15.262 +    buffer = (*cinfo->mem->access_virt_barray)
  15.263 +      ((j_common_ptr) cinfo, coef->whole_image[ci],
  15.264 +       coef->iMCU_row_num * compptr->v_samp_factor,
  15.265 +       (JDIMENSION) compptr->v_samp_factor, TRUE);
  15.266 +    /* Count non-dummy DCT block rows in this iMCU row. */
  15.267 +    if (coef->iMCU_row_num < last_iMCU_row)
  15.268 +      block_rows = compptr->v_samp_factor;
  15.269 +    else {
  15.270 +      /* NB: can't use last_row_height here, since may not be set! */
  15.271 +      block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  15.272 +      if (block_rows == 0) block_rows = compptr->v_samp_factor;
  15.273 +    }
  15.274 +    blocks_across = compptr->width_in_blocks;
  15.275 +    h_samp_factor = compptr->h_samp_factor;
  15.276 +    /* Count number of dummy blocks to be added at the right margin. */
  15.277 +    ndummy = (int) (blocks_across % h_samp_factor);
  15.278 +    if (ndummy > 0)
  15.279 +      ndummy = h_samp_factor - ndummy;
  15.280 +    /* Perform DCT for all non-dummy blocks in this iMCU row.  Each call
  15.281 +     * on forward_DCT processes a complete horizontal row of DCT blocks.
  15.282 +     */
  15.283 +    for (block_row = 0; block_row < block_rows; block_row++) {
  15.284 +      thisblockrow = buffer[block_row];
  15.285 +      (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  15.286 +				   input_buf[ci], thisblockrow,
  15.287 +				   (JDIMENSION) (block_row * DCTSIZE),
  15.288 +				   (JDIMENSION) 0, blocks_across);
  15.289 +      if (ndummy > 0) {
  15.290 +	/* Create dummy blocks at the right edge of the image. */
  15.291 +	thisblockrow += blocks_across; /* => first dummy block */
  15.292 +	jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  15.293 +	lastDC = thisblockrow[-1][0];
  15.294 +	for (bi = 0; bi < ndummy; bi++) {
  15.295 +	  thisblockrow[bi][0] = lastDC;
  15.296 +	}
  15.297 +      }
  15.298 +    }
  15.299 +    /* If at end of image, create dummy block rows as needed.
  15.300 +     * The tricky part here is that within each MCU, we want the DC values
  15.301 +     * of the dummy blocks to match the last real block's DC value.
  15.302 +     * This squeezes a few more bytes out of the resulting file...
  15.303 +     */
  15.304 +    if (coef->iMCU_row_num == last_iMCU_row) {
  15.305 +      blocks_across += ndummy;	/* include lower right corner */
  15.306 +      MCUs_across = blocks_across / h_samp_factor;
  15.307 +      for (block_row = block_rows; block_row < compptr->v_samp_factor;
  15.308 +	   block_row++) {
  15.309 +	thisblockrow = buffer[block_row];
  15.310 +	lastblockrow = buffer[block_row-1];
  15.311 +	jzero_far((void FAR *) thisblockrow,
  15.312 +		  (size_t) (blocks_across * SIZEOF(JBLOCK)));
  15.313 +	for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  15.314 +	  lastDC = lastblockrow[h_samp_factor-1][0];
  15.315 +	  for (bi = 0; bi < h_samp_factor; bi++) {
  15.316 +	    thisblockrow[bi][0] = lastDC;
  15.317 +	  }
  15.318 +	  thisblockrow += h_samp_factor; /* advance to next MCU in row */
  15.319 +	  lastblockrow += h_samp_factor;
  15.320 +	}
  15.321 +      }
  15.322 +    }
  15.323 +  }
  15.324 +  /* NB: compress_output will increment iMCU_row_num if successful.
  15.325 +   * A suspension return will result in redoing all the work above next time.
  15.326 +   */
  15.327 +
  15.328 +  /* Emit data to the entropy encoder, sharing code with subsequent passes */
  15.329 +  return compress_output(cinfo, input_buf);
  15.330 +}
  15.331 +
  15.332 +
  15.333 +/*
  15.334 + * Process some data in subsequent passes of a multi-pass case.
  15.335 + * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  15.336 + * per call, ie, v_samp_factor block rows for each component in the scan.
  15.337 + * The data is obtained from the virtual arrays and fed to the entropy coder.
  15.338 + * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  15.339 + *
  15.340 + * NB: input_buf is ignored; it is likely to be a NULL pointer.
  15.341 + */
  15.342 +
  15.343 +METHODDEF(boolean)
  15.344 +compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  15.345 +{
  15.346 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  15.347 +  JDIMENSION MCU_col_num;	/* index of current MCU within row */
  15.348 +  int blkn, ci, xindex, yindex, yoffset;
  15.349 +  JDIMENSION start_col;
  15.350 +  JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  15.351 +  JBLOCKROW buffer_ptr;
  15.352 +  jpeg_component_info *compptr;
  15.353 +
  15.354 +  /* Align the virtual buffers for the components used in this scan.
  15.355 +   * NB: during first pass, this is safe only because the buffers will
  15.356 +   * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  15.357 +   */
  15.358 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  15.359 +    compptr = cinfo->cur_comp_info[ci];
  15.360 +    buffer[ci] = (*cinfo->mem->access_virt_barray)
  15.361 +      ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  15.362 +       coef->iMCU_row_num * compptr->v_samp_factor,
  15.363 +       (JDIMENSION) compptr->v_samp_factor, FALSE);
  15.364 +  }
  15.365 +
  15.366 +  /* Loop to process one whole iMCU row */
  15.367 +  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  15.368 +       yoffset++) {
  15.369 +    for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  15.370 +	 MCU_col_num++) {
  15.371 +      /* Construct list of pointers to DCT blocks belonging to this MCU */
  15.372 +      blkn = 0;			/* index of current DCT block within MCU */
  15.373 +      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  15.374 +	compptr = cinfo->cur_comp_info[ci];
  15.375 +	start_col = MCU_col_num * compptr->MCU_width;
  15.376 +	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  15.377 +	  buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  15.378 +	  for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  15.379 +	    coef->MCU_buffer[blkn++] = buffer_ptr++;
  15.380 +	  }
  15.381 +	}
  15.382 +      }
  15.383 +      /* Try to write the MCU. */
  15.384 +      if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  15.385 +	/* Suspension forced; update state counters and exit */
  15.386 +	coef->MCU_vert_offset = yoffset;
  15.387 +	coef->mcu_ctr = MCU_col_num;
  15.388 +	return FALSE;
  15.389 +      }
  15.390 +    }
  15.391 +    /* Completed an MCU row, but perhaps not an iMCU row */
  15.392 +    coef->mcu_ctr = 0;
  15.393 +  }
  15.394 +  /* Completed the iMCU row, advance counters for next one */
  15.395 +  coef->iMCU_row_num++;
  15.396 +  start_iMCU_row(cinfo);
  15.397 +  return TRUE;
  15.398 +}
  15.399 +
  15.400 +#endif /* FULL_COEF_BUFFER_SUPPORTED */
  15.401 +
  15.402 +
  15.403 +/*
  15.404 + * Initialize coefficient buffer controller.
  15.405 + */
  15.406 +
  15.407 +GLOBAL(void)
  15.408 +jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  15.409 +{
  15.410 +  my_coef_ptr coef;
  15.411 +
  15.412 +  coef = (my_coef_ptr)
  15.413 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  15.414 +				SIZEOF(my_coef_controller));
  15.415 +  cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  15.416 +  coef->pub.start_pass = start_pass_coef;
  15.417 +
  15.418 +  /* Create the coefficient buffer. */
  15.419 +  if (need_full_buffer) {
  15.420 +#ifdef FULL_COEF_BUFFER_SUPPORTED
  15.421 +    /* Allocate a full-image virtual array for each component, */
  15.422 +    /* padded to a multiple of samp_factor DCT blocks in each direction. */
  15.423 +    int ci;
  15.424 +    jpeg_component_info *compptr;
  15.425 +
  15.426 +    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  15.427 +	 ci++, compptr++) {
  15.428 +      coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  15.429 +	((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  15.430 +	 (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  15.431 +				(long) compptr->h_samp_factor),
  15.432 +	 (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  15.433 +				(long) compptr->v_samp_factor),
  15.434 +	 (JDIMENSION) compptr->v_samp_factor);
  15.435 +    }
  15.436 +#else
  15.437 +    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  15.438 +#endif
  15.439 +  } else {
  15.440 +    /* We only need a single-MCU buffer. */
  15.441 +    JBLOCKROW buffer;
  15.442 +    int i;
  15.443 +
  15.444 +    buffer = (JBLOCKROW)
  15.445 +      (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  15.446 +				  C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  15.447 +    for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  15.448 +      coef->MCU_buffer[i] = buffer + i;
  15.449 +    }
  15.450 +    coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  15.451 +  }
  15.452 +}
    16.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    16.2 +++ b/libs/libjpeg/jccolor.c	Thu Sep 08 06:28:38 2011 +0300
    16.3 @@ -0,0 +1,459 @@
    16.4 +/*
    16.5 + * jccolor.c
    16.6 + *
    16.7 + * Copyright (C) 1991-1996, Thomas G. Lane.
    16.8 + * This file is part of the Independent JPEG Group's software.
    16.9 + * For conditions of distribution and use, see the accompanying README file.
   16.10 + *
   16.11 + * This file contains input colorspace conversion routines.
   16.12 + */
   16.13 +
   16.14 +#define JPEG_INTERNALS
   16.15 +#include "jinclude.h"
   16.16 +#include "jpeglib.h"
   16.17 +
   16.18 +
   16.19 +/* Private subobject */
   16.20 +
   16.21 +typedef struct {
   16.22 +  struct jpeg_color_converter pub; /* public fields */
   16.23 +
   16.24 +  /* Private state for RGB->YCC conversion */
   16.25 +  INT32 * rgb_ycc_tab;		/* => table for RGB to YCbCr conversion */
   16.26 +} my_color_converter;
   16.27 +
   16.28 +typedef my_color_converter * my_cconvert_ptr;
   16.29 +
   16.30 +
   16.31 +/**************** RGB -> YCbCr conversion: most common case **************/
   16.32 +
   16.33 +/*
   16.34 + * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
   16.35 + * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
   16.36 + * The conversion equations to be implemented are therefore
   16.37 + *	Y  =  0.29900 * R + 0.58700 * G + 0.11400 * B
   16.38 + *	Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B  + CENTERJSAMPLE
   16.39 + *	Cr =  0.50000 * R - 0.41869 * G - 0.08131 * B  + CENTERJSAMPLE
   16.40 + * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
   16.41 + * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
   16.42 + * rather than CENTERJSAMPLE, for Cb and Cr.  This gave equal positive and
   16.43 + * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
   16.44 + * were not represented exactly.  Now we sacrifice exact representation of
   16.45 + * maximum red and maximum blue in order to get exact grayscales.
   16.46 + *
   16.47 + * To avoid floating-point arithmetic, we represent the fractional constants
   16.48 + * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
   16.49 + * the products by 2^16, with appropriate rounding, to get the correct answer.
   16.50 + *
   16.51 + * For even more speed, we avoid doing any multiplications in the inner loop
   16.52 + * by precalculating the constants times R,G,B for all possible values.
   16.53 + * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
   16.54 + * for 12-bit samples it is still acceptable.  It's not very reasonable for
   16.55 + * 16-bit samples, but if you want lossless storage you shouldn't be changing
   16.56 + * colorspace anyway.
   16.57 + * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
   16.58 + * in the tables to save adding them separately in the inner loop.
   16.59 + */
   16.60 +
   16.61 +#define SCALEBITS	16	/* speediest right-shift on some machines */
   16.62 +#define CBCR_OFFSET	((INT32) CENTERJSAMPLE << SCALEBITS)
   16.63 +#define ONE_HALF	((INT32) 1 << (SCALEBITS-1))
   16.64 +#define FIX(x)		((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
   16.65 +
   16.66 +/* We allocate one big table and divide it up into eight parts, instead of
   16.67 + * doing eight alloc_small requests.  This lets us use a single table base
   16.68 + * address, which can be held in a register in the inner loops on many
   16.69 + * machines (more than can hold all eight addresses, anyway).
   16.70 + */
   16.71 +
   16.72 +#define R_Y_OFF		0			/* offset to R => Y section */
   16.73 +#define G_Y_OFF		(1*(MAXJSAMPLE+1))	/* offset to G => Y section */
   16.74 +#define B_Y_OFF		(2*(MAXJSAMPLE+1))	/* etc. */
   16.75 +#define R_CB_OFF	(3*(MAXJSAMPLE+1))
   16.76 +#define G_CB_OFF	(4*(MAXJSAMPLE+1))
   16.77 +#define B_CB_OFF	(5*(MAXJSAMPLE+1))
   16.78 +#define R_CR_OFF	B_CB_OFF		/* B=>Cb, R=>Cr are the same */
   16.79 +#define G_CR_OFF	(6*(MAXJSAMPLE+1))
   16.80 +#define B_CR_OFF	(7*(MAXJSAMPLE+1))
   16.81 +#define TABLE_SIZE	(8*(MAXJSAMPLE+1))
   16.82 +
   16.83 +
   16.84 +/*
   16.85 + * Initialize for RGB->YCC colorspace conversion.
   16.86 + */
   16.87 +
   16.88 +METHODDEF(void)
   16.89 +rgb_ycc_start (j_compress_ptr cinfo)
   16.90 +{
   16.91 +  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
   16.92 +  INT32 * rgb_ycc_tab;
   16.93 +  INT32 i;
   16.94 +
   16.95 +  /* Allocate and fill in the conversion tables. */
   16.96 +  cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
   16.97 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
   16.98 +				(TABLE_SIZE * SIZEOF(INT32)));
   16.99 +
  16.100 +  for (i = 0; i <= MAXJSAMPLE; i++) {
  16.101 +    rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  16.102 +    rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  16.103 +    rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i     + ONE_HALF;
  16.104 +    rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  16.105 +    rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  16.106 +    /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  16.107 +     * This ensures that the maximum output will round to MAXJSAMPLE
  16.108 +     * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  16.109 +     */
  16.110 +    rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i    + CBCR_OFFSET + ONE_HALF-1;
  16.111 +/*  B=>Cb and R=>Cr tables are the same
  16.112 +    rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i    + CBCR_OFFSET + ONE_HALF-1;
  16.113 +*/
  16.114 +    rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  16.115 +    rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  16.116 +  }
  16.117 +}
  16.118 +
  16.119 +
  16.120 +/*
  16.121 + * Convert some rows of samples to the JPEG colorspace.
  16.122 + *
  16.123 + * Note that we change from the application's interleaved-pixel format
  16.124 + * to our internal noninterleaved, one-plane-per-component format.
  16.125 + * The input buffer is therefore three times as wide as the output buffer.
  16.126 + *
  16.127 + * A starting row offset is provided only for the output buffer.  The caller
  16.128 + * can easily adjust the passed input_buf value to accommodate any row
  16.129 + * offset required on that side.
  16.130 + */
  16.131 +
  16.132 +METHODDEF(void)
  16.133 +rgb_ycc_convert (j_compress_ptr cinfo,
  16.134 +		 JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  16.135 +		 JDIMENSION output_row, int num_rows)
  16.136 +{
  16.137 +  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  16.138 +  register int r, g, b;
  16.139 +  register INT32 * ctab = cconvert->rgb_ycc_tab;
  16.140 +  register JSAMPROW inptr;
  16.141 +  register JSAMPROW outptr0, outptr1, outptr2;
  16.142 +  register JDIMENSION col;
  16.143 +  JDIMENSION num_cols = cinfo->image_width;
  16.144 +
  16.145 +  while (--num_rows >= 0) {
  16.146 +    inptr = *input_buf++;
  16.147 +    outptr0 = output_buf[0][output_row];
  16.148 +    outptr1 = output_buf[1][output_row];
  16.149 +    outptr2 = output_buf[2][output_row];
  16.150 +    output_row++;
  16.151 +    for (col = 0; col < num_cols; col++) {
  16.152 +      r = GETJSAMPLE(inptr[RGB_RED]);
  16.153 +      g = GETJSAMPLE(inptr[RGB_GREEN]);
  16.154 +      b = GETJSAMPLE(inptr[RGB_BLUE]);
  16.155 +      inptr += RGB_PIXELSIZE;
  16.156 +      /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  16.157 +       * must be too; we do not need an explicit range-limiting operation.
  16.158 +       * Hence the value being shifted is never negative, and we don't
  16.159 +       * need the general RIGHT_SHIFT macro.
  16.160 +       */
  16.161 +      /* Y */
  16.162 +      outptr0[col] = (JSAMPLE)
  16.163 +		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  16.164 +		 >> SCALEBITS);
  16.165 +      /* Cb */
  16.166 +      outptr1[col] = (JSAMPLE)
  16.167 +		((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  16.168 +		 >> SCALEBITS);
  16.169 +      /* Cr */
  16.170 +      outptr2[col] = (JSAMPLE)
  16.171 +		((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  16.172 +		 >> SCALEBITS);
  16.173 +    }
  16.174 +  }
  16.175 +}
  16.176 +
  16.177 +
  16.178 +/**************** Cases other than RGB -> YCbCr **************/
  16.179 +
  16.180 +
  16.181 +/*
  16.182 + * Convert some rows of samples to the JPEG colorspace.
  16.183 + * This version handles RGB->grayscale conversion, which is the same
  16.184 + * as the RGB->Y portion of RGB->YCbCr.
  16.185 + * We assume rgb_ycc_start has been called (we only use the Y tables).
  16.186 + */
  16.187 +
  16.188 +METHODDEF(void)
  16.189 +rgb_gray_convert (j_compress_ptr cinfo,
  16.190 +		  JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  16.191 +		  JDIMENSION output_row, int num_rows)
  16.192 +{
  16.193 +  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  16.194 +  register int r, g, b;
  16.195 +  register INT32 * ctab = cconvert->rgb_ycc_tab;
  16.196 +  register JSAMPROW inptr;
  16.197 +  register JSAMPROW outptr;
  16.198 +  register JDIMENSION col;
  16.199 +  JDIMENSION num_cols = cinfo->image_width;
  16.200 +
  16.201 +  while (--num_rows >= 0) {
  16.202 +    inptr = *input_buf++;
  16.203 +    outptr = output_buf[0][output_row];
  16.204 +    output_row++;
  16.205 +    for (col = 0; col < num_cols; col++) {
  16.206 +      r = GETJSAMPLE(inptr[RGB_RED]);
  16.207 +      g = GETJSAMPLE(inptr[RGB_GREEN]);
  16.208 +      b = GETJSAMPLE(inptr[RGB_BLUE]);
  16.209 +      inptr += RGB_PIXELSIZE;
  16.210 +      /* Y */
  16.211 +      outptr[col] = (JSAMPLE)
  16.212 +		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  16.213 +		 >> SCALEBITS);
  16.214 +    }
  16.215 +  }
  16.216 +}
  16.217 +
  16.218 +
  16.219 +/*
  16.220 + * Convert some rows of samples to the JPEG colorspace.
  16.221 + * This version handles Adobe-style CMYK->YCCK conversion,
  16.222 + * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  16.223 + * conversion as above, while passing K (black) unchanged.
  16.224 + * We assume rgb_ycc_start has been called.
  16.225 + */
  16.226 +
  16.227 +METHODDEF(void)
  16.228 +cmyk_ycck_convert (j_compress_ptr cinfo,
  16.229 +		   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  16.230 +		   JDIMENSION output_row, int num_rows)
  16.231 +{
  16.232 +  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  16.233 +  register int r, g, b;
  16.234 +  register INT32 * ctab = cconvert->rgb_ycc_tab;
  16.235 +  register JSAMPROW inptr;
  16.236 +  register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  16.237 +  register JDIMENSION col;
  16.238 +  JDIMENSION num_cols = cinfo->image_width;
  16.239 +
  16.240 +  while (--num_rows >= 0) {
  16.241 +    inptr = *input_buf++;
  16.242 +    outptr0 = output_buf[0][output_row];
  16.243 +    outptr1 = output_buf[1][output_row];
  16.244 +    outptr2 = output_buf[2][output_row];
  16.245 +    outptr3 = output_buf[3][output_row];
  16.246 +    output_row++;
  16.247 +    for (col = 0; col < num_cols; col++) {
  16.248 +      r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  16.249 +      g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  16.250 +      b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  16.251 +      /* K passes through as-is */
  16.252 +      outptr3[col] = inptr[3];	/* don't need GETJSAMPLE here */
  16.253 +      inptr += 4;
  16.254 +      /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  16.255 +       * must be too; we do not need an explicit range-limiting operation.
  16.256 +       * Hence the value being shifted is never negative, and we don't
  16.257 +       * need the general RIGHT_SHIFT macro.
  16.258 +       */
  16.259 +      /* Y */
  16.260 +      outptr0[col] = (JSAMPLE)
  16.261 +		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  16.262 +		 >> SCALEBITS);
  16.263 +      /* Cb */
  16.264 +      outptr1[col] = (JSAMPLE)
  16.265 +		((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  16.266 +		 >> SCALEBITS);
  16.267 +      /* Cr */
  16.268 +      outptr2[col] = (JSAMPLE)
  16.269 +		((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  16.270 +		 >> SCALEBITS);
  16.271 +    }
  16.272 +  }
  16.273 +}
  16.274 +
  16.275 +
  16.276 +/*
  16.277 + * Convert some rows of samples to the JPEG colorspace.
  16.278 + * This version handles grayscale output with no conversion.
  16.279 + * The source can be either plain grayscale or YCbCr (since Y == gray).
  16.280 + */
  16.281 +
  16.282 +METHODDEF(void)
  16.283 +grayscale_convert (j_compress_ptr cinfo,
  16.284 +		   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  16.285 +		   JDIMENSION output_row, int num_rows)
  16.286 +{
  16.287 +  register JSAMPROW inptr;
  16.288 +  register JSAMPROW outptr;
  16.289 +  register JDIMENSION col;
  16.290 +  JDIMENSION num_cols = cinfo->image_width;
  16.291 +  int instride = cinfo->input_components;
  16.292 +
  16.293 +  while (--num_rows >= 0) {
  16.294 +    inptr = *input_buf++;
  16.295 +    outptr = output_buf[0][output_row];
  16.296 +    output_row++;
  16.297 +    for (col = 0; col < num_cols; col++) {
  16.298 +      outptr[col] = inptr[0];	/* don't need GETJSAMPLE() here */
  16.299 +      inptr += instride;
  16.300 +    }
  16.301 +  }
  16.302 +}
  16.303 +
  16.304 +
  16.305 +/*
  16.306 + * Convert some rows of samples to the JPEG colorspace.
  16.307 + * This version handles multi-component colorspaces without conversion.
  16.308 + * We assume input_components == num_components.
  16.309 + */
  16.310 +
  16.311 +METHODDEF(void)
  16.312 +null_convert (j_compress_ptr cinfo,
  16.313 +	      JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  16.314 +	      JDIMENSION output_row, int num_rows)
  16.315 +{
  16.316 +  register JSAMPROW inptr;
  16.317 +  register JSAMPROW outptr;
  16.318 +  register JDIMENSION col;
  16.319 +  register int ci;
  16.320 +  int nc = cinfo->num_components;
  16.321 +  JDIMENSION num_cols = cinfo->image_width;
  16.322 +
  16.323 +  while (--num_rows >= 0) {
  16.324 +    /* It seems fastest to make a separate pass for each component. */
  16.325 +    for (ci = 0; ci < nc; ci++) {
  16.326 +      inptr = *input_buf;
  16.327 +      outptr = output_buf[ci][output_row];
  16.328 +      for (col = 0; col < num_cols; col++) {
  16.329 +	outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  16.330 +	inptr += nc;
  16.331 +      }
  16.332 +    }
  16.333 +    input_buf++;
  16.334 +    output_row++;
  16.335 +  }
  16.336 +}
  16.337 +
  16.338 +
  16.339 +/*
  16.340 + * Empty method for start_pass.
  16.341 + */
  16.342 +
  16.343 +METHODDEF(void)
  16.344 +null_method (j_compress_ptr cinfo)
  16.345 +{
  16.346 +  /* no work needed */
  16.347 +}
  16.348 +
  16.349 +
  16.350 +/*
  16.351 + * Module initialization routine for input colorspace conversion.
  16.352 + */
  16.353 +
  16.354 +GLOBAL(void)
  16.355 +jinit_color_converter (j_compress_ptr cinfo)
  16.356 +{
  16.357 +  my_cconvert_ptr cconvert;
  16.358 +
  16.359 +  cconvert = (my_cconvert_ptr)
  16.360 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  16.361 +				SIZEOF(my_color_converter));
  16.362 +  cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  16.363 +  /* set start_pass to null method until we find out differently */
  16.364 +  cconvert->pub.start_pass = null_method;
  16.365 +
  16.366 +  /* Make sure input_components agrees with in_color_space */
  16.367 +  switch (cinfo->in_color_space) {
  16.368 +  case JCS_GRAYSCALE:
  16.369 +    if (cinfo->input_components != 1)
  16.370 +      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  16.371 +    break;
  16.372 +
  16.373 +  case JCS_RGB:
  16.374 +#if RGB_PIXELSIZE != 3
  16.375 +    if (cinfo->input_components != RGB_PIXELSIZE)
  16.376 +      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  16.377 +    break;
  16.378 +#endif /* else share code with YCbCr */
  16.379 +
  16.380 +  case JCS_YCbCr:
  16.381 +    if (cinfo->input_components != 3)
  16.382 +      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  16.383 +    break;
  16.384 +
  16.385 +  case JCS_CMYK:
  16.386 +  case JCS_YCCK:
  16.387 +    if (cinfo->input_components != 4)
  16.388 +      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  16.389 +    break;
  16.390 +
  16.391 +  default:			/* JCS_UNKNOWN can be anything */
  16.392 +    if (cinfo->input_components < 1)
  16.393 +      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  16.394 +    break;
  16.395 +  }
  16.396 +
  16.397 +  /* Check num_components, set conversion method based on requested space */
  16.398 +  switch (cinfo->jpeg_color_space) {
  16.399 +  case JCS_GRAYSCALE:
  16.400 +    if (cinfo->num_components != 1)
  16.401 +      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  16.402 +    if (cinfo->in_color_space == JCS_GRAYSCALE)
  16.403 +      cconvert->pub.color_convert = grayscale_convert;
  16.404 +    else if (cinfo->in_color_space == JCS_RGB) {
  16.405 +      cconvert->pub.start_pass = rgb_ycc_start;
  16.406 +      cconvert->pub.color_convert = rgb_gray_convert;
  16.407 +    } else if (cinfo->in_color_space == JCS_YCbCr)
  16.408 +      cconvert->pub.color_convert = grayscale_convert;
  16.409 +    else
  16.410 +      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  16.411 +    break;
  16.412 +
  16.413 +  case JCS_RGB:
  16.414 +    if (cinfo->num_components != 3)
  16.415 +      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  16.416 +    if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  16.417 +      cconvert->pub.color_convert = null_convert;
  16.418 +    else
  16.419 +      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  16.420 +    break;
  16.421 +
  16.422 +  case JCS_YCbCr:
  16.423 +    if (cinfo->num_components != 3)
  16.424 +      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  16.425 +    if (cinfo->in_color_space == JCS_RGB) {
  16.426 +      cconvert->pub.start_pass = rgb_ycc_start;
  16.427 +      cconvert->pub.color_convert = rgb_ycc_convert;
  16.428 +    } else if (cinfo->in_color_space == JCS_YCbCr)
  16.429 +      cconvert->pub.color_convert = null_convert;
  16.430 +    else
  16.431 +      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  16.432 +    break;
  16.433 +
  16.434 +  case JCS_CMYK:
  16.435 +    if (cinfo->num_components != 4)
  16.436 +      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  16.437 +    if (cinfo->in_color_space == JCS_CMYK)
  16.438 +      cconvert->pub.color_convert = null_convert;
  16.439 +    else
  16.440 +      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  16.441 +    break;
  16.442 +
  16.443 +  case JCS_YCCK:
  16.444 +    if (cinfo->num_components != 4)
  16.445 +      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  16.446 +    if (cinfo->in_color_space == JCS_CMYK) {
  16.447 +      cconvert->pub.start_pass = rgb_ycc_start;
  16.448 +      cconvert->pub.color_convert = cmyk_ycck_convert;
  16.449 +    } else if (cinfo->in_color_space == JCS_YCCK)
  16.450 +      cconvert->pub.color_convert = null_convert;
  16.451 +    else
  16.452 +      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  16.453 +    break;
  16.454 +
  16.455 +  default:			/* allow null conversion of JCS_UNKNOWN */
  16.456 +    if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  16.457 +	cinfo->num_components != cinfo->input_components)
  16.458 +      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  16.459 +    cconvert->pub.color_convert = null_convert;
  16.460 +    break;
  16.461 +  }
  16.462 +}
    17.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    17.2 +++ b/libs/libjpeg/jcdctmgr.c	Thu Sep 08 06:28:38 2011 +0300
    17.3 @@ -0,0 +1,387 @@
    17.4 +/*
    17.5 + * jcdctmgr.c
    17.6 + *
    17.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    17.8 + * This file is part of the Independent JPEG Group's software.
    17.9 + * For conditions of distribution and use, see the accompanying README file.
   17.10 + *
   17.11 + * This file contains the forward-DCT management logic.
   17.12 + * This code selects a particular DCT implementation to be used,
   17.13 + * and it performs related housekeeping chores including coefficient
   17.14 + * quantization.
   17.15 + */
   17.16 +
   17.17 +#define JPEG_INTERNALS
   17.18 +#include "jinclude.h"
   17.19 +#include "jpeglib.h"
   17.20 +#include "jdct.h"		/* Private declarations for DCT subsystem */
   17.21 +
   17.22 +
   17.23 +/* Private subobject for this module */
   17.24 +
   17.25 +typedef struct {
   17.26 +  struct jpeg_forward_dct pub;	/* public fields */
   17.27 +
   17.28 +  /* Pointer to the DCT routine actually in use */
   17.29 +  forward_DCT_method_ptr do_dct;
   17.30 +
   17.31 +  /* The actual post-DCT divisors --- not identical to the quant table
   17.32 +   * entries, because of scaling (especially for an unnormalized DCT).
   17.33 +   * Each table is given in normal array order.
   17.34 +   */
   17.35 +  DCTELEM * divisors[NUM_QUANT_TBLS];
   17.36 +
   17.37 +#ifdef DCT_FLOAT_SUPPORTED
   17.38 +  /* Same as above for the floating-point case. */
   17.39 +  float_DCT_method_ptr do_float_dct;
   17.40 +  FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
   17.41 +#endif
   17.42 +} my_fdct_controller;
   17.43 +
   17.44 +typedef my_fdct_controller * my_fdct_ptr;
   17.45 +
   17.46 +
   17.47 +/*
   17.48 + * Initialize for a processing pass.
   17.49 + * Verify that all referenced Q-tables are present, and set up
   17.50 + * the divisor table for each one.
   17.51 + * In the current implementation, DCT of all components is done during
   17.52 + * the first pass, even if only some components will be output in the
   17.53 + * first scan.  Hence all components should be examined here.
   17.54 + */
   17.55 +
   17.56 +METHODDEF(void)
   17.57 +start_pass_fdctmgr (j_compress_ptr cinfo)
   17.58 +{
   17.59 +  my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
   17.60 +  int ci, qtblno, i;
   17.61 +  jpeg_component_info *compptr;
   17.62 +  JQUANT_TBL * qtbl;
   17.63 +  DCTELEM * dtbl;
   17.64 +
   17.65 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
   17.66 +       ci++, compptr++) {
   17.67 +    qtblno = compptr->quant_tbl_no;
   17.68 +    /* Make sure specified quantization table is present */
   17.69 +    if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
   17.70 +	cinfo->quant_tbl_ptrs[qtblno] == NULL)
   17.71 +      ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
   17.72 +    qtbl = cinfo->quant_tbl_ptrs[qtblno];
   17.73 +    /* Compute divisors for this quant table */
   17.74 +    /* We may do this more than once for same table, but it's not a big deal */
   17.75 +    switch (cinfo->dct_method) {
   17.76 +#ifdef DCT_ISLOW_SUPPORTED
   17.77 +    case JDCT_ISLOW:
   17.78 +      /* For LL&M IDCT method, divisors are equal to raw quantization
   17.79 +       * coefficients multiplied by 8 (to counteract scaling).
   17.80 +       */
   17.81 +      if (fdct->divisors[qtblno] == NULL) {
   17.82 +	fdct->divisors[qtblno] = (DCTELEM *)
   17.83 +	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
   17.84 +				      DCTSIZE2 * SIZEOF(DCTELEM));
   17.85 +      }
   17.86 +      dtbl = fdct->divisors[qtblno];
   17.87 +      for (i = 0; i < DCTSIZE2; i++) {
   17.88 +	dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
   17.89 +      }
   17.90 +      break;
   17.91 +#endif
   17.92 +#ifdef DCT_IFAST_SUPPORTED
   17.93 +    case JDCT_IFAST:
   17.94 +      {
   17.95 +	/* For AA&N IDCT method, divisors are equal to quantization
   17.96 +	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
   17.97 +	 *   scalefactor[0] = 1
   17.98 +	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
   17.99 +	 * We apply a further scale factor of 8.
  17.100 +	 */
  17.101 +#define CONST_BITS 14
  17.102 +	static const INT16 aanscales[DCTSIZE2] = {
  17.103 +	  /* precomputed values scaled up by 14 bits */
  17.104 +	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
  17.105 +	  22725, 31521, 29692, 26722, 22725, 17855, 12299,  6270,
  17.106 +	  21407, 29692, 27969, 25172, 21407, 16819, 11585,  5906,
  17.107 +	  19266, 26722, 25172, 22654, 19266, 15137, 10426,  5315,
  17.108 +	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
  17.109 +	  12873, 17855, 16819, 15137, 12873, 10114,  6967,  3552,
  17.110 +	   8867, 12299, 11585, 10426,  8867,  6967,  4799,  2446,
  17.111 +	   4520,  6270,  5906,  5315,  4520,  3552,  2446,  1247
  17.112 +	};
  17.113 +	SHIFT_TEMPS
  17.114 +
  17.115 +	if (fdct->divisors[qtblno] == NULL) {
  17.116 +	  fdct->divisors[qtblno] = (DCTELEM *)
  17.117 +	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  17.118 +					DCTSIZE2 * SIZEOF(DCTELEM));
  17.119 +	}
  17.120 +	dtbl = fdct->divisors[qtblno];
  17.121 +	for (i = 0; i < DCTSIZE2; i++) {
  17.122 +	  dtbl[i] = (DCTELEM)
  17.123 +	    DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  17.124 +				  (INT32) aanscales[i]),
  17.125 +		    CONST_BITS-3);
  17.126 +	}
  17.127 +      }
  17.128 +      break;
  17.129 +#endif
  17.130 +#ifdef DCT_FLOAT_SUPPORTED
  17.131 +    case JDCT_FLOAT:
  17.132 +      {
  17.133 +	/* For float AA&N IDCT method, divisors are equal to quantization
  17.134 +	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
  17.135 +	 *   scalefactor[0] = 1
  17.136 +	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
  17.137 +	 * We apply a further scale factor of 8.
  17.138 +	 * What's actually stored is 1/divisor so that the inner loop can
  17.139 +	 * use a multiplication rather than a division.
  17.140 +	 */
  17.141 +	FAST_FLOAT * fdtbl;
  17.142 +	int row, col;
  17.143 +	static const double aanscalefactor[DCTSIZE] = {
  17.144 +	  1.0, 1.387039845, 1.306562965, 1.175875602,
  17.145 +	  1.0, 0.785694958, 0.541196100, 0.275899379
  17.146 +	};
  17.147 +
  17.148 +	if (fdct->float_divisors[qtblno] == NULL) {
  17.149 +	  fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  17.150 +	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  17.151 +					DCTSIZE2 * SIZEOF(FAST_FLOAT));
  17.152 +	}
  17.153 +	fdtbl = fdct->float_divisors[qtblno];
  17.154 +	i = 0;
  17.155 +	for (row = 0; row < DCTSIZE; row++) {
  17.156 +	  for (col = 0; col < DCTSIZE; col++) {
  17.157 +	    fdtbl[i] = (FAST_FLOAT)
  17.158 +	      (1.0 / (((double) qtbl->quantval[i] *
  17.159 +		       aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  17.160 +	    i++;
  17.161 +	  }
  17.162 +	}
  17.163 +      }
  17.164 +      break;
  17.165 +#endif
  17.166 +    default:
  17.167 +      ERREXIT(cinfo, JERR_NOT_COMPILED);
  17.168 +      break;
  17.169 +    }
  17.170 +  }
  17.171 +}
  17.172 +
  17.173 +
  17.174 +/*
  17.175 + * Perform forward DCT on one or more blocks of a component.
  17.176 + *
  17.177 + * The input samples are taken from the sample_data[] array starting at
  17.178 + * position start_row/start_col, and moving to the right for any additional
  17.179 + * blocks. The quantized coefficients are returned in coef_blocks[].
  17.180 + */
  17.181 +
  17.182 +METHODDEF(void)
  17.183 +forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  17.184 +	     JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  17.185 +	     JDIMENSION start_row, JDIMENSION start_col,
  17.186 +	     JDIMENSION num_blocks)
  17.187 +/* This version is used for integer DCT implementations. */
  17.188 +{
  17.189 +  /* This routine is heavily used, so it's worth coding it tightly. */
  17.190 +  my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  17.191 +  forward_DCT_method_ptr do_dct = fdct->do_dct;
  17.192 +  DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  17.193 +  DCTELEM workspace[DCTSIZE2];	/* work area for FDCT subroutine */
  17.194 +  JDIMENSION bi;
  17.195 +
  17.196 +  sample_data += start_row;	/* fold in the vertical offset once */
  17.197 +
  17.198 +  for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  17.199 +    /* Load data into workspace, applying unsigned->signed conversion */
  17.200 +    { register DCTELEM *workspaceptr;
  17.201 +      register JSAMPROW elemptr;
  17.202 +      register int elemr;
  17.203 +
  17.204 +      workspaceptr = workspace;
  17.205 +      for (elemr = 0; elemr < DCTSIZE; elemr++) {
  17.206 +	elemptr = sample_data[elemr] + start_col;
  17.207 +#if DCTSIZE == 8		/* unroll the inner loop */
  17.208 +	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  17.209 +	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  17.210 +	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  17.211 +	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  17.212 +	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  17.213 +	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  17.214 +	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  17.215 +	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  17.216 +#else
  17.217 +	{ register int elemc;
  17.218 +	  for (elemc = DCTSIZE; elemc > 0; elemc--) {
  17.219 +	    *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  17.220 +	  }
  17.221 +	}
  17.222 +#endif
  17.223 +      }
  17.224 +    }
  17.225 +
  17.226 +    /* Perform the DCT */
  17.227 +    (*do_dct) (workspace);
  17.228 +
  17.229 +    /* Quantize/descale the coefficients, and store into coef_blocks[] */
  17.230 +    { register DCTELEM temp, qval;
  17.231 +      register int i;
  17.232 +      register JCOEFPTR output_ptr = coef_blocks[bi];
  17.233 +
  17.234 +      for (i = 0; i < DCTSIZE2; i++) {
  17.235 +	qval = divisors[i];
  17.236 +	temp = workspace[i];
  17.237 +	/* Divide the coefficient value by qval, ensuring proper rounding.
  17.238 +	 * Since C does not specify the direction of rounding for negative
  17.239 +	 * quotients, we have to force the dividend positive for portability.
  17.240 +	 *
  17.241 +	 * In most files, at least half of the output values will be zero
  17.242 +	 * (at default quantization settings, more like three-quarters...)
  17.243 +	 * so we should ensure that this case is fast.  On many machines,
  17.244 +	 * a comparison is enough cheaper than a divide to make a special test
  17.245 +	 * a win.  Since both inputs will be nonnegative, we need only test
  17.246 +	 * for a < b to discover whether a/b is 0.
  17.247 +	 * If your machine's division is fast enough, define FAST_DIVIDE.
  17.248 +	 */
  17.249 +#ifdef FAST_DIVIDE
  17.250 +#define DIVIDE_BY(a,b)	a /= b
  17.251 +#else
  17.252 +#define DIVIDE_BY(a,b)	if (a >= b) a /= b; else a = 0
  17.253 +#endif
  17.254 +	if (temp < 0) {
  17.255 +	  temp = -temp;
  17.256 +	  temp += qval>>1;	/* for rounding */
  17.257 +	  DIVIDE_BY(temp, qval);
  17.258 +	  temp = -temp;
  17.259 +	} else {
  17.260 +	  temp += qval>>1;	/* for rounding */
  17.261 +	  DIVIDE_BY(temp, qval);
  17.262 +	}
  17.263 +	output_ptr[i] = (JCOEF) temp;
  17.264 +      }
  17.265 +    }
  17.266 +  }
  17.267 +}
  17.268 +
  17.269 +
  17.270 +#ifdef DCT_FLOAT_SUPPORTED
  17.271 +
  17.272 +METHODDEF(void)
  17.273 +forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  17.274 +		   JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  17.275 +		   JDIMENSION start_row, JDIMENSION start_col,
  17.276 +		   JDIMENSION num_blocks)
  17.277 +/* This version is used for floating-point DCT implementations. */
  17.278 +{
  17.279 +  /* This routine is heavily used, so it's worth coding it tightly. */
  17.280 +  my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  17.281 +  float_DCT_method_ptr do_dct = fdct->do_float_dct;
  17.282 +  FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  17.283 +  FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  17.284 +  JDIMENSION bi;
  17.285 +
  17.286 +  sample_data += start_row;	/* fold in the vertical offset once */
  17.287 +
  17.288 +  for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  17.289 +    /* Load data into workspace, applying unsigned->signed conversion */
  17.290 +    { register FAST_FLOAT *workspaceptr;
  17.291 +      register JSAMPROW elemptr;
  17.292 +      register int elemr;
  17.293 +
  17.294 +      workspaceptr = workspace;
  17.295 +      for (elemr = 0; elemr < DCTSIZE; elemr++) {
  17.296 +	elemptr = sample_data[elemr] + start_col;
  17.297 +#if DCTSIZE == 8		/* unroll the inner loop */
  17.298 +	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  17.299 +	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  17.300 +	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  17.301 +	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  17.302 +	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  17.303 +	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  17.304 +	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  17.305 +	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  17.306 +#else
  17.307 +	{ register int elemc;
  17.308 +	  for (elemc = DCTSIZE; elemc > 0; elemc--) {
  17.309 +	    *workspaceptr++ = (FAST_FLOAT)
  17.310 +	      (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  17.311 +	  }
  17.312 +	}
  17.313 +#endif
  17.314 +      }
  17.315 +    }
  17.316 +
  17.317 +    /* Perform the DCT */
  17.318 +    (*do_dct) (workspace);
  17.319 +
  17.320 +    /* Quantize/descale the coefficients, and store into coef_blocks[] */
  17.321 +    { register FAST_FLOAT temp;
  17.322 +      register int i;
  17.323 +      register JCOEFPTR output_ptr = coef_blocks[bi];
  17.324 +
  17.325 +      for (i = 0; i < DCTSIZE2; i++) {
  17.326 +	/* Apply the quantization and scaling factor */
  17.327 +	temp = workspace[i] * divisors[i];
  17.328 +	/* Round to nearest integer.
  17.329 +	 * Since C does not specify the direction of rounding for negative
  17.330 +	 * quotients, we have to force the dividend positive for portability.
  17.331 +	 * The maximum coefficient size is +-16K (for 12-bit data), so this
  17.332 +	 * code should work for either 16-bit or 32-bit ints.
  17.333 +	 */
  17.334 +	output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  17.335 +      }
  17.336 +    }
  17.337 +  }
  17.338 +}
  17.339 +
  17.340 +#endif /* DCT_FLOAT_SUPPORTED */
  17.341 +
  17.342 +
  17.343 +/*
  17.344 + * Initialize FDCT manager.
  17.345 + */
  17.346 +
  17.347 +GLOBAL(void)
  17.348 +jinit_forward_dct (j_compress_ptr cinfo)
  17.349 +{
  17.350 +  my_fdct_ptr fdct;
  17.351 +  int i;
  17.352 +
  17.353 +  fdct = (my_fdct_ptr)
  17.354 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  17.355 +				SIZEOF(my_fdct_controller));
  17.356 +  cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  17.357 +  fdct->pub.start_pass = start_pass_fdctmgr;
  17.358 +
  17.359 +  switch (cinfo->dct_method) {
  17.360 +#ifdef DCT_ISLOW_SUPPORTED
  17.361 +  case JDCT_ISLOW:
  17.362 +    fdct->pub.forward_DCT = forward_DCT;
  17.363 +    fdct->do_dct = jpeg_fdct_islow;
  17.364 +    break;
  17.365 +#endif
  17.366 +#ifdef DCT_IFAST_SUPPORTED
  17.367 +  case JDCT_IFAST:
  17.368 +    fdct->pub.forward_DCT = forward_DCT;
  17.369 +    fdct->do_dct = jpeg_fdct_ifast;
  17.370 +    break;
  17.371 +#endif
  17.372 +#ifdef DCT_FLOAT_SUPPORTED
  17.373 +  case JDCT_FLOAT:
  17.374 +    fdct->pub.forward_DCT = forward_DCT_float;
  17.375 +    fdct->do_float_dct = jpeg_fdct_float;
  17.376 +    break;
  17.377 +#endif
  17.378 +  default:
  17.379 +    ERREXIT(cinfo, JERR_NOT_COMPILED);
  17.380 +    break;
  17.381 +  }
  17.382 +
  17.383 +  /* Mark divisor tables unallocated */
  17.384 +  for (i = 0; i < NUM_QUANT_TBLS; i++) {
  17.385 +    fdct->divisors[i] = NULL;
  17.386 +#ifdef DCT_FLOAT_SUPPORTED
  17.387 +    fdct->float_divisors[i] = NULL;
  17.388 +#endif
  17.389 +  }
  17.390 +}
    18.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    18.2 +++ b/libs/libjpeg/jchuff.c	Thu Sep 08 06:28:38 2011 +0300
    18.3 @@ -0,0 +1,909 @@
    18.4 +/*
    18.5 + * jchuff.c
    18.6 + *
    18.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    18.8 + * This file is part of the Independent JPEG Group's software.
    18.9 + * For conditions of distribution and use, see the accompanying README file.
   18.10 + *
   18.11 + * This file contains Huffman entropy encoding routines.
   18.12 + *
   18.13 + * Much of the complexity here has to do with supporting output suspension.
   18.14 + * If the data destination module demands suspension, we want to be able to
   18.15 + * back up to the start of the current MCU.  To do this, we copy state
   18.16 + * variables into local working storage, and update them back to the
   18.17 + * permanent JPEG objects only upon successful completion of an MCU.
   18.18 + */
   18.19 +
   18.20 +#define JPEG_INTERNALS
   18.21 +#include "jinclude.h"
   18.22 +#include "jpeglib.h"
   18.23 +#include "jchuff.h"		/* Declarations shared with jcphuff.c */
   18.24 +
   18.25 +
   18.26 +/* Expanded entropy encoder object for Huffman encoding.
   18.27 + *
   18.28 + * The savable_state subrecord contains fields that change within an MCU,
   18.29 + * but must not be updated permanently until we complete the MCU.
   18.30 + */
   18.31 +
   18.32 +typedef struct {
   18.33 +  INT32 put_buffer;		/* current bit-accumulation buffer */
   18.34 +  int put_bits;			/* # of bits now in it */
   18.35 +  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
   18.36 +} savable_state;
   18.37 +
   18.38 +/* This macro is to work around compilers with missing or broken
   18.39 + * structure assignment.  You'll need to fix this code if you have
   18.40 + * such a compiler and you change MAX_COMPS_IN_SCAN.
   18.41 + */
   18.42 +
   18.43 +#ifndef NO_STRUCT_ASSIGN
   18.44 +#define ASSIGN_STATE(dest,src)  ((dest) = (src))
   18.45 +#else
   18.46 +#if MAX_COMPS_IN_SCAN == 4
   18.47 +#define ASSIGN_STATE(dest,src)  \
   18.48 +	((dest).put_buffer = (src).put_buffer, \
   18.49 +	 (dest).put_bits = (src).put_bits, \
   18.50 +	 (dest).last_dc_val[0] = (src).last_dc_val[0], \
   18.51 +	 (dest).last_dc_val[1] = (src).last_dc_val[1], \
   18.52 +	 (dest).last_dc_val[2] = (src).last_dc_val[2], \
   18.53 +	 (dest).last_dc_val[3] = (src).last_dc_val[3])
   18.54 +#endif
   18.55 +#endif
   18.56 +
   18.57 +
   18.58 +typedef struct {
   18.59 +  struct jpeg_entropy_encoder pub; /* public fields */
   18.60 +
   18.61 +  savable_state saved;		/* Bit buffer & DC state at start of MCU */
   18.62 +
   18.63 +  /* These fields are NOT loaded into local working state. */
   18.64 +  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
   18.65 +  int next_restart_num;		/* next restart number to write (0-7) */
   18.66 +
   18.67 +  /* Pointers to derived tables (these workspaces have image lifespan) */
   18.68 +  c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
   18.69 +  c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
   18.70 +
   18.71 +#ifdef ENTROPY_OPT_SUPPORTED	/* Statistics tables for optimization */
   18.72 +  long * dc_count_ptrs[NUM_HUFF_TBLS];
   18.73 +  long * ac_count_ptrs[NUM_HUFF_TBLS];
   18.74 +#endif
   18.75 +} huff_entropy_encoder;
   18.76 +
   18.77 +typedef huff_entropy_encoder * huff_entropy_ptr;
   18.78 +
   18.79 +/* Working state while writing an MCU.
   18.80 + * This struct contains all the fields that are needed by subroutines.
   18.81 + */
   18.82 +
   18.83 +typedef struct {
   18.84 +  JOCTET * next_output_byte;	/* => next byte to write in buffer */
   18.85 +  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
   18.86 +  savable_state cur;		/* Current bit buffer & DC state */
   18.87 +  j_compress_ptr cinfo;		/* dump_buffer needs access to this */
   18.88 +} working_state;
   18.89 +
   18.90 +
   18.91 +/* Forward declarations */
   18.92 +METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
   18.93 +					JBLOCKROW *MCU_data));
   18.94 +METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
   18.95 +#ifdef ENTROPY_OPT_SUPPORTED
   18.96 +METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
   18.97 +					  JBLOCKROW *MCU_data));
   18.98 +METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
   18.99 +#endif
  18.100 +
  18.101 +
  18.102 +/*
  18.103 + * Initialize for a Huffman-compressed scan.
  18.104 + * If gather_statistics is TRUE, we do not output anything during the scan,
  18.105 + * just count the Huffman symbols used and generate Huffman code tables.
  18.106 + */
  18.107 +
  18.108 +METHODDEF(void)
  18.109 +start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  18.110 +{
  18.111 +  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  18.112 +  int ci, dctbl, actbl;
  18.113 +  jpeg_component_info * compptr;
  18.114 +
  18.115 +  if (gather_statistics) {
  18.116 +#ifdef ENTROPY_OPT_SUPPORTED
  18.117 +    entropy->pub.encode_mcu = encode_mcu_gather;
  18.118 +    entropy->pub.finish_pass = finish_pass_gather;
  18.119 +#else
  18.120 +    ERREXIT(cinfo, JERR_NOT_COMPILED);
  18.121 +#endif
  18.122 +  } else {
  18.123 +    entropy->pub.encode_mcu = encode_mcu_huff;
  18.124 +    entropy->pub.finish_pass = finish_pass_huff;
  18.125 +  }
  18.126 +
  18.127 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  18.128 +    compptr = cinfo->cur_comp_info[ci];
  18.129 +    dctbl = compptr->dc_tbl_no;
  18.130 +    actbl = compptr->ac_tbl_no;
  18.131 +    if (gather_statistics) {
  18.132 +#ifdef ENTROPY_OPT_SUPPORTED
  18.133 +      /* Check for invalid table indexes */
  18.134 +      /* (make_c_derived_tbl does this in the other path) */
  18.135 +      if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  18.136 +	ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  18.137 +      if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  18.138 +	ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  18.139 +      /* Allocate and zero the statistics tables */
  18.140 +      /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  18.141 +      if (entropy->dc_count_ptrs[dctbl] == NULL)
  18.142 +	entropy->dc_count_ptrs[dctbl] = (long *)
  18.143 +	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  18.144 +				      257 * SIZEOF(long));
  18.145 +      MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  18.146 +      if (entropy->ac_count_ptrs[actbl] == NULL)
  18.147 +	entropy->ac_count_ptrs[actbl] = (long *)
  18.148 +	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  18.149 +				      257 * SIZEOF(long));
  18.150 +      MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  18.151 +#endif
  18.152 +    } else {
  18.153 +      /* Compute derived values for Huffman tables */
  18.154 +      /* We may do this more than once for a table, but it's not expensive */
  18.155 +      jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  18.156 +			      & entropy->dc_derived_tbls[dctbl]);
  18.157 +      jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  18.158 +			      & entropy->ac_derived_tbls[actbl]);
  18.159 +    }
  18.160 +    /* Initialize DC predictions to 0 */
  18.161 +    entropy->saved.last_dc_val[ci] = 0;
  18.162 +  }
  18.163 +
  18.164 +  /* Initialize bit buffer to empty */
  18.165 +  entropy->saved.put_buffer = 0;
  18.166 +  entropy->saved.put_bits = 0;
  18.167 +
  18.168 +  /* Initialize restart stuff */
  18.169 +  entropy->restarts_to_go = cinfo->restart_interval;
  18.170 +  entropy->next_restart_num = 0;
  18.171 +}
  18.172 +
  18.173 +
  18.174 +/*
  18.175 + * Compute the derived values for a Huffman table.
  18.176 + * This routine also performs some validation checks on the table.
  18.177 + *
  18.178 + * Note this is also used by jcphuff.c.
  18.179 + */
  18.180 +
  18.181 +GLOBAL(void)
  18.182 +jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  18.183 +			 c_derived_tbl ** pdtbl)
  18.184 +{
  18.185 +  JHUFF_TBL *htbl;
  18.186 +  c_derived_tbl *dtbl;
  18.187 +  int p, i, l, lastp, si, maxsymbol;
  18.188 +  char huffsize[257];
  18.189 +  unsigned int huffcode[257];
  18.190 +  unsigned int code;
  18.191 +
  18.192 +  /* Note that huffsize[] and huffcode[] are filled in code-length order,
  18.193 +   * paralleling the order of the symbols themselves in htbl->huffval[].
  18.194 +   */
  18.195 +
  18.196 +  /* Find the input Huffman table */
  18.197 +  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  18.198 +    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  18.199 +  htbl =
  18.200 +    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  18.201 +  if (htbl == NULL)
  18.202 +    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  18.203 +
  18.204 +  /* Allocate a workspace if we haven't already done so. */
  18.205 +  if (*pdtbl == NULL)
  18.206 +    *pdtbl = (c_derived_tbl *)
  18.207 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  18.208 +				  SIZEOF(c_derived_tbl));
  18.209 +  dtbl = *pdtbl;
  18.210 +  
  18.211 +  /* Figure C.1: make table of Huffman code length for each symbol */
  18.212 +
  18.213 +  p = 0;
  18.214 +  for (l = 1; l <= 16; l++) {
  18.215 +    i = (int) htbl->bits[l];
  18.216 +    if (i < 0 || p + i > 256)	/* protect against table overrun */
  18.217 +      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  18.218 +    while (i--)
  18.219 +      huffsize[p++] = (char) l;
  18.220 +  }
  18.221 +  huffsize[p] = 0;
  18.222 +  lastp = p;
  18.223 +  
  18.224 +  /* Figure C.2: generate the codes themselves */
  18.225 +  /* We also validate that the counts represent a legal Huffman code tree. */
  18.226 +
  18.227 +  code = 0;
  18.228 +  si = huffsize[0];
  18.229 +  p = 0;
  18.230 +  while (huffsize[p]) {
  18.231 +    while (((int) huffsize[p]) == si) {
  18.232 +      huffcode[p++] = code;
  18.233 +      code++;
  18.234 +    }
  18.235 +    /* code is now 1 more than the last code used for codelength si; but
  18.236 +     * it must still fit in si bits, since no code is allowed to be all ones.
  18.237 +     */
  18.238 +    if (((INT32) code) >= (((INT32) 1) << si))
  18.239 +      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  18.240 +    code <<= 1;
  18.241 +    si++;
  18.242 +  }
  18.243 +  
  18.244 +  /* Figure C.3: generate encoding tables */
  18.245 +  /* These are code and size indexed by symbol value */
  18.246 +
  18.247 +  /* Set all codeless symbols to have code length 0;
  18.248 +   * this lets us detect duplicate VAL entries here, and later
  18.249 +   * allows emit_bits to detect any attempt to emit such symbols.
  18.250 +   */
  18.251 +  MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  18.252 +
  18.253 +  /* This is also a convenient place to check for out-of-range
  18.254 +   * and duplicated VAL entries.  We allow 0..255 for AC symbols
  18.255 +   * but only 0..15 for DC.  (We could constrain them further
  18.256 +   * based on data depth and mode, but this seems enough.)
  18.257 +   */
  18.258 +  maxsymbol = isDC ? 15 : 255;
  18.259 +
  18.260 +  for (p = 0; p < lastp; p++) {
  18.261 +    i = htbl->huffval[p];
  18.262 +    if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  18.263 +      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  18.264 +    dtbl->ehufco[i] = huffcode[p];
  18.265 +    dtbl->ehufsi[i] = huffsize[p];
  18.266 +  }
  18.267 +}
  18.268 +
  18.269 +
  18.270 +/* Outputting bytes to the file */
  18.271 +
  18.272 +/* Emit a byte, taking 'action' if must suspend. */
  18.273 +#define emit_byte(state,val,action)  \
  18.274 +	{ *(state)->next_output_byte++ = (JOCTET) (val);  \
  18.275 +	  if (--(state)->free_in_buffer == 0)  \
  18.276 +	    if (! dump_buffer(state))  \
  18.277 +	      { action; } }
  18.278 +
  18.279 +
  18.280 +LOCAL(boolean)
  18.281 +dump_buffer (working_state * state)
  18.282 +/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  18.283 +{
  18.284 +  struct jpeg_destination_mgr * dest = state->cinfo->dest;
  18.285 +
  18.286 +  if (! (*dest->empty_output_buffer) (state->cinfo))
  18.287 +    return FALSE;
  18.288 +  /* After a successful buffer dump, must reset buffer pointers */
  18.289 +  state->next_output_byte = dest->next_output_byte;
  18.290 +  state->free_in_buffer = dest->free_in_buffer;
  18.291 +  return TRUE;
  18.292 +}
  18.293 +
  18.294 +
  18.295 +/* Outputting bits to the file */
  18.296 +
  18.297 +/* Only the right 24 bits of put_buffer are used; the valid bits are
  18.298 + * left-justified in this part.  At most 16 bits can be passed to emit_bits
  18.299 + * in one call, and we never retain more than 7 bits in put_buffer
  18.300 + * between calls, so 24 bits are sufficient.
  18.301 + */
  18.302 +
  18.303 +INLINE
  18.304 +LOCAL(boolean)
  18.305 +emit_bits (working_state * state, unsigned int code, int size)
  18.306 +/* Emit some bits; return TRUE if successful, FALSE if must suspend */
  18.307 +{
  18.308 +  /* This routine is heavily used, so it's worth coding tightly. */
  18.309 +  register INT32 put_buffer = (INT32) code;
  18.310 +  register int put_bits = state->cur.put_bits;
  18.311 +
  18.312 +  /* if size is 0, caller used an invalid Huffman table entry */
  18.313 +  if (size == 0)
  18.314 +    ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  18.315 +
  18.316 +  put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  18.317 +  
  18.318 +  put_bits += size;		/* new number of bits in buffer */
  18.319 +  
  18.320 +  put_buffer <<= 24 - put_bits; /* align incoming bits */
  18.321 +
  18.322 +  put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  18.323 +  
  18.324 +  while (put_bits >= 8) {
  18.325 +    int c = (int) ((put_buffer >> 16) & 0xFF);
  18.326 +    
  18.327 +    emit_byte(state, c, return FALSE);
  18.328 +    if (c == 0xFF) {		/* need to stuff a zero byte? */
  18.329 +      emit_byte(state, 0, return FALSE);
  18.330 +    }
  18.331 +    put_buffer <<= 8;
  18.332 +    put_bits -= 8;
  18.333 +  }
  18.334 +
  18.335 +  state->cur.put_buffer = put_buffer; /* update state variables */
  18.336 +  state->cur.put_bits = put_bits;
  18.337 +
  18.338 +  return TRUE;
  18.339 +}
  18.340 +
  18.341 +
  18.342 +LOCAL(boolean)
  18.343 +flush_bits (working_state * state)
  18.344 +{
  18.345 +  if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  18.346 +    return FALSE;
  18.347 +  state->cur.put_buffer = 0;	/* and reset bit-buffer to empty */
  18.348 +  state->cur.put_bits = 0;
  18.349 +  return TRUE;
  18.350 +}
  18.351 +
  18.352 +
  18.353 +/* Encode a single block's worth of coefficients */
  18.354 +
  18.355 +LOCAL(boolean)
  18.356 +encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  18.357 +		  c_derived_tbl *dctbl, c_derived_tbl *actbl)
  18.358 +{
  18.359 +  register int temp, temp2;
  18.360 +  register int nbits;
  18.361 +  register int k, r, i;
  18.362 +  
  18.363 +  /* Encode the DC coefficient difference per section F.1.2.1 */
  18.364 +  
  18.365 +  temp = temp2 = block[0] - last_dc_val;
  18.366 +
  18.367 +  if (temp < 0) {
  18.368 +    temp = -temp;		/* temp is abs value of input */
  18.369 +    /* For a negative input, want temp2 = bitwise complement of abs(input) */
  18.370 +    /* This code assumes we are on a two's complement machine */
  18.371 +    temp2--;
  18.372 +  }
  18.373 +  
  18.374 +  /* Find the number of bits needed for the magnitude of the coefficient */
  18.375 +  nbits = 0;
  18.376 +  while (temp) {
  18.377 +    nbits++;
  18.378 +    temp >>= 1;
  18.379 +  }
  18.380 +  /* Check for out-of-range coefficient values.
  18.381 +   * Since we're encoding a difference, the range limit is twice as much.
  18.382 +   */
  18.383 +  if (nbits > MAX_COEF_BITS+1)
  18.384 +    ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  18.385 +  
  18.386 +  /* Emit the Huffman-coded symbol for the number of bits */
  18.387 +  if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  18.388 +    return FALSE;
  18.389 +
  18.390 +  /* Emit that number of bits of the value, if positive, */
  18.391 +  /* or the complement of its magnitude, if negative. */
  18.392 +  if (nbits)			/* emit_bits rejects calls with size 0 */
  18.393 +    if (! emit_bits(state, (unsigned int) temp2, nbits))
  18.394 +      return FALSE;
  18.395 +
  18.396 +  /* Encode the AC coefficients per section F.1.2.2 */
  18.397 +  
  18.398 +  r = 0;			/* r = run length of zeros */
  18.399 +  
  18.400 +  for (k = 1; k < DCTSIZE2; k++) {
  18.401 +    if ((temp = block[jpeg_natural_order[k]]) == 0) {
  18.402 +      r++;
  18.403 +    } else {
  18.404 +      /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  18.405 +      while (r > 15) {
  18.406 +	if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  18.407 +	  return FALSE;
  18.408 +	r -= 16;
  18.409 +      }
  18.410 +
  18.411 +      temp2 = temp;
  18.412 +      if (temp < 0) {
  18.413 +	temp = -temp;		/* temp is abs value of input */
  18.414 +	/* This code assumes we are on a two's complement machine */
  18.415 +	temp2--;
  18.416 +      }
  18.417 +      
  18.418 +      /* Find the number of bits needed for the magnitude of the coefficient */
  18.419 +      nbits = 1;		/* there must be at least one 1 bit */
  18.420 +      while ((temp >>= 1))
  18.421 +	nbits++;
  18.422 +      /* Check for out-of-range coefficient values */
  18.423 +      if (nbits > MAX_COEF_BITS)
  18.424 +	ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  18.425 +      
  18.426 +      /* Emit Huffman symbol for run length / number of bits */
  18.427 +      i = (r << 4) + nbits;
  18.428 +      if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  18.429 +	return FALSE;
  18.430 +
  18.431 +      /* Emit that number of bits of the value, if positive, */
  18.432 +      /* or the complement of its magnitude, if negative. */
  18.433 +      if (! emit_bits(state, (unsigned int) temp2, nbits))
  18.434 +	return FALSE;
  18.435 +      
  18.436 +      r = 0;
  18.437 +    }
  18.438 +  }
  18.439 +
  18.440 +  /* If the last coef(s) were zero, emit an end-of-block code */
  18.441 +  if (r > 0)
  18.442 +    if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  18.443 +      return FALSE;
  18.444 +
  18.445 +  return TRUE;
  18.446 +}
  18.447 +
  18.448 +
  18.449 +/*
  18.450 + * Emit a restart marker & resynchronize predictions.
  18.451 + */
  18.452 +
  18.453 +LOCAL(boolean)
  18.454 +emit_restart (working_state * state, int restart_num)
  18.455 +{
  18.456 +  int ci;
  18.457 +
  18.458 +  if (! flush_bits(state))
  18.459 +    return FALSE;
  18.460 +
  18.461 +  emit_byte(state, 0xFF, return FALSE);
  18.462 +  emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  18.463 +
  18.464 +  /* Re-initialize DC predictions to 0 */
  18.465 +  for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  18.466 +    state->cur.last_dc_val[ci] = 0;
  18.467 +
  18.468 +  /* The restart counter is not updated until we successfully write the MCU. */
  18.469 +
  18.470 +  return TRUE;
  18.471 +}
  18.472 +
  18.473 +
  18.474 +/*
  18.475 + * Encode and output one MCU's worth of Huffman-compressed coefficients.
  18.476 + */
  18.477 +
  18.478 +METHODDEF(boolean)
  18.479 +encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  18.480 +{
  18.481 +  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  18.482 +  working_state state;
  18.483 +  int blkn, ci;
  18.484 +  jpeg_component_info * compptr;
  18.485 +
  18.486 +  /* Load up working state */
  18.487 +  state.next_output_byte = cinfo->dest->next_output_byte;
  18.488 +  state.free_in_buffer = cinfo->dest->free_in_buffer;
  18.489 +  ASSIGN_STATE(state.cur, entropy->saved);
  18.490 +  state.cinfo = cinfo;
  18.491 +
  18.492 +  /* Emit restart marker if needed */
  18.493 +  if (cinfo->restart_interval) {
  18.494 +    if (entropy->restarts_to_go == 0)
  18.495 +      if (! emit_restart(&state, entropy->next_restart_num))
  18.496 +	return FALSE;
  18.497 +  }
  18.498 +
  18.499 +  /* Encode the MCU data blocks */
  18.500 +  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  18.501 +    ci = cinfo->MCU_membership[blkn];
  18.502 +    compptr = cinfo->cur_comp_info[ci];
  18.503 +    if (! encode_one_block(&state,
  18.504 +			   MCU_data[blkn][0], state.cur.last_dc_val[ci],
  18.505 +			   entropy->dc_derived_tbls[compptr->dc_tbl_no],
  18.506 +			   entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  18.507 +      return FALSE;
  18.508 +    /* Update last_dc_val */
  18.509 +    state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  18.510 +  }
  18.511 +
  18.512 +  /* Completed MCU, so update state */
  18.513 +  cinfo->dest->next_output_byte = state.next_output_byte;
  18.514 +  cinfo->dest->free_in_buffer = state.free_in_buffer;
  18.515 +  ASSIGN_STATE(entropy->saved, state.cur);
  18.516 +
  18.517 +  /* Update restart-interval state too */
  18.518 +  if (cinfo->restart_interval) {
  18.519 +    if (entropy->restarts_to_go == 0) {
  18.520 +      entropy->restarts_to_go = cinfo->restart_interval;
  18.521 +      entropy->next_restart_num++;
  18.522 +      entropy->next_restart_num &= 7;
  18.523 +    }
  18.524 +    entropy->restarts_to_go--;
  18.525 +  }
  18.526 +
  18.527 +  return TRUE;
  18.528 +}
  18.529 +
  18.530 +
  18.531 +/*
  18.532 + * Finish up at the end of a Huffman-compressed scan.
  18.533 + */
  18.534 +
  18.535 +METHODDEF(void)
  18.536 +finish_pass_huff (j_compress_ptr cinfo)
  18.537 +{
  18.538 +  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  18.539 +  working_state state;
  18.540 +
  18.541 +  /* Load up working state ... flush_bits needs it */
  18.542 +  state.next_output_byte = cinfo->dest->next_output_byte;
  18.543 +  state.free_in_buffer = cinfo->dest->free_in_buffer;
  18.544 +  ASSIGN_STATE(state.cur, entropy->saved);
  18.545 +  state.cinfo = cinfo;
  18.546 +
  18.547 +  /* Flush out the last data */
  18.548 +  if (! flush_bits(&state))
  18.549 +    ERREXIT(cinfo, JERR_CANT_SUSPEND);
  18.550 +
  18.551 +  /* Update state */
  18.552 +  cinfo->dest->next_output_byte = state.next_output_byte;
  18.553 +  cinfo->dest->free_in_buffer = state.free_in_buffer;
  18.554 +  ASSIGN_STATE(entropy->saved, state.cur);
  18.555 +}
  18.556 +
  18.557 +
  18.558 +/*
  18.559 + * Huffman coding optimization.
  18.560 + *
  18.561 + * We first scan the supplied data and count the number of uses of each symbol
  18.562 + * that is to be Huffman-coded. (This process MUST agree with the code above.)
  18.563 + * Then we build a Huffman coding tree for the observed counts.
  18.564 + * Symbols which are not needed at all for the particular image are not
  18.565 + * assigned any code, which saves space in the DHT marker as well as in
  18.566 + * the compressed data.
  18.567 + */
  18.568 +
  18.569 +#ifdef ENTROPY_OPT_SUPPORTED
  18.570 +
  18.571 +
  18.572 +/* Process a single block's worth of coefficients */
  18.573 +
  18.574 +LOCAL(void)
  18.575 +htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  18.576 +		 long dc_counts[], long ac_counts[])
  18.577 +{
  18.578 +  register int temp;
  18.579 +  register int nbits;
  18.580 +  register int k, r;
  18.581 +  
  18.582 +  /* Encode the DC coefficient difference per section F.1.2.1 */
  18.583 +  
  18.584 +  temp = block[0] - last_dc_val;
  18.585 +  if (temp < 0)
  18.586 +    temp = -temp;
  18.587 +  
  18.588 +  /* Find the number of bits needed for the magnitude of the coefficient */
  18.589 +  nbits = 0;
  18.590 +  while (temp) {
  18.591 +    nbits++;
  18.592 +    temp >>= 1;
  18.593 +  }
  18.594 +  /* Check for out-of-range coefficient values.
  18.595 +   * Since we're encoding a difference, the range limit is twice as much.
  18.596 +   */
  18.597 +  if (nbits > MAX_COEF_BITS+1)
  18.598 +    ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  18.599 +
  18.600 +  /* Count the Huffman symbol for the number of bits */
  18.601 +  dc_counts[nbits]++;
  18.602 +  
  18.603 +  /* Encode the AC coefficients per section F.1.2.2 */
  18.604 +  
  18.605 +  r = 0;			/* r = run length of zeros */
  18.606 +  
  18.607 +  for (k = 1; k < DCTSIZE2; k++) {
  18.608 +    if ((temp = block[jpeg_natural_order[k]]) == 0) {
  18.609 +      r++;
  18.610 +    } else {
  18.611 +      /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  18.612 +      while (r > 15) {
  18.613 +	ac_counts[0xF0]++;
  18.614 +	r -= 16;
  18.615 +      }
  18.616 +      
  18.617 +      /* Find the number of bits needed for the magnitude of the coefficient */
  18.618 +      if (temp < 0)
  18.619 +	temp = -temp;
  18.620 +      
  18.621 +      /* Find the number of bits needed for the magnitude of the coefficient */
  18.622 +      nbits = 1;		/* there must be at least one 1 bit */
  18.623 +      while ((temp >>= 1))
  18.624 +	nbits++;
  18.625 +      /* Check for out-of-range coefficient values */
  18.626 +      if (nbits > MAX_COEF_BITS)
  18.627 +	ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  18.628 +      
  18.629 +      /* Count Huffman symbol for run length / number of bits */
  18.630 +      ac_counts[(r << 4) + nbits]++;
  18.631 +      
  18.632 +      r = 0;
  18.633 +    }
  18.634 +  }
  18.635 +
  18.636 +  /* If the last coef(s) were zero, emit an end-of-block code */
  18.637 +  if (r > 0)
  18.638 +    ac_counts[0]++;
  18.639 +}
  18.640 +
  18.641 +
  18.642 +/*
  18.643 + * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  18.644 + * No data is actually output, so no suspension return is possible.
  18.645 + */
  18.646 +
  18.647 +METHODDEF(boolean)
  18.648 +encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  18.649 +{
  18.650 +  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  18.651 +  int blkn, ci;
  18.652 +  jpeg_component_info * compptr;
  18.653 +
  18.654 +  /* Take care of restart intervals if needed */
  18.655 +  if (cinfo->restart_interval) {
  18.656 +    if (entropy->restarts_to_go == 0) {
  18.657 +      /* Re-initialize DC predictions to 0 */
  18.658 +      for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  18.659 +	entropy->saved.last_dc_val[ci] = 0;
  18.660 +      /* Update restart state */
  18.661 +      entropy->restarts_to_go = cinfo->restart_interval;
  18.662 +    }
  18.663 +    entropy->restarts_to_go--;
  18.664 +  }
  18.665 +
  18.666 +  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  18.667 +    ci = cinfo->MCU_membership[blkn];
  18.668 +    compptr = cinfo->cur_comp_info[ci];
  18.669 +    htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  18.670 +		    entropy->dc_count_ptrs[compptr->dc_tbl_no],
  18.671 +		    entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  18.672 +    entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  18.673 +  }
  18.674 +
  18.675 +  return TRUE;
  18.676 +}
  18.677 +
  18.678 +
  18.679 +/*
  18.680 + * Generate the best Huffman code table for the given counts, fill htbl.
  18.681 + * Note this is also used by jcphuff.c.
  18.682 + *
  18.683 + * The JPEG standard requires that no symbol be assigned a codeword of all
  18.684 + * one bits (so that padding bits added at the end of a compressed segment
  18.685 + * can't look like a valid code).  Because of the canonical ordering of
  18.686 + * codewords, this just means that there must be an unused slot in the
  18.687 + * longest codeword length category.  Section K.2 of the JPEG spec suggests
  18.688 + * reserving such a slot by pretending that symbol 256 is a valid symbol
  18.689 + * with count 1.  In theory that's not optimal; giving it count zero but
  18.690 + * including it in the symbol set anyway should give a better Huffman code.
  18.691 + * But the theoretically better code actually seems to come out worse in
  18.692 + * practice, because it produces more all-ones bytes (which incur stuffed
  18.693 + * zero bytes in the final file).  In any case the difference is tiny.
  18.694 + *
  18.695 + * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  18.696 + * If some symbols have a very small but nonzero probability, the Huffman tree
  18.697 + * must be adjusted to meet the code length restriction.  We currently use
  18.698 + * the adjustment method suggested in JPEG section K.2.  This method is *not*
  18.699 + * optimal; it may not choose the best possible limited-length code.  But
  18.700 + * typically only very-low-frequency symbols will be given less-than-optimal
  18.701 + * lengths, so the code is almost optimal.  Experimental comparisons against
  18.702 + * an optimal limited-length-code algorithm indicate that the difference is
  18.703 + * microscopic --- usually less than a hundredth of a percent of total size.
  18.704 + * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  18.705 + */
  18.706 +
  18.707 +GLOBAL(void)
  18.708 +jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  18.709 +{
  18.710 +#define MAX_CLEN 32		/* assumed maximum initial code length */
  18.711 +  UINT8 bits[MAX_CLEN+1];	/* bits[k] = # of symbols with code length k */
  18.712 +  int codesize[257];		/* codesize[k] = code length of symbol k */
  18.713 +  int others[257];		/* next symbol in current branch of tree */
  18.714 +  int c1, c2;
  18.715 +  int p, i, j;
  18.716 +  long v;
  18.717 +
  18.718 +  /* This algorithm is explained in section K.2 of the JPEG standard */
  18.719 +
  18.720 +  MEMZERO(bits, SIZEOF(bits));
  18.721 +  MEMZERO(codesize, SIZEOF(codesize));
  18.722 +  for (i = 0; i < 257; i++)
  18.723 +    others[i] = -1;		/* init links to empty */
  18.724 +  
  18.725 +  freq[256] = 1;		/* make sure 256 has a nonzero count */
  18.726 +  /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  18.727 +   * that no real symbol is given code-value of all ones, because 256
  18.728 +   * will be placed last in the largest codeword category.
  18.729 +   */
  18.730 +
  18.731 +  /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  18.732 +
  18.733 +  for (;;) {
  18.734 +    /* Find the smallest nonzero frequency, set c1 = its symbol */
  18.735 +    /* In case of ties, take the larger symbol number */
  18.736 +    c1 = -1;
  18.737 +    v = 1000000000L;
  18.738 +    for (i = 0; i <= 256; i++) {
  18.739 +      if (freq[i] && freq[i] <= v) {
  18.740 +	v = freq[i];
  18.741 +	c1 = i;
  18.742 +      }
  18.743 +    }
  18.744 +
  18.745 +    /* Find the next smallest nonzero frequency, set c2 = its symbol */
  18.746 +    /* In case of ties, take the larger symbol number */
  18.747 +    c2 = -1;
  18.748 +    v = 1000000000L;
  18.749 +    for (i = 0; i <= 256; i++) {
  18.750 +      if (freq[i] && freq[i] <= v && i != c1) {
  18.751 +	v = freq[i];
  18.752 +	c2 = i;
  18.753 +      }
  18.754 +    }
  18.755 +
  18.756 +    /* Done if we've merged everything into one frequency */
  18.757 +    if (c2 < 0)
  18.758 +      break;
  18.759 +    
  18.760 +    /* Else merge the two counts/trees */
  18.761 +    freq[c1] += freq[c2];
  18.762 +    freq[c2] = 0;
  18.763 +
  18.764 +    /* Increment the codesize of everything in c1's tree branch */
  18.765 +    codesize[c1]++;
  18.766 +    while (others[c1] >= 0) {
  18.767 +      c1 = others[c1];
  18.768 +      codesize[c1]++;
  18.769 +    }
  18.770 +    
  18.771 +    others[c1] = c2;		/* chain c2 onto c1's tree branch */
  18.772 +    
  18.773 +    /* Increment the codesize of everything in c2's tree branch */
  18.774 +    codesize[c2]++;
  18.775 +    while (others[c2] >= 0) {
  18.776 +      c2 = others[c2];
  18.777 +      codesize[c2]++;
  18.778 +    }
  18.779 +  }
  18.780 +
  18.781 +  /* Now count the number of symbols of each code length */
  18.782 +  for (i = 0; i <= 256; i++) {
  18.783 +    if (codesize[i]) {
  18.784 +      /* The JPEG standard seems to think that this can't happen, */
  18.785 +      /* but I'm paranoid... */
  18.786 +      if (codesize[i] > MAX_CLEN)
  18.787 +	ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  18.788 +
  18.789 +      bits[codesize[i]]++;
  18.790 +    }
  18.791 +  }
  18.792 +
  18.793 +  /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  18.794 +   * Huffman procedure assigned any such lengths, we must adjust the coding.
  18.795 +   * Here is what the JPEG spec says about how this next bit works:
  18.796 +   * Since symbols are paired for the longest Huffman code, the symbols are
  18.797 +   * removed from this length category two at a time.  The prefix for the pair
  18.798 +   * (which is one bit shorter) is allocated to one of the pair; then,
  18.799 +   * skipping the BITS entry for that prefix length, a code word from the next
  18.800 +   * shortest nonzero BITS entry is converted into a prefix for two code words
  18.801 +   * one bit longer.
  18.802 +   */
  18.803 +  
  18.804 +  for (i = MAX_CLEN; i > 16; i--) {
  18.805 +    while (bits[i] > 0) {
  18.806 +      j = i - 2;		/* find length of new prefix to be used */
  18.807 +      while (bits[j] == 0)
  18.808 +	j--;
  18.809 +      
  18.810 +      bits[i] -= 2;		/* remove two symbols */
  18.811 +      bits[i-1]++;		/* one goes in this length */
  18.812 +      bits[j+1] += 2;		/* two new symbols in this length */
  18.813 +      bits[j]--;		/* symbol of this length is now a prefix */
  18.814 +    }
  18.815 +  }
  18.816 +
  18.817 +  /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  18.818 +  while (bits[i] == 0)		/* find largest codelength still in use */
  18.819 +    i--;
  18.820 +  bits[i]--;
  18.821 +  
  18.822 +  /* Return final symbol counts (only for lengths 0..16) */
  18.823 +  MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  18.824 +  
  18.825 +  /* Return a list of the symbols sorted by code length */
  18.826 +  /* It's not real clear to me why we don't need to consider the codelength
  18.827 +   * changes made above, but the JPEG spec seems to think this works.
  18.828 +   */
  18.829 +  p = 0;
  18.830 +  for (i = 1; i <= MAX_CLEN; i++) {
  18.831 +    for (j = 0; j <= 255; j++) {
  18.832 +      if (codesize[j] == i) {
  18.833 +	htbl->huffval[p] = (UINT8) j;
  18.834 +	p++;
  18.835 +      }
  18.836 +    }
  18.837 +  }
  18.838 +
  18.839 +  /* Set sent_table FALSE so updated table will be written to JPEG file. */
  18.840 +  htbl->sent_table = FALSE;
  18.841 +}
  18.842 +
  18.843 +
  18.844 +/*
  18.845 + * Finish up a statistics-gathering pass and create the new Huffman tables.
  18.846 + */
  18.847 +
  18.848 +METHODDEF(void)
  18.849 +finish_pass_gather (j_compress_ptr cinfo)
  18.850 +{
  18.851 +  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  18.852 +  int ci, dctbl, actbl;
  18.853 +  jpeg_component_info * compptr;
  18.854 +  JHUFF_TBL **htblptr;
  18.855 +  boolean did_dc[NUM_HUFF_TBLS];
  18.856 +  boolean did_ac[NUM_HUFF_TBLS];
  18.857 +
  18.858 +  /* It's important not to apply jpeg_gen_optimal_table more than once
  18.859 +   * per table, because it clobbers the input frequency counts!
  18.860 +   */
  18.861 +  MEMZERO(did_dc, SIZEOF(did_dc));
  18.862 +  MEMZERO(did_ac, SIZEOF(did_ac));
  18.863 +
  18.864 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  18.865 +    compptr = cinfo->cur_comp_info[ci];
  18.866 +    dctbl = compptr->dc_tbl_no;
  18.867 +    actbl = compptr->ac_tbl_no;
  18.868 +    if (! did_dc[dctbl]) {
  18.869 +      htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  18.870 +      if (*htblptr == NULL)
  18.871 +	*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  18.872 +      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  18.873 +      did_dc[dctbl] = TRUE;
  18.874 +    }
  18.875 +    if (! did_ac[actbl]) {
  18.876 +      htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  18.877 +      if (*htblptr == NULL)
  18.878 +	*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  18.879 +      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  18.880 +      did_ac[actbl] = TRUE;
  18.881 +    }
  18.882 +  }
  18.883 +}
  18.884 +
  18.885 +
  18.886 +#endif /* ENTROPY_OPT_SUPPORTED */
  18.887 +
  18.888 +
  18.889 +/*
  18.890 + * Module initialization routine for Huffman entropy encoding.
  18.891 + */
  18.892 +
  18.893 +GLOBAL(void)
  18.894 +jinit_huff_encoder (j_compress_ptr cinfo)
  18.895 +{
  18.896 +  huff_entropy_ptr entropy;
  18.897 +  int i;
  18.898 +
  18.899 +  entropy = (huff_entropy_ptr)
  18.900 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  18.901 +				SIZEOF(huff_entropy_encoder));
  18.902 +  cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  18.903 +  entropy->pub.start_pass = start_pass_huff;
  18.904 +
  18.905 +  /* Mark tables unallocated */
  18.906 +  for (i = 0; i < NUM_HUFF_TBLS; i++) {
  18.907 +    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  18.908 +#ifdef ENTROPY_OPT_SUPPORTED
  18.909 +    entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  18.910 +#endif
  18.911 +  }
  18.912 +}
    19.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    19.2 +++ b/libs/libjpeg/jchuff.h	Thu Sep 08 06:28:38 2011 +0300
    19.3 @@ -0,0 +1,47 @@
    19.4 +/*
    19.5 + * jchuff.h
    19.6 + *
    19.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    19.8 + * This file is part of the Independent JPEG Group's software.
    19.9 + * For conditions of distribution and use, see the accompanying README file.
   19.10 + *
   19.11 + * This file contains declarations for Huffman entropy encoding routines
   19.12 + * that are shared between the sequential encoder (jchuff.c) and the
   19.13 + * progressive encoder (jcphuff.c).  No other modules need to see these.
   19.14 + */
   19.15 +
   19.16 +/* The legal range of a DCT coefficient is
   19.17 + *  -1024 .. +1023  for 8-bit data;
   19.18 + * -16384 .. +16383 for 12-bit data.
   19.19 + * Hence the magnitude should always fit in 10 or 14 bits respectively.
   19.20 + */
   19.21 +
   19.22 +#if BITS_IN_JSAMPLE == 8
   19.23 +#define MAX_COEF_BITS 10
   19.24 +#else
   19.25 +#define MAX_COEF_BITS 14
   19.26 +#endif
   19.27 +
   19.28 +/* Derived data constructed for each Huffman table */
   19.29 +
   19.30 +typedef struct {
   19.31 +  unsigned int ehufco[256];	/* code for each symbol */
   19.32 +  char ehufsi[256];		/* length of code for each symbol */
   19.33 +  /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
   19.34 +} c_derived_tbl;
   19.35 +
   19.36 +/* Short forms of external names for systems with brain-damaged linkers. */
   19.37 +
   19.38 +#ifdef NEED_SHORT_EXTERNAL_NAMES
   19.39 +#define jpeg_make_c_derived_tbl	jMkCDerived
   19.40 +#define jpeg_gen_optimal_table	jGenOptTbl
   19.41 +#endif /* NEED_SHORT_EXTERNAL_NAMES */
   19.42 +
   19.43 +/* Expand a Huffman table definition into the derived format */
   19.44 +EXTERN(void) jpeg_make_c_derived_tbl
   19.45 +	JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
   19.46 +	     c_derived_tbl ** pdtbl));
   19.47 +
   19.48 +/* Generate an optimal table definition given the specified counts */
   19.49 +EXTERN(void) jpeg_gen_optimal_table
   19.50 +	JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
    20.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    20.2 +++ b/libs/libjpeg/jcinit.c	Thu Sep 08 06:28:38 2011 +0300
    20.3 @@ -0,0 +1,72 @@
    20.4 +/*
    20.5 + * jcinit.c
    20.6 + *
    20.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    20.8 + * This file is part of the Independent JPEG Group's software.
    20.9 + * For conditions of distribution and use, see the accompanying README file.
   20.10 + *
   20.11 + * This file contains initialization logic for the JPEG compressor.
   20.12 + * This routine is in charge of selecting the modules to be executed and
   20.13 + * making an initialization call to each one.
   20.14 + *
   20.15 + * Logically, this code belongs in jcmaster.c.  It's split out because
   20.16 + * linking this routine implies linking the entire compression library.
   20.17 + * For a transcoding-only application, we want to be able to use jcmaster.c
   20.18 + * without linking in the whole library.
   20.19 + */
   20.20 +
   20.21 +#define JPEG_INTERNALS
   20.22 +#include "jinclude.h"
   20.23 +#include "jpeglib.h"
   20.24 +
   20.25 +
   20.26 +/*
   20.27 + * Master selection of compression modules.
   20.28 + * This is done once at the start of processing an image.  We determine
   20.29 + * which modules will be used and give them appropriate initialization calls.
   20.30 + */
   20.31 +
   20.32 +GLOBAL(void)
   20.33 +jinit_compress_master (j_compress_ptr cinfo)
   20.34 +{
   20.35 +  /* Initialize master control (includes parameter checking/processing) */
   20.36 +  jinit_c_master_control(cinfo, FALSE /* full compression */);
   20.37 +
   20.38 +  /* Preprocessing */
   20.39 +  if (! cinfo->raw_data_in) {
   20.40 +    jinit_color_converter(cinfo);
   20.41 +    jinit_downsampler(cinfo);
   20.42 +    jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
   20.43 +  }
   20.44 +  /* Forward DCT */
   20.45 +  jinit_forward_dct(cinfo);
   20.46 +  /* Entropy encoding: either Huffman or arithmetic coding. */
   20.47 +  if (cinfo->arith_code) {
   20.48 +    ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
   20.49 +  } else {
   20.50 +    if (cinfo->progressive_mode) {
   20.51 +#ifdef C_PROGRESSIVE_SUPPORTED
   20.52 +      jinit_phuff_encoder(cinfo);
   20.53 +#else
   20.54 +      ERREXIT(cinfo, JERR_NOT_COMPILED);
   20.55 +#endif
   20.56 +    } else
   20.57 +      jinit_huff_encoder(cinfo);
   20.58 +  }
   20.59 +
   20.60 +  /* Need a full-image coefficient buffer in any multi-pass mode. */
   20.61 +  jinit_c_coef_controller(cinfo,
   20.62 +		(boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
   20.63 +  jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
   20.64 +
   20.65 +  jinit_marker_writer(cinfo);
   20.66 +
   20.67 +  /* We can now tell the memory manager to allocate virtual arrays. */
   20.68 +  (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
   20.69 +
   20.70 +  /* Write the datastream header (SOI) immediately.
   20.71 +   * Frame and scan headers are postponed till later.
   20.72 +   * This lets application insert special markers after the SOI.
   20.73 +   */
   20.74 +  (*cinfo->marker->write_file_header) (cinfo);
   20.75 +}
    21.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    21.2 +++ b/libs/libjpeg/jcmainct.c	Thu Sep 08 06:28:38 2011 +0300
    21.3 @@ -0,0 +1,293 @@
    21.4 +/*
    21.5 + * jcmainct.c
    21.6 + *
    21.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    21.8 + * This file is part of the Independent JPEG Group's software.
    21.9 + * For conditions of distribution and use, see the accompanying README file.
   21.10 + *
   21.11 + * This file contains the main buffer controller for compression.
   21.12 + * The main buffer lies between the pre-processor and the JPEG
   21.13 + * compressor proper; it holds downsampled data in the JPEG colorspace.
   21.14 + */
   21.15 +
   21.16 +#define JPEG_INTERNALS
   21.17 +#include "jinclude.h"
   21.18 +#include "jpeglib.h"
   21.19 +
   21.20 +
   21.21 +/* Note: currently, there is no operating mode in which a full-image buffer
   21.22 + * is needed at this step.  If there were, that mode could not be used with
   21.23 + * "raw data" input, since this module is bypassed in that case.  However,
   21.24 + * we've left the code here for possible use in special applications.
   21.25 + */
   21.26 +#undef FULL_MAIN_BUFFER_SUPPORTED
   21.27 +
   21.28 +
   21.29 +/* Private buffer controller object */
   21.30 +
   21.31 +typedef struct {
   21.32 +  struct jpeg_c_main_controller pub; /* public fields */
   21.33 +
   21.34 +  JDIMENSION cur_iMCU_row;	/* number of current iMCU row */
   21.35 +  JDIMENSION rowgroup_ctr;	/* counts row groups received in iMCU row */
   21.36 +  boolean suspended;		/* remember if we suspended output */
   21.37 +  J_BUF_MODE pass_mode;		/* current operating mode */
   21.38 +
   21.39 +  /* If using just a strip buffer, this points to the entire set of buffers
   21.40 +   * (we allocate one for each component).  In the full-image case, this
   21.41 +   * points to the currently accessible strips of the virtual arrays.
   21.42 +   */
   21.43 +  JSAMPARRAY buffer[MAX_COMPONENTS];
   21.44 +
   21.45 +#ifdef FULL_MAIN_BUFFER_SUPPORTED
   21.46 +  /* If using full-image storage, this array holds pointers to virtual-array
   21.47 +   * control blocks for each component.  Unused if not full-image storage.
   21.48 +   */
   21.49 +  jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
   21.50 +#endif
   21.51 +} my_main_controller;
   21.52 +
   21.53 +typedef my_main_controller * my_main_ptr;
   21.54 +
   21.55 +
   21.56 +/* Forward declarations */
   21.57 +METHODDEF(void) process_data_simple_main
   21.58 +	JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
   21.59 +	     JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
   21.60 +#ifdef FULL_MAIN_BUFFER_SUPPORTED
   21.61 +METHODDEF(void) process_data_buffer_main
   21.62 +	JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
   21.63 +	     JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
   21.64 +#endif
   21.65 +
   21.66 +
   21.67 +/*
   21.68 + * Initialize for a processing pass.
   21.69 + */
   21.70 +
   21.71 +METHODDEF(void)
   21.72 +start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
   21.73 +{
   21.74 +  my_main_ptr main = (my_main_ptr) cinfo->main;
   21.75 +
   21.76 +  /* Do nothing in raw-data mode. */
   21.77 +  if (cinfo->raw_data_in)
   21.78 +    return;
   21.79 +
   21.80 +  main->cur_iMCU_row = 0;	/* initialize counters */
   21.81 +  main->rowgroup_ctr = 0;
   21.82 +  main->suspended = FALSE;
   21.83 +  main->pass_mode = pass_mode;	/* save mode for use by process_data */
   21.84 +
   21.85 +  switch (pass_mode) {
   21.86 +  case JBUF_PASS_THRU:
   21.87 +#ifdef FULL_MAIN_BUFFER_SUPPORTED
   21.88 +    if (main->whole_image[0] != NULL)
   21.89 +      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
   21.90 +#endif
   21.91 +    main->pub.process_data = process_data_simple_main;
   21.92 +    break;
   21.93 +#ifdef FULL_MAIN_BUFFER_SUPPORTED
   21.94 +  case JBUF_SAVE_SOURCE:
   21.95 +  case JBUF_CRANK_DEST:
   21.96 +  case JBUF_SAVE_AND_PASS:
   21.97 +    if (main->whole_image[0] == NULL)
   21.98 +      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
   21.99 +    main->pub.process_data = process_data_buffer_main;
  21.100 +    break;
  21.101 +#endif
  21.102 +  default:
  21.103 +    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  21.104 +    break;
  21.105 +  }
  21.106 +}
  21.107 +
  21.108 +
  21.109 +/*
  21.110 + * Process some data.
  21.111 + * This routine handles the simple pass-through mode,
  21.112 + * where we have only a strip buffer.
  21.113 + */
  21.114 +
  21.115 +METHODDEF(void)
  21.116 +process_data_simple_main (j_compress_ptr cinfo,
  21.117 +			  JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  21.118 +			  JDIMENSION in_rows_avail)
  21.119 +{
  21.120 +  my_main_ptr main = (my_main_ptr) cinfo->main;
  21.121 +
  21.122 +  while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  21.123 +    /* Read input data if we haven't filled the main buffer yet */
  21.124 +    if (main->rowgroup_ctr < DCTSIZE)
  21.125 +      (*cinfo->prep->pre_process_data) (cinfo,
  21.126 +					input_buf, in_row_ctr, in_rows_avail,
  21.127 +					main->buffer, &main->rowgroup_ctr,
  21.128 +					(JDIMENSION) DCTSIZE);
  21.129 +
  21.130 +    /* If we don't have a full iMCU row buffered, return to application for
  21.131 +     * more data.  Note that preprocessor will always pad to fill the iMCU row
  21.132 +     * at the bottom of the image.
  21.133 +     */
  21.134 +    if (main->rowgroup_ctr != DCTSIZE)
  21.135 +      return;
  21.136 +
  21.137 +    /* Send the completed row to the compressor */
  21.138 +    if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  21.139 +      /* If compressor did not consume the whole row, then we must need to
  21.140 +       * suspend processing and return to the application.  In this situation
  21.141 +       * we pretend we didn't yet consume the last input row; otherwise, if
  21.142 +       * it happened to be the last row of the image, the application would
  21.143 +       * think we were done.
  21.144 +       */
  21.145 +      if (! main->suspended) {
  21.146 +	(*in_row_ctr)--;
  21.147 +	main->suspended = TRUE;
  21.148 +      }
  21.149 +      return;
  21.150 +    }
  21.151 +    /* We did finish the row.  Undo our little suspension hack if a previous
  21.152 +     * call suspended; then mark the main buffer empty.
  21.153 +     */
  21.154 +    if (main->suspended) {
  21.155 +      (*in_row_ctr)++;
  21.156 +      main->suspended = FALSE;
  21.157 +    }
  21.158 +    main->rowgroup_ctr = 0;
  21.159 +    main->cur_iMCU_row++;
  21.160 +  }
  21.161 +}
  21.162 +
  21.163 +
  21.164 +#ifdef FULL_MAIN_BUFFER_SUPPORTED
  21.165 +
  21.166 +/*
  21.167 + * Process some data.
  21.168 + * This routine handles all of the modes that use a full-size buffer.
  21.169 + */
  21.170 +
  21.171 +METHODDEF(void)
  21.172 +process_data_buffer_main (j_compress_ptr cinfo,
  21.173 +			  JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  21.174 +			  JDIMENSION in_rows_avail)
  21.175 +{
  21.176 +  my_main_ptr main = (my_main_ptr) cinfo->main;
  21.177 +  int ci;
  21.178 +  jpeg_component_info *compptr;
  21.179 +  boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  21.180 +
  21.181 +  while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  21.182 +    /* Realign the virtual buffers if at the start of an iMCU row. */
  21.183 +    if (main->rowgroup_ctr == 0) {
  21.184 +      for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  21.185 +	   ci++, compptr++) {
  21.186 +	main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  21.187 +	  ((j_common_ptr) cinfo, main->whole_image[ci],
  21.188 +	   main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  21.189 +	   (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  21.190 +      }
  21.191 +      /* In a read pass, pretend we just read some source data. */
  21.192 +      if (! writing) {
  21.193 +	*in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  21.194 +	main->rowgroup_ctr = DCTSIZE;
  21.195 +      }
  21.196 +    }
  21.197 +
  21.198 +    /* If a write pass, read input data until the current iMCU row is full. */
  21.199 +    /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  21.200 +    if (writing) {
  21.201 +      (*cinfo->prep->pre_process_data) (cinfo,
  21.202 +					input_buf, in_row_ctr, in_rows_avail,
  21.203 +					main->buffer, &main->rowgroup_ctr,
  21.204 +					(JDIMENSION) DCTSIZE);
  21.205 +      /* Return to application if we need more data to fill the iMCU row. */
  21.206 +      if (main->rowgroup_ctr < DCTSIZE)
  21.207 +	return;
  21.208 +    }
  21.209 +
  21.210 +    /* Emit data, unless this is a sink-only pass. */
  21.211 +    if (main->pass_mode != JBUF_SAVE_SOURCE) {
  21.212 +      if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  21.213 +	/* If compressor did not consume the whole row, then we must need to
  21.214 +	 * suspend processing and return to the application.  In this situation
  21.215 +	 * we pretend we didn't yet consume the last input row; otherwise, if
  21.216 +	 * it happened to be the last row of the image, the application would
  21.217 +	 * think we were done.
  21.218 +	 */
  21.219 +	if (! main->suspended) {
  21.220 +	  (*in_row_ctr)--;
  21.221 +	  main->suspended = TRUE;
  21.222 +	}
  21.223 +	return;
  21.224 +      }
  21.225 +      /* We did finish the row.  Undo our little suspension hack if a previous
  21.226 +       * call suspended; then mark the main buffer empty.
  21.227 +       */
  21.228 +      if (main->suspended) {
  21.229 +	(*in_row_ctr)++;
  21.230 +	main->suspended = FALSE;
  21.231 +      }
  21.232 +    }
  21.233 +
  21.234 +    /* If get here, we are done with this iMCU row.  Mark buffer empty. */
  21.235 +    main->rowgroup_ctr = 0;
  21.236 +    main->cur_iMCU_row++;
  21.237 +  }
  21.238 +}
  21.239 +
  21.240 +#endif /* FULL_MAIN_BUFFER_SUPPORTED */
  21.241 +
  21.242 +
  21.243 +/*
  21.244 + * Initialize main buffer controller.
  21.245 + */
  21.246 +
  21.247 +GLOBAL(void)
  21.248 +jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  21.249 +{
  21.250 +  my_main_ptr main;
  21.251 +  int ci;
  21.252 +  jpeg_component_info *compptr;
  21.253 +
  21.254 +  main = (my_main_ptr)
  21.255 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  21.256 +				SIZEOF(my_main_controller));
  21.257 +  cinfo->main = (struct jpeg_c_main_controller *) main;
  21.258 +  main->pub.start_pass = start_pass_main;
  21.259 +
  21.260 +  /* We don't need to create a buffer in raw-data mode. */
  21.261 +  if (cinfo->raw_data_in)
  21.262 +    return;
  21.263 +
  21.264 +  /* Create the buffer.  It holds downsampled data, so each component
  21.265 +   * may be of a different size.
  21.266 +   */
  21.267 +  if (need_full_buffer) {
  21.268 +#ifdef FULL_MAIN_BUFFER_SUPPORTED
  21.269 +    /* Allocate a full-image virtual array for each component */
  21.270 +    /* Note we pad the bottom to a multiple of the iMCU height */
  21.271 +    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  21.272 +	 ci++, compptr++) {
  21.273 +      main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  21.274 +	((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  21.275 +	 compptr->width_in_blocks * DCTSIZE,
  21.276 +	 (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  21.277 +				(long) compptr->v_samp_factor) * DCTSIZE,
  21.278 +	 (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  21.279 +    }
  21.280 +#else
  21.281 +    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  21.282 +#endif
  21.283 +  } else {
  21.284 +#ifdef FULL_MAIN_BUFFER_SUPPORTED
  21.285 +    main->whole_image[0] = NULL; /* flag for no virtual arrays */
  21.286 +#endif
  21.287 +    /* Allocate a strip buffer for each component */
  21.288 +    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  21.289 +	 ci++, compptr++) {
  21.290 +      main->buffer[ci] = (*cinfo->mem->alloc_sarray)
  21.291 +	((j_common_ptr) cinfo, JPOOL_IMAGE,
  21.292 +	 compptr->width_in_blocks * DCTSIZE,
  21.293 +	 (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  21.294 +    }
  21.295 +  }
  21.296 +}
    22.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    22.2 +++ b/libs/libjpeg/jcmarker.c	Thu Sep 08 06:28:38 2011 +0300
    22.3 @@ -0,0 +1,664 @@
    22.4 +/*
    22.5 + * jcmarker.c
    22.6 + *
    22.7 + * Copyright (C) 1991-1998, Thomas G. Lane.
    22.8 + * This file is part of the Independent JPEG Group's software.
    22.9 + * For conditions of distribution and use, see the accompanying README file.
   22.10 + *
   22.11 + * This file contains routines to write JPEG datastream markers.
   22.12 + */
   22.13 +
   22.14 +#define JPEG_INTERNALS
   22.15 +#include "jinclude.h"
   22.16 +#include "jpeglib.h"
   22.17 +
   22.18 +
   22.19 +typedef enum {			/* JPEG marker codes */
   22.20 +  M_SOF0  = 0xc0,
   22.21 +  M_SOF1  = 0xc1,
   22.22 +  M_SOF2  = 0xc2,
   22.23 +  M_SOF3  = 0xc3,
   22.24 +  
   22.25 +  M_SOF5  = 0xc5,
   22.26 +  M_SOF6  = 0xc6,
   22.27 +  M_SOF7  = 0xc7,
   22.28 +  
   22.29 +  M_JPG   = 0xc8,
   22.30 +  M_SOF9  = 0xc9,
   22.31 +  M_SOF10 = 0xca,
   22.32 +  M_SOF11 = 0xcb,
   22.33 +  
   22.34 +  M_SOF13 = 0xcd,
   22.35 +  M_SOF14 = 0xce,
   22.36 +  M_SOF15 = 0xcf,
   22.37 +  
   22.38 +  M_DHT   = 0xc4,
   22.39 +  
   22.40 +  M_DAC   = 0xcc,
   22.41 +  
   22.42 +  M_RST0  = 0xd0,
   22.43 +  M_RST1  = 0xd1,
   22.44 +  M_RST2  = 0xd2,
   22.45 +  M_RST3  = 0xd3,
   22.46 +  M_RST4  = 0xd4,
   22.47 +  M_RST5  = 0xd5,
   22.48 +  M_RST6  = 0xd6,
   22.49 +  M_RST7  = 0xd7,
   22.50 +  
   22.51 +  M_SOI   = 0xd8,
   22.52 +  M_EOI   = 0xd9,
   22.53 +  M_SOS   = 0xda,
   22.54 +  M_DQT   = 0xdb,
   22.55 +  M_DNL   = 0xdc,
   22.56 +  M_DRI   = 0xdd,
   22.57 +  M_DHP   = 0xde,
   22.58 +  M_EXP   = 0xdf,
   22.59 +  
   22.60 +  M_APP0  = 0xe0,
   22.61 +  M_APP1  = 0xe1,
   22.62 +  M_APP2  = 0xe2,
   22.63 +  M_APP3  = 0xe3,
   22.64 +  M_APP4  = 0xe4,
   22.65 +  M_APP5  = 0xe5,
   22.66 +  M_APP6  = 0xe6,
   22.67 +  M_APP7  = 0xe7,
   22.68 +  M_APP8  = 0xe8,
   22.69 +  M_APP9  = 0xe9,
   22.70 +  M_APP10 = 0xea,
   22.71 +  M_APP11 = 0xeb,
   22.72 +  M_APP12 = 0xec,
   22.73 +  M_APP13 = 0xed,
   22.74 +  M_APP14 = 0xee,
   22.75 +  M_APP15 = 0xef,
   22.76 +  
   22.77 +  M_JPG0  = 0xf0,
   22.78 +  M_JPG13 = 0xfd,
   22.79 +  M_COM   = 0xfe,
   22.80 +  
   22.81 +  M_TEM   = 0x01,
   22.82 +  
   22.83 +  M_ERROR = 0x100
   22.84 +} JPEG_MARKER;
   22.85 +
   22.86 +
   22.87 +/* Private state */
   22.88 +
   22.89 +typedef struct {
   22.90 +  struct jpeg_marker_writer pub; /* public fields */
   22.91 +
   22.92 +  unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
   22.93 +} my_marker_writer;
   22.94 +
   22.95 +typedef my_marker_writer * my_marker_ptr;
   22.96 +
   22.97 +
   22.98 +/*
   22.99 + * Basic output routines.
  22.100 + *
  22.101 + * Note that we do not support suspension while writing a marker.
  22.102 + * Therefore, an application using suspension must ensure that there is
  22.103 + * enough buffer space for the initial markers (typ. 600-700 bytes) before
  22.104 + * calling jpeg_start_compress, and enough space to write the trailing EOI
  22.105 + * (a few bytes) before calling jpeg_finish_compress.  Multipass compression
  22.106 + * modes are not supported at all with suspension, so those two are the only
  22.107 + * points where markers will be written.
  22.108 + */
  22.109 +
  22.110 +LOCAL(void)
  22.111 +emit_byte (j_compress_ptr cinfo, int val)
  22.112 +/* Emit a byte */
  22.113 +{
  22.114 +  struct jpeg_destination_mgr * dest = cinfo->dest;
  22.115 +
  22.116 +  *(dest->next_output_byte)++ = (JOCTET) val;
  22.117 +  if (--dest->free_in_buffer == 0) {
  22.118 +    if (! (*dest->empty_output_buffer) (cinfo))
  22.119 +      ERREXIT(cinfo, JERR_CANT_SUSPEND);
  22.120 +  }
  22.121 +}
  22.122 +
  22.123 +
  22.124 +LOCAL(void)
  22.125 +emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  22.126 +/* Emit a marker code */
  22.127 +{
  22.128 +  emit_byte(cinfo, 0xFF);
  22.129 +  emit_byte(cinfo, (int) mark);
  22.130 +}
  22.131 +
  22.132 +
  22.133 +LOCAL(void)
  22.134 +emit_2bytes (j_compress_ptr cinfo, int value)
  22.135 +/* Emit a 2-byte integer; these are always MSB first in JPEG files */
  22.136 +{
  22.137 +  emit_byte(cinfo, (value >> 8) & 0xFF);
  22.138 +  emit_byte(cinfo, value & 0xFF);
  22.139 +}
  22.140 +
  22.141 +
  22.142 +/*
  22.143 + * Routines to write specific marker types.
  22.144 + */
  22.145 +
  22.146 +LOCAL(int)
  22.147 +emit_dqt (j_compress_ptr cinfo, int index)
  22.148 +/* Emit a DQT marker */
  22.149 +/* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  22.150 +{
  22.151 +  JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  22.152 +  int prec;
  22.153 +  int i;
  22.154 +
  22.155 +  if (qtbl == NULL)
  22.156 +    ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  22.157 +
  22.158 +  prec = 0;
  22.159 +  for (i = 0; i < DCTSIZE2; i++) {
  22.160 +    if (qtbl->quantval[i] > 255)
  22.161 +      prec = 1;
  22.162 +  }
  22.163 +
  22.164 +  if (! qtbl->sent_table) {
  22.165 +    emit_marker(cinfo, M_DQT);
  22.166 +
  22.167 +    emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  22.168 +
  22.169 +    emit_byte(cinfo, index + (prec<<4));
  22.170 +
  22.171 +    for (i = 0; i < DCTSIZE2; i++) {
  22.172 +      /* The table entries must be emitted in zigzag order. */
  22.173 +      unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  22.174 +      if (prec)
  22.175 +	emit_byte(cinfo, (int) (qval >> 8));
  22.176 +      emit_byte(cinfo, (int) (qval & 0xFF));
  22.177 +    }
  22.178 +
  22.179 +    qtbl->sent_table = TRUE;
  22.180 +  }
  22.181 +
  22.182 +  return prec;
  22.183 +}
  22.184 +
  22.185 +
  22.186 +LOCAL(void)
  22.187 +emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  22.188 +/* Emit a DHT marker */
  22.189 +{
  22.190 +  JHUFF_TBL * htbl;
  22.191 +  int length, i;
  22.192 +  
  22.193 +  if (is_ac) {
  22.194 +    htbl = cinfo->ac_huff_tbl_ptrs[index];
  22.195 +    index += 0x10;		/* output index has AC bit set */
  22.196 +  } else {
  22.197 +    htbl = cinfo->dc_huff_tbl_ptrs[index];
  22.198 +  }
  22.199 +
  22.200 +  if (htbl == NULL)
  22.201 +    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  22.202 +  
  22.203 +  if (! htbl->sent_table) {
  22.204 +    emit_marker(cinfo, M_DHT);
  22.205 +    
  22.206 +    length = 0;
  22.207 +    for (i = 1; i <= 16; i++)
  22.208 +      length += htbl->bits[i];
  22.209 +    
  22.210 +    emit_2bytes(cinfo, length + 2 + 1 + 16);
  22.211 +    emit_byte(cinfo, index);
  22.212 +    
  22.213 +    for (i = 1; i <= 16; i++)
  22.214 +      emit_byte(cinfo, htbl->bits[i]);
  22.215 +    
  22.216 +    for (i = 0; i < length; i++)
  22.217 +      emit_byte(cinfo, htbl->huffval[i]);
  22.218 +    
  22.219 +    htbl->sent_table = TRUE;
  22.220 +  }
  22.221 +}
  22.222 +
  22.223 +
  22.224 +LOCAL(void)
  22.225 +emit_dac (j_compress_ptr cinfo)
  22.226 +/* Emit a DAC marker */
  22.227 +/* Since the useful info is so small, we want to emit all the tables in */
  22.228 +/* one DAC marker.  Therefore this routine does its own scan of the table. */
  22.229 +{
  22.230 +#ifdef C_ARITH_CODING_SUPPORTED
  22.231 +  char dc_in_use[NUM_ARITH_TBLS];
  22.232 +  char ac_in_use[NUM_ARITH_TBLS];
  22.233 +  int length, i;
  22.234 +  jpeg_component_info *compptr;
  22.235 +  
  22.236 +  for (i = 0; i < NUM_ARITH_TBLS; i++)
  22.237 +    dc_in_use[i] = ac_in_use[i] = 0;
  22.238 +  
  22.239 +  for (i = 0; i < cinfo->comps_in_scan; i++) {
  22.240 +    compptr = cinfo->cur_comp_info[i];
  22.241 +    dc_in_use[compptr->dc_tbl_no] = 1;
  22.242 +    ac_in_use[compptr->ac_tbl_no] = 1;
  22.243 +  }
  22.244 +  
  22.245 +  length = 0;
  22.246 +  for (i = 0; i < NUM_ARITH_TBLS; i++)
  22.247 +    length += dc_in_use[i] + ac_in_use[i];
  22.248 +  
  22.249 +  emit_marker(cinfo, M_DAC);
  22.250 +  
  22.251 +  emit_2bytes(cinfo, length*2 + 2);
  22.252 +  
  22.253 +  for (i = 0; i < NUM_ARITH_TBLS; i++) {
  22.254 +    if (dc_in_use[i]) {
  22.255 +      emit_byte(cinfo, i);
  22.256 +      emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  22.257 +    }
  22.258 +    if (ac_in_use[i]) {
  22.259 +      emit_byte(cinfo, i + 0x10);
  22.260 +      emit_byte(cinfo, cinfo->arith_ac_K[i]);
  22.261 +    }
  22.262 +  }
  22.263 +#endif /* C_ARITH_CODING_SUPPORTED */
  22.264 +}
  22.265 +
  22.266 +
  22.267 +LOCAL(void)
  22.268 +emit_dri (j_compress_ptr cinfo)
  22.269 +/* Emit a DRI marker */
  22.270 +{
  22.271 +  emit_marker(cinfo, M_DRI);
  22.272 +  
  22.273 +  emit_2bytes(cinfo, 4);	/* fixed length */
  22.274 +
  22.275 +  emit_2bytes(cinfo, (int) cinfo->restart_interval);
  22.276 +}
  22.277 +
  22.278 +
  22.279 +LOCAL(void)
  22.280 +emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  22.281 +/* Emit a SOF marker */
  22.282 +{
  22.283 +  int ci;
  22.284 +  jpeg_component_info *compptr;
  22.285 +  
  22.286 +  emit_marker(cinfo, code);
  22.287 +  
  22.288 +  emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  22.289 +
  22.290 +  /* Make sure image isn't bigger than SOF field can handle */
  22.291 +  if ((long) cinfo->image_height > 65535L ||
  22.292 +      (long) cinfo->image_width > 65535L)
  22.293 +    ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  22.294 +
  22.295 +  emit_byte(cinfo, cinfo->data_precision);
  22.296 +  emit_2bytes(cinfo, (int) cinfo->image_height);
  22.297 +  emit_2bytes(cinfo, (int) cinfo->image_width);
  22.298 +
  22.299 +  emit_byte(cinfo, cinfo->num_components);
  22.300 +
  22.301 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  22.302 +       ci++, compptr++) {
  22.303 +    emit_byte(cinfo, compptr->component_id);
  22.304 +    emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  22.305 +    emit_byte(cinfo, compptr->quant_tbl_no);
  22.306 +  }
  22.307 +}
  22.308 +
  22.309 +
  22.310 +LOCAL(void)
  22.311 +emit_sos (j_compress_ptr cinfo)
  22.312 +/* Emit a SOS marker */
  22.313 +{
  22.314 +  int i, td, ta;
  22.315 +  jpeg_component_info *compptr;
  22.316 +  
  22.317 +  emit_marker(cinfo, M_SOS);
  22.318 +  
  22.319 +  emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  22.320 +  
  22.321 +  emit_byte(cinfo, cinfo->comps_in_scan);
  22.322 +  
  22.323 +  for (i = 0; i < cinfo->comps_in_scan; i++) {
  22.324 +    compptr = cinfo->cur_comp_info[i];
  22.325 +    emit_byte(cinfo, compptr->component_id);
  22.326 +    td = compptr->dc_tbl_no;
  22.327 +    ta = compptr->ac_tbl_no;
  22.328 +    if (cinfo->progressive_mode) {
  22.329 +      /* Progressive mode: only DC or only AC tables are used in one scan;
  22.330 +       * furthermore, Huffman coding of DC refinement uses no table at all.
  22.331 +       * We emit 0 for unused field(s); this is recommended by the P&M text
  22.332 +       * but does not seem to be specified in the standard.
  22.333 +       */
  22.334 +      if (cinfo->Ss == 0) {
  22.335 +	ta = 0;			/* DC scan */
  22.336 +	if (cinfo->Ah != 0 && !cinfo->arith_code)
  22.337 +	  td = 0;		/* no DC table either */
  22.338 +      } else {
  22.339 +	td = 0;			/* AC scan */
  22.340 +      }
  22.341 +    }
  22.342 +    emit_byte(cinfo, (td << 4) + ta);
  22.343 +  }
  22.344 +
  22.345 +  emit_byte(cinfo, cinfo->Ss);
  22.346 +  emit_byte(cinfo, cinfo->Se);
  22.347 +  emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  22.348 +}
  22.349 +
  22.350 +
  22.351 +LOCAL(void)
  22.352 +emit_jfif_app0 (j_compress_ptr cinfo)
  22.353 +/* Emit a JFIF-compliant APP0 marker */
  22.354 +{
  22.355 +  /*
  22.356 +   * Length of APP0 block	(2 bytes)
  22.357 +   * Block ID			(4 bytes - ASCII "JFIF")
  22.358 +   * Zero byte			(1 byte to terminate the ID string)
  22.359 +   * Version Major, Minor	(2 bytes - major first)
  22.360 +   * Units			(1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  22.361 +   * Xdpu			(2 bytes - dots per unit horizontal)
  22.362 +   * Ydpu			(2 bytes - dots per unit vertical)
  22.363 +   * Thumbnail X size		(1 byte)
  22.364 +   * Thumbnail Y size		(1 byte)
  22.365 +   */
  22.366 +  
  22.367 +  emit_marker(cinfo, M_APP0);
  22.368 +  
  22.369 +  emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  22.370 +
  22.371 +  emit_byte(cinfo, 0x4A);	/* Identifier: ASCII "JFIF" */
  22.372 +  emit_byte(cinfo, 0x46);
  22.373 +  emit_byte(cinfo, 0x49);
  22.374 +  emit_byte(cinfo, 0x46);
  22.375 +  emit_byte(cinfo, 0);
  22.376 +  emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  22.377 +  emit_byte(cinfo, cinfo->JFIF_minor_version);
  22.378 +  emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  22.379 +  emit_2bytes(cinfo, (int) cinfo->X_density);
  22.380 +  emit_2bytes(cinfo, (int) cinfo->Y_density);
  22.381 +  emit_byte(cinfo, 0);		/* No thumbnail image */
  22.382 +  emit_byte(cinfo, 0);
  22.383 +}
  22.384 +
  22.385 +
  22.386 +LOCAL(void)
  22.387 +emit_adobe_app14 (j_compress_ptr cinfo)
  22.388 +/* Emit an Adobe APP14 marker */
  22.389 +{
  22.390 +  /*
  22.391 +   * Length of APP14 block	(2 bytes)
  22.392 +   * Block ID			(5 bytes - ASCII "Adobe")
  22.393 +   * Version Number		(2 bytes - currently 100)
  22.394 +   * Flags0			(2 bytes - currently 0)
  22.395 +   * Flags1			(2 bytes - currently 0)
  22.396 +   * Color transform		(1 byte)
  22.397 +   *
  22.398 +   * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  22.399 +   * now in circulation seem to use Version = 100, so that's what we write.
  22.400 +   *
  22.401 +   * We write the color transform byte as 1 if the JPEG color space is
  22.402 +   * YCbCr, 2 if it's YCCK, 0 otherwise.  Adobe's definition has to do with
  22.403 +   * whether the encoder performed a transformation, which is pretty useless.
  22.404 +   */
  22.405 +  
  22.406 +  emit_marker(cinfo, M_APP14);
  22.407 +  
  22.408 +  emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  22.409 +
  22.410 +  emit_byte(cinfo, 0x41);	/* Identifier: ASCII "Adobe" */
  22.411 +  emit_byte(cinfo, 0x64);
  22.412 +  emit_byte(cinfo, 0x6F);
  22.413 +  emit_byte(cinfo, 0x62);
  22.414 +  emit_byte(cinfo, 0x65);
  22.415 +  emit_2bytes(cinfo, 100);	/* Version */
  22.416 +  emit_2bytes(cinfo, 0);	/* Flags0 */
  22.417 +  emit_2bytes(cinfo, 0);	/* Flags1 */
  22.418 +  switch (cinfo->jpeg_color_space) {
  22.419 +  case JCS_YCbCr:
  22.420 +    emit_byte(cinfo, 1);	/* Color transform = 1 */
  22.421 +    break;
  22.422 +  case JCS_YCCK:
  22.423 +    emit_byte(cinfo, 2);	/* Color transform = 2 */
  22.424 +    break;
  22.425 +  default:
  22.426 +    emit_byte(cinfo, 0);	/* Color transform = 0 */
  22.427 +    break;
  22.428 +  }
  22.429 +}
  22.430 +
  22.431 +
  22.432 +/*
  22.433 + * These routines allow writing an arbitrary marker with parameters.
  22.434 + * The only intended use is to emit COM or APPn markers after calling
  22.435 + * write_file_header and before calling write_frame_header.
  22.436 + * Other uses are not guaranteed to produce desirable results.
  22.437 + * Counting the parameter bytes properly is the caller's responsibility.
  22.438 + */
  22.439 +
  22.440 +METHODDEF(void)
  22.441 +write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  22.442 +/* Emit an arbitrary marker header */
  22.443 +{
  22.444 +  if (datalen > (unsigned int) 65533)		/* safety check */
  22.445 +    ERREXIT(cinfo, JERR_BAD_LENGTH);
  22.446 +
  22.447 +  emit_marker(cinfo, (JPEG_MARKER) marker);
  22.448 +
  22.449 +  emit_2bytes(cinfo, (int) (datalen + 2));	/* total length */
  22.450 +}
  22.451 +
  22.452 +METHODDEF(void)
  22.453 +write_marker_byte (j_compress_ptr cinfo, int val)
  22.454 +/* Emit one byte of marker parameters following write_marker_header */
  22.455 +{
  22.456 +  emit_byte(cinfo, val);
  22.457 +}
  22.458 +
  22.459 +
  22.460 +/*
  22.461 + * Write datastream header.
  22.462 + * This consists of an SOI and optional APPn markers.
  22.463 + * We recommend use of the JFIF marker, but not the Adobe marker,
  22.464 + * when using YCbCr or grayscale data.  The JFIF marker should NOT
  22.465 + * be used for any other JPEG colorspace.  The Adobe marker is helpful
  22.466 + * to distinguish RGB, CMYK, and YCCK colorspaces.
  22.467 + * Note that an application can write additional header markers after
  22.468 + * jpeg_start_compress returns.
  22.469 + */
  22.470 +
  22.471 +METHODDEF(void)
  22.472 +write_file_header (j_compress_ptr cinfo)
  22.473 +{
  22.474 +  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  22.475 +
  22.476 +  emit_marker(cinfo, M_SOI);	/* first the SOI */
  22.477 +
  22.478 +  /* SOI is defined to reset restart interval to 0 */
  22.479 +  marker->last_restart_interval = 0;
  22.480 +
  22.481 +  if (cinfo->write_JFIF_header)	/* next an optional JFIF APP0 */
  22.482 +    emit_jfif_app0(cinfo);
  22.483 +  if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  22.484 +    emit_adobe_app14(cinfo);
  22.485 +}
  22.486 +
  22.487 +
  22.488 +/*
  22.489 + * Write frame header.
  22.490 + * This consists of DQT and SOFn markers.
  22.491 + * Note that we do not emit the SOF until we have emitted the DQT(s).
  22.492 + * This avoids compatibility problems with incorrect implementations that
  22.493 + * try to error-check the quant table numbers as soon as they see the SOF.
  22.494 + */
  22.495 +
  22.496 +METHODDEF(void)
  22.497 +write_frame_header (j_compress_ptr cinfo)
  22.498 +{
  22.499 +  int ci, prec;
  22.500 +  boolean is_baseline;
  22.501 +  jpeg_component_info *compptr;
  22.502 +  
  22.503 +  /* Emit DQT for each quantization table.
  22.504 +   * Note that emit_dqt() suppresses any duplicate tables.
  22.505 +   */
  22.506 +  prec = 0;
  22.507 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  22.508 +       ci++, compptr++) {
  22.509 +    prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  22.510 +  }
  22.511 +  /* now prec is nonzero iff there are any 16-bit quant tables. */
  22.512 +
  22.513 +  /* Check for a non-baseline specification.
  22.514 +   * Note we assume that Huffman table numbers won't be changed later.
  22.515 +   */
  22.516 +  if (cinfo->arith_code || cinfo->progressive_mode ||
  22.517 +      cinfo->data_precision != 8) {
  22.518 +    is_baseline = FALSE;
  22.519 +  } else {
  22.520 +    is_baseline = TRUE;
  22.521 +    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  22.522 +	 ci++, compptr++) {
  22.523 +      if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  22.524 +	is_baseline = FALSE;
  22.525 +    }
  22.526 +    if (prec && is_baseline) {
  22.527 +      is_baseline = FALSE;
  22.528 +      /* If it's baseline except for quantizer size, warn the user */
  22.529 +      TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  22.530 +    }
  22.531 +  }
  22.532 +
  22.533 +  /* Emit the proper SOF marker */
  22.534 +  if (cinfo->arith_code) {
  22.535 +    emit_sof(cinfo, M_SOF9);	/* SOF code for arithmetic coding */
  22.536 +  } else {
  22.537 +    if (cinfo->progressive_mode)
  22.538 +      emit_sof(cinfo, M_SOF2);	/* SOF code for progressive Huffman */
  22.539 +    else if (is_baseline)
  22.540 +      emit_sof(cinfo, M_SOF0);	/* SOF code for baseline implementation */
  22.541 +    else
  22.542 +      emit_sof(cinfo, M_SOF1);	/* SOF code for non-baseline Huffman file */
  22.543 +  }
  22.544 +}
  22.545 +
  22.546 +
  22.547 +/*
  22.548 + * Write scan header.
  22.549 + * This consists of DHT or DAC markers, optional DRI, and SOS.
  22.550 + * Compressed data will be written following the SOS.
  22.551 + */
  22.552 +
  22.553 +METHODDEF(void)
  22.554 +write_scan_header (j_compress_ptr cinfo)
  22.555 +{
  22.556 +  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  22.557 +  int i;
  22.558 +  jpeg_component_info *compptr;
  22.559 +
  22.560 +  if (cinfo->arith_code) {
  22.561 +    /* Emit arith conditioning info.  We may have some duplication
  22.562 +     * if the file has multiple scans, but it's so small it's hardly
  22.563 +     * worth worrying about.
  22.564 +     */
  22.565 +    emit_dac(cinfo);
  22.566 +  } else {
  22.567 +    /* Emit Huffman tables.
  22.568 +     * Note that emit_dht() suppresses any duplicate tables.
  22.569 +     */
  22.570 +    for (i = 0; i < cinfo->comps_in_scan; i++) {
  22.571 +      compptr = cinfo->cur_comp_info[i];
  22.572 +      if (cinfo->progressive_mode) {
  22.573 +	/* Progressive mode: only DC or only AC tables are used in one scan */
  22.574 +	if (cinfo->Ss == 0) {
  22.575 +	  if (cinfo->Ah == 0)	/* DC needs no table for refinement scan */
  22.576 +	    emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  22.577 +	} else {
  22.578 +	  emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  22.579 +	}
  22.580 +      } else {
  22.581 +	/* Sequential mode: need both DC and AC tables */
  22.582 +	emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  22.583 +	emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  22.584 +      }
  22.585 +    }
  22.586 +  }
  22.587 +
  22.588 +  /* Emit DRI if required --- note that DRI value could change for each scan.
  22.589 +   * We avoid wasting space with unnecessary DRIs, however.
  22.590 +   */
  22.591 +  if (cinfo->restart_interval != marker->last_restart_interval) {
  22.592 +    emit_dri(cinfo);
  22.593 +    marker->last_restart_interval = cinfo->restart_interval;
  22.594 +  }
  22.595 +
  22.596 +  emit_sos(cinfo);
  22.597 +}
  22.598 +
  22.599 +
  22.600 +/*
  22.601 + * Write datastream trailer.
  22.602 + */
  22.603 +
  22.604 +METHODDEF(void)
  22.605 +write_file_trailer (j_compress_ptr cinfo)
  22.606 +{
  22.607 +  emit_marker(cinfo, M_EOI);
  22.608 +}
  22.609 +
  22.610 +
  22.611 +/*
  22.612 + * Write an abbreviated table-specification datastream.
  22.613 + * This consists of SOI, DQT and DHT tables, and EOI.
  22.614 + * Any table that is defined and not marked sent_table = TRUE will be
  22.615 + * emitted.  Note that all tables will be marked sent_table = TRUE at exit.
  22.616 + */
  22.617 +
  22.618 +METHODDEF(void)
  22.619 +write_tables_only (j_compress_ptr cinfo)
  22.620 +{
  22.621 +  int i;
  22.622 +
  22.623 +  emit_marker(cinfo, M_SOI);
  22.624 +
  22.625 +  for (i = 0; i < NUM_QUANT_TBLS; i++) {
  22.626 +    if (cinfo->quant_tbl_ptrs[i] != NULL)
  22.627 +      (void) emit_dqt(cinfo, i);
  22.628 +  }
  22.629 +
  22.630 +  if (! cinfo->arith_code) {
  22.631 +    for (i = 0; i < NUM_HUFF_TBLS; i++) {
  22.632 +      if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  22.633 +	emit_dht(cinfo, i, FALSE);
  22.634 +      if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  22.635 +	emit_dht(cinfo, i, TRUE);
  22.636 +    }
  22.637 +  }
  22.638 +
  22.639 +  emit_marker(cinfo, M_EOI);
  22.640 +}
  22.641 +
  22.642 +
  22.643 +/*
  22.644 + * Initialize the marker writer module.
  22.645 + */
  22.646 +
  22.647 +GLOBAL(void)
  22.648 +jinit_marker_writer (j_compress_ptr cinfo)
  22.649 +{
  22.650 +  my_marker_ptr marker;
  22.651 +
  22.652 +  /* Create the subobject */
  22.653 +  marker = (my_marker_ptr)
  22.654 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  22.655 +				SIZEOF(my_marker_writer));
  22.656 +  cinfo->marker = (struct jpeg_marker_writer *) marker;
  22.657 +  /* Initialize method pointers */
  22.658 +  marker->pub.write_file_header = write_file_header;
  22.659 +  marker->pub.write_frame_header = write_frame_header;
  22.660 +  marker->pub.write_scan_header = write_scan_header;
  22.661 +  marker->pub.write_file_trailer = write_file_trailer;
  22.662 +  marker->pub.write_tables_only = write_tables_only;
  22.663 +  marker->pub.write_marker_header = write_marker_header;
  22.664 +  marker->pub.write_marker_byte = write_marker_byte;
  22.665 +  /* Initialize private state */
  22.666 +  marker->last_restart_interval = 0;
  22.667 +}
    23.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    23.2 +++ b/libs/libjpeg/jcmaster.c	Thu Sep 08 06:28:38 2011 +0300
    23.3 @@ -0,0 +1,590 @@
    23.4 +/*
    23.5 + * jcmaster.c
    23.6 + *
    23.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    23.8 + * This file is part of the Independent JPEG Group's software.
    23.9 + * For conditions of distribution and use, see the accompanying README file.
   23.10 + *
   23.11 + * This file contains master control logic for the JPEG compressor.
   23.12 + * These routines are concerned with parameter validation, initial setup,
   23.13 + * and inter-pass control (determining the number of passes and the work 
   23.14 + * to be done in each pass).
   23.15 + */
   23.16 +
   23.17 +#define JPEG_INTERNALS
   23.18 +#include "jinclude.h"
   23.19 +#include "jpeglib.h"
   23.20 +
   23.21 +
   23.22 +/* Private state */
   23.23 +
   23.24 +typedef enum {
   23.25 +	main_pass,		/* input data, also do first output step */
   23.26 +	huff_opt_pass,		/* Huffman code optimization pass */
   23.27 +	output_pass		/* data output pass */
   23.28 +} c_pass_type;
   23.29 +
   23.30 +typedef struct {
   23.31 +  struct jpeg_comp_master pub;	/* public fields */
   23.32 +
   23.33 +  c_pass_type pass_type;	/* the type of the current pass */
   23.34 +
   23.35 +  int pass_number;		/* # of passes completed */
   23.36 +  int total_passes;		/* total # of passes needed */
   23.37 +
   23.38 +  int scan_number;		/* current index in scan_info[] */
   23.39 +} my_comp_master;
   23.40 +
   23.41 +typedef my_comp_master * my_master_ptr;
   23.42 +
   23.43 +
   23.44 +/*
   23.45 + * Support routines that do various essential calculations.
   23.46 + */
   23.47 +
   23.48 +LOCAL(void)
   23.49 +initial_setup (j_compress_ptr cinfo)
   23.50 +/* Do computations that are needed before master selection phase */
   23.51 +{
   23.52 +  int ci;
   23.53 +  jpeg_component_info *compptr;
   23.54 +  long samplesperrow;
   23.55 +  JDIMENSION jd_samplesperrow;
   23.56 +
   23.57 +  /* Sanity check on image dimensions */
   23.58 +  if (cinfo->image_height <= 0 || cinfo->image_width <= 0
   23.59 +      || cinfo->num_components <= 0 || cinfo->input_components <= 0)
   23.60 +    ERREXIT(cinfo, JERR_EMPTY_IMAGE);
   23.61 +
   23.62 +  /* Make sure image isn't bigger than I can handle */
   23.63 +  if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
   23.64 +      (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
   23.65 +    ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
   23.66 +
   23.67 +  /* Width of an input scanline must be representable as JDIMENSION. */
   23.68 +  samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
   23.69 +  jd_samplesperrow = (JDIMENSION) samplesperrow;
   23.70 +  if ((long) jd_samplesperrow != samplesperrow)
   23.71 +    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
   23.72 +
   23.73 +  /* For now, precision must match compiled-in value... */
   23.74 +  if (cinfo->data_precision != BITS_IN_JSAMPLE)
   23.75 +    ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
   23.76 +
   23.77 +  /* Check that number of components won't exceed internal array sizes */
   23.78 +  if (cinfo->num_components > MAX_COMPONENTS)
   23.79 +    ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
   23.80 +	     MAX_COMPONENTS);
   23.81 +
   23.82 +  /* Compute maximum sampling factors; check factor validity */
   23.83 +  cinfo->max_h_samp_factor = 1;
   23.84 +  cinfo->max_v_samp_factor = 1;
   23.85 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
   23.86 +       ci++, compptr++) {
   23.87 +    if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
   23.88 +	compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
   23.89 +      ERREXIT(cinfo, JERR_BAD_SAMPLING);
   23.90 +    cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
   23.91 +				   compptr->h_samp_factor);
   23.92 +    cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
   23.93 +				   compptr->v_samp_factor);
   23.94 +  }
   23.95 +
   23.96 +  /* Compute dimensions of components */
   23.97 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
   23.98 +       ci++, compptr++) {
   23.99 +    /* Fill in the correct component_index value; don't rely on application */
  23.100 +    compptr->component_index = ci;
  23.101 +    /* For compression, we never do DCT scaling. */
  23.102 +    compptr->DCT_scaled_size = DCTSIZE;
  23.103 +    /* Size in DCT blocks */
  23.104 +    compptr->width_in_blocks = (JDIMENSION)
  23.105 +      jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  23.106 +		    (long) (cinfo->max_h_samp_factor * DCTSIZE));
  23.107 +    compptr->height_in_blocks = (JDIMENSION)
  23.108 +      jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  23.109 +		    (long) (cinfo->max_v_samp_factor * DCTSIZE));
  23.110 +    /* Size in samples */
  23.111 +    compptr->downsampled_width = (JDIMENSION)
  23.112 +      jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  23.113 +		    (long) cinfo->max_h_samp_factor);
  23.114 +    compptr->downsampled_height = (JDIMENSION)
  23.115 +      jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  23.116 +		    (long) cinfo->max_v_samp_factor);
  23.117 +    /* Mark component needed (this flag isn't actually used for compression) */
  23.118 +    compptr->component_needed = TRUE;
  23.119 +  }
  23.120 +
  23.121 +  /* Compute number of fully interleaved MCU rows (number of times that
  23.122 +   * main controller will call coefficient controller).
  23.123 +   */
  23.124 +  cinfo->total_iMCU_rows = (JDIMENSION)
  23.125 +    jdiv_round_up((long) cinfo->image_height,
  23.126 +		  (long) (cinfo->max_v_samp_factor*DCTSIZE));
  23.127 +}
  23.128 +
  23.129 +
  23.130 +#ifdef C_MULTISCAN_FILES_SUPPORTED
  23.131 +
  23.132 +LOCAL(void)
  23.133 +validate_script (j_compress_ptr cinfo)
  23.134 +/* Verify that the scan script in cinfo->scan_info[] is valid; also
  23.135 + * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  23.136 + */
  23.137 +{
  23.138 +  const jpeg_scan_info * scanptr;
  23.139 +  int scanno, ncomps, ci, coefi, thisi;
  23.140 +  int Ss, Se, Ah, Al;
  23.141 +  boolean component_sent[MAX_COMPONENTS];
  23.142 +#ifdef C_PROGRESSIVE_SUPPORTED
  23.143 +  int * last_bitpos_ptr;
  23.144 +  int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  23.145 +  /* -1 until that coefficient has been seen; then last Al for it */
  23.146 +#endif
  23.147 +
  23.148 +  if (cinfo->num_scans <= 0)
  23.149 +    ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  23.150 +
  23.151 +  /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  23.152 +   * for progressive JPEG, no scan can have this.
  23.153 +   */
  23.154 +  scanptr = cinfo->scan_info;
  23.155 +  if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  23.156 +#ifdef C_PROGRESSIVE_SUPPORTED
  23.157 +    cinfo->progressive_mode = TRUE;
  23.158 +    last_bitpos_ptr = & last_bitpos[0][0];
  23.159 +    for (ci = 0; ci < cinfo->num_components; ci++) 
  23.160 +      for (coefi = 0; coefi < DCTSIZE2; coefi++)
  23.161 +	*last_bitpos_ptr++ = -1;
  23.162 +#else
  23.163 +    ERREXIT(cinfo, JERR_NOT_COMPILED);
  23.164 +#endif
  23.165 +  } else {
  23.166 +    cinfo->progressive_mode = FALSE;
  23.167 +    for (ci = 0; ci < cinfo->num_components; ci++) 
  23.168 +      component_sent[ci] = FALSE;
  23.169 +  }
  23.170 +
  23.171 +  for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  23.172 +    /* Validate component indexes */
  23.173 +    ncomps = scanptr->comps_in_scan;
  23.174 +    if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  23.175 +      ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  23.176 +    for (ci = 0; ci < ncomps; ci++) {
  23.177 +      thisi = scanptr->component_index[ci];
  23.178 +      if (thisi < 0 || thisi >= cinfo->num_components)
  23.179 +	ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  23.180 +      /* Components must appear in SOF order within each scan */
  23.181 +      if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  23.182 +	ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  23.183 +    }
  23.184 +    /* Validate progression parameters */
  23.185 +    Ss = scanptr->Ss;
  23.186 +    Se = scanptr->Se;
  23.187 +    Ah = scanptr->Ah;
  23.188 +    Al = scanptr->Al;
  23.189 +    if (cinfo->progressive_mode) {
  23.190 +#ifdef C_PROGRESSIVE_SUPPORTED
  23.191 +      /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  23.192 +       * seems wrong: the upper bound ought to depend on data precision.
  23.193 +       * Perhaps they really meant 0..N+1 for N-bit precision.
  23.194 +       * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  23.195 +       * out-of-range reconstructed DC values during the first DC scan,
  23.196 +       * which might cause problems for some decoders.
  23.197 +       */
  23.198 +#if BITS_IN_JSAMPLE == 8
  23.199 +#define MAX_AH_AL 10
  23.200 +#else
  23.201 +#define MAX_AH_AL 13
  23.202 +#endif
  23.203 +      if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  23.204 +	  Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  23.205 +	ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  23.206 +      if (Ss == 0) {
  23.207 +	if (Se != 0)		/* DC and AC together not OK */
  23.208 +	  ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  23.209 +      } else {
  23.210 +	if (ncomps != 1)	/* AC scans must be for only one component */
  23.211 +	  ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  23.212 +      }
  23.213 +      for (ci = 0; ci < ncomps; ci++) {
  23.214 +	last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  23.215 +	if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  23.216 +	  ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  23.217 +	for (coefi = Ss; coefi <= Se; coefi++) {
  23.218 +	  if (last_bitpos_ptr[coefi] < 0) {
  23.219 +	    /* first scan of this coefficient */
  23.220 +	    if (Ah != 0)
  23.221 +	      ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  23.222 +	  } else {
  23.223 +	    /* not first scan */
  23.224 +	    if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  23.225 +	      ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  23.226 +	  }
  23.227 +	  last_bitpos_ptr[coefi] = Al;
  23.228 +	}
  23.229 +      }
  23.230 +#endif
  23.231 +    } else {
  23.232 +      /* For sequential JPEG, all progression parameters must be these: */
  23.233 +      if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  23.234 +	ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  23.235 +      /* Make sure components are not sent twice */
  23.236 +      for (ci = 0; ci < ncomps; ci++) {
  23.237 +	thisi = scanptr->component_index[ci];
  23.238 +	if (component_sent[thisi])
  23.239 +	  ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  23.240 +	component_sent[thisi] = TRUE;
  23.241 +      }
  23.242 +    }
  23.243 +  }
  23.244 +
  23.245 +  /* Now verify that everything got sent. */
  23.246 +  if (cinfo->progressive_mode) {
  23.247 +#ifdef C_PROGRESSIVE_SUPPORTED
  23.248 +    /* For progressive mode, we only check that at least some DC data
  23.249 +     * got sent for each component; the spec does not require that all bits
  23.250 +     * of all coefficients be transmitted.  Would it be wiser to enforce
  23.251 +     * transmission of all coefficient bits??
  23.252 +     */
  23.253 +    for (ci = 0; ci < cinfo->num_components; ci++) {
  23.254 +      if (last_bitpos[ci][0] < 0)
  23.255 +	ERREXIT(cinfo, JERR_MISSING_DATA);
  23.256 +    }
  23.257 +#endif
  23.258 +  } else {
  23.259 +    for (ci = 0; ci < cinfo->num_components; ci++) {
  23.260 +      if (! component_sent[ci])
  23.261 +	ERREXIT(cinfo, JERR_MISSING_DATA);
  23.262 +    }
  23.263 +  }
  23.264 +}
  23.265 +
  23.266 +#endif /* C_MULTISCAN_FILES_SUPPORTED */
  23.267 +
  23.268 +
  23.269 +LOCAL(void)
  23.270 +select_scan_parameters (j_compress_ptr cinfo)
  23.271 +/* Set up the scan parameters for the current scan */
  23.272 +{
  23.273 +  int ci;
  23.274 +
  23.275 +#ifdef C_MULTISCAN_FILES_SUPPORTED
  23.276 +  if (cinfo->scan_info != NULL) {
  23.277 +    /* Prepare for current scan --- the script is already validated */
  23.278 +    my_master_ptr master = (my_master_ptr) cinfo->master;
  23.279 +    const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  23.280 +
  23.281 +    cinfo->comps_in_scan = scanptr->comps_in_scan;
  23.282 +    for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  23.283 +      cinfo->cur_comp_info[ci] =
  23.284 +	&cinfo->comp_info[scanptr->component_index[ci]];
  23.285 +    }
  23.286 +    cinfo->Ss = scanptr->Ss;
  23.287 +    cinfo->Se = scanptr->Se;
  23.288 +    cinfo->Ah = scanptr->Ah;
  23.289 +    cinfo->Al = scanptr->Al;
  23.290 +  }
  23.291 +  else
  23.292 +#endif
  23.293 +  {
  23.294 +    /* Prepare for single sequential-JPEG scan containing all components */
  23.295 +    if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  23.296 +      ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  23.297 +	       MAX_COMPS_IN_SCAN);
  23.298 +    cinfo->comps_in_scan = cinfo->num_components;
  23.299 +    for (ci = 0; ci < cinfo->num_components; ci++) {
  23.300 +      cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  23.301 +    }
  23.302 +    cinfo->Ss = 0;
  23.303 +    cinfo->Se = DCTSIZE2-1;
  23.304 +    cinfo->Ah = 0;
  23.305 +    cinfo->Al = 0;
  23.306 +  }
  23.307 +}
  23.308 +
  23.309 +
  23.310 +LOCAL(void)
  23.311 +per_scan_setup (j_compress_ptr cinfo)
  23.312 +/* Do computations that are needed before processing a JPEG scan */
  23.313 +/* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  23.314 +{
  23.315 +  int ci, mcublks, tmp;
  23.316 +  jpeg_component_info *compptr;
  23.317 +  
  23.318 +  if (cinfo->comps_in_scan == 1) {
  23.319 +    
  23.320 +    /* Noninterleaved (single-component) scan */
  23.321 +    compptr = cinfo->cur_comp_info[0];
  23.322 +    
  23.323 +    /* Overall image size in MCUs */
  23.324 +    cinfo->MCUs_per_row = compptr->width_in_blocks;
  23.325 +    cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  23.326 +    
  23.327 +    /* For noninterleaved scan, always one block per MCU */
  23.328 +    compptr->MCU_width = 1;
  23.329 +    compptr->MCU_height = 1;
  23.330 +    compptr->MCU_blocks = 1;
  23.331 +    compptr->MCU_sample_width = DCTSIZE;
  23.332 +    compptr->last_col_width = 1;
  23.333 +    /* For noninterleaved scans, it is convenient to define last_row_height
  23.334 +     * as the number of block rows present in the last iMCU row.
  23.335 +     */
  23.336 +    tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  23.337 +    if (tmp == 0) tmp = compptr->v_samp_factor;
  23.338 +    compptr->last_row_height = tmp;
  23.339 +    
  23.340 +    /* Prepare array describing MCU composition */
  23.341 +    cinfo->blocks_in_MCU = 1;
  23.342 +    cinfo->MCU_membership[0] = 0;
  23.343 +    
  23.344 +  } else {
  23.345 +    
  23.346 +    /* Interleaved (multi-component) scan */
  23.347 +    if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  23.348 +      ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  23.349 +	       MAX_COMPS_IN_SCAN);
  23.350 +    
  23.351 +    /* Overall image size in MCUs */
  23.352 +    cinfo->MCUs_per_row = (JDIMENSION)
  23.353 +      jdiv_round_up((long) cinfo->image_width,
  23.354 +		    (long) (cinfo->max_h_samp_factor*DCTSIZE));
  23.355 +    cinfo->MCU_rows_in_scan = (JDIMENSION)
  23.356 +      jdiv_round_up((long) cinfo->image_height,
  23.357 +		    (long) (cinfo->max_v_samp_factor*DCTSIZE));
  23.358 +    
  23.359 +    cinfo->blocks_in_MCU = 0;
  23.360 +    
  23.361 +    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  23.362 +      compptr = cinfo->cur_comp_info[ci];
  23.363 +      /* Sampling factors give # of blocks of component in each MCU */
  23.364 +      compptr->MCU_width = compptr->h_samp_factor;
  23.365 +      compptr->MCU_height = compptr->v_samp_factor;
  23.366 +      compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  23.367 +      compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  23.368 +      /* Figure number of non-dummy blocks in last MCU column & row */
  23.369 +      tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  23.370 +      if (tmp == 0) tmp = compptr->MCU_width;
  23.371 +      compptr->last_col_width = tmp;
  23.372 +      tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  23.373 +      if (tmp == 0) tmp = compptr->MCU_height;
  23.374 +      compptr->last_row_height = tmp;
  23.375 +      /* Prepare array describing MCU composition */
  23.376 +      mcublks = compptr->MCU_blocks;
  23.377 +      if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  23.378 +	ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  23.379 +      while (mcublks-- > 0) {
  23.380 +	cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  23.381 +      }
  23.382 +    }
  23.383 +    
  23.384 +  }
  23.385 +
  23.386 +  /* Convert restart specified in rows to actual MCU count. */
  23.387 +  /* Note that count must fit in 16 bits, so we provide limiting. */
  23.388 +  if (cinfo->restart_in_rows > 0) {
  23.389 +    long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  23.390 +    cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  23.391 +  }
  23.392 +}
  23.393 +
  23.394 +
  23.395 +/*
  23.396 + * Per-pass setup.
  23.397 + * This is called at the beginning of each pass.  We determine which modules
  23.398 + * will be active during this pass and give them appropriate start_pass calls.
  23.399 + * We also set is_last_pass to indicate whether any more passes will be
  23.400 + * required.
  23.401 + */
  23.402 +
  23.403 +METHODDEF(void)
  23.404 +prepare_for_pass (j_compress_ptr cinfo)
  23.405 +{
  23.406 +  my_master_ptr master = (my_master_ptr) cinfo->master;
  23.407 +
  23.408 +  switch (master->pass_type) {
  23.409 +  case main_pass:
  23.410 +    /* Initial pass: will collect input data, and do either Huffman
  23.411 +     * optimization or data output for the first scan.
  23.412 +     */
  23.413 +    select_scan_parameters(cinfo);
  23.414 +    per_scan_setup(cinfo);
  23.415 +    if (! cinfo->raw_data_in) {
  23.416 +      (*cinfo->cconvert->start_pass) (cinfo);
  23.417 +      (*cinfo->downsample->start_pass) (cinfo);
  23.418 +      (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  23.419 +    }
  23.420 +    (*cinfo->fdct->start_pass) (cinfo);
  23.421 +    (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  23.422 +    (*cinfo->coef->start_pass) (cinfo,
  23.423 +				(master->total_passes > 1 ?
  23.424 +				 JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  23.425 +    (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  23.426 +    if (cinfo->optimize_coding) {
  23.427 +      /* No immediate data output; postpone writing frame/scan headers */
  23.428 +      master->pub.call_pass_startup = FALSE;
  23.429 +    } else {
  23.430 +      /* Will write frame/scan headers at first jpeg_write_scanlines call */
  23.431 +      master->pub.call_pass_startup = TRUE;
  23.432 +    }
  23.433 +    break;
  23.434 +#ifdef ENTROPY_OPT_SUPPORTED
  23.435 +  case huff_opt_pass:
  23.436 +    /* Do Huffman optimization for a scan after the first one. */
  23.437 +    select_scan_parameters(cinfo);
  23.438 +    per_scan_setup(cinfo);
  23.439 +    if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  23.440 +      (*cinfo->entropy->start_pass) (cinfo, TRUE);
  23.441 +      (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  23.442 +      master->pub.call_pass_startup = FALSE;
  23.443 +      break;
  23.444 +    }
  23.445 +    /* Special case: Huffman DC refinement scans need no Huffman table
  23.446 +     * and therefore we can skip the optimization pass for them.
  23.447 +     */
  23.448 +    master->pass_type = output_pass;
  23.449 +    master->pass_number++;
  23.450 +    /*FALLTHROUGH*/
  23.451 +#endif
  23.452 +  case output_pass:
  23.453 +    /* Do a data-output pass. */
  23.454 +    /* We need not repeat per-scan setup if prior optimization pass did it. */
  23.455 +    if (! cinfo->optimize_coding) {
  23.456 +      select_scan_parameters(cinfo);
  23.457 +      per_scan_setup(cinfo);
  23.458 +    }
  23.459 +    (*cinfo->entropy->start_pass) (cinfo, FALSE);
  23.460 +    (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  23.461 +    /* We emit frame/scan headers now */
  23.462 +    if (master->scan_number == 0)
  23.463 +      (*cinfo->marker->write_frame_header) (cinfo);
  23.464 +    (*cinfo->marker->write_scan_header) (cinfo);
  23.465 +    master->pub.call_pass_startup = FALSE;
  23.466 +    break;
  23.467 +  default:
  23.468 +    ERREXIT(cinfo, JERR_NOT_COMPILED);
  23.469 +  }
  23.470 +
  23.471 +  master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  23.472 +
  23.473 +  /* Set up progress monitor's pass info if present */
  23.474 +  if (cinfo->progress != NULL) {
  23.475 +    cinfo->progress->completed_passes = master->pass_number;
  23.476 +    cinfo->progress->total_passes = master->total_passes;
  23.477 +  }
  23.478 +}
  23.479 +
  23.480 +
  23.481 +/*
  23.482 + * Special start-of-pass hook.
  23.483 + * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  23.484 + * In single-pass processing, we need this hook because we don't want to
  23.485 + * write frame/scan headers during jpeg_start_compress; we want to let the
  23.486 + * application write COM markers etc. between jpeg_start_compress and the
  23.487 + * jpeg_write_scanlines loop.
  23.488 + * In multi-pass processing, this routine is not used.
  23.489 + */
  23.490 +
  23.491 +METHODDEF(void)
  23.492 +pass_startup (j_compress_ptr cinfo)
  23.493 +{
  23.494 +  cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  23.495 +
  23.496 +  (*cinfo->marker->write_frame_header) (cinfo);
  23.497 +  (*cinfo->marker->write_scan_header) (cinfo);
  23.498 +}
  23.499 +
  23.500 +
  23.501 +/*
  23.502 + * Finish up at end of pass.
  23.503 + */
  23.504 +
  23.505 +METHODDEF(void)
  23.506 +finish_pass_master (j_compress_ptr cinfo)
  23.507 +{
  23.508 +  my_master_ptr master = (my_master_ptr) cinfo->master;
  23.509 +
  23.510 +  /* The entropy coder always needs an end-of-pass call,
  23.511 +   * either to analyze statistics or to flush its output buffer.
  23.512 +   */
  23.513 +  (*cinfo->entropy->finish_pass) (cinfo);
  23.514 +
  23.515 +  /* Update state for next pass */
  23.516 +  switch (master->pass_type) {
  23.517 +  case main_pass:
  23.518 +    /* next pass is either output of scan 0 (after optimization)
  23.519 +     * or output of scan 1 (if no optimization).
  23.520 +     */
  23.521 +    master->pass_type = output_pass;
  23.522 +    if (! cinfo->optimize_coding)
  23.523 +      master->scan_number++;
  23.524 +    break;
  23.525 +  case huff_opt_pass:
  23.526 +    /* next pass is always output of current scan */
  23.527 +    master->pass_type = output_pass;
  23.528 +    break;
  23.529 +  case output_pass:
  23.530 +    /* next pass is either optimization or output of next scan */
  23.531 +    if (cinfo->optimize_coding)
  23.532 +      master->pass_type = huff_opt_pass;
  23.533 +    master->scan_number++;
  23.534 +    break;
  23.535 +  }
  23.536 +
  23.537 +  master->pass_number++;
  23.538 +}
  23.539 +
  23.540 +
  23.541 +/*
  23.542 + * Initialize master compression control.
  23.543 + */
  23.544 +
  23.545 +GLOBAL(void)
  23.546 +jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  23.547 +{
  23.548 +  my_master_ptr master;
  23.549 +
  23.550 +  master = (my_master_ptr)
  23.551 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  23.552 +				  SIZEOF(my_comp_master));
  23.553 +  cinfo->master = (struct jpeg_comp_master *) master;
  23.554 +  master->pub.prepare_for_pass = prepare_for_pass;
  23.555 +  master->pub.pass_startup = pass_startup;
  23.556 +  master->pub.finish_pass = finish_pass_master;
  23.557 +  master->pub.is_last_pass = FALSE;
  23.558 +
  23.559 +  /* Validate parameters, determine derived values */
  23.560 +  initial_setup(cinfo);
  23.561 +
  23.562 +  if (cinfo->scan_info != NULL) {
  23.563 +#ifdef C_MULTISCAN_FILES_SUPPORTED
  23.564 +    validate_script(cinfo);
  23.565 +#else
  23.566 +    ERREXIT(cinfo, JERR_NOT_COMPILED);
  23.567 +#endif
  23.568 +  } else {
  23.569 +    cinfo->progressive_mode = FALSE;
  23.570 +    cinfo->num_scans = 1;
  23.571 +  }
  23.572 +
  23.573 +  if (cinfo->progressive_mode)	/*  TEMPORARY HACK ??? */
  23.574 +    cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  23.575 +
  23.576 +  /* Initialize my private state */
  23.577 +  if (transcode_only) {
  23.578 +    /* no main pass in transcoding */
  23.579 +    if (cinfo->optimize_coding)
  23.580 +      master->pass_type = huff_opt_pass;
  23.581 +    else
  23.582 +      master->pass_type = output_pass;
  23.583 +  } else {
  23.584 +    /* for normal compression, first pass is always this type: */
  23.585 +    master->pass_type = main_pass;
  23.586 +  }
  23.587 +  master->scan_number = 0;
  23.588 +  master->pass_number = 0;
  23.589 +  if (cinfo->optimize_coding)
  23.590 +    master->total_passes = cinfo->num_scans * 2;
  23.591 +  else
  23.592 +    master->total_passes = cinfo->num_scans;
  23.593 +}
    24.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    24.2 +++ b/libs/libjpeg/jcomapi.c	Thu Sep 08 06:28:38 2011 +0300
    24.3 @@ -0,0 +1,106 @@
    24.4 +/*
    24.5 + * jcomapi.c
    24.6 + *
    24.7 + * Copyright (C) 1994-1997, Thomas G. Lane.
    24.8 + * This file is part of the Independent JPEG Group's software.
    24.9 + * For conditions of distribution and use, see the accompanying README file.
   24.10 + *
   24.11 + * This file contains application interface routines that are used for both
   24.12 + * compression and decompression.
   24.13 + */
   24.14 +
   24.15 +#define JPEG_INTERNALS
   24.16 +#include "jinclude.h"
   24.17 +#include "jpeglib.h"
   24.18 +
   24.19 +
   24.20 +/*
   24.21 + * Abort processing of a JPEG compression or decompression operation,
   24.22 + * but don't destroy the object itself.
   24.23 + *
   24.24 + * For this, we merely clean up all the nonpermanent memory pools.
   24.25 + * Note that temp files (virtual arrays) are not allowed to belong to
   24.26 + * the permanent pool, so we will be able to close all temp files here.
   24.27 + * Closing a data source or destination, if necessary, is the application's
   24.28 + * responsibility.
   24.29 + */
   24.30 +
   24.31 +GLOBAL(void)
   24.32 +jpeg_abort (j_common_ptr cinfo)
   24.33 +{
   24.34 +  int pool;
   24.35 +
   24.36 +  /* Do nothing if called on a not-initialized or destroyed JPEG object. */
   24.37 +  if (cinfo->mem == NULL)
   24.38 +    return;
   24.39 +
   24.40 +  /* Releasing pools in reverse order might help avoid fragmentation
   24.41 +   * with some (brain-damaged) malloc libraries.
   24.42 +   */
   24.43 +  for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
   24.44 +    (*cinfo->mem->free_pool) (cinfo, pool);
   24.45 +  }
   24.46 +
   24.47 +  /* Reset overall state for possible reuse of object */
   24.48 +  if (cinfo->is_decompressor) {
   24.49 +    cinfo->global_state = DSTATE_START;
   24.50 +    /* Try to keep application from accessing now-deleted marker list.
   24.51 +     * A bit kludgy to do it here, but this is the most central place.
   24.52 +     */
   24.53 +    ((j_decompress_ptr) cinfo)->marker_list = NULL;
   24.54 +  } else {
   24.55 +    cinfo->global_state = CSTATE_START;
   24.56 +  }
   24.57 +}
   24.58 +
   24.59 +
   24.60 +/*
   24.61 + * Destruction of a JPEG object.
   24.62 + *
   24.63 + * Everything gets deallocated except the master jpeg_compress_struct itself
   24.64 + * and the error manager struct.  Both of these are supplied by the application
   24.65 + * and must be freed, if necessary, by the application.  (Often they are on
   24.66 + * the stack and so don't need to be freed anyway.)
   24.67 + * Closing a data source or destination, if necessary, is the application's
   24.68 + * responsibility.
   24.69 + */
   24.70 +
   24.71 +GLOBAL(void)
   24.72 +jpeg_destroy (j_common_ptr cinfo)
   24.73 +{
   24.74 +  /* We need only tell the memory manager to release everything. */
   24.75 +  /* NB: mem pointer is NULL if memory mgr failed to initialize. */
   24.76 +  if (cinfo->mem != NULL)
   24.77 +    (*cinfo->mem->self_destruct) (cinfo);
   24.78 +  cinfo->mem = NULL;		/* be safe if jpeg_destroy is called twice */
   24.79 +  cinfo->global_state = 0;	/* mark it destroyed */
   24.80 +}
   24.81 +
   24.82 +
   24.83 +/*
   24.84 + * Convenience routines for allocating quantization and Huffman tables.
   24.85 + * (Would jutils.c be a more reasonable place to put these?)
   24.86 + */
   24.87 +
   24.88 +GLOBAL(JQUANT_TBL *)
   24.89 +jpeg_alloc_quant_table (j_common_ptr cinfo)
   24.90 +{
   24.91 +  JQUANT_TBL *tbl;
   24.92 +
   24.93 +  tbl = (JQUANT_TBL *)
   24.94 +    (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
   24.95 +  tbl->sent_table = FALSE;	/* make sure this is false in any new table */
   24.96 +  return tbl;
   24.97 +}
   24.98 +
   24.99 +
  24.100 +GLOBAL(JHUFF_TBL *)
  24.101 +jpeg_alloc_huff_table (j_common_ptr cinfo)
  24.102 +{
  24.103 +  JHUFF_TBL *tbl;
  24.104 +
  24.105 +  tbl = (JHUFF_TBL *)
  24.106 +    (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  24.107 +  tbl->sent_table = FALSE;	/* make sure this is false in any new table */
  24.108 +  return tbl;
  24.109 +}
    25.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    25.2 +++ b/libs/libjpeg/jconfig.h	Thu Sep 08 06:28:38 2011 +0300
    25.3 @@ -0,0 +1,45 @@
    25.4 +/* jconfig.vc --- jconfig.h for Microsoft Visual C++ on Windows 95 or NT. */
    25.5 +/* see jconfig.doc for explanations */
    25.6 +
    25.7 +#define HAVE_PROTOTYPES
    25.8 +#define HAVE_UNSIGNED_CHAR
    25.9 +#define HAVE_UNSIGNED_SHORT
   25.10 +/* #define void char */
   25.11 +/* #define const */
   25.12 +#undef CHAR_IS_UNSIGNED
   25.13 +#define HAVE_STDDEF_H
   25.14 +#define HAVE_STDLIB_H
   25.15 +#undef NEED_BSD_STRINGS
   25.16 +#undef NEED_SYS_TYPES_H
   25.17 +#undef NEED_FAR_POINTERS	/* we presume a 32-bit flat memory model */
   25.18 +#undef NEED_SHORT_EXTERNAL_NAMES
   25.19 +#undef INCOMPLETE_TYPES_BROKEN
   25.20 +
   25.21 +/* Define "boolean" as unsigned char, not int, per Windows custom */
   25.22 +#ifndef __RPCNDR_H__		/* don't conflict if rpcndr.h already read */
   25.23 +typedef unsigned char boolean;
   25.24 +#endif
   25.25 +#define HAVE_BOOLEAN		/* prevent jmorecfg.h from redefining it */
   25.26 +
   25.27 +
   25.28 +#ifdef JPEG_INTERNALS
   25.29 +
   25.30 +#undef RIGHT_SHIFT_IS_UNSIGNED
   25.31 +
   25.32 +#endif /* JPEG_INTERNALS */
   25.33 +
   25.34 +#ifdef JPEG_CJPEG_DJPEG
   25.35 +
   25.36 +#define BMP_SUPPORTED		/* BMP image file format */
   25.37 +#define GIF_SUPPORTED		/* GIF image file format */
   25.38 +#define PPM_SUPPORTED		/* PBMPLUS PPM/PGM image file format */
   25.39 +#undef RLE_SUPPORTED		/* Utah RLE image file format */
   25.40 +#define TARGA_SUPPORTED		/* Targa image file format */
   25.41 +
   25.42 +#define TWO_FILE_COMMANDLINE	/* optional */
   25.43 +#define USE_SETMODE		/* Microsoft has setmode() */
   25.44 +#undef NEED_SIGNAL_CATCHER
   25.45 +#undef DONT_USE_B_MODE
   25.46 +#undef PROGRESS_REPORT		/* optional */
   25.47 +
   25.48 +#endif /* JPEG_CJPEG_DJPEG */
    26.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    26.2 +++ b/libs/libjpeg/jcparam.c	Thu Sep 08 06:28:38 2011 +0300
    26.3 @@ -0,0 +1,610 @@
    26.4 +/*
    26.5 + * jcparam.c
    26.6 + *
    26.7 + * Copyright (C) 1991-1998, Thomas G. Lane.
    26.8 + * This file is part of the Independent JPEG Group's software.
    26.9 + * For conditions of distribution and use, see the accompanying README file.
   26.10 + *
   26.11 + * This file contains optional default-setting code for the JPEG compressor.
   26.12 + * Applications do not have to use this file, but those that don't use it
   26.13 + * must know a lot more about the innards of the JPEG code.
   26.14 + */
   26.15 +
   26.16 +#define JPEG_INTERNALS
   26.17 +#include "jinclude.h"
   26.18 +#include "jpeglib.h"
   26.19 +
   26.20 +
   26.21 +/*
   26.22 + * Quantization table setup routines
   26.23 + */
   26.24 +
   26.25 +GLOBAL(void)
   26.26 +jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
   26.27 +		      const unsigned int *basic_table,
   26.28 +		      int scale_factor, boolean force_baseline)
   26.29 +/* Define a quantization table equal to the basic_table times
   26.30 + * a scale factor (given as a percentage).
   26.31 + * If force_baseline is TRUE, the computed quantization table entries
   26.32 + * are limited to 1..255 for JPEG baseline compatibility.
   26.33 + */
   26.34 +{
   26.35 +  JQUANT_TBL ** qtblptr;
   26.36 +  int i;
   26.37 +  long temp;
   26.38 +
   26.39 +  /* Safety check to ensure start_compress not called yet. */
   26.40 +  if (cinfo->global_state != CSTATE_START)
   26.41 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
   26.42 +
   26.43 +  if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
   26.44 +    ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
   26.45 +
   26.46 +  qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
   26.47 +
   26.48 +  if (*qtblptr == NULL)
   26.49 +    *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
   26.50 +
   26.51 +  for (i = 0; i < DCTSIZE2; i++) {
   26.52 +    temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
   26.53 +    /* limit the values to the valid range */
   26.54 +    if (temp <= 0L) temp = 1L;
   26.55 +    if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
   26.56 +    if (force_baseline && temp > 255L)
   26.57 +      temp = 255L;		/* limit to baseline range if requested */
   26.58 +    (*qtblptr)->quantval[i] = (UINT16) temp;
   26.59 +  }
   26.60 +
   26.61 +  /* Initialize sent_table FALSE so table will be written to JPEG file. */
   26.62 +  (*qtblptr)->sent_table = FALSE;
   26.63 +}
   26.64 +
   26.65 +
   26.66 +GLOBAL(void)
   26.67 +jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
   26.68 +			 boolean force_baseline)
   26.69 +/* Set or change the 'quality' (quantization) setting, using default tables
   26.70 + * and a straight percentage-scaling quality scale.  In most cases it's better
   26.71 + * to use jpeg_set_quality (below); this entry point is provided for
   26.72 + * applications that insist on a linear percentage scaling.
   26.73 + */
   26.74 +{
   26.75 +  /* These are the sample quantization tables given in JPEG spec section K.1.
   26.76 +   * The spec says that the values given produce "good" quality, and
   26.77 +   * when divided by 2, "very good" quality.
   26.78 +   */
   26.79 +  static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
   26.80 +    16,  11,  10,  16,  24,  40,  51,  61,
   26.81 +    12,  12,  14,  19,  26,  58,  60,  55,
   26.82 +    14,  13,  16,  24,  40,  57,  69,  56,
   26.83 +    14,  17,  22,  29,  51,  87,  80,  62,
   26.84 +    18,  22,  37,  56,  68, 109, 103,  77,
   26.85 +    24,  35,  55,  64,  81, 104, 113,  92,
   26.86 +    49,  64,  78,  87, 103, 121, 120, 101,
   26.87 +    72,  92,  95,  98, 112, 100, 103,  99
   26.88 +  };
   26.89 +  static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
   26.90 +    17,  18,  24,  47,  99,  99,  99,  99,
   26.91 +    18,  21,  26,  66,  99,  99,  99,  99,
   26.92 +    24,  26,  56,  99,  99,  99,  99,  99,
   26.93 +    47,  66,  99,  99,  99,  99,  99,  99,
   26.94 +    99,  99,  99,  99,  99,  99,  99,  99,
   26.95 +    99,  99,  99,  99,  99,  99,  99,  99,
   26.96 +    99,  99,  99,  99,  99,  99,  99,  99,
   26.97 +    99,  99,  99,  99,  99,  99,  99,  99
   26.98 +  };
   26.99 +
  26.100 +  /* Set up two quantization tables using the specified scaling */
  26.101 +  jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  26.102 +		       scale_factor, force_baseline);
  26.103 +  jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  26.104 +		       scale_factor, force_baseline);
  26.105 +}
  26.106 +
  26.107 +
  26.108 +GLOBAL(int)
  26.109 +jpeg_quality_scaling (int quality)
  26.110 +/* Convert a user-specified quality rating to a percentage scaling factor
  26.111 + * for an underlying quantization table, using our recommended scaling curve.
  26.112 + * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  26.113 + */
  26.114 +{
  26.115 +  /* Safety limit on quality factor.  Convert 0 to 1 to avoid zero divide. */
  26.116 +  if (quality <= 0) quality = 1;
  26.117 +  if (quality > 100) quality = 100;
  26.118 +
  26.119 +  /* The basic table is used as-is (scaling 100) for a quality of 50.
  26.120 +   * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  26.121 +   * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  26.122 +   * to make all the table entries 1 (hence, minimum quantization loss).
  26.123 +   * Qualities 1..50 are converted to scaling percentage 5000/Q.
  26.124 +   */
  26.125 +  if (quality < 50)
  26.126 +    quality = 5000 / quality;
  26.127 +  else
  26.128 +    quality = 200 - quality*2;
  26.129 +
  26.130 +  return quality;
  26.131 +}
  26.132 +
  26.133 +
  26.134 +GLOBAL(void)
  26.135 +jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  26.136 +/* Set or change the 'quality' (quantization) setting, using default tables.
  26.137 + * This is the standard quality-adjusting entry point for typical user
  26.138 + * interfaces; only those who want detailed control over quantization tables
  26.139 + * would use the preceding three routines directly.
  26.140 + */
  26.141 +{
  26.142 +  /* Convert user 0-100 rating to percentage scaling */
  26.143 +  quality = jpeg_quality_scaling(quality);
  26.144 +
  26.145 +  /* Set up standard quality tables */
  26.146 +  jpeg_set_linear_quality(cinfo, quality, force_baseline);
  26.147 +}
  26.148 +
  26.149 +
  26.150 +/*
  26.151 + * Huffman table setup routines
  26.152 + */
  26.153 +
  26.154 +LOCAL(void)
  26.155 +add_huff_table (j_compress_ptr cinfo,
  26.156 +		JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  26.157 +/* Define a Huffman table */
  26.158 +{
  26.159 +  int nsymbols, len;
  26.160 +
  26.161 +  if (*htblptr == NULL)
  26.162 +    *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  26.163 +
  26.164 +  /* Copy the number-of-symbols-of-each-code-length counts */
  26.165 +  MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  26.166 +
  26.167 +  /* Validate the counts.  We do this here mainly so we can copy the right
  26.168 +   * number of symbols from the val[] array, without risking marching off
  26.169 +   * the end of memory.  jchuff.c will do a more thorough test later.
  26.170 +   */
  26.171 +  nsymbols = 0;
  26.172 +  for (len = 1; len <= 16; len++)
  26.173 +    nsymbols += bits[len];
  26.174 +  if (nsymbols < 1 || nsymbols > 256)
  26.175 +    ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  26.176 +
  26.177 +  MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  26.178 +
  26.179 +  /* Initialize sent_table FALSE so table will be written to JPEG file. */
  26.180 +  (*htblptr)->sent_table = FALSE;
  26.181 +}
  26.182 +
  26.183 +
  26.184 +LOCAL(void)
  26.185 +std_huff_tables (j_compress_ptr cinfo)
  26.186 +/* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  26.187 +/* IMPORTANT: these are only valid for 8-bit data precision! */
  26.188 +{
  26.189 +  static const UINT8 bits_dc_luminance[17] =
  26.190 +    { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  26.191 +  static const UINT8 val_dc_luminance[] =
  26.192 +    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  26.193 +  
  26.194 +  static const UINT8 bits_dc_chrominance[17] =
  26.195 +    { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  26.196 +  static const UINT8 val_dc_chrominance[] =
  26.197 +    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  26.198 +  
  26.199 +  static const UINT8 bits_ac_luminance[17] =
  26.200 +    { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  26.201 +  static const UINT8 val_ac_luminance[] =
  26.202 +    { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  26.203 +      0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  26.204 +      0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  26.205 +      0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  26.206 +      0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  26.207 +      0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  26.208 +      0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  26.209 +      0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  26.210 +      0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  26.211 +      0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  26.212 +      0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  26.213 +      0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  26.214 +      0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  26.215 +      0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  26.216 +      0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  26.217 +      0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  26.218 +      0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  26.219 +      0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  26.220 +      0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  26.221 +      0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  26.222 +      0xf9, 0xfa };
  26.223 +  
  26.224 +  static const UINT8 bits_ac_chrominance[17] =
  26.225 +    { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  26.226 +  static const UINT8 val_ac_chrominance[] =
  26.227 +    { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  26.228 +      0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  26.229 +      0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  26.230 +      0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  26.231 +      0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  26.232 +      0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  26.233 +      0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  26.234 +      0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  26.235 +      0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  26.236 +      0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  26.237 +      0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  26.238 +      0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  26.239 +      0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  26.240 +      0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  26.241 +      0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  26.242 +      0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  26.243 +      0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  26.244 +      0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  26.245 +      0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  26.246 +      0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  26.247 +      0xf9, 0xfa };
  26.248 +  
  26.249 +  add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  26.250 +		 bits_dc_luminance, val_dc_luminance);
  26.251 +  add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  26.252 +		 bits_ac_luminance, val_ac_luminance);
  26.253 +  add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  26.254 +		 bits_dc_chrominance, val_dc_chrominance);
  26.255 +  add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  26.256 +		 bits_ac_chrominance, val_ac_chrominance);
  26.257 +}
  26.258 +
  26.259 +
  26.260 +/*
  26.261 + * Default parameter setup for compression.
  26.262 + *
  26.263 + * Applications that don't choose to use this routine must do their
  26.264 + * own setup of all these parameters.  Alternately, you can call this
  26.265 + * to establish defaults and then alter parameters selectively.  This
  26.266 + * is the recommended approach since, if we add any new parameters,
  26.267 + * your code will still work (they'll be set to reasonable defaults).
  26.268 + */
  26.269 +
  26.270 +GLOBAL(void)
  26.271 +jpeg_set_defaults (j_compress_ptr cinfo)
  26.272 +{
  26.273 +  int i;
  26.274 +
  26.275 +  /* Safety check to ensure start_compress not called yet. */
  26.276 +  if (cinfo->global_state != CSTATE_START)
  26.277 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  26.278 +
  26.279 +  /* Allocate comp_info array large enough for maximum component count.
  26.280 +   * Array is made permanent in case application wants to compress
  26.281 +   * multiple images at same param settings.
  26.282 +   */
  26.283 +  if (cinfo->comp_info == NULL)
  26.284 +    cinfo->comp_info = (jpeg_component_info *)
  26.285 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  26.286 +				  MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  26.287 +
  26.288 +  /* Initialize everything not dependent on the color space */
  26.289 +
  26.290 +  cinfo->data_precision = BITS_IN_JSAMPLE;
  26.291 +  /* Set up two quantization tables using default quality of 75 */
  26.292 +  jpeg_set_quality(cinfo, 75, TRUE);
  26.293 +  /* Set up two Huffman tables */
  26.294 +  std_huff_tables(cinfo);
  26.295 +
  26.296 +  /* Initialize default arithmetic coding conditioning */
  26.297 +  for (i = 0; i < NUM_ARITH_TBLS; i++) {
  26.298 +    cinfo->arith_dc_L[i] = 0;
  26.299 +    cinfo->arith_dc_U[i] = 1;
  26.300 +    cinfo->arith_ac_K[i] = 5;
  26.301 +  }
  26.302 +
  26.303 +  /* Default is no multiple-scan output */
  26.304 +  cinfo->scan_info = NULL;
  26.305 +  cinfo->num_scans = 0;
  26.306 +
  26.307 +  /* Expect normal source image, not raw downsampled data */
  26.308 +  cinfo->raw_data_in = FALSE;
  26.309 +
  26.310 +  /* Use Huffman coding, not arithmetic coding, by default */
  26.311 +  cinfo->arith_code = FALSE;
  26.312 +
  26.313 +  /* By default, don't do extra passes to optimize entropy coding */
  26.314 +  cinfo->optimize_coding = FALSE;
  26.315 +  /* The standard Huffman tables are only valid for 8-bit data precision.
  26.316 +   * If the precision is higher, force optimization on so that usable
  26.317 +   * tables will be computed.  This test can be removed if default tables
  26.318 +   * are supplied that are valid for the desired precision.
  26.319 +   */
  26.320 +  if (cinfo->data_precision > 8)
  26.321 +    cinfo->optimize_coding = TRUE;
  26.322 +
  26.323 +  /* By default, use the simpler non-cosited sampling alignment */
  26.324 +  cinfo->CCIR601_sampling = FALSE;
  26.325 +
  26.326 +  /* No input smoothing */
  26.327 +  cinfo->smoothing_factor = 0;
  26.328 +
  26.329 +  /* DCT algorithm preference */
  26.330 +  cinfo->dct_method = JDCT_DEFAULT;
  26.331 +
  26.332 +  /* No restart markers */
  26.333 +  cinfo->restart_interval = 0;
  26.334 +  cinfo->restart_in_rows = 0;
  26.335 +
  26.336 +  /* Fill in default JFIF marker parameters.  Note that whether the marker
  26.337 +   * will actually be written is determined by jpeg_set_colorspace.
  26.338 +   *
  26.339 +   * By default, the library emits JFIF version code 1.01.
  26.340 +   * An application that wants to emit JFIF 1.02 extension markers should set
  26.341 +   * JFIF_minor_version to 2.  We could probably get away with just defaulting
  26.342 +   * to 1.02, but there may still be some decoders in use that will complain
  26.343 +   * about that; saying 1.01 should minimize compatibility problems.
  26.344 +   */
  26.345 +  cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  26.346 +  cinfo->JFIF_minor_version = 1;
  26.347 +  cinfo->density_unit = 0;	/* Pixel size is unknown by default */
  26.348 +  cinfo->X_density = 1;		/* Pixel aspect ratio is square by default */
  26.349 +  cinfo->Y_density = 1;
  26.350 +
  26.351 +  /* Choose JPEG colorspace based on input space, set defaults accordingly */
  26.352 +
  26.353 +  jpeg_default_colorspace(cinfo);
  26.354 +}
  26.355 +
  26.356 +
  26.357 +/*
  26.358 + * Select an appropriate JPEG colorspace for in_color_space.
  26.359 + */
  26.360 +
  26.361 +GLOBAL(void)
  26.362 +jpeg_default_colorspace (j_compress_ptr cinfo)
  26.363 +{
  26.364 +  switch (cinfo->in_color_space) {
  26.365 +  case JCS_GRAYSCALE:
  26.366 +    jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  26.367 +    break;
  26.368 +  case JCS_RGB:
  26.369 +    jpeg_set_colorspace(cinfo, JCS_YCbCr);
  26.370 +    break;
  26.371 +  case JCS_YCbCr:
  26.372 +    jpeg_set_colorspace(cinfo, JCS_YCbCr);
  26.373 +    break;
  26.374 +  case JCS_CMYK:
  26.375 +    jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  26.376 +    break;
  26.377 +  case JCS_YCCK:
  26.378 +    jpeg_set_colorspace(cinfo, JCS_YCCK);
  26.379 +    break;
  26.380 +  case JCS_UNKNOWN:
  26.381 +    jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  26.382 +    break;
  26.383 +  default:
  26.384 +    ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  26.385 +  }
  26.386 +}
  26.387 +
  26.388 +
  26.389 +/*
  26.390 + * Set the JPEG colorspace, and choose colorspace-dependent default values.
  26.391 + */
  26.392 +
  26.393 +GLOBAL(void)
  26.394 +jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  26.395 +{
  26.396 +  jpeg_component_info * compptr;
  26.397 +  int ci;
  26.398 +
  26.399 +#define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl)  \
  26.400 +  (compptr = &cinfo->comp_info[index], \
  26.401 +   compptr->component_id = (id), \
  26.402 +   compptr->h_samp_factor = (hsamp), \
  26.403 +   compptr->v_samp_factor = (vsamp), \
  26.404 +   compptr->quant_tbl_no = (quant), \
  26.405 +   compptr->dc_tbl_no = (dctbl), \
  26.406 +   compptr->ac_tbl_no = (actbl) )
  26.407 +
  26.408 +  /* Safety check to ensure start_compress not called yet. */
  26.409 +  if (cinfo->global_state != CSTATE_START)
  26.410 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  26.411 +
  26.412 +  /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  26.413 +   * tables 1 for chrominance components.
  26.414 +   */
  26.415 +
  26.416 +  cinfo->jpeg_color_space = colorspace;
  26.417 +
  26.418 +  cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  26.419 +  cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  26.420 +
  26.421 +  switch (colorspace) {
  26.422 +  case JCS_GRAYSCALE:
  26.423 +    cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  26.424 +    cinfo->num_components = 1;
  26.425 +    /* JFIF specifies component ID 1 */
  26.426 +    SET_COMP(0, 1, 1,1, 0, 0,0);
  26.427 +    break;
  26.428 +  case JCS_RGB:
  26.429 +    cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  26.430 +    cinfo->num_components = 3;
  26.431 +    SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  26.432 +    SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  26.433 +    SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  26.434 +    break;
  26.435 +  case JCS_YCbCr:
  26.436 +    cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  26.437 +    cinfo->num_components = 3;
  26.438 +    /* JFIF specifies component IDs 1,2,3 */
  26.439 +    /* We default to 2x2 subsamples of chrominance */
  26.440 +    SET_COMP(0, 1, 2,2, 0, 0,0);
  26.441 +    SET_COMP(1, 2, 1,1, 1, 1,1);
  26.442 +    SET_COMP(2, 3, 1,1, 1, 1,1);
  26.443 +    break;
  26.444 +  case JCS_CMYK:
  26.445 +    cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  26.446 +    cinfo->num_components = 4;
  26.447 +    SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  26.448 +    SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  26.449 +    SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  26.450 +    SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  26.451 +    break;
  26.452 +  case JCS_YCCK:
  26.453 +    cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  26.454 +    cinfo->num_components = 4;
  26.455 +    SET_COMP(0, 1, 2,2, 0, 0,0);
  26.456 +    SET_COMP(1, 2, 1,1, 1, 1,1);
  26.457 +    SET_COMP(2, 3, 1,1, 1, 1,1);
  26.458 +    SET_COMP(3, 4, 2,2, 0, 0,0);
  26.459 +    break;
  26.460 +  case JCS_UNKNOWN:
  26.461 +    cinfo->num_components = cinfo->input_components;
  26.462 +    if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  26.463 +      ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  26.464 +	       MAX_COMPONENTS);
  26.465 +    for (ci = 0; ci < cinfo->num_components; ci++) {
  26.466 +      SET_COMP(ci, ci, 1,1, 0, 0,0);
  26.467 +    }
  26.468 +    break;
  26.469 +  default:
  26.470 +    ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  26.471 +  }
  26.472 +}
  26.473 +
  26.474 +
  26.475 +#ifdef C_PROGRESSIVE_SUPPORTED
  26.476 +
  26.477 +LOCAL(jpeg_scan_info *)
  26.478 +fill_a_scan (jpeg_scan_info * scanptr, int ci,
  26.479 +	     int Ss, int Se, int Ah, int Al)
  26.480 +/* Support routine: generate one scan for specified component */
  26.481 +{
  26.482 +  scanptr->comps_in_scan = 1;
  26.483 +  scanptr->component_index[0] = ci;
  26.484 +  scanptr->Ss = Ss;
  26.485 +  scanptr->Se = Se;
  26.486 +  scanptr->Ah = Ah;
  26.487 +  scanptr->Al = Al;
  26.488 +  scanptr++;
  26.489 +  return scanptr;
  26.490 +}
  26.491 +
  26.492 +LOCAL(jpeg_scan_info *)
  26.493 +fill_scans (jpeg_scan_info * scanptr, int ncomps,
  26.494 +	    int Ss, int Se, int Ah, int Al)
  26.495 +/* Support routine: generate one scan for each component */
  26.496 +{
  26.497 +  int ci;
  26.498 +
  26.499 +  for (ci = 0; ci < ncomps; ci++) {
  26.500 +    scanptr->comps_in_scan = 1;
  26.501 +    scanptr->component_index[0] = ci;
  26.502 +    scanptr->Ss = Ss;
  26.503 +    scanptr->Se = Se;
  26.504 +    scanptr->Ah = Ah;
  26.505 +    scanptr->Al = Al;
  26.506 +    scanptr++;
  26.507 +  }
  26.508 +  return scanptr;
  26.509 +}
  26.510 +
  26.511 +LOCAL(jpeg_scan_info *)
  26.512 +fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  26.513 +/* Support routine: generate interleaved DC scan if possible, else N scans */
  26.514 +{
  26.515 +  int ci;
  26.516 +
  26.517 +  if (ncomps <= MAX_COMPS_IN_SCAN) {
  26.518 +    /* Single interleaved DC scan */
  26.519 +    scanptr->comps_in_scan = ncomps;
  26.520 +    for (ci = 0; ci < ncomps; ci++)
  26.521 +      scanptr->component_index[ci] = ci;
  26.522 +    scanptr->Ss = scanptr->Se = 0;
  26.523 +    scanptr->Ah = Ah;
  26.524 +    scanptr->Al = Al;
  26.525 +    scanptr++;
  26.526 +  } else {
  26.527 +    /* Noninterleaved DC scan for each component */
  26.528 +    scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  26.529 +  }
  26.530 +  return scanptr;
  26.531 +}
  26.532 +
  26.533 +
  26.534 +/*
  26.535 + * Create a recommended progressive-JPEG script.
  26.536 + * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  26.537 + */
  26.538 +
  26.539 +GLOBAL(void)
  26.540 +jpeg_simple_progression (j_compress_ptr cinfo)
  26.541 +{
  26.542 +  int ncomps = cinfo->num_components;
  26.543 +  int nscans;
  26.544 +  jpeg_scan_info * scanptr;
  26.545 +
  26.546 +  /* Safety check to ensure start_compress not called yet. */
  26.547 +  if (cinfo->global_state != CSTATE_START)
  26.548 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  26.549 +
  26.550 +  /* Figure space needed for script.  Calculation must match code below! */
  26.551 +  if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  26.552 +    /* Custom script for YCbCr color images. */
  26.553 +    nscans = 10;
  26.554 +  } else {
  26.555 +    /* All-purpose script for other color spaces. */
  26.556 +    if (ncomps > MAX_COMPS_IN_SCAN)
  26.557 +      nscans = 6 * ncomps;	/* 2 DC + 4 AC scans per component */
  26.558 +    else
  26.559 +      nscans = 2 + 4 * ncomps;	/* 2 DC scans; 4 AC scans per component */
  26.560 +  }
  26.561 +
  26.562 +  /* Allocate space for script.
  26.563 +   * We need to put it in the permanent pool in case the application performs
  26.564 +   * multiple compressions without changing the settings.  To avoid a memory
  26.565 +   * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  26.566 +   * object, we try to re-use previously allocated space, and we allocate
  26.567 +   * enough space to handle YCbCr even if initially asked for grayscale.
  26.568 +   */
  26.569 +  if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  26.570 +    cinfo->script_space_size = MAX(nscans, 10);
  26.571 +    cinfo->script_space = (jpeg_scan_info *)
  26.572 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  26.573 +			cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  26.574 +  }
  26.575 +  scanptr = cinfo->script_space;
  26.576 +  cinfo->scan_info = scanptr;
  26.577 +  cinfo->num_scans = nscans;
  26.578 +
  26.579 +  if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  26.580 +    /* Custom script for YCbCr color images. */
  26.581 +    /* Initial DC scan */
  26.582 +    scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  26.583 +    /* Initial AC scan: get some luma data out in a hurry */
  26.584 +    scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  26.585 +    /* Chroma data is too small to be worth expending many scans on */
  26.586 +    scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  26.587 +    scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  26.588 +    /* Complete spectral selection for luma AC */
  26.589 +    scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  26.590 +    /* Refine next bit of luma AC */
  26.591 +    scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  26.592 +    /* Finish DC successive approximation */
  26.593 +    scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  26.594 +    /* Finish AC successive approximation */
  26.595 +    scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  26.596 +    scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  26.597 +    /* Luma bottom bit comes last since it's usually largest scan */
  26.598 +    scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  26.599 +  } else {
  26.600 +    /* All-purpose script for other color spaces. */
  26.601 +    /* Successive approximation first pass */
  26.602 +    scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  26.603 +    scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  26.604 +    scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  26.605 +    /* Successive approximation second pass */
  26.606 +    scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  26.607 +    /* Successive approximation final pass */
  26.608 +    scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  26.609 +    scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  26.610 +  }
  26.611 +}
  26.612 +
  26.613 +#endif /* C_PROGRESSIVE_SUPPORTED */
    27.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    27.2 +++ b/libs/libjpeg/jcphuff.c	Thu Sep 08 06:28:38 2011 +0300
    27.3 @@ -0,0 +1,833 @@
    27.4 +/*
    27.5 + * jcphuff.c
    27.6 + *
    27.7 + * Copyright (C) 1995-1997, Thomas G. Lane.
    27.8 + * This file is part of the Independent JPEG Group's software.
    27.9 + * For conditions of distribution and use, see the accompanying README file.
   27.10 + *
   27.11 + * This file contains Huffman entropy encoding routines for progressive JPEG.
   27.12 + *
   27.13 + * We do not support output suspension in this module, since the library
   27.14 + * currently does not allow multiple-scan files to be written with output
   27.15 + * suspension.
   27.16 + */
   27.17 +
   27.18 +#define JPEG_INTERNALS
   27.19 +#include "jinclude.h"
   27.20 +#include "jpeglib.h"
   27.21 +#include "jchuff.h"		/* Declarations shared with jchuff.c */
   27.22 +
   27.23 +#ifdef C_PROGRESSIVE_SUPPORTED
   27.24 +
   27.25 +/* Expanded entropy encoder object for progressive Huffman encoding. */
   27.26 +
   27.27 +typedef struct {
   27.28 +  struct jpeg_entropy_encoder pub; /* public fields */
   27.29 +
   27.30 +  /* Mode flag: TRUE for optimization, FALSE for actual data output */
   27.31 +  boolean gather_statistics;
   27.32 +
   27.33 +  /* Bit-level coding status.
   27.34 +   * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
   27.35 +   */
   27.36 +  JOCTET * next_output_byte;	/* => next byte to write in buffer */
   27.37 +  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
   27.38 +  INT32 put_buffer;		/* current bit-accumulation buffer */
   27.39 +  int put_bits;			/* # of bits now in it */
   27.40 +  j_compress_ptr cinfo;		/* link to cinfo (needed for dump_buffer) */
   27.41 +
   27.42 +  /* Coding status for DC components */
   27.43 +  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
   27.44 +
   27.45 +  /* Coding status for AC components */
   27.46 +  int ac_tbl_no;		/* the table number of the single component */
   27.47 +  unsigned int EOBRUN;		/* run length of EOBs */
   27.48 +  unsigned int BE;		/* # of buffered correction bits before MCU */
   27.49 +  char * bit_buffer;		/* buffer for correction bits (1 per char) */
   27.50 +  /* packing correction bits tightly would save some space but cost time... */
   27.51 +
   27.52 +  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
   27.53 +  int next_restart_num;		/* next restart number to write (0-7) */
   27.54 +
   27.55 +  /* Pointers to derived tables (these workspaces have image lifespan).
   27.56 +   * Since any one scan codes only DC or only AC, we only need one set
   27.57 +   * of tables, not one for DC and one for AC.
   27.58 +   */
   27.59 +  c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
   27.60 +
   27.61 +  /* Statistics tables for optimization; again, one set is enough */
   27.62 +  long * count_ptrs[NUM_HUFF_TBLS];
   27.63 +} phuff_entropy_encoder;
   27.64 +
   27.65 +typedef phuff_entropy_encoder * phuff_entropy_ptr;
   27.66 +
   27.67 +/* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
   27.68 + * buffer can hold.  Larger sizes may slightly improve compression, but
   27.69 + * 1000 is already well into the realm of overkill.
   27.70 + * The minimum safe size is 64 bits.
   27.71 + */
   27.72 +
   27.73 +#define MAX_CORR_BITS  1000	/* Max # of correction bits I can buffer */
   27.74 +
   27.75 +/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
   27.76 + * We assume that int right shift is unsigned if INT32 right shift is,
   27.77 + * which should be safe.
   27.78 + */
   27.79 +
   27.80 +#ifdef RIGHT_SHIFT_IS_UNSIGNED
   27.81 +#define ISHIFT_TEMPS	int ishift_temp;
   27.82 +#define IRIGHT_SHIFT(x,shft)  \
   27.83 +	((ishift_temp = (x)) < 0 ? \
   27.84 +	 (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
   27.85 +	 (ishift_temp >> (shft)))
   27.86 +#else
   27.87 +#define ISHIFT_TEMPS
   27.88 +#define IRIGHT_SHIFT(x,shft)	((x) >> (shft))
   27.89 +#endif
   27.90 +
   27.91 +/* Forward declarations */
   27.92 +METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
   27.93 +					    JBLOCKROW *MCU_data));
   27.94 +METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
   27.95 +					    JBLOCKROW *MCU_data));
   27.96 +METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
   27.97 +					     JBLOCKROW *MCU_data));
   27.98 +METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
   27.99 +					     JBLOCKROW *MCU_data));
  27.100 +METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  27.101 +METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  27.102 +
  27.103 +
  27.104 +/*
  27.105 + * Initialize for a Huffman-compressed scan using progressive JPEG.
  27.106 + */
  27.107 +
  27.108 +METHODDEF(void)
  27.109 +start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  27.110 +{  
  27.111 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  27.112 +  boolean is_DC_band;
  27.113 +  int ci, tbl;
  27.114 +  jpeg_component_info * compptr;
  27.115 +
  27.116 +  entropy->cinfo = cinfo;
  27.117 +  entropy->gather_statistics = gather_statistics;
  27.118 +
  27.119 +  is_DC_band = (cinfo->Ss == 0);
  27.120 +
  27.121 +  /* We assume jcmaster.c already validated the scan parameters. */
  27.122 +
  27.123 +  /* Select execution routines */
  27.124 +  if (cinfo->Ah == 0) {
  27.125 +    if (is_DC_band)
  27.126 +      entropy->pub.encode_mcu = encode_mcu_DC_first;
  27.127 +    else
  27.128 +      entropy->pub.encode_mcu = encode_mcu_AC_first;
  27.129 +  } else {
  27.130 +    if (is_DC_band)
  27.131 +      entropy->pub.encode_mcu = encode_mcu_DC_refine;
  27.132 +    else {
  27.133 +      entropy->pub.encode_mcu = encode_mcu_AC_refine;
  27.134 +      /* AC refinement needs a correction bit buffer */
  27.135 +      if (entropy->bit_buffer == NULL)
  27.136 +	entropy->bit_buffer = (char *)
  27.137 +	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  27.138 +				      MAX_CORR_BITS * SIZEOF(char));
  27.139 +    }
  27.140 +  }
  27.141 +  if (gather_statistics)
  27.142 +    entropy->pub.finish_pass = finish_pass_gather_phuff;
  27.143 +  else
  27.144 +    entropy->pub.finish_pass = finish_pass_phuff;
  27.145 +
  27.146 +  /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  27.147 +   * for AC coefficients.
  27.148 +   */
  27.149 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  27.150 +    compptr = cinfo->cur_comp_info[ci];
  27.151 +    /* Initialize DC predictions to 0 */
  27.152 +    entropy->last_dc_val[ci] = 0;
  27.153 +    /* Get table index */
  27.154 +    if (is_DC_band) {
  27.155 +      if (cinfo->Ah != 0)	/* DC refinement needs no table */
  27.156 +	continue;
  27.157 +      tbl = compptr->dc_tbl_no;
  27.158 +    } else {
  27.159 +      entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  27.160 +    }
  27.161 +    if (gather_statistics) {
  27.162 +      /* Check for invalid table index */
  27.163 +      /* (make_c_derived_tbl does this in the other path) */
  27.164 +      if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  27.165 +        ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  27.166 +      /* Allocate and zero the statistics tables */
  27.167 +      /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  27.168 +      if (entropy->count_ptrs[tbl] == NULL)
  27.169 +	entropy->count_ptrs[tbl] = (long *)
  27.170 +	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  27.171 +				      257 * SIZEOF(long));
  27.172 +      MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  27.173 +    } else {
  27.174 +      /* Compute derived values for Huffman table */
  27.175 +      /* We may do this more than once for a table, but it's not expensive */
  27.176 +      jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  27.177 +			      & entropy->derived_tbls[tbl]);
  27.178 +    }
  27.179 +  }
  27.180 +
  27.181 +  /* Initialize AC stuff */
  27.182 +  entropy->EOBRUN = 0;
  27.183 +  entropy->BE = 0;
  27.184 +
  27.185 +  /* Initialize bit buffer to empty */
  27.186 +  entropy->put_buffer = 0;
  27.187 +  entropy->put_bits = 0;
  27.188 +
  27.189 +  /* Initialize restart stuff */
  27.190 +  entropy->restarts_to_go = cinfo->restart_interval;
  27.191 +  entropy->next_restart_num = 0;
  27.192 +}
  27.193 +
  27.194 +
  27.195 +/* Outputting bytes to the file.
  27.196 + * NB: these must be called only when actually outputting,
  27.197 + * that is, entropy->gather_statistics == FALSE.
  27.198 + */
  27.199 +
  27.200 +/* Emit a byte */
  27.201 +#define emit_byte(entropy,val)  \
  27.202 +	{ *(entropy)->next_output_byte++ = (JOCTET) (val);  \
  27.203 +	  if (--(entropy)->free_in_buffer == 0)  \
  27.204 +	    dump_buffer(entropy); }
  27.205 +
  27.206 +
  27.207 +LOCAL(void)
  27.208 +dump_buffer (phuff_entropy_ptr entropy)
  27.209 +/* Empty the output buffer; we do not support suspension in this module. */
  27.210 +{
  27.211 +  struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  27.212 +
  27.213 +  if (! (*dest->empty_output_buffer) (entropy->cinfo))
  27.214 +    ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  27.215 +  /* After a successful buffer dump, must reset buffer pointers */
  27.216 +  entropy->next_output_byte = dest->next_output_byte;
  27.217 +  entropy->free_in_buffer = dest->free_in_buffer;
  27.218 +}
  27.219 +
  27.220 +
  27.221 +/* Outputting bits to the file */
  27.222 +
  27.223 +/* Only the right 24 bits of put_buffer are used; the valid bits are
  27.224 + * left-justified in this part.  At most 16 bits can be passed to emit_bits
  27.225 + * in one call, and we never retain more than 7 bits in put_buffer
  27.226 + * between calls, so 24 bits are sufficient.
  27.227 + */
  27.228 +
  27.229 +INLINE
  27.230 +LOCAL(void)
  27.231 +emit_bits (phuff_entropy_ptr entropy, unsigned int code, int size)
  27.232 +/* Emit some bits, unless we are in gather mode */
  27.233 +{
  27.234 +  /* This routine is heavily used, so it's worth coding tightly. */
  27.235 +  register INT32 put_buffer = (INT32) code;
  27.236 +  register int put_bits = entropy->put_bits;
  27.237 +
  27.238 +  /* if size is 0, caller used an invalid Huffman table entry */
  27.239 +  if (size == 0)
  27.240 +    ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  27.241 +
  27.242 +  if (entropy->gather_statistics)
  27.243 +    return;			/* do nothing if we're only getting stats */
  27.244 +
  27.245 +  put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  27.246 +  
  27.247 +  put_bits += size;		/* new number of bits in buffer */
  27.248 +  
  27.249 +  put_buffer <<= 24 - put_bits; /* align incoming bits */
  27.250 +
  27.251 +  put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  27.252 +
  27.253 +  while (put_bits >= 8) {
  27.254 +    int c = (int) ((put_buffer >> 16) & 0xFF);
  27.255 +    
  27.256 +    emit_byte(entropy, c);
  27.257 +    if (c == 0xFF) {		/* need to stuff a zero byte? */
  27.258 +      emit_byte(entropy, 0);
  27.259 +    }
  27.260 +    put_buffer <<= 8;
  27.261 +    put_bits -= 8;
  27.262 +  }
  27.263 +
  27.264 +  entropy->put_buffer = put_buffer; /* update variables */
  27.265 +  entropy->put_bits = put_bits;
  27.266 +}
  27.267 +
  27.268 +
  27.269 +LOCAL(void)
  27.270 +flush_bits (phuff_entropy_ptr entropy)
  27.271 +{
  27.272 +  emit_bits(entropy, 0x7F, 7); /* fill any partial byte with ones */
  27.273 +  entropy->put_buffer = 0;     /* and reset bit-buffer to empty */
  27.274 +  entropy->put_bits = 0;
  27.275 +}
  27.276 +
  27.277 +
  27.278 +/*
  27.279 + * Emit (or just count) a Huffman symbol.
  27.280 + */
  27.281 +
  27.282 +INLINE
  27.283 +LOCAL(void)
  27.284 +emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  27.285 +{
  27.286 +  if (entropy->gather_statistics)
  27.287 +    entropy->count_ptrs[tbl_no][symbol]++;
  27.288 +  else {
  27.289 +    c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  27.290 +    emit_bits(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  27.291 +  }
  27.292 +}
  27.293 +
  27.294 +
  27.295 +/*
  27.296 + * Emit bits from a correction bit buffer.
  27.297 + */
  27.298 +
  27.299 +LOCAL(void)
  27.300 +emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  27.301 +		    unsigned int nbits)
  27.302 +{
  27.303 +  if (entropy->gather_statistics)
  27.304 +    return;			/* no real work */
  27.305 +
  27.306 +  while (nbits > 0) {
  27.307 +    emit_bits(entropy, (unsigned int) (*bufstart), 1);
  27.308 +    bufstart++;
  27.309 +    nbits--;
  27.310 +  }
  27.311 +}
  27.312 +
  27.313 +
  27.314 +/*
  27.315 + * Emit any pending EOBRUN symbol.
  27.316 + */
  27.317 +
  27.318 +LOCAL(void)
  27.319 +emit_eobrun (phuff_entropy_ptr entropy)
  27.320 +{
  27.321 +  register int temp, nbits;
  27.322 +
  27.323 +  if (entropy->EOBRUN > 0) {	/* if there is any pending EOBRUN */
  27.324 +    temp = entropy->EOBRUN;
  27.325 +    nbits = 0;
  27.326 +    while ((temp >>= 1))
  27.327 +      nbits++;
  27.328 +    /* safety check: shouldn't happen given limited correction-bit buffer */
  27.329 +    if (nbits > 14)
  27.330 +      ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  27.331 +
  27.332 +    emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  27.333 +    if (nbits)
  27.334 +      emit_bits(entropy, entropy->EOBRUN, nbits);
  27.335 +
  27.336 +    entropy->EOBRUN = 0;
  27.337 +
  27.338 +    /* Emit any buffered correction bits */
  27.339 +    emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  27.340 +    entropy->BE = 0;
  27.341 +  }
  27.342 +}
  27.343 +
  27.344 +
  27.345 +/*
  27.346 + * Emit a restart marker & resynchronize predictions.
  27.347 + */
  27.348 +
  27.349 +LOCAL(void)
  27.350 +emit_restart (phuff_entropy_ptr entropy, int restart_num)
  27.351 +{
  27.352 +  int ci;
  27.353 +
  27.354 +  emit_eobrun(entropy);
  27.355 +
  27.356 +  if (! entropy->gather_statistics) {
  27.357 +    flush_bits(entropy);
  27.358 +    emit_byte(entropy, 0xFF);
  27.359 +    emit_byte(entropy, JPEG_RST0 + restart_num);
  27.360 +  }
  27.361 +
  27.362 +  if (entropy->cinfo->Ss == 0) {
  27.363 +    /* Re-initialize DC predictions to 0 */
  27.364 +    for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  27.365 +      entropy->last_dc_val[ci] = 0;
  27.366 +  } else {
  27.367 +    /* Re-initialize all AC-related fields to 0 */
  27.368 +    entropy->EOBRUN = 0;
  27.369 +    entropy->BE = 0;
  27.370 +  }
  27.371 +}
  27.372 +
  27.373 +
  27.374 +/*
  27.375 + * MCU encoding for DC initial scan (either spectral selection,
  27.376 + * or first pass of successive approximation).
  27.377 + */
  27.378 +
  27.379 +METHODDEF(boolean)
  27.380 +encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  27.381 +{
  27.382 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  27.383 +  register int temp, temp2;
  27.384 +  register int nbits;
  27.385 +  int blkn, ci;
  27.386 +  int Al = cinfo->Al;
  27.387 +  JBLOCKROW block;
  27.388 +  jpeg_component_info * compptr;
  27.389 +  ISHIFT_TEMPS
  27.390 +
  27.391 +  entropy->next_output_byte = cinfo->dest->next_output_byte;
  27.392 +  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  27.393 +
  27.394 +  /* Emit restart marker if needed */
  27.395 +  if (cinfo->restart_interval)
  27.396 +    if (entropy->restarts_to_go == 0)
  27.397 +      emit_restart(entropy, entropy->next_restart_num);
  27.398 +
  27.399 +  /* Encode the MCU data blocks */
  27.400 +  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  27.401 +    block = MCU_data[blkn];
  27.402 +    ci = cinfo->MCU_membership[blkn];
  27.403 +    compptr = cinfo->cur_comp_info[ci];
  27.404 +
  27.405 +    /* Compute the DC value after the required point transform by Al.
  27.406 +     * This is simply an arithmetic right shift.
  27.407 +     */
  27.408 +    temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  27.409 +
  27.410 +    /* DC differences are figured on the point-transformed values. */
  27.411 +    temp = temp2 - entropy->last_dc_val[ci];
  27.412 +    entropy->last_dc_val[ci] = temp2;
  27.413 +
  27.414 +    /* Encode the DC coefficient difference per section G.1.2.1 */
  27.415 +    temp2 = temp;
  27.416 +    if (temp < 0) {
  27.417 +      temp = -temp;		/* temp is abs value of input */
  27.418 +      /* For a negative input, want temp2 = bitwise complement of abs(input) */
  27.419 +      /* This code assumes we are on a two's complement machine */
  27.420 +      temp2--;
  27.421 +    }
  27.422 +    
  27.423 +    /* Find the number of bits needed for the magnitude of the coefficient */
  27.424 +    nbits = 0;
  27.425 +    while (temp) {
  27.426 +      nbits++;
  27.427 +      temp >>= 1;
  27.428 +    }
  27.429 +    /* Check for out-of-range coefficient values.
  27.430 +     * Since we're encoding a difference, the range limit is twice as much.
  27.431 +     */
  27.432 +    if (nbits > MAX_COEF_BITS+1)
  27.433 +      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  27.434 +    
  27.435 +    /* Count/emit the Huffman-coded symbol for the number of bits */
  27.436 +    emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  27.437 +    
  27.438 +    /* Emit that number of bits of the value, if positive, */
  27.439 +    /* or the complement of its magnitude, if negative. */
  27.440 +    if (nbits)			/* emit_bits rejects calls with size 0 */
  27.441 +      emit_bits(entropy, (unsigned int) temp2, nbits);
  27.442 +  }
  27.443 +
  27.444 +  cinfo->dest->next_output_byte = entropy->next_output_byte;
  27.445 +  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  27.446 +
  27.447 +  /* Update restart-interval state too */
  27.448 +  if (cinfo->restart_interval) {
  27.449 +    if (entropy->restarts_to_go == 0) {
  27.450 +      entropy->restarts_to_go = cinfo->restart_interval;
  27.451 +      entropy->next_restart_num++;
  27.452 +      entropy->next_restart_num &= 7;
  27.453 +    }
  27.454 +    entropy->restarts_to_go--;
  27.455 +  }
  27.456 +
  27.457 +  return TRUE;
  27.458 +}
  27.459 +
  27.460 +
  27.461 +/*
  27.462 + * MCU encoding for AC initial scan (either spectral selection,
  27.463 + * or first pass of successive approximation).
  27.464 + */
  27.465 +
  27.466 +METHODDEF(boolean)
  27.467 +encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  27.468 +{
  27.469 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  27.470 +  register int temp, temp2;
  27.471 +  register int nbits;
  27.472 +  register int r, k;
  27.473 +  int Se = cinfo->Se;
  27.474 +  int Al = cinfo->Al;
  27.475 +  JBLOCKROW block;
  27.476 +
  27.477 +  entropy->next_output_byte = cinfo->dest->next_output_byte;
  27.478 +  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  27.479 +
  27.480 +  /* Emit restart marker if needed */
  27.481 +  if (cinfo->restart_interval)
  27.482 +    if (entropy->restarts_to_go == 0)
  27.483 +      emit_restart(entropy, entropy->next_restart_num);
  27.484 +
  27.485 +  /* Encode the MCU data block */
  27.486 +  block = MCU_data[0];
  27.487 +
  27.488 +  /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  27.489 +  
  27.490 +  r = 0;			/* r = run length of zeros */
  27.491 +   
  27.492 +  for (k = cinfo->Ss; k <= Se; k++) {
  27.493 +    if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  27.494 +      r++;
  27.495 +      continue;
  27.496 +    }
  27.497 +    /* We must apply the point transform by Al.  For AC coefficients this
  27.498 +     * is an integer division with rounding towards 0.  To do this portably
  27.499 +     * in C, we shift after obtaining the absolute value; so the code is
  27.500 +     * interwoven with finding the abs value (temp) and output bits (temp2).
  27.501 +     */
  27.502 +    if (temp < 0) {
  27.503 +      temp = -temp;		/* temp is abs value of input */
  27.504 +      temp >>= Al;		/* apply the point transform */
  27.505 +      /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  27.506 +      temp2 = ~temp;
  27.507 +    } else {
  27.508 +      temp >>= Al;		/* apply the point transform */
  27.509 +      temp2 = temp;
  27.510 +    }
  27.511 +    /* Watch out for case that nonzero coef is zero after point transform */
  27.512 +    if (temp == 0) {
  27.513 +      r++;
  27.514 +      continue;
  27.515 +    }
  27.516 +
  27.517 +    /* Emit any pending EOBRUN */
  27.518 +    if (entropy->EOBRUN > 0)
  27.519 +      emit_eobrun(entropy);
  27.520 +    /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  27.521 +    while (r > 15) {
  27.522 +      emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  27.523 +      r -= 16;
  27.524 +    }
  27.525 +
  27.526 +    /* Find the number of bits needed for the magnitude of the coefficient */
  27.527 +    nbits = 1;			/* there must be at least one 1 bit */
  27.528 +    while ((temp >>= 1))
  27.529 +      nbits++;
  27.530 +    /* Check for out-of-range coefficient values */
  27.531 +    if (nbits > MAX_COEF_BITS)
  27.532 +      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  27.533 +
  27.534 +    /* Count/emit Huffman symbol for run length / number of bits */
  27.535 +    emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  27.536 +
  27.537 +    /* Emit that number of bits of the value, if positive, */
  27.538 +    /* or the complement of its magnitude, if negative. */
  27.539 +    emit_bits(entropy, (unsigned int) temp2, nbits);
  27.540 +
  27.541 +    r = 0;			/* reset zero run length */
  27.542 +  }
  27.543 +
  27.544 +  if (r > 0) {			/* If there are trailing zeroes, */
  27.545 +    entropy->EOBRUN++;		/* count an EOB */
  27.546 +    if (entropy->EOBRUN == 0x7FFF)
  27.547 +      emit_eobrun(entropy);	/* force it out to avoid overflow */
  27.548 +  }
  27.549 +
  27.550 +  cinfo->dest->next_output_byte = entropy->next_output_byte;
  27.551 +  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  27.552 +
  27.553 +  /* Update restart-interval state too */
  27.554 +  if (cinfo->restart_interval) {
  27.555 +    if (entropy->restarts_to_go == 0) {
  27.556 +      entropy->restarts_to_go = cinfo->restart_interval;
  27.557 +      entropy->next_restart_num++;
  27.558 +      entropy->next_restart_num &= 7;
  27.559 +    }
  27.560 +    entropy->restarts_to_go--;
  27.561 +  }
  27.562 +
  27.563 +  return TRUE;
  27.564 +}
  27.565 +
  27.566 +
  27.567 +/*
  27.568 + * MCU encoding for DC successive approximation refinement scan.
  27.569 + * Note: we assume such scans can be multi-component, although the spec
  27.570 + * is not very clear on the point.
  27.571 + */
  27.572 +
  27.573 +METHODDEF(boolean)
  27.574 +encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  27.575 +{
  27.576 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  27.577 +  register int temp;
  27.578 +  int blkn;
  27.579 +  int Al = cinfo->Al;
  27.580 +  JBLOCKROW block;
  27.581 +
  27.582 +  entropy->next_output_byte = cinfo->dest->next_output_byte;
  27.583 +  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  27.584 +
  27.585 +  /* Emit restart marker if needed */
  27.586 +  if (cinfo->restart_interval)
  27.587 +    if (entropy->restarts_to_go == 0)
  27.588 +      emit_restart(entropy, entropy->next_restart_num);
  27.589 +
  27.590 +  /* Encode the MCU data blocks */
  27.591 +  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  27.592 +    block = MCU_data[blkn];
  27.593 +
  27.594 +    /* We simply emit the Al'th bit of the DC coefficient value. */
  27.595 +    temp = (*block)[0];
  27.596 +    emit_bits(entropy, (unsigned int) (temp >> Al), 1);
  27.597 +  }
  27.598 +
  27.599 +  cinfo->dest->next_output_byte = entropy->next_output_byte;
  27.600 +  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  27.601 +
  27.602 +  /* Update restart-interval state too */
  27.603 +  if (cinfo->restart_interval) {
  27.604 +    if (entropy->restarts_to_go == 0) {
  27.605 +      entropy->restarts_to_go = cinfo->restart_interval;
  27.606 +      entropy->next_restart_num++;
  27.607 +      entropy->next_restart_num &= 7;
  27.608 +    }
  27.609 +    entropy->restarts_to_go--;
  27.610 +  }
  27.611 +
  27.612 +  return TRUE;
  27.613 +}
  27.614 +
  27.615 +
  27.616 +/*
  27.617 + * MCU encoding for AC successive approximation refinement scan.
  27.618 + */
  27.619 +
  27.620 +METHODDEF(boolean)
  27.621 +encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  27.622 +{
  27.623 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  27.624 +  register int temp;
  27.625 +  register int r, k;
  27.626 +  int EOB;
  27.627 +  char *BR_buffer;
  27.628 +  unsigned int BR;
  27.629 +  int Se = cinfo->Se;
  27.630 +  int Al = cinfo->Al;
  27.631 +  JBLOCKROW block;
  27.632 +  int absvalues[DCTSIZE2];
  27.633 +
  27.634 +  entropy->next_output_byte = cinfo->dest->next_output_byte;
  27.635 +  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  27.636 +
  27.637 +  /* Emit restart marker if needed */
  27.638 +  if (cinfo->restart_interval)
  27.639 +    if (entropy->restarts_to_go == 0)
  27.640 +      emit_restart(entropy, entropy->next_restart_num);
  27.641 +
  27.642 +  /* Encode the MCU data block */
  27.643 +  block = MCU_data[0];
  27.644 +
  27.645 +  /* It is convenient to make a pre-pass to determine the transformed
  27.646 +   * coefficients' absolute values and the EOB position.
  27.647 +   */
  27.648 +  EOB = 0;
  27.649 +  for (k = cinfo->Ss; k <= Se; k++) {
  27.650 +    temp = (*block)[jpeg_natural_order[k]];
  27.651 +    /* We must apply the point transform by Al.  For AC coefficients this
  27.652 +     * is an integer division with rounding towards 0.  To do this portably
  27.653 +     * in C, we shift after obtaining the absolute value.
  27.654 +     */
  27.655 +    if (temp < 0)
  27.656 +      temp = -temp;		/* temp is abs value of input */
  27.657 +    temp >>= Al;		/* apply the point transform */
  27.658 +    absvalues[k] = temp;	/* save abs value for main pass */
  27.659 +    if (temp == 1)
  27.660 +      EOB = k;			/* EOB = index of last newly-nonzero coef */
  27.661 +  }
  27.662 +
  27.663 +  /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  27.664 +  
  27.665 +  r = 0;			/* r = run length of zeros */
  27.666 +  BR = 0;			/* BR = count of buffered bits added now */
  27.667 +  BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  27.668 +
  27.669 +  for (k = cinfo->Ss; k <= Se; k++) {
  27.670 +    if ((temp = absvalues[k]) == 0) {
  27.671 +      r++;
  27.672 +      continue;
  27.673 +    }
  27.674 +
  27.675 +    /* Emit any required ZRLs, but not if they can be folded into EOB */
  27.676 +    while (r > 15 && k <= EOB) {
  27.677 +      /* emit any pending EOBRUN and the BE correction bits */
  27.678 +      emit_eobrun(entropy);
  27.679 +      /* Emit ZRL */
  27.680 +      emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  27.681 +      r -= 16;
  27.682 +      /* Emit buffered correction bits that must be associated with ZRL */
  27.683 +      emit_buffered_bits(entropy, BR_buffer, BR);
  27.684 +      BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  27.685 +      BR = 0;
  27.686 +    }
  27.687 +
  27.688 +    /* If the coef was previously nonzero, it only needs a correction bit.
  27.689 +     * NOTE: a straight translation of the spec's figure G.7 would suggest
  27.690 +     * that we also need to test r > 15.  But if r > 15, we can only get here
  27.691 +     * if k > EOB, which implies that this coefficient is not 1.
  27.692 +     */
  27.693 +    if (temp > 1) {
  27.694 +      /* The correction bit is the next bit of the absolute value. */
  27.695 +      BR_buffer[BR++] = (char) (temp & 1);
  27.696 +      continue;
  27.697 +    }
  27.698 +
  27.699 +    /* Emit any pending EOBRUN and the BE correction bits */
  27.700 +    emit_eobrun(entropy);
  27.701 +
  27.702 +    /* Count/emit Huffman symbol for run length / number of bits */
  27.703 +    emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  27.704 +
  27.705 +    /* Emit output bit for newly-nonzero coef */
  27.706 +    temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  27.707 +    emit_bits(entropy, (unsigned int) temp, 1);
  27.708 +
  27.709 +    /* Emit buffered correction bits that must be associated with this code */
  27.710 +    emit_buffered_bits(entropy, BR_buffer, BR);
  27.711 +    BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  27.712 +    BR = 0;
  27.713 +    r = 0;			/* reset zero run length */
  27.714 +  }
  27.715 +
  27.716 +  if (r > 0 || BR > 0) {	/* If there are trailing zeroes, */
  27.717 +    entropy->EOBRUN++;		/* count an EOB */
  27.718 +    entropy->BE += BR;		/* concat my correction bits to older ones */
  27.719 +    /* We force out the EOB if we risk either:
  27.720 +     * 1. overflow of the EOB counter;
  27.721 +     * 2. overflow of the correction bit buffer during the next MCU.
  27.722 +     */
  27.723 +    if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  27.724 +      emit_eobrun(entropy);
  27.725 +  }
  27.726 +
  27.727 +  cinfo->dest->next_output_byte = entropy->next_output_byte;
  27.728 +  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  27.729 +
  27.730 +  /* Update restart-interval state too */
  27.731 +  if (cinfo->restart_interval) {
  27.732 +    if (entropy->restarts_to_go == 0) {
  27.733 +      entropy->restarts_to_go = cinfo->restart_interval;
  27.734 +      entropy->next_restart_num++;
  27.735 +      entropy->next_restart_num &= 7;
  27.736 +    }
  27.737 +    entropy->restarts_to_go--;
  27.738 +  }
  27.739 +
  27.740 +  return TRUE;
  27.741 +}
  27.742 +
  27.743 +
  27.744 +/*
  27.745 + * Finish up at the end of a Huffman-compressed progressive scan.
  27.746 + */
  27.747 +
  27.748 +METHODDEF(void)
  27.749 +finish_pass_phuff (j_compress_ptr cinfo)
  27.750 +{   
  27.751 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  27.752 +
  27.753 +  entropy->next_output_byte = cinfo->dest->next_output_byte;
  27.754 +  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  27.755 +
  27.756 +  /* Flush out any buffered data */
  27.757 +  emit_eobrun(entropy);
  27.758 +  flush_bits(entropy);
  27.759 +
  27.760 +  cinfo->dest->next_output_byte = entropy->next_output_byte;
  27.761 +  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  27.762 +}
  27.763 +
  27.764 +
  27.765 +/*
  27.766 + * Finish up a statistics-gathering pass and create the new Huffman tables.
  27.767 + */
  27.768 +
  27.769 +METHODDEF(void)
  27.770 +finish_pass_gather_phuff (j_compress_ptr cinfo)
  27.771 +{
  27.772 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  27.773 +  boolean is_DC_band;
  27.774 +  int ci, tbl;
  27.775 +  jpeg_component_info * compptr;
  27.776 +  JHUFF_TBL **htblptr;
  27.777 +  boolean did[NUM_HUFF_TBLS];
  27.778 +
  27.779 +  /* Flush out buffered data (all we care about is counting the EOB symbol) */
  27.780 +  emit_eobrun(entropy);
  27.781 +
  27.782 +  is_DC_band = (cinfo->Ss == 0);
  27.783 +
  27.784 +  /* It's important not to apply jpeg_gen_optimal_table more than once
  27.785 +   * per table, because it clobbers the input frequency counts!
  27.786 +   */
  27.787 +  MEMZERO(did, SIZEOF(did));
  27.788 +
  27.789 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  27.790 +    compptr = cinfo->cur_comp_info[ci];
  27.791 +    if (is_DC_band) {
  27.792 +      if (cinfo->Ah != 0)	/* DC refinement needs no table */
  27.793 +	continue;
  27.794 +      tbl = compptr->dc_tbl_no;
  27.795 +    } else {
  27.796 +      tbl = compptr->ac_tbl_no;
  27.797 +    }
  27.798 +    if (! did[tbl]) {
  27.799 +      if (is_DC_band)
  27.800 +        htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  27.801 +      else
  27.802 +        htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  27.803 +      if (*htblptr == NULL)
  27.804 +        *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  27.805 +      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  27.806 +      did[tbl] = TRUE;
  27.807 +    }
  27.808 +  }
  27.809 +}
  27.810 +
  27.811 +
  27.812 +/*
  27.813 + * Module initialization routine for progressive Huffman entropy encoding.
  27.814 + */
  27.815 +
  27.816 +GLOBAL(void)
  27.817 +jinit_phuff_encoder (j_compress_ptr cinfo)
  27.818 +{
  27.819 +  phuff_entropy_ptr entropy;
  27.820 +  int i;
  27.821 +
  27.822 +  entropy = (phuff_entropy_ptr)
  27.823 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  27.824 +				SIZEOF(phuff_entropy_encoder));
  27.825 +  cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  27.826 +  entropy->pub.start_pass = start_pass_phuff;
  27.827 +
  27.828 +  /* Mark tables unallocated */
  27.829 +  for (i = 0; i < NUM_HUFF_TBLS; i++) {
  27.830 +    entropy->derived_tbls[i] = NULL;
  27.831 +    entropy->count_ptrs[i] = NULL;
  27.832 +  }
  27.833 +  entropy->bit_buffer = NULL;	/* needed only in AC refinement scan */
  27.834 +}
  27.835 +
  27.836 +#endif /* C_PROGRESSIVE_SUPPORTED */
    28.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    28.2 +++ b/libs/libjpeg/jcprepct.c	Thu Sep 08 06:28:38 2011 +0300
    28.3 @@ -0,0 +1,354 @@
    28.4 +/*
    28.5 + * jcprepct.c
    28.6 + *
    28.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    28.8 + * This file is part of the Independent JPEG Group's software.
    28.9 + * For conditions of distribution and use, see the accompanying README file.
   28.10 + *
   28.11 + * This file contains the compression preprocessing controller.
   28.12 + * This controller manages the color conversion, downsampling,
   28.13 + * and edge expansion steps.
   28.14 + *
   28.15 + * Most of the complexity here is associated with buffering input rows
   28.16 + * as required by the downsampler.  See the comments at the head of
   28.17 + * jcsample.c for the downsampler's needs.
   28.18 + */
   28.19 +
   28.20 +#define JPEG_INTERNALS
   28.21 +#include "jinclude.h"
   28.22 +#include "jpeglib.h"
   28.23 +
   28.24 +
   28.25 +/* At present, jcsample.c can request context rows only for smoothing.
   28.26 + * In the future, we might also need context rows for CCIR601 sampling
   28.27 + * or other more-complex downsampling procedures.  The code to support
   28.28 + * context rows should be compiled only if needed.
   28.29 + */
   28.30 +#ifdef INPUT_SMOOTHING_SUPPORTED
   28.31 +#define CONTEXT_ROWS_SUPPORTED
   28.32 +#endif
   28.33 +
   28.34 +
   28.35 +/*
   28.36 + * For the simple (no-context-row) case, we just need to buffer one
   28.37 + * row group's worth of pixels for the downsampling step.  At the bottom of
   28.38 + * the image, we pad to a full row group by replicating the last pixel row.
   28.39 + * The downsampler's last output row is then replicated if needed to pad
   28.40 + * out to a full iMCU row.
   28.41 + *
   28.42 + * When providing context rows, we must buffer three row groups' worth of
   28.43 + * pixels.  Three row groups are physically allocated, but the row pointer
   28.44 + * arrays are made five row groups high, with the extra pointers above and
   28.45 + * below "wrapping around" to point to the last and first real row groups.
   28.46 + * This allows the downsampler to access the proper context rows.
   28.47 + * At the top and bottom of the image, we create dummy context rows by
   28.48 + * copying the first or last real pixel row.  This copying could be avoided
   28.49 + * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
   28.50 + * trouble on the compression side.
   28.51 + */
   28.52 +
   28.53 +
   28.54 +/* Private buffer controller object */
   28.55 +
   28.56 +typedef struct {
   28.57 +  struct jpeg_c_prep_controller pub; /* public fields */
   28.58 +
   28.59 +  /* Downsampling input buffer.  This buffer holds color-converted data
   28.60 +   * until we have enough to do a downsample step.
   28.61 +   */
   28.62 +  JSAMPARRAY color_buf[MAX_COMPONENTS];
   28.63 +
   28.64 +  JDIMENSION rows_to_go;	/* counts rows remaining in source image */
   28.65 +  int next_buf_row;		/* index of next row to store in color_buf */
   28.66 +
   28.67 +#ifdef CONTEXT_ROWS_SUPPORTED	/* only needed for context case */
   28.68 +  int this_row_group;		/* starting row index of group to process */
   28.69 +  int next_buf_stop;		/* downsample when we reach this index */
   28.70 +#endif
   28.71 +} my_prep_controller;
   28.72 +
   28.73 +typedef my_prep_controller * my_prep_ptr;
   28.74 +
   28.75 +
   28.76 +/*
   28.77 + * Initialize for a processing pass.
   28.78 + */
   28.79 +
   28.80 +METHODDEF(void)
   28.81 +start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
   28.82 +{
   28.83 +  my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
   28.84 +
   28.85 +  if (pass_mode != JBUF_PASS_THRU)
   28.86 +    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
   28.87 +
   28.88 +  /* Initialize total-height counter for detecting bottom of image */
   28.89 +  prep->rows_to_go = cinfo->image_height;
   28.90 +  /* Mark the conversion buffer empty */
   28.91 +  prep->next_buf_row = 0;
   28.92 +#ifdef CONTEXT_ROWS_SUPPORTED
   28.93 +  /* Preset additional state variables for context mode.
   28.94 +   * These aren't used in non-context mode, so we needn't test which mode.
   28.95 +   */
   28.96 +  prep->this_row_group = 0;
   28.97 +  /* Set next_buf_stop to stop after two row groups have been read in. */
   28.98 +  prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
   28.99 +#endif
  28.100 +}
  28.101 +
  28.102 +
  28.103 +/*
  28.104 + * Expand an image vertically from height input_rows to height output_rows,
  28.105 + * by duplicating the bottom row.
  28.106 + */
  28.107 +
  28.108 +LOCAL(void)
  28.109 +expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  28.110 +		    int input_rows, int output_rows)
  28.111 +{
  28.112 +  register int row;
  28.113 +
  28.114 +  for (row = input_rows; row < output_rows; row++) {
  28.115 +    jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  28.116 +		      1, num_cols);
  28.117 +  }
  28.118 +}
  28.119 +
  28.120 +
  28.121 +/*
  28.122 + * Process some data in the simple no-context case.
  28.123 + *
  28.124 + * Preprocessor output data is counted in "row groups".  A row group
  28.125 + * is defined to be v_samp_factor sample rows of each component.
  28.126 + * Downsampling will produce this much data from each max_v_samp_factor
  28.127 + * input rows.
  28.128 + */
  28.129 +
  28.130 +METHODDEF(void)
  28.131 +pre_process_data (j_compress_ptr cinfo,
  28.132 +		  JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  28.133 +		  JDIMENSION in_rows_avail,
  28.134 +		  JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  28.135 +		  JDIMENSION out_row_groups_avail)
  28.136 +{
  28.137 +  my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  28.138 +  int numrows, ci;
  28.139 +  JDIMENSION inrows;
  28.140 +  jpeg_component_info * compptr;
  28.141 +
  28.142 +  while (*in_row_ctr < in_rows_avail &&
  28.143 +	 *out_row_group_ctr < out_row_groups_avail) {
  28.144 +    /* Do color conversion to fill the conversion buffer. */
  28.145 +    inrows = in_rows_avail - *in_row_ctr;
  28.146 +    numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  28.147 +    numrows = (int) MIN((JDIMENSION) numrows, inrows);
  28.148 +    (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  28.149 +				       prep->color_buf,
  28.150 +				       (JDIMENSION) prep->next_buf_row,
  28.151 +				       numrows);
  28.152 +    *in_row_ctr += numrows;
  28.153 +    prep->next_buf_row += numrows;
  28.154 +    prep->rows_to_go -= numrows;
  28.155 +    /* If at bottom of image, pad to fill the conversion buffer. */
  28.156 +    if (prep->rows_to_go == 0 &&
  28.157 +	prep->next_buf_row < cinfo->max_v_samp_factor) {
  28.158 +      for (ci = 0; ci < cinfo->num_components; ci++) {
  28.159 +	expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  28.160 +			   prep->next_buf_row, cinfo->max_v_samp_factor);
  28.161 +      }
  28.162 +      prep->next_buf_row = cinfo->max_v_samp_factor;
  28.163 +    }
  28.164 +    /* If we've filled the conversion buffer, empty it. */
  28.165 +    if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  28.166 +      (*cinfo->downsample->downsample) (cinfo,
  28.167 +					prep->color_buf, (JDIMENSION) 0,
  28.168 +					output_buf, *out_row_group_ctr);
  28.169 +      prep->next_buf_row = 0;
  28.170 +      (*out_row_group_ctr)++;
  28.171 +    }
  28.172 +    /* If at bottom of image, pad the output to a full iMCU height.
  28.173 +     * Note we assume the caller is providing a one-iMCU-height output buffer!
  28.174 +     */
  28.175 +    if (prep->rows_to_go == 0 &&
  28.176 +	*out_row_group_ctr < out_row_groups_avail) {
  28.177 +      for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  28.178 +	   ci++, compptr++) {
  28.179 +	expand_bottom_edge(output_buf[ci],
  28.180 +			   compptr->width_in_blocks * DCTSIZE,
  28.181 +			   (int) (*out_row_group_ctr * compptr->v_samp_factor),
  28.182 +			   (int) (out_row_groups_avail * compptr->v_samp_factor));
  28.183 +      }
  28.184 +      *out_row_group_ctr = out_row_groups_avail;
  28.185 +      break;			/* can exit outer loop without test */
  28.186 +    }
  28.187 +  }
  28.188 +}
  28.189 +
  28.190 +
  28.191 +#ifdef CONTEXT_ROWS_SUPPORTED
  28.192 +
  28.193 +/*
  28.194 + * Process some data in the context case.
  28.195 + */
  28.196 +
  28.197 +METHODDEF(void)
  28.198 +pre_process_context (j_compress_ptr cinfo,
  28.199 +		     JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  28.200 +		     JDIMENSION in_rows_avail,
  28.201 +		     JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  28.202 +		     JDIMENSION out_row_groups_avail)
  28.203 +{
  28.204 +  my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  28.205 +  int numrows, ci;
  28.206 +  int buf_height = cinfo->max_v_samp_factor * 3;
  28.207 +  JDIMENSION inrows;
  28.208 +
  28.209 +  while (*out_row_group_ctr < out_row_groups_avail) {
  28.210 +    if (*in_row_ctr < in_rows_avail) {
  28.211 +      /* Do color conversion to fill the conversion buffer. */
  28.212 +      inrows = in_rows_avail - *in_row_ctr;
  28.213 +      numrows = prep->next_buf_stop - prep->next_buf_row;
  28.214 +      numrows = (int) MIN((JDIMENSION) numrows, inrows);
  28.215 +      (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  28.216 +					 prep->color_buf,
  28.217 +					 (JDIMENSION) prep->next_buf_row,
  28.218 +					 numrows);
  28.219 +      /* Pad at top of image, if first time through */
  28.220 +      if (prep->rows_to_go == cinfo->image_height) {
  28.221 +	for (ci = 0; ci < cinfo->num_components; ci++) {
  28.222 +	  int row;
  28.223 +	  for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  28.224 +	    jcopy_sample_rows(prep->color_buf[ci], 0,
  28.225 +			      prep->color_buf[ci], -row,
  28.226 +			      1, cinfo->image_width);
  28.227 +	  }
  28.228 +	}
  28.229 +      }
  28.230 +      *in_row_ctr += numrows;
  28.231 +      prep->next_buf_row += numrows;
  28.232 +      prep->rows_to_go -= numrows;
  28.233 +    } else {
  28.234 +      /* Return for more data, unless we are at the bottom of the image. */
  28.235 +      if (prep->rows_to_go != 0)
  28.236 +	break;
  28.237 +      /* When at bottom of image, pad to fill the conversion buffer. */
  28.238 +      if (prep->next_buf_row < prep->next_buf_stop) {
  28.239 +	for (ci = 0; ci < cinfo->num_components; ci++) {
  28.240 +	  expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  28.241 +			     prep->next_buf_row, prep->next_buf_stop);
  28.242 +	}
  28.243 +	prep->next_buf_row = prep->next_buf_stop;
  28.244 +      }
  28.245 +    }
  28.246 +    /* If we've gotten enough data, downsample a row group. */
  28.247 +    if (prep->next_buf_row == prep->next_buf_stop) {
  28.248 +      (*cinfo->downsample->downsample) (cinfo,
  28.249 +					prep->color_buf,
  28.250 +					(JDIMENSION) prep->this_row_group,
  28.251 +					output_buf, *out_row_group_ctr);
  28.252 +      (*out_row_group_ctr)++;
  28.253 +      /* Advance pointers with wraparound as necessary. */
  28.254 +      prep->this_row_group += cinfo->max_v_samp_factor;
  28.255 +      if (prep->this_row_group >= buf_height)
  28.256 +	prep->this_row_group = 0;
  28.257 +      if (prep->next_buf_row >= buf_height)
  28.258 +	prep->next_buf_row = 0;
  28.259 +      prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  28.260 +    }
  28.261 +  }
  28.262 +}
  28.263 +
  28.264 +
  28.265 +/*
  28.266 + * Create the wrapped-around downsampling input buffer needed for context mode.
  28.267 + */
  28.268 +
  28.269 +LOCAL(void)
  28.270 +create_context_buffer (j_compress_ptr cinfo)
  28.271 +{
  28.272 +  my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  28.273 +  int rgroup_height = cinfo->max_v_samp_factor;
  28.274 +  int ci, i;
  28.275 +  jpeg_component_info * compptr;
  28.276 +  JSAMPARRAY true_buffer, fake_buffer;
  28.277 +
  28.278 +  /* Grab enough space for fake row pointers for all the components;
  28.279 +   * we need five row groups' worth of pointers for each component.
  28.280 +   */
  28.281 +  fake_buffer = (JSAMPARRAY)
  28.282 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  28.283 +				(cinfo->num_components * 5 * rgroup_height) *
  28.284 +				SIZEOF(JSAMPROW));
  28.285 +
  28.286 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  28.287 +       ci++, compptr++) {
  28.288 +    /* Allocate the actual buffer space (3 row groups) for this component.
  28.289 +     * We make the buffer wide enough to allow the downsampler to edge-expand
  28.290 +     * horizontally within the buffer, if it so chooses.
  28.291 +     */
  28.292 +    true_buffer = (*cinfo->mem->alloc_sarray)
  28.293 +      ((j_common_ptr) cinfo, JPOOL_IMAGE,
  28.294 +       (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  28.295 +		      cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  28.296 +       (JDIMENSION) (3 * rgroup_height));
  28.297 +    /* Copy true buffer row pointers into the middle of the fake row array */
  28.298 +    MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  28.299 +	    3 * rgroup_height * SIZEOF(JSAMPROW));
  28.300 +    /* Fill in the above and below wraparound pointers */
  28.301 +    for (i = 0; i < rgroup_height; i++) {
  28.302 +      fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  28.303 +      fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  28.304 +    }
  28.305 +    prep->color_buf[ci] = fake_buffer + rgroup_height;
  28.306 +    fake_buffer += 5 * rgroup_height; /* point to space for next component */
  28.307 +  }
  28.308 +}
  28.309 +
  28.310 +#endif /* CONTEXT_ROWS_SUPPORTED */
  28.311 +
  28.312 +
  28.313 +/*
  28.314 + * Initialize preprocessing controller.
  28.315 + */
  28.316 +
  28.317 +GLOBAL(void)
  28.318 +jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  28.319 +{
  28.320 +  my_prep_ptr prep;
  28.321 +  int ci;
  28.322 +  jpeg_component_info * compptr;
  28.323 +
  28.324 +  if (need_full_buffer)		/* safety check */
  28.325 +    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  28.326 +
  28.327 +  prep = (my_prep_ptr)
  28.328 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  28.329 +				SIZEOF(my_prep_controller));
  28.330 +  cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  28.331 +  prep->pub.start_pass = start_pass_prep;
  28.332 +
  28.333 +  /* Allocate the color conversion buffer.
  28.334 +   * We make the buffer wide enough to allow the downsampler to edge-expand
  28.335 +   * horizontally within the buffer, if it so chooses.
  28.336 +   */
  28.337 +  if (cinfo->downsample->need_context_rows) {
  28.338 +    /* Set up to provide context rows */
  28.339 +#ifdef CONTEXT_ROWS_SUPPORTED
  28.340 +    prep->pub.pre_process_data = pre_process_context;
  28.341 +    create_context_buffer(cinfo);
  28.342 +#else
  28.343 +    ERREXIT(cinfo, JERR_NOT_COMPILED);
  28.344 +#endif
  28.345 +  } else {
  28.346 +    /* No context, just make it tall enough for one row group */
  28.347 +    prep->pub.pre_process_data = pre_process_data;
  28.348 +    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  28.349 +	 ci++, compptr++) {
  28.350 +      prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  28.351 +	((j_common_ptr) cinfo, JPOOL_IMAGE,
  28.352 +	 (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  28.353 +			cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  28.354 +	 (JDIMENSION) cinfo->max_v_samp_factor);
  28.355 +    }
  28.356 +  }
  28.357 +}
    29.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    29.2 +++ b/libs/libjpeg/jcsample.c	Thu Sep 08 06:28:38 2011 +0300
    29.3 @@ -0,0 +1,519 @@
    29.4 +/*
    29.5 + * jcsample.c
    29.6 + *
    29.7 + * Copyright (C) 1991-1996, Thomas G. Lane.
    29.8 + * This file is part of the Independent JPEG Group's software.
    29.9 + * For conditions of distribution and use, see the accompanying README file.
   29.10 + *
   29.11 + * This file contains downsampling routines.
   29.12 + *
   29.13 + * Downsampling input data is counted in "row groups".  A row group
   29.14 + * is defined to be max_v_samp_factor pixel rows of each component,
   29.15 + * from which the downsampler produces v_samp_factor sample rows.
   29.16 + * A single row group is processed in each call to the downsampler module.
   29.17 + *
   29.18 + * The downsampler is responsible for edge-expansion of its output data
   29.19 + * to fill an integral number of DCT blocks horizontally.  The source buffer
   29.20 + * may be modified if it is helpful for this purpose (the source buffer is
   29.21 + * allocated wide enough to correspond to the desired output width).
   29.22 + * The caller (the prep controller) is responsible for vertical padding.
   29.23 + *
   29.24 + * The downsampler may request "context rows" by setting need_context_rows
   29.25 + * during startup.  In this case, the input arrays will contain at least
   29.26 + * one row group's worth of pixels above and below the passed-in data;
   29.27 + * the caller will create dummy rows at image top and bottom by replicating
   29.28 + * the first or last real pixel row.
   29.29 + *
   29.30 + * An excellent reference for image resampling is
   29.31 + *   Digital Image Warping, George Wolberg, 1990.
   29.32 + *   Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7.
   29.33 + *
   29.34 + * The downsampling algorithm used here is a simple average of the source
   29.35 + * pixels covered by the output pixel.  The hi-falutin sampling literature
   29.36 + * refers to this as a "box filter".  In general the characteristics of a box
   29.37 + * filter are not very good, but for the specific cases we normally use (1:1
   29.38 + * and 2:1 ratios) the box is equivalent to a "triangle filter" which is not
   29.39 + * nearly so bad.  If you intend to use other sampling ratios, you'd be well
   29.40 + * advised to improve this code.
   29.41 + *
   29.42 + * A simple input-smoothing capability is provided.  This is mainly intended
   29.43 + * for cleaning up color-dithered GIF input files (if you find it inadequate,
   29.44 + * we suggest using an external filtering program such as pnmconvol).  When
   29.45 + * enabled, each input pixel P is replaced by a weighted sum of itself and its
   29.46 + * eight neighbors.  P's weight is 1-8*SF and each neighbor's weight is SF,
   29.47 + * where SF = (smoothing_factor / 1024).
   29.48 + * Currently, smoothing is only supported for 2h2v sampling factors.
   29.49 + */
   29.50 +
   29.51 +#define JPEG_INTERNALS
   29.52 +#include "jinclude.h"
   29.53 +#include "jpeglib.h"
   29.54 +
   29.55 +
   29.56 +/* Pointer to routine to downsample a single component */
   29.57 +typedef JMETHOD(void, downsample1_ptr,
   29.58 +		(j_compress_ptr cinfo, jpeg_component_info * compptr,
   29.59 +		 JSAMPARRAY input_data, JSAMPARRAY output_data));
   29.60 +
   29.61 +/* Private subobject */
   29.62 +
   29.63 +typedef struct {
   29.64 +  struct jpeg_downsampler pub;	/* public fields */
   29.65 +
   29.66 +  /* Downsampling method pointers, one per component */
   29.67 +  downsample1_ptr methods[MAX_COMPONENTS];
   29.68 +} my_downsampler;
   29.69 +
   29.70 +typedef my_downsampler * my_downsample_ptr;
   29.71 +
   29.72 +
   29.73 +/*
   29.74 + * Initialize for a downsampling pass.
   29.75 + */
   29.76 +
   29.77 +METHODDEF(void)
   29.78 +start_pass_downsample (j_compress_ptr cinfo)
   29.79 +{
   29.80 +  /* no work for now */
   29.81 +}
   29.82 +
   29.83 +
   29.84 +/*
   29.85 + * Expand a component horizontally from width input_cols to width output_cols,
   29.86 + * by duplicating the rightmost samples.
   29.87 + */
   29.88 +
   29.89 +LOCAL(void)
   29.90 +expand_right_edge (JSAMPARRAY image_data, int num_rows,
   29.91 +		   JDIMENSION input_cols, JDIMENSION output_cols)
   29.92 +{
   29.93 +  register JSAMPROW ptr;
   29.94 +  register JSAMPLE pixval;
   29.95 +  register int count;
   29.96 +  int row;
   29.97 +  int numcols = (int) (output_cols - input_cols);
   29.98 +
   29.99 +  if (numcols > 0) {
  29.100 +    for (row = 0; row < num_rows; row++) {
  29.101 +      ptr = image_data[row] + input_cols;
  29.102 +      pixval = ptr[-1];		/* don't need GETJSAMPLE() here */
  29.103 +      for (count = numcols; count > 0; count--)
  29.104 +	*ptr++ = pixval;
  29.105 +    }
  29.106 +  }
  29.107 +}
  29.108 +
  29.109 +
  29.110 +/*
  29.111 + * Do downsampling for a whole row group (all components).
  29.112 + *
  29.113 + * In this version we simply downsample each component independently.
  29.114 + */
  29.115 +
  29.116 +METHODDEF(void)
  29.117 +sep_downsample (j_compress_ptr cinfo,
  29.118 +		JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  29.119 +		JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  29.120 +{
  29.121 +  my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  29.122 +  int ci;
  29.123 +  jpeg_component_info * compptr;
  29.124 +  JSAMPARRAY in_ptr, out_ptr;
  29.125 +
  29.126 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  29.127 +       ci++, compptr++) {
  29.128 +    in_ptr = input_buf[ci] + in_row_index;
  29.129 +    out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  29.130 +    (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  29.131 +  }
  29.132 +}
  29.133 +
  29.134 +
  29.135 +/*
  29.136 + * Downsample pixel values of a single component.
  29.137 + * One row group is processed per call.
  29.138 + * This version handles arbitrary integral sampling ratios, without smoothing.
  29.139 + * Note that this version is not actually used for customary sampling ratios.
  29.140 + */
  29.141 +
  29.142 +METHODDEF(void)
  29.143 +int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  29.144 +		JSAMPARRAY input_data, JSAMPARRAY output_data)
  29.145 +{
  29.146 +  int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  29.147 +  JDIMENSION outcol, outcol_h;	/* outcol_h == outcol*h_expand */
  29.148 +  JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  29.149 +  JSAMPROW inptr, outptr;
  29.150 +  INT32 outvalue;
  29.151 +
  29.152 +  h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  29.153 +  v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  29.154 +  numpix = h_expand * v_expand;
  29.155 +  numpix2 = numpix/2;
  29.156 +
  29.157 +  /* Expand input data enough to let all the output samples be generated
  29.158 +   * by the standard loop.  Special-casing padded output would be more
  29.159 +   * efficient.
  29.160 +   */
  29.161 +  expand_right_edge(input_data, cinfo->max_v_samp_factor,
  29.162 +		    cinfo->image_width, output_cols * h_expand);
  29.163 +
  29.164 +  inrow = 0;
  29.165 +  for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  29.166 +    outptr = output_data[outrow];
  29.167 +    for (outcol = 0, outcol_h = 0; outcol < output_cols;
  29.168 +	 outcol++, outcol_h += h_expand) {
  29.169 +      outvalue = 0;
  29.170 +      for (v = 0; v < v_expand; v++) {
  29.171 +	inptr = input_data[inrow+v] + outcol_h;
  29.172 +	for (h = 0; h < h_expand; h++) {
  29.173 +	  outvalue += (INT32) GETJSAMPLE(*inptr++);
  29.174 +	}
  29.175 +      }
  29.176 +      *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  29.177 +    }
  29.178 +    inrow += v_expand;
  29.179 +  }
  29.180 +}
  29.181 +
  29.182 +
  29.183 +/*
  29.184 + * Downsample pixel values of a single component.
  29.185 + * This version handles the special case of a full-size component,
  29.186 + * without smoothing.
  29.187 + */
  29.188 +
  29.189 +METHODDEF(void)
  29.190 +fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  29.191 +		     JSAMPARRAY input_data, JSAMPARRAY output_data)
  29.192 +{
  29.193 +  /* Copy the data */
  29.194 +  jcopy_sample_rows(input_data, 0, output_data, 0,
  29.195 +		    cinfo->max_v_samp_factor, cinfo->image_width);
  29.196 +  /* Edge-expand */
  29.197 +  expand_right_edge(output_data, cinfo->max_v_samp_factor,
  29.198 +		    cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  29.199 +}
  29.200 +
  29.201 +
  29.202 +/*
  29.203 + * Downsample pixel values of a single component.
  29.204 + * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  29.205 + * without smoothing.
  29.206 + *
  29.207 + * A note about the "bias" calculations: when rounding fractional values to
  29.208 + * integer, we do not want to always round 0.5 up to the next integer.
  29.209 + * If we did that, we'd introduce a noticeable bias towards larger values.
  29.210 + * Instead, this code is arranged so that 0.5 will be rounded up or down at
  29.211 + * alternate pixel locations (a simple ordered dither pattern).
  29.212 + */
  29.213 +
  29.214 +METHODDEF(void)
  29.215 +h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  29.216 +		 JSAMPARRAY input_data, JSAMPARRAY output_data)
  29.217 +{
  29.218 +  int outrow;
  29.219 +  JDIMENSION outcol;
  29.220 +  JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  29.221 +  register JSAMPROW inptr, outptr;
  29.222 +  register int bias;
  29.223 +
  29.224 +  /* Expand input data enough to let all the output samples be generated
  29.225 +   * by the standard loop.  Special-casing padded output would be more
  29.226 +   * efficient.
  29.227 +   */
  29.228 +  expand_right_edge(input_data, cinfo->max_v_samp_factor,
  29.229 +		    cinfo->image_width, output_cols * 2);
  29.230 +
  29.231 +  for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  29.232 +    outptr = output_data[outrow];
  29.233 +    inptr = input_data[outrow];
  29.234 +    bias = 0;			/* bias = 0,1,0,1,... for successive samples */
  29.235 +    for (outcol = 0; outcol < output_cols; outcol++) {
  29.236 +      *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  29.237 +			      + bias) >> 1);
  29.238 +      bias ^= 1;		/* 0=>1, 1=>0 */
  29.239 +      inptr += 2;
  29.240 +    }
  29.241 +  }
  29.242 +}
  29.243 +
  29.244 +
  29.245 +/*
  29.246 + * Downsample pixel values of a single component.
  29.247 + * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  29.248 + * without smoothing.
  29.249 + */
  29.250 +
  29.251 +METHODDEF(void)
  29.252 +h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  29.253 +		 JSAMPARRAY input_data, JSAMPARRAY output_data)
  29.254 +{
  29.255 +  int inrow, outrow;
  29.256 +  JDIMENSION outcol;
  29.257 +  JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  29.258 +  register JSAMPROW inptr0, inptr1, outptr;
  29.259 +  register int bias;
  29.260 +
  29.261 +  /* Expand input data enough to let all the output samples be generated
  29.262 +   * by the standard loop.  Special-casing padded output would be more
  29.263 +   * efficient.
  29.264 +   */
  29.265 +  expand_right_edge(input_data, cinfo->max_v_samp_factor,
  29.266 +		    cinfo->image_width, output_cols * 2);
  29.267 +
  29.268 +  inrow = 0;
  29.269 +  for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  29.270 +    outptr = output_data[outrow];
  29.271 +    inptr0 = input_data[inrow];
  29.272 +    inptr1 = input_data[inrow+1];
  29.273 +    bias = 1;			/* bias = 1,2,1,2,... for successive samples */
  29.274 +    for (outcol = 0; outcol < output_cols; outcol++) {
  29.275 +      *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  29.276 +			      GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  29.277 +			      + bias) >> 2);
  29.278 +      bias ^= 3;		/* 1=>2, 2=>1 */
  29.279 +      inptr0 += 2; inptr1 += 2;
  29.280 +    }
  29.281 +    inrow += 2;
  29.282 +  }
  29.283 +}
  29.284 +
  29.285 +
  29.286 +#ifdef INPUT_SMOOTHING_SUPPORTED
  29.287 +
  29.288 +/*
  29.289 + * Downsample pixel values of a single component.
  29.290 + * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  29.291 + * with smoothing.  One row of context is required.
  29.292 + */
  29.293 +
  29.294 +METHODDEF(void)
  29.295 +h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  29.296 +			JSAMPARRAY input_data, JSAMPARRAY output_data)
  29.297 +{
  29.298 +  int inrow, outrow;
  29.299 +  JDIMENSION colctr;
  29.300 +  JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  29.301 +  register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  29.302 +  INT32 membersum, neighsum, memberscale, neighscale;
  29.303 +
  29.304 +  /* Expand input data enough to let all the output samples be generated
  29.305 +   * by the standard loop.  Special-casing padded output would be more
  29.306 +   * efficient.
  29.307 +   */
  29.308 +  expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  29.309 +		    cinfo->image_width, output_cols * 2);
  29.310 +
  29.311 +  /* We don't bother to form the individual "smoothed" input pixel values;
  29.312 +   * we can directly compute the output which is the average of the four
  29.313 +   * smoothed values.  Each of the four member pixels contributes a fraction
  29.314 +   * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  29.315 +   * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  29.316 +   * output.  The four corner-adjacent neighbor pixels contribute a fraction
  29.317 +   * SF to just one smoothed pixel, or SF/4 to the final output; while the
  29.318 +   * eight edge-adjacent neighbors contribute SF to each of two smoothed
  29.319 +   * pixels, or SF/2 overall.  In order to use integer arithmetic, these
  29.320 +   * factors are scaled by 2^16 = 65536.
  29.321 +   * Also recall that SF = smoothing_factor / 1024.
  29.322 +   */
  29.323 +
  29.324 +  memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  29.325 +  neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  29.326 +
  29.327 +  inrow = 0;
  29.328 +  for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  29.329 +    outptr = output_data[outrow];
  29.330 +    inptr0 = input_data[inrow];
  29.331 +    inptr1 = input_data[inrow+1];
  29.332 +    above_ptr = input_data[inrow-1];
  29.333 +    below_ptr = input_data[inrow+2];
  29.334 +
  29.335 +    /* Special case for first column: pretend column -1 is same as column 0 */
  29.336 +    membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  29.337 +		GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  29.338 +    neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  29.339 +	       GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  29.340 +	       GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  29.341 +	       GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  29.342 +    neighsum += neighsum;
  29.343 +    neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  29.344 +		GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  29.345 +    membersum = membersum * memberscale + neighsum * neighscale;
  29.346 +    *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  29.347 +    inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  29.348 +
  29.349 +    for (colctr = output_cols - 2; colctr > 0; colctr--) {
  29.350 +      /* sum of pixels directly mapped to this output element */
  29.351 +      membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  29.352 +		  GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  29.353 +      /* sum of edge-neighbor pixels */
  29.354 +      neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  29.355 +		 GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  29.356 +		 GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  29.357 +		 GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  29.358 +      /* The edge-neighbors count twice as much as corner-neighbors */
  29.359 +      neighsum += neighsum;
  29.360 +      /* Add in the corner-neighbors */
  29.361 +      neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  29.362 +		  GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  29.363 +      /* form final output scaled up by 2^16 */
  29.364 +      membersum = membersum * memberscale + neighsum * neighscale;
  29.365 +      /* round, descale and output it */
  29.366 +      *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  29.367 +      inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  29.368 +    }
  29.369 +
  29.370 +    /* Special case for last column */
  29.371 +    membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  29.372 +		GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  29.373 +    neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  29.374 +	       GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  29.375 +	       GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  29.376 +	       GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  29.377 +    neighsum += neighsum;
  29.378 +    neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  29.379 +		GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  29.380 +    membersum = membersum * memberscale + neighsum * neighscale;
  29.381 +    *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  29.382 +
  29.383 +    inrow += 2;
  29.384 +  }
  29.385 +}
  29.386 +
  29.387 +
  29.388 +/*
  29.389 + * Downsample pixel values of a single component.
  29.390 + * This version handles the special case of a full-size component,
  29.391 + * with smoothing.  One row of context is required.
  29.392 + */
  29.393 +
  29.394 +METHODDEF(void)
  29.395 +fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  29.396 +			    JSAMPARRAY input_data, JSAMPARRAY output_data)
  29.397 +{
  29.398 +  int outrow;
  29.399 +  JDIMENSION colctr;
  29.400 +  JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  29.401 +  register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  29.402 +  INT32 membersum, neighsum, memberscale, neighscale;
  29.403 +  int colsum, lastcolsum, nextcolsum;
  29.404 +
  29.405 +  /* Expand input data enough to let all the output samples be generated
  29.406 +   * by the standard loop.  Special-casing padded output would be more
  29.407 +   * efficient.
  29.408 +   */
  29.409 +  expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  29.410 +		    cinfo->image_width, output_cols);
  29.411 +
  29.412 +  /* Each of the eight neighbor pixels contributes a fraction SF to the
  29.413 +   * smoothed pixel, while the main pixel contributes (1-8*SF).  In order
  29.414 +   * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  29.415 +   * Also recall that SF = smoothing_factor / 1024.
  29.416 +   */
  29.417 +
  29.418 +  memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  29.419 +  neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  29.420 +
  29.421 +  for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  29.422 +    outptr = output_data[outrow];
  29.423 +    inptr = input_data[outrow];
  29.424 +    above_ptr = input_data[outrow-1];
  29.425 +    below_ptr = input_data[outrow+1];
  29.426 +
  29.427 +    /* Special case for first column */
  29.428 +    colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  29.429 +	     GETJSAMPLE(*inptr);
  29.430 +    membersum = GETJSAMPLE(*inptr++);
  29.431 +    nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  29.432 +		 GETJSAMPLE(*inptr);
  29.433 +    neighsum = colsum + (colsum - membersum) + nextcolsum;
  29.434 +    membersum = membersum * memberscale + neighsum * neighscale;
  29.435 +    *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  29.436 +    lastcolsum = colsum; colsum = nextcolsum;
  29.437 +
  29.438 +    for (colctr = output_cols - 2; colctr > 0; colctr--) {
  29.439 +      membersum = GETJSAMPLE(*inptr++);
  29.440 +      above_ptr++; below_ptr++;
  29.441 +      nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  29.442 +		   GETJSAMPLE(*inptr);
  29.443 +      neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  29.444 +      membersum = membersum * memberscale + neighsum * neighscale;
  29.445 +      *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  29.446 +      lastcolsum = colsum; colsum = nextcolsum;
  29.447 +    }
  29.448 +
  29.449 +    /* Special case for last column */
  29.450 +    membersum = GETJSAMPLE(*inptr);
  29.451 +    neighsum = lastcolsum + (colsum - membersum) + colsum;
  29.452 +    membersum = membersum * memberscale + neighsum * neighscale;
  29.453 +    *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  29.454 +
  29.455 +  }
  29.456 +}
  29.457 +
  29.458 +#endif /* INPUT_SMOOTHING_SUPPORTED */
  29.459 +
  29.460 +
  29.461 +/*
  29.462 + * Module initialization routine for downsampling.
  29.463 + * Note that we must select a routine for each component.
  29.464 + */
  29.465 +
  29.466 +GLOBAL(void)
  29.467 +jinit_downsampler (j_compress_ptr cinfo)
  29.468 +{
  29.469 +  my_downsample_ptr downsample;
  29.470 +  int ci;
  29.471 +  jpeg_component_info * compptr;
  29.472 +  boolean smoothok = TRUE;
  29.473 +
  29.474 +  downsample = (my_downsample_ptr)
  29.475 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  29.476 +				SIZEOF(my_downsampler));
  29.477 +  cinfo->downsample = (struct jpeg_downsampler *) downsample;
  29.478 +  downsample->pub.start_pass = start_pass_downsample;
  29.479 +  downsample->pub.downsample = sep_downsample;
  29.480 +  downsample->pub.need_context_rows = FALSE;
  29.481 +
  29.482 +  if (cinfo->CCIR601_sampling)
  29.483 +    ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  29.484 +
  29.485 +  /* Verify we can handle the sampling factors, and set up method pointers */
  29.486 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  29.487 +       ci++, compptr++) {
  29.488 +    if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  29.489 +	compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  29.490 +#ifdef INPUT_SMOOTHING_SUPPORTED
  29.491 +      if (cinfo->smoothing_factor) {
  29.492 +	downsample->methods[ci] = fullsize_smooth_downsample;
  29.493 +	downsample->pub.need_context_rows = TRUE;
  29.494 +      } else
  29.495 +#endif
  29.496 +	downsample->methods[ci] = fullsize_downsample;
  29.497 +    } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  29.498 +	       compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  29.499 +      smoothok = FALSE;
  29.500 +      downsample->methods[ci] = h2v1_downsample;
  29.501 +    } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  29.502 +	       compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  29.503 +#ifdef INPUT_SMOOTHING_SUPPORTED
  29.504 +      if (cinfo->smoothing_factor) {
  29.505 +	downsample->methods[ci] = h2v2_smooth_downsample;
  29.506 +	downsample->pub.need_context_rows = TRUE;
  29.507 +      } else
  29.508 +#endif
  29.509 +	downsample->methods[ci] = h2v2_downsample;
  29.510 +    } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  29.511 +	       (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  29.512 +      smoothok = FALSE;
  29.513 +      downsample->methods[ci] = int_downsample;
  29.514 +    } else
  29.515 +      ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  29.516 +  }
  29.517 +
  29.518 +#ifdef INPUT_SMOOTHING_SUPPORTED
  29.519 +  if (cinfo->smoothing_factor && !smoothok)
  29.520 +    TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  29.521 +#endif
  29.522 +}
    30.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    30.2 +++ b/libs/libjpeg/jctrans.c	Thu Sep 08 06:28:38 2011 +0300
    30.3 @@ -0,0 +1,388 @@
    30.4 +/*
    30.5 + * jctrans.c
    30.6 + *
    30.7 + * Copyright (C) 1995-1998, Thomas G. Lane.
    30.8 + * This file is part of the Independent JPEG Group's software.
    30.9 + * For conditions of distribution and use, see the accompanying README file.
   30.10 + *
   30.11 + * This file contains library routines for transcoding compression,
   30.12 + * that is, writing raw DCT coefficient arrays to an output JPEG file.
   30.13 + * The routines in jcapimin.c will also be needed by a transcoder.
   30.14 + */
   30.15 +
   30.16 +#define JPEG_INTERNALS
   30.17 +#include "jinclude.h"
   30.18 +#include "jpeglib.h"
   30.19 +
   30.20 +
   30.21 +/* Forward declarations */
   30.22 +LOCAL(void) transencode_master_selection
   30.23 +	JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
   30.24 +LOCAL(void) transencode_coef_controller
   30.25 +	JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
   30.26 +
   30.27 +
   30.28 +/*
   30.29 + * Compression initialization for writing raw-coefficient data.
   30.30 + * Before calling this, all parameters and a data destination must be set up.
   30.31 + * Call jpeg_finish_compress() to actually write the data.
   30.32 + *
   30.33 + * The number of passed virtual arrays must match cinfo->num_components.
   30.34 + * Note that the virtual arrays need not be filled or even realized at
   30.35 + * the time write_coefficients is called; indeed, if the virtual arrays
   30.36 + * were requested from this compression object's memory manager, they
   30.37 + * typically will be realized during this routine and filled afterwards.
   30.38 + */
   30.39 +
   30.40 +GLOBAL(void)
   30.41 +jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
   30.42 +{
   30.43 +  if (cinfo->global_state != CSTATE_START)
   30.44 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
   30.45 +  /* Mark all tables to be written */
   30.46 +  jpeg_suppress_tables(cinfo, FALSE);
   30.47 +  /* (Re)initialize error mgr and destination modules */
   30.48 +  (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
   30.49 +  (*cinfo->dest->init_destination) (cinfo);
   30.50 +  /* Perform master selection of active modules */
   30.51 +  transencode_master_selection(cinfo, coef_arrays);
   30.52 +  /* Wait for jpeg_finish_compress() call */
   30.53 +  cinfo->next_scanline = 0;	/* so jpeg_write_marker works */
   30.54 +  cinfo->global_state = CSTATE_WRCOEFS;
   30.55 +}
   30.56 +
   30.57 +
   30.58 +/*
   30.59 + * Initialize the compression object with default parameters,
   30.60 + * then copy from the source object all parameters needed for lossless
   30.61 + * transcoding.  Parameters that can be varied without loss (such as
   30.62 + * scan script and Huffman optimization) are left in their default states.
   30.63 + */
   30.64 +
   30.65 +GLOBAL(void)
   30.66 +jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
   30.67 +			       j_compress_ptr dstinfo)
   30.68 +{
   30.69 +  JQUANT_TBL ** qtblptr;
   30.70 +  jpeg_component_info *incomp, *outcomp;
   30.71 +  JQUANT_TBL *c_quant, *slot_quant;
   30.72 +  int tblno, ci, coefi;
   30.73 +
   30.74 +  /* Safety check to ensure start_compress not called yet. */
   30.75 +  if (dstinfo->global_state != CSTATE_START)
   30.76 +    ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
   30.77 +  /* Copy fundamental image dimensions */
   30.78 +  dstinfo->image_width = srcinfo->image_width;
   30.79 +  dstinfo->image_height = srcinfo->image_height;
   30.80 +  dstinfo->input_components = srcinfo->num_components;
   30.81 +  dstinfo->in_color_space = srcinfo->jpeg_color_space;
   30.82 +  /* Initialize all parameters to default values */
   30.83 +  jpeg_set_defaults(dstinfo);
   30.84 +  /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
   30.85 +   * Fix it to get the right header markers for the image colorspace.
   30.86 +   */
   30.87 +  jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
   30.88 +  dstinfo->data_precision = srcinfo->data_precision;
   30.89 +  dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
   30.90 +  /* Copy the source's quantization tables. */
   30.91 +  for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
   30.92 +    if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
   30.93 +      qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
   30.94 +      if (*qtblptr == NULL)
   30.95 +	*qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
   30.96 +      MEMCOPY((*qtblptr)->quantval,
   30.97 +	      srcinfo->quant_tbl_ptrs[tblno]->quantval,
   30.98 +	      SIZEOF((*qtblptr)->quantval));
   30.99 +      (*qtblptr)->sent_table = FALSE;
  30.100 +    }
  30.101 +  }
  30.102 +  /* Copy the source's per-component info.
  30.103 +   * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  30.104 +   */
  30.105 +  dstinfo->num_components = srcinfo->num_components;
  30.106 +  if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  30.107 +    ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  30.108 +	     MAX_COMPONENTS);
  30.109 +  for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  30.110 +       ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  30.111 +    outcomp->component_id = incomp->component_id;
  30.112 +    outcomp->h_samp_factor = incomp->h_samp_factor;
  30.113 +    outcomp->v_samp_factor = incomp->v_samp_factor;
  30.114 +    outcomp->quant_tbl_no = incomp->quant_tbl_no;
  30.115 +    /* Make sure saved quantization table for component matches the qtable
  30.116 +     * slot.  If not, the input file re-used this qtable slot.
  30.117 +     * IJG encoder currently cannot duplicate this.
  30.118 +     */
  30.119 +    tblno = outcomp->quant_tbl_no;
  30.120 +    if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  30.121 +	srcinfo->quant_tbl_ptrs[tblno] == NULL)
  30.122 +      ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  30.123 +    slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  30.124 +    c_quant = incomp->quant_table;
  30.125 +    if (c_quant != NULL) {
  30.126 +      for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  30.127 +	if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  30.128 +	  ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  30.129 +      }
  30.130 +    }
  30.131 +    /* Note: we do not copy the source's Huffman table assignments;
  30.132 +     * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  30.133 +     */
  30.134 +  }
  30.135 +  /* Also copy JFIF version and resolution information, if available.
  30.136 +   * Strictly speaking this isn't "critical" info, but it's nearly
  30.137 +   * always appropriate to copy it if available.  In particular,
  30.138 +   * if the application chooses to copy JFIF 1.02 extension markers from
  30.139 +   * the source file, we need to copy the version to make sure we don't
  30.140 +   * emit a file that has 1.02 extensions but a claimed version of 1.01.
  30.141 +   * We will *not*, however, copy version info from mislabeled "2.01" files.
  30.142 +   */
  30.143 +  if (srcinfo->saw_JFIF_marker) {
  30.144 +    if (srcinfo->JFIF_major_version == 1) {
  30.145 +      dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  30.146 +      dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  30.147 +    }
  30.148 +    dstinfo->density_unit = srcinfo->density_unit;
  30.149 +    dstinfo->X_density = srcinfo->X_density;
  30.150 +    dstinfo->Y_density = srcinfo->Y_density;
  30.151 +  }
  30.152 +}
  30.153 +
  30.154 +
  30.155 +/*
  30.156 + * Master selection of compression modules for transcoding.
  30.157 + * This substitutes for jcinit.c's initialization of the full compressor.
  30.158 + */
  30.159 +
  30.160 +LOCAL(void)
  30.161 +transencode_master_selection (j_compress_ptr cinfo,
  30.162 +			      jvirt_barray_ptr * coef_arrays)
  30.163 +{
  30.164 +  /* Although we don't actually use input_components for transcoding,
  30.165 +   * jcmaster.c's initial_setup will complain if input_components is 0.
  30.166 +   */
  30.167 +  cinfo->input_components = 1;
  30.168 +  /* Initialize master control (includes parameter checking/processing) */
  30.169 +  jinit_c_master_control(cinfo, TRUE /* transcode only */);
  30.170 +
  30.171 +  /* Entropy encoding: either Huffman or arithmetic coding. */
  30.172 +  if (cinfo->arith_code) {
  30.173 +    ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  30.174 +  } else {
  30.175 +    if (cinfo->progressive_mode) {
  30.176 +#ifdef C_PROGRESSIVE_SUPPORTED
  30.177 +      jinit_phuff_encoder(cinfo);
  30.178 +#else
  30.179 +      ERREXIT(cinfo, JERR_NOT_COMPILED);
  30.180 +#endif
  30.181 +    } else
  30.182 +      jinit_huff_encoder(cinfo);
  30.183 +  }
  30.184 +
  30.185 +  /* We need a special coefficient buffer controller. */
  30.186 +  transencode_coef_controller(cinfo, coef_arrays);
  30.187 +
  30.188 +  jinit_marker_writer(cinfo);
  30.189 +
  30.190 +  /* We can now tell the memory manager to allocate virtual arrays. */
  30.191 +  (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  30.192 +
  30.193 +  /* Write the datastream header (SOI, JFIF) immediately.
  30.194 +   * Frame and scan headers are postponed till later.
  30.195 +   * This lets application insert special markers after the SOI.
  30.196 +   */
  30.197 +  (*cinfo->marker->write_file_header) (cinfo);
  30.198 +}
  30.199 +
  30.200 +
  30.201 +/*
  30.202 + * The rest of this file is a special implementation of the coefficient
  30.203 + * buffer controller.  This is similar to jccoefct.c, but it handles only
  30.204 + * output from presupplied virtual arrays.  Furthermore, we generate any
  30.205 + * dummy padding blocks on-the-fly rather than expecting them to be present
  30.206 + * in the arrays.
  30.207 + */
  30.208 +
  30.209 +/* Private buffer controller object */
  30.210 +
  30.211 +typedef struct {
  30.212 +  struct jpeg_c_coef_controller pub; /* public fields */
  30.213 +
  30.214 +  JDIMENSION iMCU_row_num;	/* iMCU row # within image */
  30.215 +  JDIMENSION mcu_ctr;		/* counts MCUs processed in current row */
  30.216 +  int MCU_vert_offset;		/* counts MCU rows within iMCU row */
  30.217 +  int MCU_rows_per_iMCU_row;	/* number of such rows needed */
  30.218 +
  30.219 +  /* Virtual block array for each component. */
  30.220 +  jvirt_barray_ptr * whole_image;
  30.221 +
  30.222 +  /* Workspace for constructing dummy blocks at right/bottom edges. */
  30.223 +  JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  30.224 +} my_coef_controller;
  30.225 +
  30.226 +typedef my_coef_controller * my_coef_ptr;
  30.227 +
  30.228 +
  30.229 +LOCAL(void)
  30.230 +start_iMCU_row (j_compress_ptr cinfo)
  30.231 +/* Reset within-iMCU-row counters for a new row */
  30.232 +{
  30.233 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  30.234 +
  30.235 +  /* In an interleaved scan, an MCU row is the same as an iMCU row.
  30.236 +   * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  30.237 +   * But at the bottom of the image, process only what's left.
  30.238 +   */
  30.239 +  if (cinfo->comps_in_scan > 1) {
  30.240 +    coef->MCU_rows_per_iMCU_row = 1;
  30.241 +  } else {
  30.242 +    if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  30.243 +      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  30.244 +    else
  30.245 +      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  30.246 +  }
  30.247 +
  30.248 +  coef->mcu_ctr = 0;
  30.249 +  coef->MCU_vert_offset = 0;
  30.250 +}
  30.251 +
  30.252 +
  30.253 +/*
  30.254 + * Initialize for a processing pass.
  30.255 + */
  30.256 +
  30.257 +METHODDEF(void)
  30.258 +start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  30.259 +{
  30.260 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  30.261 +
  30.262 +  if (pass_mode != JBUF_CRANK_DEST)
  30.263 +    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  30.264 +
  30.265 +  coef->iMCU_row_num = 0;
  30.266 +  start_iMCU_row(cinfo);
  30.267 +}
  30.268 +
  30.269 +
  30.270 +/*
  30.271 + * Process some data.
  30.272 + * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  30.273 + * per call, ie, v_samp_factor block rows for each component in the scan.
  30.274 + * The data is obtained from the virtual arrays and fed to the entropy coder.
  30.275 + * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  30.276 + *
  30.277 + * NB: input_buf is ignored; it is likely to be a NULL pointer.
  30.278 + */
  30.279 +
  30.280 +METHODDEF(boolean)
  30.281 +compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  30.282 +{
  30.283 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  30.284 +  JDIMENSION MCU_col_num;	/* index of current MCU within row */
  30.285 +  JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  30.286 +  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  30.287 +  int blkn, ci, xindex, yindex, yoffset, blockcnt;
  30.288 +  JDIMENSION start_col;
  30.289 +  JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  30.290 +  JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  30.291 +  JBLOCKROW buffer_ptr;
  30.292 +  jpeg_component_info *compptr;
  30.293 +
  30.294 +  /* Align the virtual buffers for the components used in this scan. */
  30.295 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  30.296 +    compptr = cinfo->cur_comp_info[ci];
  30.297 +    buffer[ci] = (*cinfo->mem->access_virt_barray)
  30.298 +      ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  30.299 +       coef->iMCU_row_num * compptr->v_samp_factor,
  30.300 +       (JDIMENSION) compptr->v_samp_factor, FALSE);
  30.301 +  }
  30.302 +
  30.303 +  /* Loop to process one whole iMCU row */
  30.304 +  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  30.305 +       yoffset++) {
  30.306 +    for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  30.307 +	 MCU_col_num++) {
  30.308 +      /* Construct list of pointers to DCT blocks belonging to this MCU */
  30.309 +      blkn = 0;			/* index of current DCT block within MCU */
  30.310 +      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  30.311 +	compptr = cinfo->cur_comp_info[ci];
  30.312 +	start_col = MCU_col_num * compptr->MCU_width;
  30.313 +	blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  30.314 +						: compptr->last_col_width;
  30.315 +	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  30.316 +	  if (coef->iMCU_row_num < last_iMCU_row ||
  30.317 +	      yindex+yoffset < compptr->last_row_height) {
  30.318 +	    /* Fill in pointers to real blocks in this row */
  30.319 +	    buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  30.320 +	    for (xindex = 0; xindex < blockcnt; xindex++)
  30.321 +	      MCU_buffer[blkn++] = buffer_ptr++;
  30.322 +	  } else {
  30.323 +	    /* At bottom of image, need a whole row of dummy blocks */
  30.324 +	    xindex = 0;
  30.325 +	  }
  30.326 +	  /* Fill in any dummy blocks needed in this row.
  30.327 +	   * Dummy blocks are filled in the same way as in jccoefct.c:
  30.328 +	   * all zeroes in the AC entries, DC entries equal to previous
  30.329 +	   * block's DC value.  The init routine has already zeroed the
  30.330 +	   * AC entries, so we need only set the DC entries correctly.
  30.331 +	   */
  30.332 +	  for (; xindex < compptr->MCU_width; xindex++) {
  30.333 +	    MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  30.334 +	    MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  30.335 +	    blkn++;
  30.336 +	  }
  30.337 +	}
  30.338 +      }
  30.339 +      /* Try to write the MCU. */
  30.340 +      if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  30.341 +	/* Suspension forced; update state counters and exit */
  30.342 +	coef->MCU_vert_offset = yoffset;
  30.343 +	coef->mcu_ctr = MCU_col_num;
  30.344 +	return FALSE;
  30.345 +      }
  30.346 +    }
  30.347 +    /* Completed an MCU row, but perhaps not an iMCU row */
  30.348 +    coef->mcu_ctr = 0;
  30.349 +  }
  30.350 +  /* Completed the iMCU row, advance counters for next one */
  30.351 +  coef->iMCU_row_num++;
  30.352 +  start_iMCU_row(cinfo);
  30.353 +  return TRUE;
  30.354 +}
  30.355 +
  30.356 +
  30.357 +/*
  30.358 + * Initialize coefficient buffer controller.
  30.359 + *
  30.360 + * Each passed coefficient array must be the right size for that
  30.361 + * coefficient: width_in_blocks wide and height_in_blocks high,
  30.362 + * with unitheight at least v_samp_factor.
  30.363 + */
  30.364 +
  30.365 +LOCAL(void)
  30.366 +transencode_coef_controller (j_compress_ptr cinfo,
  30.367 +			     jvirt_barray_ptr * coef_arrays)
  30.368 +{
  30.369 +  my_coef_ptr coef;
  30.370 +  JBLOCKROW buffer;
  30.371 +  int i;
  30.372 +
  30.373 +  coef = (my_coef_ptr)
  30.374 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  30.375 +				SIZEOF(my_coef_controller));
  30.376 +  cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  30.377 +  coef->pub.start_pass = start_pass_coef;
  30.378 +  coef->pub.compress_data = compress_output;
  30.379 +
  30.380 +  /* Save pointer to virtual arrays */
  30.381 +  coef->whole_image = coef_arrays;
  30.382 +
  30.383 +  /* Allocate and pre-zero space for dummy DCT blocks. */
  30.384 +  buffer = (JBLOCKROW)
  30.385 +    (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  30.386 +				C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  30.387 +  jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  30.388 +  for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  30.389 +    coef->dummy_buffer[i] = buffer + i;
  30.390 +  }
  30.391 +}
    31.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    31.2 +++ b/libs/libjpeg/jdapimin.c	Thu Sep 08 06:28:38 2011 +0300
    31.3 @@ -0,0 +1,395 @@
    31.4 +/*
    31.5 + * jdapimin.c
    31.6 + *
    31.7 + * Copyright (C) 1994-1998, Thomas G. Lane.
    31.8 + * This file is part of the Independent JPEG Group's software.
    31.9 + * For conditions of distribution and use, see the accompanying README file.
   31.10 + *
   31.11 + * This file contains application interface code for the decompression half
   31.12 + * of the JPEG library.  These are the "minimum" API routines that may be
   31.13 + * needed in either the normal full-decompression case or the
   31.14 + * transcoding-only case.
   31.15 + *
   31.16 + * Most of the routines intended to be called directly by an application
   31.17 + * are in this file or in jdapistd.c.  But also see jcomapi.c for routines
   31.18 + * shared by compression and decompression, and jdtrans.c for the transcoding
   31.19 + * case.
   31.20 + */
   31.21 +
   31.22 +#define JPEG_INTERNALS
   31.23 +#include "jinclude.h"
   31.24 +#include "jpeglib.h"
   31.25 +
   31.26 +
   31.27 +/*
   31.28 + * Initialization of a JPEG decompression object.
   31.29 + * The error manager must already be set up (in case memory manager fails).
   31.30 + */
   31.31 +
   31.32 +GLOBAL(void)
   31.33 +jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
   31.34 +{
   31.35 +  int i;
   31.36 +
   31.37 +  /* Guard against version mismatches between library and caller. */
   31.38 +  cinfo->mem = NULL;		/* so jpeg_destroy knows mem mgr not called */
   31.39 +  if (version != JPEG_LIB_VERSION)
   31.40 +    ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
   31.41 +  if (structsize != SIZEOF(struct jpeg_decompress_struct))
   31.42 +    ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE, 
   31.43 +	     (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
   31.44 +
   31.45 +  /* For debugging purposes, we zero the whole master structure.
   31.46 +   * But the application has already set the err pointer, and may have set
   31.47 +   * client_data, so we have to save and restore those fields.
   31.48 +   * Note: if application hasn't set client_data, tools like Purify may
   31.49 +   * complain here.
   31.50 +   */
   31.51 +  {
   31.52 +    struct jpeg_error_mgr * err = cinfo->err;
   31.53 +    void * client_data = cinfo->client_data; /* ignore Purify complaint here */
   31.54 +    MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
   31.55 +    cinfo->err = err;
   31.56 +    cinfo->client_data = client_data;
   31.57 +  }
   31.58 +  cinfo->is_decompressor = TRUE;
   31.59 +
   31.60 +  /* Initialize a memory manager instance for this object */
   31.61 +  jinit_memory_mgr((j_common_ptr) cinfo);
   31.62 +
   31.63 +  /* Zero out pointers to permanent structures. */
   31.64 +  cinfo->progress = NULL;
   31.65 +  cinfo->src = NULL;
   31.66 +
   31.67 +  for (i = 0; i < NUM_QUANT_TBLS; i++)
   31.68 +    cinfo->quant_tbl_ptrs[i] = NULL;
   31.69 +
   31.70 +  for (i = 0; i < NUM_HUFF_TBLS; i++) {
   31.71 +    cinfo->dc_huff_tbl_ptrs[i] = NULL;
   31.72 +    cinfo->ac_huff_tbl_ptrs[i] = NULL;
   31.73 +  }
   31.74 +
   31.75 +  /* Initialize marker processor so application can override methods
   31.76 +   * for COM, APPn markers before calling jpeg_read_header.
   31.77 +   */
   31.78 +  cinfo->marker_list = NULL;
   31.79 +  jinit_marker_reader(cinfo);
   31.80 +
   31.81 +  /* And initialize the overall input controller. */
   31.82 +  jinit_input_controller(cinfo);
   31.83 +
   31.84 +  /* OK, I'm ready */
   31.85 +  cinfo->global_state = DSTATE_START;
   31.86 +}
   31.87 +
   31.88 +
   31.89 +/*
   31.90 + * Destruction of a JPEG decompression object
   31.91 + */
   31.92 +
   31.93 +GLOBAL(void)
   31.94 +jpeg_destroy_decompress (j_decompress_ptr cinfo)
   31.95 +{
   31.96 +  jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
   31.97 +}
   31.98 +
   31.99 +
  31.100 +/*
  31.101 + * Abort processing of a JPEG decompression operation,
  31.102 + * but don't destroy the object itself.
  31.103 + */
  31.104 +
  31.105 +GLOBAL(void)
  31.106 +jpeg_abort_decompress (j_decompress_ptr cinfo)
  31.107 +{
  31.108 +  jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  31.109 +}
  31.110 +
  31.111 +
  31.112 +/*
  31.113 + * Set default decompression parameters.
  31.114 + */
  31.115 +
  31.116 +LOCAL(void)
  31.117 +default_decompress_parms (j_decompress_ptr cinfo)
  31.118 +{
  31.119 +  /* Guess the input colorspace, and set output colorspace accordingly. */
  31.120 +  /* (Wish JPEG committee had provided a real way to specify this...) */
  31.121 +  /* Note application may override our guesses. */
  31.122 +  switch (cinfo->num_components) {
  31.123 +  case 1:
  31.124 +    cinfo->jpeg_color_space = JCS_GRAYSCALE;
  31.125 +    cinfo->out_color_space = JCS_GRAYSCALE;
  31.126 +    break;
  31.127 +    
  31.128 +  case 3:
  31.129 +    if (cinfo->saw_JFIF_marker) {
  31.130 +      cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  31.131 +    } else if (cinfo->saw_Adobe_marker) {
  31.132 +      switch (cinfo->Adobe_transform) {
  31.133 +      case 0:
  31.134 +	cinfo->jpeg_color_space = JCS_RGB;
  31.135 +	break;
  31.136 +      case 1:
  31.137 +	cinfo->jpeg_color_space = JCS_YCbCr;
  31.138 +	break;
  31.139 +      default:
  31.140 +	WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  31.141 +	cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  31.142 +	break;
  31.143 +      }
  31.144 +    } else {
  31.145 +      /* Saw no special markers, try to guess from the component IDs */
  31.146 +      int cid0 = cinfo->comp_info[0].component_id;
  31.147 +      int cid1 = cinfo->comp_info[1].component_id;
  31.148 +      int cid2 = cinfo->comp_info[2].component_id;
  31.149 +
  31.150 +      if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  31.151 +	cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  31.152 +      else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  31.153 +	cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  31.154 +      else {
  31.155 +	TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  31.156 +	cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  31.157 +      }
  31.158 +    }
  31.159 +    /* Always guess RGB is proper output colorspace. */
  31.160 +    cinfo->out_color_space = JCS_RGB;
  31.161 +    break;
  31.162 +    
  31.163 +  case 4:
  31.164 +    if (cinfo->saw_Adobe_marker) {
  31.165 +      switch (cinfo->Adobe_transform) {
  31.166 +      case 0:
  31.167 +	cinfo->jpeg_color_space = JCS_CMYK;
  31.168 +	break;
  31.169 +      case 2:
  31.170 +	cinfo->jpeg_color_space = JCS_YCCK;
  31.171 +	break;
  31.172 +      default:
  31.173 +	WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  31.174 +	cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  31.175 +	break;
  31.176 +      }
  31.177 +    } else {
  31.178 +      /* No special markers, assume straight CMYK. */
  31.179 +      cinfo->jpeg_color_space = JCS_CMYK;
  31.180 +    }
  31.181 +    cinfo->out_color_space = JCS_CMYK;
  31.182 +    break;
  31.183 +    
  31.184 +  default:
  31.185 +    cinfo->jpeg_color_space = JCS_UNKNOWN;
  31.186 +    cinfo->out_color_space = JCS_UNKNOWN;
  31.187 +    break;
  31.188 +  }
  31.189 +
  31.190 +  /* Set defaults for other decompression parameters. */
  31.191 +  cinfo->scale_num = 1;		/* 1:1 scaling */
  31.192 +  cinfo->scale_denom = 1;
  31.193 +  cinfo->output_gamma = 1.0;
  31.194 +  cinfo->buffered_image = FALSE;
  31.195 +  cinfo->raw_data_out = FALSE;
  31.196 +  cinfo->dct_method = JDCT_DEFAULT;
  31.197 +  cinfo->do_fancy_upsampling = TRUE;
  31.198 +  cinfo->do_block_smoothing = TRUE;
  31.199 +  cinfo->quantize_colors = FALSE;
  31.200 +  /* We set these in case application only sets quantize_colors. */
  31.201 +  cinfo->dither_mode = JDITHER_FS;
  31.202 +#ifdef QUANT_2PASS_SUPPORTED
  31.203 +  cinfo->two_pass_quantize = TRUE;
  31.204 +#else
  31.205 +  cinfo->two_pass_quantize = FALSE;
  31.206 +#endif
  31.207 +  cinfo->desired_number_of_colors = 256;
  31.208 +  cinfo->colormap = NULL;
  31.209 +  /* Initialize for no mode change in buffered-image mode. */
  31.210 +  cinfo->enable_1pass_quant = FALSE;
  31.211 +  cinfo->enable_external_quant = FALSE;
  31.212 +  cinfo->enable_2pass_quant = FALSE;
  31.213 +}
  31.214 +
  31.215 +
  31.216 +/*
  31.217 + * Decompression startup: read start of JPEG datastream to see what's there.
  31.218 + * Need only initialize JPEG object and supply a data source before calling.
  31.219 + *
  31.220 + * This routine will read as far as the first SOS marker (ie, actual start of
  31.221 + * compressed data), and will save all tables and parameters in the JPEG
  31.222 + * object.  It will also initialize the decompression parameters to default
  31.223 + * values, and finally return JPEG_HEADER_OK.  On return, the application may
  31.224 + * adjust the decompression parameters and then call jpeg_start_decompress.
  31.225 + * (Or, if the application only wanted to determine the image parameters,
  31.226 + * the data need not be decompressed.  In that case, call jpeg_abort or
  31.227 + * jpeg_destroy to release any temporary space.)
  31.228 + * If an abbreviated (tables only) datastream is presented, the routine will
  31.229 + * return JPEG_HEADER_TABLES_ONLY upon reaching EOI.  The application may then
  31.230 + * re-use the JPEG object to read the abbreviated image datastream(s).
  31.231 + * It is unnecessary (but OK) to call jpeg_abort in this case.
  31.232 + * The JPEG_SUSPENDED return code only occurs if the data source module
  31.233 + * requests suspension of the decompressor.  In this case the application
  31.234 + * should load more source data and then re-call jpeg_read_header to resume
  31.235 + * processing.
  31.236 + * If a non-suspending data source is used and require_image is TRUE, then the
  31.237 + * return code need not be inspected since only JPEG_HEADER_OK is possible.
  31.238 + *
  31.239 + * This routine is now just a front end to jpeg_consume_input, with some
  31.240 + * extra error checking.
  31.241 + */
  31.242 +
  31.243 +GLOBAL(int)
  31.244 +jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  31.245 +{
  31.246 +  int retcode;
  31.247 +
  31.248 +  if (cinfo->global_state != DSTATE_START &&
  31.249 +      cinfo->global_state != DSTATE_INHEADER)
  31.250 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  31.251 +
  31.252 +  retcode = jpeg_consume_input(cinfo);
  31.253 +
  31.254 +  switch (retcode) {
  31.255 +  case JPEG_REACHED_SOS:
  31.256 +    retcode = JPEG_HEADER_OK;
  31.257 +    break;
  31.258 +  case JPEG_REACHED_EOI:
  31.259 +    if (require_image)		/* Complain if application wanted an image */
  31.260 +      ERREXIT(cinfo, JERR_NO_IMAGE);
  31.261 +    /* Reset to start state; it would be safer to require the application to
  31.262 +     * call jpeg_abort, but we can't change it now for compatibility reasons.
  31.263 +     * A side effect is to free any temporary memory (there shouldn't be any).
  31.264 +     */
  31.265 +    jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  31.266 +    retcode = JPEG_HEADER_TABLES_ONLY;
  31.267 +    break;
  31.268 +  case JPEG_SUSPENDED:
  31.269 +    /* no work */
  31.270 +    break;
  31.271 +  }
  31.272 +
  31.273 +  return retcode;
  31.274 +}
  31.275 +
  31.276 +
  31.277 +/*
  31.278 + * Consume data in advance of what the decompressor requires.
  31.279 + * This can be called at any time once the decompressor object has
  31.280 + * been created and a data source has been set up.
  31.281 + *
  31.282 + * This routine is essentially a state machine that handles a couple
  31.283 + * of critical state-transition actions, namely initial setup and
  31.284 + * transition from header scanning to ready-for-start_decompress.
  31.285 + * All the actual input is done via the input controller's consume_input
  31.286 + * method.
  31.287 + */
  31.288 +
  31.289 +GLOBAL(int)
  31.290 +jpeg_consume_input (j_decompress_ptr cinfo)
  31.291 +{
  31.292 +  int retcode = JPEG_SUSPENDED;
  31.293 +
  31.294 +  /* NB: every possible DSTATE value should be listed in this switch */
  31.295 +  switch (cinfo->global_state) {
  31.296 +  case DSTATE_START:
  31.297 +    /* Start-of-datastream actions: reset appropriate modules */
  31.298 +    (*cinfo->inputctl->reset_input_controller) (cinfo);
  31.299 +    /* Initialize application's data source module */
  31.300 +    (*cinfo->src->init_source) (cinfo);
  31.301 +    cinfo->global_state = DSTATE_INHEADER;
  31.302 +    /*FALLTHROUGH*/
  31.303 +  case DSTATE_INHEADER:
  31.304 +    retcode = (*cinfo->inputctl->consume_input) (cinfo);
  31.305 +    if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  31.306 +      /* Set up default parameters based on header data */
  31.307 +      default_decompress_parms(cinfo);
  31.308 +      /* Set global state: ready for start_decompress */
  31.309 +      cinfo->global_state = DSTATE_READY;
  31.310 +    }
  31.311 +    break;
  31.312 +  case DSTATE_READY:
  31.313 +    /* Can't advance past first SOS until start_decompress is called */
  31.314 +    retcode = JPEG_REACHED_SOS;
  31.315 +    break;
  31.316 +  case DSTATE_PRELOAD:
  31.317 +  case DSTATE_PRESCAN:
  31.318 +  case DSTATE_SCANNING:
  31.319 +  case DSTATE_RAW_OK:
  31.320 +  case DSTATE_BUFIMAGE:
  31.321 +  case DSTATE_BUFPOST:
  31.322 +  case DSTATE_STOPPING:
  31.323 +    retcode = (*cinfo->inputctl->consume_input) (cinfo);
  31.324 +    break;
  31.325 +  default:
  31.326 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  31.327 +  }
  31.328 +  return retcode;
  31.329 +}
  31.330 +
  31.331 +
  31.332 +/*
  31.333 + * Have we finished reading the input file?
  31.334 + */
  31.335 +
  31.336 +GLOBAL(boolean)
  31.337 +jpeg_input_complete (j_decompress_ptr cinfo)
  31.338 +{
  31.339 +  /* Check for valid jpeg object */
  31.340 +  if (cinfo->global_state < DSTATE_START ||
  31.341 +      cinfo->global_state > DSTATE_STOPPING)
  31.342 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  31.343 +  return cinfo->inputctl->eoi_reached;
  31.344 +}
  31.345 +
  31.346 +
  31.347 +/*
  31.348 + * Is there more than one scan?
  31.349 + */
  31.350 +
  31.351 +GLOBAL(boolean)
  31.352 +jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  31.353 +{
  31.354 +  /* Only valid after jpeg_read_header completes */
  31.355 +  if (cinfo->global_state < DSTATE_READY ||
  31.356 +      cinfo->global_state > DSTATE_STOPPING)
  31.357 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  31.358 +  return cinfo->inputctl->has_multiple_scans;
  31.359 +}
  31.360 +
  31.361 +
  31.362 +/*
  31.363 + * Finish JPEG decompression.
  31.364 + *
  31.365 + * This will normally just verify the file trailer and release temp storage.
  31.366 + *
  31.367 + * Returns FALSE if suspended.  The return value need be inspected only if
  31.368 + * a suspending data source is used.
  31.369 + */
  31.370 +
  31.371 +GLOBAL(boolean)
  31.372 +jpeg_finish_decompress (j_decompress_ptr cinfo)
  31.373 +{
  31.374 +  if ((cinfo->global_state == DSTATE_SCANNING ||
  31.375 +       cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  31.376 +    /* Terminate final pass of non-buffered mode */
  31.377 +    if (cinfo->output_scanline < cinfo->output_height)
  31.378 +      ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  31.379 +    (*cinfo->master->finish_output_pass) (cinfo);
  31.380 +    cinfo->global_state = DSTATE_STOPPING;
  31.381 +  } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  31.382 +    /* Finishing after a buffered-image operation */
  31.383 +    cinfo->global_state = DSTATE_STOPPING;
  31.384 +  } else if (cinfo->global_state != DSTATE_STOPPING) {
  31.385 +    /* STOPPING = repeat call after a suspension, anything else is error */
  31.386 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  31.387 +  }
  31.388 +  /* Read until EOI */
  31.389 +  while (! cinfo->inputctl->eoi_reached) {
  31.390 +    if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  31.391 +      return FALSE;		/* Suspend, come back later */
  31.392 +  }
  31.393 +  /* Do final cleanup */
  31.394 +  (*cinfo->src->term_source) (cinfo);
  31.395 +  /* We can use jpeg_abort to release memory and reset global_state */
  31.396 +  jpeg_abort((j_common_ptr) cinfo);
  31.397 +  return TRUE;
  31.398 +}
    32.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    32.2 +++ b/libs/libjpeg/jdapistd.c	Thu Sep 08 06:28:38 2011 +0300
    32.3 @@ -0,0 +1,275 @@
    32.4 +/*
    32.5 + * jdapistd.c
    32.6 + *
    32.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    32.8 + * This file is part of the Independent JPEG Group's software.
    32.9 + * For conditions of distribution and use, see the accompanying README file.
   32.10 + *
   32.11 + * This file contains application interface code for the decompression half
   32.12 + * of the JPEG library.  These are the "standard" API routines that are
   32.13 + * used in the normal full-decompression case.  They are not used by a
   32.14 + * transcoding-only application.  Note that if an application links in
   32.15 + * jpeg_start_decompress, it will end up linking in the entire decompressor.
   32.16 + * We thus must separate this file from jdapimin.c to avoid linking the
   32.17 + * whole decompression library into a transcoder.
   32.18 + */
   32.19 +
   32.20 +#define JPEG_INTERNALS
   32.21 +#include "jinclude.h"
   32.22 +#include "jpeglib.h"
   32.23 +
   32.24 +
   32.25 +/* Forward declarations */
   32.26 +LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
   32.27 +
   32.28 +
   32.29 +/*
   32.30 + * Decompression initialization.
   32.31 + * jpeg_read_header must be completed before calling this.
   32.32 + *
   32.33 + * If a multipass operating mode was selected, this will do all but the
   32.34 + * last pass, and thus may take a great deal of time.
   32.35 + *
   32.36 + * Returns FALSE if suspended.  The return value need be inspected only if
   32.37 + * a suspending data source is used.
   32.38 + */
   32.39 +
   32.40 +GLOBAL(boolean)
   32.41 +jpeg_start_decompress (j_decompress_ptr cinfo)
   32.42 +{
   32.43 +  if (cinfo->global_state == DSTATE_READY) {
   32.44 +    /* First call: initialize master control, select active modules */
   32.45 +    jinit_master_decompress(cinfo);
   32.46 +    if (cinfo->buffered_image) {
   32.47 +      /* No more work here; expecting jpeg_start_output next */
   32.48 +      cinfo->global_state = DSTATE_BUFIMAGE;
   32.49 +      return TRUE;
   32.50 +    }
   32.51 +    cinfo->global_state = DSTATE_PRELOAD;
   32.52 +  }
   32.53 +  if (cinfo->global_state == DSTATE_PRELOAD) {
   32.54 +    /* If file has multiple scans, absorb them all into the coef buffer */
   32.55 +    if (cinfo->inputctl->has_multiple_scans) {
   32.56 +#ifdef D_MULTISCAN_FILES_SUPPORTED
   32.57 +      for (;;) {
   32.58 +	int retcode;
   32.59 +	/* Call progress monitor hook if present */
   32.60 +	if (cinfo->progress != NULL)
   32.61 +	  (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
   32.62 +	/* Absorb some more input */
   32.63 +	retcode = (*cinfo->inputctl->consume_input) (cinfo);
   32.64 +	if (retcode == JPEG_SUSPENDED)
   32.65 +	  return FALSE;
   32.66 +	if (retcode == JPEG_REACHED_EOI)
   32.67 +	  break;
   32.68 +	/* Advance progress counter if appropriate */
   32.69 +	if (cinfo->progress != NULL &&
   32.70 +	    (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
   32.71 +	  if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
   32.72 +	    /* jdmaster underestimated number of scans; ratchet up one scan */
   32.73 +	    cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
   32.74 +	  }
   32.75 +	}
   32.76 +      }
   32.77 +#else
   32.78 +      ERREXIT(cinfo, JERR_NOT_COMPILED);
   32.79 +#endif /* D_MULTISCAN_FILES_SUPPORTED */
   32.80 +    }
   32.81 +    cinfo->output_scan_number = cinfo->input_scan_number;
   32.82 +  } else if (cinfo->global_state != DSTATE_PRESCAN)
   32.83 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
   32.84 +  /* Perform any dummy output passes, and set up for the final pass */
   32.85 +  return output_pass_setup(cinfo);
   32.86 +}
   32.87 +
   32.88 +
   32.89 +/*
   32.90 + * Set up for an output pass, and perform any dummy pass(es) needed.
   32.91 + * Common subroutine for jpeg_start_decompress and jpeg_start_output.
   32.92 + * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
   32.93 + * Exit: If done, returns TRUE and sets global_state for proper output mode.
   32.94 + *       If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
   32.95 + */
   32.96 +
   32.97 +LOCAL(boolean)
   32.98 +output_pass_setup (j_decompress_ptr cinfo)
   32.99 +{
  32.100 +  if (cinfo->global_state != DSTATE_PRESCAN) {
  32.101 +    /* First call: do pass setup */
  32.102 +    (*cinfo->master->prepare_for_output_pass) (cinfo);
  32.103 +    cinfo->output_scanline = 0;
  32.104 +    cinfo->global_state = DSTATE_PRESCAN;
  32.105 +  }
  32.106 +  /* Loop over any required dummy passes */
  32.107 +  while (cinfo->master->is_dummy_pass) {
  32.108 +#ifdef QUANT_2PASS_SUPPORTED
  32.109 +    /* Crank through the dummy pass */
  32.110 +    while (cinfo->output_scanline < cinfo->output_height) {
  32.111 +      JDIMENSION last_scanline;
  32.112 +      /* Call progress monitor hook if present */
  32.113 +      if (cinfo->progress != NULL) {
  32.114 +	cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  32.115 +	cinfo->progress->pass_limit = (long) cinfo->output_height;
  32.116 +	(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  32.117 +      }
  32.118 +      /* Process some data */
  32.119 +      last_scanline = cinfo->output_scanline;
  32.120 +      (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  32.121 +				    &cinfo->output_scanline, (JDIMENSION) 0);
  32.122 +      if (cinfo->output_scanline == last_scanline)
  32.123 +	return FALSE;		/* No progress made, must suspend */
  32.124 +    }
  32.125 +    /* Finish up dummy pass, and set up for another one */
  32.126 +    (*cinfo->master->finish_output_pass) (cinfo);
  32.127 +    (*cinfo->master->prepare_for_output_pass) (cinfo);
  32.128 +    cinfo->output_scanline = 0;
  32.129 +#else
  32.130 +    ERREXIT(cinfo, JERR_NOT_COMPILED);
  32.131 +#endif /* QUANT_2PASS_SUPPORTED */
  32.132 +  }
  32.133 +  /* Ready for application to drive output pass through
  32.134 +   * jpeg_read_scanlines or jpeg_read_raw_data.
  32.135 +   */
  32.136 +  cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  32.137 +  return TRUE;
  32.138 +}
  32.139 +
  32.140 +
  32.141 +/*
  32.142 + * Read some scanlines of data from the JPEG decompressor.
  32.143 + *
  32.144 + * The return value will be the number of lines actually read.
  32.145 + * This may be less than the number requested in several cases,
  32.146 + * including bottom of image, data source suspension, and operating
  32.147 + * modes that emit multiple scanlines at a time.
  32.148 + *
  32.149 + * Note: we warn about excess calls to jpeg_read_scanlines() since
  32.150 + * this likely signals an application programmer error.  However,
  32.151 + * an oversize buffer (max_lines > scanlines remaining) is not an error.
  32.152 + */
  32.153 +
  32.154 +GLOBAL(JDIMENSION)
  32.155 +jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  32.156 +		     JDIMENSION max_lines)
  32.157 +{
  32.158 +  JDIMENSION row_ctr;
  32.159 +
  32.160 +  if (cinfo->global_state != DSTATE_SCANNING)
  32.161 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  32.162 +  if (cinfo->output_scanline >= cinfo->output_height) {
  32.163 +    WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  32.164 +    return 0;
  32.165 +  }
  32.166 +
  32.167 +  /* Call progress monitor hook if present */
  32.168 +  if (cinfo->progress != NULL) {
  32.169 +    cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  32.170 +    cinfo->progress->pass_limit = (long) cinfo->output_height;
  32.171 +    (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  32.172 +  }
  32.173 +
  32.174 +  /* Process some data */
  32.175 +  row_ctr = 0;
  32.176 +  (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  32.177 +  cinfo->output_scanline += row_ctr;
  32.178 +  return row_ctr;
  32.179 +}
  32.180 +
  32.181 +
  32.182 +/*
  32.183 + * Alternate entry point to read raw data.
  32.184 + * Processes exactly one iMCU row per call, unless suspended.
  32.185 + */
  32.186 +
  32.187 +GLOBAL(JDIMENSION)
  32.188 +jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  32.189 +		    JDIMENSION max_lines)
  32.190 +{
  32.191 +  JDIMENSION lines_per_iMCU_row;
  32.192 +
  32.193 +  if (cinfo->global_state != DSTATE_RAW_OK)
  32.194 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  32.195 +  if (cinfo->output_scanline >= cinfo->output_height) {
  32.196 +    WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  32.197 +    return 0;
  32.198 +  }
  32.199 +
  32.200 +  /* Call progress monitor hook if present */
  32.201 +  if (cinfo->progress != NULL) {
  32.202 +    cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  32.203 +    cinfo->progress->pass_limit = (long) cinfo->output_height;
  32.204 +    (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  32.205 +  }
  32.206 +
  32.207 +  /* Verify that at least one iMCU row can be returned. */
  32.208 +  lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  32.209 +  if (max_lines < lines_per_iMCU_row)
  32.210 +    ERREXIT(cinfo, JERR_BUFFER_SIZE);
  32.211 +
  32.212 +  /* Decompress directly into user's buffer. */
  32.213 +  if (! (*cinfo->coef->decompress_data) (cinfo, data))
  32.214 +    return 0;			/* suspension forced, can do nothing more */
  32.215 +
  32.216 +  /* OK, we processed one iMCU row. */
  32.217 +  cinfo->output_scanline += lines_per_iMCU_row;
  32.218 +  return lines_per_iMCU_row;
  32.219 +}
  32.220 +
  32.221 +
  32.222 +/* Additional entry points for buffered-image mode. */
  32.223 +
  32.224 +#ifdef D_MULTISCAN_FILES_SUPPORTED
  32.225 +
  32.226 +/*
  32.227 + * Initialize for an output pass in buffered-image mode.
  32.228 + */
  32.229 +
  32.230 +GLOBAL(boolean)
  32.231 +jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  32.232 +{
  32.233 +  if (cinfo->global_state != DSTATE_BUFIMAGE &&
  32.234 +      cinfo->global_state != DSTATE_PRESCAN)
  32.235 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  32.236 +  /* Limit scan number to valid range */
  32.237 +  if (scan_number <= 0)
  32.238 +    scan_number = 1;
  32.239 +  if (cinfo->inputctl->eoi_reached &&
  32.240 +      scan_number > cinfo->input_scan_number)
  32.241 +    scan_number = cinfo->input_scan_number;
  32.242 +  cinfo->output_scan_number = scan_number;
  32.243 +  /* Perform any dummy output passes, and set up for the real pass */
  32.244 +  return output_pass_setup(cinfo);
  32.245 +}
  32.246 +
  32.247 +
  32.248 +/*
  32.249 + * Finish up after an output pass in buffered-image mode.
  32.250 + *
  32.251 + * Returns FALSE if suspended.  The return value need be inspected only if
  32.252 + * a suspending data source is used.
  32.253 + */
  32.254 +
  32.255 +GLOBAL(boolean)
  32.256 +jpeg_finish_output (j_decompress_ptr cinfo)
  32.257 +{
  32.258 +  if ((cinfo->global_state == DSTATE_SCANNING ||
  32.259 +       cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  32.260 +    /* Terminate this pass. */
  32.261 +    /* We do not require the whole pass to have been completed. */
  32.262 +    (*cinfo->master->finish_output_pass) (cinfo);
  32.263 +    cinfo->global_state = DSTATE_BUFPOST;
  32.264 +  } else if (cinfo->global_state != DSTATE_BUFPOST) {
  32.265 +    /* BUFPOST = repeat call after a suspension, anything else is error */
  32.266 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  32.267 +  }
  32.268 +  /* Read markers looking for SOS or EOI */
  32.269 +  while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  32.270 +	 ! cinfo->inputctl->eoi_reached) {
  32.271 +    if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  32.272 +      return FALSE;		/* Suspend, come back later */
  32.273 +  }
  32.274 +  cinfo->global_state = DSTATE_BUFIMAGE;
  32.275 +  return TRUE;
  32.276 +}
  32.277 +
  32.278 +#endif /* D_MULTISCAN_FILES_SUPPORTED */
    33.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    33.2 +++ b/libs/libjpeg/jdatadst.c	Thu Sep 08 06:28:38 2011 +0300
    33.3 @@ -0,0 +1,151 @@
    33.4 +/*
    33.5 + * jdatadst.c
    33.6 + *
    33.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    33.8 + * This file is part of the Independent JPEG Group's software.
    33.9 + * For conditions of distribution and use, see the accompanying README file.
   33.10 + *
   33.11 + * This file contains compression data destination routines for the case of
   33.12 + * emitting JPEG data to a file (or any stdio stream).  While these routines
   33.13 + * are sufficient for most applications, some will want to use a different
   33.14 + * destination manager.
   33.15 + * IMPORTANT: we assume that fwrite() will correctly transcribe an array of
   33.16 + * JOCTETs into 8-bit-wide elements on external storage.  If char is wider
   33.17 + * than 8 bits on your machine, you may need to do some tweaking.
   33.18 + */
   33.19 +
   33.20 +/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
   33.21 +#include "jinclude.h"
   33.22 +#include "jpeglib.h"
   33.23 +#include "jerror.h"
   33.24 +
   33.25 +
   33.26 +/* Expanded data destination object for stdio output */
   33.27 +
   33.28 +typedef struct {
   33.29 +  struct jpeg_destination_mgr pub; /* public fields */
   33.30 +
   33.31 +  FILE * outfile;		/* target stream */
   33.32 +  JOCTET * buffer;		/* start of buffer */
   33.33 +} my_destination_mgr;
   33.34 +
   33.35 +typedef my_destination_mgr * my_dest_ptr;
   33.36 +
   33.37 +#define OUTPUT_BUF_SIZE  4096	/* choose an efficiently fwrite'able size */
   33.38 +
   33.39 +
   33.40 +/*
   33.41 + * Initialize destination --- called by jpeg_start_compress
   33.42 + * before any data is actually written.
   33.43 + */
   33.44 +
   33.45 +METHODDEF(void)
   33.46 +init_destination (j_compress_ptr cinfo)
   33.47 +{
   33.48 +  my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
   33.49 +
   33.50 +  /* Allocate the output buffer --- it will be released when done with image */
   33.51 +  dest->buffer = (JOCTET *)
   33.52 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
   33.53 +				  OUTPUT_BUF_SIZE * SIZEOF(JOCTET));
   33.54 +
   33.55 +  dest->pub.next_output_byte = dest->buffer;
   33.56 +  dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
   33.57 +}
   33.58 +
   33.59 +
   33.60 +/*
   33.61 + * Empty the output buffer --- called whenever buffer fills up.
   33.62 + *
   33.63 + * In typical applications, this should write the entire output buffer
   33.64 + * (ignoring the current state of next_output_byte & free_in_buffer),
   33.65 + * reset the pointer & count to the start of the buffer, and return TRUE
   33.66 + * indicating that the buffer has been dumped.
   33.67 + *
   33.68 + * In applications that need to be able to suspend compression due to output
   33.69 + * overrun, a FALSE return indicates that the buffer cannot be emptied now.
   33.70 + * In this situation, the compressor will return to its caller (possibly with
   33.71 + * an indication that it has not accepted all the supplied scanlines).  The
   33.72 + * application should resume compression after it has made more room in the
   33.73 + * output buffer.  Note that there are substantial restrictions on the use of
   33.74 + * suspension --- see the documentation.
   33.75 + *
   33.76 + * When suspending, the compressor will back up to a convenient restart point
   33.77 + * (typically the start of the current MCU). next_output_byte & free_in_buffer
   33.78 + * indicate where the restart point will be if the current call returns FALSE.
   33.79 + * Data beyond this point will be regenerated after resumption, so do not
   33.80 + * write it out when emptying the buffer externally.
   33.81 + */
   33.82 +
   33.83 +METHODDEF(boolean)
   33.84 +empty_output_buffer (j_compress_ptr cinfo)
   33.85 +{
   33.86 +  my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
   33.87 +
   33.88 +  if (JFWRITE(dest->outfile, dest->buffer, OUTPUT_BUF_SIZE) !=
   33.89 +      (size_t) OUTPUT_BUF_SIZE)
   33.90 +    ERREXIT(cinfo, JERR_FILE_WRITE);
   33.91 +
   33.92 +  dest->pub.next_output_byte = dest->buffer;
   33.93 +  dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
   33.94 +
   33.95 +  return TRUE;
   33.96 +}
   33.97 +
   33.98 +
   33.99 +/*
  33.100 + * Terminate destination --- called by jpeg_finish_compress
  33.101 + * after all data has been written.  Usually needs to flush buffer.
  33.102 + *
  33.103 + * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  33.104 + * application must deal with any cleanup that should happen even
  33.105 + * for error exit.
  33.106 + */
  33.107 +
  33.108 +METHODDEF(void)
  33.109 +term_destination (j_compress_ptr cinfo)
  33.110 +{
  33.111 +  my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
  33.112 +  size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
  33.113 +
  33.114 +  /* Write any data remaining in the buffer */
  33.115 +  if (datacount > 0) {
  33.116 +    if (JFWRITE(dest->outfile, dest->buffer, datacount) != datacount)
  33.117 +      ERREXIT(cinfo, JERR_FILE_WRITE);
  33.118 +  }
  33.119 +  fflush(dest->outfile);
  33.120 +  /* Make sure we wrote the output file OK */
  33.121 +  if (ferror(dest->outfile))
  33.122 +    ERREXIT(cinfo, JERR_FILE_WRITE);
  33.123 +}
  33.124 +
  33.125 +
  33.126 +/*
  33.127 + * Prepare for output to a stdio stream.
  33.128 + * The caller must have already opened the stream, and is responsible
  33.129 + * for closing it after finishing compression.
  33.130 + */
  33.131 +
  33.132 +GLOBAL(void)
  33.133 +jpeg_stdio_dest (j_compress_ptr cinfo, FILE * outfile)
  33.134 +{
  33.135 +  my_dest_ptr dest;
  33.136 +
  33.137 +  /* The destination object is made permanent so that multiple JPEG images
  33.138 +   * can be written to the same file without re-executing jpeg_stdio_dest.
  33.139 +   * This makes it dangerous to use this manager and a different destination
  33.140 +   * manager serially with the same JPEG object, because their private object
  33.141 +   * sizes may be different.  Caveat programmer.
  33.142 +   */
  33.143 +  if (cinfo->dest == NULL) {	/* first time for this JPEG object? */
  33.144 +    cinfo->dest = (struct jpeg_destination_mgr *)
  33.145 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  33.146 +				  SIZEOF(my_destination_mgr));
  33.147 +  }
  33.148 +
  33.149 +  dest = (my_dest_ptr) cinfo->dest;
  33.150 +  dest->pub.init_destination = init_destination;
  33.151 +  dest->pub.empty_output_buffer = empty_output_buffer;
  33.152 +  dest->pub.term_destination = term_destination;
  33.153 +  dest->outfile = outfile;
  33.154 +}
    34.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    34.2 +++ b/libs/libjpeg/jdatasrc.c	Thu Sep 08 06:28:38 2011 +0300
    34.3 @@ -0,0 +1,212 @@
    34.4 +/*
    34.5 + * jdatasrc.c
    34.6 + *
    34.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    34.8 + * This file is part of the Independent JPEG Group's software.
    34.9 + * For conditions of distribution and use, see the accompanying README file.
   34.10 + *
   34.11 + * This file contains decompression data source routines for the case of
   34.12 + * reading JPEG data from a file (or any stdio stream).  While these routines
   34.13 + * are sufficient for most applications, some will want to use a different
   34.14 + * source manager.
   34.15 + * IMPORTANT: we assume that fread() will correctly transcribe an array of
   34.16 + * JOCTETs from 8-bit-wide elements on external storage.  If char is wider
   34.17 + * than 8 bits on your machine, you may need to do some tweaking.
   34.18 + */
   34.19 +
   34.20 +/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
   34.21 +#include "jinclude.h"
   34.22 +#include "jpeglib.h"
   34.23 +#include "jerror.h"
   34.24 +
   34.25 +
   34.26 +/* Expanded data source object for stdio input */
   34.27 +
   34.28 +typedef struct {
   34.29 +  struct jpeg_source_mgr pub;	/* public fields */
   34.30 +
   34.31 +  FILE * infile;		/* source stream */
   34.32 +  JOCTET * buffer;		/* start of buffer */
   34.33 +  boolean start_of_file;	/* have we gotten any data yet? */
   34.34 +} my_source_mgr;
   34.35 +
   34.36 +typedef my_source_mgr * my_src_ptr;
   34.37 +
   34.38 +#define INPUT_BUF_SIZE  4096	/* choose an efficiently fread'able size */
   34.39 +
   34.40 +
   34.41 +/*
   34.42 + * Initialize source --- called by jpeg_read_header
   34.43 + * before any data is actually read.
   34.44 + */
   34.45 +
   34.46 +METHODDEF(void)
   34.47 +init_source (j_decompress_ptr cinfo)
   34.48 +{
   34.49 +  my_src_ptr src = (my_src_ptr) cinfo->src;
   34.50 +
   34.51 +  /* We reset the empty-input-file flag for each image,
   34.52 +   * but we don't clear the input buffer.
   34.53 +   * This is correct behavior for reading a series of images from one source.
   34.54 +   */
   34.55 +  src->start_of_file = TRUE;
   34.56 +}
   34.57 +
   34.58 +
   34.59 +/*
   34.60 + * Fill the input buffer --- called whenever buffer is emptied.
   34.61 + *
   34.62 + * In typical applications, this should read fresh data into the buffer
   34.63 + * (ignoring the current state of next_input_byte & bytes_in_buffer),
   34.64 + * reset the pointer & count to the start of the buffer, and return TRUE
   34.65 + * indicating that the buffer has been reloaded.  It is not necessary to
   34.66 + * fill the buffer entirely, only to obtain at least one more byte.
   34.67 + *
   34.68 + * There is no such thing as an EOF return.  If the end of the file has been
   34.69 + * reached, the routine has a choice of ERREXIT() or inserting fake data into
   34.70 + * the buffer.  In most cases, generating a warning message and inserting a
   34.71 + * fake EOI marker is the best course of action --- this will allow the
   34.72 + * decompressor to output however much of the image is there.  However,
   34.73 + * the resulting error message is misleading if the real problem is an empty
   34.74 + * input file, so we handle that case specially.
   34.75 + *
   34.76 + * In applications that need to be able to suspend compression due to input
   34.77 + * not being available yet, a FALSE return indicates that no more data can be
   34.78 + * obtained right now, but more may be forthcoming later.  In this situation,
   34.79 + * the decompressor will return to its caller (with an indication of the
   34.80 + * number of scanlines it has read, if any).  The application should resume
   34.81 + * decompression after it has loaded more data into the input buffer.  Note
   34.82 + * that there are substantial restrictions on the use of suspension --- see
   34.83 + * the documentation.
   34.84 + *
   34.85 + * When suspending, the decompressor will back up to a convenient restart point
   34.86 + * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
   34.87 + * indicate where the restart point will be if the current call returns FALSE.
   34.88 + * Data beyond this point must be rescanned after resumption, so move it to
   34.89 + * the front of the buffer rather than discarding it.
   34.90 + */
   34.91 +
   34.92 +METHODDEF(boolean)
   34.93 +fill_input_buffer (j_decompress_ptr cinfo)
   34.94 +{
   34.95 +  my_src_ptr src = (my_src_ptr) cinfo->src;
   34.96 +  size_t nbytes;
   34.97 +
   34.98 +  nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
   34.99 +
  34.100 +  if (nbytes <= 0) {
  34.101 +    if (src->start_of_file)	/* Treat empty input file as fatal error */
  34.102 +      ERREXIT(cinfo, JERR_INPUT_EMPTY);
  34.103 +    WARNMS(cinfo, JWRN_JPEG_EOF);
  34.104 +    /* Insert a fake EOI marker */
  34.105 +    src->buffer[0] = (JOCTET) 0xFF;
  34.106 +    src->buffer[1] = (JOCTET) JPEG_EOI;
  34.107 +    nbytes = 2;
  34.108 +  }
  34.109 +
  34.110 +  src->pub.next_input_byte = src->buffer;
  34.111 +  src->pub.bytes_in_buffer = nbytes;
  34.112 +  src->start_of_file = FALSE;
  34.113 +
  34.114 +  return TRUE;
  34.115 +}
  34.116 +
  34.117 +
  34.118 +/*
  34.119 + * Skip data --- used to skip over a potentially large amount of
  34.120 + * uninteresting data (such as an APPn marker).
  34.121 + *
  34.122 + * Writers of suspendable-input applications must note that skip_input_data
  34.123 + * is not granted the right to give a suspension return.  If the skip extends
  34.124 + * beyond the data currently in the buffer, the buffer can be marked empty so
  34.125 + * that the next read will cause a fill_input_buffer call that can suspend.
  34.126 + * Arranging for additional bytes to be discarded before reloading the input
  34.127 + * buffer is the application writer's problem.
  34.128 + */
  34.129 +
  34.130 +METHODDEF(void)
  34.131 +skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  34.132 +{
  34.133 +  my_src_ptr src = (my_src_ptr) cinfo->src;
  34.134 +
  34.135 +  /* Just a dumb implementation for now.  Could use fseek() except
  34.136 +   * it doesn't work on pipes.  Not clear that being smart is worth
  34.137 +   * any trouble anyway --- large skips are infrequent.
  34.138 +   */
  34.139 +  if (num_bytes > 0) {
  34.140 +    while (num_bytes > (long) src->pub.bytes_in_buffer) {
  34.141 +      num_bytes -= (long) src->pub.bytes_in_buffer;
  34.142 +      (void) fill_input_buffer(cinfo);
  34.143 +      /* note we assume that fill_input_buffer will never return FALSE,
  34.144 +       * so suspension need not be handled.
  34.145 +       */
  34.146 +    }
  34.147 +    src->pub.next_input_byte += (size_t) num_bytes;
  34.148 +    src->pub.bytes_in_buffer -= (size_t) num_bytes;
  34.149 +  }
  34.150 +}
  34.151 +
  34.152 +
  34.153 +/*
  34.154 + * An additional method that can be provided by data source modules is the
  34.155 + * resync_to_restart method for error recovery in the presence of RST markers.
  34.156 + * For the moment, this source module just uses the default resync method
  34.157 + * provided by the JPEG library.  That method assumes that no backtracking
  34.158 + * is possible.
  34.159 + */
  34.160 +
  34.161 +
  34.162 +/*
  34.163 + * Terminate source --- called by jpeg_finish_decompress
  34.164 + * after all data has been read.  Often a no-op.
  34.165 + *
  34.166 + * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  34.167 + * application must deal with any cleanup that should happen even
  34.168 + * for error exit.
  34.169 + */
  34.170 +
  34.171 +METHODDEF(void)
  34.172 +term_source (j_decompress_ptr cinfo)
  34.173 +{
  34.174 +  /* no work necessary here */
  34.175 +}
  34.176 +
  34.177 +
  34.178 +/*
  34.179 + * Prepare for input from a stdio stream.
  34.180 + * The caller must have already opened the stream, and is responsible
  34.181 + * for closing it after finishing decompression.
  34.182 + */
  34.183 +
  34.184 +GLOBAL(void)
  34.185 +jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  34.186 +{
  34.187 +  my_src_ptr src;
  34.188 +
  34.189 +  /* The source object and input buffer are made permanent so that a series
  34.190 +   * of JPEG images can be read from the same file by calling jpeg_stdio_src
  34.191 +   * only before the first one.  (If we discarded the buffer at the end of
  34.192 +   * one image, we'd likely lose the start of the next one.)
  34.193 +   * This makes it unsafe to use this manager and a different source
  34.194 +   * manager serially with the same JPEG object.  Caveat programmer.
  34.195 +   */
  34.196 +  if (cinfo->src == NULL) {	/* first time for this JPEG object? */
  34.197 +    cinfo->src = (struct jpeg_source_mgr *)
  34.198 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  34.199 +				  SIZEOF(my_source_mgr));
  34.200 +    src = (my_src_ptr) cinfo->src;
  34.201 +    src->buffer = (JOCTET *)
  34.202 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  34.203 +				  INPUT_BUF_SIZE * SIZEOF(JOCTET));
  34.204 +  }
  34.205 +
  34.206 +  src = (my_src_ptr) cinfo->src;
  34.207 +  src->pub.init_source = init_source;
  34.208 +  src->pub.fill_input_buffer = fill_input_buffer;
  34.209 +  src->pub.skip_input_data = skip_input_data;
  34.210 +  src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  34.211 +  src->pub.term_source = term_source;
  34.212 +  src->infile = infile;
  34.213 +  src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  34.214 +  src->pub.next_input_byte = NULL; /* until buffer loaded */
  34.215 +}
    35.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    35.2 +++ b/libs/libjpeg/jdcoefct.c	Thu Sep 08 06:28:38 2011 +0300
    35.3 @@ -0,0 +1,736 @@
    35.4 +/*
    35.5 + * jdcoefct.c
    35.6 + *
    35.7 + * Copyright (C) 1994-1997, Thomas G. Lane.
    35.8 + * This file is part of the Independent JPEG Group's software.
    35.9 + * For conditions of distribution and use, see the accompanying README file.
   35.10 + *
   35.11 + * This file contains the coefficient buffer controller for decompression.
   35.12 + * This controller is the top level of the JPEG decompressor proper.
   35.13 + * The coefficient buffer lies between entropy decoding and inverse-DCT steps.
   35.14 + *
   35.15 + * In buffered-image mode, this controller is the interface between
   35.16 + * input-oriented processing and output-oriented processing.
   35.17 + * Also, the input side (only) is used when reading a file for transcoding.
   35.18 + */
   35.19 +
   35.20 +#define JPEG_INTERNALS
   35.21 +#include "jinclude.h"
   35.22 +#include "jpeglib.h"
   35.23 +
   35.24 +/* Block smoothing is only applicable for progressive JPEG, so: */
   35.25 +#ifndef D_PROGRESSIVE_SUPPORTED
   35.26 +#undef BLOCK_SMOOTHING_SUPPORTED
   35.27 +#endif
   35.28 +
   35.29 +/* Private buffer controller object */
   35.30 +
   35.31 +typedef struct {
   35.32 +  struct jpeg_d_coef_controller pub; /* public fields */
   35.33 +
   35.34 +  /* These variables keep track of the current location of the input side. */
   35.35 +  /* cinfo->input_iMCU_row is also used for this. */
   35.36 +  JDIMENSION MCU_ctr;		/* counts MCUs processed in current row */
   35.37 +  int MCU_vert_offset;		/* counts MCU rows within iMCU row */
   35.38 +  int MCU_rows_per_iMCU_row;	/* number of such rows needed */
   35.39 +
   35.40 +  /* The output side's location is represented by cinfo->output_iMCU_row. */
   35.41 +
   35.42 +  /* In single-pass modes, it's sufficient to buffer just one MCU.
   35.43 +   * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
   35.44 +   * and let the entropy decoder write into that workspace each time.
   35.45 +   * (On 80x86, the workspace is FAR even though it's not really very big;
   35.46 +   * this is to keep the module interfaces unchanged when a large coefficient
   35.47 +   * buffer is necessary.)
   35.48 +   * In multi-pass modes, this array points to the current MCU's blocks
   35.49 +   * within the virtual arrays; it is used only by the input side.
   35.50 +   */
   35.51 +  JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
   35.52 +
   35.53 +#ifdef D_MULTISCAN_FILES_SUPPORTED
   35.54 +  /* In multi-pass modes, we need a virtual block array for each component. */
   35.55 +  jvirt_barray_ptr whole_image[MAX_COMPONENTS];
   35.56 +#endif
   35.57 +
   35.58 +#ifdef BLOCK_SMOOTHING_SUPPORTED
   35.59 +  /* When doing block smoothing, we latch coefficient Al values here */
   35.60 +  int * coef_bits_latch;
   35.61 +#define SAVED_COEFS  6		/* we save coef_bits[0..5] */
   35.62 +#endif
   35.63 +} my_coef_controller;
   35.64 +
   35.65 +typedef my_coef_controller * my_coef_ptr;
   35.66 +
   35.67 +/* Forward declarations */
   35.68 +METHODDEF(int) decompress_onepass
   35.69 +	JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
   35.70 +#ifdef D_MULTISCAN_FILES_SUPPORTED
   35.71 +METHODDEF(int) decompress_data
   35.72 +	JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
   35.73 +#endif
   35.74 +#ifdef BLOCK_SMOOTHING_SUPPORTED
   35.75 +LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
   35.76 +METHODDEF(int) decompress_smooth_data
   35.77 +	JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
   35.78 +#endif
   35.79 +
   35.80 +
   35.81 +LOCAL(void)
   35.82 +start_iMCU_row (j_decompress_ptr cinfo)
   35.83 +/* Reset within-iMCU-row counters for a new row (input side) */
   35.84 +{
   35.85 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
   35.86 +
   35.87 +  /* In an interleaved scan, an MCU row is the same as an iMCU row.
   35.88 +   * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
   35.89 +   * But at the bottom of the image, process only what's left.
   35.90 +   */
   35.91 +  if (cinfo->comps_in_scan > 1) {
   35.92 +    coef->MCU_rows_per_iMCU_row = 1;
   35.93 +  } else {
   35.94 +    if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
   35.95 +      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
   35.96 +    else
   35.97 +      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
   35.98 +  }
   35.99 +
  35.100 +  coef->MCU_ctr = 0;
  35.101 +  coef->MCU_vert_offset = 0;
  35.102 +}
  35.103 +
  35.104 +
  35.105 +/*
  35.106 + * Initialize for an input processing pass.
  35.107 + */
  35.108 +
  35.109 +METHODDEF(void)
  35.110 +start_input_pass (j_decompress_ptr cinfo)
  35.111 +{
  35.112 +  cinfo->input_iMCU_row = 0;
  35.113 +  start_iMCU_row(cinfo);
  35.114 +}
  35.115 +
  35.116 +
  35.117 +/*
  35.118 + * Initialize for an output processing pass.
  35.119 + */
  35.120 +
  35.121 +METHODDEF(void)
  35.122 +start_output_pass (j_decompress_ptr cinfo)
  35.123 +{
  35.124 +#ifdef BLOCK_SMOOTHING_SUPPORTED
  35.125 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  35.126 +
  35.127 +  /* If multipass, check to see whether to use block smoothing on this pass */
  35.128 +  if (coef->pub.coef_arrays != NULL) {
  35.129 +    if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  35.130 +      coef->pub.decompress_data = decompress_smooth_data;
  35.131 +    else
  35.132 +      coef->pub.decompress_data = decompress_data;
  35.133 +  }
  35.134 +#endif
  35.135 +  cinfo->output_iMCU_row = 0;
  35.136 +}
  35.137 +
  35.138 +
  35.139 +/*
  35.140 + * Decompress and return some data in the single-pass case.
  35.141 + * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  35.142 + * Input and output must run in lockstep since we have only a one-MCU buffer.
  35.143 + * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  35.144 + *
  35.145 + * NB: output_buf contains a plane for each component in image,
  35.146 + * which we index according to the component's SOF position.
  35.147 + */
  35.148 +
  35.149 +METHODDEF(int)
  35.150 +decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  35.151 +{
  35.152 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  35.153 +  JDIMENSION MCU_col_num;	/* index of current MCU within row */
  35.154 +  JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  35.155 +  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  35.156 +  int blkn, ci, xindex, yindex, yoffset, useful_width;
  35.157 +  JSAMPARRAY output_ptr;
  35.158 +  JDIMENSION start_col, output_col;
  35.159 +  jpeg_component_info *compptr;
  35.160 +  inverse_DCT_method_ptr inverse_DCT;
  35.161 +
  35.162 +  /* Loop to process as much as one whole iMCU row */
  35.163 +  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  35.164 +       yoffset++) {
  35.165 +    for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  35.166 +	 MCU_col_num++) {
  35.167 +      /* Try to fetch an MCU.  Entropy decoder expects buffer to be zeroed. */
  35.168 +      jzero_far((void FAR *) coef->MCU_buffer[0],
  35.169 +		(size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  35.170 +      if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  35.171 +	/* Suspension forced; update state counters and exit */
  35.172 +	coef->MCU_vert_offset = yoffset;
  35.173 +	coef->MCU_ctr = MCU_col_num;
  35.174 +	return JPEG_SUSPENDED;
  35.175 +      }
  35.176 +      /* Determine where data should go in output_buf and do the IDCT thing.
  35.177 +       * We skip dummy blocks at the right and bottom edges (but blkn gets
  35.178 +       * incremented past them!).  Note the inner loop relies on having
  35.179 +       * allocated the MCU_buffer[] blocks sequentially.
  35.180 +       */
  35.181 +      blkn = 0;			/* index of current DCT block within MCU */
  35.182 +      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  35.183 +	compptr = cinfo->cur_comp_info[ci];
  35.184 +	/* Don't bother to IDCT an uninteresting component. */
  35.185 +	if (! compptr->component_needed) {
  35.186 +	  blkn += compptr->MCU_blocks;
  35.187 +	  continue;
  35.188 +	}
  35.189 +	inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  35.190 +	useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  35.191 +						    : compptr->last_col_width;
  35.192 +	output_ptr = output_buf[compptr->component_index] +
  35.193 +	  yoffset * compptr->DCT_scaled_size;
  35.194 +	start_col = MCU_col_num * compptr->MCU_sample_width;
  35.195 +	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  35.196 +	  if (cinfo->input_iMCU_row < last_iMCU_row ||
  35.197 +	      yoffset+yindex < compptr->last_row_height) {
  35.198 +	    output_col = start_col;
  35.199 +	    for (xindex = 0; xindex < useful_width; xindex++) {
  35.200 +	      (*inverse_DCT) (cinfo, compptr,
  35.201 +			      (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  35.202 +			      output_ptr, output_col);
  35.203 +	      output_col += compptr->DCT_scaled_size;
  35.204 +	    }
  35.205 +	  }
  35.206 +	  blkn += compptr->MCU_width;
  35.207 +	  output_ptr += compptr->DCT_scaled_size;
  35.208 +	}
  35.209 +      }
  35.210 +    }
  35.211 +    /* Completed an MCU row, but perhaps not an iMCU row */
  35.212 +    coef->MCU_ctr = 0;
  35.213 +  }
  35.214 +  /* Completed the iMCU row, advance counters for next one */
  35.215 +  cinfo->output_iMCU_row++;
  35.216 +  if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  35.217 +    start_iMCU_row(cinfo);
  35.218 +    return JPEG_ROW_COMPLETED;
  35.219 +  }
  35.220 +  /* Completed the scan */
  35.221 +  (*cinfo->inputctl->finish_input_pass) (cinfo);
  35.222 +  return JPEG_SCAN_COMPLETED;
  35.223 +}
  35.224 +
  35.225 +
  35.226 +/*
  35.227 + * Dummy consume-input routine for single-pass operation.
  35.228 + */
  35.229 +
  35.230 +METHODDEF(int)
  35.231 +dummy_consume_data (j_decompress_ptr cinfo)
  35.232 +{
  35.233 +  return JPEG_SUSPENDED;	/* Always indicate nothing was done */
  35.234 +}
  35.235 +
  35.236 +
  35.237 +#ifdef D_MULTISCAN_FILES_SUPPORTED
  35.238 +
  35.239 +/*
  35.240 + * Consume input data and store it in the full-image coefficient buffer.
  35.241 + * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  35.242 + * ie, v_samp_factor block rows for each component in the scan.
  35.243 + * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  35.244 + */
  35.245 +
  35.246 +METHODDEF(int)
  35.247 +consume_data (j_decompress_ptr cinfo)
  35.248 +{
  35.249 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  35.250 +  JDIMENSION MCU_col_num;	/* index of current MCU within row */
  35.251 +  int blkn, ci, xindex, yindex, yoffset;
  35.252 +  JDIMENSION start_col;
  35.253 +  JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  35.254 +  JBLOCKROW buffer_ptr;
  35.255 +  jpeg_component_info *compptr;
  35.256 +
  35.257 +  /* Align the virtual buffers for the components used in this scan. */
  35.258 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  35.259 +    compptr = cinfo->cur_comp_info[ci];
  35.260 +    buffer[ci] = (*cinfo->mem->access_virt_barray)
  35.261 +      ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  35.262 +       cinfo->input_iMCU_row * compptr->v_samp_factor,
  35.263 +       (JDIMENSION) compptr->v_samp_factor, TRUE);
  35.264 +    /* Note: entropy decoder expects buffer to be zeroed,
  35.265 +     * but this is handled automatically by the memory manager
  35.266 +     * because we requested a pre-zeroed array.
  35.267 +     */
  35.268 +  }
  35.269 +
  35.270 +  /* Loop to process one whole iMCU row */
  35.271 +  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  35.272 +       yoffset++) {
  35.273 +    for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  35.274 +	 MCU_col_num++) {
  35.275 +      /* Construct list of pointers to DCT blocks belonging to this MCU */
  35.276 +      blkn = 0;			/* index of current DCT block within MCU */
  35.277 +      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  35.278 +	compptr = cinfo->cur_comp_info[ci];
  35.279 +	start_col = MCU_col_num * compptr->MCU_width;
  35.280 +	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  35.281 +	  buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  35.282 +	  for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  35.283 +	    coef->MCU_buffer[blkn++] = buffer_ptr++;
  35.284 +	  }
  35.285 +	}
  35.286 +      }
  35.287 +      /* Try to fetch the MCU. */
  35.288 +      if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  35.289 +	/* Suspension forced; update state counters and exit */
  35.290 +	coef->MCU_vert_offset = yoffset;
  35.291 +	coef->MCU_ctr = MCU_col_num;
  35.292 +	return JPEG_SUSPENDED;
  35.293 +      }
  35.294 +    }
  35.295 +    /* Completed an MCU row, but perhaps not an iMCU row */
  35.296 +    coef->MCU_ctr = 0;
  35.297 +  }
  35.298 +  /* Completed the iMCU row, advance counters for next one */
  35.299 +  if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  35.300 +    start_iMCU_row(cinfo);
  35.301 +    return JPEG_ROW_COMPLETED;
  35.302 +  }
  35.303 +  /* Completed the scan */
  35.304 +  (*cinfo->inputctl->finish_input_pass) (cinfo);
  35.305 +  return JPEG_SCAN_COMPLETED;
  35.306 +}
  35.307 +
  35.308 +
  35.309 +/*
  35.310 + * Decompress and return some data in the multi-pass case.
  35.311 + * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  35.312 + * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  35.313 + *
  35.314 + * NB: output_buf contains a plane for each component in image.
  35.315 + */
  35.316 +
  35.317 +METHODDEF(int)
  35.318 +decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  35.319 +{
  35.320 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  35.321 +  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  35.322 +  JDIMENSION block_num;
  35.323 +  int ci, block_row, block_rows;
  35.324 +  JBLOCKARRAY buffer;
  35.325 +  JBLOCKROW buffer_ptr;
  35.326 +  JSAMPARRAY output_ptr;
  35.327 +  JDIMENSION output_col;
  35.328 +  jpeg_component_info *compptr;
  35.329 +  inverse_DCT_method_ptr inverse_DCT;
  35.330 +
  35.331 +  /* Force some input to be done if we are getting ahead of the input. */
  35.332 +  while (cinfo->input_scan_number < cinfo->output_scan_number ||
  35.333 +	 (cinfo->input_scan_number == cinfo->output_scan_number &&
  35.334 +	  cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  35.335 +    if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  35.336 +      return JPEG_SUSPENDED;
  35.337 +  }
  35.338 +
  35.339 +  /* OK, output from the virtual arrays. */
  35.340 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  35.341 +       ci++, compptr++) {
  35.342 +    /* Don't bother to IDCT an uninteresting component. */
  35.343 +    if (! compptr->component_needed)
  35.344 +      continue;
  35.345 +    /* Align the virtual buffer for this component. */
  35.346 +    buffer = (*cinfo->mem->access_virt_barray)
  35.347 +      ((j_common_ptr) cinfo, coef->whole_image[ci],
  35.348 +       cinfo->output_iMCU_row * compptr->v_samp_factor,
  35.349 +       (JDIMENSION) compptr->v_samp_factor, FALSE);
  35.350 +    /* Count non-dummy DCT block rows in this iMCU row. */
  35.351 +    if (cinfo->output_iMCU_row < last_iMCU_row)
  35.352 +      block_rows = compptr->v_samp_factor;
  35.353 +    else {
  35.354 +      /* NB: can't use last_row_height here; it is input-side-dependent! */
  35.355 +      block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  35.356 +      if (block_rows == 0) block_rows = compptr->v_samp_factor;
  35.357 +    }
  35.358 +    inverse_DCT = cinfo->idct->inverse_DCT[ci];
  35.359 +    output_ptr = output_buf[ci];
  35.360 +    /* Loop over all DCT blocks to be processed. */
  35.361 +    for (block_row = 0; block_row < block_rows; block_row++) {
  35.362 +      buffer_ptr = buffer[block_row];
  35.363 +      output_col = 0;
  35.364 +      for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  35.365 +	(*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  35.366 +			output_ptr, output_col);
  35.367 +	buffer_ptr++;
  35.368 +	output_col += compptr->DCT_scaled_size;
  35.369 +      }
  35.370 +      output_ptr += compptr->DCT_scaled_size;
  35.371 +    }
  35.372 +  }
  35.373 +
  35.374 +  if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  35.375 +    return JPEG_ROW_COMPLETED;
  35.376 +  return JPEG_SCAN_COMPLETED;
  35.377 +}
  35.378 +
  35.379 +#endif /* D_MULTISCAN_FILES_SUPPORTED */
  35.380 +
  35.381 +
  35.382 +#ifdef BLOCK_SMOOTHING_SUPPORTED
  35.383 +
  35.384 +/*
  35.385 + * This code applies interblock smoothing as described by section K.8
  35.386 + * of the JPEG standard: the first 5 AC coefficients are estimated from
  35.387 + * the DC values of a DCT block and its 8 neighboring blocks.
  35.388 + * We apply smoothing only for progressive JPEG decoding, and only if
  35.389 + * the coefficients it can estimate are not yet known to full precision.
  35.390 + */
  35.391 +
  35.392 +/* Natural-order array positions of the first 5 zigzag-order coefficients */
  35.393 +#define Q01_POS  1
  35.394 +#define Q10_POS  8
  35.395 +#define Q20_POS  16
  35.396 +#define Q11_POS  9
  35.397 +#define Q02_POS  2
  35.398 +
  35.399 +/*
  35.400 + * Determine whether block smoothing is applicable and safe.
  35.401 + * We also latch the current states of the coef_bits[] entries for the
  35.402 + * AC coefficients; otherwise, if the input side of the decompressor
  35.403 + * advances into a new scan, we might think the coefficients are known
  35.404 + * more accurately than they really are.
  35.405 + */
  35.406 +
  35.407 +LOCAL(boolean)
  35.408 +smoothing_ok (j_decompress_ptr cinfo)
  35.409 +{
  35.410 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  35.411 +  boolean smoothing_useful = FALSE;
  35.412 +  int ci, coefi;
  35.413 +  jpeg_component_info *compptr;
  35.414 +  JQUANT_TBL * qtable;
  35.415 +  int * coef_bits;
  35.416 +  int * coef_bits_latch;
  35.417 +
  35.418 +  if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  35.419 +    return FALSE;
  35.420 +
  35.421 +  /* Allocate latch area if not already done */
  35.422 +  if (coef->coef_bits_latch == NULL)
  35.423 +    coef->coef_bits_latch = (int *)
  35.424 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  35.425 +				  cinfo->num_components *
  35.426 +				  (SAVED_COEFS * SIZEOF(int)));
  35.427 +  coef_bits_latch = coef->coef_bits_latch;
  35.428 +
  35.429 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  35.430 +       ci++, compptr++) {
  35.431 +    /* All components' quantization values must already be latched. */
  35.432 +    if ((qtable = compptr->quant_table) == NULL)
  35.433 +      return FALSE;
  35.434 +    /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  35.435 +    if (qtable->quantval[0] == 0 ||
  35.436 +	qtable->quantval[Q01_POS] == 0 ||
  35.437 +	qtable->quantval[Q10_POS] == 0 ||
  35.438 +	qtable->quantval[Q20_POS] == 0 ||
  35.439 +	qtable->quantval[Q11_POS] == 0 ||
  35.440 +	qtable->quantval[Q02_POS] == 0)
  35.441 +      return FALSE;
  35.442 +    /* DC values must be at least partly known for all components. */
  35.443 +    coef_bits = cinfo->coef_bits[ci];
  35.444 +    if (coef_bits[0] < 0)
  35.445 +      return FALSE;
  35.446 +    /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  35.447 +    for (coefi = 1; coefi <= 5; coefi++) {
  35.448 +      coef_bits_latch[coefi] = coef_bits[coefi];
  35.449 +      if (coef_bits[coefi] != 0)
  35.450 +	smoothing_useful = TRUE;
  35.451 +    }
  35.452 +    coef_bits_latch += SAVED_COEFS;
  35.453 +  }
  35.454 +
  35.455 +  return smoothing_useful;
  35.456 +}
  35.457 +
  35.458 +
  35.459 +/*
  35.460 + * Variant of decompress_data for use when doing block smoothing.
  35.461 + */
  35.462 +
  35.463 +METHODDEF(int)
  35.464 +decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  35.465 +{
  35.466 +  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  35.467 +  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  35.468 +  JDIMENSION block_num, last_block_column;
  35.469 +  int ci, block_row, block_rows, access_rows;
  35.470 +  JBLOCKARRAY buffer;
  35.471 +  JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  35.472 +  JSAMPARRAY output_ptr;
  35.473 +  JDIMENSION output_col;
  35.474 +  jpeg_component_info *compptr;
  35.475 +  inverse_DCT_method_ptr inverse_DCT;
  35.476 +  boolean first_row, last_row;
  35.477 +  JBLOCK workspace;
  35.478 +  int *coef_bits;
  35.479 +  JQUANT_TBL *quanttbl;
  35.480 +  INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  35.481 +  int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  35.482 +  int Al, pred;
  35.483 +
  35.484 +  /* Force some input to be done if we are getting ahead of the input. */
  35.485 +  while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  35.486 +	 ! cinfo->inputctl->eoi_reached) {
  35.487 +    if (cinfo->input_scan_number == cinfo->output_scan_number) {
  35.488 +      /* If input is working on current scan, we ordinarily want it to
  35.489 +       * have completed the current row.  But if input scan is DC,
  35.490 +       * we want it to keep one row ahead so that next block row's DC
  35.491 +       * values are up to date.
  35.492 +       */
  35.493 +      JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  35.494 +      if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  35.495 +	break;
  35.496 +    }
  35.497 +    if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  35.498 +      return JPEG_SUSPENDED;
  35.499 +  }
  35.500 +
  35.501 +  /* OK, output from the virtual arrays. */
  35.502 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  35.503 +       ci++, compptr++) {
  35.504 +    /* Don't bother to IDCT an uninteresting component. */
  35.505 +    if (! compptr->component_needed)
  35.506 +      continue;
  35.507 +    /* Count non-dummy DCT block rows in this iMCU row. */
  35.508 +    if (cinfo->output_iMCU_row < last_iMCU_row) {
  35.509 +      block_rows = compptr->v_samp_factor;
  35.510 +      access_rows = block_rows * 2; /* this and next iMCU row */
  35.511 +      last_row = FALSE;
  35.512 +    } else {
  35.513 +      /* NB: can't use last_row_height here; it is input-side-dependent! */
  35.514 +      block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  35.515 +      if (block_rows == 0) block_rows = compptr->v_samp_factor;
  35.516 +      access_rows = block_rows; /* this iMCU row only */
  35.517 +      last_row = TRUE;
  35.518 +    }
  35.519 +    /* Align the virtual buffer for this component. */
  35.520 +    if (cinfo->output_iMCU_row > 0) {
  35.521 +      access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  35.522 +      buffer = (*cinfo->mem->access_virt_barray)
  35.523 +	((j_common_ptr) cinfo, coef->whole_image[ci],
  35.524 +	 (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  35.525 +	 (JDIMENSION) access_rows, FALSE);
  35.526 +      buffer += compptr->v_samp_factor;	/* point to current iMCU row */
  35.527 +      first_row = FALSE;
  35.528 +    } else {
  35.529 +      buffer = (*cinfo->mem->access_virt_barray)
  35.530 +	((j_common_ptr) cinfo, coef->whole_image[ci],
  35.531 +	 (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  35.532 +      first_row = TRUE;
  35.533 +    }
  35.534 +    /* Fetch component-dependent info */
  35.535 +    coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  35.536 +    quanttbl = compptr->quant_table;
  35.537 +    Q00 = quanttbl->quantval[0];
  35.538 +    Q01 = quanttbl->quantval[Q01_POS];
  35.539 +    Q10 = quanttbl->quantval[Q10_POS];
  35.540 +    Q20 = quanttbl->quantval[Q20_POS];
  35.541 +    Q11 = quanttbl->quantval[Q11_POS];
  35.542 +    Q02 = quanttbl->quantval[Q02_POS];
  35.543 +    inverse_DCT = cinfo->idct->inverse_DCT[ci];
  35.544 +    output_ptr = output_buf[ci];
  35.545 +    /* Loop over all DCT blocks to be processed. */
  35.546 +    for (block_row = 0; block_row < block_rows; block_row++) {
  35.547 +      buffer_ptr = buffer[block_row];
  35.548 +      if (first_row && block_row == 0)
  35.549 +	prev_block_row = buffer_ptr;
  35.550 +      else
  35.551 +	prev_block_row = buffer[block_row-1];
  35.552 +      if (last_row && block_row == block_rows-1)
  35.553 +	next_block_row = buffer_ptr;
  35.554 +      else
  35.555 +	next_block_row = buffer[block_row+1];
  35.556 +      /* We fetch the surrounding DC values using a sliding-register approach.
  35.557 +       * Initialize all nine here so as to do the right thing on narrow pics.
  35.558 +       */
  35.559 +      DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  35.560 +      DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  35.561 +      DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  35.562 +      output_col = 0;
  35.563 +      last_block_column = compptr->width_in_blocks - 1;
  35.564 +      for (block_num = 0; block_num <= last_block_column; block_num++) {
  35.565 +	/* Fetch current DCT block into workspace so we can modify it. */
  35.566 +	jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  35.567 +	/* Update DC values */
  35.568 +	if (block_num < last_block_column) {
  35.569 +	  DC3 = (int) prev_block_row[1][0];
  35.570 +	  DC6 = (int) buffer_ptr[1][0];
  35.571 +	  DC9 = (int) next_block_row[1][0];
  35.572 +	}
  35.573 +	/* Compute coefficient estimates per K.8.
  35.574 +	 * An estimate is applied only if coefficient is still zero,
  35.575 +	 * and is not known to be fully accurate.
  35.576 +	 */
  35.577 +	/* AC01 */
  35.578 +	if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  35.579 +	  num = 36 * Q00 * (DC4 - DC6);
  35.580 +	  if (num >= 0) {
  35.581 +	    pred = (int) (((Q01<<7) + num) / (Q01<<8));
  35.582 +	    if (Al > 0 && pred >= (1<<Al))
  35.583 +	      pred = (1<<Al)-1;
  35.584 +	  } else {
  35.585 +	    pred = (int) (((Q01<<7) - num) / (Q01<<8));
  35.586 +	    if (Al > 0 && pred >= (1<<Al))
  35.587 +	      pred = (1<<Al)-1;
  35.588 +	    pred = -pred;
  35.589 +	  }
  35.590 +	  workspace[1] = (JCOEF) pred;
  35.591 +	}
  35.592 +	/* AC10 */
  35.593 +	if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  35.594 +	  num = 36 * Q00 * (DC2 - DC8);
  35.595 +	  if (num >= 0) {
  35.596 +	    pred = (int) (((Q10<<7) + num) / (Q10<<8));
  35.597 +	    if (Al > 0 && pred >= (1<<Al))
  35.598 +	      pred = (1<<Al)-1;
  35.599 +	  } else {
  35.600 +	    pred = (int) (((Q10<<7) - num) / (Q10<<8));
  35.601 +	    if (Al > 0 && pred >= (1<<Al))
  35.602 +	      pred = (1<<Al)-1;
  35.603 +	    pred = -pred;
  35.604 +	  }
  35.605 +	  workspace[8] = (JCOEF) pred;
  35.606 +	}
  35.607 +	/* AC20 */
  35.608 +	if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  35.609 +	  num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  35.610 +	  if (num >= 0) {
  35.611 +	    pred = (int) (((Q20<<7) + num) / (Q20<<8));
  35.612 +	    if (Al > 0 && pred >= (1<<Al))
  35.613 +	      pred = (1<<Al)-1;
  35.614 +	  } else {
  35.615 +	    pred = (int) (((Q20<<7) - num) / (Q20<<8));
  35.616 +	    if (Al > 0 && pred >= (1<<Al))
  35.617 +	      pred = (1<<Al)-1;
  35.618 +	    pred = -pred;
  35.619 +	  }
  35.620 +	  workspace[16] = (JCOEF) pred;
  35.621 +	}
  35.622 +	/* AC11 */
  35.623 +	if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  35.624 +	  num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  35.625 +	  if (num >= 0) {
  35.626 +	    pred = (int) (((Q11<<7) + num) / (Q11<<8));
  35.627 +	    if (Al > 0 && pred >= (1<<Al))
  35.628 +	      pred = (1<<Al)-1;
  35.629 +	  } else {
  35.630 +	    pred = (int) (((Q11<<7) - num) / (Q11<<8));
  35.631 +	    if (Al > 0 && pred >= (1<<Al))
  35.632 +	      pred = (1<<Al)-1;
  35.633 +	    pred = -pred;
  35.634 +	  }
  35.635 +	  workspace[9] = (JCOEF) pred;
  35.636 +	}
  35.637 +	/* AC02 */
  35.638 +	if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  35.639 +	  num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  35.640 +	  if (num >= 0) {
  35.641 +	    pred = (int) (((Q02<<7) + num) / (Q02<<8));
  35.642 +	    if (Al > 0 && pred >= (1<<Al))
  35.643 +	      pred = (1<<Al)-1;
  35.644 +	  } else {
  35.645 +	    pred = (int) (((Q02<<7) - num) / (Q02<<8));
  35.646 +	    if (Al > 0 && pred >= (1<<Al))
  35.647 +	      pred = (1<<Al)-1;
  35.648 +	    pred = -pred;
  35.649 +	  }
  35.650 +	  workspace[2] = (JCOEF) pred;
  35.651 +	}
  35.652 +	/* OK, do the IDCT */
  35.653 +	(*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  35.654 +			output_ptr, output_col);
  35.655 +	/* Advance for next column */
  35.656 +	DC1 = DC2; DC2 = DC3;
  35.657 +	DC4 = DC5; DC5 = DC6;
  35.658 +	DC7 = DC8; DC8 = DC9;
  35.659 +	buffer_ptr++, prev_block_row++, next_block_row++;
  35.660 +	output_col += compptr->DCT_scaled_size;
  35.661 +      }
  35.662 +      output_ptr += compptr->DCT_scaled_size;
  35.663 +    }
  35.664 +  }
  35.665 +
  35.666 +  if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  35.667 +    return JPEG_ROW_COMPLETED;
  35.668 +  return JPEG_SCAN_COMPLETED;
  35.669 +}
  35.670 +
  35.671 +#endif /* BLOCK_SMOOTHING_SUPPORTED */
  35.672 +
  35.673 +
  35.674 +/*
  35.675 + * Initialize coefficient buffer controller.
  35.676 + */
  35.677 +
  35.678 +GLOBAL(void)
  35.679 +jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  35.680 +{
  35.681 +  my_coef_ptr coef;
  35.682 +
  35.683 +  coef = (my_coef_ptr)
  35.684 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  35.685 +				SIZEOF(my_coef_controller));
  35.686 +  cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  35.687 +  coef->pub.start_input_pass = start_input_pass;
  35.688 +  coef->pub.start_output_pass = start_output_pass;
  35.689 +#ifdef BLOCK_SMOOTHING_SUPPORTED
  35.690 +  coef->coef_bits_latch = NULL;
  35.691 +#endif
  35.692 +
  35.693 +  /* Create the coefficient buffer. */
  35.694 +  if (need_full_buffer) {
  35.695 +#ifdef D_MULTISCAN_FILES_SUPPORTED
  35.696 +    /* Allocate a full-image virtual array for each component, */
  35.697 +    /* padded to a multiple of samp_factor DCT blocks in each direction. */
  35.698 +    /* Note we ask for a pre-zeroed array. */
  35.699 +    int ci, access_rows;
  35.700 +    jpeg_component_info *compptr;
  35.701 +
  35.702 +    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  35.703 +	 ci++, compptr++) {
  35.704 +      access_rows = compptr->v_samp_factor;
  35.705 +#ifdef BLOCK_SMOOTHING_SUPPORTED
  35.706 +      /* If block smoothing could be used, need a bigger window */
  35.707 +      if (cinfo->progressive_mode)
  35.708 +	access_rows *= 3;
  35.709 +#endif
  35.710 +      coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  35.711 +	((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  35.712 +	 (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  35.713 +				(long) compptr->h_samp_factor),
  35.714 +	 (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  35.715 +				(long) compptr->v_samp_factor),
  35.716 +	 (JDIMENSION) access_rows);
  35.717 +    }
  35.718 +    coef->pub.consume_data = consume_data;
  35.719 +    coef->pub.decompress_data = decompress_data;
  35.720 +    coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  35.721 +#else
  35.722 +    ERREXIT(cinfo, JERR_NOT_COMPILED);
  35.723 +#endif
  35.724 +  } else {
  35.725 +    /* We only need a single-MCU buffer. */
  35.726 +    JBLOCKROW buffer;
  35.727 +    int i;
  35.728 +
  35.729 +    buffer = (JBLOCKROW)
  35.730 +      (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  35.731 +				  D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  35.732 +    for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  35.733 +      coef->MCU_buffer[i] = buffer + i;
  35.734 +    }
  35.735 +    coef->pub.consume_data = dummy_consume_data;
  35.736 +    coef->pub.decompress_data = decompress_onepass;
  35.737 +    coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  35.738 +  }
  35.739 +}
    36.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    36.2 +++ b/libs/libjpeg/jdcolor.c	Thu Sep 08 06:28:38 2011 +0300
    36.3 @@ -0,0 +1,396 @@
    36.4 +/*
    36.5 + * jdcolor.c
    36.6 + *
    36.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    36.8 + * This file is part of the Independent JPEG Group's software.
    36.9 + * For conditions of distribution and use, see the accompanying README file.
   36.10 + *
   36.11 + * This file contains output colorspace conversion routines.
   36.12 + */
   36.13 +
   36.14 +#define JPEG_INTERNALS
   36.15 +#include "jinclude.h"
   36.16 +#include "jpeglib.h"
   36.17 +
   36.18 +
   36.19 +/* Private subobject */
   36.20 +
   36.21 +typedef struct {
   36.22 +  struct jpeg_color_deconverter pub; /* public fields */
   36.23 +
   36.24 +  /* Private state for YCC->RGB conversion */
   36.25 +  int * Cr_r_tab;		/* => table for Cr to R conversion */
   36.26 +  int * Cb_b_tab;		/* => table for Cb to B conversion */
   36.27 +  INT32 * Cr_g_tab;		/* => table for Cr to G conversion */
   36.28 +  INT32 * Cb_g_tab;		/* => table for Cb to G conversion */
   36.29 +} my_color_deconverter;
   36.30 +
   36.31 +typedef my_color_deconverter * my_cconvert_ptr;
   36.32 +
   36.33 +
   36.34 +/**************** YCbCr -> RGB conversion: most common case **************/
   36.35 +
   36.36 +/*
   36.37 + * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
   36.38 + * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
   36.39 + * The conversion equations to be implemented are therefore
   36.40 + *	R = Y                + 1.40200 * Cr
   36.41 + *	G = Y - 0.34414 * Cb - 0.71414 * Cr
   36.42 + *	B = Y + 1.77200 * Cb
   36.43 + * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
   36.44 + * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
   36.45 + *
   36.46 + * To avoid floating-point arithmetic, we represent the fractional constants
   36.47 + * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
   36.48 + * the products by 2^16, with appropriate rounding, to get the correct answer.
   36.49 + * Notice that Y, being an integral input, does not contribute any fraction
   36.50 + * so it need not participate in the rounding.
   36.51 + *
   36.52 + * For even more speed, we avoid doing any multiplications in the inner loop
   36.53 + * by precalculating the constants times Cb and Cr for all possible values.
   36.54 + * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
   36.55 + * for 12-bit samples it is still acceptable.  It's not very reasonable for
   36.56 + * 16-bit samples, but if you want lossless storage you shouldn't be changing
   36.57 + * colorspace anyway.
   36.58 + * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
   36.59 + * values for the G calculation are left scaled up, since we must add them
   36.60 + * together before rounding.
   36.61 + */
   36.62 +
   36.63 +#define SCALEBITS	16	/* speediest right-shift on some machines */
   36.64 +#define ONE_HALF	((INT32) 1 << (SCALEBITS-1))
   36.65 +#define FIX(x)		((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
   36.66 +
   36.67 +
   36.68 +/*
   36.69 + * Initialize tables for YCC->RGB colorspace conversion.
   36.70 + */
   36.71 +
   36.72 +LOCAL(void)
   36.73 +build_ycc_rgb_table (j_decompress_ptr cinfo)
   36.74 +{
   36.75 +  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
   36.76 +  int i;
   36.77 +  INT32 x;
   36.78 +  SHIFT_TEMPS
   36.79 +
   36.80 +  cconvert->Cr_r_tab = (int *)
   36.81 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
   36.82 +				(MAXJSAMPLE+1) * SIZEOF(int));
   36.83 +  cconvert->Cb_b_tab = (int *)
   36.84 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
   36.85 +				(MAXJSAMPLE+1) * SIZEOF(int));
   36.86 +  cconvert->Cr_g_tab = (INT32 *)
   36.87 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
   36.88 +				(MAXJSAMPLE+1) * SIZEOF(INT32));
   36.89 +  cconvert->Cb_g_tab = (INT32 *)
   36.90 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
   36.91 +				(MAXJSAMPLE+1) * SIZEOF(INT32));
   36.92 +
   36.93 +  for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
   36.94 +    /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
   36.95 +    /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
   36.96 +    /* Cr=>R value is nearest int to 1.40200 * x */
   36.97 +    cconvert->Cr_r_tab[i] = (int)
   36.98 +		    RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
   36.99 +    /* Cb=>B value is nearest int to 1.77200 * x */
  36.100 +    cconvert->Cb_b_tab[i] = (int)
  36.101 +		    RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  36.102 +    /* Cr=>G value is scaled-up -0.71414 * x */
  36.103 +    cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  36.104 +    /* Cb=>G value is scaled-up -0.34414 * x */
  36.105 +    /* We also add in ONE_HALF so that need not do it in inner loop */
  36.106 +    cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  36.107 +  }
  36.108 +}
  36.109 +
  36.110 +
  36.111 +/*
  36.112 + * Convert some rows of samples to the output colorspace.
  36.113 + *
  36.114 + * Note that we change from noninterleaved, one-plane-per-component format
  36.115 + * to interleaved-pixel format.  The output buffer is therefore three times
  36.116 + * as wide as the input buffer.
  36.117 + * A starting row offset is provided only for the input buffer.  The caller
  36.118 + * can easily adjust the passed output_buf value to accommodate any row
  36.119 + * offset required on that side.
  36.120 + */
  36.121 +
  36.122 +METHODDEF(void)
  36.123 +ycc_rgb_convert (j_decompress_ptr cinfo,
  36.124 +		 JSAMPIMAGE input_buf, JDIMENSION input_row,
  36.125 +		 JSAMPARRAY output_buf, int num_rows)
  36.126 +{
  36.127 +  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  36.128 +  register int y, cb, cr;
  36.129 +  register JSAMPROW outptr;
  36.130 +  register JSAMPROW inptr0, inptr1, inptr2;
  36.131 +  register JDIMENSION col;
  36.132 +  JDIMENSION num_cols = cinfo->output_width;
  36.133 +  /* copy these pointers into registers if possible */
  36.134 +  register JSAMPLE * range_limit = cinfo->sample_range_limit;
  36.135 +  register int * Crrtab = cconvert->Cr_r_tab;
  36.136 +  register int * Cbbtab = cconvert->Cb_b_tab;
  36.137 +  register INT32 * Crgtab = cconvert->Cr_g_tab;
  36.138 +  register INT32 * Cbgtab = cconvert->Cb_g_tab;
  36.139 +  SHIFT_TEMPS
  36.140 +
  36.141 +  while (--num_rows >= 0) {
  36.142 +    inptr0 = input_buf[0][input_row];
  36.143 +    inptr1 = input_buf[1][input_row];
  36.144 +    inptr2 = input_buf[2][input_row];
  36.145 +    input_row++;
  36.146 +    outptr = *output_buf++;
  36.147 +    for (col = 0; col < num_cols; col++) {
  36.148 +      y  = GETJSAMPLE(inptr0[col]);
  36.149 +      cb = GETJSAMPLE(inptr1[col]);
  36.150 +      cr = GETJSAMPLE(inptr2[col]);
  36.151 +      /* Range-limiting is essential due to noise introduced by DCT losses. */
  36.152 +      outptr[RGB_RED] =   range_limit[y + Crrtab[cr]];
  36.153 +      outptr[RGB_GREEN] = range_limit[y +
  36.154 +			      ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  36.155 +						 SCALEBITS))];
  36.156 +      outptr[RGB_BLUE] =  range_limit[y + Cbbtab[cb]];
  36.157 +      outptr += RGB_PIXELSIZE;
  36.158 +    }
  36.159 +  }
  36.160 +}
  36.161 +
  36.162 +
  36.163 +/**************** Cases other than YCbCr -> RGB **************/
  36.164 +
  36.165 +
  36.166 +/*
  36.167 + * Color conversion for no colorspace change: just copy the data,
  36.168 + * converting from separate-planes to interleaved representation.
  36.169 + */
  36.170 +
  36.171 +METHODDEF(void)
  36.172 +null_convert (j_decompress_ptr cinfo,
  36.173 +	      JSAMPIMAGE input_buf, JDIMENSION input_row,
  36.174 +	      JSAMPARRAY output_buf, int num_rows)
  36.175 +{
  36.176 +  register JSAMPROW inptr, outptr;
  36.177 +  register JDIMENSION count;
  36.178 +  register int num_components = cinfo->num_components;
  36.179 +  JDIMENSION num_cols = cinfo->output_width;
  36.180 +  int ci;
  36.181 +
  36.182 +  while (--num_rows >= 0) {
  36.183 +    for (ci = 0; ci < num_components; ci++) {
  36.184 +      inptr = input_buf[ci][input_row];
  36.185 +      outptr = output_buf[0] + ci;
  36.186 +      for (count = num_cols; count > 0; count--) {
  36.187 +	*outptr = *inptr++;	/* needn't bother with GETJSAMPLE() here */
  36.188 +	outptr += num_components;
  36.189 +      }
  36.190 +    }
  36.191 +    input_row++;
  36.192 +    output_buf++;
  36.193 +  }
  36.194 +}
  36.195 +
  36.196 +
  36.197 +/*
  36.198 + * Color conversion for grayscale: just copy the data.
  36.199 + * This also works for YCbCr -> grayscale conversion, in which
  36.200 + * we just copy the Y (luminance) component and ignore chrominance.
  36.201 + */
  36.202 +
  36.203 +METHODDEF(void)
  36.204 +grayscale_convert (j_decompress_ptr cinfo,
  36.205 +		   JSAMPIMAGE input_buf, JDIMENSION input_row,
  36.206 +		   JSAMPARRAY output_buf, int num_rows)
  36.207 +{
  36.208 +  jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  36.209 +		    num_rows, cinfo->output_width);
  36.210 +}
  36.211 +
  36.212 +
  36.213 +/*
  36.214 + * Convert grayscale to RGB: just duplicate the graylevel three times.
  36.215 + * This is provided to support applications that don't want to cope
  36.216 + * with grayscale as a separate case.
  36.217 + */
  36.218 +
  36.219 +METHODDEF(void)
  36.220 +gray_rgb_convert (j_decompress_ptr cinfo,
  36.221 +		  JSAMPIMAGE input_buf, JDIMENSION input_row,
  36.222 +		  JSAMPARRAY output_buf, int num_rows)
  36.223 +{
  36.224 +  register JSAMPROW inptr, outptr;
  36.225 +  register JDIMENSION col;
  36.226 +  JDIMENSION num_cols = cinfo->output_width;
  36.227 +
  36.228 +  while (--num_rows >= 0) {
  36.229 +    inptr = input_buf[0][input_row++];
  36.230 +    outptr = *output_buf++;
  36.231 +    for (col = 0; col < num_cols; col++) {
  36.232 +      /* We can dispense with GETJSAMPLE() here */
  36.233 +      outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  36.234 +      outptr += RGB_PIXELSIZE;
  36.235 +    }
  36.236 +  }
  36.237 +}
  36.238 +
  36.239 +
  36.240 +/*
  36.241 + * Adobe-style YCCK->CMYK conversion.
  36.242 + * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  36.243 + * conversion as above, while passing K (black) unchanged.
  36.244 + * We assume build_ycc_rgb_table has been called.
  36.245 + */
  36.246 +
  36.247 +METHODDEF(void)
  36.248 +ycck_cmyk_convert (j_decompress_ptr cinfo,
  36.249 +		   JSAMPIMAGE input_buf, JDIMENSION input_row,
  36.250 +		   JSAMPARRAY output_buf, int num_rows)
  36.251 +{
  36.252 +  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  36.253 +  register int y, cb, cr;
  36.254 +  register JSAMPROW outptr;
  36.255 +  register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  36.256 +  register JDIMENSION col;
  36.257 +  JDIMENSION num_cols = cinfo->output_width;
  36.258 +  /* copy these pointers into registers if possible */
  36.259 +  register JSAMPLE * range_limit = cinfo->sample_range_limit;
  36.260 +  register int * Crrtab = cconvert->Cr_r_tab;
  36.261 +  register int * Cbbtab = cconvert->Cb_b_tab;
  36.262 +  register INT32 * Crgtab = cconvert->Cr_g_tab;
  36.263 +  register INT32 * Cbgtab = cconvert->Cb_g_tab;
  36.264 +  SHIFT_TEMPS
  36.265 +
  36.266 +  while (--num_rows >= 0) {
  36.267 +    inptr0 = input_buf[0][input_row];
  36.268 +    inptr1 = input_buf[1][input_row];
  36.269 +    inptr2 = input_buf[2][input_row];
  36.270 +    inptr3 = input_buf[3][input_row];
  36.271 +    input_row++;
  36.272 +    outptr = *output_buf++;
  36.273 +    for (col = 0; col < num_cols; col++) {
  36.274 +      y  = GETJSAMPLE(inptr0[col]);
  36.275 +      cb = GETJSAMPLE(inptr1[col]);
  36.276 +      cr = GETJSAMPLE(inptr2[col]);
  36.277 +      /* Range-limiting is essential due to noise introduced by DCT losses. */
  36.278 +      outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])];	/* red */
  36.279 +      outptr[1] = range_limit[MAXJSAMPLE - (y +			/* green */
  36.280 +			      ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  36.281 +						 SCALEBITS)))];
  36.282 +      outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])];	/* blue */
  36.283 +      /* K passes through unchanged */
  36.284 +      outptr[3] = inptr3[col];	/* don't need GETJSAMPLE here */
  36.285 +      outptr += 4;
  36.286 +    }
  36.287 +  }
  36.288 +}
  36.289 +
  36.290 +
  36.291 +/*
  36.292 + * Empty method for start_pass.
  36.293 + */
  36.294 +
  36.295 +METHODDEF(void)
  36.296 +start_pass_dcolor (j_decompress_ptr cinfo)
  36.297 +{
  36.298 +  /* no work needed */
  36.299 +}
  36.300 +
  36.301 +
  36.302 +/*
  36.303 + * Module initialization routine for output colorspace conversion.
  36.304 + */
  36.305 +
  36.306 +GLOBAL(void)
  36.307 +jinit_color_deconverter (j_decompress_ptr cinfo)
  36.308 +{
  36.309 +  my_cconvert_ptr cconvert;
  36.310 +  int ci;
  36.311 +
  36.312 +  cconvert = (my_cconvert_ptr)
  36.313 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  36.314 +				SIZEOF(my_color_deconverter));
  36.315 +  cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  36.316 +  cconvert->pub.start_pass = start_pass_dcolor;
  36.317 +
  36.318 +  /* Make sure num_components agrees with jpeg_color_space */
  36.319 +  switch (cinfo->jpeg_color_space) {
  36.320 +  case JCS_GRAYSCALE:
  36.321 +    if (cinfo->num_components != 1)
  36.322 +      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  36.323 +    break;
  36.324 +
  36.325 +  case JCS_RGB:
  36.326 +  case JCS_YCbCr:
  36.327 +    if (cinfo->num_components != 3)
  36.328 +      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  36.329 +    break;
  36.330 +
  36.331 +  case JCS_CMYK:
  36.332 +  case JCS_YCCK:
  36.333 +    if (cinfo->num_components != 4)
  36.334 +      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  36.335 +    break;
  36.336 +
  36.337 +  default:			/* JCS_UNKNOWN can be anything */
  36.338 +    if (cinfo->num_components < 1)
  36.339 +      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  36.340 +    break;
  36.341 +  }
  36.342 +
  36.343 +  /* Set out_color_components and conversion method based on requested space.
  36.344 +   * Also clear the component_needed flags for any unused components,
  36.345 +   * so that earlier pipeline stages can avoid useless computation.
  36.346 +   */
  36.347 +
  36.348 +  switch (cinfo->out_color_space) {
  36.349 +  case JCS_GRAYSCALE:
  36.350 +    cinfo->out_color_components = 1;
  36.351 +    if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  36.352 +	cinfo->jpeg_color_space == JCS_YCbCr) {
  36.353 +      cconvert->pub.color_convert = grayscale_convert;
  36.354 +      /* For color->grayscale conversion, only the Y (0) component is needed */
  36.355 +      for (ci = 1; ci < cinfo->num_components; ci++)
  36.356 +	cinfo->comp_info[ci].component_needed = FALSE;
  36.357 +    } else
  36.358 +      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  36.359 +    break;
  36.360 +
  36.361 +  case JCS_RGB:
  36.362 +    cinfo->out_color_components = RGB_PIXELSIZE;
  36.363 +    if (cinfo->jpeg_color_space == JCS_YCbCr) {
  36.364 +      cconvert->pub.color_convert = ycc_rgb_convert;
  36.365 +      build_ycc_rgb_table(cinfo);
  36.366 +    } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  36.367 +      cconvert->pub.color_convert = gray_rgb_convert;
  36.368 +    } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  36.369 +      cconvert->pub.color_convert = null_convert;
  36.370 +    } else
  36.371 +      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  36.372 +    break;
  36.373 +
  36.374 +  case JCS_CMYK:
  36.375 +    cinfo->out_color_components = 4;
  36.376 +    if (cinfo->jpeg_color_space == JCS_YCCK) {
  36.377 +      cconvert->pub.color_convert = ycck_cmyk_convert;
  36.378 +      build_ycc_rgb_table(cinfo);
  36.379 +    } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  36.380 +      cconvert->pub.color_convert = null_convert;
  36.381 +    } else
  36.382 +      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  36.383 +    break;
  36.384 +
  36.385 +  default:
  36.386 +    /* Permit null conversion to same output space */
  36.387 +    if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  36.388 +      cinfo->out_color_components = cinfo->num_components;
  36.389 +      cconvert->pub.color_convert = null_convert;
  36.390 +    } else			/* unsupported non-null conversion */
  36.391 +      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  36.392 +    break;
  36.393 +  }
  36.394 +
  36.395 +  if (cinfo->quantize_colors)
  36.396 +    cinfo->output_components = 1; /* single colormapped output component */
  36.397 +  else
  36.398 +    cinfo->output_components = cinfo->out_color_components;
  36.399 +}
    37.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    37.2 +++ b/libs/libjpeg/jdct.h	Thu Sep 08 06:28:38 2011 +0300
    37.3 @@ -0,0 +1,176 @@
    37.4 +/*
    37.5 + * jdct.h
    37.6 + *
    37.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    37.8 + * This file is part of the Independent JPEG Group's software.
    37.9 + * For conditions of distribution and use, see the accompanying README file.
   37.10 + *
   37.11 + * This include file contains common declarations for the forward and
   37.12 + * inverse DCT modules.  These declarations are private to the DCT managers
   37.13 + * (jcdctmgr.c, jddctmgr.c) and the individual DCT algorithms.
   37.14 + * The individual DCT algorithms are kept in separate files to ease 
   37.15 + * machine-dependent tuning (e.g., assembly coding).
   37.16 + */
   37.17 +
   37.18 +
   37.19 +/*
   37.20 + * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
   37.21 + * the DCT is to be performed in-place in that buffer.  Type DCTELEM is int
   37.22 + * for 8-bit samples, INT32 for 12-bit samples.  (NOTE: Floating-point DCT
   37.23 + * implementations use an array of type FAST_FLOAT, instead.)
   37.24 + * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
   37.25 + * The DCT outputs are returned scaled up by a factor of 8; they therefore
   37.26 + * have a range of +-8K for 8-bit data, +-128K for 12-bit data.  This
   37.27 + * convention improves accuracy in integer implementations and saves some
   37.28 + * work in floating-point ones.
   37.29 + * Quantization of the output coefficients is done by jcdctmgr.c.
   37.30 + */
   37.31 +
   37.32 +#if BITS_IN_JSAMPLE == 8
   37.33 +typedef int DCTELEM;		/* 16 or 32 bits is fine */
   37.34 +#else
   37.35 +typedef INT32 DCTELEM;		/* must have 32 bits */
   37.36 +#endif
   37.37 +
   37.38 +typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
   37.39 +typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
   37.40 +
   37.41 +
   37.42 +/*
   37.43 + * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
   37.44 + * to an output sample array.  The routine must dequantize the input data as
   37.45 + * well as perform the IDCT; for dequantization, it uses the multiplier table
   37.46 + * pointed to by compptr->dct_table.  The output data is to be placed into the
   37.47 + * sample array starting at a specified column.  (Any row offset needed will
   37.48 + * be applied to the array pointer before it is passed to the IDCT code.)
   37.49 + * Note that the number of samples emitted by the IDCT routine is
   37.50 + * DCT_scaled_size * DCT_scaled_size.
   37.51 + */
   37.52 +
   37.53 +/* typedef inverse_DCT_method_ptr is declared in jpegint.h */
   37.54 +
   37.55 +/*
   37.56 + * Each IDCT routine has its own ideas about the best dct_table element type.
   37.57 + */
   37.58 +
   37.59 +typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
   37.60 +#if BITS_IN_JSAMPLE == 8
   37.61 +typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
   37.62 +#define IFAST_SCALE_BITS  2	/* fractional bits in scale factors */
   37.63 +#else
   37.64 +typedef INT32 IFAST_MULT_TYPE;	/* need 32 bits for scaled quantizers */
   37.65 +#define IFAST_SCALE_BITS  13	/* fractional bits in scale factors */
   37.66 +#endif
   37.67 +typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
   37.68 +
   37.69 +
   37.70 +/*
   37.71 + * Each IDCT routine is responsible for range-limiting its results and
   37.72 + * converting them to unsigned form (0..MAXJSAMPLE).  The raw outputs could
   37.73 + * be quite far out of range if the input data is corrupt, so a bulletproof
   37.74 + * range-limiting step is required.  We use a mask-and-table-lookup method
   37.75 + * to do the combined operations quickly.  See the comments with
   37.76 + * prepare_range_limit_table (in jdmaster.c) for more info.
   37.77 + */
   37.78 +
   37.79 +#define IDCT_range_limit(cinfo)  ((cinfo)->sample_range_limit + CENTERJSAMPLE)
   37.80 +
   37.81 +#define RANGE_MASK  (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
   37.82 +
   37.83 +
   37.84 +/* Short forms of external names for systems with brain-damaged linkers. */
   37.85 +
   37.86 +#ifdef NEED_SHORT_EXTERNAL_NAMES
   37.87 +#define jpeg_fdct_islow		jFDislow
   37.88 +#define jpeg_fdct_ifast		jFDifast
   37.89 +#define jpeg_fdct_float		jFDfloat
   37.90 +#define jpeg_idct_islow		jRDislow
   37.91 +#define jpeg_idct_ifast		jRDifast
   37.92 +#define jpeg_idct_float		jRDfloat
   37.93 +#define jpeg_idct_4x4		jRD4x4
   37.94 +#define jpeg_idct_2x2		jRD2x2
   37.95 +#define jpeg_idct_1x1		jRD1x1
   37.96 +#endif /* NEED_SHORT_EXTERNAL_NAMES */
   37.97 +
   37.98 +/* Extern declarations for the forward and inverse DCT routines. */
   37.99 +
  37.100 +EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  37.101 +EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  37.102 +EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  37.103 +
  37.104 +EXTERN(void) jpeg_idct_islow
  37.105 +    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  37.106 +	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  37.107 +EXTERN(void) jpeg_idct_ifast
  37.108 +    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  37.109 +	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  37.110 +EXTERN(void) jpeg_idct_float
  37.111 +    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  37.112 +	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  37.113 +EXTERN(void) jpeg_idct_4x4
  37.114 +    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  37.115 +	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  37.116 +EXTERN(void) jpeg_idct_2x2
  37.117 +    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  37.118 +	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  37.119 +EXTERN(void) jpeg_idct_1x1
  37.120 +    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  37.121 +	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  37.122 +
  37.123 +
  37.124 +/*
  37.125 + * Macros for handling fixed-point arithmetic; these are used by many
  37.126 + * but not all of the DCT/IDCT modules.
  37.127 + *
  37.128 + * All values are expected to be of type INT32.
  37.129 + * Fractional constants are scaled left by CONST_BITS bits.
  37.130 + * CONST_BITS is defined within each module using these macros,
  37.131 + * and may differ from one module to the next.
  37.132 + */
  37.133 +
  37.134 +#define ONE	((INT32) 1)
  37.135 +#define CONST_SCALE (ONE << CONST_BITS)
  37.136 +
  37.137 +/* Convert a positive real constant to an integer scaled by CONST_SCALE.
  37.138 + * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  37.139 + * thus causing a lot of useless floating-point operations at run time.
  37.140 + */
  37.141 +
  37.142 +#define FIX(x)	((INT32) ((x) * CONST_SCALE + 0.5))
  37.143 +
  37.144 +/* Descale and correctly round an INT32 value that's scaled by N bits.
  37.145 + * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  37.146 + * the fudge factor is correct for either sign of X.
  37.147 + */
  37.148 +
  37.149 +#define DESCALE(x,n)  RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  37.150 +
  37.151 +/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  37.152 + * This macro is used only when the two inputs will actually be no more than
  37.153 + * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  37.154 + * full 32x32 multiply.  This provides a useful speedup on many machines.
  37.155 + * Unfortunately there is no way to specify a 16x16->32 multiply portably
  37.156 + * in C, but some C compilers will do the right thing if you provide the
  37.157 + * correct combination of casts.
  37.158 + */
  37.159 +
  37.160 +#ifdef SHORTxSHORT_32		/* may work if 'int' is 32 bits */
  37.161 +#define MULTIPLY16C16(var,const)  (((INT16) (var)) * ((INT16) (const)))
  37.162 +#endif
  37.163 +#ifdef SHORTxLCONST_32		/* known to work with Microsoft C 6.0 */
  37.164 +#define MULTIPLY16C16(var,const)  (((INT16) (var)) * ((INT32) (const)))
  37.165 +#endif
  37.166 +
  37.167 +#ifndef MULTIPLY16C16		/* default definition */
  37.168 +#define MULTIPLY16C16(var,const)  ((var) * (const))
  37.169 +#endif
  37.170 +
  37.171 +/* Same except both inputs are variables. */
  37.172 +
  37.173 +#ifdef SHORTxSHORT_32		/* may work if 'int' is 32 bits */
  37.174 +#define MULTIPLY16V16(var1,var2)  (((INT16) (var1)) * ((INT16) (var2)))
  37.175 +#endif
  37.176 +
  37.177 +#ifndef MULTIPLY16V16		/* default definition */
  37.178 +#define MULTIPLY16V16(var1,var2)  ((var1) * (var2))
  37.179 +#endif
    38.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    38.2 +++ b/libs/libjpeg/jddctmgr.c	Thu Sep 08 06:28:38 2011 +0300
    38.3 @@ -0,0 +1,269 @@
    38.4 +/*
    38.5 + * jddctmgr.c
    38.6 + *
    38.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    38.8 + * This file is part of the Independent JPEG Group's software.
    38.9 + * For conditions of distribution and use, see the accompanying README file.
   38.10 + *
   38.11 + * This file contains the inverse-DCT management logic.
   38.12 + * This code selects a particular IDCT implementation to be used,
   38.13 + * and it performs related housekeeping chores.  No code in this file
   38.14 + * is executed per IDCT step, only during output pass setup.
   38.15 + *
   38.16 + * Note that the IDCT routines are responsible for performing coefficient
   38.17 + * dequantization as well as the IDCT proper.  This module sets up the
   38.18 + * dequantization multiplier table needed by the IDCT routine.
   38.19 + */
   38.20 +
   38.21 +#define JPEG_INTERNALS
   38.22 +#include "jinclude.h"
   38.23 +#include "jpeglib.h"
   38.24 +#include "jdct.h"		/* Private declarations for DCT subsystem */
   38.25 +
   38.26 +
   38.27 +/*
   38.28 + * The decompressor input side (jdinput.c) saves away the appropriate
   38.29 + * quantization table for each component at the start of the first scan
   38.30 + * involving that component.  (This is necessary in order to correctly
   38.31 + * decode files that reuse Q-table slots.)
   38.32 + * When we are ready to make an output pass, the saved Q-table is converted
   38.33 + * to a multiplier table that will actually be used by the IDCT routine.
   38.34 + * The multiplier table contents are IDCT-method-dependent.  To support
   38.35 + * application changes in IDCT method between scans, we can remake the
   38.36 + * multiplier tables if necessary.
   38.37 + * In buffered-image mode, the first output pass may occur before any data
   38.38 + * has been seen for some components, and thus before their Q-tables have
   38.39 + * been saved away.  To handle this case, multiplier tables are preset
   38.40 + * to zeroes; the result of the IDCT will be a neutral gray level.
   38.41 + */
   38.42 +
   38.43 +
   38.44 +/* Private subobject for this module */
   38.45 +
   38.46 +typedef struct {
   38.47 +  struct jpeg_inverse_dct pub;	/* public fields */
   38.48 +
   38.49 +  /* This array contains the IDCT method code that each multiplier table
   38.50 +   * is currently set up for, or -1 if it's not yet set up.
   38.51 +   * The actual multiplier tables are pointed to by dct_table in the
   38.52 +   * per-component comp_info structures.
   38.53 +   */
   38.54 +  int cur_method[MAX_COMPONENTS];
   38.55 +} my_idct_controller;
   38.56 +
   38.57 +typedef my_idct_controller * my_idct_ptr;
   38.58 +
   38.59 +
   38.60 +/* Allocated multiplier tables: big enough for any supported variant */
   38.61 +
   38.62 +typedef union {
   38.63 +  ISLOW_MULT_TYPE islow_array[DCTSIZE2];
   38.64 +#ifdef DCT_IFAST_SUPPORTED
   38.65 +  IFAST_MULT_TYPE ifast_array[DCTSIZE2];
   38.66 +#endif
   38.67 +#ifdef DCT_FLOAT_SUPPORTED
   38.68 +  FLOAT_MULT_TYPE float_array[DCTSIZE2];
   38.69 +#endif
   38.70 +} multiplier_table;
   38.71 +
   38.72 +
   38.73 +/* The current scaled-IDCT routines require ISLOW-style multiplier tables,
   38.74 + * so be sure to compile that code if either ISLOW or SCALING is requested.
   38.75 + */
   38.76 +#ifdef DCT_ISLOW_SUPPORTED
   38.77 +#define PROVIDE_ISLOW_TABLES
   38.78 +#else
   38.79 +#ifdef IDCT_SCALING_SUPPORTED
   38.80 +#define PROVIDE_ISLOW_TABLES
   38.81 +#endif
   38.82 +#endif
   38.83 +
   38.84 +
   38.85 +/*
   38.86 + * Prepare for an output pass.
   38.87 + * Here we select the proper IDCT routine for each component and build
   38.88 + * a matching multiplier table.
   38.89 + */
   38.90 +
   38.91 +METHODDEF(void)
   38.92 +start_pass (j_decompress_ptr cinfo)
   38.93 +{
   38.94 +  my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
   38.95 +  int ci, i;
   38.96 +  jpeg_component_info *compptr;
   38.97 +  int method = 0;
   38.98 +  inverse_DCT_method_ptr method_ptr = NULL;
   38.99 +  JQUANT_TBL * qtbl;
  38.100 +
  38.101 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  38.102 +       ci++, compptr++) {
  38.103 +    /* Select the proper IDCT routine for this component's scaling */
  38.104 +    switch (compptr->DCT_scaled_size) {
  38.105 +#ifdef IDCT_SCALING_SUPPORTED
  38.106 +    case 1:
  38.107 +      method_ptr = jpeg_idct_1x1;
  38.108 +      method = JDCT_ISLOW;	/* jidctred uses islow-style table */
  38.109 +      break;
  38.110 +    case 2:
  38.111 +      method_ptr = jpeg_idct_2x2;
  38.112 +      method = JDCT_ISLOW;	/* jidctred uses islow-style table */
  38.113 +      break;
  38.114 +    case 4:
  38.115 +      method_ptr = jpeg_idct_4x4;
  38.116 +      method = JDCT_ISLOW;	/* jidctred uses islow-style table */
  38.117 +      break;
  38.118 +#endif
  38.119 +    case DCTSIZE:
  38.120 +      switch (cinfo->dct_method) {
  38.121 +#ifdef DCT_ISLOW_SUPPORTED
  38.122 +      case JDCT_ISLOW:
  38.123 +	method_ptr = jpeg_idct_islow;
  38.124 +	method = JDCT_ISLOW;
  38.125 +	break;
  38.126 +#endif
  38.127 +#ifdef DCT_IFAST_SUPPORTED
  38.128 +      case JDCT_IFAST:
  38.129 +	method_ptr = jpeg_idct_ifast;
  38.130 +	method = JDCT_IFAST;
  38.131 +	break;
  38.132 +#endif
  38.133 +#ifdef DCT_FLOAT_SUPPORTED
  38.134 +      case JDCT_FLOAT:
  38.135 +	method_ptr = jpeg_idct_float;
  38.136 +	method = JDCT_FLOAT;
  38.137 +	break;
  38.138 +#endif
  38.139 +      default:
  38.140 +	ERREXIT(cinfo, JERR_NOT_COMPILED);
  38.141 +	break;
  38.142 +      }
  38.143 +      break;
  38.144 +    default:
  38.145 +      ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  38.146 +      break;
  38.147 +    }
  38.148 +    idct->pub.inverse_DCT[ci] = method_ptr;
  38.149 +    /* Create multiplier table from quant table.
  38.150 +     * However, we can skip this if the component is uninteresting
  38.151 +     * or if we already built the table.  Also, if no quant table
  38.152 +     * has yet been saved for the component, we leave the
  38.153 +     * multiplier table all-zero; we'll be reading zeroes from the
  38.154 +     * coefficient controller's buffer anyway.
  38.155 +     */
  38.156 +    if (! compptr->component_needed || idct->cur_method[ci] == method)
  38.157 +      continue;
  38.158 +    qtbl = compptr->quant_table;
  38.159 +    if (qtbl == NULL)		/* happens if no data yet for component */
  38.160 +      continue;
  38.161 +    idct->cur_method[ci] = method;
  38.162 +    switch (method) {
  38.163 +#ifdef PROVIDE_ISLOW_TABLES
  38.164 +    case JDCT_ISLOW:
  38.165 +      {
  38.166 +	/* For LL&M IDCT method, multipliers are equal to raw quantization
  38.167 +	 * coefficients, but are stored as ints to ensure access efficiency.
  38.168 +	 */
  38.169 +	ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  38.170 +	for (i = 0; i < DCTSIZE2; i++) {
  38.171 +	  ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  38.172 +	}
  38.173 +      }
  38.174 +      break;
  38.175 +#endif
  38.176 +#ifdef DCT_IFAST_SUPPORTED
  38.177 +    case JDCT_IFAST:
  38.178 +      {
  38.179 +	/* For AA&N IDCT method, multipliers are equal to quantization
  38.180 +	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
  38.181 +	 *   scalefactor[0] = 1
  38.182 +	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
  38.183 +	 * For integer operation, the multiplier table is to be scaled by
  38.184 +	 * IFAST_SCALE_BITS.
  38.185 +	 */
  38.186 +	IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  38.187 +#define CONST_BITS 14
  38.188 +	static const INT16 aanscales[DCTSIZE2] = {
  38.189 +	  /* precomputed values scaled up by 14 bits */
  38.190 +	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
  38.191 +	  22725, 31521, 29692, 26722, 22725, 17855, 12299,  6270,
  38.192 +	  21407, 29692, 27969, 25172, 21407, 16819, 11585,  5906,
  38.193 +	  19266, 26722, 25172, 22654, 19266, 15137, 10426,  5315,
  38.194 +	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
  38.195 +	  12873, 17855, 16819, 15137, 12873, 10114,  6967,  3552,
  38.196 +	   8867, 12299, 11585, 10426,  8867,  6967,  4799,  2446,
  38.197 +	   4520,  6270,  5906,  5315,  4520,  3552,  2446,  1247
  38.198 +	};
  38.199 +	SHIFT_TEMPS
  38.200 +
  38.201 +	for (i = 0; i < DCTSIZE2; i++) {
  38.202 +	  ifmtbl[i] = (IFAST_MULT_TYPE)
  38.203 +	    DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  38.204 +				  (INT32) aanscales[i]),
  38.205 +		    CONST_BITS-IFAST_SCALE_BITS);
  38.206 +	}
  38.207 +      }
  38.208 +      break;
  38.209 +#endif
  38.210 +#ifdef DCT_FLOAT_SUPPORTED
  38.211 +    case JDCT_FLOAT:
  38.212 +      {
  38.213 +	/* For float AA&N IDCT method, multipliers are equal to quantization
  38.214 +	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
  38.215 +	 *   scalefactor[0] = 1
  38.216 +	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
  38.217 +	 */
  38.218 +	FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  38.219 +	int row, col;
  38.220 +	static const double aanscalefactor[DCTSIZE] = {
  38.221 +	  1.0, 1.387039845, 1.306562965, 1.175875602,
  38.222 +	  1.0, 0.785694958, 0.541196100, 0.275899379
  38.223 +	};
  38.224 +
  38.225 +	i = 0;
  38.226 +	for (row = 0; row < DCTSIZE; row++) {
  38.227 +	  for (col = 0; col < DCTSIZE; col++) {
  38.228 +	    fmtbl[i] = (FLOAT_MULT_TYPE)
  38.229 +	      ((double) qtbl->quantval[i] *
  38.230 +	       aanscalefactor[row] * aanscalefactor[col]);
  38.231 +	    i++;
  38.232 +	  }
  38.233 +	}
  38.234 +      }
  38.235 +      break;
  38.236 +#endif
  38.237 +    default:
  38.238 +      ERREXIT(cinfo, JERR_NOT_COMPILED);
  38.239 +      break;
  38.240 +    }
  38.241 +  }
  38.242 +}
  38.243 +
  38.244 +
  38.245 +/*
  38.246 + * Initialize IDCT manager.
  38.247 + */
  38.248 +
  38.249 +GLOBAL(void)
  38.250 +jinit_inverse_dct (j_decompress_ptr cinfo)
  38.251 +{
  38.252 +  my_idct_ptr idct;
  38.253 +  int ci;
  38.254 +  jpeg_component_info *compptr;
  38.255 +
  38.256 +  idct = (my_idct_ptr)
  38.257 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  38.258 +				SIZEOF(my_idct_controller));
  38.259 +  cinfo->idct = (struct jpeg_inverse_dct *) idct;
  38.260 +  idct->pub.start_pass = start_pass;
  38.261 +
  38.262 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  38.263 +       ci++, compptr++) {
  38.264 +    /* Allocate and pre-zero a multiplier table for each component */
  38.265 +    compptr->dct_table =
  38.266 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  38.267 +				  SIZEOF(multiplier_table));
  38.268 +    MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  38.269 +    /* Mark multiplier table not yet set up for any method */
  38.270 +    idct->cur_method[ci] = -1;
  38.271 +  }
  38.272 +}
    39.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    39.2 +++ b/libs/libjpeg/jdhuff.c	Thu Sep 08 06:28:38 2011 +0300
    39.3 @@ -0,0 +1,651 @@
    39.4 +/*
    39.5 + * jdhuff.c
    39.6 + *
    39.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    39.8 + * This file is part of the Independent JPEG Group's software.
    39.9 + * For conditions of distribution and use, see the accompanying README file.
   39.10 + *
   39.11 + * This file contains Huffman entropy decoding routines.
   39.12 + *
   39.13 + * Much of the complexity here has to do with supporting input suspension.
   39.14 + * If the data source module demands suspension, we want to be able to back
   39.15 + * up to the start of the current MCU.  To do this, we copy state variables
   39.16 + * into local working storage, and update them back to the permanent
   39.17 + * storage only upon successful completion of an MCU.
   39.18 + */
   39.19 +
   39.20 +#define JPEG_INTERNALS
   39.21 +#include "jinclude.h"
   39.22 +#include "jpeglib.h"
   39.23 +#include "jdhuff.h"		/* Declarations shared with jdphuff.c */
   39.24 +
   39.25 +
   39.26 +/*
   39.27 + * Expanded entropy decoder object for Huffman decoding.
   39.28 + *
   39.29 + * The savable_state subrecord contains fields that change within an MCU,
   39.30 + * but must not be updated permanently until we complete the MCU.
   39.31 + */
   39.32 +
   39.33 +typedef struct {
   39.34 +  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
   39.35 +} savable_state;
   39.36 +
   39.37 +/* This macro is to work around compilers with missing or broken
   39.38 + * structure assignment.  You'll need to fix this code if you have
   39.39 + * such a compiler and you change MAX_COMPS_IN_SCAN.
   39.40 + */
   39.41 +
   39.42 +#ifndef NO_STRUCT_ASSIGN
   39.43 +#define ASSIGN_STATE(dest,src)  ((dest) = (src))
   39.44 +#else
   39.45 +#if MAX_COMPS_IN_SCAN == 4
   39.46 +#define ASSIGN_STATE(dest,src)  \
   39.47 +	((dest).last_dc_val[0] = (src).last_dc_val[0], \
   39.48 +	 (dest).last_dc_val[1] = (src).last_dc_val[1], \
   39.49 +	 (dest).last_dc_val[2] = (src).last_dc_val[2], \
   39.50 +	 (dest).last_dc_val[3] = (src).last_dc_val[3])
   39.51 +#endif
   39.52 +#endif
   39.53 +
   39.54 +
   39.55 +typedef struct {
   39.56 +  struct jpeg_entropy_decoder pub; /* public fields */
   39.57 +
   39.58 +  /* These fields are loaded into local variables at start of each MCU.
   39.59 +   * In case of suspension, we exit WITHOUT updating them.
   39.60 +   */
   39.61 +  bitread_perm_state bitstate;	/* Bit buffer at start of MCU */
   39.62 +  savable_state saved;		/* Other state at start of MCU */
   39.63 +
   39.64 +  /* These fields are NOT loaded into local working state. */
   39.65 +  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
   39.66 +
   39.67 +  /* Pointers to derived tables (these workspaces have image lifespan) */
   39.68 +  d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
   39.69 +  d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
   39.70 +
   39.71 +  /* Precalculated info set up by start_pass for use in decode_mcu: */
   39.72 +
   39.73 +  /* Pointers to derived tables to be used for each block within an MCU */
   39.74 +  d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
   39.75 +  d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
   39.76 +  /* Whether we care about the DC and AC coefficient values for each block */
   39.77 +  boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
   39.78 +  boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
   39.79 +} huff_entropy_decoder;
   39.80 +
   39.81 +typedef huff_entropy_decoder * huff_entropy_ptr;
   39.82 +
   39.83 +
   39.84 +/*
   39.85 + * Initialize for a Huffman-compressed scan.
   39.86 + */
   39.87 +
   39.88 +METHODDEF(void)
   39.89 +start_pass_huff_decoder (j_decompress_ptr cinfo)
   39.90 +{
   39.91 +  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
   39.92 +  int ci, blkn, dctbl, actbl;
   39.93 +  jpeg_component_info * compptr;
   39.94 +
   39.95 +  /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
   39.96 +   * This ought to be an error condition, but we make it a warning because
   39.97 +   * there are some baseline files out there with all zeroes in these bytes.
   39.98 +   */
   39.99 +  if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  39.100 +      cinfo->Ah != 0 || cinfo->Al != 0)
  39.101 +    WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  39.102 +
  39.103 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  39.104 +    compptr = cinfo->cur_comp_info[ci];
  39.105 +    dctbl = compptr->dc_tbl_no;
  39.106 +    actbl = compptr->ac_tbl_no;
  39.107 +    /* Compute derived values for Huffman tables */
  39.108 +    /* We may do this more than once for a table, but it's not expensive */
  39.109 +    jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  39.110 +			    & entropy->dc_derived_tbls[dctbl]);
  39.111 +    jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  39.112 +			    & entropy->ac_derived_tbls[actbl]);
  39.113 +    /* Initialize DC predictions to 0 */
  39.114 +    entropy->saved.last_dc_val[ci] = 0;
  39.115 +  }
  39.116 +
  39.117 +  /* Precalculate decoding info for each block in an MCU of this scan */
  39.118 +  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  39.119 +    ci = cinfo->MCU_membership[blkn];
  39.120 +    compptr = cinfo->cur_comp_info[ci];
  39.121 +    /* Precalculate which table to use for each block */
  39.122 +    entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  39.123 +    entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  39.124 +    /* Decide whether we really care about the coefficient values */
  39.125 +    if (compptr->component_needed) {
  39.126 +      entropy->dc_needed[blkn] = TRUE;
  39.127 +      /* we don't need the ACs if producing a 1/8th-size image */
  39.128 +      entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  39.129 +    } else {
  39.130 +      entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  39.131 +    }
  39.132 +  }
  39.133 +
  39.134 +  /* Initialize bitread state variables */
  39.135 +  entropy->bitstate.bits_left = 0;
  39.136 +  entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  39.137 +  entropy->pub.insufficient_data = FALSE;
  39.138 +
  39.139 +  /* Initialize restart counter */
  39.140 +  entropy->restarts_to_go = cinfo->restart_interval;
  39.141 +}
  39.142 +
  39.143 +
  39.144 +/*
  39.145 + * Compute the derived values for a Huffman table.
  39.146 + * This routine also performs some validation checks on the table.
  39.147 + *
  39.148 + * Note this is also used by jdphuff.c.
  39.149 + */
  39.150 +
  39.151 +GLOBAL(void)
  39.152 +jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  39.153 +			 d_derived_tbl ** pdtbl)
  39.154 +{
  39.155 +  JHUFF_TBL *htbl;
  39.156 +  d_derived_tbl *dtbl;
  39.157 +  int p, i, l, si, numsymbols;
  39.158 +  int lookbits, ctr;
  39.159 +  char huffsize[257];
  39.160 +  unsigned int huffcode[257];
  39.161 +  unsigned int code;
  39.162 +
  39.163 +  /* Note that huffsize[] and huffcode[] are filled in code-length order,
  39.164 +   * paralleling the order of the symbols themselves in htbl->huffval[].
  39.165 +   */
  39.166 +
  39.167 +  /* Find the input Huffman table */
  39.168 +  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  39.169 +    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  39.170 +  htbl =
  39.171 +    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  39.172 +  if (htbl == NULL)
  39.173 +    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  39.174 +
  39.175 +  /* Allocate a workspace if we haven't already done so. */
  39.176 +  if (*pdtbl == NULL)
  39.177 +    *pdtbl = (d_derived_tbl *)
  39.178 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  39.179 +				  SIZEOF(d_derived_tbl));
  39.180 +  dtbl = *pdtbl;
  39.181 +  dtbl->pub = htbl;		/* fill in back link */
  39.182 +  
  39.183 +  /* Figure C.1: make table of Huffman code length for each symbol */
  39.184 +
  39.185 +  p = 0;
  39.186 +  for (l = 1; l <= 16; l++) {
  39.187 +    i = (int) htbl->bits[l];
  39.188 +    if (i < 0 || p + i > 256)	/* protect against table overrun */
  39.189 +      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  39.190 +    while (i--)
  39.191 +      huffsize[p++] = (char) l;
  39.192 +  }
  39.193 +  huffsize[p] = 0;
  39.194 +  numsymbols = p;
  39.195 +  
  39.196 +  /* Figure C.2: generate the codes themselves */
  39.197 +  /* We also validate that the counts represent a legal Huffman code tree. */
  39.198 +  
  39.199 +  code = 0;
  39.200 +  si = huffsize[0];
  39.201 +  p = 0;
  39.202 +  while (huffsize[p]) {
  39.203 +    while (((int) huffsize[p]) == si) {
  39.204 +      huffcode[p++] = code;
  39.205 +      code++;
  39.206 +    }
  39.207 +    /* code is now 1 more than the last code used for codelength si; but
  39.208 +     * it must still fit in si bits, since no code is allowed to be all ones.
  39.209 +     */
  39.210 +    if (((INT32) code) >= (((INT32) 1) << si))
  39.211 +      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  39.212 +    code <<= 1;
  39.213 +    si++;
  39.214 +  }
  39.215 +
  39.216 +  /* Figure F.15: generate decoding tables for bit-sequential decoding */
  39.217 +
  39.218 +  p = 0;
  39.219 +  for (l = 1; l <= 16; l++) {
  39.220 +    if (htbl->bits[l]) {
  39.221 +      /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  39.222 +       * minus the minimum code of length l
  39.223 +       */
  39.224 +      dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  39.225 +      p += htbl->bits[l];
  39.226 +      dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  39.227 +    } else {
  39.228 +      dtbl->maxcode[l] = -1;	/* -1 if no codes of this length */
  39.229 +    }
  39.230 +  }
  39.231 +  dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  39.232 +
  39.233 +  /* Compute lookahead tables to speed up decoding.
  39.234 +   * First we set all the table entries to 0, indicating "too long";
  39.235 +   * then we iterate through the Huffman codes that are short enough and
  39.236 +   * fill in all the entries that correspond to bit sequences starting
  39.237 +   * with that code.
  39.238 +   */
  39.239 +
  39.240 +  MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  39.241 +
  39.242 +  p = 0;
  39.243 +  for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  39.244 +    for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  39.245 +      /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  39.246 +      /* Generate left-justified code followed by all possible bit sequences */
  39.247 +      lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  39.248 +      for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  39.249 +	dtbl->look_nbits[lookbits] = l;
  39.250 +	dtbl->look_sym[lookbits] = htbl->huffval[p];
  39.251 +	lookbits++;
  39.252 +      }
  39.253 +    }
  39.254 +  }
  39.255 +
  39.256 +  /* Validate symbols as being reasonable.
  39.257 +   * For AC tables, we make no check, but accept all byte values 0..255.
  39.258 +   * For DC tables, we require the symbols to be in range 0..15.
  39.259 +   * (Tighter bounds could be applied depending on the data depth and mode,
  39.260 +   * but this is sufficient to ensure safe decoding.)
  39.261 +   */
  39.262 +  if (isDC) {
  39.263 +    for (i = 0; i < numsymbols; i++) {
  39.264 +      int sym = htbl->huffval[i];
  39.265 +      if (sym < 0 || sym > 15)
  39.266 +	ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  39.267 +    }
  39.268 +  }
  39.269 +}
  39.270 +
  39.271 +
  39.272 +/*
  39.273 + * Out-of-line code for bit fetching (shared with jdphuff.c).
  39.274 + * See jdhuff.h for info about usage.
  39.275 + * Note: current values of get_buffer and bits_left are passed as parameters,
  39.276 + * but are returned in the corresponding fields of the state struct.
  39.277 + *
  39.278 + * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  39.279 + * of get_buffer to be used.  (On machines with wider words, an even larger
  39.280 + * buffer could be used.)  However, on some machines 32-bit shifts are
  39.281 + * quite slow and take time proportional to the number of places shifted.
  39.282 + * (This is true with most PC compilers, for instance.)  In this case it may
  39.283 + * be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
  39.284 + * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  39.285 + */
  39.286 +
  39.287 +#ifdef SLOW_SHIFT_32
  39.288 +#define MIN_GET_BITS  15	/* minimum allowable value */
  39.289 +#else
  39.290 +#define MIN_GET_BITS  (BIT_BUF_SIZE-7)
  39.291 +#endif
  39.292 +
  39.293 +
  39.294 +GLOBAL(boolean)
  39.295 +jpeg_fill_bit_buffer (bitread_working_state * state,
  39.296 +		      register bit_buf_type get_buffer, register int bits_left,
  39.297 +		      int nbits)
  39.298 +/* Load up the bit buffer to a depth of at least nbits */
  39.299 +{
  39.300 +  /* Copy heavily used state fields into locals (hopefully registers) */
  39.301 +  register const JOCTET * next_input_byte = state->next_input_byte;
  39.302 +  register size_t bytes_in_buffer = state->bytes_in_buffer;
  39.303 +  j_decompress_ptr cinfo = state->cinfo;
  39.304 +
  39.305 +  /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  39.306 +  /* (It is assumed that no request will be for more than that many bits.) */
  39.307 +  /* We fail to do so only if we hit a marker or are forced to suspend. */
  39.308 +
  39.309 +  if (cinfo->unread_marker == 0) {	/* cannot advance past a marker */
  39.310 +    while (bits_left < MIN_GET_BITS) {
  39.311 +      register int c;
  39.312 +
  39.313 +      /* Attempt to read a byte */
  39.314 +      if (bytes_in_buffer == 0) {
  39.315 +	if (! (*cinfo->src->fill_input_buffer) (cinfo))
  39.316 +	  return FALSE;
  39.317 +	next_input_byte = cinfo->src->next_input_byte;
  39.318 +	bytes_in_buffer = cinfo->src->bytes_in_buffer;
  39.319 +      }
  39.320 +      bytes_in_buffer--;
  39.321 +      c = GETJOCTET(*next_input_byte++);
  39.322 +
  39.323 +      /* If it's 0xFF, check and discard stuffed zero byte */
  39.324 +      if (c == 0xFF) {
  39.325 +	/* Loop here to discard any padding FF's on terminating marker,
  39.326 +	 * so that we can save a valid unread_marker value.  NOTE: we will
  39.327 +	 * accept multiple FF's followed by a 0 as meaning a single FF data
  39.328 +	 * byte.  This data pattern is not valid according to the standard.
  39.329 +	 */
  39.330 +	do {
  39.331 +	  if (bytes_in_buffer == 0) {
  39.332 +	    if (! (*cinfo->src->fill_input_buffer) (cinfo))
  39.333 +	      return FALSE;
  39.334 +	    next_input_byte = cinfo->src->next_input_byte;
  39.335 +	    bytes_in_buffer = cinfo->src->bytes_in_buffer;
  39.336 +	  }
  39.337 +	  bytes_in_buffer--;
  39.338 +	  c = GETJOCTET(*next_input_byte++);
  39.339 +	} while (c == 0xFF);
  39.340 +
  39.341 +	if (c == 0) {
  39.342 +	  /* Found FF/00, which represents an FF data byte */
  39.343 +	  c = 0xFF;
  39.344 +	} else {
  39.345 +	  /* Oops, it's actually a marker indicating end of compressed data.
  39.346 +	   * Save the marker code for later use.
  39.347 +	   * Fine point: it might appear that we should save the marker into
  39.348 +	   * bitread working state, not straight into permanent state.  But
  39.349 +	   * once we have hit a marker, we cannot need to suspend within the
  39.350 +	   * current MCU, because we will read no more bytes from the data
  39.351 +	   * source.  So it is OK to update permanent state right away.
  39.352 +	   */
  39.353 +	  cinfo->unread_marker = c;
  39.354 +	  /* See if we need to insert some fake zero bits. */
  39.355 +	  goto no_more_bytes;
  39.356 +	}
  39.357 +      }
  39.358 +
  39.359 +      /* OK, load c into get_buffer */
  39.360 +      get_buffer = (get_buffer << 8) | c;
  39.361 +      bits_left += 8;
  39.362 +    } /* end while */
  39.363 +  } else {
  39.364 +  no_more_bytes:
  39.365 +    /* We get here if we've read the marker that terminates the compressed
  39.366 +     * data segment.  There should be enough bits in the buffer register
  39.367 +     * to satisfy the request; if so, no problem.
  39.368 +     */
  39.369 +    if (nbits > bits_left) {
  39.370 +      /* Uh-oh.  Report corrupted data to user and stuff zeroes into
  39.371 +       * the data stream, so that we can produce some kind of image.
  39.372 +       * We use a nonvolatile flag to ensure that only one warning message
  39.373 +       * appears per data segment.
  39.374 +       */
  39.375 +      if (! cinfo->entropy->insufficient_data) {
  39.376 +	WARNMS(cinfo, JWRN_HIT_MARKER);
  39.377 +	cinfo->entropy->insufficient_data = TRUE;
  39.378 +      }
  39.379 +      /* Fill the buffer with zero bits */
  39.380 +      get_buffer <<= MIN_GET_BITS - bits_left;
  39.381 +      bits_left = MIN_GET_BITS;
  39.382 +    }
  39.383 +  }
  39.384 +
  39.385 +  /* Unload the local registers */
  39.386 +  state->next_input_byte = next_input_byte;
  39.387 +  state->bytes_in_buffer = bytes_in_buffer;
  39.388 +  state->get_buffer = get_buffer;
  39.389 +  state->bits_left = bits_left;
  39.390 +
  39.391 +  return TRUE;
  39.392 +}
  39.393 +
  39.394 +
  39.395 +/*
  39.396 + * Out-of-line code for Huffman code decoding.
  39.397 + * See jdhuff.h for info about usage.
  39.398 + */
  39.399 +
  39.400 +GLOBAL(int)
  39.401 +jpeg_huff_decode (bitread_working_state * state,
  39.402 +		  register bit_buf_type get_buffer, register int bits_left,
  39.403 +		  d_derived_tbl * htbl, int min_bits)
  39.404 +{
  39.405 +  register int l = min_bits;
  39.406 +  register INT32 code;
  39.407 +
  39.408 +  /* HUFF_DECODE has determined that the code is at least min_bits */
  39.409 +  /* bits long, so fetch that many bits in one swoop. */
  39.410 +
  39.411 +  CHECK_BIT_BUFFER(*state, l, return -1);
  39.412 +  code = GET_BITS(l);
  39.413 +
  39.414 +  /* Collect the rest of the Huffman code one bit at a time. */
  39.415 +  /* This is per Figure F.16 in the JPEG spec. */
  39.416 +
  39.417 +  while (code > htbl->maxcode[l]) {
  39.418 +    code <<= 1;
  39.419 +    CHECK_BIT_BUFFER(*state, 1, return -1);
  39.420 +    code |= GET_BITS(1);
  39.421 +    l++;
  39.422 +  }
  39.423 +
  39.424 +  /* Unload the local registers */
  39.425 +  state->get_buffer = get_buffer;
  39.426 +  state->bits_left = bits_left;
  39.427 +
  39.428 +  /* With garbage input we may reach the sentinel value l = 17. */
  39.429 +
  39.430 +  if (l > 16) {
  39.431 +    WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  39.432 +    return 0;			/* fake a zero as the safest result */
  39.433 +  }
  39.434 +
  39.435 +  return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  39.436 +}
  39.437 +
  39.438 +
  39.439 +/*
  39.440 + * Figure F.12: extend sign bit.
  39.441 + * On some machines, a shift and add will be faster than a table lookup.
  39.442 + */
  39.443 +
  39.444 +#ifdef AVOID_TABLES
  39.445 +
  39.446 +#define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  39.447 +
  39.448 +#else
  39.449 +
  39.450 +#define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  39.451 +
  39.452 +static const int extend_test[16] =   /* entry n is 2**(n-1) */
  39.453 +  { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  39.454 +    0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  39.455 +
  39.456 +static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  39.457 +  { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  39.458 +    ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  39.459 +    ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  39.460 +    ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  39.461 +
  39.462 +#endif /* AVOID_TABLES */
  39.463 +
  39.464 +
  39.465 +/*
  39.466 + * Check for a restart marker & resynchronize decoder.
  39.467 + * Returns FALSE if must suspend.
  39.468 + */
  39.469 +
  39.470 +LOCAL(boolean)
  39.471 +process_restart (j_decompress_ptr cinfo)
  39.472 +{
  39.473 +  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  39.474 +  int ci;
  39.475 +
  39.476 +  /* Throw away any unused bits remaining in bit buffer; */
  39.477 +  /* include any full bytes in next_marker's count of discarded bytes */
  39.478 +  cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  39.479 +  entropy->bitstate.bits_left = 0;
  39.480 +
  39.481 +  /* Advance past the RSTn marker */
  39.482 +  if (! (*cinfo->marker->read_restart_marker) (cinfo))
  39.483 +    return FALSE;
  39.484 +
  39.485 +  /* Re-initialize DC predictions to 0 */
  39.486 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  39.487 +    entropy->saved.last_dc_val[ci] = 0;
  39.488 +
  39.489 +  /* Reset restart counter */
  39.490 +  entropy->restarts_to_go = cinfo->restart_interval;
  39.491 +
  39.492 +  /* Reset out-of-data flag, unless read_restart_marker left us smack up
  39.493 +   * against a marker.  In that case we will end up treating the next data
  39.494 +   * segment as empty, and we can avoid producing bogus output pixels by
  39.495 +   * leaving the flag set.
  39.496 +   */
  39.497 +  if (cinfo->unread_marker == 0)
  39.498 +    entropy->pub.insufficient_data = FALSE;
  39.499 +
  39.500 +  return TRUE;
  39.501 +}
  39.502 +
  39.503 +
  39.504 +/*
  39.505 + * Decode and return one MCU's worth of Huffman-compressed coefficients.
  39.506 + * The coefficients are reordered from zigzag order into natural array order,
  39.507 + * but are not dequantized.
  39.508 + *
  39.509 + * The i'th block of the MCU is stored into the block pointed to by
  39.510 + * MCU_data[i].  WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  39.511 + * (Wholesale zeroing is usually a little faster than retail...)
  39.512 + *
  39.513 + * Returns FALSE if data source requested suspension.  In that case no
  39.514 + * changes have been made to permanent state.  (Exception: some output
  39.515 + * coefficients may already have been assigned.  This is harmless for
  39.516 + * this module, since we'll just re-assign them on the next call.)
  39.517 + */
  39.518 +
  39.519 +METHODDEF(boolean)
  39.520 +decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  39.521 +{
  39.522 +  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  39.523 +  int blkn;
  39.524 +  BITREAD_STATE_VARS;
  39.525 +  savable_state state;
  39.526 +
  39.527 +  /* Process restart marker if needed; may have to suspend */
  39.528 +  if (cinfo->restart_interval) {
  39.529 +    if (entropy->restarts_to_go == 0)
  39.530 +      if (! process_restart(cinfo))
  39.531 +	return FALSE;
  39.532 +  }
  39.533 +
  39.534 +  /* If we've run out of data, just leave the MCU set to zeroes.
  39.535 +   * This way, we return uniform gray for the remainder of the segment.
  39.536 +   */
  39.537 +  if (! entropy->pub.insufficient_data) {
  39.538 +
  39.539 +    /* Load up working state */
  39.540 +    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  39.541 +    ASSIGN_STATE(state, entropy->saved);
  39.542 +
  39.543 +    /* Outer loop handles each block in the MCU */
  39.544 +
  39.545 +    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  39.546 +      JBLOCKROW block = MCU_data[blkn];
  39.547 +      d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  39.548 +      d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  39.549 +      register int s, k, r;
  39.550 +
  39.551 +      /* Decode a single block's worth of coefficients */
  39.552 +
  39.553 +      /* Section F.2.2.1: decode the DC coefficient difference */
  39.554 +      HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  39.555 +      if (s) {
  39.556 +	CHECK_BIT_BUFFER(br_state, s, return FALSE);
  39.557 +	r = GET_BITS(s);
  39.558 +	s = HUFF_EXTEND(r, s);
  39.559 +      }
  39.560 +
  39.561 +      if (entropy->dc_needed[blkn]) {
  39.562 +	/* Convert DC difference to actual value, update last_dc_val */
  39.563 +	int ci = cinfo->MCU_membership[blkn];
  39.564 +	s += state.last_dc_val[ci];
  39.565 +	state.last_dc_val[ci] = s;
  39.566 +	/* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  39.567 +	(*block)[0] = (JCOEF) s;
  39.568 +      }
  39.569 +
  39.570 +      if (entropy->ac_needed[blkn]) {
  39.571 +
  39.572 +	/* Section F.2.2.2: decode the AC coefficients */
  39.573 +	/* Since zeroes are skipped, output area must be cleared beforehand */
  39.574 +	for (k = 1; k < DCTSIZE2; k++) {
  39.575 +	  HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  39.576 +      
  39.577 +	  r = s >> 4;
  39.578 +	  s &= 15;
  39.579 +      
  39.580 +	  if (s) {
  39.581 +	    k += r;
  39.582 +	    CHECK_BIT_BUFFER(br_state, s, return FALSE);
  39.583 +	    r = GET_BITS(s);
  39.584 +	    s = HUFF_EXTEND(r, s);
  39.585 +	    /* Output coefficient in natural (dezigzagged) order.
  39.586 +	     * Note: the extra entries in jpeg_natural_order[] will save us
  39.587 +	     * if k >= DCTSIZE2, which could happen if the data is corrupted.
  39.588 +	     */
  39.589 +	    (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  39.590 +	  } else {
  39.591 +	    if (r != 15)
  39.592 +	      break;
  39.593 +	    k += 15;
  39.594 +	  }
  39.595 +	}
  39.596 +
  39.597 +      } else {
  39.598 +
  39.599 +	/* Section F.2.2.2: decode the AC coefficients */
  39.600 +	/* In this path we just discard the values */
  39.601 +	for (k = 1; k < DCTSIZE2; k++) {
  39.602 +	  HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  39.603 +      
  39.604 +	  r = s >> 4;
  39.605 +	  s &= 15;
  39.606 +      
  39.607 +	  if (s) {
  39.608 +	    k += r;
  39.609 +	    CHECK_BIT_BUFFER(br_state, s, return FALSE);
  39.610 +	    DROP_BITS(s);
  39.611 +	  } else {
  39.612 +	    if (r != 15)
  39.613 +	      break;
  39.614 +	    k += 15;
  39.615 +	  }
  39.616 +	}
  39.617 +
  39.618 +      }
  39.619 +    }
  39.620 +
  39.621 +    /* Completed MCU, so update state */
  39.622 +    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  39.623 +    ASSIGN_STATE(entropy->saved, state);
  39.624 +  }
  39.625 +
  39.626 +  /* Account for restart interval (no-op if not using restarts) */
  39.627 +  entropy->restarts_to_go--;
  39.628 +
  39.629 +  return TRUE;
  39.630 +}
  39.631 +
  39.632 +
  39.633 +/*
  39.634 + * Module initialization routine for Huffman entropy decoding.
  39.635 + */
  39.636 +
  39.637 +GLOBAL(void)
  39.638 +jinit_huff_decoder (j_decompress_ptr cinfo)
  39.639 +{
  39.640 +  huff_entropy_ptr entropy;
  39.641 +  int i;
  39.642 +
  39.643 +  entropy = (huff_entropy_ptr)
  39.644 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  39.645 +				SIZEOF(huff_entropy_decoder));
  39.646 +  cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  39.647 +  entropy->pub.start_pass = start_pass_huff_decoder;
  39.648 +  entropy->pub.decode_mcu = decode_mcu;
  39.649 +
  39.650 +  /* Mark tables unallocated */
  39.651 +  for (i = 0; i < NUM_HUFF_TBLS; i++) {
  39.652 +    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  39.653 +  }
  39.654 +}
    40.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    40.2 +++ b/libs/libjpeg/jdhuff.h	Thu Sep 08 06:28:38 2011 +0300
    40.3 @@ -0,0 +1,201 @@
    40.4 +/*
    40.5 + * jdhuff.h
    40.6 + *
    40.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    40.8 + * This file is part of the Independent JPEG Group's software.
    40.9 + * For conditions of distribution and use, see the accompanying README file.
   40.10 + *
   40.11 + * This file contains declarations for Huffman entropy decoding routines
   40.12 + * that are shared between the sequential decoder (jdhuff.c) and the
   40.13 + * progressive decoder (jdphuff.c).  No other modules need to see these.
   40.14 + */
   40.15 +
   40.16 +/* Short forms of external names for systems with brain-damaged linkers. */
   40.17 +
   40.18 +#ifdef NEED_SHORT_EXTERNAL_NAMES
   40.19 +#define jpeg_make_d_derived_tbl	jMkDDerived
   40.20 +#define jpeg_fill_bit_buffer	jFilBitBuf
   40.21 +#define jpeg_huff_decode	jHufDecode
   40.22 +#endif /* NEED_SHORT_EXTERNAL_NAMES */
   40.23 +
   40.24 +
   40.25 +/* Derived data constructed for each Huffman table */
   40.26 +
   40.27 +#define HUFF_LOOKAHEAD	8	/* # of bits of lookahead */
   40.28 +
   40.29 +typedef struct {
   40.30 +  /* Basic tables: (element [0] of each array is unused) */
   40.31 +  INT32 maxcode[18];		/* largest code of length k (-1 if none) */
   40.32 +  /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
   40.33 +  INT32 valoffset[17];		/* huffval[] offset for codes of length k */
   40.34 +  /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
   40.35 +   * the smallest code of length k; so given a code of length k, the
   40.36 +   * corresponding symbol is huffval[code + valoffset[k]]
   40.37 +   */
   40.38 +
   40.39 +  /* Link to public Huffman table (needed only in jpeg_huff_decode) */
   40.40 +  JHUFF_TBL *pub;
   40.41 +
   40.42 +  /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
   40.43 +   * the input data stream.  If the next Huffman code is no more
   40.44 +   * than HUFF_LOOKAHEAD bits long, we can obtain its length and
   40.45 +   * the corresponding symbol directly from these tables.
   40.46 +   */
   40.47 +  int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
   40.48 +  UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
   40.49 +} d_derived_tbl;
   40.50 +
   40.51 +/* Expand a Huffman table definition into the derived format */
   40.52 +EXTERN(void) jpeg_make_d_derived_tbl
   40.53 +	JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
   40.54 +	     d_derived_tbl ** pdtbl));
   40.55 +
   40.56 +
   40.57 +/*
   40.58 + * Fetching the next N bits from the input stream is a time-critical operation
   40.59 + * for the Huffman decoders.  We implement it with a combination of inline
   40.60 + * macros and out-of-line subroutines.  Note that N (the number of bits
   40.61 + * demanded at one time) never exceeds 15 for JPEG use.
   40.62 + *
   40.63 + * We read source bytes into get_buffer and dole out bits as needed.
   40.64 + * If get_buffer already contains enough bits, they are fetched in-line
   40.65 + * by the macros CHECK_BIT_BUFFER and GET_BITS.  When there aren't enough
   40.66 + * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
   40.67 + * as full as possible (not just to the number of bits needed; this
   40.68 + * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
   40.69 + * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
   40.70 + * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
   40.71 + * at least the requested number of bits --- dummy zeroes are inserted if
   40.72 + * necessary.
   40.73 + */
   40.74 +
   40.75 +typedef INT32 bit_buf_type;	/* type of bit-extraction buffer */
   40.76 +#define BIT_BUF_SIZE  32	/* size of buffer in bits */
   40.77 +
   40.78 +/* If long is > 32 bits on your machine, and shifting/masking longs is
   40.79 + * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
   40.80 + * appropriately should be a win.  Unfortunately we can't define the size
   40.81 + * with something like  #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
   40.82 + * because not all machines measure sizeof in 8-bit bytes.
   40.83 + */
   40.84 +
   40.85 +typedef struct {		/* Bitreading state saved across MCUs */
   40.86 +  bit_buf_type get_buffer;	/* current bit-extraction buffer */
   40.87 +  int bits_left;		/* # of unused bits in it */
   40.88 +} bitread_perm_state;
   40.89 +
   40.90 +typedef struct {		/* Bitreading working state within an MCU */
   40.91 +  /* Current data source location */
   40.92 +  /* We need a copy, rather than munging the original, in case of suspension */
   40.93 +  const JOCTET * next_input_byte; /* => next byte to read from source */
   40.94 +  size_t bytes_in_buffer;	/* # of bytes remaining in source buffer */
   40.95 +  /* Bit input buffer --- note these values are kept in register variables,
   40.96 +   * not in this struct, inside the inner loops.
   40.97 +   */
   40.98 +  bit_buf_type get_buffer;	/* current bit-extraction buffer */
   40.99 +  int bits_left;		/* # of unused bits in it */
  40.100 +  /* Pointer needed by jpeg_fill_bit_buffer. */
  40.101 +  j_decompress_ptr cinfo;	/* back link to decompress master record */
  40.102 +} bitread_working_state;
  40.103 +
  40.104 +/* Macros to declare and load/save bitread local variables. */
  40.105 +#define BITREAD_STATE_VARS  \
  40.106 +	register bit_buf_type get_buffer;  \
  40.107 +	register int bits_left;  \
  40.108 +	bitread_working_state br_state
  40.109 +
  40.110 +#define BITREAD_LOAD_STATE(cinfop,permstate)  \
  40.111 +	br_state.cinfo = cinfop; \
  40.112 +	br_state.next_input_byte = cinfop->src->next_input_byte; \
  40.113 +	br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  40.114 +	get_buffer = permstate.get_buffer; \
  40.115 +	bits_left = permstate.bits_left;
  40.116 +
  40.117 +#define BITREAD_SAVE_STATE(cinfop,permstate)  \
  40.118 +	cinfop->src->next_input_byte = br_state.next_input_byte; \
  40.119 +	cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  40.120 +	permstate.get_buffer = get_buffer; \
  40.121 +	permstate.bits_left = bits_left
  40.122 +
  40.123 +/*
  40.124 + * These macros provide the in-line portion of bit fetching.
  40.125 + * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  40.126 + * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  40.127 + * The variables get_buffer and bits_left are assumed to be locals,
  40.128 + * but the state struct might not be (jpeg_huff_decode needs this).
  40.129 + *	CHECK_BIT_BUFFER(state,n,action);
  40.130 + *		Ensure there are N bits in get_buffer; if suspend, take action.
  40.131 + *      val = GET_BITS(n);
  40.132 + *		Fetch next N bits.
  40.133 + *      val = PEEK_BITS(n);
  40.134 + *		Fetch next N bits without removing them from the buffer.
  40.135 + *	DROP_BITS(n);
  40.136 + *		Discard next N bits.
  40.137 + * The value N should be a simple variable, not an expression, because it
  40.138 + * is evaluated multiple times.
  40.139 + */
  40.140 +
  40.141 +#define CHECK_BIT_BUFFER(state,nbits,action) \
  40.142 +	{ if (bits_left < (nbits)) {  \
  40.143 +	    if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits))  \
  40.144 +	      { action; }  \
  40.145 +	    get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  40.146 +
  40.147 +#define GET_BITS(nbits) \
  40.148 +	(((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  40.149 +
  40.150 +#define PEEK_BITS(nbits) \
  40.151 +	(((int) (get_buffer >> (bits_left -  (nbits)))) & ((1<<(nbits))-1))
  40.152 +
  40.153 +#define DROP_BITS(nbits) \
  40.154 +	(bits_left -= (nbits))
  40.155 +
  40.156 +/* Load up the bit buffer to a depth of at least nbits */
  40.157 +EXTERN(boolean) jpeg_fill_bit_buffer
  40.158 +	JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  40.159 +	     register int bits_left, int nbits));
  40.160 +
  40.161 +
  40.162 +/*
  40.163 + * Code for extracting next Huffman-coded symbol from input bit stream.
  40.164 + * Again, this is time-critical and we make the main paths be macros.
  40.165 + *
  40.166 + * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  40.167 + * without looping.  Usually, more than 95% of the Huffman codes will be 8
  40.168 + * or fewer bits long.  The few overlength codes are handled with a loop,
  40.169 + * which need not be inline code.
  40.170 + *
  40.171 + * Notes about the HUFF_DECODE macro:
  40.172 + * 1. Near the end of the data segment, we may fail to get enough bits
  40.173 + *    for a lookahead.  In that case, we do it the hard way.
  40.174 + * 2. If the lookahead table contains no entry, the next code must be
  40.175 + *    more than HUFF_LOOKAHEAD bits long.
  40.176 + * 3. jpeg_huff_decode returns -1 if forced to suspend.
  40.177 + */
  40.178 +
  40.179 +#define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  40.180 +{ register int nb, look; \
  40.181 +  if (bits_left < HUFF_LOOKAHEAD) { \
  40.182 +    if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  40.183 +    get_buffer = state.get_buffer; bits_left = state.bits_left; \
  40.184 +    if (bits_left < HUFF_LOOKAHEAD) { \
  40.185 +      nb = 1; goto slowlabel; \
  40.186 +    } \
  40.187 +  } \
  40.188 +  look = PEEK_BITS(HUFF_LOOKAHEAD); \
  40.189 +  if ((nb = htbl->look_nbits[look]) != 0) { \
  40.190 +    DROP_BITS(nb); \
  40.191 +    result = htbl->look_sym[look]; \
  40.192 +  } else { \
  40.193 +    nb = HUFF_LOOKAHEAD+1; \
  40.194 +slowlabel: \
  40.195 +    if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  40.196 +	{ failaction; } \
  40.197 +    get_buffer = state.get_buffer; bits_left = state.bits_left; \
  40.198 +  } \
  40.199 +}
  40.200 +
  40.201 +/* Out-of-line case for Huffman code fetching */
  40.202 +EXTERN(int) jpeg_huff_decode
  40.203 +	JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  40.204 +	     register int bits_left, d_derived_tbl * htbl, int min_bits));
    41.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    41.2 +++ b/libs/libjpeg/jdinput.c	Thu Sep 08 06:28:38 2011 +0300
    41.3 @@ -0,0 +1,381 @@
    41.4 +/*
    41.5 + * jdinput.c
    41.6 + *
    41.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    41.8 + * This file is part of the Independent JPEG Group's software.
    41.9 + * For conditions of distribution and use, see the accompanying README file.
   41.10 + *
   41.11 + * This file contains input control logic for the JPEG decompressor.
   41.12 + * These routines are concerned with controlling the decompressor's input
   41.13 + * processing (marker reading and coefficient decoding).  The actual input
   41.14 + * reading is done in jdmarker.c, jdhuff.c, and jdphuff.c.
   41.15 + */
   41.16 +
   41.17 +#define JPEG_INTERNALS
   41.18 +#include "jinclude.h"
   41.19 +#include "jpeglib.h"
   41.20 +
   41.21 +
   41.22 +/* Private state */
   41.23 +
   41.24 +typedef struct {
   41.25 +  struct jpeg_input_controller pub; /* public fields */
   41.26 +
   41.27 +  boolean inheaders;		/* TRUE until first SOS is reached */
   41.28 +} my_input_controller;
   41.29 +
   41.30 +typedef my_input_controller * my_inputctl_ptr;
   41.31 +
   41.32 +
   41.33 +/* Forward declarations */
   41.34 +METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
   41.35 +
   41.36 +
   41.37 +/*
   41.38 + * Routines to calculate various quantities related to the size of the image.
   41.39 + */
   41.40 +
   41.41 +LOCAL(void)
   41.42 +initial_setup (j_decompress_ptr cinfo)
   41.43 +/* Called once, when first SOS marker is reached */
   41.44 +{
   41.45 +  int ci;
   41.46 +  jpeg_component_info *compptr;
   41.47 +
   41.48 +  /* Make sure image isn't bigger than I can handle */
   41.49 +  if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
   41.50 +      (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
   41.51 +    ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
   41.52 +
   41.53 +  /* For now, precision must match compiled-in value... */
   41.54 +  if (cinfo->data_precision != BITS_IN_JSAMPLE)
   41.55 +    ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
   41.56 +
   41.57 +  /* Check that number of components won't exceed internal array sizes */
   41.58 +  if (cinfo->num_components > MAX_COMPONENTS)
   41.59 +    ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
   41.60 +	     MAX_COMPONENTS);
   41.61 +
   41.62 +  /* Compute maximum sampling factors; check factor validity */
   41.63 +  cinfo->max_h_samp_factor = 1;
   41.64 +  cinfo->max_v_samp_factor = 1;
   41.65 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
   41.66 +       ci++, compptr++) {
   41.67 +    if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
   41.68 +	compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
   41.69 +      ERREXIT(cinfo, JERR_BAD_SAMPLING);
   41.70 +    cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
   41.71 +				   compptr->h_samp_factor);
   41.72 +    cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
   41.73 +				   compptr->v_samp_factor);
   41.74 +  }
   41.75 +
   41.76 +  /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
   41.77 +   * In the full decompressor, this will be overridden by jdmaster.c;
   41.78 +   * but in the transcoder, jdmaster.c is not used, so we must do it here.
   41.79 +   */
   41.80 +  cinfo->min_DCT_scaled_size = DCTSIZE;
   41.81 +
   41.82 +  /* Compute dimensions of components */
   41.83 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
   41.84 +       ci++, compptr++) {
   41.85 +    compptr->DCT_scaled_size = DCTSIZE;
   41.86 +    /* Size in DCT blocks */
   41.87 +    compptr->width_in_blocks = (JDIMENSION)
   41.88 +      jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
   41.89 +		    (long) (cinfo->max_h_samp_factor * DCTSIZE));
   41.90 +    compptr->height_in_blocks = (JDIMENSION)
   41.91 +      jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
   41.92 +		    (long) (cinfo->max_v_samp_factor * DCTSIZE));
   41.93 +    /* downsampled_width and downsampled_height will also be overridden by
   41.94 +     * jdmaster.c if we are doing full decompression.  The transcoder library
   41.95 +     * doesn't use these values, but the calling application might.
   41.96 +     */
   41.97 +    /* Size in samples */
   41.98 +    compptr->downsampled_width = (JDIMENSION)
   41.99 +      jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  41.100 +		    (long) cinfo->max_h_samp_factor);
  41.101 +    compptr->downsampled_height = (JDIMENSION)
  41.102 +      jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  41.103 +		    (long) cinfo->max_v_samp_factor);
  41.104 +    /* Mark component needed, until color conversion says otherwise */
  41.105 +    compptr->component_needed = TRUE;
  41.106 +    /* Mark no quantization table yet saved for component */
  41.107 +    compptr->quant_table = NULL;
  41.108 +  }
  41.109 +
  41.110 +  /* Compute number of fully interleaved MCU rows. */
  41.111 +  cinfo->total_iMCU_rows = (JDIMENSION)
  41.112 +    jdiv_round_up((long) cinfo->image_height,
  41.113 +		  (long) (cinfo->max_v_samp_factor*DCTSIZE));
  41.114 +
  41.115 +  /* Decide whether file contains multiple scans */
  41.116 +  if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  41.117 +    cinfo->inputctl->has_multiple_scans = TRUE;
  41.118 +  else
  41.119 +    cinfo->inputctl->has_multiple_scans = FALSE;
  41.120 +}
  41.121 +
  41.122 +
  41.123 +LOCAL(void)
  41.124 +per_scan_setup (j_decompress_ptr cinfo)
  41.125 +/* Do computations that are needed before processing a JPEG scan */
  41.126 +/* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  41.127 +{
  41.128 +  int ci, mcublks, tmp;
  41.129 +  jpeg_component_info *compptr;
  41.130 +  
  41.131 +  if (cinfo->comps_in_scan == 1) {
  41.132 +    
  41.133 +    /* Noninterleaved (single-component) scan */
  41.134 +    compptr = cinfo->cur_comp_info[0];
  41.135 +    
  41.136 +    /* Overall image size in MCUs */
  41.137 +    cinfo->MCUs_per_row = compptr->width_in_blocks;
  41.138 +    cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  41.139 +    
  41.140 +    /* For noninterleaved scan, always one block per MCU */
  41.141 +    compptr->MCU_width = 1;
  41.142 +    compptr->MCU_height = 1;
  41.143 +    compptr->MCU_blocks = 1;
  41.144 +    compptr->MCU_sample_width = compptr->DCT_scaled_size;
  41.145 +    compptr->last_col_width = 1;
  41.146 +    /* For noninterleaved scans, it is convenient to define last_row_height
  41.147 +     * as the number of block rows present in the last iMCU row.
  41.148 +     */
  41.149 +    tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  41.150 +    if (tmp == 0) tmp = compptr->v_samp_factor;
  41.151 +    compptr->last_row_height = tmp;
  41.152 +    
  41.153 +    /* Prepare array describing MCU composition */
  41.154 +    cinfo->blocks_in_MCU = 1;
  41.155 +    cinfo->MCU_membership[0] = 0;
  41.156 +    
  41.157 +  } else {
  41.158 +    
  41.159 +    /* Interleaved (multi-component) scan */
  41.160 +    if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  41.161 +      ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  41.162 +	       MAX_COMPS_IN_SCAN);
  41.163 +    
  41.164 +    /* Overall image size in MCUs */
  41.165 +    cinfo->MCUs_per_row = (JDIMENSION)
  41.166 +      jdiv_round_up((long) cinfo->image_width,
  41.167 +		    (long) (cinfo->max_h_samp_factor*DCTSIZE));
  41.168 +    cinfo->MCU_rows_in_scan = (JDIMENSION)
  41.169 +      jdiv_round_up((long) cinfo->image_height,
  41.170 +		    (long) (cinfo->max_v_samp_factor*DCTSIZE));
  41.171 +    
  41.172 +    cinfo->blocks_in_MCU = 0;
  41.173 +    
  41.174 +    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  41.175 +      compptr = cinfo->cur_comp_info[ci];
  41.176 +      /* Sampling factors give # of blocks of component in each MCU */
  41.177 +      compptr->MCU_width = compptr->h_samp_factor;
  41.178 +      compptr->MCU_height = compptr->v_samp_factor;
  41.179 +      compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  41.180 +      compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  41.181 +      /* Figure number of non-dummy blocks in last MCU column & row */
  41.182 +      tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  41.183 +      if (tmp == 0) tmp = compptr->MCU_width;
  41.184 +      compptr->last_col_width = tmp;
  41.185 +      tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  41.186 +      if (tmp == 0) tmp = compptr->MCU_height;
  41.187 +      compptr->last_row_height = tmp;
  41.188 +      /* Prepare array describing MCU composition */
  41.189 +      mcublks = compptr->MCU_blocks;
  41.190 +      if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  41.191 +	ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  41.192 +      while (mcublks-- > 0) {
  41.193 +	cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  41.194 +      }
  41.195 +    }
  41.196 +    
  41.197 +  }
  41.198 +}
  41.199 +
  41.200 +
  41.201 +/*
  41.202 + * Save away a copy of the Q-table referenced by each component present
  41.203 + * in the current scan, unless already saved during a prior scan.
  41.204 + *
  41.205 + * In a multiple-scan JPEG file, the encoder could assign different components
  41.206 + * the same Q-table slot number, but change table definitions between scans
  41.207 + * so that each component uses a different Q-table.  (The IJG encoder is not
  41.208 + * currently capable of doing this, but other encoders might.)  Since we want
  41.209 + * to be able to dequantize all the components at the end of the file, this
  41.210 + * means that we have to save away the table actually used for each component.
  41.211 + * We do this by copying the table at the start of the first scan containing
  41.212 + * the component.
  41.213 + * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  41.214 + * slot between scans of a component using that slot.  If the encoder does so
  41.215 + * anyway, this decoder will simply use the Q-table values that were current
  41.216 + * at the start of the first scan for the component.
  41.217 + *
  41.218 + * The decompressor output side looks only at the saved quant tables,
  41.219 + * not at the current Q-table slots.
  41.220 + */
  41.221 +
  41.222 +LOCAL(void)
  41.223 +latch_quant_tables (j_decompress_ptr cinfo)
  41.224 +{
  41.225 +  int ci, qtblno;
  41.226 +  jpeg_component_info *compptr;
  41.227 +  JQUANT_TBL * qtbl;
  41.228 +
  41.229 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  41.230 +    compptr = cinfo->cur_comp_info[ci];
  41.231 +    /* No work if we already saved Q-table for this component */
  41.232 +    if (compptr->quant_table != NULL)
  41.233 +      continue;
  41.234 +    /* Make sure specified quantization table is present */
  41.235 +    qtblno = compptr->quant_tbl_no;
  41.236 +    if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  41.237 +	cinfo->quant_tbl_ptrs[qtblno] == NULL)
  41.238 +      ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  41.239 +    /* OK, save away the quantization table */
  41.240 +    qtbl = (JQUANT_TBL *)
  41.241 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  41.242 +				  SIZEOF(JQUANT_TBL));
  41.243 +    MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  41.244 +    compptr->quant_table = qtbl;
  41.245 +  }
  41.246 +}
  41.247 +
  41.248 +
  41.249 +/*
  41.250 + * Initialize the input modules to read a scan of compressed data.
  41.251 + * The first call to this is done by jdmaster.c after initializing
  41.252 + * the entire decompressor (during jpeg_start_decompress).
  41.253 + * Subsequent calls come from consume_markers, below.
  41.254 + */
  41.255 +
  41.256 +METHODDEF(void)
  41.257 +start_input_pass (j_decompress_ptr cinfo)
  41.258 +{
  41.259 +  per_scan_setup(cinfo);
  41.260 +  latch_quant_tables(cinfo);
  41.261 +  (*cinfo->entropy->start_pass) (cinfo);
  41.262 +  (*cinfo->coef->start_input_pass) (cinfo);
  41.263 +  cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  41.264 +}
  41.265 +
  41.266 +
  41.267 +/*
  41.268 + * Finish up after inputting a compressed-data scan.
  41.269 + * This is called by the coefficient controller after it's read all
  41.270 + * the expected data of the scan.
  41.271 + */
  41.272 +
  41.273 +METHODDEF(void)
  41.274 +finish_input_pass (j_decompress_ptr cinfo)
  41.275 +{
  41.276 +  cinfo->inputctl->consume_input = consume_markers;
  41.277 +}
  41.278 +
  41.279 +
  41.280 +/*
  41.281 + * Read JPEG markers before, between, or after compressed-data scans.
  41.282 + * Change state as necessary when a new scan is reached.
  41.283 + * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  41.284 + *
  41.285 + * The consume_input method pointer points either here or to the
  41.286 + * coefficient controller's consume_data routine, depending on whether
  41.287 + * we are reading a compressed data segment or inter-segment markers.
  41.288 + */
  41.289 +
  41.290 +METHODDEF(int)
  41.291 +consume_markers (j_decompress_ptr cinfo)
  41.292 +{
  41.293 +  my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  41.294 +  int val;
  41.295 +
  41.296 +  if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  41.297 +    return JPEG_REACHED_EOI;
  41.298 +
  41.299 +  val = (*cinfo->marker->read_markers) (cinfo);
  41.300 +
  41.301 +  switch (val) {
  41.302 +  case JPEG_REACHED_SOS:	/* Found SOS */
  41.303 +    if (inputctl->inheaders) {	/* 1st SOS */
  41.304 +      initial_setup(cinfo);
  41.305 +      inputctl->inheaders = FALSE;
  41.306 +      /* Note: start_input_pass must be called by jdmaster.c
  41.307 +       * before any more input can be consumed.  jdapimin.c is
  41.308 +       * responsible for enforcing this sequencing.
  41.309 +       */
  41.310 +    } else {			/* 2nd or later SOS marker */
  41.311 +      if (! inputctl->pub.has_multiple_scans)
  41.312 +	ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  41.313 +      start_input_pass(cinfo);
  41.314 +    }
  41.315 +    break;
  41.316 +  case JPEG_REACHED_EOI:	/* Found EOI */
  41.317 +    inputctl->pub.eoi_reached = TRUE;
  41.318 +    if (inputctl->inheaders) {	/* Tables-only datastream, apparently */
  41.319 +      if (cinfo->marker->saw_SOF)
  41.320 +	ERREXIT(cinfo, JERR_SOF_NO_SOS);
  41.321 +    } else {
  41.322 +      /* Prevent infinite loop in coef ctlr's decompress_data routine
  41.323 +       * if user set output_scan_number larger than number of scans.
  41.324 +       */
  41.325 +      if (cinfo->output_scan_number > cinfo->input_scan_number)
  41.326 +	cinfo->output_scan_number = cinfo->input_scan_number;
  41.327 +    }
  41.328 +    break;
  41.329 +  case JPEG_SUSPENDED:
  41.330 +    break;
  41.331 +  }
  41.332 +
  41.333 +  return val;
  41.334 +}
  41.335 +
  41.336 +
  41.337 +/*
  41.338 + * Reset state to begin a fresh datastream.
  41.339 + */
  41.340 +
  41.341 +METHODDEF(void)
  41.342 +reset_input_controller (j_decompress_ptr cinfo)
  41.343 +{
  41.344 +  my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  41.345 +
  41.346 +  inputctl->pub.consume_input = consume_markers;
  41.347 +  inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  41.348 +  inputctl->pub.eoi_reached = FALSE;
  41.349 +  inputctl->inheaders = TRUE;
  41.350 +  /* Reset other modules */
  41.351 +  (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  41.352 +  (*cinfo->marker->reset_marker_reader) (cinfo);
  41.353 +  /* Reset progression state -- would be cleaner if entropy decoder did this */
  41.354 +  cinfo->coef_bits = NULL;
  41.355 +}
  41.356 +
  41.357 +
  41.358 +/*
  41.359 + * Initialize the input controller module.
  41.360 + * This is called only once, when the decompression object is created.
  41.361 + */
  41.362 +
  41.363 +GLOBAL(void)
  41.364 +jinit_input_controller (j_decompress_ptr cinfo)
  41.365 +{
  41.366 +  my_inputctl_ptr inputctl;
  41.367 +
  41.368 +  /* Create subobject in permanent pool */
  41.369 +  inputctl = (my_inputctl_ptr)
  41.370 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  41.371 +				SIZEOF(my_input_controller));
  41.372 +  cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  41.373 +  /* Initialize method pointers */
  41.374 +  inputctl->pub.consume_input = consume_markers;
  41.375 +  inputctl->pub.reset_input_controller = reset_input_controller;
  41.376 +  inputctl->pub.start_input_pass = start_input_pass;
  41.377 +  inputctl->pub.finish_input_pass = finish_input_pass;
  41.378 +  /* Initialize state: can't use reset_input_controller since we don't
  41.379 +   * want to try to reset other modules yet.
  41.380 +   */
  41.381 +  inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  41.382 +  inputctl->pub.eoi_reached = FALSE;
  41.383 +  inputctl->inheaders = TRUE;
  41.384 +}
    42.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    42.2 +++ b/libs/libjpeg/jdmainct.c	Thu Sep 08 06:28:38 2011 +0300
    42.3 @@ -0,0 +1,512 @@
    42.4 +/*
    42.5 + * jdmainct.c
    42.6 + *
    42.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    42.8 + * This file is part of the Independent JPEG Group's software.
    42.9 + * For conditions of distribution and use, see the accompanying README file.
   42.10 + *
   42.11 + * This file contains the main buffer controller for decompression.
   42.12 + * The main buffer lies between the JPEG decompressor proper and the
   42.13 + * post-processor; it holds downsampled data in the JPEG colorspace.
   42.14 + *
   42.15 + * Note that this code is bypassed in raw-data mode, since the application
   42.16 + * supplies the equivalent of the main buffer in that case.
   42.17 + */
   42.18 +
   42.19 +#define JPEG_INTERNALS
   42.20 +#include "jinclude.h"
   42.21 +#include "jpeglib.h"
   42.22 +
   42.23 +
   42.24 +/*
   42.25 + * In the current system design, the main buffer need never be a full-image
   42.26 + * buffer; any full-height buffers will be found inside the coefficient or
   42.27 + * postprocessing controllers.  Nonetheless, the main controller is not
   42.28 + * trivial.  Its responsibility is to provide context rows for upsampling/
   42.29 + * rescaling, and doing this in an efficient fashion is a bit tricky.
   42.30 + *
   42.31 + * Postprocessor input data is counted in "row groups".  A row group
   42.32 + * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
   42.33 + * sample rows of each component.  (We require DCT_scaled_size values to be
   42.34 + * chosen such that these numbers are integers.  In practice DCT_scaled_size
   42.35 + * values will likely be powers of two, so we actually have the stronger
   42.36 + * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
   42.37 + * Upsampling will typically produce max_v_samp_factor pixel rows from each
   42.38 + * row group (times any additional scale factor that the upsampler is
   42.39 + * applying).
   42.40 + *
   42.41 + * The coefficient controller will deliver data to us one iMCU row at a time;
   42.42 + * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
   42.43 + * exactly min_DCT_scaled_size row groups.  (This amount of data corresponds
   42.44 + * to one row of MCUs when the image is fully interleaved.)  Note that the
   42.45 + * number of sample rows varies across components, but the number of row
   42.46 + * groups does not.  Some garbage sample rows may be included in the last iMCU
   42.47 + * row at the bottom of the image.
   42.48 + *
   42.49 + * Depending on the vertical scaling algorithm used, the upsampler may need
   42.50 + * access to the sample row(s) above and below its current input row group.
   42.51 + * The upsampler is required to set need_context_rows TRUE at global selection
   42.52 + * time if so.  When need_context_rows is FALSE, this controller can simply
   42.53 + * obtain one iMCU row at a time from the coefficient controller and dole it
   42.54 + * out as row groups to the postprocessor.
   42.55 + *
   42.56 + * When need_context_rows is TRUE, this controller guarantees that the buffer
   42.57 + * passed to postprocessing contains at least one row group's worth of samples
   42.58 + * above and below the row group(s) being processed.  Note that the context
   42.59 + * rows "above" the first passed row group appear at negative row offsets in
   42.60 + * the passed buffer.  At the top and bottom of the image, the required
   42.61 + * context rows are manufactured by duplicating the first or last real sample
   42.62 + * row; this avoids having special cases in the upsampling inner loops.
   42.63 + *
   42.64 + * The amount of context is fixed at one row group just because that's a
   42.65 + * convenient number for this controller to work with.  The existing
   42.66 + * upsamplers really only need one sample row of context.  An upsampler
   42.67 + * supporting arbitrary output rescaling might wish for more than one row
   42.68 + * group of context when shrinking the image; tough, we don't handle that.
   42.69 + * (This is justified by the assumption that downsizing will be handled mostly
   42.70 + * by adjusting the DCT_scaled_size values, so that the actual scale factor at
   42.71 + * the upsample step needn't be much less than one.)
   42.72 + *
   42.73 + * To provide the desired context, we have to retain the last two row groups
   42.74 + * of one iMCU row while reading in the next iMCU row.  (The last row group
   42.75 + * can't be processed until we have another row group for its below-context,
   42.76 + * and so we have to save the next-to-last group too for its above-context.)
   42.77 + * We could do this most simply by copying data around in our buffer, but
   42.78 + * that'd be very slow.  We can avoid copying any data by creating a rather
   42.79 + * strange pointer structure.  Here's how it works.  We allocate a workspace
   42.80 + * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
   42.81 + * of row groups per iMCU row).  We create two sets of redundant pointers to
   42.82 + * the workspace.  Labeling the physical row groups 0 to M+1, the synthesized
   42.83 + * pointer lists look like this:
   42.84 + *                   M+1                          M-1
   42.85 + * master pointer --> 0         master pointer --> 0
   42.86 + *                    1                            1
   42.87 + *                   ...                          ...
   42.88 + *                   M-3                          M-3
   42.89 + *                   M-2                           M
   42.90 + *                   M-1                          M+1
   42.91 + *                    M                           M-2
   42.92 + *                   M+1                          M-1
   42.93 + *                    0                            0
   42.94 + * We read alternate iMCU rows using each master pointer; thus the last two
   42.95 + * row groups of the previous iMCU row remain un-overwritten in the workspace.
   42.96 + * The pointer lists are set up so that the required context rows appear to
   42.97 + * be adjacent to the proper places when we pass the pointer lists to the
   42.98 + * upsampler.
   42.99 + *
  42.100 + * The above pictures describe the normal state of the pointer lists.
  42.101 + * At top and bottom of the image, we diddle the pointer lists to duplicate
  42.102 + * the first or last sample row as necessary (this is cheaper than copying
  42.103 + * sample rows around).
  42.104 + *
  42.105 + * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1.  In that
  42.106 + * situation each iMCU row provides only one row group so the buffering logic
  42.107 + * must be different (eg, we must read two iMCU rows before we can emit the
  42.108 + * first row group).  For now, we simply do not support providing context
  42.109 + * rows when min_DCT_scaled_size is 1.  That combination seems unlikely to
  42.110 + * be worth providing --- if someone wants a 1/8th-size preview, they probably
  42.111 + * want it quick and dirty, so a context-free upsampler is sufficient.
  42.112 + */
  42.113 +
  42.114 +
  42.115 +/* Private buffer controller object */
  42.116 +
  42.117 +typedef struct {
  42.118 +  struct jpeg_d_main_controller pub; /* public fields */
  42.119 +
  42.120 +  /* Pointer to allocated workspace (M or M+2 row groups). */
  42.121 +  JSAMPARRAY buffer[MAX_COMPONENTS];
  42.122 +
  42.123 +  boolean buffer_full;		/* Have we gotten an iMCU row from decoder? */
  42.124 +  JDIMENSION rowgroup_ctr;	/* counts row groups output to postprocessor */
  42.125 +
  42.126 +  /* Remaining fields are only used in the context case. */
  42.127 +
  42.128 +  /* These are the master pointers to the funny-order pointer lists. */
  42.129 +  JSAMPIMAGE xbuffer[2];	/* pointers to weird pointer lists */
  42.130 +
  42.131 +  int whichptr;			/* indicates which pointer set is now in use */
  42.132 +  int context_state;		/* process_data state machine status */
  42.133 +  JDIMENSION rowgroups_avail;	/* row groups available to postprocessor */
  42.134 +  JDIMENSION iMCU_row_ctr;	/* counts iMCU rows to detect image top/bot */
  42.135 +} my_main_controller;
  42.136 +
  42.137 +typedef my_main_controller * my_main_ptr;
  42.138 +
  42.139 +/* context_state values: */
  42.140 +#define CTX_PREPARE_FOR_IMCU	0	/* need to prepare for MCU row */
  42.141 +#define CTX_PROCESS_IMCU	1	/* feeding iMCU to postprocessor */
  42.142 +#define CTX_POSTPONED_ROW	2	/* feeding postponed row group */
  42.143 +
  42.144 +
  42.145 +/* Forward declarations */
  42.146 +METHODDEF(void) process_data_simple_main
  42.147 +	JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  42.148 +	     JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  42.149 +METHODDEF(void) process_data_context_main
  42.150 +	JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  42.151 +	     JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  42.152 +#ifdef QUANT_2PASS_SUPPORTED
  42.153 +METHODDEF(void) process_data_crank_post
  42.154 +	JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  42.155 +	     JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  42.156 +#endif
  42.157 +
  42.158 +
  42.159 +LOCAL(void)
  42.160 +alloc_funny_pointers (j_decompress_ptr cinfo)
  42.161 +/* Allocate space for the funny pointer lists.
  42.162 + * This is done only once, not once per pass.
  42.163 + */
  42.164 +{
  42.165 +  my_main_ptr main = (my_main_ptr) cinfo->main;
  42.166 +  int ci, rgroup;
  42.167 +  int M = cinfo->min_DCT_scaled_size;
  42.168 +  jpeg_component_info *compptr;
  42.169 +  JSAMPARRAY xbuf;
  42.170 +
  42.171 +  /* Get top-level space for component array pointers.
  42.172 +   * We alloc both arrays with one call to save a few cycles.
  42.173 +   */
  42.174 +  main->xbuffer[0] = (JSAMPIMAGE)
  42.175 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  42.176 +				cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  42.177 +  main->xbuffer[1] = main->xbuffer[0] + cinfo->num_components;
  42.178 +
  42.179 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  42.180 +       ci++, compptr++) {
  42.181 +    rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  42.182 +      cinfo->min_DCT_scaled_size; /* height of a row group of component */
  42.183 +    /* Get space for pointer lists --- M+4 row groups in each list.
  42.184 +     * We alloc both pointer lists with one call to save a few cycles.
  42.185 +     */
  42.186 +    xbuf = (JSAMPARRAY)
  42.187 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  42.188 +				  2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  42.189 +    xbuf += rgroup;		/* want one row group at negative offsets */
  42.190 +    main->xbuffer[0][ci] = xbuf;
  42.191 +    xbuf += rgroup * (M + 4);
  42.192 +    main->xbuffer[1][ci] = xbuf;
  42.193 +  }
  42.194 +}
  42.195 +
  42.196 +
  42.197 +LOCAL(void)
  42.198 +make_funny_pointers (j_decompress_ptr cinfo)
  42.199 +/* Create the funny pointer lists discussed in the comments above.
  42.200 + * The actual workspace is already allocated (in main->buffer),
  42.201 + * and the space for the pointer lists is allocated too.
  42.202 + * This routine just fills in the curiously ordered lists.
  42.203 + * This will be repeated at the beginning of each pass.
  42.204 + */
  42.205 +{
  42.206 +  my_main_ptr main = (my_main_ptr) cinfo->main;
  42.207 +  int ci, i, rgroup;
  42.208 +  int M = cinfo->min_DCT_scaled_size;
  42.209 +  jpeg_component_info *compptr;
  42.210 +  JSAMPARRAY buf, xbuf0, xbuf1;
  42.211 +
  42.212 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  42.213 +       ci++, compptr++) {
  42.214 +    rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  42.215 +      cinfo->min_DCT_scaled_size; /* height of a row group of component */
  42.216 +    xbuf0 = main->xbuffer[0][ci];
  42.217 +    xbuf1 = main->xbuffer[1][ci];
  42.218 +    /* First copy the workspace pointers as-is */
  42.219 +    buf = main->buffer[ci];
  42.220 +    for (i = 0; i < rgroup * (M + 2); i++) {
  42.221 +      xbuf0[i] = xbuf1[i] = buf[i];
  42.222 +    }
  42.223 +    /* In the second list, put the last four row groups in swapped order */
  42.224 +    for (i = 0; i < rgroup * 2; i++) {
  42.225 +      xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  42.226 +      xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  42.227 +    }
  42.228 +    /* The wraparound pointers at top and bottom will be filled later
  42.229 +     * (see set_wraparound_pointers, below).  Initially we want the "above"
  42.230 +     * pointers to duplicate the first actual data line.  This only needs
  42.231 +     * to happen in xbuffer[0].
  42.232 +     */
  42.233 +    for (i = 0; i < rgroup; i++) {
  42.234 +      xbuf0[i - rgroup] = xbuf0[0];
  42.235 +    }
  42.236 +  }
  42.237 +}
  42.238 +
  42.239 +
  42.240 +LOCAL(void)
  42.241 +set_wraparound_pointers (j_decompress_ptr cinfo)
  42.242 +/* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  42.243 + * This changes the pointer list state from top-of-image to the normal state.
  42.244 + */
  42.245 +{
  42.246 +  my_main_ptr main = (my_main_ptr) cinfo->main;
  42.247 +  int ci, i, rgroup;
  42.248 +  int M = cinfo->min_DCT_scaled_size;
  42.249 +  jpeg_component_info *compptr;
  42.250 +  JSAMPARRAY xbuf0, xbuf1;
  42.251 +
  42.252 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  42.253 +       ci++, compptr++) {
  42.254 +    rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  42.255 +      cinfo->min_DCT_scaled_size; /* height of a row group of component */
  42.256 +    xbuf0 = main->xbuffer[0][ci];
  42.257 +    xbuf1 = main->xbuffer[1][ci];
  42.258 +    for (i = 0; i < rgroup; i++) {
  42.259 +      xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  42.260 +      xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  42.261 +      xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  42.262 +      xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  42.263 +    }
  42.264 +  }
  42.265 +}
  42.266 +
  42.267 +
  42.268 +LOCAL(void)
  42.269 +set_bottom_pointers (j_decompress_ptr cinfo)
  42.270 +/* Change the pointer lists to duplicate the last sample row at the bottom
  42.271 + * of the image.  whichptr indicates which xbuffer holds the final iMCU row.
  42.272 + * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  42.273 + */
  42.274 +{
  42.275 +  my_main_ptr main = (my_main_ptr) cinfo->main;
  42.276 +  int ci, i, rgroup, iMCUheight, rows_left;
  42.277 +  jpeg_component_info *compptr;
  42.278 +  JSAMPARRAY xbuf;
  42.279 +
  42.280 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  42.281 +       ci++, compptr++) {
  42.282 +    /* Count sample rows in one iMCU row and in one row group */
  42.283 +    iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  42.284 +    rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  42.285 +    /* Count nondummy sample rows remaining for this component */
  42.286 +    rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  42.287 +    if (rows_left == 0) rows_left = iMCUheight;
  42.288 +    /* Count nondummy row groups.  Should get same answer for each component,
  42.289 +     * so we need only do it once.
  42.290 +     */
  42.291 +    if (ci == 0) {
  42.292 +      main->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  42.293 +    }
  42.294 +    /* Duplicate the last real sample row rgroup*2 times; this pads out the
  42.295 +     * last partial rowgroup and ensures at least one full rowgroup of context.
  42.296 +     */
  42.297 +    xbuf = main->xbuffer[main->whichptr][ci];
  42.298 +    for (i = 0; i < rgroup * 2; i++) {
  42.299 +      xbuf[rows_left + i] = xbuf[rows_left-1];
  42.300 +    }
  42.301 +  }
  42.302 +}
  42.303 +
  42.304 +
  42.305 +/*
  42.306 + * Initialize for a processing pass.
  42.307 + */
  42.308 +
  42.309 +METHODDEF(void)
  42.310 +start_pass_main (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  42.311 +{
  42.312 +  my_main_ptr main = (my_main_ptr) cinfo->main;
  42.313 +
  42.314 +  switch (pass_mode) {
  42.315 +  case JBUF_PASS_THRU:
  42.316 +    if (cinfo->upsample->need_context_rows) {
  42.317 +      main->pub.process_data = process_data_context_main;
  42.318 +      make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  42.319 +      main->whichptr = 0;	/* Read first iMCU row into xbuffer[0] */
  42.320 +      main->context_state = CTX_PREPARE_FOR_IMCU;
  42.321 +      main->iMCU_row_ctr = 0;
  42.322 +    } else {
  42.323 +      /* Simple case with no context needed */
  42.324 +      main->pub.process_data = process_data_simple_main;
  42.325 +    }
  42.326 +    main->buffer_full = FALSE;	/* Mark buffer empty */
  42.327 +    main->rowgroup_ctr = 0;
  42.328 +    break;
  42.329 +#ifdef QUANT_2PASS_SUPPORTED
  42.330 +  case JBUF_CRANK_DEST:
  42.331 +    /* For last pass of 2-pass quantization, just crank the postprocessor */
  42.332 +    main->pub.process_data = process_data_crank_post;
  42.333 +    break;
  42.334 +#endif
  42.335 +  default:
  42.336 +    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  42.337 +    break;
  42.338 +  }
  42.339 +}
  42.340 +
  42.341 +
  42.342 +/*
  42.343 + * Process some data.
  42.344 + * This handles the simple case where no context is required.
  42.345 + */
  42.346 +
  42.347 +METHODDEF(void)
  42.348 +process_data_simple_main (j_decompress_ptr cinfo,
  42.349 +			  JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  42.350 +			  JDIMENSION out_rows_avail)
  42.351 +{
  42.352 +  my_main_ptr main = (my_main_ptr) cinfo->main;
  42.353 +  JDIMENSION rowgroups_avail;
  42.354 +
  42.355 +  /* Read input data if we haven't filled the main buffer yet */
  42.356 +  if (! main->buffer_full) {
  42.357 +    if (! (*cinfo->coef->decompress_data) (cinfo, main->buffer))
  42.358 +      return;			/* suspension forced, can do nothing more */
  42.359 +    main->buffer_full = TRUE;	/* OK, we have an iMCU row to work with */
  42.360 +  }
  42.361 +
  42.362 +  /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  42.363 +  rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  42.364 +  /* Note: at the bottom of the image, we may pass extra garbage row groups
  42.365 +   * to the postprocessor.  The postprocessor has to check for bottom
  42.366 +   * of image anyway (at row resolution), so no point in us doing it too.
  42.367 +   */
  42.368 +
  42.369 +  /* Feed the postprocessor */
  42.370 +  (*cinfo->post->post_process_data) (cinfo, main->buffer,
  42.371 +				     &main->rowgroup_ctr, rowgroups_avail,
  42.372 +				     output_buf, out_row_ctr, out_rows_avail);
  42.373 +
  42.374 +  /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  42.375 +  if (main->rowgroup_ctr >= rowgroups_avail) {
  42.376 +    main->buffer_full = FALSE;
  42.377 +    main->rowgroup_ctr = 0;
  42.378 +  }
  42.379 +}
  42.380 +
  42.381 +
  42.382 +/*
  42.383 + * Process some data.
  42.384 + * This handles the case where context rows must be provided.
  42.385 + */
  42.386 +
  42.387 +METHODDEF(void)
  42.388 +process_data_context_main (j_decompress_ptr cinfo,
  42.389 +			   JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  42.390 +			   JDIMENSION out_rows_avail)
  42.391 +{
  42.392 +  my_main_ptr main = (my_main_ptr) cinfo->main;
  42.393 +
  42.394 +  /* Read input data if we haven't filled the main buffer yet */
  42.395 +  if (! main->buffer_full) {
  42.396 +    if (! (*cinfo->coef->decompress_data) (cinfo,
  42.397 +					   main->xbuffer[main->whichptr]))
  42.398 +      return;			/* suspension forced, can do nothing more */
  42.399 +    main->buffer_full = TRUE;	/* OK, we have an iMCU row to work with */
  42.400 +    main->iMCU_row_ctr++;	/* count rows received */
  42.401 +  }
  42.402 +
  42.403 +  /* Postprocessor typically will not swallow all the input data it is handed
  42.404 +   * in one call (due to filling the output buffer first).  Must be prepared
  42.405 +   * to exit and restart.  This switch lets us keep track of how far we got.
  42.406 +   * Note that each case falls through to the next on successful completion.
  42.407 +   */
  42.408 +  switch (main->context_state) {
  42.409 +  case CTX_POSTPONED_ROW:
  42.410 +    /* Call postprocessor using previously set pointers for postponed row */
  42.411 +    (*cinfo->post->post_process_data) (cinfo, main->xbuffer[main->whichptr],
  42.412 +			&main->rowgroup_ctr, main->rowgroups_avail,
  42.413 +			output_buf, out_row_ctr, out_rows_avail);
  42.414 +    if (main->rowgroup_ctr < main->rowgroups_avail)
  42.415 +      return;			/* Need to suspend */
  42.416 +    main->context_state = CTX_PREPARE_FOR_IMCU;
  42.417 +    if (*out_row_ctr >= out_rows_avail)
  42.418 +      return;			/* Postprocessor exactly filled output buf */
  42.419 +    /*FALLTHROUGH*/
  42.420 +  case CTX_PREPARE_FOR_IMCU:
  42.421 +    /* Prepare to process first M-1 row groups of this iMCU row */
  42.422 +    main->rowgroup_ctr = 0;
  42.423 +    main->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  42.424 +    /* Check for bottom of image: if so, tweak pointers to "duplicate"
  42.425 +     * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  42.426 +     */
  42.427 +    if (main->iMCU_row_ctr == cinfo->total_iMCU_rows)
  42.428 +      set_bottom_pointers(cinfo);
  42.429 +    main->context_state = CTX_PROCESS_IMCU;
  42.430 +    /*FALLTHROUGH*/
  42.431 +  case CTX_PROCESS_IMCU:
  42.432 +    /* Call postprocessor using previously set pointers */
  42.433 +    (*cinfo->post->post_process_data) (cinfo, main->xbuffer[main->whichptr],
  42.434 +			&main->rowgroup_ctr, main->rowgroups_avail,
  42.435 +			output_buf, out_row_ctr, out_rows_avail);
  42.436 +    if (main->rowgroup_ctr < main->rowgroups_avail)
  42.437 +      return;			/* Need to suspend */
  42.438 +    /* After the first iMCU, change wraparound pointers to normal state */
  42.439 +    if (main->iMCU_row_ctr == 1)
  42.440 +      set_wraparound_pointers(cinfo);
  42.441 +    /* Prepare to load new iMCU row using other xbuffer list */
  42.442 +    main->whichptr ^= 1;	/* 0=>1 or 1=>0 */
  42.443 +    main->buffer_full = FALSE;
  42.444 +    /* Still need to process last row group of this iMCU row, */
  42.445 +    /* which is saved at index M+1 of the other xbuffer */
  42.446 +    main->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  42.447 +    main->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  42.448 +    main->context_state = CTX_POSTPONED_ROW;
  42.449 +  }
  42.450 +}
  42.451 +
  42.452 +
  42.453 +/*
  42.454 + * Process some data.
  42.455 + * Final pass of two-pass quantization: just call the postprocessor.
  42.456 + * Source data will be the postprocessor controller's internal buffer.
  42.457 + */
  42.458 +
  42.459 +#ifdef QUANT_2PASS_SUPPORTED
  42.460 +
  42.461 +METHODDEF(void)
  42.462 +process_data_crank_post (j_decompress_ptr cinfo,
  42.463 +			 JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  42.464 +			 JDIMENSION out_rows_avail)
  42.465 +{
  42.466 +  (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  42.467 +				     (JDIMENSION *) NULL, (JDIMENSION) 0,
  42.468 +				     output_buf, out_row_ctr, out_rows_avail);
  42.469 +}
  42.470 +
  42.471 +#endif /* QUANT_2PASS_SUPPORTED */
  42.472 +
  42.473 +
  42.474 +/*
  42.475 + * Initialize main buffer controller.
  42.476 + */
  42.477 +
  42.478 +GLOBAL(void)
  42.479 +jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  42.480 +{
  42.481 +  my_main_ptr main;
  42.482 +  int ci, rgroup, ngroups;
  42.483 +  jpeg_component_info *compptr;
  42.484 +
  42.485 +  main = (my_main_ptr)
  42.486 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  42.487 +				SIZEOF(my_main_controller));
  42.488 +  cinfo->main = (struct jpeg_d_main_controller *) main;
  42.489 +  main->pub.start_pass = start_pass_main;
  42.490 +
  42.491 +  if (need_full_buffer)		/* shouldn't happen */
  42.492 +    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  42.493 +
  42.494 +  /* Allocate the workspace.
  42.495 +   * ngroups is the number of row groups we need.
  42.496 +   */
  42.497 +  if (cinfo->upsample->need_context_rows) {
  42.498 +    if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  42.499 +      ERREXIT(cinfo, JERR_NOTIMPL);
  42.500 +    alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  42.501 +    ngroups = cinfo->min_DCT_scaled_size + 2;
  42.502 +  } else {
  42.503 +    ngroups = cinfo->min_DCT_scaled_size;
  42.504 +  }
  42.505 +
  42.506 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  42.507 +       ci++, compptr++) {
  42.508 +    rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  42.509 +      cinfo->min_DCT_scaled_size; /* height of a row group of component */
  42.510 +    main->buffer[ci] = (*cinfo->mem->alloc_sarray)
  42.511 +			((j_common_ptr) cinfo, JPOOL_IMAGE,
  42.512 +			 compptr->width_in_blocks * compptr->DCT_scaled_size,
  42.513 +			 (JDIMENSION) (rgroup * ngroups));
  42.514 +  }
  42.515 +}
    43.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    43.2 +++ b/libs/libjpeg/jdmarker.c	Thu Sep 08 06:28:38 2011 +0300
    43.3 @@ -0,0 +1,1360 @@
    43.4 +/*
    43.5 + * jdmarker.c
    43.6 + *
    43.7 + * Copyright (C) 1991-1998, Thomas G. Lane.
    43.8 + * This file is part of the Independent JPEG Group's software.
    43.9 + * For conditions of distribution and use, see the accompanying README file.
   43.10 + *
   43.11 + * This file contains routines to decode JPEG datastream markers.
   43.12 + * Most of the complexity arises from our desire to support input
   43.13 + * suspension: if not all of the data for a marker is available,
   43.14 + * we must exit back to the application.  On resumption, we reprocess
   43.15 + * the marker.
   43.16 + */
   43.17 +
   43.18 +#define JPEG_INTERNALS
   43.19 +#include "jinclude.h"
   43.20 +#include "jpeglib.h"
   43.21 +
   43.22 +
   43.23 +typedef enum {			/* JPEG marker codes */
   43.24 +  M_SOF0  = 0xc0,
   43.25 +  M_SOF1  = 0xc1,
   43.26 +  M_SOF2  = 0xc2,
   43.27 +  M_SOF3  = 0xc3,
   43.28 +  
   43.29 +  M_SOF5  = 0xc5,
   43.30 +  M_SOF6  = 0xc6,
   43.31 +  M_SOF7  = 0xc7,
   43.32 +  
   43.33 +  M_JPG   = 0xc8,
   43.34 +  M_SOF9  = 0xc9,
   43.35 +  M_SOF10 = 0xca,
   43.36 +  M_SOF11 = 0xcb,
   43.37 +  
   43.38 +  M_SOF13 = 0xcd,
   43.39 +  M_SOF14 = 0xce,
   43.40 +  M_SOF15 = 0xcf,
   43.41 +  
   43.42 +  M_DHT   = 0xc4,
   43.43 +  
   43.44 +  M_DAC   = 0xcc,
   43.45 +  
   43.46 +  M_RST0  = 0xd0,
   43.47 +  M_RST1  = 0xd1,
   43.48 +  M_RST2  = 0xd2,
   43.49 +  M_RST3  = 0xd3,
   43.50 +  M_RST4  = 0xd4,
   43.51 +  M_RST5  = 0xd5,
   43.52 +  M_RST6  = 0xd6,
   43.53 +  M_RST7  = 0xd7,
   43.54 +  
   43.55 +  M_SOI   = 0xd8,
   43.56 +  M_EOI   = 0xd9,
   43.57 +  M_SOS   = 0xda,
   43.58 +  M_DQT   = 0xdb,
   43.59 +  M_DNL   = 0xdc,
   43.60 +  M_DRI   = 0xdd,
   43.61 +  M_DHP   = 0xde,
   43.62 +  M_EXP   = 0xdf,
   43.63 +  
   43.64 +  M_APP0  = 0xe0,
   43.65 +  M_APP1  = 0xe1,
   43.66 +  M_APP2  = 0xe2,
   43.67 +  M_APP3  = 0xe3,
   43.68 +  M_APP4  = 0xe4,
   43.69 +  M_APP5  = 0xe5,
   43.70 +  M_APP6  = 0xe6,
   43.71 +  M_APP7  = 0xe7,
   43.72 +  M_APP8  = 0xe8,
   43.73 +  M_APP9  = 0xe9,
   43.74 +  M_APP10 = 0xea,
   43.75 +  M_APP11 = 0xeb,
   43.76 +  M_APP12 = 0xec,
   43.77 +  M_APP13 = 0xed,
   43.78 +  M_APP14 = 0xee,
   43.79 +  M_APP15 = 0xef,
   43.80 +  
   43.81 +  M_JPG0  = 0xf0,
   43.82 +  M_JPG13 = 0xfd,
   43.83 +  M_COM   = 0xfe,
   43.84 +  
   43.85 +  M_TEM   = 0x01,
   43.86 +  
   43.87 +  M_ERROR = 0x100
   43.88 +} JPEG_MARKER;
   43.89 +
   43.90 +
   43.91 +/* Private state */
   43.92 +
   43.93 +typedef struct {
   43.94 +  struct jpeg_marker_reader pub; /* public fields */
   43.95 +
   43.96 +  /* Application-overridable marker processing methods */
   43.97 +  jpeg_marker_parser_method process_COM;
   43.98 +  jpeg_marker_parser_method process_APPn[16];
   43.99 +
  43.100 +  /* Limit on marker data length to save for each marker type */
  43.101 +  unsigned int length_limit_COM;
  43.102 +  unsigned int length_limit_APPn[16];
  43.103 +
  43.104 +  /* Status of COM/APPn marker saving */
  43.105 +  jpeg_saved_marker_ptr cur_marker;	/* NULL if not processing a marker */
  43.106 +  unsigned int bytes_read;		/* data bytes read so far in marker */
  43.107 +  /* Note: cur_marker is not linked into marker_list until it's all read. */
  43.108 +} my_marker_reader;
  43.109 +
  43.110 +typedef my_marker_reader * my_marker_ptr;
  43.111 +
  43.112 +
  43.113 +/*
  43.114 + * Macros for fetching data from the data source module.
  43.115 + *
  43.116 + * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  43.117 + * the current restart point; we update them only when we have reached a
  43.118 + * suitable place to restart if a suspension occurs.
  43.119 + */
  43.120 +
  43.121 +/* Declare and initialize local copies of input pointer/count */
  43.122 +#define INPUT_VARS(cinfo)  \
  43.123 +	struct jpeg_source_mgr * datasrc = (cinfo)->src;  \
  43.124 +	const JOCTET * next_input_byte = datasrc->next_input_byte;  \
  43.125 +	size_t bytes_in_buffer = datasrc->bytes_in_buffer
  43.126 +
  43.127 +/* Unload the local copies --- do this only at a restart boundary */
  43.128 +#define INPUT_SYNC(cinfo)  \
  43.129 +	( datasrc->next_input_byte = next_input_byte,  \
  43.130 +	  datasrc->bytes_in_buffer = bytes_in_buffer )
  43.131 +
  43.132 +/* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  43.133 +#define INPUT_RELOAD(cinfo)  \
  43.134 +	( next_input_byte = datasrc->next_input_byte,  \
  43.135 +	  bytes_in_buffer = datasrc->bytes_in_buffer )
  43.136 +
  43.137 +/* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  43.138 + * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  43.139 + * but we must reload the local copies after a successful fill.
  43.140 + */
  43.141 +#define MAKE_BYTE_AVAIL(cinfo,action)  \
  43.142 +	if (bytes_in_buffer == 0) {  \
  43.143 +	  if (! (*datasrc->fill_input_buffer) (cinfo))  \
  43.144 +	    { action; }  \
  43.145 +	  INPUT_RELOAD(cinfo);  \
  43.146 +	}
  43.147 +
  43.148 +/* Read a byte into variable V.
  43.149 + * If must suspend, take the specified action (typically "return FALSE").
  43.150 + */
  43.151 +#define INPUT_BYTE(cinfo,V,action)  \
  43.152 +	MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  43.153 +		  bytes_in_buffer--; \
  43.154 +		  V = GETJOCTET(*next_input_byte++); )
  43.155 +
  43.156 +/* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  43.157 + * V should be declared unsigned int or perhaps INT32.
  43.158 + */
  43.159 +#define INPUT_2BYTES(cinfo,V,action)  \
  43.160 +	MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  43.161 +		  bytes_in_buffer--; \
  43.162 +		  V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  43.163 +		  MAKE_BYTE_AVAIL(cinfo,action); \
  43.164 +		  bytes_in_buffer--; \
  43.165 +		  V += GETJOCTET(*next_input_byte++); )
  43.166 +
  43.167 +
  43.168 +/*
  43.169 + * Routines to process JPEG markers.
  43.170 + *
  43.171 + * Entry condition: JPEG marker itself has been read and its code saved
  43.172 + *   in cinfo->unread_marker; input restart point is just after the marker.
  43.173 + *
  43.174 + * Exit: if return TRUE, have read and processed any parameters, and have
  43.175 + *   updated the restart point to point after the parameters.
  43.176 + *   If return FALSE, was forced to suspend before reaching end of
  43.177 + *   marker parameters; restart point has not been moved.  Same routine
  43.178 + *   will be called again after application supplies more input data.
  43.179 + *
  43.180 + * This approach to suspension assumes that all of a marker's parameters
  43.181 + * can fit into a single input bufferload.  This should hold for "normal"
  43.182 + * markers.  Some COM/APPn markers might have large parameter segments
  43.183 + * that might not fit.  If we are simply dropping such a marker, we use
  43.184 + * skip_input_data to get past it, and thereby put the problem on the
  43.185 + * source manager's shoulders.  If we are saving the marker's contents
  43.186 + * into memory, we use a slightly different convention: when forced to
  43.187 + * suspend, the marker processor updates the restart point to the end of
  43.188 + * what it's consumed (ie, the end of the buffer) before returning FALSE.
  43.189 + * On resumption, cinfo->unread_marker still contains the marker code,
  43.190 + * but the data source will point to the next chunk of marker data.
  43.191 + * The marker processor must retain internal state to deal with this.
  43.192 + *
  43.193 + * Note that we don't bother to avoid duplicate trace messages if a
  43.194 + * suspension occurs within marker parameters.  Other side effects
  43.195 + * require more care.
  43.196 + */
  43.197 +
  43.198 +
  43.199 +LOCAL(boolean)
  43.200 +get_soi (j_decompress_ptr cinfo)
  43.201 +/* Process an SOI marker */
  43.202 +{
  43.203 +  int i;
  43.204 +  
  43.205 +  TRACEMS(cinfo, 1, JTRC_SOI);
  43.206 +
  43.207 +  if (cinfo->marker->saw_SOI)
  43.208 +    ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  43.209 +
  43.210 +  /* Reset all parameters that are defined to be reset by SOI */
  43.211 +
  43.212 +  for (i = 0; i < NUM_ARITH_TBLS; i++) {
  43.213 +    cinfo->arith_dc_L[i] = 0;
  43.214 +    cinfo->arith_dc_U[i] = 1;
  43.215 +    cinfo->arith_ac_K[i] = 5;
  43.216 +  }
  43.217 +  cinfo->restart_interval = 0;
  43.218 +
  43.219 +  /* Set initial assumptions for colorspace etc */
  43.220 +
  43.221 +  cinfo->jpeg_color_space = JCS_UNKNOWN;
  43.222 +  cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  43.223 +
  43.224 +  cinfo->saw_JFIF_marker = FALSE;
  43.225 +  cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  43.226 +  cinfo->JFIF_minor_version = 1;
  43.227 +  cinfo->density_unit = 0;
  43.228 +  cinfo->X_density = 1;
  43.229 +  cinfo->Y_density = 1;
  43.230 +  cinfo->saw_Adobe_marker = FALSE;
  43.231 +  cinfo->Adobe_transform = 0;
  43.232 +
  43.233 +  cinfo->marker->saw_SOI = TRUE;
  43.234 +
  43.235 +  return TRUE;
  43.236 +}
  43.237 +
  43.238 +
  43.239 +LOCAL(boolean)
  43.240 +get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  43.241 +/* Process a SOFn marker */
  43.242 +{
  43.243 +  INT32 length;
  43.244 +  int c, ci;
  43.245 +  jpeg_component_info * compptr;
  43.246 +  INPUT_VARS(cinfo);
  43.247 +
  43.248 +  cinfo->progressive_mode = is_prog;
  43.249 +  cinfo->arith_code = is_arith;
  43.250 +
  43.251 +  INPUT_2BYTES(cinfo, length, return FALSE);
  43.252 +
  43.253 +  INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  43.254 +  INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  43.255 +  INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  43.256 +  INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  43.257 +
  43.258 +  length -= 8;
  43.259 +
  43.260 +  TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  43.261 +	   (int) cinfo->image_width, (int) cinfo->image_height,
  43.262 +	   cinfo->num_components);
  43.263 +
  43.264 +  if (cinfo->marker->saw_SOF)
  43.265 +    ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  43.266 +
  43.267 +  /* We don't support files in which the image height is initially specified */
  43.268 +  /* as 0 and is later redefined by DNL.  As long as we have to check that,  */
  43.269 +  /* might as well have a general sanity check. */
  43.270 +  if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  43.271 +      || cinfo->num_components <= 0)
  43.272 +    ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  43.273 +
  43.274 +  if (length != (cinfo->num_components * 3))
  43.275 +    ERREXIT(cinfo, JERR_BAD_LENGTH);
  43.276 +
  43.277 +  if (cinfo->comp_info == NULL)	/* do only once, even if suspend */
  43.278 +    cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  43.279 +			((j_common_ptr) cinfo, JPOOL_IMAGE,
  43.280 +			 cinfo->num_components * SIZEOF(jpeg_component_info));
  43.281 +  
  43.282 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  43.283 +       ci++, compptr++) {
  43.284 +    compptr->component_index = ci;
  43.285 +    INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  43.286 +    INPUT_BYTE(cinfo, c, return FALSE);
  43.287 +    compptr->h_samp_factor = (c >> 4) & 15;
  43.288 +    compptr->v_samp_factor = (c     ) & 15;
  43.289 +    INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  43.290 +
  43.291 +    TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  43.292 +	     compptr->component_id, compptr->h_samp_factor,
  43.293 +	     compptr->v_samp_factor, compptr->quant_tbl_no);
  43.294 +  }
  43.295 +
  43.296 +  cinfo->marker->saw_SOF = TRUE;
  43.297 +
  43.298 +  INPUT_SYNC(cinfo);
  43.299 +  return TRUE;
  43.300 +}
  43.301 +
  43.302 +
  43.303 +LOCAL(boolean)
  43.304 +get_sos (j_decompress_ptr cinfo)
  43.305 +/* Process a SOS marker */
  43.306 +{
  43.307 +  INT32 length;
  43.308 +  int i, ci, n, c, cc;
  43.309 +  jpeg_component_info * compptr;
  43.310 +  INPUT_VARS(cinfo);
  43.311 +
  43.312 +  if (! cinfo->marker->saw_SOF)
  43.313 +    ERREXIT(cinfo, JERR_SOS_NO_SOF);
  43.314 +
  43.315 +  INPUT_2BYTES(cinfo, length, return FALSE);
  43.316 +
  43.317 +  INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  43.318 +
  43.319 +  TRACEMS1(cinfo, 1, JTRC_SOS, n);
  43.320 +
  43.321 +  if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  43.322 +    ERREXIT(cinfo, JERR_BAD_LENGTH);
  43.323 +
  43.324 +  cinfo->comps_in_scan = n;
  43.325 +
  43.326 +  /* Collect the component-spec parameters */
  43.327 +
  43.328 +  for (i = 0; i < n; i++) {
  43.329 +    INPUT_BYTE(cinfo, cc, return FALSE);
  43.330 +    INPUT_BYTE(cinfo, c, return FALSE);
  43.331 +    
  43.332 +    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  43.333 +	 ci++, compptr++) {
  43.334 +      if (cc == compptr->component_id)
  43.335 +	goto id_found;
  43.336 +    }
  43.337 +
  43.338 +    ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  43.339 +
  43.340 +  id_found:
  43.341 +
  43.342 +    cinfo->cur_comp_info[i] = compptr;
  43.343 +    compptr->dc_tbl_no = (c >> 4) & 15;
  43.344 +    compptr->ac_tbl_no = (c     ) & 15;
  43.345 +    
  43.346 +    TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  43.347 +	     compptr->dc_tbl_no, compptr->ac_tbl_no);
  43.348 +  }
  43.349 +
  43.350 +  /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  43.351 +  INPUT_BYTE(cinfo, c, return FALSE);
  43.352 +  cinfo->Ss = c;
  43.353 +  INPUT_BYTE(cinfo, c, return FALSE);
  43.354 +  cinfo->Se = c;
  43.355 +  INPUT_BYTE(cinfo, c, return FALSE);
  43.356 +  cinfo->Ah = (c >> 4) & 15;
  43.357 +  cinfo->Al = (c     ) & 15;
  43.358 +
  43.359 +  TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  43.360 +	   cinfo->Ah, cinfo->Al);
  43.361 +
  43.362 +  /* Prepare to scan data & restart markers */
  43.363 +  cinfo->marker->next_restart_num = 0;
  43.364 +
  43.365 +  /* Count another SOS marker */
  43.366 +  cinfo->input_scan_number++;
  43.367 +
  43.368 +  INPUT_SYNC(cinfo);
  43.369 +  return TRUE;
  43.370 +}
  43.371 +
  43.372 +
  43.373 +#ifdef D_ARITH_CODING_SUPPORTED
  43.374 +
  43.375 +LOCAL(boolean)
  43.376 +get_dac (j_decompress_ptr cinfo)
  43.377 +/* Process a DAC marker */
  43.378 +{
  43.379 +  INT32 length;
  43.380 +  int index, val;
  43.381 +  INPUT_VARS(cinfo);
  43.382 +
  43.383 +  INPUT_2BYTES(cinfo, length, return FALSE);
  43.384 +  length -= 2;
  43.385 +  
  43.386 +  while (length > 0) {
  43.387 +    INPUT_BYTE(cinfo, index, return FALSE);
  43.388 +    INPUT_BYTE(cinfo, val, return FALSE);
  43.389 +
  43.390 +    length -= 2;
  43.391 +
  43.392 +    TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  43.393 +
  43.394 +    if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  43.395 +      ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  43.396 +
  43.397 +    if (index >= NUM_ARITH_TBLS) { /* define AC table */
  43.398 +      cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  43.399 +    } else {			/* define DC table */
  43.400 +      cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  43.401 +      cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  43.402 +      if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  43.403 +	ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  43.404 +    }
  43.405 +  }
  43.406 +
  43.407 +  if (length != 0)
  43.408 +    ERREXIT(cinfo, JERR_BAD_LENGTH);
  43.409 +
  43.410 +  INPUT_SYNC(cinfo);
  43.411 +  return TRUE;
  43.412 +}
  43.413 +
  43.414 +#else /* ! D_ARITH_CODING_SUPPORTED */
  43.415 +
  43.416 +#define get_dac(cinfo)  skip_variable(cinfo)
  43.417 +
  43.418 +#endif /* D_ARITH_CODING_SUPPORTED */
  43.419 +
  43.420 +
  43.421 +LOCAL(boolean)
  43.422 +get_dht (j_decompress_ptr cinfo)
  43.423 +/* Process a DHT marker */
  43.424 +{
  43.425 +  INT32 length;
  43.426 +  UINT8 bits[17];
  43.427 +  UINT8 huffval[256];
  43.428 +  int i, index, count;
  43.429 +  JHUFF_TBL **htblptr;
  43.430 +  INPUT_VARS(cinfo);
  43.431 +
  43.432 +  INPUT_2BYTES(cinfo, length, return FALSE);
  43.433 +  length -= 2;
  43.434 +  
  43.435 +  while (length > 16) {
  43.436 +    INPUT_BYTE(cinfo, index, return FALSE);
  43.437 +
  43.438 +    TRACEMS1(cinfo, 1, JTRC_DHT, index);
  43.439 +      
  43.440 +    bits[0] = 0;
  43.441 +    count = 0;
  43.442 +    for (i = 1; i <= 16; i++) {
  43.443 +      INPUT_BYTE(cinfo, bits[i], return FALSE);
  43.444 +      count += bits[i];
  43.445 +    }
  43.446 +
  43.447 +    length -= 1 + 16;
  43.448 +
  43.449 +    TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  43.450 +	     bits[1], bits[2], bits[3], bits[4],
  43.451 +	     bits[5], bits[6], bits[7], bits[8]);
  43.452 +    TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  43.453 +	     bits[9], bits[10], bits[11], bits[12],
  43.454 +	     bits[13], bits[14], bits[15], bits[16]);
  43.455 +
  43.456 +    /* Here we just do minimal validation of the counts to avoid walking
  43.457 +     * off the end of our table space.  jdhuff.c will check more carefully.
  43.458 +     */
  43.459 +    if (count > 256 || ((INT32) count) > length)
  43.460 +      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  43.461 +
  43.462 +    for (i = 0; i < count; i++)
  43.463 +      INPUT_BYTE(cinfo, huffval[i], return FALSE);
  43.464 +
  43.465 +    length -= count;
  43.466 +
  43.467 +    if (index & 0x10) {		/* AC table definition */
  43.468 +      index -= 0x10;
  43.469 +      htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  43.470 +    } else {			/* DC table definition */
  43.471 +      htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  43.472 +    }
  43.473 +
  43.474 +    if (index < 0 || index >= NUM_HUFF_TBLS)
  43.475 +      ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  43.476 +
  43.477 +    if (*htblptr == NULL)
  43.478 +      *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  43.479 +  
  43.480 +    MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  43.481 +    MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  43.482 +  }
  43.483 +
  43.484 +  if (length != 0)
  43.485 +    ERREXIT(cinfo, JERR_BAD_LENGTH);
  43.486 +
  43.487 +  INPUT_SYNC(cinfo);
  43.488 +  return TRUE;
  43.489 +}
  43.490 +
  43.491 +
  43.492 +LOCAL(boolean)
  43.493 +get_dqt (j_decompress_ptr cinfo)
  43.494 +/* Process a DQT marker */
  43.495 +{
  43.496 +  INT32 length;
  43.497 +  int n, i, prec;
  43.498 +  unsigned int tmp;
  43.499 +  JQUANT_TBL *quant_ptr;
  43.500 +  INPUT_VARS(cinfo);
  43.501 +
  43.502 +  INPUT_2BYTES(cinfo, length, return FALSE);
  43.503 +  length -= 2;
  43.504 +
  43.505 +  while (length > 0) {
  43.506 +    INPUT_BYTE(cinfo, n, return FALSE);
  43.507 +    prec = n >> 4;
  43.508 +    n &= 0x0F;
  43.509 +
  43.510 +    TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  43.511 +
  43.512 +    if (n >= NUM_QUANT_TBLS)
  43.513 +      ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  43.514 +      
  43.515 +    if (cinfo->quant_tbl_ptrs[n] == NULL)
  43.516 +      cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  43.517 +    quant_ptr = cinfo->quant_tbl_ptrs[n];
  43.518 +
  43.519 +    for (i = 0; i < DCTSIZE2; i++) {
  43.520 +      if (prec)
  43.521 +	INPUT_2BYTES(cinfo, tmp, return FALSE);
  43.522 +      else
  43.523 +	INPUT_BYTE(cinfo, tmp, return FALSE);
  43.524 +      /* We convert the zigzag-order table to natural array order. */
  43.525 +      quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  43.526 +    }
  43.527 +
  43.528 +    if (cinfo->err->trace_level >= 2) {
  43.529 +      for (i = 0; i < DCTSIZE2; i += 8) {
  43.530 +	TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  43.531 +		 quant_ptr->quantval[i],   quant_ptr->quantval[i+1],
  43.532 +		 quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  43.533 +		 quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  43.534 +		 quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  43.535 +      }
  43.536 +    }
  43.537 +
  43.538 +    length -= DCTSIZE2+1;
  43.539 +    if (prec) length -= DCTSIZE2;
  43.540 +  }
  43.541 +
  43.542 +  if (length != 0)
  43.543 +    ERREXIT(cinfo, JERR_BAD_LENGTH);
  43.544 +
  43.545 +  INPUT_SYNC(cinfo);
  43.546 +  return TRUE;
  43.547 +}
  43.548 +
  43.549 +
  43.550 +LOCAL(boolean)
  43.551 +get_dri (j_decompress_ptr cinfo)
  43.552 +/* Process a DRI marker */
  43.553 +{
  43.554 +  INT32 length;
  43.555 +  unsigned int tmp;
  43.556 +  INPUT_VARS(cinfo);
  43.557 +
  43.558 +  INPUT_2BYTES(cinfo, length, return FALSE);
  43.559 +  
  43.560 +  if (length != 4)
  43.561 +    ERREXIT(cinfo, JERR_BAD_LENGTH);
  43.562 +
  43.563 +  INPUT_2BYTES(cinfo, tmp, return FALSE);
  43.564 +
  43.565 +  TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  43.566 +
  43.567 +  cinfo->restart_interval = tmp;
  43.568 +
  43.569 +  INPUT_SYNC(cinfo);
  43.570 +  return TRUE;
  43.571 +}
  43.572 +
  43.573 +
  43.574 +/*
  43.575 + * Routines for processing APPn and COM markers.
  43.576 + * These are either saved in memory or discarded, per application request.
  43.577 + * APP0 and APP14 are specially checked to see if they are
  43.578 + * JFIF and Adobe markers, respectively.
  43.579 + */
  43.580 +
  43.581 +#define APP0_DATA_LEN	14	/* Length of interesting data in APP0 */
  43.582 +#define APP14_DATA_LEN	12	/* Length of interesting data in APP14 */
  43.583 +#define APPN_DATA_LEN	14	/* Must be the largest of the above!! */
  43.584 +
  43.585 +
  43.586 +LOCAL(void)
  43.587 +examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  43.588 +	      unsigned int datalen, INT32 remaining)
  43.589 +/* Examine first few bytes from an APP0.
  43.590 + * Take appropriate action if it is a JFIF marker.
  43.591 + * datalen is # of bytes at data[], remaining is length of rest of marker data.
  43.592 + */
  43.593 +{
  43.594 +  INT32 totallen = (INT32) datalen + remaining;
  43.595 +
  43.596 +  if (datalen >= APP0_DATA_LEN &&
  43.597 +      GETJOCTET(data[0]) == 0x4A &&
  43.598 +      GETJOCTET(data[1]) == 0x46 &&
  43.599 +      GETJOCTET(data[2]) == 0x49 &&
  43.600 +      GETJOCTET(data[3]) == 0x46 &&
  43.601 +      GETJOCTET(data[4]) == 0) {
  43.602 +    /* Found JFIF APP0 marker: save info */
  43.603 +    cinfo->saw_JFIF_marker = TRUE;
  43.604 +    cinfo->JFIF_major_version = GETJOCTET(data[5]);
  43.605 +    cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  43.606 +    cinfo->density_unit = GETJOCTET(data[7]);
  43.607 +    cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  43.608 +    cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  43.609 +    /* Check version.
  43.610 +     * Major version must be 1, anything else signals an incompatible change.
  43.611 +     * (We used to treat this as an error, but now it's a nonfatal warning,
  43.612 +     * because some bozo at Hijaak couldn't read the spec.)
  43.613 +     * Minor version should be 0..2, but process anyway if newer.
  43.614 +     */
  43.615 +    if (cinfo->JFIF_major_version != 1)
  43.616 +      WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  43.617 +	      cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  43.618 +    /* Generate trace messages */
  43.619 +    TRACEMS5(cinfo, 1, JTRC_JFIF,
  43.620 +	     cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  43.621 +	     cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  43.622 +    /* Validate thumbnail dimensions and issue appropriate messages */
  43.623 +    if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  43.624 +      TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  43.625 +	       GETJOCTET(data[12]), GETJOCTET(data[13]));
  43.626 +    totallen -= APP0_DATA_LEN;
  43.627 +    if (totallen !=
  43.628 +	((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  43.629 +      TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  43.630 +  } else if (datalen >= 6 &&
  43.631 +      GETJOCTET(data[0]) == 0x4A &&
  43.632 +      GETJOCTET(data[1]) == 0x46 &&
  43.633 +      GETJOCTET(data[2]) == 0x58 &&
  43.634 +      GETJOCTET(data[3]) == 0x58 &&
  43.635 +      GETJOCTET(data[4]) == 0) {
  43.636 +    /* Found JFIF "JFXX" extension APP0 marker */
  43.637 +    /* The library doesn't actually do anything with these,
  43.638 +     * but we try to produce a helpful trace message.
  43.639 +     */
  43.640 +    switch (GETJOCTET(data[5])) {
  43.641 +    case 0x10:
  43.642 +      TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  43.643 +      break;
  43.644 +    case 0x11:
  43.645 +      TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  43.646 +      break;
  43.647 +    case 0x13:
  43.648 +      TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  43.649 +      break;
  43.650 +    default:
  43.651 +      TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  43.652 +	       GETJOCTET(data[5]), (int) totallen);
  43.653 +      break;
  43.654 +    }
  43.655 +  } else {
  43.656 +    /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  43.657 +    TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  43.658 +  }
  43.659 +}
  43.660 +
  43.661 +
  43.662 +LOCAL(void)
  43.663 +examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  43.664 +	       unsigned int datalen, INT32 remaining)
  43.665 +/* Examine first few bytes from an APP14.
  43.666 + * Take appropriate action if it is an Adobe marker.
  43.667 + * datalen is # of bytes at data[], remaining is length of rest of marker data.
  43.668 + */
  43.669 +{
  43.670 +  unsigned int version, flags0, flags1, transform;
  43.671 +
  43.672 +  if (datalen >= APP14_DATA_LEN &&
  43.673 +      GETJOCTET(data[0]) == 0x41 &&
  43.674 +      GETJOCTET(data[1]) == 0x64 &&
  43.675 +      GETJOCTET(data[2]) == 0x6F &&
  43.676 +      GETJOCTET(data[3]) == 0x62 &&
  43.677 +      GETJOCTET(data[4]) == 0x65) {
  43.678 +    /* Found Adobe APP14 marker */
  43.679 +    version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  43.680 +    flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  43.681 +    flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  43.682 +    transform = GETJOCTET(data[11]);
  43.683 +    TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  43.684 +    cinfo->saw_Adobe_marker = TRUE;
  43.685 +    cinfo->Adobe_transform = (UINT8) transform;
  43.686 +  } else {
  43.687 +    /* Start of APP14 does not match "Adobe", or too short */
  43.688 +    TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  43.689 +  }
  43.690 +}
  43.691 +
  43.692 +
  43.693 +METHODDEF(boolean)
  43.694 +get_interesting_appn (j_decompress_ptr cinfo)
  43.695 +/* Process an APP0 or APP14 marker without saving it */
  43.696 +{
  43.697 +  INT32 length;
  43.698 +  JOCTET b[APPN_DATA_LEN];
  43.699 +  unsigned int i, numtoread;
  43.700 +  INPUT_VARS(cinfo);
  43.701 +
  43.702 +  INPUT_2BYTES(cinfo, length, return FALSE);
  43.703 +  length -= 2;
  43.704 +
  43.705 +  /* get the interesting part of the marker data */
  43.706 +  if (length >= APPN_DATA_LEN)
  43.707 +    numtoread = APPN_DATA_LEN;
  43.708 +  else if (length > 0)
  43.709 +    numtoread = (unsigned int) length;
  43.710 +  else
  43.711 +    numtoread = 0;
  43.712 +  for (i = 0; i < numtoread; i++)
  43.713 +    INPUT_BYTE(cinfo, b[i], return FALSE);
  43.714 +  length -= numtoread;
  43.715 +
  43.716 +  /* process it */
  43.717 +  switch (cinfo->unread_marker) {
  43.718 +  case M_APP0:
  43.719 +    examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  43.720 +    break;
  43.721 +  case M_APP14:
  43.722 +    examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  43.723 +    break;
  43.724 +  default:
  43.725 +    /* can't get here unless jpeg_save_markers chooses wrong processor */
  43.726 +    ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  43.727 +    break;
  43.728 +  }
  43.729 +
  43.730 +  /* skip any remaining data -- could be lots */
  43.731 +  INPUT_SYNC(cinfo);
  43.732 +  if (length > 0)
  43.733 +    (*cinfo->src->skip_input_data) (cinfo, (long) length);
  43.734 +
  43.735 +  return TRUE;
  43.736 +}
  43.737 +
  43.738 +
  43.739 +#ifdef SAVE_MARKERS_SUPPORTED
  43.740 +
  43.741 +METHODDEF(boolean)
  43.742 +save_marker (j_decompress_ptr cinfo)
  43.743 +/* Save an APPn or COM marker into the marker list */
  43.744 +{
  43.745 +  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  43.746 +  jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  43.747 +  unsigned int bytes_read, data_length;
  43.748 +  JOCTET FAR * data;
  43.749 +  INT32 length = 0;
  43.750 +  INPUT_VARS(cinfo);
  43.751 +
  43.752 +  if (cur_marker == NULL) {
  43.753 +    /* begin reading a marker */
  43.754 +    INPUT_2BYTES(cinfo, length, return FALSE);
  43.755 +    length -= 2;
  43.756 +    if (length >= 0) {		/* watch out for bogus length word */
  43.757 +      /* figure out how much we want to save */
  43.758 +      unsigned int limit;
  43.759 +      if (cinfo->unread_marker == (int) M_COM)
  43.760 +	limit = marker->length_limit_COM;
  43.761 +      else
  43.762 +	limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  43.763 +      if ((unsigned int) length < limit)
  43.764 +	limit = (unsigned int) length;
  43.765 +      /* allocate and initialize the marker item */
  43.766 +      cur_marker = (jpeg_saved_marker_ptr)
  43.767 +	(*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  43.768 +				    SIZEOF(struct jpeg_marker_struct) + limit);
  43.769 +      cur_marker->next = NULL;
  43.770 +      cur_marker->marker = (UINT8) cinfo->unread_marker;
  43.771 +      cur_marker->original_length = (unsigned int) length;
  43.772 +      cur_marker->data_length = limit;
  43.773 +      /* data area is just beyond the jpeg_marker_struct */
  43.774 +      data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  43.775 +      marker->cur_marker = cur_marker;
  43.776 +      marker->bytes_read = 0;
  43.777 +      bytes_read = 0;
  43.778 +      data_length = limit;
  43.779 +    } else {
  43.780 +      /* deal with bogus length word */
  43.781 +      bytes_read = data_length = 0;
  43.782 +      data = NULL;
  43.783 +    }
  43.784 +  } else {
  43.785 +    /* resume reading a marker */
  43.786 +    bytes_read = marker->bytes_read;
  43.787 +    data_length = cur_marker->data_length;
  43.788 +    data = cur_marker->data + bytes_read;
  43.789 +  }
  43.790 +
  43.791 +  while (bytes_read < data_length) {
  43.792 +    INPUT_SYNC(cinfo);		/* move the restart point to here */
  43.793 +    marker->bytes_read = bytes_read;
  43.794 +    /* If there's not at least one byte in buffer, suspend */
  43.795 +    MAKE_BYTE_AVAIL(cinfo, return FALSE);
  43.796 +    /* Copy bytes with reasonable rapidity */
  43.797 +    while (bytes_read < data_length && bytes_in_buffer > 0) {
  43.798 +      *data++ = *next_input_byte++;
  43.799 +      bytes_in_buffer--;
  43.800 +      bytes_read++;
  43.801 +    }
  43.802 +  }
  43.803 +
  43.804 +  /* Done reading what we want to read */
  43.805 +  if (cur_marker != NULL) {	/* will be NULL if bogus length word */
  43.806 +    /* Add new marker to end of list */
  43.807 +    if (cinfo->marker_list == NULL) {
  43.808 +      cinfo->marker_list = cur_marker;
  43.809 +    } else {
  43.810 +      jpeg_saved_marker_ptr prev = cinfo->marker_list;
  43.811 +      while (prev->next != NULL)
  43.812 +	prev = prev->next;
  43.813 +      prev->next = cur_marker;
  43.814 +    }
  43.815 +    /* Reset pointer & calc remaining data length */
  43.816 +    data = cur_marker->data;
  43.817 +    length = cur_marker->original_length - data_length;
  43.818 +  }
  43.819 +  /* Reset to initial state for next marker */
  43.820 +  marker->cur_marker = NULL;
  43.821 +
  43.822 +  /* Process the marker if interesting; else just make a generic trace msg */
  43.823 +  switch (cinfo->unread_marker) {
  43.824 +  case M_APP0:
  43.825 +    examine_app0(cinfo, data, data_length, length);
  43.826 +    break;
  43.827 +  case M_APP14:
  43.828 +    examine_app14(cinfo, data, data_length, length);
  43.829 +    break;
  43.830 +  default:
  43.831 +    TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  43.832 +	     (int) (data_length + length));
  43.833 +    break;
  43.834 +  }
  43.835 +
  43.836 +  /* skip any remaining data -- could be lots */
  43.837 +  INPUT_SYNC(cinfo);		/* do before skip_input_data */
  43.838 +  if (length > 0)
  43.839 +    (*cinfo->src->skip_input_data) (cinfo, (long) length);
  43.840 +
  43.841 +  return TRUE;
  43.842 +}
  43.843 +
  43.844 +#endif /* SAVE_MARKERS_SUPPORTED */
  43.845 +
  43.846 +
  43.847 +METHODDEF(boolean)
  43.848 +skip_variable (j_decompress_ptr cinfo)
  43.849 +/* Skip over an unknown or uninteresting variable-length marker */
  43.850 +{
  43.851 +  INT32 length;
  43.852 +  INPUT_VARS(cinfo);
  43.853 +
  43.854 +  INPUT_2BYTES(cinfo, length, return FALSE);
  43.855 +  length -= 2;
  43.856 +  
  43.857 +  TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  43.858 +
  43.859 +  INPUT_SYNC(cinfo);		/* do before skip_input_data */
  43.860 +  if (length > 0)
  43.861 +    (*cinfo->src->skip_input_data) (cinfo, (long) length);
  43.862 +
  43.863 +  return TRUE;
  43.864 +}
  43.865 +
  43.866 +
  43.867 +/*
  43.868 + * Find the next JPEG marker, save it in cinfo->unread_marker.
  43.869 + * Returns FALSE if had to suspend before reaching a marker;
  43.870 + * in that case cinfo->unread_marker is unchanged.
  43.871 + *
  43.872 + * Note that the result might not be a valid marker code,
  43.873 + * but it will never be 0 or FF.
  43.874 + */
  43.875 +
  43.876 +LOCAL(boolean)
  43.877 +next_marker (j_decompress_ptr cinfo)
  43.878 +{
  43.879 +  int c;
  43.880 +  INPUT_VARS(cinfo);
  43.881 +
  43.882 +  for (;;) {
  43.883 +    INPUT_BYTE(cinfo, c, return FALSE);
  43.884 +    /* Skip any non-FF bytes.
  43.885 +     * This may look a bit inefficient, but it will not occur in a valid file.
  43.886 +     * We sync after each discarded byte so that a suspending data source
  43.887 +     * can discard the byte from its buffer.
  43.888 +     */
  43.889 +    while (c != 0xFF) {
  43.890 +      cinfo->marker->discarded_bytes++;
  43.891 +      INPUT_SYNC(cinfo);
  43.892 +      INPUT_BYTE(cinfo, c, return FALSE);
  43.893 +    }
  43.894 +    /* This loop swallows any duplicate FF bytes.  Extra FFs are legal as
  43.895 +     * pad bytes, so don't count them in discarded_bytes.  We assume there
  43.896 +     * will not be so many consecutive FF bytes as to overflow a suspending
  43.897 +     * data source's input buffer.
  43.898 +     */
  43.899 +    do {
  43.900 +      INPUT_BYTE(cinfo, c, return FALSE);
  43.901 +    } while (c == 0xFF);
  43.902 +    if (c != 0)
  43.903 +      break;			/* found a valid marker, exit loop */
  43.904 +    /* Reach here if we found a stuffed-zero data sequence (FF/00).
  43.905 +     * Discard it and loop back to try again.
  43.906 +     */
  43.907 +    cinfo->marker->discarded_bytes += 2;
  43.908 +    INPUT_SYNC(cinfo);
  43.909 +  }
  43.910 +
  43.911 +  if (cinfo->marker->discarded_bytes != 0) {
  43.912 +    WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  43.913 +    cinfo->marker->discarded_bytes = 0;
  43.914 +  }
  43.915 +
  43.916 +  cinfo->unread_marker = c;
  43.917 +
  43.918 +  INPUT_SYNC(cinfo);
  43.919 +  return TRUE;
  43.920 +}
  43.921 +
  43.922 +
  43.923 +LOCAL(boolean)
  43.924 +first_marker (j_decompress_ptr cinfo)
  43.925 +/* Like next_marker, but used to obtain the initial SOI marker. */
  43.926 +/* For this marker, we do not allow preceding garbage or fill; otherwise,
  43.927 + * we might well scan an entire input file before realizing it ain't JPEG.
  43.928 + * If an application wants to process non-JFIF files, it must seek to the
  43.929 + * SOI before calling the JPEG library.
  43.930 + */
  43.931 +{
  43.932 +  int c, c2;
  43.933 +  INPUT_VARS(cinfo);
  43.934 +
  43.935 +  INPUT_BYTE(cinfo, c, return FALSE);
  43.936 +  INPUT_BYTE(cinfo, c2, return FALSE);
  43.937 +  if (c != 0xFF || c2 != (int) M_SOI)
  43.938 +    ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  43.939 +
  43.940 +  cinfo->unread_marker = c2;
  43.941 +
  43.942 +  INPUT_SYNC(cinfo);
  43.943 +  return TRUE;
  43.944 +}
  43.945 +
  43.946 +
  43.947 +/*
  43.948 + * Read markers until SOS or EOI.
  43.949 + *
  43.950 + * Returns same codes as are defined for jpeg_consume_input:
  43.951 + * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  43.952 + */
  43.953 +
  43.954 +METHODDEF(int)
  43.955 +read_markers (j_decompress_ptr cinfo)
  43.956 +{
  43.957 +  /* Outer loop repeats once for each marker. */
  43.958 +  for (;;) {
  43.959 +    /* Collect the marker proper, unless we already did. */
  43.960 +    /* NB: first_marker() enforces the requirement that SOI appear first. */
  43.961 +    if (cinfo->unread_marker == 0) {
  43.962 +      if (! cinfo->marker->saw_SOI) {
  43.963 +	if (! first_marker(cinfo))
  43.964 +	  return JPEG_SUSPENDED;
  43.965 +      } else {
  43.966 +	if (! next_marker(cinfo))
  43.967 +	  return JPEG_SUSPENDED;
  43.968 +      }
  43.969 +    }
  43.970 +    /* At this point cinfo->unread_marker contains the marker code and the
  43.971 +     * input point is just past the marker proper, but before any parameters.
  43.972 +     * A suspension will cause us to return with this state still true.
  43.973 +     */
  43.974 +    switch (cinfo->unread_marker) {
  43.975 +    case M_SOI:
  43.976 +      if (! get_soi(cinfo))
  43.977 +	return JPEG_SUSPENDED;
  43.978 +      break;
  43.979 +
  43.980 +    case M_SOF0:		/* Baseline */
  43.981 +    case M_SOF1:		/* Extended sequential, Huffman */
  43.982 +      if (! get_sof(cinfo, FALSE, FALSE))
  43.983 +	return JPEG_SUSPENDED;
  43.984 +      break;
  43.985 +
  43.986 +    case M_SOF2:		/* Progressive, Huffman */
  43.987 +      if (! get_sof(cinfo, TRUE, FALSE))
  43.988 +	return JPEG_SUSPENDED;
  43.989 +      break;
  43.990 +
  43.991 +    case M_SOF9:		/* Extended sequential, arithmetic */
  43.992 +      if (! get_sof(cinfo, FALSE, TRUE))
  43.993 +	return JPEG_SUSPENDED;
  43.994 +      break;
  43.995 +
  43.996 +    case M_SOF10:		/* Progressive, arithmetic */
  43.997 +      if (! get_sof(cinfo, TRUE, TRUE))
  43.998 +	return JPEG_SUSPENDED;
  43.999 +      break;
 43.1000 +
 43.1001 +    /* Currently unsupported SOFn types */
 43.1002 +    case M_SOF3:		/* Lossless, Huffman */
 43.1003 +    case M_SOF5:		/* Differential sequential, Huffman */
 43.1004 +    case M_SOF6:		/* Differential progressive, Huffman */
 43.1005 +    case M_SOF7:		/* Differential lossless, Huffman */
 43.1006 +    case M_JPG:			/* Reserved for JPEG extensions */
 43.1007 +    case M_SOF11:		/* Lossless, arithmetic */
 43.1008 +    case M_SOF13:		/* Differential sequential, arithmetic */
 43.1009 +    case M_SOF14:		/* Differential progressive, arithmetic */
 43.1010 +    case M_SOF15:		/* Differential lossless, arithmetic */
 43.1011 +      ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
 43.1012 +      break;
 43.1013 +
 43.1014 +    case M_SOS:
 43.1015 +      if (! get_sos(cinfo))
 43.1016 +	return JPEG_SUSPENDED;
 43.1017 +      cinfo->unread_marker = 0;	/* processed the marker */
 43.1018 +      return JPEG_REACHED_SOS;
 43.1019 +    
 43.1020 +    case M_EOI:
 43.1021 +      TRACEMS(cinfo, 1, JTRC_EOI);
 43.1022 +      cinfo->unread_marker = 0;	/* processed the marker */
 43.1023 +      return JPEG_REACHED_EOI;
 43.1024 +      
 43.1025 +    case M_DAC:
 43.1026 +      if (! get_dac(cinfo))
 43.1027 +	return JPEG_SUSPENDED;
 43.1028 +      break;
 43.1029 +      
 43.1030 +    case M_DHT:
 43.1031 +      if (! get_dht(cinfo))
 43.1032 +	return JPEG_SUSPENDED;
 43.1033 +      break;
 43.1034 +      
 43.1035 +    case M_DQT:
 43.1036 +      if (! get_dqt(cinfo))
 43.1037 +	return JPEG_SUSPENDED;
 43.1038 +      break;
 43.1039 +      
 43.1040 +    case M_DRI:
 43.1041 +      if (! get_dri(cinfo))
 43.1042 +	return JPEG_SUSPENDED;
 43.1043 +      break;
 43.1044 +      
 43.1045 +    case M_APP0:
 43.1046 +    case M_APP1:
 43.1047 +    case M_APP2:
 43.1048 +    case M_APP3:
 43.1049 +    case M_APP4:
 43.1050 +    case M_APP5:
 43.1051 +    case M_APP6:
 43.1052 +    case M_APP7:
 43.1053 +    case M_APP8:
 43.1054 +    case M_APP9:
 43.1055 +    case M_APP10:
 43.1056 +    case M_APP11:
 43.1057 +    case M_APP12:
 43.1058 +    case M_APP13:
 43.1059 +    case M_APP14:
 43.1060 +    case M_APP15:
 43.1061 +      if (! (*((my_marker_ptr) cinfo->marker)->process_APPn[
 43.1062 +		cinfo->unread_marker - (int) M_APP0]) (cinfo))
 43.1063 +	return JPEG_SUSPENDED;
 43.1064 +      break;
 43.1065 +      
 43.1066 +    case M_COM:
 43.1067 +      if (! (*((my_marker_ptr) cinfo->marker)->process_COM) (cinfo))
 43.1068 +	return JPEG_SUSPENDED;
 43.1069 +      break;
 43.1070 +
 43.1071 +    case M_RST0:		/* these are all parameterless */
 43.1072 +    case M_RST1:
 43.1073 +    case M_RST2:
 43.1074 +    case M_RST3:
 43.1075 +    case M_RST4:
 43.1076 +    case M_RST5:
 43.1077 +    case M_RST6:
 43.1078 +    case M_RST7:
 43.1079 +    case M_TEM:
 43.1080 +      TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
 43.1081 +      break;
 43.1082 +
 43.1083 +    case M_DNL:			/* Ignore DNL ... perhaps the wrong thing */
 43.1084 +      if (! skip_variable(cinfo))
 43.1085 +	return JPEG_SUSPENDED;
 43.1086 +      break;
 43.1087 +
 43.1088 +    default:			/* must be DHP, EXP, JPGn, or RESn */
 43.1089 +      /* For now, we treat the reserved markers as fatal errors since they are
 43.1090 +       * likely to be used to signal incompatible JPEG Part 3 extensions.
 43.1091 +       * Once the JPEG 3 version-number marker is well defined, this code
 43.1092 +       * ought to change!
 43.1093 +       */
 43.1094 +      ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
 43.1095 +      break;
 43.1096 +    }
 43.1097 +    /* Successfully processed marker, so reset state variable */
 43.1098 +    cinfo->unread_marker = 0;
 43.1099 +  } /* end loop */
 43.1100 +}
 43.1101 +
 43.1102 +
 43.1103 +/*
 43.1104 + * Read a restart marker, which is expected to appear next in the datastream;
 43.1105 + * if the marker is not there, take appropriate recovery action.
 43.1106 + * Returns FALSE if suspension is required.
 43.1107 + *
 43.1108 + * This is called by the entropy decoder after it has read an appropriate
 43.1109 + * number of MCUs.  cinfo->unread_marker may be nonzero if the entropy decoder
 43.1110 + * has already read a marker from the data source.  Under normal conditions
 43.1111 + * cinfo->unread_marker will be reset to 0 before returning; if not reset,
 43.1112 + * it holds a marker which the decoder will be unable to read past.
 43.1113 + */
 43.1114 +
 43.1115 +METHODDEF(boolean)
 43.1116 +read_restart_marker (j_decompress_ptr cinfo)
 43.1117 +{
 43.1118 +  /* Obtain a marker unless we already did. */
 43.1119 +  /* Note that next_marker will complain if it skips any data. */
 43.1120 +  if (cinfo->unread_marker == 0) {
 43.1121 +    if (! next_marker(cinfo))
 43.1122 +      return FALSE;
 43.1123 +  }
 43.1124 +
 43.1125 +  if (cinfo->unread_marker ==
 43.1126 +      ((int) M_RST0 + cinfo->marker->next_restart_num)) {
 43.1127 +    /* Normal case --- swallow the marker and let entropy decoder continue */
 43.1128 +    TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
 43.1129 +    cinfo->unread_marker = 0;
 43.1130 +  } else {
 43.1131 +    /* Uh-oh, the restart markers have been messed up. */
 43.1132 +    /* Let the data source manager determine how to resync. */
 43.1133 +    if (! (*cinfo->src->resync_to_restart) (cinfo,
 43.1134 +					    cinfo->marker->next_restart_num))
 43.1135 +      return FALSE;
 43.1136 +  }
 43.1137 +
 43.1138 +  /* Update next-restart state */
 43.1139 +  cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
 43.1140 +
 43.1141 +  return TRUE;
 43.1142 +}
 43.1143 +
 43.1144 +
 43.1145 +/*
 43.1146 + * This is the default resync_to_restart method for data source managers
 43.1147 + * to use if they don't have any better approach.  Some data source managers
 43.1148 + * may be able to back up, or may have additional knowledge about the data
 43.1149 + * which permits a more intelligent recovery strategy; such managers would
 43.1150 + * presumably supply their own resync method.
 43.1151 + *
 43.1152 + * read_restart_marker calls resync_to_restart if it finds a marker other than
 43.1153 + * the restart marker it was expecting.  (This code is *not* used unless
 43.1154 + * a nonzero restart interval has been declared.)  cinfo->unread_marker is
 43.1155 + * the marker code actually found (might be anything, except 0 or FF).
 43.1156 + * The desired restart marker number (0..7) is passed as a parameter.
 43.1157 + * This routine is supposed to apply whatever error recovery strategy seems
 43.1158 + * appropriate in order to position the input stream to the next data segment.
 43.1159 + * Note that cinfo->unread_marker is treated as a marker appearing before
 43.1160 + * the current data-source input point; usually it should be reset to zero
 43.1161 + * before returning.
 43.1162 + * Returns FALSE if suspension is required.
 43.1163 + *
 43.1164 + * This implementation is substantially constrained by wanting to treat the
 43.1165 + * input as a data stream; this means we can't back up.  Therefore, we have
 43.1166 + * only the following actions to work with:
 43.1167 + *   1. Simply discard the marker and let the entropy decoder resume at next
 43.1168 + *      byte of file.
 43.1169 + *   2. Read forward until we find another marker, discarding intervening
 43.1170 + *      data.  (In theory we could look ahead within the current bufferload,
 43.1171 + *      without having to discard data if we don't find the desired marker.
 43.1172 + *      This idea is not implemented here, in part because it makes behavior
 43.1173 + *      dependent on buffer size and chance buffer-boundary positions.)
 43.1174 + *   3. Leave the marker unread (by failing to zero cinfo->unread_marker).
 43.1175 + *      This will cause the entropy decoder to process an empty data segment,
 43.1176 + *      inserting dummy zeroes, and then we will reprocess the marker.
 43.1177 + *
 43.1178 + * #2 is appropriate if we think the desired marker lies ahead, while #3 is
 43.1179 + * appropriate if the found marker is a future restart marker (indicating
 43.1180 + * that we have missed the desired restart marker, probably because it got
 43.1181 + * corrupted).
 43.1182 + * We apply #2 or #3 if the found marker is a restart marker no more than
 43.1183 + * two counts behind or ahead of the expected one.  We also apply #2 if the
 43.1184 + * found marker is not a legal JPEG marker code (it's certainly bogus data).
 43.1185 + * If the found marker is a restart marker more than 2 counts away, we do #1
 43.1186 + * (too much risk that the marker is erroneous; with luck we will be able to
 43.1187 + * resync at some future point).
 43.1188 + * For any valid non-restart JPEG marker, we apply #3.  This keeps us from
 43.1189 + * overrunning the end of a scan.  An implementation limited to single-scan
 43.1190 + * files might find it better to apply #2 for markers other than EOI, since
 43.1191 + * any other marker would have to be bogus data in that case.
 43.1192 + */
 43.1193 +
 43.1194 +GLOBAL(boolean)
 43.1195 +jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
 43.1196 +{
 43.1197 +  int marker = cinfo->unread_marker;
 43.1198 +  int action = 1;
 43.1199 +  
 43.1200 +  /* Always put up a warning. */
 43.1201 +  WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
 43.1202 +  
 43.1203 +  /* Outer loop handles repeated decision after scanning forward. */
 43.1204 +  for (;;) {
 43.1205 +    if (marker < (int) M_SOF0)
 43.1206 +      action = 2;		/* invalid marker */
 43.1207 +    else if (marker < (int) M_RST0 || marker > (int) M_RST7)
 43.1208 +      action = 3;		/* valid non-restart marker */
 43.1209 +    else {
 43.1210 +      if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
 43.1211 +	  marker == ((int) M_RST0 + ((desired+2) & 7)))
 43.1212 +	action = 3;		/* one of the next two expected restarts */
 43.1213 +      else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
 43.1214 +	       marker == ((int) M_RST0 + ((desired-2) & 7)))
 43.1215 +	action = 2;		/* a prior restart, so advance */
 43.1216 +      else
 43.1217 +	action = 1;		/* desired restart or too far away */
 43.1218 +    }
 43.1219 +    TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
 43.1220 +    switch (action) {
 43.1221 +    case 1:
 43.1222 +      /* Discard marker and let entropy decoder resume processing. */
 43.1223 +      cinfo->unread_marker = 0;
 43.1224 +      return TRUE;
 43.1225 +    case 2:
 43.1226 +      /* Scan to the next marker, and repeat the decision loop. */
 43.1227 +      if (! next_marker(cinfo))
 43.1228 +	return FALSE;
 43.1229 +      marker = cinfo->unread_marker;
 43.1230 +      break;
 43.1231 +    case 3:
 43.1232 +      /* Return without advancing past this marker. */
 43.1233 +      /* Entropy decoder will be forced to process an empty segment. */
 43.1234 +      return TRUE;
 43.1235 +    }
 43.1236 +  } /* end loop */
 43.1237 +}
 43.1238 +
 43.1239 +
 43.1240 +/*
 43.1241 + * Reset marker processing state to begin a fresh datastream.
 43.1242 + */
 43.1243 +
 43.1244 +METHODDEF(void)
 43.1245 +reset_marker_reader (j_decompress_ptr cinfo)
 43.1246 +{
 43.1247 +  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
 43.1248 +
 43.1249 +  cinfo->comp_info = NULL;		/* until allocated by get_sof */
 43.1250 +  cinfo->input_scan_number = 0;		/* no SOS seen yet */
 43.1251 +  cinfo->unread_marker = 0;		/* no pending marker */
 43.1252 +  marker->pub.saw_SOI = FALSE;		/* set internal state too */
 43.1253 +  marker->pub.saw_SOF = FALSE;
 43.1254 +  marker->pub.discarded_bytes = 0;
 43.1255 +  marker->cur_marker = NULL;
 43.1256 +}
 43.1257 +
 43.1258 +
 43.1259 +/*
 43.1260 + * Initialize the marker reader module.
 43.1261 + * This is called only once, when the decompression object is created.
 43.1262 + */
 43.1263 +
 43.1264 +GLOBAL(void)
 43.1265 +jinit_marker_reader (j_decompress_ptr cinfo)
 43.1266 +{
 43.1267 +  my_marker_ptr marker;
 43.1268 +  int i;
 43.1269 +
 43.1270 +  /* Create subobject in permanent pool */
 43.1271 +  marker = (my_marker_ptr)
 43.1272 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
 43.1273 +				SIZEOF(my_marker_reader));
 43.1274 +  cinfo->marker = (struct jpeg_marker_reader *) marker;
 43.1275 +  /* Initialize public method pointers */
 43.1276 +  marker->pub.reset_marker_reader = reset_marker_reader;
 43.1277 +  marker->pub.read_markers = read_markers;
 43.1278 +  marker->pub.read_restart_marker = read_restart_marker;
 43.1279 +  /* Initialize COM/APPn processing.
 43.1280 +   * By default, we examine and then discard APP0 and APP14,
 43.1281 +   * but simply discard COM and all other APPn.
 43.1282 +   */
 43.1283 +  marker->process_COM = skip_variable;
 43.1284 +  marker->length_limit_COM = 0;
 43.1285 +  for (i = 0; i < 16; i++) {
 43.1286 +    marker->process_APPn[i] = skip_variable;
 43.1287 +    marker->length_limit_APPn[i] = 0;
 43.1288 +  }
 43.1289 +  marker->process_APPn[0] = get_interesting_appn;
 43.1290 +  marker->process_APPn[14] = get_interesting_appn;
 43.1291 +  /* Reset marker processing state */
 43.1292 +  reset_marker_reader(cinfo);
 43.1293 +}
 43.1294 +
 43.1295 +
 43.1296 +/*
 43.1297 + * Control saving of COM and APPn markers into marker_list.
 43.1298 + */
 43.1299 +
 43.1300 +#ifdef SAVE_MARKERS_SUPPORTED
 43.1301 +
 43.1302 +GLOBAL(void)
 43.1303 +jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
 43.1304 +		   unsigned int length_limit)
 43.1305 +{
 43.1306 +  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
 43.1307 +  long maxlength;
 43.1308 +  jpeg_marker_parser_method processor;
 43.1309 +
 43.1310 +  /* Length limit mustn't be larger than what we can allocate
 43.1311 +   * (should only be a concern in a 16-bit environment).
 43.1312 +   */
 43.1313 +  maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
 43.1314 +  if (((long) length_limit) > maxlength)
 43.1315 +    length_limit = (unsigned int) maxlength;
 43.1316 +
 43.1317 +  /* Choose processor routine to use.
 43.1318 +   * APP0/APP14 have special requirements.
 43.1319 +   */
 43.1320 +  if (length_limit) {
 43.1321 +    processor = save_marker;
 43.1322 +    /* If saving APP0/APP14, save at least enough for our internal use. */
 43.1323 +    if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
 43.1324 +      length_limit = APP0_DATA_LEN;
 43.1325 +    else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
 43.1326 +      length_limit = APP14_DATA_LEN;
 43.1327 +  } else {
 43.1328 +    processor = skip_variable;
 43.1329 +    /* If discarding APP0/APP14, use our regular on-the-fly processor. */
 43.1330 +    if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
 43.1331 +      processor = get_interesting_appn;
 43.1332 +  }
 43.1333 +
 43.1334 +  if (marker_code == (int) M_COM) {
 43.1335 +    marker->process_COM = processor;
 43.1336 +    marker->length_limit_COM = length_limit;
 43.1337 +  } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
 43.1338 +    marker->process_APPn[marker_code - (int) M_APP0] = processor;
 43.1339 +    marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
 43.1340 +  } else
 43.1341 +    ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
 43.1342 +}
 43.1343 +
 43.1344 +#endif /* SAVE_MARKERS_SUPPORTED */
 43.1345 +
 43.1346 +
 43.1347 +/*
 43.1348 + * Install a special processing method for COM or APPn markers.
 43.1349 + */
 43.1350 +
 43.1351 +GLOBAL(void)
 43.1352 +jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
 43.1353 +			   jpeg_marker_parser_method routine)
 43.1354 +{
 43.1355 +  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
 43.1356 +
 43.1357 +  if (marker_code == (int) M_COM)
 43.1358 +    marker->process_COM = routine;
 43.1359 +  else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
 43.1360 +    marker->process_APPn[marker_code - (int) M_APP0] = routine;
 43.1361 +  else
 43.1362 +    ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
 43.1363 +}
    44.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    44.2 +++ b/libs/libjpeg/jdmaster.c	Thu Sep 08 06:28:38 2011 +0300
    44.3 @@ -0,0 +1,557 @@
    44.4 +/*
    44.5 + * jdmaster.c
    44.6 + *
    44.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    44.8 + * This file is part of the Independent JPEG Group's software.
    44.9 + * For conditions of distribution and use, see the accompanying README file.
   44.10 + *
   44.11 + * This file contains master control logic for the JPEG decompressor.
   44.12 + * These routines are concerned with selecting the modules to be executed
   44.13 + * and with determining the number of passes and the work to be done in each
   44.14 + * pass.
   44.15 + */
   44.16 +
   44.17 +#define JPEG_INTERNALS
   44.18 +#include "jinclude.h"
   44.19 +#include "jpeglib.h"
   44.20 +
   44.21 +
   44.22 +/* Private state */
   44.23 +
   44.24 +typedef struct {
   44.25 +  struct jpeg_decomp_master pub; /* public fields */
   44.26 +
   44.27 +  int pass_number;		/* # of passes completed */
   44.28 +
   44.29 +  boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
   44.30 +
   44.31 +  /* Saved references to initialized quantizer modules,
   44.32 +   * in case we need to switch modes.
   44.33 +   */
   44.34 +  struct jpeg_color_quantizer * quantizer_1pass;
   44.35 +  struct jpeg_color_quantizer * quantizer_2pass;
   44.36 +} my_decomp_master;
   44.37 +
   44.38 +typedef my_decomp_master * my_master_ptr;
   44.39 +
   44.40 +
   44.41 +/*
   44.42 + * Determine whether merged upsample/color conversion should be used.
   44.43 + * CRUCIAL: this must match the actual capabilities of jdmerge.c!
   44.44 + */
   44.45 +
   44.46 +LOCAL(boolean)
   44.47 +use_merged_upsample (j_decompress_ptr cinfo)
   44.48 +{
   44.49 +#ifdef UPSAMPLE_MERGING_SUPPORTED
   44.50 +  /* Merging is the equivalent of plain box-filter upsampling */
   44.51 +  if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
   44.52 +    return FALSE;
   44.53 +  /* jdmerge.c only supports YCC=>RGB color conversion */
   44.54 +  if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
   44.55 +      cinfo->out_color_space != JCS_RGB ||
   44.56 +      cinfo->out_color_components != RGB_PIXELSIZE)
   44.57 +    return FALSE;
   44.58 +  /* and it only handles 2h1v or 2h2v sampling ratios */
   44.59 +  if (cinfo->comp_info[0].h_samp_factor != 2 ||
   44.60 +      cinfo->comp_info[1].h_samp_factor != 1 ||
   44.61 +      cinfo->comp_info[2].h_samp_factor != 1 ||
   44.62 +      cinfo->comp_info[0].v_samp_factor >  2 ||
   44.63 +      cinfo->comp_info[1].v_samp_factor != 1 ||
   44.64 +      cinfo->comp_info[2].v_samp_factor != 1)
   44.65 +    return FALSE;
   44.66 +  /* furthermore, it doesn't work if we've scaled the IDCTs differently */
   44.67 +  if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
   44.68 +      cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
   44.69 +      cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
   44.70 +    return FALSE;
   44.71 +  /* ??? also need to test for upsample-time rescaling, when & if supported */
   44.72 +  return TRUE;			/* by golly, it'll work... */
   44.73 +#else
   44.74 +  return FALSE;
   44.75 +#endif
   44.76 +}
   44.77 +
   44.78 +
   44.79 +/*
   44.80 + * Compute output image dimensions and related values.
   44.81 + * NOTE: this is exported for possible use by application.
   44.82 + * Hence it mustn't do anything that can't be done twice.
   44.83 + * Also note that it may be called before the master module is initialized!
   44.84 + */
   44.85 +
   44.86 +GLOBAL(void)
   44.87 +jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
   44.88 +/* Do computations that are needed before master selection phase */
   44.89 +{
   44.90 +#ifdef IDCT_SCALING_SUPPORTED
   44.91 +  int ci;
   44.92 +  jpeg_component_info *compptr;
   44.93 +#endif
   44.94 +
   44.95 +  /* Prevent application from calling me at wrong times */
   44.96 +  if (cinfo->global_state != DSTATE_READY)
   44.97 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
   44.98 +
   44.99 +#ifdef IDCT_SCALING_SUPPORTED
  44.100 +
  44.101 +  /* Compute actual output image dimensions and DCT scaling choices. */
  44.102 +  if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  44.103 +    /* Provide 1/8 scaling */
  44.104 +    cinfo->output_width = (JDIMENSION)
  44.105 +      jdiv_round_up((long) cinfo->image_width, 8L);
  44.106 +    cinfo->output_height = (JDIMENSION)
  44.107 +      jdiv_round_up((long) cinfo->image_height, 8L);
  44.108 +    cinfo->min_DCT_scaled_size = 1;
  44.109 +  } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  44.110 +    /* Provide 1/4 scaling */
  44.111 +    cinfo->output_width = (JDIMENSION)
  44.112 +      jdiv_round_up((long) cinfo->image_width, 4L);
  44.113 +    cinfo->output_height = (JDIMENSION)
  44.114 +      jdiv_round_up((long) cinfo->image_height, 4L);
  44.115 +    cinfo->min_DCT_scaled_size = 2;
  44.116 +  } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  44.117 +    /* Provide 1/2 scaling */
  44.118 +    cinfo->output_width = (JDIMENSION)
  44.119 +      jdiv_round_up((long) cinfo->image_width, 2L);
  44.120 +    cinfo->output_height = (JDIMENSION)
  44.121 +      jdiv_round_up((long) cinfo->image_height, 2L);
  44.122 +    cinfo->min_DCT_scaled_size = 4;
  44.123 +  } else {
  44.124 +    /* Provide 1/1 scaling */
  44.125 +    cinfo->output_width = cinfo->image_width;
  44.126 +    cinfo->output_height = cinfo->image_height;
  44.127 +    cinfo->min_DCT_scaled_size = DCTSIZE;
  44.128 +  }
  44.129 +  /* In selecting the actual DCT scaling for each component, we try to
  44.130 +   * scale up the chroma components via IDCT scaling rather than upsampling.
  44.131 +   * This saves time if the upsampler gets to use 1:1 scaling.
  44.132 +   * Note this code assumes that the supported DCT scalings are powers of 2.
  44.133 +   */
  44.134 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  44.135 +       ci++, compptr++) {
  44.136 +    int ssize = cinfo->min_DCT_scaled_size;
  44.137 +    while (ssize < DCTSIZE &&
  44.138 +	   (compptr->h_samp_factor * ssize * 2 <=
  44.139 +	    cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  44.140 +	   (compptr->v_samp_factor * ssize * 2 <=
  44.141 +	    cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  44.142 +      ssize = ssize * 2;
  44.143 +    }
  44.144 +    compptr->DCT_scaled_size = ssize;
  44.145 +  }
  44.146 +
  44.147 +  /* Recompute downsampled dimensions of components;
  44.148 +   * application needs to know these if using raw downsampled data.
  44.149 +   */
  44.150 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  44.151 +       ci++, compptr++) {
  44.152 +    /* Size in samples, after IDCT scaling */
  44.153 +    compptr->downsampled_width = (JDIMENSION)
  44.154 +      jdiv_round_up((long) cinfo->image_width *
  44.155 +		    (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  44.156 +		    (long) (cinfo->max_h_samp_factor * DCTSIZE));
  44.157 +    compptr->downsampled_height = (JDIMENSION)
  44.158 +      jdiv_round_up((long) cinfo->image_height *
  44.159 +		    (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  44.160 +		    (long) (cinfo->max_v_samp_factor * DCTSIZE));
  44.161 +  }
  44.162 +
  44.163 +#else /* !IDCT_SCALING_SUPPORTED */
  44.164 +
  44.165 +  /* Hardwire it to "no scaling" */
  44.166 +  cinfo->output_width = cinfo->image_width;
  44.167 +  cinfo->output_height = cinfo->image_height;
  44.168 +  /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  44.169 +   * and has computed unscaled downsampled_width and downsampled_height.
  44.170 +   */
  44.171 +
  44.172 +#endif /* IDCT_SCALING_SUPPORTED */
  44.173 +
  44.174 +  /* Report number of components in selected colorspace. */
  44.175 +  /* Probably this should be in the color conversion module... */
  44.176 +  switch (cinfo->out_color_space) {
  44.177 +  case JCS_GRAYSCALE:
  44.178 +    cinfo->out_color_components = 1;
  44.179 +    break;
  44.180 +  case JCS_RGB:
  44.181 +#if RGB_PIXELSIZE != 3
  44.182 +    cinfo->out_color_components = RGB_PIXELSIZE;
  44.183 +    break;
  44.184 +#endif /* else share code with YCbCr */
  44.185 +  case JCS_YCbCr:
  44.186 +    cinfo->out_color_components = 3;
  44.187 +    break;
  44.188 +  case JCS_CMYK:
  44.189 +  case JCS_YCCK:
  44.190 +    cinfo->out_color_components = 4;
  44.191 +    break;
  44.192 +  default:			/* else must be same colorspace as in file */
  44.193 +    cinfo->out_color_components = cinfo->num_components;
  44.194 +    break;
  44.195 +  }
  44.196 +  cinfo->output_components = (cinfo->quantize_colors ? 1 :
  44.197 +			      cinfo->out_color_components);
  44.198 +
  44.199 +  /* See if upsampler will want to emit more than one row at a time */
  44.200 +  if (use_merged_upsample(cinfo))
  44.201 +    cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  44.202 +  else
  44.203 +    cinfo->rec_outbuf_height = 1;
  44.204 +}
  44.205 +
  44.206 +
  44.207 +/*
  44.208 + * Several decompression processes need to range-limit values to the range
  44.209 + * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  44.210 + * due to noise introduced by quantization, roundoff error, etc.  These
  44.211 + * processes are inner loops and need to be as fast as possible.  On most
  44.212 + * machines, particularly CPUs with pipelines or instruction prefetch,
  44.213 + * a (subscript-check-less) C table lookup
  44.214 + *		x = sample_range_limit[x];
  44.215 + * is faster than explicit tests
  44.216 + *		if (x < 0)  x = 0;
  44.217 + *		else if (x > MAXJSAMPLE)  x = MAXJSAMPLE;
  44.218 + * These processes all use a common table prepared by the routine below.
  44.219 + *
  44.220 + * For most steps we can mathematically guarantee that the initial value
  44.221 + * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  44.222 + * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient.  But for the initial
  44.223 + * limiting step (just after the IDCT), a wildly out-of-range value is 
  44.224 + * possible if the input data is corrupt.  To avoid any chance of indexing
  44.225 + * off the end of memory and getting a bad-pointer trap, we perform the
  44.226 + * post-IDCT limiting thus:
  44.227 + *		x = range_limit[x & MASK];
  44.228 + * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  44.229 + * samples.  Under normal circumstances this is more than enough range and
  44.230 + * a correct output will be generated; with bogus input data the mask will
  44.231 + * cause wraparound, and we will safely generate a bogus-but-in-range output.
  44.232 + * For the post-IDCT step, we want to convert the data from signed to unsigned
  44.233 + * representation by adding CENTERJSAMPLE at the same time that we limit it.
  44.234 + * So the post-IDCT limiting table ends up looking like this:
  44.235 + *   CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  44.236 + *   MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  44.237 + *   0          (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  44.238 + *   0,1,...,CENTERJSAMPLE-1
  44.239 + * Negative inputs select values from the upper half of the table after
  44.240 + * masking.
  44.241 + *
  44.242 + * We can save some space by overlapping the start of the post-IDCT table
  44.243 + * with the simpler range limiting table.  The post-IDCT table begins at
  44.244 + * sample_range_limit + CENTERJSAMPLE.
  44.245 + *
  44.246 + * Note that the table is allocated in near data space on PCs; it's small
  44.247 + * enough and used often enough to justify this.
  44.248 + */
  44.249 +
  44.250 +LOCAL(void)
  44.251 +prepare_range_limit_table (j_decompress_ptr cinfo)
  44.252 +/* Allocate and fill in the sample_range_limit table */
  44.253 +{
  44.254 +  JSAMPLE * table;
  44.255 +  int i;
  44.256 +
  44.257 +  table = (JSAMPLE *)
  44.258 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  44.259 +		(5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  44.260 +  table += (MAXJSAMPLE+1);	/* allow negative subscripts of simple table */
  44.261 +  cinfo->sample_range_limit = table;
  44.262 +  /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  44.263 +  MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  44.264 +  /* Main part of "simple" table: limit[x] = x */
  44.265 +  for (i = 0; i <= MAXJSAMPLE; i++)
  44.266 +    table[i] = (JSAMPLE) i;
  44.267 +  table += CENTERJSAMPLE;	/* Point to where post-IDCT table starts */
  44.268 +  /* End of simple table, rest of first half of post-IDCT table */
  44.269 +  for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  44.270 +    table[i] = MAXJSAMPLE;
  44.271 +  /* Second half of post-IDCT table */
  44.272 +  MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  44.273 +	  (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  44.274 +  MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  44.275 +	  cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  44.276 +}
  44.277 +
  44.278 +
  44.279 +/*
  44.280 + * Master selection of decompression modules.
  44.281 + * This is done once at jpeg_start_decompress time.  We determine
  44.282 + * which modules will be used and give them appropriate initialization calls.
  44.283 + * We also initialize the decompressor input side to begin consuming data.
  44.284 + *
  44.285 + * Since jpeg_read_header has finished, we know what is in the SOF
  44.286 + * and (first) SOS markers.  We also have all the application parameter
  44.287 + * settings.
  44.288 + */
  44.289 +
  44.290 +LOCAL(void)
  44.291 +master_selection (j_decompress_ptr cinfo)
  44.292 +{
  44.293 +  my_master_ptr master = (my_master_ptr) cinfo->master;
  44.294 +  boolean use_c_buffer;
  44.295 +  long samplesperrow;
  44.296 +  JDIMENSION jd_samplesperrow;
  44.297 +
  44.298 +  /* Initialize dimensions and other stuff */
  44.299 +  jpeg_calc_output_dimensions(cinfo);
  44.300 +  prepare_range_limit_table(cinfo);
  44.301 +
  44.302 +  /* Width of an output scanline must be representable as JDIMENSION. */
  44.303 +  samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  44.304 +  jd_samplesperrow = (JDIMENSION) samplesperrow;
  44.305 +  if ((long) jd_samplesperrow != samplesperrow)
  44.306 +    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  44.307 +
  44.308 +  /* Initialize my private state */
  44.309 +  master->pass_number = 0;
  44.310 +  master->using_merged_upsample = use_merged_upsample(cinfo);
  44.311 +
  44.312 +  /* Color quantizer selection */
  44.313 +  master->quantizer_1pass = NULL;
  44.314 +  master->quantizer_2pass = NULL;
  44.315 +  /* No mode changes if not using buffered-image mode. */
  44.316 +  if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  44.317 +    cinfo->enable_1pass_quant = FALSE;
  44.318 +    cinfo->enable_external_quant = FALSE;
  44.319 +    cinfo->enable_2pass_quant = FALSE;
  44.320 +  }
  44.321 +  if (cinfo->quantize_colors) {
  44.322 +    if (cinfo->raw_data_out)
  44.323 +      ERREXIT(cinfo, JERR_NOTIMPL);
  44.324 +    /* 2-pass quantizer only works in 3-component color space. */
  44.325 +    if (cinfo->out_color_components != 3) {
  44.326 +      cinfo->enable_1pass_quant = TRUE;
  44.327 +      cinfo->enable_external_quant = FALSE;
  44.328 +      cinfo->enable_2pass_quant = FALSE;
  44.329 +      cinfo->colormap = NULL;
  44.330 +    } else if (cinfo->colormap != NULL) {
  44.331 +      cinfo->enable_external_quant = TRUE;
  44.332 +    } else if (cinfo->two_pass_quantize) {
  44.333 +      cinfo->enable_2pass_quant = TRUE;
  44.334 +    } else {
  44.335 +      cinfo->enable_1pass_quant = TRUE;
  44.336 +    }
  44.337 +
  44.338 +    if (cinfo->enable_1pass_quant) {
  44.339 +#ifdef QUANT_1PASS_SUPPORTED
  44.340 +      jinit_1pass_quantizer(cinfo);
  44.341 +      master->quantizer_1pass = cinfo->cquantize;
  44.342 +#else
  44.343 +      ERREXIT(cinfo, JERR_NOT_COMPILED);
  44.344 +#endif
  44.345 +    }
  44.346 +
  44.347 +    /* We use the 2-pass code to map to external colormaps. */
  44.348 +    if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  44.349 +#ifdef QUANT_2PASS_SUPPORTED
  44.350 +      jinit_2pass_quantizer(cinfo);
  44.351 +      master->quantizer_2pass = cinfo->cquantize;
  44.352 +#else
  44.353 +      ERREXIT(cinfo, JERR_NOT_COMPILED);
  44.354 +#endif
  44.355 +    }
  44.356 +    /* If both quantizers are initialized, the 2-pass one is left active;
  44.357 +     * this is necessary for starting with quantization to an external map.
  44.358 +     */
  44.359 +  }
  44.360 +
  44.361 +  /* Post-processing: in particular, color conversion first */
  44.362 +  if (! cinfo->raw_data_out) {
  44.363 +    if (master->using_merged_upsample) {
  44.364 +#ifdef UPSAMPLE_MERGING_SUPPORTED
  44.365 +      jinit_merged_upsampler(cinfo); /* does color conversion too */
  44.366 +#else
  44.367 +      ERREXIT(cinfo, JERR_NOT_COMPILED);
  44.368 +#endif
  44.369 +    } else {
  44.370 +      jinit_color_deconverter(cinfo);
  44.371 +      jinit_upsampler(cinfo);
  44.372 +    }
  44.373 +    jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  44.374 +  }
  44.375 +  /* Inverse DCT */
  44.376 +  jinit_inverse_dct(cinfo);
  44.377 +  /* Entropy decoding: either Huffman or arithmetic coding. */
  44.378 +  if (cinfo->arith_code) {
  44.379 +    ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  44.380 +  } else {
  44.381 +    if (cinfo->progressive_mode) {
  44.382 +#ifdef D_PROGRESSIVE_SUPPORTED
  44.383 +      jinit_phuff_decoder(cinfo);
  44.384 +#else
  44.385 +      ERREXIT(cinfo, JERR_NOT_COMPILED);
  44.386 +#endif
  44.387 +    } else
  44.388 +      jinit_huff_decoder(cinfo);
  44.389 +  }
  44.390 +
  44.391 +  /* Initialize principal buffer controllers. */
  44.392 +  use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  44.393 +  jinit_d_coef_controller(cinfo, use_c_buffer);
  44.394 +
  44.395 +  if (! cinfo->raw_data_out)
  44.396 +    jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  44.397 +
  44.398 +  /* We can now tell the memory manager to allocate virtual arrays. */
  44.399 +  (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  44.400 +
  44.401 +  /* Initialize input side of decompressor to consume first scan. */
  44.402 +  (*cinfo->inputctl->start_input_pass) (cinfo);
  44.403 +
  44.404 +#ifdef D_MULTISCAN_FILES_SUPPORTED
  44.405 +  /* If jpeg_start_decompress will read the whole file, initialize
  44.406 +   * progress monitoring appropriately.  The input step is counted
  44.407 +   * as one pass.
  44.408 +   */
  44.409 +  if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  44.410 +      cinfo->inputctl->has_multiple_scans) {
  44.411 +    int nscans;
  44.412 +    /* Estimate number of scans to set pass_limit. */
  44.413 +    if (cinfo->progressive_mode) {
  44.414 +      /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  44.415 +      nscans = 2 + 3 * cinfo->num_components;
  44.416 +    } else {
  44.417 +      /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  44.418 +      nscans = cinfo->num_components;
  44.419 +    }
  44.420 +    cinfo->progress->pass_counter = 0L;
  44.421 +    cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  44.422 +    cinfo->progress->completed_passes = 0;
  44.423 +    cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  44.424 +    /* Count the input pass as done */
  44.425 +    master->pass_number++;
  44.426 +  }
  44.427 +#endif /* D_MULTISCAN_FILES_SUPPORTED */
  44.428 +}
  44.429 +
  44.430 +
  44.431 +/*
  44.432 + * Per-pass setup.
  44.433 + * This is called at the beginning of each output pass.  We determine which
  44.434 + * modules will be active during this pass and give them appropriate
  44.435 + * start_pass calls.  We also set is_dummy_pass to indicate whether this
  44.436 + * is a "real" output pass or a dummy pass for color quantization.
  44.437 + * (In the latter case, jdapistd.c will crank the pass to completion.)
  44.438 + */
  44.439 +
  44.440 +METHODDEF(void)
  44.441 +prepare_for_output_pass (j_decompress_ptr cinfo)
  44.442 +{
  44.443 +  my_master_ptr master = (my_master_ptr) cinfo->master;
  44.444 +
  44.445 +  if (master->pub.is_dummy_pass) {
  44.446 +#ifdef QUANT_2PASS_SUPPORTED
  44.447 +    /* Final pass of 2-pass quantization */
  44.448 +    master->pub.is_dummy_pass = FALSE;
  44.449 +    (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  44.450 +    (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  44.451 +    (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  44.452 +#else
  44.453 +    ERREXIT(cinfo, JERR_NOT_COMPILED);
  44.454 +#endif /* QUANT_2PASS_SUPPORTED */
  44.455 +  } else {
  44.456 +    if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  44.457 +      /* Select new quantization method */
  44.458 +      if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  44.459 +	cinfo->cquantize = master->quantizer_2pass;
  44.460 +	master->pub.is_dummy_pass = TRUE;
  44.461 +      } else if (cinfo->enable_1pass_quant) {
  44.462 +	cinfo->cquantize = master->quantizer_1pass;
  44.463 +      } else {
  44.464 +	ERREXIT(cinfo, JERR_MODE_CHANGE);
  44.465 +      }
  44.466 +    }
  44.467 +    (*cinfo->idct->start_pass) (cinfo);
  44.468 +    (*cinfo->coef->start_output_pass) (cinfo);
  44.469 +    if (! cinfo->raw_data_out) {
  44.470 +      if (! master->using_merged_upsample)
  44.471 +	(*cinfo->cconvert->start_pass) (cinfo);
  44.472 +      (*cinfo->upsample->start_pass) (cinfo);
  44.473 +      if (cinfo->quantize_colors)
  44.474 +	(*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  44.475 +      (*cinfo->post->start_pass) (cinfo,
  44.476 +	    (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  44.477 +      (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  44.478 +    }
  44.479 +  }
  44.480 +
  44.481 +  /* Set up progress monitor's pass info if present */
  44.482 +  if (cinfo->progress != NULL) {
  44.483 +    cinfo->progress->completed_passes = master->pass_number;
  44.484 +    cinfo->progress->total_passes = master->pass_number +
  44.485 +				    (master->pub.is_dummy_pass ? 2 : 1);
  44.486 +    /* In buffered-image mode, we assume one more output pass if EOI not
  44.487 +     * yet reached, but no more passes if EOI has been reached.
  44.488 +     */
  44.489 +    if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  44.490 +      cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  44.491 +    }
  44.492 +  }
  44.493 +}
  44.494 +
  44.495 +
  44.496 +/*
  44.497 + * Finish up at end of an output pass.
  44.498 + */
  44.499 +
  44.500 +METHODDEF(void)
  44.501 +finish_output_pass (j_decompress_ptr cinfo)
  44.502 +{
  44.503 +  my_master_ptr master = (my_master_ptr) cinfo->master;
  44.504 +
  44.505 +  if (cinfo->quantize_colors)
  44.506 +    (*cinfo->cquantize->finish_pass) (cinfo);
  44.507 +  master->pass_number++;
  44.508 +}
  44.509 +
  44.510 +
  44.511 +#ifdef D_MULTISCAN_FILES_SUPPORTED
  44.512 +
  44.513 +/*
  44.514 + * Switch to a new external colormap between output passes.
  44.515 + */
  44.516 +
  44.517 +GLOBAL(void)
  44.518 +jpeg_new_colormap (j_decompress_ptr cinfo)
  44.519 +{
  44.520 +  my_master_ptr master = (my_master_ptr) cinfo->master;
  44.521 +
  44.522 +  /* Prevent application from calling me at wrong times */
  44.523 +  if (cinfo->global_state != DSTATE_BUFIMAGE)
  44.524 +    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  44.525 +
  44.526 +  if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  44.527 +      cinfo->colormap != NULL) {
  44.528 +    /* Select 2-pass quantizer for external colormap use */
  44.529 +    cinfo->cquantize = master->quantizer_2pass;
  44.530 +    /* Notify quantizer of colormap change */
  44.531 +    (*cinfo->cquantize->new_color_map) (cinfo);
  44.532 +    master->pub.is_dummy_pass = FALSE; /* just in case */
  44.533 +  } else
  44.534 +    ERREXIT(cinfo, JERR_MODE_CHANGE);
  44.535 +}
  44.536 +
  44.537 +#endif /* D_MULTISCAN_FILES_SUPPORTED */
  44.538 +
  44.539 +
  44.540 +/*
  44.541 + * Initialize master decompression control and select active modules.
  44.542 + * This is performed at the start of jpeg_start_decompress.
  44.543 + */
  44.544 +
  44.545 +GLOBAL(void)
  44.546 +jinit_master_decompress (j_decompress_ptr cinfo)
  44.547 +{
  44.548 +  my_master_ptr master;
  44.549 +
  44.550 +  master = (my_master_ptr)
  44.551 +      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  44.552 +				  SIZEOF(my_decomp_master));
  44.553 +  cinfo->master = (struct jpeg_decomp_master *) master;
  44.554 +  master->pub.prepare_for_output_pass = prepare_for_output_pass;
  44.555 +  master->pub.finish_output_pass = finish_output_pass;
  44.556 +
  44.557 +  master->pub.is_dummy_pass = FALSE;
  44.558 +
  44.559 +  master_selection(cinfo);
  44.560 +}
    45.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    45.2 +++ b/libs/libjpeg/jdmerge.c	Thu Sep 08 06:28:38 2011 +0300
    45.3 @@ -0,0 +1,400 @@
    45.4 +/*
    45.5 + * jdmerge.c
    45.6 + *
    45.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    45.8 + * This file is part of the Independent JPEG Group's software.
    45.9 + * For conditions of distribution and use, see the accompanying README file.
   45.10 + *
   45.11 + * This file contains code for merged upsampling/color conversion.
   45.12 + *
   45.13 + * This file combines functions from jdsample.c and jdcolor.c;
   45.14 + * read those files first to understand what's going on.
   45.15 + *
   45.16 + * When the chroma components are to be upsampled by simple replication
   45.17 + * (ie, box filtering), we can save some work in color conversion by
   45.18 + * calculating all the output pixels corresponding to a pair of chroma
   45.19 + * samples at one time.  In the conversion equations
   45.20 + *	R = Y           + K1 * Cr
   45.21 + *	G = Y + K2 * Cb + K3 * Cr
   45.22 + *	B = Y + K4 * Cb
   45.23 + * only the Y term varies among the group of pixels corresponding to a pair
   45.24 + * of chroma samples, so the rest of the terms can be calculated just once.
   45.25 + * At typical sampling ratios, this eliminates half or three-quarters of the
   45.26 + * multiplications needed for color conversion.
   45.27 + *
   45.28 + * This file currently provides implementations for the following cases:
   45.29 + *	YCbCr => RGB color conversion only.
   45.30 + *	Sampling ratios of 2h1v or 2h2v.
   45.31 + *	No scaling needed at upsample time.
   45.32 + *	Corner-aligned (non-CCIR601) sampling alignment.
   45.33 + * Other special cases could be added, but in most applications these are
   45.34 + * the only common cases.  (For uncommon cases we fall back on the more
   45.35 + * general code in jdsample.c and jdcolor.c.)
   45.36 + */
   45.37 +
   45.38 +#define JPEG_INTERNALS
   45.39 +#include "jinclude.h"
   45.40 +#include "jpeglib.h"
   45.41 +
   45.42 +#ifdef UPSAMPLE_MERGING_SUPPORTED
   45.43 +
   45.44 +
   45.45 +/* Private subobject */
   45.46 +
   45.47 +typedef struct {
   45.48 +  struct jpeg_upsampler pub;	/* public fields */
   45.49 +
   45.50 +  /* Pointer to routine to do actual upsampling/conversion of one row group */
   45.51 +  JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
   45.52 +			   JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
   45.53 +			   JSAMPARRAY output_buf));
   45.54 +
   45.55 +  /* Private state for YCC->RGB conversion */
   45.56 +  int * Cr_r_tab;		/* => table for Cr to R conversion */
   45.57 +  int * Cb_b_tab;		/* => table for Cb to B conversion */
   45.58 +  INT32 * Cr_g_tab;		/* => table for Cr to G conversion */
   45.59 +  INT32 * Cb_g_tab;		/* => table for Cb to G conversion */
   45.60 +
   45.61 +  /* For 2:1 vertical sampling, we produce two output rows at a time.
   45.62 +   * We need a "spare" row buffer to hold the second output row if the
   45.63 +   * application provides just a one-row buffer; we also use the spare
   45.64 +   * to discard the dummy last row if the image height is odd.
   45.65 +   */
   45.66 +  JSAMPROW spare_row;
   45.67 +  boolean spare_full;		/* T if spare buffer is occupied */
   45.68 +
   45.69 +  JDIMENSION out_row_width;	/* samples per output row */
   45.70 +  JDIMENSION rows_to_go;	/* counts rows remaining in image */
   45.71 +} my_upsampler;
   45.72 +
   45.73 +typedef my_upsampler * my_upsample_ptr;
   45.74 +
   45.75 +#define SCALEBITS	16	/* speediest right-shift on some machines */
   45.76 +#define ONE_HALF	((INT32) 1 << (SCALEBITS-1))
   45.77 +#define FIX(x)		((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
   45.78 +
   45.79 +
   45.80 +/*
   45.81 + * Initialize tables for YCC->RGB colorspace conversion.
   45.82 + * This is taken directly from jdcolor.c; see that file for more info.
   45.83 + */
   45.84 +
   45.85 +LOCAL(void)
   45.86 +build_ycc_rgb_table (j_decompress_ptr cinfo)
   45.87 +{
   45.88 +  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
   45.89 +  int i;
   45.90 +  INT32 x;
   45.91 +  SHIFT_TEMPS
   45.92 +
   45.93 +  upsample->Cr_r_tab = (int *)
   45.94 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
   45.95 +				(MAXJSAMPLE+1) * SIZEOF(int));
   45.96 +  upsample->Cb_b_tab = (int *)
   45.97 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
   45.98 +				(MAXJSAMPLE+1) * SIZEOF(int));
   45.99 +  upsample->Cr_g_tab = (INT32 *)
  45.100 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  45.101 +				(MAXJSAMPLE+1) * SIZEOF(INT32));
  45.102 +  upsample->Cb_g_tab = (INT32 *)
  45.103 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  45.104 +				(MAXJSAMPLE+1) * SIZEOF(INT32));
  45.105 +
  45.106 +  for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  45.107 +    /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  45.108 +    /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  45.109 +    /* Cr=>R value is nearest int to 1.40200 * x */
  45.110 +    upsample->Cr_r_tab[i] = (int)
  45.111 +		    RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  45.112 +    /* Cb=>B value is nearest int to 1.77200 * x */
  45.113 +    upsample->Cb_b_tab[i] = (int)
  45.114 +		    RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  45.115 +    /* Cr=>G value is scaled-up -0.71414 * x */
  45.116 +    upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  45.117 +    /* Cb=>G value is scaled-up -0.34414 * x */
  45.118 +    /* We also add in ONE_HALF so that need not do it in inner loop */
  45.119 +    upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  45.120 +  }
  45.121 +}
  45.122 +
  45.123 +
  45.124 +/*
  45.125 + * Initialize for an upsampling pass.
  45.126 + */
  45.127 +
  45.128 +METHODDEF(void)
  45.129 +start_pass_merged_upsample (j_decompress_ptr cinfo)
  45.130 +{
  45.131 +  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  45.132 +
  45.133 +  /* Mark the spare buffer empty */
  45.134 +  upsample->spare_full = FALSE;
  45.135 +  /* Initialize total-height counter for detecting bottom of image */
  45.136 +  upsample->rows_to_go = cinfo->output_height;
  45.137 +}
  45.138 +
  45.139 +
  45.140 +/*
  45.141 + * Control routine to do upsampling (and color conversion).
  45.142 + *
  45.143 + * The control routine just handles the row buffering considerations.
  45.144 + */
  45.145 +
  45.146 +METHODDEF(void)
  45.147 +merged_2v_upsample (j_decompress_ptr cinfo,
  45.148 +		    JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  45.149 +		    JDIMENSION in_row_groups_avail,
  45.150 +		    JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  45.151 +		    JDIMENSION out_rows_avail)
  45.152 +/* 2:1 vertical sampling case: may need a spare row. */
  45.153 +{
  45.154 +  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  45.155 +  JSAMPROW work_ptrs[2];
  45.156 +  JDIMENSION num_rows;		/* number of rows returned to caller */
  45.157 +
  45.158 +  if (upsample->spare_full) {
  45.159 +    /* If we have a spare row saved from a previous cycle, just return it. */
  45.160 +    jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  45.161 +		      1, upsample->out_row_width);
  45.162 +    num_rows = 1;
  45.163 +    upsample->spare_full = FALSE;
  45.164 +  } else {
  45.165 +    /* Figure number of rows to return to caller. */
  45.166 +    num_rows = 2;
  45.167 +    /* Not more than the distance to the end of the image. */
  45.168 +    if (num_rows > upsample->rows_to_go)
  45.169 +      num_rows = upsample->rows_to_go;
  45.170 +    /* And not more than what the client can accept: */
  45.171 +    out_rows_avail -= *out_row_ctr;
  45.172 +    if (num_rows > out_rows_avail)
  45.173 +      num_rows = out_rows_avail;
  45.174 +    /* Create output pointer array for upsampler. */
  45.175 +    work_ptrs[0] = output_buf[*out_row_ctr];
  45.176 +    if (num_rows > 1) {
  45.177 +      work_ptrs[1] = output_buf[*out_row_ctr + 1];
  45.178 +    } else {
  45.179 +      work_ptrs[1] = upsample->spare_row;
  45.180 +      upsample->spare_full = TRUE;
  45.181 +    }
  45.182 +    /* Now do the upsampling. */
  45.183 +    (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  45.184 +  }
  45.185 +
  45.186 +  /* Adjust counts */
  45.187 +  *out_row_ctr += num_rows;
  45.188 +  upsample->rows_to_go -= num_rows;
  45.189 +  /* When the buffer is emptied, declare this input row group consumed */
  45.190 +  if (! upsample->spare_full)
  45.191 +    (*in_row_group_ctr)++;
  45.192 +}
  45.193 +
  45.194 +
  45.195 +METHODDEF(void)
  45.196 +merged_1v_upsample (j_decompress_ptr cinfo,
  45.197 +		    JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  45.198 +		    JDIMENSION in_row_groups_avail,
  45.199 +		    JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  45.200 +		    JDIMENSION out_rows_avail)
  45.201 +/* 1:1 vertical sampling case: much easier, never need a spare row. */
  45.202 +{
  45.203 +  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  45.204 +
  45.205 +  /* Just do the upsampling. */
  45.206 +  (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  45.207 +			 output_buf + *out_row_ctr);
  45.208 +  /* Adjust counts */
  45.209 +  (*out_row_ctr)++;
  45.210 +  (*in_row_group_ctr)++;
  45.211 +}
  45.212 +
  45.213 +
  45.214 +/*
  45.215 + * These are the routines invoked by the control routines to do
  45.216 + * the actual upsampling/conversion.  One row group is processed per call.
  45.217 + *
  45.218 + * Note: since we may be writing directly into application-supplied buffers,
  45.219 + * we have to be honest about the output width; we can't assume the buffer
  45.220 + * has been rounded up to an even width.
  45.221 + */
  45.222 +
  45.223 +
  45.224 +/*
  45.225 + * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  45.226 + */
  45.227 +
  45.228 +METHODDEF(void)
  45.229 +h2v1_merged_upsample (j_decompress_ptr cinfo,
  45.230 +		      JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  45.231 +		      JSAMPARRAY output_buf)
  45.232 +{
  45.233 +  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  45.234 +  register int y, cred, cgreen, cblue;
  45.235 +  int cb, cr;
  45.236 +  register JSAMPROW outptr;
  45.237 +  JSAMPROW inptr0, inptr1, inptr2;
  45.238 +  JDIMENSION col;
  45.239 +  /* copy these pointers into registers if possible */
  45.240 +  register JSAMPLE * range_limit = cinfo->sample_range_limit;
  45.241 +  int * Crrtab = upsample->Cr_r_tab;
  45.242 +  int * Cbbtab = upsample->Cb_b_tab;
  45.243 +  INT32 * Crgtab = upsample->Cr_g_tab;
  45.244 +  INT32 * Cbgtab = upsample->Cb_g_tab;
  45.245 +  SHIFT_TEMPS
  45.246 +
  45.247 +  inptr0 = input_buf[0][in_row_group_ctr];
  45.248 +  inptr1 = input_buf[1][in_row_group_ctr];
  45.249 +  inptr2 = input_buf[2][in_row_group_ctr];
  45.250 +  outptr = output_buf[0];
  45.251 +  /* Loop for each pair of output pixels */
  45.252 +  for (col = cinfo->output_width >> 1; col > 0; col--) {
  45.253 +    /* Do the chroma part of the calculation */
  45.254 +    cb = GETJSAMPLE(*inptr1++);
  45.255 +    cr = GETJSAMPLE(*inptr2++);
  45.256 +    cred = Crrtab[cr];
  45.257 +    cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  45.258 +    cblue = Cbbtab[cb];
  45.259 +    /* Fetch 2 Y values and emit 2 pixels */
  45.260 +    y  = GETJSAMPLE(*inptr0++);
  45.261 +    outptr[RGB_RED] =   range_limit[y + cred];
  45.262 +    outptr[RGB_GREEN] = range_limit[y + cgreen];
  45.263 +    outptr[RGB_BLUE] =  range_limit[y + cblue];
  45.264 +    outptr += RGB_PIXELSIZE;
  45.265 +    y  = GETJSAMPLE(*inptr0++);
  45.266 +    outptr[RGB_RED] =   range_limit[y + cred];
  45.267 +    outptr[RGB_GREEN] = range_limit[y + cgreen];
  45.268 +    outptr[RGB_BLUE] =  range_limit[y + cblue];
  45.269 +    outptr += RGB_PIXELSIZE;
  45.270 +  }
  45.271 +  /* If image width is odd, do the last output column separately */
  45.272 +  if (cinfo->output_width & 1) {
  45.273 +    cb = GETJSAMPLE(*inptr1);
  45.274 +    cr = GETJSAMPLE(*inptr2);
  45.275 +    cred = Crrtab[cr];
  45.276 +    cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  45.277 +    cblue = Cbbtab[cb];
  45.278 +    y  = GETJSAMPLE(*inptr0);
  45.279 +    outptr[RGB_RED] =   range_limit[y + cred];
  45.280 +    outptr[RGB_GREEN] = range_limit[y + cgreen];
  45.281 +    outptr[RGB_BLUE] =  range_limit[y + cblue];
  45.282 +  }
  45.283 +}
  45.284 +
  45.285 +
  45.286 +/*
  45.287 + * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  45.288 + */
  45.289 +
  45.290 +METHODDEF(void)
  45.291 +h2v2_merged_upsample (j_decompress_ptr cinfo,
  45.292 +		      JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  45.293 +		      JSAMPARRAY output_buf)
  45.294 +{
  45.295 +  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  45.296 +  register int y, cred, cgreen, cblue;
  45.297 +  int cb, cr;
  45.298 +  register JSAMPROW outptr0, outptr1;
  45.299 +  JSAMPROW inptr00, inptr01, inptr1, inptr2;
  45.300 +  JDIMENSION col;
  45.301 +  /* copy these pointers into registers if possible */
  45.302 +  register JSAMPLE * range_limit = cinfo->sample_range_limit;
  45.303 +  int * Crrtab = upsample->Cr_r_tab;
  45.304 +  int * Cbbtab = upsample->Cb_b_tab;
  45.305 +  INT32 * Crgtab = upsample->Cr_g_tab;
  45.306 +  INT32 * Cbgtab = upsample->Cb_g_tab;
  45.307 +  SHIFT_TEMPS
  45.308 +
  45.309 +  inptr00 = input_buf[0][in_row_group_ctr*2];
  45.310 +  inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  45.311 +  inptr1 = input_buf[1][in_row_group_ctr];
  45.312 +  inptr2 = input_buf[2][in_row_group_ctr];
  45.313 +  outptr0 = output_buf[0];
  45.314 +  outptr1 = output_buf[1];
  45.315 +  /* Loop for each group of output pixels */
  45.316 +  for (col = cinfo->output_width >> 1; col > 0; col--) {
  45.317 +    /* Do the chroma part of the calculation */
  45.318 +    cb = GETJSAMPLE(*inptr1++);
  45.319 +    cr = GETJSAMPLE(*inptr2++);
  45.320 +    cred = Crrtab[cr];
  45.321 +    cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  45.322 +    cblue = Cbbtab[cb];
  45.323 +    /* Fetch 4 Y values and emit 4 pixels */
  45.324 +    y  = GETJSAMPLE(*inptr00++);
  45.325 +    outptr0[RGB_RED] =   range_limit[y + cred];
  45.326 +    outptr0[RGB_GREEN] = range_limit[y + cgreen];
  45.327 +    outptr0[RGB_BLUE] =  range_limit[y + cblue];
  45.328 +    outptr0 += RGB_PIXELSIZE;
  45.329 +    y  = GETJSAMPLE(*inptr00++);
  45.330 +    outptr0[RGB_RED] =   range_limit[y + cred];
  45.331 +    outptr0[RGB_GREEN] = range_limit[y + cgreen];
  45.332 +    outptr0[RGB_BLUE] =  range_limit[y + cblue];
  45.333 +    outptr0 += RGB_PIXELSIZE;
  45.334 +    y  = GETJSAMPLE(*inptr01++);
  45.335 +    outptr1[RGB_RED] =   range_limit[y + cred];
  45.336 +    outptr1[RGB_GREEN] = range_limit[y + cgreen];
  45.337 +    outptr1[RGB_BLUE] =  range_limit[y + cblue];
  45.338 +    outptr1 += RGB_PIXELSIZE;
  45.339 +    y  = GETJSAMPLE(*inptr01++);
  45.340 +    outptr1[RGB_RED] =   range_limit[y + cred];
  45.341 +    outptr1[RGB_GREEN] = range_limit[y + cgreen];
  45.342 +    outptr1[RGB_BLUE] =  range_limit[y + cblue];
  45.343 +    outptr1 += RGB_PIXELSIZE;
  45.344 +  }
  45.345 +  /* If image width is odd, do the last output column separately */
  45.346 +  if (cinfo->output_width & 1) {
  45.347 +    cb = GETJSAMPLE(*inptr1);
  45.348 +    cr = GETJSAMPLE(*inptr2);
  45.349 +    cred = Crrtab[cr];
  45.350 +    cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  45.351 +    cblue = Cbbtab[cb];
  45.352 +    y  = GETJSAMPLE(*inptr00);
  45.353 +    outptr0[RGB_RED] =   range_limit[y + cred];
  45.354 +    outptr0[RGB_GREEN] = range_limit[y + cgreen];
  45.355 +    outptr0[RGB_BLUE] =  range_limit[y + cblue];
  45.356 +    y  = GETJSAMPLE(*inptr01);
  45.357 +    outptr1[RGB_RED] =   range_limit[y + cred];
  45.358 +    outptr1[RGB_GREEN] = range_limit[y + cgreen];
  45.359 +    outptr1[RGB_BLUE] =  range_limit[y + cblue];
  45.360 +  }
  45.361 +}
  45.362 +
  45.363 +
  45.364 +/*
  45.365 + * Module initialization routine for merged upsampling/color conversion.
  45.366 + *
  45.367 + * NB: this is called under the conditions determined by use_merged_upsample()
  45.368 + * in jdmaster.c.  That routine MUST correspond to the actual capabilities
  45.369 + * of this module; no safety checks are made here.
  45.370 + */
  45.371 +
  45.372 +GLOBAL(void)
  45.373 +jinit_merged_upsampler (j_decompress_ptr cinfo)
  45.374 +{
  45.375 +  my_upsample_ptr upsample;
  45.376 +
  45.377 +  upsample = (my_upsample_ptr)
  45.378 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  45.379 +				SIZEOF(my_upsampler));
  45.380 +  cinfo->upsample = (struct jpeg_upsampler *) upsample;
  45.381 +  upsample->pub.start_pass = start_pass_merged_upsample;
  45.382 +  upsample->pub.need_context_rows = FALSE;
  45.383 +
  45.384 +  upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  45.385 +
  45.386 +  if (cinfo->max_v_samp_factor == 2) {
  45.387 +    upsample->pub.upsample = merged_2v_upsample;
  45.388 +    upsample->upmethod = h2v2_merged_upsample;
  45.389 +    /* Allocate a spare row buffer */
  45.390 +    upsample->spare_row = (JSAMPROW)
  45.391 +      (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  45.392 +		(size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  45.393 +  } else {
  45.394 +    upsample->pub.upsample = merged_1v_upsample;
  45.395 +    upsample->upmethod = h2v1_merged_upsample;
  45.396 +    /* No spare row needed */
  45.397 +    upsample->spare_row = NULL;
  45.398 +  }
  45.399 +
  45.400 +  build_ycc_rgb_table(cinfo);
  45.401 +}
  45.402 +
  45.403 +#endif /* UPSAMPLE_MERGING_SUPPORTED */
    46.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    46.2 +++ b/libs/libjpeg/jdphuff.c	Thu Sep 08 06:28:38 2011 +0300
    46.3 @@ -0,0 +1,668 @@
    46.4 +/*
    46.5 + * jdphuff.c
    46.6 + *
    46.7 + * Copyright (C) 1995-1997, Thomas G. Lane.
    46.8 + * This file is part of the Independent JPEG Group's software.
    46.9 + * For conditions of distribution and use, see the accompanying README file.
   46.10 + *
   46.11 + * This file contains Huffman entropy decoding routines for progressive JPEG.
   46.12 + *
   46.13 + * Much of the complexity here has to do with supporting input suspension.
   46.14 + * If the data source module demands suspension, we want to be able to back
   46.15 + * up to the start of the current MCU.  To do this, we copy state variables
   46.16 + * into local working storage, and update them back to the permanent
   46.17 + * storage only upon successful completion of an MCU.
   46.18 + */
   46.19 +
   46.20 +#define JPEG_INTERNALS
   46.21 +#include "jinclude.h"
   46.22 +#include "jpeglib.h"
   46.23 +#include "jdhuff.h"		/* Declarations shared with jdhuff.c */
   46.24 +
   46.25 +
   46.26 +#ifdef D_PROGRESSIVE_SUPPORTED
   46.27 +
   46.28 +/*
   46.29 + * Expanded entropy decoder object for progressive Huffman decoding.
   46.30 + *
   46.31 + * The savable_state subrecord contains fields that change within an MCU,
   46.32 + * but must not be updated permanently until we complete the MCU.
   46.33 + */
   46.34 +
   46.35 +typedef struct {
   46.36 +  unsigned int EOBRUN;			/* remaining EOBs in EOBRUN */
   46.37 +  int last_dc_val[MAX_COMPS_IN_SCAN];	/* last DC coef for each component */
   46.38 +} savable_state;
   46.39 +
   46.40 +/* This macro is to work around compilers with missing or broken
   46.41 + * structure assignment.  You'll need to fix this code if you have
   46.42 + * such a compiler and you change MAX_COMPS_IN_SCAN.
   46.43 + */
   46.44 +
   46.45 +#ifndef NO_STRUCT_ASSIGN
   46.46 +#define ASSIGN_STATE(dest,src)  ((dest) = (src))
   46.47 +#else
   46.48 +#if MAX_COMPS_IN_SCAN == 4
   46.49 +#define ASSIGN_STATE(dest,src)  \
   46.50 +	((dest).EOBRUN = (src).EOBRUN, \
   46.51 +	 (dest).last_dc_val[0] = (src).last_dc_val[0], \
   46.52 +	 (dest).last_dc_val[1] = (src).last_dc_val[1], \
   46.53 +	 (dest).last_dc_val[2] = (src).last_dc_val[2], \
   46.54 +	 (dest).last_dc_val[3] = (src).last_dc_val[3])
   46.55 +#endif
   46.56 +#endif
   46.57 +
   46.58 +
   46.59 +typedef struct {
   46.60 +  struct jpeg_entropy_decoder pub; /* public fields */
   46.61 +
   46.62 +  /* These fields are loaded into local variables at start of each MCU.
   46.63 +   * In case of suspension, we exit WITHOUT updating them.
   46.64 +   */
   46.65 +  bitread_perm_state bitstate;	/* Bit buffer at start of MCU */
   46.66 +  savable_state saved;		/* Other state at start of MCU */
   46.67 +
   46.68 +  /* These fields are NOT loaded into local working state. */
   46.69 +  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
   46.70 +
   46.71 +  /* Pointers to derived tables (these workspaces have image lifespan) */
   46.72 +  d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
   46.73 +
   46.74 +  d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
   46.75 +} phuff_entropy_decoder;
   46.76 +
   46.77 +typedef phuff_entropy_decoder * phuff_entropy_ptr;
   46.78 +
   46.79 +/* Forward declarations */
   46.80 +METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
   46.81 +					    JBLOCKROW *MCU_data));
   46.82 +METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
   46.83 +					    JBLOCKROW *MCU_data));
   46.84 +METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
   46.85 +					     JBLOCKROW *MCU_data));
   46.86 +METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
   46.87 +					     JBLOCKROW *MCU_data));
   46.88 +
   46.89 +
   46.90 +/*
   46.91 + * Initialize for a Huffman-compressed scan.
   46.92 + */
   46.93 +
   46.94 +METHODDEF(void)
   46.95 +start_pass_phuff_decoder (j_decompress_ptr cinfo)
   46.96 +{
   46.97 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
   46.98 +  boolean is_DC_band, bad;
   46.99 +  int ci, coefi, tbl;
  46.100 +  int *coef_bit_ptr;
  46.101 +  jpeg_component_info * compptr;
  46.102 +
  46.103 +  is_DC_band = (cinfo->Ss == 0);
  46.104 +
  46.105 +  /* Validate scan parameters */
  46.106 +  bad = FALSE;
  46.107 +  if (is_DC_band) {
  46.108 +    if (cinfo->Se != 0)
  46.109 +      bad = TRUE;
  46.110 +  } else {
  46.111 +    /* need not check Ss/Se < 0 since they came from unsigned bytes */
  46.112 +    if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  46.113 +      bad = TRUE;
  46.114 +    /* AC scans may have only one component */
  46.115 +    if (cinfo->comps_in_scan != 1)
  46.116 +      bad = TRUE;
  46.117 +  }
  46.118 +  if (cinfo->Ah != 0) {
  46.119 +    /* Successive approximation refinement scan: must have Al = Ah-1. */
  46.120 +    if (cinfo->Al != cinfo->Ah-1)
  46.121 +      bad = TRUE;
  46.122 +  }
  46.123 +  if (cinfo->Al > 13)		/* need not check for < 0 */
  46.124 +    bad = TRUE;
  46.125 +  /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  46.126 +   * but the spec doesn't say so, and we try to be liberal about what we
  46.127 +   * accept.  Note: large Al values could result in out-of-range DC
  46.128 +   * coefficients during early scans, leading to bizarre displays due to
  46.129 +   * overflows in the IDCT math.  But we won't crash.
  46.130 +   */
  46.131 +  if (bad)
  46.132 +    ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  46.133 +	     cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  46.134 +  /* Update progression status, and verify that scan order is legal.
  46.135 +   * Note that inter-scan inconsistencies are treated as warnings
  46.136 +   * not fatal errors ... not clear if this is right way to behave.
  46.137 +   */
  46.138 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  46.139 +    int cindex = cinfo->cur_comp_info[ci]->component_index;
  46.140 +    coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  46.141 +    if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  46.142 +      WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  46.143 +    for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  46.144 +      int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  46.145 +      if (cinfo->Ah != expected)
  46.146 +	WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  46.147 +      coef_bit_ptr[coefi] = cinfo->Al;
  46.148 +    }
  46.149 +  }
  46.150 +
  46.151 +  /* Select MCU decoding routine */
  46.152 +  if (cinfo->Ah == 0) {
  46.153 +    if (is_DC_band)
  46.154 +      entropy->pub.decode_mcu = decode_mcu_DC_first;
  46.155 +    else
  46.156 +      entropy->pub.decode_mcu = decode_mcu_AC_first;
  46.157 +  } else {
  46.158 +    if (is_DC_band)
  46.159 +      entropy->pub.decode_mcu = decode_mcu_DC_refine;
  46.160 +    else
  46.161 +      entropy->pub.decode_mcu = decode_mcu_AC_refine;
  46.162 +  }
  46.163 +
  46.164 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  46.165 +    compptr = cinfo->cur_comp_info[ci];
  46.166 +    /* Make sure requested tables are present, and compute derived tables.
  46.167 +     * We may build same derived table more than once, but it's not expensive.
  46.168 +     */
  46.169 +    if (is_DC_band) {
  46.170 +      if (cinfo->Ah == 0) {	/* DC refinement needs no table */
  46.171 +	tbl = compptr->dc_tbl_no;
  46.172 +	jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  46.173 +				& entropy->derived_tbls[tbl]);
  46.174 +      }
  46.175 +    } else {
  46.176 +      tbl = compptr->ac_tbl_no;
  46.177 +      jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  46.178 +			      & entropy->derived_tbls[tbl]);
  46.179 +      /* remember the single active table */
  46.180 +      entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  46.181 +    }
  46.182 +    /* Initialize DC predictions to 0 */
  46.183 +    entropy->saved.last_dc_val[ci] = 0;
  46.184 +  }
  46.185 +
  46.186 +  /* Initialize bitread state variables */
  46.187 +  entropy->bitstate.bits_left = 0;
  46.188 +  entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  46.189 +  entropy->pub.insufficient_data = FALSE;
  46.190 +
  46.191 +  /* Initialize private state variables */
  46.192 +  entropy->saved.EOBRUN = 0;
  46.193 +
  46.194 +  /* Initialize restart counter */
  46.195 +  entropy->restarts_to_go = cinfo->restart_interval;
  46.196 +}
  46.197 +
  46.198 +
  46.199 +/*
  46.200 + * Figure F.12: extend sign bit.
  46.201 + * On some machines, a shift and add will be faster than a table lookup.
  46.202 + */
  46.203 +
  46.204 +#ifdef AVOID_TABLES
  46.205 +
  46.206 +#define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  46.207 +
  46.208 +#else
  46.209 +
  46.210 +#define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  46.211 +
  46.212 +static const int extend_test[16] =   /* entry n is 2**(n-1) */
  46.213 +  { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  46.214 +    0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  46.215 +
  46.216 +static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  46.217 +  { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  46.218 +    ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  46.219 +    ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  46.220 +    ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  46.221 +
  46.222 +#endif /* AVOID_TABLES */
  46.223 +
  46.224 +
  46.225 +/*
  46.226 + * Check for a restart marker & resynchronize decoder.
  46.227 + * Returns FALSE if must suspend.
  46.228 + */
  46.229 +
  46.230 +LOCAL(boolean)
  46.231 +process_restart (j_decompress_ptr cinfo)
  46.232 +{
  46.233 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  46.234 +  int ci;
  46.235 +
  46.236 +  /* Throw away any unused bits remaining in bit buffer; */
  46.237 +  /* include any full bytes in next_marker's count of discarded bytes */
  46.238 +  cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  46.239 +  entropy->bitstate.bits_left = 0;
  46.240 +
  46.241 +  /* Advance past the RSTn marker */
  46.242 +  if (! (*cinfo->marker->read_restart_marker) (cinfo))
  46.243 +    return FALSE;
  46.244 +
  46.245 +  /* Re-initialize DC predictions to 0 */
  46.246 +  for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  46.247 +    entropy->saved.last_dc_val[ci] = 0;
  46.248 +  /* Re-init EOB run count, too */
  46.249 +  entropy->saved.EOBRUN = 0;
  46.250 +
  46.251 +  /* Reset restart counter */
  46.252 +  entropy->restarts_to_go = cinfo->restart_interval;
  46.253 +
  46.254 +  /* Reset out-of-data flag, unless read_restart_marker left us smack up
  46.255 +   * against a marker.  In that case we will end up treating the next data
  46.256 +   * segment as empty, and we can avoid producing bogus output pixels by
  46.257 +   * leaving the flag set.
  46.258 +   */
  46.259 +  if (cinfo->unread_marker == 0)
  46.260 +    entropy->pub.insufficient_data = FALSE;
  46.261 +
  46.262 +  return TRUE;
  46.263 +}
  46.264 +
  46.265 +
  46.266 +/*
  46.267 + * Huffman MCU decoding.
  46.268 + * Each of these routines decodes and returns one MCU's worth of
  46.269 + * Huffman-compressed coefficients. 
  46.270 + * The coefficients are reordered from zigzag order into natural array order,
  46.271 + * but are not dequantized.
  46.272 + *
  46.273 + * The i'th block of the MCU is stored into the block pointed to by
  46.274 + * MCU_data[i].  WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  46.275 + *
  46.276 + * We return FALSE if data source requested suspension.  In that case no
  46.277 + * changes have been made to permanent state.  (Exception: some output
  46.278 + * coefficients may already have been assigned.  This is harmless for
  46.279 + * spectral selection, since we'll just re-assign them on the next call.
  46.280 + * Successive approximation AC refinement has to be more careful, however.)
  46.281 + */
  46.282 +
  46.283 +/*
  46.284 + * MCU decoding for DC initial scan (either spectral selection,
  46.285 + * or first pass of successive approximation).
  46.286 + */
  46.287 +
  46.288 +METHODDEF(boolean)
  46.289 +decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  46.290 +{   
  46.291 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  46.292 +  int Al = cinfo->Al;
  46.293 +  register int s, r;
  46.294 +  int blkn, ci;
  46.295 +  JBLOCKROW block;
  46.296 +  BITREAD_STATE_VARS;
  46.297 +  savable_state state;
  46.298 +  d_derived_tbl * tbl;
  46.299 +  jpeg_component_info * compptr;
  46.300 +
  46.301 +  /* Process restart marker if needed; may have to suspend */
  46.302 +  if (cinfo->restart_interval) {
  46.303 +    if (entropy->restarts_to_go == 0)
  46.304 +      if (! process_restart(cinfo))
  46.305 +	return FALSE;
  46.306 +  }
  46.307 +
  46.308 +  /* If we've run out of data, just leave the MCU set to zeroes.
  46.309 +   * This way, we return uniform gray for the remainder of the segment.
  46.310 +   */
  46.311 +  if (! entropy->pub.insufficient_data) {
  46.312 +
  46.313 +    /* Load up working state */
  46.314 +    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  46.315 +    ASSIGN_STATE(state, entropy->saved);
  46.316 +
  46.317 +    /* Outer loop handles each block in the MCU */
  46.318 +
  46.319 +    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  46.320 +      block = MCU_data[blkn];
  46.321 +      ci = cinfo->MCU_membership[blkn];
  46.322 +      compptr = cinfo->cur_comp_info[ci];
  46.323 +      tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  46.324 +
  46.325 +      /* Decode a single block's worth of coefficients */
  46.326 +
  46.327 +      /* Section F.2.2.1: decode the DC coefficient difference */
  46.328 +      HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  46.329 +      if (s) {
  46.330 +	CHECK_BIT_BUFFER(br_state, s, return FALSE);
  46.331 +	r = GET_BITS(s);
  46.332 +	s = HUFF_EXTEND(r, s);
  46.333 +      }
  46.334 +
  46.335 +      /* Convert DC difference to actual value, update last_dc_val */
  46.336 +      s += state.last_dc_val[ci];
  46.337 +      state.last_dc_val[ci] = s;
  46.338 +      /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  46.339 +      (*block)[0] = (JCOEF) (s << Al);
  46.340 +    }
  46.341 +
  46.342 +    /* Completed MCU, so update state */
  46.343 +    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  46.344 +    ASSIGN_STATE(entropy->saved, state);
  46.345 +  }
  46.346 +
  46.347 +  /* Account for restart interval (no-op if not using restarts) */
  46.348 +  entropy->restarts_to_go--;
  46.349 +
  46.350 +  return TRUE;
  46.351 +}
  46.352 +
  46.353 +
  46.354 +/*
  46.355 + * MCU decoding for AC initial scan (either spectral selection,
  46.356 + * or first pass of successive approximation).
  46.357 + */
  46.358 +
  46.359 +METHODDEF(boolean)
  46.360 +decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  46.361 +{   
  46.362 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  46.363 +  int Se = cinfo->Se;
  46.364 +  int Al = cinfo->Al;
  46.365 +  register int s, k, r;
  46.366 +  unsigned int EOBRUN;
  46.367 +  JBLOCKROW block;
  46.368 +  BITREAD_STATE_VARS;
  46.369 +  d_derived_tbl * tbl;
  46.370 +
  46.371 +  /* Process restart marker if needed; may have to suspend */
  46.372 +  if (cinfo->restart_interval) {
  46.373 +    if (entropy->restarts_to_go == 0)
  46.374 +      if (! process_restart(cinfo))
  46.375 +	return FALSE;
  46.376 +  }
  46.377 +
  46.378 +  /* If we've run out of data, just leave the MCU set to zeroes.
  46.379 +   * This way, we return uniform gray for the remainder of the segment.
  46.380 +   */
  46.381 +  if (! entropy->pub.insufficient_data) {
  46.382 +
  46.383 +    /* Load up working state.
  46.384 +     * We can avoid loading/saving bitread state if in an EOB run.
  46.385 +     */
  46.386 +    EOBRUN = entropy->saved.EOBRUN;	/* only part of saved state we need */
  46.387 +
  46.388 +    /* There is always only one block per MCU */
  46.389 +
  46.390 +    if (EOBRUN > 0)		/* if it's a band of zeroes... */
  46.391 +      EOBRUN--;			/* ...process it now (we do nothing) */
  46.392 +    else {
  46.393 +      BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  46.394 +      block = MCU_data[0];
  46.395 +      tbl = entropy->ac_derived_tbl;
  46.396 +
  46.397 +      for (k = cinfo->Ss; k <= Se; k++) {
  46.398 +	HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  46.399 +	r = s >> 4;
  46.400 +	s &= 15;
  46.401 +	if (s) {
  46.402 +	  k += r;
  46.403 +	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
  46.404 +	  r = GET_BITS(s);
  46.405 +	  s = HUFF_EXTEND(r, s);
  46.406 +	  /* Scale and output coefficient in natural (dezigzagged) order */
  46.407 +	  (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  46.408 +	} else {
  46.409 +	  if (r == 15) {	/* ZRL */
  46.410 +	    k += 15;		/* skip 15 zeroes in band */
  46.411 +	  } else {		/* EOBr, run length is 2^r + appended bits */
  46.412 +	    EOBRUN = 1 << r;
  46.413 +	    if (r) {		/* EOBr, r > 0 */
  46.414 +	      CHECK_BIT_BUFFER(br_state, r, return FALSE);
  46.415 +	      r = GET_BITS(r);
  46.416 +	      EOBRUN += r;
  46.417 +	    }
  46.418 +	    EOBRUN--;		/* this band is processed at this moment */
  46.419 +	    break;		/* force end-of-band */
  46.420 +	  }
  46.421 +	}
  46.422 +      }
  46.423 +
  46.424 +      BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  46.425 +    }
  46.426 +
  46.427 +    /* Completed MCU, so update state */
  46.428 +    entropy->saved.EOBRUN = EOBRUN;	/* only part of saved state we need */
  46.429 +  }
  46.430 +
  46.431 +  /* Account for restart interval (no-op if not using restarts) */
  46.432 +  entropy->restarts_to_go--;
  46.433 +
  46.434 +  return TRUE;
  46.435 +}
  46.436 +
  46.437 +
  46.438 +/*
  46.439 + * MCU decoding for DC successive approximation refinement scan.
  46.440 + * Note: we assume such scans can be multi-component, although the spec
  46.441 + * is not very clear on the point.
  46.442 + */
  46.443 +
  46.444 +METHODDEF(boolean)
  46.445 +decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  46.446 +{   
  46.447 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  46.448 +  int p1 = 1 << cinfo->Al;	/* 1 in the bit position being coded */
  46.449 +  int blkn;
  46.450 +  JBLOCKROW block;
  46.451 +  BITREAD_STATE_VARS;
  46.452 +
  46.453 +  /* Process restart marker if needed; may have to suspend */
  46.454 +  if (cinfo->restart_interval) {
  46.455 +    if (entropy->restarts_to_go == 0)
  46.456 +      if (! process_restart(cinfo))
  46.457 +	return FALSE;
  46.458 +  }
  46.459 +
  46.460 +  /* Not worth the cycles to check insufficient_data here,
  46.461 +   * since we will not change the data anyway if we read zeroes.
  46.462 +   */
  46.463 +
  46.464 +  /* Load up working state */
  46.465 +  BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  46.466 +
  46.467 +  /* Outer loop handles each block in the MCU */
  46.468 +
  46.469 +  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  46.470 +    block = MCU_data[blkn];
  46.471 +
  46.472 +    /* Encoded data is simply the next bit of the two's-complement DC value */
  46.473 +    CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  46.474 +    if (GET_BITS(1))
  46.475 +      (*block)[0] |= p1;
  46.476 +    /* Note: since we use |=, repeating the assignment later is safe */
  46.477 +  }
  46.478 +
  46.479 +  /* Completed MCU, so update state */
  46.480 +  BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  46.481 +
  46.482 +  /* Account for restart interval (no-op if not using restarts) */
  46.483 +  entropy->restarts_to_go--;
  46.484 +
  46.485 +  return TRUE;
  46.486 +}
  46.487 +
  46.488 +
  46.489 +/*
  46.490 + * MCU decoding for AC successive approximation refinement scan.
  46.491 + */
  46.492 +
  46.493 +METHODDEF(boolean)
  46.494 +decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  46.495 +{   
  46.496 +  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  46.497 +  int Se = cinfo->Se;
  46.498 +  int p1 = 1 << cinfo->Al;	/* 1 in the bit position being coded */
  46.499 +  int m1 = (-1) << cinfo->Al;	/* -1 in the bit position being coded */
  46.500 +  register int s, k, r;
  46.501 +  unsigned int EOBRUN;
  46.502 +  JBLOCKROW block;
  46.503 +  JCOEFPTR thiscoef;
  46.504 +  BITREAD_STATE_VARS;
  46.505 +  d_derived_tbl * tbl;
  46.506 +  int num_newnz;
  46.507 +  int newnz_pos[DCTSIZE2];
  46.508 +
  46.509 +  /* Process restart marker if needed; may have to suspend */
  46.510 +  if (cinfo->restart_interval) {
  46.511 +    if (entropy->restarts_to_go == 0)
  46.512 +      if (! process_restart(cinfo))
  46.513 +	return FALSE;
  46.514 +  }
  46.515 +
  46.516 +  /* If we've run out of data, don't modify the MCU.
  46.517 +   */
  46.518 +  if (! entropy->pub.insufficient_data) {
  46.519 +
  46.520 +    /* Load up working state */
  46.521 +    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  46.522 +    EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  46.523 +
  46.524 +    /* There is always only one block per MCU */
  46.525 +    block = MCU_data[0];
  46.526 +    tbl = entropy->ac_derived_tbl;
  46.527 +
  46.528 +    /* If we are forced to suspend, we must undo the assignments to any newly
  46.529 +     * nonzero coefficients in the block, because otherwise we'd get confused
  46.530 +     * next time about which coefficients were already nonzero.
  46.531 +     * But we need not undo addition of bits to already-nonzero coefficients;
  46.532 +     * instead, we can test the current bit to see if we already did it.
  46.533 +     */
  46.534 +    num_newnz = 0;
  46.535 +
  46.536 +    /* initialize coefficient loop counter to start of band */
  46.537 +    k = cinfo->Ss;
  46.538 +
  46.539 +    if (EOBRUN == 0) {
  46.540 +      for (; k <= Se; k++) {
  46.541 +	HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  46.542 +	r = s >> 4;
  46.543 +	s &= 15;
  46.544 +	if (s) {
  46.545 +	  if (s != 1)		/* size of new coef should always be 1 */
  46.546 +	    WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  46.547 +	  CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  46.548 +	  if (GET_BITS(1))
  46.549 +	    s = p1;		/* newly nonzero coef is positive */
  46.550 +	  else
  46.551 +	    s = m1;		/* newly nonzero coef is negative */
  46.552 +	} else {
  46.553 +	  if (r != 15) {
  46.554 +	    EOBRUN = 1 << r;	/* EOBr, run length is 2^r + appended bits */
  46.555 +	    if (r) {
  46.556 +	      CHECK_BIT_BUFFER(br_state, r, goto undoit);
  46.557 +	      r = GET_BITS(r);
  46.558 +	      EOBRUN += r;
  46.559 +	    }
  46.560 +	    break;		/* rest of block is handled by EOB logic */
  46.561 +	  }
  46.562 +	  /* note s = 0 for processing ZRL */
  46.563 +	}
  46.564 +	/* Advance over already-nonzero coefs and r still-zero coefs,
  46.565 +	 * appending correction bits to the nonzeroes.  A correction bit is 1
  46.566 +	 * if the absolute value of the coefficient must be increased.
  46.567 +	 */
  46.568 +	do {
  46.569 +	  thiscoef = *block + jpeg_natural_order[k];
  46.570 +	  if (*thiscoef != 0) {
  46.571 +	    CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  46.572 +	    if (GET_BITS(1)) {
  46.573 +	      if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  46.574 +		if (*thiscoef >= 0)
  46.575 +		  *thiscoef += p1;
  46.576 +		else
  46.577 +		  *thiscoef += m1;
  46.578 +	      }
  46.579 +	    }
  46.580 +	  } else {
  46.581 +	    if (--r < 0)
  46.582 +	      break;		/* reached target zero coefficient */
  46.583 +	  }
  46.584 +	  k++;
  46.585 +	} while (k <= Se);
  46.586 +	if (s) {
  46.587 +	  int pos = jpeg_natural_order[k];
  46.588 +	  /* Output newly nonzero coefficient */
  46.589 +	  (*block)[pos] = (JCOEF) s;
  46.590 +	  /* Remember its position in case we have to suspend */
  46.591 +	  newnz_pos[num_newnz++] = pos;
  46.592 +	}
  46.593 +      }
  46.594 +    }
  46.595 +
  46.596 +    if (EOBRUN > 0) {
  46.597 +      /* Scan any remaining coefficient positions after the end-of-band
  46.598 +       * (the last newly nonzero coefficient, if any).  Append a correction
  46.599 +       * bit to each already-nonzero coefficient.  A correction bit is 1
  46.600 +       * if the absolute value of the coefficient must be increased.
  46.601 +       */
  46.602 +      for (; k <= Se; k++) {
  46.603 +	thiscoef = *block + jpeg_natural_order[k];
  46.604 +	if (*thiscoef != 0) {
  46.605 +	  CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  46.606 +	  if (GET_BITS(1)) {
  46.607 +	    if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  46.608 +	      if (*thiscoef >= 0)
  46.609 +		*thiscoef += p1;
  46.610 +	      else
  46.611 +		*thiscoef += m1;
  46.612 +	    }
  46.613 +	  }
  46.614 +	}
  46.615 +      }
  46.616 +      /* Count one block completed in EOB run */
  46.617 +      EOBRUN--;
  46.618 +    }
  46.619 +
  46.620 +    /* Completed MCU, so update state */
  46.621 +    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  46.622 +    entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  46.623 +  }
  46.624 +
  46.625 +  /* Account for restart interval (no-op if not using restarts) */
  46.626 +  entropy->restarts_to_go--;
  46.627 +
  46.628 +  return TRUE;
  46.629 +
  46.630 +undoit:
  46.631 +  /* Re-zero any output coefficients that we made newly nonzero */
  46.632 +  while (num_newnz > 0)
  46.633 +    (*block)[newnz_pos[--num_newnz]] = 0;
  46.634 +
  46.635 +  return FALSE;
  46.636 +}
  46.637 +
  46.638 +
  46.639 +/*
  46.640 + * Module initialization routine for progressive Huffman entropy decoding.
  46.641 + */
  46.642 +
  46.643 +GLOBAL(void)
  46.644 +jinit_phuff_decoder (j_decompress_ptr cinfo)
  46.645 +{
  46.646 +  phuff_entropy_ptr entropy;
  46.647 +  int *coef_bit_ptr;
  46.648 +  int ci, i;
  46.649 +
  46.650 +  entropy = (phuff_entropy_ptr)
  46.651 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  46.652 +				SIZEOF(phuff_entropy_decoder));
  46.653 +  cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  46.654 +  entropy->pub.start_pass = start_pass_phuff_decoder;
  46.655 +
  46.656 +  /* Mark derived tables unallocated */
  46.657 +  for (i = 0; i < NUM_HUFF_TBLS; i++) {
  46.658 +    entropy->derived_tbls[i] = NULL;
  46.659 +  }
  46.660 +
  46.661 +  /* Create progression status table */
  46.662 +  cinfo->coef_bits = (int (*)[DCTSIZE2])
  46.663 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  46.664 +				cinfo->num_components*DCTSIZE2*SIZEOF(int));
  46.665 +  coef_bit_ptr = & cinfo->coef_bits[0][0];
  46.666 +  for (ci = 0; ci < cinfo->num_components; ci++) 
  46.667 +    for (i = 0; i < DCTSIZE2; i++)
  46.668 +      *coef_bit_ptr++ = -1;
  46.669 +}
  46.670 +
  46.671 +#endif /* D_PROGRESSIVE_SUPPORTED */
    47.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    47.2 +++ b/libs/libjpeg/jdpostct.c	Thu Sep 08 06:28:38 2011 +0300
    47.3 @@ -0,0 +1,290 @@
    47.4 +/*
    47.5 + * jdpostct.c
    47.6 + *
    47.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    47.8 + * This file is part of the Independent JPEG Group's software.
    47.9 + * For conditions of distribution and use, see the accompanying README file.
   47.10 + *
   47.11 + * This file contains the decompression postprocessing controller.
   47.12 + * This controller manages the upsampling, color conversion, and color
   47.13 + * quantization/reduction steps; specifically, it controls the buffering
   47.14 + * between upsample/color conversion and color quantization/reduction.
   47.15 + *
   47.16 + * If no color quantization/reduction is required, then this module has no
   47.17 + * work to do, and it just hands off to the upsample/color conversion code.
   47.18 + * An integrated upsample/convert/quantize process would replace this module
   47.19 + * entirely.
   47.20 + */
   47.21 +
   47.22 +#define JPEG_INTERNALS
   47.23 +#include "jinclude.h"
   47.24 +#include "jpeglib.h"
   47.25 +
   47.26 +
   47.27 +/* Private buffer controller object */
   47.28 +
   47.29 +typedef struct {
   47.30 +  struct jpeg_d_post_controller pub; /* public fields */
   47.31 +
   47.32 +  /* Color quantization source buffer: this holds output data from
   47.33 +   * the upsample/color conversion step to be passed to the quantizer.
   47.34 +   * For two-pass color quantization, we need a full-image buffer;
   47.35 +   * for one-pass operation, a strip buffer is sufficient.
   47.36 +   */
   47.37 +  jvirt_sarray_ptr whole_image;	/* virtual array, or NULL if one-pass */
   47.38 +  JSAMPARRAY buffer;		/* strip buffer, or current strip of virtual */
   47.39 +  JDIMENSION strip_height;	/* buffer size in rows */
   47.40 +  /* for two-pass mode only: */
   47.41 +  JDIMENSION starting_row;	/* row # of first row in current strip */
   47.42 +  JDIMENSION next_row;		/* index of next row to fill/empty in strip */
   47.43 +} my_post_controller;
   47.44 +
   47.45 +typedef my_post_controller * my_post_ptr;
   47.46 +
   47.47 +
   47.48 +/* Forward declarations */
   47.49 +METHODDEF(void) post_process_1pass
   47.50 +	JPP((j_decompress_ptr cinfo,
   47.51 +	     JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
   47.52 +	     JDIMENSION in_row_groups_avail,
   47.53 +	     JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
   47.54 +	     JDIMENSION out_rows_avail));
   47.55 +#ifdef QUANT_2PASS_SUPPORTED
   47.56 +METHODDEF(void) post_process_prepass
   47.57 +	JPP((j_decompress_ptr cinfo,
   47.58 +	     JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
   47.59 +	     JDIMENSION in_row_groups_avail,
   47.60 +	     JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
   47.61 +	     JDIMENSION out_rows_avail));
   47.62 +METHODDEF(void) post_process_2pass
   47.63 +	JPP((j_decompress_ptr cinfo,
   47.64 +	     JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
   47.65 +	     JDIMENSION in_row_groups_avail,
   47.66 +	     JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
   47.67 +	     JDIMENSION out_rows_avail));
   47.68 +#endif
   47.69 +
   47.70 +
   47.71 +/*
   47.72 + * Initialize for a processing pass.
   47.73 + */
   47.74 +
   47.75 +METHODDEF(void)
   47.76 +start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
   47.77 +{
   47.78 +  my_post_ptr post = (my_post_ptr) cinfo->post;
   47.79 +
   47.80 +  switch (pass_mode) {
   47.81 +  case JBUF_PASS_THRU:
   47.82 +    if (cinfo->quantize_colors) {
   47.83 +      /* Single-pass processing with color quantization. */
   47.84 +      post->pub.post_process_data = post_process_1pass;
   47.85 +      /* We could be doing buffered-image output before starting a 2-pass
   47.86 +       * color quantization; in that case, jinit_d_post_controller did not
   47.87 +       * allocate a strip buffer.  Use the virtual-array buffer as workspace.
   47.88 +       */
   47.89 +      if (post->buffer == NULL) {
   47.90 +	post->buffer = (*cinfo->mem->access_virt_sarray)
   47.91 +	  ((j_common_ptr) cinfo, post->whole_image,
   47.92 +	   (JDIMENSION) 0, post->strip_height, TRUE);
   47.93 +      }
   47.94 +    } else {
   47.95 +      /* For single-pass processing without color quantization,
   47.96 +       * I have no work to do; just call the upsampler directly.
   47.97 +       */
   47.98 +      post->pub.post_process_data = cinfo->upsample->upsample;
   47.99 +    }
  47.100 +    break;
  47.101 +#ifdef QUANT_2PASS_SUPPORTED
  47.102 +  case JBUF_SAVE_AND_PASS:
  47.103 +    /* First pass of 2-pass quantization */
  47.104 +    if (post->whole_image == NULL)
  47.105 +      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  47.106 +    post->pub.post_process_data = post_process_prepass;
  47.107 +    break;
  47.108 +  case JBUF_CRANK_DEST:
  47.109 +    /* Second pass of 2-pass quantization */
  47.110 +    if (post->whole_image == NULL)
  47.111 +      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  47.112 +    post->pub.post_process_data = post_process_2pass;
  47.113 +    break;
  47.114 +#endif /* QUANT_2PASS_SUPPORTED */
  47.115 +  default:
  47.116 +    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  47.117 +    break;
  47.118 +  }
  47.119 +  post->starting_row = post->next_row = 0;
  47.120 +}
  47.121 +
  47.122 +
  47.123 +/*
  47.124 + * Process some data in the one-pass (strip buffer) case.
  47.125 + * This is used for color precision reduction as well as one-pass quantization.
  47.126 + */
  47.127 +
  47.128 +METHODDEF(void)
  47.129 +post_process_1pass (j_decompress_ptr cinfo,
  47.130 +		    JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  47.131 +		    JDIMENSION in_row_groups_avail,
  47.132 +		    JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  47.133 +		    JDIMENSION out_rows_avail)
  47.134 +{
  47.135 +  my_post_ptr post = (my_post_ptr) cinfo->post;
  47.136 +  JDIMENSION num_rows, max_rows;
  47.137 +
  47.138 +  /* Fill the buffer, but not more than what we can dump out in one go. */
  47.139 +  /* Note we rely on the upsampler to detect bottom of image. */
  47.140 +  max_rows = out_rows_avail - *out_row_ctr;
  47.141 +  if (max_rows > post->strip_height)
  47.142 +    max_rows = post->strip_height;
  47.143 +  num_rows = 0;
  47.144 +  (*cinfo->upsample->upsample) (cinfo,
  47.145 +		input_buf, in_row_group_ctr, in_row_groups_avail,
  47.146 +		post->buffer, &num_rows, max_rows);
  47.147 +  /* Quantize and emit data. */
  47.148 +  (*cinfo->cquantize->color_quantize) (cinfo,
  47.149 +		post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  47.150 +  *out_row_ctr += num_rows;
  47.151 +}
  47.152 +
  47.153 +
  47.154 +#ifdef QUANT_2PASS_SUPPORTED
  47.155 +
  47.156 +/*
  47.157 + * Process some data in the first pass of 2-pass quantization.
  47.158 + */
  47.159 +
  47.160 +METHODDEF(void)
  47.161 +post_process_prepass (j_decompress_ptr cinfo,
  47.162 +		      JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  47.163 +		      JDIMENSION in_row_groups_avail,
  47.164 +		      JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  47.165 +		      JDIMENSION out_rows_avail)
  47.166 +{
  47.167 +  my_post_ptr post = (my_post_ptr) cinfo->post;
  47.168 +  JDIMENSION old_next_row, num_rows;
  47.169 +
  47.170 +  /* Reposition virtual buffer if at start of strip. */
  47.171 +  if (post->next_row == 0) {
  47.172 +    post->buffer = (*cinfo->mem->access_virt_sarray)
  47.173 +	((j_common_ptr) cinfo, post->whole_image,
  47.174 +	 post->starting_row, post->strip_height, TRUE);
  47.175 +  }
  47.176 +
  47.177 +  /* Upsample some data (up to a strip height's worth). */
  47.178 +  old_next_row = post->next_row;
  47.179 +  (*cinfo->upsample->upsample) (cinfo,
  47.180 +		input_buf, in_row_group_ctr, in_row_groups_avail,
  47.181 +		post->buffer, &post->next_row, post->strip_height);
  47.182 +
  47.183 +  /* Allow quantizer to scan new data.  No data is emitted, */
  47.184 +  /* but we advance out_row_ctr so outer loop can tell when we're done. */
  47.185 +  if (post->next_row > old_next_row) {
  47.186 +    num_rows = post->next_row - old_next_row;
  47.187 +    (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  47.188 +					 (JSAMPARRAY) NULL, (int) num_rows);
  47.189 +    *out_row_ctr += num_rows;
  47.190 +  }
  47.191 +
  47.192 +  /* Advance if we filled the strip. */
  47.193 +  if (post->next_row >= post->strip_height) {
  47.194 +    post->starting_row += post->strip_height;
  47.195 +    post->next_row = 0;
  47.196 +  }
  47.197 +}
  47.198 +
  47.199 +
  47.200 +/*
  47.201 + * Process some data in the second pass of 2-pass quantization.
  47.202 + */
  47.203 +
  47.204 +METHODDEF(void)
  47.205 +post_process_2pass (j_decompress_ptr cinfo,
  47.206 +		    JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  47.207 +		    JDIMENSION in_row_groups_avail,
  47.208 +		    JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  47.209 +		    JDIMENSION out_rows_avail)
  47.210 +{
  47.211 +  my_post_ptr post = (my_post_ptr) cinfo->post;
  47.212 +  JDIMENSION num_rows, max_rows;
  47.213 +
  47.214 +  /* Reposition virtual buffer if at start of strip. */
  47.215 +  if (post->next_row == 0) {
  47.216 +    post->buffer = (*cinfo->mem->access_virt_sarray)
  47.217 +	((j_common_ptr) cinfo, post->whole_image,
  47.218 +	 post->starting_row, post->strip_height, FALSE);
  47.219 +  }
  47.220 +
  47.221 +  /* Determine number of rows to emit. */
  47.222 +  num_rows = post->strip_height - post->next_row; /* available in strip */
  47.223 +  max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  47.224 +  if (num_rows > max_rows)
  47.225 +    num_rows = max_rows;
  47.226 +  /* We have to check bottom of image here, can't depend on upsampler. */
  47.227 +  max_rows = cinfo->output_height - post->starting_row;
  47.228 +  if (num_rows > max_rows)
  47.229 +    num_rows = max_rows;
  47.230 +
  47.231 +  /* Quantize and emit data. */
  47.232 +  (*cinfo->cquantize->color_quantize) (cinfo,
  47.233 +		post->buffer + post->next_row, output_buf + *out_row_ctr,
  47.234 +		(int) num_rows);
  47.235 +  *out_row_ctr += num_rows;
  47.236 +
  47.237 +  /* Advance if we filled the strip. */
  47.238 +  post->next_row += num_rows;
  47.239 +  if (post->next_row >= post->strip_height) {
  47.240 +    post->starting_row += post->strip_height;
  47.241 +    post->next_row = 0;
  47.242 +  }
  47.243 +}
  47.244 +
  47.245 +#endif /* QUANT_2PASS_SUPPORTED */
  47.246 +
  47.247 +
  47.248 +/*
  47.249 + * Initialize postprocessing controller.
  47.250 + */
  47.251 +
  47.252 +GLOBAL(void)
  47.253 +jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  47.254 +{
  47.255 +  my_post_ptr post;
  47.256 +
  47.257 +  post = (my_post_ptr)
  47.258 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  47.259 +				SIZEOF(my_post_controller));
  47.260 +  cinfo->post = (struct jpeg_d_post_controller *) post;
  47.261 +  post->pub.start_pass = start_pass_dpost;
  47.262 +  post->whole_image = NULL;	/* flag for no virtual arrays */
  47.263 +  post->buffer = NULL;		/* flag for no strip buffer */
  47.264 +
  47.265 +  /* Create the quantization buffer, if needed */
  47.266 +  if (cinfo->quantize_colors) {
  47.267 +    /* The buffer strip height is max_v_samp_factor, which is typically
  47.268 +     * an efficient number of rows for upsampling to return.
  47.269 +     * (In the presence of output rescaling, we might want to be smarter?)
  47.270 +     */
  47.271 +    post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  47.272 +    if (need_full_buffer) {
  47.273 +      /* Two-pass color quantization: need full-image storage. */
  47.274 +      /* We round up the number of rows to a multiple of the strip height. */
  47.275 +#ifdef QUANT_2PASS_SUPPORTED
  47.276 +      post->whole_image = (*cinfo->mem->request_virt_sarray)
  47.277 +	((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  47.278 +	 cinfo->output_width * cinfo->out_color_components,
  47.279 +	 (JDIMENSION) jround_up((long) cinfo->output_height,
  47.280 +				(long) post->strip_height),
  47.281 +	 post->strip_height);
  47.282 +#else
  47.283 +      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  47.284 +#endif /* QUANT_2PASS_SUPPORTED */
  47.285 +    } else {
  47.286 +      /* One-pass color quantization: just make a strip buffer. */
  47.287 +      post->buffer = (*cinfo->mem->alloc_sarray)
  47.288 +	((j_common_ptr) cinfo, JPOOL_IMAGE,
  47.289 +	 cinfo->output_width * cinfo->out_color_components,
  47.290 +	 post->strip_height);
  47.291 +    }
  47.292 +  }
  47.293 +}
    48.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    48.2 +++ b/libs/libjpeg/jdsample.c	Thu Sep 08 06:28:38 2011 +0300
    48.3 @@ -0,0 +1,478 @@
    48.4 +/*
    48.5 + * jdsample.c
    48.6 + *
    48.7 + * Copyright (C) 1991-1996, Thomas G. Lane.
    48.8 + * This file is part of the Independent JPEG Group's software.
    48.9 + * For conditions of distribution and use, see the accompanying README file.
   48.10 + *
   48.11 + * This file contains upsampling routines.
   48.12 + *
   48.13 + * Upsampling input data is counted in "row groups".  A row group
   48.14 + * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
   48.15 + * sample rows of each component.  Upsampling will normally produce
   48.16 + * max_v_samp_factor pixel rows from each row group (but this could vary
   48.17 + * if the upsampler is applying a scale factor of its own).
   48.18 + *
   48.19 + * An excellent reference for image resampling is
   48.20 + *   Digital Image Warping, George Wolberg, 1990.
   48.21 + *   Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7.
   48.22 + */
   48.23 +
   48.24 +#define JPEG_INTERNALS
   48.25 +#include "jinclude.h"
   48.26 +#include "jpeglib.h"
   48.27 +
   48.28 +
   48.29 +/* Pointer to routine to upsample a single component */
   48.30 +typedef JMETHOD(void, upsample1_ptr,
   48.31 +		(j_decompress_ptr cinfo, jpeg_component_info * compptr,
   48.32 +		 JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
   48.33 +
   48.34 +/* Private subobject */
   48.35 +
   48.36 +typedef struct {
   48.37 +  struct jpeg_upsampler pub;	/* public fields */
   48.38 +
   48.39 +  /* Color conversion buffer.  When using separate upsampling and color
   48.40 +   * conversion steps, this buffer holds one upsampled row group until it
   48.41 +   * has been color converted and output.
   48.42 +   * Note: we do not allocate any storage for component(s) which are full-size,
   48.43 +   * ie do not need rescaling.  The corresponding entry of color_buf[] is
   48.44 +   * simply set to point to the input data array, thereby avoiding copying.
   48.45 +   */
   48.46 +  JSAMPARRAY color_buf[MAX_COMPONENTS];
   48.47 +
   48.48 +  /* Per-component upsampling method pointers */
   48.49 +  upsample1_ptr methods[MAX_COMPONENTS];
   48.50 +
   48.51 +  int next_row_out;		/* counts rows emitted from color_buf */
   48.52 +  JDIMENSION rows_to_go;	/* counts rows remaining in image */
   48.53 +
   48.54 +  /* Height of an input row group for each component. */
   48.55 +  int rowgroup_height[MAX_COMPONENTS];
   48.56 +
   48.57 +  /* These arrays save pixel expansion factors so that int_expand need not
   48.58 +   * recompute them each time.  They are unused for other upsampling methods.
   48.59 +   */
   48.60 +  UINT8 h_expand[MAX_COMPONENTS];
   48.61 +  UINT8 v_expand[MAX_COMPONENTS];
   48.62 +} my_upsampler;
   48.63 +
   48.64 +typedef my_upsampler * my_upsample_ptr;
   48.65 +
   48.66 +
   48.67 +/*
   48.68 + * Initialize for an upsampling pass.
   48.69 + */
   48.70 +
   48.71 +METHODDEF(void)
   48.72 +start_pass_upsample (j_decompress_ptr cinfo)
   48.73 +{
   48.74 +  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
   48.75 +
   48.76 +  /* Mark the conversion buffer empty */
   48.77 +  upsample->next_row_out = cinfo->max_v_samp_factor;
   48.78 +  /* Initialize total-height counter for detecting bottom of image */
   48.79 +  upsample->rows_to_go = cinfo->output_height;
   48.80 +}
   48.81 +
   48.82 +
   48.83 +/*
   48.84 + * Control routine to do upsampling (and color conversion).
   48.85 + *
   48.86 + * In this version we upsample each component independently.
   48.87 + * We upsample one row group into the conversion buffer, then apply
   48.88 + * color conversion a row at a time.
   48.89 + */
   48.90 +
   48.91 +METHODDEF(void)
   48.92 +sep_upsample (j_decompress_ptr cinfo,
   48.93 +	      JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
   48.94 +	      JDIMENSION in_row_groups_avail,
   48.95 +	      JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
   48.96 +	      JDIMENSION out_rows_avail)
   48.97 +{
   48.98 +  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
   48.99 +  int ci;
  48.100 +  jpeg_component_info * compptr;
  48.101 +  JDIMENSION num_rows;
  48.102 +
  48.103 +  /* Fill the conversion buffer, if it's empty */
  48.104 +  if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  48.105 +    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  48.106 +	 ci++, compptr++) {
  48.107 +      /* Invoke per-component upsample method.  Notice we pass a POINTER
  48.108 +       * to color_buf[ci], so that fullsize_upsample can change it.
  48.109 +       */
  48.110 +      (*upsample->methods[ci]) (cinfo, compptr,
  48.111 +	input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  48.112 +	upsample->color_buf + ci);
  48.113 +    }
  48.114 +    upsample->next_row_out = 0;
  48.115 +  }
  48.116 +
  48.117 +  /* Color-convert and emit rows */
  48.118 +
  48.119 +  /* How many we have in the buffer: */
  48.120 +  num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  48.121 +  /* Not more than the distance to the end of the image.  Need this test
  48.122 +   * in case the image height is not a multiple of max_v_samp_factor:
  48.123 +   */
  48.124 +  if (num_rows > upsample->rows_to_go) 
  48.125 +    num_rows = upsample->rows_to_go;
  48.126 +  /* And not more than what the client can accept: */
  48.127 +  out_rows_avail -= *out_row_ctr;
  48.128 +  if (num_rows > out_rows_avail)
  48.129 +    num_rows = out_rows_avail;
  48.130 +
  48.131 +  (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  48.132 +				     (JDIMENSION) upsample->next_row_out,
  48.133 +				     output_buf + *out_row_ctr,
  48.134 +				     (int) num_rows);
  48.135 +
  48.136 +  /* Adjust counts */
  48.137 +  *out_row_ctr += num_rows;
  48.138 +  upsample->rows_to_go -= num_rows;
  48.139 +  upsample->next_row_out += num_rows;
  48.140 +  /* When the buffer is emptied, declare this input row group consumed */
  48.141 +  if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  48.142 +    (*in_row_group_ctr)++;
  48.143 +}
  48.144 +
  48.145 +
  48.146 +/*
  48.147 + * These are the routines invoked by sep_upsample to upsample pixel values
  48.148 + * of a single component.  One row group is processed per call.
  48.149 + */
  48.150 +
  48.151 +
  48.152 +/*
  48.153 + * For full-size components, we just make color_buf[ci] point at the
  48.154 + * input buffer, and thus avoid copying any data.  Note that this is
  48.155 + * safe only because sep_upsample doesn't declare the input row group
  48.156 + * "consumed" until we are done color converting and emitting it.
  48.157 + */
  48.158 +
  48.159 +METHODDEF(void)
  48.160 +fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  48.161 +		   JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  48.162 +{
  48.163 +  *output_data_ptr = input_data;
  48.164 +}
  48.165 +
  48.166 +
  48.167 +/*
  48.168 + * This is a no-op version used for "uninteresting" components.
  48.169 + * These components will not be referenced by color conversion.
  48.170 + */
  48.171 +
  48.172 +METHODDEF(void)
  48.173 +noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  48.174 +	       JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  48.175 +{
  48.176 +  *output_data_ptr = NULL;	/* safety check */
  48.177 +}
  48.178 +
  48.179 +
  48.180 +/*
  48.181 + * This version handles any integral sampling ratios.
  48.182 + * This is not used for typical JPEG files, so it need not be fast.
  48.183 + * Nor, for that matter, is it particularly accurate: the algorithm is
  48.184 + * simple replication of the input pixel onto the corresponding output
  48.185 + * pixels.  The hi-falutin sampling literature refers to this as a
  48.186 + * "box filter".  A box filter tends to introduce visible artifacts,
  48.187 + * so if you are actually going to use 3:1 or 4:1 sampling ratios
  48.188 + * you would be well advised to improve this code.
  48.189 + */
  48.190 +
  48.191 +METHODDEF(void)
  48.192 +int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  48.193 +	      JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  48.194 +{
  48.195 +  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  48.196 +  JSAMPARRAY output_data = *output_data_ptr;
  48.197 +  register JSAMPROW inptr, outptr;
  48.198 +  register JSAMPLE invalue;
  48.199 +  register int h;
  48.200 +  JSAMPROW outend;
  48.201 +  int h_expand, v_expand;
  48.202 +  int inrow, outrow;
  48.203 +
  48.204 +  h_expand = upsample->h_expand[compptr->component_index];
  48.205 +  v_expand = upsample->v_expand[compptr->component_index];
  48.206 +
  48.207 +  inrow = outrow = 0;
  48.208 +  while (outrow < cinfo->max_v_samp_factor) {
  48.209 +    /* Generate one output row with proper horizontal expansion */
  48.210 +    inptr = input_data[inrow];
  48.211 +    outptr = output_data[outrow];
  48.212 +    outend = outptr + cinfo->output_width;
  48.213 +    while (outptr < outend) {
  48.214 +      invalue = *inptr++;	/* don't need GETJSAMPLE() here */
  48.215 +      for (h = h_expand; h > 0; h--) {
  48.216 +	*outptr++ = invalue;
  48.217 +      }
  48.218 +    }
  48.219 +    /* Generate any additional output rows by duplicating the first one */
  48.220 +    if (v_expand > 1) {
  48.221 +      jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  48.222 +			v_expand-1, cinfo->output_width);
  48.223 +    }
  48.224 +    inrow++;
  48.225 +    outrow += v_expand;
  48.226 +  }
  48.227 +}
  48.228 +
  48.229 +
  48.230 +/*
  48.231 + * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  48.232 + * It's still a box filter.
  48.233 + */
  48.234 +
  48.235 +METHODDEF(void)
  48.236 +h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  48.237 +	       JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  48.238 +{
  48.239 +  JSAMPARRAY output_data = *output_data_ptr;
  48.240 +  register JSAMPROW inptr, outptr;
  48.241 +  register JSAMPLE invalue;
  48.242 +  JSAMPROW outend;
  48.243 +  int inrow;
  48.244 +
  48.245 +  for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  48.246 +    inptr = input_data[inrow];
  48.247 +    outptr = output_data[inrow];
  48.248 +    outend = outptr + cinfo->output_width;
  48.249 +    while (outptr < outend) {
  48.250 +      invalue = *inptr++;	/* don't need GETJSAMPLE() here */
  48.251 +      *outptr++ = invalue;
  48.252 +      *outptr++ = invalue;
  48.253 +    }
  48.254 +  }
  48.255 +}
  48.256 +
  48.257 +
  48.258 +/*
  48.259 + * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  48.260 + * It's still a box filter.
  48.261 + */
  48.262 +
  48.263 +METHODDEF(void)
  48.264 +h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  48.265 +	       JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  48.266 +{
  48.267 +  JSAMPARRAY output_data = *output_data_ptr;
  48.268 +  register JSAMPROW inptr, outptr;
  48.269 +  register JSAMPLE invalue;
  48.270 +  JSAMPROW outend;
  48.271 +  int inrow, outrow;
  48.272 +
  48.273 +  inrow = outrow = 0;
  48.274 +  while (outrow < cinfo->max_v_samp_factor) {
  48.275 +    inptr = input_data[inrow];
  48.276 +    outptr = output_data[outrow];
  48.277 +    outend = outptr + cinfo->output_width;
  48.278 +    while (outptr < outend) {
  48.279 +      invalue = *inptr++;	/* don't need GETJSAMPLE() here */
  48.280 +      *outptr++ = invalue;
  48.281 +      *outptr++ = invalue;
  48.282 +    }
  48.283 +    jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  48.284 +		      1, cinfo->output_width);
  48.285 +    inrow++;
  48.286 +    outrow += 2;
  48.287 +  }
  48.288 +}
  48.289 +
  48.290 +
  48.291 +/*
  48.292 + * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  48.293 + *
  48.294 + * The upsampling algorithm is linear interpolation between pixel centers,
  48.295 + * also known as a "triangle filter".  This is a good compromise between
  48.296 + * speed and visual quality.  The centers of the output pixels are 1/4 and 3/4
  48.297 + * of the way between input pixel centers.
  48.298 + *
  48.299 + * A note about the "bias" calculations: when rounding fractional values to
  48.300 + * integer, we do not want to always round 0.5 up to the next integer.
  48.301 + * If we did that, we'd introduce a noticeable bias towards larger values.
  48.302 + * Instead, this code is arranged so that 0.5 will be rounded up or down at
  48.303 + * alternate pixel locations (a simple ordered dither pattern).
  48.304 + */
  48.305 +
  48.306 +METHODDEF(void)
  48.307 +h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  48.308 +		     JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  48.309 +{
  48.310 +  JSAMPARRAY output_data = *output_data_ptr;
  48.311 +  register JSAMPROW inptr, outptr;
  48.312 +  register int invalue;
  48.313 +  register JDIMENSION colctr;
  48.314 +  int inrow;
  48.315 +
  48.316 +  for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  48.317 +    inptr = input_data[inrow];
  48.318 +    outptr = output_data[inrow];
  48.319 +    /* Special case for first column */
  48.320 +    invalue = GETJSAMPLE(*inptr++);
  48.321 +    *outptr++ = (JSAMPLE) invalue;
  48.322 +    *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  48.323 +
  48.324 +    for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  48.325 +      /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  48.326 +      invalue = GETJSAMPLE(*inptr++) * 3;
  48.327 +      *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  48.328 +      *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  48.329 +    }
  48.330 +
  48.331 +    /* Special case for last column */
  48.332 +    invalue = GETJSAMPLE(*inptr);
  48.333 +    *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  48.334 +    *outptr++ = (JSAMPLE) invalue;
  48.335 +  }
  48.336 +}
  48.337 +
  48.338 +
  48.339 +/*
  48.340 + * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  48.341 + * Again a triangle filter; see comments for h2v1 case, above.
  48.342 + *
  48.343 + * It is OK for us to reference the adjacent input rows because we demanded
  48.344 + * context from the main buffer controller (see initialization code).
  48.345 + */
  48.346 +
  48.347 +METHODDEF(void)
  48.348 +h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  48.349 +		     JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  48.350 +{
  48.351 +  JSAMPARRAY output_data = *output_data_ptr;
  48.352 +  register JSAMPROW inptr0, inptr1, outptr;
  48.353 +#if BITS_IN_JSAMPLE == 8
  48.354 +  register int thiscolsum, lastcolsum, nextcolsum;
  48.355 +#else
  48.356 +  register INT32 thiscolsum, lastcolsum, nextcolsum;
  48.357 +#endif
  48.358 +  register JDIMENSION colctr;
  48.359 +  int inrow, outrow, v;
  48.360 +
  48.361 +  inrow = outrow = 0;
  48.362 +  while (outrow < cinfo->max_v_samp_factor) {
  48.363 +    for (v = 0; v < 2; v++) {
  48.364 +      /* inptr0 points to nearest input row, inptr1 points to next nearest */
  48.365 +      inptr0 = input_data[inrow];
  48.366 +      if (v == 0)		/* next nearest is row above */
  48.367 +	inptr1 = input_data[inrow-1];
  48.368 +      else			/* next nearest is row below */
  48.369 +	inptr1 = input_data[inrow+1];
  48.370 +      outptr = output_data[outrow++];
  48.371 +
  48.372 +      /* Special case for first column */
  48.373 +      thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  48.374 +      nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  48.375 +      *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  48.376 +      *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  48.377 +      lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  48.378 +
  48.379 +      for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  48.380 +	/* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  48.381 +	/* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  48.382 +	nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  48.383 +	*outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  48.384 +	*outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  48.385 +	lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  48.386 +      }
  48.387 +
  48.388 +      /* Special case for last column */
  48.389 +      *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  48.390 +      *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  48.391 +    }
  48.392 +    inrow++;
  48.393 +  }
  48.394 +}
  48.395 +
  48.396 +
  48.397 +/*
  48.398 + * Module initialization routine for upsampling.
  48.399 + */
  48.400 +
  48.401 +GLOBAL(void)
  48.402 +jinit_upsampler (j_decompress_ptr cinfo)
  48.403 +{
  48.404 +  my_upsample_ptr upsample;
  48.405 +  int ci;
  48.406 +  jpeg_component_info * compptr;
  48.407 +  boolean need_buffer, do_fancy;
  48.408 +  int h_in_group, v_in_group, h_out_group, v_out_group;
  48.409 +
  48.410 +  upsample = (my_upsample_ptr)
  48.411 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  48.412 +				SIZEOF(my_upsampler));
  48.413 +  cinfo->upsample = (struct jpeg_upsampler *) upsample;
  48.414 +  upsample->pub.start_pass = start_pass_upsample;
  48.415 +  upsample->pub.upsample = sep_upsample;
  48.416 +  upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  48.417 +
  48.418 +  if (cinfo->CCIR601_sampling)	/* this isn't supported */
  48.419 +    ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  48.420 +
  48.421 +  /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  48.422 +   * so don't ask for it.
  48.423 +   */
  48.424 +  do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  48.425 +
  48.426 +  /* Verify we can handle the sampling factors, select per-component methods,
  48.427 +   * and create storage as needed.
  48.428 +   */
  48.429 +  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  48.430 +       ci++, compptr++) {
  48.431 +    /* Compute size of an "input group" after IDCT scaling.  This many samples
  48.432 +     * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  48.433 +     */
  48.434 +    h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  48.435 +		 cinfo->min_DCT_scaled_size;
  48.436 +    v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  48.437 +		 cinfo->min_DCT_scaled_size;
  48.438 +    h_out_group = cinfo->max_h_samp_factor;
  48.439 +    v_out_group = cinfo->max_v_samp_factor;
  48.440 +    upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  48.441 +    need_buffer = TRUE;
  48.442 +    if (! compptr->component_needed) {
  48.443 +      /* Don't bother to upsample an uninteresting component. */
  48.444 +      upsample->methods[ci] = noop_upsample;
  48.445 +      need_buffer = FALSE;
  48.446 +    } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  48.447 +      /* Fullsize components can be processed without any work. */
  48.448 +      upsample->methods[ci] = fullsize_upsample;
  48.449 +      need_buffer = FALSE;
  48.450 +    } else if (h_in_group * 2 == h_out_group &&
  48.451 +	       v_in_group == v_out_group) {
  48.452 +      /* Special cases for 2h1v upsampling */
  48.453 +      if (do_fancy && compptr->downsampled_width > 2)
  48.454 +	upsample->methods[ci] = h2v1_fancy_upsample;
  48.455 +      else
  48.456 +	upsample->methods[ci] = h2v1_upsample;
  48.457 +    } else if (h_in_group * 2 == h_out_group &&
  48.458 +	       v_in_group * 2 == v_out_group) {
  48.459 +      /* Special cases for 2h2v upsampling */
  48.460 +      if (do_fancy && compptr->downsampled_width > 2) {
  48.461 +	upsample->methods[ci] = h2v2_fancy_upsample;
  48.462 +	upsample->pub.need_context_rows = TRUE;
  48.463 +      } else
  48.464 +	upsample->methods[ci] = h2v2_upsample;
  48.465 +    } else if ((h_out_group % h_in_group) == 0 &&
  48.466 +	       (v_out_group % v_in_group) == 0) {
  48.467 +      /* Generic integral-factors upsampling method */
  48.468 +      upsample->methods[ci] = int_upsample;
  48.469 +      upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  48.470 +      upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  48.471 +    } else
  48.472 +      ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  48.473 +    if (need_buffer) {
  48.474 +      upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  48.475 +	((j_common_ptr) cinfo, JPOOL_IMAGE,
  48.476 +	 (JDIMENSION) jround_up((long) cinfo->output_width,
  48.477 +				(long) cinfo->max_h_samp_factor),
  48.478 +	 (JDIMENSION) cinfo->max_v_samp_factor);
  48.479 +    }
  48.480 +  }
  48.481 +}
    49.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    49.2 +++ b/libs/libjpeg/jdtrans.c	Thu Sep 08 06:28:38 2011 +0300
    49.3 @@ -0,0 +1,143 @@
    49.4 +/*
    49.5 + * jdtrans.c
    49.6 + *
    49.7 + * Copyright (C) 1995-1997, Thomas G. Lane.
    49.8 + * This file is part of the Independent JPEG Group's software.
    49.9 + * For conditions of distribution and use, see the accompanying README file.
   49.10 + *
   49.11 + * This file contains library routines for transcoding decompression,
   49.12 + * that is, reading raw DCT coefficient arrays from an input JPEG file.
   49.13 + * The routines in jdapimin.c will also be needed by a transcoder.
   49.14 + */
   49.15 +
   49.16 +#define JPEG_INTERNALS
   49.17 +#include "jinclude.h"
   49.18 +#include "jpeglib.h"
   49.19 +
   49.20 +
   49.21 +/* Forward declarations */
   49.22 +LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
   49.23 +
   49.24 +
   49.25 +/*
   49.26 + * Read the coefficient arrays from a JPEG file.
   49.27 + * jpeg_read_header must be completed before calling this.
   49.28 + *
   49.29 + * The entire image is read into a set of virtual coefficient-block arrays,
   49.30 + * one per component.  The return value is a pointer to the array of
   49.31 + * virtual-array descriptors.  These can be manipulated directly via the
   49.32 + * JPEG memory manager, or handed off to jpeg_write_coefficients().
   49.33 + * To release the memory occupied by the virtual arrays, call
   49.34 + * jpeg_finish_decompress() when done with the data.
   49.35 + *
   49.36 + * An alternative usage is to simply obtain access to the coefficient arrays
   49.37 + * during a buffered-image-mode decompression operation.  This is allowed
   49.38 + * after any jpeg_finish_output() call.  The arrays can be accessed until
   49.39 + * jpeg_finish_decompress() is called.  (Note that any call to the library
   49.40 + * may reposition the arrays, so don't rely on access_virt_barray() results
   49.41 + * to stay valid across library calls.)
   49.42 + *
   49.43 + * Returns NULL if suspended.  This case need be checked only if
   49.44 + * a suspending data source is used.
   49.45 + */
   49.46 +
   49.47 +GLOBAL(jvirt_barray_ptr *)
   49.48 +jpeg_read_coefficients (j_decompress_ptr cinfo)
   49.49 +{
   49.50 +  if (cinfo->global_state == DSTATE_READY) {
   49.51 +    /* First call: initialize active modules */
   49.52 +    transdecode_master_selection(cinfo);
   49.53 +    cinfo->global_state = DSTATE_RDCOEFS;
   49.54 +  }
   49.55 +  if (cinfo->global_state == DSTATE_RDCOEFS) {
   49.56 +    /* Absorb whole file into the coef buffer */
   49.57 +    for (;;) {
   49.58 +      int retcode;
   49.59 +      /* Call progress monitor hook if present */
   49.60 +      if (cinfo->progress != NULL)
   49.61 +	(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
   49.62 +      /* Absorb some more input */
   49.63 +      retcode = (*cinfo->inputctl->consume_input) (cinfo);
   49.64 +      if (retcode == JPEG_SUSPENDED)
   49.65 +	return NULL;
   49.66 +      if (retcode == JPEG_REACHED_EOI)
   49.67 +	break;
   49.68 +      /* Advance progress counter if appropriate */
   49.69 +      if (cinfo->progress != NULL &&
   49.70 +	  (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
   49.71 +	if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
   49.72 +	  /* startup underestimated number of scans; ratchet up one scan */
   49.73 +	  cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
   49.74 +	}
   49.75 +      }
   49.76 +    }
   49.77 +    /* Set state so that jpeg_finish_decompress does the right thing */
   49.78 +    cinfo->global_state = DSTATE_STOPPING;
   49.79 +  }
   49.80 +  /* At this point we should be in state DSTATE_STOPPING if being used
   49.81 +   * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
   49.82 +   * to the coefficients during a full buffered-image-mode decompression.
   49.83 +   */
   49.84 +  if ((cinfo->global_state == DSTATE_STOPPING ||
   49.85 +       cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
   49.86 +    return cinfo->coef->coef_arrays;
   49.87 +  }
   49.88 +  /* Oops, improper usage */
   49.89 +  ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
   49.90 +  return NULL;			/* keep compiler happy */
   49.91 +}
   49.92 +
   49.93 +
   49.94 +/*
   49.95 + * Master selection of decompression modules for transcoding.
   49.96 + * This substitutes for jdmaster.c's initialization of the full decompressor.
   49.97 + */
   49.98 +
   49.99 +LOCAL(void)
  49.100 +transdecode_master_selection (j_decompress_ptr cinfo)
  49.101 +{
  49.102 +  /* This is effectively a buffered-image operation. */
  49.103 +  cinfo->buffered_image = TRUE;
  49.104 +
  49.105 +  /* Entropy decoding: either Huffman or arithmetic coding. */
  49.106 +  if (cinfo->arith_code) {
  49.107 +    ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  49.108 +  } else {
  49.109 +    if (cinfo->progressive_mode) {
  49.110 +#ifdef D_PROGRESSIVE_SUPPORTED
  49.111 +      jinit_phuff_decoder(cinfo);
  49.112 +#else
  49.113 +      ERREXIT(cinfo, JERR_NOT_COMPILED);
  49.114 +#endif
  49.115 +    } else
  49.116 +      jinit_huff_decoder(cinfo);
  49.117 +  }
  49.118 +
  49.119 +  /* Always get a full-image coefficient buffer. */
  49.120 +  jinit_d_coef_controller(cinfo, TRUE);
  49.121 +
  49.122 +  /* We can now tell the memory manager to allocate virtual arrays. */
  49.123 +  (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  49.124 +
  49.125 +  /* Initialize input side of decompressor to consume first scan. */
  49.126 +  (*cinfo->inputctl->start_input_pass) (cinfo);
  49.127 +
  49.128 +  /* Initialize progress monitoring. */
  49.129 +  if (cinfo->progress != NULL) {
  49.130 +    int nscans;
  49.131 +    /* Estimate number of scans to set pass_limit. */
  49.132 +    if (cinfo->progressive_mode) {
  49.133 +      /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  49.134 +      nscans = 2 + 3 * cinfo->num_components;
  49.135 +    } else if (cinfo->inputctl->has_multiple_scans) {
  49.136 +      /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  49.137 +      nscans = cinfo->num_components;
  49.138 +    } else {
  49.139 +      nscans = 1;
  49.140 +    }
  49.141 +    cinfo->progress->pass_counter = 0L;
  49.142 +    cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  49.143 +    cinfo->progress->completed_passes = 0;
  49.144 +    cinfo->progress->total_passes = 1;
  49.145 +  }
  49.146 +}
    50.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    50.2 +++ b/libs/libjpeg/jerror.c	Thu Sep 08 06:28:38 2011 +0300
    50.3 @@ -0,0 +1,252 @@
    50.4 +/*
    50.5 + * jerror.c
    50.6 + *
    50.7 + * Copyright (C) 1991-1998, Thomas G. Lane.
    50.8 + * This file is part of the Independent JPEG Group's software.
    50.9 + * For conditions of distribution and use, see the accompanying README file.
   50.10 + *
   50.11 + * This file contains simple error-reporting and trace-message routines.
   50.12 + * These are suitable for Unix-like systems and others where writing to
   50.13 + * stderr is the right thing to do.  Many applications will want to replace
   50.14 + * some or all of these routines.
   50.15 + *
   50.16 + * If you define USE_WINDOWS_MESSAGEBOX in jconfig.h or in the makefile,
   50.17 + * you get a Windows-specific hack to display error messages in a dialog box.
   50.18 + * It ain't much, but it beats dropping error messages into the bit bucket,
   50.19 + * which is what happens to output to stderr under most Windows C compilers.
   50.20 + *
   50.21 + * These routines are used by both the compression and decompression code.
   50.22 + */
   50.23 +
   50.24 +/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
   50.25 +#include "jinclude.h"
   50.26 +#include "jpeglib.h"
   50.27 +#include "jversion.h"
   50.28 +#include "jerror.h"
   50.29 +
   50.30 +#ifdef USE_WINDOWS_MESSAGEBOX
   50.31 +#include <windows.h>
   50.32 +#endif
   50.33 +
   50.34 +#ifndef EXIT_FAILURE		/* define exit() codes if not provided */
   50.35 +#define EXIT_FAILURE  1
   50.36 +#endif
   50.37 +
   50.38 +
   50.39 +/*
   50.40 + * Create the message string table.
   50.41 + * We do this from the master message list in jerror.h by re-reading
   50.42 + * jerror.h with a suitable definition for macro JMESSAGE.
   50.43 + * The message table is made an external symbol just in case any applications
   50.44 + * want to refer to it directly.
   50.45 + */
   50.46 +
   50.47 +#ifdef NEED_SHORT_EXTERNAL_NAMES
   50.48 +#define jpeg_std_message_table	jMsgTable
   50.49 +#endif
   50.50 +
   50.51 +#define JMESSAGE(code,string)	string ,
   50.52 +
   50.53 +const char * const jpeg_std_message_table[] = {
   50.54 +#include "jerror.h"
   50.55 +  NULL
   50.56 +};
   50.57 +
   50.58 +
   50.59 +/*
   50.60 + * Error exit handler: must not return to caller.
   50.61 + *
   50.62 + * Applications may override this if they want to get control back after
   50.63 + * an error.  Typically one would longjmp somewhere instead of exiting.
   50.64 + * The setjmp buffer can be made a private field within an expanded error
   50.65 + * handler object.  Note that the info needed to generate an error message
   50.66 + * is stored in the error object, so you can generate the message now or
   50.67 + * later, at your convenience.
   50.68 + * You should make sure that the JPEG object is cleaned up (with jpeg_abort
   50.69 + * or jpeg_destroy) at some point.
   50.70 + */
   50.71 +
   50.72 +METHODDEF(void)
   50.73 +error_exit (j_common_ptr cinfo)
   50.74 +{
   50.75 +  /* Always display the message */
   50.76 +  (*cinfo->err->output_message) (cinfo);
   50.77 +
   50.78 +  /* Let the memory manager delete any temp files before we die */
   50.79 +  jpeg_destroy(cinfo);
   50.80 +
   50.81 +  exit(EXIT_FAILURE);
   50.82 +}
   50.83 +
   50.84 +
   50.85 +/*
   50.86 + * Actual output of an error or trace message.
   50.87 + * Applications may override this method to send JPEG messages somewhere
   50.88 + * other than stderr.
   50.89 + *
   50.90 + * On Windows, printing to stderr is generally completely useless,
   50.91 + * so we provide optional code to produce an error-dialog popup.
   50.92 + * Most Windows applications will still prefer to override this routine,
   50.93 + * but if they don't, it'll do something at least marginally useful.
   50.94 + *
   50.95 + * NOTE: to use the library in an environment that doesn't support the
   50.96 + * C stdio library, you may have to delete the call to fprintf() entirely,
   50.97 + * not just not use this routine.
   50.98 + */
   50.99 +
  50.100 +METHODDEF(void)
  50.101 +output_message (j_common_ptr cinfo)
  50.102 +{
  50.103 +  char buffer[JMSG_LENGTH_MAX];
  50.104 +
  50.105 +  /* Create the message */
  50.106 +  (*cinfo->err->format_message) (cinfo, buffer);
  50.107 +
  50.108 +#ifdef USE_WINDOWS_MESSAGEBOX
  50.109 +  /* Display it in a message dialog box */
  50.110 +  MessageBox(GetActiveWindow(), buffer, "JPEG Library Error",
  50.111 +	     MB_OK | MB_ICONERROR);
  50.112 +#else
  50.113 +  /* Send it to stderr, adding a newline */
  50.114 +  fprintf(stderr, "%s\n", buffer);
  50.115 +#endif
  50.116 +}
  50.117 +
  50.118 +
  50.119 +/*
  50.120 + * Decide whether to emit a trace or warning message.
  50.121 + * msg_level is one of:
  50.122 + *   -1: recoverable corrupt-data warning, may want to abort.
  50.123 + *    0: important advisory messages (always display to user).
  50.124 + *    1: first level of tracing detail.
  50.125 + *    2,3,...: successively more detailed tracing messages.
  50.126 + * An application might override this method if it wanted to abort on warnings
  50.127 + * or change the policy about which messages to display.
  50.128 + */
  50.129 +
  50.130 +METHODDEF(void)
  50.131 +emit_message (j_common_ptr cinfo, int msg_level)
  50.132 +{
  50.133 +  struct jpeg_error_mgr * err = cinfo->err;
  50.134 +
  50.135 +  if (msg_level < 0) {
  50.136 +    /* It's a warning message.  Since corrupt files may generate many warnings,
  50.137 +     * the policy implemented here is to show only the first warning,
  50.138 +     * unless trace_level >= 3.
  50.139 +     */
  50.140 +    if (err->num_warnings == 0 || err->trace_level >= 3)
  50.141 +      (*err->output_message) (cinfo);
  50.142 +    /* Always count warnings in num_warnings. */
  50.143 +    err->num_warnings++;
  50.144 +  } else {
  50.145 +    /* It's a trace message.  Show it if trace_level >= msg_level. */
  50.146 +    if (err->trace_level >= msg_level)
  50.147 +      (*err->output_message) (cinfo);
  50.148 +  }
  50.149 +}
  50.150 +
  50.151 +
  50.152 +/*
  50.153 + * Format a message string for the most recent JPEG error or message.
  50.154 + * The message is stored into buffer, which should be at least JMSG_LENGTH_MAX
  50.155 + * characters.  Note that no '\n' character is added to the string.
  50.156 + * Few applications should need to override this method.
  50.157 + */
  50.158 +
  50.159 +METHODDEF(void)
  50.160 +format_message (j_common_ptr cinfo, char * buffer)
  50.161 +{
  50.162 +  struct jpeg_error_mgr * err = cinfo->err;
  50.163 +  int msg_code = err->msg_code;
  50.164 +  const char * msgtext = NULL;
  50.165 +  const char * msgptr;
  50.166 +  char ch;
  50.167 +  boolean isstring;
  50.168 +
  50.169 +  /* Look up message string in proper table */
  50.170 +  if (msg_code > 0 && msg_code <= err->last_jpeg_message) {
  50.171 +    msgtext = err->jpeg_message_table[msg_code];
  50.172 +  } else if (err->addon_message_table != NULL &&
  50.173 +	     msg_code >= err->first_addon_message &&
  50.174 +	     msg_code <= err->last_addon_message) {
  50.175 +    msgtext = err->addon_message_table[msg_code - err->first_addon_message];
  50.176 +  }
  50.177 +
  50.178 +  /* Defend against bogus message number */
  50.179 +  if (msgtext == NULL) {
  50.180 +    err->msg_parm.i[0] = msg_code;
  50.181 +    msgtext = err->jpeg_message_table[0];
  50.182 +  }
  50.183 +
  50.184 +  /* Check for string parameter, as indicated by %s in the message text */
  50.185 +  isstring = FALSE;
  50.186 +  msgptr = msgtext;
  50.187 +  while ((ch = *msgptr++) != '\0') {
  50.188 +    if (ch == '%') {
  50.189 +      if (*msgptr == 's') isstring = TRUE;
  50.190 +      break;
  50.191 +    }
  50.192 +  }
  50.193 +
  50.194 +  /* Format the message into the passed buffer */
  50.195 +  if (isstring)
  50.196 +    sprintf(buffer, msgtext, err->msg_parm.s);
  50.197 +  else
  50.198 +    sprintf(buffer, msgtext,
  50.199 +	    err->msg_parm.i[0], err->msg_parm.i[1],
  50.200 +	    err->msg_parm.i[2], err->msg_parm.i[3],
  50.201 +	    err->msg_parm.i[4], err->msg_parm.i[5],
  50.202 +	    err->msg_parm.i[6], err->msg_parm.i[7]);
  50.203 +}
  50.204 +
  50.205 +
  50.206 +/*
  50.207 + * Reset error state variables at start of a new image.
  50.208 + * This is called during compression startup to reset trace/error
  50.209 + * processing to default state, without losing any application-specific
  50.210 + * method pointers.  An application might possibly want to override
  50.211 + * this method if it has additional error processing state.
  50.212 + */
  50.213 +
  50.214 +METHODDEF(void)
  50.215 +reset_error_mgr (j_common_ptr cinfo)
  50.216 +{
  50.217 +  cinfo->err->num_warnings = 0;
  50.218 +  /* trace_level is not reset since it is an application-supplied parameter */
  50.219 +  cinfo->err->msg_code = 0;	/* may be useful as a flag for "no error" */
  50.220 +}
  50.221 +
  50.222 +
  50.223 +/*
  50.224 + * Fill in the standard error-handling methods in a jpeg_error_mgr object.
  50.225 + * Typical call is:
  50.226 + *	struct jpeg_compress_struct cinfo;
  50.227 + *	struct jpeg_error_mgr err;
  50.228 + *
  50.229 + *	cinfo.err = jpeg_std_error(&err);
  50.230 + * after which the application may override some of the methods.
  50.231 + */
  50.232 +
  50.233 +GLOBAL(struct jpeg_error_mgr *)
  50.234 +jpeg_std_error (struct jpeg_error_mgr * err)
  50.235 +{
  50.236 +  err->error_exit = error_exit;
  50.237 +  err->emit_message = emit_message;
  50.238 +  err->output_message = output_message;
  50.239 +  err->format_message = format_message;
  50.240 +  err->reset_error_mgr = reset_error_mgr;
  50.241 +
  50.242 +  err->trace_level = 0;		/* default = no tracing */
  50.243 +  err->num_warnings = 0;	/* no warnings emitted yet */
  50.244 +  err->msg_code = 0;		/* may be useful as a flag for "no error" */
  50.245 +
  50.246 +  /* Initialize message table pointers */
  50.247 +  err->jpeg_message_table = jpeg_std_message_table;
  50.248 +  err->last_jpeg_message = (int) JMSG_LASTMSGCODE - 1;
  50.249 +
  50.250 +  err->addon_message_table = NULL;
  50.251 +  err->first_addon_message = 0;	/* for safety */
  50.252 +  err->last_addon_message = 0;
  50.253 +
  50.254 +  return err;
  50.255 +}
    51.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    51.2 +++ b/libs/libjpeg/jerror.h	Thu Sep 08 06:28:38 2011 +0300
    51.3 @@ -0,0 +1,291 @@
    51.4 +/*
    51.5 + * jerror.h
    51.6 + *
    51.7 + * Copyright (C) 1994-1997, Thomas G. Lane.
    51.8 + * This file is part of the Independent JPEG Group's software.
    51.9 + * For conditions of distribution and use, see the accompanying README file.
   51.10 + *
   51.11 + * This file defines the error and message codes for the JPEG library.
   51.12 + * Edit this file to add new codes, or to translate the message strings to
   51.13 + * some other language.
   51.14 + * A set of error-reporting macros are defined too.  Some applications using
   51.15 + * the JPEG library may wish to include this file to get the error codes
   51.16 + * and/or the macros.
   51.17 + */
   51.18 +
   51.19 +/*
   51.20 + * To define the enum list of message codes, include this file without
   51.21 + * defining macro JMESSAGE.  To create a message string table, include it
   51.22 + * again with a suitable JMESSAGE definition (see jerror.c for an example).
   51.23 + */
   51.24 +#ifndef JMESSAGE
   51.25 +#ifndef JERROR_H
   51.26 +/* First time through, define the enum list */
   51.27 +#define JMAKE_ENUM_LIST
   51.28 +#else
   51.29 +/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
   51.30 +#define JMESSAGE(code,string)
   51.31 +#endif /* JERROR_H */
   51.32 +#endif /* JMESSAGE */
   51.33 +
   51.34 +#ifdef JMAKE_ENUM_LIST
   51.35 +
   51.36 +typedef enum {
   51.37 +
   51.38 +#define JMESSAGE(code,string)	code ,
   51.39 +
   51.40 +#endif /* JMAKE_ENUM_LIST */
   51.41 +
   51.42 +JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
   51.43 +
   51.44 +/* For maintenance convenience, list is alphabetical by message code name */
   51.45 +JMESSAGE(JERR_ARITH_NOTIMPL,
   51.46 +	 "Sorry, there are legal restrictions on arithmetic coding")
   51.47 +JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
   51.48 +JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
   51.49 +JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
   51.50 +JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
   51.51 +JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
   51.52 +JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
   51.53 +JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
   51.54 +JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
   51.55 +JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
   51.56 +JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
   51.57 +JMESSAGE(JERR_BAD_LIB_VERSION,
   51.58 +	 "Wrong JPEG library version: library is %d, caller expects %d")
   51.59 +JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
   51.60 +JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
   51.61 +JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
   51.62 +JMESSAGE(JERR_BAD_PROGRESSION,
   51.63 +	 "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
   51.64 +JMESSAGE(JERR_BAD_PROG_SCRIPT,
   51.65 +	 "Invalid progressive parameters at scan script entry %d")
   51.66 +JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
   51.67 +JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
   51.68 +JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
   51.69 +JMESSAGE(JERR_BAD_STRUCT_SIZE,
   51.70 +	 "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
   51.71 +JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
   51.72 +JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
   51.73 +JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
   51.74 +JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
   51.75 +JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
   51.76 +JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
   51.77 +JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
   51.78 +JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
   51.79 +JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
   51.80 +JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
   51.81 +JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
   51.82 +JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
   51.83 +JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
   51.84 +JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
   51.85 +JMESSAGE(JERR_FILE_READ, "Input file read error")
   51.86 +JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
   51.87 +JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
   51.88 +JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
   51.89 +JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
   51.90 +JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
   51.91 +JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
   51.92 +JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
   51.93 +JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
   51.94 +	 "Cannot transcode due to multiple use of quantization table %d")
   51.95 +JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
   51.96 +JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
   51.97 +JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
   51.98 +JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
   51.99 +JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  51.100 +JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  51.101 +JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  51.102 +JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  51.103 +JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  51.104 +JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  51.105 +JMESSAGE(JERR_QUANT_COMPONENTS,
  51.106 +	 "Cannot quantize more than %d color components")
  51.107 +JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  51.108 +JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  51.109 +JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  51.110 +JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  51.111 +JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  51.112 +JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  51.113 +JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  51.114 +JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  51.115 +JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  51.116 +JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  51.117 +JMESSAGE(JERR_TFILE_WRITE,
  51.118 +	 "Write failed on temporary file --- out of disk space?")
  51.119 +JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  51.120 +JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  51.121 +JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  51.122 +JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  51.123 +JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  51.124 +JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  51.125 +JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  51.126 +JMESSAGE(JMSG_VERSION, JVERSION)
  51.127 +JMESSAGE(JTRC_16BIT_TABLES,
  51.128 +	 "Caution: quantization tables are too coarse for baseline JPEG")
  51.129 +JMESSAGE(JTRC_ADOBE,
  51.130 +	 "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  51.131 +JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  51.132 +JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  51.133 +JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  51.134 +JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  51.135 +JMESSAGE(JTRC_DQT, "Define Quantization Table %d  precision %d")
  51.136 +JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  51.137 +JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  51.138 +JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  51.139 +JMESSAGE(JTRC_EOI, "End Of Image")
  51.140 +JMESSAGE(JTRC_HUFFBITS, "        %3d %3d %3d %3d %3d %3d %3d %3d")
  51.141 +JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d  %d")
  51.142 +JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  51.143 +	 "Warning: thumbnail image size does not match data length %u")
  51.144 +JMESSAGE(JTRC_JFIF_EXTENSION,
  51.145 +	 "JFIF extension marker: type 0x%02x, length %u")
  51.146 +JMESSAGE(JTRC_JFIF_THUMBNAIL, "    with %d x %d thumbnail image")
  51.147 +JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  51.148 +JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  51.149 +JMESSAGE(JTRC_QUANTVALS, "        %4u %4u %4u %4u %4u %4u %4u %4u")
  51.150 +JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  51.151 +JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  51.152 +JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  51.153 +JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  51.154 +JMESSAGE(JTRC_RST, "RST%d")
  51.155 +JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  51.156 +	 "Smoothing not supported with nonstandard sampling ratios")
  51.157 +JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  51.158 +JMESSAGE(JTRC_SOF_COMPONENT, "    Component %d: %dhx%dv q=%d")
  51.159 +JMESSAGE(JTRC_SOI, "Start of Image")
  51.160 +JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  51.161 +JMESSAGE(JTRC_SOS_COMPONENT, "    Component %d: dc=%d ac=%d")
  51.162 +JMESSAGE(JTRC_SOS_PARAMS, "  Ss=%d, Se=%d, Ah=%d, Al=%d")
  51.163 +JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  51.164 +JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  51.165 +JMESSAGE(JTRC_THUMB_JPEG,
  51.166 +	 "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  51.167 +JMESSAGE(JTRC_THUMB_PALETTE,
  51.168 +	 "JFIF extension marker: palette thumbnail image, length %u")
  51.169 +JMESSAGE(JTRC_THUMB_RGB,
  51.170 +	 "JFIF extension marker: RGB thumbnail image, length %u")
  51.171 +JMESSAGE(JTRC_UNKNOWN_IDS,
  51.172 +	 "Unrecognized component IDs %d %d %d, assuming YCbCr")
  51.173 +JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  51.174 +JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  51.175 +JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  51.176 +JMESSAGE(JWRN_BOGUS_PROGRESSION,
  51.177 +	 "Inconsistent progression sequence for component %d coefficient %d")
  51.178 +JMESSAGE(JWRN_EXTRANEOUS_DATA,
  51.179 +	 "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  51.180 +JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  51.181 +JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  51.182 +JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  51.183 +JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  51.184 +JMESSAGE(JWRN_MUST_RESYNC,
  51.185 +	 "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  51.186 +JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  51.187 +JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  51.188 +
  51.189 +#ifdef JMAKE_ENUM_LIST
  51.190 +
  51.191 +  JMSG_LASTMSGCODE
  51.192 +} J_MESSAGE_CODE;
  51.193 +
  51.194 +#undef JMAKE_ENUM_LIST
  51.195 +#endif /* JMAKE_ENUM_LIST */
  51.196 +
  51.197 +/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  51.198 +#undef JMESSAGE
  51.199 +
  51.200 +
  51.201 +#ifndef JERROR_H
  51.202 +#define JERROR_H
  51.203 +
  51.204 +/* Macros to simplify using the error and trace message stuff */
  51.205 +/* The first parameter is either type of cinfo pointer */
  51.206 +
  51.207 +/* Fatal errors (print message and exit) */
  51.208 +#define ERREXIT(cinfo,code)  \
  51.209 +  ((cinfo)->err->msg_code = (code), \
  51.210 +   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  51.211 +#define ERREXIT1(cinfo,code,p1)  \
  51.212 +  ((cinfo)->err->msg_code = (code), \
  51.213 +   (cinfo)->err->msg_parm.i[0] = (p1), \
  51.214 +   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  51.215 +#define ERREXIT2(cinfo,code,p1,p2)  \
  51.216 +  ((cinfo)->err->msg_code = (code), \
  51.217 +   (cinfo)->err->msg_parm.i[0] = (p1), \
  51.218 +   (cinfo)->err->msg_parm.i[1] = (p2), \
  51.219 +   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  51.220 +#define ERREXIT3(cinfo,code,p1,p2,p3)  \
  51.221 +  ((cinfo)->err->msg_code = (code), \
  51.222 +   (cinfo)->err->msg_parm.i[0] = (p1), \
  51.223 +   (cinfo)->err->msg_parm.i[1] = (p2), \
  51.224 +   (cinfo)->err->msg_parm.i[2] = (p3), \
  51.225 +   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  51.226 +#define ERREXIT4(cinfo,code,p1,p2,p3,p4)  \
  51.227 +  ((cinfo)->err->msg_code = (code), \
  51.228 +   (cinfo)->err->msg_parm.i[0] = (p1), \
  51.229 +   (cinfo)->err->msg_parm.i[1] = (p2), \
  51.230 +   (cinfo)->err->msg_parm.i[2] = (p3), \
  51.231 +   (cinfo)->err->msg_parm.i[3] = (p4), \
  51.232 +   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  51.233 +#define ERREXITS(cinfo,code,str)  \
  51.234 +  ((cinfo)->err->msg_code = (code), \
  51.235 +   strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  51.236 +   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  51.237 +
  51.238 +#define MAKESTMT(stuff)		do { stuff } while (0)
  51.239 +
  51.240 +/* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  51.241 +#define WARNMS(cinfo,code)  \
  51.242 +  ((cinfo)->err->msg_code = (code), \
  51.243 +   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  51.244 +#define WARNMS1(cinfo,code,p1)  \
  51.245 +  ((cinfo)->err->msg_code = (code), \
  51.246 +   (cinfo)->err->msg_parm.i[0] = (p1), \
  51.247 +   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  51.248 +#define WARNMS2(cinfo,code,p1,p2)  \
  51.249 +  ((cinfo)->err->msg_code = (code), \
  51.250 +   (cinfo)->err->msg_parm.i[0] = (p1), \
  51.251 +   (cinfo)->err->msg_parm.i[1] = (p2), \
  51.252 +   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  51.253 +
  51.254 +/* Informational/debugging messages */
  51.255 +#define TRACEMS(cinfo,lvl,code)  \
  51.256 +  ((cinfo)->err->msg_code = (code), \
  51.257 +   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  51.258 +#define TRACEMS1(cinfo,lvl,code,p1)  \
  51.259 +  ((cinfo)->err->msg_code = (code), \
  51.260 +   (cinfo)->err->msg_parm.i[0] = (p1), \
  51.261 +   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  51.262 +#define TRACEMS2(cinfo,lvl,code,p1,p2)  \
  51.263 +  ((cinfo)->err->msg_code = (code), \
  51.264 +   (cinfo)->err->msg_parm.i[0] = (p1), \
  51.265 +   (cinfo)->err->msg_parm.i[1] = (p2), \
  51.266 +   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  51.267 +#define TRACEMS3(cinfo,lvl,code,p1,p2,p3)  \
  51.268 +  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  51.269 +	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  51.270 +	   (cinfo)->err->msg_code = (code); \
  51.271 +	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  51.272 +#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4)  \
  51.273 +  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  51.274 +	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  51.275 +	   (cinfo)->err->msg_code = (code); \
  51.276 +	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  51.277 +#define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5)  \
  51.278 +  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  51.279 +	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  51.280 +	   _mp[4] = (p5); \
  51.281 +	   (cinfo)->err->msg_code = (code); \
  51.282 +	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  51.283 +#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8)  \
  51.284 +  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  51.285 +	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  51.286 +	   _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  51.287 +	   (cinfo)->err->msg_code = (code); \
  51.288 +	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  51.289 +#define TRACEMSS(cinfo,lvl,code,str)  \
  51.290 +  ((cinfo)->err->msg_code = (code), \
  51.291 +   strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  51.292 +   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  51.293 +
  51.294 +#endif /* JERROR_H */
    52.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    52.2 +++ b/libs/libjpeg/jfdctflt.c	Thu Sep 08 06:28:38 2011 +0300
    52.3 @@ -0,0 +1,168 @@
    52.4 +/*
    52.5 + * jfdctflt.c
    52.6 + *
    52.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    52.8 + * This file is part of the Independent JPEG Group's software.
    52.9 + * For conditions of distribution and use, see the accompanying README file.
   52.10 + *
   52.11 + * This file contains a floating-point implementation of the
   52.12 + * forward DCT (Discrete Cosine Transform).
   52.13 + *
   52.14 + * This implementation should be more accurate than either of the integer
   52.15 + * DCT implementations.  However, it may not give the same results on all
   52.16 + * machines because of differences in roundoff behavior.  Speed will depend
   52.17 + * on the hardware's floating point capacity.
   52.18 + *
   52.19 + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
   52.20 + * on each column.  Direct algorithms are also available, but they are
   52.21 + * much more complex and seem not to be any faster when reduced to code.
   52.22 + *
   52.23 + * This implementation is based on Arai, Agui, and Nakajima's algorithm for
   52.24 + * scaled DCT.  Their original paper (Trans. IEICE E-71(11):1095) is in
   52.25 + * Japanese, but the algorithm is described in the Pennebaker & Mitchell
   52.26 + * JPEG textbook (see REFERENCES section in file README).  The following code
   52.27 + * is based directly on figure 4-8 in P&M.
   52.28 + * While an 8-point DCT cannot be done in less than 11 multiplies, it is
   52.29 + * possible to arrange the computation so that many of the multiplies are
   52.30 + * simple scalings of the final outputs.  These multiplies can then be
   52.31 + * folded into the multiplications or divisions by the JPEG quantization
   52.32 + * table entries.  The AA&N method leaves only 5 multiplies and 29 adds
   52.33 + * to be done in the DCT itself.
   52.34 + * The primary disadvantage of this method is that with a fixed-point
   52.35 + * implementation, accuracy is lost due to imprecise representation of the
   52.36 + * scaled quantization values.  However, that problem does not arise if
   52.37 + * we use floating point arithmetic.
   52.38 + */
   52.39 +
   52.40 +#define JPEG_INTERNALS
   52.41 +#include "jinclude.h"
   52.42 +#include "jpeglib.h"
   52.43 +#include "jdct.h"		/* Private declarations for DCT subsystem */
   52.44 +
   52.45 +#ifdef DCT_FLOAT_SUPPORTED
   52.46 +
   52.47 +
   52.48 +/*
   52.49 + * This module is specialized to the case DCTSIZE = 8.
   52.50 + */
   52.51 +
   52.52 +#if DCTSIZE != 8
   52.53 +  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
   52.54 +#endif
   52.55 +
   52.56 +
   52.57 +/*
   52.58 + * Perform the forward DCT on one block of samples.
   52.59 + */
   52.60 +
   52.61 +GLOBAL(void)
   52.62 +jpeg_fdct_float (FAST_FLOAT * data)
   52.63 +{
   52.64 +  FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
   52.65 +  FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
   52.66 +  FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
   52.67 +  FAST_FLOAT *dataptr;
   52.68 +  int ctr;
   52.69 +
   52.70 +  /* Pass 1: process rows. */
   52.71 +
   52.72 +  dataptr = data;
   52.73 +  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
   52.74 +    tmp0 = dataptr[0] + dataptr[7];
   52.75 +    tmp7 = dataptr[0] - dataptr[7];
   52.76 +    tmp1 = dataptr[1] + dataptr[6];
   52.77 +    tmp6 = dataptr[1] - dataptr[6];
   52.78 +    tmp2 = dataptr[2] + dataptr[5];
   52.79 +    tmp5 = dataptr[2] - dataptr[5];
   52.80 +    tmp3 = dataptr[3] + dataptr[4];
   52.81 +    tmp4 = dataptr[3] - dataptr[4];
   52.82 +    
   52.83 +    /* Even part */
   52.84 +    
   52.85 +    tmp10 = tmp0 + tmp3;	/* phase 2 */
   52.86 +    tmp13 = tmp0 - tmp3;
   52.87 +    tmp11 = tmp1 + tmp2;
   52.88 +    tmp12 = tmp1 - tmp2;
   52.89 +    
   52.90 +    dataptr[0] = tmp10 + tmp11; /* phase 3 */
   52.91 +    dataptr[4] = tmp10 - tmp11;
   52.92 +    
   52.93 +    z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
   52.94 +    dataptr[2] = tmp13 + z1;	/* phase 5 */
   52.95 +    dataptr[6] = tmp13 - z1;
   52.96 +    
   52.97 +    /* Odd part */
   52.98 +
   52.99 +    tmp10 = tmp4 + tmp5;	/* phase 2 */
  52.100 +    tmp11 = tmp5 + tmp6;
  52.101 +    tmp12 = tmp6 + tmp7;
  52.102 +
  52.103 +    /* The rotator is modified from fig 4-8 to avoid extra negations. */
  52.104 +    z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  52.105 +    z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  52.106 +    z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  52.107 +    z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  52.108 +
  52.109 +    z11 = tmp7 + z3;		/* phase 5 */
  52.110 +    z13 = tmp7 - z3;
  52.111 +
  52.112 +    dataptr[5] = z13 + z2;	/* phase 6 */
  52.113 +    dataptr[3] = z13 - z2;
  52.114 +    dataptr[1] = z11 + z4;
  52.115 +    dataptr[7] = z11 - z4;
  52.116 +
  52.117 +    dataptr += DCTSIZE;		/* advance pointer to next row */
  52.118 +  }
  52.119 +
  52.120 +  /* Pass 2: process columns. */
  52.121 +
  52.122 +  dataptr = data;
  52.123 +  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  52.124 +    tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  52.125 +    tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  52.126 +    tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  52.127 +    tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  52.128 +    tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  52.129 +    tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  52.130 +    tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  52.131 +    tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  52.132 +    
  52.133 +    /* Even part */
  52.134 +    
  52.135 +    tmp10 = tmp0 + tmp3;	/* phase 2 */
  52.136 +    tmp13 = tmp0 - tmp3;
  52.137 +    tmp11 = tmp1 + tmp2;
  52.138 +    tmp12 = tmp1 - tmp2;
  52.139 +    
  52.140 +    dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  52.141 +    dataptr[DCTSIZE*4] = tmp10 - tmp11;
  52.142 +    
  52.143 +    z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  52.144 +    dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  52.145 +    dataptr[DCTSIZE*6] = tmp13 - z1;
  52.146 +    
  52.147 +    /* Odd part */
  52.148 +
  52.149 +    tmp10 = tmp4 + tmp5;	/* phase 2 */
  52.150 +    tmp11 = tmp5 + tmp6;
  52.151 +    tmp12 = tmp6 + tmp7;
  52.152 +
  52.153 +    /* The rotator is modified from fig 4-8 to avoid extra negations. */
  52.154 +    z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  52.155 +    z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  52.156 +    z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  52.157 +    z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  52.158 +
  52.159 +    z11 = tmp7 + z3;		/* phase 5 */
  52.160 +    z13 = tmp7 - z3;
  52.161 +
  52.162 +    dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  52.163 +    dataptr[DCTSIZE*3] = z13 - z2;
  52.164 +    dataptr[DCTSIZE*1] = z11 + z4;
  52.165 +    dataptr[DCTSIZE*7] = z11 - z4;
  52.166 +
  52.167 +    dataptr++;			/* advance pointer to next column */
  52.168 +  }
  52.169 +}
  52.170 +
  52.171 +#endif /* DCT_FLOAT_SUPPORTED */
    53.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    53.2 +++ b/libs/libjpeg/jfdctfst.c	Thu Sep 08 06:28:38 2011 +0300
    53.3 @@ -0,0 +1,224 @@
    53.4 +/*
    53.5 + * jfdctfst.c
    53.6 + *
    53.7 + * Copyright (C) 1994-1996, Thomas G. Lane.
    53.8 + * This file is part of the Independent JPEG Group's software.
    53.9 + * For conditions of distribution and use, see the accompanying README file.
   53.10 + *
   53.11 + * This file contains a fast, not so accurate integer implementation of the
   53.12 + * forward DCT (Discrete Cosine Transform).
   53.13 + *
   53.14 + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
   53.15 + * on each column.  Direct algorithms are also available, but they are
   53.16 + * much more complex and seem not to be any faster when reduced to code.
   53.17 + *
   53.18 + * This implementation is based on Arai, Agui, and Nakajima's algorithm for
   53.19 + * scaled DCT.  Their original paper (Trans. IEICE E-71(11):1095) is in
   53.20 + * Japanese, but the algorithm is described in the Pennebaker & Mitchell
   53.21 + * JPEG textbook (see REFERENCES section in file README).  The following code
   53.22 + * is based directly on figure 4-8 in P&M.
   53.23 + * While an 8-point DCT cannot be done in less than 11 multiplies, it is
   53.24 + * possible to arrange the computation so that many of the multiplies are
   53.25 + * simple scalings of the final outputs.  These multiplies can then be
   53.26 + * folded into the multiplications or divisions by the JPEG quantization
   53.27 + * table entries.  The AA&N method leaves only 5 multiplies and 29 adds
   53.28 + * to be done in the DCT itself.
   53.29 + * The primary disadvantage of this method is that with fixed-point math,
   53.30 + * accuracy is lost due to imprecise representation of the scaled
   53.31 + * quantization values.  The smaller the quantization table entry, the less
   53.32 + * precise the scaled value, so this implementation does worse with high-
   53.33 + * quality-setting files than with low-quality ones.
   53.34 + */
   53.35 +
   53.36 +#define JPEG_INTERNALS
   53.37 +#include "jinclude.h"
   53.38 +#include "jpeglib.h"
   53.39 +#include "jdct.h"		/* Private declarations for DCT subsystem */
   53.40 +
   53.41 +#ifdef DCT_IFAST_SUPPORTED
   53.42 +
   53.43 +
   53.44 +/*
   53.45 + * This module is specialized to the case DCTSIZE = 8.
   53.46 + */
   53.47 +
   53.48 +#if DCTSIZE != 8
   53.49 +  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
   53.50 +#endif
   53.51 +
   53.52 +
   53.53 +/* Scaling decisions are generally the same as in the LL&M algorithm;
   53.54 + * see jfdctint.c for more details.  However, we choose to descale
   53.55 + * (right shift) multiplication products as soon as they are formed,
   53.56 + * rather than carrying additional fractional bits into subsequent additions.
   53.57 + * This compromises accuracy slightly, but it lets us save a few shifts.
   53.58 + * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
   53.59 + * everywhere except in the multiplications proper; this saves a good deal
   53.60 + * of work on 16-bit-int machines.
   53.61 + *
   53.62 + * Again to save a few shifts, the intermediate results between pass 1 and
   53.63 + * pass 2 are not upscaled, but are represented only to integral precision.
   53.64 + *
   53.65 + * A final compromise is to represent the multiplicative constants to only
   53.66 + * 8 fractional bits, rather than 13.  This saves some shifting work on some
   53.67 + * machines, and may also reduce the cost of multiplication (since there
   53.68 + * are fewer one-bits in the constants).
   53.69 + */
   53.70 +
   53.71 +#define CONST_BITS  8
   53.72 +
   53.73 +
   53.74 +/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
   53.75 + * causing a lot of useless floating-point operations at run time.
   53.76 + * To get around this we use the following pre-calculated constants.
   53.77 + * If you change CONST_BITS you may want to add appropriate values.
   53.78 + * (With a reasonable C compiler, you can just rely on the FIX() macro...)
   53.79 + */
   53.80 +
   53.81 +#if CONST_BITS == 8
   53.82 +#define FIX_0_382683433  ((INT32)   98)		/* FIX(0.382683433) */
   53.83 +#define FIX_0_541196100  ((INT32)  139)		/* FIX(0.541196100) */
   53.84 +#define FIX_0_707106781  ((INT32)  181)		/* FIX(0.707106781) */
   53.85 +#define FIX_1_306562965  ((INT32)  334)		/* FIX(1.306562965) */
   53.86 +#else
   53.87 +#define FIX_0_382683433  FIX(0.382683433)
   53.88 +#define FIX_0_541196100  FIX(0.541196100)
   53.89 +#define FIX_0_707106781  FIX(0.707106781)
   53.90 +#define FIX_1_306562965  FIX(1.306562965)
   53.91 +#endif
   53.92 +
   53.93 +
   53.94 +/* We can gain a little more speed, with a further compromise in accuracy,
   53.95 + * by omitting the addition in a descaling shift.  This yields an incorrectly
   53.96 + * rounded result half the time...
   53.97 + */
   53.98 +
   53.99 +#ifndef USE_ACCURATE_ROUNDING
  53.100 +#undef DESCALE
  53.101 +#define DESCALE(x,n)  RIGHT_SHIFT(x, n)
  53.102 +#endif
  53.103 +
  53.104 +
  53.105 +/* Multiply a DCTELEM variable by an INT32 constant, and immediately
  53.106 + * descale to yield a DCTELEM result.
  53.107 + */
  53.108 +
  53.109 +#define MULTIPLY(var,const)  ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  53.110 +
  53.111 +
  53.112 +/*
  53.113 + * Perform the forward DCT on one block of samples.
  53.114 + */
  53.115 +
  53.116 +GLOBAL(void)
  53.117 +jpeg_fdct_ifast (DCTELEM * data)
  53.118 +{
  53.119 +  DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  53.120 +  DCTELEM tmp10, tmp11, tmp12, tmp13;
  53.121 +  DCTELEM z1, z2, z3, z4, z5, z11, z13;
  53.122 +  DCTELEM *dataptr;
  53.123 +  int ctr;
  53.124 +  SHIFT_TEMPS
  53.125 +
  53.126 +  /* Pass 1: process rows. */
  53.127 +
  53.128 +  dataptr = data;
  53.129 +  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  53.130 +    tmp0 = dataptr[0] + dataptr[7];
  53.131 +    tmp7 = dataptr[0] - dataptr[7];
  53.132 +    tmp1 = dataptr[1] + dataptr[6];
  53.133 +    tmp6 = dataptr[1] - dataptr[6];
  53.134 +    tmp2 = dataptr[2] + dataptr[5];
  53.135 +    tmp5 = dataptr[2] - dataptr[5];
  53.136 +    tmp3 = dataptr[3] + dataptr[4];
  53.137 +    tmp4 = dataptr[3] - dataptr[4];
  53.138 +    
  53.139 +    /* Even part */
  53.140 +    
  53.141 +    tmp10 = tmp0 + tmp3;	/* phase 2 */
  53.142 +    tmp13 = tmp0 - tmp3;
  53.143 +    tmp11 = tmp1 + tmp2;
  53.144 +    tmp12 = tmp1 - tmp2;
  53.145 +    
  53.146 +    dataptr[0] = tmp10 + tmp11; /* phase 3 */
  53.147 +    dataptr[4] = tmp10 - tmp11;
  53.148 +    
  53.149 +    z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  53.150 +    dataptr[2] = tmp13 + z1;	/* phase 5 */
  53.151 +    dataptr[6] = tmp13 - z1;
  53.152 +    
  53.153 +    /* Odd part */
  53.154 +
  53.155 +    tmp10 = tmp4 + tmp5;	/* phase 2 */
  53.156 +    tmp11 = tmp5 + tmp6;
  53.157 +    tmp12 = tmp6 + tmp7;
  53.158 +
  53.159 +    /* The rotator is modified from fig 4-8 to avoid extra negations. */
  53.160 +    z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  53.161 +    z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  53.162 +    z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  53.163 +    z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  53.164 +
  53.165 +    z11 = tmp7 + z3;		/* phase 5 */
  53.166 +    z13 = tmp7 - z3;
  53.167 +
  53.168 +    dataptr[5] = z13 + z2;	/* phase 6 */
  53.169 +    dataptr[3] = z13 - z2;
  53.170 +    dataptr[1] = z11 + z4;
  53.171 +    dataptr[7] = z11 - z4;
  53.172 +
  53.173 +    dataptr += DCTSIZE;		/* advance pointer to next row */
  53.174 +  }
  53.175 +
  53.176 +  /* Pass 2: process columns. */
  53.177 +
  53.178 +  dataptr = data;
  53.179 +  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  53.180 +    tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  53.181 +    tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  53.182 +    tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  53.183 +    tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  53.184 +    tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  53.185 +    tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  53.186 +    tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  53.187 +    tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  53.188 +    
  53.189 +    /* Even part */
  53.190 +    
  53.191 +    tmp10 = tmp0 + tmp3;	/* phase 2 */
  53.192 +    tmp13 = tmp0 - tmp3;
  53.193 +    tmp11 = tmp1 + tmp2;
  53.194 +    tmp12 = tmp1 - tmp2;
  53.195 +    
  53.196 +    dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  53.197 +    dataptr[DCTSIZE*4] = tmp10 - tmp11;
  53.198 +    
  53.199 +    z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  53.200 +    dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  53.201 +    dataptr[DCTSIZE*6] = tmp13 - z1;
  53.202 +    
  53.203 +    /* Odd part */
  53.204 +
  53.205 +    tmp10 = tmp4 + tmp5;	/* phase 2 */
  53.206 +    tmp11 = tmp5 + tmp6;
  53.207 +    tmp12 = tmp6 + tmp7;
  53.208 +
  53.209 +    /* The rotator is modified from fig 4-8 to avoid extra negations. */
  53.210 +    z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  53.211 +    z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  53.212 +    z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  53.213 +    z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  53.214 +
  53.215 +    z11 = tmp7 + z3;		/* phase 5 */
  53.216 +    z13 = tmp7 - z3;
  53.217 +
  53.218 +    dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  53.219 +    dataptr[DCTSIZE*3] = z13 - z2;
  53.220 +    dataptr[DCTSIZE*1] = z11 + z4;
  53.221 +    dataptr[DCTSIZE*7] = z11 - z4;
  53.222 +
  53.223 +    dataptr++;			/* advance pointer to next column */
  53.224 +  }
  53.225 +}
  53.226 +
  53.227 +#endif /* DCT_IFAST_SUPPORTED */
    54.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    54.2 +++ b/libs/libjpeg/jfdctint.c	Thu Sep 08 06:28:38 2011 +0300
    54.3 @@ -0,0 +1,283 @@
    54.4 +/*
    54.5 + * jfdctint.c
    54.6 + *
    54.7 + * Copyright (C) 1991-1996, Thomas G. Lane.
    54.8 + * This file is part of the Independent JPEG Group's software.
    54.9 + * For conditions of distribution and use, see the accompanying README file.
   54.10 + *
   54.11 + * This file contains a slow-but-accurate integer implementation of the
   54.12 + * forward DCT (Discrete Cosine Transform).
   54.13 + *
   54.14 + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
   54.15 + * on each column.  Direct algorithms are also available, but they are
   54.16 + * much more complex and seem not to be any faster when reduced to code.
   54.17 + *
   54.18 + * This implementation is based on an algorithm described in
   54.19 + *   C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
   54.20 + *   Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
   54.21 + *   Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
   54.22 + * The primary algorithm described there uses 11 multiplies and 29 adds.
   54.23 + * We use their alternate method with 12 multiplies and 32 adds.
   54.24 + * The advantage of this method is that no data path contains more than one
   54.25 + * multiplication; this allows a very simple and accurate implementation in
   54.26 + * scaled fixed-point arithmetic, with a minimal number of shifts.
   54.27 + */
   54.28 +
   54.29 +#define JPEG_INTERNALS
   54.30 +#include "jinclude.h"
   54.31 +#include "jpeglib.h"
   54.32 +#include "jdct.h"		/* Private declarations for DCT subsystem */
   54.33 +
   54.34 +#ifdef DCT_ISLOW_SUPPORTED
   54.35 +
   54.36 +
   54.37 +/*
   54.38 + * This module is specialized to the case DCTSIZE = 8.
   54.39 + */
   54.40 +
   54.41 +#if DCTSIZE != 8
   54.42 +  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
   54.43 +#endif
   54.44 +
   54.45 +
   54.46 +/*
   54.47 + * The poop on this scaling stuff is as follows:
   54.48 + *
   54.49 + * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
   54.50 + * larger than the true DCT outputs.  The final outputs are therefore
   54.51 + * a factor of N larger than desired; since N=8 this can be cured by
   54.52 + * a simple right shift at the end of the algorithm.  The advantage of
   54.53 + * this arrangement is that we save two multiplications per 1-D DCT,
   54.54 + * because the y0 and y4 outputs need not be divided by sqrt(N).
   54.55 + * In the IJG code, this factor of 8 is removed by the quantization step
   54.56 + * (in jcdctmgr.c), NOT in this module.
   54.57 + *
   54.58 + * We have to do addition and subtraction of the integer inputs, which
   54.59 + * is no problem, and multiplication by fractional constants, which is
   54.60 + * a problem to do in integer arithmetic.  We multiply all the constants
   54.61 + * by CONST_SCALE and convert them to integer constants (thus retaining
   54.62 + * CONST_BITS bits of precision in the constants).  After doing a
   54.63 + * multiplication we have to divide the product by CONST_SCALE, with proper
   54.64 + * rounding, to produce the correct output.  This division can be done
   54.65 + * cheaply as a right shift of CONST_BITS bits.  We postpone shifting
   54.66 + * as long as possible so that partial sums can be added together with
   54.67 + * full fractional precision.
   54.68 + *
   54.69 + * The outputs of the first pass are scaled up by PASS1_BITS bits so that
   54.70 + * they are represented to better-than-integral precision.  These outputs
   54.71 + * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
   54.72 + * with the recommended scaling.  (For 12-bit sample data, the intermediate
   54.73 + * array is INT32 anyway.)
   54.74 + *
   54.75 + * To avoid overflow of the 32-bit intermediate results in pass 2, we must
   54.76 + * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26.  Error analysis
   54.77 + * shows that the values given below are the most effective.
   54.78 + */
   54.79 +
   54.80 +#if BITS_IN_JSAMPLE == 8
   54.81 +#define CONST_BITS  13
   54.82 +#define PASS1_BITS  2
   54.83 +#else
   54.84 +#define CONST_BITS  13
   54.85 +#define PASS1_BITS  1		/* lose a little precision to avoid overflow */
   54.86 +#endif
   54.87 +
   54.88 +/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
   54.89 + * causing a lot of useless floating-point operations at run time.
   54.90 + * To get around this we use the following pre-calculated constants.
   54.91 + * If you change CONST_BITS you may want to add appropriate values.
   54.92 + * (With a reasonable C compiler, you can just rely on the FIX() macro...)
   54.93 + */
   54.94 +
   54.95 +#if CONST_BITS == 13
   54.96 +#define FIX_0_298631336  ((INT32)  2446)	/* FIX(0.298631336) */
   54.97 +#define FIX_0_390180644  ((INT32)  3196)	/* FIX(0.390180644) */
   54.98 +#define FIX_0_541196100  ((INT32)  4433)	/* FIX(0.541196100) */
   54.99 +#define FIX_0_765366865  ((INT32)  6270)	/* FIX(0.765366865) */
  54.100 +#define FIX_0_899976223  ((INT32)  7373)	/* FIX(0.899976223) */
  54.101 +#define FIX_1_175875602  ((INT32)  9633)	/* FIX(1.175875602) */
  54.102 +#define FIX_1_501321110  ((INT32)  12299)	/* FIX(1.501321110) */
  54.103 +#define FIX_1_847759065  ((INT32)  15137)	/* FIX(1.847759065) */
  54.104 +#define FIX_1_961570560  ((INT32)  16069)	/* FIX(1.961570560) */
  54.105 +#define FIX_2_053119869  ((INT32)  16819)	/* FIX(2.053119869) */
  54.106 +#define FIX_2_562915447  ((INT32)  20995)	/* FIX(2.562915447) */
  54.107 +#define FIX_3_072711026  ((INT32)  25172)	/* FIX(3.072711026) */
  54.108 +#else
  54.109 +#define FIX_0_298631336  FIX(0.298631336)
  54.110 +#define FIX_0_390180644  FIX(0.390180644)
  54.111 +#define FIX_0_541196100  FIX(0.541196100)
  54.112 +#define FIX_0_765366865  FIX(0.765366865)
  54.113 +#define FIX_0_899976223  FIX(0.899976223)
  54.114 +#define FIX_1_175875602  FIX(1.175875602)
  54.115 +#define FIX_1_501321110  FIX(1.501321110)
  54.116 +#define FIX_1_847759065  FIX(1.847759065)
  54.117 +#define FIX_1_961570560  FIX(1.961570560)
  54.118 +#define FIX_2_053119869  FIX(2.053119869)
  54.119 +#define FIX_2_562915447  FIX(2.562915447)
  54.120 +#define FIX_3_072711026  FIX(3.072711026)
  54.121 +#endif
  54.122 +
  54.123 +
  54.124 +/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  54.125 + * For 8-bit samples with the recommended scaling, all the variable
  54.126 + * and constant values involved are no more than 16 bits wide, so a
  54.127 + * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  54.128 + * For 12-bit samples, a full 32-bit multiplication will be needed.
  54.129 + */
  54.130 +
  54.131 +#if BITS_IN_JSAMPLE == 8
  54.132 +#define MULTIPLY(var,const)  MULTIPLY16C16(var,const)
  54.133 +#else
  54.134 +#define MULTIPLY(var,const)  ((var) * (const))
  54.135 +#endif
  54.136 +
  54.137 +
  54.138 +/*
  54.139 + * Perform the forward DCT on one block of samples.
  54.140 + */
  54.141 +
  54.142 +GLOBAL(void)
  54.143 +jpeg_fdct_islow (DCTELEM * data)
  54.144 +{
  54.145 +  INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  54.146 +  INT32 tmp10, tmp11, tmp12, tmp13;
  54.147 +  INT32 z1, z2, z3, z4, z5;
  54.148 +  DCTELEM *dataptr;
  54.149 +  int ctr;
  54.150 +  SHIFT_TEMPS
  54.151 +
  54.152 +  /* Pass 1: process rows. */
  54.153 +  /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  54.154 +  /* furthermore, we scale the results by 2**PASS1_BITS. */
  54.155 +
  54.156 +  dataptr = data;
  54.157 +  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  54.158 +    tmp0 = dataptr[0] + dataptr[7];
  54.159 +    tmp7 = dataptr[0] - dataptr[7];
  54.160 +    tmp1 = dataptr[1] + dataptr[6];
  54.161 +    tmp6 = dataptr[1] - dataptr[6];
  54.162 +    tmp2 = dataptr[2] + dataptr[5];
  54.163 +    tmp5 = dataptr[2] - dataptr[5];
  54.164 +    tmp3 = dataptr[3] + dataptr[4];
  54.165 +    tmp4 = dataptr[3] - dataptr[4];
  54.166 +    
  54.167 +    /* Even part per LL&M figure 1 --- note that published figure is faulty;
  54.168 +     * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  54.169 +     */
  54.170 +    
  54.171 +    tmp10 = tmp0 + tmp3;
  54.172 +    tmp13 = tmp0 - tmp3;
  54.173 +    tmp11 = tmp1 + tmp2;
  54.174 +    tmp12 = tmp1 - tmp2;
  54.175 +    
  54.176 +    dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  54.177 +    dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  54.178 +    
  54.179 +    z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  54.180 +    dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  54.181 +				   CONST_BITS-PASS1_BITS);
  54.182 +    dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  54.183 +				   CONST_BITS-PASS1_BITS);
  54.184 +    
  54.185 +    /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  54.186 +     * cK represents cos(K*pi/16).
  54.187 +     * i0..i3 in the paper are tmp4..tmp7 here.
  54.188 +     */
  54.189 +    
  54.190 +    z1 = tmp4 + tmp7;
  54.191 +    z2 = tmp5 + tmp6;
  54.192 +    z3 = tmp4 + tmp6;
  54.193 +    z4 = tmp5 + tmp7;
  54.194 +    z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  54.195 +    
  54.196 +    tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  54.197 +    tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  54.198 +    tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  54.199 +    tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  54.200 +    z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  54.201 +    z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  54.202 +    z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  54.203 +    z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  54.204 +    
  54.205 +    z3 += z5;
  54.206 +    z4 += z5;
  54.207 +    
  54.208 +    dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  54.209 +    dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  54.210 +    dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  54.211 +    dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  54.212 +    
  54.213 +    dataptr += DCTSIZE;		/* advance pointer to next row */
  54.214 +  }
  54.215 +
  54.216 +  /* Pass 2: process columns.
  54.217 +   * We remove the PASS1_BITS scaling, but leave the results scaled up
  54.218 +   * by an overall factor of 8.
  54.219 +   */
  54.220 +
  54.221 +  dataptr = data;
  54.222 +  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  54.223 +    tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  54.224 +    tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  54.225 +    tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  54.226 +    tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  54.227 +    tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  54.228 +    tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  54.229 +    tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  54.230 +    tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  54.231 +    
  54.232 +    /* Even part per LL&M figure 1 --- note that published figure is faulty;
  54.233 +     * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  54.234 +     */
  54.235 +    
  54.236 +    tmp10 = tmp0 + tmp3;
  54.237 +    tmp13 = tmp0 - tmp3;
  54.238 +    tmp11 = tmp1 + tmp2;
  54.239 +    tmp12 = tmp1 - tmp2;
  54.240 +    
  54.241 +    dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  54.242 +    dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  54.243 +    
  54.244 +    z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  54.245 +    dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  54.246 +					   CONST_BITS+PASS1_BITS);
  54.247 +    dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  54.248 +					   CONST_BITS+PASS1_BITS);
  54.249 +    
  54.250 +    /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  54.251 +     * cK represents cos(K*pi/16).
  54.252 +     * i0..i3 in the paper are tmp4..tmp7 here.
  54.253 +     */
  54.254 +    
  54.255 +    z1 = tmp4 + tmp7;
  54.256 +    z2 = tmp5 + tmp6;
  54.257 +    z3 = tmp4 + tmp6;
  54.258 +    z4 = tmp5 + tmp7;
  54.259 +    z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  54.260 +    
  54.261 +    tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  54.262 +    tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  54.263 +    tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  54.264 +    tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  54.265 +    z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  54.266 +    z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  54.267 +    z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  54.268 +    z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  54.269 +    
  54.270 +    z3 += z5;
  54.271 +    z4 += z5;
  54.272 +    
  54.273 +    dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  54.274 +					   CONST_BITS+PASS1_BITS);
  54.275 +    dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  54.276 +					   CONST_BITS+PASS1_BITS);
  54.277 +    dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  54.278 +					   CONST_BITS+PASS1_BITS);
  54.279 +    dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  54.280 +					   CONST_BITS+PASS1_BITS);
  54.281 +    
  54.282 +    dataptr++;			/* advance pointer to next column */
  54.283 +  }
  54.284 +}
  54.285 +
  54.286 +#endif /* DCT_ISLOW_SUPPORTED */
    55.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    55.2 +++ b/libs/libjpeg/jidctflt.c	Thu Sep 08 06:28:38 2011 +0300
    55.3 @@ -0,0 +1,242 @@
    55.4 +/*
    55.5 + * jidctflt.c
    55.6 + *
    55.7 + * Copyright (C) 1994-1998, Thomas G. Lane.
    55.8 + * This file is part of the Independent JPEG Group's software.
    55.9 + * For conditions of distribution and use, see the accompanying README file.
   55.10 + *
   55.11 + * This file contains a floating-point implementation of the
   55.12 + * inverse DCT (Discrete Cosine Transform).  In the IJG code, this routine
   55.13 + * must also perform dequantization of the input coefficients.
   55.14 + *
   55.15 + * This implementation should be more accurate than either of the integer
   55.16 + * IDCT implementations.  However, it may not give the same results on all
   55.17 + * machines because of differences in roundoff behavior.  Speed will depend
   55.18 + * on the hardware's floating point capacity.
   55.19 + *
   55.20 + * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
   55.21 + * on each row (or vice versa, but it's more convenient to emit a row at
   55.22 + * a time).  Direct algorithms are also available, but they are much more
   55.23 + * complex and seem not to be any faster when reduced to code.
   55.24 + *
   55.25 + * This implementation is based on Arai, Agui, and Nakajima's algorithm for
   55.26 + * scaled DCT.  Their original paper (Trans. IEICE E-71(11):1095) is in
   55.27 + * Japanese, but the algorithm is described in the Pennebaker & Mitchell
   55.28 + * JPEG textbook (see REFERENCES section in file README).  The following code
   55.29 + * is based directly on figure 4-8 in P&M.
   55.30 + * While an 8-point DCT cannot be done in less than 11 multiplies, it is
   55.31 + * possible to arrange the computation so that many of the multiplies are
   55.32 + * simple scalings of the final outputs.  These multiplies can then be
   55.33 + * folded into the multiplications or divisions by the JPEG quantization
   55.34 + * table entries.  The AA&N method leaves only 5 multiplies and 29 adds
   55.35 + * to be done in the DCT itself.
   55.36 + * The primary disadvantage of this method is that with a fixed-point
   55.37 + * implementation, accuracy is lost due to imprecise representation of the
   55.38 + * scaled quantization values.  However, that problem does not arise if
   55.39 + * we use floating point arithmetic.
   55.40 + */
   55.41 +
   55.42 +#define JPEG_INTERNALS
   55.43 +#include "jinclude.h"
   55.44 +#include "jpeglib.h"
   55.45 +#include "jdct.h"		/* Private declarations for DCT subsystem */
   55.46 +
   55.47 +#ifdef DCT_FLOAT_SUPPORTED
   55.48 +
   55.49 +
   55.50 +/*
   55.51 + * This module is specialized to the case DCTSIZE = 8.
   55.52 + */
   55.53 +
   55.54 +#if DCTSIZE != 8
   55.55 +  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
   55.56 +#endif
   55.57 +
   55.58 +
   55.59 +/* Dequantize a coefficient by multiplying it by the multiplier-table
   55.60 + * entry; produce a float result.
   55.61 + */
   55.62 +
   55.63 +#define DEQUANTIZE(coef,quantval)  (((FAST_FLOAT) (coef)) * (quantval))
   55.64 +
   55.65 +
   55.66 +/*
   55.67 + * Perform dequantization and inverse DCT on one block of coefficients.
   55.68 + */
   55.69 +
   55.70 +GLOBAL(void)
   55.71 +jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
   55.72 +		 JCOEFPTR coef_block,
   55.73 +		 JSAMPARRAY output_buf, JDIMENSION output_col)
   55.74 +{
   55.75 +  FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
   55.76 +  FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
   55.77 +  FAST_FLOAT z5, z10, z11, z12, z13;
   55.78 +  JCOEFPTR inptr;
   55.79 +  FLOAT_MULT_TYPE * quantptr;
   55.80 +  FAST_FLOAT * wsptr;
   55.81 +  JSAMPROW outptr;
   55.82 +  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
   55.83 +  int ctr;
   55.84 +  FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
   55.85 +  SHIFT_TEMPS
   55.86 +
   55.87 +  /* Pass 1: process columns from input, store into work array. */
   55.88 +
   55.89 +  inptr = coef_block;
   55.90 +  quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
   55.91 +  wsptr = workspace;
   55.92 +  for (ctr = DCTSIZE; ctr > 0; ctr--) {
   55.93 +    /* Due to quantization, we will usually find that many of the input
   55.94 +     * coefficients are zero, especially the AC terms.  We can exploit this
   55.95 +     * by short-circuiting the IDCT calculation for any column in which all
   55.96 +     * the AC terms are zero.  In that case each output is equal to the
   55.97 +     * DC coefficient (with scale factor as needed).
   55.98 +     * With typical images and quantization tables, half or more of the
   55.99 +     * column DCT calculations can be simplified this way.
  55.100 +     */
  55.101 +    
  55.102 +    if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  55.103 +	inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  55.104 +	inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  55.105 +	inptr[DCTSIZE*7] == 0) {
  55.106 +      /* AC terms all zero */
  55.107 +      FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  55.108 +      
  55.109 +      wsptr[DCTSIZE*0] = dcval;
  55.110 +      wsptr[DCTSIZE*1] = dcval;
  55.111 +      wsptr[DCTSIZE*2] = dcval;
  55.112 +      wsptr[DCTSIZE*3] = dcval;
  55.113 +      wsptr[DCTSIZE*4] = dcval;
  55.114 +      wsptr[DCTSIZE*5] = dcval;
  55.115 +      wsptr[DCTSIZE*6] = dcval;
  55.116 +      wsptr[DCTSIZE*7] = dcval;
  55.117 +      
  55.118 +      inptr++;			/* advance pointers to next column */
  55.119 +      quantptr++;
  55.120 +      wsptr++;
  55.121 +      continue;
  55.122 +    }
  55.123 +    
  55.124 +    /* Even part */
  55.125 +
  55.126 +    tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  55.127 +    tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  55.128 +    tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  55.129 +    tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  55.130 +
  55.131 +    tmp10 = tmp0 + tmp2;	/* phase 3 */
  55.132 +    tmp11 = tmp0 - tmp2;
  55.133 +
  55.134 +    tmp13 = tmp1 + tmp3;	/* phases 5-3 */
  55.135 +    tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  55.136 +
  55.137 +    tmp0 = tmp10 + tmp13;	/* phase 2 */
  55.138 +    tmp3 = tmp10 - tmp13;
  55.139 +    tmp1 = tmp11 + tmp12;
  55.140 +    tmp2 = tmp11 - tmp12;
  55.141 +    
  55.142 +    /* Odd part */
  55.143 +
  55.144 +    tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  55.145 +    tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  55.146 +    tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  55.147 +    tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  55.148 +
  55.149 +    z13 = tmp6 + tmp5;		/* phase 6 */
  55.150 +    z10 = tmp6 - tmp5;
  55.151 +    z11 = tmp4 + tmp7;
  55.152 +    z12 = tmp4 - tmp7;
  55.153 +
  55.154 +    tmp7 = z11 + z13;		/* phase 5 */
  55.155 +    tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  55.156 +
  55.157 +    z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  55.158 +    tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  55.159 +    tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  55.160 +
  55.161 +    tmp6 = tmp12 - tmp7;	/* phase 2 */
  55.162 +    tmp5 = tmp11 - tmp6;
  55.163 +    tmp4 = tmp10 + tmp5;
  55.164 +
  55.165 +    wsptr[DCTSIZE*0] = tmp0 + tmp7;
  55.166 +    wsptr[DCTSIZE*7] = tmp0 - tmp7;
  55.167 +    wsptr[DCTSIZE*1] = tmp1 + tmp6;
  55.168 +    wsptr[DCTSIZE*6] = tmp1 - tmp6;
  55.169 +    wsptr[DCTSIZE*2] = tmp2 + tmp5;
  55.170 +    wsptr[DCTSIZE*5] = tmp2 - tmp5;
  55.171 +    wsptr[DCTSIZE*4] = tmp3 + tmp4;
  55.172 +    wsptr[DCTSIZE*3] = tmp3 - tmp4;
  55.173 +
  55.174 +    inptr++;			/* advance pointers to next column */
  55.175 +    quantptr++;
  55.176 +    wsptr++;
  55.177 +  }
  55.178 +  
  55.179 +  /* Pass 2: process rows from work array, store into output array. */
  55.180 +  /* Note that we must descale the results by a factor of 8 == 2**3. */
  55.181 +
  55.182 +  wsptr = workspace;
  55.183 +  for (ctr = 0; ctr < DCTSIZE; ctr++) {
  55.184 +    outptr = output_buf[ctr] + output_col;
  55.185 +    /* Rows of zeroes can be exploited in the same way as we did with columns.
  55.186 +     * However, the column calculation has created many nonzero AC terms, so
  55.187 +     * the simplification applies less often (typically 5% to 10% of the time).
  55.188 +     * And testing floats for zero is relatively expensive, so we don't bother.
  55.189 +     */
  55.190 +    
  55.191 +    /* Even part */
  55.192 +
  55.193 +    tmp10 = wsptr[0] + wsptr[4];
  55.194 +    tmp11 = wsptr[0] - wsptr[4];
  55.195 +
  55.196 +    tmp13 = wsptr[2] + wsptr[6];
  55.197 +    tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  55.198 +
  55.199 +    tmp0 = tmp10 + tmp13;
  55.200 +    tmp3 = tmp10 - tmp13;
  55.201 +    tmp1 = tmp11 + tmp12;
  55.202 +    tmp2 = tmp11 - tmp12;
  55.203 +
  55.204 +    /* Odd part */
  55.205 +
  55.206 +    z13 = wsptr[5] + wsptr[3];
  55.207 +    z10 = wsptr[5] - wsptr[3];
  55.208 +    z11 = wsptr[1] + wsptr[7];
  55.209 +    z12 = wsptr[1] - wsptr[7];
  55.210 +
  55.211 +    tmp7 = z11 + z13;
  55.212 +    tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  55.213 +
  55.214 +    z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  55.215 +    tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  55.216 +    tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  55.217 +
  55.218 +    tmp6 = tmp12 - tmp7;
  55.219 +    tmp5 = tmp11 - tmp6;
  55.220 +    tmp4 = tmp10 + tmp5;
  55.221 +
  55.222 +    /* Final output stage: scale down by a factor of 8 and range-limit */
  55.223 +
  55.224 +    outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  55.225 +			    & RANGE_MASK];
  55.226 +    outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  55.227 +			    & RANGE_MASK];
  55.228 +    outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  55.229 +			    & RANGE_MASK];
  55.230 +    outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  55.231 +			    & RANGE_MASK];
  55.232 +    outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  55.233 +			    & RANGE_MASK];
  55.234 +    outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  55.235 +			    & RANGE_MASK];
  55.236 +    outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  55.237 +			    & RANGE_MASK];
  55.238 +    outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  55.239 +			    & RANGE_MASK];
  55.240 +    
  55.241 +    wsptr += DCTSIZE;		/* advance pointer to next row */
  55.242 +  }
  55.243 +}
  55.244 +
  55.245 +#endif /* DCT_FLOAT_SUPPORTED */
    56.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    56.2 +++ b/libs/libjpeg/jidctfst.c	Thu Sep 08 06:28:38 2011 +0300
    56.3 @@ -0,0 +1,368 @@
    56.4 +/*
    56.5 + * jidctfst.c
    56.6 + *
    56.7 + * Copyright (C) 1994-1998, Thomas G. Lane.
    56.8 + * This file is part of the Independent JPEG Group's software.
    56.9 + * For conditions of distribution and use, see the accompanying README file.
   56.10 + *
   56.11 + * This file contains a fast, not so accurate integer implementation of the
   56.12 + * inverse DCT (Discrete Cosine Transform).  In the IJG code, this routine
   56.13 + * must also perform dequantization of the input coefficients.
   56.14 + *
   56.15 + * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
   56.16 + * on each row (or vice versa, but it's more convenient to emit a row at
   56.17 + * a time).  Direct algorithms are also available, but they are much more
   56.18 + * complex and seem not to be any faster when reduced to code.
   56.19 + *
   56.20 + * This implementation is based on Arai, Agui, and Nakajima's algorithm for
   56.21 + * scaled DCT.  Their original paper (Trans. IEICE E-71(11):1095) is in
   56.22 + * Japanese, but the algorithm is described in the Pennebaker & Mitchell
   56.23 + * JPEG textbook (see REFERENCES section in file README).  The following code
   56.24 + * is based directly on figure 4-8 in P&M.
   56.25 + * While an 8-point DCT cannot be done in less than 11 multiplies, it is
   56.26 + * possible to arrange the computation so that many of the multiplies are
   56.27 + * simple scalings of the final outputs.  These multiplies can then be
   56.28 + * folded into the multiplications or divisions by the JPEG quantization
   56.29 + * table entries.  The AA&N method leaves only 5 multiplies and 29 adds
   56.30 + * to be done in the DCT itself.
   56.31 + * The primary disadvantage of this method is that with fixed-point math,
   56.32 + * accuracy is lost due to imprecise representation of the scaled
   56.33 + * quantization values.  The smaller the quantization table entry, the less
   56.34 + * precise the scaled value, so this implementation does worse with high-
   56.35 + * quality-setting files than with low-quality ones.
   56.36 + */
   56.37 +
   56.38 +#define JPEG_INTERNALS
   56.39 +#include "jinclude.h"
   56.40 +#include "jpeglib.h"
   56.41 +#include "jdct.h"		/* Private declarations for DCT subsystem */
   56.42 +
   56.43 +#ifdef DCT_IFAST_SUPPORTED
   56.44 +
   56.45 +
   56.46 +/*
   56.47 + * This module is specialized to the case DCTSIZE = 8.
   56.48 + */
   56.49 +
   56.50 +#if DCTSIZE != 8
   56.51 +  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
   56.52 +#endif
   56.53 +
   56.54 +
   56.55 +/* Scaling decisions are generally the same as in the LL&M algorithm;
   56.56 + * see jidctint.c for more details.  However, we choose to descale
   56.57 + * (right shift) multiplication products as soon as they are formed,
   56.58 + * rather than carrying additional fractional bits into subsequent additions.
   56.59 + * This compromises accuracy slightly, but it lets us save a few shifts.
   56.60 + * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
   56.61 + * everywhere except in the multiplications proper; this saves a good deal
   56.62 + * of work on 16-bit-int machines.
   56.63 + *
   56.64 + * The dequantized coefficients are not integers because the AA&N scaling
   56.65 + * factors have been incorporated.  We represent them scaled up by PASS1_BITS,
   56.66 + * so that the first and second IDCT rounds have the same input scaling.
   56.67 + * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
   56.68 + * avoid a descaling shift; this compromises accuracy rather drastically
   56.69 + * for small quantization table entries, but it saves a lot of shifts.
   56.70 + * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
   56.71 + * so we use a much larger scaling factor to preserve accuracy.
   56.72 + *
   56.73 + * A final compromise is to represent the multiplicative constants to only
   56.74 + * 8 fractional bits, rather than 13.  This saves some shifting work on some
   56.75 + * machines, and may also reduce the cost of multiplication (since there
   56.76 + * are fewer one-bits in the constants).
   56.77 + */
   56.78 +
   56.79 +#if BITS_IN_JSAMPLE == 8
   56.80 +#define CONST_BITS  8
   56.81 +#define PASS1_BITS  2
   56.82 +#else
   56.83 +#define CONST_BITS  8
   56.84 +#define PASS1_BITS  1		/* lose a little precision to avoid overflow */
   56.85 +#endif
   56.86 +
   56.87 +/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
   56.88 + * causing a lot of useless floating-point operations at run time.
   56.89 + * To get around this we use the following pre-calculated constants.
   56.90 + * If you change CONST_BITS you may want to add appropriate values.
   56.91 + * (With a reasonable C compiler, you can just rely on the FIX() macro...)
   56.92 + */
   56.93 +
   56.94 +#if CONST_BITS == 8
   56.95 +#define FIX_1_082392200  ((INT32)  277)		/* FIX(1.082392200) */
   56.96 +#define FIX_1_414213562  ((INT32)  362)		/* FIX(1.414213562) */
   56.97 +#define FIX_1_847759065  ((INT32)  473)		/* FIX(1.847759065) */
   56.98 +#define FIX_2_613125930  ((INT32)  669)		/* FIX(2.613125930) */
   56.99 +#else
  56.100 +#define FIX_1_082392200  FIX(1.082392200)
  56.101 +#define FIX_1_414213562  FIX(1.414213562)
  56.102 +#define FIX_1_847759065  FIX(1.847759065)
  56.103 +#define FIX_2_613125930  FIX(2.613125930)
  56.104 +#endif
  56.105 +
  56.106 +
  56.107 +/* We can gain a little more speed, with a further compromise in accuracy,
  56.108 + * by omitting the addition in a descaling shift.  This yields an incorrectly
  56.109 + * rounded result half the time...
  56.110 + */
  56.111 +
  56.112 +#ifndef USE_ACCURATE_ROUNDING
  56.113 +#undef DESCALE
  56.114 +#define DESCALE(x,n)  RIGHT_SHIFT(x, n)
  56.115 +#endif
  56.116 +
  56.117 +
  56.118 +/* Multiply a DCTELEM variable by an INT32 constant, and immediately
  56.119 + * descale to yield a DCTELEM result.
  56.120 + */
  56.121 +
  56.122 +#define MULTIPLY(var,const)  ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  56.123 +
  56.124 +
  56.125 +/* Dequantize a coefficient by multiplying it by the multiplier-table
  56.126 + * entry; produce a DCTELEM result.  For 8-bit data a 16x16->16
  56.127 + * multiplication will do.  For 12-bit data, the multiplier table is
  56.128 + * declared INT32, so a 32-bit multiply will be used.
  56.129 + */
  56.130 +
  56.131 +#if BITS_IN_JSAMPLE == 8
  56.132 +#define DEQUANTIZE(coef,quantval)  (((IFAST_MULT_TYPE) (coef)) * (quantval))
  56.133 +#else
  56.134 +#define DEQUANTIZE(coef,quantval)  \
  56.135 +	DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  56.136 +#endif
  56.137 +
  56.138 +
  56.139 +/* Like DESCALE, but applies to a DCTELEM and produces an int.
  56.140 + * We assume that int right shift is unsigned if INT32 right shift is.
  56.141 + */
  56.142 +
  56.143 +#ifdef RIGHT_SHIFT_IS_UNSIGNED
  56.144 +#define ISHIFT_TEMPS	DCTELEM ishift_temp;
  56.145 +#if BITS_IN_JSAMPLE == 8
  56.146 +#define DCTELEMBITS  16		/* DCTELEM may be 16 or 32 bits */
  56.147 +#else
  56.148 +#define DCTELEMBITS  32		/* DCTELEM must be 32 bits */
  56.149 +#endif
  56.150 +#define IRIGHT_SHIFT(x,shft)  \
  56.151 +    ((ishift_temp = (x)) < 0 ? \
  56.152 +     (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  56.153 +     (ishift_temp >> (shft)))
  56.154 +#else
  56.155 +#define ISHIFT_TEMPS
  56.156 +#define IRIGHT_SHIFT(x,shft)	((x) >> (shft))
  56.157 +#endif
  56.158 +
  56.159 +#ifdef USE_ACCURATE_ROUNDING
  56.160 +#define IDESCALE(x,n)  ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  56.161 +#else
  56.162 +#define IDESCALE(x,n)  ((int) IRIGHT_SHIFT(x, n))
  56.163 +#endif
  56.164 +
  56.165 +
  56.166 +/*
  56.167 + * Perform dequantization and inverse DCT on one block of coefficients.
  56.168 + */
  56.169 +
  56.170 +GLOBAL(void)
  56.171 +jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  56.172 +		 JCOEFPTR coef_block,
  56.173 +		 JSAMPARRAY output_buf, JDIMENSION output_col)
  56.174 +{
  56.175 +  DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  56.176 +  DCTELEM tmp10, tmp11, tmp12, tmp13;
  56.177 +  DCTELEM z5, z10, z11, z12, z13;
  56.178 +  JCOEFPTR inptr;
  56.179 +  IFAST_MULT_TYPE * quantptr;
  56.180 +  int * wsptr;
  56.181 +  JSAMPROW outptr;
  56.182 +  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  56.183 +  int ctr;
  56.184 +  int workspace[DCTSIZE2];	/* buffers data between passes */
  56.185 +  SHIFT_TEMPS			/* for DESCALE */
  56.186 +  ISHIFT_TEMPS			/* for IDESCALE */
  56.187 +
  56.188 +  /* Pass 1: process columns from input, store into work array. */
  56.189 +
  56.190 +  inptr = coef_block;
  56.191 +  quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  56.192 +  wsptr = workspace;
  56.193 +  for (ctr = DCTSIZE; ctr > 0; ctr--) {
  56.194 +    /* Due to quantization, we will usually find that many of the input
  56.195 +     * coefficients are zero, especially the AC terms.  We can exploit this
  56.196 +     * by short-circuiting the IDCT calculation for any column in which all
  56.197 +     * the AC terms are zero.  In that case each output is equal to the
  56.198 +     * DC coefficient (with scale factor as needed).
  56.199 +     * With typical images and quantization tables, half or more of the
  56.200 +     * column DCT calculations can be simplified this way.
  56.201 +     */
  56.202 +    
  56.203 +    if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  56.204 +	inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  56.205 +	inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  56.206 +	inptr[DCTSIZE*7] == 0) {
  56.207 +      /* AC terms all zero */
  56.208 +      int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  56.209 +
  56.210 +      wsptr[DCTSIZE*0] = dcval;
  56.211 +      wsptr[DCTSIZE*1] = dcval;
  56.212 +      wsptr[DCTSIZE*2] = dcval;
  56.213 +      wsptr[DCTSIZE*3] = dcval;
  56.214 +      wsptr[DCTSIZE*4] = dcval;
  56.215 +      wsptr[DCTSIZE*5] = dcval;
  56.216 +      wsptr[DCTSIZE*6] = dcval;
  56.217 +      wsptr[DCTSIZE*7] = dcval;
  56.218 +      
  56.219 +      inptr++;			/* advance pointers to next column */
  56.220 +      quantptr++;
  56.221 +      wsptr++;
  56.222 +      continue;
  56.223 +    }
  56.224 +    
  56.225 +    /* Even part */
  56.226 +
  56.227 +    tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  56.228 +    tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  56.229 +    tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  56.230 +    tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  56.231 +
  56.232 +    tmp10 = tmp0 + tmp2;	/* phase 3 */
  56.233 +    tmp11 = tmp0 - tmp2;
  56.234 +
  56.235 +    tmp13 = tmp1 + tmp3;	/* phases 5-3 */
  56.236 +    tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  56.237 +
  56.238 +    tmp0 = tmp10 + tmp13;	/* phase 2 */
  56.239 +    tmp3 = tmp10 - tmp13;
  56.240 +    tmp1 = tmp11 + tmp12;
  56.241 +    tmp2 = tmp11 - tmp12;
  56.242 +    
  56.243 +    /* Odd part */
  56.244 +
  56.245 +    tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  56.246 +    tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  56.247 +    tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  56.248 +    tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  56.249 +
  56.250 +    z13 = tmp6 + tmp5;		/* phase 6 */
  56.251 +    z10 = tmp6 - tmp5;
  56.252 +    z11 = tmp4 + tmp7;
  56.253 +    z12 = tmp4 - tmp7;
  56.254 +
  56.255 +    tmp7 = z11 + z13;		/* phase 5 */
  56.256 +    tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  56.257 +
  56.258 +    z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  56.259 +    tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  56.260 +    tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  56.261 +
  56.262 +    tmp6 = tmp12 - tmp7;	/* phase 2 */
  56.263 +    tmp5 = tmp11 - tmp6;
  56.264 +    tmp4 = tmp10 + tmp5;
  56.265 +
  56.266 +    wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  56.267 +    wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  56.268 +    wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  56.269 +    wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  56.270 +    wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  56.271 +    wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  56.272 +    wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  56.273 +    wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  56.274 +
  56.275 +    inptr++;			/* advance pointers to next column */
  56.276 +    quantptr++;
  56.277 +    wsptr++;
  56.278 +  }
  56.279 +  
  56.280 +  /* Pass 2: process rows from work array, store into output array. */
  56.281 +  /* Note that we must descale the results by a factor of 8 == 2**3, */
  56.282 +  /* and also undo the PASS1_BITS scaling. */
  56.283 +
  56.284 +  wsptr = workspace;
  56.285 +  for (ctr = 0; ctr < DCTSIZE; ctr++) {
  56.286 +    outptr = output_buf[ctr] + output_col;
  56.287 +    /* Rows of zeroes can be exploited in the same way as we did with columns.
  56.288 +     * However, the column calculation has created many nonzero AC terms, so
  56.289 +     * the simplification applies less often (typically 5% to 10% of the time).
  56.290 +     * On machines with very fast multiplication, it's possible that the
  56.291 +     * test takes more time than it's worth.  In that case this section
  56.292 +     * may be commented out.
  56.293 +     */
  56.294 +    
  56.295 +#ifndef NO_ZERO_ROW_TEST
  56.296 +    if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  56.297 +	wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  56.298 +      /* AC terms all zero */
  56.299 +      JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  56.300 +				  & RANGE_MASK];
  56.301 +      
  56.302 +      outptr[0] = dcval;
  56.303 +      outptr[1] = dcval;
  56.304 +      outptr[2] = dcval;
  56.305 +      outptr[3] = dcval;
  56.306 +      outptr[4] = dcval;
  56.307 +      outptr[5] = dcval;
  56.308 +      outptr[6] = dcval;
  56.309 +      outptr[7] = dcval;
  56.310 +
  56.311 +      wsptr += DCTSIZE;		/* advance pointer to next row */
  56.312 +      continue;
  56.313 +    }
  56.314 +#endif
  56.315 +    
  56.316 +    /* Even part */
  56.317 +
  56.318 +    tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  56.319 +    tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  56.320 +
  56.321 +    tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  56.322 +    tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  56.323 +	    - tmp13;
  56.324 +
  56.325 +    tmp0 = tmp10 + tmp13;
  56.326 +    tmp3 = tmp10 - tmp13;
  56.327 +    tmp1 = tmp11 + tmp12;
  56.328 +    tmp2 = tmp11 - tmp12;
  56.329 +
  56.330 +    /* Odd part */
  56.331 +
  56.332 +    z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  56.333 +    z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  56.334 +    z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  56.335 +    z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  56.336 +
  56.337 +    tmp7 = z11 + z13;		/* phase 5 */
  56.338 +    tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  56.339 +
  56.340 +    z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  56.341 +    tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  56.342 +    tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  56.343 +
  56.344 +    tmp6 = tmp12 - tmp7;	/* phase 2 */
  56.345 +    tmp5 = tmp11 - tmp6;
  56.346 +    tmp4 = tmp10 + tmp5;
  56.347 +
  56.348 +    /* Final output stage: scale down by a factor of 8 and range-limit */
  56.349 +
  56.350 +    outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  56.351 +			    & RANGE_MASK];
  56.352 +    outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  56.353 +			    & RANGE_MASK];
  56.354 +    outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  56.355 +			    & RANGE_MASK];
  56.356 +    outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  56.357 +			    & RANGE_MASK];
  56.358 +    outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  56.359 +			    & RANGE_MASK];
  56.360 +    outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  56.361 +			    & RANGE_MASK];
  56.362 +    outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  56.363 +			    & RANGE_MASK];
  56.364 +    outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  56.365 +			    & RANGE_MASK];
  56.366 +
  56.367 +    wsptr += DCTSIZE;		/* advance pointer to next row */
  56.368 +  }
  56.369 +}
  56.370 +
  56.371 +#endif /* DCT_IFAST_SUPPORTED */
    57.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    57.2 +++ b/libs/libjpeg/jidctint.c	Thu Sep 08 06:28:38 2011 +0300
    57.3 @@ -0,0 +1,389 @@
    57.4 +/*
    57.5 + * jidctint.c
    57.6 + *
    57.7 + * Copyright (C) 1991-1998, Thomas G. Lane.
    57.8 + * This file is part of the Independent JPEG Group's software.
    57.9 + * For conditions of distribution and use, see the accompanying README file.
   57.10 + *
   57.11 + * This file contains a slow-but-accurate integer implementation of the
   57.12 + * inverse DCT (Discrete Cosine Transform).  In the IJG code, this routine
   57.13 + * must also perform dequantization of the input coefficients.
   57.14 + *
   57.15 + * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
   57.16 + * on each row (or vice versa, but it's more convenient to emit a row at
   57.17 + * a time).  Direct algorithms are also available, but they are much more
   57.18 + * complex and seem not to be any faster when reduced to code.
   57.19 + *
   57.20 + * This implementation is based on an algorithm described in
   57.21 + *   C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
   57.22 + *   Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
   57.23 + *   Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
   57.24 + * The primary algorithm described there uses 11 multiplies and 29 adds.
   57.25 + * We use their alternate method with 12 multiplies and 32 adds.
   57.26 + * The advantage of this method is that no data path contains more than one
   57.27 + * multiplication; this allows a very simple and accurate implementation in
   57.28 + * scaled fixed-point arithmetic, with a minimal number of shifts.
   57.29 + */
   57.30 +
   57.31 +#define JPEG_INTERNALS
   57.32 +#include "jinclude.h"
   57.33 +#include "jpeglib.h"
   57.34 +#include "jdct.h"		/* Private declarations for DCT subsystem */
   57.35 +
   57.36 +#ifdef DCT_ISLOW_SUPPORTED
   57.37 +
   57.38 +
   57.39 +/*
   57.40 + * This module is specialized to the case DCTSIZE = 8.
   57.41 + */
   57.42 +
   57.43 +#if DCTSIZE != 8
   57.44 +  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
   57.45 +#endif
   57.46 +
   57.47 +
   57.48 +/*
   57.49 + * The poop on this scaling stuff is as follows:
   57.50 + *
   57.51 + * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
   57.52 + * larger than the true IDCT outputs.  The final outputs are therefore
   57.53 + * a factor of N larger than desired; since N=8 this can be cured by
   57.54 + * a simple right shift at the end of the algorithm.  The advantage of
   57.55 + * this arrangement is that we save two multiplications per 1-D IDCT,
   57.56 + * because the y0 and y4 inputs need not be divided by sqrt(N).
   57.57 + *
   57.58 + * We have to do addition and subtraction of the integer inputs, which
   57.59 + * is no problem, and multiplication by fractional constants, which is
   57.60 + * a problem to do in integer arithmetic.  We multiply all the constants
   57.61 + * by CONST_SCALE and convert them to integer constants (thus retaining
   57.62 + * CONST_BITS bits of precision in the constants).  After doing a
   57.63 + * multiplication we have to divide the product by CONST_SCALE, with proper
   57.64 + * rounding, to produce the correct output.  This division can be done
   57.65 + * cheaply as a right shift of CONST_BITS bits.  We postpone shifting
   57.66 + * as long as possible so that partial sums can be added together with
   57.67 + * full fractional precision.
   57.68 + *
   57.69 + * The outputs of the first pass are scaled up by PASS1_BITS bits so that
   57.70 + * they are represented to better-than-integral precision.  These outputs
   57.71 + * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
   57.72 + * with the recommended scaling.  (To scale up 12-bit sample data further, an
   57.73 + * intermediate INT32 array would be needed.)
   57.74 + *
   57.75 + * To avoid overflow of the 32-bit intermediate results in pass 2, we must
   57.76 + * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26.  Error analysis
   57.77 + * shows that the values given below are the most effective.
   57.78 + */
   57.79 +
   57.80 +#if BITS_IN_JSAMPLE == 8
   57.81 +#define CONST_BITS  13
   57.82 +#define PASS1_BITS  2
   57.83 +#else
   57.84 +#define CONST_BITS  13
   57.85 +#define PASS1_BITS  1		/* lose a little precision to avoid overflow */
   57.86 +#endif
   57.87 +
   57.88 +/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
   57.89 + * causing a lot of useless floating-point operations at run time.
   57.90 + * To get around this we use the following pre-calculated constants.
   57.91 + * If you change CONST_BITS you may want to add appropriate values.
   57.92 + * (With a reasonable C compiler, you can just rely on the FIX() macro...)
   57.93 + */
   57.94 +
   57.95 +#if CONST_BITS == 13
   57.96 +#define FIX_0_298631336  ((INT32)  2446)	/* FIX(0.298631336) */
   57.97 +#define FIX_0_390180644  ((INT32)  3196)	/* FIX(0.390180644) */
   57.98 +#define FIX_0_541196100  ((INT32)  4433)	/* FIX(0.541196100) */
   57.99 +#define FIX_0_765366865  ((INT32)  6270)	/* FIX(0.765366865) */
  57.100 +#define FIX_0_899976223  ((INT32)  7373)	/* FIX(0.899976223) */
  57.101 +#define FIX_1_175875602  ((INT32)  9633)	/* FIX(1.175875602) */
  57.102 +#define FIX_1_501321110  ((INT32)  12299)	/* FIX(1.501321110) */
  57.103 +#define FIX_1_847759065  ((INT32)  15137)	/* FIX(1.847759065) */
  57.104 +#define FIX_1_961570560  ((INT32)  16069)	/* FIX(1.961570560) */
  57.105 +#define FIX_2_053119869  ((INT32)  16819)	/* FIX(2.053119869) */
  57.106 +#define FIX_2_562915447  ((INT32)  20995)	/* FIX(2.562915447) */
  57.107 +#define FIX_3_072711026  ((INT32)  25172)	/* FIX(3.072711026) */
  57.108 +#else
  57.109 +#define FIX_0_298631336  FIX(0.298631336)
  57.110 +#define FIX_0_390180644  FIX(0.390180644)
  57.111 +#define FIX_0_541196100  FIX(0.541196100)
  57.112 +#define FIX_0_765366865  FIX(0.765366865)
  57.113 +#define FIX_0_899976223  FIX(0.899976223)
  57.114 +#define FIX_1_175875602  FIX(1.175875602)
  57.115 +#define FIX_1_501321110  FIX(1.501321110)
  57.116 +#define FIX_1_847759065  FIX(1.847759065)
  57.117 +#define FIX_1_961570560  FIX(1.961570560)
  57.118 +#define FIX_2_053119869  FIX(2.053119869)
  57.119 +#define FIX_2_562915447  FIX(2.562915447)
  57.120 +#define FIX_3_072711026  FIX(3.072711026)
  57.121 +#endif
  57.122 +
  57.123 +
  57.124 +/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  57.125 + * For 8-bit samples with the recommended scaling, all the variable
  57.126 + * and constant values involved are no more than 16 bits wide, so a
  57.127 + * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  57.128 + * For 12-bit samples, a full 32-bit multiplication will be needed.
  57.129 + */
  57.130 +
  57.131 +#if BITS_IN_JSAMPLE == 8
  57.132 +#define MULTIPLY(var,const)  MULTIPLY16C16(var,const)
  57.133 +#else
  57.134 +#define MULTIPLY(var,const)  ((var) * (const))
  57.135 +#endif
  57.136 +
  57.137 +
  57.138 +/* Dequantize a coefficient by multiplying it by the multiplier-table
  57.139 + * entry; produce an int result.  In this module, both inputs and result
  57.140 + * are 16 bits or less, so either int or short multiply will work.
  57.141 + */
  57.142 +
  57.143 +#define DEQUANTIZE(coef,quantval)  (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  57.144 +
  57.145 +
  57.146 +/*
  57.147 + * Perform dequantization and inverse DCT on one block of coefficients.
  57.148 + */
  57.149 +
  57.150 +GLOBAL(void)
  57.151 +jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  57.152 +		 JCOEFPTR coef_block,
  57.153 +		 JSAMPARRAY output_buf, JDIMENSION output_col)
  57.154 +{
  57.155 +  INT32 tmp0, tmp1, tmp2, tmp3;
  57.156 +  INT32 tmp10, tmp11, tmp12, tmp13;
  57.157 +  INT32 z1, z2, z3, z4, z5;
  57.158 +  JCOEFPTR inptr;
  57.159 +  ISLOW_MULT_TYPE * quantptr;
  57.160 +  int * wsptr;
  57.161 +  JSAMPROW outptr;
  57.162 +  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  57.163 +  int ctr;
  57.164 +  int workspace[DCTSIZE2];	/* buffers data between passes */
  57.165 +  SHIFT_TEMPS
  57.166 +
  57.167 +  /* Pass 1: process columns from input, store into work array. */
  57.168 +  /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  57.169 +  /* furthermore, we scale the results by 2**PASS1_BITS. */
  57.170 +
  57.171 +  inptr = coef_block;
  57.172 +  quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  57.173 +  wsptr = workspace;
  57.174 +  for (ctr = DCTSIZE; ctr > 0; ctr--) {
  57.175 +    /* Due to quantization, we will usually find that many of the input
  57.176 +     * coefficients are zero, especially the AC terms.  We can exploit this
  57.177 +     * by short-circuiting the IDCT calculation for any column in which all
  57.178 +     * the AC terms are zero.  In that case each output is equal to the
  57.179 +     * DC coefficient (with scale factor as needed).
  57.180 +     * With typical images and quantization tables, half or more of the
  57.181 +     * column DCT calculations can be simplified this way.
  57.182 +     */
  57.183 +    
  57.184 +    if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  57.185 +	inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  57.186 +	inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  57.187 +	inptr[DCTSIZE*7] == 0) {
  57.188 +      /* AC terms all zero */
  57.189 +      int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  57.190 +      
  57.191 +      wsptr[DCTSIZE*0] = dcval;
  57.192 +      wsptr[DCTSIZE*1] = dcval;
  57.193 +      wsptr[DCTSIZE*2] = dcval;
  57.194 +      wsptr[DCTSIZE*3] = dcval;
  57.195 +      wsptr[DCTSIZE*4] = dcval;
  57.196 +      wsptr[DCTSIZE*5] = dcval;
  57.197 +      wsptr[DCTSIZE*6] = dcval;
  57.198 +      wsptr[DCTSIZE*7] = dcval;
  57.199 +      
  57.200 +      inptr++;			/* advance pointers to next column */
  57.201 +      quantptr++;
  57.202 +      wsptr++;
  57.203 +      continue;
  57.204 +    }
  57.205 +    
  57.206 +    /* Even part: reverse the even part of the forward DCT. */
  57.207 +    /* The rotator is sqrt(2)*c(-6). */
  57.208 +    
  57.209 +    z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  57.210 +    z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  57.211 +    
  57.212 +    z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  57.213 +    tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  57.214 +    tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  57.215 +    
  57.216 +    z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  57.217 +    z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  57.218 +
  57.219 +    tmp0 = (z2 + z3) << CONST_BITS;
  57.220 +    tmp1 = (z2 - z3) << CONST_BITS;
  57.221 +    
  57.222 +    tmp10 = tmp0 + tmp3;
  57.223 +    tmp13 = tmp0 - tmp3;
  57.224 +    tmp11 = tmp1 + tmp2;
  57.225 +    tmp12 = tmp1 - tmp2;
  57.226 +    
  57.227 +    /* Odd part per figure 8; the matrix is unitary and hence its
  57.228 +     * transpose is its inverse.  i0..i3 are y7,y5,y3,y1 respectively.
  57.229 +     */
  57.230 +    
  57.231 +    tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  57.232 +    tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  57.233 +    tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  57.234 +    tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  57.235 +    
  57.236 +    z1 = tmp0 + tmp3;
  57.237 +    z2 = tmp1 + tmp2;
  57.238 +    z3 = tmp0 + tmp2;
  57.239 +    z4 = tmp1 + tmp3;
  57.240 +    z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  57.241 +    
  57.242 +    tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  57.243 +    tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  57.244 +    tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  57.245 +    tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  57.246 +    z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  57.247 +    z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  57.248 +    z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  57.249 +    z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  57.250 +    
  57.251 +    z3 += z5;
  57.252 +    z4 += z5;
  57.253 +    
  57.254 +    tmp0 += z1 + z3;
  57.255 +    tmp1 += z2 + z4;
  57.256 +    tmp2 += z2 + z3;
  57.257 +    tmp3 += z1 + z4;
  57.258 +    
  57.259 +    /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  57.260 +    
  57.261 +    wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  57.262 +    wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  57.263 +    wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  57.264 +    wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  57.265 +    wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  57.266 +    wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  57.267 +    wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  57.268 +    wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  57.269 +    
  57.270 +    inptr++;			/* advance pointers to next column */
  57.271 +    quantptr++;
  57.272 +    wsptr++;
  57.273 +  }
  57.274 +  
  57.275 +  /* Pass 2: process rows from work array, store into output array. */
  57.276 +  /* Note that we must descale the results by a factor of 8 == 2**3, */
  57.277 +  /* and also undo the PASS1_BITS scaling. */
  57.278 +
  57.279 +  wsptr = workspace;
  57.280 +  for (ctr = 0; ctr < DCTSIZE; ctr++) {
  57.281 +    outptr = output_buf[ctr] + output_col;
  57.282 +    /* Rows of zeroes can be exploited in the same way as we did with columns.
  57.283 +     * However, the column calculation has created many nonzero AC terms, so
  57.284 +     * the simplification applies less often (typically 5% to 10% of the time).
  57.285 +     * On machines with very fast multiplication, it's possible that the
  57.286 +     * test takes more time than it's worth.  In that case this section
  57.287 +     * may be commented out.
  57.288 +     */
  57.289 +    
  57.290 +#ifndef NO_ZERO_ROW_TEST
  57.291 +    if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  57.292 +	wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  57.293 +      /* AC terms all zero */
  57.294 +      JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  57.295 +				  & RANGE_MASK];
  57.296 +      
  57.297 +      outptr[0] = dcval;
  57.298 +      outptr[1] = dcval;
  57.299 +      outptr[2] = dcval;
  57.300 +      outptr[3] = dcval;
  57.301 +      outptr[4] = dcval;
  57.302 +      outptr[5] = dcval;
  57.303 +      outptr[6] = dcval;
  57.304 +      outptr[7] = dcval;
  57.305 +
  57.306 +      wsptr += DCTSIZE;		/* advance pointer to next row */
  57.307 +      continue;
  57.308 +    }
  57.309 +#endif
  57.310 +    
  57.311 +    /* Even part: reverse the even part of the forward DCT. */
  57.312 +    /* The rotator is sqrt(2)*c(-6). */
  57.313 +    
  57.314 +    z2 = (INT32) wsptr[2];
  57.315 +    z3 = (INT32) wsptr[6];
  57.316 +    
  57.317 +    z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  57.318 +    tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  57.319 +    tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  57.320 +    
  57.321 +    tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  57.322 +    tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  57.323 +    
  57.324 +    tmp10 = tmp0 + tmp3;
  57.325 +    tmp13 = tmp0 - tmp3;
  57.326 +    tmp11 = tmp1 + tmp2;
  57.327 +    tmp12 = tmp1 - tmp2;
  57.328 +    
  57.329 +    /* Odd part per figure 8; the matrix is unitary and hence its
  57.330 +     * transpose is its inverse.  i0..i3 are y7,y5,y3,y1 respectively.
  57.331 +     */
  57.332 +    
  57.333 +    tmp0 = (INT32) wsptr[7];
  57.334 +    tmp1 = (INT32) wsptr[5];
  57.335 +    tmp2 = (INT32) wsptr[3];
  57.336 +    tmp3 = (INT32) wsptr[1];
  57.337 +    
  57.338 +    z1 = tmp0 + tmp3;
  57.339 +    z2 = tmp1 + tmp2;
  57.340 +    z3 = tmp0 + tmp2;
  57.341 +    z4 = tmp1 + tmp3;
  57.342 +    z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  57.343 +    
  57.344 +    tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  57.345 +    tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  57.346 +    tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  57.347 +    tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  57.348 +    z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  57.349 +    z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  57.350 +    z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  57.351 +    z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  57.352 +    
  57.353 +    z3 += z5;
  57.354 +    z4 += z5;
  57.355 +    
  57.356 +    tmp0 += z1 + z3;
  57.357 +    tmp1 += z2 + z4;
  57.358 +    tmp2 += z2 + z3;
  57.359 +    tmp3 += z1 + z4;
  57.360 +    
  57.361 +    /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  57.362 +    
  57.363 +    outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  57.364 +					  CONST_BITS+PASS1_BITS+3)
  57.365 +			    & RANGE_MASK];
  57.366 +    outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  57.367 +					  CONST_BITS+PASS1_BITS+3)
  57.368 +			    & RANGE_MASK];
  57.369 +    outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  57.370 +					  CONST_BITS+PASS1_BITS+3)
  57.371 +			    & RANGE_MASK];
  57.372 +    outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  57.373 +					  CONST_BITS+PASS1_BITS+3)
  57.374 +			    & RANGE_MASK];
  57.375 +    outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  57.376 +					  CONST_BITS+PASS1_BITS+3)
  57.377 +			    & RANGE_MASK];
  57.378 +    outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  57.379 +					  CONST_BITS+PASS1_BITS+3)
  57.380 +			    & RANGE_MASK];
  57.381 +    outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  57.382 +					  CONST_BITS+PASS1_BITS+3)
  57.383 +			    & RANGE_MASK];
  57.384 +    outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  57.385 +					  CONST_BITS+PASS1_BITS+3)
  57.386 +			    & RANGE_MASK];
  57.387 +    
  57.388 +    wsptr += DCTSIZE;		/* advance pointer to next row */
  57.389 +  }
  57.390 +}
  57.391 +
  57.392 +#endif /* DCT_ISLOW_SUPPORTED */
    58.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    58.2 +++ b/libs/libjpeg/jidctred.c	Thu Sep 08 06:28:38 2011 +0300
    58.3 @@ -0,0 +1,398 @@
    58.4 +/*
    58.5 + * jidctred.c
    58.6 + *
    58.7 + * Copyright (C) 1994-1998, Thomas G. Lane.
    58.8 + * This file is part of the Independent JPEG Group's software.
    58.9 + * For conditions of distribution and use, see the accompanying README file.
   58.10 + *
   58.11 + * This file contains inverse-DCT routines that produce reduced-size output:
   58.12 + * either 4x4, 2x2, or 1x1 pixels from an 8x8 DCT block.
   58.13 + *
   58.14 + * The implementation is based on the Loeffler, Ligtenberg and Moschytz (LL&M)
   58.15 + * algorithm used in jidctint.c.  We simply replace each 8-to-8 1-D IDCT step
   58.16 + * with an 8-to-4 step that produces the four averages of two adjacent outputs
   58.17 + * (or an 8-to-2 step producing two averages of four outputs, for 2x2 output).
   58.18 + * These steps were derived by computing the corresponding values at the end
   58.19 + * of the normal LL&M code, then simplifying as much as possible.
   58.20 + *
   58.21 + * 1x1 is trivial: just take the DC coefficient divided by 8.
   58.22 + *
   58.23 + * See jidctint.c for additional comments.
   58.24 + */
   58.25 +
   58.26 +#define JPEG_INTERNALS
   58.27 +#include "jinclude.h"
   58.28 +#include "jpeglib.h"
   58.29 +#include "jdct.h"		/* Private declarations for DCT subsystem */
   58.30 +
   58.31 +#ifdef IDCT_SCALING_SUPPORTED
   58.32 +
   58.33 +
   58.34 +/*
   58.35 + * This module is specialized to the case DCTSIZE = 8.
   58.36 + */
   58.37 +
   58.38 +#if DCTSIZE != 8
   58.39 +  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
   58.40 +#endif
   58.41 +
   58.42 +
   58.43 +/* Scaling is the same as in jidctint.c. */
   58.44 +
   58.45 +#if BITS_IN_JSAMPLE == 8
   58.46 +#define CONST_BITS  13
   58.47 +#define PASS1_BITS  2
   58.48 +#else
   58.49 +#define CONST_BITS  13
   58.50 +#define PASS1_BITS  1		/* lose a little precision to avoid overflow */
   58.51 +#endif
   58.52 +
   58.53 +/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
   58.54 + * causing a lot of useless floating-point operations at run time.
   58.55 + * To get around this we use the following pre-calculated constants.
   58.56 + * If you change CONST_BITS you may want to add appropriate values.
   58.57 + * (With a reasonable C compiler, you can just rely on the FIX() macro...)
   58.58 + */
   58.59 +
   58.60 +#if CONST_BITS == 13
   58.61 +#define FIX_0_211164243  ((INT32)  1730)	/* FIX(0.211164243) */
   58.62 +#define FIX_0_509795579  ((INT32)  4176)	/* FIX(0.509795579) */
   58.63 +#define FIX_0_601344887  ((INT32)  4926)	/* FIX(0.601344887) */
   58.64 +#define FIX_0_720959822  ((INT32)  5906)	/* FIX(0.720959822) */
   58.65 +#define FIX_0_765366865  ((INT32)  6270)	/* FIX(0.765366865) */
   58.66 +#define FIX_0_850430095  ((INT32)  6967)	/* FIX(0.850430095) */
   58.67 +#define FIX_0_899976223  ((INT32)  7373)	/* FIX(0.899976223) */
   58.68 +#define FIX_1_061594337  ((INT32)  8697)	/* FIX(1.061594337) */
   58.69 +#define FIX_1_272758580  ((INT32)  10426)	/* FIX(1.272758580) */
   58.70 +#define FIX_1_451774981  ((INT32)  11893)	/* FIX(1.451774981) */
   58.71 +#define FIX_1_847759065  ((INT32)  15137)	/* FIX(1.847759065) */
   58.72 +#define FIX_2_172734803  ((INT32)  17799)	/* FIX(2.172734803) */
   58.73 +#define FIX_2_562915447  ((INT32)  20995)	/* FIX(2.562915447) */
   58.74 +#define FIX_3_624509785  ((INT32)  29692)	/* FIX(3.624509785) */
   58.75 +#else
   58.76 +#define FIX_0_211164243  FIX(0.211164243)
   58.77 +#define FIX_0_509795579  FIX(0.509795579)
   58.78 +#define FIX_0_601344887  FIX(0.601344887)
   58.79 +#define FIX_0_720959822  FIX(0.720959822)
   58.80 +#define FIX_0_765366865  FIX(0.765366865)
   58.81 +#define FIX_0_850430095  FIX(0.850430095)
   58.82 +#define FIX_0_899976223  FIX(0.899976223)
   58.83 +#define FIX_1_061594337  FIX(1.061594337)
   58.84 +#define FIX_1_272758580  FIX(1.272758580)
   58.85 +#define FIX_1_451774981  FIX(1.451774981)
   58.86 +#define FIX_1_847759065  FIX(1.847759065)
   58.87 +#define FIX_2_172734803  FIX(2.172734803)
   58.88 +#define FIX_2_562915447  FIX(2.562915447)
   58.89 +#define FIX_3_624509785  FIX(3.624509785)
   58.90 +#endif
   58.91 +
   58.92 +
   58.93 +/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
   58.94 + * For 8-bit samples with the recommended scaling, all the variable
   58.95 + * and constant values involved are no more than 16 bits wide, so a
   58.96 + * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
   58.97 + * For 12-bit samples, a full 32-bit multiplication will be needed.
   58.98 + */
   58.99 +
  58.100 +#if BITS_IN_JSAMPLE == 8
  58.101 +#define MULTIPLY(var,const)  MULTIPLY16C16(var,const)
  58.102 +#else
  58.103 +#define MULTIPLY(var,const)  ((var) * (const))
  58.104 +#endif
  58.105 +
  58.106 +
  58.107 +/* Dequantize a coefficient by multiplying it by the multiplier-table
  58.108 + * entry; produce an int result.  In this module, both inputs and result
  58.109 + * are 16 bits or less, so either int or short multiply will work.
  58.110 + */
  58.111 +
  58.112 +#define DEQUANTIZE(coef,quantval)  (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  58.113 +
  58.114 +
  58.115 +/*
  58.116 + * Perform dequantization and inverse DCT on one block of coefficients,
  58.117 + * producing a reduced-size 4x4 output block.
  58.118 + */
  58.119 +
  58.120 +GLOBAL(void)
  58.121 +jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  58.122 +	       JCOEFPTR coef_block,
  58.123 +	       JSAMPARRAY output_buf, JDIMENSION output_col)
  58.124 +{
  58.125 +  INT32 tmp0, tmp2, tmp10, tmp12;
  58.126 +  INT32 z1, z2, z3, z4;
  58.127 +  JCOEFPTR inptr;
  58.128 +  ISLOW_MULT_TYPE * quantptr;
  58.129 +  int * wsptr;
  58.130 +  JSAMPROW outptr;
  58.131 +  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  58.132 +  int ctr;
  58.133 +  int workspace[DCTSIZE*4];	/* buffers data between passes */
  58.134 +  SHIFT_TEMPS
  58.135 +
  58.136 +  /* Pass 1: process columns from input, store into work array. */
  58.137 +
  58.138 +  inptr = coef_block;
  58.139 +  quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  58.140 +  wsptr = workspace;
  58.141 +  for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  58.142 +    /* Don't bother to process column 4, because second pass won't use it */
  58.143 +    if (ctr == DCTSIZE-4)
  58.144 +      continue;
  58.145 +    if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  58.146 +	inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  58.147 +	inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  58.148 +      /* AC terms all zero; we need not examine term 4 for 4x4 output */
  58.149 +      int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  58.150 +      
  58.151 +      wsptr[DCTSIZE*0] = dcval;
  58.152 +      wsptr[DCTSIZE*1] = dcval;
  58.153 +      wsptr[DCTSIZE*2] = dcval;
  58.154 +      wsptr[DCTSIZE*3] = dcval;
  58.155 +      
  58.156 +      continue;
  58.157 +    }
  58.158 +    
  58.159 +    /* Even part */
  58.160 +    
  58.161 +    tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  58.162 +    tmp0 <<= (CONST_BITS+1);
  58.163 +    
  58.164 +    z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  58.165 +    z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  58.166 +
  58.167 +    tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  58.168 +    
  58.169 +    tmp10 = tmp0 + tmp2;
  58.170 +    tmp12 = tmp0 - tmp2;
  58.171 +    
  58.172 +    /* Odd part */
  58.173 +    
  58.174 +    z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  58.175 +    z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  58.176 +    z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  58.177 +    z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  58.178 +    
  58.179 +    tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  58.180 +	 + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  58.181 +	 + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  58.182 +	 + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  58.183 +    
  58.184 +    tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  58.185 +	 + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  58.186 +	 + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  58.187 +	 + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  58.188 +
  58.189 +    /* Final output stage */
  58.190 +    
  58.191 +    wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  58.192 +    wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  58.193 +    wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  58.194 +    wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  58.195 +  }
  58.196 +  
  58.197 +  /* Pass 2: process 4 rows from work array, store into output array. */
  58.198 +
  58.199 +  wsptr = workspace;
  58.200 +  for (ctr = 0; ctr < 4; ctr++) {
  58.201 +    outptr = output_buf[ctr] + output_col;
  58.202 +    /* It's not clear whether a zero row test is worthwhile here ... */
  58.203 +
  58.204 +#ifndef NO_ZERO_ROW_TEST
  58.205 +    if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  58.206 +	wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  58.207 +      /* AC terms all zero */
  58.208 +      JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  58.209 +				  & RANGE_MASK];
  58.210 +      
  58.211 +      outptr[0] = dcval;
  58.212 +      outptr[1] = dcval;
  58.213 +      outptr[2] = dcval;
  58.214 +      outptr[3] = dcval;
  58.215 +      
  58.216 +      wsptr += DCTSIZE;		/* advance pointer to next row */
  58.217 +      continue;
  58.218 +    }
  58.219 +#endif
  58.220 +    
  58.221 +    /* Even part */
  58.222 +    
  58.223 +    tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  58.224 +    
  58.225 +    tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  58.226 +	 + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  58.227 +    
  58.228 +    tmp10 = tmp0 + tmp2;
  58.229 +    tmp12 = tmp0 - tmp2;
  58.230 +    
  58.231 +    /* Odd part */
  58.232 +    
  58.233 +    z1 = (INT32) wsptr[7];
  58.234 +    z2 = (INT32) wsptr[5];
  58.235 +    z3 = (INT32) wsptr[3];
  58.236 +    z4 = (INT32) wsptr[1];
  58.237 +    
  58.238 +    tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  58.239 +	 + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  58.240 +	 + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  58.241 +	 + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  58.242 +    
  58.243 +    tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  58.244 +	 + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  58.245 +	 + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  58.246 +	 + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  58.247 +
  58.248 +    /* Final output stage */
  58.249 +    
  58.250 +    outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  58.251 +					  CONST_BITS+PASS1_BITS+3+1)
  58.252 +			    & RANGE_MASK];
  58.253 +    outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  58.254 +					  CONST_BITS+PASS1_BITS+3+1)
  58.255 +			    & RANGE_MASK];
  58.256 +    outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  58.257 +					  CONST_BITS+PASS1_BITS+3+1)
  58.258 +			    & RANGE_MASK];
  58.259 +    outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  58.260 +					  CONST_BITS+PASS1_BITS+3+1)
  58.261 +			    & RANGE_MASK];
  58.262 +    
  58.263 +    wsptr += DCTSIZE;		/* advance pointer to next row */
  58.264 +  }
  58.265 +}
  58.266 +
  58.267 +
  58.268 +/*
  58.269 + * Perform dequantization and inverse DCT on one block of coefficients,
  58.270 + * producing a reduced-size 2x2 output block.
  58.271 + */
  58.272 +
  58.273 +GLOBAL(void)
  58.274 +jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  58.275 +	       JCOEFPTR coef_block,
  58.276 +	       JSAMPARRAY output_buf, JDIMENSION output_col)
  58.277 +{
  58.278 +  INT32 tmp0, tmp10, z1;
  58.279 +  JCOEFPTR inptr;
  58.280 +  ISLOW_MULT_TYPE * quantptr;
  58.281 +  int * wsptr;
  58.282 +  JSAMPROW outptr;
  58.283 +  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  58.284 +  int ctr;
  58.285 +  int workspace[DCTSIZE*2];	/* buffers data between passes */
  58.286 +  SHIFT_TEMPS
  58.287 +
  58.288 +  /* Pass 1: process columns from input, store into work array. */
  58.289 +
  58.290 +  inptr = coef_block;
  58.291 +  quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  58.292 +  wsptr = workspace;
  58.293 +  for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  58.294 +    /* Don't bother to process columns 2,4,6 */
  58.295 +    if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  58.296 +      continue;
  58.297 +    if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  58.298 +	inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  58.299 +      /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  58.300 +      int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  58.301 +      
  58.302 +      wsptr[DCTSIZE*0] = dcval;
  58.303 +      wsptr[DCTSIZE*1] = dcval;
  58.304 +      
  58.305 +      continue;
  58.306 +    }
  58.307 +    
  58.308 +    /* Even part */
  58.309 +    
  58.310 +    z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  58.311 +    tmp10 = z1 << (CONST_BITS+2);
  58.312 +    
  58.313 +    /* Odd part */
  58.314 +
  58.315 +    z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  58.316 +    tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  58.317 +    z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  58.318 +    tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  58.319 +    z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  58.320 +    tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  58.321 +    z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  58.322 +    tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  58.323 +
  58.324 +    /* Final output stage */
  58.325 +    
  58.326 +    wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  58.327 +    wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  58.328 +  }
  58.329 +  
  58.330 +  /* Pass 2: process 2 rows from work array, store into output array. */
  58.331 +
  58.332 +  wsptr = workspace;
  58.333 +  for (ctr = 0; ctr < 2; ctr++) {
  58.334 +    outptr = output_buf[ctr] + output_col;
  58.335 +    /* It's not clear whether a zero row test is worthwhile here ... */
  58.336 +
  58.337 +#ifndef NO_ZERO_ROW_TEST
  58.338 +    if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  58.339 +      /* AC terms all zero */
  58.340 +      JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  58.341 +				  & RANGE_MASK];
  58.342 +      
  58.343 +      outptr[0] = dcval;
  58.344 +      outptr[1] = dcval;
  58.345 +      
  58.346 +      wsptr += DCTSIZE;		/* advance pointer to next row */
  58.347 +      continue;
  58.348 +    }
  58.349 +#endif
  58.350 +    
  58.351 +    /* Even part */
  58.352 +    
  58.353 +    tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  58.354 +    
  58.355 +    /* Odd part */
  58.356 +
  58.357 +    tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  58.358 +	 + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  58.359 +	 + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  58.360 +	 + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  58.361 +
  58.362 +    /* Final output stage */
  58.363 +    
  58.364 +    outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  58.365 +					  CONST_BITS+PASS1_BITS+3+2)
  58.366 +			    & RANGE_MASK];
  58.367 +    outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  58.368 +					  CONST_BITS+PASS1_BITS+3+2)
  58.369 +			    & RANGE_MASK];
  58.370 +    
  58.371 +    wsptr += DCTSIZE;		/* advance pointer to next row */
  58.372 +  }
  58.373 +}
  58.374 +
  58.375 +
  58.376 +/*
  58.377 + * Perform dequantization and inverse DCT on one block of coefficients,
  58.378 + * producing a reduced-size 1x1 output block.
  58.379 + */
  58.380 +
  58.381 +GLOBAL(void)
  58.382 +jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  58.383 +	       JCOEFPTR coef_block,
  58.384 +	       JSAMPARRAY output_buf, JDIMENSION output_col)
  58.385 +{
  58.386 +  int dcval;
  58.387 +  ISLOW_MULT_TYPE * quantptr;
  58.388 +  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  58.389 +  SHIFT_TEMPS
  58.390 +
  58.391 +  /* We hardly need an inverse DCT routine for this: just take the
  58.392 +   * average pixel value, which is one-eighth of the DC coefficient.
  58.393 +   */
  58.394 +  quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  58.395 +  dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  58.396 +  dcval = (int) DESCALE((INT32) dcval, 3);
  58.397 +
  58.398 +  output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  58.399 +}
  58.400 +
  58.401 +#endif /* IDCT_SCALING_SUPPORTED */
    59.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    59.2 +++ b/libs/libjpeg/jinclude.h	Thu Sep 08 06:28:38 2011 +0300
    59.3 @@ -0,0 +1,91 @@
    59.4 +/*
    59.5 + * jinclude.h
    59.6 + *
    59.7 + * Copyright (C) 1991-1994, Thomas G. Lane.
    59.8 + * This file is part of the Independent JPEG Group's software.
    59.9 + * For conditions of distribution and use, see the accompanying README file.
   59.10 + *
   59.11 + * This file exists to provide a single place to fix any problems with
   59.12 + * including the wrong system include files.  (Common problems are taken
   59.13 + * care of by the standard jconfig symbols, but on really weird systems
   59.14 + * you may have to edit this file.)
   59.15 + *
   59.16 + * NOTE: this file is NOT intended to be included by applications using the
   59.17 + * JPEG library.  Most applications need only include jpeglib.h.
   59.18 + */
   59.19 +
   59.20 +
   59.21 +/* Include auto-config file to find out which system include files we need. */
   59.22 +
   59.23 +#include "jconfig.h"		/* auto configuration options */
   59.24 +#define JCONFIG_INCLUDED	/* so that jpeglib.h doesn't do it again */
   59.25 +
   59.26 +/*
   59.27 + * We need the NULL macro and size_t typedef.
   59.28 + * On an ANSI-conforming system it is sufficient to include <stddef.h>.
   59.29 + * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
   59.30 + * pull in <sys/types.h> as well.
   59.31 + * Note that the core JPEG library does not require <stdio.h>;
   59.32 + * only the default error handler and data source/destination modules do.
   59.33 + * But we must pull it in because of the references to FILE in jpeglib.h.
   59.34 + * You can remove those references if you want to compile without <stdio.h>.
   59.35 + */
   59.36 +
   59.37 +#ifdef HAVE_STDDEF_H
   59.38 +#include <stddef.h>
   59.39 +#endif
   59.40 +
   59.41 +#ifdef HAVE_STDLIB_H
   59.42 +#include <stdlib.h>
   59.43 +#endif
   59.44 +
   59.45 +#ifdef NEED_SYS_TYPES_H
   59.46 +#include <sys/types.h>
   59.47 +#endif
   59.48 +
   59.49 +#include <stdio.h>
   59.50 +
   59.51 +/*
   59.52 + * We need memory copying and zeroing functions, plus strncpy().
   59.53 + * ANSI and System V implementations declare these in <string.h>.
   59.54 + * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
   59.55 + * Some systems may declare memset and memcpy in <memory.h>.
   59.56 + *
   59.57 + * NOTE: we assume the size parameters to these functions are of type size_t.
   59.58 + * Change the casts in these macros if not!
   59.59 + */
   59.60 +
   59.61 +#ifdef NEED_BSD_STRINGS
   59.62 +
   59.63 +#include <strings.h>
   59.64 +#define MEMZERO(target,size)	bzero((void *)(target), (size_t)(size))
   59.65 +#define MEMCOPY(dest,src,size)	bcopy((const void *)(src), (void *)(dest), (size_t)(size))
   59.66 +
   59.67 +#else /* not BSD, assume ANSI/SysV string lib */
   59.68 +
   59.69 +#include <string.h>
   59.70 +#define MEMZERO(target,size)	memset((void *)(target), 0, (size_t)(size))
   59.71 +#define MEMCOPY(dest,src,size)	memcpy((void *)(dest), (const void *)(src), (size_t)(size))
   59.72 +
   59.73 +#endif
   59.74 +
   59.75 +/*
   59.76 + * In ANSI C, and indeed any rational implementation, size_t is also the
   59.77 + * type returned by sizeof().  However, it seems there are some irrational
   59.78 + * implementations out there, in which sizeof() returns an int even though
   59.79 + * size_t is defined as long or unsigned long.  To ensure consistent results
   59.80 + * we always use this SIZEOF() macro in place of using sizeof() directly.
   59.81 + */
   59.82 +
   59.83 +#define SIZEOF(object)	((size_t) sizeof(object))
   59.84 +
   59.85 +/*
   59.86 + * The modules that use fread() and fwrite() always invoke them through
   59.87 + * these macros.  On some systems you may need to twiddle the argument casts.
   59.88 + * CAUTION: argument order is different from underlying functions!
   59.89 + */
   59.90 +
   59.91 +#define JFREAD(file,buf,sizeofbuf)  \
   59.92 +  ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
   59.93 +#define JFWRITE(file,buf,sizeofbuf)  \
   59.94 +  ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
    60.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    60.2 +++ b/libs/libjpeg/jmemmgr.c	Thu Sep 08 06:28:38 2011 +0300
    60.3 @@ -0,0 +1,1118 @@
    60.4 +/*
    60.5 + * jmemmgr.c
    60.6 + *
    60.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    60.8 + * This file is part of the Independent JPEG Group's software.
    60.9 + * For conditions of distribution and use, see the accompanying README file.
   60.10 + *
   60.11 + * This file contains the JPEG system-independent memory management
   60.12 + * routines.  This code is usable across a wide variety of machines; most
   60.13 + * of the system dependencies have been isolated in a separate file.
   60.14 + * The major functions provided here are:
   60.15 + *   * pool-based allocation and freeing of memory;
   60.16 + *   * policy decisions about how to divide available memory among the
   60.17 + *     virtual arrays;
   60.18 + *   * control logic for swapping virtual arrays between main memory and
   60.19 + *     backing storage.
   60.20 + * The separate system-dependent file provides the actual backing-storage
   60.21 + * access code, and it contains the policy decision about how much total
   60.22 + * main memory to use.
   60.23 + * This file is system-dependent in the sense that some of its functions
   60.24 + * are unnecessary in some systems.  For example, if there is enough virtual
   60.25 + * memory so that backing storage will never be used, much of the virtual
   60.26 + * array control logic could be removed.  (Of course, if you have that much
   60.27 + * memory then you shouldn't care about a little bit of unused code...)
   60.28 + */
   60.29 +
   60.30 +#define JPEG_INTERNALS
   60.31 +#define AM_MEMORY_MANAGER	/* we define jvirt_Xarray_control structs */
   60.32 +#include "jinclude.h"
   60.33 +#include "jpeglib.h"
   60.34 +#include "jmemsys.h"		/* import the system-dependent declarations */
   60.35 +
   60.36 +#ifndef NO_GETENV
   60.37 +#ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare getenv() */
   60.38 +extern char * getenv JPP((const char * name));
   60.39 +#endif
   60.40 +#endif
   60.41 +
   60.42 +
   60.43 +/*
   60.44 + * Some important notes:
   60.45 + *   The allocation routines provided here must never return NULL.
   60.46 + *   They should exit to error_exit if unsuccessful.
   60.47 + *
   60.48 + *   It's not a good idea to try to merge the sarray and barray routines,
   60.49 + *   even though they are textually almost the same, because samples are
   60.50 + *   usually stored as bytes while coefficients are shorts or ints.  Thus,
   60.51 + *   in machines where byte pointers have a different representation from
   60.52 + *   word pointers, the resulting machine code could not be the same.
   60.53 + */
   60.54 +
   60.55 +
   60.56 +/*
   60.57 + * Many machines require storage alignment: longs must start on 4-byte
   60.58 + * boundaries, doubles on 8-byte boundaries, etc.  On such machines, malloc()
   60.59 + * always returns pointers that are multiples of the worst-case alignment
   60.60 + * requirement, and we had better do so too.
   60.61 + * There isn't any really portable way to determine the worst-case alignment
   60.62 + * requirement.  This module assumes that the alignment requirement is
   60.63 + * multiples of sizeof(ALIGN_TYPE).
   60.64 + * By default, we define ALIGN_TYPE as double.  This is necessary on some
   60.65 + * workstations (where doubles really do need 8-byte alignment) and will work
   60.66 + * fine on nearly everything.  If your machine has lesser alignment needs,
   60.67 + * you can save a few bytes by making ALIGN_TYPE smaller.
   60.68 + * The only place I know of where this will NOT work is certain Macintosh
   60.69 + * 680x0 compilers that define double as a 10-byte IEEE extended float.
   60.70 + * Doing 10-byte alignment is counterproductive because longwords won't be
   60.71 + * aligned well.  Put "#define ALIGN_TYPE long" in jconfig.h if you have
   60.72 + * such a compiler.
   60.73 + */
   60.74 +
   60.75 +#ifndef ALIGN_TYPE		/* so can override from jconfig.h */
   60.76 +#define ALIGN_TYPE  double
   60.77 +#endif
   60.78 +
   60.79 +
   60.80 +/*
   60.81 + * We allocate objects from "pools", where each pool is gotten with a single
   60.82 + * request to jpeg_get_small() or jpeg_get_large().  There is no per-object
   60.83 + * overhead within a pool, except for alignment padding.  Each pool has a
   60.84 + * header with a link to the next pool of the same class.
   60.85 + * Small and large pool headers are identical except that the latter's
   60.86 + * link pointer must be FAR on 80x86 machines.
   60.87 + * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
   60.88 + * field.  This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
   60.89 + * of the alignment requirement of ALIGN_TYPE.
   60.90 + */
   60.91 +
   60.92 +typedef union small_pool_struct * small_pool_ptr;
   60.93 +
   60.94 +typedef union small_pool_struct {
   60.95 +  struct {
   60.96 +    small_pool_ptr next;	/* next in list of pools */
   60.97 +    size_t bytes_used;		/* how many bytes already used within pool */
   60.98 +    size_t bytes_left;		/* bytes still available in this pool */
   60.99 +  } hdr;
  60.100 +  ALIGN_TYPE dummy;		/* included in union to ensure alignment */
  60.101 +} small_pool_hdr;
  60.102 +
  60.103 +typedef union large_pool_struct FAR * large_pool_ptr;
  60.104 +
  60.105 +typedef union large_pool_struct {
  60.106 +  struct {
  60.107 +    large_pool_ptr next;	/* next in list of pools */
  60.108 +    size_t bytes_used;		/* how many bytes already used within pool */
  60.109 +    size_t bytes_left;		/* bytes still available in this pool */
  60.110 +  } hdr;
  60.111 +  ALIGN_TYPE dummy;		/* included in union to ensure alignment */
  60.112 +} large_pool_hdr;
  60.113 +
  60.114 +
  60.115 +/*
  60.116 + * Here is the full definition of a memory manager object.
  60.117 + */
  60.118 +
  60.119 +typedef struct {
  60.120 +  struct jpeg_memory_mgr pub;	/* public fields */
  60.121 +
  60.122 +  /* Each pool identifier (lifetime class) names a linked list of pools. */
  60.123 +  small_pool_ptr small_list[JPOOL_NUMPOOLS];
  60.124 +  large_pool_ptr large_list[JPOOL_NUMPOOLS];
  60.125 +
  60.126 +  /* Since we only have one lifetime class of virtual arrays, only one
  60.127 +   * linked list is necessary (for each datatype).  Note that the virtual
  60.128 +   * array control blocks being linked together are actually stored somewhere
  60.129 +   * in the small-pool list.
  60.130 +   */
  60.131 +  jvirt_sarray_ptr virt_sarray_list;
  60.132 +  jvirt_barray_ptr virt_barray_list;
  60.133 +
  60.134 +  /* This counts total space obtained from jpeg_get_small/large */
  60.135 +  long total_space_allocated;
  60.136 +
  60.137 +  /* alloc_sarray and alloc_barray set this value for use by virtual
  60.138 +   * array routines.
  60.139 +   */
  60.140 +  JDIMENSION last_rowsperchunk;	/* from most recent alloc_sarray/barray */
  60.141 +} my_memory_mgr;
  60.142 +
  60.143 +typedef my_memory_mgr * my_mem_ptr;
  60.144 +
  60.145 +
  60.146 +/*
  60.147 + * The control blocks for virtual arrays.
  60.148 + * Note that these blocks are allocated in the "small" pool area.
  60.149 + * System-dependent info for the associated backing store (if any) is hidden
  60.150 + * inside the backing_store_info struct.
  60.151 + */
  60.152 +
  60.153 +struct jvirt_sarray_control {
  60.154 +  JSAMPARRAY mem_buffer;	/* => the in-memory buffer */
  60.155 +  JDIMENSION rows_in_array;	/* total virtual array height */
  60.156 +  JDIMENSION samplesperrow;	/* width of array (and of memory buffer) */
  60.157 +  JDIMENSION maxaccess;		/* max rows accessed by access_virt_sarray */
  60.158 +  JDIMENSION rows_in_mem;	/* height of memory buffer */
  60.159 +  JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
  60.160 +  JDIMENSION cur_start_row;	/* first logical row # in the buffer */
  60.161 +  JDIMENSION first_undef_row;	/* row # of first uninitialized row */
  60.162 +  boolean pre_zero;		/* pre-zero mode requested? */
  60.163 +  boolean dirty;		/* do current buffer contents need written? */
  60.164 +  boolean b_s_open;		/* is backing-store data valid? */
  60.165 +  jvirt_sarray_ptr next;	/* link to next virtual sarray control block */
  60.166 +  backing_store_info b_s_info;	/* System-dependent control info */
  60.167 +};
  60.168 +
  60.169 +struct jvirt_barray_control {
  60.170 +  JBLOCKARRAY mem_buffer;	/* => the in-memory buffer */
  60.171 +  JDIMENSION rows_in_array;	/* total virtual array height */
  60.172 +  JDIMENSION blocksperrow;	/* width of array (and of memory buffer) */
  60.173 +  JDIMENSION maxaccess;		/* max rows accessed by access_virt_barray */
  60.174 +  JDIMENSION rows_in_mem;	/* height of memory buffer */
  60.175 +  JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
  60.176 +  JDIMENSION cur_start_row;	/* first logical row # in the buffer */
  60.177 +  JDIMENSION first_undef_row;	/* row # of first uninitialized row */
  60.178 +  boolean pre_zero;		/* pre-zero mode requested? */
  60.179 +  boolean dirty;		/* do current buffer contents need written? */
  60.180 +  boolean b_s_open;		/* is backing-store data valid? */
  60.181 +  jvirt_barray_ptr next;	/* link to next virtual barray control block */
  60.182 +  backing_store_info b_s_info;	/* System-dependent control info */
  60.183 +};
  60.184 +
  60.185 +
  60.186 +#ifdef MEM_STATS		/* optional extra stuff for statistics */
  60.187 +
  60.188 +LOCAL(void)
  60.189 +print_mem_stats (j_common_ptr cinfo, int pool_id)
  60.190 +{
  60.191 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  60.192 +  small_pool_ptr shdr_ptr;
  60.193 +  large_pool_ptr lhdr_ptr;
  60.194 +
  60.195 +  /* Since this is only a debugging stub, we can cheat a little by using
  60.196 +   * fprintf directly rather than going through the trace message code.
  60.197 +   * This is helpful because message parm array can't handle longs.
  60.198 +   */
  60.199 +  fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  60.200 +	  pool_id, mem->total_space_allocated);
  60.201 +
  60.202 +  for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  60.203 +       lhdr_ptr = lhdr_ptr->hdr.next) {
  60.204 +    fprintf(stderr, "  Large chunk used %ld\n",
  60.205 +	    (long) lhdr_ptr->hdr.bytes_used);
  60.206 +  }
  60.207 +
  60.208 +  for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  60.209 +       shdr_ptr = shdr_ptr->hdr.next) {
  60.210 +    fprintf(stderr, "  Small chunk used %ld free %ld\n",
  60.211 +	    (long) shdr_ptr->hdr.bytes_used,
  60.212 +	    (long) shdr_ptr->hdr.bytes_left);
  60.213 +  }
  60.214 +}
  60.215 +
  60.216 +#endif /* MEM_STATS */
  60.217 +
  60.218 +
  60.219 +LOCAL(void)
  60.220 +out_of_memory (j_common_ptr cinfo, int which)
  60.221 +/* Report an out-of-memory error and stop execution */
  60.222 +/* If we compiled MEM_STATS support, report alloc requests before dying */
  60.223 +{
  60.224 +#ifdef MEM_STATS
  60.225 +  cinfo->err->trace_level = 2;	/* force self_destruct to report stats */
  60.226 +#endif
  60.227 +  ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  60.228 +}
  60.229 +
  60.230 +
  60.231 +/*
  60.232 + * Allocation of "small" objects.
  60.233 + *
  60.234 + * For these, we use pooled storage.  When a new pool must be created,
  60.235 + * we try to get enough space for the current request plus a "slop" factor,
  60.236 + * where the slop will be the amount of leftover space in the new pool.
  60.237 + * The speed vs. space tradeoff is largely determined by the slop values.
  60.238 + * A different slop value is provided for each pool class (lifetime),
  60.239 + * and we also distinguish the first pool of a class from later ones.
  60.240 + * NOTE: the values given work fairly well on both 16- and 32-bit-int
  60.241 + * machines, but may be too small if longs are 64 bits or more.
  60.242 + */
  60.243 +
  60.244 +static const size_t first_pool_slop[JPOOL_NUMPOOLS] = 
  60.245 +{
  60.246 +	1600,			/* first PERMANENT pool */
  60.247 +	16000			/* first IMAGE pool */
  60.248 +};
  60.249 +
  60.250 +static const size_t extra_pool_slop[JPOOL_NUMPOOLS] = 
  60.251 +{
  60.252 +	0,			/* additional PERMANENT pools */
  60.253 +	5000			/* additional IMAGE pools */
  60.254 +};
  60.255 +
  60.256 +#define MIN_SLOP  50		/* greater than 0 to avoid futile looping */
  60.257 +
  60.258 +
  60.259 +METHODDEF(void *)
  60.260 +alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  60.261 +/* Allocate a "small" object */
  60.262 +{
  60.263 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  60.264 +  small_pool_ptr hdr_ptr, prev_hdr_ptr;
  60.265 +  char * data_ptr;
  60.266 +  size_t odd_bytes, min_request, slop;
  60.267 +
  60.268 +  /* Check for unsatisfiable request (do now to ensure no overflow below) */
  60.269 +  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  60.270 +    out_of_memory(cinfo, 1);	/* request exceeds malloc's ability */
  60.271 +
  60.272 +  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  60.273 +  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  60.274 +  if (odd_bytes > 0)
  60.275 +    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  60.276 +
  60.277 +  /* See if space is available in any existing pool */
  60.278 +  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  60.279 +    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
  60.280 +  prev_hdr_ptr = NULL;
  60.281 +  hdr_ptr = mem->small_list[pool_id];
  60.282 +  while (hdr_ptr != NULL) {
  60.283 +    if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  60.284 +      break;			/* found pool with enough space */
  60.285 +    prev_hdr_ptr = hdr_ptr;
  60.286 +    hdr_ptr = hdr_ptr->hdr.next;
  60.287 +  }
  60.288 +
  60.289 +  /* Time to make a new pool? */
  60.290 +  if (hdr_ptr == NULL) {
  60.291 +    /* min_request is what we need now, slop is what will be leftover */
  60.292 +    min_request = sizeofobject + SIZEOF(small_pool_hdr);
  60.293 +    if (prev_hdr_ptr == NULL)	/* first pool in class? */
  60.294 +      slop = first_pool_slop[pool_id];
  60.295 +    else
  60.296 +      slop = extra_pool_slop[pool_id];
  60.297 +    /* Don't ask for more than MAX_ALLOC_CHUNK */
  60.298 +    if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  60.299 +      slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  60.300 +    /* Try to get space, if fail reduce slop and try again */
  60.301 +    for (;;) {
  60.302 +      hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  60.303 +      if (hdr_ptr != NULL)
  60.304 +	break;
  60.305 +      slop /= 2;
  60.306 +      if (slop < MIN_SLOP)	/* give up when it gets real small */
  60.307 +	out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  60.308 +    }
  60.309 +    mem->total_space_allocated += min_request + slop;
  60.310 +    /* Success, initialize the new pool header and add to end of list */
  60.311 +    hdr_ptr->hdr.next = NULL;
  60.312 +    hdr_ptr->hdr.bytes_used = 0;
  60.313 +    hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  60.314 +    if (prev_hdr_ptr == NULL)	/* first pool in class? */
  60.315 +      mem->small_list[pool_id] = hdr_ptr;
  60.316 +    else
  60.317 +      prev_hdr_ptr->hdr.next = hdr_ptr;
  60.318 +  }
  60.319 +
  60.320 +  /* OK, allocate the object from the current pool */
  60.321 +  data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  60.322 +  data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  60.323 +  hdr_ptr->hdr.bytes_used += sizeofobject;
  60.324 +  hdr_ptr->hdr.bytes_left -= sizeofobject;
  60.325 +
  60.326 +  return (void *) data_ptr;
  60.327 +}
  60.328 +
  60.329 +
  60.330 +/*
  60.331 + * Allocation of "large" objects.
  60.332 + *
  60.333 + * The external semantics of these are the same as "small" objects,
  60.334 + * except that FAR pointers are used on 80x86.  However the pool
  60.335 + * management heuristics are quite different.  We assume that each
  60.336 + * request is large enough that it may as well be passed directly to
  60.337 + * jpeg_get_large; the pool management just links everything together
  60.338 + * so that we can free it all on demand.
  60.339 + * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  60.340 + * structures.  The routines that create these structures (see below)
  60.341 + * deliberately bunch rows together to ensure a large request size.
  60.342 + */
  60.343 +
  60.344 +METHODDEF(void FAR *)
  60.345 +alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  60.346 +/* Allocate a "large" object */
  60.347 +{
  60.348 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  60.349 +  large_pool_ptr hdr_ptr;
  60.350 +  size_t odd_bytes;
  60.351 +
  60.352 +  /* Check for unsatisfiable request (do now to ensure no overflow below) */
  60.353 +  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  60.354 +    out_of_memory(cinfo, 3);	/* request exceeds malloc's ability */
  60.355 +
  60.356 +  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  60.357 +  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  60.358 +  if (odd_bytes > 0)
  60.359 +    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  60.360 +
  60.361 +  /* Always make a new pool */
  60.362 +  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  60.363 +    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
  60.364 +
  60.365 +  hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  60.366 +					    SIZEOF(large_pool_hdr));
  60.367 +  if (hdr_ptr == NULL)
  60.368 +    out_of_memory(cinfo, 4);	/* jpeg_get_large failed */
  60.369 +  mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  60.370 +
  60.371 +  /* Success, initialize the new pool header and add to list */
  60.372 +  hdr_ptr->hdr.next = mem->large_list[pool_id];
  60.373 +  /* We maintain space counts in each pool header for statistical purposes,
  60.374 +   * even though they are not needed for allocation.
  60.375 +   */
  60.376 +  hdr_ptr->hdr.bytes_used = sizeofobject;
  60.377 +  hdr_ptr->hdr.bytes_left = 0;
  60.378 +  mem->large_list[pool_id] = hdr_ptr;
  60.379 +
  60.380 +  return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  60.381 +}
  60.382 +
  60.383 +
  60.384 +/*
  60.385 + * Creation of 2-D sample arrays.
  60.386 + * The pointers are in near heap, the samples themselves in FAR heap.
  60.387 + *
  60.388 + * To minimize allocation overhead and to allow I/O of large contiguous
  60.389 + * blocks, we allocate the sample rows in groups of as many rows as possible
  60.390 + * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  60.391 + * NB: the virtual array control routines, later in this file, know about
  60.392 + * this chunking of rows.  The rowsperchunk value is left in the mem manager
  60.393 + * object so that it can be saved away if this sarray is the workspace for
  60.394 + * a virtual array.
  60.395 + */
  60.396 +
  60.397 +METHODDEF(JSAMPARRAY)
  60.398 +alloc_sarray (j_common_ptr cinfo, int pool_id,
  60.399 +	      JDIMENSION samplesperrow, JDIMENSION numrows)
  60.400 +/* Allocate a 2-D sample array */
  60.401 +{
  60.402 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  60.403 +  JSAMPARRAY result;
  60.404 +  JSAMPROW workspace;
  60.405 +  JDIMENSION rowsperchunk, currow, i;
  60.406 +  long ltemp;
  60.407 +
  60.408 +  /* Calculate max # of rows allowed in one allocation chunk */
  60.409 +  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  60.410 +	  ((long) samplesperrow * SIZEOF(JSAMPLE));
  60.411 +  if (ltemp <= 0)
  60.412 +    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  60.413 +  if (ltemp < (long) numrows)
  60.414 +    rowsperchunk = (JDIMENSION) ltemp;
  60.415 +  else
  60.416 +    rowsperchunk = numrows;
  60.417 +  mem->last_rowsperchunk = rowsperchunk;
  60.418 +
  60.419 +  /* Get space for row pointers (small object) */
  60.420 +  result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  60.421 +				    (size_t) (numrows * SIZEOF(JSAMPROW)));
  60.422 +
  60.423 +  /* Get the rows themselves (large objects) */
  60.424 +  currow = 0;
  60.425 +  while (currow < numrows) {
  60.426 +    rowsperchunk = MIN(rowsperchunk, numrows - currow);
  60.427 +    workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  60.428 +	(size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  60.429 +		  * SIZEOF(JSAMPLE)));
  60.430 +    for (i = rowsperchunk; i > 0; i--) {
  60.431 +      result[currow++] = workspace;
  60.432 +      workspace += samplesperrow;
  60.433 +    }
  60.434 +  }
  60.435 +
  60.436 +  return result;
  60.437 +}
  60.438 +
  60.439 +
  60.440 +/*
  60.441 + * Creation of 2-D coefficient-block arrays.
  60.442 + * This is essentially the same as the code for sample arrays, above.
  60.443 + */
  60.444 +
  60.445 +METHODDEF(JBLOCKARRAY)
  60.446 +alloc_barray (j_common_ptr cinfo, int pool_id,
  60.447 +	      JDIMENSION blocksperrow, JDIMENSION numrows)
  60.448 +/* Allocate a 2-D coefficient-block array */
  60.449 +{
  60.450 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  60.451 +  JBLOCKARRAY result;
  60.452 +  JBLOCKROW workspace;
  60.453 +  JDIMENSION rowsperchunk, currow, i;
  60.454 +  long ltemp;
  60.455 +
  60.456 +  /* Calculate max # of rows allowed in one allocation chunk */
  60.457 +  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  60.458 +	  ((long) blocksperrow * SIZEOF(JBLOCK));
  60.459 +  if (ltemp <= 0)
  60.460 +    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  60.461 +  if (ltemp < (long) numrows)
  60.462 +    rowsperchunk = (JDIMENSION) ltemp;
  60.463 +  else
  60.464 +    rowsperchunk = numrows;
  60.465 +  mem->last_rowsperchunk = rowsperchunk;
  60.466 +
  60.467 +  /* Get space for row pointers (small object) */
  60.468 +  result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  60.469 +				     (size_t) (numrows * SIZEOF(JBLOCKROW)));
  60.470 +
  60.471 +  /* Get the rows themselves (large objects) */
  60.472 +  currow = 0;
  60.473 +  while (currow < numrows) {
  60.474 +    rowsperchunk = MIN(rowsperchunk, numrows - currow);
  60.475 +    workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  60.476 +	(size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  60.477 +		  * SIZEOF(JBLOCK)));
  60.478 +    for (i = rowsperchunk; i > 0; i--) {
  60.479 +      result[currow++] = workspace;
  60.480 +      workspace += blocksperrow;
  60.481 +    }
  60.482 +  }
  60.483 +
  60.484 +  return result;
  60.485 +}
  60.486 +
  60.487 +
  60.488 +/*
  60.489 + * About virtual array management:
  60.490 + *
  60.491 + * The above "normal" array routines are only used to allocate strip buffers
  60.492 + * (as wide as the image, but just a few rows high).  Full-image-sized buffers
  60.493 + * are handled as "virtual" arrays.  The array is still accessed a strip at a
  60.494 + * time, but the memory manager must save the whole array for repeated
  60.495 + * accesses.  The intended implementation is that there is a strip buffer in
  60.496 + * memory (as high as is possible given the desired memory limit), plus a
  60.497 + * backing file that holds the rest of the array.
  60.498 + *
  60.499 + * The request_virt_array routines are told the total size of the image and
  60.500 + * the maximum number of rows that will be accessed at once.  The in-memory
  60.501 + * buffer must be at least as large as the maxaccess value.
  60.502 + *
  60.503 + * The request routines create control blocks but not the in-memory buffers.
  60.504 + * That is postponed until realize_virt_arrays is called.  At that time the
  60.505 + * total amount of space needed is known (approximately, anyway), so free
  60.506 + * memory can be divided up fairly.
  60.507 + *
  60.508 + * The access_virt_array routines are responsible for making a specific strip
  60.509 + * area accessible (after reading or writing the backing file, if necessary).
  60.510 + * Note that the access routines are told whether the caller intends to modify
  60.511 + * the accessed strip; during a read-only pass this saves having to rewrite
  60.512 + * data to disk.  The access routines are also responsible for pre-zeroing
  60.513 + * any newly accessed rows, if pre-zeroing was requested.
  60.514 + *
  60.515 + * In current usage, the access requests are usually for nonoverlapping
  60.516 + * strips; that is, successive access start_row numbers differ by exactly
  60.517 + * num_rows = maxaccess.  This means we can get good performance with simple
  60.518 + * buffer dump/reload logic, by making the in-memory buffer be a multiple
  60.519 + * of the access height; then there will never be accesses across bufferload
  60.520 + * boundaries.  The code will still work with overlapping access requests,
  60.521 + * but it doesn't handle bufferload overlaps very efficiently.
  60.522 + */
  60.523 +
  60.524 +
  60.525 +METHODDEF(jvirt_sarray_ptr)
  60.526 +request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  60.527 +		     JDIMENSION samplesperrow, JDIMENSION numrows,
  60.528 +		     JDIMENSION maxaccess)
  60.529 +/* Request a virtual 2-D sample array */
  60.530 +{
  60.531 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  60.532 +  jvirt_sarray_ptr result;
  60.533 +
  60.534 +  /* Only IMAGE-lifetime virtual arrays are currently supported */
  60.535 +  if (pool_id != JPOOL_IMAGE)
  60.536 +    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
  60.537 +
  60.538 +  /* get control block */
  60.539 +  result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  60.540 +					  SIZEOF(struct jvirt_sarray_control));
  60.541 +
  60.542 +  result->mem_buffer = NULL;	/* marks array not yet realized */
  60.543 +  result->rows_in_array = numrows;
  60.544 +  result->samplesperrow = samplesperrow;
  60.545 +  result->maxaccess = maxaccess;
  60.546 +  result->pre_zero = pre_zero;
  60.547 +  result->b_s_open = FALSE;	/* no associated backing-store object */
  60.548 +  result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  60.549 +  mem->virt_sarray_list = result;
  60.550 +
  60.551 +  return result;
  60.552 +}
  60.553 +
  60.554 +
  60.555 +METHODDEF(jvirt_barray_ptr)
  60.556 +request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  60.557 +		     JDIMENSION blocksperrow, JDIMENSION numrows,
  60.558 +		     JDIMENSION maxaccess)
  60.559 +/* Request a virtual 2-D coefficient-block array */
  60.560 +{
  60.561 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  60.562 +  jvirt_barray_ptr result;
  60.563 +
  60.564 +  /* Only IMAGE-lifetime virtual arrays are currently supported */
  60.565 +  if (pool_id != JPOOL_IMAGE)
  60.566 +    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
  60.567 +
  60.568 +  /* get control block */
  60.569 +  result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  60.570 +					  SIZEOF(struct jvirt_barray_control));
  60.571 +
  60.572 +  result->mem_buffer = NULL;	/* marks array not yet realized */
  60.573 +  result->rows_in_array = numrows;
  60.574 +  result->blocksperrow = blocksperrow;
  60.575 +  result->maxaccess = maxaccess;
  60.576 +  result->pre_zero = pre_zero;
  60.577 +  result->b_s_open = FALSE;	/* no associated backing-store object */
  60.578 +  result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  60.579 +  mem->virt_barray_list = result;
  60.580 +
  60.581 +  return result;
  60.582 +}
  60.583 +
  60.584 +
  60.585 +METHODDEF(void)
  60.586 +realize_virt_arrays (j_common_ptr cinfo)
  60.587 +/* Allocate the in-memory buffers for any unrealized virtual arrays */
  60.588 +{
  60.589 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  60.590 +  long space_per_minheight, maximum_space, avail_mem;
  60.591 +  long minheights, max_minheights;
  60.592 +  jvirt_sarray_ptr sptr;
  60.593 +  jvirt_barray_ptr bptr;
  60.594 +
  60.595 +  /* Compute the minimum space needed (maxaccess rows in each buffer)
  60.596 +   * and the maximum space needed (full image height in each buffer).
  60.597 +   * These may be of use to the system-dependent jpeg_mem_available routine.
  60.598 +   */
  60.599 +  space_per_minheight = 0;
  60.600 +  maximum_space = 0;
  60.601 +  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  60.602 +    if (sptr->mem_buffer == NULL) { /* if not realized yet */
  60.603 +      space_per_minheight += (long) sptr->maxaccess *
  60.604 +			     (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  60.605 +      maximum_space += (long) sptr->rows_in_array *
  60.606 +		       (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  60.607 +    }
  60.608 +  }
  60.609 +  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  60.610 +    if (bptr->mem_buffer == NULL) { /* if not realized yet */
  60.611 +      space_per_minheight += (long) bptr->maxaccess *
  60.612 +			     (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  60.613 +      maximum_space += (long) bptr->rows_in_array *
  60.614 +		       (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  60.615 +    }
  60.616 +  }
  60.617 +
  60.618 +  if (space_per_minheight <= 0)
  60.619 +    return;			/* no unrealized arrays, no work */
  60.620 +
  60.621 +  /* Determine amount of memory to actually use; this is system-dependent. */
  60.622 +  avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  60.623 +				 mem->total_space_allocated);
  60.624 +
  60.625 +  /* If the maximum space needed is available, make all the buffers full
  60.626 +   * height; otherwise parcel it out with the same number of minheights
  60.627 +   * in each buffer.
  60.628 +   */
  60.629 +  if (avail_mem >= maximum_space)
  60.630 +    max_minheights = 1000000000L;
  60.631 +  else {
  60.632 +    max_minheights = avail_mem / space_per_minheight;
  60.633 +    /* If there doesn't seem to be enough space, try to get the minimum
  60.634 +     * anyway.  This allows a "stub" implementation of jpeg_mem_available().
  60.635 +     */
  60.636 +    if (max_minheights <= 0)
  60.637 +      max_minheights = 1;
  60.638 +  }
  60.639 +
  60.640 +  /* Allocate the in-memory buffers and initialize backing store as needed. */
  60.641 +
  60.642 +  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  60.643 +    if (sptr->mem_buffer == NULL) { /* if not realized yet */
  60.644 +      minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  60.645 +      if (minheights <= max_minheights) {
  60.646 +	/* This buffer fits in memory */
  60.647 +	sptr->rows_in_mem = sptr->rows_in_array;
  60.648 +      } else {
  60.649 +	/* It doesn't fit in memory, create backing store. */
  60.650 +	sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  60.651 +	jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  60.652 +				(long) sptr->rows_in_array *
  60.653 +				(long) sptr->samplesperrow *
  60.654 +				(long) SIZEOF(JSAMPLE));
  60.655 +	sptr->b_s_open = TRUE;
  60.656 +      }
  60.657 +      sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  60.658 +				      sptr->samplesperrow, sptr->rows_in_mem);
  60.659 +      sptr->rowsperchunk = mem->last_rowsperchunk;
  60.660 +      sptr->cur_start_row = 0;
  60.661 +      sptr->first_undef_row = 0;
  60.662 +      sptr->dirty = FALSE;
  60.663 +    }
  60.664 +  }
  60.665 +
  60.666 +  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  60.667 +    if (bptr->mem_buffer == NULL) { /* if not realized yet */
  60.668 +      minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  60.669 +      if (minheights <= max_minheights) {
  60.670 +	/* This buffer fits in memory */
  60.671 +	bptr->rows_in_mem = bptr->rows_in_array;
  60.672 +      } else {
  60.673 +	/* It doesn't fit in memory, create backing store. */
  60.674 +	bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  60.675 +	jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  60.676 +				(long) bptr->rows_in_array *
  60.677 +				(long) bptr->blocksperrow *
  60.678 +				(long) SIZEOF(JBLOCK));
  60.679 +	bptr->b_s_open = TRUE;
  60.680 +      }
  60.681 +      bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  60.682 +				      bptr->blocksperrow, bptr->rows_in_mem);
  60.683 +      bptr->rowsperchunk = mem->last_rowsperchunk;
  60.684 +      bptr->cur_start_row = 0;
  60.685 +      bptr->first_undef_row = 0;
  60.686 +      bptr->dirty = FALSE;
  60.687 +    }
  60.688 +  }
  60.689 +}
  60.690 +
  60.691 +
  60.692 +LOCAL(void)
  60.693 +do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  60.694 +/* Do backing store read or write of a virtual sample array */
  60.695 +{
  60.696 +  long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  60.697 +
  60.698 +  bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  60.699 +  file_offset = ptr->cur_start_row * bytesperrow;
  60.700 +  /* Loop to read or write each allocation chunk in mem_buffer */
  60.701 +  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  60.702 +    /* One chunk, but check for short chunk at end of buffer */
  60.703 +    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  60.704 +    /* Transfer no more than is currently defined */
  60.705 +    thisrow = (long) ptr->cur_start_row + i;
  60.706 +    rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  60.707 +    /* Transfer no more than fits in file */
  60.708 +    rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  60.709 +    if (rows <= 0)		/* this chunk might be past end of file! */
  60.710 +      break;
  60.711 +    byte_count = rows * bytesperrow;
  60.712 +    if (writing)
  60.713 +      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  60.714 +					    (void FAR *) ptr->mem_buffer[i],
  60.715 +					    file_offset, byte_count);
  60.716 +    else
  60.717 +      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  60.718 +					   (void FAR *) ptr->mem_buffer[i],
  60.719 +					   file_offset, byte_count);
  60.720 +    file_offset += byte_count;
  60.721 +  }
  60.722 +}
  60.723 +
  60.724 +
  60.725 +LOCAL(void)
  60.726 +do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  60.727 +/* Do backing store read or write of a virtual coefficient-block array */
  60.728 +{
  60.729 +  long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  60.730 +
  60.731 +  bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  60.732 +  file_offset = ptr->cur_start_row * bytesperrow;
  60.733 +  /* Loop to read or write each allocation chunk in mem_buffer */
  60.734 +  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  60.735 +    /* One chunk, but check for short chunk at end of buffer */
  60.736 +    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  60.737 +    /* Transfer no more than is currently defined */
  60.738 +    thisrow = (long) ptr->cur_start_row + i;
  60.739 +    rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  60.740 +    /* Transfer no more than fits in file */
  60.741 +    rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  60.742 +    if (rows <= 0)		/* this chunk might be past end of file! */
  60.743 +      break;
  60.744 +    byte_count = rows * bytesperrow;
  60.745 +    if (writing)
  60.746 +      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  60.747 +					    (void FAR *) ptr->mem_buffer[i],
  60.748 +					    file_offset, byte_count);
  60.749 +    else
  60.750 +      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  60.751 +					   (void FAR *) ptr->mem_buffer[i],
  60.752 +					   file_offset, byte_count);
  60.753 +    file_offset += byte_count;
  60.754 +  }
  60.755 +}
  60.756 +
  60.757 +
  60.758 +METHODDEF(JSAMPARRAY)
  60.759 +access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  60.760 +		    JDIMENSION start_row, JDIMENSION num_rows,
  60.761 +		    boolean writable)
  60.762 +/* Access the part of a virtual sample array starting at start_row */
  60.763 +/* and extending for num_rows rows.  writable is true if  */
  60.764 +/* caller intends to modify the accessed area. */
  60.765 +{
  60.766 +  JDIMENSION end_row = start_row + num_rows;
  60.767 +  JDIMENSION undef_row;
  60.768 +
  60.769 +  /* debugging check */
  60.770 +  if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  60.771 +      ptr->mem_buffer == NULL)
  60.772 +    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  60.773 +
  60.774 +  /* Make the desired part of the virtual array accessible */
  60.775 +  if (start_row < ptr->cur_start_row ||
  60.776 +      end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  60.777 +    if (! ptr->b_s_open)
  60.778 +      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  60.779 +    /* Flush old buffer contents if necessary */
  60.780 +    if (ptr->dirty) {
  60.781 +      do_sarray_io(cinfo, ptr, TRUE);
  60.782 +      ptr->dirty = FALSE;
  60.783 +    }
  60.784 +    /* Decide what part of virtual array to access.
  60.785 +     * Algorithm: if target address > current window, assume forward scan,
  60.786 +     * load starting at target address.  If target address < current window,
  60.787 +     * assume backward scan, load so that target area is top of window.
  60.788 +     * Note that when switching from forward write to forward read, will have
  60.789 +     * start_row = 0, so the limiting case applies and we load from 0 anyway.
  60.790 +     */
  60.791 +    if (start_row > ptr->cur_start_row) {
  60.792 +      ptr->cur_start_row = start_row;
  60.793 +    } else {
  60.794 +      /* use long arithmetic here to avoid overflow & unsigned problems */
  60.795 +      long ltemp;
  60.796 +
  60.797 +      ltemp = (long) end_row - (long) ptr->rows_in_mem;
  60.798 +      if (ltemp < 0)
  60.799 +	ltemp = 0;		/* don't fall off front end of file */
  60.800 +      ptr->cur_start_row = (JDIMENSION) ltemp;
  60.801 +    }
  60.802 +    /* Read in the selected part of the array.
  60.803 +     * During the initial write pass, we will do no actual read
  60.804 +     * because the selected part is all undefined.
  60.805 +     */
  60.806 +    do_sarray_io(cinfo, ptr, FALSE);
  60.807 +  }
  60.808 +  /* Ensure the accessed part of the array is defined; prezero if needed.
  60.809 +   * To improve locality of access, we only prezero the part of the array
  60.810 +   * that the caller is about to access, not the entire in-memory array.
  60.811 +   */
  60.812 +  if (ptr->first_undef_row < end_row) {
  60.813 +    if (ptr->first_undef_row < start_row) {
  60.814 +      if (writable)		/* writer skipped over a section of array */
  60.815 +	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  60.816 +      undef_row = start_row;	/* but reader is allowed to read ahead */
  60.817 +    } else {
  60.818 +      undef_row = ptr->first_undef_row;
  60.819 +    }
  60.820 +    if (writable)
  60.821 +      ptr->first_undef_row = end_row;
  60.822 +    if (ptr->pre_zero) {
  60.823 +      size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  60.824 +      undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  60.825 +      end_row -= ptr->cur_start_row;
  60.826 +      while (undef_row < end_row) {
  60.827 +	jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  60.828 +	undef_row++;
  60.829 +      }
  60.830 +    } else {
  60.831 +      if (! writable)		/* reader looking at undefined data */
  60.832 +	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  60.833 +    }
  60.834 +  }
  60.835 +  /* Flag the buffer dirty if caller will write in it */
  60.836 +  if (writable)
  60.837 +    ptr->dirty = TRUE;
  60.838 +  /* Return address of proper part of the buffer */
  60.839 +  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  60.840 +}
  60.841 +
  60.842 +
  60.843 +METHODDEF(JBLOCKARRAY)
  60.844 +access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  60.845 +		    JDIMENSION start_row, JDIMENSION num_rows,
  60.846 +		    boolean writable)
  60.847 +/* Access the part of a virtual block array starting at start_row */
  60.848 +/* and extending for num_rows rows.  writable is true if  */
  60.849 +/* caller intends to modify the accessed area. */
  60.850 +{
  60.851 +  JDIMENSION end_row = start_row + num_rows;
  60.852 +  JDIMENSION undef_row;
  60.853 +
  60.854 +  /* debugging check */
  60.855 +  if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  60.856 +      ptr->mem_buffer == NULL)
  60.857 +    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  60.858 +
  60.859 +  /* Make the desired part of the virtual array accessible */
  60.860 +  if (start_row < ptr->cur_start_row ||
  60.861 +      end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  60.862 +    if (! ptr->b_s_open)
  60.863 +      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  60.864 +    /* Flush old buffer contents if necessary */
  60.865 +    if (ptr->dirty) {
  60.866 +      do_barray_io(cinfo, ptr, TRUE);
  60.867 +      ptr->dirty = FALSE;
  60.868 +    }
  60.869 +    /* Decide what part of virtual array to access.
  60.870 +     * Algorithm: if target address > current window, assume forward scan,
  60.871 +     * load starting at target address.  If target address < current window,
  60.872 +     * assume backward scan, load so that target area is top of window.
  60.873 +     * Note that when switching from forward write to forward read, will have
  60.874 +     * start_row = 0, so the limiting case applies and we load from 0 anyway.
  60.875 +     */
  60.876 +    if (start_row > ptr->cur_start_row) {
  60.877 +      ptr->cur_start_row = start_row;
  60.878 +    } else {
  60.879 +      /* use long arithmetic here to avoid overflow & unsigned problems */
  60.880 +      long ltemp;
  60.881 +
  60.882 +      ltemp = (long) end_row - (long) ptr->rows_in_mem;
  60.883 +      if (ltemp < 0)
  60.884 +	ltemp = 0;		/* don't fall off front end of file */
  60.885 +      ptr->cur_start_row = (JDIMENSION) ltemp;
  60.886 +    }
  60.887 +    /* Read in the selected part of the array.
  60.888 +     * During the initial write pass, we will do no actual read
  60.889 +     * because the selected part is all undefined.
  60.890 +     */
  60.891 +    do_barray_io(cinfo, ptr, FALSE);
  60.892 +  }
  60.893 +  /* Ensure the accessed part of the array is defined; prezero if needed.
  60.894 +   * To improve locality of access, we only prezero the part of the array
  60.895 +   * that the caller is about to access, not the entire in-memory array.
  60.896 +   */
  60.897 +  if (ptr->first_undef_row < end_row) {
  60.898 +    if (ptr->first_undef_row < start_row) {
  60.899 +      if (writable)		/* writer skipped over a section of array */
  60.900 +	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  60.901 +      undef_row = start_row;	/* but reader is allowed to read ahead */
  60.902 +    } else {
  60.903 +      undef_row = ptr->first_undef_row;
  60.904 +    }
  60.905 +    if (writable)
  60.906 +      ptr->first_undef_row = end_row;
  60.907 +    if (ptr->pre_zero) {
  60.908 +      size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  60.909 +      undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  60.910 +      end_row -= ptr->cur_start_row;
  60.911 +      while (undef_row < end_row) {
  60.912 +	jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  60.913 +	undef_row++;
  60.914 +      }
  60.915 +    } else {
  60.916 +      if (! writable)		/* reader looking at undefined data */
  60.917 +	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  60.918 +    }
  60.919 +  }
  60.920 +  /* Flag the buffer dirty if caller will write in it */
  60.921 +  if (writable)
  60.922 +    ptr->dirty = TRUE;
  60.923 +  /* Return address of proper part of the buffer */
  60.924 +  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  60.925 +}
  60.926 +
  60.927 +
  60.928 +/*
  60.929 + * Release all objects belonging to a specified pool.
  60.930 + */
  60.931 +
  60.932 +METHODDEF(void)
  60.933 +free_pool (j_common_ptr cinfo, int pool_id)
  60.934 +{
  60.935 +  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  60.936 +  small_pool_ptr shdr_ptr;
  60.937 +  large_pool_ptr lhdr_ptr;
  60.938 +  size_t space_freed;
  60.939 +
  60.940 +  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  60.941 +    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
  60.942 +
  60.943 +#ifdef MEM_STATS
  60.944 +  if (cinfo->err->trace_level > 1)
  60.945 +    print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  60.946 +#endif
  60.947 +
  60.948 +  /* If freeing IMAGE pool, close any virtual arrays first */
  60.949 +  if (pool_id == JPOOL_IMAGE) {
  60.950 +    jvirt_sarray_ptr sptr;
  60.951 +    jvirt_barray_ptr bptr;
  60.952 +
  60.953 +    for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  60.954 +      if (sptr->b_s_open) {	/* there may be no backing store */
  60.955 +	sptr->b_s_open = FALSE;	/* prevent recursive close if error */
  60.956 +	(*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  60.957 +      }
  60.958 +    }
  60.959 +    mem->virt_sarray_list = NULL;
  60.960 +    for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  60.961 +      if (bptr->b_s_open) {	/* there may be no backing store */
  60.962 +	bptr->b_s_open = FALSE;	/* prevent recursive close if error */
  60.963 +	(*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  60.964 +      }
  60.965 +    }
  60.966 +    mem->virt_barray_list = NULL;
  60.967 +  }
  60.968 +
  60.969 +  /* Release large objects */
  60.970 +  lhdr_ptr = mem->large_list[pool_id];
  60.971 +  mem->large_list[pool_id] = NULL;
  60.972 +
  60.973 +  while (lhdr_ptr != NULL) {
  60.974 +    large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  60.975 +    space_freed = lhdr_ptr->hdr.bytes_used +
  60.976 +		  lhdr_ptr->hdr.bytes_left +
  60.977 +		  SIZEOF(large_pool_hdr);
  60.978 +    jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  60.979 +    mem->total_space_allocated -= space_freed;
  60.980 +    lhdr_ptr = next_lhdr_ptr;
  60.981 +  }
  60.982 +
  60.983 +  /* Release small objects */
  60.984 +  shdr_ptr = mem->small_list[pool_id];
  60.985 +  mem->small_list[pool_id] = NULL;
  60.986 +
  60.987 +  while (shdr_ptr != NULL) {
  60.988 +    small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  60.989 +    space_freed = shdr_ptr->hdr.bytes_used +
  60.990 +		  shdr_ptr->hdr.bytes_left +
  60.991 +		  SIZEOF(small_pool_hdr);
  60.992 +    jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  60.993 +    mem->total_space_allocated -= space_freed;
  60.994 +    shdr_ptr = next_shdr_ptr;
  60.995 +  }
  60.996 +}
  60.997 +
  60.998 +
  60.999 +/*
 60.1000 + * Close up shop entirely.
 60.1001 + * Note that this cannot be called unless cinfo->mem is non-NULL.
 60.1002 + */
 60.1003 +
 60.1004 +METHODDEF(void)
 60.1005 +self_destruct (j_common_ptr cinfo)
 60.1006 +{
 60.1007 +  int pool;
 60.1008 +
 60.1009 +  /* Close all backing store, release all memory.
 60.1010 +   * Releasing pools in reverse order might help avoid fragmentation
 60.1011 +   * with some (brain-damaged) malloc libraries.
 60.1012 +   */
 60.1013 +  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
 60.1014 +    free_pool(cinfo, pool);
 60.1015 +  }
 60.1016 +
 60.1017 +  /* Release the memory manager control block too. */
 60.1018 +  jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
 60.1019 +  cinfo->mem = NULL;		/* ensures I will be called only once */
 60.1020 +
 60.1021 +  jpeg_mem_term(cinfo);		/* system-dependent cleanup */
 60.1022 +}
 60.1023 +
 60.1024 +
 60.1025 +/*
 60.1026 + * Memory manager initialization.
 60.1027 + * When this is called, only the error manager pointer is valid in cinfo!
 60.1028 + */
 60.1029 +
 60.1030 +GLOBAL(void)
 60.1031 +jinit_memory_mgr (j_common_ptr cinfo)
 60.1032 +{
 60.1033 +  my_mem_ptr mem;
 60.1034 +  long max_to_use;
 60.1035 +  int pool;
 60.1036 +  size_t test_mac;
 60.1037 +
 60.1038 +  cinfo->mem = NULL;		/* for safety if init fails */
 60.1039 +
 60.1040 +  /* Check for configuration errors.
 60.1041 +   * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
 60.1042 +   * doesn't reflect any real hardware alignment requirement.
 60.1043 +   * The test is a little tricky: for X>0, X and X-1 have no one-bits
 60.1044 +   * in common if and only if X is a power of 2, ie has only one one-bit.
 60.1045 +   * Some compilers may give an "unreachable code" warning here; ignore it.
 60.1046 +   */
 60.1047 +  if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
 60.1048 +    ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
 60.1049 +  /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
 60.1050 +   * a multiple of SIZEOF(ALIGN_TYPE).
 60.1051 +   * Again, an "unreachable code" warning may be ignored here.
 60.1052 +   * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
 60.1053 +   */
 60.1054 +  test_mac = (size_t) MAX_ALLOC_CHUNK;
 60.1055 +  if ((long) test_mac != MAX_ALLOC_CHUNK ||
 60.1056 +      (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
 60.1057 +    ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
 60.1058 +
 60.1059 +  max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
 60.1060 +
 60.1061 +  /* Attempt to allocate memory manager's control block */
 60.1062 +  mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
 60.1063 +
 60.1064 +  if (mem == NULL) {
 60.1065 +    jpeg_mem_term(cinfo);	/* system-dependent cleanup */
 60.1066 +    ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
 60.1067 +  }
 60.1068 +
 60.1069 +  /* OK, fill in the method pointers */
 60.1070 +  mem->pub.alloc_small = alloc_small;
 60.1071 +  mem->pub.alloc_large = alloc_large;
 60.1072 +  mem->pub.alloc_sarray = alloc_sarray;
 60.1073 +  mem->pub.alloc_barray = alloc_barray;
 60.1074 +  mem->pub.request_virt_sarray = request_virt_sarray;
 60.1075 +  mem->pub.request_virt_barray = request_virt_barray;
 60.1076 +  mem->pub.realize_virt_arrays = realize_virt_arrays;
 60.1077 +  mem->pub.access_virt_sarray = access_virt_sarray;
 60.1078 +  mem->pub.access_virt_barray = access_virt_barray;
 60.1079 +  mem->pub.free_pool = free_pool;
 60.1080 +  mem->pub.self_destruct = self_destruct;
 60.1081 +
 60.1082 +  /* Make MAX_ALLOC_CHUNK accessible to other modules */
 60.1083 +  mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
 60.1084 +
 60.1085 +  /* Initialize working state */
 60.1086 +  mem->pub.max_memory_to_use = max_to_use;
 60.1087 +
 60.1088 +  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
 60.1089 +    mem->small_list[pool] = NULL;
 60.1090 +    mem->large_list[pool] = NULL;
 60.1091 +  }
 60.1092 +  mem->virt_sarray_list = NULL;
 60.1093 +  mem->virt_barray_list = NULL;
 60.1094 +
 60.1095 +  mem->total_space_allocated = SIZEOF(my_memory_mgr);
 60.1096 +
 60.1097 +  /* Declare ourselves open for business */
 60.1098 +  cinfo->mem = & mem->pub;
 60.1099 +
 60.1100 +  /* Check for an environment variable JPEGMEM; if found, override the
 60.1101 +   * default max_memory setting from jpeg_mem_init.  Note that the
 60.1102 +   * surrounding application may again override this value.
 60.1103 +   * If your system doesn't support getenv(), define NO_GETENV to disable
 60.1104 +   * this feature.
 60.1105 +   */
 60.1106 +#ifndef NO_GETENV
 60.1107 +  { char * memenv;
 60.1108 +
 60.1109 +    if ((memenv = getenv("JPEGMEM")) != NULL) {
 60.1110 +      char ch = 'x';
 60.1111 +
 60.1112 +      if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
 60.1113 +	if (ch == 'm' || ch == 'M')
 60.1114 +	  max_to_use *= 1000L;
 60.1115 +	mem->pub.max_memory_to_use = max_to_use * 1000L;
 60.1116 +      }
 60.1117 +    }
 60.1118 +  }
 60.1119 +#endif
 60.1120 +
 60.1121 +}
    61.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    61.2 +++ b/libs/libjpeg/jmemnobs.c	Thu Sep 08 06:28:38 2011 +0300
    61.3 @@ -0,0 +1,109 @@
    61.4 +/*
    61.5 + * jmemnobs.c
    61.6 + *
    61.7 + * Copyright (C) 1992-1996, Thomas G. Lane.
    61.8 + * This file is part of the Independent JPEG Group's software.
    61.9 + * For conditions of distribution and use, see the accompanying README file.
   61.10 + *
   61.11 + * This file provides a really simple implementation of the system-
   61.12 + * dependent portion of the JPEG memory manager.  This implementation
   61.13 + * assumes that no backing-store files are needed: all required space
   61.14 + * can be obtained from malloc().
   61.15 + * This is very portable in the sense that it'll compile on almost anything,
   61.16 + * but you'd better have lots of main memory (or virtual memory) if you want
   61.17 + * to process big images.
   61.18 + * Note that the max_memory_to_use option is ignored by this implementation.
   61.19 + */
   61.20 +
   61.21 +#define JPEG_INTERNALS
   61.22 +#include "jinclude.h"
   61.23 +#include "jpeglib.h"
   61.24 +#include "jmemsys.h"		/* import the system-dependent declarations */
   61.25 +
   61.26 +#ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare malloc(),free() */
   61.27 +extern void * malloc JPP((size_t size));
   61.28 +extern void free JPP((void *ptr));
   61.29 +#endif
   61.30 +
   61.31 +
   61.32 +/*
   61.33 + * Memory allocation and freeing are controlled by the regular library
   61.34 + * routines malloc() and free().
   61.35 + */
   61.36 +
   61.37 +GLOBAL(void *)
   61.38 +jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
   61.39 +{
   61.40 +  return (void *) malloc(sizeofobject);
   61.41 +}
   61.42 +
   61.43 +GLOBAL(void)
   61.44 +jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
   61.45 +{
   61.46 +  free(object);
   61.47 +}
   61.48 +
   61.49 +
   61.50 +/*
   61.51 + * "Large" objects are treated the same as "small" ones.
   61.52 + * NB: although we include FAR keywords in the routine declarations,
   61.53 + * this file won't actually work in 80x86 small/medium model; at least,
   61.54 + * you probably won't be able to process useful-size images in only 64KB.
   61.55 + */
   61.56 +
   61.57 +GLOBAL(void FAR *)
   61.58 +jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
   61.59 +{
   61.60 +  return (void FAR *) malloc(sizeofobject);
   61.61 +}
   61.62 +
   61.63 +GLOBAL(void)
   61.64 +jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
   61.65 +{
   61.66 +  free(object);
   61.67 +}
   61.68 +
   61.69 +
   61.70 +/*
   61.71 + * This routine computes the total memory space available for allocation.
   61.72 + * Here we always say, "we got all you want bud!"
   61.73 + */
   61.74 +
   61.75 +GLOBAL(long)
   61.76 +jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
   61.77 +		    long max_bytes_needed, long already_allocated)
   61.78 +{
   61.79 +  return max_bytes_needed;
   61.80 +}
   61.81 +
   61.82 +
   61.83 +/*
   61.84 + * Backing store (temporary file) management.
   61.85 + * Since jpeg_mem_available always promised the moon,
   61.86 + * this should never be called and we can just error out.
   61.87 + */
   61.88 +
   61.89 +GLOBAL(void)
   61.90 +jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
   61.91 +			 long total_bytes_needed)
   61.92 +{
   61.93 +  ERREXIT(cinfo, JERR_NO_BACKING_STORE);
   61.94 +}
   61.95 +
   61.96 +
   61.97 +/*
   61.98 + * These routines take care of any system-dependent initialization and
   61.99 + * cleanup required.  Here, there isn't any.
  61.100 + */
  61.101 +
  61.102 +GLOBAL(long)
  61.103 +jpeg_mem_init (j_common_ptr cinfo)
  61.104 +{
  61.105 +  return 0;			/* just set max_memory_to_use to 0 */
  61.106 +}
  61.107 +
  61.108 +GLOBAL(void)
  61.109 +jpeg_mem_term (j_common_ptr cinfo)
  61.110 +{
  61.111 +  /* no work */
  61.112 +}
    62.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    62.2 +++ b/libs/libjpeg/jmemsys.h	Thu Sep 08 06:28:38 2011 +0300
    62.3 @@ -0,0 +1,198 @@
    62.4 +/*
    62.5 + * jmemsys.h
    62.6 + *
    62.7 + * Copyright (C) 1992-1997, Thomas G. Lane.
    62.8 + * This file is part of the Independent JPEG Group's software.
    62.9 + * For conditions of distribution and use, see the accompanying README file.
   62.10 + *
   62.11 + * This include file defines the interface between the system-independent
   62.12 + * and system-dependent portions of the JPEG memory manager.  No other
   62.13 + * modules need include it.  (The system-independent portion is jmemmgr.c;
   62.14 + * there are several different versions of the system-dependent portion.)
   62.15 + *
   62.16 + * This file works as-is for the system-dependent memory managers supplied
   62.17 + * in the IJG distribution.  You may need to modify it if you write a
   62.18 + * custom memory manager.  If system-dependent changes are needed in
   62.19 + * this file, the best method is to #ifdef them based on a configuration
   62.20 + * symbol supplied in jconfig.h, as we have done with USE_MSDOS_MEMMGR
   62.21 + * and USE_MAC_MEMMGR.
   62.22 + */
   62.23 +
   62.24 +
   62.25 +/* Short forms of external names for systems with brain-damaged linkers. */
   62.26 +
   62.27 +#ifdef NEED_SHORT_EXTERNAL_NAMES
   62.28 +#define jpeg_get_small		jGetSmall
   62.29 +#define jpeg_free_small		jFreeSmall
   62.30 +#define jpeg_get_large		jGetLarge
   62.31 +#define jpeg_free_large		jFreeLarge
   62.32 +#define jpeg_mem_available	jMemAvail
   62.33 +#define jpeg_open_backing_store	jOpenBackStore
   62.34 +#define jpeg_mem_init		jMemInit
   62.35 +#define jpeg_mem_term		jMemTerm
   62.36 +#endif /* NEED_SHORT_EXTERNAL_NAMES */
   62.37 +
   62.38 +
   62.39 +/*
   62.40 + * These two functions are used to allocate and release small chunks of
   62.41 + * memory.  (Typically the total amount requested through jpeg_get_small is
   62.42 + * no more than 20K or so; this will be requested in chunks of a few K each.)
   62.43 + * Behavior should be the same as for the standard library functions malloc
   62.44 + * and free; in particular, jpeg_get_small must return NULL on failure.
   62.45 + * On most systems, these ARE malloc and free.  jpeg_free_small is passed the
   62.46 + * size of the object being freed, just in case it's needed.
   62.47 + * On an 80x86 machine using small-data memory model, these manage near heap.
   62.48 + */
   62.49 +
   62.50 +EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
   62.51 +EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
   62.52 +				  size_t sizeofobject));
   62.53 +
   62.54 +/*
   62.55 + * These two functions are used to allocate and release large chunks of
   62.56 + * memory (up to the total free space designated by jpeg_mem_available).
   62.57 + * The interface is the same as above, except that on an 80x86 machine,
   62.58 + * far pointers are used.  On most other machines these are identical to
   62.59 + * the jpeg_get/free_small routines; but we keep them separate anyway,
   62.60 + * in case a different allocation strategy is desirable for large chunks.
   62.61 + */
   62.62 +
   62.63 +EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
   62.64 +				       size_t sizeofobject));
   62.65 +EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
   62.66 +				  size_t sizeofobject));
   62.67 +
   62.68 +/*
   62.69 + * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
   62.70 + * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
   62.71 + * matter, but that case should never come into play).  This macro is needed
   62.72 + * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
   62.73 + * On those machines, we expect that jconfig.h will provide a proper value.
   62.74 + * On machines with 32-bit flat address spaces, any large constant may be used.
   62.75 + *
   62.76 + * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
   62.77 + * size_t and will be a multiple of sizeof(align_type).
   62.78 + */
   62.79 +
   62.80 +#ifndef MAX_ALLOC_CHUNK		/* may be overridden in jconfig.h */
   62.81 +#define MAX_ALLOC_CHUNK  1000000000L
   62.82 +#endif
   62.83 +
   62.84 +/*
   62.85 + * This routine computes the total space still available for allocation by
   62.86 + * jpeg_get_large.  If more space than this is needed, backing store will be
   62.87 + * used.  NOTE: any memory already allocated must not be counted.
   62.88 + *
   62.89 + * There is a minimum space requirement, corresponding to the minimum
   62.90 + * feasible buffer sizes; jmemmgr.c will request that much space even if
   62.91 + * jpeg_mem_available returns zero.  The maximum space needed, enough to hold
   62.92 + * all working storage in memory, is also passed in case it is useful.
   62.93 + * Finally, the total space already allocated is passed.  If no better
   62.94 + * method is available, cinfo->mem->max_memory_to_use - already_allocated
   62.95 + * is often a suitable calculation.
   62.96 + *
   62.97 + * It is OK for jpeg_mem_available to underestimate the space available
   62.98 + * (that'll just lead to more backing-store access than is really necessary).
   62.99 + * However, an overestimate will lead to failure.  Hence it's wise to subtract
  62.100 + * a slop factor from the true available space.  5% should be enough.
  62.101 + *
  62.102 + * On machines with lots of virtual memory, any large constant may be returned.
  62.103 + * Conversely, zero may be returned to always use the minimum amount of memory.
  62.104 + */
  62.105 +
  62.106 +EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  62.107 +				     long min_bytes_needed,
  62.108 +				     long max_bytes_needed,
  62.109 +				     long already_allocated));
  62.110 +
  62.111 +
  62.112 +/*
  62.113 + * This structure holds whatever state is needed to access a single
  62.114 + * backing-store object.  The read/write/close method pointers are called
  62.115 + * by jmemmgr.c to manipulate the backing-store object; all other fields
  62.116 + * are private to the system-dependent backing store routines.
  62.117 + */
  62.118 +
  62.119 +#define TEMP_NAME_LENGTH   64	/* max length of a temporary file's name */
  62.120 +
  62.121 +
  62.122 +#ifdef USE_MSDOS_MEMMGR		/* DOS-specific junk */
  62.123 +
  62.124 +typedef unsigned short XMSH;	/* type of extended-memory handles */
  62.125 +typedef unsigned short EMSH;	/* type of expanded-memory handles */
  62.126 +
  62.127 +typedef union {
  62.128 +  short file_handle;		/* DOS file handle if it's a temp file */
  62.129 +  XMSH xms_handle;		/* handle if it's a chunk of XMS */
  62.130 +  EMSH ems_handle;		/* handle if it's a chunk of EMS */
  62.131 +} handle_union;
  62.132 +
  62.133 +#endif /* USE_MSDOS_MEMMGR */
  62.134 +
  62.135 +#ifdef USE_MAC_MEMMGR		/* Mac-specific junk */
  62.136 +#include <Files.h>
  62.137 +#endif /* USE_MAC_MEMMGR */
  62.138 +
  62.139 +
  62.140 +typedef struct backing_store_struct * backing_store_ptr;
  62.141 +
  62.142 +typedef struct backing_store_struct {
  62.143 +  /* Methods for reading/writing/closing this backing-store object */
  62.144 +  JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  62.145 +				     backing_store_ptr info,
  62.146 +				     void FAR * buffer_address,
  62.147 +				     long file_offset, long byte_count));
  62.148 +  JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  62.149 +				      backing_store_ptr info,
  62.150 +				      void FAR * buffer_address,
  62.151 +				      long file_offset, long byte_count));
  62.152 +  JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  62.153 +				      backing_store_ptr info));
  62.154 +
  62.155 +  /* Private fields for system-dependent backing-store management */
  62.156 +#ifdef USE_MSDOS_MEMMGR
  62.157 +  /* For the MS-DOS manager (jmemdos.c), we need: */
  62.158 +  handle_union handle;		/* reference to backing-store storage object */
  62.159 +  char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  62.160 +#else
  62.161 +#ifdef USE_MAC_MEMMGR
  62.162 +  /* For the Mac manager (jmemmac.c), we need: */
  62.163 +  short temp_file;		/* file reference number to temp file */
  62.164 +  FSSpec tempSpec;		/* the FSSpec for the temp file */
  62.165 +  char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  62.166 +#else
  62.167 +  /* For a typical implementation with temp files, we need: */
  62.168 +  FILE * temp_file;		/* stdio reference to temp file */
  62.169 +  char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  62.170 +#endif
  62.171 +#endif
  62.172 +} backing_store_info;
  62.173 +
  62.174 +
  62.175 +/*
  62.176 + * Initial opening of a backing-store object.  This must fill in the
  62.177 + * read/write/close pointers in the object.  The read/write routines
  62.178 + * may take an error exit if the specified maximum file size is exceeded.
  62.179 + * (If jpeg_mem_available always returns a large value, this routine can
  62.180 + * just take an error exit.)
  62.181 + */
  62.182 +
  62.183 +EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  62.184 +					  backing_store_ptr info,
  62.185 +					  long total_bytes_needed));
  62.186 +
  62.187 +
  62.188 +/*
  62.189 + * These routines take care of any system-dependent initialization and
  62.190 + * cleanup required.  jpeg_mem_init will be called before anything is
  62.191 + * allocated (and, therefore, nothing in cinfo is of use except the error
  62.192 + * manager pointer).  It should return a suitable default value for
  62.193 + * max_memory_to_use; this may subsequently be overridden by the surrounding
  62.194 + * application.  (Note that max_memory_to_use is only important if
  62.195 + * jpeg_mem_available chooses to consult it ... no one else will.)
  62.196 + * jpeg_mem_term may assume that all requested memory has been freed and that
  62.197 + * all opened backing-store objects have been closed.
  62.198 + */
  62.199 +
  62.200 +EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  62.201 +EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
    63.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    63.2 +++ b/libs/libjpeg/jmorecfg.h	Thu Sep 08 06:28:38 2011 +0300
    63.3 @@ -0,0 +1,367 @@
    63.4 +/*
    63.5 + * jmorecfg.h
    63.6 + *
    63.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    63.8 + * This file is part of the Independent JPEG Group's software.
    63.9 + * For conditions of distribution and use, see the accompanying README file.
   63.10 + *
   63.11 + * This file contains additional configuration options that customize the
   63.12 + * JPEG software for special applications or support machine-dependent
   63.13 + * optimizations.  Most users will not need to touch this file.
   63.14 + */
   63.15 +
   63.16 +
   63.17 +/*
   63.18 + * Define BITS_IN_JSAMPLE as either
   63.19 + *   8   for 8-bit sample values (the usual setting)
   63.20 + *   12  for 12-bit sample values
   63.21 + * Only 8 and 12 are legal data precisions for lossy JPEG according to the
   63.22 + * JPEG standard, and the IJG code does not support anything else!
   63.23 + * We do not support run-time selection of data precision, sorry.
   63.24 + */
   63.25 +
   63.26 +#define BITS_IN_JSAMPLE  8	/* use 8 or 12 */
   63.27 +
   63.28 +
   63.29 +/*
   63.30 + * Maximum number of components (color channels) allowed in JPEG image.
   63.31 + * To meet the letter of the JPEG spec, set this to 255.  However, darn
   63.32 + * few applications need more than 4 channels (maybe 5 for CMYK + alpha
   63.33 + * mask).  We recommend 10 as a reasonable compromise; use 4 if you are
   63.34 + * really short on memory.  (Each allowed component costs a hundred or so
   63.35 + * bytes of storage, whether actually used in an image or not.)
   63.36 + */
   63.37 +
   63.38 +#define MAX_COMPONENTS  10	/* maximum number of image components */
   63.39 +
   63.40 +
   63.41 +/*
   63.42 + * Basic data types.
   63.43 + * You may need to change these if you have a machine with unusual data
   63.44 + * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
   63.45 + * or "long" not 32 bits.  We don't care whether "int" is 16 or 32 bits,
   63.46 + * but it had better be at least 16.
   63.47 + */
   63.48 +
   63.49 +/* Representation of a single sample (pixel element value).
   63.50 + * We frequently allocate large arrays of these, so it's important to keep
   63.51 + * them small.  But if you have memory to burn and access to char or short
   63.52 + * arrays is very slow on your hardware, you might want to change these.
   63.53 + */
   63.54 +
   63.55 +#if BITS_IN_JSAMPLE == 8
   63.56 +/* JSAMPLE should be the smallest type that will hold the values 0..255.
   63.57 + * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
   63.58 + */
   63.59 +
   63.60 +#ifdef HAVE_UNSIGNED_CHAR
   63.61 +
   63.62 +typedef unsigned char JSAMPLE;
   63.63 +#define GETJSAMPLE(value)  ((int) (value))
   63.64 +
   63.65 +#else /* not HAVE_UNSIGNED_CHAR */
   63.66 +
   63.67 +typedef char JSAMPLE;
   63.68 +#ifdef CHAR_IS_UNSIGNED
   63.69 +#define GETJSAMPLE(value)  ((int) (value))
   63.70 +#else
   63.71 +#define GETJSAMPLE(value)  ((int) (value) & 0xFF)
   63.72 +#endif /* CHAR_IS_UNSIGNED */
   63.73 +
   63.74 +#endif /* HAVE_UNSIGNED_CHAR */
   63.75 +
   63.76 +#define MAXJSAMPLE	255
   63.77 +#define CENTERJSAMPLE	128
   63.78 +
   63.79 +#endif /* BITS_IN_JSAMPLE == 8 */
   63.80 +
   63.81 +
   63.82 +#if BITS_IN_JSAMPLE == 12
   63.83 +/* JSAMPLE should be the smallest type that will hold the values 0..4095.
   63.84 + * On nearly all machines "short" will do nicely.
   63.85 + */
   63.86 +
   63.87 +typedef short JSAMPLE;
   63.88 +#define GETJSAMPLE(value)  ((int) (value))
   63.89 +
   63.90 +#define MAXJSAMPLE	4095
   63.91 +#define CENTERJSAMPLE	2048
   63.92 +
   63.93 +#endif /* BITS_IN_JSAMPLE == 12 */
   63.94 +
   63.95 +
   63.96 +/* Representation of a DCT frequency coefficient.
   63.97 + * This should be a signed value of at least 16 bits; "short" is usually OK.
   63.98 + * Again, we allocate large arrays of these, but you can change to int
   63.99 + * if you have memory to burn and "short" is really slow.
  63.100 + */
  63.101 +
  63.102 +typedef short JCOEF;
  63.103 +
  63.104 +
  63.105 +/* Compressed datastreams are represented as arrays of JOCTET.
  63.106 + * These must be EXACTLY 8 bits wide, at least once they are written to
  63.107 + * external storage.  Note that when using the stdio data source/destination
  63.108 + * managers, this is also the data type passed to fread/fwrite.
  63.109 + */
  63.110 +
  63.111 +#ifdef HAVE_UNSIGNED_CHAR
  63.112 +
  63.113 +typedef unsigned char JOCTET;
  63.114 +#define GETJOCTET(value)  (value)
  63.115 +
  63.116 +#else /* not HAVE_UNSIGNED_CHAR */
  63.117 +
  63.118 +typedef char JOCTET;
  63.119 +#ifdef CHAR_IS_UNSIGNED
  63.120 +#define GETJOCTET(value)  (value)
  63.121 +#else
  63.122 +#define GETJOCTET(value)  ((value) & 0xFF)
  63.123 +#endif /* CHAR_IS_UNSIGNED */
  63.124 +
  63.125 +#endif /* HAVE_UNSIGNED_CHAR */
  63.126 +
  63.127 +
  63.128 +/* These typedefs are used for various table entries and so forth.
  63.129 + * They must be at least as wide as specified; but making them too big
  63.130 + * won't cost a huge amount of memory, so we don't provide special
  63.131 + * extraction code like we did for JSAMPLE.  (In other words, these
  63.132 + * typedefs live at a different point on the speed/space tradeoff curve.)
  63.133 + */
  63.134 +
  63.135 +/* UINT8 must hold at least the values 0..255. */
  63.136 +
  63.137 +#ifdef HAVE_UNSIGNED_CHAR
  63.138 +typedef unsigned char UINT8;
  63.139 +#else /* not HAVE_UNSIGNED_CHAR */
  63.140 +#ifdef CHAR_IS_UNSIGNED
  63.141 +typedef char UINT8;
  63.142 +#else /* not CHAR_IS_UNSIGNED */
  63.143 +typedef short UINT8;
  63.144 +#endif /* CHAR_IS_UNSIGNED */
  63.145 +#endif /* HAVE_UNSIGNED_CHAR */
  63.146 +
  63.147 +/* UINT16 must hold at least the values 0..65535. */
  63.148 +
  63.149 +#ifdef HAVE_UNSIGNED_SHORT
  63.150 +typedef unsigned short UINT16;
  63.151 +#else /* not HAVE_UNSIGNED_SHORT */
  63.152 +typedef unsigned int UINT16;
  63.153 +#endif /* HAVE_UNSIGNED_SHORT */
  63.154 +
  63.155 +/* INT16 must hold at least the values -32768..32767. */
  63.156 +
  63.157 +#ifndef XMD_H			/* X11/xmd.h correctly defines INT16 */
  63.158 +typedef short INT16;
  63.159 +#endif
  63.160 +
  63.161 +/* INT32 must hold at least signed 32-bit values. */
  63.162 +
  63.163 +#ifndef XMD_H			/* X11/xmd.h correctly defines INT32 */
  63.164 +typedef int INT32;
  63.165 +#endif
  63.166 +
  63.167 +/* Datatype used for image dimensions.  The JPEG standard only supports
  63.168 + * images up to 64K*64K due to 16-bit fields in SOF markers.  Therefore
  63.169 + * "unsigned int" is sufficient on all machines.  However, if you need to
  63.170 + * handle larger images and you don't mind deviating from the spec, you
  63.171 + * can change this datatype.
  63.172 + */
  63.173 +
  63.174 +typedef unsigned int JDIMENSION;
  63.175 +
  63.176 +#define JPEG_MAX_DIMENSION  65500L  /* a tad under 64K to prevent overflows */
  63.177 +
  63.178 +
  63.179 +/* These macros are used in all function definitions and extern declarations.
  63.180 + * You could modify them if you need to change function linkage conventions;
  63.181 + * in particular, you'll need to do that to make the library a Windows DLL.
  63.182 + * Another application is to make all functions global for use with debuggers
  63.183 + * or code profilers that require it.
  63.184 + */
  63.185 +
  63.186 +/* a function called through method pointers: */
  63.187 +#define METHODDEF(type)		static type
  63.188 +/* a function used only in its module: */
  63.189 +#define LOCAL(type)		static type
  63.190 +/* a function referenced thru EXTERNs: */
  63.191 +#define GLOBAL(type)		type
  63.192 +/* a reference to a GLOBAL function: */
  63.193 +#define EXTERN(type)		extern type
  63.194 +
  63.195 +
  63.196 +/* This macro is used to declare a "method", that is, a function pointer.
  63.197 + * We want to supply prototype parameters if the compiler can cope.
  63.198 + * Note that the arglist parameter must be parenthesized!
  63.199 + * Again, you can customize this if you need special linkage keywords.
  63.200 + */
  63.201 +
  63.202 +#ifdef HAVE_PROTOTYPES
  63.203 +#define JMETHOD(type,methodname,arglist)  type (*methodname) arglist
  63.204 +#else
  63.205 +#define JMETHOD(type,methodname,arglist)  type (*methodname) ()
  63.206 +#endif
  63.207 +
  63.208 +
  63.209 +/* Here is the pseudo-keyword for declaring pointers that must be "far"
  63.210 + * on 80x86 machines.  Most of the specialized coding for 80x86 is handled
  63.211 + * by just saying "FAR *" where such a pointer is needed.  In a few places
  63.212 + * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  63.213 + */
  63.214 +
  63.215 +#ifdef FAR
  63.216 +#undef FAR
  63.217 +#endif
  63.218 +
  63.219 +#ifdef NEED_FAR_POINTERS
  63.220 +#define FAR  far
  63.221 +#else
  63.222 +#define FAR
  63.223 +#endif
  63.224 +
  63.225 +
  63.226 +/*
  63.227 + * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  63.228 + * in standard header files.  Or you may have conflicts with application-
  63.229 + * specific header files that you want to include together with these files.
  63.230 + * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  63.231 + */
  63.232 +
  63.233 +#ifndef HAVE_BOOLEAN
  63.234 +typedef int boolean;
  63.235 +#endif
  63.236 +#ifndef FALSE			/* in case these macros already exist */
  63.237 +#define FALSE	0		/* values of boolean */
  63.238 +#endif
  63.239 +#ifndef TRUE
  63.240 +#define TRUE	1
  63.241 +#endif
  63.242 +
  63.243 +
  63.244 +/*
  63.245 + * The remaining options affect code selection within the JPEG library,
  63.246 + * but they don't need to be visible to most applications using the library.
  63.247 + * To minimize application namespace pollution, the symbols won't be
  63.248 + * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  63.249 + */
  63.250 +
  63.251 +#ifdef JPEG_INTERNALS
  63.252 +#define JPEG_INTERNAL_OPTIONS
  63.253 +#endif
  63.254 +
  63.255 +#ifdef JPEG_INTERNAL_OPTIONS
  63.256 +
  63.257 +
  63.258 +/*
  63.259 + * These defines indicate whether to include various optional functions.
  63.260 + * Undefining some of these symbols will produce a smaller but less capable
  63.261 + * library.  Note that you can leave certain source files out of the
  63.262 + * compilation/linking process if you've #undef'd the corresponding symbols.
  63.263 + * (You may HAVE to do that if your compiler doesn't like null source files.)
  63.264 + */
  63.265 +
  63.266 +/* Arithmetic coding is unsupported for legal reasons.  Complaints to IBM. */
  63.267 +
  63.268 +/* Capability options common to encoder and decoder: */
  63.269 +
  63.270 +#define DCT_ISLOW_SUPPORTED	/* slow but accurate integer algorithm */
  63.271 +#define DCT_IFAST_SUPPORTED	/* faster, less accurate integer method */
  63.272 +#define DCT_FLOAT_SUPPORTED	/* floating-point: accurate, fast on fast HW */
  63.273 +
  63.274 +/* Encoder capability options: */
  63.275 +
  63.276 +#undef  C_ARITH_CODING_SUPPORTED    /* Arithmetic coding back end? */
  63.277 +#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  63.278 +#define C_PROGRESSIVE_SUPPORTED	    /* Progressive JPEG? (Requires MULTISCAN)*/
  63.279 +#define ENTROPY_OPT_SUPPORTED	    /* Optimization of entropy coding parms? */
  63.280 +/* Note: if you selected 12-bit data precision, it is dangerous to turn off
  63.281 + * ENTROPY_OPT_SUPPORTED.  The standard Huffman tables are only good for 8-bit
  63.282 + * precision, so jchuff.c normally uses entropy optimization to compute
  63.283 + * usable tables for higher precision.  If you don't want to do optimization,
  63.284 + * you'll have to supply different default Huffman tables.
  63.285 + * The exact same statements apply for progressive JPEG: the default tables
  63.286 + * don't work for progressive mode.  (This may get fixed, however.)
  63.287 + */
  63.288 +#define INPUT_SMOOTHING_SUPPORTED   /* Input image smoothing option? */
  63.289 +
  63.290 +/* Decoder capability options: */
  63.291 +
  63.292 +#undef  D_ARITH_CODING_SUPPORTED    /* Arithmetic coding back end? */
  63.293 +#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  63.294 +#define D_PROGRESSIVE_SUPPORTED	    /* Progressive JPEG? (Requires MULTISCAN)*/
  63.295 +#define SAVE_MARKERS_SUPPORTED	    /* jpeg_save_markers() needed? */
  63.296 +#define BLOCK_SMOOTHING_SUPPORTED   /* Block smoothing? (Progressive only) */
  63.297 +#define IDCT_SCALING_SUPPORTED	    /* Output rescaling via IDCT? */
  63.298 +#undef  UPSAMPLE_SCALING_SUPPORTED  /* Output rescaling at upsample stage? */
  63.299 +#define UPSAMPLE_MERGING_SUPPORTED  /* Fast path for sloppy upsampling? */
  63.300 +#define QUANT_1PASS_SUPPORTED	    /* 1-pass color quantization? */
  63.301 +#define QUANT_2PASS_SUPPORTED	    /* 2-pass color quantization? */
  63.302 +
  63.303 +/* more capability options later, no doubt */
  63.304 +
  63.305 +
  63.306 +/*
  63.307 + * Ordering of RGB data in scanlines passed to or from the application.
  63.308 + * If your application wants to deal with data in the order B,G,R, just
  63.309 + * change these macros.  You can also deal with formats such as R,G,B,X
  63.310 + * (one extra byte per pixel) by changing RGB_PIXELSIZE.  Note that changing
  63.311 + * the offsets will also change the order in which colormap data is organized.
  63.312 + * RESTRICTIONS:
  63.313 + * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  63.314 + * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  63.315 + *    useful if you are using JPEG color spaces other than YCbCr or grayscale.
  63.316 + * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  63.317 + *    is not 3 (they don't understand about dummy color components!).  So you
  63.318 + *    can't use color quantization if you change that value.
  63.319 + */
  63.320 +
  63.321 +#define RGB_RED		0	/* Offset of Red in an RGB scanline element */
  63.322 +#define RGB_GREEN	1	/* Offset of Green */
  63.323 +#define RGB_BLUE	2	/* Offset of Blue */
  63.324 +#define RGB_PIXELSIZE	3	/* JSAMPLEs per RGB scanline element */
  63.325 +
  63.326 +
  63.327 +/* Definitions for speed-related optimizations. */
  63.328 +
  63.329 +
  63.330 +/* If your compiler supports inline functions, define INLINE
  63.331 + * as the inline keyword; otherwise define it as empty.
  63.332 + */
  63.333 +
  63.334 +#ifndef INLINE
  63.335 +#ifdef __GNUC__			/* for instance, GNU C knows about inline */
  63.336 +#define INLINE __inline__
  63.337 +#endif
  63.338 +#ifndef INLINE
  63.339 +#define INLINE			/* default is to define it as empty */
  63.340 +#endif
  63.341 +#endif
  63.342 +
  63.343 +
  63.344 +/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  63.345 + * two 16-bit shorts is faster than multiplying two ints.  Define MULTIPLIER
  63.346 + * as short on such a machine.  MULTIPLIER must be at least 16 bits wide.
  63.347 + */
  63.348 +
  63.349 +#ifndef MULTIPLIER
  63.350 +#define MULTIPLIER  int		/* type for fastest integer multiply */
  63.351 +#endif
  63.352 +
  63.353 +
  63.354 +/* FAST_FLOAT should be either float or double, whichever is done faster
  63.355 + * by your compiler.  (Note that this type is only used in the floating point
  63.356 + * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  63.357 + * Typically, float is faster in ANSI C compilers, while double is faster in
  63.358 + * pre-ANSI compilers (because they insist on converting to double anyway).
  63.359 + * The code below therefore chooses float if we have ANSI-style prototypes.
  63.360 + */
  63.361 +
  63.362 +#ifndef FAST_FLOAT
  63.363 +#ifdef HAVE_PROTOTYPES
  63.364 +#define FAST_FLOAT  float
  63.365 +#else
  63.366 +#define FAST_FLOAT  double
  63.367 +#endif
  63.368 +#endif
  63.369 +
  63.370 +#endif /* JPEG_INTERNAL_OPTIONS */
    64.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    64.2 +++ b/libs/libjpeg/jpegint.h	Thu Sep 08 06:28:38 2011 +0300
    64.3 @@ -0,0 +1,392 @@
    64.4 +/*
    64.5 + * jpegint.h
    64.6 + *
    64.7 + * Copyright (C) 1991-1997, Thomas G. Lane.
    64.8 + * This file is part of the Independent JPEG Group's software.
    64.9 + * For conditions of distribution and use, see the accompanying README file.
   64.10 + *
   64.11 + * This file provides common declarations for the various JPEG modules.
   64.12 + * These declarations are considered internal to the JPEG library; most
   64.13 + * applications using the library shouldn't need to include this file.
   64.14 + */
   64.15 +
   64.16 +
   64.17 +/* Declarations for both compression & decompression */
   64.18 +
   64.19 +typedef enum {			/* Operating modes for buffer controllers */
   64.20 +	JBUF_PASS_THRU,		/* Plain stripwise operation */
   64.21 +	/* Remaining modes require a full-image buffer to have been created */
   64.22 +	JBUF_SAVE_SOURCE,	/* Run source subobject only, save output */
   64.23 +	JBUF_CRANK_DEST,	/* Run dest subobject only, using saved data */
   64.24 +	JBUF_SAVE_AND_PASS	/* Run both subobjects, save output */
   64.25 +} J_BUF_MODE;
   64.26 +
   64.27 +/* Values of global_state field (jdapi.c has some dependencies on ordering!) */
   64.28 +#define CSTATE_START	100	/* after create_compress */
   64.29 +#define CSTATE_SCANNING	101	/* start_compress done, write_scanlines OK */
   64.30 +#define CSTATE_RAW_OK	102	/* start_compress done, write_raw_data OK */
   64.31 +#define CSTATE_WRCOEFS	103	/* jpeg_write_coefficients done */
   64.32 +#define DSTATE_START	200	/* after create_decompress */
   64.33 +#define DSTATE_INHEADER	201	/* reading header markers, no SOS yet */
   64.34 +#define DSTATE_READY	202	/* found SOS, ready for start_decompress */
   64.35 +#define DSTATE_PRELOAD	203	/* reading multiscan file in start_decompress*/
   64.36 +#define DSTATE_PRESCAN	204	/* performing dummy pass for 2-pass quant */
   64.37 +#define DSTATE_SCANNING	205	/* start_decompress done, read_scanlines OK */
   64.38 +#define DSTATE_RAW_OK	206	/* start_decompress done, read_raw_data OK */
   64.39 +#define DSTATE_BUFIMAGE	207	/* expecting jpeg_start_output */
   64.40 +#define DSTATE_BUFPOST	208	/* looking for SOS/EOI in jpeg_finish_output */
   64.41 +#define DSTATE_RDCOEFS	209	/* reading file in jpeg_read_coefficients */
   64.42 +#define DSTATE_STOPPING	210	/* looking for EOI in jpeg_finish_decompress */
   64.43 +
   64.44 +
   64.45 +/* Declarations for compression modules */
   64.46 +
   64.47 +/* Master control module */
   64.48 +struct jpeg_comp_master {
   64.49 +  JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
   64.50 +  JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
   64.51 +  JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
   64.52 +
   64.53 +  /* State variables made visible to other modules */
   64.54 +  boolean call_pass_startup;	/* True if pass_startup must be called */
   64.55 +  boolean is_last_pass;		/* True during last pass */
   64.56 +};
   64.57 +
   64.58 +/* Main buffer control (downsampled-data buffer) */
   64.59 +struct jpeg_c_main_controller {
   64.60 +  JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
   64.61 +  JMETHOD(void, process_data, (j_compress_ptr cinfo,
   64.62 +			       JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
   64.63 +			       JDIMENSION in_rows_avail));
   64.64 +};
   64.65 +
   64.66 +/* Compression preprocessing (downsampling input buffer control) */
   64.67 +struct jpeg_c_prep_controller {
   64.68 +  JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
   64.69 +  JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
   64.70 +				   JSAMPARRAY input_buf,
   64.71 +				   JDIMENSION *in_row_ctr,
   64.72 +				   JDIMENSION in_rows_avail,
   64.73 +				   JSAMPIMAGE output_buf,
   64.74 +				   JDIMENSION *out_row_group_ctr,
   64.75 +				   JDIMENSION out_row_groups_avail));
   64.76 +};
   64.77 +
   64.78 +/* Coefficient buffer control */
   64.79 +struct jpeg_c_coef_controller {
   64.80 +  JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
   64.81 +  JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
   64.82 +				   JSAMPIMAGE input_buf));
   64.83 +};
   64.84 +
   64.85 +/* Colorspace conversion */
   64.86 +struct jpeg_color_converter {
   64.87 +  JMETHOD(void, start_pass, (j_compress_ptr cinfo));
   64.88 +  JMETHOD(void, color_convert, (j_compress_ptr cinfo,
   64.89 +				JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
   64.90 +				JDIMENSION output_row, int num_rows));
   64.91 +};
   64.92 +
   64.93 +/* Downsampling */
   64.94 +struct jpeg_downsampler {
   64.95 +  JMETHOD(void, start_pass, (j_compress_ptr cinfo));
   64.96 +  JMETHOD(void, downsample, (j_compress_ptr cinfo,
   64.97 +			     JSAMPIMAGE input_buf, JDIMENSION in_row_index,
   64.98 +			     JSAMPIMAGE output_buf,
   64.99 +			     JDIMENSION out_row_group_index));
  64.100 +
  64.101 +  boolean need_context_rows;	/* TRUE if need rows above & below */
  64.102 +};
  64.103 +
  64.104 +/* Forward DCT (also controls coefficient quantization) */
  64.105 +struct jpeg_forward_dct {
  64.106 +  JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  64.107 +  /* perhaps this should be an array??? */
  64.108 +  JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  64.109 +			      jpeg_component_info * compptr,
  64.110 +			      JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  64.111 +			      JDIMENSION start_row, JDIMENSION start_col,
  64.112 +			      JDIMENSION num_blocks));
  64.113 +};
  64.114 +
  64.115 +/* Entropy encoding */
  64.116 +struct jpeg_entropy_encoder {
  64.117 +  JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  64.118 +  JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  64.119 +  JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  64.120 +};
  64.121 +
  64.122 +/* Marker writing */
  64.123 +struct jpeg_marker_writer {
  64.124 +  JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  64.125 +  JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  64.126 +  JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  64.127 +  JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  64.128 +  JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  64.129 +  /* These routines are exported to allow insertion of extra markers */
  64.130 +  /* Probably only COM and APPn markers should be written this way */
  64.131 +  JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  64.132 +				      unsigned int datalen));
  64.133 +  JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  64.134 +};
  64.135 +
  64.136 +
  64.137 +/* Declarations for decompression modules */
  64.138 +
  64.139 +/* Master control module */
  64.140 +struct jpeg_decomp_master {
  64.141 +  JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  64.142 +  JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  64.143 +
  64.144 +  /* State variables made visible to other modules */
  64.145 +  boolean is_dummy_pass;	/* True during 1st pass for 2-pass quant */
  64.146 +};
  64.147 +
  64.148 +/* Input control module */
  64.149 +struct jpeg_input_controller {
  64.150 +  JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  64.151 +  JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  64.152 +  JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  64.153 +  JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  64.154 +
  64.155 +  /* State variables made visible to other modules */
  64.156 +  boolean has_multiple_scans;	/* True if file has multiple scans */
  64.157 +  boolean eoi_reached;		/* True when EOI has been consumed */
  64.158 +};
  64.159 +
  64.160 +/* Main buffer control (downsampled-data buffer) */
  64.161 +struct jpeg_d_main_controller {
  64.162 +  JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  64.163 +  JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  64.164 +			       JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  64.165 +			       JDIMENSION out_rows_avail));
  64.166 +};
  64.167 +
  64.168 +/* Coefficient buffer control */
  64.169 +struct jpeg_d_coef_controller {
  64.170 +  JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  64.171 +  JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  64.172 +  JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  64.173 +  JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  64.174 +				 JSAMPIMAGE output_buf));
  64.175 +  /* Pointer to array of coefficient virtual arrays, or NULL if none */
  64.176 +  jvirt_barray_ptr *coef_arrays;
  64.177 +};
  64.178 +
  64.179 +/* Decompression postprocessing (color quantization buffer control) */
  64.180 +struct jpeg_d_post_controller {
  64.181 +  JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  64.182 +  JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  64.183 +				    JSAMPIMAGE input_buf,
  64.184 +				    JDIMENSION *in_row_group_ctr,
  64.185 +				    JDIMENSION in_row_groups_avail,
  64.186 +				    JSAMPARRAY output_buf,
  64.187 +				    JDIMENSION *out_row_ctr,
  64.188 +				    JDIMENSION out_rows_avail));
  64.189 +};
  64.190 +
  64.191 +/* Marker reading & parsing */
  64.192 +struct jpeg_marker_reader {
  64.193 +  JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  64.194 +  /* Read markers until SOS or EOI.
  64.195 +   * Returns same codes as are defined for jpeg_consume_input:
  64.196 +   * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  64.197 +   */
  64.198 +  JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  64.199 +  /* Read a restart marker --- exported for use by entropy decoder only */
  64.200 +  jpeg_marker_parser_method read_restart_marker;
  64.201 +
  64.202 +  /* State of marker reader --- nominally internal, but applications
  64.203 +   * supplying COM or APPn handlers might like to know the state.
  64.204 +   */
  64.205 +  boolean saw_SOI;		/* found SOI? */
  64.206 +  boolean saw_SOF;		/* found SOF? */
  64.207 +  int next_restart_num;		/* next restart number expected (0-7) */
  64.208 +  unsigned int discarded_bytes;	/* # of bytes skipped looking for a marker */
  64.209 +};
  64.210 +
  64.211 +/* Entropy decoding */
  64.212 +struct jpeg_entropy_decoder {
  64.213 +  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  64.214 +  JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  64.215 +				JBLOCKROW *MCU_data));
  64.216 +
  64.217 +  /* This is here to share code between baseline and progressive decoders; */
  64.218 +  /* other modules probably should not use it */
  64.219 +  boolean insufficient_data;	/* set TRUE after emitting warning */
  64.220 +};
  64.221 +
  64.222 +/* Inverse DCT (also performs dequantization) */
  64.223 +typedef JMETHOD(void, inverse_DCT_method_ptr,
  64.224 +		(j_decompress_ptr cinfo, jpeg_component_info * compptr,
  64.225 +		 JCOEFPTR coef_block,
  64.226 +		 JSAMPARRAY output_buf, JDIMENSION output_col));
  64.227 +
  64.228 +struct jpeg_inverse_dct {
  64.229 +  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  64.230 +  /* It is useful to allow each component to have a separate IDCT method. */
  64.231 +  inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  64.232 +};
  64.233 +
  64.234 +/* Upsampling (note that upsampler must also call color converter) */
  64.235 +struct jpeg_upsampler {
  64.236 +  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  64.237 +  JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  64.238 +			   JSAMPIMAGE input_buf,
  64.239 +			   JDIMENSION *in_row_group_ctr,
  64.240 +			   JDIMENSION in_row_groups_avail,
  64.241 +			   JSAMPARRAY output_buf,
  64.242 +			   JDIMENSION *out_row_ctr,
  64.243 +			   JDIMENSION out_rows_avail));
  64.244 +
  64.245 +  boolean need_context_rows;	/* TRUE if need rows above & below */
  64.246 +};
  64.247 +
  64.248 +/* Colorspace conversion */
  64.249 +struct jpeg_color_deconverter {
  64.250 +  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  64.251 +  JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  64.252 +				JSAMPIMAGE input_buf, JDIMENSION input_row,
  64.253 +				JSAMPARRAY output_buf, int num_rows));
  64.254 +};
  64.255 +
  64.256 +/* Color quantization or color precision reduction */
  64.257 +struct jpeg_color_quantizer {
  64.258 +  JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  64.259 +  JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  64.260 +				 JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  64.261 +				 int num_rows));
  64.262 +  JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  64.263 +  JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  64.264 +};
  64.265 +
  64.266 +
  64.267 +/* Miscellaneous useful macros */
  64.268 +
  64.269 +#undef MAX
  64.270 +#define MAX(a,b)	((a) > (b) ? (a) : (b))
  64.271 +#undef MIN
  64.272 +#define MIN(a,b)	((a) < (b) ? (a) : (b))
  64.273 +
  64.274 +
  64.275 +/* We assume that right shift corresponds to signed division by 2 with
  64.276 + * rounding towards minus infinity.  This is correct for typical "arithmetic
  64.277 + * shift" instructions that shift in copies of the sign bit.  But some
  64.278 + * C compilers implement >> with an unsigned shift.  For these machines you
  64.279 + * must define RIGHT_SHIFT_IS_UNSIGNED.
  64.280 + * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  64.281 + * It is only applied with constant shift counts.  SHIFT_TEMPS must be
  64.282 + * included in the variables of any routine using RIGHT_SHIFT.
  64.283 + */
  64.284 +
  64.285 +#ifdef RIGHT_SHIFT_IS_UNSIGNED
  64.286 +#define SHIFT_TEMPS	INT32 shift_temp;
  64.287 +#define RIGHT_SHIFT(x,shft)  \
  64.288 +	((shift_temp = (x)) < 0 ? \
  64.289 +	 (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  64.290 +	 (shift_temp >> (shft)))
  64.291 +#else
  64.292 +#define SHIFT_TEMPS
  64.293 +#define RIGHT_SHIFT(x,shft)	((x) >> (shft))
  64.294 +#endif
  64.295 +
  64.296 +
  64.297 +/* Short forms of external names for systems with brain-damaged linkers. */
  64.298 +
  64.299 +#ifdef NEED_SHORT_EXTERNAL_NAMES
  64.300 +#define jinit_compress_master	jICompress
  64.301 +#define jinit_c_master_control	jICMaster
  64.302 +#define jinit_c_main_controller	jICMainC
  64.303 +#define jinit_c_prep_controller	jICPrepC
  64.304 +#define jinit_c_coef_controller	jICCoefC
  64.305 +#define jinit_color_converter	jICColor
  64.306 +#define jinit_downsampler	jIDownsampler
  64.307 +#define jinit_forward_dct	jIFDCT
  64.308 +#define jinit_huff_encoder	jIHEncoder
  64.309 +#define jinit_phuff_encoder	jIPHEncoder
  64.310 +#define jinit_marker_writer	jIMWriter
  64.311 +#define jinit_master_decompress	jIDMaster
  64.312 +#define jinit_d_main_controller	jIDMainC
  64.313 +#define jinit_d_coef_controller	jIDCoefC
  64.314 +#define jinit_d_post_controller	jIDPostC
  64.315 +#define jinit_input_controller	jIInCtlr
  64.316 +#define jinit_marker_reader	jIMReader
  64.317 +#define jinit_huff_decoder	jIHDecoder
  64.318 +#define jinit_phuff_decoder	jIPHDecoder
  64.319 +#define jinit_inverse_dct	jIIDCT
  64.320 +#define jinit_upsampler		jIUpsampler
  64.321 +#define jinit_color_deconverter	jIDColor
  64.322 +#define jinit_1pass_quantizer	jI1Quant
  64.323 +#define jinit_2pass_quantizer	jI2Quant
  64.324 +#define jinit_merged_upsampler	jIMUpsampler
  64.325 +#define jinit_memory_mgr	jIMemMgr
  64.326 +#define jdiv_round_up		jDivRound
  64.327 +#define jround_up		jRound
  64.328 +#define jcopy_sample_rows	jCopySamples
  64.329 +#define jcopy_block_row		jCopyBlocks
  64.330 +#define jzero_far		jZeroFar
  64.331 +#define jpeg_zigzag_order	jZIGTable
  64.332 +#define jpeg_natural_order	jZAGTable
  64.333 +#endif /* NEED_SHORT_EXTERNAL_NAMES */
  64.334 +
  64.335 +
  64.336 +/* Compression module initialization routines */
  64.337 +EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  64.338 +EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  64.339 +					 boolean transcode_only));
  64.340 +EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  64.341 +					  boolean need_full_buffer));
  64.342 +EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  64.343 +					  boolean need_full_buffer));
  64.344 +EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  64.345 +					  boolean need_full_buffer));
  64.346 +EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  64.347 +EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  64.348 +EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  64.349 +EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  64.350 +EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  64.351 +EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  64.352 +/* Decompression module initialization routines */
  64.353 +EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  64.354 +EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  64.355 +					  boolean need_full_buffer));
  64.356 +EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  64.357 +					  boolean need_full_buffer));
  64.358 +EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  64.359 +					  boolean need_full_buffer));
  64.360 +EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  64.361 +EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  64.362 +EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  64.363 +EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  64.364 +EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  64.365 +EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  64.366 +EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  64.367 +EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  64.368 +EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  64.369 +EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  64.370 +/* Memory manager initialization */
  64.371 +EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  64.372 +
  64.373 +/* Utility routines in jutils.c */
  64.374 +EXTERN(long) jdiv_round_up JPP((long a, long b));
  64.375 +EXTERN(long) jround_up JPP((long a, long b));
  64.376 +EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  64.377 +				    JSAMPARRAY output_array, int dest_row,
  64.378 +				    int num_rows, JDIMENSION num_cols));
  64.379 +EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  64.380 +				  JDIMENSION num_blocks));
  64.381 +EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  64.382 +/* Constant tables in jutils.c */
  64.383 +#if 0				/* This table is not actually needed in v6a */
  64.384 +extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  64.385 +#endif
  64.386 +extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  64.387 +
  64.388 +/* Suppress undefined-structure complaints if necessary. */
  64.389 +
  64.390 +#ifdef INCOMPLETE_TYPES_BROKEN
  64.391 +#ifndef AM_MEMORY_MANAGER	/* only jmemmgr.c defines these */
  64.392 +struct jvirt_sarray_control { long dummy; };
  64.393 +struct jvirt_barray_control { long dummy; };
  64.394 +#endif
  64.395 +#endif /* INCOMPLETE_TYPES_BROKEN */
    65.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    65.2 +++ b/libs/libjpeg/jpeglib.h	Thu Sep 08 06:28:38 2011 +0300
    65.3 @@ -0,0 +1,1096 @@
    65.4 +/*
    65.5 + * jpeglib.h
    65.6 + *
    65.7 + * Copyright (C) 1991-1998, Thomas G. Lane.
    65.8 + * This file is part of the Independent JPEG Group's software.
    65.9 + * For conditions of distribution and use, see the accompanying README file.
   65.10 + *
   65.11 + * This file defines the application interface for the JPEG library.
   65.12 + * Most applications using the library need only include this file,
   65.13 + * and perhaps jerror.h if they want to know the exact error codes.
   65.14 + */
   65.15 +
   65.16 +#ifndef JPEGLIB_H
   65.17 +#define JPEGLIB_H
   65.18 +
   65.19 +/*
   65.20 + * First we include the configuration files that record how this
   65.21 + * installation of the JPEG library is set up.  jconfig.h can be
   65.22 + * generated automatically for many systems.  jmorecfg.h contains
   65.23 + * manual configuration options that most people need not worry about.
   65.24 + */
   65.25 +
   65.26 +#ifndef JCONFIG_INCLUDED	/* in case jinclude.h already did */
   65.27 +#include "jconfig.h"		/* widely used configuration options */
   65.28 +#endif
   65.29 +#include "jmorecfg.h"		/* seldom changed options */
   65.30 +
   65.31 +
   65.32 +/* Version ID for the JPEG library.
   65.33 + * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
   65.34 + */
   65.35 +
   65.36 +#define JPEG_LIB_VERSION  62	/* Version 6b */
   65.37 +
   65.38 +
   65.39 +/* Various constants determining the sizes of things.
   65.40 + * All of these are specified by the JPEG standard, so don't change them
   65.41 + * if you want to be compatible.
   65.42 + */
   65.43 +
   65.44 +#define DCTSIZE		    8	/* The basic DCT block is 8x8 samples */
   65.45 +#define DCTSIZE2	    64	/* DCTSIZE squared; # of elements in a block */
   65.46 +#define NUM_QUANT_TBLS      4	/* Quantization tables are numbered 0..3 */
   65.47 +#define NUM_HUFF_TBLS       4	/* Huffman tables are numbered 0..3 */
   65.48 +#define NUM_ARITH_TBLS      16	/* Arith-coding tables are numbered 0..15 */
   65.49 +#define MAX_COMPS_IN_SCAN   4	/* JPEG limit on # of components in one scan */
   65.50 +#define MAX_SAMP_FACTOR     4	/* JPEG limit on sampling factors */
   65.51 +/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
   65.52 + * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
   65.53 + * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
   65.54 + * to handle it.  We even let you do this from the jconfig.h file.  However,
   65.55 + * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
   65.56 + * sometimes emits noncompliant files doesn't mean you should too.
   65.57 + */
   65.58 +#define C_MAX_BLOCKS_IN_MCU   10 /* compressor's limit on blocks per MCU */
   65.59 +#ifndef D_MAX_BLOCKS_IN_MCU
   65.60 +#define D_MAX_BLOCKS_IN_MCU   10 /* decompressor's limit on blocks per MCU */
   65.61 +#endif
   65.62 +
   65.63 +
   65.64 +/* Data structures for images (arrays of samples and of DCT coefficients).
   65.65 + * On 80x86 machines, the image arrays are too big for near pointers,
   65.66 + * but the pointer arrays can fit in near memory.
   65.67 + */
   65.68 +
   65.69 +typedef JSAMPLE FAR *JSAMPROW;	/* ptr to one image row of pixel samples. */
   65.70 +typedef JSAMPROW *JSAMPARRAY;	/* ptr to some rows (a 2-D sample array) */
   65.71 +typedef JSAMPARRAY *JSAMPIMAGE;	/* a 3-D sample array: top index is color */
   65.72 +
   65.73 +typedef JCOEF JBLOCK[DCTSIZE2];	/* one block of coefficients */
   65.74 +typedef JBLOCK FAR *JBLOCKROW;	/* pointer to one row of coefficient blocks */
   65.75 +typedef JBLOCKROW *JBLOCKARRAY;		/* a 2-D array of coefficient blocks */
   65.76 +typedef JBLOCKARRAY *JBLOCKIMAGE;	/* a 3-D array of coefficient blocks */
   65.77 +
   65.78 +typedef JCOEF FAR *JCOEFPTR;	/* useful in a couple of places */
   65.79 +
   65.80 +
   65.81 +/* Types for JPEG compression parameters and working tables. */
   65.82 +
   65.83 +
   65.84 +/* DCT coefficient quantization tables. */
   65.85 +
   65.86 +typedef struct {
   65.87 +  /* This array gives the coefficient quantizers in natural array order
   65.88 +   * (not the zigzag order in which they are stored in a JPEG DQT marker).
   65.89 +   * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
   65.90 +   */
   65.91 +  UINT16 quantval[DCTSIZE2];	/* quantization step for each coefficient */
   65.92 +  /* This field is used only during compression.  It's initialized FALSE when
   65.93 +   * the table is created, and set TRUE when it's been output to the file.
   65.94 +   * You could suppress output of a table by setting this to TRUE.
   65.95 +   * (See jpeg_suppress_tables for an example.)
   65.96 +   */
   65.97 +  boolean sent_table;		/* TRUE when table has been output */
   65.98 +} JQUANT_TBL;
   65.99 +
  65.100 +
  65.101 +/* Huffman coding tables. */
  65.102 +
  65.103 +typedef struct {
  65.104 +  /* These two fields directly represent the contents of a JPEG DHT marker */
  65.105 +  UINT8 bits[17];		/* bits[k] = # of symbols with codes of */
  65.106 +				/* length k bits; bits[0] is unused */
  65.107 +  UINT8 huffval[256];		/* The symbols, in order of incr code length */
  65.108 +  /* This field is used only during compression.  It's initialized FALSE when
  65.109 +   * the table is created, and set TRUE when it's been output to the file.
  65.110 +   * You could suppress output of a table by setting this to TRUE.
  65.111 +   * (See jpeg_suppress_tables for an example.)
  65.112 +   */
  65.113 +  boolean sent_table;		/* TRUE when table has been output */
  65.114 +} JHUFF_TBL;
  65.115 +
  65.116 +
  65.117 +/* Basic info about one component (color channel). */
  65.118 +
  65.119 +typedef struct {
  65.120 +  /* These values are fixed over the whole image. */
  65.121 +  /* For compression, they must be supplied by parameter setup; */
  65.122 +  /* for decompression, they are read from the SOF marker. */
  65.123 +  int component_id;		/* identifier for this component (0..255) */
  65.124 +  int component_index;		/* its index in SOF or cinfo->comp_info[] */
  65.125 +  int h_samp_factor;		/* horizontal sampling factor (1..4) */
  65.126 +  int v_samp_factor;		/* vertical sampling factor (1..4) */
  65.127 +  int quant_tbl_no;		/* quantization table selector (0..3) */
  65.128 +  /* These values may vary between scans. */
  65.129 +  /* For compression, they must be supplied by parameter setup; */
  65.130 +  /* for decompression, they are read from the SOS marker. */
  65.131 +  /* The decompressor output side may not use these variables. */
  65.132 +  int dc_tbl_no;		/* DC entropy table selector (0..3) */
  65.133 +  int ac_tbl_no;		/* AC entropy table selector (0..3) */
  65.134 +  
  65.135 +  /* Remaining fields should be treated as private by applications. */
  65.136 +  
  65.137 +  /* These values are computed during compression or decompression startup: */
  65.138 +  /* Component's size in DCT blocks.
  65.139 +   * Any dummy blocks added to complete an MCU are not counted; therefore
  65.140 +   * these values do not depend on whether a scan is interleaved or not.
  65.141 +   */
  65.142 +  JDIMENSION width_in_blocks;
  65.143 +  JDIMENSION height_in_blocks;
  65.144 +  /* Size of a DCT block in samples.  Always DCTSIZE for compression.
  65.145 +   * For decompression this is the size of the output from one DCT block,
  65.146 +   * reflecting any scaling we choose to apply during the IDCT step.
  65.147 +   * Values of 1,2,4,8 are likely to be supported.  Note that different
  65.148 +   * components may receive different IDCT scalings.
  65.149 +   */
  65.150 +  int DCT_scaled_size;
  65.151 +  /* The downsampled dimensions are the component's actual, unpadded number
  65.152 +   * of samples at the main buffer (preprocessing/compression interface), thus
  65.153 +   * downsampled_width = ceil(image_width * Hi/Hmax)
  65.154 +   * and similarly for height.  For decompression, IDCT scaling is included, so
  65.155 +   * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  65.156 +   */
  65.157 +  JDIMENSION downsampled_width;	 /* actual width in samples */
  65.158 +  JDIMENSION downsampled_height; /* actual height in samples */
  65.159 +  /* This flag is used only for decompression.  In cases where some of the
  65.160 +   * components will be ignored (eg grayscale output from YCbCr image),
  65.161 +   * we can skip most computations for the unused components.
  65.162 +   */
  65.163 +  boolean component_needed;	/* do we need the value of this component? */
  65.164 +
  65.165 +  /* These values are computed before starting a scan of the component. */
  65.166 +  /* The decompressor output side may not use these variables. */
  65.167 +  int MCU_width;		/* number of blocks per MCU, horizontally */
  65.168 +  int MCU_height;		/* number of blocks per MCU, vertically */
  65.169 +  int MCU_blocks;		/* MCU_width * MCU_height */
  65.170 +  int MCU_sample_width;		/* MCU width in samples, MCU_width*DCT_scaled_size */
  65.171 +  int last_col_width;		/* # of non-dummy blocks across in last MCU */
  65.172 +  int last_row_height;		/* # of non-dummy blocks down in last MCU */
  65.173 +
  65.174 +  /* Saved quantization table for component; NULL if none yet saved.
  65.175 +   * See jdinput.c comments about the need for this information.
  65.176 +   * This field is currently used only for decompression.
  65.177 +   */
  65.178 +  JQUANT_TBL * quant_table;
  65.179 +
  65.180 +  /* Private per-component storage for DCT or IDCT subsystem. */
  65.181 +  void * dct_table;
  65.182 +} jpeg_component_info;
  65.183 +
  65.184 +
  65.185 +/* The script for encoding a multiple-scan file is an array of these: */
  65.186 +
  65.187 +typedef struct {
  65.188 +  int comps_in_scan;		/* number of components encoded in this scan */
  65.189 +  int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  65.190 +  int Ss, Se;			/* progressive JPEG spectral selection parms */
  65.191 +  int Ah, Al;			/* progressive JPEG successive approx. parms */
  65.192 +} jpeg_scan_info;
  65.193 +
  65.194 +/* The decompressor can save APPn and COM markers in a list of these: */
  65.195 +
  65.196 +typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  65.197 +
  65.198 +struct jpeg_marker_struct {
  65.199 +  jpeg_saved_marker_ptr next;	/* next in list, or NULL */
  65.200 +  UINT8 marker;			/* marker code: JPEG_COM, or JPEG_APP0+n */
  65.201 +  unsigned int original_length;	/* # bytes of data in the file */
  65.202 +  unsigned int data_length;	/* # bytes of data saved at data[] */
  65.203 +  JOCTET FAR * data;		/* the data contained in the marker */
  65.204 +  /* the marker length word is not counted in data_length or original_length */
  65.205 +};
  65.206 +
  65.207 +/* Known color spaces. */
  65.208 +
  65.209 +typedef enum {
  65.210 +	JCS_UNKNOWN,		/* error/unspecified */
  65.211 +	JCS_GRAYSCALE,		/* monochrome */
  65.212 +	JCS_RGB,		/* red/green/blue */
  65.213 +	JCS_YCbCr,		/* Y/Cb/Cr (also known as YUV) */
  65.214 +	JCS_CMYK,		/* C/M/Y/K */
  65.215 +	JCS_YCCK		/* Y/Cb/Cr/K */
  65.216 +} J_COLOR_SPACE;
  65.217 +
  65.218 +/* DCT/IDCT algorithm options. */
  65.219 +
  65.220 +typedef enum {
  65.221 +	JDCT_ISLOW,		/* slow but accurate integer algorithm */
  65.222 +	JDCT_IFAST,		/* faster, less accurate integer method */
  65.223 +	JDCT_FLOAT		/* floating-point: accurate, fast on fast HW */
  65.224 +} J_DCT_METHOD;
  65.225 +
  65.226 +#ifndef JDCT_DEFAULT		/* may be overridden in jconfig.h */
  65.227 +#define JDCT_DEFAULT  JDCT_ISLOW
  65.228 +#endif
  65.229 +#ifndef JDCT_FASTEST		/* may be overridden in jconfig.h */
  65.230 +#define JDCT_FASTEST  JDCT_IFAST
  65.231 +#endif
  65.232 +
  65.233 +/* Dithering options for decompression. */
  65.234 +
  65.235 +typedef enum {
  65.236 +	JDITHER_NONE,		/* no dithering */
  65.237 +	JDITHER_ORDERED,	/* simple ordered dither */
  65.238 +	JDITHER_FS		/* Floyd-Steinberg error diffusion dither */
  65.239 +} J_DITHER_MODE;
  65.240 +
  65.241 +
  65.242 +/* Common fields between JPEG compression and decompression master structs. */
  65.243 +
  65.244 +#define jpeg_common_fields \
  65.245 +  struct jpeg_error_mgr * err;	/* Error handler module */\
  65.246 +  struct jpeg_memory_mgr * mem;	/* Memory manager module */\
  65.247 +  struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  65.248 +  void * client_data;		/* Available for use by application */\
  65.249 +  boolean is_decompressor;	/* So common code can tell which is which */\
  65.250 +  int global_state		/* For checking call sequence validity */
  65.251 +
  65.252 +/* Routines that are to be used by both halves of the library are declared
  65.253 + * to receive a pointer to this structure.  There are no actual instances of
  65.254 + * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  65.255 + */
  65.256 +struct jpeg_common_struct {
  65.257 +  jpeg_common_fields;		/* Fields common to both master struct types */
  65.258 +  /* Additional fields follow in an actual jpeg_compress_struct or
  65.259 +   * jpeg_decompress_struct.  All three structs must agree on these
  65.260 +   * initial fields!  (This would be a lot cleaner in C++.)
  65.261 +   */
  65.262 +};
  65.263 +
  65.264 +typedef struct jpeg_common_struct * j_common_ptr;
  65.265 +typedef struct jpeg_compress_struct * j_compress_ptr;
  65.266 +typedef struct jpeg_decompress_struct * j_decompress_ptr;
  65.267 +
  65.268 +
  65.269 +/* Master record for a compression instance */
  65.270 +
  65.271 +struct jpeg_compress_struct {
  65.272 +  jpeg_common_fields;		/* Fields shared with jpeg_decompress_struct */
  65.273 +
  65.274 +  /* Destination for compressed data */
  65.275 +  struct jpeg_destination_mgr * dest;
  65.276 +
  65.277 +  /* Description of source image --- these fields must be filled in by
  65.278 +   * outer application before starting compression.  in_color_space must
  65.279 +   * be correct before you can even call jpeg_set_defaults().
  65.280 +   */
  65.281 +
  65.282 +  JDIMENSION image_width;	/* input image width */
  65.283 +  JDIMENSION image_height;	/* input image height */
  65.284 +  int input_components;		/* # of color components in input image */
  65.285 +  J_COLOR_SPACE in_color_space;	/* colorspace of input image */
  65.286 +
  65.287 +  double input_gamma;		/* image gamma of input image */
  65.288 +
  65.289 +  /* Compression parameters --- these fields must be set before calling
  65.290 +   * jpeg_start_compress().  We recommend calling jpeg_set_defaults() to
  65.291 +   * initialize everything to reasonable defaults, then changing anything
  65.292 +   * the application specifically wants to change.  That way you won't get
  65.293 +   * burnt when new parameters are added.  Also note that there are several
  65.294 +   * helper routines to simplify changing parameters.
  65.295 +   */
  65.296 +
  65.297 +  int data_precision;		/* bits of precision in image data */
  65.298 +
  65.299 +  int num_components;		/* # of color components in JPEG image */
  65.300 +  J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  65.301 +
  65.302 +  jpeg_component_info * comp_info;
  65.303 +  /* comp_info[i] describes component that appears i'th in SOF */
  65.304 +  
  65.305 +  JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  65.306 +  /* ptrs to coefficient quantization tables, or NULL if not defined */
  65.307 +  
  65.308 +  JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  65.309 +  JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  65.310 +  /* ptrs to Huffman coding tables, or NULL if not defined */
  65.311 +  
  65.312 +  UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  65.313 +  UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  65.314 +  UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  65.315 +
  65.316 +  int num_scans;		/* # of entries in scan_info array */
  65.317 +  const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  65.318 +  /* The default value of scan_info is NULL, which causes a single-scan
  65.319 +   * sequential JPEG file to be emitted.  To create a multi-scan file,
  65.320 +   * set num_scans and scan_info to point to an array of scan definitions.
  65.321 +   */
  65.322 +
  65.323 +  boolean raw_data_in;		/* TRUE=caller supplies downsampled data */
  65.324 +  boolean arith_code;		/* TRUE=arithmetic coding, FALSE=Huffman */
  65.325 +  boolean optimize_coding;	/* TRUE=optimize entropy encoding parms */
  65.326 +  boolean CCIR601_sampling;	/* TRUE=first samples are cosited */
  65.327 +  int smoothing_factor;		/* 1..100, or 0 for no input smoothing */
  65.328 +  J_DCT_METHOD dct_method;	/* DCT algorithm selector */
  65.329 +
  65.330 +  /* The restart interval can be specified in absolute MCUs by setting
  65.331 +   * restart_interval, or in MCU rows by setting restart_in_rows
  65.332 +   * (in which case the correct restart_interval will be figured
  65.333 +   * for each scan).
  65.334 +   */
  65.335 +  unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  65.336 +  int restart_in_rows;		/* if > 0, MCU rows per restart interval */
  65.337 +
  65.338 +  /* Parameters controlling emission of special markers. */
  65.339 +
  65.340 +  boolean write_JFIF_header;	/* should a JFIF marker be written? */
  65.341 +  UINT8 JFIF_major_version;	/* What to write for the JFIF version number */
  65.342 +  UINT8 JFIF_minor_version;
  65.343 +  /* These three values are not used by the JPEG code, merely copied */
  65.344 +  /* into the JFIF APP0 marker.  density_unit can be 0 for unknown, */
  65.345 +  /* 1 for dots/inch, or 2 for dots/cm.  Note that the pixel aspect */
  65.346 +  /* ratio is defined by X_density/Y_density even when density_unit=0. */
  65.347 +  UINT8 density_unit;		/* JFIF code for pixel size units */
  65.348 +  UINT16 X_density;		/* Horizontal pixel density */
  65.349 +  UINT16 Y_density;		/* Vertical pixel density */
  65.350 +  boolean write_Adobe_marker;	/* should an Adobe marker be written? */
  65.351 +  
  65.352 +  /* State variable: index of next scanline to be written to
  65.353 +   * jpeg_write_scanlines().  Application may use this to control its
  65.354 +   * processing loop, e.g., "while (next_scanline < image_height)".
  65.355 +   */
  65.356 +
  65.357 +  JDIMENSION next_scanline;	/* 0 .. image_height-1  */
  65.358 +
  65.359 +  /* Remaining fields are known throughout compressor, but generally
  65.360 +   * should not be touched by a surrounding application.
  65.361 +   */
  65.362 +
  65.363 +  /*
  65.364 +   * These fields are computed during compression startup
  65.365 +   */
  65.366 +  boolean progressive_mode;	/* TRUE if scan script uses progressive mode */
  65.367 +  int max_h_samp_factor;	/* largest h_samp_factor */
  65.368 +  int max_v_samp_factor;	/* largest v_samp_factor */
  65.369 +
  65.370 +  JDIMENSION total_iMCU_rows;	/* # of iMCU rows to be input to coef ctlr */
  65.371 +  /* The coefficient controller receives data in units of MCU rows as defined
  65.372 +   * for fully interleaved scans (whether the JPEG file is interleaved or not).
  65.373 +   * There are v_samp_factor * DCTSIZE sample rows of each component in an
  65.374 +   * "iMCU" (interleaved MCU) row.
  65.375 +   */
  65.376 +  
  65.377 +  /*
  65.378 +   * These fields are valid during any one scan.
  65.379 +   * They describe the components and MCUs actually appearing in the scan.
  65.380 +   */
  65.381 +  int comps_in_scan;		/* # of JPEG components in this scan */
  65.382 +  jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  65.383 +  /* *cur_comp_info[i] describes component that appears i'th in SOS */
  65.384 +  
  65.385 +  JDIMENSION MCUs_per_row;	/* # of MCUs across the image */
  65.386 +  JDIMENSION MCU_rows_in_scan;	/* # of MCU rows in the image */
  65.387 +  
  65.388 +  int blocks_in_MCU;		/* # of DCT blocks per MCU */
  65.389 +  int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  65.390 +  /* MCU_membership[i] is index in cur_comp_info of component owning */
  65.391 +  /* i'th block in an MCU */
  65.392 +
  65.393 +  int Ss, Se, Ah, Al;		/* progressive JPEG parameters for scan */
  65.394 +
  65.395 +  /*
  65.396 +   * Links to compression subobjects (methods and private variables of modules)
  65.397 +   */
  65.398 +  struct jpeg_comp_master * master;
  65.399 +  struct jpeg_c_main_controller * main;
  65.400 +  struct jpeg_c_prep_controller * prep;
  65.401 +  struct jpeg_c_coef_controller * coef;
  65.402 +  struct jpeg_marker_writer * marker;
  65.403 +  struct jpeg_color_converter * cconvert;
  65.404 +  struct jpeg_downsampler * downsample;
  65.405 +  struct jpeg_forward_dct * fdct;
  65.406 +  struct jpeg_entropy_encoder * entropy;
  65.407 +  jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  65.408 +  int script_space_size;
  65.409 +};
  65.410 +
  65.411 +
  65.412 +/* Master record for a decompression instance */
  65.413 +
  65.414 +struct jpeg_decompress_struct {
  65.415 +  jpeg_common_fields;		/* Fields shared with jpeg_compress_struct */
  65.416 +
  65.417 +  /* Source of compressed data */
  65.418 +  struct jpeg_source_mgr * src;
  65.419 +
  65.420 +  /* Basic description of image --- filled in by jpeg_read_header(). */
  65.421 +  /* Application may inspect these values to decide how to process image. */
  65.422 +
  65.423 +  JDIMENSION image_width;	/* nominal image width (from SOF marker) */
  65.424 +  JDIMENSION image_height;	/* nominal image height */
  65.425 +  int num_components;		/* # of color components in JPEG image */
  65.426 +  J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  65.427 +
  65.428 +  /* Decompression processing parameters --- these fields must be set before
  65.429 +   * calling jpeg_start_decompress().  Note that jpeg_read_header() initializes
  65.430 +   * them to default values.
  65.431 +   */
  65.432 +
  65.433 +  J_COLOR_SPACE out_color_space; /* colorspace for output */
  65.434 +
  65.435 +  unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  65.436 +
  65.437 +  double output_gamma;		/* image gamma wanted in output */
  65.438 +
  65.439 +  boolean buffered_image;	/* TRUE=multiple output passes */
  65.440 +  boolean raw_data_out;		/* TRUE=downsampled data wanted */
  65.441 +
  65.442 +  J_DCT_METHOD dct_method;	/* IDCT algorithm selector */
  65.443 +  boolean do_fancy_upsampling;	/* TRUE=apply fancy upsampling */
  65.444 +  boolean do_block_smoothing;	/* TRUE=apply interblock smoothing */
  65.445 +
  65.446 +  boolean quantize_colors;	/* TRUE=colormapped output wanted */
  65.447 +  /* the following are ignored if not quantize_colors: */
  65.448 +  J_DITHER_MODE dither_mode;	/* type of color dithering to use */
  65.449 +  boolean two_pass_quantize;	/* TRUE=use two-pass color quantization */
  65.450 +  int desired_number_of_colors;	/* max # colors to use in created colormap */
  65.451 +  /* these are significant only in buffered-image mode: */
  65.452 +  boolean enable_1pass_quant;	/* enable future use of 1-pass quantizer */
  65.453 +  boolean enable_external_quant;/* enable future use of external colormap */
  65.454 +  boolean enable_2pass_quant;	/* enable future use of 2-pass quantizer */
  65.455 +
  65.456 +  /* Description of actual output image that will be returned to application.
  65.457 +   * These fields are computed by jpeg_start_decompress().
  65.458 +   * You can also use jpeg_calc_output_dimensions() to determine these values
  65.459 +   * in advance of calling jpeg_start_decompress().
  65.460 +   */
  65.461 +
  65.462 +  JDIMENSION output_width;	/* scaled image width */
  65.463 +  JDIMENSION output_height;	/* scaled image height */
  65.464 +  int out_color_components;	/* # of color components in out_color_space */
  65.465 +  int output_components;	/* # of color components returned */
  65.466 +  /* output_components is 1 (a colormap index) when quantizing colors;
  65.467 +   * otherwise it equals out_color_components.
  65.468 +   */
  65.469 +  int rec_outbuf_height;	/* min recommended height of scanline buffer */
  65.470 +  /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  65.471 +   * high, space and time will be wasted due to unnecessary data copying.
  65.472 +   * Usually rec_outbuf_height will be 1 or 2, at most 4.
  65.473 +   */
  65.474 +
  65.475 +  /* When quantizing colors, the output colormap is described by these fields.
  65.476 +   * The application can supply a colormap by setting colormap non-NULL before
  65.477 +   * calling jpeg_start_decompress; otherwise a colormap is created during
  65.478 +   * jpeg_start_decompress or jpeg_start_output.
  65.479 +   * The map has out_color_components rows and actual_number_of_colors columns.
  65.480 +   */
  65.481 +  int actual_number_of_colors;	/* number of entries in use */
  65.482 +  JSAMPARRAY colormap;		/* The color map as a 2-D pixel array */
  65.483 +
  65.484 +  /* State variables: these variables indicate the progress of decompression.
  65.485 +   * The application may examine these but must not modify them.
  65.486 +   */
  65.487 +
  65.488 +  /* Row index of next scanline to be read from jpeg_read_scanlines().
  65.489 +   * Application may use this to control its processing loop, e.g.,
  65.490 +   * "while (output_scanline < output_height)".
  65.491 +   */
  65.492 +  JDIMENSION output_scanline;	/* 0 .. output_height-1  */
  65.493 +
  65.494 +  /* Current input scan number and number of iMCU rows completed in scan.
  65.495 +   * These indicate the progress of the decompressor input side.
  65.496 +   */
  65.497 +  int input_scan_number;	/* Number of SOS markers seen so far */
  65.498 +  JDIMENSION input_iMCU_row;	/* Number of iMCU rows completed */
  65.499 +
  65.500 +  /* The "output scan number" is the notional scan being displayed by the
  65.501 +   * output side.  The decompressor will not allow output scan/row number
  65.502 +   * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  65.503 +   */
  65.504 +  int output_scan_number;	/* Nominal scan number being displayed */
  65.505 +  JDIMENSION output_iMCU_row;	/* Number of iMCU rows read */
  65.506 +
  65.507 +  /* Current progression status.  coef_bits[c][i] indicates the precision
  65.508 +   * with which component c's DCT coefficient i (in zigzag order) is known.
  65.509 +   * It is -1 when no data has yet been received, otherwise it is the point
  65.510 +   * transform (shift) value for the most recent scan of the coefficient
  65.511 +   * (thus, 0 at completion of the progression).
  65.512 +   * This pointer is NULL when reading a non-progressive file.
  65.513 +   */
  65.514 +  int (*coef_bits)[DCTSIZE2];	/* -1 or current Al value for each coef */
  65.515 +
  65.516 +  /* Internal JPEG parameters --- the application usually need not look at
  65.517 +   * these fields.  Note that the decompressor output side may not use
  65.518 +   * any parameters that can change between scans.
  65.519 +   */
  65.520 +
  65.521 +  /* Quantization and Huffman tables are carried forward across input
  65.522 +   * datastreams when processing abbreviated JPEG datastreams.
  65.523 +   */
  65.524 +
  65.525 +  JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  65.526 +  /* ptrs to coefficient quantization tables, or NULL if not defined */
  65.527 +
  65.528 +  JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  65.529 +  JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  65.530 +  /* ptrs to Huffman coding tables, or NULL if not defined */
  65.531 +
  65.532 +  /* These parameters are never carried across datastreams, since they
  65.533 +   * are given in SOF/SOS markers or defined to be reset by SOI.
  65.534 +   */
  65.535 +
  65.536 +  int data_precision;		/* bits of precision in image data */
  65.537 +
  65.538 +  jpeg_component_info * comp_info;
  65.539 +  /* comp_info[i] describes component that appears i'th in SOF */
  65.540 +
  65.541 +  boolean progressive_mode;	/* TRUE if SOFn specifies progressive mode */
  65.542 +  boolean arith_code;		/* TRUE=arithmetic coding, FALSE=Huffman */
  65.543 +
  65.544 +  UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  65.545 +  UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  65.546 +  UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  65.547 +
  65.548 +  unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  65.549 +
  65.550 +  /* These fields record data obtained from optional markers recognized by
  65.551 +   * the JPEG library.
  65.552 +   */
  65.553 +  boolean saw_JFIF_marker;	/* TRUE iff a JFIF APP0 marker was found */
  65.554 +  /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  65.555 +  UINT8 JFIF_major_version;	/* JFIF version number */
  65.556 +  UINT8 JFIF_minor_version;
  65.557 +  UINT8 density_unit;		/* JFIF code for pixel size units */
  65.558 +  UINT16 X_density;		/* Horizontal pixel density */
  65.559 +  UINT16 Y_density;		/* Vertical pixel density */
  65.560 +  boolean saw_Adobe_marker;	/* TRUE iff an Adobe APP14 marker was found */
  65.561 +  UINT8 Adobe_transform;	/* Color transform code from Adobe marker */
  65.562 +
  65.563 +  boolean CCIR601_sampling;	/* TRUE=first samples are cosited */
  65.564 +
  65.565 +  /* Aside from the specific data retained from APPn markers known to the
  65.566 +   * library, the uninterpreted contents of any or all APPn and COM markers
  65.567 +   * can be saved in a list for examination by the application.
  65.568 +   */
  65.569 +  jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  65.570 +
  65.571 +  /* Remaining fields are known throughout decompressor, but generally
  65.572 +   * should not be touched by a surrounding application.
  65.573 +   */
  65.574 +
  65.575 +  /*
  65.576 +   * These fields are computed during decompression startup
  65.577 +   */
  65.578 +  int max_h_samp_factor;	/* largest h_samp_factor */
  65.579 +  int max_v_samp_factor;	/* largest v_samp_factor */
  65.580 +
  65.581 +  int min_DCT_scaled_size;	/* smallest DCT_scaled_size of any component */
  65.582 +
  65.583 +  JDIMENSION total_iMCU_rows;	/* # of iMCU rows in image */
  65.584 +  /* The coefficient controller's input and output progress is measured in
  65.585 +   * units of "iMCU" (interleaved MCU) rows.  These are the same as MCU rows
  65.586 +   * in fully interleaved JPEG scans, but are used whether the scan is
  65.587 +   * interleaved or not.  We define an iMCU row as v_samp_factor DCT block
  65.588 +   * rows of each component.  Therefore, the IDCT output contains
  65.589 +   * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  65.590 +   */
  65.591 +
  65.592 +  JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  65.593 +
  65.594 +  /*
  65.595 +   * These fields are valid during any one scan.
  65.596 +   * They describe the components and MCUs actually appearing in the scan.
  65.597 +   * Note that the decompressor output side must not use these fields.
  65.598 +   */
  65.599 +  int comps_in_scan;		/* # of JPEG components in this scan */
  65.600 +  jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  65.601 +  /* *cur_comp_info[i] describes component that appears i'th in SOS */
  65.602 +
  65.603 +  JDIMENSION MCUs_per_row;	/* # of MCUs across the image */
  65.604 +  JDIMENSION MCU_rows_in_scan;	/* # of MCU rows in the image */
  65.605 +
  65.606 +  int blocks_in_MCU;		/* # of DCT blocks per MCU */
  65.607 +  int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  65.608 +  /* MCU_membership[i] is index in cur_comp_info of component owning */
  65.609 +  /* i'th block in an MCU */
  65.610 +
  65.611 +  int Ss, Se, Ah, Al;		/* progressive JPEG parameters for scan */
  65.612 +
  65.613 +  /* This field is shared between entropy decoder and marker parser.
  65.614 +   * It is either zero or the code of a JPEG marker that has been
  65.615 +   * read from the data source, but has not yet been processed.
  65.616 +   */
  65.617 +  int unread_marker;
  65.618 +
  65.619 +  /*
  65.620 +   * Links to decompression subobjects (methods, private variables of modules)
  65.621 +   */
  65.622 +  struct jpeg_decomp_master * master;
  65.623 +  struct jpeg_d_main_controller * main;
  65.624 +  struct jpeg_d_coef_controller * coef;
  65.625 +  struct jpeg_d_post_controller * post;
  65.626 +  struct jpeg_input_controller * inputctl;
  65.627 +  struct jpeg_marker_reader * marker;
  65.628 +  struct jpeg_entropy_decoder * entropy;
  65.629 +  struct jpeg_inverse_dct * idct;
  65.630 +  struct jpeg_upsampler * upsample;
  65.631 +  struct jpeg_color_deconverter * cconvert;
  65.632 +  struct jpeg_color_quantizer * cquantize;
  65.633 +};
  65.634 +
  65.635 +
  65.636 +/* "Object" declarations for JPEG modules that may be supplied or called
  65.637 + * directly by the surrounding application.
  65.638 + * As with all objects in the JPEG library, these structs only define the
  65.639 + * publicly visible methods and state variables of a module.  Additional
  65.640 + * private fields may exist after the public ones.
  65.641 + */
  65.642 +
  65.643 +
  65.644 +/* Error handler object */
  65.645 +
  65.646 +struct jpeg_error_mgr {
  65.647 +  /* Error exit handler: does not return to caller */
  65.648 +  JMETHOD(void, error_exit, (j_common_ptr cinfo));
  65.649 +  /* Conditionally emit a trace or warning message */
  65.650 +  JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  65.651 +  /* Routine that actually outputs a trace or error message */
  65.652 +  JMETHOD(void, output_message, (j_common_ptr cinfo));
  65.653 +  /* Format a message string for the most recent JPEG error or message */
  65.654 +  JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  65.655 +#define JMSG_LENGTH_MAX  200	/* recommended size of format_message buffer */
  65.656 +  /* Reset error state variables at start of a new image */
  65.657 +  JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  65.658 +  
  65.659 +  /* The message ID code and any parameters are saved here.
  65.660 +   * A message can have one string parameter or up to 8 int parameters.
  65.661 +   */
  65.662 +  int msg_code;
  65.663 +#define JMSG_STR_PARM_MAX  80
  65.664 +  union {
  65.665 +    int i[8];
  65.666 +    char s[JMSG_STR_PARM_MAX];
  65.667 +  } msg_parm;
  65.668 +  
  65.669 +  /* Standard state variables for error facility */
  65.670 +  
  65.671 +  int trace_level;		/* max msg_level that will be displayed */
  65.672 +  
  65.673 +  /* For recoverable corrupt-data errors, we emit a warning message,
  65.674 +   * but keep going unless emit_message chooses to abort.  emit_message
  65.675 +   * should count warnings in num_warnings.  The surrounding application
  65.676 +   * can check for bad data by seeing if num_warnings is nonzero at the
  65.677 +   * end of processing.
  65.678 +   */
  65.679 +  long num_warnings;		/* number of corrupt-data warnings */
  65.680 +
  65.681 +  /* These fields point to the table(s) of error message strings.
  65.682 +   * An application can change the table pointer to switch to a different
  65.683 +   * message list (typically, to change the language in which errors are
  65.684 +   * reported).  Some applications may wish to add additional error codes
  65.685 +   * that will be handled by the JPEG library error mechanism; the second
  65.686 +   * table pointer is used for this purpose.
  65.687 +   *
  65.688 +   * First table includes all errors generated by JPEG library itself.
  65.689 +   * Error code 0 is reserved for a "no such error string" message.
  65.690 +   */
  65.691 +  const char * const * jpeg_message_table; /* Library errors */
  65.692 +  int last_jpeg_message;    /* Table contains strings 0..last_jpeg_message */
  65.693 +  /* Second table can be added by application (see cjpeg/djpeg for example).
  65.694 +   * It contains strings numbered first_addon_message..last_addon_message.
  65.695 +   */
  65.696 +  const char * const * addon_message_table; /* Non-library errors */
  65.697 +  int first_addon_message;	/* code for first string in addon table */
  65.698 +  int last_addon_message;	/* code for last string in addon table */
  65.699 +};
  65.700 +
  65.701 +
  65.702 +/* Progress monitor object */
  65.703 +
  65.704 +struct jpeg_progress_mgr {
  65.705 +  JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  65.706 +
  65.707 +  long pass_counter;		/* work units completed in this pass */
  65.708 +  long pass_limit;		/* total number of work units in this pass */
  65.709 +  int completed_passes;		/* passes completed so far */
  65.710 +  int total_passes;		/* total number of passes expected */
  65.711 +};
  65.712 +
  65.713 +
  65.714 +/* Data destination object for compression */
  65.715 +
  65.716 +struct jpeg_destination_mgr {
  65.717 +  JOCTET * next_output_byte;	/* => next byte to write in buffer */
  65.718 +  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
  65.719 +
  65.720 +  JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  65.721 +  JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  65.722 +  JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  65.723 +};
  65.724 +
  65.725 +
  65.726 +/* Data source object for decompression */
  65.727 +
  65.728 +struct jpeg_source_mgr {
  65.729 +  const JOCTET * next_input_byte; /* => next byte to read from buffer */
  65.730 +  size_t bytes_in_buffer;	/* # of bytes remaining in buffer */
  65.731 +
  65.732 +  JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  65.733 +  JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  65.734 +  JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  65.735 +  JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  65.736 +  JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  65.737 +};
  65.738 +
  65.739 +
  65.740 +/* Memory manager object.
  65.741 + * Allocates "small" objects (a few K total), "large" objects (tens of K),
  65.742 + * and "really big" objects (virtual arrays with backing store if needed).
  65.743 + * The memory manager does not allow individual objects to be freed; rather,
  65.744 + * each created object is assigned to a pool, and whole pools can be freed
  65.745 + * at once.  This is faster and more convenient than remembering exactly what
  65.746 + * to free, especially where malloc()/free() are not too speedy.
  65.747 + * NB: alloc routines never return NULL.  They exit to error_exit if not
  65.748 + * successful.
  65.749 + */
  65.750 +
  65.751 +#define JPOOL_PERMANENT	0	/* lasts until master record is destroyed */
  65.752 +#define JPOOL_IMAGE	1	/* lasts until done with image/datastream */
  65.753 +#define JPOOL_NUMPOOLS	2
  65.754 +
  65.755 +typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  65.756 +typedef struct jvirt_barray_control * jvirt_barray_ptr;
  65.757 +
  65.758 +
  65.759 +struct jpeg_memory_mgr {
  65.760 +  /* Method pointers */
  65.761 +  JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  65.762 +				size_t sizeofobject));
  65.763 +  JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  65.764 +				     size_t sizeofobject));
  65.765 +  JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  65.766 +				     JDIMENSION samplesperrow,
  65.767 +				     JDIMENSION numrows));
  65.768 +  JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  65.769 +				      JDIMENSION blocksperrow,
  65.770 +				      JDIMENSION numrows));
  65.771 +  JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  65.772 +						  int pool_id,
  65.773 +						  boolean pre_zero,
  65.774 +						  JDIMENSION samplesperrow,
  65.775 +						  JDIMENSION numrows,
  65.776 +						  JDIMENSION maxaccess));
  65.777 +  JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  65.778 +						  int pool_id,
  65.779 +						  boolean pre_zero,
  65.780 +						  JDIMENSION blocksperrow,
  65.781 +						  JDIMENSION numrows,
  65.782 +						  JDIMENSION maxaccess));
  65.783 +  JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  65.784 +  JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  65.785 +					   jvirt_sarray_ptr ptr,
  65.786 +					   JDIMENSION start_row,
  65.787 +					   JDIMENSION num_rows,
  65.788 +					   boolean writable));
  65.789 +  JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  65.790 +					    jvirt_barray_ptr ptr,
  65.791 +					    JDIMENSION start_row,
  65.792 +					    JDIMENSION num_rows,
  65.793 +					    boolean writable));
  65.794 +  JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  65.795 +  JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  65.796 +
  65.797 +  /* Limit on memory allocation for this JPEG object.  (Note that this is
  65.798 +   * merely advisory, not a guaranteed maximum; it only affects the space
  65.799 +   * used for virtual-array buffers.)  May be changed by outer application
  65.800 +   * after creating the JPEG object.
  65.801 +   */
  65.802 +  long max_memory_to_use;
  65.803 +
  65.804 +  /* Maximum allocation request accepted by alloc_large. */
  65.805 +  long max_alloc_chunk;
  65.806 +};
  65.807 +
  65.808 +
  65.809 +/* Routine signature for application-supplied marker processing methods.
  65.810 + * Need not pass marker code since it is stored in cinfo->unread_marker.
  65.811 + */
  65.812 +typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  65.813 +
  65.814 +
  65.815 +/* Declarations for routines called by application.
  65.816 + * The JPP macro hides prototype parameters from compilers that can't cope.
  65.817 + * Note JPP requires double parentheses.
  65.818 + */
  65.819 +
  65.820 +#ifdef HAVE_PROTOTYPES
  65.821 +#define JPP(arglist)	arglist
  65.822 +#else
  65.823 +#define JPP(arglist)	()
  65.824 +#endif
  65.825 +
  65.826 +
  65.827 +/* Short forms of external names for systems with brain-damaged linkers.
  65.828 + * We shorten external names to be unique in the first six letters, which
  65.829 + * is good enough for all known systems.
  65.830 + * (If your compiler itself needs names to be unique in less than 15 
  65.831 + * characters, you are out of luck.  Get a better compiler.)
  65.832 + */
  65.833 +
  65.834 +#ifdef NEED_SHORT_EXTERNAL_NAMES
  65.835 +#define jpeg_std_error		jStdError
  65.836 +#define jpeg_CreateCompress	jCreaCompress
  65.837 +#define jpeg_CreateDecompress	jCreaDecompress
  65.838 +#define jpeg_destroy_compress	jDestCompress
  65.839 +#define jpeg_destroy_decompress	jDestDecompress
  65.840 +#define jpeg_stdio_dest		jStdDest
  65.841 +#define jpeg_stdio_src		jStdSrc
  65.842 +#define jpeg_set_defaults	jSetDefaults
  65.843 +#define jpeg_set_colorspace	jSetColorspace
  65.844 +#define jpeg_default_colorspace	jDefColorspace
  65.845 +#define jpeg_set_quality	jSetQuality
  65.846 +#define jpeg_set_linear_quality	jSetLQuality
  65.847 +#define jpeg_add_quant_table	jAddQuantTable
  65.848 +#define jpeg_quality_scaling	jQualityScaling
  65.849 +#define jpeg_simple_progression	jSimProgress
  65.850 +#define jpeg_suppress_tables	jSuppressTables
  65.851 +#define jpeg_alloc_quant_table	jAlcQTable
  65.852 +#define jpeg_alloc_huff_table	jAlcHTable
  65.853 +#define jpeg_start_compress	jStrtCompress
  65.854 +#define jpeg_write_scanlines	jWrtScanlines
  65.855 +#define jpeg_finish_compress	jFinCompress
  65.856 +#define jpeg_write_raw_data	jWrtRawData
  65.857 +#define jpeg_write_marker	jWrtMarker
  65.858 +#define jpeg_write_m_header	jWrtMHeader
  65.859 +#define jpeg_write_m_byte	jWrtMByte
  65.860 +#define jpeg_write_tables	jWrtTables
  65.861 +#define jpeg_read_header	jReadHeader
  65.862 +#define jpeg_start_decompress	jStrtDecompress
  65.863 +#define jpeg_read_scanlines	jReadScanlines
  65.864 +#define jpeg_finish_decompress	jFinDecompress
  65.865 +#define jpeg_read_raw_data	jReadRawData
  65.866 +#define jpeg_has_multiple_scans	jHasMultScn
  65.867 +#define jpeg_start_output	jStrtOutput
  65.868 +#define jpeg_finish_output	jFinOutput
  65.869 +#define jpeg_input_complete	jInComplete
  65.870 +#define jpeg_new_colormap	jNewCMap
  65.871 +#define jpeg_consume_input	jConsumeInput
  65.872 +#define jpeg_calc_output_dimensions	jCalcDimensions
  65.873 +#define jpeg_save_markers	jSaveMarkers
  65.874 +#define jpeg_set_marker_processor	jSetMarker
  65.875 +#define jpeg_read_coefficients	jReadCoefs
  65.876 +#define jpeg_write_coefficients	jWrtCoefs
  65.877 +#define jpeg_copy_critical_parameters	jCopyCrit
  65.878 +#define jpeg_abort_compress	jAbrtCompress
  65.879 +#define jpeg_abort_decompress	jAbrtDecompress
  65.880 +#define jpeg_abort		jAbort
  65.881 +#define jpeg_destroy		jDestroy
  65.882 +#define jpeg_resync_to_restart	jResyncRestart
  65.883 +#endif /* NEED_SHORT_EXTERNAL_NAMES */
  65.884 +
  65.885 +
  65.886 +/* Default error-management setup */
  65.887 +EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  65.888 +	JPP((struct jpeg_error_mgr * err));
  65.889 +
  65.890 +/* Initialization of JPEG compression objects.
  65.891 + * jpeg_create_compress() and jpeg_create_decompress() are the exported
  65.892 + * names that applications should call.  These expand to calls on
  65.893 + * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  65.894 + * passed for version mismatch checking.
  65.895 + * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  65.896 + */
  65.897 +#define jpeg_create_compress(cinfo) \
  65.898 +    jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  65.899 +			(size_t) sizeof(struct jpeg_compress_struct))
  65.900 +#define jpeg_create_decompress(cinfo) \
  65.901 +    jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  65.902 +			  (size_t) sizeof(struct jpeg_decompress_struct))
  65.903 +EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  65.904 +				      int version, size_t structsize));
  65.905 +EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  65.906 +					int version, size_t structsize));
  65.907 +/* Destruction of JPEG compression objects */
  65.908 +EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  65.909 +EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  65.910 +
  65.911 +/* Standard data source and destination managers: stdio streams. */
  65.912 +/* Caller is responsible for opening the file before and closing after. */
  65.913 +EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  65.914 +EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  65.915 +
  65.916 +/* Default parameter setup for compression */
  65.917 +EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  65.918 +/* Compression parameter setup aids */
  65.919 +EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  65.920 +				      J_COLOR_SPACE colorspace));
  65.921 +EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  65.922 +EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  65.923 +				   boolean force_baseline));
  65.924 +EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  65.925 +					  int scale_factor,
  65.926 +					  boolean force_baseline));
  65.927 +EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  65.928 +				       const unsigned int *basic_table,
  65.929 +				       int scale_factor,
  65.930 +				       boolean force_baseline));
  65.931 +EXTERN(int) jpeg_quality_scaling JPP((int quality));
  65.932 +EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  65.933 +EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  65.934 +				       boolean suppress));
  65.935 +EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  65.936 +EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  65.937 +
  65.938 +/* Main entry points for compression */
  65.939 +EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  65.940 +				      boolean write_all_tables));
  65.941 +EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  65.942 +					     JSAMPARRAY scanlines,
  65.943 +					     JDIMENSION num_lines));
  65.944 +EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  65.945 +
  65.946 +/* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  65.947 +EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  65.948 +					    JSAMPIMAGE data,
  65.949 +					    JDIMENSION num_lines));
  65.950 +
  65.951 +/* Write a special marker.  See libjpeg.doc concerning safe usage. */
  65.952 +EXTERN(void) jpeg_write_marker
  65.953 +	JPP((j_compress_ptr cinfo, int marker,
  65.954 +	     const JOCTET * dataptr, unsigned int datalen));
  65.955 +/* Same, but piecemeal. */
  65.956 +EXTERN(void) jpeg_write_m_header
  65.957 +	JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  65.958 +EXTERN(void) jpeg_write_m_byte
  65.959 +	JPP((j_compress_ptr cinfo, int val));
  65.960 +
  65.961 +/* Alternate compression function: just write an abbreviated table file */
  65.962 +EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  65.963 +
  65.964 +/* Decompression startup: read start of JPEG datastream to see what's there */
  65.965 +EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  65.966 +				  boolean require_image));
  65.967 +/* Return value is one of: */
  65.968 +#define JPEG_SUSPENDED		0 /* Suspended due to lack of input data */
  65.969 +#define JPEG_HEADER_OK		1 /* Found valid image datastream */
  65.970 +#define JPEG_HEADER_TABLES_ONLY	2 /* Found valid table-specs-only datastream */
  65.971 +/* If you pass require_image = TRUE (normal case), you need not check for
  65.972 + * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  65.973 + * JPEG_SUSPENDED is only possible if you use a data source module that can
  65.974 + * give a suspension return (the stdio source module doesn't).
  65.975 + */
  65.976 +
  65.977 +/* Main entry points for decompression */
  65.978 +EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  65.979 +EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  65.980 +					    JSAMPARRAY scanlines,
  65.981 +					    JDIMENSION max_lines));
  65.982 +EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  65.983 +
  65.984 +/* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  65.985 +EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  65.986 +					   JSAMPIMAGE data,
  65.987 +					   JDIMENSION max_lines));
  65.988 +
  65.989 +/* Additional entry points for buffered-image mode. */
  65.990 +EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  65.991 +EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  65.992 +				       int scan_number));
  65.993 +EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  65.994 +EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  65.995 +EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  65.996 +EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  65.997 +/* Return value is one of: */
  65.998 +/* #define JPEG_SUSPENDED	0    Suspended due to lack of input data */
  65.999 +#define JPEG_REACHED_SOS	1 /* Reached start of new scan */
 65.1000 +#define JPEG_REACHED_EOI	2 /* Reached end of image */
 65.1001 +#define JPEG_ROW_COMPLETED	3 /* Completed one iMCU row */
 65.1002 +#define JPEG_SCAN_COMPLETED	4 /* Completed last iMCU row of a scan */
 65.1003 +
 65.1004 +/* Precalculate output dimensions for current decompression parameters. */
 65.1005 +EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
 65.1006 +
 65.1007 +/* Control saving of COM and APPn markers into marker_list. */
 65.1008 +EXTERN(void) jpeg_save_markers
 65.1009 +	JPP((j_decompress_ptr cinfo, int marker_code,
 65.1010 +	     unsigned int length_limit));
 65.1011 +
 65.1012 +/* Install a special processing method for COM or APPn markers. */
 65.1013 +EXTERN(void) jpeg_set_marker_processor
 65.1014 +	JPP((j_decompress_ptr cinfo, int marker_code,
 65.1015 +	     jpeg_marker_parser_method routine));
 65.1016 +
 65.1017 +/* Read or write raw DCT coefficients --- useful for lossless transcoding. */
 65.1018 +EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
 65.1019 +EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
 65.1020 +					  jvirt_barray_ptr * coef_arrays));
 65.1021 +EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
 65.1022 +						j_compress_ptr dstinfo));
 65.1023 +
 65.1024 +/* If you choose to abort compression or decompression before completing
 65.1025 + * jpeg_finish_(de)compress, then you need to clean up to release memory,
 65.1026 + * temporary files, etc.  You can just call jpeg_destroy_(de)compress
 65.1027 + * if you're done with the JPEG object, but if you want to clean it up and
 65.1028 + * reuse it, call this:
 65.1029 + */
 65.1030 +EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
 65.1031 +EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
 65.1032 +
 65.1033 +/* Generic versions of jpeg_abort and jpeg_destroy that work on either
 65.1034 + * flavor of JPEG object.  These may be more convenient in some places.
 65.1035 + */
 65.1036 +EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
 65.1037 +EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
 65.1038 +
 65.1039 +/* Default restart-marker-resync procedure for use by data source modules */
 65.1040 +EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
 65.1041 +					    int desired));
 65.1042 +
 65.1043 +
 65.1044 +/* These marker codes are exported since applications and data source modules
 65.1045 + * are likely to want to use them.
 65.1046 + */
 65.1047 +
 65.1048 +#define JPEG_RST0	0xD0	/* RST0 marker code */
 65.1049 +#define JPEG_EOI	0xD9	/* EOI marker code */
 65.1050 +#define JPEG_APP0	0xE0	/* APP0 marker code */
 65.1051 +#define JPEG_COM	0xFE	/* COM marker code */
 65.1052 +
 65.1053 +
 65.1054 +/* If we have a brain-damaged compiler that emits warnings (or worse, errors)
 65.1055 + * for structure definitions that are never filled in, keep it quiet by
 65.1056 + * supplying dummy definitions for the various substructures.
 65.1057 + */
 65.1058 +
 65.1059 +#ifdef INCOMPLETE_TYPES_BROKEN
 65.1060 +#ifndef JPEG_INTERNALS		/* will be defined in jpegint.h */
 65.1061 +struct jvirt_sarray_control { long dummy; };
 65.1062 +struct jvirt_barray_control { long dummy; };
 65.1063 +struct jpeg_comp_master { long dummy; };
 65.1064 +struct jpeg_c_main_controller { long dummy; };
 65.1065 +struct jpeg_c_prep_controller { long dummy; };
 65.1066 +struct jpeg_c_coef_controller { long dummy; };
 65.1067 +struct jpeg_marker_writer { long dummy; };
 65.1068 +struct jpeg_color_converter { long dummy; };
 65.1069 +struct jpeg_downsampler { long dummy; };
 65.1070 +struct jpeg_forward_dct { long dummy; };
 65.1071 +struct jpeg_entropy_encoder { long dummy; };
 65.1072 +struct jpeg_decomp_master { long dummy; };
 65.1073 +struct jpeg_d_main_controller { long dummy; };
 65.1074 +struct jpeg_d_coef_controller { long dummy; };
 65.1075 +struct jpeg_d_post_controller { long dummy; };
 65.1076 +struct jpeg_input_controller { long dummy; };
 65.1077 +struct jpeg_marker_reader { long dummy; };
 65.1078 +struct jpeg_entropy_decoder { long dummy; };
 65.1079 +struct jpeg_inverse_dct { long dummy; };
 65.1080 +struct jpeg_upsampler { long dummy; };
 65.1081 +struct jpeg_color_deconverter { long dummy; };
 65.1082 +struct jpeg_color_quantizer { long dummy; };
 65.1083 +#endif /* JPEG_INTERNALS */
 65.1084 +#endif /* INCOMPLETE_TYPES_BROKEN */
 65.1085 +
 65.1086 +
 65.1087 +/*
 65.1088 + * The JPEG library modules define JPEG_INTERNALS before including this file.
 65.1089 + * The internal structure declarations are read only when that is true.
 65.1090 + * Applications using the library should not include jpegint.h, but may wish
 65.1091 + * to include jerror.h.
 65.1092 + */
 65.1093 +
 65.1094 +#ifdef JPEG_INTERNALS
 65.1095 +#include "jpegint.h"		/* fetch private declarations */
 65.1096 +#include "jerror.h"		/* fetch error codes too */
 65.1097 +#endif
 65.1098 +
 65.1099 +#endif /* JPEGLIB_H */
    66.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    66.2 +++ b/libs/libjpeg/jquant1.c	Thu Sep 08 06:28:38 2011 +0300
    66.3 @@ -0,0 +1,856 @@
    66.4 +/*
    66.5 + * jquant1.c
    66.6 + *
    66.7 + * Copyright (C) 1991-1996, Thomas G. Lane.
    66.8 + * This file is part of the Independent JPEG Group's software.
    66.9 + * For conditions of distribution and use, see the accompanying README file.
   66.10 + *
   66.11 + * This file contains 1-pass color quantization (color mapping) routines.
   66.12 + * These routines provide mapping to a fixed color map using equally spaced
   66.13 + * color values.  Optional Floyd-Steinberg or ordered dithering is available.
   66.14 + */
   66.15 +
   66.16 +#define JPEG_INTERNALS
   66.17 +#include "jinclude.h"
   66.18 +#include "jpeglib.h"
   66.19 +
   66.20 +#ifdef QUANT_1PASS_SUPPORTED
   66.21 +
   66.22 +
   66.23 +/*
   66.24 + * The main purpose of 1-pass quantization is to provide a fast, if not very
   66.25 + * high quality, colormapped output capability.  A 2-pass quantizer usually
   66.26 + * gives better visual quality; however, for quantized grayscale output this
   66.27 + * quantizer is perfectly adequate.  Dithering is highly recommended with this
   66.28 + * quantizer, though you can turn it off if you really want to.
   66.29 + *
   66.30 + * In 1-pass quantization the colormap must be chosen in advance of seeing the
   66.31 + * image.  We use a map consisting of all combinations of Ncolors[i] color
   66.32 + * values for the i'th component.  The Ncolors[] values are chosen so that
   66.33 + * their product, the total number of colors, is no more than that requested.
   66.34 + * (In most cases, the product will be somewhat less.)
   66.35 + *
   66.36 + * Since the colormap is orthogonal, the representative value for each color
   66.37 + * component can be determined without considering the other components;
   66.38 + * then these indexes can be combined into a colormap index by a standard
   66.39 + * N-dimensional-array-subscript calculation.  Most of the arithmetic involved
   66.40 + * can be precalculated and stored in the lookup table colorindex[].
   66.41 + * colorindex[i][j] maps pixel value j in component i to the nearest
   66.42 + * representative value (grid plane) for that component; this index is
   66.43 + * multiplied by the array stride for component i, so that the
   66.44 + * index of the colormap entry closest to a given pixel value is just
   66.45 + *    sum( colorindex[component-number][pixel-component-value] )
   66.46 + * Aside from being fast, this scheme allows for variable spacing between
   66.47 + * representative values with no additional lookup cost.
   66.48 + *
   66.49 + * If gamma correction has been applied in color conversion, it might be wise
   66.50 + * to adjust the color grid spacing so that the representative colors are
   66.51 + * equidistant in linear space.  At this writing, gamma correction is not
   66.52 + * implemented by jdcolor, so nothing is done here.
   66.53 + */
   66.54 +
   66.55 +
   66.56 +/* Declarations for ordered dithering.
   66.57 + *
   66.58 + * We use a standard 16x16 ordered dither array.  The basic concept of ordered
   66.59 + * dithering is described in many references, for instance Dale Schumacher's
   66.60 + * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
   66.61 + * In place of Schumacher's comparisons against a "threshold" value, we add a
   66.62 + * "dither" value to the input pixel and then round the result to the nearest
   66.63 + * output value.  The dither value is equivalent to (0.5 - threshold) times
   66.64 + * the distance between output values.  For ordered dithering, we assume that
   66.65 + * the output colors are equally spaced; if not, results will probably be
   66.66 + * worse, since the dither may be too much or too little at a given point.
   66.67 + *
   66.68 + * The normal calculation would be to form pixel value + dither, range-limit
   66.69 + * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
   66.70 + * We can skip the separate range-limiting step by extending the colorindex
   66.71 + * table in both directions.
   66.72 + */
   66.73 +
   66.74 +#define ODITHER_SIZE  16	/* dimension of dither matrix */
   66.75 +/* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
   66.76 +#define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE)	/* # cells in matrix */
   66.77 +#define ODITHER_MASK  (ODITHER_SIZE-1) /* mask for wrapping around counters */
   66.78 +
   66.79 +typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
   66.80 +typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
   66.81 +
   66.82 +static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
   66.83 +  /* Bayer's order-4 dither array.  Generated by the code given in
   66.84 +   * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
   66.85 +   * The values in this array must range from 0 to ODITHER_CELLS-1.
   66.86 +   */
   66.87 +  {   0,192, 48,240, 12,204, 60,252,  3,195, 51,243, 15,207, 63,255 },
   66.88 +  { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
   66.89 +  {  32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
   66.90 +  { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
   66.91 +  {   8,200, 56,248,  4,196, 52,244, 11,203, 59,251,  7,199, 55,247 },
   66.92 +  { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
   66.93 +  {  40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
   66.94 +  { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
   66.95 +  {   2,194, 50,242, 14,206, 62,254,  1,193, 49,241, 13,205, 61,253 },
   66.96 +  { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
   66.97 +  {  34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
   66.98 +  { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
   66.99 +  {  10,202, 58,250,  6,198, 54,246,  9,201, 57,249,  5,197, 53,245 },
  66.100 +  { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  66.101 +  {  42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  66.102 +  { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  66.103 +};
  66.104 +
  66.105 +
  66.106 +/* Declarations for Floyd-Steinberg dithering.
  66.107 + *
  66.108 + * Errors are accumulated into the array fserrors[], at a resolution of
  66.109 + * 1/16th of a pixel count.  The error at a given pixel is propagated
  66.110 + * to its not-yet-processed neighbors using the standard F-S fractions,
  66.111 + *		...	(here)	7/16
  66.112 + *		3/16	5/16	1/16
  66.113 + * We work left-to-right on even rows, right-to-left on odd rows.
  66.114 + *
  66.115 + * We can get away with a single array (holding one row's worth of errors)
  66.116 + * by using it to store the current row's errors at pixel columns not yet
  66.117 + * processed, but the next row's errors at columns already processed.  We
  66.118 + * need only a few extra variables to hold the errors immediately around the
  66.119 + * current column.  (If we are lucky, those variables are in registers, but
  66.120 + * even if not, they're probably cheaper to access than array elements are.)
  66.121 + *
  66.122 + * The fserrors[] array is indexed [component#][position].
  66.123 + * We provide (#columns + 2) entries per component; the extra entry at each
  66.124 + * end saves us from special-casing the first and last pixels.
  66.125 + *
  66.126 + * Note: on a wide image, we might not have enough room in a PC's near data
  66.127 + * segment to hold the error array; so it is allocated with alloc_large.
  66.128 + */
  66.129 +
  66.130 +#if BITS_IN_JSAMPLE == 8
  66.131 +typedef INT16 FSERROR;		/* 16 bits should be enough */
  66.132 +typedef int LOCFSERROR;		/* use 'int' for calculation temps */
  66.133 +#else
  66.134 +typedef INT32 FSERROR;		/* may need more than 16 bits */
  66.135 +typedef INT32 LOCFSERROR;	/* be sure calculation temps are big enough */
  66.136 +#endif
  66.137 +
  66.138 +typedef FSERROR FAR *FSERRPTR;	/* pointer to error array (in FAR storage!) */
  66.139 +
  66.140 +
  66.141 +/* Private subobject */
  66.142 +
  66.143 +#define MAX_Q_COMPS 4		/* max components I can handle */
  66.144 +
  66.145 +typedef struct {
  66.146 +  struct jpeg_color_quantizer pub; /* public fields */
  66.147 +
  66.148 +  /* Initially allocated colormap is saved here */
  66.149 +  JSAMPARRAY sv_colormap;	/* The color map as a 2-D pixel array */
  66.150 +  int sv_actual;		/* number of entries in use */
  66.151 +
  66.152 +  JSAMPARRAY colorindex;	/* Precomputed mapping for speed */
  66.153 +  /* colorindex[i][j] = index of color closest to pixel value j in component i,
  66.154 +   * premultiplied as described above.  Since colormap indexes must fit into
  66.155 +   * JSAMPLEs, the entries of this array will too.
  66.156 +   */
  66.157 +  boolean is_padded;		/* is the colorindex padded for odither? */
  66.158 +
  66.159 +  int Ncolors[MAX_Q_COMPS];	/* # of values alloced to each component */
  66.160 +
  66.161 +  /* Variables for ordered dithering */
  66.162 +  int row_index;		/* cur row's vertical index in dither matrix */
  66.163 +  ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  66.164 +
  66.165 +  /* Variables for Floyd-Steinberg dithering */
  66.166 +  FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  66.167 +  boolean on_odd_row;		/* flag to remember which row we are on */
  66.168 +} my_cquantizer;
  66.169 +
  66.170 +typedef my_cquantizer * my_cquantize_ptr;
  66.171 +
  66.172 +
  66.173 +/*
  66.174 + * Policy-making subroutines for create_colormap and create_colorindex.
  66.175 + * These routines determine the colormap to be used.  The rest of the module
  66.176 + * only assumes that the colormap is orthogonal.
  66.177 + *
  66.178 + *  * select_ncolors decides how to divvy up the available colors
  66.179 + *    among the components.
  66.180 + *  * output_value defines the set of representative values for a component.
  66.181 + *  * largest_input_value defines the mapping from input values to
  66.182 + *    representative values for a component.
  66.183 + * Note that the latter two routines may impose different policies for
  66.184 + * different components, though this is not currently done.
  66.185 + */
  66.186 +
  66.187 +
  66.188 +LOCAL(int)
  66.189 +select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  66.190 +/* Determine allocation of desired colors to components, */
  66.191 +/* and fill in Ncolors[] array to indicate choice. */
  66.192 +/* Return value is total number of colors (product of Ncolors[] values). */
  66.193 +{
  66.194 +  int nc = cinfo->out_color_components; /* number of color components */
  66.195 +  int max_colors = cinfo->desired_number_of_colors;
  66.196 +  int total_colors, iroot, i, j;
  66.197 +  boolean changed;
  66.198 +  long temp;
  66.199 +  static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  66.200 +
  66.201 +  /* We can allocate at least the nc'th root of max_colors per component. */
  66.202 +  /* Compute floor(nc'th root of max_colors). */
  66.203 +  iroot = 1;
  66.204 +  do {
  66.205 +    iroot++;
  66.206 +    temp = iroot;		/* set temp = iroot ** nc */
  66.207 +    for (i = 1; i < nc; i++)
  66.208 +      temp *= iroot;
  66.209 +  } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  66.210 +  iroot--;			/* now iroot = floor(root) */
  66.211 +
  66.212 +  /* Must have at least 2 color values per component */
  66.213 +  if (iroot < 2)
  66.214 +    ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  66.215 +
  66.216 +  /* Initialize to iroot color values for each component */
  66.217 +  total_colors = 1;
  66.218 +  for (i = 0; i < nc; i++) {
  66.219 +    Ncolors[i] = iroot;
  66.220 +    total_colors *= iroot;
  66.221 +  }
  66.222 +  /* We may be able to increment the count for one or more components without
  66.223 +   * exceeding max_colors, though we know not all can be incremented.
  66.224 +   * Sometimes, the first component can be incremented more than once!
  66.225 +   * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  66.226 +   * In RGB colorspace, try to increment G first, then R, then B.
  66.227 +   */
  66.228 +  do {
  66.229 +    changed = FALSE;
  66.230 +    for (i = 0; i < nc; i++) {
  66.231 +      j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  66.232 +      /* calculate new total_colors if Ncolors[j] is incremented */
  66.233 +      temp = total_colors / Ncolors[j];
  66.234 +      temp *= Ncolors[j]+1;	/* done in long arith to avoid oflo */
  66.235 +      if (temp > (long) max_colors)
  66.236 +	break;			/* won't fit, done with this pass */
  66.237 +      Ncolors[j]++;		/* OK, apply the increment */
  66.238 +      total_colors = (int) temp;
  66.239 +      changed = TRUE;
  66.240 +    }
  66.241 +  } while (changed);
  66.242 +
  66.243 +  return total_colors;
  66.244 +}
  66.245 +
  66.246 +
  66.247 +LOCAL(int)
  66.248 +output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  66.249 +/* Return j'th output value, where j will range from 0 to maxj */
  66.250 +/* The output values must fall in 0..MAXJSAMPLE in increasing order */
  66.251 +{
  66.252 +  /* We always provide values 0 and MAXJSAMPLE for each component;
  66.253 +   * any additional values are equally spaced between these limits.
  66.254 +   * (Forcing the upper and lower values to the limits ensures that
  66.255 +   * dithering can't produce a color outside the selected gamut.)
  66.256 +   */
  66.257 +  return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  66.258 +}
  66.259 +
  66.260 +
  66.261 +LOCAL(int)
  66.262 +largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  66.263 +/* Return largest input value that should map to j'th output value */
  66.264 +/* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  66.265 +{
  66.266 +  /* Breakpoints are halfway between values returned by output_value */
  66.267 +  return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  66.268 +}
  66.269 +
  66.270 +
  66.271 +/*
  66.272 + * Create the colormap.
  66.273 + */
  66.274 +
  66.275 +LOCAL(void)
  66.276 +create_colormap (j_decompress_ptr cinfo)
  66.277 +{
  66.278 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  66.279 +  JSAMPARRAY colormap;		/* Created colormap */
  66.280 +  int total_colors;		/* Number of distinct output colors */
  66.281 +  int i,j,k, nci, blksize, blkdist, ptr, val;
  66.282 +
  66.283 +  /* Select number of colors for each component */
  66.284 +  total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  66.285 +
  66.286 +  /* Report selected color counts */
  66.287 +  if (cinfo->out_color_components == 3)
  66.288 +    TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  66.289 +	     total_colors, cquantize->Ncolors[0],
  66.290 +	     cquantize->Ncolors[1], cquantize->Ncolors[2]);
  66.291 +  else
  66.292 +    TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  66.293 +
  66.294 +  /* Allocate and fill in the colormap. */
  66.295 +  /* The colors are ordered in the map in standard row-major order, */
  66.296 +  /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  66.297 +
  66.298 +  colormap = (*cinfo->mem->alloc_sarray)
  66.299 +    ((j_common_ptr) cinfo, JPOOL_IMAGE,
  66.300 +     (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  66.301 +
  66.302 +  /* blksize is number of adjacent repeated entries for a component */
  66.303 +  /* blkdist is distance between groups of identical entries for a component */
  66.304 +  blkdist = total_colors;
  66.305 +
  66.306 +  for (i = 0; i < cinfo->out_color_components; i++) {
  66.307 +    /* fill in colormap entries for i'th color component */
  66.308 +    nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  66.309 +    blksize = blkdist / nci;
  66.310 +    for (j = 0; j < nci; j++) {
  66.311 +      /* Compute j'th output value (out of nci) for component */
  66.312 +      val = output_value(cinfo, i, j, nci-1);
  66.313 +      /* Fill in all colormap entries that have this value of this component */
  66.314 +      for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  66.315 +	/* fill in blksize entries beginning at ptr */
  66.316 +	for (k = 0; k < blksize; k++)
  66.317 +	  colormap[i][ptr+k] = (JSAMPLE) val;
  66.318 +      }
  66.319 +    }
  66.320 +    blkdist = blksize;		/* blksize of this color is blkdist of next */
  66.321 +  }
  66.322 +
  66.323 +  /* Save the colormap in private storage,
  66.324 +   * where it will survive color quantization mode changes.
  66.325 +   */
  66.326 +  cquantize->sv_colormap = colormap;
  66.327 +  cquantize->sv_actual = total_colors;
  66.328 +}
  66.329 +
  66.330 +
  66.331 +/*
  66.332 + * Create the color index table.
  66.333 + */
  66.334 +
  66.335 +LOCAL(void)
  66.336 +create_colorindex (j_decompress_ptr cinfo)
  66.337 +{
  66.338 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  66.339 +  JSAMPROW indexptr;
  66.340 +  int i,j,k, nci, blksize, val, pad;
  66.341 +
  66.342 +  /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  66.343 +   * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  66.344 +   * This is not necessary in the other dithering modes.  However, we
  66.345 +   * flag whether it was done in case user changes dithering mode.
  66.346 +   */
  66.347 +  if (cinfo->dither_mode == JDITHER_ORDERED) {
  66.348 +    pad = MAXJSAMPLE*2;
  66.349 +    cquantize->is_padded = TRUE;
  66.350 +  } else {
  66.351 +    pad = 0;
  66.352 +    cquantize->is_padded = FALSE;
  66.353 +  }
  66.354 +
  66.355 +  cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  66.356 +    ((j_common_ptr) cinfo, JPOOL_IMAGE,
  66.357 +     (JDIMENSION) (MAXJSAMPLE+1 + pad),
  66.358 +     (JDIMENSION) cinfo->out_color_components);
  66.359 +
  66.360 +  /* blksize is number of adjacent repeated entries for a component */
  66.361 +  blksize = cquantize->sv_actual;
  66.362 +
  66.363 +  for (i = 0; i < cinfo->out_color_components; i++) {
  66.364 +    /* fill in colorindex entries for i'th color component */
  66.365 +    nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  66.366 +    blksize = blksize / nci;
  66.367 +
  66.368 +    /* adjust colorindex pointers to provide padding at negative indexes. */
  66.369 +    if (pad)
  66.370 +      cquantize->colorindex[i] += MAXJSAMPLE;
  66.371 +
  66.372 +    /* in loop, val = index of current output value, */
  66.373 +    /* and k = largest j that maps to current val */
  66.374 +    indexptr = cquantize->colorindex[i];
  66.375 +    val = 0;
  66.376 +    k = largest_input_value(cinfo, i, 0, nci-1);
  66.377 +    for (j = 0; j <= MAXJSAMPLE; j++) {
  66.378 +      while (j > k)		/* advance val if past boundary */
  66.379 +	k = largest_input_value(cinfo, i, ++val, nci-1);
  66.380 +      /* premultiply so that no multiplication needed in main processing */
  66.381 +      indexptr[j] = (JSAMPLE) (val * blksize);
  66.382 +    }
  66.383 +    /* Pad at both ends if necessary */
  66.384 +    if (pad)
  66.385 +      for (j = 1; j <= MAXJSAMPLE; j++) {
  66.386 +	indexptr[-j] = indexptr[0];
  66.387 +	indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  66.388 +      }
  66.389 +  }
  66.390 +}
  66.391 +
  66.392 +
  66.393 +/*
  66.394 + * Create an ordered-dither array for a component having ncolors
  66.395 + * distinct output values.
  66.396 + */
  66.397 +
  66.398 +LOCAL(ODITHER_MATRIX_PTR)
  66.399 +make_odither_array (j_decompress_ptr cinfo, int ncolors)
  66.400 +{
  66.401 +  ODITHER_MATRIX_PTR odither;
  66.402 +  int j,k;
  66.403 +  INT32 num,den;
  66.404 +
  66.405 +  odither = (ODITHER_MATRIX_PTR)
  66.406 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  66.407 +				SIZEOF(ODITHER_MATRIX));
  66.408 +  /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  66.409 +   * Hence the dither value for the matrix cell with fill order f
  66.410 +   * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  66.411 +   * On 16-bit-int machine, be careful to avoid overflow.
  66.412 +   */
  66.413 +  den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  66.414 +  for (j = 0; j < ODITHER_SIZE; j++) {
  66.415 +    for (k = 0; k < ODITHER_SIZE; k++) {
  66.416 +      num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  66.417 +	    * MAXJSAMPLE;
  66.418 +      /* Ensure round towards zero despite C's lack of consistency
  66.419 +       * about rounding negative values in integer division...
  66.420 +       */
  66.421 +      odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  66.422 +    }
  66.423 +  }
  66.424 +  return odither;
  66.425 +}
  66.426 +
  66.427 +
  66.428 +/*
  66.429 + * Create the ordered-dither tables.
  66.430 + * Components having the same number of representative colors may 
  66.431 + * share a dither table.
  66.432 + */
  66.433 +
  66.434 +LOCAL(void)
  66.435 +create_odither_tables (j_decompress_ptr cinfo)
  66.436 +{
  66.437 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  66.438 +  ODITHER_MATRIX_PTR odither;
  66.439 +  int i, j, nci;
  66.440 +
  66.441 +  for (i = 0; i < cinfo->out_color_components; i++) {
  66.442 +    nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  66.443 +    odither = NULL;		/* search for matching prior component */
  66.444 +    for (j = 0; j < i; j++) {
  66.445 +      if (nci == cquantize->Ncolors[j]) {
  66.446 +	odither = cquantize->odither[j];
  66.447 +	break;
  66.448 +      }
  66.449 +    }
  66.450 +    if (odither == NULL)	/* need a new table? */
  66.451 +      odither = make_odither_array(cinfo, nci);
  66.452 +    cquantize->odither[i] = odither;
  66.453 +  }
  66.454 +}
  66.455 +
  66.456 +
  66.457 +/*
  66.458 + * Map some rows of pixels to the output colormapped representation.
  66.459 + */
  66.460 +
  66.461 +METHODDEF(void)
  66.462 +color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  66.463 +		JSAMPARRAY output_buf, int num_rows)
  66.464 +/* General case, no dithering */
  66.465 +{
  66.466 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  66.467 +  JSAMPARRAY colorindex = cquantize->colorindex;
  66.468 +  register int pixcode, ci;
  66.469 +  register JSAMPROW ptrin, ptrout;
  66.470 +  int row;
  66.471 +  JDIMENSION col;
  66.472 +  JDIMENSION width = cinfo->output_width;
  66.473 +  register int nc = cinfo->out_color_components;
  66.474 +
  66.475 +  for (row = 0; row < num_rows; row++) {
  66.476 +    ptrin = input_buf[row];
  66.477 +    ptrout = output_buf[row];
  66.478 +    for (col = width; col > 0; col--) {
  66.479 +      pixcode = 0;
  66.480 +      for (ci = 0; ci < nc; ci++) {
  66.481 +	pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  66.482 +      }
  66.483 +      *ptrout++ = (JSAMPLE) pixcode;
  66.484 +    }
  66.485 +  }
  66.486 +}
  66.487 +
  66.488 +
  66.489 +METHODDEF(void)
  66.490 +color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  66.491 +		 JSAMPARRAY output_buf, int num_rows)
  66.492 +/* Fast path for out_color_components==3, no dithering */
  66.493 +{
  66.494 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  66.495 +  register int pixcode;
  66.496 +  register JSAMPROW ptrin, ptrout;
  66.497 +  JSAMPROW colorindex0 = cquantize->colorindex[0];
  66.498 +  JSAMPROW colorindex1 = cquantize->colorindex[1];
  66.499 +  JSAMPROW colorindex2 = cquantize->colorindex[2];
  66.500 +  int row;
  66.501 +  JDIMENSION col;
  66.502 +  JDIMENSION width = cinfo->output_width;
  66.503 +
  66.504 +  for (row = 0; row < num_rows; row++) {
  66.505 +    ptrin = input_buf[row];
  66.506 +    ptrout = output_buf[row];
  66.507 +    for (col = width; col > 0; col--) {
  66.508 +      pixcode  = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  66.509 +      pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  66.510 +      pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  66.511 +      *ptrout++ = (JSAMPLE) pixcode;
  66.512 +    }
  66.513 +  }
  66.514 +}
  66.515 +
  66.516 +
  66.517 +METHODDEF(void)
  66.518 +quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  66.519 +		     JSAMPARRAY output_buf, int num_rows)
  66.520 +/* General case, with ordered dithering */
  66.521 +{
  66.522 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  66.523 +  register JSAMPROW input_ptr;
  66.524 +  register JSAMPROW output_ptr;
  66.525 +  JSAMPROW colorindex_ci;
  66.526 +  int * dither;			/* points to active row of dither matrix */
  66.527 +  int row_index, col_index;	/* current indexes into dither matrix */
  66.528 +  int nc = cinfo->out_color_components;
  66.529 +  int ci;
  66.530 +  int row;
  66.531 +  JDIMENSION col;
  66.532 +  JDIMENSION width = cinfo->output_width;
  66.533 +
  66.534 +  for (row = 0; row < num_rows; row++) {
  66.535 +    /* Initialize output values to 0 so can process components separately */
  66.536 +    jzero_far((void FAR *) output_buf[row],
  66.537 +	      (size_t) (width * SIZEOF(JSAMPLE)));
  66.538 +    row_index = cquantize->row_index;
  66.539 +    for (ci = 0; ci < nc; ci++) {
  66.540 +      input_ptr = input_buf[row] + ci;
  66.541 +      output_ptr = output_buf[row];
  66.542 +      colorindex_ci = cquantize->colorindex[ci];
  66.543 +      dither = cquantize->odither[ci][row_index];
  66.544 +      col_index = 0;
  66.545 +
  66.546 +      for (col = width; col > 0; col--) {
  66.547 +	/* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  66.548 +	 * select output value, accumulate into output code for this pixel.
  66.549 +	 * Range-limiting need not be done explicitly, as we have extended
  66.550 +	 * the colorindex table to produce the right answers for out-of-range
  66.551 +	 * inputs.  The maximum dither is +- MAXJSAMPLE; this sets the
  66.552 +	 * required amount of padding.
  66.553 +	 */
  66.554 +	*output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  66.555 +	input_ptr += nc;
  66.556 +	output_ptr++;
  66.557 +	col_index = (col_index + 1) & ODITHER_MASK;
  66.558 +      }
  66.559 +    }
  66.560 +    /* Advance row index for next row */
  66.561 +    row_index = (row_index + 1) & ODITHER_MASK;
  66.562 +    cquantize->row_index = row_index;
  66.563 +  }
  66.564 +}
  66.565 +
  66.566 +
  66.567 +METHODDEF(void)
  66.568 +quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  66.569 +		      JSAMPARRAY output_buf, int num_rows)
  66.570 +/* Fast path for out_color_components==3, with ordered dithering */
  66.571 +{
  66.572 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  66.573 +  register int pixcode;
  66.574 +  register JSAMPROW input_ptr;
  66.575 +  register JSAMPROW output_ptr;
  66.576 +  JSAMPROW colorindex0 = cquantize->colorindex[0];
  66.577 +  JSAMPROW colorindex1 = cquantize->colorindex[1];
  66.578 +  JSAMPROW colorindex2 = cquantize->colorindex[2];
  66.579 +  int * dither0;		/* points to active row of dither matrix */
  66.580 +  int * dither1;
  66.581 +  int * dither2;
  66.582 +  int row_index, col_index;	/* current indexes into dither matrix */
  66.583 +  int row;
  66.584 +  JDIMENSION col;
  66.585 +  JDIMENSION width = cinfo->output_width;
  66.586 +
  66.587 +  for (row = 0; row < num_rows; row++) {
  66.588 +    row_index = cquantize->row_index;
  66.589 +    input_ptr = input_buf[row];
  66.590 +    output_ptr = output_buf[row];
  66.591 +    dither0 = cquantize->odither[0][row_index];
  66.592 +    dither1 = cquantize->odither[1][row_index];
  66.593 +    dither2 = cquantize->odither[2][row_index];
  66.594 +    col_index = 0;
  66.595 +
  66.596 +    for (col = width; col > 0; col--) {
  66.597 +      pixcode  = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  66.598 +					dither0[col_index]]);
  66.599 +      pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  66.600 +					dither1[col_index]]);
  66.601 +      pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  66.602 +					dither2[col_index]]);
  66.603 +      *output_ptr++ = (JSAMPLE) pixcode;
  66.604 +      col_index = (col_index + 1) & ODITHER_MASK;
  66.605 +    }
  66.606 +    row_index = (row_index + 1) & ODITHER_MASK;
  66.607 +    cquantize->row_index = row_index;
  66.608 +  }
  66.609 +}
  66.610 +
  66.611 +
  66.612 +METHODDEF(void)
  66.613 +quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  66.614 +		    JSAMPARRAY output_buf, int num_rows)
  66.615 +/* General case, with Floyd-Steinberg dithering */
  66.616 +{
  66.617 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  66.618 +  register LOCFSERROR cur;	/* current error or pixel value */
  66.619 +  LOCFSERROR belowerr;		/* error for pixel below cur */
  66.620 +  LOCFSERROR bpreverr;		/* error for below/prev col */
  66.621 +  LOCFSERROR bnexterr;		/* error for below/next col */
  66.622 +  LOCFSERROR delta;
  66.623 +  register FSERRPTR errorptr;	/* => fserrors[] at column before current */
  66.624 +  register JSAMPROW input_ptr;
  66.625 +  register JSAMPROW output_ptr;
  66.626 +  JSAMPROW colorindex_ci;
  66.627 +  JSAMPROW colormap_ci;
  66.628 +  int pixcode;
  66.629 +  int nc = cinfo->out_color_components;
  66.630 +  int dir;			/* 1 for left-to-right, -1 for right-to-left */
  66.631 +  int dirnc;			/* dir * nc */
  66.632 +  int ci;
  66.633 +  int row;
  66.634 +  JDIMENSION col;
  66.635 +  JDIMENSION width = cinfo->output_width;
  66.636 +  JSAMPLE *range_limit = cinfo->sample_range_limit;
  66.637 +  SHIFT_TEMPS
  66.638 +
  66.639 +  for (row = 0; row < num_rows; row++) {
  66.640 +    /* Initialize output values to 0 so can process components separately */
  66.641 +    jzero_far((void FAR *) output_buf[row],
  66.642 +	      (size_t) (width * SIZEOF(JSAMPLE)));
  66.643 +    for (ci = 0; ci < nc; ci++) {
  66.644 +      input_ptr = input_buf[row] + ci;
  66.645 +      output_ptr = output_buf[row];
  66.646 +      if (cquantize->on_odd_row) {
  66.647 +	/* work right to left in this row */
  66.648 +	input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  66.649 +	output_ptr += width-1;
  66.650 +	dir = -1;
  66.651 +	dirnc = -nc;
  66.652 +	errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  66.653 +      } else {
  66.654 +	/* work left to right in this row */
  66.655 +	dir = 1;
  66.656 +	dirnc = nc;
  66.657 +	errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  66.658 +      }
  66.659 +      colorindex_ci = cquantize->colorindex[ci];
  66.660 +      colormap_ci = cquantize->sv_colormap[ci];
  66.661 +      /* Preset error values: no error propagated to first pixel from left */
  66.662 +      cur = 0;
  66.663 +      /* and no error propagated to row below yet */
  66.664 +      belowerr = bpreverr = 0;
  66.665 +
  66.666 +      for (col = width; col > 0; col--) {
  66.667 +	/* cur holds the error propagated from the previous pixel on the
  66.668 +	 * current line.  Add the error propagated from the previous line
  66.669 +	 * to form the complete error correction term for this pixel, and
  66.670 +	 * round the error term (which is expressed * 16) to an integer.
  66.671 +	 * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  66.672 +	 * for either sign of the error value.
  66.673 +	 * Note: errorptr points to *previous* column's array entry.
  66.674 +	 */
  66.675 +	cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  66.676 +	/* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  66.677 +	 * The maximum error is +- MAXJSAMPLE; this sets the required size
  66.678 +	 * of the range_limit array.
  66.679 +	 */
  66.680 +	cur += GETJSAMPLE(*input_ptr);
  66.681 +	cur = GETJSAMPLE(range_limit[cur]);
  66.682 +	/* Select output value, accumulate into output code for this pixel */
  66.683 +	pixcode = GETJSAMPLE(colorindex_ci[cur]);
  66.684 +	*output_ptr += (JSAMPLE) pixcode;
  66.685 +	/* Compute actual representation error at this pixel */
  66.686 +	/* Note: we can do this even though we don't have the final */
  66.687 +	/* pixel code, because the colormap is orthogonal. */
  66.688 +	cur -= GETJSAMPLE(colormap_ci[pixcode]);
  66.689 +	/* Compute error fractions to be propagated to adjacent pixels.
  66.690 +	 * Add these into the running sums, and simultaneously shift the
  66.691 +	 * next-line error sums left by 1 column.
  66.692 +	 */
  66.693 +	bnexterr = cur;
  66.694 +	delta = cur * 2;
  66.695 +	cur += delta;		/* form error * 3 */
  66.696 +	errorptr[0] = (FSERROR) (bpreverr + cur);
  66.697 +	cur += delta;		/* form error * 5 */
  66.698 +	bpreverr = belowerr + cur;
  66.699 +	belowerr = bnexterr;
  66.700 +	cur += delta;		/* form error * 7 */
  66.701 +	/* At this point cur contains the 7/16 error value to be propagated
  66.702 +	 * to the next pixel on the current line, and all the errors for the
  66.703 +	 * next line have been shifted over. We are therefore ready to move on.
  66.704 +	 */
  66.705 +	input_ptr += dirnc;	/* advance input ptr to next column */
  66.706 +	output_ptr += dir;	/* advance output ptr to next column */
  66.707 +	errorptr += dir;	/* advance errorptr to current column */
  66.708 +      }
  66.709 +      /* Post-loop cleanup: we must unload the final error value into the
  66.710 +       * final fserrors[] entry.  Note we need not unload belowerr because
  66.711 +       * it is for the dummy column before or after the actual array.
  66.712 +       */
  66.713 +      errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  66.714 +    }
  66.715 +    cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  66.716 +  }
  66.717 +}
  66.718 +
  66.719 +
  66.720 +/*
  66.721 + * Allocate workspace for Floyd-Steinberg errors.
  66.722 + */
  66.723 +
  66.724 +LOCAL(void)
  66.725 +alloc_fs_workspace (j_decompress_ptr cinfo)
  66.726 +{
  66.727 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  66.728 +  size_t arraysize;
  66.729 +  int i;
  66.730 +
  66.731 +  arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  66.732 +  for (i = 0; i < cinfo->out_color_components; i++) {
  66.733 +    cquantize->fserrors[i] = (FSERRPTR)
  66.734 +      (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  66.735 +  }
  66.736 +}
  66.737 +
  66.738 +
  66.739 +/*
  66.740 + * Initialize for one-pass color quantization.
  66.741 + */
  66.742 +
  66.743 +METHODDEF(void)
  66.744 +start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  66.745 +{
  66.746 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  66.747 +  size_t arraysize;
  66.748 +  int i;
  66.749 +
  66.750 +  /* Install my colormap. */
  66.751 +  cinfo->colormap = cquantize->sv_colormap;
  66.752 +  cinfo->actual_number_of_colors = cquantize->sv_actual;
  66.753 +
  66.754 +  /* Initialize for desired dithering mode. */
  66.755 +  switch (cinfo->dither_mode) {
  66.756 +  case JDITHER_NONE:
  66.757 +    if (cinfo->out_color_components == 3)
  66.758 +      cquantize->pub.color_quantize = color_quantize3;
  66.759 +    else
  66.760 +      cquantize->pub.color_quantize = color_quantize;
  66.761 +    break;
  66.762 +  case JDITHER_ORDERED:
  66.763 +    if (cinfo->out_color_components == 3)
  66.764 +      cquantize->pub.color_quantize = quantize3_ord_dither;
  66.765 +    else
  66.766 +      cquantize->pub.color_quantize = quantize_ord_dither;
  66.767 +    cquantize->row_index = 0;	/* initialize state for ordered dither */
  66.768 +    /* If user changed to ordered dither from another mode,
  66.769 +     * we must recreate the color index table with padding.
  66.770 +     * This will cost extra space, but probably isn't very likely.
  66.771 +     */
  66.772 +    if (! cquantize->is_padded)
  66.773 +      create_colorindex(cinfo);
  66.774 +    /* Create ordered-dither tables if we didn't already. */
  66.775 +    if (cquantize->odither[0] == NULL)
  66.776 +      create_odither_tables(cinfo);
  66.777 +    break;
  66.778 +  case JDITHER_FS:
  66.779 +    cquantize->pub.color_quantize = quantize_fs_dither;
  66.780 +    cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  66.781 +    /* Allocate Floyd-Steinberg workspace if didn't already. */
  66.782 +    if (cquantize->fserrors[0] == NULL)
  66.783 +      alloc_fs_workspace(cinfo);
  66.784 +    /* Initialize the propagated errors to zero. */
  66.785 +    arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  66.786 +    for (i = 0; i < cinfo->out_color_components; i++)
  66.787 +      jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  66.788 +    break;
  66.789 +  default:
  66.790 +    ERREXIT(cinfo, JERR_NOT_COMPILED);
  66.791 +    break;
  66.792 +  }
  66.793 +}
  66.794 +
  66.795 +
  66.796 +/*
  66.797 + * Finish up at the end of the pass.
  66.798 + */
  66.799 +
  66.800 +METHODDEF(void)
  66.801 +finish_pass_1_quant (j_decompress_ptr cinfo)
  66.802 +{
  66.803 +  /* no work in 1-pass case */
  66.804 +}
  66.805 +
  66.806 +
  66.807 +/*
  66.808 + * Switch to a new external colormap between output passes.
  66.809 + * Shouldn't get to this module!
  66.810 + */
  66.811 +
  66.812 +METHODDEF(void)
  66.813 +new_color_map_1_quant (j_decompress_ptr cinfo)
  66.814 +{
  66.815 +  ERREXIT(cinfo, JERR_MODE_CHANGE);
  66.816 +}
  66.817 +
  66.818 +
  66.819 +/*
  66.820 + * Module initialization routine for 1-pass color quantization.
  66.821 + */
  66.822 +
  66.823 +GLOBAL(void)
  66.824 +jinit_1pass_quantizer (j_decompress_ptr cinfo)
  66.825 +{
  66.826 +  my_cquantize_ptr cquantize;
  66.827 +
  66.828 +  cquantize = (my_cquantize_ptr)
  66.829 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  66.830 +				SIZEOF(my_cquantizer));
  66.831 +  cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  66.832 +  cquantize->pub.start_pass = start_pass_1_quant;
  66.833 +  cquantize->pub.finish_pass = finish_pass_1_quant;
  66.834 +  cquantize->pub.new_color_map = new_color_map_1_quant;
  66.835 +  cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  66.836 +  cquantize->odither[0] = NULL;	/* Also flag odither arrays not allocated */
  66.837 +
  66.838 +  /* Make sure my internal arrays won't overflow */
  66.839 +  if (cinfo->out_color_components > MAX_Q_COMPS)
  66.840 +    ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  66.841 +  /* Make sure colormap indexes can be represented by JSAMPLEs */
  66.842 +  if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  66.843 +    ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  66.844 +
  66.845 +  /* Create the colormap and color index table. */
  66.846 +  create_colormap(cinfo);
  66.847 +  create_colorindex(cinfo);
  66.848 +
  66.849 +  /* Allocate Floyd-Steinberg workspace now if requested.
  66.850 +   * We do this now since it is FAR storage and may affect the memory
  66.851 +   * manager's space calculations.  If the user changes to FS dither
  66.852 +   * mode in a later pass, we will allocate the space then, and will
  66.853 +   * possibly overrun the max_memory_to_use setting.
  66.854 +   */
  66.855 +  if (cinfo->dither_mode == JDITHER_FS)
  66.856 +    alloc_fs_workspace(cinfo);
  66.857 +}
  66.858 +
  66.859 +#endif /* QUANT_1PASS_SUPPORTED */
    67.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    67.2 +++ b/libs/libjpeg/jquant2.c	Thu Sep 08 06:28:38 2011 +0300
    67.3 @@ -0,0 +1,1310 @@
    67.4 +/*
    67.5 + * jquant2.c
    67.6 + *
    67.7 + * Copyright (C) 1991-1996, Thomas G. Lane.
    67.8 + * This file is part of the Independent JPEG Group's software.
    67.9 + * For conditions of distribution and use, see the accompanying README file.
   67.10 + *
   67.11 + * This file contains 2-pass color quantization (color mapping) routines.
   67.12 + * These routines provide selection of a custom color map for an image,
   67.13 + * followed by mapping of the image to that color map, with optional
   67.14 + * Floyd-Steinberg dithering.
   67.15 + * It is also possible to use just the second pass to map to an arbitrary
   67.16 + * externally-given color map.
   67.17 + *
   67.18 + * Note: ordered dithering is not supported, since there isn't any fast
   67.19 + * way to compute intercolor distances; it's unclear that ordered dither's
   67.20 + * fundamental assumptions even hold with an irregularly spaced color map.
   67.21 + */
   67.22 +
   67.23 +#define JPEG_INTERNALS
   67.24 +#include "jinclude.h"
   67.25 +#include "jpeglib.h"
   67.26 +
   67.27 +#ifdef QUANT_2PASS_SUPPORTED
   67.28 +
   67.29 +
   67.30 +/*
   67.31 + * This module implements the well-known Heckbert paradigm for color
   67.32 + * quantization.  Most of the ideas used here can be traced back to
   67.33 + * Heckbert's seminal paper
   67.34 + *   Heckbert, Paul.  "Color Image Quantization for Frame Buffer Display",
   67.35 + *   Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
   67.36 + *
   67.37 + * In the first pass over the image, we accumulate a histogram showing the
   67.38 + * usage count of each possible color.  To keep the histogram to a reasonable
   67.39 + * size, we reduce the precision of the input; typical practice is to retain
   67.40 + * 5 or 6 bits per color, so that 8 or 4 different input values are counted
   67.41 + * in the same histogram cell.
   67.42 + *
   67.43 + * Next, the color-selection step begins with a box representing the whole
   67.44 + * color space, and repeatedly splits the "largest" remaining box until we
   67.45 + * have as many boxes as desired colors.  Then the mean color in each
   67.46 + * remaining box becomes one of the possible output colors.
   67.47 + * 
   67.48 + * The second pass over the image maps each input pixel to the closest output
   67.49 + * color (optionally after applying a Floyd-Steinberg dithering correction).
   67.50 + * This mapping is logically trivial, but making it go fast enough requires
   67.51 + * considerable care.
   67.52 + *
   67.53 + * Heckbert-style quantizers vary a good deal in their policies for choosing
   67.54 + * the "largest" box and deciding where to cut it.  The particular policies
   67.55 + * used here have proved out well in experimental comparisons, but better ones
   67.56 + * may yet be found.
   67.57 + *
   67.58 + * In earlier versions of the IJG code, this module quantized in YCbCr color
   67.59 + * space, processing the raw upsampled data without a color conversion step.
   67.60 + * This allowed the color conversion math to be done only once per colormap
   67.61 + * entry, not once per pixel.  However, that optimization precluded other
   67.62 + * useful optimizations (such as merging color conversion with upsampling)
   67.63 + * and it also interfered with desired capabilities such as quantizing to an
   67.64 + * externally-supplied colormap.  We have therefore abandoned that approach.
   67.65 + * The present code works in the post-conversion color space, typically RGB.
   67.66 + *
   67.67 + * To improve the visual quality of the results, we actually work in scaled
   67.68 + * RGB space, giving G distances more weight than R, and R in turn more than
   67.69 + * B.  To do everything in integer math, we must use integer scale factors.
   67.70 + * The 2/3/1 scale factors used here correspond loosely to the relative
   67.71 + * weights of the colors in the NTSC grayscale equation.
   67.72 + * If you want to use this code to quantize a non-RGB color space, you'll
   67.73 + * probably need to change these scale factors.
   67.74 + */
   67.75 +
   67.76 +#define R_SCALE 2		/* scale R distances by this much */
   67.77 +#define G_SCALE 3		/* scale G distances by this much */
   67.78 +#define B_SCALE 1		/* and B by this much */
   67.79 +
   67.80 +/* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
   67.81 + * in jmorecfg.h.  As the code stands, it will do the right thing for R,G,B
   67.82 + * and B,G,R orders.  If you define some other weird order in jmorecfg.h,
   67.83 + * you'll get compile errors until you extend this logic.  In that case
   67.84 + * you'll probably want to tweak the histogram sizes too.
   67.85 + */
   67.86 +
   67.87 +#if RGB_RED == 0
   67.88 +#define C0_SCALE R_SCALE
   67.89 +#endif
   67.90 +#if RGB_BLUE == 0
   67.91 +#define C0_SCALE B_SCALE
   67.92 +#endif
   67.93 +#if RGB_GREEN == 1
   67.94 +#define C1_SCALE G_SCALE
   67.95 +#endif
   67.96 +#if RGB_RED == 2
   67.97 +#define C2_SCALE R_SCALE
   67.98 +#endif
   67.99 +#if RGB_BLUE == 2
  67.100 +#define C2_SCALE B_SCALE
  67.101 +#endif
  67.102 +
  67.103 +
  67.104 +/*
  67.105 + * First we have the histogram data structure and routines for creating it.
  67.106 + *
  67.107 + * The number of bits of precision can be adjusted by changing these symbols.
  67.108 + * We recommend keeping 6 bits for G and 5 each for R and B.
  67.109 + * If you have plenty of memory and cycles, 6 bits all around gives marginally
  67.110 + * better results; if you are short of memory, 5 bits all around will save
  67.111 + * some space but degrade the results.
  67.112 + * To maintain a fully accurate histogram, we'd need to allocate a "long"
  67.113 + * (preferably unsigned long) for each cell.  In practice this is overkill;
  67.114 + * we can get by with 16 bits per cell.  Few of the cell counts will overflow,
  67.115 + * and clamping those that do overflow to the maximum value will give close-
  67.116 + * enough results.  This reduces the recommended histogram size from 256Kb
  67.117 + * to 128Kb, which is a useful savings on PC-class machines.
  67.118 + * (In the second pass the histogram space is re-used for pixel mapping data;
  67.119 + * in that capacity, each cell must be able to store zero to the number of
  67.120 + * desired colors.  16 bits/cell is plenty for that too.)
  67.121 + * Since the JPEG code is intended to run in small memory model on 80x86
  67.122 + * machines, we can't just allocate the histogram in one chunk.  Instead
  67.123 + * of a true 3-D array, we use a row of pointers to 2-D arrays.  Each
  67.124 + * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  67.125 + * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries.  Note that
  67.126 + * on 80x86 machines, the pointer row is in near memory but the actual
  67.127 + * arrays are in far memory (same arrangement as we use for image arrays).
  67.128 + */
  67.129 +
  67.130 +#define MAXNUMCOLORS  (MAXJSAMPLE+1) /* maximum size of colormap */
  67.131 +
  67.132 +/* These will do the right thing for either R,G,B or B,G,R color order,
  67.133 + * but you may not like the results for other color orders.
  67.134 + */
  67.135 +#define HIST_C0_BITS  5		/* bits of precision in R/B histogram */
  67.136 +#define HIST_C1_BITS  6		/* bits of precision in G histogram */
  67.137 +#define HIST_C2_BITS  5		/* bits of precision in B/R histogram */
  67.138 +
  67.139 +/* Number of elements along histogram axes. */
  67.140 +#define HIST_C0_ELEMS  (1<<HIST_C0_BITS)
  67.141 +#define HIST_C1_ELEMS  (1<<HIST_C1_BITS)
  67.142 +#define HIST_C2_ELEMS  (1<<HIST_C2_BITS)
  67.143 +
  67.144 +/* These are the amounts to shift an input value to get a histogram index. */
  67.145 +#define C0_SHIFT  (BITS_IN_JSAMPLE-HIST_C0_BITS)
  67.146 +#define C1_SHIFT  (BITS_IN_JSAMPLE-HIST_C1_BITS)
  67.147 +#define C2_SHIFT  (BITS_IN_JSAMPLE-HIST_C2_BITS)
  67.148 +
  67.149 +
  67.150 +typedef UINT16 histcell;	/* histogram cell; prefer an unsigned type */
  67.151 +
  67.152 +typedef histcell FAR * histptr;	/* for pointers to histogram cells */
  67.153 +
  67.154 +typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  67.155 +typedef hist1d FAR * hist2d;	/* type for the 2nd-level pointers */
  67.156 +typedef hist2d * hist3d;	/* type for top-level pointer */
  67.157 +
  67.158 +
  67.159 +/* Declarations for Floyd-Steinberg dithering.
  67.160 + *
  67.161 + * Errors are accumulated into the array fserrors[], at a resolution of
  67.162 + * 1/16th of a pixel count.  The error at a given pixel is propagated
  67.163 + * to its not-yet-processed neighbors using the standard F-S fractions,
  67.164 + *		...	(here)	7/16
  67.165 + *		3/16	5/16	1/16
  67.166 + * We work left-to-right on even rows, right-to-left on odd rows.
  67.167 + *
  67.168 + * We can get away with a single array (holding one row's worth of errors)
  67.169 + * by using it to store the current row's errors at pixel columns not yet
  67.170 + * processed, but the next row's errors at columns already processed.  We
  67.171 + * need only a few extra variables to hold the errors immediately around the
  67.172 + * current column.  (If we are lucky, those variables are in registers, but
  67.173 + * even if not, they're probably cheaper to access than array elements are.)
  67.174 + *
  67.175 + * The fserrors[] array has (#columns + 2) entries; the extra entry at
  67.176 + * each end saves us from special-casing the first and last pixels.
  67.177 + * Each entry is three values long, one value for each color component.
  67.178 + *
  67.179 + * Note: on a wide image, we might not have enough room in a PC's near data
  67.180 + * segment to hold the error array; so it is allocated with alloc_large.
  67.181 + */
  67.182 +
  67.183 +#if BITS_IN_JSAMPLE == 8
  67.184 +typedef INT16 FSERROR;		/* 16 bits should be enough */
  67.185 +typedef int LOCFSERROR;		/* use 'int' for calculation temps */
  67.186 +#else
  67.187 +typedef INT32 FSERROR;		/* may need more than 16 bits */
  67.188 +typedef INT32 LOCFSERROR;	/* be sure calculation temps are big enough */
  67.189 +#endif
  67.190 +
  67.191 +typedef FSERROR FAR *FSERRPTR;	/* pointer to error array (in FAR storage!) */
  67.192 +
  67.193 +
  67.194 +/* Private subobject */
  67.195 +
  67.196 +typedef struct {
  67.197 +  struct jpeg_color_quantizer pub; /* public fields */
  67.198 +
  67.199 +  /* Space for the eventually created colormap is stashed here */
  67.200 +  JSAMPARRAY sv_colormap;	/* colormap allocated at init time */
  67.201 +  int desired;			/* desired # of colors = size of colormap */
  67.202 +
  67.203 +  /* Variables for accumulating image statistics */
  67.204 +  hist3d histogram;		/* pointer to the histogram */
  67.205 +
  67.206 +  boolean needs_zeroed;		/* TRUE if next pass must zero histogram */
  67.207 +
  67.208 +  /* Variables for Floyd-Steinberg dithering */
  67.209 +  FSERRPTR fserrors;		/* accumulated errors */
  67.210 +  boolean on_odd_row;		/* flag to remember which row we are on */
  67.211 +  int * error_limiter;		/* table for clamping the applied error */
  67.212 +} my_cquantizer;
  67.213 +
  67.214 +typedef my_cquantizer * my_cquantize_ptr;
  67.215 +
  67.216 +
  67.217 +/*
  67.218 + * Prescan some rows of pixels.
  67.219 + * In this module the prescan simply updates the histogram, which has been
  67.220 + * initialized to zeroes by start_pass.
  67.221 + * An output_buf parameter is required by the method signature, but no data
  67.222 + * is actually output (in fact the buffer controller is probably passing a
  67.223 + * NULL pointer).
  67.224 + */
  67.225 +
  67.226 +METHODDEF(void)
  67.227 +prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  67.228 +		  JSAMPARRAY output_buf, int num_rows)
  67.229 +{
  67.230 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  67.231 +  register JSAMPROW ptr;
  67.232 +  register histptr histp;
  67.233 +  register hist3d histogram = cquantize->histogram;
  67.234 +  int row;
  67.235 +  JDIMENSION col;
  67.236 +  JDIMENSION width = cinfo->output_width;
  67.237 +
  67.238 +  for (row = 0; row < num_rows; row++) {
  67.239 +    ptr = input_buf[row];
  67.240 +    for (col = width; col > 0; col--) {
  67.241 +      /* get pixel value and index into the histogram */
  67.242 +      histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  67.243 +			 [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  67.244 +			 [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  67.245 +      /* increment, check for overflow and undo increment if so. */
  67.246 +      if (++(*histp) <= 0)
  67.247 +	(*histp)--;
  67.248 +      ptr += 3;
  67.249 +    }
  67.250 +  }
  67.251 +}
  67.252 +
  67.253 +
  67.254 +/*
  67.255 + * Next we have the really interesting routines: selection of a colormap
  67.256 + * given the completed histogram.
  67.257 + * These routines work with a list of "boxes", each representing a rectangular
  67.258 + * subset of the input color space (to histogram precision).
  67.259 + */
  67.260 +
  67.261 +typedef struct {
  67.262 +  /* The bounds of the box (inclusive); expressed as histogram indexes */
  67.263 +  int c0min, c0max;
  67.264 +  int c1min, c1max;
  67.265 +  int c2min, c2max;
  67.266 +  /* The volume (actually 2-norm) of the box */
  67.267 +  INT32 volume;
  67.268 +  /* The number of nonzero histogram cells within this box */
  67.269 +  long colorcount;
  67.270 +} box;
  67.271 +
  67.272 +typedef box * boxptr;
  67.273 +
  67.274 +
  67.275 +LOCAL(boxptr)
  67.276 +find_biggest_color_pop (boxptr boxlist, int numboxes)
  67.277 +/* Find the splittable box with the largest color population */
  67.278 +/* Returns NULL if no splittable boxes remain */
  67.279 +{
  67.280 +  register boxptr boxp;
  67.281 +  register int i;
  67.282 +  register long maxc = 0;
  67.283 +  boxptr which = NULL;
  67.284 +  
  67.285 +  for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  67.286 +    if (boxp->colorcount > maxc && boxp->volume > 0) {
  67.287 +      which = boxp;
  67.288 +      maxc = boxp->colorcount;
  67.289 +    }
  67.290 +  }
  67.291 +  return which;
  67.292 +}
  67.293 +
  67.294 +
  67.295 +LOCAL(boxptr)
  67.296 +find_biggest_volume (boxptr boxlist, int numboxes)
  67.297 +/* Find the splittable box with the largest (scaled) volume */
  67.298 +/* Returns NULL if no splittable boxes remain */
  67.299 +{
  67.300 +  register boxptr boxp;
  67.301 +  register int i;
  67.302 +  register INT32 maxv = 0;
  67.303 +  boxptr which = NULL;
  67.304 +  
  67.305 +  for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  67.306 +    if (boxp->volume > maxv) {
  67.307 +      which = boxp;
  67.308 +      maxv = boxp->volume;
  67.309 +    }
  67.310 +  }
  67.311 +  return which;
  67.312 +}
  67.313 +
  67.314 +
  67.315 +LOCAL(void)
  67.316 +update_box (j_decompress_ptr cinfo, boxptr boxp)
  67.317 +/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  67.318 +/* and recompute its volume and population */
  67.319 +{
  67.320 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  67.321 +  hist3d histogram = cquantize->histogram;
  67.322 +  histptr histp;
  67.323 +  int c0,c1,c2;
  67.324 +  int c0min,c0max,c1min,c1max,c2min,c2max;
  67.325 +  INT32 dist0,dist1,dist2;
  67.326 +  long ccount;
  67.327 +  
  67.328 +  c0min = boxp->c0min;  c0max = boxp->c0max;
  67.329 +  c1min = boxp->c1min;  c1max = boxp->c1max;
  67.330 +  c2min = boxp->c2min;  c2max = boxp->c2max;
  67.331 +  
  67.332 +  if (c0max > c0min)
  67.333 +    for (c0 = c0min; c0 <= c0max; c0++)
  67.334 +      for (c1 = c1min; c1 <= c1max; c1++) {
  67.335 +	histp = & histogram[c0][c1][c2min];
  67.336 +	for (c2 = c2min; c2 <= c2max; c2++)
  67.337 +	  if (*histp++ != 0) {
  67.338 +	    boxp->c0min = c0min = c0;
  67.339 +	    goto have_c0min;
  67.340 +	  }
  67.341 +      }
  67.342 + have_c0min:
  67.343 +  if (c0max > c0min)
  67.344 +    for (c0 = c0max; c0 >= c0min; c0--)
  67.345 +      for (c1 = c1min; c1 <= c1max; c1++) {
  67.346 +	histp = & histogram[c0][c1][c2min];
  67.347 +	for (c2 = c2min; c2 <= c2max; c2++)
  67.348 +	  if (*histp++ != 0) {
  67.349 +	    boxp->c0max = c0max = c0;
  67.350 +	    goto have_c0max;
  67.351 +	  }
  67.352 +      }
  67.353 + have_c0max:
  67.354 +  if (c1max > c1min)
  67.355 +    for (c1 = c1min; c1 <= c1max; c1++)
  67.356 +      for (c0 = c0min; c0 <= c0max; c0++) {
  67.357 +	histp = & histogram[c0][c1][c2min];
  67.358 +	for (c2 = c2min; c2 <= c2max; c2++)
  67.359 +	  if (*histp++ != 0) {
  67.360 +	    boxp->c1min = c1min = c1;
  67.361 +	    goto have_c1min;
  67.362 +	  }
  67.363 +      }
  67.364 + have_c1min:
  67.365 +  if (c1max > c1min)
  67.366 +    for (c1 = c1max; c1 >= c1min; c1--)
  67.367 +      for (c0 = c0min; c0 <= c0max; c0++) {
  67.368 +	histp = & histogram[c0][c1][c2min];
  67.369 +	for (c2 = c2min; c2 <= c2max; c2++)
  67.370 +	  if (*histp++ != 0) {
  67.371 +	    boxp->c1max = c1max = c1;
  67.372 +	    goto have_c1max;
  67.373 +	  }
  67.374 +      }
  67.375 + have_c1max:
  67.376 +  if (c2max > c2min)
  67.377 +    for (c2 = c2min; c2 <= c2max; c2++)
  67.378 +      for (c0 = c0min; c0 <= c0max; c0++) {
  67.379 +	histp = & histogram[c0][c1min][c2];
  67.380 +	for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  67.381 +	  if (*histp != 0) {
  67.382 +	    boxp->c2min = c2min = c2;
  67.383 +	    goto have_c2min;
  67.384 +	  }
  67.385 +      }
  67.386 + have_c2min:
  67.387 +  if (c2max > c2min)
  67.388 +    for (c2 = c2max; c2 >= c2min; c2--)
  67.389 +      for (c0 = c0min; c0 <= c0max; c0++) {
  67.390 +	histp = & histogram[c0][c1min][c2];
  67.391 +	for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  67.392 +	  if (*histp != 0) {
  67.393 +	    boxp->c2max = c2max = c2;
  67.394 +	    goto have_c2max;
  67.395 +	  }
  67.396 +      }
  67.397 + have_c2max:
  67.398 +
  67.399 +  /* Update box volume.
  67.400 +   * We use 2-norm rather than real volume here; this biases the method
  67.401 +   * against making long narrow boxes, and it has the side benefit that
  67.402 +   * a box is splittable iff norm > 0.
  67.403 +   * Since the differences are expressed in histogram-cell units,
  67.404 +   * we have to shift back to JSAMPLE units to get consistent distances;
  67.405 +   * after which, we scale according to the selected distance scale factors.
  67.406 +   */
  67.407 +  dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  67.408 +  dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  67.409 +  dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  67.410 +  boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  67.411 +  
  67.412 +  /* Now scan remaining volume of box and compute population */
  67.413 +  ccount = 0;
  67.414 +  for (c0 = c0min; c0 <= c0max; c0++)
  67.415 +    for (c1 = c1min; c1 <= c1max; c1++) {
  67.416 +      histp = & histogram[c0][c1][c2min];
  67.417 +      for (c2 = c2min; c2 <= c2max; c2++, histp++)
  67.418 +	if (*histp != 0) {
  67.419 +	  ccount++;
  67.420 +	}
  67.421 +    }
  67.422 +  boxp->colorcount = ccount;
  67.423 +}
  67.424 +
  67.425 +
  67.426 +LOCAL(int)
  67.427 +median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  67.428 +	    int desired_colors)
  67.429 +/* Repeatedly select and split the largest box until we have enough boxes */
  67.430 +{
  67.431 +  int n,lb;
  67.432 +  int c0,c1,c2,cmax;
  67.433 +  register boxptr b1,b2;
  67.434 +
  67.435 +  while (numboxes < desired_colors) {
  67.436 +    /* Select box to split.
  67.437 +     * Current algorithm: by population for first half, then by volume.
  67.438 +     */
  67.439 +    if (numboxes*2 <= desired_colors) {
  67.440 +      b1 = find_biggest_color_pop(boxlist, numboxes);
  67.441 +    } else {
  67.442 +      b1 = find_biggest_volume(boxlist, numboxes);
  67.443 +    }
  67.444 +    if (b1 == NULL)		/* no splittable boxes left! */
  67.445 +      break;
  67.446 +    b2 = &boxlist[numboxes];	/* where new box will go */
  67.447 +    /* Copy the color bounds to the new box. */
  67.448 +    b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  67.449 +    b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  67.450 +    /* Choose which axis to split the box on.
  67.451 +     * Current algorithm: longest scaled axis.
  67.452 +     * See notes in update_box about scaling distances.
  67.453 +     */
  67.454 +    c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  67.455 +    c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  67.456 +    c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  67.457 +    /* We want to break any ties in favor of green, then red, blue last.
  67.458 +     * This code does the right thing for R,G,B or B,G,R color orders only.
  67.459 +     */
  67.460 +#if RGB_RED == 0
  67.461 +    cmax = c1; n = 1;
  67.462 +    if (c0 > cmax) { cmax = c0; n = 0; }
  67.463 +    if (c2 > cmax) { n = 2; }
  67.464 +#else
  67.465 +    cmax = c1; n = 1;
  67.466 +    if (c2 > cmax) { cmax = c2; n = 2; }
  67.467 +    if (c0 > cmax) { n = 0; }
  67.468 +#endif
  67.469 +    /* Choose split point along selected axis, and update box bounds.
  67.470 +     * Current algorithm: split at halfway point.
  67.471 +     * (Since the box has been shrunk to minimum volume,
  67.472 +     * any split will produce two nonempty subboxes.)
  67.473 +     * Note that lb value is max for lower box, so must be < old max.
  67.474 +     */
  67.475 +    switch (n) {
  67.476 +    case 0:
  67.477 +      lb = (b1->c0max + b1->c0min) / 2;
  67.478 +      b1->c0max = lb;
  67.479 +      b2->c0min = lb+1;
  67.480 +      break;
  67.481 +    case 1:
  67.482 +      lb = (b1->c1max + b1->c1min) / 2;
  67.483 +      b1->c1max = lb;
  67.484 +      b2->c1min = lb+1;
  67.485 +      break;
  67.486 +    case 2:
  67.487 +      lb = (b1->c2max + b1->c2min) / 2;
  67.488 +      b1->c2max = lb;
  67.489 +      b2->c2min = lb+1;
  67.490 +      break;
  67.491 +    }
  67.492 +    /* Update stats for boxes */
  67.493 +    update_box(cinfo, b1);
  67.494 +    update_box(cinfo, b2);
  67.495 +    numboxes++;
  67.496 +  }
  67.497 +  return numboxes;
  67.498 +}
  67.499 +
  67.500 +
  67.501 +LOCAL(void)
  67.502 +compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  67.503 +/* Compute representative color for a box, put it in colormap[icolor] */
  67.504 +{
  67.505 +  /* Current algorithm: mean weighted by pixels (not colors) */
  67.506 +  /* Note it is important to get the rounding correct! */
  67.507 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  67.508 +  hist3d histogram = cquantize->histogram;
  67.509 +  histptr histp;
  67.510 +  int c0,c1,c2;
  67.511 +  int c0min,c0max,c1min,c1max,c2min,c2max;
  67.512 +  long count;
  67.513 +  long total = 0;
  67.514 +  long c0total = 0;
  67.515 +  long c1total = 0;
  67.516 +  long c2total = 0;
  67.517 +  
  67.518 +  c0min = boxp->c0min;  c0max = boxp->c0max;
  67.519 +  c1min = boxp->c1min;  c1max = boxp->c1max;
  67.520 +  c2min = boxp->c2min;  c2max = boxp->c2max;
  67.521 +  
  67.522 +  for (c0 = c0min; c0 <= c0max; c0++)
  67.523 +    for (c1 = c1min; c1 <= c1max; c1++) {
  67.524 +      histp = & histogram[c0][c1][c2min];
  67.525 +      for (c2 = c2min; c2 <= c2max; c2++) {
  67.526 +	if ((count = *histp++) != 0) {
  67.527 +	  total += count;
  67.528 +	  c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  67.529 +	  c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  67.530 +	  c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  67.531 +	}
  67.532 +      }
  67.533 +    }
  67.534 +  
  67.535 +  cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  67.536 +  cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  67.537 +  cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  67.538 +}
  67.539 +
  67.540 +
  67.541 +LOCAL(void)
  67.542 +select_colors (j_decompress_ptr cinfo, int desired_colors)
  67.543 +/* Master routine for color selection */
  67.544 +{
  67.545 +  boxptr boxlist;
  67.546 +  int numboxes;
  67.547 +  int i;
  67.548 +
  67.549 +  /* Allocate workspace for box list */
  67.550 +  boxlist = (boxptr) (*cinfo->mem->alloc_small)
  67.551 +    ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  67.552 +  /* Initialize one box containing whole space */
  67.553 +  numboxes = 1;
  67.554 +  boxlist[0].c0min = 0;
  67.555 +  boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  67.556 +  boxlist[0].c1min = 0;
  67.557 +  boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  67.558 +  boxlist[0].c2min = 0;
  67.559 +  boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  67.560 +  /* Shrink it to actually-used volume and set its statistics */
  67.561 +  update_box(cinfo, & boxlist[0]);
  67.562 +  /* Perform median-cut to produce final box list */
  67.563 +  numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  67.564 +  /* Compute the representative color for each box, fill colormap */
  67.565 +  for (i = 0; i < numboxes; i++)
  67.566 +    compute_color(cinfo, & boxlist[i], i);
  67.567 +  cinfo->actual_number_of_colors = numboxes;
  67.568 +  TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  67.569 +}
  67.570 +
  67.571 +
  67.572 +/*
  67.573 + * These routines are concerned with the time-critical task of mapping input
  67.574 + * colors to the nearest color in the selected colormap.
  67.575 + *
  67.576 + * We re-use the histogram space as an "inverse color map", essentially a
  67.577 + * cache for the results of nearest-color searches.  All colors within a
  67.578 + * histogram cell will be mapped to the same colormap entry, namely the one
  67.579 + * closest to the cell's center.  This may not be quite the closest entry to
  67.580 + * the actual input color, but it's almost as good.  A zero in the cache
  67.581 + * indicates we haven't found the nearest color for that cell yet; the array
  67.582 + * is cleared to zeroes before starting the mapping pass.  When we find the
  67.583 + * nearest color for a cell, its colormap index plus one is recorded in the
  67.584 + * cache for future use.  The pass2 scanning routines call fill_inverse_cmap
  67.585 + * when they need to use an unfilled entry in the cache.
  67.586 + *
  67.587 + * Our method of efficiently finding nearest colors is based on the "locally
  67.588 + * sorted search" idea described by Heckbert and on the incremental distance
  67.589 + * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  67.590 + * Gems II (James Arvo, ed.  Academic Press, 1991).  Thomas points out that
  67.591 + * the distances from a given colormap entry to each cell of the histogram can
  67.592 + * be computed quickly using an incremental method: the differences between
  67.593 + * distances to adjacent cells themselves differ by a constant.  This allows a
  67.594 + * fairly fast implementation of the "brute force" approach of computing the
  67.595 + * distance from every colormap entry to every histogram cell.  Unfortunately,
  67.596 + * it needs a work array to hold the best-distance-so-far for each histogram
  67.597 + * cell (because the inner loop has to be over cells, not colormap entries).
  67.598 + * The work array elements have to be INT32s, so the work array would need
  67.599 + * 256Kb at our recommended precision.  This is not feasible in DOS machines.
  67.600 + *
  67.601 + * To get around these problems, we apply Thomas' method to compute the
  67.602 + * nearest colors for only the cells within a small subbox of the histogram.
  67.603 + * The work array need be only as big as the subbox, so the memory usage
  67.604 + * problem is solved.  Furthermore, we need not fill subboxes that are never
  67.605 + * referenced in pass2; many images use only part of the color gamut, so a
  67.606 + * fair amount of work is saved.  An additional advantage of this
  67.607 + * approach is that we can apply Heckbert's locality criterion to quickly
  67.608 + * eliminate colormap entries that are far away from the subbox; typically
  67.609 + * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  67.610 + * and we need not compute their distances to individual cells in the subbox.
  67.611 + * The speed of this approach is heavily influenced by the subbox size: too
  67.612 + * small means too much overhead, too big loses because Heckbert's criterion
  67.613 + * can't eliminate as many colormap entries.  Empirically the best subbox
  67.614 + * size seems to be about 1/512th of the histogram (1/8th in each direction).
  67.615 + *
  67.616 + * Thomas' article also describes a refined method which is asymptotically
  67.617 + * faster than the brute-force method, but it is also far more complex and
  67.618 + * cannot efficiently be applied to small subboxes.  It is therefore not
  67.619 + * useful for programs intended to be portable to DOS machines.  On machines
  67.620 + * with plenty of memory, filling the whole histogram in one shot with Thomas'
  67.621 + * refined method might be faster than the present code --- but then again,
  67.622 + * it might not be any faster, and it's certainly more complicated.
  67.623 + */
  67.624 +
  67.625 +
  67.626 +/* log2(histogram cells in update box) for each axis; this can be adjusted */
  67.627 +#define BOX_C0_LOG  (HIST_C0_BITS-3)
  67.628 +#define BOX_C1_LOG  (HIST_C1_BITS-3)
  67.629 +#define BOX_C2_LOG  (HIST_C2_BITS-3)
  67.630 +
  67.631 +#define BOX_C0_ELEMS  (1<<BOX_C0_LOG) /* # of hist cells in update box */
  67.632 +#define BOX_C1_ELEMS  (1<<BOX_C1_LOG)
  67.633 +#define BOX_C2_ELEMS  (1<<BOX_C2_LOG)
  67.634 +
  67.635 +#define BOX_C0_SHIFT  (C0_SHIFT + BOX_C0_LOG)
  67.636 +#define BOX_C1_SHIFT  (C1_SHIFT + BOX_C1_LOG)
  67.637 +#define BOX_C2_SHIFT  (C2_SHIFT + BOX_C2_LOG)
  67.638 +
  67.639 +
  67.640 +/*
  67.641 + * The next three routines implement inverse colormap filling.  They could
  67.642 + * all be folded into one big routine, but splitting them up this way saves
  67.643 + * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  67.644 + * and may allow some compilers to produce better code by registerizing more
  67.645 + * inner-loop variables.
  67.646 + */
  67.647 +
  67.648 +LOCAL(int)
  67.649 +find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  67.650 +		    JSAMPLE colorlist[])
  67.651 +/* Locate the colormap entries close enough to an update box to be candidates
  67.652 + * for the nearest entry to some cell(s) in the update box.  The update box
  67.653 + * is specified by the center coordinates of its first cell.  The number of
  67.654 + * candidate colormap entries is returned, and their colormap indexes are
  67.655 + * placed in colorlist[].
  67.656 + * This routine uses Heckbert's "locally sorted search" criterion to select
  67.657 + * the colors that need further consideration.
  67.658 + */
  67.659 +{
  67.660 +  int numcolors = cinfo->actual_number_of_colors;
  67.661 +  int maxc0, maxc1, maxc2;
  67.662 +  int centerc0, centerc1, centerc2;
  67.663 +  int i, x, ncolors;
  67.664 +  INT32 minmaxdist, min_dist, max_dist, tdist;
  67.665 +  INT32 mindist[MAXNUMCOLORS];	/* min distance to colormap entry i */
  67.666 +
  67.667 +  /* Compute true coordinates of update box's upper corner and center.
  67.668 +   * Actually we compute the coordinates of the center of the upper-corner
  67.669 +   * histogram cell, which are the upper bounds of the volume we care about.
  67.670 +   * Note that since ">>" rounds down, the "center" values may be closer to
  67.671 +   * min than to max; hence comparisons to them must be "<=", not "<".
  67.672 +   */
  67.673 +  maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  67.674 +  centerc0 = (minc0 + maxc0) >> 1;
  67.675 +  maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  67.676 +  centerc1 = (minc1 + maxc1) >> 1;
  67.677 +  maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  67.678 +  centerc2 = (minc2 + maxc2) >> 1;
  67.679 +
  67.680 +  /* For each color in colormap, find:
  67.681 +   *  1. its minimum squared-distance to any point in the update box
  67.682 +   *     (zero if color is within update box);
  67.683 +   *  2. its maximum squared-distance to any point in the update box.
  67.684 +   * Both of these can be found by considering only the corners of the box.
  67.685 +   * We save the minimum distance for each color in mindist[];
  67.686 +   * only the smallest maximum distance is of interest.
  67.687 +   */
  67.688 +  minmaxdist = 0x7FFFFFFFL;
  67.689 +
  67.690 +  for (i = 0; i < numcolors; i++) {
  67.691 +    /* We compute the squared-c0-distance term, then add in the other two. */
  67.692 +    x = GETJSAMPLE(cinfo->colormap[0][i]);
  67.693 +    if (x < minc0) {
  67.694 +      tdist = (x - minc0) * C0_SCALE;
  67.695 +      min_dist = tdist*tdist;
  67.696 +      tdist = (x - maxc0) * C0_SCALE;
  67.697 +      max_dist = tdist*tdist;
  67.698 +    } else if (x > maxc0) {
  67.699 +      tdist = (x - maxc0) * C0_SCALE;
  67.700 +      min_dist = tdist*tdist;
  67.701 +      tdist = (x - minc0) * C0_SCALE;
  67.702 +      max_dist = tdist*tdist;
  67.703 +    } else {
  67.704 +      /* within cell range so no contribution to min_dist */
  67.705 +      min_dist = 0;
  67.706 +      if (x <= centerc0) {
  67.707 +	tdist = (x - maxc0) * C0_SCALE;
  67.708 +	max_dist = tdist*tdist;
  67.709 +      } else {
  67.710 +	tdist = (x - minc0) * C0_SCALE;
  67.711 +	max_dist = tdist*tdist;
  67.712 +      }
  67.713 +    }
  67.714 +
  67.715 +    x = GETJSAMPLE(cinfo->colormap[1][i]);
  67.716 +    if (x < minc1) {
  67.717 +      tdist = (x - minc1) * C1_SCALE;
  67.718 +      min_dist += tdist*tdist;
  67.719 +      tdist = (x - maxc1) * C1_SCALE;
  67.720 +      max_dist += tdist*tdist;
  67.721 +    } else if (x > maxc1) {
  67.722 +      tdist = (x - maxc1) * C1_SCALE;
  67.723 +      min_dist += tdist*tdist;
  67.724 +      tdist = (x - minc1) * C1_SCALE;
  67.725 +      max_dist += tdist*tdist;
  67.726 +    } else {
  67.727 +      /* within cell range so no contribution to min_dist */
  67.728 +      if (x <= centerc1) {
  67.729 +	tdist = (x - maxc1) * C1_SCALE;
  67.730 +	max_dist += tdist*tdist;
  67.731 +      } else {
  67.732 +	tdist = (x - minc1) * C1_SCALE;
  67.733 +	max_dist += tdist*tdist;
  67.734 +      }
  67.735 +    }
  67.736 +
  67.737 +    x = GETJSAMPLE(cinfo->colormap[2][i]);
  67.738 +    if (x < minc2) {
  67.739 +      tdist = (x - minc2) * C2_SCALE;
  67.740 +      min_dist += tdist*tdist;
  67.741 +      tdist = (x - maxc2) * C2_SCALE;
  67.742 +      max_dist += tdist*tdist;
  67.743 +    } else if (x > maxc2) {
  67.744 +      tdist = (x - maxc2) * C2_SCALE;
  67.745 +      min_dist += tdist*tdist;
  67.746 +      tdist = (x - minc2) * C2_SCALE;
  67.747 +      max_dist += tdist*tdist;
  67.748 +    } else {
  67.749 +      /* within cell range so no contribution to min_dist */
  67.750 +      if (x <= centerc2) {
  67.751 +	tdist = (x - maxc2) * C2_SCALE;
  67.752 +	max_dist += tdist*tdist;
  67.753 +      } else {
  67.754 +	tdist = (x - minc2) * C2_SCALE;
  67.755 +	max_dist += tdist*tdist;
  67.756 +      }
  67.757 +    }
  67.758 +
  67.759 +    mindist[i] = min_dist;	/* save away the results */
  67.760 +    if (max_dist < minmaxdist)
  67.761 +      minmaxdist = max_dist;
  67.762 +  }
  67.763 +
  67.764 +  /* Now we know that no cell in the update box is more than minmaxdist
  67.765 +   * away from some colormap entry.  Therefore, only colors that are
  67.766 +   * within minmaxdist of some part of the box need be considered.
  67.767 +   */
  67.768 +  ncolors = 0;
  67.769 +  for (i = 0; i < numcolors; i++) {
  67.770 +    if (mindist[i] <= minmaxdist)
  67.771 +      colorlist[ncolors++] = (JSAMPLE) i;
  67.772 +  }
  67.773 +  return ncolors;
  67.774 +}
  67.775 +
  67.776 +
  67.777 +LOCAL(void)
  67.778 +find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  67.779 +		  int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  67.780 +/* Find the closest colormap entry for each cell in the update box,
  67.781 + * given the list of candidate colors prepared by find_nearby_colors.
  67.782 + * Return the indexes of the closest entries in the bestcolor[] array.
  67.783 + * This routine uses Thomas' incremental distance calculation method to
  67.784 + * find the distance from a colormap entry to successive cells in the box.
  67.785 + */
  67.786 +{
  67.787 +  int ic0, ic1, ic2;
  67.788 +  int i, icolor;
  67.789 +  register INT32 * bptr;	/* pointer into bestdist[] array */
  67.790 +  JSAMPLE * cptr;		/* pointer into bestcolor[] array */
  67.791 +  INT32 dist0, dist1;		/* initial distance values */
  67.792 +  register INT32 dist2;		/* current distance in inner loop */
  67.793 +  INT32 xx0, xx1;		/* distance increments */
  67.794 +  register INT32 xx2;
  67.795 +  INT32 inc0, inc1, inc2;	/* initial values for increments */
  67.796 +  /* This array holds the distance to the nearest-so-far color for each cell */
  67.797 +  INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  67.798 +
  67.799 +  /* Initialize best-distance for each cell of the update box */
  67.800 +  bptr = bestdist;
  67.801 +  for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  67.802 +    *bptr++ = 0x7FFFFFFFL;
  67.803 +  
  67.804 +  /* For each color selected by find_nearby_colors,
  67.805 +   * compute its distance to the center of each cell in the box.
  67.806 +   * If that's less than best-so-far, update best distance and color number.
  67.807 +   */
  67.808 +  
  67.809 +  /* Nominal steps between cell centers ("x" in Thomas article) */
  67.810 +#define STEP_C0  ((1 << C0_SHIFT) * C0_SCALE)
  67.811 +#define STEP_C1  ((1 << C1_SHIFT) * C1_SCALE)
  67.812 +#define STEP_C2  ((1 << C2_SHIFT) * C2_SCALE)
  67.813 +  
  67.814 +  for (i = 0; i < numcolors; i++) {
  67.815 +    icolor = GETJSAMPLE(colorlist[i]);
  67.816 +    /* Compute (square of) distance from minc0/c1/c2 to this color */
  67.817 +    inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  67.818 +    dist0 = inc0*inc0;
  67.819 +    inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  67.820 +    dist0 += inc1*inc1;
  67.821 +    inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  67.822 +    dist0 += inc2*inc2;
  67.823 +    /* Form the initial difference increments */
  67.824 +    inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  67.825 +    inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  67.826 +    inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  67.827 +    /* Now loop over all cells in box, updating distance per Thomas method */
  67.828 +    bptr = bestdist;
  67.829 +    cptr = bestcolor;
  67.830 +    xx0 = inc0;
  67.831 +    for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  67.832 +      dist1 = dist0;
  67.833 +      xx1 = inc1;
  67.834 +      for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  67.835 +	dist2 = dist1;
  67.836 +	xx2 = inc2;
  67.837 +	for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  67.838 +	  if (dist2 < *bptr) {
  67.839 +	    *bptr = dist2;
  67.840 +	    *cptr = (JSAMPLE) icolor;
  67.841 +	  }
  67.842 +	  dist2 += xx2;
  67.843 +	  xx2 += 2 * STEP_C2 * STEP_C2;
  67.844 +	  bptr++;
  67.845 +	  cptr++;
  67.846 +	}
  67.847 +	dist1 += xx1;
  67.848 +	xx1 += 2 * STEP_C1 * STEP_C1;
  67.849 +      }
  67.850 +      dist0 += xx0;
  67.851 +      xx0 += 2 * STEP_C0 * STEP_C0;
  67.852 +    }
  67.853 +  }
  67.854 +}
  67.855 +
  67.856 +
  67.857 +LOCAL(void)
  67.858 +fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  67.859 +/* Fill the inverse-colormap entries in the update box that contains */
  67.860 +/* histogram cell c0/c1/c2.  (Only that one cell MUST be filled, but */
  67.861 +/* we can fill as many others as we wish.) */
  67.862 +{
  67.863 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  67.864 +  hist3d histogram = cquantize->histogram;
  67.865 +  int minc0, minc1, minc2;	/* lower left corner of update box */
  67.866 +  int ic0, ic1, ic2;
  67.867 +  register JSAMPLE * cptr;	/* pointer into bestcolor[] array */
  67.868 +  register histptr cachep;	/* pointer into main cache array */
  67.869 +  /* This array lists the candidate colormap indexes. */
  67.870 +  JSAMPLE colorlist[MAXNUMCOLORS];
  67.871 +  int numcolors;		/* number of candidate colors */
  67.872 +  /* This array holds the actually closest colormap index for each cell. */
  67.873 +  JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  67.874 +
  67.875 +  /* Convert cell coordinates to update box ID */
  67.876 +  c0 >>= BOX_C0_LOG;
  67.877 +  c1 >>= BOX_C1_LOG;
  67.878 +  c2 >>= BOX_C2_LOG;
  67.879 +
  67.880 +  /* Compute true coordinates of update box's origin corner.
  67.881 +   * Actually we compute the coordinates of the center of the corner
  67.882 +   * histogram cell, which are the lower bounds of the volume we care about.
  67.883 +   */
  67.884 +  minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  67.885 +  minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  67.886 +  minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  67.887 +  
  67.888 +  /* Determine which colormap entries are close enough to be candidates
  67.889 +   * for the nearest entry to some cell in the update box.
  67.890 +   */
  67.891 +  numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  67.892 +
  67.893 +  /* Determine the actually nearest colors. */
  67.894 +  find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  67.895 +		   bestcolor);
  67.896 +
  67.897 +  /* Save the best color numbers (plus 1) in the main cache array */
  67.898 +  c0 <<= BOX_C0_LOG;		/* convert ID back to base cell indexes */
  67.899 +  c1 <<= BOX_C1_LOG;
  67.900 +  c2 <<= BOX_C2_LOG;
  67.901 +  cptr = bestcolor;
  67.902 +  for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  67.903 +    for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  67.904 +      cachep = & histogram[c0+ic0][c1+ic1][c2];
  67.905 +      for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  67.906 +	*cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  67.907 +      }
  67.908 +    }
  67.909 +  }
  67.910 +}
  67.911 +
  67.912 +
  67.913 +/*
  67.914 + * Map some rows of pixels to the output colormapped representation.
  67.915 + */
  67.916 +
  67.917 +METHODDEF(void)
  67.918 +pass2_no_dither (j_decompress_ptr cinfo,
  67.919 +		 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  67.920 +/* This version performs no dithering */
  67.921 +{
  67.922 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  67.923 +  hist3d histogram = cquantize->histogram;
  67.924 +  register JSAMPROW inptr, outptr;
  67.925 +  register histptr cachep;
  67.926 +  register int c0, c1, c2;
  67.927 +  int row;
  67.928 +  JDIMENSION col;
  67.929 +  JDIMENSION width = cinfo->output_width;
  67.930 +
  67.931 +  for (row = 0; row < num_rows; row++) {
  67.932 +    inptr = input_buf[row];
  67.933 +    outptr = output_buf[row];
  67.934 +    for (col = width; col > 0; col--) {
  67.935 +      /* get pixel value and index into the cache */
  67.936 +      c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  67.937 +      c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  67.938 +      c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  67.939 +      cachep = & histogram[c0][c1][c2];
  67.940 +      /* If we have not seen this color before, find nearest colormap entry */
  67.941 +      /* and update the cache */
  67.942 +      if (*cachep == 0)
  67.943 +	fill_inverse_cmap(cinfo, c0,c1,c2);
  67.944 +      /* Now emit the colormap index for this cell */
  67.945 +      *outptr++ = (JSAMPLE) (*cachep - 1);
  67.946 +    }
  67.947 +  }
  67.948 +}
  67.949 +
  67.950 +
  67.951 +METHODDEF(void)
  67.952 +pass2_fs_dither (j_decompress_ptr cinfo,
  67.953 +		 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  67.954 +/* This version performs Floyd-Steinberg dithering */
  67.955 +{
  67.956 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  67.957 +  hist3d histogram = cquantize->histogram;
  67.958 +  register LOCFSERROR cur0, cur1, cur2;	/* current error or pixel value */
  67.959 +  LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  67.960 +  LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  67.961 +  register FSERRPTR errorptr;	/* => fserrors[] at column before current */
  67.962 +  JSAMPROW inptr;		/* => current input pixel */
  67.963 +  JSAMPROW outptr;		/* => current output pixel */
  67.964 +  histptr cachep;
  67.965 +  int dir;			/* +1 or -1 depending on direction */
  67.966 +  int dir3;			/* 3*dir, for advancing inptr & errorptr */
  67.967 +  int row;
  67.968 +  JDIMENSION col;
  67.969 +  JDIMENSION width = cinfo->output_width;
  67.970 +  JSAMPLE *range_limit = cinfo->sample_range_limit;
  67.971 +  int *error_limit = cquantize->error_limiter;
  67.972 +  JSAMPROW colormap0 = cinfo->colormap[0];
  67.973 +  JSAMPROW colormap1 = cinfo->colormap[1];
  67.974 +  JSAMPROW colormap2 = cinfo->colormap[2];
  67.975 +  SHIFT_TEMPS
  67.976 +
  67.977 +  for (row = 0; row < num_rows; row++) {
  67.978 +    inptr = input_buf[row];
  67.979 +    outptr = output_buf[row];
  67.980 +    if (cquantize->on_odd_row) {
  67.981 +      /* work right to left in this row */
  67.982 +      inptr += (width-1) * 3;	/* so point to rightmost pixel */
  67.983 +      outptr += width-1;
  67.984 +      dir = -1;
  67.985 +      dir3 = -3;
  67.986 +      errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  67.987 +      cquantize->on_odd_row = FALSE; /* flip for next time */
  67.988 +    } else {
  67.989 +      /* work left to right in this row */
  67.990 +      dir = 1;
  67.991 +      dir3 = 3;
  67.992 +      errorptr = cquantize->fserrors; /* => entry before first real column */
  67.993 +      cquantize->on_odd_row = TRUE; /* flip for next time */
  67.994 +    }
  67.995 +    /* Preset error values: no error propagated to first pixel from left */
  67.996 +    cur0 = cur1 = cur2 = 0;
  67.997 +    /* and no error propagated to row below yet */
  67.998 +    belowerr0 = belowerr1 = belowerr2 = 0;
  67.999 +    bpreverr0 = bpreverr1 = bpreverr2 = 0;
 67.1000 +
 67.1001 +    for (col = width; col > 0; col--) {
 67.1002 +      /* curN holds the error propagated from the previous pixel on the
 67.1003 +       * current line.  Add the error propagated from the previous line
 67.1004 +       * to form the complete error correction term for this pixel, and
 67.1005 +       * round the error term (which is expressed * 16) to an integer.
 67.1006 +       * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
 67.1007 +       * for either sign of the error value.
 67.1008 +       * Note: errorptr points to *previous* column's array entry.
 67.1009 +       */
 67.1010 +      cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
 67.1011 +      cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
 67.1012 +      cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
 67.1013 +      /* Limit the error using transfer function set by init_error_limit.
 67.1014 +       * See comments with init_error_limit for rationale.
 67.1015 +       */
 67.1016 +      cur0 = error_limit[cur0];
 67.1017 +      cur1 = error_limit[cur1];
 67.1018 +      cur2 = error_limit[cur2];
 67.1019 +      /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
 67.1020 +       * The maximum error is +- MAXJSAMPLE (or less with error limiting);
 67.1021 +       * this sets the required size of the range_limit array.
 67.1022 +       */
 67.1023 +      cur0 += GETJSAMPLE(inptr[0]);
 67.1024 +      cur1 += GETJSAMPLE(inptr[1]);
 67.1025 +      cur2 += GETJSAMPLE(inptr[2]);
 67.1026 +      cur0 = GETJSAMPLE(range_limit[cur0]);
 67.1027 +      cur1 = GETJSAMPLE(range_limit[cur1]);
 67.1028 +      cur2 = GETJSAMPLE(range_limit[cur2]);
 67.1029 +      /* Index into the cache with adjusted pixel value */
 67.1030 +      cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
 67.1031 +      /* If we have not seen this color before, find nearest colormap */
 67.1032 +      /* entry and update the cache */
 67.1033 +      if (*cachep == 0)
 67.1034 +	fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
 67.1035 +      /* Now emit the colormap index for this cell */
 67.1036 +      { register int pixcode = *cachep - 1;
 67.1037 +	*outptr = (JSAMPLE) pixcode;
 67.1038 +	/* Compute representation error for this pixel */
 67.1039 +	cur0 -= GETJSAMPLE(colormap0[pixcode]);
 67.1040 +	cur1 -= GETJSAMPLE(colormap1[pixcode]);
 67.1041 +	cur2 -= GETJSAMPLE(colormap2[pixcode]);
 67.1042 +      }
 67.1043 +      /* Compute error fractions to be propagated to adjacent pixels.
 67.1044 +       * Add these into the running sums, and simultaneously shift the
 67.1045 +       * next-line error sums left by 1 column.
 67.1046 +       */
 67.1047 +      { register LOCFSERROR bnexterr, delta;
 67.1048 +
 67.1049 +	bnexterr = cur0;	/* Process component 0 */
 67.1050 +	delta = cur0 * 2;
 67.1051 +	cur0 += delta;		/* form error * 3 */
 67.1052 +	errorptr[0] = (FSERROR) (bpreverr0 + cur0);
 67.1053 +	cur0 += delta;		/* form error * 5 */
 67.1054 +	bpreverr0 = belowerr0 + cur0;
 67.1055 +	belowerr0 = bnexterr;
 67.1056 +	cur0 += delta;		/* form error * 7 */
 67.1057 +	bnexterr = cur1;	/* Process component 1 */
 67.1058 +	delta = cur1 * 2;
 67.1059 +	cur1 += delta;		/* form error * 3 */
 67.1060 +	errorptr[1] = (FSERROR) (bpreverr1 + cur1);
 67.1061 +	cur1 += delta;		/* form error * 5 */
 67.1062 +	bpreverr1 = belowerr1 + cur1;
 67.1063 +	belowerr1 = bnexterr;
 67.1064 +	cur1 += delta;		/* form error * 7 */
 67.1065 +	bnexterr = cur2;	/* Process component 2 */
 67.1066 +	delta = cur2 * 2;
 67.1067 +	cur2 += delta;		/* form error * 3 */
 67.1068 +	errorptr[2] = (FSERROR) (bpreverr2 + cur2);
 67.1069 +	cur2 += delta;		/* form error * 5 */
 67.1070 +	bpreverr2 = belowerr2 + cur2;
 67.1071 +	belowerr2 = bnexterr;
 67.1072 +	cur2 += delta;		/* form error * 7 */
 67.1073 +      }
 67.1074 +      /* At this point curN contains the 7/16 error value to be propagated
 67.1075 +       * to the next pixel on the current line, and all the errors for the
 67.1076 +       * next line have been shifted over.  We are therefore ready to move on.
 67.1077 +       */
 67.1078 +      inptr += dir3;		/* Advance pixel pointers to next column */
 67.1079 +      outptr += dir;
 67.1080 +      errorptr += dir3;		/* advance errorptr to current column */
 67.1081 +    }
 67.1082 +    /* Post-loop cleanup: we must unload the final error values into the
 67.1083 +     * final fserrors[] entry.  Note we need not unload belowerrN because
 67.1084 +     * it is for the dummy column before or after the actual array.
 67.1085 +     */
 67.1086 +    errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
 67.1087 +    errorptr[1] = (FSERROR) bpreverr1;
 67.1088 +    errorptr[2] = (FSERROR) bpreverr2;
 67.1089 +  }
 67.1090 +}
 67.1091 +
 67.1092 +
 67.1093 +/*
 67.1094 + * Initialize the error-limiting transfer function (lookup table).
 67.1095 + * The raw F-S error computation can potentially compute error values of up to
 67.1096 + * +- MAXJSAMPLE.  But we want the maximum correction applied to a pixel to be
 67.1097 + * much less, otherwise obviously wrong pixels will be created.  (Typical
 67.1098 + * effects include weird fringes at color-area boundaries, isolated bright
 67.1099 + * pixels in a dark area, etc.)  The standard advice for avoiding this problem
 67.1100 + * is to ensure that the "corners" of the color cube are allocated as output
 67.1101 + * colors; then repeated errors in the same direction cannot cause cascading
 67.1102 + * error buildup.  However, that only prevents the error from getting
 67.1103 + * completely out of hand; Aaron Giles reports that error limiting improves
 67.1104 + * the results even with corner colors allocated.
 67.1105 + * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
 67.1106 + * well, but the smoother transfer function used below is even better.  Thanks
 67.1107 + * to Aaron Giles for this idea.
 67.1108 + */
 67.1109 +
 67.1110 +LOCAL(void)
 67.1111 +init_error_limit (j_decompress_ptr cinfo)
 67.1112 +/* Allocate and fill in the error_limiter table */
 67.1113 +{
 67.1114 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
 67.1115 +  int * table;
 67.1116 +  int in, out;
 67.1117 +
 67.1118 +  table = (int *) (*cinfo->mem->alloc_small)
 67.1119 +    ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
 67.1120 +  table += MAXJSAMPLE;		/* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
 67.1121 +  cquantize->error_limiter = table;
 67.1122 +
 67.1123 +#define STEPSIZE ((MAXJSAMPLE+1)/16)
 67.1124 +  /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
 67.1125 +  out = 0;
 67.1126 +  for (in = 0; in < STEPSIZE; in++, out++) {
 67.1127 +    table[in] = out; table[-in] = -out;
 67.1128 +  }
 67.1129 +  /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
 67.1130 +  for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
 67.1131 +    table[in] = out; table[-in] = -out;
 67.1132 +  }
 67.1133 +  /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
 67.1134 +  for (; in <= MAXJSAMPLE; in++) {
 67.1135 +    table[in] = out; table[-in] = -out;
 67.1136 +  }
 67.1137 +#undef STEPSIZE
 67.1138 +}
 67.1139 +
 67.1140 +
 67.1141 +/*
 67.1142 + * Finish up at the end of each pass.
 67.1143 + */
 67.1144 +
 67.1145 +METHODDEF(void)
 67.1146 +finish_pass1 (j_decompress_ptr cinfo)
 67.1147 +{
 67.1148 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
 67.1149 +
 67.1150 +  /* Select the representative colors and fill in cinfo->colormap */
 67.1151 +  cinfo->colormap = cquantize->sv_colormap;
 67.1152 +  select_colors(cinfo, cquantize->desired);
 67.1153 +  /* Force next pass to zero the color index table */
 67.1154 +  cquantize->needs_zeroed = TRUE;
 67.1155 +}
 67.1156 +
 67.1157 +
 67.1158 +METHODDEF(void)
 67.1159 +finish_pass2 (j_decompress_ptr cinfo)
 67.1160 +{
 67.1161 +  /* no work */
 67.1162 +}
 67.1163 +
 67.1164 +
 67.1165 +/*
 67.1166 + * Initialize for each processing pass.
 67.1167 + */
 67.1168 +
 67.1169 +METHODDEF(void)
 67.1170 +start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
 67.1171 +{
 67.1172 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
 67.1173 +  hist3d histogram = cquantize->histogram;
 67.1174 +  int i;
 67.1175 +
 67.1176 +  /* Only F-S dithering or no dithering is supported. */
 67.1177 +  /* If user asks for ordered dither, give him F-S. */
 67.1178 +  if (cinfo->dither_mode != JDITHER_NONE)
 67.1179 +    cinfo->dither_mode = JDITHER_FS;
 67.1180 +
 67.1181 +  if (is_pre_scan) {
 67.1182 +    /* Set up method pointers */
 67.1183 +    cquantize->pub.color_quantize = prescan_quantize;
 67.1184 +    cquantize->pub.finish_pass = finish_pass1;
 67.1185 +    cquantize->needs_zeroed = TRUE; /* Always zero histogram */
 67.1186 +  } else {
 67.1187 +    /* Set up method pointers */
 67.1188 +    if (cinfo->dither_mode == JDITHER_FS)
 67.1189 +      cquantize->pub.color_quantize = pass2_fs_dither;
 67.1190 +    else
 67.1191 +      cquantize->pub.color_quantize = pass2_no_dither;
 67.1192 +    cquantize->pub.finish_pass = finish_pass2;
 67.1193 +
 67.1194 +    /* Make sure color count is acceptable */
 67.1195 +    i = cinfo->actual_number_of_colors;
 67.1196 +    if (i < 1)
 67.1197 +      ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
 67.1198 +    if (i > MAXNUMCOLORS)
 67.1199 +      ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
 67.1200 +
 67.1201 +    if (cinfo->dither_mode == JDITHER_FS) {
 67.1202 +      size_t arraysize = (size_t) ((cinfo->output_width + 2) *
 67.1203 +				   (3 * SIZEOF(FSERROR)));
 67.1204 +      /* Allocate Floyd-Steinberg workspace if we didn't already. */
 67.1205 +      if (cquantize->fserrors == NULL)
 67.1206 +	cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
 67.1207 +	  ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
 67.1208 +      /* Initialize the propagated errors to zero. */
 67.1209 +      jzero_far((void FAR *) cquantize->fserrors, arraysize);
 67.1210 +      /* Make the error-limit table if we didn't already. */
 67.1211 +      if (cquantize->error_limiter == NULL)
 67.1212 +	init_error_limit(cinfo);
 67.1213 +      cquantize->on_odd_row = FALSE;
 67.1214 +    }
 67.1215 +
 67.1216 +  }
 67.1217 +  /* Zero the histogram or inverse color map, if necessary */
 67.1218 +  if (cquantize->needs_zeroed) {
 67.1219 +    for (i = 0; i < HIST_C0_ELEMS; i++) {
 67.1220 +      jzero_far((void FAR *) histogram[i],
 67.1221 +		HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
 67.1222 +    }
 67.1223 +    cquantize->needs_zeroed = FALSE;
 67.1224 +  }
 67.1225 +}
 67.1226 +
 67.1227 +
 67.1228 +/*
 67.1229 + * Switch to a new external colormap between output passes.
 67.1230 + */
 67.1231 +
 67.1232 +METHODDEF(void)
 67.1233 +new_color_map_2_quant (j_decompress_ptr cinfo)
 67.1234 +{
 67.1235 +  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
 67.1236 +
 67.1237 +  /* Reset the inverse color map */
 67.1238 +  cquantize->needs_zeroed = TRUE;
 67.1239 +}
 67.1240 +
 67.1241 +
 67.1242 +/*
 67.1243 + * Module initialization routine for 2-pass color quantization.
 67.1244 + */
 67.1245 +
 67.1246 +GLOBAL(void)
 67.1247 +jinit_2pass_quantizer (j_decompress_ptr cinfo)
 67.1248 +{
 67.1249 +  my_cquantize_ptr cquantize;
 67.1250 +  int i;
 67.1251 +
 67.1252 +  cquantize = (my_cquantize_ptr)
 67.1253 +    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
 67.1254 +				SIZEOF(my_cquantizer));
 67.1255 +  cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
 67.1256 +  cquantize->pub.start_pass = start_pass_2_quant;
 67.1257 +  cquantize->pub.new_color_map = new_color_map_2_quant;
 67.1258 +  cquantize->fserrors = NULL;	/* flag optional arrays not allocated */
 67.1259 +  cquantize->error_limiter = NULL;
 67.1260 +
 67.1261 +  /* Make sure jdmaster didn't give me a case I can't handle */
 67.1262 +  if (cinfo->out_color_components != 3)
 67.1263 +    ERREXIT(cinfo, JERR_NOTIMPL);
 67.1264 +
 67.1265 +  /* Allocate the histogram/inverse colormap storage */
 67.1266 +  cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
 67.1267 +    ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
 67.1268 +  for (i = 0; i < HIST_C0_ELEMS; i++) {
 67.1269 +    cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
 67.1270 +      ((j_common_ptr) cinfo, JPOOL_IMAGE,
 67.1271 +       HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
 67.1272 +  }
 67.1273 +  cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
 67.1274 +
 67.1275 +  /* Allocate storage for the completed colormap, if required.
 67.1276 +   * We do this now since it is FAR storage and may affect
 67.1277 +   * the memory manager's space calculations.
 67.1278 +   */
 67.1279 +  if (cinfo->enable_2pass_quant) {
 67.1280 +    /* Make sure color count is acceptable */
 67.1281 +    int desired = cinfo->desired_number_of_colors;
 67.1282 +    /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
 67.1283 +    if (desired < 8)
 67.1284 +      ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
 67.1285 +    /* Make sure colormap indexes can be represented by JSAMPLEs */
 67.1286 +    if (desired > MAXNUMCOLORS)
 67.1287 +      ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
 67.1288 +    cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
 67.1289 +      ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
 67.1290 +    cquantize->desired = desired;
 67.1291 +  } else
 67.1292 +    cquantize->sv_colormap = NULL;
 67.1293 +
 67.1294 +  /* Only F-S dithering or no dithering is supported. */
 67.1295 +  /* If user asks for ordered dither, give him F-S. */
 67.1296 +  if (cinfo->dither_mode != JDITHER_NONE)
 67.1297 +    cinfo->dither_mode = JDITHER_FS;
 67.1298 +
 67.1299 +  /* Allocate Floyd-Steinberg workspace if necessary.
 67.1300 +   * This isn't really needed until pass 2, but again it is FAR storage.
 67.1301 +   * Although we will cope with a later change in dither_mode,
 67.1302 +   * we do not promise to honor max_memory_to_use if dither_mode changes.
 67.1303 +   */
 67.1304 +  if (cinfo->dither_mode == JDITHER_FS) {
 67.1305 +    cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
 67.1306 +      ((j_common_ptr) cinfo, JPOOL_IMAGE,
 67.1307 +       (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
 67.1308 +    /* Might as well create the error-limiting table too. */
 67.1309 +    init_error_limit(cinfo);
 67.1310 +  }
 67.1311 +}
 67.1312 +
 67.1313 +#endif /* QUANT_2PASS_SUPPORTED */
    68.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    68.2 +++ b/libs/libjpeg/jutils.c	Thu Sep 08 06:28:38 2011 +0300
    68.3 @@ -0,0 +1,179 @@
    68.4 +/*
    68.5 + * jutils.c
    68.6 + *
    68.7 + * Copyright (C) 1991-1996, Thomas G. Lane.
    68.8 + * This file is part of the Independent JPEG Group's software.
    68.9 + * For conditions of distribution and use, see the accompanying README file.
   68.10 + *
   68.11 + * This file contains tables and miscellaneous utility routines needed
   68.12 + * for both compression and decompression.
   68.13 + * Note we prefix all global names with "j" to minimize conflicts with
   68.14 + * a surrounding application.
   68.15 + */
   68.16 +
   68.17 +#define JPEG_INTERNALS
   68.18 +#include "jinclude.h"
   68.19 +#include "jpeglib.h"
   68.20 +
   68.21 +
   68.22 +/*
   68.23 + * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
   68.24 + * of a DCT block read in natural order (left to right, top to bottom).
   68.25 + */
   68.26 +
   68.27 +#if 0				/* This table is not actually needed in v6a */
   68.28 +
   68.29 +const int jpeg_zigzag_order[DCTSIZE2] = {
   68.30 +   0,  1,  5,  6, 14, 15, 27, 28,
   68.31 +   2,  4,  7, 13, 16, 26, 29, 42,
   68.32 +   3,  8, 12, 17, 25, 30, 41, 43,
   68.33 +   9, 11, 18, 24, 31, 40, 44, 53,
   68.34 +  10, 19, 23, 32, 39, 45, 52, 54,
   68.35 +  20, 22, 33, 38, 46, 51, 55, 60,
   68.36 +  21, 34, 37, 47, 50, 56, 59, 61,
   68.37 +  35, 36, 48, 49, 57, 58, 62, 63
   68.38 +};
   68.39 +
   68.40 +#endif
   68.41 +
   68.42 +/*
   68.43 + * jpeg_natural_order[i] is the natural-order position of the i'th element
   68.44 + * of zigzag order.
   68.45 + *
   68.46 + * When reading corrupted data, the Huffman decoders could attempt
   68.47 + * to reference an entry beyond the end of this array (if the decoded
   68.48 + * zero run length reaches past the end of the block).  To prevent
   68.49 + * wild stores without adding an inner-loop test, we put some extra
   68.50 + * "63"s after the real entries.  This will cause the extra coefficient
   68.51 + * to be stored in location 63 of the block, not somewhere random.
   68.52 + * The worst case would be a run-length of 15, which means we need 16
   68.53 + * fake entries.
   68.54 + */
   68.55 +
   68.56 +const int jpeg_natural_order[DCTSIZE2+16] = {
   68.57 +  0,  1,  8, 16,  9,  2,  3, 10,
   68.58 + 17, 24, 32, 25, 18, 11,  4,  5,
   68.59 + 12, 19, 26, 33, 40, 48, 41, 34,
   68.60 + 27, 20, 13,  6,  7, 14, 21, 28,
   68.61 + 35, 42, 49, 56, 57, 50, 43, 36,
   68.62 + 29, 22, 15, 23, 30, 37, 44, 51,
   68.63 + 58, 59, 52, 45, 38, 31, 39, 46,
   68.64 + 53, 60, 61, 54, 47, 55, 62, 63,
   68.65 + 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
   68.66 + 63, 63, 63, 63, 63, 63, 63, 63
   68.67 +};
   68.68 +
   68.69 +
   68.70 +/*
   68.71 + * Arithmetic utilities
   68.72 + */
   68.73 +
   68.74 +GLOBAL(long)
   68.75 +jdiv_round_up (long a, long b)
   68.76 +/* Compute a/b rounded up to next integer, ie, ceil(a/b) */
   68.77 +/* Assumes a >= 0, b > 0 */
   68.78 +{
   68.79 +  return (a + b - 1L) / b;
   68.80 +}
   68.81 +
   68.82 +
   68.83 +GLOBAL(long)
   68.84 +jround_up (long a, long b)
   68.85 +/* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
   68.86 +/* Assumes a >= 0, b > 0 */
   68.87 +{
   68.88 +  a += b - 1L;
   68.89 +  return a - (a % b);
   68.90 +}
   68.91 +
   68.92 +
   68.93 +/* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
   68.94 + * and coefficient-block arrays.  This won't work on 80x86 because the arrays
   68.95 + * are FAR and we're assuming a small-pointer memory model.  However, some
   68.96 + * DOS compilers provide far-pointer versions of memcpy() and memset() even
   68.97 + * in the small-model libraries.  These will be used if USE_FMEM is defined.
   68.98 + * Otherwise, the routines below do it the hard way.  (The performance cost
   68.99 + * is not all that great, because these routines aren't very heavily used.)
  68.100 + */
  68.101 +
  68.102 +#ifndef NEED_FAR_POINTERS	/* normal case, same as regular macros */
  68.103 +#define FMEMCOPY(dest,src,size)	MEMCOPY(dest,src,size)
  68.104 +#define FMEMZERO(target,size)	MEMZERO(target,size)
  68.105 +#else				/* 80x86 case, define if we can */
  68.106 +#ifdef USE_FMEM
  68.107 +#define FMEMCOPY(dest,src,size)	_fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  68.108 +#define FMEMZERO(target,size)	_fmemset((void FAR *)(target), 0, (size_t)(size))
  68.109 +#endif
  68.110 +#endif
  68.111 +
  68.112 +
  68.113 +GLOBAL(void)
  68.114 +jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  68.115 +		   JSAMPARRAY output_array, int dest_row,
  68.116 +		   int num_rows, JDIMENSION num_cols)
  68.117 +/* Copy some rows of samples from one place to another.
  68.118 + * num_rows rows are copied from input_array[source_row++]
  68.119 + * to output_array[dest_row++]; these areas may overlap for duplication.
  68.120 + * The source and destination arrays must be at least as wide as num_cols.
  68.121 + */
  68.122 +{
  68.123 +  register JSAMPROW inptr, outptr;
  68.124 +#ifdef FMEMCOPY
  68.125 +  register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  68.126 +#else
  68.127 +  register JDIMENSION count;
  68.128 +#endif
  68.129 +  register int row;
  68.130 +
  68.131 +  input_array += source_row;
  68.132 +  output_array += dest_row;
  68.133 +
  68.134 +  for (row = num_rows; row > 0; row--) {
  68.135 +    inptr = *input_array++;
  68.136 +    outptr = *output_array++;
  68.137 +#ifdef FMEMCOPY
  68.138 +    FMEMCOPY(outptr, inptr, count);
  68.139 +#else
  68.140 +    for (count = num_cols; count > 0; count--)
  68.141 +      *outptr++ = *inptr++;	/* needn't bother with GETJSAMPLE() here */
  68.142 +#endif
  68.143 +  }
  68.144 +}
  68.145 +
  68.146 +
  68.147 +GLOBAL(void)
  68.148 +jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  68.149 +		 JDIMENSION num_blocks)
  68.150 +/* Copy a row of coefficient blocks from one place to another. */
  68.151 +{
  68.152 +#ifdef FMEMCOPY
  68.153 +  FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  68.154 +#else
  68.155 +  register JCOEFPTR inptr, outptr;
  68.156 +  register long count;
  68.157 +
  68.158 +  inptr = (JCOEFPTR) input_row;
  68.159 +  outptr = (JCOEFPTR) output_row;
  68.160 +  for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  68.161 +    *outptr++ = *inptr++;
  68.162 +  }
  68.163 +#endif
  68.164 +}
  68.165 +
  68.166 +
  68.167 +GLOBAL(void)
  68.168 +jzero_far (void FAR * target, size_t bytestozero)
  68.169 +/* Zero out a chunk of FAR memory. */
  68.170 +/* This might be sample-array data, block-array data, or alloc_large data. */
  68.171 +{
  68.172 +#ifdef FMEMZERO
  68.173 +  FMEMZERO(target, bytestozero);
  68.174 +#else
  68.175 +  register char FAR * ptr = (char FAR *) target;
  68.176 +  register size_t count;
  68.177 +
  68.178 +  for (count = bytestozero; count > 0; count--) {
  68.179 +    *ptr++ = 0;
  68.180 +  }
  68.181 +#endif
  68.182 +}
    69.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    69.2 +++ b/libs/libjpeg/jversion.h	Thu Sep 08 06:28:38 2011 +0300
    69.3 @@ -0,0 +1,14 @@
    69.4 +/*
    69.5 + * jversion.h
    69.6 + *
    69.7 + * Copyright (C) 1991-1998, Thomas G. Lane.
    69.8 + * This file is part of the Independent JPEG Group's software.
    69.9 + * For conditions of distribution and use, see the accompanying README file.
   69.10 + *
   69.11 + * This file contains software version identification.
   69.12 + */
   69.13 +
   69.14 +
   69.15 +#define JVERSION	"6b  27-Mar-1998"
   69.16 +
   69.17 +#define JCOPYRIGHT	"Copyright (C) 1998, Thomas G. Lane"
    70.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    70.2 +++ b/libs/libpng/png.c	Thu Sep 08 06:28:38 2011 +0300
    70.3 @@ -0,0 +1,799 @@
    70.4 +
    70.5 +/* png.c - location for general purpose libpng functions
    70.6 + *
    70.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    70.8 + * For conditions of distribution and use, see copyright notice in png.h
    70.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   70.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   70.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   70.12 + */
   70.13 +
   70.14 +#define PNG_INTERNAL
   70.15 +#define PNG_NO_EXTERN
   70.16 +#include "png.h"
   70.17 +
   70.18 +/* Generate a compiler error if there is an old png.h in the search path. */
   70.19 +typedef version_1_2_33 Your_png_h_is_not_version_1_2_33;
   70.20 +
   70.21 +/* Version information for C files.  This had better match the version
   70.22 + * string defined in png.h.  */
   70.23 +
   70.24 +#ifdef PNG_USE_GLOBAL_ARRAYS
   70.25 +/* png_libpng_ver was changed to a function in version 1.0.5c */
   70.26 +PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
   70.27 +
   70.28 +#ifdef PNG_READ_SUPPORTED
   70.29 +
   70.30 +/* png_sig was changed to a function in version 1.0.5c */
   70.31 +/* Place to hold the signature string for a PNG file. */
   70.32 +PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
   70.33 +#endif /* PNG_READ_SUPPORTED */
   70.34 +
   70.35 +/* Invoke global declarations for constant strings for known chunk types */
   70.36 +PNG_IHDR;
   70.37 +PNG_IDAT;
   70.38 +PNG_IEND;
   70.39 +PNG_PLTE;
   70.40 +PNG_bKGD;
   70.41 +PNG_cHRM;
   70.42 +PNG_gAMA;
   70.43 +PNG_hIST;
   70.44 +PNG_iCCP;
   70.45 +PNG_iTXt;
   70.46 +PNG_oFFs;
   70.47 +PNG_pCAL;
   70.48 +PNG_sCAL;
   70.49 +PNG_pHYs;
   70.50 +PNG_sBIT;
   70.51 +PNG_sPLT;
   70.52 +PNG_sRGB;
   70.53 +PNG_tEXt;
   70.54 +PNG_tIME;
   70.55 +PNG_tRNS;
   70.56 +PNG_zTXt;
   70.57 +
   70.58 +#ifdef PNG_READ_SUPPORTED
   70.59 +/* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
   70.60 +
   70.61 +/* start of interlace block */
   70.62 +PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
   70.63 +
   70.64 +/* offset to next interlace block */
   70.65 +PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
   70.66 +
   70.67 +/* start of interlace block in the y direction */
   70.68 +PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
   70.69 +
   70.70 +/* offset to next interlace block in the y direction */
   70.71 +PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
   70.72 +
   70.73 +/* Height of interlace block.  This is not currently used - if you need
   70.74 + * it, uncomment it here and in png.h
   70.75 +PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
   70.76 +*/
   70.77 +
   70.78 +/* Mask to determine which pixels are valid in a pass */
   70.79 +PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
   70.80 +
   70.81 +/* Mask to determine which pixels to overwrite while displaying */
   70.82 +PNG_CONST int FARDATA png_pass_dsp_mask[]
   70.83 +   = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
   70.84 +
   70.85 +#endif /* PNG_READ_SUPPORTED */
   70.86 +#endif /* PNG_USE_GLOBAL_ARRAYS */
   70.87 +
   70.88 +/* Tells libpng that we have already handled the first "num_bytes" bytes
   70.89 + * of the PNG file signature.  If the PNG data is embedded into another
   70.90 + * stream we can set num_bytes = 8 so that libpng will not attempt to read
   70.91 + * or write any of the magic bytes before it starts on the IHDR.
   70.92 + */
   70.93 +
   70.94 +#ifdef PNG_READ_SUPPORTED
   70.95 +void PNGAPI
   70.96 +png_set_sig_bytes(png_structp png_ptr, int num_bytes)
   70.97 +{
   70.98 +   if (png_ptr == NULL) return;
   70.99 +   png_debug(1, "in png_set_sig_bytes\n");
  70.100 +   if (num_bytes > 8)
  70.101 +      png_error(png_ptr, "Too many bytes for PNG signature.");
  70.102 +
  70.103 +   png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  70.104 +}
  70.105 +
  70.106 +/* Checks whether the supplied bytes match the PNG signature.  We allow
  70.107 + * checking less than the full 8-byte signature so that those apps that
  70.108 + * already read the first few bytes of a file to determine the file type
  70.109 + * can simply check the remaining bytes for extra assurance.  Returns
  70.110 + * an integer less than, equal to, or greater than zero if sig is found,
  70.111 + * respectively, to be less than, to match, or be greater than the correct
  70.112 + * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  70.113 + */
  70.114 +int PNGAPI
  70.115 +png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  70.116 +{
  70.117 +   png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  70.118 +   if (num_to_check > 8)
  70.119 +      num_to_check = 8;
  70.120 +   else if (num_to_check < 1)
  70.121 +      return (-1);
  70.122 +
  70.123 +   if (start > 7)
  70.124 +      return (-1);
  70.125 +
  70.126 +   if (start + num_to_check > 8)
  70.127 +      num_to_check = 8 - start;
  70.128 +
  70.129 +   return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  70.130 +}
  70.131 +
  70.132 +#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  70.133 +/* (Obsolete) function to check signature bytes.  It does not allow one
  70.134 + * to check a partial signature.  This function might be removed in the
  70.135 + * future - use png_sig_cmp().  Returns true (nonzero) if the file is PNG.
  70.136 + */
  70.137 +int PNGAPI
  70.138 +png_check_sig(png_bytep sig, int num)
  70.139 +{
  70.140 +  return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  70.141 +}
  70.142 +#endif
  70.143 +#endif /* PNG_READ_SUPPORTED */
  70.144 +
  70.145 +#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  70.146 +/* Function to allocate memory for zlib and clear it to 0. */
  70.147 +#ifdef PNG_1_0_X
  70.148 +voidpf PNGAPI
  70.149 +#else
  70.150 +voidpf /* private */
  70.151 +#endif
  70.152 +png_zalloc(voidpf png_ptr, uInt items, uInt size)
  70.153 +{
  70.154 +   png_voidp ptr;
  70.155 +   png_structp p=(png_structp)png_ptr;
  70.156 +   png_uint_32 save_flags=p->flags;
  70.157 +   png_uint_32 num_bytes;
  70.158 +
  70.159 +   if (png_ptr == NULL) return (NULL);
  70.160 +   if (items > PNG_UINT_32_MAX/size)
  70.161 +   {
  70.162 +     png_warning (p, "Potential overflow in png_zalloc()");
  70.163 +     return (NULL);
  70.164 +   }
  70.165 +   num_bytes = (png_uint_32)items * size;
  70.166 +
  70.167 +   p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  70.168 +   ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  70.169 +   p->flags=save_flags;
  70.170 +
  70.171 +#if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  70.172 +   if (ptr == NULL)
  70.173 +       return ((voidpf)ptr);
  70.174 +
  70.175 +   if (num_bytes > (png_uint_32)0x8000L)
  70.176 +   {
  70.177 +      png_memset(ptr, 0, (png_size_t)0x8000L);
  70.178 +      png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  70.179 +         (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  70.180 +   }
  70.181 +   else
  70.182 +   {
  70.183 +      png_memset(ptr, 0, (png_size_t)num_bytes);
  70.184 +   }
  70.185 +#endif
  70.186 +   return ((voidpf)ptr);
  70.187 +}
  70.188 +
  70.189 +/* function to free memory for zlib */
  70.190 +#ifdef PNG_1_0_X
  70.191 +void PNGAPI
  70.192 +#else
  70.193 +void /* private */
  70.194 +#endif
  70.195 +png_zfree(voidpf png_ptr, voidpf ptr)
  70.196 +{
  70.197 +   png_free((png_structp)png_ptr, (png_voidp)ptr);
  70.198 +}
  70.199 +
  70.200 +/* Reset the CRC variable to 32 bits of 1's.  Care must be taken
  70.201 + * in case CRC is > 32 bits to leave the top bits 0.
  70.202 + */
  70.203 +void /* PRIVATE */
  70.204 +png_reset_crc(png_structp png_ptr)
  70.205 +{
  70.206 +   png_ptr->crc = crc32(0, Z_NULL, 0);
  70.207 +}
  70.208 +
  70.209 +/* Calculate the CRC over a section of data.  We can only pass as
  70.210 + * much data to this routine as the largest single buffer size.  We
  70.211 + * also check that this data will actually be used before going to the
  70.212 + * trouble of calculating it.
  70.213 + */
  70.214 +void /* PRIVATE */
  70.215 +png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  70.216 +{
  70.217 +   int need_crc = 1;
  70.218 +
  70.219 +   if (png_ptr->chunk_name[0] & 0x20)                     /* ancillary */
  70.220 +   {
  70.221 +      if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  70.222 +          (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  70.223 +         need_crc = 0;
  70.224 +   }
  70.225 +   else                                                    /* critical */
  70.226 +   {
  70.227 +      if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  70.228 +         need_crc = 0;
  70.229 +   }
  70.230 +
  70.231 +   if (need_crc)
  70.232 +      png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  70.233 +}
  70.234 +
  70.235 +/* Allocate the memory for an info_struct for the application.  We don't
  70.236 + * really need the png_ptr, but it could potentially be useful in the
  70.237 + * future.  This should be used in favour of malloc(png_sizeof(png_info))
  70.238 + * and png_info_init() so that applications that want to use a shared
  70.239 + * libpng don't have to be recompiled if png_info changes size.
  70.240 + */
  70.241 +png_infop PNGAPI
  70.242 +png_create_info_struct(png_structp png_ptr)
  70.243 +{
  70.244 +   png_infop info_ptr;
  70.245 +
  70.246 +   png_debug(1, "in png_create_info_struct\n");
  70.247 +   if (png_ptr == NULL) return (NULL);
  70.248 +#ifdef PNG_USER_MEM_SUPPORTED
  70.249 +   info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  70.250 +      png_ptr->malloc_fn, png_ptr->mem_ptr);
  70.251 +#else
  70.252 +   info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  70.253 +#endif
  70.254 +   if (info_ptr != NULL)
  70.255 +      png_info_init_3(&info_ptr, png_sizeof(png_info));
  70.256 +
  70.257 +   return (info_ptr);
  70.258 +}
  70.259 +
  70.260 +/* This function frees the memory associated with a single info struct.
  70.261 + * Normally, one would use either png_destroy_read_struct() or
  70.262 + * png_destroy_write_struct() to free an info struct, but this may be
  70.263 + * useful for some applications.
  70.264 + */
  70.265 +void PNGAPI
  70.266 +png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  70.267 +{
  70.268 +   png_infop info_ptr = NULL;
  70.269 +   if (png_ptr == NULL) return;
  70.270 +
  70.271 +   png_debug(1, "in png_destroy_info_struct\n");
  70.272 +   if (info_ptr_ptr != NULL)
  70.273 +      info_ptr = *info_ptr_ptr;
  70.274 +
  70.275 +   if (info_ptr != NULL)
  70.276 +   {
  70.277 +      png_info_destroy(png_ptr, info_ptr);
  70.278 +
  70.279 +#ifdef PNG_USER_MEM_SUPPORTED
  70.280 +      png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  70.281 +          png_ptr->mem_ptr);
  70.282 +#else
  70.283 +      png_destroy_struct((png_voidp)info_ptr);
  70.284 +#endif
  70.285 +      *info_ptr_ptr = NULL;
  70.286 +   }
  70.287 +}
  70.288 +
  70.289 +/* Initialize the info structure.  This is now an internal function (0.89)
  70.290 + * and applications using it are urged to use png_create_info_struct()
  70.291 + * instead.
  70.292 + */
  70.293 +#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  70.294 +#undef png_info_init
  70.295 +void PNGAPI
  70.296 +png_info_init(png_infop info_ptr)
  70.297 +{
  70.298 +   /* We only come here via pre-1.0.12-compiled applications */
  70.299 +   png_info_init_3(&info_ptr, 0);
  70.300 +}
  70.301 +#endif
  70.302 +
  70.303 +void PNGAPI
  70.304 +png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  70.305 +{
  70.306 +   png_infop info_ptr = *ptr_ptr;
  70.307 +
  70.308 +   if (info_ptr == NULL) return;
  70.309 +
  70.310 +   png_debug(1, "in png_info_init_3\n");
  70.311 +
  70.312 +   if (png_sizeof(png_info) > png_info_struct_size)
  70.313 +     {
  70.314 +       png_destroy_struct(info_ptr);
  70.315 +       info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  70.316 +       *ptr_ptr = info_ptr;
  70.317 +     }
  70.318 +
  70.319 +   /* set everything to 0 */
  70.320 +   png_memset(info_ptr, 0, png_sizeof(png_info));
  70.321 +}
  70.322 +
  70.323 +#ifdef PNG_FREE_ME_SUPPORTED
  70.324 +void PNGAPI
  70.325 +png_data_freer(png_structp png_ptr, png_infop info_ptr,
  70.326 +   int freer, png_uint_32 mask)
  70.327 +{
  70.328 +   png_debug(1, "in png_data_freer\n");
  70.329 +   if (png_ptr == NULL || info_ptr == NULL)
  70.330 +      return;
  70.331 +   if (freer == PNG_DESTROY_WILL_FREE_DATA)
  70.332 +      info_ptr->free_me |= mask;
  70.333 +   else if (freer == PNG_USER_WILL_FREE_DATA)
  70.334 +      info_ptr->free_me &= ~mask;
  70.335 +   else
  70.336 +      png_warning(png_ptr,
  70.337 +         "Unknown freer parameter in png_data_freer.");
  70.338 +}
  70.339 +#endif
  70.340 +
  70.341 +void PNGAPI
  70.342 +png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  70.343 +   int num)
  70.344 +{
  70.345 +   png_debug(1, "in png_free_data\n");
  70.346 +   if (png_ptr == NULL || info_ptr == NULL)
  70.347 +      return;
  70.348 +
  70.349 +#if defined(PNG_TEXT_SUPPORTED)
  70.350 +/* free text item num or (if num == -1) all text items */
  70.351 +#ifdef PNG_FREE_ME_SUPPORTED
  70.352 +if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  70.353 +#else
  70.354 +if (mask & PNG_FREE_TEXT)
  70.355 +#endif
  70.356 +{
  70.357 +   if (num != -1)
  70.358 +   {
  70.359 +     if (info_ptr->text && info_ptr->text[num].key)
  70.360 +     {
  70.361 +         png_free(png_ptr, info_ptr->text[num].key);
  70.362 +         info_ptr->text[num].key = NULL;
  70.363 +     }
  70.364 +   }
  70.365 +   else
  70.366 +   {
  70.367 +       int i;
  70.368 +       for (i = 0; i < info_ptr->num_text; i++)
  70.369 +           png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  70.370 +       png_free(png_ptr, info_ptr->text);
  70.371 +       info_ptr->text = NULL;
  70.372 +       info_ptr->num_text=0;
  70.373 +   }
  70.374 +}
  70.375 +#endif
  70.376 +
  70.377 +#if defined(PNG_tRNS_SUPPORTED)
  70.378 +/* free any tRNS entry */
  70.379 +#ifdef PNG_FREE_ME_SUPPORTED
  70.380 +if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  70.381 +#else
  70.382 +if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  70.383 +#endif
  70.384 +{
  70.385 +    png_free(png_ptr, info_ptr->trans);
  70.386 +    info_ptr->trans = NULL;
  70.387 +    info_ptr->valid &= ~PNG_INFO_tRNS;
  70.388 +#ifndef PNG_FREE_ME_SUPPORTED
  70.389 +    png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  70.390 +#endif
  70.391 +}
  70.392 +#endif
  70.393 +
  70.394 +#if defined(PNG_sCAL_SUPPORTED)
  70.395 +/* free any sCAL entry */
  70.396 +#ifdef PNG_FREE_ME_SUPPORTED
  70.397 +if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  70.398 +#else
  70.399 +if (mask & PNG_FREE_SCAL)
  70.400 +#endif
  70.401 +{
  70.402 +#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  70.403 +    png_free(png_ptr, info_ptr->scal_s_width);
  70.404 +    png_free(png_ptr, info_ptr->scal_s_height);
  70.405 +    info_ptr->scal_s_width = NULL;
  70.406 +    info_ptr->scal_s_height = NULL;
  70.407 +#endif
  70.408 +    info_ptr->valid &= ~PNG_INFO_sCAL;
  70.409 +}
  70.410 +#endif
  70.411 +
  70.412 +#if defined(PNG_pCAL_SUPPORTED)
  70.413 +/* free any pCAL entry */
  70.414 +#ifdef PNG_FREE_ME_SUPPORTED
  70.415 +if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  70.416 +#else
  70.417 +if (mask & PNG_FREE_PCAL)
  70.418 +#endif
  70.419 +{
  70.420 +    png_free(png_ptr, info_ptr->pcal_purpose);
  70.421 +    png_free(png_ptr, info_ptr->pcal_units);
  70.422 +    info_ptr->pcal_purpose = NULL;
  70.423 +    info_ptr->pcal_units = NULL;
  70.424 +    if (info_ptr->pcal_params != NULL)
  70.425 +    {
  70.426 +        int i;
  70.427 +        for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  70.428 +        {
  70.429 +          png_free(png_ptr, info_ptr->pcal_params[i]);
  70.430 +          info_ptr->pcal_params[i]=NULL;
  70.431 +        }
  70.432 +        png_free(png_ptr, info_ptr->pcal_params);
  70.433 +        info_ptr->pcal_params = NULL;
  70.434 +    }
  70.435 +    info_ptr->valid &= ~PNG_INFO_pCAL;
  70.436 +}
  70.437 +#endif
  70.438 +
  70.439 +#if defined(PNG_iCCP_SUPPORTED)
  70.440 +/* free any iCCP entry */
  70.441 +#ifdef PNG_FREE_ME_SUPPORTED
  70.442 +if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  70.443 +#else
  70.444 +if (mask & PNG_FREE_ICCP)
  70.445 +#endif
  70.446 +{
  70.447 +    png_free(png_ptr, info_ptr->iccp_name);
  70.448 +    png_free(png_ptr, info_ptr->iccp_profile);
  70.449 +    info_ptr->iccp_name = NULL;
  70.450 +    info_ptr->iccp_profile = NULL;
  70.451 +    info_ptr->valid &= ~PNG_INFO_iCCP;
  70.452 +}
  70.453 +#endif
  70.454 +
  70.455 +#if defined(PNG_sPLT_SUPPORTED)
  70.456 +/* free a given sPLT entry, or (if num == -1) all sPLT entries */
  70.457 +#ifdef PNG_FREE_ME_SUPPORTED
  70.458 +if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  70.459 +#else
  70.460 +if (mask & PNG_FREE_SPLT)
  70.461 +#endif
  70.462 +{
  70.463 +   if (num != -1)
  70.464 +   {
  70.465 +      if (info_ptr->splt_palettes)
  70.466 +      {
  70.467 +          png_free(png_ptr, info_ptr->splt_palettes[num].name);
  70.468 +          png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  70.469 +          info_ptr->splt_palettes[num].name = NULL;
  70.470 +          info_ptr->splt_palettes[num].entries = NULL;
  70.471 +      }
  70.472 +   }
  70.473 +   else
  70.474 +   {
  70.475 +       if (info_ptr->splt_palettes_num)
  70.476 +       {
  70.477 +         int i;
  70.478 +         for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  70.479 +            png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  70.480 +
  70.481 +         png_free(png_ptr, info_ptr->splt_palettes);
  70.482 +         info_ptr->splt_palettes = NULL;
  70.483 +         info_ptr->splt_palettes_num = 0;
  70.484 +       }
  70.485 +       info_ptr->valid &= ~PNG_INFO_sPLT;
  70.486 +   }
  70.487 +}
  70.488 +#endif
  70.489 +
  70.490 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  70.491 +  if (png_ptr->unknown_chunk.data)
  70.492 +  {
  70.493 +    png_free(png_ptr, png_ptr->unknown_chunk.data);
  70.494 +    png_ptr->unknown_chunk.data = NULL;
  70.495 +  }
  70.496 +
  70.497 +#ifdef PNG_FREE_ME_SUPPORTED
  70.498 +if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  70.499 +#else
  70.500 +if (mask & PNG_FREE_UNKN)
  70.501 +#endif
  70.502 +{
  70.503 +   if (num != -1)
  70.504 +   {
  70.505 +       if (info_ptr->unknown_chunks)
  70.506 +       {
  70.507 +          png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  70.508 +          info_ptr->unknown_chunks[num].data = NULL;
  70.509 +       }
  70.510 +   }
  70.511 +   else
  70.512 +   {
  70.513 +       int i;
  70.514 +
  70.515 +       if (info_ptr->unknown_chunks_num)
  70.516 +       {
  70.517 +         for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  70.518 +            png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  70.519 +
  70.520 +         png_free(png_ptr, info_ptr->unknown_chunks);
  70.521 +         info_ptr->unknown_chunks = NULL;
  70.522 +         info_ptr->unknown_chunks_num = 0;
  70.523 +       }
  70.524 +   }
  70.525 +}
  70.526 +#endif
  70.527 +
  70.528 +#if defined(PNG_hIST_SUPPORTED)
  70.529 +/* free any hIST entry */
  70.530 +#ifdef PNG_FREE_ME_SUPPORTED
  70.531 +if ((mask & PNG_FREE_HIST)  & info_ptr->free_me)
  70.532 +#else
  70.533 +if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  70.534 +#endif
  70.535 +{
  70.536 +    png_free(png_ptr, info_ptr->hist);
  70.537 +    info_ptr->hist = NULL;
  70.538 +    info_ptr->valid &= ~PNG_INFO_hIST;
  70.539 +#ifndef PNG_FREE_ME_SUPPORTED
  70.540 +    png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  70.541 +#endif
  70.542 +}
  70.543 +#endif
  70.544 +
  70.545 +/* free any PLTE entry that was internally allocated */
  70.546 +#ifdef PNG_FREE_ME_SUPPORTED
  70.547 +if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  70.548 +#else
  70.549 +if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  70.550 +#endif
  70.551 +{
  70.552 +    png_zfree(png_ptr, info_ptr->palette);
  70.553 +    info_ptr->palette = NULL;
  70.554 +    info_ptr->valid &= ~PNG_INFO_PLTE;
  70.555 +#ifndef PNG_FREE_ME_SUPPORTED
  70.556 +    png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  70.557 +#endif
  70.558 +    info_ptr->num_palette = 0;
  70.559 +}
  70.560 +
  70.561 +#if defined(PNG_INFO_IMAGE_SUPPORTED)
  70.562 +/* free any image bits attached to the info structure */
  70.563 +#ifdef PNG_FREE_ME_SUPPORTED
  70.564 +if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  70.565 +#else
  70.566 +if (mask & PNG_FREE_ROWS)
  70.567 +#endif
  70.568 +{
  70.569 +    if (info_ptr->row_pointers)
  70.570 +    {
  70.571 +       int row;
  70.572 +       for (row = 0; row < (int)info_ptr->height; row++)
  70.573 +       {
  70.574 +          png_free(png_ptr, info_ptr->row_pointers[row]);
  70.575 +          info_ptr->row_pointers[row]=NULL;
  70.576 +       }
  70.577 +       png_free(png_ptr, info_ptr->row_pointers);
  70.578 +       info_ptr->row_pointers=NULL;
  70.579 +    }
  70.580 +    info_ptr->valid &= ~PNG_INFO_IDAT;
  70.581 +}
  70.582 +#endif
  70.583 +
  70.584 +#ifdef PNG_FREE_ME_SUPPORTED
  70.585 +   if (num == -1)
  70.586 +     info_ptr->free_me &= ~mask;
  70.587 +   else
  70.588 +     info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  70.589 +#endif
  70.590 +}
  70.591 +
  70.592 +/* This is an internal routine to free any memory that the info struct is
  70.593 + * pointing to before re-using it or freeing the struct itself.  Recall
  70.594 + * that png_free() checks for NULL pointers for us.
  70.595 + */
  70.596 +void /* PRIVATE */
  70.597 +png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  70.598 +{
  70.599 +   png_debug(1, "in png_info_destroy\n");
  70.600 +
  70.601 +   png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  70.602 +
  70.603 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  70.604 +   if (png_ptr->num_chunk_list)
  70.605 +   {
  70.606 +       png_free(png_ptr, png_ptr->chunk_list);
  70.607 +       png_ptr->chunk_list=NULL;
  70.608 +       png_ptr->num_chunk_list = 0;
  70.609 +   }
  70.610 +#endif
  70.611 +
  70.612 +   png_info_init_3(&info_ptr, png_sizeof(png_info));
  70.613 +}
  70.614 +#endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  70.615 +
  70.616 +/* This function returns a pointer to the io_ptr associated with the user
  70.617 + * functions.  The application should free any memory associated with this
  70.618 + * pointer before png_write_destroy() or png_read_destroy() are called.
  70.619 + */
  70.620 +png_voidp PNGAPI
  70.621 +png_get_io_ptr(png_structp png_ptr)
  70.622 +{
  70.623 +   if (png_ptr == NULL) return (NULL);
  70.624 +   return (png_ptr->io_ptr);
  70.625 +}
  70.626 +
  70.627 +#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  70.628 +#if !defined(PNG_NO_STDIO)
  70.629 +/* Initialize the default input/output functions for the PNG file.  If you
  70.630 + * use your own read or write routines, you can call either png_set_read_fn()
  70.631 + * or png_set_write_fn() instead of png_init_io().  If you have defined
  70.632 + * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  70.633 + * necessarily available.
  70.634 + */
  70.635 +void PNGAPI
  70.636 +png_init_io(png_structp png_ptr, png_FILE_p fp)
  70.637 +{
  70.638 +   png_debug(1, "in png_init_io\n");
  70.639 +   if (png_ptr == NULL) return;
  70.640 +   png_ptr->io_ptr = (png_voidp)fp;
  70.641 +}
  70.642 +#endif
  70.643 +
  70.644 +#if defined(PNG_TIME_RFC1123_SUPPORTED)
  70.645 +/* Convert the supplied time into an RFC 1123 string suitable for use in
  70.646 + * a "Creation Time" or other text-based time string.
  70.647 + */
  70.648 +png_charp PNGAPI
  70.649 +png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  70.650 +{
  70.651 +   static PNG_CONST char short_months[12][4] =
  70.652 +        {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  70.653 +         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  70.654 +
  70.655 +   if (png_ptr == NULL) return (NULL);
  70.656 +   if (png_ptr->time_buffer == NULL)
  70.657 +   {
  70.658 +      png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  70.659 +         png_sizeof(char)));
  70.660 +   }
  70.661 +
  70.662 +#if defined(_WIN32_WCE)
  70.663 +   {
  70.664 +      wchar_t time_buf[29];
  70.665 +      wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  70.666 +          ptime->day % 32, short_months[(ptime->month - 1) % 12],
  70.667 +        ptime->year, ptime->hour % 24, ptime->minute % 60,
  70.668 +          ptime->second % 61);
  70.669 +      WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  70.670 +          NULL, NULL);
  70.671 +   }
  70.672 +#else
  70.673 +#ifdef USE_FAR_KEYWORD
  70.674 +   {
  70.675 +      char near_time_buf[29];
  70.676 +      png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000",
  70.677 +          ptime->day % 32, short_months[(ptime->month - 1) % 12],
  70.678 +          ptime->year, ptime->hour % 24, ptime->minute % 60,
  70.679 +          ptime->second % 61);
  70.680 +      png_memcpy(png_ptr->time_buffer, near_time_buf,
  70.681 +          29*png_sizeof(char));
  70.682 +   }
  70.683 +#else
  70.684 +   png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000",
  70.685 +       ptime->day % 32, short_months[(ptime->month - 1) % 12],
  70.686 +       ptime->year, ptime->hour % 24, ptime->minute % 60,
  70.687 +       ptime->second % 61);
  70.688 +#endif
  70.689 +#endif /* _WIN32_WCE */
  70.690 +   return ((png_charp)png_ptr->time_buffer);
  70.691 +}
  70.692 +#endif /* PNG_TIME_RFC1123_SUPPORTED */
  70.693 +
  70.694 +#endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  70.695 +
  70.696 +png_charp PNGAPI
  70.697 +png_get_copyright(png_structp png_ptr)
  70.698 +{
  70.699 +   png_ptr = png_ptr;  /* silence compiler warning about unused png_ptr */
  70.700 +   return ((png_charp) "\n libpng version 1.2.33 - October 31, 2008\n\
  70.701 +   Copyright (c) 1998-2008 Glenn Randers-Pehrson\n\
  70.702 +   Copyright (c) 1996-1997 Andreas Dilger\n\
  70.703 +   Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  70.704 +}
  70.705 +
  70.706 +/* The following return the library version as a short string in the
  70.707 + * format 1.0.0 through 99.99.99zz.  To get the version of *.h files
  70.708 + * used with your application, print out PNG_LIBPNG_VER_STRING, which
  70.709 + * is defined in png.h.
  70.710 + * Note: now there is no difference between png_get_libpng_ver() and
  70.711 + * png_get_header_ver().  Due to the version_nn_nn_nn typedef guard,
  70.712 + * it is guaranteed that png.c uses the correct version of png.h.
  70.713 + */
  70.714 +png_charp PNGAPI
  70.715 +png_get_libpng_ver(png_structp png_ptr)
  70.716 +{
  70.717 +   /* Version of *.c files used when building libpng */
  70.718 +   png_ptr = png_ptr;  /* silence compiler warning about unused png_ptr */
  70.719 +   return ((png_charp) PNG_LIBPNG_VER_STRING);
  70.720 +}
  70.721 +
  70.722 +png_charp PNGAPI
  70.723 +png_get_header_ver(png_structp png_ptr)
  70.724 +{
  70.725 +   /* Version of *.h files used when building libpng */
  70.726 +   png_ptr = png_ptr;  /* silence compiler warning about unused png_ptr */
  70.727 +   return ((png_charp) PNG_LIBPNG_VER_STRING);
  70.728 +}
  70.729 +
  70.730 +png_charp PNGAPI
  70.731 +png_get_header_version(png_structp png_ptr)
  70.732 +{
  70.733 +   /* Returns longer string containing both version and date */
  70.734 +   png_ptr = png_ptr;  /* silence compiler warning about unused png_ptr */
  70.735 +   return ((png_charp) PNG_HEADER_VERSION_STRING
  70.736 +#ifndef PNG_READ_SUPPORTED
  70.737 +   "     (NO READ SUPPORT)"
  70.738 +#endif
  70.739 +   "\n");
  70.740 +}
  70.741 +
  70.742 +#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  70.743 +#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  70.744 +int PNGAPI
  70.745 +png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  70.746 +{
  70.747 +   /* check chunk_name and return "keep" value if it's on the list, else 0 */
  70.748 +   int i;
  70.749 +   png_bytep p;
  70.750 +   if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  70.751 +      return 0;
  70.752 +   p = png_ptr->chunk_list + png_ptr->num_chunk_list*5 - 5;
  70.753 +   for (i = png_ptr->num_chunk_list; i; i--, p -= 5)
  70.754 +      if (!png_memcmp(chunk_name, p, 4))
  70.755 +        return ((int)*(p + 4));
  70.756 +   return 0;
  70.757 +}
  70.758 +#endif
  70.759 +
  70.760 +/* This function, added to libpng-1.0.6g, is untested. */
  70.761 +int PNGAPI
  70.762 +png_reset_zstream(png_structp png_ptr)
  70.763 +{
  70.764 +   if (png_ptr == NULL) return Z_STREAM_ERROR;
  70.765 +   return (inflateReset(&png_ptr->zstream));
  70.766 +}
  70.767 +#endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  70.768 +
  70.769 +/* This function was added to libpng-1.0.7 */
  70.770 +png_uint_32 PNGAPI
  70.771 +png_access_version_number(void)
  70.772 +{
  70.773 +   /* Version of *.c files used when building libpng */
  70.774 +   return((png_uint_32) PNG_LIBPNG_VER);
  70.775 +}
  70.776 +
  70.777 +
  70.778 +#if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  70.779 +#if !defined(PNG_1_0_X)
  70.780 +/* this function was added to libpng 1.2.0 */
  70.781 +int PNGAPI
  70.782 +png_mmx_support(void)
  70.783 +{
  70.784 +   /* obsolete, to be removed from libpng-1.4.0 */
  70.785 +    return -1;
  70.786 +}
  70.787 +#endif /* PNG_1_0_X */
  70.788 +#endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  70.789 +
  70.790 +#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  70.791 +#ifdef PNG_SIZE_T
  70.792 +/* Added at libpng version 1.2.6 */
  70.793 +   PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  70.794 +png_size_t PNGAPI
  70.795 +png_convert_size(size_t size)
  70.796 +{
  70.797 +  if (size > (png_size_t)-1)
  70.798 +     PNG_ABORT();  /* We haven't got access to png_ptr, so no png_error() */
  70.799 +  return ((png_size_t)size);
  70.800 +}
  70.801 +#endif /* PNG_SIZE_T */
  70.802 +#endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
    71.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    71.2 +++ b/libs/libpng/png.h	Thu Sep 08 06:28:38 2011 +0300
    71.3 @@ -0,0 +1,3597 @@
    71.4 +/* png.h - header file for PNG reference library
    71.5 + *
    71.6 + * libpng version 1.2.33 - October 31, 2008
    71.7 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
    71.8 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
    71.9 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   71.10 + *
   71.11 + * Authors and maintainers:
   71.12 + *  libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
   71.13 + *  libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
   71.14 + *  libpng versions 0.97, January 1998, through 1.2.33 - October 31, 2008: Glenn
   71.15 + *  See also "Contributing Authors", below.
   71.16 + *
   71.17 + * Note about libpng version numbers:
   71.18 + *
   71.19 + *    Due to various miscommunications, unforeseen code incompatibilities
   71.20 + *    and occasional factors outside the authors' control, version numbering
   71.21 + *    on the library has not always been consistent and straightforward.
   71.22 + *    The following table summarizes matters since version 0.89c, which was
   71.23 + *    the first widely used release:
   71.24 + *
   71.25 + *    source                 png.h  png.h  shared-lib
   71.26 + *    version                string   int  version
   71.27 + *    -------                ------ -----  ----------
   71.28 + *    0.89c "1.0 beta 3"     0.89      89  1.0.89
   71.29 + *    0.90  "1.0 beta 4"     0.90      90  0.90  [should have been 2.0.90]
   71.30 + *    0.95  "1.0 beta 5"     0.95      95  0.95  [should have been 2.0.95]
   71.31 + *    0.96  "1.0 beta 6"     0.96      96  0.96  [should have been 2.0.96]
   71.32 + *    0.97b "1.00.97 beta 7" 1.00.97   97  1.0.1 [should have been 2.0.97]
   71.33 + *    0.97c                  0.97      97  2.0.97
   71.34 + *    0.98                   0.98      98  2.0.98
   71.35 + *    0.99                   0.99      98  2.0.99
   71.36 + *    0.99a-m                0.99      99  2.0.99
   71.37 + *    1.00                   1.00     100  2.1.0 [100 should be 10000]
   71.38 + *    1.0.0      (from here on, the   100  2.1.0 [100 should be 10000]
   71.39 + *    1.0.1       png.h string is   10001  2.1.0
   71.40 + *    1.0.1a-e    identical to the  10002  from here on, the shared library
   71.41 + *    1.0.2       source version)   10002  is 2.V where V is the source code
   71.42 + *    1.0.2a-b                      10003  version, except as noted.
   71.43 + *    1.0.3                         10003
   71.44 + *    1.0.3a-d                      10004
   71.45 + *    1.0.4                         10004
   71.46 + *    1.0.4a-f                      10005
   71.47 + *    1.0.5 (+ 2 patches)           10005
   71.48 + *    1.0.5a-d                      10006
   71.49 + *    1.0.5e-r                      10100 (not source compatible)
   71.50 + *    1.0.5s-v                      10006 (not binary compatible)
   71.51 + *    1.0.6 (+ 3 patches)           10006 (still binary incompatible)
   71.52 + *    1.0.6d-f                      10007 (still binary incompatible)
   71.53 + *    1.0.6g                        10007
   71.54 + *    1.0.6h                        10007  10.6h (testing xy.z so-numbering)
   71.55 + *    1.0.6i                        10007  10.6i
   71.56 + *    1.0.6j                        10007  2.1.0.6j (incompatible with 1.0.0)
   71.57 + *    1.0.7beta11-14        DLLNUM  10007  2.1.0.7beta11-14 (binary compatible)
   71.58 + *    1.0.7beta15-18           1    10007  2.1.0.7beta15-18 (binary compatible)
   71.59 + *    1.0.7rc1-2               1    10007  2.1.0.7rc1-2 (binary compatible)
   71.60 + *    1.0.7                    1    10007  (still compatible)
   71.61 + *    1.0.8beta1-4             1    10008  2.1.0.8beta1-4
   71.62 + *    1.0.8rc1                 1    10008  2.1.0.8rc1
   71.63 + *    1.0.8                    1    10008  2.1.0.8
   71.64 + *    1.0.9beta1-6             1    10009  2.1.0.9beta1-6
   71.65 + *    1.0.9rc1                 1    10009  2.1.0.9rc1
   71.66 + *    1.0.9beta7-10            1    10009  2.1.0.9beta7-10
   71.67 + *    1.0.9rc2                 1    10009  2.1.0.9rc2
   71.68 + *    1.0.9                    1    10009  2.1.0.9
   71.69 + *    1.0.10beta1              1    10010  2.1.0.10beta1
   71.70 + *    1.0.10rc1                1    10010  2.1.0.10rc1
   71.71 + *    1.0.10                   1    10010  2.1.0.10
   71.72 + *    1.0.11beta1-3            1    10011  2.1.0.11beta1-3
   71.73 + *    1.0.11rc1                1    10011  2.1.0.11rc1
   71.74 + *    1.0.11                   1    10011  2.1.0.11
   71.75 + *    1.0.12beta1-2            2    10012  2.1.0.12beta1-2
   71.76 + *    1.0.12rc1                2    10012  2.1.0.12rc1
   71.77 + *    1.0.12                   2    10012  2.1.0.12
   71.78 + *    1.1.0a-f                 -    10100  2.1.1.0a-f (branch abandoned)
   71.79 + *    1.2.0beta1-2             2    10200  2.1.2.0beta1-2
   71.80 + *    1.2.0beta3-5             3    10200  3.1.2.0beta3-5
   71.81 + *    1.2.0rc1                 3    10200  3.1.2.0rc1
   71.82 + *    1.2.0                    3    10200  3.1.2.0
   71.83 + *    1.2.1beta1-4             3    10201  3.1.2.1beta1-4
   71.84 + *    1.2.1rc1-2               3    10201  3.1.2.1rc1-2
   71.85 + *    1.2.1                    3    10201  3.1.2.1
   71.86 + *    1.2.2beta1-6            12    10202  12.so.0.1.2.2beta1-6
   71.87 + *    1.0.13beta1             10    10013  10.so.0.1.0.13beta1
   71.88 + *    1.0.13rc1               10    10013  10.so.0.1.0.13rc1
   71.89 + *    1.2.2rc1                12    10202  12.so.0.1.2.2rc1
   71.90 + *    1.0.13                  10    10013  10.so.0.1.0.13
   71.91 + *    1.2.2                   12    10202  12.so.0.1.2.2
   71.92 + *    1.2.3rc1-6              12    10203  12.so.0.1.2.3rc1-6
   71.93 + *    1.2.3                   12    10203  12.so.0.1.2.3
   71.94 + *    1.2.4beta1-3            13    10204  12.so.0.1.2.4beta1-3
   71.95 + *    1.0.14rc1               13    10014  10.so.0.1.0.14rc1
   71.96 + *    1.2.4rc1                13    10204  12.so.0.1.2.4rc1
   71.97 + *    1.0.14                  10    10014  10.so.0.1.0.14
   71.98 + *    1.2.4                   13    10204  12.so.0.1.2.4
   71.99 + *    1.2.5beta1-2            13    10205  12.so.0.1.2.5beta1-2
  71.100 + *    1.0.15rc1-3             10    10015  10.so.0.1.0.15rc1-3
  71.101 + *    1.2.5rc1-3              13    10205  12.so.0.1.2.5rc1-3
  71.102 + *    1.0.15                  10    10015  10.so.0.1.0.15
  71.103 + *    1.2.5                   13    10205  12.so.0.1.2.5
  71.104 + *    1.2.6beta1-4            13    10206  12.so.0.1.2.6beta1-4
  71.105 + *    1.0.16                  10    10016  10.so.0.1.0.16
  71.106 + *    1.2.6                   13    10206  12.so.0.1.2.6
  71.107 + *    1.2.7beta1-2            13    10207  12.so.0.1.2.7beta1-2
  71.108 + *    1.0.17rc1               10    10017  10.so.0.1.0.17rc1
  71.109 + *    1.2.7rc1                13    10207  12.so.0.1.2.7rc1
  71.110 + *    1.0.17                  10    10017  10.so.0.1.0.17
  71.111 + *    1.2.7                   13    10207  12.so.0.1.2.7
  71.112 + *    1.2.8beta1-5            13    10208  12.so.0.1.2.8beta1-5
  71.113 + *    1.0.18rc1-5             10    10018  10.so.0.1.0.18rc1-5
  71.114 + *    1.2.8rc1-5              13    10208  12.so.0.1.2.8rc1-5
  71.115 + *    1.0.18                  10    10018  10.so.0.1.0.18
  71.116 + *    1.2.8                   13    10208  12.so.0.1.2.8
  71.117 + *    1.2.9beta1-3            13    10209  12.so.0.1.2.9beta1-3
  71.118 + *    1.2.9beta4-11           13    10209  12.so.0.9[.0]
  71.119 + *    1.2.9rc1                13    10209  12.so.0.9[.0]
  71.120 + *    1.2.9                   13    10209  12.so.0.9[.0]
  71.121 + *    1.2.10beta1-8           13    10210  12.so.0.10[.0]
  71.122 + *    1.2.10rc1-3             13    10210  12.so.0.10[.0]
  71.123 + *    1.2.10                  13    10210  12.so.0.10[.0]
  71.124 + *    1.2.11beta1-4           13    10211  12.so.0.11[.0]
  71.125 + *    1.0.19rc1-5             10    10019  10.so.0.19[.0]
  71.126 + *    1.2.11rc1-5             13    10211  12.so.0.11[.0]
  71.127 + *    1.0.19                  10    10019  10.so.0.19[.0]
  71.128 + *    1.2.11                  13    10211  12.so.0.11[.0]
  71.129 + *    1.0.20                  10    10020  10.so.0.20[.0]
  71.130 + *    1.2.12                  13    10212  12.so.0.12[.0]
  71.131 + *    1.2.13beta1             13    10213  12.so.0.13[.0]
  71.132 + *    1.0.21                  10    10021  10.so.0.21[.0]
  71.133 + *    1.2.13                  13    10213  12.so.0.13[.0]
  71.134 + *    1.2.14beta1-2           13    10214  12.so.0.14[.0]
  71.135 + *    1.0.22rc1               10    10022  10.so.0.22[.0]
  71.136 + *    1.2.14rc1               13    10214  12.so.0.14[.0]
  71.137 + *    1.0.22                  10    10022  10.so.0.22[.0]
  71.138 + *    1.2.14                  13    10214  12.so.0.14[.0]
  71.139 + *    1.2.15beta1-6           13    10215  12.so.0.15[.0]
  71.140 + *    1.0.23rc1-5             10    10023  10.so.0.23[.0]
  71.141 + *    1.2.15rc1-5             13    10215  12.so.0.15[.0]
  71.142 + *    1.0.23                  10    10023  10.so.0.23[.0]
  71.143 + *    1.2.15                  13    10215  12.so.0.15[.0]
  71.144 + *    1.2.16beta1-2           13    10216  12.so.0.16[.0]
  71.145 + *    1.2.16rc1               13    10216  12.so.0.16[.0]
  71.146 + *    1.0.24                  10    10024  10.so.0.24[.0]
  71.147 + *    1.2.16                  13    10216  12.so.0.16[.0]
  71.148 + *    1.2.17beta1-2           13    10217  12.so.0.17[.0]
  71.149 + *    1.0.25rc1               10    10025  10.so.0.25[.0]
  71.150 + *    1.2.17rc1-3             13    10217  12.so.0.17[.0]
  71.151 + *    1.0.25                  10    10025  10.so.0.25[.0]
  71.152 + *    1.2.17                  13    10217  12.so.0.17[.0]
  71.153 + *    1.0.26                  10    10026  10.so.0.26[.0]
  71.154 + *    1.2.18                  13    10218  12.so.0.18[.0]
  71.155 + *    1.2.19beta1-31          13    10219  12.so.0.19[.0]
  71.156 + *    1.0.27rc1-6             10    10027  10.so.0.27[.0]
  71.157 + *    1.2.19rc1-6             13    10219  12.so.0.19[.0]
  71.158 + *    1.0.27                  10    10027  10.so.0.27[.0]
  71.159 + *    1.2.19                  13    10219  12.so.0.19[.0]
  71.160 + *    1.2.20beta01-04         13    10220  12.so.0.20[.0]
  71.161 + *    1.0.28rc1-6             10    10028  10.so.0.28[.0]
  71.162 + *    1.2.20rc1-6             13    10220  12.so.0.20[.0]
  71.163 + *    1.0.28                  10    10028  10.so.0.28[.0]
  71.164 + *    1.2.20                  13    10220  12.so.0.20[.0]
  71.165 + *    1.2.21beta1-2           13    10221  12.so.0.21[.0]
  71.166 + *    1.2.21rc1-3             13    10221  12.so.0.21[.0]
  71.167 + *    1.0.29                  10    10029  10.so.0.29[.0]
  71.168 + *    1.2.21                  13    10221  12.so.0.21[.0]
  71.169 + *    1.2.22beta1-4           13    10222  12.so.0.22[.0]
  71.170 + *    1.0.30rc1               10    10030  10.so.0.30[.0]
  71.171 + *    1.2.22rc1               13    10222  12.so.0.22[.0]
  71.172 + *    1.0.30                  10    10030  10.so.0.30[.0]
  71.173 + *    1.2.22                  13    10222  12.so.0.22[.0]
  71.174 + *    1.2.23beta01-05         13    10223  12.so.0.23[.0]
  71.175 + *    1.2.23rc01              13    10223  12.so.0.23[.0]
  71.176 + *    1.2.23                  13    10223  12.so.0.23[.0]
  71.177 + *    1.2.24beta01-02         13    10224  12.so.0.24[.0]
  71.178 + *    1.2.24rc01              13    10224  12.so.0.24[.0]
  71.179 + *    1.2.24                  13    10224  12.so.0.24[.0]
  71.180 + *    1.2.25beta01-06         13    10225  12.so.0.25[.0]
  71.181 + *    1.2.25rc01-02           13    10225  12.so.0.25[.0]
  71.182 + *    1.0.31                  10    10031  10.so.0.31[.0]
  71.183 + *    1.2.25                  13    10225  12.so.0.25[.0]
  71.184 + *    1.2.26beta01-06         13    10226  12.so.0.26[.0]
  71.185 + *    1.2.26rc01              13    10226  12.so.0.26[.0]
  71.186 + *    1.2.26                  13    10226  12.so.0.26[.0]
  71.187 + *    1.0.32                  10    10032  10.so.0.32[.0]
  71.188 + *    1.2.27beta01-06         13    10227  12.so.0.27[.0]
  71.189 + *    1.2.27rc01              13    10227  12.so.0.27[.0]
  71.190 + *    1.0.33                  10    10033  10.so.0.33[.0]
  71.191 + *    1.2.27                  13    10227  12.so.0.27[.0]
  71.192 + *    1.0.34                  10    10034  10.so.0.34[.0]
  71.193 + *    1.2.28                  13    10228  12.so.0.28[.0]
  71.194 + *    1.2.29beta01-03         13    10229  12.so.0.29[.0]
  71.195 + *    1.2.29rc01              13    10229  12.so.0.29[.0]
  71.196 + *    1.0.35                  10    10035  10.so.0.35[.0]
  71.197 + *    1.2.29                  13    10229  12.so.0.29[.0]
  71.198 + *    1.0.37                  10    10037  10.so.0.37[.0]
  71.199 + *    1.2.30beta01-04         13    10230  12.so.0.30[.0]
  71.200 + *    1.0.38rc01-08           10    10038  10.so.0.38[.0]
  71.201 + *    1.2.30rc01-08           13    10230  12.so.0.30[.0]
  71.202 + *    1.0.38                  10    10038  10.so.0.38[.0]
  71.203 + *    1.2.30                  13    10230  12.so.0.30[.0]
  71.204 + *    1.0.39rc01-03           10    10039  10.so.0.39[.0]
  71.205 + *    1.2.31rc01-03           13    10231  12.so.0.31[.0]
  71.206 + *    1.0.39                  10    10039  10.so.0.39[.0]
  71.207 + *    1.2.31                  13    10231  12.so.0.31[.0]
  71.208 + *    1.2.32beta01-02         13    10232  12.so.0.32[.0]
  71.209 + *    1.0.40rc01              10    10040  10.so.0.40[.0]
  71.210 + *    1.2.32rc01              13    10232  12.so.0.32[.0]
  71.211 + *    1.0.40                  10    10040  10.so.0.40[.0]
  71.212 + *    1.2.32                  13    10232  12.so.0.32[.0]
  71.213 + *    1.2.33beta01-02         13    10233  12.so.0.33[.0]
  71.214 + *    1.2.33rc01-02           13    10233  12.so.0.33[.0]
  71.215 + *    1.0.41rc01              10    10041  10.so.0.41[.0]
  71.216 + *    1.2.33                  13    10233  12.so.0.33[.0]
  71.217 + *    1.0.41                  10    10041  10.so.0.41[.0]
  71.218 + *
  71.219 + *    Henceforth the source version will match the shared-library major
  71.220 + *    and minor numbers; the shared-library major version number will be
  71.221 + *    used for changes in backward compatibility, as it is intended.  The
  71.222 + *    PNG_LIBPNG_VER macro, which is not used within libpng but is available
  71.223 + *    for applications, is an unsigned integer of the form xyyzz corresponding
  71.224 + *    to the source version x.y.z (leading zeros in y and z).  Beta versions
  71.225 + *    were given the previous public release number plus a letter, until
  71.226 + *    version 1.0.6j; from then on they were given the upcoming public
  71.227 + *    release number plus "betaNN" or "rcNN".
  71.228 + *
  71.229 + *    Binary incompatibility exists only when applications make direct access
  71.230 + *    to the info_ptr or png_ptr members through png.h, and the compiled
  71.231 + *    application is loaded with a different version of the library.
  71.232 + *
  71.233 + *    DLLNUM will change each time there are forward or backward changes
  71.234 + *    in binary compatibility (e.g., when a new feature is added).
  71.235 + *
  71.236 + * See libpng.txt or libpng.3 for more information.  The PNG specification
  71.237 + * is available as a W3C Recommendation and as an ISO Specification,
  71.238 + * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  71.239 + */
  71.240 +
  71.241 +/*
  71.242 + * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  71.243 + *
  71.244 + * If you modify libpng you may insert additional notices immediately following
  71.245 + * this sentence.
  71.246 + *
  71.247 + * libpng versions 1.2.6, August 15, 2004, through 1.2.33, October 31, 2008, are
  71.248 + * Copyright (c) 2004, 2006-2008 Glenn Randers-Pehrson, and are
  71.249 + * distributed according to the same disclaimer and license as libpng-1.2.5
  71.250 + * with the following individual added to the list of Contributing Authors:
  71.251 + *
  71.252 + *    Cosmin Truta
  71.253 + *
  71.254 + * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  71.255 + * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  71.256 + * distributed according to the same disclaimer and license as libpng-1.0.6
  71.257 + * with the following individuals added to the list of Contributing Authors:
  71.258 + *
  71.259 + *    Simon-Pierre Cadieux
  71.260 + *    Eric S. Raymond
  71.261 + *    Gilles Vollant
  71.262 + *
  71.263 + * and with the following additions to the disclaimer:
  71.264 + *
  71.265 + *    There is no warranty against interference with your enjoyment of the
  71.266 + *    library or against infringement.  There is no warranty that our
  71.267 + *    efforts or the library will fulfill any of your particular purposes
  71.268 + *    or needs.  This library is provided with all faults, and the entire
  71.269 + *    risk of satisfactory quality, performance, accuracy, and effort is with
  71.270 + *    the user.
  71.271 + *
  71.272 + * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  71.273 + * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  71.274 + * distributed according to the same disclaimer and license as libpng-0.96,
  71.275 + * with the following individuals added to the list of Contributing Authors:
  71.276 + *
  71.277 + *    Tom Lane
  71.278 + *    Glenn Randers-Pehrson
  71.279 + *    Willem van Schaik
  71.280 + *
  71.281 + * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  71.282 + * Copyright (c) 1996, 1997 Andreas Dilger
  71.283 + * Distributed according to the same disclaimer and license as libpng-0.88,
  71.284 + * with the following individuals added to the list of Contributing Authors:
  71.285 + *
  71.286 + *    John Bowler
  71.287 + *    Kevin Bracey
  71.288 + *    Sam Bushell
  71.289 + *    Magnus Holmgren
  71.290 + *    Greg Roelofs
  71.291 + *    Tom Tanner
  71.292 + *
  71.293 + * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  71.294 + * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  71.295 + *
  71.296 + * For the purposes of this copyright and license, "Contributing Authors"
  71.297 + * is defined as the following set of individuals:
  71.298 + *
  71.299 + *    Andreas Dilger
  71.300 + *    Dave Martindale
  71.301 + *    Guy Eric Schalnat
  71.302 + *    Paul Schmidt
  71.303 + *    Tim Wegner
  71.304 + *
  71.305 + * The PNG Reference Library is supplied "AS IS".  The Contributing Authors
  71.306 + * and Group 42, Inc. disclaim all warranties, expressed or implied,
  71.307 + * including, without limitation, the warranties of merchantability and of
  71.308 + * fitness for any purpose.  The Contributing Authors and Group 42, Inc.
  71.309 + * assume no liability for direct, indirect, incidental, special, exemplary,
  71.310 + * or consequential damages, which may result from the use of the PNG
  71.311 + * Reference Library, even if advised of the possibility of such damage.
  71.312 + *
  71.313 + * Permission is hereby granted to use, copy, modify, and distribute this
  71.314 + * source code, or portions hereof, for any purpose, without fee, subject
  71.315 + * to the following restrictions:
  71.316 + *
  71.317 + * 1. The origin of this source code must not be misrepresented.
  71.318 + *
  71.319 + * 2. Altered versions must be plainly marked as such and
  71.320 + * must not be misrepresented as being the original source.
  71.321 + *
  71.322 + * 3. This Copyright notice may not be removed or altered from
  71.323 + *    any source or altered source distribution.
  71.324 + *
  71.325 + * The Contributing Authors and Group 42, Inc. specifically permit, without
  71.326 + * fee, and encourage the use of this source code as a component to
  71.327 + * supporting the PNG file format in commercial products.  If you use this
  71.328 + * source code in a product, acknowledgment is not required but would be
  71.329 + * appreciated.
  71.330 + */
  71.331 +
  71.332 +/*
  71.333 + * A "png_get_copyright" function is available, for convenient use in "about"
  71.334 + * boxes and the like:
  71.335 + *
  71.336 + * printf("%s",png_get_copyright(NULL));
  71.337 + *
  71.338 + * Also, the PNG logo (in PNG format, of course) is supplied in the
  71.339 + * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  71.340 + */
  71.341 +
  71.342 +/*
  71.343 + * Libpng is OSI Certified Open Source Software.  OSI Certified is a
  71.344 + * certification mark of the Open Source Initiative.
  71.345 + */
  71.346 +
  71.347 +/*
  71.348 + * The contributing authors would like to thank all those who helped
  71.349 + * with testing, bug fixes, and patience.  This wouldn't have been
  71.350 + * possible without all of you.
  71.351 + *
  71.352 + * Thanks to Frank J. T. Wojcik for helping with the documentation.
  71.353 + */
  71.354 +
  71.355 +/*
  71.356 + * Y2K compliance in libpng:
  71.357 + * =========================
  71.358 + *
  71.359 + *    October 31, 2008
  71.360 + *
  71.361 + *    Since the PNG Development group is an ad-hoc body, we can't make
  71.362 + *    an official declaration.
  71.363 + *
  71.364 + *    This is your unofficial assurance that libpng from version 0.71 and
  71.365 + *    upward through 1.2.33 are Y2K compliant.  It is my belief that earlier
  71.366 + *    versions were also Y2K compliant.
  71.367 + *
  71.368 + *    Libpng only has three year fields.  One is a 2-byte unsigned integer
  71.369 + *    that will hold years up to 65535.  The other two hold the date in text
  71.370 + *    format, and will hold years up to 9999.
  71.371 + *
  71.372 + *    The integer is
  71.373 + *        "png_uint_16 year" in png_time_struct.
  71.374 + *
  71.375 + *    The strings are
  71.376 + *        "png_charp time_buffer" in png_struct and
  71.377 + *        "near_time_buffer", which is a local character string in png.c.
  71.378 + *
  71.379 + *    There are seven time-related functions:
  71.380 + *        png.c: png_convert_to_rfc_1123() in png.c
  71.381 + *          (formerly png_convert_to_rfc_1152() in error)
  71.382 + *        png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  71.383 + *        png_convert_from_time_t() in pngwrite.c
  71.384 + *        png_get_tIME() in pngget.c
  71.385 + *        png_handle_tIME() in pngrutil.c, called in pngread.c
  71.386 + *        png_set_tIME() in pngset.c
  71.387 + *        png_write_tIME() in pngwutil.c, called in pngwrite.c
  71.388 + *
  71.389 + *    All handle dates properly in a Y2K environment.  The
  71.390 + *    png_convert_from_time_t() function calls gmtime() to convert from system
  71.391 + *    clock time, which returns (year - 1900), which we properly convert to
  71.392 + *    the full 4-digit year.  There is a possibility that applications using
  71.393 + *    libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  71.394 + *    function, or that they are incorrectly passing only a 2-digit year
  71.395 + *    instead of "year - 1900" into the png_convert_from_struct_tm() function,
  71.396 + *    but this is not under our control.  The libpng documentation has always
  71.397 + *    stated that it works with 4-digit years, and the APIs have been
  71.398 + *    documented as such.
  71.399 + *
  71.400 + *    The tIME chunk itself is also Y2K compliant.  It uses a 2-byte unsigned
  71.401 + *    integer to hold the year, and can hold years as large as 65535.
  71.402 + *
  71.403 + *    zlib, upon which libpng depends, is also Y2K compliant.  It contains
  71.404 + *    no date-related code.
  71.405 + *
  71.406 + *       Glenn Randers-Pehrson
  71.407 + *       libpng maintainer
  71.408 + *       PNG Development Group
  71.409 + */
  71.410 +
  71.411 +#ifndef PNG_H
  71.412 +#define PNG_H
  71.413 +
  71.414 +/* This is not the place to learn how to use libpng.  The file libpng.txt
  71.415 + * describes how to use libpng, and the file example.c summarizes it
  71.416 + * with some code on which to build.  This file is useful for looking
  71.417 + * at the actual function definitions and structure components.
  71.418 + */
  71.419 +
  71.420 +/* Version information for png.h - this should match the version in png.c */
  71.421 +#define PNG_LIBPNG_VER_STRING "1.2.33"
  71.422 +#define PNG_HEADER_VERSION_STRING \
  71.423 +   " libpng version 1.2.33 - October 31, 2008\n"
  71.424 +
  71.425 +#define PNG_LIBPNG_VER_SONUM   0
  71.426 +#define PNG_LIBPNG_VER_DLLNUM  13
  71.427 +
  71.428 +/* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  71.429 +#define PNG_LIBPNG_VER_MAJOR   1
  71.430 +#define PNG_LIBPNG_VER_MINOR   2
  71.431 +#define PNG_LIBPNG_VER_RELEASE 33
  71.432 +/* This should match the numeric part of the final component of
  71.433 + * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  71.434 +
  71.435 +#define PNG_LIBPNG_VER_BUILD  0
  71.436 +
  71.437 +/* Release Status */
  71.438 +#define PNG_LIBPNG_BUILD_ALPHA    1
  71.439 +#define PNG_LIBPNG_BUILD_BETA     2
  71.440 +#define PNG_LIBPNG_BUILD_RC       3
  71.441 +#define PNG_LIBPNG_BUILD_STABLE   4
  71.442 +#define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  71.443 +  
  71.444 +/* Release-Specific Flags */
  71.445 +#define PNG_LIBPNG_BUILD_PATCH    8 /* Can be OR'ed with
  71.446 +                                       PNG_LIBPNG_BUILD_STABLE only */
  71.447 +#define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  71.448 +                                       PNG_LIBPNG_BUILD_SPECIAL */
  71.449 +#define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  71.450 +                                       PNG_LIBPNG_BUILD_PRIVATE */
  71.451 +
  71.452 +#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  71.453 +
  71.454 +/* Careful here.  At one time, Guy wanted to use 082, but that would be octal.
  71.455 + * We must not include leading zeros.
  71.456 + * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  71.457 + * version 1.0.0 was mis-numbered 100 instead of 10000).  From
  71.458 + * version 1.0.1 it's    xxyyzz, where x=major, y=minor, z=release */
  71.459 +#define PNG_LIBPNG_VER 10233 /* 1.2.33 */
  71.460 +
  71.461 +#ifndef PNG_VERSION_INFO_ONLY
  71.462 +/* include the compression library's header */
  71.463 +#include "zlib.h"
  71.464 +#endif
  71.465 +
  71.466 +/* include all user configurable info, including optional assembler routines */
  71.467 +#include "pngconf.h"
  71.468 +
  71.469 +/*
  71.470 + * Added at libpng-1.2.8 */
  71.471 +/* Ref MSDN: Private as priority over Special
  71.472 + * VS_FF_PRIVATEBUILD File *was not* built using standard release
  71.473 + * procedures. If this value is given, the StringFileInfo block must
  71.474 + * contain a PrivateBuild string. 
  71.475 + *
  71.476 + * VS_FF_SPECIALBUILD File *was* built by the original company using
  71.477 + * standard release procedures but is a variation of the standard
  71.478 + * file of the same version number. If this value is given, the
  71.479 + * StringFileInfo block must contain a SpecialBuild string. 
  71.480 + */
  71.481 +
  71.482 +#if defined(PNG_USER_PRIVATEBUILD)
  71.483 +#  define PNG_LIBPNG_BUILD_TYPE \
  71.484 +          (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  71.485 +#else
  71.486 +#  if defined(PNG_LIBPNG_SPECIALBUILD)
  71.487 +#    define PNG_LIBPNG_BUILD_TYPE \
  71.488 +            (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  71.489 +#  else
  71.490 +#    define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  71.491 +#  endif
  71.492 +#endif
  71.493 +
  71.494 +#ifndef PNG_VERSION_INFO_ONLY
  71.495 +
  71.496 +/* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  71.497 +#ifdef __cplusplus
  71.498 +extern "C" {
  71.499 +#endif /* __cplusplus */
  71.500 +
  71.501 +/* This file is arranged in several sections.  The first section contains
  71.502 + * structure and type definitions.  The second section contains the external
  71.503 + * library functions, while the third has the internal library functions,
  71.504 + * which applications aren't expected to use directly.
  71.505 + */
  71.506 +
  71.507 +#ifndef PNG_NO_TYPECAST_NULL
  71.508 +#define int_p_NULL                (int *)NULL
  71.509 +#define png_bytep_NULL            (png_bytep)NULL
  71.510 +#define png_bytepp_NULL           (png_bytepp)NULL
  71.511 +#define png_doublep_NULL          (png_doublep)NULL
  71.512 +#define png_error_ptr_NULL        (png_error_ptr)NULL
  71.513 +#define png_flush_ptr_NULL        (png_flush_ptr)NULL
  71.514 +#define png_free_ptr_NULL         (png_free_ptr)NULL
  71.515 +#define png_infopp_NULL           (png_infopp)NULL
  71.516 +#define png_malloc_ptr_NULL       (png_malloc_ptr)NULL
  71.517 +#define png_read_status_ptr_NULL  (png_read_status_ptr)NULL
  71.518 +#define png_rw_ptr_NULL           (png_rw_ptr)NULL
  71.519 +#define png_structp_NULL          (png_structp)NULL
  71.520 +#define png_uint_16p_NULL         (png_uint_16p)NULL
  71.521 +#define png_voidp_NULL            (png_voidp)NULL
  71.522 +#define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  71.523 +#else
  71.524 +#define int_p_NULL                NULL
  71.525 +#define png_bytep_NULL            NULL
  71.526 +#define png_bytepp_NULL           NULL
  71.527 +#define png_doublep_NULL          NULL
  71.528 +#define png_error_ptr_NULL        NULL
  71.529 +#define png_flush_ptr_NULL        NULL
  71.530 +#define png_free_ptr_NULL         NULL
  71.531 +#define png_infopp_NULL           NULL
  71.532 +#define png_malloc_ptr_NULL       NULL
  71.533 +#define png_read_status_ptr_NULL  NULL
  71.534 +#define png_rw_ptr_NULL           NULL
  71.535 +#define png_structp_NULL          NULL
  71.536 +#define png_uint_16p_NULL         NULL
  71.537 +#define png_voidp_NULL            NULL
  71.538 +#define png_write_status_ptr_NULL NULL
  71.539 +#endif
  71.540 +
  71.541 +/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  71.542 +#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  71.543 +/* Version information for C files, stored in png.c.  This had better match
  71.544 + * the version above.
  71.545 + */
  71.546 +#ifdef PNG_USE_GLOBAL_ARRAYS
  71.547 +PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  71.548 +  /* need room for 99.99.99beta99z */
  71.549 +#else
  71.550 +#define png_libpng_ver png_get_header_ver(NULL)
  71.551 +#endif
  71.552 +
  71.553 +#ifdef PNG_USE_GLOBAL_ARRAYS
  71.554 +/* This was removed in version 1.0.5c */
  71.555 +/* Structures to facilitate easy interlacing.  See png.c for more details */
  71.556 +PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  71.557 +PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  71.558 +PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  71.559 +PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  71.560 +PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  71.561 +PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  71.562 +/* This isn't currently used.  If you need it, see png.c for more details.
  71.563 +PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  71.564 +*/
  71.565 +#endif
  71.566 +
  71.567 +#endif /* PNG_NO_EXTERN */
  71.568 +
  71.569 +/* Three color definitions.  The order of the red, green, and blue, (and the
  71.570 + * exact size) is not important, although the size of the fields need to
  71.571 + * be png_byte or png_uint_16 (as defined below).
  71.572 + */
  71.573 +typedef struct png_color_struct
  71.574 +{
  71.575 +   png_byte red;
  71.576 +   png_byte green;
  71.577 +   png_byte blue;
  71.578 +} png_color;
  71.579 +typedef png_color FAR * png_colorp;
  71.580 +typedef png_color FAR * FAR * png_colorpp;
  71.581 +
  71.582 +typedef struct png_color_16_struct
  71.583 +{
  71.584 +   png_byte index;    /* used for palette files */
  71.585 +   png_uint_16 red;   /* for use in red green blue files */
  71.586 +   png_uint_16 green;
  71.587 +   png_uint_16 blue;
  71.588 +   png_uint_16 gray;  /* for use in grayscale files */
  71.589 +} png_color_16;
  71.590 +typedef png_color_16 FAR * png_color_16p;
  71.591 +typedef png_color_16 FAR * FAR * png_color_16pp;
  71.592 +
  71.593 +typedef struct png_color_8_struct
  71.594 +{
  71.595 +   png_byte red;   /* for use in red green blue files */
  71.596 +   png_byte green;
  71.597 +   png_byte blue;
  71.598 +   png_byte gray;  /* for use in grayscale files */
  71.599 +   png_byte alpha; /* for alpha channel files */
  71.600 +} png_color_8;
  71.601 +typedef png_color_8 FAR * png_color_8p;
  71.602 +typedef png_color_8 FAR * FAR * png_color_8pp;
  71.603 +
  71.604 +/*
  71.605 + * The following two structures are used for the in-core representation
  71.606 + * of sPLT chunks.
  71.607 + */
  71.608 +typedef struct png_sPLT_entry_struct
  71.609 +{
  71.610 +   png_uint_16 red;
  71.611 +   png_uint_16 green;
  71.612 +   png_uint_16 blue;
  71.613 +   png_uint_16 alpha;
  71.614 +   png_uint_16 frequency;
  71.615 +} png_sPLT_entry;
  71.616 +typedef png_sPLT_entry FAR * png_sPLT_entryp;
  71.617 +typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  71.618 +
  71.619 +/*  When the depth of the sPLT palette is 8 bits, the color and alpha samples
  71.620 + *  occupy the LSB of their respective members, and the MSB of each member
  71.621 + *  is zero-filled.  The frequency member always occupies the full 16 bits.
  71.622 + */
  71.623 +
  71.624 +typedef struct png_sPLT_struct
  71.625 +{
  71.626 +   png_charp name;           /* palette name */
  71.627 +   png_byte depth;           /* depth of palette samples */
  71.628 +   png_sPLT_entryp entries;  /* palette entries */
  71.629 +   png_int_32 nentries;      /* number of palette entries */
  71.630 +} png_sPLT_t;
  71.631 +typedef png_sPLT_t FAR * png_sPLT_tp;
  71.632 +typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  71.633 +
  71.634 +#ifdef PNG_TEXT_SUPPORTED
  71.635 +/* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  71.636 + * and whether that contents is compressed or not.  The "key" field
  71.637 + * points to a regular zero-terminated C string.  The "text", "lang", and
  71.638 + * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  71.639 + * However, the * structure returned by png_get_text() will always contain
  71.640 + * regular zero-terminated C strings (possibly empty), never NULL pointers,
  71.641 + * so they can be safely used in printf() and other string-handling functions.
  71.642 + */
  71.643 +typedef struct png_text_struct
  71.644 +{
  71.645 +   int  compression;       /* compression value:
  71.646 +                             -1: tEXt, none
  71.647 +                              0: zTXt, deflate
  71.648 +                              1: iTXt, none
  71.649 +                              2: iTXt, deflate  */
  71.650 +   png_charp key;          /* keyword, 1-79 character description of "text" */
  71.651 +   png_charp text;         /* comment, may be an empty string (ie "")
  71.652 +                              or a NULL pointer */
  71.653 +   png_size_t text_length; /* length of the text string */
  71.654 +#ifdef PNG_iTXt_SUPPORTED
  71.655 +   png_size_t itxt_length; /* length of the itxt string */
  71.656 +   png_charp lang;         /* language code, 0-79 characters
  71.657 +                              or a NULL pointer */
  71.658 +   png_charp lang_key;     /* keyword translated UTF-8 string, 0 or more
  71.659 +                              chars or a NULL pointer */
  71.660 +#endif
  71.661 +} png_text;
  71.662 +typedef png_text FAR * png_textp;
  71.663 +typedef png_text FAR * FAR * png_textpp;
  71.664 +#endif
  71.665 +
  71.666 +/* Supported compression types for text in PNG files (tEXt, and zTXt).
  71.667 + * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  71.668 +#define PNG_TEXT_COMPRESSION_NONE_WR -3
  71.669 +#define PNG_TEXT_COMPRESSION_zTXt_WR -2
  71.670 +#define PNG_TEXT_COMPRESSION_NONE    -1
  71.671 +#define PNG_TEXT_COMPRESSION_zTXt     0
  71.672 +#define PNG_ITXT_COMPRESSION_NONE     1
  71.673 +#define PNG_ITXT_COMPRESSION_zTXt     2
  71.674 +#define PNG_TEXT_COMPRESSION_LAST     3  /* Not a valid value */
  71.675 +
  71.676 +/* png_time is a way to hold the time in an machine independent way.
  71.677 + * Two conversions are provided, both from time_t and struct tm.  There
  71.678 + * is no portable way to convert to either of these structures, as far
  71.679 + * as I know.  If you know of a portable way, send it to me.  As a side
  71.680 + * note - PNG has always been Year 2000 compliant!
  71.681 + */
  71.682 +typedef struct png_time_struct
  71.683 +{
  71.684 +   png_uint_16 year; /* full year, as in, 1995 */
  71.685 +   png_byte month;   /* month of year, 1 - 12 */
  71.686 +   png_byte day;     /* day of month, 1 - 31 */
  71.687 +   png_byte hour;    /* hour of day, 0 - 23 */
  71.688 +   png_byte minute;  /* minute of hour, 0 - 59 */
  71.689 +   png_byte second;  /* second of minute, 0 - 60 (for leap seconds) */
  71.690 +} png_time;
  71.691 +typedef png_time FAR * png_timep;
  71.692 +typedef png_time FAR * FAR * png_timepp;
  71.693 +
  71.694 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  71.695 +/* png_unknown_chunk is a structure to hold queued chunks for which there is
  71.696 + * no specific support.  The idea is that we can use this to queue
  71.697 + * up private chunks for output even though the library doesn't actually
  71.698 + * know about their semantics.
  71.699 + */
  71.700 +#define PNG_CHUNK_NAME_LENGTH 5
  71.701 +typedef struct png_unknown_chunk_t
  71.702 +{
  71.703 +    png_byte name[PNG_CHUNK_NAME_LENGTH];
  71.704 +    png_byte *data;
  71.705 +    png_size_t size;
  71.706 +
  71.707 +    /* libpng-using applications should NOT directly modify this byte. */
  71.708 +    png_byte location; /* mode of operation at read time */
  71.709 +}
  71.710 +png_unknown_chunk;
  71.711 +typedef png_unknown_chunk FAR * png_unknown_chunkp;
  71.712 +typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  71.713 +#endif
  71.714 +
  71.715 +/* png_info is a structure that holds the information in a PNG file so
  71.716 + * that the application can find out the characteristics of the image.
  71.717 + * If you are reading the file, this structure will tell you what is
  71.718 + * in the PNG file.  If you are writing the file, fill in the information
  71.719 + * you want to put into the PNG file, then call png_write_info().
  71.720 + * The names chosen should be very close to the PNG specification, so
  71.721 + * consult that document for information about the meaning of each field.
  71.722 + *
  71.723 + * With libpng < 0.95, it was only possible to directly set and read the
  71.724 + * the values in the png_info_struct, which meant that the contents and
  71.725 + * order of the values had to remain fixed.  With libpng 0.95 and later,
  71.726 + * however, there are now functions that abstract the contents of
  71.727 + * png_info_struct from the application, so this makes it easier to use
  71.728 + * libpng with dynamic libraries, and even makes it possible to use
  71.729 + * libraries that don't have all of the libpng ancillary chunk-handing
  71.730 + * functionality.
  71.731 + *
  71.732 + * In any case, the order of the parameters in png_info_struct should NOT
  71.733 + * be changed for as long as possible to keep compatibility with applications
  71.734 + * that use the old direct-access method with png_info_struct.
  71.735 + *
  71.736 + * The following members may have allocated storage attached that should be
  71.737 + * cleaned up before the structure is discarded: palette, trans, text,
  71.738 + * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  71.739 + * splt_palettes, scal_unit, row_pointers, and unknowns.   By default, these
  71.740 + * are automatically freed when the info structure is deallocated, if they were
  71.741 + * allocated internally by libpng.  This behavior can be changed by means
  71.742 + * of the png_data_freer() function.
  71.743 + *
  71.744 + * More allocation details: all the chunk-reading functions that
  71.745 + * change these members go through the corresponding png_set_*
  71.746 + * functions.  A function to clear these members is available: see
  71.747 + * png_free_data().  The png_set_* functions do not depend on being
  71.748 + * able to point info structure members to any of the storage they are
  71.749 + * passed (they make their own copies), EXCEPT that the png_set_text
  71.750 + * functions use the same storage passed to them in the text_ptr or
  71.751 + * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  71.752 + * functions do not make their own copies.
  71.753 + */
  71.754 +typedef struct png_info_struct
  71.755 +{
  71.756 +   /* the following are necessary for every PNG file */
  71.757 +   png_uint_32 width;       /* width of image in pixels (from IHDR) */
  71.758 +   png_uint_32 height;      /* height of image in pixels (from IHDR) */
  71.759 +   png_uint_32 valid;       /* valid chunk data (see PNG_INFO_ below) */
  71.760 +   png_uint_32 rowbytes;    /* bytes needed to hold an untransformed row */
  71.761 +   png_colorp palette;      /* array of color values (valid & PNG_INFO_PLTE) */
  71.762 +   png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  71.763 +   png_uint_16 num_trans;   /* number of transparent palette color (tRNS) */
  71.764 +   png_byte bit_depth;      /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  71.765 +   png_byte color_type;     /* see PNG_COLOR_TYPE_ below (from IHDR) */
  71.766 +   /* The following three should have been named *_method not *_type */
  71.767 +   png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  71.768 +   png_byte filter_type;    /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  71.769 +   png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  71.770 +
  71.771 +   /* The following is informational only on read, and not used on writes. */
  71.772 +   png_byte channels;       /* number of data channels per pixel (1, 2, 3, 4) */
  71.773 +   png_byte pixel_depth;    /* number of bits per pixel */
  71.774 +   png_byte spare_byte;     /* to align the data, and for future use */
  71.775 +   png_byte signature[8];   /* magic bytes read by libpng from start of file */
  71.776 +
  71.777 +   /* The rest of the data is optional.  If you are reading, check the
  71.778 +    * valid field to see if the information in these are valid.  If you
  71.779 +    * are writing, set the valid field to those chunks you want written,
  71.780 +    * and initialize the appropriate fields below.
  71.781 +    */
  71.782 +
  71.783 +#if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  71.784 +   /* The gAMA chunk describes the gamma characteristics of the system
  71.785 +    * on which the image was created, normally in the range [1.0, 2.5].
  71.786 +    * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  71.787 +    */
  71.788 +   float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  71.789 +#endif
  71.790 +
  71.791 +#if defined(PNG_sRGB_SUPPORTED)
  71.792 +    /* GR-P, 0.96a */
  71.793 +    /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  71.794 +   png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  71.795 +#endif
  71.796 +
  71.797 +#if defined(PNG_TEXT_SUPPORTED)
  71.798 +   /* The tEXt, and zTXt chunks contain human-readable textual data in
  71.799 +    * uncompressed, compressed, and optionally compressed forms, respectively.
  71.800 +    * The data in "text" is an array of pointers to uncompressed,
  71.801 +    * null-terminated C strings. Each chunk has a keyword that describes the
  71.802 +    * textual data contained in that chunk.  Keywords are not required to be
  71.803 +    * unique, and the text string may be empty.  Any number of text chunks may
  71.804 +    * be in an image.
  71.805 +    */
  71.806 +   int num_text; /* number of comments read/to write */
  71.807 +   int max_text; /* current size of text array */
  71.808 +   png_textp text; /* array of comments read/to write */
  71.809 +#endif /* PNG_TEXT_SUPPORTED */
  71.810 +
  71.811 +#if defined(PNG_tIME_SUPPORTED)
  71.812 +   /* The tIME chunk holds the last time the displayed image data was
  71.813 +    * modified.  See the png_time struct for the contents of this struct.
  71.814 +    */
  71.815 +   png_time mod_time;
  71.816 +#endif
  71.817 +
  71.818 +#if defined(PNG_sBIT_SUPPORTED)
  71.819 +   /* The sBIT chunk specifies the number of significant high-order bits
  71.820 +    * in the pixel data.  Values are in the range [1, bit_depth], and are
  71.821 +    * only specified for the channels in the pixel data.  The contents of
  71.822 +    * the low-order bits is not specified.  Data is valid if
  71.823 +    * (valid & PNG_INFO_sBIT) is non-zero.
  71.824 +    */
  71.825 +   png_color_8 sig_bit; /* significant bits in color channels */
  71.826 +#endif
  71.827 +
  71.828 +#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  71.829 +defined(PNG_READ_BACKGROUND_SUPPORTED)
  71.830 +   /* The tRNS chunk supplies transparency data for paletted images and
  71.831 +    * other image types that don't need a full alpha channel.  There are
  71.832 +    * "num_trans" transparency values for a paletted image, stored in the
  71.833 +    * same order as the palette colors, starting from index 0.  Values
  71.834 +    * for the data are in the range [0, 255], ranging from fully transparent
  71.835 +    * to fully opaque, respectively.  For non-paletted images, there is a
  71.836 +    * single color specified that should be treated as fully transparent.
  71.837 +    * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  71.838 +    */
  71.839 +   png_bytep trans; /* transparent values for paletted image */
  71.840 +   png_color_16 trans_values; /* transparent color for non-palette image */
  71.841 +#endif
  71.842 +
  71.843 +#if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  71.844 +   /* The bKGD chunk gives the suggested image background color if the
  71.845 +    * display program does not have its own background color and the image
  71.846 +    * is needs to composited onto a background before display.  The colors
  71.847 +    * in "background" are normally in the same color space/depth as the
  71.848 +    * pixel data.  Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  71.849 +    */
  71.850 +   png_color_16 background;
  71.851 +#endif
  71.852 +
  71.853 +#if defined(PNG_oFFs_SUPPORTED)
  71.854 +   /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  71.855 +    * and downwards from the top-left corner of the display, page, or other
  71.856 +    * application-specific co-ordinate space.  See the PNG_OFFSET_ defines
  71.857 +    * below for the unit types.  Valid if (valid & PNG_INFO_oFFs) non-zero.
  71.858 +    */
  71.859 +   png_int_32 x_offset; /* x offset on page */
  71.860 +   png_int_32 y_offset; /* y offset on page */
  71.861 +   png_byte offset_unit_type; /* offset units type */
  71.862 +#endif
  71.863 +
  71.864 +#if defined(PNG_pHYs_SUPPORTED)
  71.865 +   /* The pHYs chunk gives the physical pixel density of the image for
  71.866 +    * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  71.867 +    * defines below).  Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  71.868 +    */
  71.869 +   png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  71.870 +   png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  71.871 +   png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  71.872 +#endif
  71.873 +
  71.874 +#if defined(PNG_hIST_SUPPORTED)
  71.875 +   /* The hIST chunk contains the relative frequency or importance of the
  71.876 +    * various palette entries, so that a viewer can intelligently select a
  71.877 +    * reduced-color palette, if required.  Data is an array of "num_palette"
  71.878 +    * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  71.879 +    * is non-zero.
  71.880 +    */
  71.881 +   png_uint_16p hist;
  71.882 +#endif
  71.883 +
  71.884 +#ifdef PNG_cHRM_SUPPORTED
  71.885 +   /* The cHRM chunk describes the CIE color characteristics of the monitor
  71.886 +    * on which the PNG was created.  This data allows the viewer to do gamut
  71.887 +    * mapping of the input image to ensure that the viewer sees the same
  71.888 +    * colors in the image as the creator.  Values are in the range
  71.889 +    * [0.0, 0.8].  Data valid if (valid & PNG_INFO_cHRM) non-zero.
  71.890 +    */
  71.891 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  71.892 +   float x_white;
  71.893 +   float y_white;
  71.894 +   float x_red;
  71.895 +   float y_red;
  71.896 +   float x_green;
  71.897 +   float y_green;
  71.898 +   float x_blue;
  71.899 +   float y_blue;
  71.900 +#endif
  71.901 +#endif
  71.902 +
  71.903 +#if defined(PNG_pCAL_SUPPORTED)
  71.904 +   /* The pCAL chunk describes a transformation between the stored pixel
  71.905 +    * values and original physical data values used to create the image.
  71.906 +    * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  71.907 +    * range given by [pcal_X0, pcal_X1], and are further transformed by a
  71.908 +    * (possibly non-linear) transformation function given by "pcal_type"
  71.909 +    * and "pcal_params" into "pcal_units".  Please see the PNG_EQUATION_
  71.910 +    * defines below, and the PNG-Group's PNG extensions document for a
  71.911 +    * complete description of the transformations and how they should be
  71.912 +    * implemented, and for a description of the ASCII parameter strings.
  71.913 +    * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  71.914 +    */
  71.915 +   png_charp pcal_purpose;  /* pCAL chunk description string */
  71.916 +   png_int_32 pcal_X0;      /* minimum value */
  71.917 +   png_int_32 pcal_X1;      /* maximum value */
  71.918 +   png_charp pcal_units;    /* Latin-1 string giving physical units */
  71.919 +   png_charpp pcal_params;  /* ASCII strings containing parameter values */
  71.920 +   png_byte pcal_type;      /* equation type (see PNG_EQUATION_ below) */
  71.921 +   png_byte pcal_nparams;   /* number of parameters given in pcal_params */
  71.922 +#endif
  71.923 +
  71.924 +/* New members added in libpng-1.0.6 */
  71.925 +#ifdef PNG_FREE_ME_SUPPORTED
  71.926 +   png_uint_32 free_me;     /* flags items libpng is responsible for freeing */
  71.927 +#endif
  71.928 +
  71.929 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  71.930 +   /* storage for unknown chunks that the library doesn't recognize. */
  71.931 +   png_unknown_chunkp unknown_chunks;
  71.932 +   png_size_t unknown_chunks_num;
  71.933 +#endif
  71.934 +
  71.935 +#if defined(PNG_iCCP_SUPPORTED)
  71.936 +   /* iCCP chunk data. */
  71.937 +   png_charp iccp_name;     /* profile name */
  71.938 +   png_charp iccp_profile;  /* International Color Consortium profile data */
  71.939 +                            /* Note to maintainer: should be png_bytep */
  71.940 +   png_uint_32 iccp_proflen;  /* ICC profile data length */
  71.941 +   png_byte iccp_compression; /* Always zero */
  71.942 +#endif
  71.943 +
  71.944 +#if defined(PNG_sPLT_SUPPORTED)
  71.945 +   /* data on sPLT chunks (there may be more than one). */
  71.946 +   png_sPLT_tp splt_palettes;
  71.947 +   png_uint_32 splt_palettes_num;
  71.948 +#endif
  71.949 +
  71.950 +#if defined(PNG_sCAL_SUPPORTED)
  71.951 +   /* The sCAL chunk describes the actual physical dimensions of the
  71.952 +    * subject matter of the graphic.  The chunk contains a unit specification
  71.953 +    * a byte value, and two ASCII strings representing floating-point
  71.954 +    * values.  The values are width and height corresponsing to one pixel
  71.955 +    * in the image.  This external representation is converted to double
  71.956 +    * here.  Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  71.957 +    */
  71.958 +   png_byte scal_unit;         /* unit of physical scale */
  71.959 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  71.960 +   double scal_pixel_width;    /* width of one pixel */
  71.961 +   double scal_pixel_height;   /* height of one pixel */
  71.962 +#endif
  71.963 +#ifdef PNG_FIXED_POINT_SUPPORTED
  71.964 +   png_charp scal_s_width;     /* string containing height */
  71.965 +   png_charp scal_s_height;    /* string containing width */
  71.966 +#endif
  71.967 +#endif
  71.968 +
  71.969 +#if defined(PNG_INFO_IMAGE_SUPPORTED)
  71.970 +   /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  71.971 +   /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  71.972 +   png_bytepp row_pointers;        /* the image bits */
  71.973 +#endif
  71.974 +
  71.975 +#if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  71.976 +   png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  71.977 +#endif
  71.978 +
  71.979 +#if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  71.980 +   png_fixed_point int_x_white;
  71.981 +   png_fixed_point int_y_white;
  71.982 +   png_fixed_point int_x_red;
  71.983 +   png_fixed_point int_y_red;
  71.984 +   png_fixed_point int_x_green;
  71.985 +   png_fixed_point int_y_green;
  71.986 +   png_fixed_point int_x_blue;
  71.987 +   png_fixed_point int_y_blue;
  71.988 +#endif
  71.989 +
  71.990 +} png_info;
  71.991 +
  71.992 +typedef png_info FAR * png_infop;
  71.993 +typedef png_info FAR * FAR * png_infopp;
  71.994 +
  71.995 +/* Maximum positive integer used in PNG is (2^31)-1 */
  71.996 +#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  71.997 +#define PNG_UINT_32_MAX ((png_uint_32)(-1))
  71.998 +#define PNG_SIZE_MAX ((png_size_t)(-1))
  71.999 +#if defined(PNG_1_0_X) || defined (PNG_1_2_X)
 71.1000 +/* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
 71.1001 +#define PNG_MAX_UINT PNG_UINT_31_MAX
 71.1002 +#endif
 71.1003 +
 71.1004 +/* These describe the color_type field in png_info. */
 71.1005 +/* color type masks */
 71.1006 +#define PNG_COLOR_MASK_PALETTE    1
 71.1007 +#define PNG_COLOR_MASK_COLOR      2
 71.1008 +#define PNG_COLOR_MASK_ALPHA      4
 71.1009 +
 71.1010 +/* color types.  Note that not all combinations are legal */
 71.1011 +#define PNG_COLOR_TYPE_GRAY 0
 71.1012 +#define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
 71.1013 +#define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
 71.1014 +#define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
 71.1015 +#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
 71.1016 +/* aliases */
 71.1017 +#define PNG_COLOR_TYPE_RGBA  PNG_COLOR_TYPE_RGB_ALPHA
 71.1018 +#define PNG_COLOR_TYPE_GA  PNG_COLOR_TYPE_GRAY_ALPHA
 71.1019 +
 71.1020 +/* This is for compression type. PNG 1.0-1.2 only define the single type. */
 71.1021 +#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
 71.1022 +#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
 71.1023 +
 71.1024 +/* This is for filter type. PNG 1.0-1.2 only define the single type. */
 71.1025 +#define PNG_FILTER_TYPE_BASE      0 /* Single row per-byte filtering */
 71.1026 +#define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
 71.1027 +#define PNG_FILTER_TYPE_DEFAULT   PNG_FILTER_TYPE_BASE
 71.1028 +
 71.1029 +/* These are for the interlacing type.  These values should NOT be changed. */
 71.1030 +#define PNG_INTERLACE_NONE        0 /* Non-interlaced image */
 71.1031 +#define PNG_INTERLACE_ADAM7       1 /* Adam7 interlacing */
 71.1032 +#define PNG_INTERLACE_LAST        2 /* Not a valid value */
 71.1033 +
 71.1034 +/* These are for the oFFs chunk.  These values should NOT be changed. */
 71.1035 +#define PNG_OFFSET_PIXEL          0 /* Offset in pixels */
 71.1036 +#define PNG_OFFSET_MICROMETER     1 /* Offset in micrometers (1/10^6 meter) */
 71.1037 +#define PNG_OFFSET_LAST           2 /* Not a valid value */
 71.1038 +
 71.1039 +/* These are for the pCAL chunk.  These values should NOT be changed. */
 71.1040 +#define PNG_EQUATION_LINEAR       0 /* Linear transformation */
 71.1041 +#define PNG_EQUATION_BASE_E       1 /* Exponential base e transform */
 71.1042 +#define PNG_EQUATION_ARBITRARY    2 /* Arbitrary base exponential transform */
 71.1043 +#define PNG_EQUATION_HYPERBOLIC   3 /* Hyperbolic sine transformation */
 71.1044 +#define PNG_EQUATION_LAST         4 /* Not a valid value */
 71.1045 +
 71.1046 +/* These are for the sCAL chunk.  These values should NOT be changed. */
 71.1047 +#define PNG_SCALE_UNKNOWN         0 /* unknown unit (image scale) */
 71.1048 +#define PNG_SCALE_METER           1 /* meters per pixel */
 71.1049 +#define PNG_SCALE_RADIAN          2 /* radians per pixel */
 71.1050 +#define PNG_SCALE_LAST            3 /* Not a valid value */
 71.1051 +
 71.1052 +/* These are for the pHYs chunk.  These values should NOT be changed. */
 71.1053 +#define PNG_RESOLUTION_UNKNOWN    0 /* pixels/unknown unit (aspect ratio) */
 71.1054 +#define PNG_RESOLUTION_METER      1 /* pixels/meter */
 71.1055 +#define PNG_RESOLUTION_LAST       2 /* Not a valid value */
 71.1056 +
 71.1057 +/* These are for the sRGB chunk.  These values should NOT be changed. */
 71.1058 +#define PNG_sRGB_INTENT_PERCEPTUAL 0
 71.1059 +#define PNG_sRGB_INTENT_RELATIVE   1
 71.1060 +#define PNG_sRGB_INTENT_SATURATION 2
 71.1061 +#define PNG_sRGB_INTENT_ABSOLUTE   3
 71.1062 +#define PNG_sRGB_INTENT_LAST       4 /* Not a valid value */
 71.1063 +
 71.1064 +/* This is for text chunks */
 71.1065 +#define PNG_KEYWORD_MAX_LENGTH     79
 71.1066 +
 71.1067 +/* Maximum number of entries in PLTE/sPLT/tRNS arrays */
 71.1068 +#define PNG_MAX_PALETTE_LENGTH    256
 71.1069 +
 71.1070 +/* These determine if an ancillary chunk's data has been successfully read
 71.1071 + * from the PNG header, or if the application has filled in the corresponding
 71.1072 + * data in the info_struct to be written into the output file.  The values
 71.1073 + * of the PNG_INFO_<chunk> defines should NOT be changed.
 71.1074 + */
 71.1075 +#define PNG_INFO_gAMA 0x0001
 71.1076 +#define PNG_INFO_sBIT 0x0002
 71.1077 +#define PNG_INFO_cHRM 0x0004
 71.1078 +#define PNG_INFO_PLTE 0x0008
 71.1079 +#define PNG_INFO_tRNS 0x0010
 71.1080 +#define PNG_INFO_bKGD 0x0020
 71.1081 +#define PNG_INFO_hIST 0x0040
 71.1082 +#define PNG_INFO_pHYs 0x0080
 71.1083 +#define PNG_INFO_oFFs 0x0100
 71.1084 +#define PNG_INFO_tIME 0x0200
 71.1085 +#define PNG_INFO_pCAL 0x0400
 71.1086 +#define PNG_INFO_sRGB 0x0800   /* GR-P, 0.96a */
 71.1087 +#define PNG_INFO_iCCP 0x1000   /* ESR, 1.0.6 */
 71.1088 +#define PNG_INFO_sPLT 0x2000   /* ESR, 1.0.6 */
 71.1089 +#define PNG_INFO_sCAL 0x4000   /* ESR, 1.0.6 */
 71.1090 +#define PNG_INFO_IDAT 0x8000L  /* ESR, 1.0.6 */
 71.1091 +
 71.1092 +/* This is used for the transformation routines, as some of them
 71.1093 + * change these values for the row.  It also should enable using
 71.1094 + * the routines for other purposes.
 71.1095 + */
 71.1096 +typedef struct png_row_info_struct
 71.1097 +{
 71.1098 +   png_uint_32 width; /* width of row */
 71.1099 +   png_uint_32 rowbytes; /* number of bytes in row */
 71.1100 +   png_byte color_type; /* color type of row */
 71.1101 +   png_byte bit_depth; /* bit depth of row */
 71.1102 +   png_byte channels; /* number of channels (1, 2, 3, or 4) */
 71.1103 +   png_byte pixel_depth; /* bits per pixel (depth * channels) */
 71.1104 +} png_row_info;
 71.1105 +
 71.1106 +typedef png_row_info FAR * png_row_infop;
 71.1107 +typedef png_row_info FAR * FAR * png_row_infopp;
 71.1108 +
 71.1109 +/* These are the function types for the I/O functions and for the functions
 71.1110 + * that allow the user to override the default I/O functions with his or her
 71.1111 + * own.  The png_error_ptr type should match that of user-supplied warning
 71.1112 + * and error functions, while the png_rw_ptr type should match that of the
 71.1113 + * user read/write data functions.
 71.1114 + */
 71.1115 +typedef struct png_struct_def png_struct;
 71.1116 +typedef png_struct FAR * png_structp;
 71.1117 +
 71.1118 +typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
 71.1119 +typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
 71.1120 +typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
 71.1121 +typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
 71.1122 +   int));
 71.1123 +typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
 71.1124 +   int));
 71.1125 +
 71.1126 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 71.1127 +typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
 71.1128 +typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
 71.1129 +typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
 71.1130 +   png_uint_32, int));
 71.1131 +#endif
 71.1132 +
 71.1133 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
 71.1134 +    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
 71.1135 +    defined(PNG_LEGACY_SUPPORTED)
 71.1136 +typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
 71.1137 +    png_row_infop, png_bytep));
 71.1138 +#endif
 71.1139 +
 71.1140 +#if defined(PNG_USER_CHUNKS_SUPPORTED)
 71.1141 +typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
 71.1142 +#endif
 71.1143 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
 71.1144 +typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
 71.1145 +#endif
 71.1146 +
 71.1147 +/* Transform masks for the high-level interface */
 71.1148 +#define PNG_TRANSFORM_IDENTITY       0x0000    /* read and write */
 71.1149 +#define PNG_TRANSFORM_STRIP_16       0x0001    /* read only */
 71.1150 +#define PNG_TRANSFORM_STRIP_ALPHA    0x0002    /* read only */
 71.1151 +#define PNG_TRANSFORM_PACKING        0x0004    /* read and write */
 71.1152 +#define PNG_TRANSFORM_PACKSWAP       0x0008    /* read and write */
 71.1153 +#define PNG_TRANSFORM_EXPAND         0x0010    /* read only */
 71.1154 +#define PNG_TRANSFORM_INVERT_MONO    0x0020    /* read and write */
 71.1155 +#define PNG_TRANSFORM_SHIFT          0x0040    /* read and write */
 71.1156 +#define PNG_TRANSFORM_BGR            0x0080    /* read and write */
 71.1157 +#define PNG_TRANSFORM_SWAP_ALPHA     0x0100    /* read and write */
 71.1158 +#define PNG_TRANSFORM_SWAP_ENDIAN    0x0200    /* read and write */
 71.1159 +#define PNG_TRANSFORM_INVERT_ALPHA   0x0400    /* read and write */
 71.1160 +#define PNG_TRANSFORM_STRIP_FILLER   0x0800    /* WRITE only */
 71.1161 +
 71.1162 +/* Flags for MNG supported features */
 71.1163 +#define PNG_FLAG_MNG_EMPTY_PLTE     0x01
 71.1164 +#define PNG_FLAG_MNG_FILTER_64      0x04
 71.1165 +#define PNG_ALL_MNG_FEATURES        0x05
 71.1166 +
 71.1167 +typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
 71.1168 +typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
 71.1169 +
 71.1170 +/* The structure that holds the information to read and write PNG files.
 71.1171 + * The only people who need to care about what is inside of this are the
 71.1172 + * people who will be modifying the library for their own special needs.
 71.1173 + * It should NOT be accessed directly by an application, except to store
 71.1174 + * the jmp_buf.
 71.1175 + */
 71.1176 +
 71.1177 +struct png_struct_def
 71.1178 +{
 71.1179 +#ifdef PNG_SETJMP_SUPPORTED
 71.1180 +   jmp_buf jmpbuf;            /* used in png_error */
 71.1181 +#endif
 71.1182 +   png_error_ptr error_fn;    /* function for printing errors and aborting */
 71.1183 +   png_error_ptr warning_fn;  /* function for printing warnings */
 71.1184 +   png_voidp error_ptr;       /* user supplied struct for error functions */
 71.1185 +   png_rw_ptr write_data_fn;  /* function for writing output data */
 71.1186 +   png_rw_ptr read_data_fn;   /* function for reading input data */
 71.1187 +   png_voidp io_ptr;          /* ptr to application struct for I/O functions */
 71.1188 +
 71.1189 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
 71.1190 +   png_user_transform_ptr read_user_transform_fn; /* user read transform */
 71.1191 +#endif
 71.1192 +
 71.1193 +#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
 71.1194 +   png_user_transform_ptr write_user_transform_fn; /* user write transform */
 71.1195 +#endif
 71.1196 +
 71.1197 +/* These were added in libpng-1.0.2 */
 71.1198 +#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
 71.1199 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
 71.1200 +    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
 71.1201 +   png_voidp user_transform_ptr; /* user supplied struct for user transform */
 71.1202 +   png_byte user_transform_depth;    /* bit depth of user transformed pixels */
 71.1203 +   png_byte user_transform_channels; /* channels in user transformed pixels */
 71.1204 +#endif
 71.1205 +#endif
 71.1206 +
 71.1207 +   png_uint_32 mode;          /* tells us where we are in the PNG file */
 71.1208 +   png_uint_32 flags;         /* flags indicating various things to libpng */
 71.1209 +   png_uint_32 transformations; /* which transformations to perform */
 71.1210 +
 71.1211 +   z_stream zstream;          /* pointer to decompression structure (below) */
 71.1212 +   png_bytep zbuf;            /* buffer for zlib */
 71.1213 +   png_size_t zbuf_size;      /* size of zbuf */
 71.1214 +   int zlib_level;            /* holds zlib compression level */
 71.1215 +   int zlib_method;           /* holds zlib compression method */
 71.1216 +   int zlib_window_bits;      /* holds zlib compression window bits */
 71.1217 +   int zlib_mem_level;        /* holds zlib compression memory level */
 71.1218 +   int zlib_strategy;         /* holds zlib compression strategy */
 71.1219 +
 71.1220 +   png_uint_32 width;         /* width of image in pixels */
 71.1221 +   png_uint_32 height;        /* height of image in pixels */
 71.1222 +   png_uint_32 num_rows;      /* number of rows in current pass */
 71.1223 +   png_uint_32 usr_width;     /* width of row at start of write */
 71.1224 +   png_uint_32 rowbytes;      /* size of row in bytes */
 71.1225 +   png_uint_32 irowbytes;     /* size of current interlaced row in bytes */
 71.1226 +   png_uint_32 iwidth;        /* width of current interlaced row in pixels */
 71.1227 +   png_uint_32 row_number;    /* current row in interlace pass */
 71.1228 +   png_bytep prev_row;        /* buffer to save previous (unfiltered) row */
 71.1229 +   png_bytep row_buf;         /* buffer to save current (unfiltered) row */
 71.1230 +#ifndef PNG_NO_WRITE_FILTER
 71.1231 +   png_bytep sub_row;         /* buffer to save "sub" row when filtering */
 71.1232 +   png_bytep up_row;          /* buffer to save "up" row when filtering */
 71.1233 +   png_bytep avg_row;         /* buffer to save "avg" row when filtering */
 71.1234 +   png_bytep paeth_row;       /* buffer to save "Paeth" row when filtering */
 71.1235 +#endif
 71.1236 +   png_row_info row_info;     /* used for transformation routines */
 71.1237 +
 71.1238 +   png_uint_32 idat_size;     /* current IDAT size for read */
 71.1239 +   png_uint_32 crc;           /* current chunk CRC value */
 71.1240 +   png_colorp palette;        /* palette from the input file */
 71.1241 +   png_uint_16 num_palette;   /* number of color entries in palette */
 71.1242 +   png_uint_16 num_trans;     /* number of transparency values */
 71.1243 +   png_byte chunk_name[5];    /* null-terminated name of current chunk */
 71.1244 +   png_byte compression;      /* file compression type (always 0) */
 71.1245 +   png_byte filter;           /* file filter type (always 0) */
 71.1246 +   png_byte interlaced;       /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
 71.1247 +   png_byte pass;             /* current interlace pass (0 - 6) */
 71.1248 +   png_byte do_filter;        /* row filter flags (see PNG_FILTER_ below ) */
 71.1249 +   png_byte color_type;       /* color type of file */
 71.1250 +   png_byte bit_depth;        /* bit depth of file */
 71.1251 +   png_byte usr_bit_depth;    /* bit depth of users row */
 71.1252 +   png_byte pixel_depth;      /* number of bits per pixel */
 71.1253 +   png_byte channels;         /* number of channels in file */
 71.1254 +   png_byte usr_channels;     /* channels at start of write */
 71.1255 +   png_byte sig_bytes;        /* magic bytes read/written from start of file */
 71.1256 +
 71.1257 +#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
 71.1258 +#ifdef PNG_LEGACY_SUPPORTED
 71.1259 +   png_byte filler;           /* filler byte for pixel expansion */
 71.1260 +#else
 71.1261 +   png_uint_16 filler;           /* filler bytes for pixel expansion */
 71.1262 +#endif
 71.1263 +#endif
 71.1264 +
 71.1265 +#if defined(PNG_bKGD_SUPPORTED)
 71.1266 +   png_byte background_gamma_type;
 71.1267 +#  ifdef PNG_FLOATING_POINT_SUPPORTED
 71.1268 +   float background_gamma;
 71.1269 +#  endif
 71.1270 +   png_color_16 background;   /* background color in screen gamma space */
 71.1271 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 71.1272 +   png_color_16 background_1; /* background normalized to gamma 1.0 */
 71.1273 +#endif
 71.1274 +#endif /* PNG_bKGD_SUPPORTED */
 71.1275 +
 71.1276 +#if defined(PNG_WRITE_FLUSH_SUPPORTED)
 71.1277 +   png_flush_ptr output_flush_fn;/* Function for flushing output */
 71.1278 +   png_uint_32 flush_dist;    /* how many rows apart to flush, 0 - no flush */
 71.1279 +   png_uint_32 flush_rows;    /* number of rows written since last flush */
 71.1280 +#endif
 71.1281 +
 71.1282 +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
 71.1283 +   int gamma_shift;      /* number of "insignificant" bits 16-bit gamma */
 71.1284 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.1285 +   float gamma;          /* file gamma value */
 71.1286 +   float screen_gamma;   /* screen gamma value (display_exponent) */
 71.1287 +#endif
 71.1288 +#endif
 71.1289 +
 71.1290 +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
 71.1291 +   png_bytep gamma_table;     /* gamma table for 8-bit depth files */
 71.1292 +   png_bytep gamma_from_1;    /* converts from 1.0 to screen */
 71.1293 +   png_bytep gamma_to_1;      /* converts from file to 1.0 */
 71.1294 +   png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
 71.1295 +   png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
 71.1296 +   png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
 71.1297 +#endif
 71.1298 +
 71.1299 +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
 71.1300 +   png_color_8 sig_bit;       /* significant bits in each available channel */
 71.1301 +#endif
 71.1302 +
 71.1303 +#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
 71.1304 +   png_color_8 shift;         /* shift for significant bit tranformation */
 71.1305 +#endif
 71.1306 +
 71.1307 +#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
 71.1308 + || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
 71.1309 +   png_bytep trans;           /* transparency values for paletted files */
 71.1310 +   png_color_16 trans_values; /* transparency values for non-paletted files */
 71.1311 +#endif
 71.1312 +
 71.1313 +   png_read_status_ptr read_row_fn;   /* called after each row is decoded */
 71.1314 +   png_write_status_ptr write_row_fn; /* called after each row is encoded */
 71.1315 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 71.1316 +   png_progressive_info_ptr info_fn; /* called after header data fully read */
 71.1317 +   png_progressive_row_ptr row_fn;   /* called after each prog. row is decoded */
 71.1318 +   png_progressive_end_ptr end_fn;   /* called after image is complete */
 71.1319 +   png_bytep save_buffer_ptr;        /* current location in save_buffer */
 71.1320 +   png_bytep save_buffer;            /* buffer for previously read data */
 71.1321 +   png_bytep current_buffer_ptr;     /* current location in current_buffer */
 71.1322 +   png_bytep current_buffer;         /* buffer for recently used data */
 71.1323 +   png_uint_32 push_length;          /* size of current input chunk */
 71.1324 +   png_uint_32 skip_length;          /* bytes to skip in input data */
 71.1325 +   png_size_t save_buffer_size;      /* amount of data now in save_buffer */
 71.1326 +   png_size_t save_buffer_max;       /* total size of save_buffer */
 71.1327 +   png_size_t buffer_size;           /* total amount of available input data */
 71.1328 +   png_size_t current_buffer_size;   /* amount of data now in current_buffer */
 71.1329 +   int process_mode;                 /* what push library is currently doing */
 71.1330 +   int cur_palette;                  /* current push library palette index */
 71.1331 +
 71.1332 +#  if defined(PNG_TEXT_SUPPORTED)
 71.1333 +     png_size_t current_text_size;   /* current size of text input data */
 71.1334 +     png_size_t current_text_left;   /* how much text left to read in input */
 71.1335 +     png_charp current_text;         /* current text chunk buffer */
 71.1336 +     png_charp current_text_ptr;     /* current location in current_text */
 71.1337 +#  endif /* PNG_TEXT_SUPPORTED */
 71.1338 +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
 71.1339 +
 71.1340 +#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
 71.1341 +/* for the Borland special 64K segment handler */
 71.1342 +   png_bytepp offset_table_ptr;
 71.1343 +   png_bytep offset_table;
 71.1344 +   png_uint_16 offset_table_number;
 71.1345 +   png_uint_16 offset_table_count;
 71.1346 +   png_uint_16 offset_table_count_free;
 71.1347 +#endif
 71.1348 +
 71.1349 +#if defined(PNG_READ_DITHER_SUPPORTED)
 71.1350 +   png_bytep palette_lookup;         /* lookup table for dithering */
 71.1351 +   png_bytep dither_index;           /* index translation for palette files */
 71.1352 +#endif
 71.1353 +
 71.1354 +#if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
 71.1355 +   png_uint_16p hist;                /* histogram */
 71.1356 +#endif
 71.1357 +
 71.1358 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 71.1359 +   png_byte heuristic_method;        /* heuristic for row filter selection */
 71.1360 +   png_byte num_prev_filters;        /* number of weights for previous rows */
 71.1361 +   png_bytep prev_filters;           /* filter type(s) of previous row(s) */
 71.1362 +   png_uint_16p filter_weights;      /* weight(s) for previous line(s) */
 71.1363 +   png_uint_16p inv_filter_weights;  /* 1/weight(s) for previous line(s) */
 71.1364 +   png_uint_16p filter_costs;        /* relative filter calculation cost */
 71.1365 +   png_uint_16p inv_filter_costs;    /* 1/relative filter calculation cost */
 71.1366 +#endif
 71.1367 +
 71.1368 +#if defined(PNG_TIME_RFC1123_SUPPORTED)
 71.1369 +   png_charp time_buffer;            /* String to hold RFC 1123 time text */
 71.1370 +#endif
 71.1371 +
 71.1372 +/* New members added in libpng-1.0.6 */
 71.1373 +
 71.1374 +#ifdef PNG_FREE_ME_SUPPORTED
 71.1375 +   png_uint_32 free_me;       /* flags items libpng is responsible for freeing */
 71.1376 +#endif
 71.1377 +
 71.1378 +#if defined(PNG_USER_CHUNKS_SUPPORTED)
 71.1379 +   png_voidp user_chunk_ptr;
 71.1380 +   png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
 71.1381 +#endif
 71.1382 +
 71.1383 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
 71.1384 +   int num_chunk_list;
 71.1385 +   png_bytep chunk_list;
 71.1386 +#endif
 71.1387 +
 71.1388 +/* New members added in libpng-1.0.3 */
 71.1389 +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
 71.1390 +   png_byte rgb_to_gray_status;
 71.1391 +   /* These were changed from png_byte in libpng-1.0.6 */
 71.1392 +   png_uint_16 rgb_to_gray_red_coeff;
 71.1393 +   png_uint_16 rgb_to_gray_green_coeff;
 71.1394 +   png_uint_16 rgb_to_gray_blue_coeff;
 71.1395 +#endif
 71.1396 +
 71.1397 +/* New member added in libpng-1.0.4 (renamed in 1.0.9) */
 71.1398 +#if defined(PNG_MNG_FEATURES_SUPPORTED) || \
 71.1399 +    defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
 71.1400 +    defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
 71.1401 +/* changed from png_byte to png_uint_32 at version 1.2.0 */
 71.1402 +#ifdef PNG_1_0_X
 71.1403 +   png_byte mng_features_permitted;
 71.1404 +#else
 71.1405 +   png_uint_32 mng_features_permitted;
 71.1406 +#endif /* PNG_1_0_X */
 71.1407 +#endif
 71.1408 +
 71.1409 +/* New member added in libpng-1.0.7 */
 71.1410 +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
 71.1411 +   png_fixed_point int_gamma;
 71.1412 +#endif
 71.1413 +
 71.1414 +/* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
 71.1415 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
 71.1416 +   png_byte filter_type;
 71.1417 +#endif
 71.1418 +
 71.1419 +#if defined(PNG_1_0_X)
 71.1420 +/* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
 71.1421 +   png_uint_32 row_buf_size;
 71.1422 +#endif
 71.1423 +
 71.1424 +/* New members added in libpng-1.2.0 */
 71.1425 +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
 71.1426 +#  if !defined(PNG_1_0_X)
 71.1427 +#    if defined(PNG_MMX_CODE_SUPPORTED)
 71.1428 +   png_byte     mmx_bitdepth_threshold;
 71.1429 +   png_uint_32  mmx_rowbytes_threshold;
 71.1430 +#    endif
 71.1431 +   png_uint_32  asm_flags;
 71.1432 +#  endif
 71.1433 +#endif
 71.1434 +
 71.1435 +/* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
 71.1436 +#ifdef PNG_USER_MEM_SUPPORTED
 71.1437 +   png_voidp mem_ptr;                /* user supplied struct for mem functions */
 71.1438 +   png_malloc_ptr malloc_fn;         /* function for allocating memory */
 71.1439 +   png_free_ptr free_fn;             /* function for freeing memory */
 71.1440 +#endif
 71.1441 +
 71.1442 +/* New member added in libpng-1.0.13 and 1.2.0 */
 71.1443 +   png_bytep big_row_buf;         /* buffer to save current (unfiltered) row */
 71.1444 +
 71.1445 +#if defined(PNG_READ_DITHER_SUPPORTED)
 71.1446 +/* The following three members were added at version 1.0.14 and 1.2.4 */
 71.1447 +   png_bytep dither_sort;            /* working sort array */
 71.1448 +   png_bytep index_to_palette;       /* where the original index currently is */
 71.1449 +                                     /* in the palette */
 71.1450 +   png_bytep palette_to_index;       /* which original index points to this */
 71.1451 +                                     /* palette color */
 71.1452 +#endif
 71.1453 +
 71.1454 +/* New members added in libpng-1.0.16 and 1.2.6 */
 71.1455 +   png_byte compression_type;
 71.1456 +
 71.1457 +#ifdef PNG_SET_USER_LIMITS_SUPPORTED
 71.1458 +   png_uint_32 user_width_max;
 71.1459 +   png_uint_32 user_height_max;
 71.1460 +#endif
 71.1461 +
 71.1462 +/* New member added in libpng-1.0.25 and 1.2.17 */
 71.1463 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
 71.1464 +   /* storage for unknown chunk that the library doesn't recognize. */
 71.1465 +   png_unknown_chunk unknown_chunk;
 71.1466 +#endif
 71.1467 +
 71.1468 +/* New members added in libpng-1.2.26 */
 71.1469 +  png_uint_32 old_big_row_buf_size, old_prev_row_size;
 71.1470 +
 71.1471 +/* New member added in libpng-1.2.30 */
 71.1472 +  png_charp chunkdata;  /* buffer for reading chunk data */
 71.1473 +
 71.1474 +};
 71.1475 +
 71.1476 +
 71.1477 +/* This triggers a compiler error in png.c, if png.c and png.h
 71.1478 + * do not agree upon the version number.
 71.1479 + */
 71.1480 +typedef png_structp version_1_2_33;
 71.1481 +
 71.1482 +typedef png_struct FAR * FAR * png_structpp;
 71.1483 +
 71.1484 +/* Here are the function definitions most commonly used.  This is not
 71.1485 + * the place to find out how to use libpng.  See libpng.txt for the
 71.1486 + * full explanation, see example.c for the summary.  This just provides
 71.1487 + * a simple one line description of the use of each function.
 71.1488 + */
 71.1489 +
 71.1490 +/* Returns the version number of the library */
 71.1491 +extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
 71.1492 +
 71.1493 +/* Tell lib we have already handled the first <num_bytes> magic bytes.
 71.1494 + * Handling more than 8 bytes from the beginning of the file is an error.
 71.1495 + */
 71.1496 +extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
 71.1497 +   int num_bytes));
 71.1498 +
 71.1499 +/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
 71.1500 + * PNG file.  Returns zero if the supplied bytes match the 8-byte PNG
 71.1501 + * signature, and non-zero otherwise.  Having num_to_check == 0 or
 71.1502 + * start > 7 will always fail (ie return non-zero).
 71.1503 + */
 71.1504 +extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
 71.1505 +   png_size_t num_to_check));
 71.1506 +
 71.1507 +/* Simple signature checking function.  This is the same as calling
 71.1508 + * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
 71.1509 + */
 71.1510 +extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
 71.1511 +
 71.1512 +/* Allocate and initialize png_ptr struct for reading, and any other memory. */
 71.1513 +extern PNG_EXPORT(png_structp,png_create_read_struct)
 71.1514 +   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
 71.1515 +   png_error_ptr error_fn, png_error_ptr warn_fn));
 71.1516 +
 71.1517 +/* Allocate and initialize png_ptr struct for writing, and any other memory */
 71.1518 +extern PNG_EXPORT(png_structp,png_create_write_struct)
 71.1519 +   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
 71.1520 +   png_error_ptr error_fn, png_error_ptr warn_fn));
 71.1521 +
 71.1522 +#ifdef PNG_WRITE_SUPPORTED
 71.1523 +extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
 71.1524 +   PNGARG((png_structp png_ptr));
 71.1525 +#endif
 71.1526 +
 71.1527 +#ifdef PNG_WRITE_SUPPORTED
 71.1528 +extern PNG_EXPORT(void,png_set_compression_buffer_size)
 71.1529 +   PNGARG((png_structp png_ptr, png_uint_32 size));
 71.1530 +#endif
 71.1531 +
 71.1532 +/* Reset the compression stream */
 71.1533 +extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
 71.1534 +
 71.1535 +/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
 71.1536 +#ifdef PNG_USER_MEM_SUPPORTED
 71.1537 +extern PNG_EXPORT(png_structp,png_create_read_struct_2)
 71.1538 +   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
 71.1539 +   png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
 71.1540 +   png_malloc_ptr malloc_fn, png_free_ptr free_fn));
 71.1541 +extern PNG_EXPORT(png_structp,png_create_write_struct_2)
 71.1542 +   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
 71.1543 +   png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
 71.1544 +   png_malloc_ptr malloc_fn, png_free_ptr free_fn));
 71.1545 +#endif
 71.1546 +
 71.1547 +/* Write a PNG chunk - size, type, (optional) data, CRC. */
 71.1548 +extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
 71.1549 +   png_bytep chunk_name, png_bytep data, png_size_t length));
 71.1550 +
 71.1551 +/* Write the start of a PNG chunk - length and chunk name. */
 71.1552 +extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
 71.1553 +   png_bytep chunk_name, png_uint_32 length));
 71.1554 +
 71.1555 +/* Write the data of a PNG chunk started with png_write_chunk_start(). */
 71.1556 +extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
 71.1557 +   png_bytep data, png_size_t length));
 71.1558 +
 71.1559 +/* Finish a chunk started with png_write_chunk_start() (includes CRC). */
 71.1560 +extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
 71.1561 +
 71.1562 +/* Allocate and initialize the info structure */
 71.1563 +extern PNG_EXPORT(png_infop,png_create_info_struct)
 71.1564 +   PNGARG((png_structp png_ptr));
 71.1565 +
 71.1566 +#if defined(PNG_1_0_X) || defined (PNG_1_2_X)
 71.1567 +/* Initialize the info structure (old interface - DEPRECATED) */
 71.1568 +extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
 71.1569 +#undef png_info_init
 71.1570 +#define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
 71.1571 +    png_sizeof(png_info));
 71.1572 +#endif
 71.1573 +
 71.1574 +extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
 71.1575 +    png_size_t png_info_struct_size));
 71.1576 +
 71.1577 +/* Writes all the PNG information before the image. */
 71.1578 +extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
 71.1579 +   png_infop info_ptr));
 71.1580 +extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
 71.1581 +   png_infop info_ptr));
 71.1582 +
 71.1583 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
 71.1584 +/* read the information before the actual image data. */
 71.1585 +extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
 71.1586 +   png_infop info_ptr));
 71.1587 +#endif
 71.1588 +
 71.1589 +#if defined(PNG_TIME_RFC1123_SUPPORTED)
 71.1590 +extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
 71.1591 +   PNGARG((png_structp png_ptr, png_timep ptime));
 71.1592 +#endif
 71.1593 +
 71.1594 +#if !defined(_WIN32_WCE)
 71.1595 +/* "time.h" functions are not supported on WindowsCE */
 71.1596 +#if defined(PNG_WRITE_tIME_SUPPORTED)
 71.1597 +/* convert from a struct tm to png_time */
 71.1598 +extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
 71.1599 +   struct tm FAR * ttime));
 71.1600 +
 71.1601 +/* convert from time_t to png_time.  Uses gmtime() */
 71.1602 +extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
 71.1603 +   time_t ttime));
 71.1604 +#endif /* PNG_WRITE_tIME_SUPPORTED */
 71.1605 +#endif /* _WIN32_WCE */
 71.1606 +
 71.1607 +#if defined(PNG_READ_EXPAND_SUPPORTED)
 71.1608 +/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
 71.1609 +extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
 71.1610 +#if !defined(PNG_1_0_X)
 71.1611 +extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
 71.1612 +  png_ptr));
 71.1613 +#endif
 71.1614 +extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
 71.1615 +extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
 71.1616 +#if defined(PNG_1_0_X) || defined (PNG_1_2_X)
 71.1617 +/* Deprecated */
 71.1618 +extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
 71.1619 +#endif
 71.1620 +#endif
 71.1621 +
 71.1622 +#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
 71.1623 +/* Use blue, green, red order for pixels. */
 71.1624 +extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
 71.1625 +#endif
 71.1626 +
 71.1627 +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
 71.1628 +/* Expand the grayscale to 24-bit RGB if necessary. */
 71.1629 +extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
 71.1630 +#endif
 71.1631 +
 71.1632 +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
 71.1633 +/* Reduce RGB to grayscale. */
 71.1634 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.1635 +extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
 71.1636 +   int error_action, double red, double green ));
 71.1637 +#endif
 71.1638 +extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
 71.1639 +   int error_action, png_fixed_point red, png_fixed_point green ));
 71.1640 +extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
 71.1641 +   png_ptr));
 71.1642 +#endif
 71.1643 +
 71.1644 +extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
 71.1645 +   png_colorp palette));
 71.1646 +
 71.1647 +#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
 71.1648 +extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
 71.1649 +#endif
 71.1650 +
 71.1651 +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
 71.1652 +    defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
 71.1653 +extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
 71.1654 +#endif
 71.1655 +
 71.1656 +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
 71.1657 +    defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
 71.1658 +extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
 71.1659 +#endif
 71.1660 +
 71.1661 +#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
 71.1662 +/* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
 71.1663 +extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
 71.1664 +   png_uint_32 filler, int flags));
 71.1665 +/* The values of the PNG_FILLER_ defines should NOT be changed */
 71.1666 +#define PNG_FILLER_BEFORE 0
 71.1667 +#define PNG_FILLER_AFTER 1
 71.1668 +/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
 71.1669 +#if !defined(PNG_1_0_X)
 71.1670 +extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
 71.1671 +   png_uint_32 filler, int flags));
 71.1672 +#endif
 71.1673 +#endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
 71.1674 +
 71.1675 +#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
 71.1676 +/* Swap bytes in 16-bit depth files. */
 71.1677 +extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
 71.1678 +#endif
 71.1679 +
 71.1680 +#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
 71.1681 +/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
 71.1682 +extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
 71.1683 +#endif
 71.1684 +
 71.1685 +#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
 71.1686 +/* Swap packing order of pixels in bytes. */
 71.1687 +extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
 71.1688 +#endif
 71.1689 +
 71.1690 +#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
 71.1691 +/* Converts files to legal bit depths. */
 71.1692 +extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
 71.1693 +   png_color_8p true_bits));
 71.1694 +#endif
 71.1695 +
 71.1696 +#if defined(PNG_READ_INTERLACING_SUPPORTED) || \
 71.1697 +    defined(PNG_WRITE_INTERLACING_SUPPORTED)
 71.1698 +/* Have the code handle the interlacing.  Returns the number of passes. */
 71.1699 +extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
 71.1700 +#endif
 71.1701 +
 71.1702 +#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
 71.1703 +/* Invert monochrome files */
 71.1704 +extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
 71.1705 +#endif
 71.1706 +
 71.1707 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 71.1708 +/* Handle alpha and tRNS by replacing with a background color. */
 71.1709 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.1710 +extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
 71.1711 +   png_color_16p background_color, int background_gamma_code,
 71.1712 +   int need_expand, double background_gamma));
 71.1713 +#endif
 71.1714 +#define PNG_BACKGROUND_GAMMA_UNKNOWN 0
 71.1715 +#define PNG_BACKGROUND_GAMMA_SCREEN  1
 71.1716 +#define PNG_BACKGROUND_GAMMA_FILE    2
 71.1717 +#define PNG_BACKGROUND_GAMMA_UNIQUE  3
 71.1718 +#endif
 71.1719 +
 71.1720 +#if defined(PNG_READ_16_TO_8_SUPPORTED)
 71.1721 +/* strip the second byte of information from a 16-bit depth file. */
 71.1722 +extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
 71.1723 +#endif
 71.1724 +
 71.1725 +#if defined(PNG_READ_DITHER_SUPPORTED)
 71.1726 +/* Turn on dithering, and reduce the palette to the number of colors available. */
 71.1727 +extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
 71.1728 +   png_colorp palette, int num_palette, int maximum_colors,
 71.1729 +   png_uint_16p histogram, int full_dither));
 71.1730 +#endif
 71.1731 +
 71.1732 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 71.1733 +/* Handle gamma correction. Screen_gamma=(display_exponent) */
 71.1734 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.1735 +extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
 71.1736 +   double screen_gamma, double default_file_gamma));
 71.1737 +#endif
 71.1738 +#endif
 71.1739 +
 71.1740 +#if defined(PNG_1_0_X) || defined (PNG_1_2_X)
 71.1741 +#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
 71.1742 +    defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
 71.1743 +/* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
 71.1744 +/* Deprecated and will be removed.  Use png_permit_mng_features() instead. */
 71.1745 +extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
 71.1746 +   int empty_plte_permitted));
 71.1747 +#endif
 71.1748 +#endif
 71.1749 +
 71.1750 +#if defined(PNG_WRITE_FLUSH_SUPPORTED)
 71.1751 +/* Set how many lines between output flushes - 0 for no flushing */
 71.1752 +extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
 71.1753 +/* Flush the current PNG output buffer */
 71.1754 +extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
 71.1755 +#endif
 71.1756 +
 71.1757 +/* optional update palette with requested transformations */
 71.1758 +extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
 71.1759 +
 71.1760 +/* optional call to update the users info structure */
 71.1761 +extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
 71.1762 +   png_infop info_ptr));
 71.1763 +
 71.1764 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
 71.1765 +/* read one or more rows of image data. */
 71.1766 +extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
 71.1767 +   png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
 71.1768 +#endif
 71.1769 +
 71.1770 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
 71.1771 +/* read a row of data. */
 71.1772 +extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
 71.1773 +   png_bytep row,
 71.1774 +   png_bytep display_row));
 71.1775 +#endif
 71.1776 +
 71.1777 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
 71.1778 +/* read the whole image into memory at once. */
 71.1779 +extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
 71.1780 +   png_bytepp image));
 71.1781 +#endif
 71.1782 +
 71.1783 +/* write a row of image data */
 71.1784 +extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
 71.1785 +   png_bytep row));
 71.1786 +
 71.1787 +/* write a few rows of image data */
 71.1788 +extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
 71.1789 +   png_bytepp row, png_uint_32 num_rows));
 71.1790 +
 71.1791 +/* write the image data */
 71.1792 +extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
 71.1793 +   png_bytepp image));
 71.1794 +
 71.1795 +/* writes the end of the PNG file. */
 71.1796 +extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
 71.1797 +   png_infop info_ptr));
 71.1798 +
 71.1799 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
 71.1800 +/* read the end of the PNG file. */
 71.1801 +extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
 71.1802 +   png_infop info_ptr));
 71.1803 +#endif
 71.1804 +
 71.1805 +/* free any memory associated with the png_info_struct */
 71.1806 +extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
 71.1807 +   png_infopp info_ptr_ptr));
 71.1808 +
 71.1809 +/* free any memory associated with the png_struct and the png_info_structs */
 71.1810 +extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
 71.1811 +   png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
 71.1812 +
 71.1813 +/* free all memory used by the read (old method - NOT DLL EXPORTED) */
 71.1814 +extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.1815 +   png_infop end_info_ptr));
 71.1816 +
 71.1817 +/* free any memory associated with the png_struct and the png_info_structs */
 71.1818 +extern PNG_EXPORT(void,png_destroy_write_struct)
 71.1819 +   PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
 71.1820 +
 71.1821 +/* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
 71.1822 +extern void png_write_destroy PNGARG((png_structp png_ptr));
 71.1823 +
 71.1824 +/* set the libpng method of handling chunk CRC errors */
 71.1825 +extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
 71.1826 +   int crit_action, int ancil_action));
 71.1827 +
 71.1828 +/* Values for png_set_crc_action() to say how to handle CRC errors in
 71.1829 + * ancillary and critical chunks, and whether to use the data contained
 71.1830 + * therein.  Note that it is impossible to "discard" data in a critical
 71.1831 + * chunk.  For versions prior to 0.90, the action was always error/quit,
 71.1832 + * whereas in version 0.90 and later, the action for CRC errors in ancillary
 71.1833 + * chunks is warn/discard.  These values should NOT be changed.
 71.1834 + *
 71.1835 + *      value                       action:critical     action:ancillary
 71.1836 + */
 71.1837 +#define PNG_CRC_DEFAULT       0  /* error/quit          warn/discard data */
 71.1838 +#define PNG_CRC_ERROR_QUIT    1  /* error/quit          error/quit        */
 71.1839 +#define PNG_CRC_WARN_DISCARD  2  /* (INVALID)           warn/discard data */
 71.1840 +#define PNG_CRC_WARN_USE      3  /* warn/use data       warn/use data     */
 71.1841 +#define PNG_CRC_QUIET_USE     4  /* quiet/use data      quiet/use data    */
 71.1842 +#define PNG_CRC_NO_CHANGE     5  /* use current value   use current value */
 71.1843 +
 71.1844 +/* These functions give the user control over the scan-line filtering in
 71.1845 + * libpng and the compression methods used by zlib.  These functions are
 71.1846 + * mainly useful for testing, as the defaults should work with most users.
 71.1847 + * Those users who are tight on memory or want faster performance at the
 71.1848 + * expense of compression can modify them.  See the compression library
 71.1849 + * header file (zlib.h) for an explination of the compression functions.
 71.1850 + */
 71.1851 +
 71.1852 +/* set the filtering method(s) used by libpng.  Currently, the only valid
 71.1853 + * value for "method" is 0.
 71.1854 + */
 71.1855 +extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
 71.1856 +   int filters));
 71.1857 +
 71.1858 +/* Flags for png_set_filter() to say which filters to use.  The flags
 71.1859 + * are chosen so that they don't conflict with real filter types
 71.1860 + * below, in case they are supplied instead of the #defined constants.
 71.1861 + * These values should NOT be changed.
 71.1862 + */
 71.1863 +#define PNG_NO_FILTERS     0x00
 71.1864 +#define PNG_FILTER_NONE    0x08
 71.1865 +#define PNG_FILTER_SUB     0x10
 71.1866 +#define PNG_FILTER_UP      0x20
 71.1867 +#define PNG_FILTER_AVG     0x40
 71.1868 +#define PNG_FILTER_PAETH   0x80
 71.1869 +#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
 71.1870 +                         PNG_FILTER_AVG | PNG_FILTER_PAETH)
 71.1871 +
 71.1872 +/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
 71.1873 + * These defines should NOT be changed.
 71.1874 + */
 71.1875 +#define PNG_FILTER_VALUE_NONE  0
 71.1876 +#define PNG_FILTER_VALUE_SUB   1
 71.1877 +#define PNG_FILTER_VALUE_UP    2
 71.1878 +#define PNG_FILTER_VALUE_AVG   3
 71.1879 +#define PNG_FILTER_VALUE_PAETH 4
 71.1880 +#define PNG_FILTER_VALUE_LAST  5
 71.1881 +
 71.1882 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
 71.1883 +/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
 71.1884 + * defines, either the default (minimum-sum-of-absolute-differences), or
 71.1885 + * the experimental method (weighted-minimum-sum-of-absolute-differences).
 71.1886 + *
 71.1887 + * Weights are factors >= 1.0, indicating how important it is to keep the
 71.1888 + * filter type consistent between rows.  Larger numbers mean the current
 71.1889 + * filter is that many times as likely to be the same as the "num_weights"
 71.1890 + * previous filters.  This is cumulative for each previous row with a weight.
 71.1891 + * There needs to be "num_weights" values in "filter_weights", or it can be
 71.1892 + * NULL if the weights aren't being specified.  Weights have no influence on
 71.1893 + * the selection of the first row filter.  Well chosen weights can (in theory)
 71.1894 + * improve the compression for a given image.
 71.1895 + *
 71.1896 + * Costs are factors >= 1.0 indicating the relative decoding costs of a
 71.1897 + * filter type.  Higher costs indicate more decoding expense, and are
 71.1898 + * therefore less likely to be selected over a filter with lower computational
 71.1899 + * costs.  There needs to be a value in "filter_costs" for each valid filter
 71.1900 + * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
 71.1901 + * setting the costs.  Costs try to improve the speed of decompression without
 71.1902 + * unduly increasing the compressed image size.
 71.1903 + *
 71.1904 + * A negative weight or cost indicates the default value is to be used, and
 71.1905 + * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
 71.1906 + * The default values for both weights and costs are currently 1.0, but may
 71.1907 + * change if good general weighting/cost heuristics can be found.  If both
 71.1908 + * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
 71.1909 + * to the UNWEIGHTED method, but with added encoding time/computation.
 71.1910 + */
 71.1911 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.1912 +extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
 71.1913 +   int heuristic_method, int num_weights, png_doublep filter_weights,
 71.1914 +   png_doublep filter_costs));
 71.1915 +#endif
 71.1916 +#endif /*  PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
 71.1917 +
 71.1918 +/* Heuristic used for row filter selection.  These defines should NOT be
 71.1919 + * changed.
 71.1920 + */
 71.1921 +#define PNG_FILTER_HEURISTIC_DEFAULT    0  /* Currently "UNWEIGHTED" */
 71.1922 +#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1  /* Used by libpng < 0.95 */
 71.1923 +#define PNG_FILTER_HEURISTIC_WEIGHTED   2  /* Experimental feature */
 71.1924 +#define PNG_FILTER_HEURISTIC_LAST       3  /* Not a valid value */
 71.1925 +
 71.1926 +/* Set the library compression level.  Currently, valid values range from
 71.1927 + * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
 71.1928 + * (0 - no compression, 9 - "maximal" compression).  Note that tests have
 71.1929 + * shown that zlib compression levels 3-6 usually perform as well as level 9
 71.1930 + * for PNG images, and do considerably fewer caclulations.  In the future,
 71.1931 + * these values may not correspond directly to the zlib compression levels.
 71.1932 + */
 71.1933 +extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
 71.1934 +   int level));
 71.1935 +
 71.1936 +extern PNG_EXPORT(void,png_set_compression_mem_level)
 71.1937 +   PNGARG((png_structp png_ptr, int mem_level));
 71.1938 +
 71.1939 +extern PNG_EXPORT(void,png_set_compression_strategy)
 71.1940 +   PNGARG((png_structp png_ptr, int strategy));
 71.1941 +
 71.1942 +extern PNG_EXPORT(void,png_set_compression_window_bits)
 71.1943 +   PNGARG((png_structp png_ptr, int window_bits));
 71.1944 +
 71.1945 +extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
 71.1946 +   int method));
 71.1947 +
 71.1948 +/* These next functions are called for input/output, memory, and error
 71.1949 + * handling.  They are in the file pngrio.c, pngwio.c, and pngerror.c,
 71.1950 + * and call standard C I/O routines such as fread(), fwrite(), and
 71.1951 + * fprintf().  These functions can be made to use other I/O routines
 71.1952 + * at run time for those applications that need to handle I/O in a
 71.1953 + * different manner by calling png_set_???_fn().  See libpng.txt for
 71.1954 + * more information.
 71.1955 + */
 71.1956 +
 71.1957 +#if !defined(PNG_NO_STDIO)
 71.1958 +/* Initialize the input/output for the PNG file to the default functions. */
 71.1959 +extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
 71.1960 +#endif
 71.1961 +
 71.1962 +/* Replace the (error and abort), and warning functions with user
 71.1963 + * supplied functions.  If no messages are to be printed you must still
 71.1964 + * write and use replacement functions. The replacement error_fn should
 71.1965 + * still do a longjmp to the last setjmp location if you are using this
 71.1966 + * method of error handling.  If error_fn or warning_fn is NULL, the
 71.1967 + * default function will be used.
 71.1968 + */
 71.1969 +
 71.1970 +extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
 71.1971 +   png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
 71.1972 +
 71.1973 +/* Return the user pointer associated with the error functions */
 71.1974 +extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
 71.1975 +
 71.1976 +/* Replace the default data output functions with a user supplied one(s).
 71.1977 + * If buffered output is not used, then output_flush_fn can be set to NULL.
 71.1978 + * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
 71.1979 + * output_flush_fn will be ignored (and thus can be NULL).
 71.1980 + */
 71.1981 +extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
 71.1982 +   png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
 71.1983 +
 71.1984 +/* Replace the default data input function with a user supplied one. */
 71.1985 +extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
 71.1986 +   png_voidp io_ptr, png_rw_ptr read_data_fn));
 71.1987 +
 71.1988 +/* Return the user pointer associated with the I/O functions */
 71.1989 +extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
 71.1990 +
 71.1991 +extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
 71.1992 +   png_read_status_ptr read_row_fn));
 71.1993 +
 71.1994 +extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
 71.1995 +   png_write_status_ptr write_row_fn));
 71.1996 +
 71.1997 +#ifdef PNG_USER_MEM_SUPPORTED
 71.1998 +/* Replace the default memory allocation functions with user supplied one(s). */
 71.1999 +extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
 71.2000 +   png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
 71.2001 +/* Return the user pointer associated with the memory functions */
 71.2002 +extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
 71.2003 +#endif
 71.2004 +
 71.2005 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
 71.2006 +    defined(PNG_LEGACY_SUPPORTED)
 71.2007 +extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
 71.2008 +   png_ptr, png_user_transform_ptr read_user_transform_fn));
 71.2009 +#endif
 71.2010 +
 71.2011 +#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
 71.2012 +    defined(PNG_LEGACY_SUPPORTED)
 71.2013 +extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
 71.2014 +   png_ptr, png_user_transform_ptr write_user_transform_fn));
 71.2015 +#endif
 71.2016 +
 71.2017 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
 71.2018 +    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
 71.2019 +    defined(PNG_LEGACY_SUPPORTED)
 71.2020 +extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
 71.2021 +   png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
 71.2022 +   int user_transform_channels));
 71.2023 +/* Return the user pointer associated with the user transform functions */
 71.2024 +extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
 71.2025 +   PNGARG((png_structp png_ptr));
 71.2026 +#endif
 71.2027 +
 71.2028 +#ifdef PNG_USER_CHUNKS_SUPPORTED
 71.2029 +extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
 71.2030 +   png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
 71.2031 +extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
 71.2032 +   png_ptr));
 71.2033 +#endif
 71.2034 +
 71.2035 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 71.2036 +/* Sets the function callbacks for the push reader, and a pointer to a
 71.2037 + * user-defined structure available to the callback functions.
 71.2038 + */
 71.2039 +extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
 71.2040 +   png_voidp progressive_ptr,
 71.2041 +   png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
 71.2042 +   png_progressive_end_ptr end_fn));
 71.2043 +
 71.2044 +/* returns the user pointer associated with the push read functions */
 71.2045 +extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
 71.2046 +   PNGARG((png_structp png_ptr));
 71.2047 +
 71.2048 +/* function to be called when data becomes available */
 71.2049 +extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
 71.2050 +   png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
 71.2051 +
 71.2052 +/* function that combines rows.  Not very much different than the
 71.2053 + * png_combine_row() call.  Is this even used?????
 71.2054 + */
 71.2055 +extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
 71.2056 +   png_bytep old_row, png_bytep new_row));
 71.2057 +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
 71.2058 +
 71.2059 +extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
 71.2060 +   png_uint_32 size));
 71.2061 +
 71.2062 +#if defined(PNG_1_0_X)
 71.2063 +#  define png_malloc_warn png_malloc
 71.2064 +#else
 71.2065 +/* Added at libpng version 1.2.4 */
 71.2066 +extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
 71.2067 +   png_uint_32 size));
 71.2068 +#endif
 71.2069 +
 71.2070 +/* frees a pointer allocated by png_malloc() */
 71.2071 +extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
 71.2072 +
 71.2073 +#if defined(PNG_1_0_X)
 71.2074 +/* Function to allocate memory for zlib. */
 71.2075 +extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
 71.2076 +   uInt size));
 71.2077 +
 71.2078 +/* Function to free memory for zlib */
 71.2079 +extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
 71.2080 +#endif
 71.2081 +
 71.2082 +/* Free data that was allocated internally */
 71.2083 +extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
 71.2084 +   png_infop info_ptr, png_uint_32 free_me, int num));
 71.2085 +#ifdef PNG_FREE_ME_SUPPORTED
 71.2086 +/* Reassign responsibility for freeing existing data, whether allocated
 71.2087 + * by libpng or by the application */
 71.2088 +extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
 71.2089 +   png_infop info_ptr, int freer, png_uint_32 mask));
 71.2090 +#endif
 71.2091 +/* assignments for png_data_freer */
 71.2092 +#define PNG_DESTROY_WILL_FREE_DATA 1
 71.2093 +#define PNG_SET_WILL_FREE_DATA 1
 71.2094 +#define PNG_USER_WILL_FREE_DATA 2
 71.2095 +/* Flags for png_ptr->free_me and info_ptr->free_me */
 71.2096 +#define PNG_FREE_HIST 0x0008
 71.2097 +#define PNG_FREE_ICCP 0x0010
 71.2098 +#define PNG_FREE_SPLT 0x0020
 71.2099 +#define PNG_FREE_ROWS 0x0040
 71.2100 +#define PNG_FREE_PCAL 0x0080
 71.2101 +#define PNG_FREE_SCAL 0x0100
 71.2102 +#define PNG_FREE_UNKN 0x0200
 71.2103 +#define PNG_FREE_LIST 0x0400
 71.2104 +#define PNG_FREE_PLTE 0x1000
 71.2105 +#define PNG_FREE_TRNS 0x2000
 71.2106 +#define PNG_FREE_TEXT 0x4000
 71.2107 +#define PNG_FREE_ALL  0x7fff
 71.2108 +#define PNG_FREE_MUL  0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
 71.2109 +
 71.2110 +#ifdef PNG_USER_MEM_SUPPORTED
 71.2111 +extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
 71.2112 +   png_uint_32 size));
 71.2113 +extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
 71.2114 +   png_voidp ptr));
 71.2115 +#endif
 71.2116 +
 71.2117 +extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
 71.2118 +   png_voidp s1, png_voidp s2, png_uint_32 size));
 71.2119 +
 71.2120 +extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
 71.2121 +   png_voidp s1, int value, png_uint_32 size));
 71.2122 +
 71.2123 +#if defined(USE_FAR_KEYWORD)  /* memory model conversion function */
 71.2124 +extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
 71.2125 +   int check));
 71.2126 +#endif /* USE_FAR_KEYWORD */
 71.2127 +
 71.2128 +#ifndef PNG_NO_ERROR_TEXT
 71.2129 +/* Fatal error in PNG image of libpng - can't continue */
 71.2130 +extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
 71.2131 +   png_const_charp error_message));
 71.2132 +
 71.2133 +/* The same, but the chunk name is prepended to the error string. */
 71.2134 +extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
 71.2135 +   png_const_charp error_message));
 71.2136 +#else
 71.2137 +/* Fatal error in PNG image of libpng - can't continue */
 71.2138 +extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
 71.2139 +#endif
 71.2140 +
 71.2141 +#ifndef PNG_NO_WARNINGS
 71.2142 +/* Non-fatal error in libpng.  Can continue, but may have a problem. */
 71.2143 +extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
 71.2144 +   png_const_charp warning_message));
 71.2145 +
 71.2146 +#ifdef PNG_READ_SUPPORTED
 71.2147 +/* Non-fatal error in libpng, chunk name is prepended to message. */
 71.2148 +extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
 71.2149 +   png_const_charp warning_message));
 71.2150 +#endif /* PNG_READ_SUPPORTED */
 71.2151 +#endif /* PNG_NO_WARNINGS */
 71.2152 +
 71.2153 +/* The png_set_<chunk> functions are for storing values in the png_info_struct.
 71.2154 + * Similarly, the png_get_<chunk> calls are used to read values from the
 71.2155 + * png_info_struct, either storing the parameters in the passed variables, or
 71.2156 + * setting pointers into the png_info_struct where the data is stored.  The
 71.2157 + * png_get_<chunk> functions return a non-zero value if the data was available
 71.2158 + * in info_ptr, or return zero and do not change any of the parameters if the
 71.2159 + * data was not available.
 71.2160 + *
 71.2161 + * These functions should be used instead of directly accessing png_info
 71.2162 + * to avoid problems with future changes in the size and internal layout of
 71.2163 + * png_info_struct.
 71.2164 + */
 71.2165 +/* Returns "flag" if chunk data is valid in info_ptr. */
 71.2166 +extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
 71.2167 +png_infop info_ptr, png_uint_32 flag));
 71.2168 +
 71.2169 +/* Returns number of bytes needed to hold a transformed row. */
 71.2170 +extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
 71.2171 +png_infop info_ptr));
 71.2172 +
 71.2173 +#if defined(PNG_INFO_IMAGE_SUPPORTED)
 71.2174 +/* Returns row_pointers, which is an array of pointers to scanlines that was
 71.2175 +returned from png_read_png(). */
 71.2176 +extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
 71.2177 +png_infop info_ptr));
 71.2178 +/* Set row_pointers, which is an array of pointers to scanlines for use
 71.2179 +by png_write_png(). */
 71.2180 +extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
 71.2181 +   png_infop info_ptr, png_bytepp row_pointers));
 71.2182 +#endif
 71.2183 +
 71.2184 +/* Returns number of color channels in image. */
 71.2185 +extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
 71.2186 +png_infop info_ptr));
 71.2187 +
 71.2188 +#ifdef PNG_EASY_ACCESS_SUPPORTED
 71.2189 +/* Returns image width in pixels. */
 71.2190 +extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
 71.2191 +png_ptr, png_infop info_ptr));
 71.2192 +
 71.2193 +/* Returns image height in pixels. */
 71.2194 +extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
 71.2195 +png_ptr, png_infop info_ptr));
 71.2196 +
 71.2197 +/* Returns image bit_depth. */
 71.2198 +extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
 71.2199 +png_ptr, png_infop info_ptr));
 71.2200 +
 71.2201 +/* Returns image color_type. */
 71.2202 +extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
 71.2203 +png_ptr, png_infop info_ptr));
 71.2204 +
 71.2205 +/* Returns image filter_type. */
 71.2206 +extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
 71.2207 +png_ptr, png_infop info_ptr));
 71.2208 +
 71.2209 +/* Returns image interlace_type. */
 71.2210 +extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
 71.2211 +png_ptr, png_infop info_ptr));
 71.2212 +
 71.2213 +/* Returns image compression_type. */
 71.2214 +extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
 71.2215 +png_ptr, png_infop info_ptr));
 71.2216 +
 71.2217 +/* Returns image resolution in pixels per meter, from pHYs chunk data. */
 71.2218 +extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
 71.2219 +png_ptr, png_infop info_ptr));
 71.2220 +extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
 71.2221 +png_ptr, png_infop info_ptr));
 71.2222 +extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
 71.2223 +png_ptr, png_infop info_ptr));
 71.2224 +
 71.2225 +/* Returns pixel aspect ratio, computed from pHYs chunk data.  */
 71.2226 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.2227 +extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
 71.2228 +png_ptr, png_infop info_ptr));
 71.2229 +#endif
 71.2230 +
 71.2231 +/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
 71.2232 +extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
 71.2233 +png_ptr, png_infop info_ptr));
 71.2234 +extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
 71.2235 +png_ptr, png_infop info_ptr));
 71.2236 +extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
 71.2237 +png_ptr, png_infop info_ptr));
 71.2238 +extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
 71.2239 +png_ptr, png_infop info_ptr));
 71.2240 +
 71.2241 +#endif /* PNG_EASY_ACCESS_SUPPORTED */
 71.2242 +
 71.2243 +/* Returns pointer to signature string read from PNG header */
 71.2244 +extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
 71.2245 +png_infop info_ptr));
 71.2246 +
 71.2247 +#if defined(PNG_bKGD_SUPPORTED)
 71.2248 +extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
 71.2249 +   png_infop info_ptr, png_color_16p *background));
 71.2250 +#endif
 71.2251 +
 71.2252 +#if defined(PNG_bKGD_SUPPORTED)
 71.2253 +extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
 71.2254 +   png_infop info_ptr, png_color_16p background));
 71.2255 +#endif
 71.2256 +
 71.2257 +#if defined(PNG_cHRM_SUPPORTED)
 71.2258 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.2259 +extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
 71.2260 +   png_infop info_ptr, double *white_x, double *white_y, double *red_x,
 71.2261 +   double *red_y, double *green_x, double *green_y, double *blue_x,
 71.2262 +   double *blue_y));
 71.2263 +#endif
 71.2264 +#ifdef PNG_FIXED_POINT_SUPPORTED
 71.2265 +extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
 71.2266 +   png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
 71.2267 +   *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
 71.2268 +   png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
 71.2269 +   *int_blue_x, png_fixed_point *int_blue_y));
 71.2270 +#endif
 71.2271 +#endif
 71.2272 +
 71.2273 +#if defined(PNG_cHRM_SUPPORTED)
 71.2274 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.2275 +extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
 71.2276 +   png_infop info_ptr, double white_x, double white_y, double red_x,
 71.2277 +   double red_y, double green_x, double green_y, double blue_x, double blue_y));
 71.2278 +#endif
 71.2279 +#ifdef PNG_FIXED_POINT_SUPPORTED
 71.2280 +extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
 71.2281 +   png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
 71.2282 +   png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
 71.2283 +   int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
 71.2284 +   png_fixed_point int_blue_y));
 71.2285 +#endif
 71.2286 +#endif
 71.2287 +
 71.2288 +#if defined(PNG_gAMA_SUPPORTED)
 71.2289 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.2290 +extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
 71.2291 +   png_infop info_ptr, double *file_gamma));
 71.2292 +#endif
 71.2293 +extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
 71.2294 +   png_infop info_ptr, png_fixed_point *int_file_gamma));
 71.2295 +#endif
 71.2296 +
 71.2297 +#if defined(PNG_gAMA_SUPPORTED)
 71.2298 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.2299 +extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
 71.2300 +   png_infop info_ptr, double file_gamma));
 71.2301 +#endif
 71.2302 +extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
 71.2303 +   png_infop info_ptr, png_fixed_point int_file_gamma));
 71.2304 +#endif
 71.2305 +
 71.2306 +#if defined(PNG_hIST_SUPPORTED)
 71.2307 +extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
 71.2308 +   png_infop info_ptr, png_uint_16p *hist));
 71.2309 +#endif
 71.2310 +
 71.2311 +#if defined(PNG_hIST_SUPPORTED)
 71.2312 +extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
 71.2313 +   png_infop info_ptr, png_uint_16p hist));
 71.2314 +#endif
 71.2315 +
 71.2316 +extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
 71.2317 +   png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
 71.2318 +   int *bit_depth, int *color_type, int *interlace_method,
 71.2319 +   int *compression_method, int *filter_method));
 71.2320 +
 71.2321 +extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
 71.2322 +   png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
 71.2323 +   int color_type, int interlace_method, int compression_method,
 71.2324 +   int filter_method));
 71.2325 +
 71.2326 +#if defined(PNG_oFFs_SUPPORTED)
 71.2327 +extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
 71.2328 +   png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
 71.2329 +   int *unit_type));
 71.2330 +#endif
 71.2331 +
 71.2332 +#if defined(PNG_oFFs_SUPPORTED)
 71.2333 +extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
 71.2334 +   png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
 71.2335 +   int unit_type));
 71.2336 +#endif
 71.2337 +
 71.2338 +#if defined(PNG_pCAL_SUPPORTED)
 71.2339 +extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
 71.2340 +   png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
 71.2341 +   int *type, int *nparams, png_charp *units, png_charpp *params));
 71.2342 +#endif
 71.2343 +
 71.2344 +#if defined(PNG_pCAL_SUPPORTED)
 71.2345 +extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
 71.2346 +   png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
 71.2347 +   int type, int nparams, png_charp units, png_charpp params));
 71.2348 +#endif
 71.2349 +
 71.2350 +#if defined(PNG_pHYs_SUPPORTED)
 71.2351 +extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
 71.2352 +   png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
 71.2353 +#endif
 71.2354 +
 71.2355 +#if defined(PNG_pHYs_SUPPORTED)
 71.2356 +extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
 71.2357 +   png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
 71.2358 +#endif
 71.2359 +
 71.2360 +extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
 71.2361 +   png_infop info_ptr, png_colorp *palette, int *num_palette));
 71.2362 +
 71.2363 +extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
 71.2364 +   png_infop info_ptr, png_colorp palette, int num_palette));
 71.2365 +
 71.2366 +#if defined(PNG_sBIT_SUPPORTED)
 71.2367 +extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
 71.2368 +   png_infop info_ptr, png_color_8p *sig_bit));
 71.2369 +#endif
 71.2370 +
 71.2371 +#if defined(PNG_sBIT_SUPPORTED)
 71.2372 +extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
 71.2373 +   png_infop info_ptr, png_color_8p sig_bit));
 71.2374 +#endif
 71.2375 +
 71.2376 +#if defined(PNG_sRGB_SUPPORTED)
 71.2377 +extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
 71.2378 +   png_infop info_ptr, int *intent));
 71.2379 +#endif
 71.2380 +
 71.2381 +#if defined(PNG_sRGB_SUPPORTED)
 71.2382 +extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
 71.2383 +   png_infop info_ptr, int intent));
 71.2384 +extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
 71.2385 +   png_infop info_ptr, int intent));
 71.2386 +#endif
 71.2387 +
 71.2388 +#if defined(PNG_iCCP_SUPPORTED)
 71.2389 +extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
 71.2390 +   png_infop info_ptr, png_charpp name, int *compression_type,
 71.2391 +   png_charpp profile, png_uint_32 *proflen));
 71.2392 +   /* Note to maintainer: profile should be png_bytepp */
 71.2393 +#endif
 71.2394 +
 71.2395 +#if defined(PNG_iCCP_SUPPORTED)
 71.2396 +extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
 71.2397 +   png_infop info_ptr, png_charp name, int compression_type,
 71.2398 +   png_charp profile, png_uint_32 proflen));
 71.2399 +   /* Note to maintainer: profile should be png_bytep */
 71.2400 +#endif
 71.2401 +
 71.2402 +#if defined(PNG_sPLT_SUPPORTED)
 71.2403 +extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
 71.2404 +   png_infop info_ptr, png_sPLT_tpp entries));
 71.2405 +#endif
 71.2406 +
 71.2407 +#if defined(PNG_sPLT_SUPPORTED)
 71.2408 +extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
 71.2409 +   png_infop info_ptr, png_sPLT_tp entries, int nentries));
 71.2410 +#endif
 71.2411 +
 71.2412 +#if defined(PNG_TEXT_SUPPORTED)
 71.2413 +/* png_get_text also returns the number of text chunks in *num_text */
 71.2414 +extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
 71.2415 +   png_infop info_ptr, png_textp *text_ptr, int *num_text));
 71.2416 +#endif
 71.2417 +
 71.2418 +/*
 71.2419 + *  Note while png_set_text() will accept a structure whose text,
 71.2420 + *  language, and  translated keywords are NULL pointers, the structure
 71.2421 + *  returned by png_get_text will always contain regular
 71.2422 + *  zero-terminated C strings.  They might be empty strings but
 71.2423 + *  they will never be NULL pointers.
 71.2424 + */
 71.2425 +
 71.2426 +#if defined(PNG_TEXT_SUPPORTED)
 71.2427 +extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
 71.2428 +   png_infop info_ptr, png_textp text_ptr, int num_text));
 71.2429 +#endif
 71.2430 +
 71.2431 +#if defined(PNG_tIME_SUPPORTED)
 71.2432 +extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
 71.2433 +   png_infop info_ptr, png_timep *mod_time));
 71.2434 +#endif
 71.2435 +
 71.2436 +#if defined(PNG_tIME_SUPPORTED)
 71.2437 +extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
 71.2438 +   png_infop info_ptr, png_timep mod_time));
 71.2439 +#endif
 71.2440 +
 71.2441 +#if defined(PNG_tRNS_SUPPORTED)
 71.2442 +extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
 71.2443 +   png_infop info_ptr, png_bytep *trans, int *num_trans,
 71.2444 +   png_color_16p *trans_values));
 71.2445 +#endif
 71.2446 +
 71.2447 +#if defined(PNG_tRNS_SUPPORTED)
 71.2448 +extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
 71.2449 +   png_infop info_ptr, png_bytep trans, int num_trans,
 71.2450 +   png_color_16p trans_values));
 71.2451 +#endif
 71.2452 +
 71.2453 +#if defined(PNG_tRNS_SUPPORTED)
 71.2454 +#endif
 71.2455 +
 71.2456 +#if defined(PNG_sCAL_SUPPORTED)
 71.2457 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.2458 +extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
 71.2459 +   png_infop info_ptr, int *unit, double *width, double *height));
 71.2460 +#else
 71.2461 +#ifdef PNG_FIXED_POINT_SUPPORTED
 71.2462 +extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
 71.2463 +   png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
 71.2464 +#endif
 71.2465 +#endif
 71.2466 +#endif /* PNG_sCAL_SUPPORTED */
 71.2467 +
 71.2468 +#if defined(PNG_sCAL_SUPPORTED)
 71.2469 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.2470 +extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
 71.2471 +   png_infop info_ptr, int unit, double width, double height));
 71.2472 +#else
 71.2473 +#ifdef PNG_FIXED_POINT_SUPPORTED
 71.2474 +extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
 71.2475 +   png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
 71.2476 +#endif
 71.2477 +#endif
 71.2478 +#endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
 71.2479 +
 71.2480 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
 71.2481 +/* provide a list of chunks and how they are to be handled, if the built-in
 71.2482 +   handling or default unknown chunk handling is not desired.  Any chunks not
 71.2483 +   listed will be handled in the default manner.  The IHDR and IEND chunks
 71.2484 +   must not be listed.
 71.2485 +      keep = 0: follow default behaviour
 71.2486 +           = 1: do not keep
 71.2487 +           = 2: keep only if safe-to-copy
 71.2488 +           = 3: keep even if unsafe-to-copy
 71.2489 +*/
 71.2490 +extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
 71.2491 +   png_ptr, int keep, png_bytep chunk_list, int num_chunks));
 71.2492 +extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
 71.2493 +   png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
 71.2494 +extern PNG_EXPORT(void, png_set_unknown_chunk_location)
 71.2495 +   PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
 71.2496 +extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
 71.2497 +   png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
 71.2498 +#endif
 71.2499 +#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 71.2500 +PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
 71.2501 +   chunk_name));
 71.2502 +#endif
 71.2503 +
 71.2504 +/* Png_free_data() will turn off the "valid" flag for anything it frees.
 71.2505 +   If you need to turn it off for a chunk that your application has freed,
 71.2506 +   you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
 71.2507 +extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
 71.2508 +   png_infop info_ptr, int mask));
 71.2509 +
 71.2510 +#if defined(PNG_INFO_IMAGE_SUPPORTED)
 71.2511 +/* The "params" pointer is currently not used and is for future expansion. */
 71.2512 +extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
 71.2513 +                        png_infop info_ptr,
 71.2514 +                        int transforms,
 71.2515 +                        png_voidp params));
 71.2516 +extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
 71.2517 +                        png_infop info_ptr,
 71.2518 +                        int transforms,
 71.2519 +                        png_voidp params));
 71.2520 +#endif
 71.2521 +
 71.2522 +/* Define PNG_DEBUG at compile time for debugging information.  Higher
 71.2523 + * numbers for PNG_DEBUG mean more debugging information.  This has
 71.2524 + * only been added since version 0.95 so it is not implemented throughout
 71.2525 + * libpng yet, but more support will be added as needed.
 71.2526 + */
 71.2527 +#ifdef PNG_DEBUG
 71.2528 +#if (PNG_DEBUG > 0)
 71.2529 +#if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
 71.2530 +#include <crtdbg.h>
 71.2531 +#if (PNG_DEBUG > 1)
 71.2532 +#define png_debug(l,m)  _RPT0(_CRT_WARN,m)
 71.2533 +#define png_debug1(l,m,p1)  _RPT1(_CRT_WARN,m,p1)
 71.2534 +#define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
 71.2535 +#endif
 71.2536 +#else /* PNG_DEBUG_FILE || !_MSC_VER */
 71.2537 +#ifndef PNG_DEBUG_FILE
 71.2538 +#define PNG_DEBUG_FILE stderr
 71.2539 +#endif /* PNG_DEBUG_FILE */
 71.2540 +#if (PNG_DEBUG > 1)
 71.2541 +#define png_debug(l,m) \
 71.2542 +{ \
 71.2543 +     int num_tabs=l; \
 71.2544 +     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
 71.2545 +       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
 71.2546 +}
 71.2547 +#define png_debug1(l,m,p1) \
 71.2548 +{ \
 71.2549 +     int num_tabs=l; \
 71.2550 +     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
 71.2551 +       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
 71.2552 +}
 71.2553 +#define png_debug2(l,m,p1,p2) \
 71.2554 +{ \
 71.2555 +     int num_tabs=l; \
 71.2556 +     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
 71.2557 +       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
 71.2558 +}
 71.2559 +#endif /* (PNG_DEBUG > 1) */
 71.2560 +#endif /* _MSC_VER */
 71.2561 +#endif /* (PNG_DEBUG > 0) */
 71.2562 +#endif /* PNG_DEBUG */
 71.2563 +#ifndef png_debug
 71.2564 +#define png_debug(l, m)
 71.2565 +#endif
 71.2566 +#ifndef png_debug1
 71.2567 +#define png_debug1(l, m, p1)
 71.2568 +#endif
 71.2569 +#ifndef png_debug2
 71.2570 +#define png_debug2(l, m, p1, p2)
 71.2571 +#endif
 71.2572 +
 71.2573 +extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
 71.2574 +extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
 71.2575 +extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
 71.2576 +extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
 71.2577 +
 71.2578 +#ifdef PNG_MNG_FEATURES_SUPPORTED
 71.2579 +extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
 71.2580 +   png_ptr, png_uint_32 mng_features_permitted));
 71.2581 +#endif
 71.2582 +
 71.2583 +/* For use in png_set_keep_unknown, added to version 1.2.6 */
 71.2584 +#define PNG_HANDLE_CHUNK_AS_DEFAULT   0
 71.2585 +#define PNG_HANDLE_CHUNK_NEVER        1
 71.2586 +#define PNG_HANDLE_CHUNK_IF_SAFE      2
 71.2587 +#define PNG_HANDLE_CHUNK_ALWAYS       3
 71.2588 +
 71.2589 +/* Added to version 1.2.0 */
 71.2590 +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
 71.2591 +#if defined(PNG_MMX_CODE_SUPPORTED)
 71.2592 +#define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED  0x01  /* not user-settable */
 71.2593 +#define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU    0x02  /* not user-settable */
 71.2594 +#define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW  0x04
 71.2595 +#define PNG_ASM_FLAG_MMX_READ_INTERLACE    0x08
 71.2596 +#define PNG_ASM_FLAG_MMX_READ_FILTER_SUB   0x10
 71.2597 +#define PNG_ASM_FLAG_MMX_READ_FILTER_UP    0x20
 71.2598 +#define PNG_ASM_FLAG_MMX_READ_FILTER_AVG   0x40
 71.2599 +#define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
 71.2600 +#define PNG_ASM_FLAGS_INITIALIZED          0x80000000  /* not user-settable */
 71.2601 +
 71.2602 +#define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW  \
 71.2603 +                           | PNG_ASM_FLAG_MMX_READ_INTERLACE    \
 71.2604 +                           | PNG_ASM_FLAG_MMX_READ_FILTER_SUB   \
 71.2605 +                           | PNG_ASM_FLAG_MMX_READ_FILTER_UP    \
 71.2606 +                           | PNG_ASM_FLAG_MMX_READ_FILTER_AVG   \
 71.2607 +                           | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
 71.2608 +#define PNG_MMX_WRITE_FLAGS ( 0 )
 71.2609 +
 71.2610 +#define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
 71.2611 +                      | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU   \
 71.2612 +                      | PNG_MMX_READ_FLAGS                \
 71.2613 +                      | PNG_MMX_WRITE_FLAGS )
 71.2614 +
 71.2615 +#define PNG_SELECT_READ   1
 71.2616 +#define PNG_SELECT_WRITE  2
 71.2617 +#endif /* PNG_MMX_CODE_SUPPORTED */
 71.2618 +
 71.2619 +#if !defined(PNG_1_0_X)
 71.2620 +/* pngget.c */
 71.2621 +extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
 71.2622 +   PNGARG((int flag_select, int *compilerID));
 71.2623 +
 71.2624 +/* pngget.c */
 71.2625 +extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
 71.2626 +   PNGARG((int flag_select));
 71.2627 +
 71.2628 +/* pngget.c */
 71.2629 +extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
 71.2630 +   PNGARG((png_structp png_ptr));
 71.2631 +
 71.2632 +/* pngget.c */
 71.2633 +extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
 71.2634 +   PNGARG((png_structp png_ptr));
 71.2635 +
 71.2636 +/* pngget.c */
 71.2637 +extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
 71.2638 +   PNGARG((png_structp png_ptr));
 71.2639 +
 71.2640 +/* pngset.c */
 71.2641 +extern PNG_EXPORT(void,png_set_asm_flags)
 71.2642 +   PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
 71.2643 +
 71.2644 +/* pngset.c */
 71.2645 +extern PNG_EXPORT(void,png_set_mmx_thresholds)
 71.2646 +   PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
 71.2647 +   png_uint_32 mmx_rowbytes_threshold));
 71.2648 +
 71.2649 +#endif /* PNG_1_0_X */
 71.2650 +
 71.2651 +#if !defined(PNG_1_0_X)
 71.2652 +/* png.c, pnggccrd.c, or pngvcrd.c */
 71.2653 +extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
 71.2654 +#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
 71.2655 +
 71.2656 +/* Strip the prepended error numbers ("#nnn ") from error and warning
 71.2657 + * messages before passing them to the error or warning handler. */
 71.2658 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
 71.2659 +extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
 71.2660 +   png_ptr, png_uint_32 strip_mode));
 71.2661 +#endif
 71.2662 +
 71.2663 +#endif /* PNG_1_0_X */
 71.2664 +
 71.2665 +/* Added at libpng-1.2.6 */
 71.2666 +#ifdef PNG_SET_USER_LIMITS_SUPPORTED
 71.2667 +extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
 71.2668 +   png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
 71.2669 +extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
 71.2670 +   png_ptr));
 71.2671 +extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
 71.2672 +   png_ptr));
 71.2673 +#endif
 71.2674 +
 71.2675 +
 71.2676 +/* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
 71.2677 +
 71.2678 +#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
 71.2679 +/* With these routines we avoid an integer divide, which will be slower on
 71.2680 + * most machines.  However, it does take more operations than the corresponding
 71.2681 + * divide method, so it may be slower on a few RISC systems.  There are two
 71.2682 + * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
 71.2683 + *
 71.2684 + * Note that the rounding factors are NOT supposed to be the same!  128 and
 71.2685 + * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
 71.2686 + * standard method.
 71.2687 + *
 71.2688 + * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
 71.2689 + */
 71.2690 +
 71.2691 + /* fg and bg should be in `gamma 1.0' space; alpha is the opacity          */
 71.2692 +
 71.2693 +#  define png_composite(composite, fg, alpha, bg)                            \
 71.2694 +     { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
 71.2695 +                        +        (png_uint_16)(bg)*(png_uint_16)(255 -       \
 71.2696 +                        (png_uint_16)(alpha)) + (png_uint_16)128);           \
 71.2697 +       (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
 71.2698 +
 71.2699 +#  define png_composite_16(composite, fg, alpha, bg)                         \
 71.2700 +     { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
 71.2701 +                        + (png_uint_32)(bg)*(png_uint_32)(65535L -           \
 71.2702 +                        (png_uint_32)(alpha)) + (png_uint_32)32768L);        \
 71.2703 +       (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
 71.2704 +
 71.2705 +#else  /* standard method using integer division */
 71.2706 +
 71.2707 +#  define png_composite(composite, fg, alpha, bg)                            \
 71.2708 +     (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) +    \
 71.2709 +       (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) +       \
 71.2710 +       (png_uint_16)127) / 255)
 71.2711 +
 71.2712 +#  define png_composite_16(composite, fg, alpha, bg)                         \
 71.2713 +     (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
 71.2714 +       (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) +      \
 71.2715 +       (png_uint_32)32767) / (png_uint_32)65535L)
 71.2716 +
 71.2717 +#endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
 71.2718 +
 71.2719 +/* Inline macros to do direct reads of bytes from the input buffer.  These
 71.2720 + * require that you are using an architecture that uses PNG byte ordering
 71.2721 + * (MSB first) and supports unaligned data storage.  I think that PowerPC
 71.2722 + * in big-endian mode and 680x0 are the only ones that will support this.
 71.2723 + * The x86 line of processors definitely do not.  The png_get_int_32()
 71.2724 + * routine also assumes we are using two's complement format for negative
 71.2725 + * values, which is almost certainly true.
 71.2726 + */
 71.2727 +#if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
 71.2728 +#  define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
 71.2729 +#  define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
 71.2730 +#  define png_get_int_32(buf)  ( *((png_int_32p)  (buf)))
 71.2731 +#else
 71.2732 +extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
 71.2733 +extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
 71.2734 +extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
 71.2735 +#endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
 71.2736 +extern PNG_EXPORT(png_uint_32,png_get_uint_31)
 71.2737 +  PNGARG((png_structp png_ptr, png_bytep buf));
 71.2738 +/* No png_get_int_16 -- may be added if there's a real need for it. */
 71.2739 +
 71.2740 +/* Place a 32-bit number into a buffer in PNG byte order (big-endian).
 71.2741 + */
 71.2742 +extern PNG_EXPORT(void,png_save_uint_32)
 71.2743 +   PNGARG((png_bytep buf, png_uint_32 i));
 71.2744 +extern PNG_EXPORT(void,png_save_int_32)
 71.2745 +   PNGARG((png_bytep buf, png_int_32 i));
 71.2746 +
 71.2747 +/* Place a 16-bit number into a buffer in PNG byte order.
 71.2748 + * The parameter is declared unsigned int, not png_uint_16,
 71.2749 + * just to avoid potential problems on pre-ANSI C compilers.
 71.2750 + */
 71.2751 +extern PNG_EXPORT(void,png_save_uint_16)
 71.2752 +   PNGARG((png_bytep buf, unsigned int i));
 71.2753 +/* No png_save_int_16 -- may be added if there's a real need for it. */
 71.2754 +
 71.2755 +/* ************************************************************************* */
 71.2756 +
 71.2757 +/* These next functions are used internally in the code.  They generally
 71.2758 + * shouldn't be used unless you are writing code to add or replace some
 71.2759 + * functionality in libpng.  More information about most functions can
 71.2760 + * be found in the files where the functions are located.
 71.2761 + */
 71.2762 +
 71.2763 +
 71.2764 +/* Various modes of operation, that are visible to applications because
 71.2765 + * they are used for unknown chunk location.
 71.2766 + */
 71.2767 +#define PNG_HAVE_IHDR               0x01
 71.2768 +#define PNG_HAVE_PLTE               0x02
 71.2769 +#define PNG_HAVE_IDAT               0x04
 71.2770 +#define PNG_AFTER_IDAT              0x08 /* Have complete zlib datastream */
 71.2771 +#define PNG_HAVE_IEND               0x10
 71.2772 +
 71.2773 +#if defined(PNG_INTERNAL)
 71.2774 +
 71.2775 +/* More modes of operation.  Note that after an init, mode is set to
 71.2776 + * zero automatically when the structure is created.
 71.2777 + */
 71.2778 +#define PNG_HAVE_gAMA               0x20
 71.2779 +#define PNG_HAVE_cHRM               0x40
 71.2780 +#define PNG_HAVE_sRGB               0x80
 71.2781 +#define PNG_HAVE_CHUNK_HEADER      0x100
 71.2782 +#define PNG_WROTE_tIME             0x200
 71.2783 +#define PNG_WROTE_INFO_BEFORE_PLTE 0x400
 71.2784 +#define PNG_BACKGROUND_IS_GRAY     0x800
 71.2785 +#define PNG_HAVE_PNG_SIGNATURE    0x1000
 71.2786 +#define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
 71.2787 +
 71.2788 +/* flags for the transformations the PNG library does on the image data */
 71.2789 +#define PNG_BGR                0x0001
 71.2790 +#define PNG_INTERLACE          0x0002
 71.2791 +#define PNG_PACK               0x0004
 71.2792 +#define PNG_SHIFT              0x0008
 71.2793 +#define PNG_SWAP_BYTES         0x0010
 71.2794 +#define PNG_INVERT_MONO        0x0020
 71.2795 +#define PNG_DITHER             0x0040
 71.2796 +#define PNG_BACKGROUND         0x0080
 71.2797 +#define PNG_BACKGROUND_EXPAND  0x0100
 71.2798 +                          /*   0x0200 unused */
 71.2799 +#define PNG_16_TO_8            0x0400
 71.2800 +#define PNG_RGBA               0x0800
 71.2801 +#define PNG_EXPAND             0x1000
 71.2802 +#define PNG_GAMMA              0x2000
 71.2803 +#define PNG_GRAY_TO_RGB        0x4000
 71.2804 +#define PNG_FILLER             0x8000L
 71.2805 +#define PNG_PACKSWAP          0x10000L
 71.2806 +#define PNG_SWAP_ALPHA        0x20000L
 71.2807 +#define PNG_STRIP_ALPHA       0x40000L
 71.2808 +#define PNG_INVERT_ALPHA      0x80000L
 71.2809 +#define PNG_USER_TRANSFORM   0x100000L
 71.2810 +#define PNG_RGB_TO_GRAY_ERR  0x200000L
 71.2811 +#define PNG_RGB_TO_GRAY_WARN 0x400000L
 71.2812 +#define PNG_RGB_TO_GRAY      0x600000L  /* two bits, RGB_TO_GRAY_ERR|WARN */
 71.2813 +                       /*    0x800000L     Unused */
 71.2814 +#define PNG_ADD_ALPHA       0x1000000L  /* Added to libpng-1.2.7 */
 71.2815 +#define PNG_EXPAND_tRNS     0x2000000L  /* Added to libpng-1.2.9 */
 71.2816 +                       /*   0x4000000L  unused */
 71.2817 +                       /*   0x8000000L  unused */
 71.2818 +                       /*  0x10000000L  unused */
 71.2819 +                       /*  0x20000000L  unused */
 71.2820 +                       /*  0x40000000L  unused */
 71.2821 +
 71.2822 +/* flags for png_create_struct */
 71.2823 +#define PNG_STRUCT_PNG   0x0001
 71.2824 +#define PNG_STRUCT_INFO  0x0002
 71.2825 +
 71.2826 +/* Scaling factor for filter heuristic weighting calculations */
 71.2827 +#define PNG_WEIGHT_SHIFT 8
 71.2828 +#define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
 71.2829 +#define PNG_COST_SHIFT 3
 71.2830 +#define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
 71.2831 +
 71.2832 +/* flags for the png_ptr->flags rather than declaring a byte for each one */
 71.2833 +#define PNG_FLAG_ZLIB_CUSTOM_STRATEGY     0x0001
 71.2834 +#define PNG_FLAG_ZLIB_CUSTOM_LEVEL        0x0002
 71.2835 +#define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL    0x0004
 71.2836 +#define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS  0x0008
 71.2837 +#define PNG_FLAG_ZLIB_CUSTOM_METHOD       0x0010
 71.2838 +#define PNG_FLAG_ZLIB_FINISHED            0x0020
 71.2839 +#define PNG_FLAG_ROW_INIT                 0x0040
 71.2840 +#define PNG_FLAG_FILLER_AFTER             0x0080
 71.2841 +#define PNG_FLAG_CRC_ANCILLARY_USE        0x0100
 71.2842 +#define PNG_FLAG_CRC_ANCILLARY_NOWARN     0x0200
 71.2843 +#define PNG_FLAG_CRC_CRITICAL_USE         0x0400
 71.2844 +#define PNG_FLAG_CRC_CRITICAL_IGNORE      0x0800
 71.2845 +#define PNG_FLAG_FREE_PLTE                0x1000
 71.2846 +#define PNG_FLAG_FREE_TRNS                0x2000
 71.2847 +#define PNG_FLAG_FREE_HIST                0x4000
 71.2848 +#define PNG_FLAG_KEEP_UNKNOWN_CHUNKS      0x8000L
 71.2849 +#define PNG_FLAG_KEEP_UNSAFE_CHUNKS       0x10000L
 71.2850 +#define PNG_FLAG_LIBRARY_MISMATCH         0x20000L
 71.2851 +#define PNG_FLAG_STRIP_ERROR_NUMBERS      0x40000L
 71.2852 +#define PNG_FLAG_STRIP_ERROR_TEXT         0x80000L
 71.2853 +#define PNG_FLAG_MALLOC_NULL_MEM_OK       0x100000L
 71.2854 +#define PNG_FLAG_ADD_ALPHA                0x200000L  /* Added to libpng-1.2.8 */
 71.2855 +#define PNG_FLAG_STRIP_ALPHA              0x400000L  /* Added to libpng-1.2.8 */
 71.2856 +                                  /*      0x800000L  unused */
 71.2857 +                                  /*     0x1000000L  unused */
 71.2858 +                                  /*     0x2000000L  unused */
 71.2859 +                                  /*     0x4000000L  unused */
 71.2860 +                                  /*     0x8000000L  unused */
 71.2861 +                                  /*    0x10000000L  unused */
 71.2862 +                                  /*    0x20000000L  unused */
 71.2863 +                                  /*    0x40000000L  unused */
 71.2864 +
 71.2865 +#define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
 71.2866 +                                     PNG_FLAG_CRC_ANCILLARY_NOWARN)
 71.2867 +
 71.2868 +#define PNG_FLAG_CRC_CRITICAL_MASK  (PNG_FLAG_CRC_CRITICAL_USE | \
 71.2869 +                                     PNG_FLAG_CRC_CRITICAL_IGNORE)
 71.2870 +
 71.2871 +#define PNG_FLAG_CRC_MASK           (PNG_FLAG_CRC_ANCILLARY_MASK | \
 71.2872 +                                     PNG_FLAG_CRC_CRITICAL_MASK)
 71.2873 +
 71.2874 +/* save typing and make code easier to understand */
 71.2875 +
 71.2876 +#define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
 71.2877 +   abs((int)((c1).green) - (int)((c2).green)) + \
 71.2878 +   abs((int)((c1).blue) - (int)((c2).blue)))
 71.2879 +
 71.2880 +/* Added to libpng-1.2.6 JB */
 71.2881 +#define PNG_ROWBYTES(pixel_bits, width) \
 71.2882 +    ((pixel_bits) >= 8 ? \
 71.2883 +    ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
 71.2884 +    (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
 71.2885 +
 71.2886 +/* PNG_OUT_OF_RANGE returns true if value is outside the range
 71.2887 +   ideal-delta..ideal+delta.  Each argument is evaluated twice.
 71.2888 +   "ideal" and "delta" should be constants, normally simple
 71.2889 +   integers, "value" a variable. Added to libpng-1.2.6 JB */
 71.2890 +#define PNG_OUT_OF_RANGE(value, ideal, delta) \
 71.2891 +        ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
 71.2892 +
 71.2893 +/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
 71.2894 +#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
 71.2895 +/* place to hold the signature string for a PNG file. */
 71.2896 +#ifdef PNG_USE_GLOBAL_ARRAYS
 71.2897 +   PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
 71.2898 +#else
 71.2899 +#endif
 71.2900 +#endif /* PNG_NO_EXTERN */
 71.2901 +
 71.2902 +/* Constant strings for known chunk types.  If you need to add a chunk,
 71.2903 + * define the name here, and add an invocation of the macro in png.c and
 71.2904 + * wherever it's needed.
 71.2905 + */
 71.2906 +#define PNG_IHDR png_byte png_IHDR[5] = { 73,  72,  68,  82, '\0'}
 71.2907 +#define PNG_IDAT png_byte png_IDAT[5] = { 73,  68,  65,  84, '\0'}
 71.2908 +#define PNG_IEND png_byte png_IEND[5] = { 73,  69,  78,  68, '\0'}
 71.2909 +#define PNG_PLTE png_byte png_PLTE[5] = { 80,  76,  84,  69, '\0'}
 71.2910 +#define PNG_bKGD png_byte png_bKGD[5] = { 98,  75,  71,  68, '\0'}
 71.2911 +#define PNG_cHRM png_byte png_cHRM[5] = { 99,  72,  82,  77, '\0'}
 71.2912 +#define PNG_gAMA png_byte png_gAMA[5] = {103,  65,  77,  65, '\0'}
 71.2913 +#define PNG_hIST png_byte png_hIST[5] = {104,  73,  83,  84, '\0'}
 71.2914 +#define PNG_iCCP png_byte png_iCCP[5] = {105,  67,  67,  80, '\0'}
 71.2915 +#define PNG_iTXt png_byte png_iTXt[5] = {105,  84,  88, 116, '\0'}
 71.2916 +#define PNG_oFFs png_byte png_oFFs[5] = {111,  70,  70, 115, '\0'}
 71.2917 +#define PNG_pCAL png_byte png_pCAL[5] = {112,  67,  65,  76, '\0'}
 71.2918 +#define PNG_sCAL png_byte png_sCAL[5] = {115,  67,  65,  76, '\0'}
 71.2919 +#define PNG_pHYs png_byte png_pHYs[5] = {112,  72,  89, 115, '\0'}
 71.2920 +#define PNG_sBIT png_byte png_sBIT[5] = {115,  66,  73,  84, '\0'}
 71.2921 +#define PNG_sPLT png_byte png_sPLT[5] = {115,  80,  76,  84, '\0'}
 71.2922 +#define PNG_sRGB png_byte png_sRGB[5] = {115,  82,  71,  66, '\0'}
 71.2923 +#define PNG_tEXt png_byte png_tEXt[5] = {116,  69,  88, 116, '\0'}
 71.2924 +#define PNG_tIME png_byte png_tIME[5] = {116,  73,  77,  69, '\0'}
 71.2925 +#define PNG_tRNS png_byte png_tRNS[5] = {116,  82,  78,  83, '\0'}
 71.2926 +#define PNG_zTXt png_byte png_zTXt[5] = {122,  84,  88, 116, '\0'}
 71.2927 +
 71.2928 +#ifdef PNG_USE_GLOBAL_ARRAYS
 71.2929 +PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
 71.2930 +PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
 71.2931 +PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
 71.2932 +PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
 71.2933 +PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
 71.2934 +PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
 71.2935 +PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
 71.2936 +PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
 71.2937 +PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
 71.2938 +PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
 71.2939 +PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
 71.2940 +PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
 71.2941 +PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
 71.2942 +PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
 71.2943 +PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
 71.2944 +PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
 71.2945 +PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
 71.2946 +PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
 71.2947 +PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
 71.2948 +PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
 71.2949 +PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
 71.2950 +#endif /* PNG_USE_GLOBAL_ARRAYS */
 71.2951 +
 71.2952 +#if defined(PNG_1_0_X) || defined (PNG_1_2_X)
 71.2953 +/* Initialize png_ptr struct for reading, and allocate any other memory.
 71.2954 + * (old interface - DEPRECATED - use png_create_read_struct instead).
 71.2955 + */
 71.2956 +extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
 71.2957 +#undef png_read_init
 71.2958 +#define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
 71.2959 +    PNG_LIBPNG_VER_STRING,  png_sizeof(png_struct));
 71.2960 +#endif
 71.2961 +
 71.2962 +extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
 71.2963 +    png_const_charp user_png_ver, png_size_t png_struct_size));
 71.2964 +#if defined(PNG_1_0_X) || defined (PNG_1_2_X)
 71.2965 +extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
 71.2966 +    png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
 71.2967 +    png_info_size));
 71.2968 +#endif
 71.2969 +
 71.2970 +#if defined(PNG_1_0_X) || defined (PNG_1_2_X)
 71.2971 +/* Initialize png_ptr struct for writing, and allocate any other memory.
 71.2972 + * (old interface - DEPRECATED - use png_create_write_struct instead).
 71.2973 + */
 71.2974 +extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
 71.2975 +#undef png_write_init
 71.2976 +#define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
 71.2977 +    PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
 71.2978 +#endif
 71.2979 +
 71.2980 +extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
 71.2981 +    png_const_charp user_png_ver, png_size_t png_struct_size));
 71.2982 +extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
 71.2983 +    png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
 71.2984 +    png_info_size));
 71.2985 +
 71.2986 +/* Allocate memory for an internal libpng struct */
 71.2987 +PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
 71.2988 +
 71.2989 +/* Free memory from internal libpng struct */
 71.2990 +PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
 71.2991 +
 71.2992 +PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
 71.2993 +  malloc_fn, png_voidp mem_ptr));
 71.2994 +PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
 71.2995 +   png_free_ptr free_fn, png_voidp mem_ptr));
 71.2996 +
 71.2997 +/* Free any memory that info_ptr points to and reset struct. */
 71.2998 +PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
 71.2999 +   png_infop info_ptr));
 71.3000 +
 71.3001 +#ifndef PNG_1_0_X
 71.3002 +/* Function to allocate memory for zlib. */
 71.3003 +PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
 71.3004 +
 71.3005 +/* Function to free memory for zlib */
 71.3006 +PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
 71.3007 +
 71.3008 +#ifdef PNG_SIZE_T
 71.3009 +/* Function to convert a sizeof an item to png_sizeof item */
 71.3010 +   PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
 71.3011 +#endif
 71.3012 +
 71.3013 +/* Next four functions are used internally as callbacks.  PNGAPI is required
 71.3014 + * but not PNG_EXPORT.  PNGAPI added at libpng version 1.2.3. */
 71.3015 +
 71.3016 +PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
 71.3017 +   png_bytep data, png_size_t length));
 71.3018 +
 71.3019 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 71.3020 +PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
 71.3021 +   png_bytep buffer, png_size_t length));
 71.3022 +#endif
 71.3023 +
 71.3024 +PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
 71.3025 +   png_bytep data, png_size_t length));
 71.3026 +
 71.3027 +#if defined(PNG_WRITE_FLUSH_SUPPORTED)
 71.3028 +#if !defined(PNG_NO_STDIO)
 71.3029 +PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
 71.3030 +#endif
 71.3031 +#endif
 71.3032 +#else /* PNG_1_0_X */
 71.3033 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 71.3034 +PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
 71.3035 +   png_bytep buffer, png_size_t length));
 71.3036 +#endif
 71.3037 +#endif /* PNG_1_0_X */
 71.3038 +
 71.3039 +/* Reset the CRC variable */
 71.3040 +PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
 71.3041 +
 71.3042 +/* Write the "data" buffer to whatever output you are using. */
 71.3043 +PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
 71.3044 +   png_size_t length));
 71.3045 +
 71.3046 +/* Read data from whatever input you are using into the "data" buffer */
 71.3047 +PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
 71.3048 +   png_size_t length));
 71.3049 +
 71.3050 +/* Read bytes into buf, and update png_ptr->crc */
 71.3051 +PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
 71.3052 +   png_size_t length));
 71.3053 +
 71.3054 +/* Decompress data in a chunk that uses compression */
 71.3055 +#if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
 71.3056 +    defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
 71.3057 +PNG_EXTERN void png_decompress_chunk PNGARG((png_structp png_ptr,
 71.3058 +   int comp_type, png_size_t chunklength,
 71.3059 +   png_size_t prefix_length, png_size_t *data_length));
 71.3060 +#endif
 71.3061 +
 71.3062 +/* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
 71.3063 +PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
 71.3064 +
 71.3065 +/* Read the CRC from the file and compare it to the libpng calculated CRC */
 71.3066 +PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
 71.3067 +
 71.3068 +/* Calculate the CRC over a section of data.  Note that we are only
 71.3069 + * passing a maximum of 64K on systems that have this as a memory limit,
 71.3070 + * since this is the maximum buffer size we can specify.
 71.3071 + */
 71.3072 +PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
 71.3073 +   png_size_t length));
 71.3074 +
 71.3075 +#if defined(PNG_WRITE_FLUSH_SUPPORTED)
 71.3076 +PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
 71.3077 +#endif
 71.3078 +
 71.3079 +/* simple function to write the signature */
 71.3080 +PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
 71.3081 +
 71.3082 +/* write various chunks */
 71.3083 +
 71.3084 +/* Write the IHDR chunk, and update the png_struct with the necessary
 71.3085 + * information.
 71.3086 + */
 71.3087 +PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
 71.3088 +   png_uint_32 height,
 71.3089 +   int bit_depth, int color_type, int compression_method, int filter_method,
 71.3090 +   int interlace_method));
 71.3091 +
 71.3092 +PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
 71.3093 +   png_uint_32 num_pal));
 71.3094 +
 71.3095 +PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
 71.3096 +   png_size_t length));
 71.3097 +
 71.3098 +PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
 71.3099 +
 71.3100 +#if defined(PNG_WRITE_gAMA_SUPPORTED)
 71.3101 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.3102 +PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
 71.3103 +#endif
 71.3104 +#ifdef PNG_FIXED_POINT_SUPPORTED
 71.3105 +PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
 71.3106 +    file_gamma));
 71.3107 +#endif
 71.3108 +#endif
 71.3109 +
 71.3110 +#if defined(PNG_WRITE_sBIT_SUPPORTED)
 71.3111 +PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
 71.3112 +   int color_type));
 71.3113 +#endif
 71.3114 +
 71.3115 +#if defined(PNG_WRITE_cHRM_SUPPORTED)
 71.3116 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 71.3117 +PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
 71.3118 +   double white_x, double white_y,
 71.3119 +   double red_x, double red_y, double green_x, double green_y,
 71.3120 +   double blue_x, double blue_y));
 71.3121 +#endif
 71.3122 +#ifdef PNG_FIXED_POINT_SUPPORTED
 71.3123 +PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
 71.3124 +   png_fixed_point int_white_x, png_fixed_point int_white_y,
 71.3125 +   png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
 71.3126 +   int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
 71.3127 +   png_fixed_point int_blue_y));
 71.3128 +#endif
 71.3129 +#endif
 71.3130 +
 71.3131 +#if defined(PNG_WRITE_sRGB_SUPPORTED)
 71.3132 +PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
 71.3133 +   int intent));
 71.3134 +#endif
 71.3135 +
 71.3136 +#if defined(PNG_WRITE_iCCP_SUPPORTED)
 71.3137 +PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
 71.3138 +   png_charp name, int compression_type,
 71.3139 +   png_charp profile, int proflen));
 71.3140 +   /* Note to maintainer: profile should be png_bytep */
 71.3141 +#endif
 71.3142 +
 71.3143 +#if defined(PNG_WRITE_sPLT_SUPPORTED)
 71.3144 +PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
 71.3145 +   png_sPLT_tp palette));
 71.3146 +#endif
 71.3147 +
 71.3148 +#if defined(PNG_WRITE_tRNS_SUPPORTED)
 71.3149 +PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
 71.3150 +   png_color_16p values, int number, int color_type));
 71.3151 +#endif
 71.3152 +
 71.3153 +#if defined(PNG_WRITE_bKGD_SUPPORTED)
 71.3154 +PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
 71.3155 +   png_color_16p values, int color_type));
 71.3156 +#endif
 71.3157 +
 71.3158 +#if defined(PNG_WRITE_hIST_SUPPORTED)
 71.3159 +PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
 71.3160 +   int num_hist));
 71.3161 +#endif
 71.3162 +
 71.3163 +#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
 71.3164 +    defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
 71.3165 +PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
 71.3166 +   png_charp key, png_charpp new_key));
 71.3167 +#endif
 71.3168 +
 71.3169 +#if defined(PNG_WRITE_tEXt_SUPPORTED)
 71.3170 +PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
 71.3171 +   png_charp text, png_size_t text_len));
 71.3172 +#endif
 71.3173 +
 71.3174 +#if defined(PNG_WRITE_zTXt_SUPPORTED)
 71.3175 +PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
 71.3176 +   png_charp text, png_size_t text_len, int compression));
 71.3177 +#endif
 71.3178 +
 71.3179 +#if defined(PNG_WRITE_iTXt_SUPPORTED)
 71.3180 +PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
 71.3181 +   int compression, png_charp key, png_charp lang, png_charp lang_key,
 71.3182 +   png_charp text));
 71.3183 +#endif
 71.3184 +
 71.3185 +#if defined(PNG_TEXT_SUPPORTED)  /* Added at version 1.0.14 and 1.2.4 */
 71.3186 +PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
 71.3187 +   png_infop info_ptr, png_textp text_ptr, int num_text));
 71.3188 +#endif
 71.3189 +
 71.3190 +#if defined(PNG_WRITE_oFFs_SUPPORTED)
 71.3191 +PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
 71.3192 +   png_int_32 x_offset, png_int_32 y_offset, int unit_type));
 71.3193 +#endif
 71.3194 +
 71.3195 +#if defined(PNG_WRITE_pCAL_SUPPORTED)
 71.3196 +PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
 71.3197 +   png_int_32 X0, png_int_32 X1, int type, int nparams,
 71.3198 +   png_charp units, png_charpp params));
 71.3199 +#endif
 71.3200 +
 71.3201 +#if defined(PNG_WRITE_pHYs_SUPPORTED)
 71.3202 +PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
 71.3203 +   png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
 71.3204 +   int unit_type));
 71.3205 +#endif
 71.3206 +
 71.3207 +#if defined(PNG_WRITE_tIME_SUPPORTED)
 71.3208 +PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
 71.3209 +   png_timep mod_time));
 71.3210 +#endif
 71.3211 +
 71.3212 +#if defined(PNG_WRITE_sCAL_SUPPORTED)
 71.3213 +#if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
 71.3214 +PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
 71.3215 +   int unit, double width, double height));
 71.3216 +#else
 71.3217 +#ifdef PNG_FIXED_POINT_SUPPORTED
 71.3218 +PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
 71.3219 +   int unit, png_charp width, png_charp height));
 71.3220 +#endif
 71.3221 +#endif
 71.3222 +#endif
 71.3223 +
 71.3224 +/* Called when finished processing a row of data */
 71.3225 +PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
 71.3226 +
 71.3227 +/* Internal use only.   Called before first row of data */
 71.3228 +PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
 71.3229 +
 71.3230 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 71.3231 +PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
 71.3232 +#endif
 71.3233 +
 71.3234 +/* combine a row of data, dealing with alpha, etc. if requested */
 71.3235 +PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
 71.3236 +   int mask));
 71.3237 +
 71.3238 +#if defined(PNG_READ_INTERLACING_SUPPORTED)
 71.3239 +/* expand an interlaced row */
 71.3240 +/* OLD pre-1.0.9 interface:
 71.3241 +PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
 71.3242 +   png_bytep row, int pass, png_uint_32 transformations));
 71.3243 + */
 71.3244 +PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
 71.3245 +#endif
 71.3246 +
 71.3247 +/* GRR TO DO (2.0 or whenever):  simplify other internal calling interfaces */
 71.3248 +
 71.3249 +#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
 71.3250 +/* grab pixels out of a row for an interlaced pass */
 71.3251 +PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
 71.3252 +   png_bytep row, int pass));
 71.3253 +#endif
 71.3254 +
 71.3255 +/* unfilter a row */
 71.3256 +PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
 71.3257 +   png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
 71.3258 +
 71.3259 +/* Choose the best filter to use and filter the row data */
 71.3260 +PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
 71.3261 +   png_row_infop row_info));
 71.3262 +
 71.3263 +/* Write out the filtered row. */
 71.3264 +PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
 71.3265 +   png_bytep filtered_row));
 71.3266 +/* finish a row while reading, dealing with interlacing passes, etc. */
 71.3267 +PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
 71.3268 +
 71.3269 +/* initialize the row buffers, etc. */
 71.3270 +PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
 71.3271 +/* optional call to update the users info structure */
 71.3272 +PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
 71.3273 +   png_infop info_ptr));
 71.3274 +
 71.3275 +/* these are the functions that do the transformations */
 71.3276 +#if defined(PNG_READ_FILLER_SUPPORTED)
 71.3277 +PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
 71.3278 +   png_bytep row, png_uint_32 filler, png_uint_32 flags));
 71.3279 +#endif
 71.3280 +
 71.3281 +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
 71.3282 +PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
 71.3283 +   png_bytep row));
 71.3284 +#endif
 71.3285 +
 71.3286 +#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
 71.3287 +PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
 71.3288 +   png_bytep row));
 71.3289 +#endif
 71.3290 +
 71.3291 +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
 71.3292 +PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
 71.3293 +   png_bytep row));
 71.3294 +#endif
 71.3295 +
 71.3296 +#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
 71.3297 +PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
 71.3298 +   png_bytep row));
 71.3299 +#endif
 71.3300 +
 71.3301 +#if defined(PNG_WRITE_FILLER_SUPPORTED) || \
 71.3302 +    defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
 71.3303 +PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
 71.3304 +   png_bytep row, png_uint_32 flags));
 71.3305 +#endif
 71.3306 +
 71.3307 +#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
 71.3308 +PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
 71.3309 +#endif
 71.3310 +
 71.3311 +#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
 71.3312 +PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
 71.3313 +#endif
 71.3314 +
 71.3315 +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
 71.3316 +PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
 71.3317 +   row_info, png_bytep row));
 71.3318 +#endif
 71.3319 +
 71.3320 +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
 71.3321 +PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
 71.3322 +   png_bytep row));
 71.3323 +#endif
 71.3324 +
 71.3325 +#if defined(PNG_READ_PACK_SUPPORTED)
 71.3326 +PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
 71.3327 +#endif
 71.3328 +
 71.3329 +#if defined(PNG_READ_SHIFT_SUPPORTED)
 71.3330 +PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
 71.3331 +   png_color_8p sig_bits));
 71.3332 +#endif
 71.3333 +
 71.3334 +#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
 71.3335 +PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
 71.3336 +#endif
 71.3337 +
 71.3338 +#if defined(PNG_READ_16_TO_8_SUPPORTED)
 71.3339 +PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
 71.3340 +#endif
 71.3341 +
 71.3342 +#if defined(PNG_READ_DITHER_SUPPORTED)
 71.3343 +PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
 71.3344 +   png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
 71.3345 +
 71.3346 +#  if defined(PNG_CORRECT_PALETTE_SUPPORTED)
 71.3347 +PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
 71.3348 +   png_colorp palette, int num_palette));
 71.3349 +#  endif
 71.3350 +#endif
 71.3351 +
 71.3352 +#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
 71.3353 +PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
 71.3354 +#endif
 71.3355 +
 71.3356 +#if defined(PNG_WRITE_PACK_SUPPORTED)
 71.3357 +PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
 71.3358 +   png_bytep row, png_uint_32 bit_depth));
 71.3359 +#endif
 71.3360 +
 71.3361 +#if defined(PNG_WRITE_SHIFT_SUPPORTED)
 71.3362 +PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
 71.3363 +   png_color_8p bit_depth));
 71.3364 +#endif
 71.3365 +
 71.3366 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 71.3367 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 71.3368 +PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
 71.3369 +   png_color_16p trans_values, png_color_16p background,
 71.3370 +   png_color_16p background_1,
 71.3371 +   png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
 71.3372 +   png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
 71.3373 +   png_uint_16pp gamma_16_to_1, int gamma_shift));
 71.3374 +#else
 71.3375 +PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
 71.3376 +   png_color_16p trans_values, png_color_16p background));
 71.3377 +#endif
 71.3378 +#endif
 71.3379 +
 71.3380 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 71.3381 +PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
 71.3382 +   png_bytep gamma_table, png_uint_16pp gamma_16_table,
 71.3383 +   int gamma_shift));
 71.3384 +#endif
 71.3385 +
 71.3386 +#if defined(PNG_READ_EXPAND_SUPPORTED)
 71.3387 +PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
 71.3388 +   png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
 71.3389 +PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
 71.3390 +   png_bytep row, png_color_16p trans_value));
 71.3391 +#endif
 71.3392 +
 71.3393 +/* The following decodes the appropriate chunks, and does error correction,
 71.3394 + * then calls the appropriate callback for the chunk if it is valid.
 71.3395 + */
 71.3396 +
 71.3397 +/* decode the IHDR chunk */
 71.3398 +PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3399 +   png_uint_32 length));
 71.3400 +PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3401 +   png_uint_32 length));
 71.3402 +PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3403 +   png_uint_32 length));
 71.3404 +
 71.3405 +#if defined(PNG_READ_bKGD_SUPPORTED)
 71.3406 +PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3407 +   png_uint_32 length));
 71.3408 +#endif
 71.3409 +
 71.3410 +#if defined(PNG_READ_cHRM_SUPPORTED)
 71.3411 +PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3412 +   png_uint_32 length));
 71.3413 +#endif
 71.3414 +
 71.3415 +#if defined(PNG_READ_gAMA_SUPPORTED)
 71.3416 +PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3417 +   png_uint_32 length));
 71.3418 +#endif
 71.3419 +
 71.3420 +#if defined(PNG_READ_hIST_SUPPORTED)
 71.3421 +PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3422 +   png_uint_32 length));
 71.3423 +#endif
 71.3424 +
 71.3425 +#if defined(PNG_READ_iCCP_SUPPORTED)
 71.3426 +extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3427 +   png_uint_32 length));
 71.3428 +#endif /* PNG_READ_iCCP_SUPPORTED */
 71.3429 +
 71.3430 +#if defined(PNG_READ_iTXt_SUPPORTED)
 71.3431 +PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3432 +   png_uint_32 length));
 71.3433 +#endif
 71.3434 +
 71.3435 +#if defined(PNG_READ_oFFs_SUPPORTED)
 71.3436 +PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3437 +   png_uint_32 length));
 71.3438 +#endif
 71.3439 +
 71.3440 +#if defined(PNG_READ_pCAL_SUPPORTED)
 71.3441 +PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3442 +   png_uint_32 length));
 71.3443 +#endif
 71.3444 +
 71.3445 +#if defined(PNG_READ_pHYs_SUPPORTED)
 71.3446 +PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3447 +   png_uint_32 length));
 71.3448 +#endif
 71.3449 +
 71.3450 +#if defined(PNG_READ_sBIT_SUPPORTED)
 71.3451 +PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3452 +   png_uint_32 length));
 71.3453 +#endif
 71.3454 +
 71.3455 +#if defined(PNG_READ_sCAL_SUPPORTED)
 71.3456 +PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3457 +   png_uint_32 length));
 71.3458 +#endif
 71.3459 +
 71.3460 +#if defined(PNG_READ_sPLT_SUPPORTED)
 71.3461 +extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3462 +   png_uint_32 length));
 71.3463 +#endif /* PNG_READ_sPLT_SUPPORTED */
 71.3464 +
 71.3465 +#if defined(PNG_READ_sRGB_SUPPORTED)
 71.3466 +PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3467 +   png_uint_32 length));
 71.3468 +#endif
 71.3469 +
 71.3470 +#if defined(PNG_READ_tEXt_SUPPORTED)
 71.3471 +PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3472 +   png_uint_32 length));
 71.3473 +#endif
 71.3474 +
 71.3475 +#if defined(PNG_READ_tIME_SUPPORTED)
 71.3476 +PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3477 +   png_uint_32 length));
 71.3478 +#endif
 71.3479 +
 71.3480 +#if defined(PNG_READ_tRNS_SUPPORTED)
 71.3481 +PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3482 +   png_uint_32 length));
 71.3483 +#endif
 71.3484 +
 71.3485 +#if defined(PNG_READ_zTXt_SUPPORTED)
 71.3486 +PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
 71.3487 +   png_uint_32 length));
 71.3488 +#endif
 71.3489 +
 71.3490 +PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
 71.3491 +   png_infop info_ptr, png_uint_32 length));
 71.3492 +
 71.3493 +PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
 71.3494 +   png_bytep chunk_name));
 71.3495 +
 71.3496 +/* handle the transformations for reading and writing */
 71.3497 +PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
 71.3498 +PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
 71.3499 +
 71.3500 +PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
 71.3501 +
 71.3502 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 71.3503 +PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
 71.3504 +   png_infop info_ptr));
 71.3505 +PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
 71.3506 +   png_infop info_ptr));
 71.3507 +PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
 71.3508 +PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
 71.3509 +   png_uint_32 length));
 71.3510 +PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
 71.3511 +PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
 71.3512 +PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
 71.3513 +   png_bytep buffer, png_size_t buffer_length));
 71.3514 +PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
 71.3515 +PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
 71.3516 +   png_bytep buffer, png_size_t buffer_length));
 71.3517 +PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
 71.3518 +PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
 71.3519 +   png_infop info_ptr, png_uint_32 length));
 71.3520 +PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
 71.3521 +   png_infop info_ptr));
 71.3522 +PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
 71.3523 +   png_infop info_ptr));
 71.3524 +PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
 71.3525 +PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
 71.3526 +   png_infop info_ptr));
 71.3527 +PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
 71.3528 +   png_infop info_ptr));
 71.3529 +PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
 71.3530 +#if defined(PNG_READ_tEXt_SUPPORTED)
 71.3531 +PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
 71.3532 +   png_infop info_ptr, png_uint_32 length));
 71.3533 +PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
 71.3534 +   png_infop info_ptr));
 71.3535 +#endif
 71.3536 +#if defined(PNG_READ_zTXt_SUPPORTED)
 71.3537 +PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
 71.3538 +   png_infop info_ptr, png_uint_32 length));
 71.3539 +PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
 71.3540 +   png_infop info_ptr));
 71.3541 +#endif
 71.3542 +#if defined(PNG_READ_iTXt_SUPPORTED)
 71.3543 +PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
 71.3544 +   png_infop info_ptr, png_uint_32 length));
 71.3545 +PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
 71.3546 +   png_infop info_ptr));
 71.3547 +#endif
 71.3548 +
 71.3549 +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
 71.3550 +
 71.3551 +#ifdef PNG_MNG_FEATURES_SUPPORTED
 71.3552 +PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
 71.3553 +   png_bytep row));
 71.3554 +PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
 71.3555 +   png_bytep row));
 71.3556 +#endif
 71.3557 +
 71.3558 +#if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
 71.3559 +#if defined(PNG_MMX_CODE_SUPPORTED)
 71.3560 +/* png.c */ /* PRIVATE */
 71.3561 +PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
 71.3562 +#endif
 71.3563 +#endif
 71.3564 +
 71.3565 +#if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
 71.3566 +PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
 71.3567 +png_infop info_ptr));
 71.3568 +
 71.3569 +PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
 71.3570 +png_infop info_ptr));
 71.3571 +
 71.3572 +PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
 71.3573 +png_infop info_ptr));
 71.3574 +
 71.3575 +PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
 71.3576 +png_infop info_ptr));
 71.3577 +
 71.3578 +PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
 71.3579 +png_infop info_ptr));
 71.3580 +
 71.3581 +#if defined(PNG_pHYs_SUPPORTED)
 71.3582 +PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
 71.3583 +png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
 71.3584 +#endif /* PNG_pHYs_SUPPORTED */
 71.3585 +#endif  /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
 71.3586 +
 71.3587 +/* Read the chunk header (length + type name) */
 71.3588 +PNG_EXTERN png_uint_32 png_read_chunk_header PNGARG((png_structp png_ptr));
 71.3589 +
 71.3590 +/* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
 71.3591 +
 71.3592 +#endif /* PNG_INTERNAL */
 71.3593 +
 71.3594 +#ifdef __cplusplus
 71.3595 +}
 71.3596 +#endif
 71.3597 +
 71.3598 +#endif /* PNG_VERSION_INFO_ONLY */
 71.3599 +/* do not put anything past this line */
 71.3600 +#endif /* PNG_H */
    72.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    72.2 +++ b/libs/libpng/pngconf.h	Thu Sep 08 06:28:38 2011 +0300
    72.3 @@ -0,0 +1,1481 @@
    72.4 +
    72.5 +/* pngconf.h - machine configurable file for libpng
    72.6 + *
    72.7 + * libpng version 1.2.33 - October 31, 2008
    72.8 + * For conditions of distribution and use, see copyright notice in png.h
    72.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   72.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   72.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   72.12 + */
   72.13 +
   72.14 +/* Any machine specific code is near the front of this file, so if you
   72.15 + * are configuring libpng for a machine, you may want to read the section
   72.16 + * starting here down to where it starts to typedef png_color, png_text,
   72.17 + * and png_info.
   72.18 + */
   72.19 +
   72.20 +#ifndef PNGCONF_H
   72.21 +#define PNGCONF_H
   72.22 +
   72.23 +#define PNG_1_2_X
   72.24 +
   72.25 +/* 
   72.26 + * PNG_USER_CONFIG has to be defined on the compiler command line. This
   72.27 + * includes the resource compiler for Windows DLL configurations.
   72.28 + */
   72.29 +#ifdef PNG_USER_CONFIG
   72.30 +#  ifndef PNG_USER_PRIVATEBUILD
   72.31 +#    define PNG_USER_PRIVATEBUILD
   72.32 +#  endif
   72.33 +#include "pngusr.h"
   72.34 +#endif
   72.35 +
   72.36 +/* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
   72.37 +#ifdef PNG_CONFIGURE_LIBPNG
   72.38 +#ifdef HAVE_CONFIG_H
   72.39 +#include "config.h"
   72.40 +#endif
   72.41 +#endif
   72.42 +
   72.43 +/*
   72.44 + * Added at libpng-1.2.8
   72.45 + *  
   72.46 + * If you create a private DLL you need to define in "pngusr.h" the followings:
   72.47 + * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
   72.48 + *        the DLL was built>
   72.49 + *  e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
   72.50 + * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
   72.51 + *        distinguish your DLL from those of the official release. These
   72.52 + *        correspond to the trailing letters that come after the version
   72.53 + *        number and must match your private DLL name>
   72.54 + *  e.g. // private DLL "libpng13gx.dll"
   72.55 + *       #define PNG_USER_DLLFNAME_POSTFIX "gx"
   72.56 + * 
   72.57 + * The following macros are also at your disposal if you want to complete the 
   72.58 + * DLL VERSIONINFO structure.
   72.59 + * - PNG_USER_VERSIONINFO_COMMENTS
   72.60 + * - PNG_USER_VERSIONINFO_COMPANYNAME
   72.61 + * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
   72.62 + */
   72.63 +
   72.64 +#ifdef __STDC__
   72.65 +#ifdef SPECIALBUILD
   72.66 +#  pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
   72.67 + are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
   72.68 +#endif
   72.69 +
   72.70 +#ifdef PRIVATEBUILD
   72.71 +# pragma message("PRIVATEBUILD is deprecated.\
   72.72 + Use PNG_USER_PRIVATEBUILD instead.")
   72.73 +# define PNG_USER_PRIVATEBUILD PRIVATEBUILD
   72.74 +#endif
   72.75 +#endif /* __STDC__ */
   72.76 +
   72.77 +#ifndef PNG_VERSION_INFO_ONLY
   72.78 +
   72.79 +/* End of material added to libpng-1.2.8 */
   72.80 +
   72.81 +/* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
   72.82 +   Restored at libpng-1.2.21 */
   72.83 +#if !defined(PNG_NO_WARN_UNINITIALIZED_ROW) && \
   72.84 +    !defined(PNG_WARN_UNINITIALIZED_ROW)
   72.85 +#  define PNG_WARN_UNINITIALIZED_ROW 1
   72.86 +#endif
   72.87 +/* End of material added at libpng-1.2.19/1.2.21 */
   72.88 +
   72.89 +/* This is the size of the compression buffer, and thus the size of
   72.90 + * an IDAT chunk.  Make this whatever size you feel is best for your
   72.91 + * machine.  One of these will be allocated per png_struct.  When this
   72.92 + * is full, it writes the data to the disk, and does some other
   72.93 + * calculations.  Making this an extremely small size will slow
   72.94 + * the library down, but you may want to experiment to determine
   72.95 + * where it becomes significant, if you are concerned with memory
   72.96 + * usage.  Note that zlib allocates at least 32Kb also.  For readers,
   72.97 + * this describes the size of the buffer available to read the data in.
   72.98 + * Unless this gets smaller than the size of a row (compressed),
   72.99 + * it should not make much difference how big this is.
  72.100 + */
  72.101 +
  72.102 +#ifndef PNG_ZBUF_SIZE
  72.103 +#  define PNG_ZBUF_SIZE 8192
  72.104 +#endif
  72.105 +
  72.106 +/* Enable if you want a write-only libpng */
  72.107 +
  72.108 +#ifndef PNG_NO_READ_SUPPORTED
  72.109 +#  define PNG_READ_SUPPORTED
  72.110 +#endif
  72.111 +
  72.112 +/* Enable if you want a read-only libpng */
  72.113 +
  72.114 +#ifndef PNG_NO_WRITE_SUPPORTED
  72.115 +#  define PNG_WRITE_SUPPORTED
  72.116 +#endif
  72.117 +
  72.118 +/* Enabled by default in 1.2.0.  You can disable this if you don't need to
  72.119 +   support PNGs that are embedded in MNG datastreams */
  72.120 +#if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  72.121 +#  ifndef PNG_MNG_FEATURES_SUPPORTED
  72.122 +#    define PNG_MNG_FEATURES_SUPPORTED
  72.123 +#  endif
  72.124 +#endif
  72.125 +
  72.126 +#ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  72.127 +#  ifndef PNG_FLOATING_POINT_SUPPORTED
  72.128 +#    define PNG_FLOATING_POINT_SUPPORTED
  72.129 +#  endif
  72.130 +#endif
  72.131 +
  72.132 +/* If you are running on a machine where you cannot allocate more
  72.133 + * than 64K of memory at once, uncomment this.  While libpng will not
  72.134 + * normally need that much memory in a chunk (unless you load up a very
  72.135 + * large file), zlib needs to know how big of a chunk it can use, and
  72.136 + * libpng thus makes sure to check any memory allocation to verify it
  72.137 + * will fit into memory.
  72.138 +#define PNG_MAX_MALLOC_64K
  72.139 + */
  72.140 +#if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  72.141 +#  define PNG_MAX_MALLOC_64K
  72.142 +#endif
  72.143 +
  72.144 +/* Special munging to support doing things the 'cygwin' way:
  72.145 + * 'Normal' png-on-win32 defines/defaults:
  72.146 + *   PNG_BUILD_DLL -- building dll
  72.147 + *   PNG_USE_DLL   -- building an application, linking to dll
  72.148 + *   (no define)   -- building static library, or building an
  72.149 + *                    application and linking to the static lib
  72.150 + * 'Cygwin' defines/defaults:
  72.151 + *   PNG_BUILD_DLL -- (ignored) building the dll
  72.152 + *   (no define)   -- (ignored) building an application, linking to the dll
  72.153 + *   PNG_STATIC    -- (ignored) building the static lib, or building an 
  72.154 + *                    application that links to the static lib.
  72.155 + *   ALL_STATIC    -- (ignored) building various static libs, or building an 
  72.156 + *                    application that links to the static libs.
  72.157 + * Thus,
  72.158 + * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  72.159 + * this bit of #ifdefs will define the 'correct' config variables based on
  72.160 + * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  72.161 + * unnecessary.
  72.162 + *
  72.163 + * Also, the precedence order is:
  72.164 + *   ALL_STATIC (since we can't #undef something outside our namespace)
  72.165 + *   PNG_BUILD_DLL
  72.166 + *   PNG_STATIC
  72.167 + *   (nothing) == PNG_USE_DLL
  72.168 + * 
  72.169 + * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  72.170 + *   of auto-import in binutils, we no longer need to worry about 
  72.171 + *   __declspec(dllexport) / __declspec(dllimport) and friends.  Therefore,
  72.172 + *   we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  72.173 + *   to __declspec() stuff.  However, we DO need to worry about 
  72.174 + *   PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  72.175 + *   such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  72.176 + */
  72.177 +#if defined(__CYGWIN__)
  72.178 +#  if defined(ALL_STATIC)
  72.179 +#    if defined(PNG_BUILD_DLL)
  72.180 +#      undef PNG_BUILD_DLL
  72.181 +#    endif
  72.182 +#    if defined(PNG_USE_DLL)
  72.183 +#      undef PNG_USE_DLL
  72.184 +#    endif
  72.185 +#    if defined(PNG_DLL)
  72.186 +#      undef PNG_DLL
  72.187 +#    endif
  72.188 +#    if !defined(PNG_STATIC)
  72.189 +#      define PNG_STATIC
  72.190 +#    endif
  72.191 +#  else
  72.192 +#    if defined (PNG_BUILD_DLL)
  72.193 +#      if defined(PNG_STATIC)
  72.194 +#        undef PNG_STATIC
  72.195 +#      endif
  72.196 +#      if defined(PNG_USE_DLL)
  72.197 +#        undef PNG_USE_DLL
  72.198 +#      endif
  72.199 +#      if !defined(PNG_DLL)
  72.200 +#        define PNG_DLL
  72.201 +#      endif
  72.202 +#    else
  72.203 +#      if defined(PNG_STATIC)
  72.204 +#        if defined(PNG_USE_DLL)
  72.205 +#          undef PNG_USE_DLL
  72.206 +#        endif
  72.207 +#        if defined(PNG_DLL)
  72.208 +#          undef PNG_DLL
  72.209 +#        endif
  72.210 +#      else
  72.211 +#        if !defined(PNG_USE_DLL)
  72.212 +#          define PNG_USE_DLL
  72.213 +#        endif
  72.214 +#        if !defined(PNG_DLL)
  72.215 +#          define PNG_DLL
  72.216 +#        endif
  72.217 +#      endif  
  72.218 +#    endif  
  72.219 +#  endif
  72.220 +#endif
  72.221 +
  72.222 +/* This protects us against compilers that run on a windowing system
  72.223 + * and thus don't have or would rather us not use the stdio types:
  72.224 + * stdin, stdout, and stderr.  The only one currently used is stderr
  72.225 + * in png_error() and png_warning().  #defining PNG_NO_CONSOLE_IO will
  72.226 + * prevent these from being compiled and used. #defining PNG_NO_STDIO
  72.227 + * will also prevent these, plus will prevent the entire set of stdio
  72.228 + * macros and functions (FILE *, printf, etc.) from being compiled and used,
  72.229 + * unless (PNG_DEBUG > 0) has been #defined.
  72.230 + *
  72.231 + * #define PNG_NO_CONSOLE_IO
  72.232 + * #define PNG_NO_STDIO
  72.233 + */
  72.234 +
  72.235 +#if defined(_WIN32_WCE)
  72.236 +#  include <windows.h>
  72.237 +   /* Console I/O functions are not supported on WindowsCE */
  72.238 +#  define PNG_NO_CONSOLE_IO
  72.239 +#  ifdef PNG_DEBUG
  72.240 +#    undef PNG_DEBUG
  72.241 +#  endif
  72.242 +#endif
  72.243 +
  72.244 +#ifdef PNG_BUILD_DLL
  72.245 +#  ifndef PNG_CONSOLE_IO_SUPPORTED
  72.246 +#    ifndef PNG_NO_CONSOLE_IO
  72.247 +#      define PNG_NO_CONSOLE_IO
  72.248 +#    endif
  72.249 +#  endif
  72.250 +#endif
  72.251 +
  72.252 +#  ifdef PNG_NO_STDIO
  72.253 +#    ifndef PNG_NO_CONSOLE_IO
  72.254 +#      define PNG_NO_CONSOLE_IO
  72.255 +#    endif
  72.256 +#    ifdef PNG_DEBUG
  72.257 +#      if (PNG_DEBUG > 0)
  72.258 +#        include <stdio.h>
  72.259 +#      endif
  72.260 +#    endif
  72.261 +#  else
  72.262 +#    if !defined(_WIN32_WCE)
  72.263 +/* "stdio.h" functions are not supported on WindowsCE */
  72.264 +#      include <stdio.h>
  72.265 +#    endif
  72.266 +#  endif
  72.267 +
  72.268 +/* This macro protects us against machines that don't have function
  72.269 + * prototypes (ie K&R style headers).  If your compiler does not handle
  72.270 + * function prototypes, define this macro and use the included ansi2knr.
  72.271 + * I've always been able to use _NO_PROTO as the indicator, but you may
  72.272 + * need to drag the empty declaration out in front of here, or change the
  72.273 + * ifdef to suit your own needs.
  72.274 + */
  72.275 +#ifndef PNGARG
  72.276 +
  72.277 +#ifdef OF /* zlib prototype munger */
  72.278 +#  define PNGARG(arglist) OF(arglist)
  72.279 +#else
  72.280 +
  72.281 +#ifdef _NO_PROTO
  72.282 +#  define PNGARG(arglist) ()
  72.283 +#  ifndef PNG_TYPECAST_NULL
  72.284 +#     define PNG_TYPECAST_NULL
  72.285 +#  endif
  72.286 +#else
  72.287 +#  define PNGARG(arglist) arglist
  72.288 +#endif /* _NO_PROTO */
  72.289 +
  72.290 +
  72.291 +#endif /* OF */
  72.292 +
  72.293 +#endif /* PNGARG */
  72.294 +
  72.295 +/* Try to determine if we are compiling on a Mac.  Note that testing for
  72.296 + * just __MWERKS__ is not good enough, because the Codewarrior is now used
  72.297 + * on non-Mac platforms.
  72.298 + */
  72.299 +#ifndef MACOS
  72.300 +#  if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  72.301 +      defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  72.302 +#    define MACOS
  72.303 +#  endif
  72.304 +#endif
  72.305 +
  72.306 +/* enough people need this for various reasons to include it here */
  72.307 +#if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  72.308 +#  include <sys/types.h>
  72.309 +#endif
  72.310 +
  72.311 +#if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  72.312 +#  define PNG_SETJMP_SUPPORTED
  72.313 +#endif
  72.314 +
  72.315 +#ifdef PNG_SETJMP_SUPPORTED
  72.316 +/* This is an attempt to force a single setjmp behaviour on Linux.  If
  72.317 + * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  72.318 + */
  72.319 +
  72.320 +#  ifdef __linux__
  72.321 +#    ifdef _BSD_SOURCE
  72.322 +#      define PNG_SAVE_BSD_SOURCE
  72.323 +#      undef _BSD_SOURCE
  72.324 +#    endif
  72.325 +#    ifdef _SETJMP_H
  72.326 +     /* If you encounter a compiler error here, see the explanation
  72.327 +      * near the end of INSTALL.
  72.328 +      */
  72.329 +         __pngconf.h__ already includes setjmp.h;
  72.330 +         __dont__ include it again.;
  72.331 +#    endif
  72.332 +#  endif /* __linux__ */
  72.333 +
  72.334 +   /* include setjmp.h for error handling */
  72.335 +#  include <setjmp.h>
  72.336 +
  72.337 +#  ifdef __linux__
  72.338 +#    ifdef PNG_SAVE_BSD_SOURCE
  72.339 +#      ifndef _BSD_SOURCE
  72.340 +#        define _BSD_SOURCE
  72.341 +#      endif
  72.342 +#      undef PNG_SAVE_BSD_SOURCE
  72.343 +#    endif
  72.344 +#  endif /* __linux__ */
  72.345 +#endif /* PNG_SETJMP_SUPPORTED */
  72.346 +
  72.347 +#ifdef BSD
  72.348 +#  include <strings.h>
  72.349 +#else
  72.350 +#  include <string.h>
  72.351 +#endif
  72.352 +
  72.353 +/* Other defines for things like memory and the like can go here.  */
  72.354 +#ifdef PNG_INTERNAL
  72.355 +
  72.356 +#include <stdlib.h>
  72.357 +
  72.358 +/* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  72.359 + * aren't usually used outside the library (as far as I know), so it is
  72.360 + * debatable if they should be exported at all.  In the future, when it is
  72.361 + * possible to have run-time registry of chunk-handling functions, some of
  72.362 + * these will be made available again.
  72.363 +#define PNG_EXTERN extern
  72.364 + */
  72.365 +#define PNG_EXTERN
  72.366 +
  72.367 +/* Other defines specific to compilers can go here.  Try to keep
  72.368 + * them inside an appropriate ifdef/endif pair for portability.
  72.369 + */
  72.370 +
  72.371 +#if defined(PNG_FLOATING_POINT_SUPPORTED)
  72.372 +#  if defined(MACOS)
  72.373 +     /* We need to check that <math.h> hasn't already been included earlier
  72.374 +      * as it seems it doesn't agree with <fp.h>, yet we should really use
  72.375 +      * <fp.h> if possible.
  72.376 +      */
  72.377 +#    if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  72.378 +#      include <fp.h>
  72.379 +#    endif
  72.380 +#  else
  72.381 +#    include <math.h>
  72.382 +#  endif
  72.383 +#  if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  72.384 +     /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  72.385 +      * MATH=68881
  72.386 +      */
  72.387 +#    include <m68881.h>
  72.388 +#  endif
  72.389 +#endif
  72.390 +
  72.391 +/* Codewarrior on NT has linking problems without this. */
  72.392 +#if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  72.393 +#  define PNG_ALWAYS_EXTERN
  72.394 +#endif
  72.395 +
  72.396 +/* This provides the non-ANSI (far) memory allocation routines. */
  72.397 +#if defined(__TURBOC__) && defined(__MSDOS__)
  72.398 +#  include <mem.h>
  72.399 +#  include <alloc.h>
  72.400 +#endif
  72.401 +
  72.402 +/* I have no idea why is this necessary... */
  72.403 +#if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  72.404 +    defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  72.405 +#  include <malloc.h>
  72.406 +#endif
  72.407 +
  72.408 +/* This controls how fine the dithering gets.  As this allocates
  72.409 + * a largish chunk of memory (32K), those who are not as concerned
  72.410 + * with dithering quality can decrease some or all of these.
  72.411 + */
  72.412 +#ifndef PNG_DITHER_RED_BITS
  72.413 +#  define PNG_DITHER_RED_BITS 5
  72.414 +#endif
  72.415 +#ifndef PNG_DITHER_GREEN_BITS
  72.416 +#  define PNG_DITHER_GREEN_BITS 5
  72.417 +#endif
  72.418 +#ifndef PNG_DITHER_BLUE_BITS
  72.419 +#  define PNG_DITHER_BLUE_BITS 5
  72.420 +#endif
  72.421 +
  72.422 +/* This controls how fine the gamma correction becomes when you
  72.423 + * are only interested in 8 bits anyway.  Increasing this value
  72.424 + * results in more memory being used, and more pow() functions
  72.425 + * being called to fill in the gamma tables.  Don't set this value
  72.426 + * less then 8, and even that may not work (I haven't tested it).
  72.427 + */
  72.428 +
  72.429 +#ifndef PNG_MAX_GAMMA_8
  72.430 +#  define PNG_MAX_GAMMA_8 11
  72.431 +#endif
  72.432 +
  72.433 +/* This controls how much a difference in gamma we can tolerate before
  72.434 + * we actually start doing gamma conversion.
  72.435 + */
  72.436 +#ifndef PNG_GAMMA_THRESHOLD
  72.437 +#  define PNG_GAMMA_THRESHOLD 0.05
  72.438 +#endif
  72.439 +
  72.440 +#endif /* PNG_INTERNAL */
  72.441 +
  72.442 +/* The following uses const char * instead of char * for error
  72.443 + * and warning message functions, so some compilers won't complain.
  72.444 + * If you do not want to use const, define PNG_NO_CONST here.
  72.445 + */
  72.446 +
  72.447 +#ifndef PNG_NO_CONST
  72.448 +#  define PNG_CONST const
  72.449 +#else
  72.450 +#  define PNG_CONST
  72.451 +#endif
  72.452 +
  72.453 +/* The following defines give you the ability to remove code from the
  72.454 + * library that you will not be using.  I wish I could figure out how to
  72.455 + * automate this, but I can't do that without making it seriously hard
  72.456 + * on the users.  So if you are not using an ability, change the #define
  72.457 + * to and #undef, and that part of the library will not be compiled.  If
  72.458 + * your linker can't find a function, you may want to make sure the
  72.459 + * ability is defined here.  Some of these depend upon some others being
  72.460 + * defined.  I haven't figured out all the interactions here, so you may
  72.461 + * have to experiment awhile to get everything to compile.  If you are
  72.462 + * creating or using a shared library, you probably shouldn't touch this,
  72.463 + * as it will affect the size of the structures, and this will cause bad
  72.464 + * things to happen if the library and/or application ever change.
  72.465 + */
  72.466 +
  72.467 +/* Any features you will not be using can be undef'ed here */
  72.468 +
  72.469 +/* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  72.470 + * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  72.471 + * on the compile line, then pick and choose which ones to define without
  72.472 + * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  72.473 + * if you only want to have a png-compliant reader/writer but don't need
  72.474 + * any of the extra transformations.  This saves about 80 kbytes in a
  72.475 + * typical installation of the library. (PNG_NO_* form added in version
  72.476 + * 1.0.1c, for consistency)
  72.477 + */
  72.478 +
  72.479 +/* The size of the png_text structure changed in libpng-1.0.6 when
  72.480 + * iTXt support was added.  iTXt support was turned off by default through
  72.481 + * libpng-1.2.x, to support old apps that malloc the png_text structure
  72.482 + * instead of calling png_set_text() and letting libpng malloc it.  It
  72.483 + * was turned on by default in libpng-1.3.0.
  72.484 + */
  72.485 +
  72.486 +#if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  72.487 +#  ifndef PNG_NO_iTXt_SUPPORTED
  72.488 +#    define PNG_NO_iTXt_SUPPORTED
  72.489 +#  endif
  72.490 +#  ifndef PNG_NO_READ_iTXt
  72.491 +#    define PNG_NO_READ_iTXt
  72.492 +#  endif
  72.493 +#  ifndef PNG_NO_WRITE_iTXt
  72.494 +#    define PNG_NO_WRITE_iTXt
  72.495 +#  endif
  72.496 +#endif
  72.497 +
  72.498 +#if !defined(PNG_NO_iTXt_SUPPORTED)
  72.499 +#  if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  72.500 +#    define PNG_READ_iTXt
  72.501 +#  endif
  72.502 +#  if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  72.503 +#    define PNG_WRITE_iTXt
  72.504 +#  endif
  72.505 +#endif
  72.506 +
  72.507 +/* The following support, added after version 1.0.0, can be turned off here en
  72.508 + * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  72.509 + * with old applications that require the length of png_struct and png_info
  72.510 + * to remain unchanged.
  72.511 + */
  72.512 +
  72.513 +#ifdef PNG_LEGACY_SUPPORTED
  72.514 +#  define PNG_NO_FREE_ME
  72.515 +#  define PNG_NO_READ_UNKNOWN_CHUNKS
  72.516 +#  define PNG_NO_WRITE_UNKNOWN_CHUNKS
  72.517 +#  define PNG_NO_READ_USER_CHUNKS
  72.518 +#  define PNG_NO_READ_iCCP
  72.519 +#  define PNG_NO_WRITE_iCCP
  72.520 +#  define PNG_NO_READ_iTXt
  72.521 +#  define PNG_NO_WRITE_iTXt
  72.522 +#  define PNG_NO_READ_sCAL
  72.523 +#  define PNG_NO_WRITE_sCAL
  72.524 +#  define PNG_NO_READ_sPLT
  72.525 +#  define PNG_NO_WRITE_sPLT
  72.526 +#  define PNG_NO_INFO_IMAGE
  72.527 +#  define PNG_NO_READ_RGB_TO_GRAY
  72.528 +#  define PNG_NO_READ_USER_TRANSFORM
  72.529 +#  define PNG_NO_WRITE_USER_TRANSFORM
  72.530 +#  define PNG_NO_USER_MEM
  72.531 +#  define PNG_NO_READ_EMPTY_PLTE
  72.532 +#  define PNG_NO_MNG_FEATURES
  72.533 +#  define PNG_NO_FIXED_POINT_SUPPORTED
  72.534 +#endif
  72.535 +
  72.536 +/* Ignore attempt to turn off both floating and fixed point support */
  72.537 +#if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  72.538 +    !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  72.539 +#  define PNG_FIXED_POINT_SUPPORTED
  72.540 +#endif
  72.541 +
  72.542 +#ifndef PNG_NO_FREE_ME
  72.543 +#  define PNG_FREE_ME_SUPPORTED
  72.544 +#endif
  72.545 +
  72.546 +#if defined(PNG_READ_SUPPORTED)
  72.547 +
  72.548 +#if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  72.549 +      !defined(PNG_NO_READ_TRANSFORMS)
  72.550 +#  define PNG_READ_TRANSFORMS_SUPPORTED
  72.551 +#endif
  72.552 +
  72.553 +#ifdef PNG_READ_TRANSFORMS_SUPPORTED
  72.554 +#  ifndef PNG_NO_READ_EXPAND
  72.555 +#    define PNG_READ_EXPAND_SUPPORTED
  72.556 +#  endif
  72.557 +#  ifndef PNG_NO_READ_SHIFT
  72.558 +#    define PNG_READ_SHIFT_SUPPORTED
  72.559 +#  endif
  72.560 +#  ifndef PNG_NO_READ_PACK
  72.561 +#    define PNG_READ_PACK_SUPPORTED
  72.562 +#  endif
  72.563 +#  ifndef PNG_NO_READ_BGR
  72.564 +#    define PNG_READ_BGR_SUPPORTED
  72.565 +#  endif
  72.566 +#  ifndef PNG_NO_READ_SWAP
  72.567 +#    define PNG_READ_SWAP_SUPPORTED
  72.568 +#  endif
  72.569 +#  ifndef PNG_NO_READ_PACKSWAP
  72.570 +#    define PNG_READ_PACKSWAP_SUPPORTED
  72.571 +#  endif
  72.572 +#  ifndef PNG_NO_READ_INVERT
  72.573 +#    define PNG_READ_INVERT_SUPPORTED
  72.574 +#  endif
  72.575 +#  ifndef PNG_NO_READ_DITHER
  72.576 +#    define PNG_READ_DITHER_SUPPORTED
  72.577 +#  endif
  72.578 +#  ifndef PNG_NO_READ_BACKGROUND
  72.579 +#    define PNG_READ_BACKGROUND_SUPPORTED
  72.580 +#  endif
  72.581 +#  ifndef PNG_NO_READ_16_TO_8
  72.582 +#    define PNG_READ_16_TO_8_SUPPORTED
  72.583 +#  endif
  72.584 +#  ifndef PNG_NO_READ_FILLER
  72.585 +#    define PNG_READ_FILLER_SUPPORTED
  72.586 +#  endif
  72.587 +#  ifndef PNG_NO_READ_GAMMA
  72.588 +#    define PNG_READ_GAMMA_SUPPORTED
  72.589 +#  endif
  72.590 +#  ifndef PNG_NO_READ_GRAY_TO_RGB
  72.591 +#    define PNG_READ_GRAY_TO_RGB_SUPPORTED
  72.592 +#  endif
  72.593 +#  ifndef PNG_NO_READ_SWAP_ALPHA
  72.594 +#    define PNG_READ_SWAP_ALPHA_SUPPORTED
  72.595 +#  endif
  72.596 +#  ifndef PNG_NO_READ_INVERT_ALPHA
  72.597 +#    define PNG_READ_INVERT_ALPHA_SUPPORTED
  72.598 +#  endif
  72.599 +#  ifndef PNG_NO_READ_STRIP_ALPHA
  72.600 +#    define PNG_READ_STRIP_ALPHA_SUPPORTED
  72.601 +#  endif
  72.602 +#  ifndef PNG_NO_READ_USER_TRANSFORM
  72.603 +#    define PNG_READ_USER_TRANSFORM_SUPPORTED
  72.604 +#  endif
  72.605 +#  ifndef PNG_NO_READ_RGB_TO_GRAY
  72.606 +#    define PNG_READ_RGB_TO_GRAY_SUPPORTED
  72.607 +#  endif
  72.608 +#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  72.609 +
  72.610 +#if !defined(PNG_NO_PROGRESSIVE_READ) && \
  72.611 + !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive   */
  72.612 +#  define PNG_PROGRESSIVE_READ_SUPPORTED  /* reading.  This is not talking */
  72.613 +#endif                            /* about interlacing capability!  You'll */
  72.614 +           /* still have interlacing unless you change the following line: */
  72.615 +
  72.616 +#define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  72.617 +
  72.618 +#ifndef PNG_NO_READ_COMPOSITE_NODIV
  72.619 +#  ifndef PNG_NO_READ_COMPOSITED_NODIV  /* libpng-1.0.x misspelling */
  72.620 +#    define PNG_READ_COMPOSITE_NODIV_SUPPORTED  /* well tested on Intel, SGI */
  72.621 +#  endif
  72.622 +#endif
  72.623 +
  72.624 +#if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  72.625 +/* Deprecated, will be removed from version 2.0.0.
  72.626 +   Use PNG_MNG_FEATURES_SUPPORTED instead. */
  72.627 +#ifndef PNG_NO_READ_EMPTY_PLTE
  72.628 +#  define PNG_READ_EMPTY_PLTE_SUPPORTED
  72.629 +#endif
  72.630 +#endif
  72.631 +
  72.632 +#endif /* PNG_READ_SUPPORTED */
  72.633 +
  72.634 +#if defined(PNG_WRITE_SUPPORTED)
  72.635 +
  72.636 +# if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  72.637 +    !defined(PNG_NO_WRITE_TRANSFORMS)
  72.638 +#  define PNG_WRITE_TRANSFORMS_SUPPORTED
  72.639 +#endif
  72.640 +
  72.641 +#ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  72.642 +#  ifndef PNG_NO_WRITE_SHIFT
  72.643 +#    define PNG_WRITE_SHIFT_SUPPORTED
  72.644 +#  endif
  72.645 +#  ifndef PNG_NO_WRITE_PACK
  72.646 +#    define PNG_WRITE_PACK_SUPPORTED
  72.647 +#  endif
  72.648 +#  ifndef PNG_NO_WRITE_BGR
  72.649 +#    define PNG_WRITE_BGR_SUPPORTED
  72.650 +#  endif
  72.651 +#  ifndef PNG_NO_WRITE_SWAP
  72.652 +#    define PNG_WRITE_SWAP_SUPPORTED
  72.653 +#  endif
  72.654 +#  ifndef PNG_NO_WRITE_PACKSWAP
  72.655 +#    define PNG_WRITE_PACKSWAP_SUPPORTED
  72.656 +#  endif
  72.657 +#  ifndef PNG_NO_WRITE_INVERT
  72.658 +#    define PNG_WRITE_INVERT_SUPPORTED
  72.659 +#  endif
  72.660 +#  ifndef PNG_NO_WRITE_FILLER
  72.661 +#    define PNG_WRITE_FILLER_SUPPORTED   /* same as WRITE_STRIP_ALPHA */
  72.662 +#  endif
  72.663 +#  ifndef PNG_NO_WRITE_SWAP_ALPHA
  72.664 +#    define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  72.665 +#  endif
  72.666 +#  ifndef PNG_NO_WRITE_INVERT_ALPHA
  72.667 +#    define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  72.668 +#  endif
  72.669 +#  ifndef PNG_NO_WRITE_USER_TRANSFORM
  72.670 +#    define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  72.671 +#  endif
  72.672 +#endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  72.673 +
  72.674 +#if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  72.675 +    !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  72.676 +#define PNG_WRITE_INTERLACING_SUPPORTED  /* not required for PNG-compliant
  72.677 +                                            encoders, but can cause trouble
  72.678 +                                            if left undefined */
  72.679 +#endif
  72.680 +
  72.681 +#if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  72.682 +    !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  72.683 +     defined(PNG_FLOATING_POINT_SUPPORTED)
  72.684 +#  define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  72.685 +#endif
  72.686 +
  72.687 +#ifndef PNG_NO_WRITE_FLUSH
  72.688 +#  define PNG_WRITE_FLUSH_SUPPORTED
  72.689 +#endif
  72.690 +
  72.691 +#if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  72.692 +/* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  72.693 +#ifndef PNG_NO_WRITE_EMPTY_PLTE
  72.694 +#  define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  72.695 +#endif
  72.696 +#endif
  72.697 +
  72.698 +#endif /* PNG_WRITE_SUPPORTED */
  72.699 +
  72.700 +#ifndef PNG_1_0_X
  72.701 +#  ifndef PNG_NO_ERROR_NUMBERS
  72.702 +#    define PNG_ERROR_NUMBERS_SUPPORTED
  72.703 +#  endif
  72.704 +#endif /* PNG_1_0_X */
  72.705 +
  72.706 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  72.707 +    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  72.708 +#  ifndef PNG_NO_USER_TRANSFORM_PTR
  72.709 +#    define PNG_USER_TRANSFORM_PTR_SUPPORTED
  72.710 +#  endif
  72.711 +#endif
  72.712 +
  72.713 +#ifndef PNG_NO_STDIO
  72.714 +#  define PNG_TIME_RFC1123_SUPPORTED
  72.715 +#endif
  72.716 +
  72.717 +/* This adds extra functions in pngget.c for accessing data from the
  72.718 + * info pointer (added in version 0.99)
  72.719 + * png_get_image_width()
  72.720 + * png_get_image_height()
  72.721 + * png_get_bit_depth()
  72.722 + * png_get_color_type()
  72.723 + * png_get_compression_type()
  72.724 + * png_get_filter_type()
  72.725 + * png_get_interlace_type()
  72.726 + * png_get_pixel_aspect_ratio()
  72.727 + * png_get_pixels_per_meter()
  72.728 + * png_get_x_offset_pixels()
  72.729 + * png_get_y_offset_pixels()
  72.730 + * png_get_x_offset_microns()
  72.731 + * png_get_y_offset_microns()
  72.732 + */
  72.733 +#if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  72.734 +#  define PNG_EASY_ACCESS_SUPPORTED
  72.735 +#endif
  72.736 +
  72.737 +/* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0 
  72.738 + * and removed from version 1.2.20.  The following will be removed
  72.739 + * from libpng-1.4.0
  72.740 +*/
  72.741 +
  72.742 +#if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  72.743 +#  ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  72.744 +#    define PNG_OPTIMIZED_CODE_SUPPORTED
  72.745 +#  endif
  72.746 +#endif
  72.747 +
  72.748 +#if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  72.749 +#  ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  72.750 +#    define PNG_ASSEMBLER_CODE_SUPPORTED
  72.751 +#  endif
  72.752 +
  72.753 +#  if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  72.754 +     /* work around 64-bit gcc compiler bugs in gcc-3.x */
  72.755 +#    if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  72.756 +#      define PNG_NO_MMX_CODE
  72.757 +#    endif
  72.758 +#  endif
  72.759 +
  72.760 +#  if defined(__APPLE__)
  72.761 +#    if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  72.762 +#      define PNG_NO_MMX_CODE
  72.763 +#    endif
  72.764 +#  endif
  72.765 +
  72.766 +#  if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  72.767 +#    if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  72.768 +#      define PNG_NO_MMX_CODE
  72.769 +#    endif
  72.770 +#  endif
  72.771 +
  72.772 +#  if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  72.773 +#    define PNG_MMX_CODE_SUPPORTED
  72.774 +#  endif
  72.775 +
  72.776 +#endif
  72.777 +/* end of obsolete code to be removed from libpng-1.4.0 */
  72.778 +
  72.779 +#if !defined(PNG_1_0_X)
  72.780 +#if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  72.781 +#  define PNG_USER_MEM_SUPPORTED
  72.782 +#endif
  72.783 +#endif /* PNG_1_0_X */
  72.784 +
  72.785 +/* Added at libpng-1.2.6 */
  72.786 +#if !defined(PNG_1_0_X)
  72.787 +#ifndef PNG_SET_USER_LIMITS_SUPPORTED
  72.788 +#if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  72.789 +#  define PNG_SET_USER_LIMITS_SUPPORTED
  72.790 +#endif
  72.791 +#endif
  72.792 +#endif /* PNG_1_0_X */
  72.793 +
  72.794 +/* Added at libpng-1.0.16 and 1.2.6.  To accept all valid PNGS no matter
  72.795 + * how large, set these limits to 0x7fffffffL
  72.796 + */
  72.797 +#ifndef PNG_USER_WIDTH_MAX
  72.798 +#  define PNG_USER_WIDTH_MAX 1000000L
  72.799 +#endif
  72.800 +#ifndef PNG_USER_HEIGHT_MAX
  72.801 +#  define PNG_USER_HEIGHT_MAX 1000000L
  72.802 +#endif
  72.803 +
  72.804 +/* These are currently experimental features, define them if you want */
  72.805 +
  72.806 +/* very little testing */
  72.807 +/*
  72.808 +#ifdef PNG_READ_SUPPORTED
  72.809 +#  ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  72.810 +#    define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  72.811 +#  endif
  72.812 +#endif
  72.813 +*/
  72.814 +
  72.815 +/* This is only for PowerPC big-endian and 680x0 systems */
  72.816 +/* some testing */
  72.817 +/*
  72.818 +#ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  72.819 +#  define PNG_READ_BIG_ENDIAN_SUPPORTED
  72.820 +#endif
  72.821 +*/
  72.822 +
  72.823 +/* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  72.824 +/*
  72.825 +#define PNG_NO_POINTER_INDEXING
  72.826 +*/
  72.827 +
  72.828 +/* These functions are turned off by default, as they will be phased out. */
  72.829 +/*
  72.830 +#define  PNG_USELESS_TESTS_SUPPORTED
  72.831 +#define  PNG_CORRECT_PALETTE_SUPPORTED
  72.832 +*/
  72.833 +
  72.834 +/* Any chunks you are not interested in, you can undef here.  The
  72.835 + * ones that allocate memory may be expecially important (hIST,
  72.836 + * tEXt, zTXt, tRNS, pCAL).  Others will just save time and make png_info
  72.837 + * a bit smaller.
  72.838 + */
  72.839 +
  72.840 +#if defined(PNG_READ_SUPPORTED) && \
  72.841 +    !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  72.842 +    !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  72.843 +#  define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  72.844 +#endif
  72.845 +
  72.846 +#if defined(PNG_WRITE_SUPPORTED) && \
  72.847 +    !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  72.848 +    !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  72.849 +#  define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  72.850 +#endif
  72.851 +
  72.852 +#ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  72.853 +
  72.854 +#ifdef PNG_NO_READ_TEXT
  72.855 +#  define PNG_NO_READ_iTXt
  72.856 +#  define PNG_NO_READ_tEXt
  72.857 +#  define PNG_NO_READ_zTXt
  72.858 +#endif
  72.859 +#ifndef PNG_NO_READ_bKGD
  72.860 +#  define PNG_READ_bKGD_SUPPORTED
  72.861 +#  define PNG_bKGD_SUPPORTED
  72.862 +#endif
  72.863 +#ifndef PNG_NO_READ_cHRM
  72.864 +#  define PNG_READ_cHRM_SUPPORTED
  72.865 +#  define PNG_cHRM_SUPPORTED
  72.866 +#endif
  72.867 +#ifndef PNG_NO_READ_gAMA
  72.868 +#  define PNG_READ_gAMA_SUPPORTED
  72.869 +#  define PNG_gAMA_SUPPORTED
  72.870 +#endif
  72.871 +#ifndef PNG_NO_READ_hIST
  72.872 +#  define PNG_READ_hIST_SUPPORTED
  72.873 +#  define PNG_hIST_SUPPORTED
  72.874 +#endif
  72.875 +#ifndef PNG_NO_READ_iCCP
  72.876 +#  define PNG_READ_iCCP_SUPPORTED
  72.877 +#  define PNG_iCCP_SUPPORTED
  72.878 +#endif
  72.879 +#ifndef PNG_NO_READ_iTXt
  72.880 +#  ifndef PNG_READ_iTXt_SUPPORTED
  72.881 +#    define PNG_READ_iTXt_SUPPORTED
  72.882 +#  endif
  72.883 +#  ifndef PNG_iTXt_SUPPORTED
  72.884 +#    define PNG_iTXt_SUPPORTED
  72.885 +#  endif
  72.886 +#endif
  72.887 +#ifndef PNG_NO_READ_oFFs
  72.888 +#  define PNG_READ_oFFs_SUPPORTED
  72.889 +#  define PNG_oFFs_SUPPORTED
  72.890 +#endif
  72.891 +#ifndef PNG_NO_READ_pCAL
  72.892 +#  define PNG_READ_pCAL_SUPPORTED
  72.893 +#  define PNG_pCAL_SUPPORTED
  72.894 +#endif
  72.895 +#ifndef PNG_NO_READ_sCAL
  72.896 +#  define PNG_READ_sCAL_SUPPORTED
  72.897 +#  define PNG_sCAL_SUPPORTED
  72.898 +#endif
  72.899 +#ifndef PNG_NO_READ_pHYs
  72.900 +#  define PNG_READ_pHYs_SUPPORTED
  72.901 +#  define PNG_pHYs_SUPPORTED
  72.902 +#endif
  72.903 +#ifndef PNG_NO_READ_sBIT
  72.904 +#  define PNG_READ_sBIT_SUPPORTED
  72.905 +#  define PNG_sBIT_SUPPORTED
  72.906 +#endif
  72.907 +#ifndef PNG_NO_READ_sPLT
  72.908 +#  define PNG_READ_sPLT_SUPPORTED
  72.909 +#  define PNG_sPLT_SUPPORTED
  72.910 +#endif
  72.911 +#ifndef PNG_NO_READ_sRGB
  72.912 +#  define PNG_READ_sRGB_SUPPORTED
  72.913 +#  define PNG_sRGB_SUPPORTED
  72.914 +#endif
  72.915 +#ifndef PNG_NO_READ_tEXt
  72.916 +#  define PNG_READ_tEXt_SUPPORTED
  72.917 +#  define PNG_tEXt_SUPPORTED
  72.918 +#endif
  72.919 +#ifndef PNG_NO_READ_tIME
  72.920 +#  define PNG_READ_tIME_SUPPORTED
  72.921 +#  define PNG_tIME_SUPPORTED
  72.922 +#endif
  72.923 +#ifndef PNG_NO_READ_tRNS
  72.924 +#  define PNG_READ_tRNS_SUPPORTED
  72.925 +#  define PNG_tRNS_SUPPORTED
  72.926 +#endif
  72.927 +#ifndef PNG_NO_READ_zTXt
  72.928 +#  define PNG_READ_zTXt_SUPPORTED
  72.929 +#  define PNG_zTXt_SUPPORTED
  72.930 +#endif
  72.931 +#ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  72.932 +#  define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  72.933 +#  ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  72.934 +#    define PNG_UNKNOWN_CHUNKS_SUPPORTED
  72.935 +#  endif
  72.936 +#  ifndef PNG_NO_HANDLE_AS_UNKNOWN
  72.937 +#    define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  72.938 +#  endif
  72.939 +#endif
  72.940 +#if !defined(PNG_NO_READ_USER_CHUNKS) && \
  72.941 +     defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  72.942 +#  define PNG_READ_USER_CHUNKS_SUPPORTED
  72.943 +#  define PNG_USER_CHUNKS_SUPPORTED
  72.944 +#  ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  72.945 +#    undef PNG_NO_READ_UNKNOWN_CHUNKS
  72.946 +#  endif
  72.947 +#  ifdef PNG_NO_HANDLE_AS_UNKNOWN
  72.948 +#    undef PNG_NO_HANDLE_AS_UNKNOWN
  72.949 +#  endif
  72.950 +#endif
  72.951 +#ifndef PNG_NO_READ_OPT_PLTE
  72.952 +#  define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  72.953 +#endif                      /* optional PLTE chunk in RGB and RGBA images */
  72.954 +#if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  72.955 +    defined(PNG_READ_zTXt_SUPPORTED)
  72.956 +#  define PNG_READ_TEXT_SUPPORTED
  72.957 +#  define PNG_TEXT_SUPPORTED
  72.958 +#endif
  72.959 +
  72.960 +#endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  72.961 +
  72.962 +#ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  72.963 +
  72.964 +#ifdef PNG_NO_WRITE_TEXT
  72.965 +#  define PNG_NO_WRITE_iTXt
  72.966 +#  define PNG_NO_WRITE_tEXt
  72.967 +#  define PNG_NO_WRITE_zTXt
  72.968 +#endif
  72.969 +#ifndef PNG_NO_WRITE_bKGD
  72.970 +#  define PNG_WRITE_bKGD_SUPPORTED
  72.971 +#  ifndef PNG_bKGD_SUPPORTED
  72.972 +#    define PNG_bKGD_SUPPORTED
  72.973 +#  endif
  72.974 +#endif
  72.975 +#ifndef PNG_NO_WRITE_cHRM
  72.976 +#  define PNG_WRITE_cHRM_SUPPORTED
  72.977 +#  ifndef PNG_cHRM_SUPPORTED
  72.978 +#    define PNG_cHRM_SUPPORTED
  72.979 +#  endif
  72.980 +#endif
  72.981 +#ifndef PNG_NO_WRITE_gAMA
  72.982 +#  define PNG_WRITE_gAMA_SUPPORTED
  72.983 +#  ifndef PNG_gAMA_SUPPORTED
  72.984 +#    define PNG_gAMA_SUPPORTED
  72.985 +#  endif
  72.986 +#endif
  72.987 +#ifndef PNG_NO_WRITE_hIST
  72.988 +#  define PNG_WRITE_hIST_SUPPORTED
  72.989 +#  ifndef PNG_hIST_SUPPORTED
  72.990 +#    define PNG_hIST_SUPPORTED
  72.991 +#  endif
  72.992 +#endif
  72.993 +#ifndef PNG_NO_WRITE_iCCP
  72.994 +#  define PNG_WRITE_iCCP_SUPPORTED
  72.995 +#  ifndef PNG_iCCP_SUPPORTED
  72.996 +#    define PNG_iCCP_SUPPORTED
  72.997 +#  endif
  72.998 +#endif
  72.999 +#ifndef PNG_NO_WRITE_iTXt
 72.1000 +#  ifndef PNG_WRITE_iTXt_SUPPORTED
 72.1001 +#    define PNG_WRITE_iTXt_SUPPORTED
 72.1002 +#  endif
 72.1003 +#  ifndef PNG_iTXt_SUPPORTED
 72.1004 +#    define PNG_iTXt_SUPPORTED
 72.1005 +#  endif
 72.1006 +#endif
 72.1007 +#ifndef PNG_NO_WRITE_oFFs
 72.1008 +#  define PNG_WRITE_oFFs_SUPPORTED
 72.1009 +#  ifndef PNG_oFFs_SUPPORTED
 72.1010 +#    define PNG_oFFs_SUPPORTED
 72.1011 +#  endif
 72.1012 +#endif
 72.1013 +#ifndef PNG_NO_WRITE_pCAL
 72.1014 +#  define PNG_WRITE_pCAL_SUPPORTED
 72.1015 +#  ifndef PNG_pCAL_SUPPORTED
 72.1016 +#    define PNG_pCAL_SUPPORTED
 72.1017 +#  endif
 72.1018 +#endif
 72.1019 +#ifndef PNG_NO_WRITE_sCAL
 72.1020 +#  define PNG_WRITE_sCAL_SUPPORTED
 72.1021 +#  ifndef PNG_sCAL_SUPPORTED
 72.1022 +#    define PNG_sCAL_SUPPORTED
 72.1023 +#  endif
 72.1024 +#endif
 72.1025 +#ifndef PNG_NO_WRITE_pHYs
 72.1026 +#  define PNG_WRITE_pHYs_SUPPORTED
 72.1027 +#  ifndef PNG_pHYs_SUPPORTED
 72.1028 +#    define PNG_pHYs_SUPPORTED
 72.1029 +#  endif
 72.1030 +#endif
 72.1031 +#ifndef PNG_NO_WRITE_sBIT
 72.1032 +#  define PNG_WRITE_sBIT_SUPPORTED
 72.1033 +#  ifndef PNG_sBIT_SUPPORTED
 72.1034 +#    define PNG_sBIT_SUPPORTED
 72.1035 +#  endif
 72.1036 +#endif
 72.1037 +#ifndef PNG_NO_WRITE_sPLT
 72.1038 +#  define PNG_WRITE_sPLT_SUPPORTED
 72.1039 +#  ifndef PNG_sPLT_SUPPORTED
 72.1040 +#    define PNG_sPLT_SUPPORTED
 72.1041 +#  endif
 72.1042 +#endif
 72.1043 +#ifndef PNG_NO_WRITE_sRGB
 72.1044 +#  define PNG_WRITE_sRGB_SUPPORTED
 72.1045 +#  ifndef PNG_sRGB_SUPPORTED
 72.1046 +#    define PNG_sRGB_SUPPORTED
 72.1047 +#  endif
 72.1048 +#endif
 72.1049 +#ifndef PNG_NO_WRITE_tEXt
 72.1050 +#  define PNG_WRITE_tEXt_SUPPORTED
 72.1051 +#  ifndef PNG_tEXt_SUPPORTED
 72.1052 +#    define PNG_tEXt_SUPPORTED
 72.1053 +#  endif
 72.1054 +#endif
 72.1055 +#ifndef PNG_NO_WRITE_tIME
 72.1056 +#  define PNG_WRITE_tIME_SUPPORTED
 72.1057 +#  ifndef PNG_tIME_SUPPORTED
 72.1058 +#    define PNG_tIME_SUPPORTED
 72.1059 +#  endif
 72.1060 +#endif
 72.1061 +#ifndef PNG_NO_WRITE_tRNS
 72.1062 +#  define PNG_WRITE_tRNS_SUPPORTED
 72.1063 +#  ifndef PNG_tRNS_SUPPORTED
 72.1064 +#    define PNG_tRNS_SUPPORTED
 72.1065 +#  endif
 72.1066 +#endif
 72.1067 +#ifndef PNG_NO_WRITE_zTXt
 72.1068 +#  define PNG_WRITE_zTXt_SUPPORTED
 72.1069 +#  ifndef PNG_zTXt_SUPPORTED
 72.1070 +#    define PNG_zTXt_SUPPORTED
 72.1071 +#  endif
 72.1072 +#endif
 72.1073 +#ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
 72.1074 +#  define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
 72.1075 +#  ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
 72.1076 +#    define PNG_UNKNOWN_CHUNKS_SUPPORTED
 72.1077 +#  endif
 72.1078 +#  ifndef PNG_NO_HANDLE_AS_UNKNOWN
 72.1079 +#     ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 72.1080 +#       define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 72.1081 +#     endif
 72.1082 +#  endif
 72.1083 +#endif
 72.1084 +#if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
 72.1085 +    defined(PNG_WRITE_zTXt_SUPPORTED)
 72.1086 +#  define PNG_WRITE_TEXT_SUPPORTED
 72.1087 +#  ifndef PNG_TEXT_SUPPORTED
 72.1088 +#    define PNG_TEXT_SUPPORTED
 72.1089 +#  endif
 72.1090 +#endif
 72.1091 +
 72.1092 +#endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
 72.1093 +
 72.1094 +/* Turn this off to disable png_read_png() and
 72.1095 + * png_write_png() and leave the row_pointers member
 72.1096 + * out of the info structure.
 72.1097 + */
 72.1098 +#ifndef PNG_NO_INFO_IMAGE
 72.1099 +#  define PNG_INFO_IMAGE_SUPPORTED
 72.1100 +#endif
 72.1101 +
 72.1102 +/* need the time information for reading tIME chunks */
 72.1103 +#if defined(PNG_tIME_SUPPORTED)
 72.1104 +#  if !defined(_WIN32_WCE)
 72.1105 +     /* "time.h" functions are not supported on WindowsCE */
 72.1106 +#    include <time.h>
 72.1107 +#  endif
 72.1108 +#endif
 72.1109 +
 72.1110 +/* Some typedefs to get us started.  These should be safe on most of the
 72.1111 + * common platforms.  The typedefs should be at least as large as the
 72.1112 + * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
 72.1113 + * don't have to be exactly that size.  Some compilers dislike passing
 72.1114 + * unsigned shorts as function parameters, so you may be better off using
 72.1115 + * unsigned int for png_uint_16.  Likewise, for 64-bit systems, you may
 72.1116 + * want to have unsigned int for png_uint_32 instead of unsigned long.
 72.1117 + */
 72.1118 +
 72.1119 +typedef unsigned long png_uint_32;
 72.1120 +typedef long png_int_32;
 72.1121 +typedef unsigned short png_uint_16;
 72.1122 +typedef short png_int_16;
 72.1123 +typedef unsigned char png_byte;
 72.1124 +
 72.1125 +/* This is usually size_t.  It is typedef'ed just in case you need it to
 72.1126 +   change (I'm not sure if you will or not, so I thought I'd be safe) */
 72.1127 +#ifdef PNG_SIZE_T
 72.1128 +   typedef PNG_SIZE_T png_size_t;
 72.1129 +#  define png_sizeof(x) png_convert_size(sizeof(x))
 72.1130 +#else
 72.1131 +   typedef size_t png_size_t;
 72.1132 +#  define png_sizeof(x) sizeof(x)
 72.1133 +#endif
 72.1134 +
 72.1135 +/* The following is needed for medium model support.  It cannot be in the
 72.1136 + * PNG_INTERNAL section.  Needs modification for other compilers besides
 72.1137 + * MSC.  Model independent support declares all arrays and pointers to be
 72.1138 + * large using the far keyword.  The zlib version used must also support
 72.1139 + * model independent data.  As of version zlib 1.0.4, the necessary changes
 72.1140 + * have been made in zlib.  The USE_FAR_KEYWORD define triggers other
 72.1141 + * changes that are needed. (Tim Wegner)
 72.1142 + */
 72.1143 +
 72.1144 +/* Separate compiler dependencies (problem here is that zlib.h always
 72.1145 +   defines FAR. (SJT) */
 72.1146 +#ifdef __BORLANDC__
 72.1147 +#  if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
 72.1148 +#    define LDATA 1
 72.1149 +#  else
 72.1150 +#    define LDATA 0
 72.1151 +#  endif
 72.1152 +   /* GRR:  why is Cygwin in here?  Cygwin is not Borland C... */
 72.1153 +#  if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
 72.1154 +#    define PNG_MAX_MALLOC_64K
 72.1155 +#    if (LDATA != 1)
 72.1156 +#      ifndef FAR
 72.1157 +#        define FAR __far
 72.1158 +#      endif
 72.1159 +#      define USE_FAR_KEYWORD
 72.1160 +#    endif   /* LDATA != 1 */
 72.1161 +     /* Possibly useful for moving data out of default segment.
 72.1162 +      * Uncomment it if you want. Could also define FARDATA as
 72.1163 +      * const if your compiler supports it. (SJT)
 72.1164 +#    define FARDATA FAR
 72.1165 +      */
 72.1166 +#  endif  /* __WIN32__, __FLAT__, __CYGWIN__ */
 72.1167 +#endif   /* __BORLANDC__ */
 72.1168 +
 72.1169 +
 72.1170 +/* Suggest testing for specific compiler first before testing for
 72.1171 + * FAR.  The Watcom compiler defines both __MEDIUM__ and M_I86MM,
 72.1172 + * making reliance oncertain keywords suspect. (SJT)
 72.1173 + */
 72.1174 +
 72.1175 +/* MSC Medium model */
 72.1176 +#if defined(FAR)
 72.1177 +#  if defined(M_I86MM)
 72.1178 +#    define USE_FAR_KEYWORD
 72.1179 +#    define FARDATA FAR
 72.1180 +#    include <dos.h>
 72.1181 +#  endif
 72.1182 +#endif
 72.1183 +
 72.1184 +/* SJT: default case */
 72.1185 +#ifndef FAR
 72.1186 +#  define FAR
 72.1187 +#endif
 72.1188 +
 72.1189 +/* At this point FAR is always defined */
 72.1190 +#ifndef FARDATA
 72.1191 +#  define FARDATA
 72.1192 +#endif
 72.1193 +
 72.1194 +/* Typedef for floating-point numbers that are converted
 72.1195 +   to fixed-point with a multiple of 100,000, e.g., int_gamma */
 72.1196 +typedef png_int_32 png_fixed_point;
 72.1197 +
 72.1198 +/* Add typedefs for pointers */
 72.1199 +typedef void            FAR * png_voidp;
 72.1200 +typedef png_byte        FAR * png_bytep;
 72.1201 +typedef png_uint_32     FAR * png_uint_32p;
 72.1202 +typedef png_int_32      FAR * png_int_32p;
 72.1203 +typedef png_uint_16     FAR * png_uint_16p;
 72.1204 +typedef png_int_16      FAR * png_int_16p;
 72.1205 +typedef PNG_CONST char  FAR * png_const_charp;
 72.1206 +typedef char            FAR * png_charp;
 72.1207 +typedef png_fixed_point FAR * png_fixed_point_p;
 72.1208 +
 72.1209 +#ifndef PNG_NO_STDIO
 72.1210 +#if defined(_WIN32_WCE)
 72.1211 +typedef HANDLE                png_FILE_p;
 72.1212 +#else
 72.1213 +typedef FILE                * png_FILE_p;
 72.1214 +#endif
 72.1215 +#endif
 72.1216 +
 72.1217 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 72.1218 +typedef double          FAR * png_doublep;
 72.1219 +#endif
 72.1220 +
 72.1221 +/* Pointers to pointers; i.e. arrays */
 72.1222 +typedef png_byte        FAR * FAR * png_bytepp;
 72.1223 +typedef png_uint_32     FAR * FAR * png_uint_32pp;
 72.1224 +typedef png_int_32      FAR * FAR * png_int_32pp;
 72.1225 +typedef png_uint_16     FAR * FAR * png_uint_16pp;
 72.1226 +typedef png_int_16      FAR * FAR * png_int_16pp;
 72.1227 +typedef PNG_CONST char  FAR * FAR * png_const_charpp;
 72.1228 +typedef char            FAR * FAR * png_charpp;
 72.1229 +typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
 72.1230 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 72.1231 +typedef double          FAR * FAR * png_doublepp;
 72.1232 +#endif
 72.1233 +
 72.1234 +/* Pointers to pointers to pointers; i.e., pointer to array */
 72.1235 +typedef char            FAR * FAR * FAR * png_charppp;
 72.1236 +
 72.1237 +#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
 72.1238 +/* SPC -  Is this stuff deprecated? */
 72.1239 +/* It'll be removed as of libpng-1.3.0 - GR-P */
 72.1240 +/* libpng typedefs for types in zlib. If zlib changes
 72.1241 + * or another compression library is used, then change these.
 72.1242 + * Eliminates need to change all the source files.
 72.1243 + */
 72.1244 +typedef charf *         png_zcharp;
 72.1245 +typedef charf * FAR *   png_zcharpp;
 72.1246 +typedef z_stream FAR *  png_zstreamp;
 72.1247 +#endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
 72.1248 +
 72.1249 +/*
 72.1250 + * Define PNG_BUILD_DLL if the module being built is a Windows
 72.1251 + * LIBPNG DLL.
 72.1252 + *
 72.1253 + * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
 72.1254 + * It is equivalent to Microsoft predefined macro _DLL that is
 72.1255 + * automatically defined when you compile using the share
 72.1256 + * version of the CRT (C Run-Time library)
 72.1257 + *
 72.1258 + * The cygwin mods make this behavior a little different:
 72.1259 + * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
 72.1260 + * Define PNG_STATIC if you are building a static library for use with cygwin,
 72.1261 + *   -or- if you are building an application that you want to link to the
 72.1262 + *   static library.
 72.1263 + * PNG_USE_DLL is defined by default (no user action needed) unless one of
 72.1264 + *   the other flags is defined.
 72.1265 + */
 72.1266 +
 72.1267 +#if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
 72.1268 +#  define PNG_DLL
 72.1269 +#endif
 72.1270 +/* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
 72.1271 + * When building a static lib, default to no GLOBAL ARRAYS, but allow
 72.1272 + * command-line override
 72.1273 + */
 72.1274 +#if defined(__CYGWIN__)
 72.1275 +#  if !defined(PNG_STATIC)
 72.1276 +#    if defined(PNG_USE_GLOBAL_ARRAYS)
 72.1277 +#      undef PNG_USE_GLOBAL_ARRAYS
 72.1278 +#    endif
 72.1279 +#    if !defined(PNG_USE_LOCAL_ARRAYS)
 72.1280 +#      define PNG_USE_LOCAL_ARRAYS
 72.1281 +#    endif
 72.1282 +#  else
 72.1283 +#    if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
 72.1284 +#      if defined(PNG_USE_GLOBAL_ARRAYS)
 72.1285 +#        undef PNG_USE_GLOBAL_ARRAYS
 72.1286 +#      endif
 72.1287 +#    endif
 72.1288 +#  endif
 72.1289 +#  if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
 72.1290 +#    define PNG_USE_LOCAL_ARRAYS
 72.1291 +#  endif
 72.1292 +#endif
 72.1293 +
 72.1294 +/* Do not use global arrays (helps with building DLL's)
 72.1295 + * They are no longer used in libpng itself, since version 1.0.5c,
 72.1296 + * but might be required for some pre-1.0.5c applications.
 72.1297 + */
 72.1298 +#if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
 72.1299 +#  if defined(PNG_NO_GLOBAL_ARRAYS) || \
 72.1300 +      (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
 72.1301 +#    define PNG_USE_LOCAL_ARRAYS
 72.1302 +#  else
 72.1303 +#    define PNG_USE_GLOBAL_ARRAYS
 72.1304 +#  endif
 72.1305 +#endif
 72.1306 +
 72.1307 +#if defined(__CYGWIN__)
 72.1308 +#  undef PNGAPI
 72.1309 +#  define PNGAPI __cdecl
 72.1310 +#  undef PNG_IMPEXP
 72.1311 +#  define PNG_IMPEXP
 72.1312 +#endif  
 72.1313 +
 72.1314 +/* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
 72.1315 + * you may get warnings regarding the linkage of png_zalloc and png_zfree.
 72.1316 + * Don't ignore those warnings; you must also reset the default calling
 72.1317 + * convention in your compiler to match your PNGAPI, and you must build
 72.1318 + * zlib and your applications the same way you build libpng.
 72.1319 + */
 72.1320 +
 72.1321 +#if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
 72.1322 +#  ifndef PNG_NO_MODULEDEF
 72.1323 +#    define PNG_NO_MODULEDEF
 72.1324 +#  endif
 72.1325 +#endif
 72.1326 +
 72.1327 +#if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
 72.1328 +#  define PNG_IMPEXP
 72.1329 +#endif
 72.1330 +
 72.1331 +#if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
 72.1332 +    (( defined(_Windows) || defined(_WINDOWS) || \
 72.1333 +       defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
 72.1334 +
 72.1335 +#  ifndef PNGAPI
 72.1336 +#     if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
 72.1337 +#        define PNGAPI __cdecl
 72.1338 +#     else
 72.1339 +#        define PNGAPI _cdecl
 72.1340 +#     endif
 72.1341 +#  endif
 72.1342 +
 72.1343 +#  if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
 72.1344 +       0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
 72.1345 +#     define PNG_IMPEXP
 72.1346 +#  endif
 72.1347 +
 72.1348 +#  if !defined(PNG_IMPEXP)
 72.1349 +
 72.1350 +#     define PNG_EXPORT_TYPE1(type,symbol)  PNG_IMPEXP type PNGAPI symbol
 72.1351 +#     define PNG_EXPORT_TYPE2(type,symbol)  type PNG_IMPEXP PNGAPI symbol
 72.1352 +
 72.1353 +      /* Borland/Microsoft */
 72.1354 +#     if defined(_MSC_VER) || defined(__BORLANDC__)
 72.1355 +#        if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
 72.1356 +#           define PNG_EXPORT PNG_EXPORT_TYPE1
 72.1357 +#        else
 72.1358 +#           define PNG_EXPORT PNG_EXPORT_TYPE2
 72.1359 +#           if defined(PNG_BUILD_DLL)
 72.1360 +#              define PNG_IMPEXP __export
 72.1361 +#           else
 72.1362 +#              define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
 72.1363 +                                                 VC++ */
 72.1364 +#           endif                             /* Exists in Borland C++ for
 72.1365 +                                                 C++ classes (== huge) */
 72.1366 +#        endif
 72.1367 +#     endif
 72.1368 +
 72.1369 +#     if !defined(PNG_IMPEXP)
 72.1370 +#        if defined(PNG_BUILD_DLL)
 72.1371 +#           define PNG_IMPEXP __declspec(dllexport)
 72.1372 +#        else
 72.1373 +#           define PNG_IMPEXP __declspec(dllimport)
 72.1374 +#        endif
 72.1375 +#     endif
 72.1376 +#  endif  /* PNG_IMPEXP */
 72.1377 +#else /* !(DLL || non-cygwin WINDOWS) */
 72.1378 +#   if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
 72.1379 +#      ifndef PNGAPI
 72.1380 +#         define PNGAPI _System
 72.1381 +#      endif
 72.1382 +#   else
 72.1383 +#      if 0 /* ... other platforms, with other meanings */
 72.1384 +#      endif
 72.1385 +#   endif
 72.1386 +#endif
 72.1387 +
 72.1388 +#ifndef PNGAPI
 72.1389 +#  define PNGAPI
 72.1390 +#endif
 72.1391 +#ifndef PNG_IMPEXP
 72.1392 +#  define PNG_IMPEXP
 72.1393 +#endif
 72.1394 +
 72.1395 +#ifdef PNG_BUILDSYMS
 72.1396 +#  ifndef PNG_EXPORT
 72.1397 +#    define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
 72.1398 +#  endif
 72.1399 +#  ifdef PNG_USE_GLOBAL_ARRAYS
 72.1400 +#    ifndef PNG_EXPORT_VAR
 72.1401 +#      define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
 72.1402 +#    endif
 72.1403 +#  endif
 72.1404 +#endif
 72.1405 +
 72.1406 +#ifndef PNG_EXPORT
 72.1407 +#  define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
 72.1408 +#endif
 72.1409 +
 72.1410 +#ifdef PNG_USE_GLOBAL_ARRAYS
 72.1411 +#  ifndef PNG_EXPORT_VAR
 72.1412 +#    define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
 72.1413 +#  endif
 72.1414 +#endif
 72.1415 +
 72.1416 +/* User may want to use these so they are not in PNG_INTERNAL. Any library
 72.1417 + * functions that are passed far data must be model independent.
 72.1418 + */
 72.1419 +
 72.1420 +#ifndef PNG_ABORT
 72.1421 +#  define PNG_ABORT() abort()
 72.1422 +#endif
 72.1423 +
 72.1424 +#ifdef PNG_SETJMP_SUPPORTED
 72.1425 +#  define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
 72.1426 +#else
 72.1427 +#  define png_jmpbuf(png_ptr) \
 72.1428 +   (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
 72.1429 +#endif
 72.1430 +
 72.1431 +#if defined(USE_FAR_KEYWORD)  /* memory model independent fns */
 72.1432 +/* use this to make far-to-near assignments */
 72.1433 +#  define CHECK   1
 72.1434 +#  define NOCHECK 0
 72.1435 +#  define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
 72.1436 +#  define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
 72.1437 +#  define png_snprintf _fsnprintf   /* Added to v 1.2.19 */
 72.1438 +#  define png_strlen  _fstrlen
 72.1439 +#  define png_memcmp  _fmemcmp    /* SJT: added */
 72.1440 +#  define png_memcpy  _fmemcpy
 72.1441 +#  define png_memset  _fmemset
 72.1442 +#else /* use the usual functions */
 72.1443 +#  define CVT_PTR(ptr)         (ptr)
 72.1444 +#  define CVT_PTR_NOCHECK(ptr) (ptr)
 72.1445 +#  ifndef PNG_NO_SNPRINTF
 72.1446 +#    ifdef _MSC_VER
 72.1447 +#      define png_snprintf _snprintf   /* Added to v 1.2.19 */
 72.1448 +#      define png_snprintf2 _snprintf
 72.1449 +#      define png_snprintf6 _snprintf
 72.1450 +#    else
 72.1451 +#      define png_snprintf snprintf   /* Added to v 1.2.19 */
 72.1452 +#      define png_snprintf2 snprintf
 72.1453 +#      define png_snprintf6 snprintf
 72.1454 +#    endif
 72.1455 +#  else
 72.1456 +     /* You don't have or don't want to use snprintf().  Caution: Using
 72.1457 +      * sprintf instead of snprintf exposes your application to accidental
 72.1458 +      * or malevolent buffer overflows.  If you don't have snprintf()
 72.1459 +      * as a general rule you should provide one (you can get one from
 72.1460 +      * Portable OpenSSH). */
 72.1461 +#    define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
 72.1462 +#    define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
 72.1463 +#    define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
 72.1464 +        sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
 72.1465 +#  endif
 72.1466 +#  define png_strlen  strlen
 72.1467 +#  define png_memcmp  memcmp      /* SJT: added */
 72.1468 +#  define png_memcpy  memcpy
 72.1469 +#  define png_memset  memset
 72.1470 +#endif
 72.1471 +/* End of memory model independent support */
 72.1472 +
 72.1473 +/* Just a little check that someone hasn't tried to define something
 72.1474 + * contradictory.
 72.1475 + */
 72.1476 +#if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
 72.1477 +#  undef PNG_ZBUF_SIZE
 72.1478 +#  define PNG_ZBUF_SIZE 65536L
 72.1479 +#endif
 72.1480 +
 72.1481 +/* Added at libpng-1.2.8 */
 72.1482 +#endif /* PNG_VERSION_INFO_ONLY */
 72.1483 +
 72.1484 +#endif /* PNGCONF_H */
    73.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    73.2 +++ b/libs/libpng/pngerror.c	Thu Sep 08 06:28:38 2011 +0300
    73.3 @@ -0,0 +1,345 @@
    73.4 +
    73.5 +/* pngerror.c - stub functions for i/o and memory allocation
    73.6 + *
    73.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    73.8 + * For conditions of distribution and use, see copyright notice in png.h
    73.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   73.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   73.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   73.12 + *
   73.13 + * This file provides a location for all error handling.  Users who
   73.14 + * need special error handling are expected to write replacement functions
   73.15 + * and use png_set_error_fn() to use those functions.  See the instructions
   73.16 + * at each function.
   73.17 + */
   73.18 +
   73.19 +#define PNG_INTERNAL
   73.20 +#include "png.h"
   73.21 +#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
   73.22 +
   73.23 +static void /* PRIVATE */
   73.24 +png_default_error PNGARG((png_structp png_ptr,
   73.25 +  png_const_charp error_message));
   73.26 +#ifndef PNG_NO_WARNINGS
   73.27 +static void /* PRIVATE */
   73.28 +png_default_warning PNGARG((png_structp png_ptr,
   73.29 +  png_const_charp warning_message));
   73.30 +#endif /* PNG_NO_WARNINGS */
   73.31 +
   73.32 +/* This function is called whenever there is a fatal error.  This function
   73.33 + * should not be changed.  If there is a need to handle errors differently,
   73.34 + * you should supply a replacement error function and use png_set_error_fn()
   73.35 + * to replace the error function at run-time.
   73.36 + */
   73.37 +#ifndef PNG_NO_ERROR_TEXT
   73.38 +void PNGAPI
   73.39 +png_error(png_structp png_ptr, png_const_charp error_message)
   73.40 +{
   73.41 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
   73.42 +   char msg[16];
   73.43 +   if (png_ptr != NULL)
   73.44 +   {
   73.45 +     if (png_ptr->flags&
   73.46 +       (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
   73.47 +     {
   73.48 +       if (*error_message == '#')
   73.49 +       {
   73.50 +         /* Strip "#nnnn " from beginning of error message. */
   73.51 +           int offset;
   73.52 +           for (offset = 1; offset<15; offset++)
   73.53 +              if (error_message[offset] == ' ')
   73.54 +                  break;
   73.55 +           if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
   73.56 +           {
   73.57 +              int i;
   73.58 +              for (i = 0; i < offset - 1; i++)
   73.59 +                 msg[i] = error_message[i + 1];
   73.60 +              msg[i - 1] = '\0';
   73.61 +              error_message = msg;
   73.62 +           }
   73.63 +           else
   73.64 +              error_message += offset;
   73.65 +       }
   73.66 +       else
   73.67 +       {
   73.68 +           if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
   73.69 +           {
   73.70 +              msg[0] = '0';
   73.71 +              msg[1] = '\0';
   73.72 +              error_message = msg;
   73.73 +           }
   73.74 +       }
   73.75 +     }
   73.76 +   }
   73.77 +#endif
   73.78 +   if (png_ptr != NULL && png_ptr->error_fn != NULL)
   73.79 +      (*(png_ptr->error_fn))(png_ptr, error_message);
   73.80 +
   73.81 +   /* If the custom handler doesn't exist, or if it returns,
   73.82 +      use the default handler, which will not return. */
   73.83 +   png_default_error(png_ptr, error_message);
   73.84 +}
   73.85 +#else
   73.86 +void PNGAPI
   73.87 +png_err(png_structp png_ptr)
   73.88 +{
   73.89 +   if (png_ptr != NULL && png_ptr->error_fn != NULL)
   73.90 +      (*(png_ptr->error_fn))(png_ptr, '\0');
   73.91 +
   73.92 +   /* If the custom handler doesn't exist, or if it returns,
   73.93 +      use the default handler, which will not return. */
   73.94 +   png_default_error(png_ptr, '\0');
   73.95 +}
   73.96 +#endif /* PNG_NO_ERROR_TEXT */
   73.97 +
   73.98 +#ifndef PNG_NO_WARNINGS
   73.99 +/* This function is called whenever there is a non-fatal error.  This function
  73.100 + * should not be changed.  If there is a need to handle warnings differently,
  73.101 + * you should supply a replacement warning function and use
  73.102 + * png_set_error_fn() to replace the warning function at run-time.
  73.103 + */
  73.104 +void PNGAPI
  73.105 +png_warning(png_structp png_ptr, png_const_charp warning_message)
  73.106 +{
  73.107 +   int offset = 0;
  73.108 +   if (png_ptr != NULL)
  73.109 +   {
  73.110 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
  73.111 +   if (png_ptr->flags&
  73.112 +     (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  73.113 +#endif
  73.114 +     {
  73.115 +       if (*warning_message == '#')
  73.116 +       {
  73.117 +           for (offset = 1; offset < 15; offset++)
  73.118 +              if (warning_message[offset] == ' ')
  73.119 +                  break;
  73.120 +       }
  73.121 +     }
  73.122 +     if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  73.123 +        (*(png_ptr->warning_fn))(png_ptr, warning_message + offset);
  73.124 +   }
  73.125 +   else
  73.126 +      png_default_warning(png_ptr, warning_message + offset);
  73.127 +}
  73.128 +#endif /* PNG_NO_WARNINGS */
  73.129 +
  73.130 +
  73.131 +/* These utilities are used internally to build an error message that relates
  73.132 + * to the current chunk.  The chunk name comes from png_ptr->chunk_name,
  73.133 + * this is used to prefix the message.  The message is limited in length
  73.134 + * to 63 bytes, the name characters are output as hex digits wrapped in []
  73.135 + * if the character is invalid.
  73.136 + */
  73.137 +#define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  73.138 +static PNG_CONST char png_digit[16] = {
  73.139 +   '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  73.140 +   'A', 'B', 'C', 'D', 'E', 'F'
  73.141 +};
  73.142 +
  73.143 +#define PNG_MAX_ERROR_TEXT 64
  73.144 +
  73.145 +#if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  73.146 +static void /* PRIVATE */
  73.147 +png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  73.148 +   error_message)
  73.149 +{
  73.150 +   int iout = 0, iin = 0;
  73.151 +
  73.152 +   while (iin < 4)
  73.153 +   {
  73.154 +      int c = png_ptr->chunk_name[iin++];
  73.155 +      if (isnonalpha(c))
  73.156 +      {
  73.157 +         buffer[iout++] = '[';
  73.158 +         buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  73.159 +         buffer[iout++] = png_digit[c & 0x0f];
  73.160 +         buffer[iout++] = ']';
  73.161 +      }
  73.162 +      else
  73.163 +      {
  73.164 +         buffer[iout++] = (png_byte)c;
  73.165 +      }
  73.166 +   }
  73.167 +
  73.168 +   if (error_message == NULL)
  73.169 +      buffer[iout] = '\0';
  73.170 +   else
  73.171 +   {
  73.172 +      buffer[iout++] = ':';
  73.173 +      buffer[iout++] = ' ';
  73.174 +      png_memcpy(buffer + iout, error_message, PNG_MAX_ERROR_TEXT);
  73.175 +      buffer[iout + PNG_MAX_ERROR_TEXT - 1] = '\0';
  73.176 +   }
  73.177 +}
  73.178 +
  73.179 +#ifdef PNG_READ_SUPPORTED
  73.180 +void PNGAPI
  73.181 +png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  73.182 +{
  73.183 +   char msg[18+PNG_MAX_ERROR_TEXT];
  73.184 +   if (png_ptr == NULL)
  73.185 +     png_error(png_ptr, error_message);
  73.186 +   else
  73.187 +   {
  73.188 +     png_format_buffer(png_ptr, msg, error_message);
  73.189 +     png_error(png_ptr, msg);
  73.190 +   }
  73.191 +}
  73.192 +#endif /* PNG_READ_SUPPORTED */
  73.193 +#endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  73.194 +
  73.195 +#ifndef PNG_NO_WARNINGS
  73.196 +void PNGAPI
  73.197 +png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  73.198 +{
  73.199 +   char msg[18+PNG_MAX_ERROR_TEXT];
  73.200 +   if (png_ptr == NULL)
  73.201 +     png_warning(png_ptr, warning_message);
  73.202 +   else
  73.203 +   {
  73.204 +     png_format_buffer(png_ptr, msg, warning_message);
  73.205 +     png_warning(png_ptr, msg);
  73.206 +   }
  73.207 +}
  73.208 +#endif /* PNG_NO_WARNINGS */
  73.209 +
  73.210 +
  73.211 +/* This is the default error handling function.  Note that replacements for
  73.212 + * this function MUST NOT RETURN, or the program will likely crash.  This
  73.213 + * function is used by default, or if the program supplies NULL for the
  73.214 + * error function pointer in png_set_error_fn().
  73.215 + */
  73.216 +static void /* PRIVATE */
  73.217 +png_default_error(png_structp png_ptr, png_const_charp error_message)
  73.218 +{
  73.219 +#ifndef PNG_NO_CONSOLE_IO
  73.220 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
  73.221 +   if (*error_message == '#')
  73.222 +   {
  73.223 +     /* Strip "#nnnn " from beginning of warning message. */
  73.224 +     int offset;
  73.225 +     char error_number[16];
  73.226 +     for (offset = 0; offset<15; offset++)
  73.227 +     {
  73.228 +         error_number[offset] = error_message[offset + 1];
  73.229 +         if (error_message[offset] == ' ')
  73.230 +             break;
  73.231 +     }
  73.232 +     if ((offset > 1) && (offset < 15))
  73.233 +     {
  73.234 +       error_number[offset - 1] = '\0';
  73.235 +       fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  73.236 +          error_message + offset + 1);
  73.237 +     }
  73.238 +     else
  73.239 +       fprintf(stderr, "libpng error: %s, offset=%d\n", error_message, offset);
  73.240 +   }
  73.241 +   else
  73.242 +#endif
  73.243 +   fprintf(stderr, "libpng error: %s\n", error_message);
  73.244 +#endif
  73.245 +
  73.246 +#ifdef PNG_SETJMP_SUPPORTED
  73.247 +   if (png_ptr)
  73.248 +   {
  73.249 +#  ifdef USE_FAR_KEYWORD
  73.250 +   {
  73.251 +      jmp_buf jmpbuf;
  73.252 +      png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  73.253 +      longjmp(jmpbuf, 1);
  73.254 +   }
  73.255 +#  else
  73.256 +   longjmp(png_ptr->jmpbuf, 1);
  73.257 +#  endif
  73.258 +   }
  73.259 +#else
  73.260 +   PNG_ABORT();
  73.261 +#endif
  73.262 +#ifdef PNG_NO_CONSOLE_IO
  73.263 +   error_message = error_message; /* make compiler happy */
  73.264 +#endif
  73.265 +}
  73.266 +
  73.267 +#ifndef PNG_NO_WARNINGS
  73.268 +/* This function is called when there is a warning, but the library thinks
  73.269 + * it can continue anyway.  Replacement functions don't have to do anything
  73.270 + * here if you don't want them to.  In the default configuration, png_ptr is
  73.271 + * not used, but it is passed in case it may be useful.
  73.272 + */
  73.273 +static void /* PRIVATE */
  73.274 +png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  73.275 +{
  73.276 +#ifndef PNG_NO_CONSOLE_IO
  73.277 +#  ifdef PNG_ERROR_NUMBERS_SUPPORTED
  73.278 +   if (*warning_message == '#')
  73.279 +   {
  73.280 +     int offset;
  73.281 +     char warning_number[16];
  73.282 +     for (offset = 0; offset < 15; offset++)
  73.283 +     {
  73.284 +        warning_number[offset] = warning_message[offset + 1];
  73.285 +        if (warning_message[offset] == ' ')
  73.286 +            break;
  73.287 +     }
  73.288 +     if ((offset > 1) && (offset < 15))
  73.289 +     {
  73.290 +       warning_number[offset + 1] = '\0';
  73.291 +       fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  73.292 +          warning_message + offset);
  73.293 +     }
  73.294 +     else
  73.295 +       fprintf(stderr, "libpng warning: %s\n", warning_message);
  73.296 +   }
  73.297 +   else
  73.298 +#  endif
  73.299 +     fprintf(stderr, "libpng warning: %s\n", warning_message);
  73.300 +#else
  73.301 +   warning_message = warning_message; /* make compiler happy */
  73.302 +#endif
  73.303 +   png_ptr = png_ptr; /* make compiler happy */
  73.304 +}
  73.305 +#endif /* PNG_NO_WARNINGS */
  73.306 +
  73.307 +/* This function is called when the application wants to use another method
  73.308 + * of handling errors and warnings.  Note that the error function MUST NOT
  73.309 + * return to the calling routine or serious problems will occur.  The return
  73.310 + * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  73.311 + */
  73.312 +void PNGAPI
  73.313 +png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  73.314 +   png_error_ptr error_fn, png_error_ptr warning_fn)
  73.315 +{
  73.316 +   if (png_ptr == NULL)
  73.317 +      return;
  73.318 +   png_ptr->error_ptr = error_ptr;
  73.319 +   png_ptr->error_fn = error_fn;
  73.320 +   png_ptr->warning_fn = warning_fn;
  73.321 +}
  73.322 +
  73.323 +
  73.324 +/* This function returns a pointer to the error_ptr associated with the user
  73.325 + * functions.  The application should free any memory associated with this
  73.326 + * pointer before png_write_destroy and png_read_destroy are called.
  73.327 + */
  73.328 +png_voidp PNGAPI
  73.329 +png_get_error_ptr(png_structp png_ptr)
  73.330 +{
  73.331 +   if (png_ptr == NULL)
  73.332 +      return NULL;
  73.333 +   return ((png_voidp)png_ptr->error_ptr);
  73.334 +}
  73.335 +
  73.336 +
  73.337 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
  73.338 +void PNGAPI
  73.339 +png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  73.340 +{
  73.341 +   if (png_ptr != NULL)
  73.342 +   {
  73.343 +     png_ptr->flags &=
  73.344 +       ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  73.345 +   }
  73.346 +}
  73.347 +#endif
  73.348 +#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
    74.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    74.2 +++ b/libs/libpng/pnggccrd.c	Thu Sep 08 06:28:38 2011 +0300
    74.3 @@ -0,0 +1,103 @@
    74.4 +/* pnggccrd.c was removed from libpng-1.2.20. */
    74.5 +
    74.6 +/* This code snippet is for use by configure's compilation test. */
    74.7 +
    74.8 +#if (!defined _MSC_VER) && \
    74.9 +    defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \
   74.10 +    defined(PNG_MMX_CODE_SUPPORTED)
   74.11 +
   74.12 +int PNGAPI png_dummy_mmx_support(void);
   74.13 +
   74.14 +static int _mmx_supported = 2; // 0: no MMX; 1: MMX supported; 2: not tested
   74.15 +
   74.16 +int PNGAPI
   74.17 +png_dummy_mmx_support(void) __attribute__((noinline));
   74.18 +
   74.19 +int PNGAPI
   74.20 +png_dummy_mmx_support(void)
   74.21 +{
   74.22 +   int result;
   74.23 +#if defined(PNG_MMX_CODE_SUPPORTED)  // superfluous, but what the heck
   74.24 +    __asm__ __volatile__ (
   74.25 +#if defined(__x86_64__)
   74.26 +        "pushq %%rbx          \n\t"  // rbx gets clobbered by CPUID instruction
   74.27 +        "pushq %%rcx          \n\t"  // so does rcx...
   74.28 +        "pushq %%rdx          \n\t"  // ...and rdx (but rcx & rdx safe on Linux)
   74.29 +        "pushfq               \n\t"  // save Eflag to stack
   74.30 +        "popq %%rax           \n\t"  // get Eflag from stack into rax
   74.31 +        "movq %%rax, %%rcx    \n\t"  // make another copy of Eflag in rcx
   74.32 +        "xorl $0x200000, %%eax \n\t" // toggle ID bit in Eflag (i.e., bit 21)
   74.33 +        "pushq %%rax          \n\t"  // save modified Eflag back to stack
   74.34 +        "popfq                \n\t"  // restore modified value to Eflag reg
   74.35 +        "pushfq               \n\t"  // save Eflag to stack
   74.36 +        "popq %%rax           \n\t"  // get Eflag from stack
   74.37 +        "pushq %%rcx          \n\t"  // save original Eflag to stack
   74.38 +        "popfq                \n\t"  // restore original Eflag
   74.39 +#else
   74.40 +        "pushl %%ebx          \n\t"  // ebx gets clobbered by CPUID instruction
   74.41 +        "pushl %%ecx          \n\t"  // so does ecx...
   74.42 +        "pushl %%edx          \n\t"  // ...and edx (but ecx & edx safe on Linux)
   74.43 +        "pushfl               \n\t"  // save Eflag to stack
   74.44 +        "popl %%eax           \n\t"  // get Eflag from stack into eax
   74.45 +        "movl %%eax, %%ecx    \n\t"  // make another copy of Eflag in ecx
   74.46 +        "xorl $0x200000, %%eax \n\t" // toggle ID bit in Eflag (i.e., bit 21)
   74.47 +        "pushl %%eax          \n\t"  // save modified Eflag back to stack
   74.48 +        "popfl                \n\t"  // restore modified value to Eflag reg
   74.49 +        "pushfl               \n\t"  // save Eflag to stack
   74.50 +        "popl %%eax           \n\t"  // get Eflag from stack
   74.51 +        "pushl %%ecx          \n\t"  // save original Eflag to stack
   74.52 +        "popfl                \n\t"  // restore original Eflag
   74.53 +#endif
   74.54 +        "xorl %%ecx, %%eax    \n\t"  // compare new Eflag with original Eflag
   74.55 +        "jz 0f                \n\t"  // if same, CPUID instr. is not supported
   74.56 +
   74.57 +        "xorl %%eax, %%eax    \n\t"  // set eax to zero
   74.58 +//      ".byte  0x0f, 0xa2    \n\t"  // CPUID instruction (two-byte opcode)
   74.59 +        "cpuid                \n\t"  // get the CPU identification info
   74.60 +        "cmpl $1, %%eax       \n\t"  // make sure eax return non-zero value
   74.61 +        "jl 0f                \n\t"  // if eax is zero, MMX is not supported
   74.62 +
   74.63 +        "xorl %%eax, %%eax    \n\t"  // set eax to zero and...
   74.64 +        "incl %%eax           \n\t"  // ...increment eax to 1.  This pair is
   74.65 +                                     // faster than the instruction "mov eax, 1"
   74.66 +        "cpuid                \n\t"  // get the CPU identification info again
   74.67 +        "andl $0x800000, %%edx \n\t" // mask out all bits but MMX bit (23)
   74.68 +        "cmpl $0, %%edx       \n\t"  // 0 = MMX not supported
   74.69 +        "jz 0f                \n\t"  // non-zero = yes, MMX IS supported
   74.70 +
   74.71 +        "movl $1, %%eax       \n\t"  // set return value to 1
   74.72 +        "jmp  1f              \n\t"  // DONE:  have MMX support
   74.73 +
   74.74 +    "0:                       \n\t"  // .NOT_SUPPORTED: target label for jump instructions
   74.75 +        "movl $0, %%eax       \n\t"  // set return value to 0
   74.76 +    "1:                       \n\t"  // .RETURN: target label for jump instructions
   74.77 +#if defined(__x86_64__)
   74.78 +        "popq %%rdx           \n\t"  // restore rdx
   74.79 +        "popq %%rcx           \n\t"  // restore rcx
   74.80 +        "popq %%rbx           \n\t"  // restore rbx
   74.81 +#else
   74.82 +        "popl %%edx           \n\t"  // restore edx
   74.83 +        "popl %%ecx           \n\t"  // restore ecx
   74.84 +        "popl %%ebx           \n\t"  // restore ebx
   74.85 +#endif
   74.86 +
   74.87 +//      "ret                  \n\t"  // DONE:  no MMX support
   74.88 +                                     // (fall through to standard C "ret")
   74.89 +
   74.90 +        : "=a" (result)              // output list
   74.91 +
   74.92 +        :                            // any variables used on input (none)
   74.93 +
   74.94 +                                     // no clobber list
   74.95 +//      , "%ebx", "%ecx", "%edx"     // GRR:  we handle these manually
   74.96 +//      , "memory"   // if write to a variable gcc thought was in a reg
   74.97 +//      , "cc"       // "condition codes" (flag bits)
   74.98 +    );
   74.99 +    _mmx_supported = result;
  74.100 +#else
  74.101 +    _mmx_supported = 0;
  74.102 +#endif /* PNG_MMX_CODE_SUPPORTED */
  74.103 +
  74.104 +    return _mmx_supported;
  74.105 +}
  74.106 +#endif
    75.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    75.2 +++ b/libs/libpng/pngget.c	Thu Sep 08 06:28:38 2011 +0300
    75.3 @@ -0,0 +1,900 @@
    75.4 +
    75.5 +/* pngget.c - retrieval of values from info struct
    75.6 + *
    75.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    75.8 + * For conditions of distribution and use, see copyright notice in png.h
    75.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   75.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   75.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   75.12 + */
   75.13 +
   75.14 +#define PNG_INTERNAL
   75.15 +#include "png.h"
   75.16 +#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
   75.17 +
   75.18 +png_uint_32 PNGAPI
   75.19 +png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
   75.20 +{
   75.21 +   if (png_ptr != NULL && info_ptr != NULL)
   75.22 +      return(info_ptr->valid & flag);
   75.23 +   else
   75.24 +      return(0);
   75.25 +}
   75.26 +
   75.27 +png_uint_32 PNGAPI
   75.28 +png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
   75.29 +{
   75.30 +   if (png_ptr != NULL && info_ptr != NULL)
   75.31 +      return(info_ptr->rowbytes);
   75.32 +   else
   75.33 +      return(0);
   75.34 +}
   75.35 +
   75.36 +#if defined(PNG_INFO_IMAGE_SUPPORTED)
   75.37 +png_bytepp PNGAPI
   75.38 +png_get_rows(png_structp png_ptr, png_infop info_ptr)
   75.39 +{
   75.40 +   if (png_ptr != NULL && info_ptr != NULL)
   75.41 +      return(info_ptr->row_pointers);
   75.42 +   else
   75.43 +      return(0);
   75.44 +}
   75.45 +#endif
   75.46 +
   75.47 +#ifdef PNG_EASY_ACCESS_SUPPORTED
   75.48 +/* easy access to info, added in libpng-0.99 */
   75.49 +png_uint_32 PNGAPI
   75.50 +png_get_image_width(png_structp png_ptr, png_infop info_ptr)
   75.51 +{
   75.52 +   if (png_ptr != NULL && info_ptr != NULL)
   75.53 +   {
   75.54 +      return info_ptr->width;
   75.55 +   }
   75.56 +   return (0);
   75.57 +}
   75.58 +
   75.59 +png_uint_32 PNGAPI
   75.60 +png_get_image_height(png_structp png_ptr, png_infop info_ptr)
   75.61 +{
   75.62 +   if (png_ptr != NULL && info_ptr != NULL)
   75.63 +   {
   75.64 +      return info_ptr->height;
   75.65 +   }
   75.66 +   return (0);
   75.67 +}
   75.68 +
   75.69 +png_byte PNGAPI
   75.70 +png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
   75.71 +{
   75.72 +   if (png_ptr != NULL && info_ptr != NULL)
   75.73 +   {
   75.74 +      return info_ptr->bit_depth;
   75.75 +   }
   75.76 +   return (0);
   75.77 +}
   75.78 +
   75.79 +png_byte PNGAPI
   75.80 +png_get_color_type(png_structp png_ptr, png_infop info_ptr)
   75.81 +{
   75.82 +   if (png_ptr != NULL && info_ptr != NULL)
   75.83 +   {
   75.84 +      return info_ptr->color_type;
   75.85 +   }
   75.86 +   return (0);
   75.87 +}
   75.88 +
   75.89 +png_byte PNGAPI
   75.90 +png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
   75.91 +{
   75.92 +   if (png_ptr != NULL && info_ptr != NULL)
   75.93 +   {
   75.94 +      return info_ptr->filter_type;
   75.95 +   }
   75.96 +   return (0);
   75.97 +}
   75.98 +
   75.99 +png_byte PNGAPI
  75.100 +png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  75.101 +{
  75.102 +   if (png_ptr != NULL && info_ptr != NULL)
  75.103 +   {
  75.104 +      return info_ptr->interlace_type;
  75.105 +   }
  75.106 +   return (0);
  75.107 +}
  75.108 +
  75.109 +png_byte PNGAPI
  75.110 +png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  75.111 +{
  75.112 +   if (png_ptr != NULL && info_ptr != NULL)
  75.113 +   {
  75.114 +      return info_ptr->compression_type;
  75.115 +   }
  75.116 +   return (0);
  75.117 +}
  75.118 +
  75.119 +png_uint_32 PNGAPI
  75.120 +png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  75.121 +{
  75.122 +   if (png_ptr != NULL && info_ptr != NULL)
  75.123 +#if defined(PNG_pHYs_SUPPORTED)
  75.124 +   if (info_ptr->valid & PNG_INFO_pHYs)
  75.125 +   {
  75.126 +      png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  75.127 +      if (info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  75.128 +          return (0);
  75.129 +      else return (info_ptr->x_pixels_per_unit);
  75.130 +   }
  75.131 +#else
  75.132 +   return (0);
  75.133 +#endif
  75.134 +   return (0);
  75.135 +}
  75.136 +
  75.137 +png_uint_32 PNGAPI
  75.138 +png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  75.139 +{
  75.140 +   if (png_ptr != NULL && info_ptr != NULL)
  75.141 +#if defined(PNG_pHYs_SUPPORTED)
  75.142 +   if (info_ptr->valid & PNG_INFO_pHYs)
  75.143 +   {
  75.144 +      png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  75.145 +      if (info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  75.146 +          return (0);
  75.147 +      else return (info_ptr->y_pixels_per_unit);
  75.148 +   }
  75.149 +#else
  75.150 +   return (0);
  75.151 +#endif
  75.152 +   return (0);
  75.153 +}
  75.154 +
  75.155 +png_uint_32 PNGAPI
  75.156 +png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  75.157 +{
  75.158 +   if (png_ptr != NULL && info_ptr != NULL)
  75.159 +#if defined(PNG_pHYs_SUPPORTED)
  75.160 +   if (info_ptr->valid & PNG_INFO_pHYs)
  75.161 +   {
  75.162 +      png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  75.163 +      if (info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  75.164 +         info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  75.165 +          return (0);
  75.166 +      else return (info_ptr->x_pixels_per_unit);
  75.167 +   }
  75.168 +#else
  75.169 +   return (0);
  75.170 +#endif
  75.171 +   return (0);
  75.172 +}
  75.173 +
  75.174 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  75.175 +float PNGAPI
  75.176 +png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  75.177 +   {
  75.178 +   if (png_ptr != NULL && info_ptr != NULL)
  75.179 +#if defined(PNG_pHYs_SUPPORTED)
  75.180 +   if (info_ptr->valid & PNG_INFO_pHYs)
  75.181 +   {
  75.182 +      png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  75.183 +      if (info_ptr->x_pixels_per_unit == 0)
  75.184 +         return ((float)0.0);
  75.185 +      else
  75.186 +         return ((float)((float)info_ptr->y_pixels_per_unit
  75.187 +            /(float)info_ptr->x_pixels_per_unit));
  75.188 +   }
  75.189 +#else
  75.190 +   return (0.0);
  75.191 +#endif
  75.192 +   return ((float)0.0);
  75.193 +}
  75.194 +#endif
  75.195 +
  75.196 +png_int_32 PNGAPI
  75.197 +png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  75.198 +{
  75.199 +   if (png_ptr != NULL && info_ptr != NULL)
  75.200 +#if defined(PNG_oFFs_SUPPORTED)
  75.201 +   if (info_ptr->valid & PNG_INFO_oFFs)
  75.202 +   {
  75.203 +      png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  75.204 +      if (info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  75.205 +          return (0);
  75.206 +      else return (info_ptr->x_offset);
  75.207 +   }
  75.208 +#else
  75.209 +   return (0);
  75.210 +#endif
  75.211 +   return (0);
  75.212 +}
  75.213 +
  75.214 +png_int_32 PNGAPI
  75.215 +png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  75.216 +{
  75.217 +   if (png_ptr != NULL && info_ptr != NULL)
  75.218 +#if defined(PNG_oFFs_SUPPORTED)
  75.219 +   if (info_ptr->valid & PNG_INFO_oFFs)
  75.220 +   {
  75.221 +      png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  75.222 +      if (info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  75.223 +          return (0);
  75.224 +      else return (info_ptr->y_offset);
  75.225 +   }
  75.226 +#else
  75.227 +   return (0);
  75.228 +#endif
  75.229 +   return (0);
  75.230 +}
  75.231 +
  75.232 +png_int_32 PNGAPI
  75.233 +png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  75.234 +{
  75.235 +   if (png_ptr != NULL && info_ptr != NULL)
  75.236 +#if defined(PNG_oFFs_SUPPORTED)
  75.237 +   if (info_ptr->valid & PNG_INFO_oFFs)
  75.238 +   {
  75.239 +      png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  75.240 +      if (info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  75.241 +          return (0);
  75.242 +      else return (info_ptr->x_offset);
  75.243 +   }
  75.244 +#else
  75.245 +   return (0);
  75.246 +#endif
  75.247 +   return (0);
  75.248 +}
  75.249 +
  75.250 +png_int_32 PNGAPI
  75.251 +png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  75.252 +{
  75.253 +   if (png_ptr != NULL && info_ptr != NULL)
  75.254 +#if defined(PNG_oFFs_SUPPORTED)
  75.255 +   if (info_ptr->valid & PNG_INFO_oFFs)
  75.256 +   {
  75.257 +      png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  75.258 +      if (info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  75.259 +          return (0);
  75.260 +      else return (info_ptr->y_offset);
  75.261 +   }
  75.262 +#else
  75.263 +   return (0);
  75.264 +#endif
  75.265 +   return (0);
  75.266 +}
  75.267 +
  75.268 +#if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  75.269 +png_uint_32 PNGAPI
  75.270 +png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  75.271 +{
  75.272 +   return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  75.273 +     *.0254 +.5));
  75.274 +}
  75.275 +
  75.276 +png_uint_32 PNGAPI
  75.277 +png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  75.278 +{
  75.279 +   return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  75.280 +     *.0254 +.5));
  75.281 +}
  75.282 +
  75.283 +png_uint_32 PNGAPI
  75.284 +png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  75.285 +{
  75.286 +   return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  75.287 +     *.0254 +.5));
  75.288 +}
  75.289 +
  75.290 +float PNGAPI
  75.291 +png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  75.292 +{
  75.293 +   return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  75.294 +     *.00003937);
  75.295 +}
  75.296 +
  75.297 +float PNGAPI
  75.298 +png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  75.299 +{
  75.300 +   return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  75.301 +     *.00003937);
  75.302 +}
  75.303 +
  75.304 +#if defined(PNG_pHYs_SUPPORTED)
  75.305 +png_uint_32 PNGAPI
  75.306 +png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  75.307 +   png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  75.308 +{
  75.309 +   png_uint_32 retval = 0;
  75.310 +
  75.311 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  75.312 +   {
  75.313 +      png_debug1(1, "in %s retrieval function\n", "pHYs");
  75.314 +      if (res_x != NULL)
  75.315 +      {
  75.316 +         *res_x = info_ptr->x_pixels_per_unit;
  75.317 +         retval |= PNG_INFO_pHYs;
  75.318 +      }
  75.319 +      if (res_y != NULL)
  75.320 +      {
  75.321 +         *res_y = info_ptr->y_pixels_per_unit;
  75.322 +         retval |= PNG_INFO_pHYs;
  75.323 +      }
  75.324 +      if (unit_type != NULL)
  75.325 +      {
  75.326 +         *unit_type = (int)info_ptr->phys_unit_type;
  75.327 +         retval |= PNG_INFO_pHYs;
  75.328 +         if (*unit_type == 1)
  75.329 +         {
  75.330 +            if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  75.331 +            if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  75.332 +         }
  75.333 +      }
  75.334 +   }
  75.335 +   return (retval);
  75.336 +}
  75.337 +#endif /* PNG_pHYs_SUPPORTED */
  75.338 +#endif  /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  75.339 +
  75.340 +/* png_get_channels really belongs in here, too, but it's been around longer */
  75.341 +
  75.342 +#endif  /* PNG_EASY_ACCESS_SUPPORTED */
  75.343 +
  75.344 +png_byte PNGAPI
  75.345 +png_get_channels(png_structp png_ptr, png_infop info_ptr)
  75.346 +{
  75.347 +   if (png_ptr != NULL && info_ptr != NULL)
  75.348 +      return(info_ptr->channels);
  75.349 +   else
  75.350 +      return (0);
  75.351 +}
  75.352 +
  75.353 +png_bytep PNGAPI
  75.354 +png_get_signature(png_structp png_ptr, png_infop info_ptr)
  75.355 +{
  75.356 +   if (png_ptr != NULL && info_ptr != NULL)
  75.357 +      return(info_ptr->signature);
  75.358 +   else
  75.359 +      return (NULL);
  75.360 +}
  75.361 +
  75.362 +#if defined(PNG_bKGD_SUPPORTED)
  75.363 +png_uint_32 PNGAPI
  75.364 +png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  75.365 +   png_color_16p *background)
  75.366 +{
  75.367 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  75.368 +      && background != NULL)
  75.369 +   {
  75.370 +      png_debug1(1, "in %s retrieval function\n", "bKGD");
  75.371 +      *background = &(info_ptr->background);
  75.372 +      return (PNG_INFO_bKGD);
  75.373 +   }
  75.374 +   return (0);
  75.375 +}
  75.376 +#endif
  75.377 +
  75.378 +#if defined(PNG_cHRM_SUPPORTED)
  75.379 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  75.380 +png_uint_32 PNGAPI
  75.381 +png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  75.382 +   double *white_x, double *white_y, double *red_x, double *red_y,
  75.383 +   double *green_x, double *green_y, double *blue_x, double *blue_y)
  75.384 +{
  75.385 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  75.386 +   {
  75.387 +      png_debug1(1, "in %s retrieval function\n", "cHRM");
  75.388 +      if (white_x != NULL)
  75.389 +         *white_x = (double)info_ptr->x_white;
  75.390 +      if (white_y != NULL)
  75.391 +         *white_y = (double)info_ptr->y_white;
  75.392 +      if (red_x != NULL)
  75.393 +         *red_x = (double)info_ptr->x_red;
  75.394 +      if (red_y != NULL)
  75.395 +         *red_y = (double)info_ptr->y_red;
  75.396 +      if (green_x != NULL)
  75.397 +         *green_x = (double)info_ptr->x_green;
  75.398 +      if (green_y != NULL)
  75.399 +         *green_y = (double)info_ptr->y_green;
  75.400 +      if (blue_x != NULL)
  75.401 +         *blue_x = (double)info_ptr->x_blue;
  75.402 +      if (blue_y != NULL)
  75.403 +         *blue_y = (double)info_ptr->y_blue;
  75.404 +      return (PNG_INFO_cHRM);
  75.405 +   }
  75.406 +   return (0);
  75.407 +}
  75.408 +#endif
  75.409 +#ifdef PNG_FIXED_POINT_SUPPORTED
  75.410 +png_uint_32 PNGAPI
  75.411 +png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  75.412 +   png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  75.413 +   png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  75.414 +   png_fixed_point *blue_x, png_fixed_point *blue_y)
  75.415 +{
  75.416 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  75.417 +   {
  75.418 +      png_debug1(1, "in %s retrieval function\n", "cHRM");
  75.419 +      if (white_x != NULL)
  75.420 +         *white_x = info_ptr->int_x_white;
  75.421 +      if (white_y != NULL)
  75.422 +         *white_y = info_ptr->int_y_white;
  75.423 +      if (red_x != NULL)
  75.424 +         *red_x = info_ptr->int_x_red;
  75.425 +      if (red_y != NULL)
  75.426 +         *red_y = info_ptr->int_y_red;
  75.427 +      if (green_x != NULL)
  75.428 +         *green_x = info_ptr->int_x_green;
  75.429 +      if (green_y != NULL)
  75.430 +         *green_y = info_ptr->int_y_green;
  75.431 +      if (blue_x != NULL)
  75.432 +         *blue_x = info_ptr->int_x_blue;
  75.433 +      if (blue_y != NULL)
  75.434 +         *blue_y = info_ptr->int_y_blue;
  75.435 +      return (PNG_INFO_cHRM);
  75.436 +   }
  75.437 +   return (0);
  75.438 +}
  75.439 +#endif
  75.440 +#endif
  75.441 +
  75.442 +#if defined(PNG_gAMA_SUPPORTED)
  75.443 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  75.444 +png_uint_32 PNGAPI
  75.445 +png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  75.446 +{
  75.447 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  75.448 +      && file_gamma != NULL)
  75.449 +   {
  75.450 +      png_debug1(1, "in %s retrieval function\n", "gAMA");
  75.451 +      *file_gamma = (double)info_ptr->gamma;
  75.452 +      return (PNG_INFO_gAMA);
  75.453 +   }
  75.454 +   return (0);
  75.455 +}
  75.456 +#endif
  75.457 +#ifdef PNG_FIXED_POINT_SUPPORTED
  75.458 +png_uint_32 PNGAPI
  75.459 +png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  75.460 +    png_fixed_point *int_file_gamma)
  75.461 +{
  75.462 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  75.463 +      && int_file_gamma != NULL)
  75.464 +   {
  75.465 +      png_debug1(1, "in %s retrieval function\n", "gAMA");
  75.466 +      *int_file_gamma = info_ptr->int_gamma;
  75.467 +      return (PNG_INFO_gAMA);
  75.468 +   }
  75.469 +   return (0);
  75.470 +}
  75.471 +#endif
  75.472 +#endif
  75.473 +
  75.474 +#if defined(PNG_sRGB_SUPPORTED)
  75.475 +png_uint_32 PNGAPI
  75.476 +png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  75.477 +{
  75.478 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  75.479 +      && file_srgb_intent != NULL)
  75.480 +   {
  75.481 +      png_debug1(1, "in %s retrieval function\n", "sRGB");
  75.482 +      *file_srgb_intent = (int)info_ptr->srgb_intent;
  75.483 +      return (PNG_INFO_sRGB);
  75.484 +   }
  75.485 +   return (0);
  75.486 +}
  75.487 +#endif
  75.488 +
  75.489 +#if defined(PNG_iCCP_SUPPORTED)
  75.490 +png_uint_32 PNGAPI
  75.491 +png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  75.492 +             png_charpp name, int *compression_type,
  75.493 +             png_charpp profile, png_uint_32 *proflen)
  75.494 +{
  75.495 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  75.496 +      && name != NULL && profile != NULL && proflen != NULL)
  75.497 +   {
  75.498 +      png_debug1(1, "in %s retrieval function\n", "iCCP");
  75.499 +      *name = info_ptr->iccp_name;
  75.500 +      *profile = info_ptr->iccp_profile;
  75.501 +      /* compression_type is a dummy so the API won't have to change
  75.502 +         if we introduce multiple compression types later. */
  75.503 +      *proflen = (int)info_ptr->iccp_proflen;
  75.504 +      *compression_type = (int)info_ptr->iccp_compression;
  75.505 +      return (PNG_INFO_iCCP);
  75.506 +   }
  75.507 +   return (0);
  75.508 +}
  75.509 +#endif
  75.510 +
  75.511 +#if defined(PNG_sPLT_SUPPORTED)
  75.512 +png_uint_32 PNGAPI
  75.513 +png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  75.514 +             png_sPLT_tpp spalettes)
  75.515 +{
  75.516 +   if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  75.517 +   {
  75.518 +     *spalettes = info_ptr->splt_palettes;
  75.519 +     return ((png_uint_32)info_ptr->splt_palettes_num);
  75.520 +   }
  75.521 +   return (0);
  75.522 +}
  75.523 +#endif
  75.524 +
  75.525 +#if defined(PNG_hIST_SUPPORTED)
  75.526 +png_uint_32 PNGAPI
  75.527 +png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  75.528 +{
  75.529 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  75.530 +      && hist != NULL)
  75.531 +   {
  75.532 +      png_debug1(1, "in %s retrieval function\n", "hIST");
  75.533 +      *hist = info_ptr->hist;
  75.534 +      return (PNG_INFO_hIST);
  75.535 +   }
  75.536 +   return (0);
  75.537 +}
  75.538 +#endif
  75.539 +
  75.540 +png_uint_32 PNGAPI
  75.541 +png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  75.542 +   png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  75.543 +   int *color_type, int *interlace_type, int *compression_type,
  75.544 +   int *filter_type)
  75.545 +
  75.546 +{
  75.547 +   if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  75.548 +      bit_depth != NULL && color_type != NULL)
  75.549 +   {
  75.550 +      png_debug1(1, "in %s retrieval function\n", "IHDR");
  75.551 +      *width = info_ptr->width;
  75.552 +      *height = info_ptr->height;
  75.553 +      *bit_depth = info_ptr->bit_depth;
  75.554 +      if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  75.555 +        png_error(png_ptr, "Invalid bit depth");
  75.556 +      *color_type = info_ptr->color_type;
  75.557 +      if (info_ptr->color_type > 6)
  75.558 +        png_error(png_ptr, "Invalid color type");
  75.559 +      if (compression_type != NULL)
  75.560 +         *compression_type = info_ptr->compression_type;
  75.561 +      if (filter_type != NULL)
  75.562 +         *filter_type = info_ptr->filter_type;
  75.563 +      if (interlace_type != NULL)
  75.564 +         *interlace_type = info_ptr->interlace_type;
  75.565 +
  75.566 +      /* check for potential overflow of rowbytes */
  75.567 +      if (*width == 0 || *width > PNG_UINT_31_MAX)
  75.568 +        png_error(png_ptr, "Invalid image width");
  75.569 +      if (*height == 0 || *height > PNG_UINT_31_MAX)
  75.570 +        png_error(png_ptr, "Invalid image height");
  75.571 +      if (info_ptr->width > (PNG_UINT_32_MAX
  75.572 +                 >> 3)      /* 8-byte RGBA pixels */
  75.573 +                 - 64       /* bigrowbuf hack */
  75.574 +                 - 1        /* filter byte */
  75.575 +                 - 7*8      /* rounding of width to multiple of 8 pixels */
  75.576 +                 - 8)       /* extra max_pixel_depth pad */
  75.577 +      {
  75.578 +         png_warning(png_ptr,
  75.579 +            "Width too large for libpng to process image data.");
  75.580 +      }
  75.581 +      return (1);
  75.582 +   }
  75.583 +   return (0);
  75.584 +}
  75.585 +
  75.586 +#if defined(PNG_oFFs_SUPPORTED)
  75.587 +png_uint_32 PNGAPI
  75.588 +png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  75.589 +   png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  75.590 +{
  75.591 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  75.592 +      && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  75.593 +   {
  75.594 +      png_debug1(1, "in %s retrieval function\n", "oFFs");
  75.595 +      *offset_x = info_ptr->x_offset;
  75.596 +      *offset_y = info_ptr->y_offset;
  75.597 +      *unit_type = (int)info_ptr->offset_unit_type;
  75.598 +      return (PNG_INFO_oFFs);
  75.599 +   }
  75.600 +   return (0);
  75.601 +}
  75.602 +#endif
  75.603 +
  75.604 +#if defined(PNG_pCAL_SUPPORTED)
  75.605 +png_uint_32 PNGAPI
  75.606 +png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  75.607 +   png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  75.608 +   png_charp *units, png_charpp *params)
  75.609 +{
  75.610 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  75.611 +      && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  75.612 +      nparams != NULL && units != NULL && params != NULL)
  75.613 +   {
  75.614 +      png_debug1(1, "in %s retrieval function\n", "pCAL");
  75.615 +      *purpose = info_ptr->pcal_purpose;
  75.616 +      *X0 = info_ptr->pcal_X0;
  75.617 +      *X1 = info_ptr->pcal_X1;
  75.618 +      *type = (int)info_ptr->pcal_type;
  75.619 +      *nparams = (int)info_ptr->pcal_nparams;
  75.620 +      *units = info_ptr->pcal_units;
  75.621 +      *params = info_ptr->pcal_params;
  75.622 +      return (PNG_INFO_pCAL);
  75.623 +   }
  75.624 +   return (0);
  75.625 +}
  75.626 +#endif
  75.627 +
  75.628 +#if defined(PNG_sCAL_SUPPORTED)
  75.629 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  75.630 +png_uint_32 PNGAPI
  75.631 +png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  75.632 +             int *unit, double *width, double *height)
  75.633 +{
  75.634 +    if (png_ptr != NULL && info_ptr != NULL &&
  75.635 +       (info_ptr->valid & PNG_INFO_sCAL))
  75.636 +    {
  75.637 +        *unit = info_ptr->scal_unit;
  75.638 +        *width = info_ptr->scal_pixel_width;
  75.639 +        *height = info_ptr->scal_pixel_height;
  75.640 +        return (PNG_INFO_sCAL);
  75.641 +    }
  75.642 +    return(0);
  75.643 +}
  75.644 +#else
  75.645 +#ifdef PNG_FIXED_POINT_SUPPORTED
  75.646 +png_uint_32 PNGAPI
  75.647 +png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  75.648 +             int *unit, png_charpp width, png_charpp height)
  75.649 +{
  75.650 +    if (png_ptr != NULL && info_ptr != NULL &&
  75.651 +       (info_ptr->valid & PNG_INFO_sCAL))
  75.652 +    {
  75.653 +        *unit = info_ptr->scal_unit;
  75.654 +        *width = info_ptr->scal_s_width;
  75.655 +        *height = info_ptr->scal_s_height;
  75.656 +        return (PNG_INFO_sCAL);
  75.657 +    }
  75.658 +    return(0);
  75.659 +}
  75.660 +#endif
  75.661 +#endif
  75.662 +#endif
  75.663 +
  75.664 +#if defined(PNG_pHYs_SUPPORTED)
  75.665 +png_uint_32 PNGAPI
  75.666 +png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  75.667 +   png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  75.668 +{
  75.669 +   png_uint_32 retval = 0;
  75.670 +
  75.671 +   if (png_ptr != NULL && info_ptr != NULL &&
  75.672 +      (info_ptr->valid & PNG_INFO_pHYs))
  75.673 +   {
  75.674 +      png_debug1(1, "in %s retrieval function\n", "pHYs");
  75.675 +      if (res_x != NULL)
  75.676 +      {
  75.677 +         *res_x = info_ptr->x_pixels_per_unit;
  75.678 +         retval |= PNG_INFO_pHYs;
  75.679 +      }
  75.680 +      if (res_y != NULL)
  75.681 +      {
  75.682 +         *res_y = info_ptr->y_pixels_per_unit;
  75.683 +         retval |= PNG_INFO_pHYs;
  75.684 +      }
  75.685 +      if (unit_type != NULL)
  75.686 +      {
  75.687 +         *unit_type = (int)info_ptr->phys_unit_type;
  75.688 +         retval |= PNG_INFO_pHYs;
  75.689 +      }
  75.690 +   }
  75.691 +   return (retval);
  75.692 +}
  75.693 +#endif
  75.694 +
  75.695 +png_uint_32 PNGAPI
  75.696 +png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  75.697 +   int *num_palette)
  75.698 +{
  75.699 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  75.700 +       && palette != NULL)
  75.701 +   {
  75.702 +      png_debug1(1, "in %s retrieval function\n", "PLTE");
  75.703 +      *palette = info_ptr->palette;
  75.704 +      *num_palette = info_ptr->num_palette;
  75.705 +      png_debug1(3, "num_palette = %d\n", *num_palette);
  75.706 +      return (PNG_INFO_PLTE);
  75.707 +   }
  75.708 +   return (0);
  75.709 +}
  75.710 +
  75.711 +#if defined(PNG_sBIT_SUPPORTED)
  75.712 +png_uint_32 PNGAPI
  75.713 +png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  75.714 +{
  75.715 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  75.716 +      && sig_bit != NULL)
  75.717 +   {
  75.718 +      png_debug1(1, "in %s retrieval function\n", "sBIT");
  75.719 +      *sig_bit = &(info_ptr->sig_bit);
  75.720 +      return (PNG_INFO_sBIT);
  75.721 +   }
  75.722 +   return (0);
  75.723 +}
  75.724 +#endif
  75.725 +
  75.726 +#if defined(PNG_TEXT_SUPPORTED)
  75.727 +png_uint_32 PNGAPI
  75.728 +png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  75.729 +   int *num_text)
  75.730 +{
  75.731 +   if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  75.732 +   {
  75.733 +      png_debug1(1, "in %s retrieval function\n",
  75.734 +         (png_ptr->chunk_name[0] == '\0' ? "text"
  75.735 +             : (png_const_charp)png_ptr->chunk_name));
  75.736 +      if (text_ptr != NULL)
  75.737 +         *text_ptr = info_ptr->text;
  75.738 +      if (num_text != NULL)
  75.739 +         *num_text = info_ptr->num_text;
  75.740 +      return ((png_uint_32)info_ptr->num_text);
  75.741 +   }
  75.742 +   if (num_text != NULL)
  75.743 +     *num_text = 0;
  75.744 +   return(0);
  75.745 +}
  75.746 +#endif
  75.747 +
  75.748 +#if defined(PNG_tIME_SUPPORTED)
  75.749 +png_uint_32 PNGAPI
  75.750 +png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  75.751 +{
  75.752 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  75.753 +       && mod_time != NULL)
  75.754 +   {
  75.755 +      png_debug1(1, "in %s retrieval function\n", "tIME");
  75.756 +      *mod_time = &(info_ptr->mod_time);
  75.757 +      return (PNG_INFO_tIME);
  75.758 +   }
  75.759 +   return (0);
  75.760 +}
  75.761 +#endif
  75.762 +
  75.763 +#if defined(PNG_tRNS_SUPPORTED)
  75.764 +png_uint_32 PNGAPI
  75.765 +png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  75.766 +   png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  75.767 +{
  75.768 +   png_uint_32 retval = 0;
  75.769 +   if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  75.770 +   {
  75.771 +      png_debug1(1, "in %s retrieval function\n", "tRNS");
  75.772 +      if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  75.773 +      {
  75.774 +          if (trans != NULL)
  75.775 +          {
  75.776 +             *trans = info_ptr->trans;
  75.777 +             retval |= PNG_INFO_tRNS;
  75.778 +          }
  75.779 +          if (trans_values != NULL)
  75.780 +             *trans_values = &(info_ptr->trans_values);
  75.781 +      }
  75.782 +      else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  75.783 +      {
  75.784 +          if (trans_values != NULL)
  75.785 +          {
  75.786 +             *trans_values = &(info_ptr->trans_values);
  75.787 +             retval |= PNG_INFO_tRNS;
  75.788 +          }
  75.789 +          if (trans != NULL)
  75.790 +             *trans = NULL;
  75.791 +      }
  75.792 +      if (num_trans != NULL)
  75.793 +      {
  75.794 +         *num_trans = info_ptr->num_trans;
  75.795 +         retval |= PNG_INFO_tRNS;
  75.796 +      }
  75.797 +   }
  75.798 +   return (retval);
  75.799 +}
  75.800 +#endif
  75.801 +
  75.802 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  75.803 +png_uint_32 PNGAPI
  75.804 +png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  75.805 +             png_unknown_chunkpp unknowns)
  75.806 +{
  75.807 +   if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  75.808 +   {
  75.809 +     *unknowns = info_ptr->unknown_chunks;
  75.810 +     return ((png_uint_32)info_ptr->unknown_chunks_num);
  75.811 +   }
  75.812 +   return (0);
  75.813 +}
  75.814 +#endif
  75.815 +
  75.816 +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  75.817 +png_byte PNGAPI
  75.818 +png_get_rgb_to_gray_status (png_structp png_ptr)
  75.819 +{
  75.820 +   return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  75.821 +}
  75.822 +#endif
  75.823 +
  75.824 +#if defined(PNG_USER_CHUNKS_SUPPORTED)
  75.825 +png_voidp PNGAPI
  75.826 +png_get_user_chunk_ptr(png_structp png_ptr)
  75.827 +{
  75.828 +   return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  75.829 +}
  75.830 +#endif
  75.831 +
  75.832 +#ifdef PNG_WRITE_SUPPORTED
  75.833 +png_uint_32 PNGAPI
  75.834 +png_get_compression_buffer_size(png_structp png_ptr)
  75.835 +{
  75.836 +   return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  75.837 +}
  75.838 +#endif
  75.839 +
  75.840 +#ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  75.841 +#ifndef PNG_1_0_X
  75.842 +/* this function was added to libpng 1.2.0 and should exist by default */
  75.843 +png_uint_32 PNGAPI
  75.844 +png_get_asm_flags (png_structp png_ptr)
  75.845 +{
  75.846 +    /* obsolete, to be removed from libpng-1.4.0 */
  75.847 +    return (png_ptr? 0L: 0L);
  75.848 +}
  75.849 +
  75.850 +/* this function was added to libpng 1.2.0 and should exist by default */
  75.851 +png_uint_32 PNGAPI
  75.852 +png_get_asm_flagmask (int flag_select)
  75.853 +{
  75.854 +    /* obsolete, to be removed from libpng-1.4.0 */
  75.855 +    flag_select=flag_select;
  75.856 +    return 0L;
  75.857 +}
  75.858 +
  75.859 +    /* GRR:  could add this:   && defined(PNG_MMX_CODE_SUPPORTED) */
  75.860 +/* this function was added to libpng 1.2.0 */
  75.861 +png_uint_32 PNGAPI
  75.862 +png_get_mmx_flagmask (int flag_select, int *compilerID)
  75.863 +{
  75.864 +    /* obsolete, to be removed from libpng-1.4.0 */
  75.865 +    flag_select=flag_select;
  75.866 +    *compilerID = -1;   /* unknown (i.e., no asm/MMX code compiled) */
  75.867 +    return 0L;
  75.868 +}
  75.869 +
  75.870 +/* this function was added to libpng 1.2.0 */
  75.871 +png_byte PNGAPI
  75.872 +png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  75.873 +{
  75.874 +    /* obsolete, to be removed from libpng-1.4.0 */
  75.875 +    return (png_ptr? 0: 0);
  75.876 +}
  75.877 +
  75.878 +/* this function was added to libpng 1.2.0 */
  75.879 +png_uint_32 PNGAPI
  75.880 +png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  75.881 +{
  75.882 +    /* obsolete, to be removed from libpng-1.4.0 */
  75.883 +    return (png_ptr? 0L: 0L);
  75.884 +}
  75.885 +#endif /* ?PNG_1_0_X */
  75.886 +#endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  75.887 +
  75.888 +#ifdef PNG_SET_USER_LIMITS_SUPPORTED
  75.889 +/* these functions were added to libpng 1.2.6 */
  75.890 +png_uint_32 PNGAPI
  75.891 +png_get_user_width_max (png_structp png_ptr)
  75.892 +{
  75.893 +    return (png_ptr? png_ptr->user_width_max : 0);
  75.894 +}
  75.895 +png_uint_32 PNGAPI
  75.896 +png_get_user_height_max (png_structp png_ptr)
  75.897 +{
  75.898 +    return (png_ptr? png_ptr->user_height_max : 0);
  75.899 +}
  75.900 +#endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  75.901 + 
  75.902 +
  75.903 +#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
    76.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    76.2 +++ b/libs/libpng/pngmem.c	Thu Sep 08 06:28:38 2011 +0300
    76.3 @@ -0,0 +1,609 @@
    76.4 +
    76.5 +/* pngmem.c - stub functions for memory allocation
    76.6 + *
    76.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    76.8 + * For conditions of distribution and use, see copyright notice in png.h
    76.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   76.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   76.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   76.12 + *
   76.13 + * This file provides a location for all memory allocation.  Users who
   76.14 + * need special memory handling are expected to supply replacement
   76.15 + * functions for png_malloc() and png_free(), and to use
   76.16 + * png_create_read_struct_2() and png_create_write_struct_2() to
   76.17 + * identify the replacement functions.
   76.18 + */
   76.19 +
   76.20 +#define PNG_INTERNAL
   76.21 +#include "png.h"
   76.22 +#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
   76.23 +
   76.24 +/* Borland DOS special memory handler */
   76.25 +#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
   76.26 +/* if you change this, be sure to change the one in png.h also */
   76.27 +
   76.28 +/* Allocate memory for a png_struct.  The malloc and memset can be replaced
   76.29 +   by a single call to calloc() if this is thought to improve performance. */
   76.30 +png_voidp /* PRIVATE */
   76.31 +png_create_struct(int type)
   76.32 +{
   76.33 +#ifdef PNG_USER_MEM_SUPPORTED
   76.34 +   return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
   76.35 +}
   76.36 +
   76.37 +/* Alternate version of png_create_struct, for use with user-defined malloc. */
   76.38 +png_voidp /* PRIVATE */
   76.39 +png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
   76.40 +{
   76.41 +#endif /* PNG_USER_MEM_SUPPORTED */
   76.42 +   png_size_t size;
   76.43 +   png_voidp struct_ptr;
   76.44 +
   76.45 +   if (type == PNG_STRUCT_INFO)
   76.46 +     size = png_sizeof(png_info);
   76.47 +   else if (type == PNG_STRUCT_PNG)
   76.48 +     size = png_sizeof(png_struct);
   76.49 +   else
   76.50 +     return (png_get_copyright(NULL));
   76.51 +
   76.52 +#ifdef PNG_USER_MEM_SUPPORTED
   76.53 +   if (malloc_fn != NULL)
   76.54 +   {
   76.55 +      png_struct dummy_struct;
   76.56 +      png_structp png_ptr = &dummy_struct;
   76.57 +      png_ptr->mem_ptr=mem_ptr;
   76.58 +      struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
   76.59 +   }
   76.60 +   else
   76.61 +#endif /* PNG_USER_MEM_SUPPORTED */
   76.62 +      struct_ptr = (png_voidp)farmalloc(size);
   76.63 +   if (struct_ptr != NULL)
   76.64 +      png_memset(struct_ptr, 0, size);
   76.65 +   return (struct_ptr);
   76.66 +}
   76.67 +
   76.68 +/* Free memory allocated by a png_create_struct() call */
   76.69 +void /* PRIVATE */
   76.70 +png_destroy_struct(png_voidp struct_ptr)
   76.71 +{
   76.72 +#ifdef PNG_USER_MEM_SUPPORTED
   76.73 +   png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
   76.74 +}
   76.75 +
   76.76 +/* Free memory allocated by a png_create_struct() call */
   76.77 +void /* PRIVATE */
   76.78 +png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
   76.79 +    png_voidp mem_ptr)
   76.80 +{
   76.81 +#endif
   76.82 +   if (struct_ptr != NULL)
   76.83 +   {
   76.84 +#ifdef PNG_USER_MEM_SUPPORTED
   76.85 +      if (free_fn != NULL)
   76.86 +      {
   76.87 +         png_struct dummy_struct;
   76.88 +         png_structp png_ptr = &dummy_struct;
   76.89 +         png_ptr->mem_ptr=mem_ptr;
   76.90 +         (*(free_fn))(png_ptr, struct_ptr);
   76.91 +         return;
   76.92 +      }
   76.93 +#endif /* PNG_USER_MEM_SUPPORTED */
   76.94 +      farfree (struct_ptr);
   76.95 +   }
   76.96 +}
   76.97 +
   76.98 +/* Allocate memory.  For reasonable files, size should never exceed
   76.99 + * 64K.  However, zlib may allocate more then 64K if you don't tell
  76.100 + * it not to.  See zconf.h and png.h for more information. zlib does
  76.101 + * need to allocate exactly 64K, so whatever you call here must
  76.102 + * have the ability to do that.
  76.103 + *
  76.104 + * Borland seems to have a problem in DOS mode for exactly 64K.
  76.105 + * It gives you a segment with an offset of 8 (perhaps to store its
  76.106 + * memory stuff).  zlib doesn't like this at all, so we have to
  76.107 + * detect and deal with it.  This code should not be needed in
  76.108 + * Windows or OS/2 modes, and only in 16 bit mode.  This code has
  76.109 + * been updated by Alexander Lehmann for version 0.89 to waste less
  76.110 + * memory.
  76.111 + *
  76.112 + * Note that we can't use png_size_t for the "size" declaration,
  76.113 + * since on some systems a png_size_t is a 16-bit quantity, and as a
  76.114 + * result, we would be truncating potentially larger memory requests
  76.115 + * (which should cause a fatal error) and introducing major problems.
  76.116 + */
  76.117 +
  76.118 +png_voidp PNGAPI
  76.119 +png_malloc(png_structp png_ptr, png_uint_32 size)
  76.120 +{
  76.121 +   png_voidp ret;
  76.122 +
  76.123 +   if (png_ptr == NULL || size == 0)
  76.124 +      return (NULL);
  76.125 +
  76.126 +#ifdef PNG_USER_MEM_SUPPORTED
  76.127 +   if (png_ptr->malloc_fn != NULL)
  76.128 +       ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  76.129 +   else
  76.130 +       ret = (png_malloc_default(png_ptr, size));
  76.131 +   if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  76.132 +       png_error(png_ptr, "Out of memory!");
  76.133 +   return (ret);
  76.134 +}
  76.135 +
  76.136 +png_voidp PNGAPI
  76.137 +png_malloc_default(png_structp png_ptr, png_uint_32 size)
  76.138 +{
  76.139 +   png_voidp ret;
  76.140 +#endif /* PNG_USER_MEM_SUPPORTED */
  76.141 +
  76.142 +   if (png_ptr == NULL || size == 0)
  76.143 +      return (NULL);
  76.144 +
  76.145 +#ifdef PNG_MAX_MALLOC_64K
  76.146 +   if (size > (png_uint_32)65536L)
  76.147 +   {
  76.148 +      png_warning(png_ptr, "Cannot Allocate > 64K");
  76.149 +      ret = NULL;
  76.150 +   }
  76.151 +   else
  76.152 +#endif
  76.153 +
  76.154 +   if (size != (size_t)size)
  76.155 +     ret = NULL;
  76.156 +   else if (size == (png_uint_32)65536L)
  76.157 +   {
  76.158 +      if (png_ptr->offset_table == NULL)
  76.159 +      {
  76.160 +         /* try to see if we need to do any of this fancy stuff */
  76.161 +         ret = farmalloc(size);
  76.162 +         if (ret == NULL || ((png_size_t)ret & 0xffff))
  76.163 +         {
  76.164 +            int num_blocks;
  76.165 +            png_uint_32 total_size;
  76.166 +            png_bytep table;
  76.167 +            int i;
  76.168 +            png_byte huge * hptr;
  76.169 +
  76.170 +            if (ret != NULL)
  76.171 +            {
  76.172 +               farfree(ret);
  76.173 +               ret = NULL;
  76.174 +            }
  76.175 +
  76.176 +            if (png_ptr->zlib_window_bits > 14)
  76.177 +               num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  76.178 +            else
  76.179 +               num_blocks = 1;
  76.180 +            if (png_ptr->zlib_mem_level >= 7)
  76.181 +               num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  76.182 +            else
  76.183 +               num_blocks++;
  76.184 +
  76.185 +            total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  76.186 +
  76.187 +            table = farmalloc(total_size);
  76.188 +
  76.189 +            if (table == NULL)
  76.190 +            {
  76.191 +#ifndef PNG_USER_MEM_SUPPORTED
  76.192 +               if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  76.193 +                  png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  76.194 +               else
  76.195 +                  png_warning(png_ptr, "Out Of Memory.");
  76.196 +#endif
  76.197 +               return (NULL);
  76.198 +            }
  76.199 +
  76.200 +            if ((png_size_t)table & 0xfff0)
  76.201 +            {
  76.202 +#ifndef PNG_USER_MEM_SUPPORTED
  76.203 +               if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  76.204 +                  png_error(png_ptr,
  76.205 +                    "Farmalloc didn't return normalized pointer");
  76.206 +               else
  76.207 +                  png_warning(png_ptr,
  76.208 +                    "Farmalloc didn't return normalized pointer");
  76.209 +#endif
  76.210 +               return (NULL);
  76.211 +            }
  76.212 +
  76.213 +            png_ptr->offset_table = table;
  76.214 +            png_ptr->offset_table_ptr = farmalloc(num_blocks *
  76.215 +               png_sizeof(png_bytep));
  76.216 +
  76.217 +            if (png_ptr->offset_table_ptr == NULL)
  76.218 +            {
  76.219 +#ifndef PNG_USER_MEM_SUPPORTED
  76.220 +               if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  76.221 +                  png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  76.222 +               else
  76.223 +                  png_warning(png_ptr, "Out Of memory.");
  76.224 +#endif
  76.225 +               return (NULL);
  76.226 +            }
  76.227 +
  76.228 +            hptr = (png_byte huge *)table;
  76.229 +            if ((png_size_t)hptr & 0xf)
  76.230 +            {
  76.231 +               hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  76.232 +               hptr = hptr + 16L;  /* "hptr += 16L" fails on Turbo C++ 3.0 */
  76.233 +            }
  76.234 +            for (i = 0; i < num_blocks; i++)
  76.235 +            {
  76.236 +               png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  76.237 +               hptr = hptr + (png_uint_32)65536L;  /* "+=" fails on TC++3.0 */
  76.238 +            }
  76.239 +
  76.240 +            png_ptr->offset_table_number = num_blocks;
  76.241 +            png_ptr->offset_table_count = 0;
  76.242 +            png_ptr->offset_table_count_free = 0;
  76.243 +         }
  76.244 +      }
  76.245 +
  76.246 +      if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  76.247 +      {
  76.248 +#ifndef PNG_USER_MEM_SUPPORTED
  76.249 +         if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  76.250 +            png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  76.251 +         else
  76.252 +            png_warning(png_ptr, "Out of Memory.");
  76.253 +#endif
  76.254 +         return (NULL);
  76.255 +      }
  76.256 +
  76.257 +      ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  76.258 +   }
  76.259 +   else
  76.260 +      ret = farmalloc(size);
  76.261 +
  76.262 +#ifndef PNG_USER_MEM_SUPPORTED
  76.263 +   if (ret == NULL)
  76.264 +   {
  76.265 +      if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  76.266 +         png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  76.267 +      else
  76.268 +         png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  76.269 +   }
  76.270 +#endif
  76.271 +
  76.272 +   return (ret);
  76.273 +}
  76.274 +
  76.275 +/* free a pointer allocated by png_malloc().  In the default
  76.276 +   configuration, png_ptr is not used, but is passed in case it
  76.277 +   is needed.  If ptr is NULL, return without taking any action. */
  76.278 +
  76.279 +void PNGAPI
  76.280 +png_free(png_structp png_ptr, png_voidp ptr)
  76.281 +{
  76.282 +   if (png_ptr == NULL || ptr == NULL)
  76.283 +      return;
  76.284 +
  76.285 +#ifdef PNG_USER_MEM_SUPPORTED
  76.286 +   if (png_ptr->free_fn != NULL)
  76.287 +   {
  76.288 +      (*(png_ptr->free_fn))(png_ptr, ptr);
  76.289 +      return;
  76.290 +   }
  76.291 +   else png_free_default(png_ptr, ptr);
  76.292 +}
  76.293 +
  76.294 +void PNGAPI
  76.295 +png_free_default(png_structp png_ptr, png_voidp ptr)
  76.296 +{
  76.297 +#endif /* PNG_USER_MEM_SUPPORTED */
  76.298 +
  76.299 +   if (png_ptr == NULL || ptr == NULL) return;
  76.300 +
  76.301 +   if (png_ptr->offset_table != NULL)
  76.302 +   {
  76.303 +      int i;
  76.304 +
  76.305 +      for (i = 0; i < png_ptr->offset_table_count; i++)
  76.306 +      {
  76.307 +         if (ptr == png_ptr->offset_table_ptr[i])
  76.308 +         {
  76.309 +            ptr = NULL;
  76.310 +            png_ptr->offset_table_count_free++;
  76.311 +            break;
  76.312 +         }
  76.313 +      }
  76.314 +      if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  76.315 +      {
  76.316 +         farfree(png_ptr->offset_table);
  76.317 +         farfree(png_ptr->offset_table_ptr);
  76.318 +         png_ptr->offset_table = NULL;
  76.319 +         png_ptr->offset_table_ptr = NULL;
  76.320 +      }
  76.321 +   }
  76.322 +
  76.323 +   if (ptr != NULL)
  76.324 +   {
  76.325 +      farfree(ptr);
  76.326 +   }
  76.327 +}
  76.328 +
  76.329 +#else /* Not the Borland DOS special memory handler */
  76.330 +
  76.331 +/* Allocate memory for a png_struct or a png_info.  The malloc and
  76.332 +   memset can be replaced by a single call to calloc() if this is thought
  76.333 +   to improve performance noticably. */
  76.334 +png_voidp /* PRIVATE */
  76.335 +png_create_struct(int type)
  76.336 +{
  76.337 +#ifdef PNG_USER_MEM_SUPPORTED
  76.338 +   return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  76.339 +}
  76.340 +
  76.341 +/* Allocate memory for a png_struct or a png_info.  The malloc and
  76.342 +   memset can be replaced by a single call to calloc() if this is thought
  76.343 +   to improve performance noticably. */
  76.344 +png_voidp /* PRIVATE */
  76.345 +png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  76.346 +{
  76.347 +#endif /* PNG_USER_MEM_SUPPORTED */
  76.348 +   png_size_t size;
  76.349 +   png_voidp struct_ptr;
  76.350 +
  76.351 +   if (type == PNG_STRUCT_INFO)
  76.352 +      size = png_sizeof(png_info);
  76.353 +   else if (type == PNG_STRUCT_PNG)
  76.354 +      size = png_sizeof(png_struct);
  76.355 +   else
  76.356 +      return (NULL);
  76.357 +
  76.358 +#ifdef PNG_USER_MEM_SUPPORTED
  76.359 +   if (malloc_fn != NULL)
  76.360 +   {
  76.361 +      png_struct dummy_struct;
  76.362 +      png_structp png_ptr = &dummy_struct;
  76.363 +      png_ptr->mem_ptr=mem_ptr;
  76.364 +      struct_ptr = (*(malloc_fn))(png_ptr, size);
  76.365 +      if (struct_ptr != NULL)
  76.366 +         png_memset(struct_ptr, 0, size);
  76.367 +      return (struct_ptr);
  76.368 +   }
  76.369 +#endif /* PNG_USER_MEM_SUPPORTED */
  76.370 +
  76.371 +#if defined(__TURBOC__) && !defined(__FLAT__)
  76.372 +   struct_ptr = (png_voidp)farmalloc(size);
  76.373 +#else
  76.374 +# if defined(_MSC_VER) && defined(MAXSEG_64K)
  76.375 +   struct_ptr = (png_voidp)halloc(size, 1);
  76.376 +# else
  76.377 +   struct_ptr = (png_voidp)malloc(size);
  76.378 +# endif
  76.379 +#endif
  76.380 +   if (struct_ptr != NULL)
  76.381 +      png_memset(struct_ptr, 0, size);
  76.382 +
  76.383 +   return (struct_ptr);
  76.384 +}
  76.385 +
  76.386 +
  76.387 +/* Free memory allocated by a png_create_struct() call */
  76.388 +void /* PRIVATE */
  76.389 +png_destroy_struct(png_voidp struct_ptr)
  76.390 +{
  76.391 +#ifdef PNG_USER_MEM_SUPPORTED
  76.392 +   png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  76.393 +}
  76.394 +
  76.395 +/* Free memory allocated by a png_create_struct() call */
  76.396 +void /* PRIVATE */
  76.397 +png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  76.398 +    png_voidp mem_ptr)
  76.399 +{
  76.400 +#endif /* PNG_USER_MEM_SUPPORTED */
  76.401 +   if (struct_ptr != NULL)
  76.402 +   {
  76.403 +#ifdef PNG_USER_MEM_SUPPORTED
  76.404 +      if (free_fn != NULL)
  76.405 +      {
  76.406 +         png_struct dummy_struct;
  76.407 +         png_structp png_ptr = &dummy_struct;
  76.408 +         png_ptr->mem_ptr=mem_ptr;
  76.409 +         (*(free_fn))(png_ptr, struct_ptr);
  76.410 +         return;
  76.411 +      }
  76.412 +#endif /* PNG_USER_MEM_SUPPORTED */
  76.413 +#if defined(__TURBOC__) && !defined(__FLAT__)
  76.414 +      farfree(struct_ptr);
  76.415 +#else
  76.416 +# if defined(_MSC_VER) && defined(MAXSEG_64K)
  76.417 +      hfree(struct_ptr);
  76.418 +# else
  76.419 +      free(struct_ptr);
  76.420 +# endif
  76.421 +#endif
  76.422 +   }
  76.423 +}
  76.424 +
  76.425 +/* Allocate memory.  For reasonable files, size should never exceed
  76.426 +   64K.  However, zlib may allocate more then 64K if you don't tell
  76.427 +   it not to.  See zconf.h and png.h for more information.  zlib does
  76.428 +   need to allocate exactly 64K, so whatever you call here must
  76.429 +   have the ability to do that. */
  76.430 +
  76.431 +png_voidp PNGAPI
  76.432 +png_malloc(png_structp png_ptr, png_uint_32 size)
  76.433 +{
  76.434 +   png_voidp ret;
  76.435 +
  76.436 +#ifdef PNG_USER_MEM_SUPPORTED
  76.437 +   if (png_ptr == NULL || size == 0)
  76.438 +      return (NULL);
  76.439 +
  76.440 +   if (png_ptr->malloc_fn != NULL)
  76.441 +       ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  76.442 +   else
  76.443 +       ret = (png_malloc_default(png_ptr, size));
  76.444 +   if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  76.445 +       png_error(png_ptr, "Out of Memory!");
  76.446 +   return (ret);
  76.447 +}
  76.448 +
  76.449 +png_voidp PNGAPI
  76.450 +png_malloc_default(png_structp png_ptr, png_uint_32 size)
  76.451 +{
  76.452 +   png_voidp ret;
  76.453 +#endif /* PNG_USER_MEM_SUPPORTED */
  76.454 +
  76.455 +   if (png_ptr == NULL || size == 0)
  76.456 +      return (NULL);
  76.457 +
  76.458 +#ifdef PNG_MAX_MALLOC_64K
  76.459 +   if (size > (png_uint_32)65536L)
  76.460 +   {
  76.461 +#ifndef PNG_USER_MEM_SUPPORTED
  76.462 +      if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  76.463 +         png_error(png_ptr, "Cannot Allocate > 64K");
  76.464 +      else
  76.465 +#endif
  76.466 +         return NULL;
  76.467 +   }
  76.468 +#endif
  76.469 +
  76.470 + /* Check for overflow */
  76.471 +#if defined(__TURBOC__) && !defined(__FLAT__)
  76.472 + if (size != (unsigned long)size)
  76.473 +   ret = NULL;
  76.474 + else
  76.475 +   ret = farmalloc(size);
  76.476 +#else
  76.477 +# if defined(_MSC_VER) && defined(MAXSEG_64K)
  76.478 + if (size != (unsigned long)size)
  76.479 +   ret = NULL;
  76.480 + else
  76.481 +   ret = halloc(size, 1);
  76.482 +# else
  76.483 + if (size != (size_t)size)
  76.484 +   ret = NULL;
  76.485 + else
  76.486 +   ret = malloc((size_t)size);
  76.487 +# endif
  76.488 +#endif
  76.489 +
  76.490 +#ifndef PNG_USER_MEM_SUPPORTED
  76.491 +   if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  76.492 +      png_error(png_ptr, "Out of Memory");
  76.493 +#endif
  76.494 +
  76.495 +   return (ret);
  76.496 +}
  76.497 +
  76.498 +/* Free a pointer allocated by png_malloc().  If ptr is NULL, return
  76.499 +   without taking any action. */
  76.500 +void PNGAPI
  76.501 +png_free(png_structp png_ptr, png_voidp ptr)
  76.502 +{
  76.503 +   if (png_ptr == NULL || ptr == NULL)
  76.504 +      return;
  76.505 +
  76.506 +#ifdef PNG_USER_MEM_SUPPORTED
  76.507 +   if (png_ptr->free_fn != NULL)
  76.508 +   {
  76.509 +      (*(png_ptr->free_fn))(png_ptr, ptr);
  76.510 +      return;
  76.511 +   }
  76.512 +   else png_free_default(png_ptr, ptr);
  76.513 +}
  76.514 +void PNGAPI
  76.515 +png_free_default(png_structp png_ptr, png_voidp ptr)
  76.516 +{
  76.517 +   if (png_ptr == NULL || ptr == NULL)
  76.518 +      return;
  76.519 +
  76.520 +#endif /* PNG_USER_MEM_SUPPORTED */
  76.521 +
  76.522 +#if defined(__TURBOC__) && !defined(__FLAT__)
  76.523 +   farfree(ptr);
  76.524 +#else
  76.525 +# if defined(_MSC_VER) && defined(MAXSEG_64K)
  76.526 +   hfree(ptr);
  76.527 +# else
  76.528 +   free(ptr);
  76.529 +# endif
  76.530 +#endif
  76.531 +}
  76.532 +
  76.533 +#endif /* Not Borland DOS special memory handler */
  76.534 +
  76.535 +#if defined(PNG_1_0_X)
  76.536 +#  define png_malloc_warn png_malloc
  76.537 +#else
  76.538 +/* This function was added at libpng version 1.2.3.  The png_malloc_warn()
  76.539 + * function will set up png_malloc() to issue a png_warning and return NULL
  76.540 + * instead of issuing a png_error, if it fails to allocate the requested
  76.541 + * memory.
  76.542 + */
  76.543 +png_voidp PNGAPI
  76.544 +png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  76.545 +{
  76.546 +   png_voidp ptr;
  76.547 +   png_uint_32 save_flags;
  76.548 +   if (png_ptr == NULL) return (NULL);
  76.549 +
  76.550 +   save_flags = png_ptr->flags;
  76.551 +   png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  76.552 +   ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  76.553 +   png_ptr->flags=save_flags;
  76.554 +   return(ptr);
  76.555 +}
  76.556 +#endif
  76.557 +
  76.558 +png_voidp PNGAPI
  76.559 +png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  76.560 +   png_uint_32 length)
  76.561 +{
  76.562 +   png_size_t size;
  76.563 +
  76.564 +   size = (png_size_t)length;
  76.565 +   if ((png_uint_32)size != length)
  76.566 +      png_error(png_ptr, "Overflow in png_memcpy_check.");
  76.567 +
  76.568 +   return(png_memcpy (s1, s2, size));
  76.569 +}
  76.570 +
  76.571 +png_voidp PNGAPI
  76.572 +png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  76.573 +   png_uint_32 length)
  76.574 +{
  76.575 +   png_size_t size;
  76.576 +
  76.577 +   size = (png_size_t)length;
  76.578 +   if ((png_uint_32)size != length)
  76.579 +      png_error(png_ptr, "Overflow in png_memset_check.");
  76.580 +
  76.581 +   return (png_memset (s1, value, size));
  76.582 +
  76.583 +}
  76.584 +
  76.585 +#ifdef PNG_USER_MEM_SUPPORTED
  76.586 +/* This function is called when the application wants to use another method
  76.587 + * of allocating and freeing memory.
  76.588 + */
  76.589 +void PNGAPI
  76.590 +png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  76.591 +  malloc_fn, png_free_ptr free_fn)
  76.592 +{
  76.593 +   if (png_ptr != NULL)
  76.594 +   {
  76.595 +      png_ptr->mem_ptr = mem_ptr;
  76.596 +      png_ptr->malloc_fn = malloc_fn;
  76.597 +      png_ptr->free_fn = free_fn;
  76.598 +   }
  76.599 +}
  76.600 +
  76.601 +/* This function returns a pointer to the mem_ptr associated with the user
  76.602 + * functions.  The application should free any memory associated with this
  76.603 + * pointer before png_write_destroy and png_read_destroy are called.
  76.604 + */
  76.605 +png_voidp PNGAPI
  76.606 +png_get_mem_ptr(png_structp png_ptr)
  76.607 +{
  76.608 +   if (png_ptr == NULL) return (NULL);
  76.609 +   return ((png_voidp)png_ptr->mem_ptr);
  76.610 +}
  76.611 +#endif /* PNG_USER_MEM_SUPPORTED */
  76.612 +#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
    77.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    77.2 +++ b/libs/libpng/pngpread.c	Thu Sep 08 06:28:38 2011 +0300
    77.3 @@ -0,0 +1,1594 @@
    77.4 +
    77.5 +/* pngpread.c - read a png file in push mode
    77.6 + *
    77.7 + * Last changed in libpng 1.2.32 [September 18, 2008]
    77.8 + * For conditions of distribution and use, see copyright notice in png.h
    77.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   77.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   77.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   77.12 + */
   77.13 +
   77.14 +#define PNG_INTERNAL
   77.15 +#include "png.h"
   77.16 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
   77.17 +
   77.18 +/* push model modes */
   77.19 +#define PNG_READ_SIG_MODE   0
   77.20 +#define PNG_READ_CHUNK_MODE 1
   77.21 +#define PNG_READ_IDAT_MODE  2
   77.22 +#define PNG_SKIP_MODE       3
   77.23 +#define PNG_READ_tEXt_MODE  4
   77.24 +#define PNG_READ_zTXt_MODE  5
   77.25 +#define PNG_READ_DONE_MODE  6
   77.26 +#define PNG_READ_iTXt_MODE  7
   77.27 +#define PNG_ERROR_MODE      8
   77.28 +
   77.29 +void PNGAPI
   77.30 +png_process_data(png_structp png_ptr, png_infop info_ptr,
   77.31 +   png_bytep buffer, png_size_t buffer_size)
   77.32 +{
   77.33 +   if (png_ptr == NULL || info_ptr == NULL) return;
   77.34 +   png_push_restore_buffer(png_ptr, buffer, buffer_size);
   77.35 +
   77.36 +   while (png_ptr->buffer_size)
   77.37 +   {
   77.38 +      png_process_some_data(png_ptr, info_ptr);
   77.39 +   }
   77.40 +}
   77.41 +
   77.42 +/* What we do with the incoming data depends on what we were previously
   77.43 + * doing before we ran out of data...
   77.44 + */
   77.45 +void /* PRIVATE */
   77.46 +png_process_some_data(png_structp png_ptr, png_infop info_ptr)
   77.47 +{
   77.48 +   if (png_ptr == NULL) return;
   77.49 +   switch (png_ptr->process_mode)
   77.50 +   {
   77.51 +      case PNG_READ_SIG_MODE:
   77.52 +      {
   77.53 +         png_push_read_sig(png_ptr, info_ptr);
   77.54 +         break;
   77.55 +      }
   77.56 +      case PNG_READ_CHUNK_MODE:
   77.57 +      {
   77.58 +         png_push_read_chunk(png_ptr, info_ptr);
   77.59 +         break;
   77.60 +      }
   77.61 +      case PNG_READ_IDAT_MODE:
   77.62 +      {
   77.63 +         png_push_read_IDAT(png_ptr);
   77.64 +         break;
   77.65 +      }
   77.66 +#if defined(PNG_READ_tEXt_SUPPORTED)
   77.67 +      case PNG_READ_tEXt_MODE:
   77.68 +      {
   77.69 +         png_push_read_tEXt(png_ptr, info_ptr);
   77.70 +         break;
   77.71 +      }
   77.72 +#endif
   77.73 +#if defined(PNG_READ_zTXt_SUPPORTED)
   77.74 +      case PNG_READ_zTXt_MODE:
   77.75 +      {
   77.76 +         png_push_read_zTXt(png_ptr, info_ptr);
   77.77 +         break;
   77.78 +      }
   77.79 +#endif
   77.80 +#if defined(PNG_READ_iTXt_SUPPORTED)
   77.81 +      case PNG_READ_iTXt_MODE:
   77.82 +      {
   77.83 +         png_push_read_iTXt(png_ptr, info_ptr);
   77.84 +         break;
   77.85 +      }
   77.86 +#endif
   77.87 +      case PNG_SKIP_MODE:
   77.88 +      {
   77.89 +         png_push_crc_finish(png_ptr);
   77.90 +         break;
   77.91 +      }
   77.92 +      default:
   77.93 +      {
   77.94 +         png_ptr->buffer_size = 0;
   77.95 +         break;
   77.96 +      }
   77.97 +   }
   77.98 +}
   77.99 +
  77.100 +/* Read any remaining signature bytes from the stream and compare them with
  77.101 + * the correct PNG signature.  It is possible that this routine is called
  77.102 + * with bytes already read from the signature, either because they have been
  77.103 + * checked by the calling application, or because of multiple calls to this
  77.104 + * routine.
  77.105 + */
  77.106 +void /* PRIVATE */
  77.107 +png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  77.108 +{
  77.109 +   png_size_t num_checked = png_ptr->sig_bytes,
  77.110 +             num_to_check = 8 - num_checked;
  77.111 +
  77.112 +   if (png_ptr->buffer_size < num_to_check)
  77.113 +   {
  77.114 +      num_to_check = png_ptr->buffer_size;
  77.115 +   }
  77.116 +
  77.117 +   png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  77.118 +      num_to_check);
  77.119 +   png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes + num_to_check);
  77.120 +
  77.121 +   if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  77.122 +   {
  77.123 +      if (num_checked < 4 &&
  77.124 +          png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  77.125 +         png_error(png_ptr, "Not a PNG file");
  77.126 +      else
  77.127 +         png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  77.128 +   }
  77.129 +   else
  77.130 +   {
  77.131 +      if (png_ptr->sig_bytes >= 8)
  77.132 +      {
  77.133 +         png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  77.134 +      }
  77.135 +   }
  77.136 +}
  77.137 +
  77.138 +void /* PRIVATE */
  77.139 +png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  77.140 +{
  77.141 +#ifdef PNG_USE_LOCAL_ARRAYS
  77.142 +      PNG_CONST PNG_IHDR;
  77.143 +      PNG_CONST PNG_IDAT;
  77.144 +      PNG_CONST PNG_IEND;
  77.145 +      PNG_CONST PNG_PLTE;
  77.146 +#if defined(PNG_READ_bKGD_SUPPORTED)
  77.147 +      PNG_CONST PNG_bKGD;
  77.148 +#endif
  77.149 +#if defined(PNG_READ_cHRM_SUPPORTED)
  77.150 +      PNG_CONST PNG_cHRM;
  77.151 +#endif
  77.152 +#if defined(PNG_READ_gAMA_SUPPORTED)
  77.153 +      PNG_CONST PNG_gAMA;
  77.154 +#endif
  77.155 +#if defined(PNG_READ_hIST_SUPPORTED)
  77.156 +      PNG_CONST PNG_hIST;
  77.157 +#endif
  77.158 +#if defined(PNG_READ_iCCP_SUPPORTED)
  77.159 +      PNG_CONST PNG_iCCP;
  77.160 +#endif
  77.161 +#if defined(PNG_READ_iTXt_SUPPORTED)
  77.162 +      PNG_CONST PNG_iTXt;
  77.163 +#endif
  77.164 +#if defined(PNG_READ_oFFs_SUPPORTED)
  77.165 +      PNG_CONST PNG_oFFs;
  77.166 +#endif
  77.167 +#if defined(PNG_READ_pCAL_SUPPORTED)
  77.168 +      PNG_CONST PNG_pCAL;
  77.169 +#endif
  77.170 +#if defined(PNG_READ_pHYs_SUPPORTED)
  77.171 +      PNG_CONST PNG_pHYs;
  77.172 +#endif
  77.173 +#if defined(PNG_READ_sBIT_SUPPORTED)
  77.174 +      PNG_CONST PNG_sBIT;
  77.175 +#endif
  77.176 +#if defined(PNG_READ_sCAL_SUPPORTED)
  77.177 +      PNG_CONST PNG_sCAL;
  77.178 +#endif
  77.179 +#if defined(PNG_READ_sRGB_SUPPORTED)
  77.180 +      PNG_CONST PNG_sRGB;
  77.181 +#endif
  77.182 +#if defined(PNG_READ_sPLT_SUPPORTED)
  77.183 +      PNG_CONST PNG_sPLT;
  77.184 +#endif
  77.185 +#if defined(PNG_READ_tEXt_SUPPORTED)
  77.186 +      PNG_CONST PNG_tEXt;
  77.187 +#endif
  77.188 +#if defined(PNG_READ_tIME_SUPPORTED)
  77.189 +      PNG_CONST PNG_tIME;
  77.190 +#endif
  77.191 +#if defined(PNG_READ_tRNS_SUPPORTED)
  77.192 +      PNG_CONST PNG_tRNS;
  77.193 +#endif
  77.194 +#if defined(PNG_READ_zTXt_SUPPORTED)
  77.195 +      PNG_CONST PNG_zTXt;
  77.196 +#endif
  77.197 +#endif /* PNG_USE_LOCAL_ARRAYS */
  77.198 +   /* First we make sure we have enough data for the 4 byte chunk name
  77.199 +    * and the 4 byte chunk length before proceeding with decoding the
  77.200 +    * chunk data.  To fully decode each of these chunks, we also make
  77.201 +    * sure we have enough data in the buffer for the 4 byte CRC at the
  77.202 +    * end of every chunk (except IDAT, which is handled separately).
  77.203 +    */
  77.204 +   if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  77.205 +   {
  77.206 +      png_byte chunk_length[4];
  77.207 +
  77.208 +      if (png_ptr->buffer_size < 8)
  77.209 +      {
  77.210 +         png_push_save_buffer(png_ptr);
  77.211 +         return;
  77.212 +      }
  77.213 +
  77.214 +      png_push_fill_buffer(png_ptr, chunk_length, 4);
  77.215 +      png_ptr->push_length = png_get_uint_31(png_ptr, chunk_length);
  77.216 +      png_reset_crc(png_ptr);
  77.217 +      png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  77.218 +      png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  77.219 +      png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  77.220 +   }
  77.221 +
  77.222 +   if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  77.223 +     if (png_ptr->mode & PNG_AFTER_IDAT)
  77.224 +        png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  77.225 +
  77.226 +   if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  77.227 +   {
  77.228 +      if (png_ptr->push_length != 13)
  77.229 +         png_error(png_ptr, "Invalid IHDR length");
  77.230 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.231 +      {
  77.232 +         png_push_save_buffer(png_ptr);
  77.233 +         return;
  77.234 +      }
  77.235 +      png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  77.236 +   }
  77.237 +   else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  77.238 +   {
  77.239 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.240 +      {
  77.241 +         png_push_save_buffer(png_ptr);
  77.242 +         return;
  77.243 +      }
  77.244 +      png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  77.245 +
  77.246 +      png_ptr->process_mode = PNG_READ_DONE_MODE;
  77.247 +      png_push_have_end(png_ptr, info_ptr);
  77.248 +   }
  77.249 +#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  77.250 +   else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  77.251 +   {
  77.252 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.253 +      {
  77.254 +         png_push_save_buffer(png_ptr);
  77.255 +         return;
  77.256 +      }
  77.257 +      if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  77.258 +         png_ptr->mode |= PNG_HAVE_IDAT;
  77.259 +      png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  77.260 +      if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  77.261 +         png_ptr->mode |= PNG_HAVE_PLTE;
  77.262 +      else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  77.263 +      {
  77.264 +         if (!(png_ptr->mode & PNG_HAVE_IHDR))
  77.265 +            png_error(png_ptr, "Missing IHDR before IDAT");
  77.266 +         else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  77.267 +                  !(png_ptr->mode & PNG_HAVE_PLTE))
  77.268 +            png_error(png_ptr, "Missing PLTE before IDAT");
  77.269 +      }
  77.270 +   }
  77.271 +#endif
  77.272 +   else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  77.273 +   {
  77.274 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.275 +      {
  77.276 +         png_push_save_buffer(png_ptr);
  77.277 +         return;
  77.278 +      }
  77.279 +      png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  77.280 +   }
  77.281 +   else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  77.282 +   {
  77.283 +      /* If we reach an IDAT chunk, this means we have read all of the
  77.284 +       * header chunks, and we can start reading the image (or if this
  77.285 +       * is called after the image has been read - we have an error).
  77.286 +       */
  77.287 +     if (!(png_ptr->mode & PNG_HAVE_IHDR))
  77.288 +       png_error(png_ptr, "Missing IHDR before IDAT");
  77.289 +     else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  77.290 +         !(png_ptr->mode & PNG_HAVE_PLTE))
  77.291 +       png_error(png_ptr, "Missing PLTE before IDAT");
  77.292 +
  77.293 +      if (png_ptr->mode & PNG_HAVE_IDAT)
  77.294 +      {
  77.295 +         if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  77.296 +           if (png_ptr->push_length == 0)
  77.297 +              return;
  77.298 +
  77.299 +         if (png_ptr->mode & PNG_AFTER_IDAT)
  77.300 +            png_error(png_ptr, "Too many IDAT's found");
  77.301 +      }
  77.302 +
  77.303 +      png_ptr->idat_size = png_ptr->push_length;
  77.304 +      png_ptr->mode |= PNG_HAVE_IDAT;
  77.305 +      png_ptr->process_mode = PNG_READ_IDAT_MODE;
  77.306 +      png_push_have_info(png_ptr, info_ptr);
  77.307 +      png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  77.308 +      png_ptr->zstream.next_out = png_ptr->row_buf;
  77.309 +      return;
  77.310 +   }
  77.311 +#if defined(PNG_READ_gAMA_SUPPORTED)
  77.312 +   else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  77.313 +   {
  77.314 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.315 +      {
  77.316 +         png_push_save_buffer(png_ptr);
  77.317 +         return;
  77.318 +      }
  77.319 +      png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  77.320 +   }
  77.321 +#endif
  77.322 +#if defined(PNG_READ_sBIT_SUPPORTED)
  77.323 +   else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  77.324 +   {
  77.325 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.326 +      {
  77.327 +         png_push_save_buffer(png_ptr);
  77.328 +         return;
  77.329 +      }
  77.330 +      png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  77.331 +   }
  77.332 +#endif
  77.333 +#if defined(PNG_READ_cHRM_SUPPORTED)
  77.334 +   else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  77.335 +   {
  77.336 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.337 +      {
  77.338 +         png_push_save_buffer(png_ptr);
  77.339 +         return;
  77.340 +      }
  77.341 +      png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  77.342 +   }
  77.343 +#endif
  77.344 +#if defined(PNG_READ_sRGB_SUPPORTED)
  77.345 +   else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  77.346 +   {
  77.347 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.348 +      {
  77.349 +         png_push_save_buffer(png_ptr);
  77.350 +         return;
  77.351 +      }
  77.352 +      png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  77.353 +   }
  77.354 +#endif
  77.355 +#if defined(PNG_READ_iCCP_SUPPORTED)
  77.356 +   else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  77.357 +   {
  77.358 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.359 +      {
  77.360 +         png_push_save_buffer(png_ptr);
  77.361 +         return;
  77.362 +      }
  77.363 +      png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  77.364 +   }
  77.365 +#endif
  77.366 +#if defined(PNG_READ_sPLT_SUPPORTED)
  77.367 +   else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  77.368 +   {
  77.369 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.370 +      {
  77.371 +         png_push_save_buffer(png_ptr);
  77.372 +         return;
  77.373 +      }
  77.374 +      png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  77.375 +   }
  77.376 +#endif
  77.377 +#if defined(PNG_READ_tRNS_SUPPORTED)
  77.378 +   else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  77.379 +   {
  77.380 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.381 +      {
  77.382 +         png_push_save_buffer(png_ptr);
  77.383 +         return;
  77.384 +      }
  77.385 +      png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  77.386 +   }
  77.387 +#endif
  77.388 +#if defined(PNG_READ_bKGD_SUPPORTED)
  77.389 +   else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  77.390 +   {
  77.391 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.392 +      {
  77.393 +         png_push_save_buffer(png_ptr);
  77.394 +         return;
  77.395 +      }
  77.396 +      png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  77.397 +   }
  77.398 +#endif
  77.399 +#if defined(PNG_READ_hIST_SUPPORTED)
  77.400 +   else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  77.401 +   {
  77.402 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.403 +      {
  77.404 +         png_push_save_buffer(png_ptr);
  77.405 +         return;
  77.406 +      }
  77.407 +      png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  77.408 +   }
  77.409 +#endif
  77.410 +#if defined(PNG_READ_pHYs_SUPPORTED)
  77.411 +   else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  77.412 +   {
  77.413 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.414 +      {
  77.415 +         png_push_save_buffer(png_ptr);
  77.416 +         return;
  77.417 +      }
  77.418 +      png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  77.419 +   }
  77.420 +#endif
  77.421 +#if defined(PNG_READ_oFFs_SUPPORTED)
  77.422 +   else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  77.423 +   {
  77.424 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.425 +      {
  77.426 +         png_push_save_buffer(png_ptr);
  77.427 +         return;
  77.428 +      }
  77.429 +      png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  77.430 +   }
  77.431 +#endif
  77.432 +#if defined(PNG_READ_pCAL_SUPPORTED)
  77.433 +   else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  77.434 +   {
  77.435 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.436 +      {
  77.437 +         png_push_save_buffer(png_ptr);
  77.438 +         return;
  77.439 +      }
  77.440 +      png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  77.441 +   }
  77.442 +#endif
  77.443 +#if defined(PNG_READ_sCAL_SUPPORTED)
  77.444 +   else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  77.445 +   {
  77.446 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.447 +      {
  77.448 +         png_push_save_buffer(png_ptr);
  77.449 +         return;
  77.450 +      }
  77.451 +      png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  77.452 +   }
  77.453 +#endif
  77.454 +#if defined(PNG_READ_tIME_SUPPORTED)
  77.455 +   else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  77.456 +   {
  77.457 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.458 +      {
  77.459 +         png_push_save_buffer(png_ptr);
  77.460 +         return;
  77.461 +      }
  77.462 +      png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  77.463 +   }
  77.464 +#endif
  77.465 +#if defined(PNG_READ_tEXt_SUPPORTED)
  77.466 +   else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  77.467 +   {
  77.468 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.469 +      {
  77.470 +         png_push_save_buffer(png_ptr);
  77.471 +         return;
  77.472 +      }
  77.473 +      png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  77.474 +   }
  77.475 +#endif
  77.476 +#if defined(PNG_READ_zTXt_SUPPORTED)
  77.477 +   else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  77.478 +   {
  77.479 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.480 +      {
  77.481 +         png_push_save_buffer(png_ptr);
  77.482 +         return;
  77.483 +      }
  77.484 +      png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  77.485 +   }
  77.486 +#endif
  77.487 +#if defined(PNG_READ_iTXt_SUPPORTED)
  77.488 +   else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  77.489 +   {
  77.490 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.491 +      {
  77.492 +         png_push_save_buffer(png_ptr);
  77.493 +         return;
  77.494 +      }
  77.495 +      png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  77.496 +   }
  77.497 +#endif
  77.498 +   else
  77.499 +   {
  77.500 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  77.501 +      {
  77.502 +         png_push_save_buffer(png_ptr);
  77.503 +         return;
  77.504 +      }
  77.505 +      png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  77.506 +   }
  77.507 +
  77.508 +   png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  77.509 +}
  77.510 +
  77.511 +void /* PRIVATE */
  77.512 +png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  77.513 +{
  77.514 +   png_ptr->process_mode = PNG_SKIP_MODE;
  77.515 +   png_ptr->skip_length = skip;
  77.516 +}
  77.517 +
  77.518 +void /* PRIVATE */
  77.519 +png_push_crc_finish(png_structp png_ptr)
  77.520 +{
  77.521 +   if (png_ptr->skip_length && png_ptr->save_buffer_size)
  77.522 +   {
  77.523 +      png_size_t save_size;
  77.524 +
  77.525 +      if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  77.526 +         save_size = (png_size_t)png_ptr->skip_length;
  77.527 +      else
  77.528 +         save_size = png_ptr->save_buffer_size;
  77.529 +
  77.530 +      png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  77.531 +
  77.532 +      png_ptr->skip_length -= save_size;
  77.533 +      png_ptr->buffer_size -= save_size;
  77.534 +      png_ptr->save_buffer_size -= save_size;
  77.535 +      png_ptr->save_buffer_ptr += save_size;
  77.536 +   }
  77.537 +   if (png_ptr->skip_length && png_ptr->current_buffer_size)
  77.538 +   {
  77.539 +      png_size_t save_size;
  77.540 +
  77.541 +      if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  77.542 +         save_size = (png_size_t)png_ptr->skip_length;
  77.543 +      else
  77.544 +         save_size = png_ptr->current_buffer_size;
  77.545 +
  77.546 +      png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  77.547 +
  77.548 +      png_ptr->skip_length -= save_size;
  77.549 +      png_ptr->buffer_size -= save_size;
  77.550 +      png_ptr->current_buffer_size -= save_size;
  77.551 +      png_ptr->current_buffer_ptr += save_size;
  77.552 +   }
  77.553 +   if (!png_ptr->skip_length)
  77.554 +   {
  77.555 +      if (png_ptr->buffer_size < 4)
  77.556 +      {
  77.557 +         png_push_save_buffer(png_ptr);
  77.558 +         return;
  77.559 +      }
  77.560 +
  77.561 +      png_crc_finish(png_ptr, 0);
  77.562 +      png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  77.563 +   }
  77.564 +}
  77.565 +
  77.566 +void PNGAPI
  77.567 +png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  77.568 +{
  77.569 +   png_bytep ptr;
  77.570 +
  77.571 +   if (png_ptr == NULL) return;
  77.572 +   ptr = buffer;
  77.573 +   if (png_ptr->save_buffer_size)
  77.574 +   {
  77.575 +      png_size_t save_size;
  77.576 +
  77.577 +      if (length < png_ptr->save_buffer_size)
  77.578 +         save_size = length;
  77.579 +      else
  77.580 +         save_size = png_ptr->save_buffer_size;
  77.581 +
  77.582 +      png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  77.583 +      length -= save_size;
  77.584 +      ptr += save_size;
  77.585 +      png_ptr->buffer_size -= save_size;
  77.586 +      png_ptr->save_buffer_size -= save_size;
  77.587 +      png_ptr->save_buffer_ptr += save_size;
  77.588 +   }
  77.589 +   if (length && png_ptr->current_buffer_size)
  77.590 +   {
  77.591 +      png_size_t save_size;
  77.592 +
  77.593 +      if (length < png_ptr->current_buffer_size)
  77.594 +         save_size = length;
  77.595 +      else
  77.596 +         save_size = png_ptr->current_buffer_size;
  77.597 +
  77.598 +      png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  77.599 +      png_ptr->buffer_size -= save_size;
  77.600 +      png_ptr->current_buffer_size -= save_size;
  77.601 +      png_ptr->current_buffer_ptr += save_size;
  77.602 +   }
  77.603 +}
  77.604 +
  77.605 +void /* PRIVATE */
  77.606 +png_push_save_buffer(png_structp png_ptr)
  77.607 +{
  77.608 +   if (png_ptr->save_buffer_size)
  77.609 +   {
  77.610 +      if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  77.611 +      {
  77.612 +         png_size_t i, istop;
  77.613 +         png_bytep sp;
  77.614 +         png_bytep dp;
  77.615 +
  77.616 +         istop = png_ptr->save_buffer_size;
  77.617 +         for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  77.618 +            i < istop; i++, sp++, dp++)
  77.619 +         {
  77.620 +            *dp = *sp;
  77.621 +         }
  77.622 +      }
  77.623 +   }
  77.624 +   if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  77.625 +      png_ptr->save_buffer_max)
  77.626 +   {
  77.627 +      png_size_t new_max;
  77.628 +      png_bytep old_buffer;
  77.629 +
  77.630 +      if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  77.631 +         (png_ptr->current_buffer_size + 256))
  77.632 +      {
  77.633 +        png_error(png_ptr, "Potential overflow of save_buffer");
  77.634 +      }
  77.635 +      new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  77.636 +      old_buffer = png_ptr->save_buffer;
  77.637 +      png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  77.638 +         (png_uint_32)new_max);
  77.639 +      png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  77.640 +      png_free(png_ptr, old_buffer);
  77.641 +      png_ptr->save_buffer_max = new_max;
  77.642 +   }
  77.643 +   if (png_ptr->current_buffer_size)
  77.644 +   {
  77.645 +      png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  77.646 +         png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  77.647 +      png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  77.648 +      png_ptr->current_buffer_size = 0;
  77.649 +   }
  77.650 +   png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  77.651 +   png_ptr->buffer_size = 0;
  77.652 +}
  77.653 +
  77.654 +void /* PRIVATE */
  77.655 +png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  77.656 +   png_size_t buffer_length)
  77.657 +{
  77.658 +   png_ptr->current_buffer = buffer;
  77.659 +   png_ptr->current_buffer_size = buffer_length;
  77.660 +   png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  77.661 +   png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  77.662 +}
  77.663 +
  77.664 +void /* PRIVATE */
  77.665 +png_push_read_IDAT(png_structp png_ptr)
  77.666 +{
  77.667 +#ifdef PNG_USE_LOCAL_ARRAYS
  77.668 +   PNG_CONST PNG_IDAT;
  77.669 +#endif
  77.670 +   if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  77.671 +   {
  77.672 +      png_byte chunk_length[4];
  77.673 +
  77.674 +      if (png_ptr->buffer_size < 8)
  77.675 +      {
  77.676 +         png_push_save_buffer(png_ptr);
  77.677 +         return;
  77.678 +      }
  77.679 +
  77.680 +      png_push_fill_buffer(png_ptr, chunk_length, 4);
  77.681 +      png_ptr->push_length = png_get_uint_31(png_ptr, chunk_length);
  77.682 +      png_reset_crc(png_ptr);
  77.683 +      png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  77.684 +      png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  77.685 +
  77.686 +      if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  77.687 +      {
  77.688 +         png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  77.689 +         if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  77.690 +            png_error(png_ptr, "Not enough compressed data");
  77.691 +         return;
  77.692 +      }
  77.693 +
  77.694 +      png_ptr->idat_size = png_ptr->push_length;
  77.695 +   }
  77.696 +   if (png_ptr->idat_size && png_ptr->save_buffer_size)
  77.697 +   {
  77.698 +      png_size_t save_size;
  77.699 +
  77.700 +      if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  77.701 +      {
  77.702 +         save_size = (png_size_t)png_ptr->idat_size;
  77.703 +         /* check for overflow */
  77.704 +         if ((png_uint_32)save_size != png_ptr->idat_size)
  77.705 +            png_error(png_ptr, "save_size overflowed in pngpread");
  77.706 +      }
  77.707 +      else
  77.708 +         save_size = png_ptr->save_buffer_size;
  77.709 +
  77.710 +      png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  77.711 +      if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  77.712 +         png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  77.713 +      png_ptr->idat_size -= save_size;
  77.714 +      png_ptr->buffer_size -= save_size;
  77.715 +      png_ptr->save_buffer_size -= save_size;
  77.716 +      png_ptr->save_buffer_ptr += save_size;
  77.717 +   }
  77.718 +   if (png_ptr->idat_size && png_ptr->current_buffer_size)
  77.719 +   {
  77.720 +      png_size_t save_size;
  77.721 +
  77.722 +      if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  77.723 +      {
  77.724 +         save_size = (png_size_t)png_ptr->idat_size;
  77.725 +         /* check for overflow */
  77.726 +         if ((png_uint_32)save_size != png_ptr->idat_size)
  77.727 +            png_error(png_ptr, "save_size overflowed in pngpread");
  77.728 +      }
  77.729 +      else
  77.730 +         save_size = png_ptr->current_buffer_size;
  77.731 +
  77.732 +      png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  77.733 +      if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  77.734 +        png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  77.735 +
  77.736 +      png_ptr->idat_size -= save_size;
  77.737 +      png_ptr->buffer_size -= save_size;
  77.738 +      png_ptr->current_buffer_size -= save_size;
  77.739 +      png_ptr->current_buffer_ptr += save_size;
  77.740 +   }
  77.741 +   if (!png_ptr->idat_size)
  77.742 +   {
  77.743 +      if (png_ptr->buffer_size < 4)
  77.744 +      {
  77.745 +         png_push_save_buffer(png_ptr);
  77.746 +         return;
  77.747 +      }
  77.748 +
  77.749 +      png_crc_finish(png_ptr, 0);
  77.750 +      png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  77.751 +      png_ptr->mode |= PNG_AFTER_IDAT;
  77.752 +   }
  77.753 +}
  77.754 +
  77.755 +void /* PRIVATE */
  77.756 +png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  77.757 +   png_size_t buffer_length)
  77.758 +{
  77.759 +   int ret;
  77.760 +
  77.761 +   if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  77.762 +      png_error(png_ptr, "Extra compression data");
  77.763 +
  77.764 +   png_ptr->zstream.next_in = buffer;
  77.765 +   png_ptr->zstream.avail_in = (uInt)buffer_length;
  77.766 +   for (;;)
  77.767 +   {
  77.768 +      ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  77.769 +      if (ret != Z_OK)
  77.770 +      {
  77.771 +         if (ret == Z_STREAM_END)
  77.772 +         {
  77.773 +            if (png_ptr->zstream.avail_in)
  77.774 +               png_error(png_ptr, "Extra compressed data");
  77.775 +            if (!(png_ptr->zstream.avail_out))
  77.776 +            {
  77.777 +               png_push_process_row(png_ptr);
  77.778 +            }
  77.779 +
  77.780 +            png_ptr->mode |= PNG_AFTER_IDAT;
  77.781 +            png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  77.782 +            break;
  77.783 +         }
  77.784 +         else if (ret == Z_BUF_ERROR)
  77.785 +            break;
  77.786 +         else
  77.787 +            png_error(png_ptr, "Decompression Error");
  77.788 +      }
  77.789 +      if (!(png_ptr->zstream.avail_out))
  77.790 +      {
  77.791 +         if ((
  77.792 +#if defined(PNG_READ_INTERLACING_SUPPORTED)
  77.793 +             png_ptr->interlaced && png_ptr->pass > 6) ||
  77.794 +             (!png_ptr->interlaced &&
  77.795 +#endif
  77.796 +             png_ptr->row_number == png_ptr->num_rows))
  77.797 +         {
  77.798 +           if (png_ptr->zstream.avail_in)
  77.799 +             png_warning(png_ptr, "Too much data in IDAT chunks");
  77.800 +           png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  77.801 +           break;
  77.802 +         }
  77.803 +         png_push_process_row(png_ptr);
  77.804 +         png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  77.805 +         png_ptr->zstream.next_out = png_ptr->row_buf;
  77.806 +      }
  77.807 +      else
  77.808 +         break;
  77.809 +   }
  77.810 +}
  77.811 +
  77.812 +void /* PRIVATE */
  77.813 +png_push_process_row(png_structp png_ptr)
  77.814 +{
  77.815 +   png_ptr->row_info.color_type = png_ptr->color_type;
  77.816 +   png_ptr->row_info.width = png_ptr->iwidth;
  77.817 +   png_ptr->row_info.channels = png_ptr->channels;
  77.818 +   png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  77.819 +   png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  77.820 +
  77.821 +   png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  77.822 +       png_ptr->row_info.width);
  77.823 +
  77.824 +   png_read_filter_row(png_ptr, &(png_ptr->row_info),
  77.825 +      png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  77.826 +      (int)(png_ptr->row_buf[0]));
  77.827 +
  77.828 +   png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  77.829 +      png_ptr->rowbytes + 1);
  77.830 +
  77.831 +   if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  77.832 +      png_do_read_transformations(png_ptr);
  77.833 +
  77.834 +#if defined(PNG_READ_INTERLACING_SUPPORTED)
  77.835 +   /* blow up interlaced rows to full size */
  77.836 +   if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  77.837 +   {
  77.838 +      if (png_ptr->pass < 6)
  77.839 +/*       old interface (pre-1.0.9):
  77.840 +         png_do_read_interlace(&(png_ptr->row_info),
  77.841 +            png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  77.842 + */
  77.843 +         png_do_read_interlace(png_ptr);
  77.844 +
  77.845 +    switch (png_ptr->pass)
  77.846 +    {
  77.847 +         case 0:
  77.848 +         {
  77.849 +            int i;
  77.850 +            for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  77.851 +            {
  77.852 +               png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  77.853 +               png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  77.854 +            }
  77.855 +            if (png_ptr->pass == 2) /* pass 1 might be empty */
  77.856 +            {
  77.857 +               for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  77.858 +               {
  77.859 +                  png_push_have_row(png_ptr, png_bytep_NULL);
  77.860 +                  png_read_push_finish_row(png_ptr);
  77.861 +               }
  77.862 +            }
  77.863 +            if (png_ptr->pass == 4 && png_ptr->height <= 4)
  77.864 +            {
  77.865 +               for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  77.866 +               {
  77.867 +                  png_push_have_row(png_ptr, png_bytep_NULL);
  77.868 +                  png_read_push_finish_row(png_ptr);
  77.869 +               }
  77.870 +            }
  77.871 +            if (png_ptr->pass == 6 && png_ptr->height <= 4)
  77.872 +            {
  77.873 +                png_push_have_row(png_ptr, png_bytep_NULL);
  77.874 +                png_read_push_finish_row(png_ptr);
  77.875 +            }
  77.876 +            break;
  77.877 +         }
  77.878 +         case 1:
  77.879 +         {
  77.880 +            int i;
  77.881 +            for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  77.882 +            {
  77.883 +               png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  77.884 +               png_read_push_finish_row(png_ptr);
  77.885 +            }
  77.886 +            if (png_ptr->pass == 2) /* skip top 4 generated rows */
  77.887 +            {
  77.888 +               for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  77.889 +               {
  77.890 +                  png_push_have_row(png_ptr, png_bytep_NULL);
  77.891 +                  png_read_push_finish_row(png_ptr);
  77.892 +               }
  77.893 +            }
  77.894 +            break;
  77.895 +         }
  77.896 +         case 2:
  77.897 +         {
  77.898 +            int i;
  77.899 +            for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  77.900 +            {
  77.901 +               png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  77.902 +               png_read_push_finish_row(png_ptr);
  77.903 +            }
  77.904 +            for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  77.905 +            {
  77.906 +               png_push_have_row(png_ptr, png_bytep_NULL);
  77.907 +               png_read_push_finish_row(png_ptr);
  77.908 +            }
  77.909 +            if (png_ptr->pass == 4) /* pass 3 might be empty */
  77.910 +            {
  77.911 +               for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  77.912 +               {
  77.913 +                  png_push_have_row(png_ptr, png_bytep_NULL);
  77.914 +                  png_read_push_finish_row(png_ptr);
  77.915 +               }
  77.916 +            }
  77.917 +            break;
  77.918 +         }
  77.919 +         case 3:
  77.920 +         {
  77.921 +            int i;
  77.922 +            for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  77.923 +            {
  77.924 +               png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  77.925 +               png_read_push_finish_row(png_ptr);
  77.926 +            }
  77.927 +            if (png_ptr->pass == 4) /* skip top two generated rows */
  77.928 +            {
  77.929 +               for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  77.930 +               {
  77.931 +                  png_push_have_row(png_ptr, png_bytep_NULL);
  77.932 +                  png_read_push_finish_row(png_ptr);
  77.933 +               }
  77.934 +            }
  77.935 +            break;
  77.936 +         }
  77.937 +         case 4:
  77.938 +         {
  77.939 +            int i;
  77.940 +            for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  77.941 +            {
  77.942 +               png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  77.943 +               png_read_push_finish_row(png_ptr);
  77.944 +            }
  77.945 +            for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  77.946 +            {
  77.947 +               png_push_have_row(png_ptr, png_bytep_NULL);
  77.948 +               png_read_push_finish_row(png_ptr);
  77.949 +            }
  77.950 +            if (png_ptr->pass == 6) /* pass 5 might be empty */
  77.951 +            {
  77.952 +               png_push_have_row(png_ptr, png_bytep_NULL);
  77.953 +               png_read_push_finish_row(png_ptr);
  77.954 +            }
  77.955 +            break;
  77.956 +         }
  77.957 +         case 5:
  77.958 +         {
  77.959 +            int i;
  77.960 +            for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  77.961 +            {
  77.962 +               png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  77.963 +               png_read_push_finish_row(png_ptr);
  77.964 +            }
  77.965 +            if (png_ptr->pass == 6) /* skip top generated row */
  77.966 +            {
  77.967 +               png_push_have_row(png_ptr, png_bytep_NULL);
  77.968 +               png_read_push_finish_row(png_ptr);
  77.969 +            }
  77.970 +            break;
  77.971 +         }
  77.972 +         case 6:
  77.973 +         {
  77.974 +            png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  77.975 +            png_read_push_finish_row(png_ptr);
  77.976 +            if (png_ptr->pass != 6)
  77.977 +               break;
  77.978 +            png_push_have_row(png_ptr, png_bytep_NULL);
  77.979 +            png_read_push_finish_row(png_ptr);
  77.980 +         }
  77.981 +      }
  77.982 +   }
  77.983 +   else
  77.984 +#endif
  77.985 +   {
  77.986 +      png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  77.987 +      png_read_push_finish_row(png_ptr);
  77.988 +   }
  77.989 +}
  77.990 +
  77.991 +void /* PRIVATE */
  77.992 +png_read_push_finish_row(png_structp png_ptr)
  77.993 +{
  77.994 +#ifdef PNG_USE_LOCAL_ARRAYS
  77.995 +   /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  77.996 +
  77.997 +   /* start of interlace block */
  77.998 +   PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  77.999 +
 77.1000 +   /* offset to next interlace block */
 77.1001 +   PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
 77.1002 +
 77.1003 +   /* start of interlace block in the y direction */
 77.1004 +   PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
 77.1005 +
 77.1006 +   /* offset to next interlace block in the y direction */
 77.1007 +   PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
 77.1008 +
 77.1009 +   /* Height of interlace block.  This is not currently used - if you need
 77.1010 +    * it, uncomment it here and in png.h
 77.1011 +   PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
 77.1012 +   */
 77.1013 +#endif
 77.1014 +
 77.1015 +   png_ptr->row_number++;
 77.1016 +   if (png_ptr->row_number < png_ptr->num_rows)
 77.1017 +      return;
 77.1018 +
 77.1019 +   if (png_ptr->interlaced)
 77.1020 +   {
 77.1021 +      png_ptr->row_number = 0;
 77.1022 +      png_memset_check(png_ptr, png_ptr->prev_row, 0,
 77.1023 +         png_ptr->rowbytes + 1);
 77.1024 +      do
 77.1025 +      {
 77.1026 +         png_ptr->pass++;
 77.1027 +         if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
 77.1028 +             (png_ptr->pass == 3 && png_ptr->width < 3) ||
 77.1029 +             (png_ptr->pass == 5 && png_ptr->width < 2))
 77.1030 +           png_ptr->pass++;
 77.1031 +
 77.1032 +         if (png_ptr->pass > 7)
 77.1033 +            png_ptr->pass--;
 77.1034 +         if (png_ptr->pass >= 7)
 77.1035 +            break;
 77.1036 +
 77.1037 +         png_ptr->iwidth = (png_ptr->width +
 77.1038 +            png_pass_inc[png_ptr->pass] - 1 -
 77.1039 +            png_pass_start[png_ptr->pass]) /
 77.1040 +            png_pass_inc[png_ptr->pass];
 77.1041 +
 77.1042 +         png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
 77.1043 +            png_ptr->iwidth) + 1;
 77.1044 +
 77.1045 +         if (png_ptr->transformations & PNG_INTERLACE)
 77.1046 +            break;
 77.1047 +
 77.1048 +         png_ptr->num_rows = (png_ptr->height +
 77.1049 +            png_pass_yinc[png_ptr->pass] - 1 -
 77.1050 +            png_pass_ystart[png_ptr->pass]) /
 77.1051 +            png_pass_yinc[png_ptr->pass];
 77.1052 +
 77.1053 +      } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
 77.1054 +   }
 77.1055 +}
 77.1056 +
 77.1057 +#if defined(PNG_READ_tEXt_SUPPORTED)
 77.1058 +void /* PRIVATE */
 77.1059 +png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
 77.1060 +   length)
 77.1061 +{
 77.1062 +   if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
 77.1063 +      {
 77.1064 +         png_error(png_ptr, "Out of place tEXt");
 77.1065 +         info_ptr = info_ptr; /* to quiet some compiler warnings */
 77.1066 +      }
 77.1067 +
 77.1068 +#ifdef PNG_MAX_MALLOC_64K
 77.1069 +   png_ptr->skip_length = 0;  /* This may not be necessary */
 77.1070 +
 77.1071 +   if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
 77.1072 +   {
 77.1073 +      png_warning(png_ptr, "tEXt chunk too large to fit in memory");
 77.1074 +      png_ptr->skip_length = length - (png_uint_32)65535L;
 77.1075 +      length = (png_uint_32)65535L;
 77.1076 +   }
 77.1077 +#endif
 77.1078 +
 77.1079 +   png_ptr->current_text = (png_charp)png_malloc(png_ptr,
 77.1080 +      (png_uint_32)(length + 1));
 77.1081 +   png_ptr->current_text[length] = '\0';
 77.1082 +   png_ptr->current_text_ptr = png_ptr->current_text;
 77.1083 +   png_ptr->current_text_size = (png_size_t)length;
 77.1084 +   png_ptr->current_text_left = (png_size_t)length;
 77.1085 +   png_ptr->process_mode = PNG_READ_tEXt_MODE;
 77.1086 +}
 77.1087 +
 77.1088 +void /* PRIVATE */
 77.1089 +png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
 77.1090 +{
 77.1091 +   if (png_ptr->buffer_size && png_ptr->current_text_left)
 77.1092 +   {
 77.1093 +      png_size_t text_size;
 77.1094 +
 77.1095 +      if (png_ptr->buffer_size < png_ptr->current_text_left)
 77.1096 +         text_size = png_ptr->buffer_size;
 77.1097 +      else
 77.1098 +         text_size = png_ptr->current_text_left;
 77.1099 +      png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
 77.1100 +      png_ptr->current_text_left -= text_size;
 77.1101 +      png_ptr->current_text_ptr += text_size;
 77.1102 +   }
 77.1103 +   if (!(png_ptr->current_text_left))
 77.1104 +   {
 77.1105 +      png_textp text_ptr;
 77.1106 +      png_charp text;
 77.1107 +      png_charp key;
 77.1108 +      int ret;
 77.1109 +
 77.1110 +      if (png_ptr->buffer_size < 4)
 77.1111 +      {
 77.1112 +         png_push_save_buffer(png_ptr);
 77.1113 +         return;
 77.1114 +      }
 77.1115 +
 77.1116 +      png_push_crc_finish(png_ptr);
 77.1117 +
 77.1118 +#if defined(PNG_MAX_MALLOC_64K)
 77.1119 +      if (png_ptr->skip_length)
 77.1120 +         return;
 77.1121 +#endif
 77.1122 +
 77.1123 +      key = png_ptr->current_text;
 77.1124 +
 77.1125 +      for (text = key; *text; text++)
 77.1126 +         /* empty loop */ ;
 77.1127 +
 77.1128 +      if (text < key + png_ptr->current_text_size)
 77.1129 +         text++;
 77.1130 +
 77.1131 +      text_ptr = (png_textp)png_malloc(png_ptr,
 77.1132 +         (png_uint_32)png_sizeof(png_text));
 77.1133 +      text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
 77.1134 +      text_ptr->key = key;
 77.1135 +#ifdef PNG_iTXt_SUPPORTED
 77.1136 +      text_ptr->lang = NULL;
 77.1137 +      text_ptr->lang_key = NULL;
 77.1138 +#endif
 77.1139 +      text_ptr->text = text;
 77.1140 +
 77.1141 +      ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
 77.1142 +
 77.1143 +      png_free(png_ptr, key);
 77.1144 +      png_free(png_ptr, text_ptr);
 77.1145 +      png_ptr->current_text = NULL;
 77.1146 +
 77.1147 +      if (ret)
 77.1148 +        png_warning(png_ptr, "Insufficient memory to store text chunk.");
 77.1149 +   }
 77.1150 +}
 77.1151 +#endif
 77.1152 +
 77.1153 +#if defined(PNG_READ_zTXt_SUPPORTED)
 77.1154 +void /* PRIVATE */
 77.1155 +png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
 77.1156 +   length)
 77.1157 +{
 77.1158 +   if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
 77.1159 +      {
 77.1160 +         png_error(png_ptr, "Out of place zTXt");
 77.1161 +         info_ptr = info_ptr; /* to quiet some compiler warnings */
 77.1162 +      }
 77.1163 +
 77.1164 +#ifdef PNG_MAX_MALLOC_64K
 77.1165 +   /* We can't handle zTXt chunks > 64K, since we don't have enough space
 77.1166 +    * to be able to store the uncompressed data.  Actually, the threshold
 77.1167 +    * is probably around 32K, but it isn't as definite as 64K is.
 77.1168 +    */
 77.1169 +   if (length > (png_uint_32)65535L)
 77.1170 +   {
 77.1171 +      png_warning(png_ptr, "zTXt chunk too large to fit in memory");
 77.1172 +      png_push_crc_skip(png_ptr, length);
 77.1173 +      return;
 77.1174 +   }
 77.1175 +#endif
 77.1176 +
 77.1177 +   png_ptr->current_text = (png_charp)png_malloc(png_ptr,
 77.1178 +      (png_uint_32)(length + 1));
 77.1179 +   png_ptr->current_text[length] = '\0';
 77.1180 +   png_ptr->current_text_ptr = png_ptr->current_text;
 77.1181 +   png_ptr->current_text_size = (png_size_t)length;
 77.1182 +   png_ptr->current_text_left = (png_size_t)length;
 77.1183 +   png_ptr->process_mode = PNG_READ_zTXt_MODE;
 77.1184 +}
 77.1185 +
 77.1186 +void /* PRIVATE */
 77.1187 +png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
 77.1188 +{
 77.1189 +   if (png_ptr->buffer_size && png_ptr->current_text_left)
 77.1190 +   {
 77.1191 +      png_size_t text_size;
 77.1192 +
 77.1193 +      if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
 77.1194 +         text_size = png_ptr->buffer_size;
 77.1195 +      else
 77.1196 +         text_size = png_ptr->current_text_left;
 77.1197 +      png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
 77.1198 +      png_ptr->current_text_left -= text_size;
 77.1199 +      png_ptr->current_text_ptr += text_size;
 77.1200 +   }
 77.1201 +   if (!(png_ptr->current_text_left))
 77.1202 +   {
 77.1203 +      png_textp text_ptr;
 77.1204 +      png_charp text;
 77.1205 +      png_charp key;
 77.1206 +      int ret;
 77.1207 +      png_size_t text_size, key_size;
 77.1208 +
 77.1209 +      if (png_ptr->buffer_size < 4)
 77.1210 +      {
 77.1211 +         png_push_save_buffer(png_ptr);
 77.1212 +         return;
 77.1213 +      }
 77.1214 +
 77.1215 +      png_push_crc_finish(png_ptr);
 77.1216 +
 77.1217 +      key = png_ptr->current_text;
 77.1218 +
 77.1219 +      for (text = key; *text; text++)
 77.1220 +         /* empty loop */ ;
 77.1221 +
 77.1222 +      /* zTXt can't have zero text */
 77.1223 +      if (text >= key + png_ptr->current_text_size)
 77.1224 +      {
 77.1225 +         png_ptr->current_text = NULL;
 77.1226 +         png_free(png_ptr, key);
 77.1227 +         return;
 77.1228 +      }
 77.1229 +
 77.1230 +      text++;
 77.1231 +
 77.1232 +      if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
 77.1233 +      {
 77.1234 +         png_ptr->current_text = NULL;
 77.1235 +         png_free(png_ptr, key);
 77.1236 +         return;
 77.1237 +      }
 77.1238 +
 77.1239 +      text++;
 77.1240 +
 77.1241 +      png_ptr->zstream.next_in = (png_bytep )text;
 77.1242 +      png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
 77.1243 +         (text - key));
 77.1244 +      png_ptr->zstream.next_out = png_ptr->zbuf;
 77.1245 +      png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
 77.1246 +
 77.1247 +      key_size = text - key;
 77.1248 +      text_size = 0;
 77.1249 +      text = NULL;
 77.1250 +      ret = Z_STREAM_END;
 77.1251 +
 77.1252 +      while (png_ptr->zstream.avail_in)
 77.1253 +      {
 77.1254 +         ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
 77.1255 +         if (ret != Z_OK && ret != Z_STREAM_END)
 77.1256 +         {
 77.1257 +            inflateReset(&png_ptr->zstream);
 77.1258 +            png_ptr->zstream.avail_in = 0;
 77.1259 +            png_ptr->current_text = NULL;
 77.1260 +            png_free(png_ptr, key);
 77.1261 +            png_free(png_ptr, text);
 77.1262 +            return;
 77.1263 +         }
 77.1264 +         if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
 77.1265 +         {
 77.1266 +            if (text == NULL)
 77.1267 +            {
 77.1268 +               text = (png_charp)png_malloc(png_ptr,
 77.1269 +                     (png_uint_32)(png_ptr->zbuf_size
 77.1270 +                     - png_ptr->zstream.avail_out + key_size + 1));
 77.1271 +               png_memcpy(text + key_size, png_ptr->zbuf,
 77.1272 +                  png_ptr->zbuf_size - png_ptr->zstream.avail_out);
 77.1273 +               png_memcpy(text, key, key_size);
 77.1274 +               text_size = key_size + png_ptr->zbuf_size -
 77.1275 +                  png_ptr->zstream.avail_out;
 77.1276 +               *(text + text_size) = '\0';
 77.1277 +            }
 77.1278 +            else
 77.1279 +            {
 77.1280 +               png_charp tmp;
 77.1281 +
 77.1282 +               tmp = text;
 77.1283 +               text = (png_charp)png_malloc(png_ptr, text_size +
 77.1284 +                  (png_uint_32)(png_ptr->zbuf_size 
 77.1285 +                  - png_ptr->zstream.avail_out + 1));
 77.1286 +               png_memcpy(text, tmp, text_size);
 77.1287 +               png_free(png_ptr, tmp);
 77.1288 +               png_memcpy(text + text_size, png_ptr->zbuf,
 77.1289 +                  png_ptr->zbuf_size - png_ptr->zstream.avail_out);
 77.1290 +               text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
 77.1291 +               *(text + text_size) = '\0';
 77.1292 +            }
 77.1293 +            if (ret != Z_STREAM_END)
 77.1294 +            {
 77.1295 +               png_ptr->zstream.next_out = png_ptr->zbuf;
 77.1296 +               png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
 77.1297 +            }
 77.1298 +         }
 77.1299 +         else
 77.1300 +         {
 77.1301 +            break;
 77.1302 +         }
 77.1303 +
 77.1304 +         if (ret == Z_STREAM_END)
 77.1305 +            break;
 77.1306 +      }
 77.1307 +
 77.1308 +      inflateReset(&png_ptr->zstream);
 77.1309 +      png_ptr->zstream.avail_in = 0;
 77.1310 +
 77.1311 +      if (ret != Z_STREAM_END)
 77.1312 +      {
 77.1313 +         png_ptr->current_text = NULL;
 77.1314 +         png_free(png_ptr, key);
 77.1315 +         png_free(png_ptr, text);
 77.1316 +         return;
 77.1317 +      }
 77.1318 +
 77.1319 +      png_ptr->current_text = NULL;
 77.1320 +      png_free(png_ptr, key);
 77.1321 +      key = text;
 77.1322 +      text += key_size;
 77.1323 +
 77.1324 +      text_ptr = (png_textp)png_malloc(png_ptr,
 77.1325 +          (png_uint_32)png_sizeof(png_text));
 77.1326 +      text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
 77.1327 +      text_ptr->key = key;
 77.1328 +#ifdef PNG_iTXt_SUPPORTED
 77.1329 +      text_ptr->lang = NULL;
 77.1330 +      text_ptr->lang_key = NULL;
 77.1331 +#endif
 77.1332 +      text_ptr->text = text;
 77.1333 +
 77.1334 +      ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
 77.1335 +
 77.1336 +      png_free(png_ptr, key);
 77.1337 +      png_free(png_ptr, text_ptr);
 77.1338 +
 77.1339 +      if (ret)
 77.1340 +        png_warning(png_ptr, "Insufficient memory to store text chunk.");
 77.1341 +   }
 77.1342 +}
 77.1343 +#endif
 77.1344 +
 77.1345 +#if defined(PNG_READ_iTXt_SUPPORTED)
 77.1346 +void /* PRIVATE */
 77.1347 +png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
 77.1348 +   length)
 77.1349 +{
 77.1350 +   if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
 77.1351 +      {
 77.1352 +         png_error(png_ptr, "Out of place iTXt");
 77.1353 +         info_ptr = info_ptr; /* to quiet some compiler warnings */
 77.1354 +      }
 77.1355 +
 77.1356 +#ifdef PNG_MAX_MALLOC_64K
 77.1357 +   png_ptr->skip_length = 0;  /* This may not be necessary */
 77.1358 +
 77.1359 +   if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
 77.1360 +   {
 77.1361 +      png_warning(png_ptr, "iTXt chunk too large to fit in memory");
 77.1362 +      png_ptr->skip_length = length - (png_uint_32)65535L;
 77.1363 +      length = (png_uint_32)65535L;
 77.1364 +   }
 77.1365 +#endif
 77.1366 +
 77.1367 +   png_ptr->current_text = (png_charp)png_malloc(png_ptr,
 77.1368 +      (png_uint_32)(length + 1));
 77.1369 +   png_ptr->current_text[length] = '\0';
 77.1370 +   png_ptr->current_text_ptr = png_ptr->current_text;
 77.1371 +   png_ptr->current_text_size = (png_size_t)length;
 77.1372 +   png_ptr->current_text_left = (png_size_t)length;
 77.1373 +   png_ptr->process_mode = PNG_READ_iTXt_MODE;
 77.1374 +}
 77.1375 +
 77.1376 +void /* PRIVATE */
 77.1377 +png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
 77.1378 +{
 77.1379 +
 77.1380 +   if (png_ptr->buffer_size && png_ptr->current_text_left)
 77.1381 +   {
 77.1382 +      png_size_t text_size;
 77.1383 +
 77.1384 +      if (png_ptr->buffer_size < png_ptr->current_text_left)
 77.1385 +         text_size = png_ptr->buffer_size;
 77.1386 +      else
 77.1387 +         text_size = png_ptr->current_text_left;
 77.1388 +      png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
 77.1389 +      png_ptr->current_text_left -= text_size;
 77.1390 +      png_ptr->current_text_ptr += text_size;
 77.1391 +   }
 77.1392 +   if (!(png_ptr->current_text_left))
 77.1393 +   {
 77.1394 +      png_textp text_ptr;
 77.1395 +      png_charp key;
 77.1396 +      int comp_flag;
 77.1397 +      png_charp lang;
 77.1398 +      png_charp lang_key;
 77.1399 +      png_charp text;
 77.1400 +      int ret;
 77.1401 +
 77.1402 +      if (png_ptr->buffer_size < 4)
 77.1403 +      {
 77.1404 +         png_push_save_buffer(png_ptr);
 77.1405 +         return;
 77.1406 +      }
 77.1407 +
 77.1408 +      png_push_crc_finish(png_ptr);
 77.1409 +
 77.1410 +#if defined(PNG_MAX_MALLOC_64K)
 77.1411 +      if (png_ptr->skip_length)
 77.1412 +         return;
 77.1413 +#endif
 77.1414 +
 77.1415 +      key = png_ptr->current_text;
 77.1416 +
 77.1417 +      for (lang = key; *lang; lang++)
 77.1418 +         /* empty loop */ ;
 77.1419 +
 77.1420 +      if (lang < key + png_ptr->current_text_size - 3)
 77.1421 +         lang++;
 77.1422 +
 77.1423 +      comp_flag = *lang++;
 77.1424 +      lang++;     /* skip comp_type, always zero */
 77.1425 +
 77.1426 +      for (lang_key = lang; *lang_key; lang_key++)
 77.1427 +         /* empty loop */ ;
 77.1428 +      lang_key++;        /* skip NUL separator */
 77.1429 +
 77.1430 +      text=lang_key;
 77.1431 +      if (lang_key < key + png_ptr->current_text_size - 1)
 77.1432 +      {
 77.1433 +        for (; *text; text++)
 77.1434 +           /* empty loop */ ;
 77.1435 +      }
 77.1436 +
 77.1437 +      if (text < key + png_ptr->current_text_size)
 77.1438 +         text++;
 77.1439 +
 77.1440 +      text_ptr = (png_textp)png_malloc(png_ptr,
 77.1441 +         (png_uint_32)png_sizeof(png_text));
 77.1442 +      text_ptr->compression = comp_flag + 2;
 77.1443 +      text_ptr->key = key;
 77.1444 +      text_ptr->lang = lang;
 77.1445 +      text_ptr->lang_key = lang_key;
 77.1446 +      text_ptr->text = text;
 77.1447 +      text_ptr->text_length = 0;
 77.1448 +      text_ptr->itxt_length = png_strlen(text);
 77.1449 +
 77.1450 +      ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
 77.1451 +
 77.1452 +      png_ptr->current_text = NULL;
 77.1453 +
 77.1454 +      png_free(png_ptr, text_ptr);
 77.1455 +      if (ret)
 77.1456 +        png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
 77.1457 +   }
 77.1458 +}
 77.1459 +#endif
 77.1460 +
 77.1461 +/* This function is called when we haven't found a handler for this
 77.1462 + * chunk.  If there isn't a problem with the chunk itself (ie a bad chunk
 77.1463 + * name or a critical chunk), the chunk is (currently) silently ignored.
 77.1464 + */
 77.1465 +void /* PRIVATE */
 77.1466 +png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
 77.1467 +   length)
 77.1468 +{
 77.1469 +   png_uint_32 skip = 0;
 77.1470 +
 77.1471 +   if (!(png_ptr->chunk_name[0] & 0x20))
 77.1472 +   {
 77.1473 +#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
 77.1474 +      if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
 77.1475 +         PNG_HANDLE_CHUNK_ALWAYS
 77.1476 +#if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
 77.1477 +         && png_ptr->read_user_chunk_fn == NULL
 77.1478 +#endif
 77.1479 +         )
 77.1480 +#endif
 77.1481 +         png_chunk_error(png_ptr, "unknown critical chunk");
 77.1482 +
 77.1483 +      info_ptr = info_ptr; /* to quiet some compiler warnings */
 77.1484 +   }
 77.1485 +
 77.1486 +#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
 77.1487 +   if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
 77.1488 +   {
 77.1489 +#ifdef PNG_MAX_MALLOC_64K
 77.1490 +      if (length > (png_uint_32)65535L)
 77.1491 +      {
 77.1492 +          png_warning(png_ptr, "unknown chunk too large to fit in memory");
 77.1493 +          skip = length - (png_uint_32)65535L;
 77.1494 +          length = (png_uint_32)65535L;
 77.1495 +      }
 77.1496 +#endif
 77.1497 +      png_memcpy((png_charp)png_ptr->unknown_chunk.name,
 77.1498 +                 (png_charp)png_ptr->chunk_name, 
 77.1499 +                 png_sizeof(png_ptr->unknown_chunk.name));
 77.1500 +      png_ptr->unknown_chunk.name[png_sizeof(png_ptr->unknown_chunk.name) - 1]
 77.1501 +        = '\0';
 77.1502 +
 77.1503 +      png_ptr->unknown_chunk.size = (png_size_t)length;
 77.1504 +      if (length == 0)
 77.1505 +         png_ptr->unknown_chunk.data = NULL;
 77.1506 +      else
 77.1507 +      {
 77.1508 +         png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr,
 77.1509 +       (png_uint_32)length);
 77.1510 +         png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
 77.1511 +      }
 77.1512 +#if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
 77.1513 +      if (png_ptr->read_user_chunk_fn != NULL)
 77.1514 +      {
 77.1515 +         /* callback to user unknown chunk handler */
 77.1516 +         int ret;
 77.1517 +         ret = (*(png_ptr->read_user_chunk_fn))
 77.1518 +           (png_ptr, &png_ptr->unknown_chunk);
 77.1519 +         if (ret < 0)
 77.1520 +            png_chunk_error(png_ptr, "error in user chunk");
 77.1521 +         if (ret == 0)
 77.1522 +         {
 77.1523 +            if (!(png_ptr->chunk_name[0] & 0x20))
 77.1524 +               if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
 77.1525 +                    PNG_HANDLE_CHUNK_ALWAYS)
 77.1526 +                  png_chunk_error(png_ptr, "unknown critical chunk");
 77.1527 +            png_set_unknown_chunks(png_ptr, info_ptr,
 77.1528 +               &png_ptr->unknown_chunk, 1);
 77.1529 +         }
 77.1530 +      }
 77.1531 +      else
 77.1532 +#endif
 77.1533 +        png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
 77.1534 +      png_free(png_ptr, png_ptr->unknown_chunk.data);
 77.1535 +      png_ptr->unknown_chunk.data = NULL;
 77.1536 +   }
 77.1537 +   else
 77.1538 +#endif
 77.1539 +      skip=length;
 77.1540 +   png_push_crc_skip(png_ptr, skip);
 77.1541 +}
 77.1542 +
 77.1543 +void /* PRIVATE */
 77.1544 +png_push_have_info(png_structp png_ptr, png_infop info_ptr)
 77.1545 +{
 77.1546 +   if (png_ptr->info_fn != NULL)
 77.1547 +      (*(png_ptr->info_fn))(png_ptr, info_ptr);
 77.1548 +}
 77.1549 +
 77.1550 +void /* PRIVATE */
 77.1551 +png_push_have_end(png_structp png_ptr, png_infop info_ptr)
 77.1552 +{
 77.1553 +   if (png_ptr->end_fn != NULL)
 77.1554 +      (*(png_ptr->end_fn))(png_ptr, info_ptr);
 77.1555 +}
 77.1556 +
 77.1557 +void /* PRIVATE */
 77.1558 +png_push_have_row(png_structp png_ptr, png_bytep row)
 77.1559 +{
 77.1560 +   if (png_ptr->row_fn != NULL)
 77.1561 +      (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
 77.1562 +         (int)png_ptr->pass);
 77.1563 +}
 77.1564 +
 77.1565 +void PNGAPI
 77.1566 +png_progressive_combine_row (png_structp png_ptr,
 77.1567 +   png_bytep old_row, png_bytep new_row)
 77.1568 +{
 77.1569 +#ifdef PNG_USE_LOCAL_ARRAYS
 77.1570 +   PNG_CONST int FARDATA png_pass_dsp_mask[7] =
 77.1571 +      {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
 77.1572 +#endif
 77.1573 +   if (png_ptr == NULL) return;
 77.1574 +   if (new_row != NULL)    /* new_row must == png_ptr->row_buf here. */
 77.1575 +      png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
 77.1576 +}
 77.1577 +
 77.1578 +void PNGAPI
 77.1579 +png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
 77.1580 +   png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
 77.1581 +   png_progressive_end_ptr end_fn)
 77.1582 +{
 77.1583 +   if (png_ptr == NULL) return;
 77.1584 +   png_ptr->info_fn = info_fn;
 77.1585 +   png_ptr->row_fn = row_fn;
 77.1586 +   png_ptr->end_fn = end_fn;
 77.1587 +
 77.1588 +   png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
 77.1589 +}
 77.1590 +
 77.1591 +png_voidp PNGAPI
 77.1592 +png_get_progressive_ptr(png_structp png_ptr)
 77.1593 +{
 77.1594 +   if (png_ptr == NULL) return (NULL);
 77.1595 +   return png_ptr->io_ptr;
 77.1596 +}
 77.1597 +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
    78.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    78.2 +++ b/libs/libpng/pngread.c	Thu Sep 08 06:28:38 2011 +0300
    78.3 @@ -0,0 +1,1459 @@
    78.4 +
    78.5 +/* pngread.c - read a PNG file
    78.6 + *
    78.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    78.8 + * For conditions of distribution and use, see copyright notice in png.h
    78.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   78.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   78.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   78.12 + *
   78.13 + * This file contains routines that an application calls directly to
   78.14 + * read a PNG file or stream.
   78.15 + */
   78.16 +
   78.17 +#define PNG_INTERNAL
   78.18 +#include "png.h"
   78.19 +#if defined(PNG_READ_SUPPORTED)
   78.20 +
   78.21 +/* Create a PNG structure for reading, and allocate any memory needed. */
   78.22 +png_structp PNGAPI
   78.23 +png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
   78.24 +   png_error_ptr error_fn, png_error_ptr warn_fn)
   78.25 +{
   78.26 +
   78.27 +#ifdef PNG_USER_MEM_SUPPORTED
   78.28 +   return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
   78.29 +      warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
   78.30 +}
   78.31 +
   78.32 +/* Alternate create PNG structure for reading, and allocate any memory needed. */
   78.33 +png_structp PNGAPI
   78.34 +png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
   78.35 +   png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
   78.36 +   png_malloc_ptr malloc_fn, png_free_ptr free_fn)
   78.37 +{
   78.38 +#endif /* PNG_USER_MEM_SUPPORTED */
   78.39 +
   78.40 +#ifdef PNG_SETJMP_SUPPORTED
   78.41 +   volatile
   78.42 +#endif
   78.43 +   png_structp png_ptr;
   78.44 +
   78.45 +#ifdef PNG_SETJMP_SUPPORTED
   78.46 +#ifdef USE_FAR_KEYWORD
   78.47 +   jmp_buf jmpbuf;
   78.48 +#endif
   78.49 +#endif
   78.50 +
   78.51 +   int i;
   78.52 +
   78.53 +   png_debug(1, "in png_create_read_struct\n");
   78.54 +#ifdef PNG_USER_MEM_SUPPORTED
   78.55 +   png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
   78.56 +      (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
   78.57 +#else
   78.58 +   png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
   78.59 +#endif
   78.60 +   if (png_ptr == NULL)
   78.61 +      return (NULL);
   78.62 +
   78.63 +   /* added at libpng-1.2.6 */
   78.64 +#ifdef PNG_SET_USER_LIMITS_SUPPORTED
   78.65 +   png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
   78.66 +   png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
   78.67 +#endif
   78.68 +
   78.69 +#ifdef PNG_SETJMP_SUPPORTED
   78.70 +#ifdef USE_FAR_KEYWORD
   78.71 +   if (setjmp(jmpbuf))
   78.72 +#else
   78.73 +   if (setjmp(png_ptr->jmpbuf))
   78.74 +#endif
   78.75 +   {
   78.76 +      png_free(png_ptr, png_ptr->zbuf);
   78.77 +      png_ptr->zbuf = NULL;
   78.78 +#ifdef PNG_USER_MEM_SUPPORTED
   78.79 +      png_destroy_struct_2((png_voidp)png_ptr,
   78.80 +         (png_free_ptr)free_fn, (png_voidp)mem_ptr);
   78.81 +#else
   78.82 +      png_destroy_struct((png_voidp)png_ptr);
   78.83 +#endif
   78.84 +      return (NULL);
   78.85 +   }
   78.86 +#ifdef USE_FAR_KEYWORD
   78.87 +   png_memcpy(png_ptr->jmpbuf, jmpbuf, png_sizeof(jmp_buf));
   78.88 +#endif
   78.89 +#endif
   78.90 +
   78.91 +#ifdef PNG_USER_MEM_SUPPORTED
   78.92 +   png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
   78.93 +#endif
   78.94 +
   78.95 +   png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
   78.96 +
   78.97 +   if (user_png_ver)
   78.98 +   {
   78.99 +     i = 0;
  78.100 +     do
  78.101 +     {
  78.102 +       if (user_png_ver[i] != png_libpng_ver[i])
  78.103 +          png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  78.104 +     } while (png_libpng_ver[i++]);
  78.105 +   }
  78.106 +   else
  78.107 +        png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  78.108 +   
  78.109 +
  78.110 +   if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  78.111 +   {
  78.112 +     /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  78.113 +      * we must recompile any applications that use any older library version.
  78.114 +      * For versions after libpng 1.0, we will be compatible, so we need
  78.115 +      * only check the first digit.
  78.116 +      */
  78.117 +     if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  78.118 +         (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  78.119 +         (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  78.120 +     {
  78.121 +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  78.122 +        char msg[80];
  78.123 +        if (user_png_ver)
  78.124 +        {
  78.125 +          png_snprintf(msg, 80,
  78.126 +             "Application was compiled with png.h from libpng-%.20s",
  78.127 +             user_png_ver);
  78.128 +          png_warning(png_ptr, msg);
  78.129 +        }
  78.130 +        png_snprintf(msg, 80,
  78.131 +             "Application  is  running with png.c from libpng-%.20s",
  78.132 +           png_libpng_ver);
  78.133 +        png_warning(png_ptr, msg);
  78.134 +#endif
  78.135 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
  78.136 +        png_ptr->flags = 0;
  78.137 +#endif
  78.138 +        png_error(png_ptr,
  78.139 +           "Incompatible libpng version in application and library");
  78.140 +     }
  78.141 +   }
  78.142 +
  78.143 +   /* initialize zbuf - compression buffer */
  78.144 +   png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  78.145 +   png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  78.146 +     (png_uint_32)png_ptr->zbuf_size);
  78.147 +   png_ptr->zstream.zalloc = png_zalloc;
  78.148 +   png_ptr->zstream.zfree = png_zfree;
  78.149 +   png_ptr->zstream.opaque = (voidpf)png_ptr;
  78.150 +
  78.151 +   switch (inflateInit(&png_ptr->zstream))
  78.152 +   {
  78.153 +     case Z_OK: /* Do nothing */ break;
  78.154 +     case Z_MEM_ERROR:
  78.155 +     case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  78.156 +     case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  78.157 +     default: png_error(png_ptr, "Unknown zlib error");
  78.158 +   }
  78.159 +
  78.160 +   png_ptr->zstream.next_out = png_ptr->zbuf;
  78.161 +   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  78.162 +
  78.163 +   png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  78.164 +
  78.165 +#ifdef PNG_SETJMP_SUPPORTED
  78.166 +/* Applications that neglect to set up their own setjmp() and then encounter
  78.167 +   a png_error() will longjmp here.  Since the jmpbuf is then meaningless we
  78.168 +   abort instead of returning. */
  78.169 +#ifdef USE_FAR_KEYWORD
  78.170 +   if (setjmp(jmpbuf))
  78.171 +      PNG_ABORT();
  78.172 +   png_memcpy(png_ptr->jmpbuf, jmpbuf, png_sizeof(jmp_buf));
  78.173 +#else
  78.174 +   if (setjmp(png_ptr->jmpbuf))
  78.175 +      PNG_ABORT();
  78.176 +#endif
  78.177 +#endif
  78.178 +   return (png_ptr);
  78.179 +}
  78.180 +
  78.181 +#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  78.182 +/* Initialize PNG structure for reading, and allocate any memory needed.
  78.183 +   This interface is deprecated in favour of the png_create_read_struct(),
  78.184 +   and it will disappear as of libpng-1.3.0. */
  78.185 +#undef png_read_init
  78.186 +void PNGAPI
  78.187 +png_read_init(png_structp png_ptr)
  78.188 +{
  78.189 +   /* We only come here via pre-1.0.7-compiled applications */
  78.190 +   png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  78.191 +}
  78.192 +
  78.193 +void PNGAPI
  78.194 +png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  78.195 +   png_size_t png_struct_size, png_size_t png_info_size)
  78.196 +{
  78.197 +   /* We only come here via pre-1.0.12-compiled applications */
  78.198 +   if (png_ptr == NULL) return;
  78.199 +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  78.200 +   if (png_sizeof(png_struct) > png_struct_size ||
  78.201 +      png_sizeof(png_info) > png_info_size)
  78.202 +   {
  78.203 +      char msg[80];
  78.204 +      png_ptr->warning_fn = NULL;
  78.205 +      if (user_png_ver)
  78.206 +      {
  78.207 +        png_snprintf(msg, 80,
  78.208 +           "Application was compiled with png.h from libpng-%.20s",
  78.209 +           user_png_ver);
  78.210 +        png_warning(png_ptr, msg);
  78.211 +      }
  78.212 +      png_snprintf(msg, 80,
  78.213 +         "Application  is  running with png.c from libpng-%.20s",
  78.214 +         png_libpng_ver);
  78.215 +      png_warning(png_ptr, msg);
  78.216 +   }
  78.217 +#endif
  78.218 +   if (png_sizeof(png_struct) > png_struct_size)
  78.219 +     {
  78.220 +       png_ptr->error_fn = NULL;
  78.221 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
  78.222 +       png_ptr->flags = 0;
  78.223 +#endif
  78.224 +       png_error(png_ptr,
  78.225 +       "The png struct allocated by the application for reading is too small.");
  78.226 +     }
  78.227 +   if (png_sizeof(png_info) > png_info_size)
  78.228 +     {
  78.229 +       png_ptr->error_fn = NULL;
  78.230 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
  78.231 +       png_ptr->flags = 0;
  78.232 +#endif
  78.233 +       png_error(png_ptr,
  78.234 +         "The info struct allocated by application for reading is too small.");
  78.235 +     }
  78.236 +   png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  78.237 +}
  78.238 +#endif /* PNG_1_0_X || PNG_1_2_X */
  78.239 +
  78.240 +void PNGAPI
  78.241 +png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  78.242 +   png_size_t png_struct_size)
  78.243 +{
  78.244 +#ifdef PNG_SETJMP_SUPPORTED
  78.245 +   jmp_buf tmp_jmp;  /* to save current jump buffer */
  78.246 +#endif
  78.247 +
  78.248 +   int i = 0;
  78.249 +
  78.250 +   png_structp png_ptr=*ptr_ptr;
  78.251 +
  78.252 +   if (png_ptr == NULL) return;
  78.253 +
  78.254 +   do
  78.255 +   {
  78.256 +     if (user_png_ver[i] != png_libpng_ver[i])
  78.257 +     {
  78.258 +#ifdef PNG_LEGACY_SUPPORTED
  78.259 +       png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  78.260 +#else
  78.261 +       png_ptr->warning_fn = NULL;
  78.262 +       png_warning(png_ptr,
  78.263 +        "Application uses deprecated png_read_init() and should be recompiled.");
  78.264 +       break;
  78.265 +#endif
  78.266 +     }
  78.267 +   } while (png_libpng_ver[i++]);
  78.268 +
  78.269 +   png_debug(1, "in png_read_init_3\n");
  78.270 +
  78.271 +#ifdef PNG_SETJMP_SUPPORTED
  78.272 +   /* save jump buffer and error functions */
  78.273 +   png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  78.274 +#endif
  78.275 +
  78.276 +   if (png_sizeof(png_struct) > png_struct_size)
  78.277 +   {
  78.278 +      png_destroy_struct(png_ptr);
  78.279 +      *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  78.280 +      png_ptr = *ptr_ptr;
  78.281 +   }
  78.282 +
  78.283 +   /* reset all variables to 0 */
  78.284 +   png_memset(png_ptr, 0, png_sizeof(png_struct));
  78.285 +
  78.286 +#ifdef PNG_SETJMP_SUPPORTED
  78.287 +   /* restore jump buffer */
  78.288 +   png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
  78.289 +#endif
  78.290 +
  78.291 +   /* added at libpng-1.2.6 */
  78.292 +#ifdef PNG_SET_USER_LIMITS_SUPPORTED
  78.293 +   png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  78.294 +   png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  78.295 +#endif
  78.296 +
  78.297 +   /* initialize zbuf - compression buffer */
  78.298 +   png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  78.299 +   png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  78.300 +     (png_uint_32)png_ptr->zbuf_size);
  78.301 +   png_ptr->zstream.zalloc = png_zalloc;
  78.302 +   png_ptr->zstream.zfree = png_zfree;
  78.303 +   png_ptr->zstream.opaque = (voidpf)png_ptr;
  78.304 +
  78.305 +   switch (inflateInit(&png_ptr->zstream))
  78.306 +   {
  78.307 +     case Z_OK: /* Do nothing */ break;
  78.308 +     case Z_MEM_ERROR:
  78.309 +     case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  78.310 +     case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  78.311 +     default: png_error(png_ptr, "Unknown zlib error");
  78.312 +   }
  78.313 +
  78.314 +   png_ptr->zstream.next_out = png_ptr->zbuf;
  78.315 +   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  78.316 +
  78.317 +   png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  78.318 +}
  78.319 +
  78.320 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  78.321 +/* Read the information before the actual image data.  This has been
  78.322 + * changed in v0.90 to allow reading a file that already has the magic
  78.323 + * bytes read from the stream.  You can tell libpng how many bytes have
  78.324 + * been read from the beginning of the stream (up to the maximum of 8)
  78.325 + * via png_set_sig_bytes(), and we will only check the remaining bytes
  78.326 + * here.  The application can then have access to the signature bytes we
  78.327 + * read if it is determined that this isn't a valid PNG file.
  78.328 + */
  78.329 +void PNGAPI
  78.330 +png_read_info(png_structp png_ptr, png_infop info_ptr)
  78.331 +{
  78.332 +   if (png_ptr == NULL || info_ptr == NULL) return;
  78.333 +   png_debug(1, "in png_read_info\n");
  78.334 +   /* If we haven't checked all of the PNG signature bytes, do so now. */
  78.335 +   if (png_ptr->sig_bytes < 8)
  78.336 +   {
  78.337 +      png_size_t num_checked = png_ptr->sig_bytes,
  78.338 +                 num_to_check = 8 - num_checked;
  78.339 +
  78.340 +      png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  78.341 +      png_ptr->sig_bytes = 8;
  78.342 +
  78.343 +      if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  78.344 +      {
  78.345 +         if (num_checked < 4 &&
  78.346 +             png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  78.347 +            png_error(png_ptr, "Not a PNG file");
  78.348 +         else
  78.349 +            png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  78.350 +      }
  78.351 +      if (num_checked < 3)
  78.352 +         png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  78.353 +   }
  78.354 +
  78.355 +   for (;;)
  78.356 +   {
  78.357 +#ifdef PNG_USE_LOCAL_ARRAYS
  78.358 +      PNG_CONST PNG_IHDR;
  78.359 +      PNG_CONST PNG_IDAT;
  78.360 +      PNG_CONST PNG_IEND;
  78.361 +      PNG_CONST PNG_PLTE;
  78.362 +#if defined(PNG_READ_bKGD_SUPPORTED)
  78.363 +      PNG_CONST PNG_bKGD;
  78.364 +#endif
  78.365 +#if defined(PNG_READ_cHRM_SUPPORTED)
  78.366 +      PNG_CONST PNG_cHRM;
  78.367 +#endif
  78.368 +#if defined(PNG_READ_gAMA_SUPPORTED)
  78.369 +      PNG_CONST PNG_gAMA;
  78.370 +#endif
  78.371 +#if defined(PNG_READ_hIST_SUPPORTED)
  78.372 +      PNG_CONST PNG_hIST;
  78.373 +#endif
  78.374 +#if defined(PNG_READ_iCCP_SUPPORTED)
  78.375 +      PNG_CONST PNG_iCCP;
  78.376 +#endif
  78.377 +#if defined(PNG_READ_iTXt_SUPPORTED)
  78.378 +      PNG_CONST PNG_iTXt;
  78.379 +#endif
  78.380 +#if defined(PNG_READ_oFFs_SUPPORTED)
  78.381 +      PNG_CONST PNG_oFFs;
  78.382 +#endif
  78.383 +#if defined(PNG_READ_pCAL_SUPPORTED)
  78.384 +      PNG_CONST PNG_pCAL;
  78.385 +#endif
  78.386 +#if defined(PNG_READ_pHYs_SUPPORTED)
  78.387 +      PNG_CONST PNG_pHYs;
  78.388 +#endif
  78.389 +#if defined(PNG_READ_sBIT_SUPPORTED)
  78.390 +      PNG_CONST PNG_sBIT;
  78.391 +#endif
  78.392 +#if defined(PNG_READ_sCAL_SUPPORTED)
  78.393 +      PNG_CONST PNG_sCAL;
  78.394 +#endif
  78.395 +#if defined(PNG_READ_sPLT_SUPPORTED)
  78.396 +      PNG_CONST PNG_sPLT;
  78.397 +#endif
  78.398 +#if defined(PNG_READ_sRGB_SUPPORTED)
  78.399 +      PNG_CONST PNG_sRGB;
  78.400 +#endif
  78.401 +#if defined(PNG_READ_tEXt_SUPPORTED)
  78.402 +      PNG_CONST PNG_tEXt;
  78.403 +#endif
  78.404 +#if defined(PNG_READ_tIME_SUPPORTED)
  78.405 +      PNG_CONST PNG_tIME;
  78.406 +#endif
  78.407 +#if defined(PNG_READ_tRNS_SUPPORTED)
  78.408 +      PNG_CONST PNG_tRNS;
  78.409 +#endif
  78.410 +#if defined(PNG_READ_zTXt_SUPPORTED)
  78.411 +      PNG_CONST PNG_zTXt;
  78.412 +#endif
  78.413 +#endif /* PNG_USE_LOCAL_ARRAYS */
  78.414 +      png_uint_32 length = png_read_chunk_header(png_ptr);
  78.415 +      PNG_CONST png_bytep chunk_name = png_ptr->chunk_name;
  78.416 +
  78.417 +      /* This should be a binary subdivision search or a hash for
  78.418 +       * matching the chunk name rather than a linear search.
  78.419 +       */
  78.420 +      if (!png_memcmp(chunk_name, png_IDAT, 4))
  78.421 +        if (png_ptr->mode & PNG_AFTER_IDAT)
  78.422 +          png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  78.423 +
  78.424 +      if (!png_memcmp(chunk_name, png_IHDR, 4))
  78.425 +         png_handle_IHDR(png_ptr, info_ptr, length);
  78.426 +      else if (!png_memcmp(chunk_name, png_IEND, 4))
  78.427 +         png_handle_IEND(png_ptr, info_ptr, length);
  78.428 +#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  78.429 +      else if (png_handle_as_unknown(png_ptr, chunk_name))
  78.430 +      {
  78.431 +         if (!png_memcmp(chunk_name, png_IDAT, 4))
  78.432 +            png_ptr->mode |= PNG_HAVE_IDAT;
  78.433 +         png_handle_unknown(png_ptr, info_ptr, length);
  78.434 +         if (!png_memcmp(chunk_name, png_PLTE, 4))
  78.435 +            png_ptr->mode |= PNG_HAVE_PLTE;
  78.436 +         else if (!png_memcmp(chunk_name, png_IDAT, 4))
  78.437 +         {
  78.438 +            if (!(png_ptr->mode & PNG_HAVE_IHDR))
  78.439 +               png_error(png_ptr, "Missing IHDR before IDAT");
  78.440 +            else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  78.441 +                     !(png_ptr->mode & PNG_HAVE_PLTE))
  78.442 +               png_error(png_ptr, "Missing PLTE before IDAT");
  78.443 +            break;
  78.444 +         }
  78.445 +      }
  78.446 +#endif
  78.447 +      else if (!png_memcmp(chunk_name, png_PLTE, 4))
  78.448 +         png_handle_PLTE(png_ptr, info_ptr, length);
  78.449 +      else if (!png_memcmp(chunk_name, png_IDAT, 4))
  78.450 +      {
  78.451 +         if (!(png_ptr->mode & PNG_HAVE_IHDR))
  78.452 +            png_error(png_ptr, "Missing IHDR before IDAT");
  78.453 +         else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  78.454 +                  !(png_ptr->mode & PNG_HAVE_PLTE))
  78.455 +            png_error(png_ptr, "Missing PLTE before IDAT");
  78.456 +
  78.457 +         png_ptr->idat_size = length;
  78.458 +         png_ptr->mode |= PNG_HAVE_IDAT;
  78.459 +         break;
  78.460 +      }
  78.461 +#if defined(PNG_READ_bKGD_SUPPORTED)
  78.462 +      else if (!png_memcmp(chunk_name, png_bKGD, 4))
  78.463 +         png_handle_bKGD(png_ptr, info_ptr, length);
  78.464 +#endif
  78.465 +#if defined(PNG_READ_cHRM_SUPPORTED)
  78.466 +      else if (!png_memcmp(chunk_name, png_cHRM, 4))
  78.467 +         png_handle_cHRM(png_ptr, info_ptr, length);
  78.468 +#endif
  78.469 +#if defined(PNG_READ_gAMA_SUPPORTED)
  78.470 +      else if (!png_memcmp(chunk_name, png_gAMA, 4))
  78.471 +         png_handle_gAMA(png_ptr, info_ptr, length);
  78.472 +#endif
  78.473 +#if defined(PNG_READ_hIST_SUPPORTED)
  78.474 +      else if (!png_memcmp(chunk_name, png_hIST, 4))
  78.475 +         png_handle_hIST(png_ptr, info_ptr, length);
  78.476 +#endif
  78.477 +#if defined(PNG_READ_oFFs_SUPPORTED)
  78.478 +      else if (!png_memcmp(chunk_name, png_oFFs, 4))
  78.479 +         png_handle_oFFs(png_ptr, info_ptr, length);
  78.480 +#endif
  78.481 +#if defined(PNG_READ_pCAL_SUPPORTED)
  78.482 +      else if (!png_memcmp(chunk_name, png_pCAL, 4))
  78.483 +         png_handle_pCAL(png_ptr, info_ptr, length);
  78.484 +#endif
  78.485 +#if defined(PNG_READ_sCAL_SUPPORTED)
  78.486 +      else if (!png_memcmp(chunk_name, png_sCAL, 4))
  78.487 +         png_handle_sCAL(png_ptr, info_ptr, length);
  78.488 +#endif
  78.489 +#if defined(PNG_READ_pHYs_SUPPORTED)
  78.490 +      else if (!png_memcmp(chunk_name, png_pHYs, 4))
  78.491 +         png_handle_pHYs(png_ptr, info_ptr, length);
  78.492 +#endif
  78.493 +#if defined(PNG_READ_sBIT_SUPPORTED)
  78.494 +      else if (!png_memcmp(chunk_name, png_sBIT, 4))
  78.495 +         png_handle_sBIT(png_ptr, info_ptr, length);
  78.496 +#endif
  78.497 +#if defined(PNG_READ_sRGB_SUPPORTED)
  78.498 +      else if (!png_memcmp(chunk_name, png_sRGB, 4))
  78.499 +         png_handle_sRGB(png_ptr, info_ptr, length);
  78.500 +#endif
  78.501 +#if defined(PNG_READ_iCCP_SUPPORTED)
  78.502 +      else if (!png_memcmp(chunk_name, png_iCCP, 4))
  78.503 +         png_handle_iCCP(png_ptr, info_ptr, length);
  78.504 +#endif
  78.505 +#if defined(PNG_READ_sPLT_SUPPORTED)
  78.506 +      else if (!png_memcmp(chunk_name, png_sPLT, 4))
  78.507 +         png_handle_sPLT(png_ptr, info_ptr, length);
  78.508 +#endif
  78.509 +#if defined(PNG_READ_tEXt_SUPPORTED)
  78.510 +      else if (!png_memcmp(chunk_name, png_tEXt, 4))
  78.511 +         png_handle_tEXt(png_ptr, info_ptr, length);
  78.512 +#endif
  78.513 +#if defined(PNG_READ_tIME_SUPPORTED)
  78.514 +      else if (!png_memcmp(chunk_name, png_tIME, 4))
  78.515 +         png_handle_tIME(png_ptr, info_ptr, length);
  78.516 +#endif
  78.517 +#if defined(PNG_READ_tRNS_SUPPORTED)
  78.518 +      else if (!png_memcmp(chunk_name, png_tRNS, 4))
  78.519 +         png_handle_tRNS(png_ptr, info_ptr, length);
  78.520 +#endif
  78.521 +#if defined(PNG_READ_zTXt_SUPPORTED)
  78.522 +      else if (!png_memcmp(chunk_name, png_zTXt, 4))
  78.523 +         png_handle_zTXt(png_ptr, info_ptr, length);
  78.524 +#endif
  78.525 +#if defined(PNG_READ_iTXt_SUPPORTED)
  78.526 +      else if (!png_memcmp(chunk_name, png_iTXt, 4))
  78.527 +         png_handle_iTXt(png_ptr, info_ptr, length);
  78.528 +#endif
  78.529 +      else
  78.530 +         png_handle_unknown(png_ptr, info_ptr, length);
  78.531 +   }
  78.532 +}
  78.533 +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  78.534 +
  78.535 +/* optional call to update the users info_ptr structure */
  78.536 +void PNGAPI
  78.537 +png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  78.538 +{
  78.539 +   png_debug(1, "in png_read_update_info\n");
  78.540 +   if (png_ptr == NULL) return;
  78.541 +   if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  78.542 +      png_read_start_row(png_ptr);
  78.543 +   else
  78.544 +      png_warning(png_ptr,
  78.545 +      "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  78.546 +   png_read_transform_info(png_ptr, info_ptr);
  78.547 +}
  78.548 +
  78.549 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  78.550 +/* Initialize palette, background, etc, after transformations
  78.551 + * are set, but before any reading takes place.  This allows
  78.552 + * the user to obtain a gamma-corrected palette, for example.
  78.553 + * If the user doesn't call this, we will do it ourselves.
  78.554 + */
  78.555 +void PNGAPI
  78.556 +png_start_read_image(png_structp png_ptr)
  78.557 +{
  78.558 +   png_debug(1, "in png_start_read_image\n");
  78.559 +   if (png_ptr == NULL) return;
  78.560 +   if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  78.561 +      png_read_start_row(png_ptr);
  78.562 +}
  78.563 +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  78.564 +
  78.565 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  78.566 +void PNGAPI
  78.567 +png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  78.568 +{
  78.569 +#ifdef PNG_USE_LOCAL_ARRAYS
  78.570 +   PNG_CONST PNG_IDAT;
  78.571 +   PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  78.572 +      0xff};
  78.573 +   PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  78.574 +#endif
  78.575 +   int ret;
  78.576 +   if (png_ptr == NULL) return;
  78.577 +   png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  78.578 +      png_ptr->row_number, png_ptr->pass);
  78.579 +   if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  78.580 +      png_read_start_row(png_ptr);
  78.581 +   if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  78.582 +   {
  78.583 +   /* check for transforms that have been set but were defined out */
  78.584 +#if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  78.585 +   if (png_ptr->transformations & PNG_INVERT_MONO)
  78.586 +      png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  78.587 +#endif
  78.588 +#if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  78.589 +   if (png_ptr->transformations & PNG_FILLER)
  78.590 +      png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  78.591 +#endif
  78.592 +#if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  78.593 +   if (png_ptr->transformations & PNG_PACKSWAP)
  78.594 +      png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  78.595 +#endif
  78.596 +#if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  78.597 +   if (png_ptr->transformations & PNG_PACK)
  78.598 +      png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  78.599 +#endif
  78.600 +#if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  78.601 +   if (png_ptr->transformations & PNG_SHIFT)
  78.602 +      png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  78.603 +#endif
  78.604 +#if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  78.605 +   if (png_ptr->transformations & PNG_BGR)
  78.606 +      png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  78.607 +#endif
  78.608 +#if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  78.609 +   if (png_ptr->transformations & PNG_SWAP_BYTES)
  78.610 +      png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  78.611 +#endif
  78.612 +   }
  78.613 +
  78.614 +#if defined(PNG_READ_INTERLACING_SUPPORTED)
  78.615 +   /* if interlaced and we do not need a new row, combine row and return */
  78.616 +   if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  78.617 +   {
  78.618 +      switch (png_ptr->pass)
  78.619 +      {
  78.620 +         case 0:
  78.621 +            if (png_ptr->row_number & 0x07)
  78.622 +            {
  78.623 +               if (dsp_row != NULL)
  78.624 +                  png_combine_row(png_ptr, dsp_row,
  78.625 +                     png_pass_dsp_mask[png_ptr->pass]);
  78.626 +               png_read_finish_row(png_ptr);
  78.627 +               return;
  78.628 +            }
  78.629 +            break;
  78.630 +         case 1:
  78.631 +            if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  78.632 +            {
  78.633 +               if (dsp_row != NULL)
  78.634 +                  png_combine_row(png_ptr, dsp_row,
  78.635 +                     png_pass_dsp_mask[png_ptr->pass]);
  78.636 +               png_read_finish_row(png_ptr);
  78.637 +               return;
  78.638 +            }
  78.639 +            break;
  78.640 +         case 2:
  78.641 +            if ((png_ptr->row_number & 0x07) != 4)
  78.642 +            {
  78.643 +               if (dsp_row != NULL && (png_ptr->row_number & 4))
  78.644 +                  png_combine_row(png_ptr, dsp_row,
  78.645 +                     png_pass_dsp_mask[png_ptr->pass]);
  78.646 +               png_read_finish_row(png_ptr);
  78.647 +               return;
  78.648 +            }
  78.649 +            break;
  78.650 +         case 3:
  78.651 +            if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  78.652 +            {
  78.653 +               if (dsp_row != NULL)
  78.654 +                  png_combine_row(png_ptr, dsp_row,
  78.655 +                     png_pass_dsp_mask[png_ptr->pass]);
  78.656 +               png_read_finish_row(png_ptr);
  78.657 +               return;
  78.658 +            }
  78.659 +            break;
  78.660 +         case 4:
  78.661 +            if ((png_ptr->row_number & 3) != 2)
  78.662 +            {
  78.663 +               if (dsp_row != NULL && (png_ptr->row_number & 2))
  78.664 +                  png_combine_row(png_ptr, dsp_row,
  78.665 +                     png_pass_dsp_mask[png_ptr->pass]);
  78.666 +               png_read_finish_row(png_ptr);
  78.667 +               return;
  78.668 +            }
  78.669 +            break;
  78.670 +         case 5:
  78.671 +            if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  78.672 +            {
  78.673 +               if (dsp_row != NULL)
  78.674 +                  png_combine_row(png_ptr, dsp_row,
  78.675 +                     png_pass_dsp_mask[png_ptr->pass]);
  78.676 +               png_read_finish_row(png_ptr);
  78.677 +               return;
  78.678 +            }
  78.679 +            break;
  78.680 +         case 6:
  78.681 +            if (!(png_ptr->row_number & 1))
  78.682 +            {
  78.683 +               png_read_finish_row(png_ptr);
  78.684 +               return;
  78.685 +            }
  78.686 +            break;
  78.687 +      }
  78.688 +   }
  78.689 +#endif
  78.690 +
  78.691 +   if (!(png_ptr->mode & PNG_HAVE_IDAT))
  78.692 +      png_error(png_ptr, "Invalid attempt to read row data");
  78.693 +
  78.694 +   png_ptr->zstream.next_out = png_ptr->row_buf;
  78.695 +   png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  78.696 +   do
  78.697 +   {
  78.698 +      if (!(png_ptr->zstream.avail_in))
  78.699 +      {
  78.700 +         while (!png_ptr->idat_size)
  78.701 +         {
  78.702 +            png_crc_finish(png_ptr, 0);
  78.703 +
  78.704 +            png_ptr->idat_size = png_read_chunk_header(png_ptr);
  78.705 +            if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  78.706 +               png_error(png_ptr, "Not enough image data");
  78.707 +         }
  78.708 +         png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  78.709 +         png_ptr->zstream.next_in = png_ptr->zbuf;
  78.710 +         if (png_ptr->zbuf_size > png_ptr->idat_size)
  78.711 +            png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  78.712 +         png_crc_read(png_ptr, png_ptr->zbuf,
  78.713 +            (png_size_t)png_ptr->zstream.avail_in);
  78.714 +         png_ptr->idat_size -= png_ptr->zstream.avail_in;
  78.715 +      }
  78.716 +      ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  78.717 +      if (ret == Z_STREAM_END)
  78.718 +      {
  78.719 +         if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  78.720 +            png_ptr->idat_size)
  78.721 +            png_error(png_ptr, "Extra compressed data");
  78.722 +         png_ptr->mode |= PNG_AFTER_IDAT;
  78.723 +         png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  78.724 +         break;
  78.725 +      }
  78.726 +      if (ret != Z_OK)
  78.727 +         png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  78.728 +                   "Decompression error");
  78.729 +
  78.730 +   } while (png_ptr->zstream.avail_out);
  78.731 +
  78.732 +   png_ptr->row_info.color_type = png_ptr->color_type;
  78.733 +   png_ptr->row_info.width = png_ptr->iwidth;
  78.734 +   png_ptr->row_info.channels = png_ptr->channels;
  78.735 +   png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  78.736 +   png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  78.737 +   png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  78.738 +       png_ptr->row_info.width);
  78.739 +
  78.740 +   if (png_ptr->row_buf[0])
  78.741 +   png_read_filter_row(png_ptr, &(png_ptr->row_info),
  78.742 +      png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  78.743 +      (int)(png_ptr->row_buf[0]));
  78.744 +
  78.745 +   png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  78.746 +      png_ptr->rowbytes + 1);
  78.747 +
  78.748 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
  78.749 +   if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  78.750 +      (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  78.751 +   {
  78.752 +      /* Intrapixel differencing */
  78.753 +      png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  78.754 +   }
  78.755 +#endif
  78.756 +
  78.757 +
  78.758 +   if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  78.759 +      png_do_read_transformations(png_ptr);
  78.760 +
  78.761 +#if defined(PNG_READ_INTERLACING_SUPPORTED)
  78.762 +   /* blow up interlaced rows to full size */
  78.763 +   if (png_ptr->interlaced &&
  78.764 +      (png_ptr->transformations & PNG_INTERLACE))
  78.765 +   {
  78.766 +      if (png_ptr->pass < 6)
  78.767 +/*       old interface (pre-1.0.9):
  78.768 +         png_do_read_interlace(&(png_ptr->row_info),
  78.769 +            png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  78.770 + */
  78.771 +         png_do_read_interlace(png_ptr);
  78.772 +
  78.773 +      if (dsp_row != NULL)
  78.774 +         png_combine_row(png_ptr, dsp_row,
  78.775 +            png_pass_dsp_mask[png_ptr->pass]);
  78.776 +      if (row != NULL)
  78.777 +         png_combine_row(png_ptr, row,
  78.778 +            png_pass_mask[png_ptr->pass]);
  78.779 +   }
  78.780 +   else
  78.781 +#endif
  78.782 +   {
  78.783 +      if (row != NULL)
  78.784 +         png_combine_row(png_ptr, row, 0xff);
  78.785 +      if (dsp_row != NULL)
  78.786 +         png_combine_row(png_ptr, dsp_row, 0xff);
  78.787 +   }
  78.788 +   png_read_finish_row(png_ptr);
  78.789 +
  78.790 +   if (png_ptr->read_row_fn != NULL)
  78.791 +      (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  78.792 +}
  78.793 +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  78.794 +
  78.795 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  78.796 +/* Read one or more rows of image data.  If the image is interlaced,
  78.797 + * and png_set_interlace_handling() has been called, the rows need to
  78.798 + * contain the contents of the rows from the previous pass.  If the
  78.799 + * image has alpha or transparency, and png_handle_alpha()[*] has been
  78.800 + * called, the rows contents must be initialized to the contents of the
  78.801 + * screen.
  78.802 + *
  78.803 + * "row" holds the actual image, and pixels are placed in it
  78.804 + * as they arrive.  If the image is displayed after each pass, it will
  78.805 + * appear to "sparkle" in.  "display_row" can be used to display a
  78.806 + * "chunky" progressive image, with finer detail added as it becomes
  78.807 + * available.  If you do not want this "chunky" display, you may pass
  78.808 + * NULL for display_row.  If you do not want the sparkle display, and
  78.809 + * you have not called png_handle_alpha(), you may pass NULL for rows.
  78.810 + * If you have called png_handle_alpha(), and the image has either an
  78.811 + * alpha channel or a transparency chunk, you must provide a buffer for
  78.812 + * rows.  In this case, you do not have to provide a display_row buffer
  78.813 + * also, but you may.  If the image is not interlaced, or if you have
  78.814 + * not called png_set_interlace_handling(), the display_row buffer will
  78.815 + * be ignored, so pass NULL to it.
  78.816 + *
  78.817 + * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  78.818 + */
  78.819 +
  78.820 +void PNGAPI
  78.821 +png_read_rows(png_structp png_ptr, png_bytepp row,
  78.822 +   png_bytepp display_row, png_uint_32 num_rows)
  78.823 +{
  78.824 +   png_uint_32 i;
  78.825 +   png_bytepp rp;
  78.826 +   png_bytepp dp;
  78.827 +
  78.828 +   png_debug(1, "in png_read_rows\n");
  78.829 +   if (png_ptr == NULL) return;
  78.830 +   rp = row;
  78.831 +   dp = display_row;
  78.832 +   if (rp != NULL && dp != NULL)
  78.833 +      for (i = 0; i < num_rows; i++)
  78.834 +      {
  78.835 +         png_bytep rptr = *rp++;
  78.836 +         png_bytep dptr = *dp++;
  78.837 +
  78.838 +         png_read_row(png_ptr, rptr, dptr);
  78.839 +      }
  78.840 +   else if (rp != NULL)
  78.841 +      for (i = 0; i < num_rows; i++)
  78.842 +      {
  78.843 +         png_bytep rptr = *rp;
  78.844 +         png_read_row(png_ptr, rptr, png_bytep_NULL);
  78.845 +         rp++;
  78.846 +      }
  78.847 +   else if (dp != NULL)
  78.848 +      for (i = 0; i < num_rows; i++)
  78.849 +      {
  78.850 +         png_bytep dptr = *dp;
  78.851 +         png_read_row(png_ptr, png_bytep_NULL, dptr);
  78.852 +         dp++;
  78.853 +      }
  78.854 +}
  78.855 +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  78.856 +
  78.857 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  78.858 +/* Read the entire image.  If the image has an alpha channel or a tRNS
  78.859 + * chunk, and you have called png_handle_alpha()[*], you will need to
  78.860 + * initialize the image to the current image that PNG will be overlaying.
  78.861 + * We set the num_rows again here, in case it was incorrectly set in
  78.862 + * png_read_start_row() by a call to png_read_update_info() or
  78.863 + * png_start_read_image() if png_set_interlace_handling() wasn't called
  78.864 + * prior to either of these functions like it should have been.  You can
  78.865 + * only call this function once.  If you desire to have an image for
  78.866 + * each pass of a interlaced image, use png_read_rows() instead.
  78.867 + *
  78.868 + * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  78.869 + */
  78.870 +void PNGAPI
  78.871 +png_read_image(png_structp png_ptr, png_bytepp image)
  78.872 +{
  78.873 +   png_uint_32 i, image_height;
  78.874 +   int pass, j;
  78.875 +   png_bytepp rp;
  78.876 +
  78.877 +   png_debug(1, "in png_read_image\n");
  78.878 +   if (png_ptr == NULL) return;
  78.879 +
  78.880 +#ifdef PNG_READ_INTERLACING_SUPPORTED
  78.881 +   pass = png_set_interlace_handling(png_ptr);
  78.882 +#else
  78.883 +   if (png_ptr->interlaced)
  78.884 +      png_error(png_ptr,
  78.885 +        "Cannot read interlaced image -- interlace handler disabled.");
  78.886 +   pass = 1;
  78.887 +#endif
  78.888 +
  78.889 +
  78.890 +   image_height=png_ptr->height;
  78.891 +   png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  78.892 +
  78.893 +   for (j = 0; j < pass; j++)
  78.894 +   {
  78.895 +      rp = image;
  78.896 +      for (i = 0; i < image_height; i++)
  78.897 +      {
  78.898 +         png_read_row(png_ptr, *rp, png_bytep_NULL);
  78.899 +         rp++;
  78.900 +      }
  78.901 +   }
  78.902 +}
  78.903 +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  78.904 +
  78.905 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  78.906 +/* Read the end of the PNG file.  Will not read past the end of the
  78.907 + * file, will verify the end is accurate, and will read any comments
  78.908 + * or time information at the end of the file, if info is not NULL.
  78.909 + */
  78.910 +void PNGAPI
  78.911 +png_read_end(png_structp png_ptr, png_infop info_ptr)
  78.912 +{
  78.913 +   png_debug(1, "in png_read_end\n");
  78.914 +   if (png_ptr == NULL) return;
  78.915 +   png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  78.916 +
  78.917 +   do
  78.918 +   {
  78.919 +#ifdef PNG_USE_LOCAL_ARRAYS
  78.920 +      PNG_CONST PNG_IHDR;
  78.921 +      PNG_CONST PNG_IDAT;
  78.922 +      PNG_CONST PNG_IEND;
  78.923 +      PNG_CONST PNG_PLTE;
  78.924 +#if defined(PNG_READ_bKGD_SUPPORTED)
  78.925 +      PNG_CONST PNG_bKGD;
  78.926 +#endif
  78.927 +#if defined(PNG_READ_cHRM_SUPPORTED)
  78.928 +      PNG_CONST PNG_cHRM;
  78.929 +#endif
  78.930 +#if defined(PNG_READ_gAMA_SUPPORTED)
  78.931 +      PNG_CONST PNG_gAMA;
  78.932 +#endif
  78.933 +#if defined(PNG_READ_hIST_SUPPORTED)
  78.934 +      PNG_CONST PNG_hIST;
  78.935 +#endif
  78.936 +#if defined(PNG_READ_iCCP_SUPPORTED)
  78.937 +      PNG_CONST PNG_iCCP;
  78.938 +#endif
  78.939 +#if defined(PNG_READ_iTXt_SUPPORTED)
  78.940 +      PNG_CONST PNG_iTXt;
  78.941 +#endif
  78.942 +#if defined(PNG_READ_oFFs_SUPPORTED)
  78.943 +      PNG_CONST PNG_oFFs;
  78.944 +#endif
  78.945 +#if defined(PNG_READ_pCAL_SUPPORTED)
  78.946 +      PNG_CONST PNG_pCAL;
  78.947 +#endif
  78.948 +#if defined(PNG_READ_pHYs_SUPPORTED)
  78.949 +      PNG_CONST PNG_pHYs;
  78.950 +#endif
  78.951 +#if defined(PNG_READ_sBIT_SUPPORTED)
  78.952 +      PNG_CONST PNG_sBIT;
  78.953 +#endif
  78.954 +#if defined(PNG_READ_sCAL_SUPPORTED)
  78.955 +      PNG_CONST PNG_sCAL;
  78.956 +#endif
  78.957 +#if defined(PNG_READ_sPLT_SUPPORTED)
  78.958 +      PNG_CONST PNG_sPLT;
  78.959 +#endif
  78.960 +#if defined(PNG_READ_sRGB_SUPPORTED)
  78.961 +      PNG_CONST PNG_sRGB;
  78.962 +#endif
  78.963 +#if defined(PNG_READ_tEXt_SUPPORTED)
  78.964 +      PNG_CONST PNG_tEXt;
  78.965 +#endif
  78.966 +#if defined(PNG_READ_tIME_SUPPORTED)
  78.967 +      PNG_CONST PNG_tIME;
  78.968 +#endif
  78.969 +#if defined(PNG_READ_tRNS_SUPPORTED)
  78.970 +      PNG_CONST PNG_tRNS;
  78.971 +#endif
  78.972 +#if defined(PNG_READ_zTXt_SUPPORTED)
  78.973 +      PNG_CONST PNG_zTXt;
  78.974 +#endif
  78.975 +#endif /* PNG_USE_LOCAL_ARRAYS */
  78.976 +      png_uint_32 length = png_read_chunk_header(png_ptr);
  78.977 +      PNG_CONST png_bytep chunk_name = png_ptr->chunk_name;
  78.978 +
  78.979 +      if (!png_memcmp(chunk_name, png_IHDR, 4))
  78.980 +         png_handle_IHDR(png_ptr, info_ptr, length);
  78.981 +      else if (!png_memcmp(chunk_name, png_IEND, 4))
  78.982 +         png_handle_IEND(png_ptr, info_ptr, length);
  78.983 +#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  78.984 +      else if (png_handle_as_unknown(png_ptr, chunk_name))
  78.985 +      {
  78.986 +         if (!png_memcmp(chunk_name, png_IDAT, 4))
  78.987 +         {
  78.988 +            if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  78.989 +               png_error(png_ptr, "Too many IDAT's found");
  78.990 +         }
  78.991 +         png_handle_unknown(png_ptr, info_ptr, length);
  78.992 +         if (!png_memcmp(chunk_name, png_PLTE, 4))
  78.993 +            png_ptr->mode |= PNG_HAVE_PLTE;
  78.994 +      }
  78.995 +#endif
  78.996 +      else if (!png_memcmp(chunk_name, png_IDAT, 4))
  78.997 +      {
  78.998 +         /* Zero length IDATs are legal after the last IDAT has been
  78.999 +          * read, but not after other chunks have been read.
 78.1000 +          */
 78.1001 +         if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
 78.1002 +            png_error(png_ptr, "Too many IDAT's found");
 78.1003 +         png_crc_finish(png_ptr, length);
 78.1004 +      }
 78.1005 +      else if (!png_memcmp(chunk_name, png_PLTE, 4))
 78.1006 +         png_handle_PLTE(png_ptr, info_ptr, length);
 78.1007 +#if defined(PNG_READ_bKGD_SUPPORTED)
 78.1008 +      else if (!png_memcmp(chunk_name, png_bKGD, 4))
 78.1009 +         png_handle_bKGD(png_ptr, info_ptr, length);
 78.1010 +#endif
 78.1011 +#if defined(PNG_READ_cHRM_SUPPORTED)
 78.1012 +      else if (!png_memcmp(chunk_name, png_cHRM, 4))
 78.1013 +         png_handle_cHRM(png_ptr, info_ptr, length);
 78.1014 +#endif
 78.1015 +#if defined(PNG_READ_gAMA_SUPPORTED)
 78.1016 +      else if (!png_memcmp(chunk_name, png_gAMA, 4))
 78.1017 +         png_handle_gAMA(png_ptr, info_ptr, length);
 78.1018 +#endif
 78.1019 +#if defined(PNG_READ_hIST_SUPPORTED)
 78.1020 +      else if (!png_memcmp(chunk_name, png_hIST, 4))
 78.1021 +         png_handle_hIST(png_ptr, info_ptr, length);
 78.1022 +#endif
 78.1023 +#if defined(PNG_READ_oFFs_SUPPORTED)
 78.1024 +      else if (!png_memcmp(chunk_name, png_oFFs, 4))
 78.1025 +         png_handle_oFFs(png_ptr, info_ptr, length);
 78.1026 +#endif
 78.1027 +#if defined(PNG_READ_pCAL_SUPPORTED)
 78.1028 +      else if (!png_memcmp(chunk_name, png_pCAL, 4))
 78.1029 +         png_handle_pCAL(png_ptr, info_ptr, length);
 78.1030 +#endif
 78.1031 +#if defined(PNG_READ_sCAL_SUPPORTED)
 78.1032 +      else if (!png_memcmp(chunk_name, png_sCAL, 4))
 78.1033 +         png_handle_sCAL(png_ptr, info_ptr, length);
 78.1034 +#endif
 78.1035 +#if defined(PNG_READ_pHYs_SUPPORTED)
 78.1036 +      else if (!png_memcmp(chunk_name, png_pHYs, 4))
 78.1037 +         png_handle_pHYs(png_ptr, info_ptr, length);
 78.1038 +#endif
 78.1039 +#if defined(PNG_READ_sBIT_SUPPORTED)
 78.1040 +      else if (!png_memcmp(chunk_name, png_sBIT, 4))
 78.1041 +         png_handle_sBIT(png_ptr, info_ptr, length);
 78.1042 +#endif
 78.1043 +#if defined(PNG_READ_sRGB_SUPPORTED)
 78.1044 +      else if (!png_memcmp(chunk_name, png_sRGB, 4))
 78.1045 +         png_handle_sRGB(png_ptr, info_ptr, length);
 78.1046 +#endif
 78.1047 +#if defined(PNG_READ_iCCP_SUPPORTED)
 78.1048 +      else if (!png_memcmp(chunk_name, png_iCCP, 4))
 78.1049 +         png_handle_iCCP(png_ptr, info_ptr, length);
 78.1050 +#endif
 78.1051 +#if defined(PNG_READ_sPLT_SUPPORTED)
 78.1052 +      else if (!png_memcmp(chunk_name, png_sPLT, 4))
 78.1053 +         png_handle_sPLT(png_ptr, info_ptr, length);
 78.1054 +#endif
 78.1055 +#if defined(PNG_READ_tEXt_SUPPORTED)
 78.1056 +      else if (!png_memcmp(chunk_name, png_tEXt, 4))
 78.1057 +         png_handle_tEXt(png_ptr, info_ptr, length);
 78.1058 +#endif
 78.1059 +#if defined(PNG_READ_tIME_SUPPORTED)
 78.1060 +      else if (!png_memcmp(chunk_name, png_tIME, 4))
 78.1061 +         png_handle_tIME(png_ptr, info_ptr, length);
 78.1062 +#endif
 78.1063 +#if defined(PNG_READ_tRNS_SUPPORTED)
 78.1064 +      else if (!png_memcmp(chunk_name, png_tRNS, 4))
 78.1065 +         png_handle_tRNS(png_ptr, info_ptr, length);
 78.1066 +#endif
 78.1067 +#if defined(PNG_READ_zTXt_SUPPORTED)
 78.1068 +      else if (!png_memcmp(chunk_name, png_zTXt, 4))
 78.1069 +         png_handle_zTXt(png_ptr, info_ptr, length);
 78.1070 +#endif
 78.1071 +#if defined(PNG_READ_iTXt_SUPPORTED)
 78.1072 +      else if (!png_memcmp(chunk_name, png_iTXt, 4))
 78.1073 +         png_handle_iTXt(png_ptr, info_ptr, length);
 78.1074 +#endif
 78.1075 +      else
 78.1076 +         png_handle_unknown(png_ptr, info_ptr, length);
 78.1077 +   } while (!(png_ptr->mode & PNG_HAVE_IEND));
 78.1078 +}
 78.1079 +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
 78.1080 +
 78.1081 +/* free all memory used by the read */
 78.1082 +void PNGAPI
 78.1083 +png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
 78.1084 +   png_infopp end_info_ptr_ptr)
 78.1085 +{
 78.1086 +   png_structp png_ptr = NULL;
 78.1087 +   png_infop info_ptr = NULL, end_info_ptr = NULL;
 78.1088 +#ifdef PNG_USER_MEM_SUPPORTED
 78.1089 +   png_free_ptr free_fn = NULL;
 78.1090 +   png_voidp mem_ptr = NULL;
 78.1091 +#endif
 78.1092 +
 78.1093 +   png_debug(1, "in png_destroy_read_struct\n");
 78.1094 +   if (png_ptr_ptr != NULL)
 78.1095 +      png_ptr = *png_ptr_ptr;
 78.1096 +   if (png_ptr == NULL)
 78.1097 +      return;
 78.1098 +
 78.1099 +#ifdef PNG_USER_MEM_SUPPORTED
 78.1100 +   free_fn = png_ptr->free_fn;
 78.1101 +   mem_ptr = png_ptr->mem_ptr;
 78.1102 +#endif
 78.1103 +
 78.1104 +   if (info_ptr_ptr != NULL)
 78.1105 +      info_ptr = *info_ptr_ptr;
 78.1106 +
 78.1107 +   if (end_info_ptr_ptr != NULL)
 78.1108 +      end_info_ptr = *end_info_ptr_ptr;
 78.1109 +
 78.1110 +   png_read_destroy(png_ptr, info_ptr, end_info_ptr);
 78.1111 +
 78.1112 +   if (info_ptr != NULL)
 78.1113 +   {
 78.1114 +#if defined(PNG_TEXT_SUPPORTED)
 78.1115 +      png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
 78.1116 +#endif
 78.1117 +
 78.1118 +#ifdef PNG_USER_MEM_SUPPORTED
 78.1119 +      png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
 78.1120 +          (png_voidp)mem_ptr);
 78.1121 +#else
 78.1122 +      png_destroy_struct((png_voidp)info_ptr);
 78.1123 +#endif
 78.1124 +      *info_ptr_ptr = NULL;
 78.1125 +   }
 78.1126 +
 78.1127 +   if (end_info_ptr != NULL)
 78.1128 +   {
 78.1129 +#if defined(PNG_READ_TEXT_SUPPORTED)
 78.1130 +      png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
 78.1131 +#endif
 78.1132 +#ifdef PNG_USER_MEM_SUPPORTED
 78.1133 +      png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
 78.1134 +         (png_voidp)mem_ptr);
 78.1135 +#else
 78.1136 +      png_destroy_struct((png_voidp)end_info_ptr);
 78.1137 +#endif
 78.1138 +      *end_info_ptr_ptr = NULL;
 78.1139 +   }
 78.1140 +
 78.1141 +   if (png_ptr != NULL)
 78.1142 +   {
 78.1143 +#ifdef PNG_USER_MEM_SUPPORTED
 78.1144 +      png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
 78.1145 +          (png_voidp)mem_ptr);
 78.1146 +#else
 78.1147 +      png_destroy_struct((png_voidp)png_ptr);
 78.1148 +#endif
 78.1149 +      *png_ptr_ptr = NULL;
 78.1150 +   }
 78.1151 +}
 78.1152 +
 78.1153 +/* free all memory used by the read (old method) */
 78.1154 +void /* PRIVATE */
 78.1155 +png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
 78.1156 +{
 78.1157 +#ifdef PNG_SETJMP_SUPPORTED
 78.1158 +   jmp_buf tmp_jmp;
 78.1159 +#endif
 78.1160 +   png_error_ptr error_fn;
 78.1161 +   png_error_ptr warning_fn;
 78.1162 +   png_voidp error_ptr;
 78.1163 +#ifdef PNG_USER_MEM_SUPPORTED
 78.1164 +   png_free_ptr free_fn;
 78.1165 +#endif
 78.1166 +
 78.1167 +   png_debug(1, "in png_read_destroy\n");
 78.1168 +   if (info_ptr != NULL)
 78.1169 +      png_info_destroy(png_ptr, info_ptr);
 78.1170 +
 78.1171 +   if (end_info_ptr != NULL)
 78.1172 +      png_info_destroy(png_ptr, end_info_ptr);
 78.1173 +
 78.1174 +   png_free(png_ptr, png_ptr->zbuf);
 78.1175 +   png_free(png_ptr, png_ptr->big_row_buf);
 78.1176 +   png_free(png_ptr, png_ptr->prev_row);
 78.1177 +   png_free(png_ptr, png_ptr->chunkdata);
 78.1178 +#if defined(PNG_READ_DITHER_SUPPORTED)
 78.1179 +   png_free(png_ptr, png_ptr->palette_lookup);
 78.1180 +   png_free(png_ptr, png_ptr->dither_index);
 78.1181 +#endif
 78.1182 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 78.1183 +   png_free(png_ptr, png_ptr->gamma_table);
 78.1184 +#endif
 78.1185 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 78.1186 +   png_free(png_ptr, png_ptr->gamma_from_1);
 78.1187 +   png_free(png_ptr, png_ptr->gamma_to_1);
 78.1188 +#endif
 78.1189 +#ifdef PNG_FREE_ME_SUPPORTED
 78.1190 +   if (png_ptr->free_me & PNG_FREE_PLTE)
 78.1191 +      png_zfree(png_ptr, png_ptr->palette);
 78.1192 +   png_ptr->free_me &= ~PNG_FREE_PLTE;
 78.1193 +#else
 78.1194 +   if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
 78.1195 +      png_zfree(png_ptr, png_ptr->palette);
 78.1196 +   png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
 78.1197 +#endif
 78.1198 +#if defined(PNG_tRNS_SUPPORTED) || \
 78.1199 +    defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
 78.1200 +#ifdef PNG_FREE_ME_SUPPORTED
 78.1201 +   if (png_ptr->free_me & PNG_FREE_TRNS)
 78.1202 +      png_free(png_ptr, png_ptr->trans);
 78.1203 +   png_ptr->free_me &= ~PNG_FREE_TRNS;
 78.1204 +#else
 78.1205 +   if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
 78.1206 +      png_free(png_ptr, png_ptr->trans);
 78.1207 +   png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
 78.1208 +#endif
 78.1209 +#endif
 78.1210 +#if defined(PNG_READ_hIST_SUPPORTED)
 78.1211 +#ifdef PNG_FREE_ME_SUPPORTED
 78.1212 +   if (png_ptr->free_me & PNG_FREE_HIST)
 78.1213 +      png_free(png_ptr, png_ptr->hist);
 78.1214 +   png_ptr->free_me &= ~PNG_FREE_HIST;
 78.1215 +#else
 78.1216 +   if (png_ptr->flags & PNG_FLAG_FREE_HIST)
 78.1217 +      png_free(png_ptr, png_ptr->hist);
 78.1218 +   png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
 78.1219 +#endif
 78.1220 +#endif
 78.1221 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 78.1222 +   if (png_ptr->gamma_16_table != NULL)
 78.1223 +   {
 78.1224 +      int i;
 78.1225 +      int istop = (1 << (8 - png_ptr->gamma_shift));
 78.1226 +      for (i = 0; i < istop; i++)
 78.1227 +      {
 78.1228 +         png_free(png_ptr, png_ptr->gamma_16_table[i]);
 78.1229 +      }
 78.1230 +   png_free(png_ptr, png_ptr->gamma_16_table);
 78.1231 +   }
 78.1232 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 78.1233 +   if (png_ptr->gamma_16_from_1 != NULL)
 78.1234 +   {
 78.1235 +      int i;
 78.1236 +      int istop = (1 << (8 - png_ptr->gamma_shift));
 78.1237 +      for (i = 0; i < istop; i++)
 78.1238 +      {
 78.1239 +         png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
 78.1240 +      }
 78.1241 +   png_free(png_ptr, png_ptr->gamma_16_from_1);
 78.1242 +   }
 78.1243 +   if (png_ptr->gamma_16_to_1 != NULL)
 78.1244 +   {
 78.1245 +      int i;
 78.1246 +      int istop = (1 << (8 - png_ptr->gamma_shift));
 78.1247 +      for (i = 0; i < istop; i++)
 78.1248 +      {
 78.1249 +         png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
 78.1250 +      }
 78.1251 +   png_free(png_ptr, png_ptr->gamma_16_to_1);
 78.1252 +   }
 78.1253 +#endif
 78.1254 +#endif
 78.1255 +#if defined(PNG_TIME_RFC1123_SUPPORTED)
 78.1256 +   png_free(png_ptr, png_ptr->time_buffer);
 78.1257 +#endif
 78.1258 +
 78.1259 +   inflateEnd(&png_ptr->zstream);
 78.1260 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 78.1261 +   png_free(png_ptr, png_ptr->save_buffer);
 78.1262 +#endif
 78.1263 +
 78.1264 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 78.1265 +#ifdef PNG_TEXT_SUPPORTED
 78.1266 +   png_free(png_ptr, png_ptr->current_text);
 78.1267 +#endif /* PNG_TEXT_SUPPORTED */
 78.1268 +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
 78.1269 +
 78.1270 +   /* Save the important info out of the png_struct, in case it is
 78.1271 +    * being used again.
 78.1272 +    */
 78.1273 +#ifdef PNG_SETJMP_SUPPORTED
 78.1274 +   png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
 78.1275 +#endif
 78.1276 +
 78.1277 +   error_fn = png_ptr->error_fn;
 78.1278 +   warning_fn = png_ptr->warning_fn;
 78.1279 +   error_ptr = png_ptr->error_ptr;
 78.1280 +#ifdef PNG_USER_MEM_SUPPORTED
 78.1281 +   free_fn = png_ptr->free_fn;
 78.1282 +#endif
 78.1283 +
 78.1284 +   png_memset(png_ptr, 0, png_sizeof(png_struct));
 78.1285 +
 78.1286 +   png_ptr->error_fn = error_fn;
 78.1287 +   png_ptr->warning_fn = warning_fn;
 78.1288 +   png_ptr->error_ptr = error_ptr;
 78.1289 +#ifdef PNG_USER_MEM_SUPPORTED
 78.1290 +   png_ptr->free_fn = free_fn;
 78.1291 +#endif
 78.1292 +
 78.1293 +#ifdef PNG_SETJMP_SUPPORTED
 78.1294 +   png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
 78.1295 +#endif
 78.1296 +
 78.1297 +}
 78.1298 +
 78.1299 +void PNGAPI
 78.1300 +png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
 78.1301 +{
 78.1302 +   if (png_ptr == NULL) return;
 78.1303 +   png_ptr->read_row_fn = read_row_fn;
 78.1304 +}
 78.1305 +
 78.1306 +
 78.1307 +#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
 78.1308 +#if defined(PNG_INFO_IMAGE_SUPPORTED)
 78.1309 +void PNGAPI
 78.1310 +png_read_png(png_structp png_ptr, png_infop info_ptr,
 78.1311 +                           int transforms,
 78.1312 +                           voidp params)
 78.1313 +{
 78.1314 +   int row;
 78.1315 +
 78.1316 +   if (png_ptr == NULL) return;
 78.1317 +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
 78.1318 +   /* invert the alpha channel from opacity to transparency
 78.1319 +    */
 78.1320 +   if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
 78.1321 +       png_set_invert_alpha(png_ptr);
 78.1322 +#endif
 78.1323 +
 78.1324 +   /* png_read_info() gives us all of the information from the
 78.1325 +    * PNG file before the first IDAT (image data chunk).
 78.1326 +    */
 78.1327 +   png_read_info(png_ptr, info_ptr);
 78.1328 +   if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
 78.1329 +      png_error(png_ptr, "Image is too high to process with png_read_png()");
 78.1330 +
 78.1331 +   /* -------------- image transformations start here ------------------- */
 78.1332 +
 78.1333 +#if defined(PNG_READ_16_TO_8_SUPPORTED)
 78.1334 +   /* tell libpng to strip 16 bit/color files down to 8 bits per color
 78.1335 +    */
 78.1336 +   if (transforms & PNG_TRANSFORM_STRIP_16)
 78.1337 +       png_set_strip_16(png_ptr);
 78.1338 +#endif
 78.1339 +
 78.1340 +#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
 78.1341 +   /* Strip alpha bytes from the input data without combining with
 78.1342 +    * the background (not recommended).
 78.1343 +    */
 78.1344 +   if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
 78.1345 +       png_set_strip_alpha(png_ptr);
 78.1346 +#endif
 78.1347 +
 78.1348 +#if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
 78.1349 +   /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
 78.1350 +    * byte into separate bytes (useful for paletted and grayscale images).
 78.1351 +    */
 78.1352 +   if (transforms & PNG_TRANSFORM_PACKING)
 78.1353 +       png_set_packing(png_ptr);
 78.1354 +#endif
 78.1355 +
 78.1356 +#if defined(PNG_READ_PACKSWAP_SUPPORTED)
 78.1357 +   /* Change the order of packed pixels to least significant bit first
 78.1358 +    * (not useful if you are using png_set_packing).
 78.1359 +    */
 78.1360 +   if (transforms & PNG_TRANSFORM_PACKSWAP)
 78.1361 +       png_set_packswap(png_ptr);
 78.1362 +#endif
 78.1363 +
 78.1364 +#if defined(PNG_READ_EXPAND_SUPPORTED)
 78.1365 +   /* Expand paletted colors into true RGB triplets
 78.1366 +    * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
 78.1367 +    * Expand paletted or RGB images with transparency to full alpha
 78.1368 +    * channels so the data will be available as RGBA quartets.
 78.1369 +    */
 78.1370 +   if (transforms & PNG_TRANSFORM_EXPAND)
 78.1371 +       if ((png_ptr->bit_depth < 8) ||
 78.1372 +           (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
 78.1373 +           (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
 78.1374 +         png_set_expand(png_ptr);
 78.1375 +#endif
 78.1376 +
 78.1377 +   /* We don't handle background color or gamma transformation or dithering.
 78.1378 +    */
 78.1379 +
 78.1380 +#if defined(PNG_READ_INVERT_SUPPORTED)
 78.1381 +   /* invert monochrome files to have 0 as white and 1 as black
 78.1382 +    */
 78.1383 +   if (transforms & PNG_TRANSFORM_INVERT_MONO)
 78.1384 +       png_set_invert_mono(png_ptr);
 78.1385 +#endif
 78.1386 +
 78.1387 +#if defined(PNG_READ_SHIFT_SUPPORTED)
 78.1388 +   /* If you want to shift the pixel values from the range [0,255] or
 78.1389 +    * [0,65535] to the original [0,7] or [0,31], or whatever range the
 78.1390 +    * colors were originally in:
 78.1391 +    */
 78.1392 +   if ((transforms & PNG_TRANSFORM_SHIFT)
 78.1393 +       && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
 78.1394 +   {
 78.1395 +      png_color_8p sig_bit;
 78.1396 +
 78.1397 +      png_get_sBIT(png_ptr, info_ptr, &sig_bit);
 78.1398 +      png_set_shift(png_ptr, sig_bit);
 78.1399 +   }
 78.1400 +#endif
 78.1401 +
 78.1402 +#if defined(PNG_READ_BGR_SUPPORTED)
 78.1403 +   /* flip the RGB pixels to BGR (or RGBA to BGRA)
 78.1404 +    */
 78.1405 +   if (transforms & PNG_TRANSFORM_BGR)
 78.1406 +       png_set_bgr(png_ptr);
 78.1407 +#endif
 78.1408 +
 78.1409 +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
 78.1410 +   /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
 78.1411 +    */
 78.1412 +   if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
 78.1413 +       png_set_swap_alpha(png_ptr);
 78.1414 +#endif
 78.1415 +
 78.1416 +#if defined(PNG_READ_SWAP_SUPPORTED)
 78.1417 +   /* swap bytes of 16 bit files to least significant byte first
 78.1418 +    */
 78.1419 +   if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
 78.1420 +       png_set_swap(png_ptr);
 78.1421 +#endif
 78.1422 +
 78.1423 +   /* We don't handle adding filler bytes */
 78.1424 +
 78.1425 +   /* Optional call to gamma correct and add the background to the palette
 78.1426 +    * and update info structure.  REQUIRED if you are expecting libpng to
 78.1427 +    * update the palette for you (i.e., you selected such a transform above).
 78.1428 +    */
 78.1429 +   png_read_update_info(png_ptr, info_ptr);
 78.1430 +
 78.1431 +   /* -------------- image transformations end here ------------------- */
 78.1432 +
 78.1433 +#ifdef PNG_FREE_ME_SUPPORTED
 78.1434 +   png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
 78.1435 +#endif
 78.1436 +   if (info_ptr->row_pointers == NULL)
 78.1437 +   {
 78.1438 +      info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
 78.1439 +         info_ptr->height * png_sizeof(png_bytep));
 78.1440 +#ifdef PNG_FREE_ME_SUPPORTED
 78.1441 +      info_ptr->free_me |= PNG_FREE_ROWS;
 78.1442 +#endif
 78.1443 +      for (row = 0; row < (int)info_ptr->height; row++)
 78.1444 +      {
 78.1445 +         info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
 78.1446 +            png_get_rowbytes(png_ptr, info_ptr));
 78.1447 +      }
 78.1448 +   }
 78.1449 +
 78.1450 +   png_read_image(png_ptr, info_ptr->row_pointers);
 78.1451 +   info_ptr->valid |= PNG_INFO_IDAT;
 78.1452 +
 78.1453 +   /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
 78.1454 +   png_read_end(png_ptr, info_ptr);
 78.1455 +
 78.1456 +   transforms = transforms; /* quiet compiler warnings */
 78.1457 +   params = params;
 78.1458 +
 78.1459 +}
 78.1460 +#endif /* PNG_INFO_IMAGE_SUPPORTED */
 78.1461 +#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
 78.1462 +#endif /* PNG_READ_SUPPORTED */
    79.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    79.2 +++ b/libs/libpng/pngrio.c	Thu Sep 08 06:28:38 2011 +0300
    79.3 @@ -0,0 +1,166 @@
    79.4 +
    79.5 +/* pngrio.c - functions for data input
    79.6 + *
    79.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    79.8 + * For conditions of distribution and use, see copyright notice in png.h
    79.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   79.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   79.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   79.12 + *
   79.13 + * This file provides a location for all input.  Users who need
   79.14 + * special handling are expected to write a function that has the same
   79.15 + * arguments as this and performs a similar function, but that possibly
   79.16 + * has a different input method.  Note that you shouldn't change this
   79.17 + * function, but rather write a replacement function and then make
   79.18 + * libpng use it at run time with png_set_read_fn(...).
   79.19 + */
   79.20 +
   79.21 +#define PNG_INTERNAL
   79.22 +#include "png.h"
   79.23 +#if defined(PNG_READ_SUPPORTED)
   79.24 +
   79.25 +/* Read the data from whatever input you are using.  The default routine
   79.26 +   reads from a file pointer.  Note that this routine sometimes gets called
   79.27 +   with very small lengths, so you should implement some kind of simple
   79.28 +   buffering if you are using unbuffered reads.  This should never be asked
   79.29 +   to read more then 64K on a 16 bit machine. */
   79.30 +void /* PRIVATE */
   79.31 +png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
   79.32 +{
   79.33 +   png_debug1(4, "reading %d bytes\n", (int)length);
   79.34 +   if (png_ptr->read_data_fn != NULL)
   79.35 +      (*(png_ptr->read_data_fn))(png_ptr, data, length);
   79.36 +   else
   79.37 +      png_error(png_ptr, "Call to NULL read function");
   79.38 +}
   79.39 +
   79.40 +#if !defined(PNG_NO_STDIO)
   79.41 +/* This is the function that does the actual reading of data.  If you are
   79.42 +   not reading from a standard C stream, you should create a replacement
   79.43 +   read_data function and use it at run time with png_set_read_fn(), rather
   79.44 +   than changing the library. */
   79.45 +#ifndef USE_FAR_KEYWORD
   79.46 +void PNGAPI
   79.47 +png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
   79.48 +{
   79.49 +   png_size_t check;
   79.50 +
   79.51 +   if (png_ptr == NULL) return;
   79.52 +   /* fread() returns 0 on error, so it is OK to store this in a png_size_t
   79.53 +    * instead of an int, which is what fread() actually returns.
   79.54 +    */
   79.55 +#if defined(_WIN32_WCE)
   79.56 +   if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
   79.57 +      check = 0;
   79.58 +#else
   79.59 +   check = (png_size_t)fread(data, (png_size_t)1, length,
   79.60 +      (png_FILE_p)png_ptr->io_ptr);
   79.61 +#endif
   79.62 +
   79.63 +   if (check != length)
   79.64 +      png_error(png_ptr, "Read Error");
   79.65 +}
   79.66 +#else
   79.67 +/* this is the model-independent version. Since the standard I/O library
   79.68 +   can't handle far buffers in the medium and small models, we have to copy
   79.69 +   the data.
   79.70 +*/
   79.71 +
   79.72 +#define NEAR_BUF_SIZE 1024
   79.73 +#define MIN(a,b) (a <= b ? a : b)
   79.74 +
   79.75 +static void PNGAPI
   79.76 +png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
   79.77 +{
   79.78 +   int check;
   79.79 +   png_byte *n_data;
   79.80 +   png_FILE_p io_ptr;
   79.81 +
   79.82 +   if (png_ptr == NULL) return;
   79.83 +   /* Check if data really is near. If so, use usual code. */
   79.84 +   n_data = (png_byte *)CVT_PTR_NOCHECK(data);
   79.85 +   io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
   79.86 +   if ((png_bytep)n_data == data)
   79.87 +   {
   79.88 +#if defined(_WIN32_WCE)
   79.89 +      if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
   79.90 +         check = 0;
   79.91 +#else
   79.92 +      check = fread(n_data, 1, length, io_ptr);
   79.93 +#endif
   79.94 +   }
   79.95 +   else
   79.96 +   {
   79.97 +      png_byte buf[NEAR_BUF_SIZE];
   79.98 +      png_size_t read, remaining, err;
   79.99 +      check = 0;
  79.100 +      remaining = length;
  79.101 +      do
  79.102 +      {
  79.103 +         read = MIN(NEAR_BUF_SIZE, remaining);
  79.104 +#if defined(_WIN32_WCE)
  79.105 +         if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  79.106 +            err = 0;
  79.107 +#else
  79.108 +         err = fread(buf, (png_size_t)1, read, io_ptr);
  79.109 +#endif
  79.110 +         png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  79.111 +         if (err != read)
  79.112 +            break;
  79.113 +         else
  79.114 +            check += err;
  79.115 +         data += read;
  79.116 +         remaining -= read;
  79.117 +      }
  79.118 +      while (remaining != 0);
  79.119 +   }
  79.120 +   if ((png_uint_32)check != (png_uint_32)length)
  79.121 +      png_error(png_ptr, "read Error");
  79.122 +}
  79.123 +#endif
  79.124 +#endif
  79.125 +
  79.126 +/* This function allows the application to supply a new input function
  79.127 +   for libpng if standard C streams aren't being used.
  79.128 +
  79.129 +   This function takes as its arguments:
  79.130 +   png_ptr      - pointer to a png input data structure
  79.131 +   io_ptr       - pointer to user supplied structure containing info about
  79.132 +                  the input functions.  May be NULL.
  79.133 +   read_data_fn - pointer to a new input function that takes as its
  79.134 +                  arguments a pointer to a png_struct, a pointer to
  79.135 +                  a location where input data can be stored, and a 32-bit
  79.136 +                  unsigned int that is the number of bytes to be read.
  79.137 +                  To exit and output any fatal error messages the new write
  79.138 +                  function should call png_error(png_ptr, "Error msg"). */
  79.139 +void PNGAPI
  79.140 +png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  79.141 +   png_rw_ptr read_data_fn)
  79.142 +{
  79.143 +   if (png_ptr == NULL) return;
  79.144 +   png_ptr->io_ptr = io_ptr;
  79.145 +
  79.146 +#if !defined(PNG_NO_STDIO)
  79.147 +   if (read_data_fn != NULL)
  79.148 +      png_ptr->read_data_fn = read_data_fn;
  79.149 +   else
  79.150 +      png_ptr->read_data_fn = png_default_read_data;
  79.151 +#else
  79.152 +   png_ptr->read_data_fn = read_data_fn;
  79.153 +#endif
  79.154 +
  79.155 +   /* It is an error to write to a read device */
  79.156 +   if (png_ptr->write_data_fn != NULL)
  79.157 +   {
  79.158 +      png_ptr->write_data_fn = NULL;
  79.159 +      png_warning(png_ptr,
  79.160 +         "It's an error to set both read_data_fn and write_data_fn in the ");
  79.161 +      png_warning(png_ptr,
  79.162 +         "same structure.  Resetting write_data_fn to NULL.");
  79.163 +   }
  79.164 +
  79.165 +#if defined(PNG_WRITE_FLUSH_SUPPORTED)
  79.166 +   png_ptr->output_flush_fn = NULL;
  79.167 +#endif
  79.168 +}
  79.169 +#endif /* PNG_READ_SUPPORTED */
    80.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    80.2 +++ b/libs/libpng/pngrtran.c	Thu Sep 08 06:28:38 2011 +0300
    80.3 @@ -0,0 +1,4296 @@
    80.4 +
    80.5 +/* pngrtran.c - transforms the data in a row for PNG readers
    80.6 + *
    80.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    80.8 + * For conditions of distribution and use, see copyright notice in png.h
    80.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   80.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   80.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   80.12 + *
   80.13 + * This file contains functions optionally called by an application
   80.14 + * in order to tell libpng how to handle data when reading a PNG.
   80.15 + * Transformations that are used in both reading and writing are
   80.16 + * in pngtrans.c.
   80.17 + */
   80.18 +
   80.19 +#define PNG_INTERNAL
   80.20 +#include "png.h"
   80.21 +#if defined(PNG_READ_SUPPORTED)
   80.22 +
   80.23 +/* Set the action on getting a CRC error for an ancillary or critical chunk. */
   80.24 +void PNGAPI
   80.25 +png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
   80.26 +{
   80.27 +   png_debug(1, "in png_set_crc_action\n");
   80.28 +   /* Tell libpng how we react to CRC errors in critical chunks */
   80.29 +   if (png_ptr == NULL) return;
   80.30 +   switch (crit_action)
   80.31 +   {
   80.32 +      case PNG_CRC_NO_CHANGE:                        /* leave setting as is */
   80.33 +         break;
   80.34 +      case PNG_CRC_WARN_USE:                               /* warn/use data */
   80.35 +         png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
   80.36 +         png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
   80.37 +         break;
   80.38 +      case PNG_CRC_QUIET_USE:                             /* quiet/use data */
   80.39 +         png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
   80.40 +         png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
   80.41 +                           PNG_FLAG_CRC_CRITICAL_IGNORE;
   80.42 +         break;
   80.43 +      case PNG_CRC_WARN_DISCARD:    /* not a valid action for critical data */
   80.44 +         png_warning(png_ptr,
   80.45 +            "Can't discard critical data on CRC error.");
   80.46 +      case PNG_CRC_ERROR_QUIT:                                /* error/quit */
   80.47 +      case PNG_CRC_DEFAULT:
   80.48 +      default:
   80.49 +         png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
   80.50 +         break;
   80.51 +   }
   80.52 +
   80.53 +   switch (ancil_action)
   80.54 +   {
   80.55 +      case PNG_CRC_NO_CHANGE:                       /* leave setting as is */
   80.56 +         break;
   80.57 +      case PNG_CRC_WARN_USE:                              /* warn/use data */
   80.58 +         png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
   80.59 +         png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
   80.60 +         break;
   80.61 +      case PNG_CRC_QUIET_USE:                            /* quiet/use data */
   80.62 +         png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
   80.63 +         png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
   80.64 +                           PNG_FLAG_CRC_ANCILLARY_NOWARN;
   80.65 +         break;
   80.66 +      case PNG_CRC_ERROR_QUIT:                               /* error/quit */
   80.67 +         png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
   80.68 +         png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
   80.69 +         break;
   80.70 +      case PNG_CRC_WARN_DISCARD:                      /* warn/discard data */
   80.71 +      case PNG_CRC_DEFAULT:
   80.72 +      default:
   80.73 +         png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
   80.74 +         break;
   80.75 +   }
   80.76 +}
   80.77 +
   80.78 +#if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
   80.79 +    defined(PNG_FLOATING_POINT_SUPPORTED)
   80.80 +/* handle alpha and tRNS via a background color */
   80.81 +void PNGAPI
   80.82 +png_set_background(png_structp png_ptr,
   80.83 +   png_color_16p background_color, int background_gamma_code,
   80.84 +   int need_expand, double background_gamma)
   80.85 +{
   80.86 +   png_debug(1, "in png_set_background\n");
   80.87 +   if (png_ptr == NULL) return;
   80.88 +   if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
   80.89 +   {
   80.90 +      png_warning(png_ptr, "Application must supply a known background gamma");
   80.91 +      return;
   80.92 +   }
   80.93 +
   80.94 +   png_ptr->transformations |= PNG_BACKGROUND;
   80.95 +   png_memcpy(&(png_ptr->background), background_color,
   80.96 +      png_sizeof(png_color_16));
   80.97 +   png_ptr->background_gamma = (float)background_gamma;
   80.98 +   png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
   80.99 +   png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  80.100 +}
  80.101 +#endif
  80.102 +
  80.103 +#if defined(PNG_READ_16_TO_8_SUPPORTED)
  80.104 +/* strip 16 bit depth files to 8 bit depth */
  80.105 +void PNGAPI
  80.106 +png_set_strip_16(png_structp png_ptr)
  80.107 +{
  80.108 +   png_debug(1, "in png_set_strip_16\n");
  80.109 +   if (png_ptr == NULL) return;
  80.110 +   png_ptr->transformations |= PNG_16_TO_8;
  80.111 +}
  80.112 +#endif
  80.113 +
  80.114 +#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  80.115 +void PNGAPI
  80.116 +png_set_strip_alpha(png_structp png_ptr)
  80.117 +{
  80.118 +   png_debug(1, "in png_set_strip_alpha\n");
  80.119 +   if (png_ptr == NULL) return;
  80.120 +   png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  80.121 +}
  80.122 +#endif
  80.123 +
  80.124 +#if defined(PNG_READ_DITHER_SUPPORTED)
  80.125 +/* Dither file to 8 bit.  Supply a palette, the current number
  80.126 + * of elements in the palette, the maximum number of elements
  80.127 + * allowed, and a histogram if possible.  If the current number
  80.128 + * of colors is greater then the maximum number, the palette will be
  80.129 + * modified to fit in the maximum number.  "full_dither" indicates
  80.130 + * whether we need a dithering cube set up for RGB images, or if we
  80.131 + * simply are reducing the number of colors in a paletted image.
  80.132 + */
  80.133 +
  80.134 +typedef struct png_dsort_struct
  80.135 +{
  80.136 +   struct png_dsort_struct FAR * next;
  80.137 +   png_byte left;
  80.138 +   png_byte right;
  80.139 +} png_dsort;
  80.140 +typedef png_dsort FAR *       png_dsortp;
  80.141 +typedef png_dsort FAR * FAR * png_dsortpp;
  80.142 +
  80.143 +void PNGAPI
  80.144 +png_set_dither(png_structp png_ptr, png_colorp palette,
  80.145 +   int num_palette, int maximum_colors, png_uint_16p histogram,
  80.146 +   int full_dither)
  80.147 +{
  80.148 +   png_debug(1, "in png_set_dither\n");
  80.149 +   if (png_ptr == NULL) return;
  80.150 +   png_ptr->transformations |= PNG_DITHER;
  80.151 +
  80.152 +   if (!full_dither)
  80.153 +   {
  80.154 +      int i;
  80.155 +
  80.156 +      png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  80.157 +         (png_uint_32)(num_palette * png_sizeof(png_byte)));
  80.158 +      for (i = 0; i < num_palette; i++)
  80.159 +         png_ptr->dither_index[i] = (png_byte)i;
  80.160 +   }
  80.161 +
  80.162 +   if (num_palette > maximum_colors)
  80.163 +   {
  80.164 +      if (histogram != NULL)
  80.165 +      {
  80.166 +         /* This is easy enough, just throw out the least used colors.
  80.167 +            Perhaps not the best solution, but good enough. */
  80.168 +
  80.169 +         int i;
  80.170 +
  80.171 +         /* initialize an array to sort colors */
  80.172 +         png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  80.173 +            (png_uint_32)(num_palette * png_sizeof(png_byte)));
  80.174 +
  80.175 +         /* initialize the dither_sort array */
  80.176 +         for (i = 0; i < num_palette; i++)
  80.177 +            png_ptr->dither_sort[i] = (png_byte)i;
  80.178 +
  80.179 +         /* Find the least used palette entries by starting a
  80.180 +            bubble sort, and running it until we have sorted
  80.181 +            out enough colors.  Note that we don't care about
  80.182 +            sorting all the colors, just finding which are
  80.183 +            least used. */
  80.184 +
  80.185 +         for (i = num_palette - 1; i >= maximum_colors; i--)
  80.186 +         {
  80.187 +            int done; /* to stop early if the list is pre-sorted */
  80.188 +            int j;
  80.189 +
  80.190 +            done = 1;
  80.191 +            for (j = 0; j < i; j++)
  80.192 +            {
  80.193 +               if (histogram[png_ptr->dither_sort[j]]
  80.194 +                   < histogram[png_ptr->dither_sort[j + 1]])
  80.195 +               {
  80.196 +                  png_byte t;
  80.197 +
  80.198 +                  t = png_ptr->dither_sort[j];
  80.199 +                  png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  80.200 +                  png_ptr->dither_sort[j + 1] = t;
  80.201 +                  done = 0;
  80.202 +               }
  80.203 +            }
  80.204 +            if (done)
  80.205 +               break;
  80.206 +         }
  80.207 +
  80.208 +         /* swap the palette around, and set up a table, if necessary */
  80.209 +         if (full_dither)
  80.210 +         {
  80.211 +            int j = num_palette;
  80.212 +
  80.213 +            /* put all the useful colors within the max, but don't
  80.214 +               move the others */
  80.215 +            for (i = 0; i < maximum_colors; i++)
  80.216 +            {
  80.217 +               if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  80.218 +               {
  80.219 +                  do
  80.220 +                     j--;
  80.221 +                  while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  80.222 +                  palette[i] = palette[j];
  80.223 +               }
  80.224 +            }
  80.225 +         }
  80.226 +         else
  80.227 +         {
  80.228 +            int j = num_palette;
  80.229 +
  80.230 +            /* move all the used colors inside the max limit, and
  80.231 +               develop a translation table */
  80.232 +            for (i = 0; i < maximum_colors; i++)
  80.233 +            {
  80.234 +               /* only move the colors we need to */
  80.235 +               if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  80.236 +               {
  80.237 +                  png_color tmp_color;
  80.238 +
  80.239 +                  do
  80.240 +                     j--;
  80.241 +                  while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  80.242 +
  80.243 +                  tmp_color = palette[j];
  80.244 +                  palette[j] = palette[i];
  80.245 +                  palette[i] = tmp_color;
  80.246 +                  /* indicate where the color went */
  80.247 +                  png_ptr->dither_index[j] = (png_byte)i;
  80.248 +                  png_ptr->dither_index[i] = (png_byte)j;
  80.249 +               }
  80.250 +            }
  80.251 +
  80.252 +            /* find closest color for those colors we are not using */
  80.253 +            for (i = 0; i < num_palette; i++)
  80.254 +            {
  80.255 +               if ((int)png_ptr->dither_index[i] >= maximum_colors)
  80.256 +               {
  80.257 +                  int min_d, k, min_k, d_index;
  80.258 +
  80.259 +                  /* find the closest color to one we threw out */
  80.260 +                  d_index = png_ptr->dither_index[i];
  80.261 +                  min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  80.262 +                  for (k = 1, min_k = 0; k < maximum_colors; k++)
  80.263 +                  {
  80.264 +                     int d;
  80.265 +
  80.266 +                     d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  80.267 +
  80.268 +                     if (d < min_d)
  80.269 +                     {
  80.270 +                        min_d = d;
  80.271 +                        min_k = k;
  80.272 +                     }
  80.273 +                  }
  80.274 +                  /* point to closest color */
  80.275 +                  png_ptr->dither_index[i] = (png_byte)min_k;
  80.276 +               }
  80.277 +            }
  80.278 +         }
  80.279 +         png_free(png_ptr, png_ptr->dither_sort);
  80.280 +         png_ptr->dither_sort = NULL;
  80.281 +      }
  80.282 +      else
  80.283 +      {
  80.284 +         /* This is much harder to do simply (and quickly).  Perhaps
  80.285 +            we need to go through a median cut routine, but those
  80.286 +            don't always behave themselves with only a few colors
  80.287 +            as input.  So we will just find the closest two colors,
  80.288 +            and throw out one of them (chosen somewhat randomly).
  80.289 +            [We don't understand this at all, so if someone wants to
  80.290 +             work on improving it, be our guest - AED, GRP]
  80.291 +            */
  80.292 +         int i;
  80.293 +         int max_d;
  80.294 +         int num_new_palette;
  80.295 +         png_dsortp t;
  80.296 +         png_dsortpp hash;
  80.297 +
  80.298 +         t = NULL;
  80.299 +
  80.300 +         /* initialize palette index arrays */
  80.301 +         png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  80.302 +            (png_uint_32)(num_palette * png_sizeof(png_byte)));
  80.303 +         png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  80.304 +            (png_uint_32)(num_palette * png_sizeof(png_byte)));
  80.305 +
  80.306 +         /* initialize the sort array */
  80.307 +         for (i = 0; i < num_palette; i++)
  80.308 +         {
  80.309 +            png_ptr->index_to_palette[i] = (png_byte)i;
  80.310 +            png_ptr->palette_to_index[i] = (png_byte)i;
  80.311 +         }
  80.312 +
  80.313 +         hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  80.314 +            png_sizeof(png_dsortp)));
  80.315 +         for (i = 0; i < 769; i++)
  80.316 +            hash[i] = NULL;
  80.317 +/*         png_memset(hash, 0, 769 * png_sizeof(png_dsortp)); */
  80.318 +
  80.319 +         num_new_palette = num_palette;
  80.320 +
  80.321 +         /* initial wild guess at how far apart the farthest pixel
  80.322 +            pair we will be eliminating will be.  Larger
  80.323 +            numbers mean more areas will be allocated, Smaller
  80.324 +            numbers run the risk of not saving enough data, and
  80.325 +            having to do this all over again.
  80.326 +
  80.327 +            I have not done extensive checking on this number.
  80.328 +            */
  80.329 +         max_d = 96;
  80.330 +
  80.331 +         while (num_new_palette > maximum_colors)
  80.332 +         {
  80.333 +            for (i = 0; i < num_new_palette - 1; i++)
  80.334 +            {
  80.335 +               int j;
  80.336 +
  80.337 +               for (j = i + 1; j < num_new_palette; j++)
  80.338 +               {
  80.339 +                  int d;
  80.340 +
  80.341 +                  d = PNG_COLOR_DIST(palette[i], palette[j]);
  80.342 +
  80.343 +                  if (d <= max_d)
  80.344 +                  {
  80.345 +
  80.346 +                     t = (png_dsortp)png_malloc_warn(png_ptr,
  80.347 +                         (png_uint_32)(png_sizeof(png_dsort)));
  80.348 +                     if (t == NULL)
  80.349 +                         break;
  80.350 +                     t->next = hash[d];
  80.351 +                     t->left = (png_byte)i;
  80.352 +                     t->right = (png_byte)j;
  80.353 +                     hash[d] = t;
  80.354 +                  }
  80.355 +               }
  80.356 +               if (t == NULL)
  80.357 +                  break;
  80.358 +            }
  80.359 +
  80.360 +            if (t != NULL)
  80.361 +            for (i = 0; i <= max_d; i++)
  80.362 +            {
  80.363 +               if (hash[i] != NULL)
  80.364 +               {
  80.365 +                  png_dsortp p;
  80.366 +
  80.367 +                  for (p = hash[i]; p; p = p->next)
  80.368 +                  {
  80.369 +                     if ((int)png_ptr->index_to_palette[p->left]
  80.370 +                        < num_new_palette &&
  80.371 +                        (int)png_ptr->index_to_palette[p->right]
  80.372 +                        < num_new_palette)
  80.373 +                     {
  80.374 +                        int j, next_j;
  80.375 +
  80.376 +                        if (num_new_palette & 0x01)
  80.377 +                        {
  80.378 +                           j = p->left;
  80.379 +                           next_j = p->right;
  80.380 +                        }
  80.381 +                        else
  80.382 +                        {
  80.383 +                           j = p->right;
  80.384 +                           next_j = p->left;
  80.385 +                        }
  80.386 +
  80.387 +                        num_new_palette--;
  80.388 +                        palette[png_ptr->index_to_palette[j]]
  80.389 +                          = palette[num_new_palette];
  80.390 +                        if (!full_dither)
  80.391 +                        {
  80.392 +                           int k;
  80.393 +
  80.394 +                           for (k = 0; k < num_palette; k++)
  80.395 +                           {
  80.396 +                              if (png_ptr->dither_index[k] ==
  80.397 +                                 png_ptr->index_to_palette[j])
  80.398 +                                 png_ptr->dither_index[k] =
  80.399 +                                    png_ptr->index_to_palette[next_j];
  80.400 +                              if ((int)png_ptr->dither_index[k] ==
  80.401 +                                 num_new_palette)
  80.402 +                                 png_ptr->dither_index[k] =
  80.403 +                                    png_ptr->index_to_palette[j];
  80.404 +                           }
  80.405 +                        }
  80.406 +
  80.407 +                        png_ptr->index_to_palette[png_ptr->palette_to_index
  80.408 +                           [num_new_palette]] = png_ptr->index_to_palette[j];
  80.409 +                        png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  80.410 +                           = png_ptr->palette_to_index[num_new_palette];
  80.411 +
  80.412 +                        png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  80.413 +                        png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  80.414 +                     }
  80.415 +                     if (num_new_palette <= maximum_colors)
  80.416 +                        break;
  80.417 +                  }
  80.418 +                  if (num_new_palette <= maximum_colors)
  80.419 +                     break;
  80.420 +               }
  80.421 +            }
  80.422 +
  80.423 +            for (i = 0; i < 769; i++)
  80.424 +            {
  80.425 +               if (hash[i] != NULL)
  80.426 +               {
  80.427 +                  png_dsortp p = hash[i];
  80.428 +                  while (p)
  80.429 +                  {
  80.430 +                     t = p->next;
  80.431 +                     png_free(png_ptr, p);
  80.432 +                     p = t;
  80.433 +                  }
  80.434 +               }
  80.435 +               hash[i] = 0;
  80.436 +            }
  80.437 +            max_d += 96;
  80.438 +         }
  80.439 +         png_free(png_ptr, hash);
  80.440 +         png_free(png_ptr, png_ptr->palette_to_index);
  80.441 +         png_free(png_ptr, png_ptr->index_to_palette);
  80.442 +         png_ptr->palette_to_index = NULL;
  80.443 +         png_ptr->index_to_palette = NULL;
  80.444 +      }
  80.445 +      num_palette = maximum_colors;
  80.446 +   }
  80.447 +   if (png_ptr->palette == NULL)
  80.448 +   {
  80.449 +      png_ptr->palette = palette;
  80.450 +   }
  80.451 +   png_ptr->num_palette = (png_uint_16)num_palette;
  80.452 +
  80.453 +   if (full_dither)
  80.454 +   {
  80.455 +      int i;
  80.456 +      png_bytep distance;
  80.457 +      int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  80.458 +         PNG_DITHER_BLUE_BITS;
  80.459 +      int num_red = (1 << PNG_DITHER_RED_BITS);
  80.460 +      int num_green = (1 << PNG_DITHER_GREEN_BITS);
  80.461 +      int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  80.462 +      png_size_t num_entries = ((png_size_t)1 << total_bits);
  80.463 +
  80.464 +      png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  80.465 +         (png_uint_32)(num_entries * png_sizeof(png_byte)));
  80.466 +
  80.467 +      png_memset(png_ptr->palette_lookup, 0, num_entries *
  80.468 +         png_sizeof(png_byte));
  80.469 +
  80.470 +      distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  80.471 +         png_sizeof(png_byte)));
  80.472 +
  80.473 +      png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  80.474 +
  80.475 +      for (i = 0; i < num_palette; i++)
  80.476 +      {
  80.477 +         int ir, ig, ib;
  80.478 +         int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  80.479 +         int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  80.480 +         int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  80.481 +
  80.482 +         for (ir = 0; ir < num_red; ir++)
  80.483 +         {
  80.484 +            /* int dr = abs(ir - r); */
  80.485 +            int dr = ((ir > r) ? ir - r : r - ir);
  80.486 +            int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  80.487 +
  80.488 +            for (ig = 0; ig < num_green; ig++)
  80.489 +            {
  80.490 +               /* int dg = abs(ig - g); */
  80.491 +               int dg = ((ig > g) ? ig - g : g - ig);
  80.492 +               int dt = dr + dg;
  80.493 +               int dm = ((dr > dg) ? dr : dg);
  80.494 +               int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  80.495 +
  80.496 +               for (ib = 0; ib < num_blue; ib++)
  80.497 +               {
  80.498 +                  int d_index = index_g | ib;
  80.499 +                  /* int db = abs(ib - b); */
  80.500 +                  int db = ((ib > b) ? ib - b : b - ib);
  80.501 +                  int dmax = ((dm > db) ? dm : db);
  80.502 +                  int d = dmax + dt + db;
  80.503 +
  80.504 +                  if (d < (int)distance[d_index])
  80.505 +                  {
  80.506 +                     distance[d_index] = (png_byte)d;
  80.507 +                     png_ptr->palette_lookup[d_index] = (png_byte)i;
  80.508 +                  }
  80.509 +               }
  80.510 +            }
  80.511 +         }
  80.512 +      }
  80.513 +
  80.514 +      png_free(png_ptr, distance);
  80.515 +   }
  80.516 +}
  80.517 +#endif
  80.518 +
  80.519 +#if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  80.520 +/* Transform the image from the file_gamma to the screen_gamma.  We
  80.521 + * only do transformations on images where the file_gamma and screen_gamma
  80.522 + * are not close reciprocals, otherwise it slows things down slightly, and
  80.523 + * also needlessly introduces small errors.
  80.524 + *
  80.525 + * We will turn off gamma transformation later if no semitransparent entries
  80.526 + * are present in the tRNS array for palette images.  We can't do it here
  80.527 + * because we don't necessarily have the tRNS chunk yet.
  80.528 + */
  80.529 +void PNGAPI
  80.530 +png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  80.531 +{
  80.532 +   png_debug(1, "in png_set_gamma\n");
  80.533 +   if (png_ptr == NULL) return;
  80.534 +   if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  80.535 +       (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  80.536 +       (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  80.537 +     png_ptr->transformations |= PNG_GAMMA;
  80.538 +   png_ptr->gamma = (float)file_gamma;
  80.539 +   png_ptr->screen_gamma = (float)scrn_gamma;
  80.540 +}
  80.541 +#endif
  80.542 +
  80.543 +#if defined(PNG_READ_EXPAND_SUPPORTED)
  80.544 +/* Expand paletted images to RGB, expand grayscale images of
  80.545 + * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  80.546 + * to alpha channels.
  80.547 + */
  80.548 +void PNGAPI
  80.549 +png_set_expand(png_structp png_ptr)
  80.550 +{
  80.551 +   png_debug(1, "in png_set_expand\n");
  80.552 +   if (png_ptr == NULL) return;
  80.553 +   png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  80.554 +   png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  80.555 +}
  80.556 +
  80.557 +/* GRR 19990627:  the following three functions currently are identical
  80.558 + *  to png_set_expand().  However, it is entirely reasonable that someone
  80.559 + *  might wish to expand an indexed image to RGB but *not* expand a single,
  80.560 + *  fully transparent palette entry to a full alpha channel--perhaps instead
  80.561 + *  convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  80.562 + *  the transparent color with a particular RGB value, or drop tRNS entirely.
  80.563 + *  IOW, a future version of the library may make the transformations flag
  80.564 + *  a bit more fine-grained, with separate bits for each of these three
  80.565 + *  functions.
  80.566 + *
  80.567 + *  More to the point, these functions make it obvious what libpng will be
  80.568 + *  doing, whereas "expand" can (and does) mean any number of things.
  80.569 + *
  80.570 + *  GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  80.571 + *  to expand only the sample depth but not to expand the tRNS to alpha.
  80.572 + */
  80.573 +
  80.574 +/* Expand paletted images to RGB. */
  80.575 +void PNGAPI
  80.576 +png_set_palette_to_rgb(png_structp png_ptr)
  80.577 +{
  80.578 +   png_debug(1, "in png_set_palette_to_rgb\n");
  80.579 +   if (png_ptr == NULL) return;
  80.580 +   png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  80.581 +   png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  80.582 +}
  80.583 +
  80.584 +#if !defined(PNG_1_0_X)
  80.585 +/* Expand grayscale images of less than 8-bit depth to 8 bits. */
  80.586 +void PNGAPI
  80.587 +png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  80.588 +{
  80.589 +   png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  80.590 +   if (png_ptr == NULL) return;
  80.591 +   png_ptr->transformations |= PNG_EXPAND;
  80.592 +   png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  80.593 +}
  80.594 +#endif
  80.595 +
  80.596 +#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  80.597 +/* Expand grayscale images of less than 8-bit depth to 8 bits. */
  80.598 +/* Deprecated as of libpng-1.2.9 */
  80.599 +void PNGAPI
  80.600 +png_set_gray_1_2_4_to_8(png_structp png_ptr)
  80.601 +{
  80.602 +   png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  80.603 +   if (png_ptr == NULL) return;
  80.604 +   png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  80.605 +}
  80.606 +#endif
  80.607 +
  80.608 +
  80.609 +/* Expand tRNS chunks to alpha channels. */
  80.610 +void PNGAPI
  80.611 +png_set_tRNS_to_alpha(png_structp png_ptr)
  80.612 +{
  80.613 +   png_debug(1, "in png_set_tRNS_to_alpha\n");
  80.614 +   png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  80.615 +   png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  80.616 +}
  80.617 +#endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  80.618 +
  80.619 +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  80.620 +void PNGAPI
  80.621 +png_set_gray_to_rgb(png_structp png_ptr)
  80.622 +{
  80.623 +   png_debug(1, "in png_set_gray_to_rgb\n");
  80.624 +   png_ptr->transformations |= PNG_GRAY_TO_RGB;
  80.625 +   png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  80.626 +}
  80.627 +#endif
  80.628 +
  80.629 +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  80.630 +#if defined(PNG_FLOATING_POINT_SUPPORTED)
  80.631 +/* Convert a RGB image to a grayscale of the same width.  This allows us,
  80.632 + * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  80.633 + */
  80.634 +
  80.635 +void PNGAPI
  80.636 +png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  80.637 +   double green)
  80.638 +{
  80.639 +      int red_fixed = (int)((float)red*100000.0 + 0.5);
  80.640 +      int green_fixed = (int)((float)green*100000.0 + 0.5);
  80.641 +      if (png_ptr == NULL) return;
  80.642 +      png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  80.643 +}
  80.644 +#endif
  80.645 +
  80.646 +void PNGAPI
  80.647 +png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  80.648 +   png_fixed_point red, png_fixed_point green)
  80.649 +{
  80.650 +   png_debug(1, "in png_set_rgb_to_gray\n");
  80.651 +   if (png_ptr == NULL) return;
  80.652 +   switch(error_action)
  80.653 +   {
  80.654 +      case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  80.655 +              break;
  80.656 +      case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  80.657 +              break;
  80.658 +      case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  80.659 +   }
  80.660 +   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  80.661 +#if defined(PNG_READ_EXPAND_SUPPORTED)
  80.662 +      png_ptr->transformations |= PNG_EXPAND;
  80.663 +#else
  80.664 +   {
  80.665 +      png_warning(png_ptr,
  80.666 +        "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  80.667 +      png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  80.668 +   }
  80.669 +#endif
  80.670 +   {
  80.671 +      png_uint_16 red_int, green_int;
  80.672 +      if (red < 0 || green < 0)
  80.673 +      {
  80.674 +         red_int   =  6968; /* .212671 * 32768 + .5 */
  80.675 +         green_int = 23434; /* .715160 * 32768 + .5 */
  80.676 +      }
  80.677 +      else if (red + green < 100000L)
  80.678 +      {
  80.679 +        red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  80.680 +        green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  80.681 +      }
  80.682 +      else
  80.683 +      {
  80.684 +         png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  80.685 +         red_int   =  6968;
  80.686 +         green_int = 23434;
  80.687 +      }
  80.688 +      png_ptr->rgb_to_gray_red_coeff   = red_int;
  80.689 +      png_ptr->rgb_to_gray_green_coeff = green_int;
  80.690 +      png_ptr->rgb_to_gray_blue_coeff  = 
  80.691 +         (png_uint_16)(32768 - red_int - green_int);
  80.692 +   }
  80.693 +}
  80.694 +#endif
  80.695 +
  80.696 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  80.697 +    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  80.698 +    defined(PNG_LEGACY_SUPPORTED)
  80.699 +void PNGAPI
  80.700 +png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  80.701 +   read_user_transform_fn)
  80.702 +{
  80.703 +   png_debug(1, "in png_set_read_user_transform_fn\n");
  80.704 +   if (png_ptr == NULL) return;
  80.705 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  80.706 +   png_ptr->transformations |= PNG_USER_TRANSFORM;
  80.707 +   png_ptr->read_user_transform_fn = read_user_transform_fn;
  80.708 +#endif
  80.709 +#ifdef PNG_LEGACY_SUPPORTED
  80.710 +   if (read_user_transform_fn)
  80.711 +      png_warning(png_ptr,
  80.712 +        "This version of libpng does not support user transforms");
  80.713 +#endif
  80.714 +}
  80.715 +#endif
  80.716 +
  80.717 +/* Initialize everything needed for the read.  This includes modifying
  80.718 + * the palette.
  80.719 + */
  80.720 +void /* PRIVATE */
  80.721 +png_init_read_transformations(png_structp png_ptr)
  80.722 +{
  80.723 +   png_debug(1, "in png_init_read_transformations\n");
  80.724 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
  80.725 +   if (png_ptr != NULL)
  80.726 +#endif
  80.727 +  {
  80.728 +#if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  80.729 + || defined(PNG_READ_GAMMA_SUPPORTED)
  80.730 +   int color_type = png_ptr->color_type;
  80.731 +#endif
  80.732 +
  80.733 +#if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  80.734 +
  80.735 +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  80.736 +   /* Detect gray background and attempt to enable optimization
  80.737 +    * for gray --> RGB case */
  80.738 +   /* Note:  if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  80.739 +    * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  80.740 +    * background color might actually be gray yet not be flagged as such.
  80.741 +    * This is not a problem for the current code, which uses
  80.742 +    * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  80.743 +    * png_do_gray_to_rgb() transformation.
  80.744 +    */
  80.745 +   if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  80.746 +       !(color_type & PNG_COLOR_MASK_COLOR))
  80.747 +   {
  80.748 +          png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  80.749 +   } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  80.750 +              !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  80.751 +              (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  80.752 +              png_ptr->background.red == png_ptr->background.green &&
  80.753 +              png_ptr->background.red == png_ptr->background.blue)
  80.754 +   {
  80.755 +          png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  80.756 +          png_ptr->background.gray = png_ptr->background.red;
  80.757 +   }
  80.758 +#endif
  80.759 +
  80.760 +   if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  80.761 +       (png_ptr->transformations & PNG_EXPAND))
  80.762 +   {
  80.763 +      if (!(color_type & PNG_COLOR_MASK_COLOR))  /* i.e., GRAY or GRAY_ALPHA */
  80.764 +      {
  80.765 +         /* expand background and tRNS chunks */
  80.766 +         switch (png_ptr->bit_depth)
  80.767 +         {
  80.768 +            case 1:
  80.769 +               png_ptr->background.gray *= (png_uint_16)0xff;
  80.770 +               png_ptr->background.red = png_ptr->background.green
  80.771 +                 =  png_ptr->background.blue = png_ptr->background.gray;
  80.772 +               if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  80.773 +               {
  80.774 +                 png_ptr->trans_values.gray *= (png_uint_16)0xff;
  80.775 +                 png_ptr->trans_values.red = png_ptr->trans_values.green
  80.776 +                   = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  80.777 +               }
  80.778 +               break;
  80.779 +            case 2:
  80.780 +               png_ptr->background.gray *= (png_uint_16)0x55;
  80.781 +               png_ptr->background.red = png_ptr->background.green
  80.782 +                 = png_ptr->background.blue = png_ptr->background.gray;
  80.783 +               if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  80.784 +               {
  80.785 +                 png_ptr->trans_values.gray *= (png_uint_16)0x55;
  80.786 +                 png_ptr->trans_values.red = png_ptr->trans_values.green
  80.787 +                   = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  80.788 +               }
  80.789 +               break;
  80.790 +            case 4:
  80.791 +               png_ptr->background.gray *= (png_uint_16)0x11;
  80.792 +               png_ptr->background.red = png_ptr->background.green
  80.793 +                 = png_ptr->background.blue = png_ptr->background.gray;
  80.794 +               if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  80.795 +               {
  80.796 +                 png_ptr->trans_values.gray *= (png_uint_16)0x11;
  80.797 +                 png_ptr->trans_values.red = png_ptr->trans_values.green
  80.798 +                   = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  80.799 +               }
  80.800 +               break;
  80.801 +            case 8:
  80.802 +            case 16:
  80.803 +               png_ptr->background.red = png_ptr->background.green
  80.804 +                 = png_ptr->background.blue = png_ptr->background.gray;
  80.805 +               break;
  80.806 +         }
  80.807 +      }
  80.808 +      else if (color_type == PNG_COLOR_TYPE_PALETTE)
  80.809 +      {
  80.810 +         png_ptr->background.red   =
  80.811 +            png_ptr->palette[png_ptr->background.index].red;
  80.812 +         png_ptr->background.green =
  80.813 +            png_ptr->palette[png_ptr->background.index].green;
  80.814 +         png_ptr->background.blue  =
  80.815 +            png_ptr->palette[png_ptr->background.index].blue;
  80.816 +
  80.817 +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  80.818 +        if (png_ptr->transformations & PNG_INVERT_ALPHA)
  80.819 +        {
  80.820 +#if defined(PNG_READ_EXPAND_SUPPORTED)
  80.821 +           if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  80.822 +#endif
  80.823 +           {
  80.824 +           /* invert the alpha channel (in tRNS) unless the pixels are
  80.825 +              going to be expanded, in which case leave it for later */
  80.826 +              int i, istop;
  80.827 +              istop=(int)png_ptr->num_trans;
  80.828 +              for (i=0; i<istop; i++)
  80.829 +                 png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  80.830 +           }
  80.831 +        }
  80.832 +#endif
  80.833 +
  80.834 +      }
  80.835 +   }
  80.836 +#endif
  80.837 +
  80.838 +#if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  80.839 +   png_ptr->background_1 = png_ptr->background;
  80.840 +#endif
  80.841 +#if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  80.842 +
  80.843 +   if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  80.844 +       && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  80.845 +         < PNG_GAMMA_THRESHOLD))
  80.846 +   {
  80.847 +    int i, k;
  80.848 +    k=0;
  80.849 +    for (i=0; i<png_ptr->num_trans; i++)
  80.850 +    {
  80.851 +      if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  80.852 +        k=1; /* partial transparency is present */
  80.853 +    }
  80.854 +    if (k == 0)
  80.855 +      png_ptr->transformations &= ~PNG_GAMMA;
  80.856 +   }
  80.857 +
  80.858 +   if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  80.859 +        png_ptr->gamma != 0.0)
  80.860 +   {
  80.861 +      png_build_gamma_table(png_ptr);
  80.862 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
  80.863 +      if (png_ptr->transformations & PNG_BACKGROUND)
  80.864 +      {
  80.865 +         if (color_type == PNG_COLOR_TYPE_PALETTE)
  80.866 +         {
  80.867 +           /* could skip if no transparency and
  80.868 +           */
  80.869 +            png_color back, back_1;
  80.870 +            png_colorp palette = png_ptr->palette;
  80.871 +            int num_palette = png_ptr->num_palette;
  80.872 +            int i;
  80.873 +            if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  80.874 +            {
  80.875 +               back.red = png_ptr->gamma_table[png_ptr->background.red];
  80.876 +               back.green = png_ptr->gamma_table[png_ptr->background.green];
  80.877 +               back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  80.878 +
  80.879 +               back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  80.880 +               back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  80.881 +               back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  80.882 +            }
  80.883 +            else
  80.884 +            {
  80.885 +               double g, gs;
  80.886 +
  80.887 +               switch (png_ptr->background_gamma_type)
  80.888 +               {
  80.889 +                  case PNG_BACKGROUND_GAMMA_SCREEN:
  80.890 +                     g = (png_ptr->screen_gamma);
  80.891 +                     gs = 1.0;
  80.892 +                     break;
  80.893 +                  case PNG_BACKGROUND_GAMMA_FILE:
  80.894 +                     g = 1.0 / (png_ptr->gamma);
  80.895 +                     gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  80.896 +                     break;
  80.897 +                  case PNG_BACKGROUND_GAMMA_UNIQUE:
  80.898 +                     g = 1.0 / (png_ptr->background_gamma);
  80.899 +                     gs = 1.0 / (png_ptr->background_gamma *
  80.900 +                                 png_ptr->screen_gamma);
  80.901 +                     break;
  80.902 +                  default:
  80.903 +                     g = 1.0;    /* back_1 */
  80.904 +                     gs = 1.0;   /* back */
  80.905 +               }
  80.906 +
  80.907 +               if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  80.908 +               {
  80.909 +                  back.red   = (png_byte)png_ptr->background.red;
  80.910 +                  back.green = (png_byte)png_ptr->background.green;
  80.911 +                  back.blue  = (png_byte)png_ptr->background.blue;
  80.912 +               }
  80.913 +               else
  80.914 +               {
  80.915 +                  back.red = (png_byte)(pow(
  80.916 +                     (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  80.917 +                  back.green = (png_byte)(pow(
  80.918 +                     (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  80.919 +                  back.blue = (png_byte)(pow(
  80.920 +                     (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  80.921 +               }
  80.922 +
  80.923 +               back_1.red = (png_byte)(pow(
  80.924 +                  (double)png_ptr->background.red/255, g) * 255.0 + .5);
  80.925 +               back_1.green = (png_byte)(pow(
  80.926 +                  (double)png_ptr->background.green/255, g) * 255.0 + .5);
  80.927 +               back_1.blue = (png_byte)(pow(
  80.928 +                  (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  80.929 +            }
  80.930 +            for (i = 0; i < num_palette; i++)
  80.931 +            {
  80.932 +               if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  80.933 +               {
  80.934 +                  if (png_ptr->trans[i] == 0)
  80.935 +                  {
  80.936 +                     palette[i] = back;
  80.937 +                  }
  80.938 +                  else /* if (png_ptr->trans[i] != 0xff) */
  80.939 +                  {
  80.940 +                     png_byte v, w;
  80.941 +
  80.942 +                     v = png_ptr->gamma_to_1[palette[i].red];
  80.943 +                     png_composite(w, v, png_ptr->trans[i], back_1.red);
  80.944 +                     palette[i].red = png_ptr->gamma_from_1[w];
  80.945 +
  80.946 +                     v = png_ptr->gamma_to_1[palette[i].green];
  80.947 +                     png_composite(w, v, png_ptr->trans[i], back_1.green);
  80.948 +                     palette[i].green = png_ptr->gamma_from_1[w];
  80.949 +
  80.950 +                     v = png_ptr->gamma_to_1[palette[i].blue];
  80.951 +                     png_composite(w, v, png_ptr->trans[i], back_1.blue);
  80.952 +                     palette[i].blue = png_ptr->gamma_from_1[w];
  80.953 +                  }
  80.954 +               }
  80.955 +               else
  80.956 +               {
  80.957 +                  palette[i].red = png_ptr->gamma_table[palette[i].red];
  80.958 +                  palette[i].green = png_ptr->gamma_table[palette[i].green];
  80.959 +                  palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  80.960 +               }
  80.961 +            }
  80.962 +	    /* Prevent the transformations being done again, and make sure
  80.963 +	     * that the now spurious alpha channel is stripped - the code
  80.964 +	     * has just reduced background composition and gamma correction
  80.965 +	     * to a simple alpha channel strip.
  80.966 +	     */
  80.967 +	    png_ptr->transformations &= ~PNG_BACKGROUND;
  80.968 +	    png_ptr->transformations &= ~PNG_GAMMA;
  80.969 +	    png_ptr->transformations |= PNG_STRIP_ALPHA;
  80.970 +         }
  80.971 +         /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  80.972 +         else
  80.973 +         /* color_type != PNG_COLOR_TYPE_PALETTE */
  80.974 +         {
  80.975 +            double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  80.976 +            double g = 1.0;
  80.977 +            double gs = 1.0;
  80.978 +
  80.979 +            switch (png_ptr->background_gamma_type)
  80.980 +            {
  80.981 +               case PNG_BACKGROUND_GAMMA_SCREEN:
  80.982 +                  g = (png_ptr->screen_gamma);
  80.983 +                  gs = 1.0;
  80.984 +                  break;
  80.985 +               case PNG_BACKGROUND_GAMMA_FILE:
  80.986 +                  g = 1.0 / (png_ptr->gamma);
  80.987 +                  gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  80.988 +                  break;
  80.989 +               case PNG_BACKGROUND_GAMMA_UNIQUE:
  80.990 +                  g = 1.0 / (png_ptr->background_gamma);
  80.991 +                  gs = 1.0 / (png_ptr->background_gamma *
  80.992 +                     png_ptr->screen_gamma);
  80.993 +                  break;
  80.994 +            }
  80.995 +
  80.996 +            png_ptr->background_1.gray = (png_uint_16)(pow(
  80.997 +               (double)png_ptr->background.gray / m, g) * m + .5);
  80.998 +            png_ptr->background.gray = (png_uint_16)(pow(
  80.999 +               (double)png_ptr->background.gray / m, gs) * m + .5);
 80.1000 +
 80.1001 +            if ((png_ptr->background.red != png_ptr->background.green) ||
 80.1002 +                (png_ptr->background.red != png_ptr->background.blue) ||
 80.1003 +                (png_ptr->background.red != png_ptr->background.gray))
 80.1004 +            {
 80.1005 +               /* RGB or RGBA with color background */
 80.1006 +               png_ptr->background_1.red = (png_uint_16)(pow(
 80.1007 +                  (double)png_ptr->background.red / m, g) * m + .5);
 80.1008 +               png_ptr->background_1.green = (png_uint_16)(pow(
 80.1009 +                  (double)png_ptr->background.green / m, g) * m + .5);
 80.1010 +               png_ptr->background_1.blue = (png_uint_16)(pow(
 80.1011 +                  (double)png_ptr->background.blue / m, g) * m + .5);
 80.1012 +               png_ptr->background.red = (png_uint_16)(pow(
 80.1013 +                  (double)png_ptr->background.red / m, gs) * m + .5);
 80.1014 +               png_ptr->background.green = (png_uint_16)(pow(
 80.1015 +                  (double)png_ptr->background.green / m, gs) * m + .5);
 80.1016 +               png_ptr->background.blue = (png_uint_16)(pow(
 80.1017 +                  (double)png_ptr->background.blue / m, gs) * m + .5);
 80.1018 +            }
 80.1019 +            else
 80.1020 +            {
 80.1021 +               /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
 80.1022 +               png_ptr->background_1.red = png_ptr->background_1.green
 80.1023 +                 = png_ptr->background_1.blue = png_ptr->background_1.gray;
 80.1024 +               png_ptr->background.red = png_ptr->background.green
 80.1025 +                 = png_ptr->background.blue = png_ptr->background.gray;
 80.1026 +            }
 80.1027 +         }
 80.1028 +      }
 80.1029 +      else
 80.1030 +      /* transformation does not include PNG_BACKGROUND */
 80.1031 +#endif /* PNG_READ_BACKGROUND_SUPPORTED */
 80.1032 +      if (color_type == PNG_COLOR_TYPE_PALETTE)
 80.1033 +      {
 80.1034 +         png_colorp palette = png_ptr->palette;
 80.1035 +         int num_palette = png_ptr->num_palette;
 80.1036 +         int i;
 80.1037 +
 80.1038 +         for (i = 0; i < num_palette; i++)
 80.1039 +         {
 80.1040 +            palette[i].red = png_ptr->gamma_table[palette[i].red];
 80.1041 +            palette[i].green = png_ptr->gamma_table[palette[i].green];
 80.1042 +            palette[i].blue = png_ptr->gamma_table[palette[i].blue];
 80.1043 +         }
 80.1044 +
 80.1045 +	 /* Done the gamma correction. */
 80.1046 +	 png_ptr->transformations &= ~PNG_GAMMA;
 80.1047 +      }
 80.1048 +   }
 80.1049 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.1050 +   else
 80.1051 +#endif
 80.1052 +#endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
 80.1053 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.1054 +   /* No GAMMA transformation */
 80.1055 +   if ((png_ptr->transformations & PNG_BACKGROUND) &&
 80.1056 +       (color_type == PNG_COLOR_TYPE_PALETTE))
 80.1057 +   {
 80.1058 +      int i;
 80.1059 +      int istop = (int)png_ptr->num_trans;
 80.1060 +      png_color back;
 80.1061 +      png_colorp palette = png_ptr->palette;
 80.1062 +
 80.1063 +      back.red   = (png_byte)png_ptr->background.red;
 80.1064 +      back.green = (png_byte)png_ptr->background.green;
 80.1065 +      back.blue  = (png_byte)png_ptr->background.blue;
 80.1066 +
 80.1067 +      for (i = 0; i < istop; i++)
 80.1068 +      {
 80.1069 +         if (png_ptr->trans[i] == 0)
 80.1070 +         {
 80.1071 +            palette[i] = back;
 80.1072 +         }
 80.1073 +         else if (png_ptr->trans[i] != 0xff)
 80.1074 +         {
 80.1075 +            /* The png_composite() macro is defined in png.h */
 80.1076 +            png_composite(palette[i].red, palette[i].red,
 80.1077 +               png_ptr->trans[i], back.red);
 80.1078 +            png_composite(palette[i].green, palette[i].green,
 80.1079 +               png_ptr->trans[i], back.green);
 80.1080 +            png_composite(palette[i].blue, palette[i].blue,
 80.1081 +               png_ptr->trans[i], back.blue);
 80.1082 +         }
 80.1083 +      }
 80.1084 +
 80.1085 +      /* Handled alpha, still need to strip the channel. */
 80.1086 +      png_ptr->transformations &= ~PNG_BACKGROUND;
 80.1087 +      png_ptr->transformations |= PNG_STRIP_ALPHA;
 80.1088 +   }
 80.1089 +#endif /* PNG_READ_BACKGROUND_SUPPORTED */
 80.1090 +
 80.1091 +#if defined(PNG_READ_SHIFT_SUPPORTED)
 80.1092 +   if ((png_ptr->transformations & PNG_SHIFT) &&
 80.1093 +      (color_type == PNG_COLOR_TYPE_PALETTE))
 80.1094 +   {
 80.1095 +      png_uint_16 i;
 80.1096 +      png_uint_16 istop = png_ptr->num_palette;
 80.1097 +      int sr = 8 - png_ptr->sig_bit.red;
 80.1098 +      int sg = 8 - png_ptr->sig_bit.green;
 80.1099 +      int sb = 8 - png_ptr->sig_bit.blue;
 80.1100 +
 80.1101 +      if (sr < 0 || sr > 8)
 80.1102 +         sr = 0;
 80.1103 +      if (sg < 0 || sg > 8)
 80.1104 +         sg = 0;
 80.1105 +      if (sb < 0 || sb > 8)
 80.1106 +         sb = 0;
 80.1107 +      for (i = 0; i < istop; i++)
 80.1108 +      {
 80.1109 +         png_ptr->palette[i].red >>= sr;
 80.1110 +         png_ptr->palette[i].green >>= sg;
 80.1111 +         png_ptr->palette[i].blue >>= sb;
 80.1112 +      }
 80.1113 +   }
 80.1114 +#endif  /* PNG_READ_SHIFT_SUPPORTED */
 80.1115 + }
 80.1116 +#if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
 80.1117 + && !defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.1118 +   if (png_ptr)
 80.1119 +      return;
 80.1120 +#endif
 80.1121 +}
 80.1122 +
 80.1123 +/* Modify the info structure to reflect the transformations.  The
 80.1124 + * info should be updated so a PNG file could be written with it,
 80.1125 + * assuming the transformations result in valid PNG data.
 80.1126 + */
 80.1127 +void /* PRIVATE */
 80.1128 +png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
 80.1129 +{
 80.1130 +   png_debug(1, "in png_read_transform_info\n");
 80.1131 +#if defined(PNG_READ_EXPAND_SUPPORTED)
 80.1132 +   if (png_ptr->transformations & PNG_EXPAND)
 80.1133 +   {
 80.1134 +      if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 80.1135 +      {
 80.1136 +         if (png_ptr->num_trans &&
 80.1137 +              (png_ptr->transformations & PNG_EXPAND_tRNS))
 80.1138 +            info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
 80.1139 +         else
 80.1140 +            info_ptr->color_type = PNG_COLOR_TYPE_RGB;
 80.1141 +         info_ptr->bit_depth = 8;
 80.1142 +         info_ptr->num_trans = 0;
 80.1143 +      }
 80.1144 +      else
 80.1145 +      {
 80.1146 +         if (png_ptr->num_trans)
 80.1147 +         {
 80.1148 +            if (png_ptr->transformations & PNG_EXPAND_tRNS)
 80.1149 +              info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
 80.1150 +#if 0 /* Removed from libpng-1.2.27 */
 80.1151 +            else
 80.1152 +              info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
 80.1153 +#endif
 80.1154 +         }
 80.1155 +         if (info_ptr->bit_depth < 8)
 80.1156 +            info_ptr->bit_depth = 8;
 80.1157 +         info_ptr->num_trans = 0;
 80.1158 +      }
 80.1159 +   }
 80.1160 +#endif
 80.1161 +
 80.1162 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.1163 +   if (png_ptr->transformations & PNG_BACKGROUND)
 80.1164 +   {
 80.1165 +      info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
 80.1166 +      info_ptr->num_trans = 0;
 80.1167 +      info_ptr->background = png_ptr->background;
 80.1168 +   }
 80.1169 +#endif
 80.1170 +
 80.1171 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.1172 +   if (png_ptr->transformations & PNG_GAMMA)
 80.1173 +   {
 80.1174 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 80.1175 +      info_ptr->gamma = png_ptr->gamma;
 80.1176 +#endif
 80.1177 +#ifdef PNG_FIXED_POINT_SUPPORTED
 80.1178 +      info_ptr->int_gamma = png_ptr->int_gamma;
 80.1179 +#endif
 80.1180 +   }
 80.1181 +#endif
 80.1182 +
 80.1183 +#if defined(PNG_READ_16_TO_8_SUPPORTED)
 80.1184 +   if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
 80.1185 +      info_ptr->bit_depth = 8;
 80.1186 +#endif
 80.1187 +
 80.1188 +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
 80.1189 +   if (png_ptr->transformations & PNG_GRAY_TO_RGB)
 80.1190 +      info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
 80.1191 +#endif
 80.1192 +
 80.1193 +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
 80.1194 +   if (png_ptr->transformations & PNG_RGB_TO_GRAY)
 80.1195 +      info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
 80.1196 +#endif
 80.1197 +
 80.1198 +#if defined(PNG_READ_DITHER_SUPPORTED)
 80.1199 +   if (png_ptr->transformations & PNG_DITHER)
 80.1200 +   {
 80.1201 +      if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
 80.1202 +         (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
 80.1203 +         png_ptr->palette_lookup && info_ptr->bit_depth == 8)
 80.1204 +      {
 80.1205 +         info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
 80.1206 +      }
 80.1207 +   }
 80.1208 +#endif
 80.1209 +
 80.1210 +#if defined(PNG_READ_PACK_SUPPORTED)
 80.1211 +   if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
 80.1212 +      info_ptr->bit_depth = 8;
 80.1213 +#endif
 80.1214 +
 80.1215 +   if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 80.1216 +      info_ptr->channels = 1;
 80.1217 +   else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
 80.1218 +      info_ptr->channels = 3;
 80.1219 +   else
 80.1220 +      info_ptr->channels = 1;
 80.1221 +
 80.1222 +#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
 80.1223 +   if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
 80.1224 +      info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
 80.1225 +#endif
 80.1226 +
 80.1227 +   if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
 80.1228 +      info_ptr->channels++;
 80.1229 +
 80.1230 +#if defined(PNG_READ_FILLER_SUPPORTED)
 80.1231 +   /* STRIP_ALPHA and FILLER allowed:  MASK_ALPHA bit stripped above */
 80.1232 +   if ((png_ptr->transformations & PNG_FILLER) &&
 80.1233 +       ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
 80.1234 +       (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
 80.1235 +   {
 80.1236 +      info_ptr->channels++;
 80.1237 +      /* if adding a true alpha channel not just filler */
 80.1238 +#if !defined(PNG_1_0_X)
 80.1239 +      if (png_ptr->transformations & PNG_ADD_ALPHA)
 80.1240 +        info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
 80.1241 +#endif
 80.1242 +   }
 80.1243 +#endif
 80.1244 +
 80.1245 +#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
 80.1246 +defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
 80.1247 +   if (png_ptr->transformations & PNG_USER_TRANSFORM)
 80.1248 +     {
 80.1249 +       if (info_ptr->bit_depth < png_ptr->user_transform_depth)
 80.1250 +         info_ptr->bit_depth = png_ptr->user_transform_depth;
 80.1251 +       if (info_ptr->channels < png_ptr->user_transform_channels)
 80.1252 +         info_ptr->channels = png_ptr->user_transform_channels;
 80.1253 +     }
 80.1254 +#endif
 80.1255 +
 80.1256 +   info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
 80.1257 +      info_ptr->bit_depth);
 80.1258 +
 80.1259 +   info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, info_ptr->width);
 80.1260 +
 80.1261 +#if !defined(PNG_READ_EXPAND_SUPPORTED)
 80.1262 +   if (png_ptr)
 80.1263 +      return;
 80.1264 +#endif
 80.1265 +}
 80.1266 +
 80.1267 +/* Transform the row.  The order of transformations is significant,
 80.1268 + * and is very touchy.  If you add a transformation, take care to
 80.1269 + * decide how it fits in with the other transformations here.
 80.1270 + */
 80.1271 +void /* PRIVATE */
 80.1272 +png_do_read_transformations(png_structp png_ptr)
 80.1273 +{
 80.1274 +   png_debug(1, "in png_do_read_transformations\n");
 80.1275 +   if (png_ptr->row_buf == NULL)
 80.1276 +   {
 80.1277 +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
 80.1278 +      char msg[50];
 80.1279 +
 80.1280 +      png_snprintf2(msg, 50,
 80.1281 +         "NULL row buffer for row %ld, pass %d", (long)png_ptr->row_number,
 80.1282 +         png_ptr->pass);
 80.1283 +      png_error(png_ptr, msg);
 80.1284 +#else
 80.1285 +      png_error(png_ptr, "NULL row buffer");
 80.1286 +#endif
 80.1287 +   }
 80.1288 +#ifdef PNG_WARN_UNINITIALIZED_ROW
 80.1289 +   if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
 80.1290 +      /* Application has failed to call either png_read_start_image()
 80.1291 +       * or png_read_update_info() after setting transforms that expand
 80.1292 +       * pixels.  This check added to libpng-1.2.19 */
 80.1293 +#if (PNG_WARN_UNINITIALIZED_ROW==1)
 80.1294 +      png_error(png_ptr, "Uninitialized row");
 80.1295 +#else
 80.1296 +      png_warning(png_ptr, "Uninitialized row");
 80.1297 +#endif
 80.1298 +#endif
 80.1299 +
 80.1300 +#if defined(PNG_READ_EXPAND_SUPPORTED)
 80.1301 +   if (png_ptr->transformations & PNG_EXPAND)
 80.1302 +   {
 80.1303 +      if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
 80.1304 +      {
 80.1305 +         png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
 80.1306 +            png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
 80.1307 +      }
 80.1308 +      else
 80.1309 +      {
 80.1310 +         if (png_ptr->num_trans &&
 80.1311 +             (png_ptr->transformations & PNG_EXPAND_tRNS))
 80.1312 +            png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
 80.1313 +               &(png_ptr->trans_values));
 80.1314 +         else
 80.1315 +            png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
 80.1316 +               NULL);
 80.1317 +      }
 80.1318 +   }
 80.1319 +#endif
 80.1320 +
 80.1321 +#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
 80.1322 +   if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
 80.1323 +      png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
 80.1324 +         PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
 80.1325 +#endif
 80.1326 +
 80.1327 +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
 80.1328 +   if (png_ptr->transformations & PNG_RGB_TO_GRAY)
 80.1329 +   {
 80.1330 +      int rgb_error =
 80.1331 +         png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1332 +      if (rgb_error)
 80.1333 +      {
 80.1334 +         png_ptr->rgb_to_gray_status=1;
 80.1335 +         if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 
 80.1336 +             PNG_RGB_TO_GRAY_WARN)
 80.1337 +            png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
 80.1338 +         if ((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
 80.1339 +             PNG_RGB_TO_GRAY_ERR)
 80.1340 +            png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
 80.1341 +      }
 80.1342 +   }
 80.1343 +#endif
 80.1344 +
 80.1345 +/*
 80.1346 +From Andreas Dilger e-mail to png-implement, 26 March 1998:
 80.1347 +
 80.1348 +  In most cases, the "simple transparency" should be done prior to doing
 80.1349 +  gray-to-RGB, or you will have to test 3x as many bytes to check if a
 80.1350 +  pixel is transparent.  You would also need to make sure that the
 80.1351 +  transparency information is upgraded to RGB.
 80.1352 +
 80.1353 +  To summarize, the current flow is:
 80.1354 +  - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
 80.1355 +                                  with background "in place" if transparent,
 80.1356 +                                  convert to RGB if necessary
 80.1357 +  - Gray + alpha -> composite with gray background and remove alpha bytes,
 80.1358 +                                  convert to RGB if necessary
 80.1359 +
 80.1360 +  To support RGB backgrounds for gray images we need:
 80.1361 +  - Gray + simple transparency -> convert to RGB + simple transparency, compare
 80.1362 +                                  3 or 6 bytes and composite with background
 80.1363 +                                  "in place" if transparent (3x compare/pixel
 80.1364 +                                  compared to doing composite with gray bkgrnd)
 80.1365 +  - Gray + alpha -> convert to RGB + alpha, composite with background and
 80.1366 +                                  remove alpha bytes (3x float operations/pixel
 80.1367 +                                  compared with composite on gray background)
 80.1368 +
 80.1369 +  Greg's change will do this.  The reason it wasn't done before is for
 80.1370 +  performance, as this increases the per-pixel operations.  If we would check
 80.1371 +  in advance if the background was gray or RGB, and position the gray-to-RGB
 80.1372 +  transform appropriately, then it would save a lot of work/time.
 80.1373 + */
 80.1374 +
 80.1375 +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
 80.1376 +   /* if gray -> RGB, do so now only if background is non-gray; else do later
 80.1377 +    * for performance reasons */
 80.1378 +   if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
 80.1379 +       !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
 80.1380 +      png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1381 +#endif
 80.1382 +
 80.1383 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.1384 +   if ((png_ptr->transformations & PNG_BACKGROUND) &&
 80.1385 +      ((png_ptr->num_trans != 0 ) ||
 80.1386 +      (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
 80.1387 +      png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
 80.1388 +         &(png_ptr->trans_values), &(png_ptr->background)
 80.1389 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.1390 +         , &(png_ptr->background_1),
 80.1391 +         png_ptr->gamma_table, png_ptr->gamma_from_1,
 80.1392 +         png_ptr->gamma_to_1, png_ptr->gamma_16_table,
 80.1393 +         png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
 80.1394 +         png_ptr->gamma_shift
 80.1395 +#endif
 80.1396 +);
 80.1397 +#endif
 80.1398 +
 80.1399 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.1400 +   if ((png_ptr->transformations & PNG_GAMMA) &&
 80.1401 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.1402 +      !((png_ptr->transformations & PNG_BACKGROUND) &&
 80.1403 +      ((png_ptr->num_trans != 0) ||
 80.1404 +      (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
 80.1405 +#endif
 80.1406 +      (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
 80.1407 +      png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
 80.1408 +         png_ptr->gamma_table, png_ptr->gamma_16_table,
 80.1409 +         png_ptr->gamma_shift);
 80.1410 +#endif
 80.1411 +
 80.1412 +#if defined(PNG_READ_16_TO_8_SUPPORTED)
 80.1413 +   if (png_ptr->transformations & PNG_16_TO_8)
 80.1414 +      png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1415 +#endif
 80.1416 +
 80.1417 +#if defined(PNG_READ_DITHER_SUPPORTED)
 80.1418 +   if (png_ptr->transformations & PNG_DITHER)
 80.1419 +   {
 80.1420 +      png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
 80.1421 +         png_ptr->palette_lookup, png_ptr->dither_index);
 80.1422 +      if (png_ptr->row_info.rowbytes == (png_uint_32)0)
 80.1423 +         png_error(png_ptr, "png_do_dither returned rowbytes=0");
 80.1424 +   }
 80.1425 +#endif
 80.1426 +
 80.1427 +#if defined(PNG_READ_INVERT_SUPPORTED)
 80.1428 +   if (png_ptr->transformations & PNG_INVERT_MONO)
 80.1429 +      png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1430 +#endif
 80.1431 +
 80.1432 +#if defined(PNG_READ_SHIFT_SUPPORTED)
 80.1433 +   if (png_ptr->transformations & PNG_SHIFT)
 80.1434 +      png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
 80.1435 +         &(png_ptr->shift));
 80.1436 +#endif
 80.1437 +
 80.1438 +#if defined(PNG_READ_PACK_SUPPORTED)
 80.1439 +   if (png_ptr->transformations & PNG_PACK)
 80.1440 +      png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1441 +#endif
 80.1442 +
 80.1443 +#if defined(PNG_READ_BGR_SUPPORTED)
 80.1444 +   if (png_ptr->transformations & PNG_BGR)
 80.1445 +      png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1446 +#endif
 80.1447 +
 80.1448 +#if defined(PNG_READ_PACKSWAP_SUPPORTED)
 80.1449 +   if (png_ptr->transformations & PNG_PACKSWAP)
 80.1450 +      png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1451 +#endif
 80.1452 +
 80.1453 +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
 80.1454 +   /* if gray -> RGB, do so now only if we did not do so above */
 80.1455 +   if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
 80.1456 +       (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
 80.1457 +      png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1458 +#endif
 80.1459 +
 80.1460 +#if defined(PNG_READ_FILLER_SUPPORTED)
 80.1461 +   if (png_ptr->transformations & PNG_FILLER)
 80.1462 +      png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
 80.1463 +         (png_uint_32)png_ptr->filler, png_ptr->flags);
 80.1464 +#endif
 80.1465 +
 80.1466 +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
 80.1467 +   if (png_ptr->transformations & PNG_INVERT_ALPHA)
 80.1468 +      png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1469 +#endif
 80.1470 +
 80.1471 +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
 80.1472 +   if (png_ptr->transformations & PNG_SWAP_ALPHA)
 80.1473 +      png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1474 +#endif
 80.1475 +
 80.1476 +#if defined(PNG_READ_SWAP_SUPPORTED)
 80.1477 +   if (png_ptr->transformations & PNG_SWAP_BYTES)
 80.1478 +      png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
 80.1479 +#endif
 80.1480 +
 80.1481 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
 80.1482 +   if (png_ptr->transformations & PNG_USER_TRANSFORM)
 80.1483 +    {
 80.1484 +      if (png_ptr->read_user_transform_fn != NULL)
 80.1485 +        (*(png_ptr->read_user_transform_fn)) /* user read transform function */
 80.1486 +          (png_ptr,                    /* png_ptr */
 80.1487 +           &(png_ptr->row_info),       /* row_info:     */
 80.1488 +             /*  png_uint_32 width;          width of row */
 80.1489 +             /*  png_uint_32 rowbytes;       number of bytes in row */
 80.1490 +             /*  png_byte color_type;        color type of pixels */
 80.1491 +             /*  png_byte bit_depth;         bit depth of samples */
 80.1492 +             /*  png_byte channels;          number of channels (1-4) */
 80.1493 +             /*  png_byte pixel_depth;       bits per pixel (depth*channels) */
 80.1494 +           png_ptr->row_buf + 1);      /* start of pixel data for row */
 80.1495 +#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
 80.1496 +      if (png_ptr->user_transform_depth)
 80.1497 +         png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
 80.1498 +      if (png_ptr->user_transform_channels)
 80.1499 +         png_ptr->row_info.channels = png_ptr->user_transform_channels;
 80.1500 +#endif
 80.1501 +      png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
 80.1502 +         png_ptr->row_info.channels);
 80.1503 +      png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
 80.1504 +         png_ptr->row_info.width);
 80.1505 +   }
 80.1506 +#endif
 80.1507 +
 80.1508 +}
 80.1509 +
 80.1510 +#if defined(PNG_READ_PACK_SUPPORTED)
 80.1511 +/* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
 80.1512 + * without changing the actual values.  Thus, if you had a row with
 80.1513 + * a bit depth of 1, you would end up with bytes that only contained
 80.1514 + * the numbers 0 or 1.  If you would rather they contain 0 and 255, use
 80.1515 + * png_do_shift() after this.
 80.1516 + */
 80.1517 +void /* PRIVATE */
 80.1518 +png_do_unpack(png_row_infop row_info, png_bytep row)
 80.1519 +{
 80.1520 +   png_debug(1, "in png_do_unpack\n");
 80.1521 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.1522 +   if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
 80.1523 +#else
 80.1524 +   if (row_info->bit_depth < 8)
 80.1525 +#endif
 80.1526 +   {
 80.1527 +      png_uint_32 i;
 80.1528 +      png_uint_32 row_width=row_info->width;
 80.1529 +
 80.1530 +      switch (row_info->bit_depth)
 80.1531 +      {
 80.1532 +         case 1:
 80.1533 +         {
 80.1534 +            png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
 80.1535 +            png_bytep dp = row + (png_size_t)row_width - 1;
 80.1536 +            png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
 80.1537 +            for (i = 0; i < row_width; i++)
 80.1538 +            {
 80.1539 +               *dp = (png_byte)((*sp >> shift) & 0x01);
 80.1540 +               if (shift == 7)
 80.1541 +               {
 80.1542 +                  shift = 0;
 80.1543 +                  sp--;
 80.1544 +               }
 80.1545 +               else
 80.1546 +                  shift++;
 80.1547 +
 80.1548 +               dp--;
 80.1549 +            }
 80.1550 +            break;
 80.1551 +         }
 80.1552 +         case 2:
 80.1553 +         {
 80.1554 +
 80.1555 +            png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
 80.1556 +            png_bytep dp = row + (png_size_t)row_width - 1;
 80.1557 +            png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
 80.1558 +            for (i = 0; i < row_width; i++)
 80.1559 +            {
 80.1560 +               *dp = (png_byte)((*sp >> shift) & 0x03);
 80.1561 +               if (shift == 6)
 80.1562 +               {
 80.1563 +                  shift = 0;
 80.1564 +                  sp--;
 80.1565 +               }
 80.1566 +               else
 80.1567 +                  shift += 2;
 80.1568 +
 80.1569 +               dp--;
 80.1570 +            }
 80.1571 +            break;
 80.1572 +         }
 80.1573 +         case 4:
 80.1574 +         {
 80.1575 +            png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
 80.1576 +            png_bytep dp = row + (png_size_t)row_width - 1;
 80.1577 +            png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
 80.1578 +            for (i = 0; i < row_width; i++)
 80.1579 +            {
 80.1580 +               *dp = (png_byte)((*sp >> shift) & 0x0f);
 80.1581 +               if (shift == 4)
 80.1582 +               {
 80.1583 +                  shift = 0;
 80.1584 +                  sp--;
 80.1585 +               }
 80.1586 +               else
 80.1587 +                  shift = 4;
 80.1588 +
 80.1589 +               dp--;
 80.1590 +            }
 80.1591 +            break;
 80.1592 +         }
 80.1593 +      }
 80.1594 +      row_info->bit_depth = 8;
 80.1595 +      row_info->pixel_depth = (png_byte)(8 * row_info->channels);
 80.1596 +      row_info->rowbytes = row_width * row_info->channels;
 80.1597 +   }
 80.1598 +}
 80.1599 +#endif
 80.1600 +
 80.1601 +#if defined(PNG_READ_SHIFT_SUPPORTED)
 80.1602 +/* Reverse the effects of png_do_shift.  This routine merely shifts the
 80.1603 + * pixels back to their significant bits values.  Thus, if you have
 80.1604 + * a row of bit depth 8, but only 5 are significant, this will shift
 80.1605 + * the values back to 0 through 31.
 80.1606 + */
 80.1607 +void /* PRIVATE */
 80.1608 +png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
 80.1609 +{
 80.1610 +   png_debug(1, "in png_do_unshift\n");
 80.1611 +   if (
 80.1612 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.1613 +       row != NULL && row_info != NULL && sig_bits != NULL &&
 80.1614 +#endif
 80.1615 +       row_info->color_type != PNG_COLOR_TYPE_PALETTE)
 80.1616 +   {
 80.1617 +      int shift[4];
 80.1618 +      int channels = 0;
 80.1619 +      int c;
 80.1620 +      png_uint_16 value = 0;
 80.1621 +      png_uint_32 row_width = row_info->width;
 80.1622 +
 80.1623 +      if (row_info->color_type & PNG_COLOR_MASK_COLOR)
 80.1624 +      {
 80.1625 +         shift[channels++] = row_info->bit_depth - sig_bits->red;
 80.1626 +         shift[channels++] = row_info->bit_depth - sig_bits->green;
 80.1627 +         shift[channels++] = row_info->bit_depth - sig_bits->blue;
 80.1628 +      }
 80.1629 +      else
 80.1630 +      {
 80.1631 +         shift[channels++] = row_info->bit_depth - sig_bits->gray;
 80.1632 +      }
 80.1633 +      if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
 80.1634 +      {
 80.1635 +         shift[channels++] = row_info->bit_depth - sig_bits->alpha;
 80.1636 +      }
 80.1637 +
 80.1638 +      for (c = 0; c < channels; c++)
 80.1639 +      {
 80.1640 +         if (shift[c] <= 0)
 80.1641 +            shift[c] = 0;
 80.1642 +         else
 80.1643 +            value = 1;
 80.1644 +      }
 80.1645 +
 80.1646 +      if (!value)
 80.1647 +         return;
 80.1648 +
 80.1649 +      switch (row_info->bit_depth)
 80.1650 +      {
 80.1651 +         case 2:
 80.1652 +         {
 80.1653 +            png_bytep bp;
 80.1654 +            png_uint_32 i;
 80.1655 +            png_uint_32 istop = row_info->rowbytes;
 80.1656 +
 80.1657 +            for (bp = row, i = 0; i < istop; i++)
 80.1658 +            {
 80.1659 +               *bp >>= 1;
 80.1660 +               *bp++ &= 0x55;
 80.1661 +            }
 80.1662 +            break;
 80.1663 +         }
 80.1664 +         case 4:
 80.1665 +         {
 80.1666 +            png_bytep bp = row;
 80.1667 +            png_uint_32 i;
 80.1668 +            png_uint_32 istop = row_info->rowbytes;
 80.1669 +            png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
 80.1670 +               (png_byte)((int)0xf >> shift[0]));
 80.1671 +
 80.1672 +            for (i = 0; i < istop; i++)
 80.1673 +            {
 80.1674 +               *bp >>= shift[0];
 80.1675 +               *bp++ &= mask;
 80.1676 +            }
 80.1677 +            break;
 80.1678 +         }
 80.1679 +         case 8:
 80.1680 +         {
 80.1681 +            png_bytep bp = row;
 80.1682 +            png_uint_32 i;
 80.1683 +            png_uint_32 istop = row_width * channels;
 80.1684 +
 80.1685 +            for (i = 0; i < istop; i++)
 80.1686 +            {
 80.1687 +               *bp++ >>= shift[i%channels];
 80.1688 +            }
 80.1689 +            break;
 80.1690 +         }
 80.1691 +         case 16:
 80.1692 +         {
 80.1693 +            png_bytep bp = row;
 80.1694 +            png_uint_32 i;
 80.1695 +            png_uint_32 istop = channels * row_width;
 80.1696 +
 80.1697 +            for (i = 0; i < istop; i++)
 80.1698 +            {
 80.1699 +               value = (png_uint_16)((*bp << 8) + *(bp + 1));
 80.1700 +               value >>= shift[i%channels];
 80.1701 +               *bp++ = (png_byte)(value >> 8);
 80.1702 +               *bp++ = (png_byte)(value & 0xff);
 80.1703 +            }
 80.1704 +            break;
 80.1705 +         }
 80.1706 +      }
 80.1707 +   }
 80.1708 +}
 80.1709 +#endif
 80.1710 +
 80.1711 +#if defined(PNG_READ_16_TO_8_SUPPORTED)
 80.1712 +/* chop rows of bit depth 16 down to 8 */
 80.1713 +void /* PRIVATE */
 80.1714 +png_do_chop(png_row_infop row_info, png_bytep row)
 80.1715 +{
 80.1716 +   png_debug(1, "in png_do_chop\n");
 80.1717 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.1718 +   if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
 80.1719 +#else
 80.1720 +   if (row_info->bit_depth == 16)
 80.1721 +#endif
 80.1722 +   {
 80.1723 +      png_bytep sp = row;
 80.1724 +      png_bytep dp = row;
 80.1725 +      png_uint_32 i;
 80.1726 +      png_uint_32 istop = row_info->width * row_info->channels;
 80.1727 +
 80.1728 +      for (i = 0; i<istop; i++, sp += 2, dp++)
 80.1729 +      {
 80.1730 +#if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
 80.1731 +      /* This does a more accurate scaling of the 16-bit color
 80.1732 +       * value, rather than a simple low-byte truncation.
 80.1733 +       *
 80.1734 +       * What the ideal calculation should be:
 80.1735 +       *   *dp = (((((png_uint_32)(*sp) << 8) |
 80.1736 +       *          (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
 80.1737 +       *
 80.1738 +       * GRR: no, I think this is what it really should be:
 80.1739 +       *   *dp = (((((png_uint_32)(*sp) << 8) |
 80.1740 +       *           (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
 80.1741 +       *
 80.1742 +       * GRR: here's the exact calculation with shifts:
 80.1743 +       *   temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
 80.1744 +       *   *dp = (temp - (temp >> 8)) >> 8;
 80.1745 +       *
 80.1746 +       * Approximate calculation with shift/add instead of multiply/divide:
 80.1747 +       *   *dp = ((((png_uint_32)(*sp) << 8) |
 80.1748 +       *          (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
 80.1749 +       *
 80.1750 +       * What we actually do to avoid extra shifting and conversion:
 80.1751 +       */
 80.1752 +
 80.1753 +         *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
 80.1754 +#else
 80.1755 +       /* Simply discard the low order byte */
 80.1756 +         *dp = *sp;
 80.1757 +#endif
 80.1758 +      }
 80.1759 +      row_info->bit_depth = 8;
 80.1760 +      row_info->pixel_depth = (png_byte)(8 * row_info->channels);
 80.1761 +      row_info->rowbytes = row_info->width * row_info->channels;
 80.1762 +   }
 80.1763 +}
 80.1764 +#endif
 80.1765 +
 80.1766 +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
 80.1767 +void /* PRIVATE */
 80.1768 +png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
 80.1769 +{
 80.1770 +   png_debug(1, "in png_do_read_swap_alpha\n");
 80.1771 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.1772 +   if (row != NULL && row_info != NULL)
 80.1773 +#endif
 80.1774 +   {
 80.1775 +      png_uint_32 row_width = row_info->width;
 80.1776 +      if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
 80.1777 +      {
 80.1778 +         /* This converts from RGBA to ARGB */
 80.1779 +         if (row_info->bit_depth == 8)
 80.1780 +         {
 80.1781 +            png_bytep sp = row + row_info->rowbytes;
 80.1782 +            png_bytep dp = sp;
 80.1783 +            png_byte save;
 80.1784 +            png_uint_32 i;
 80.1785 +
 80.1786 +            for (i = 0; i < row_width; i++)
 80.1787 +            {
 80.1788 +               save = *(--sp);
 80.1789 +               *(--dp) = *(--sp);
 80.1790 +               *(--dp) = *(--sp);
 80.1791 +               *(--dp) = *(--sp);
 80.1792 +               *(--dp) = save;
 80.1793 +            }
 80.1794 +         }
 80.1795 +         /* This converts from RRGGBBAA to AARRGGBB */
 80.1796 +         else
 80.1797 +         {
 80.1798 +            png_bytep sp = row + row_info->rowbytes;
 80.1799 +            png_bytep dp = sp;
 80.1800 +            png_byte save[2];
 80.1801 +            png_uint_32 i;
 80.1802 +
 80.1803 +            for (i = 0; i < row_width; i++)
 80.1804 +            {
 80.1805 +               save[0] = *(--sp);
 80.1806 +               save[1] = *(--sp);
 80.1807 +               *(--dp) = *(--sp);
 80.1808 +               *(--dp) = *(--sp);
 80.1809 +               *(--dp) = *(--sp);
 80.1810 +               *(--dp) = *(--sp);
 80.1811 +               *(--dp) = *(--sp);
 80.1812 +               *(--dp) = *(--sp);
 80.1813 +               *(--dp) = save[0];
 80.1814 +               *(--dp) = save[1];
 80.1815 +            }
 80.1816 +         }
 80.1817 +      }
 80.1818 +      else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
 80.1819 +      {
 80.1820 +         /* This converts from GA to AG */
 80.1821 +         if (row_info->bit_depth == 8)
 80.1822 +         {
 80.1823 +            png_bytep sp = row + row_info->rowbytes;
 80.1824 +            png_bytep dp = sp;
 80.1825 +            png_byte save;
 80.1826 +            png_uint_32 i;
 80.1827 +
 80.1828 +            for (i = 0; i < row_width; i++)
 80.1829 +            {
 80.1830 +               save = *(--sp);
 80.1831 +               *(--dp) = *(--sp);
 80.1832 +               *(--dp) = save;
 80.1833 +            }
 80.1834 +         }
 80.1835 +         /* This converts from GGAA to AAGG */
 80.1836 +         else
 80.1837 +         {
 80.1838 +            png_bytep sp = row + row_info->rowbytes;
 80.1839 +            png_bytep dp = sp;
 80.1840 +            png_byte save[2];
 80.1841 +            png_uint_32 i;
 80.1842 +
 80.1843 +            for (i = 0; i < row_width; i++)
 80.1844 +            {
 80.1845 +               save[0] = *(--sp);
 80.1846 +               save[1] = *(--sp);
 80.1847 +               *(--dp) = *(--sp);
 80.1848 +               *(--dp) = *(--sp);
 80.1849 +               *(--dp) = save[0];
 80.1850 +               *(--dp) = save[1];
 80.1851 +            }
 80.1852 +         }
 80.1853 +      }
 80.1854 +   }
 80.1855 +}
 80.1856 +#endif
 80.1857 +
 80.1858 +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
 80.1859 +void /* PRIVATE */
 80.1860 +png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
 80.1861 +{
 80.1862 +   png_debug(1, "in png_do_read_invert_alpha\n");
 80.1863 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.1864 +   if (row != NULL && row_info != NULL)
 80.1865 +#endif
 80.1866 +   {
 80.1867 +      png_uint_32 row_width = row_info->width;
 80.1868 +      if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
 80.1869 +      {
 80.1870 +         /* This inverts the alpha channel in RGBA */
 80.1871 +         if (row_info->bit_depth == 8)
 80.1872 +         {
 80.1873 +            png_bytep sp = row + row_info->rowbytes;
 80.1874 +            png_bytep dp = sp;
 80.1875 +            png_uint_32 i;
 80.1876 +
 80.1877 +            for (i = 0; i < row_width; i++)
 80.1878 +            {
 80.1879 +               *(--dp) = (png_byte)(255 - *(--sp));
 80.1880 +
 80.1881 +/*             This does nothing:
 80.1882 +               *(--dp) = *(--sp);
 80.1883 +               *(--dp) = *(--sp);
 80.1884 +               *(--dp) = *(--sp);
 80.1885 +               We can replace it with:
 80.1886 +*/
 80.1887 +               sp-=3;
 80.1888 +               dp=sp;
 80.1889 +            }
 80.1890 +         }
 80.1891 +         /* This inverts the alpha channel in RRGGBBAA */
 80.1892 +         else
 80.1893 +         {
 80.1894 +            png_bytep sp = row + row_info->rowbytes;
 80.1895 +            png_bytep dp = sp;
 80.1896 +            png_uint_32 i;
 80.1897 +
 80.1898 +            for (i = 0; i < row_width; i++)
 80.1899 +            {
 80.1900 +               *(--dp) = (png_byte)(255 - *(--sp));
 80.1901 +               *(--dp) = (png_byte)(255 - *(--sp));
 80.1902 +
 80.1903 +/*             This does nothing:
 80.1904 +               *(--dp) = *(--sp);
 80.1905 +               *(--dp) = *(--sp);
 80.1906 +               *(--dp) = *(--sp);
 80.1907 +               *(--dp) = *(--sp);
 80.1908 +               *(--dp) = *(--sp);
 80.1909 +               *(--dp) = *(--sp);
 80.1910 +               We can replace it with:
 80.1911 +*/
 80.1912 +               sp-=6;
 80.1913 +               dp=sp;
 80.1914 +            }
 80.1915 +         }
 80.1916 +      }
 80.1917 +      else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
 80.1918 +      {
 80.1919 +         /* This inverts the alpha channel in GA */
 80.1920 +         if (row_info->bit_depth == 8)
 80.1921 +         {
 80.1922 +            png_bytep sp = row + row_info->rowbytes;
 80.1923 +            png_bytep dp = sp;
 80.1924 +            png_uint_32 i;
 80.1925 +
 80.1926 +            for (i = 0; i < row_width; i++)
 80.1927 +            {
 80.1928 +               *(--dp) = (png_byte)(255 - *(--sp));
 80.1929 +               *(--dp) = *(--sp);
 80.1930 +            }
 80.1931 +         }
 80.1932 +         /* This inverts the alpha channel in GGAA */
 80.1933 +         else
 80.1934 +         {
 80.1935 +            png_bytep sp  = row + row_info->rowbytes;
 80.1936 +            png_bytep dp = sp;
 80.1937 +            png_uint_32 i;
 80.1938 +
 80.1939 +            for (i = 0; i < row_width; i++)
 80.1940 +            {
 80.1941 +               *(--dp) = (png_byte)(255 - *(--sp));
 80.1942 +               *(--dp) = (png_byte)(255 - *(--sp));
 80.1943 +/*
 80.1944 +               *(--dp) = *(--sp);
 80.1945 +               *(--dp) = *(--sp);
 80.1946 +*/
 80.1947 +               sp-=2;
 80.1948 +               dp=sp;
 80.1949 +            }
 80.1950 +         }
 80.1951 +      }
 80.1952 +   }
 80.1953 +}
 80.1954 +#endif
 80.1955 +
 80.1956 +#if defined(PNG_READ_FILLER_SUPPORTED)
 80.1957 +/* Add filler channel if we have RGB color */
 80.1958 +void /* PRIVATE */
 80.1959 +png_do_read_filler(png_row_infop row_info, png_bytep row,
 80.1960 +   png_uint_32 filler, png_uint_32 flags)
 80.1961 +{
 80.1962 +   png_uint_32 i;
 80.1963 +   png_uint_32 row_width = row_info->width;
 80.1964 +
 80.1965 +   png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
 80.1966 +   png_byte lo_filler = (png_byte)(filler & 0xff);
 80.1967 +
 80.1968 +   png_debug(1, "in png_do_read_filler\n");
 80.1969 +   if (
 80.1970 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.1971 +       row != NULL  && row_info != NULL &&
 80.1972 +#endif
 80.1973 +       row_info->color_type == PNG_COLOR_TYPE_GRAY)
 80.1974 +   {
 80.1975 +      if (row_info->bit_depth == 8)
 80.1976 +      {
 80.1977 +         /* This changes the data from G to GX */
 80.1978 +         if (flags & PNG_FLAG_FILLER_AFTER)
 80.1979 +         {
 80.1980 +            png_bytep sp = row + (png_size_t)row_width;
 80.1981 +            png_bytep dp =  sp + (png_size_t)row_width;
 80.1982 +            for (i = 1; i < row_width; i++)
 80.1983 +            {
 80.1984 +               *(--dp) = lo_filler;
 80.1985 +               *(--dp) = *(--sp);
 80.1986 +            }
 80.1987 +            *(--dp) = lo_filler;
 80.1988 +            row_info->channels = 2;
 80.1989 +            row_info->pixel_depth = 16;
 80.1990 +            row_info->rowbytes = row_width * 2;
 80.1991 +         }
 80.1992 +      /* This changes the data from G to XG */
 80.1993 +         else
 80.1994 +         {
 80.1995 +            png_bytep sp = row + (png_size_t)row_width;
 80.1996 +            png_bytep dp = sp  + (png_size_t)row_width;
 80.1997 +            for (i = 0; i < row_width; i++)
 80.1998 +            {
 80.1999 +               *(--dp) = *(--sp);
 80.2000 +               *(--dp) = lo_filler;
 80.2001 +            }
 80.2002 +            row_info->channels = 2;
 80.2003 +            row_info->pixel_depth = 16;
 80.2004 +            row_info->rowbytes = row_width * 2;
 80.2005 +         }
 80.2006 +      }
 80.2007 +      else if (row_info->bit_depth == 16)
 80.2008 +      {
 80.2009 +         /* This changes the data from GG to GGXX */
 80.2010 +         if (flags & PNG_FLAG_FILLER_AFTER)
 80.2011 +         {
 80.2012 +            png_bytep sp = row + (png_size_t)row_width * 2;
 80.2013 +            png_bytep dp = sp  + (png_size_t)row_width * 2;
 80.2014 +            for (i = 1; i < row_width; i++)
 80.2015 +            {
 80.2016 +               *(--dp) = hi_filler;
 80.2017 +               *(--dp) = lo_filler;
 80.2018 +               *(--dp) = *(--sp);
 80.2019 +               *(--dp) = *(--sp);
 80.2020 +            }
 80.2021 +            *(--dp) = hi_filler;
 80.2022 +            *(--dp) = lo_filler;
 80.2023 +            row_info->channels = 2;
 80.2024 +            row_info->pixel_depth = 32;
 80.2025 +            row_info->rowbytes = row_width * 4;
 80.2026 +         }
 80.2027 +         /* This changes the data from GG to XXGG */
 80.2028 +         else
 80.2029 +         {
 80.2030 +            png_bytep sp = row + (png_size_t)row_width * 2;
 80.2031 +            png_bytep dp = sp  + (png_size_t)row_width * 2;
 80.2032 +            for (i = 0; i < row_width; i++)
 80.2033 +            {
 80.2034 +               *(--dp) = *(--sp);
 80.2035 +               *(--dp) = *(--sp);
 80.2036 +               *(--dp) = hi_filler;
 80.2037 +               *(--dp) = lo_filler;
 80.2038 +            }
 80.2039 +            row_info->channels = 2;
 80.2040 +            row_info->pixel_depth = 32;
 80.2041 +            row_info->rowbytes = row_width * 4;
 80.2042 +         }
 80.2043 +      }
 80.2044 +   } /* COLOR_TYPE == GRAY */
 80.2045 +   else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
 80.2046 +   {
 80.2047 +      if (row_info->bit_depth == 8)
 80.2048 +      {
 80.2049 +         /* This changes the data from RGB to RGBX */
 80.2050 +         if (flags & PNG_FLAG_FILLER_AFTER)
 80.2051 +         {
 80.2052 +            png_bytep sp = row + (png_size_t)row_width * 3;
 80.2053 +            png_bytep dp = sp  + (png_size_t)row_width;
 80.2054 +            for (i = 1; i < row_width; i++)
 80.2055 +            {
 80.2056 +               *(--dp) = lo_filler;
 80.2057 +               *(--dp) = *(--sp);
 80.2058 +               *(--dp) = *(--sp);
 80.2059 +               *(--dp) = *(--sp);
 80.2060 +            }
 80.2061 +            *(--dp) = lo_filler;
 80.2062 +            row_info->channels = 4;
 80.2063 +            row_info->pixel_depth = 32;
 80.2064 +            row_info->rowbytes = row_width * 4;
 80.2065 +         }
 80.2066 +      /* This changes the data from RGB to XRGB */
 80.2067 +         else
 80.2068 +         {
 80.2069 +            png_bytep sp = row + (png_size_t)row_width * 3;
 80.2070 +            png_bytep dp = sp + (png_size_t)row_width;
 80.2071 +            for (i = 0; i < row_width; i++)
 80.2072 +            {
 80.2073 +               *(--dp) = *(--sp);
 80.2074 +               *(--dp) = *(--sp);
 80.2075 +               *(--dp) = *(--sp);
 80.2076 +               *(--dp) = lo_filler;
 80.2077 +            }
 80.2078 +            row_info->channels = 4;
 80.2079 +            row_info->pixel_depth = 32;
 80.2080 +            row_info->rowbytes = row_width * 4;
 80.2081 +         }
 80.2082 +      }
 80.2083 +      else if (row_info->bit_depth == 16)
 80.2084 +      {
 80.2085 +         /* This changes the data from RRGGBB to RRGGBBXX */
 80.2086 +         if (flags & PNG_FLAG_FILLER_AFTER)
 80.2087 +         {
 80.2088 +            png_bytep sp = row + (png_size_t)row_width * 6;
 80.2089 +            png_bytep dp = sp  + (png_size_t)row_width * 2;
 80.2090 +            for (i = 1; i < row_width; i++)
 80.2091 +            {
 80.2092 +               *(--dp) = hi_filler;
 80.2093 +               *(--dp) = lo_filler;
 80.2094 +               *(--dp) = *(--sp);
 80.2095 +               *(--dp) = *(--sp);
 80.2096 +               *(--dp) = *(--sp);
 80.2097 +               *(--dp) = *(--sp);
 80.2098 +               *(--dp) = *(--sp);
 80.2099 +               *(--dp) = *(--sp);
 80.2100 +            }
 80.2101 +            *(--dp) = hi_filler;
 80.2102 +            *(--dp) = lo_filler;
 80.2103 +            row_info->channels = 4;
 80.2104 +            row_info->pixel_depth = 64;
 80.2105 +            row_info->rowbytes = row_width * 8;
 80.2106 +         }
 80.2107 +         /* This changes the data from RRGGBB to XXRRGGBB */
 80.2108 +         else
 80.2109 +         {
 80.2110 +            png_bytep sp = row + (png_size_t)row_width * 6;
 80.2111 +            png_bytep dp = sp  + (png_size_t)row_width * 2;
 80.2112 +            for (i = 0; i < row_width; i++)
 80.2113 +            {
 80.2114 +               *(--dp) = *(--sp);
 80.2115 +               *(--dp) = *(--sp);
 80.2116 +               *(--dp) = *(--sp);
 80.2117 +               *(--dp) = *(--sp);
 80.2118 +               *(--dp) = *(--sp);
 80.2119 +               *(--dp) = *(--sp);
 80.2120 +               *(--dp) = hi_filler;
 80.2121 +               *(--dp) = lo_filler;
 80.2122 +            }
 80.2123 +            row_info->channels = 4;
 80.2124 +            row_info->pixel_depth = 64;
 80.2125 +            row_info->rowbytes = row_width * 8;
 80.2126 +         }
 80.2127 +      }
 80.2128 +   } /* COLOR_TYPE == RGB */
 80.2129 +}
 80.2130 +#endif
 80.2131 +
 80.2132 +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
 80.2133 +/* expand grayscale files to RGB, with or without alpha */
 80.2134 +void /* PRIVATE */
 80.2135 +png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
 80.2136 +{
 80.2137 +   png_uint_32 i;
 80.2138 +   png_uint_32 row_width = row_info->width;
 80.2139 +
 80.2140 +   png_debug(1, "in png_do_gray_to_rgb\n");
 80.2141 +   if (row_info->bit_depth >= 8 &&
 80.2142 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.2143 +       row != NULL && row_info != NULL &&
 80.2144 +#endif
 80.2145 +      !(row_info->color_type & PNG_COLOR_MASK_COLOR))
 80.2146 +   {
 80.2147 +      if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
 80.2148 +      {
 80.2149 +         if (row_info->bit_depth == 8)
 80.2150 +         {
 80.2151 +            png_bytep sp = row + (png_size_t)row_width - 1;
 80.2152 +            png_bytep dp = sp  + (png_size_t)row_width * 2;
 80.2153 +            for (i = 0; i < row_width; i++)
 80.2154 +            {
 80.2155 +               *(dp--) = *sp;
 80.2156 +               *(dp--) = *sp;
 80.2157 +               *(dp--) = *(sp--);
 80.2158 +            }
 80.2159 +         }
 80.2160 +         else
 80.2161 +         {
 80.2162 +            png_bytep sp = row + (png_size_t)row_width * 2 - 1;
 80.2163 +            png_bytep dp = sp  + (png_size_t)row_width * 4;
 80.2164 +            for (i = 0; i < row_width; i++)
 80.2165 +            {
 80.2166 +               *(dp--) = *sp;
 80.2167 +               *(dp--) = *(sp - 1);
 80.2168 +               *(dp--) = *sp;
 80.2169 +               *(dp--) = *(sp - 1);
 80.2170 +               *(dp--) = *(sp--);
 80.2171 +               *(dp--) = *(sp--);
 80.2172 +            }
 80.2173 +         }
 80.2174 +      }
 80.2175 +      else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
 80.2176 +      {
 80.2177 +         if (row_info->bit_depth == 8)
 80.2178 +         {
 80.2179 +            png_bytep sp = row + (png_size_t)row_width * 2 - 1;
 80.2180 +            png_bytep dp = sp  + (png_size_t)row_width * 2;
 80.2181 +            for (i = 0; i < row_width; i++)
 80.2182 +            {
 80.2183 +               *(dp--) = *(sp--);
 80.2184 +               *(dp--) = *sp;
 80.2185 +               *(dp--) = *sp;
 80.2186 +               *(dp--) = *(sp--);
 80.2187 +            }
 80.2188 +         }
 80.2189 +         else
 80.2190 +         {
 80.2191 +            png_bytep sp = row + (png_size_t)row_width * 4 - 1;
 80.2192 +            png_bytep dp = sp  + (png_size_t)row_width * 4;
 80.2193 +            for (i = 0; i < row_width; i++)
 80.2194 +            {
 80.2195 +               *(dp--) = *(sp--);
 80.2196 +               *(dp--) = *(sp--);
 80.2197 +               *(dp--) = *sp;
 80.2198 +               *(dp--) = *(sp - 1);
 80.2199 +               *(dp--) = *sp;
 80.2200 +               *(dp--) = *(sp - 1);
 80.2201 +               *(dp--) = *(sp--);
 80.2202 +               *(dp--) = *(sp--);
 80.2203 +            }
 80.2204 +         }
 80.2205 +      }
 80.2206 +      row_info->channels += (png_byte)2;
 80.2207 +      row_info->color_type |= PNG_COLOR_MASK_COLOR;
 80.2208 +      row_info->pixel_depth = (png_byte)(row_info->channels *
 80.2209 +         row_info->bit_depth);
 80.2210 +      row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width);
 80.2211 +   }
 80.2212 +}
 80.2213 +#endif
 80.2214 +
 80.2215 +#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
 80.2216 +/* reduce RGB files to grayscale, with or without alpha
 80.2217 + * using the equation given in Poynton's ColorFAQ at
 80.2218 + * <http://www.inforamp.net/~poynton/>  (THIS LINK IS DEAD June 2008)
 80.2219 + * New link:
 80.2220 + * <http://www.poynton.com/notes/colour_and_gamma/>
 80.2221 + * Charles Poynton poynton at poynton.com
 80.2222 + *
 80.2223 + *     Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
 80.2224 + *
 80.2225 + *  We approximate this with
 80.2226 + *
 80.2227 + *     Y = 0.21268 * R    + 0.7151 * G    + 0.07217 * B
 80.2228 + *
 80.2229 + *  which can be expressed with integers as
 80.2230 + *
 80.2231 + *     Y = (6969 * R + 23434 * G + 2365 * B)/32768
 80.2232 + *
 80.2233 + *  The calculation is to be done in a linear colorspace.
 80.2234 + *
 80.2235 + *  Other integer coefficents can be used via png_set_rgb_to_gray().
 80.2236 + */
 80.2237 +int /* PRIVATE */
 80.2238 +png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
 80.2239 +
 80.2240 +{
 80.2241 +   png_uint_32 i;
 80.2242 +
 80.2243 +   png_uint_32 row_width = row_info->width;
 80.2244 +   int rgb_error = 0;
 80.2245 +
 80.2246 +   png_debug(1, "in png_do_rgb_to_gray\n");
 80.2247 +   if (
 80.2248 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.2249 +       row != NULL && row_info != NULL &&
 80.2250 +#endif
 80.2251 +      (row_info->color_type & PNG_COLOR_MASK_COLOR))
 80.2252 +   {
 80.2253 +      png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
 80.2254 +      png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
 80.2255 +      png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
 80.2256 +
 80.2257 +      if (row_info->color_type == PNG_COLOR_TYPE_RGB)
 80.2258 +      {
 80.2259 +         if (row_info->bit_depth == 8)
 80.2260 +         {
 80.2261 +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.2262 +            if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
 80.2263 +            {
 80.2264 +               png_bytep sp = row;
 80.2265 +               png_bytep dp = row;
 80.2266 +
 80.2267 +               for (i = 0; i < row_width; i++)
 80.2268 +               {
 80.2269 +                  png_byte red   = png_ptr->gamma_to_1[*(sp++)];
 80.2270 +                  png_byte green = png_ptr->gamma_to_1[*(sp++)];
 80.2271 +                  png_byte blue  = png_ptr->gamma_to_1[*(sp++)];
 80.2272 +                  if (red != green || red != blue)
 80.2273 +                  {
 80.2274 +                     rgb_error |= 1;
 80.2275 +                     *(dp++) = png_ptr->gamma_from_1[
 80.2276 +                       (rc*red + gc*green + bc*blue)>>15];
 80.2277 +                  }
 80.2278 +                  else
 80.2279 +                     *(dp++) = *(sp - 1);
 80.2280 +               }
 80.2281 +            }
 80.2282 +            else
 80.2283 +#endif
 80.2284 +            {
 80.2285 +               png_bytep sp = row;
 80.2286 +               png_bytep dp = row;
 80.2287 +               for (i = 0; i < row_width; i++)
 80.2288 +               {
 80.2289 +                  png_byte red   = *(sp++);
 80.2290 +                  png_byte green = *(sp++);
 80.2291 +                  png_byte blue  = *(sp++);
 80.2292 +                  if (red != green || red != blue)
 80.2293 +                  {
 80.2294 +                     rgb_error |= 1;
 80.2295 +                     *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
 80.2296 +                  }
 80.2297 +                  else
 80.2298 +                     *(dp++) = *(sp - 1);
 80.2299 +               }
 80.2300 +            }
 80.2301 +         }
 80.2302 +
 80.2303 +         else /* RGB bit_depth == 16 */
 80.2304 +         {
 80.2305 +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.2306 +            if (png_ptr->gamma_16_to_1 != NULL &&
 80.2307 +                png_ptr->gamma_16_from_1 != NULL)
 80.2308 +            {
 80.2309 +               png_bytep sp = row;
 80.2310 +               png_bytep dp = row;
 80.2311 +               for (i = 0; i < row_width; i++)
 80.2312 +               {
 80.2313 +                  png_uint_16 red, green, blue, w;
 80.2314 +
 80.2315 +                  red   = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
 80.2316 +                  green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
 80.2317 +                  blue  = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
 80.2318 +
 80.2319 +                  if (red == green && red == blue)
 80.2320 +                     w = red;
 80.2321 +                  else
 80.2322 +                  {
 80.2323 +                     png_uint_16 red_1   = png_ptr->gamma_16_to_1[(red&0xff) >>
 80.2324 +                                  png_ptr->gamma_shift][red>>8];
 80.2325 +                     png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
 80.2326 +                                  png_ptr->gamma_shift][green>>8];
 80.2327 +                     png_uint_16 blue_1  = png_ptr->gamma_16_to_1[(blue&0xff) >>
 80.2328 +                                  png_ptr->gamma_shift][blue>>8];
 80.2329 +                     png_uint_16 gray16  = (png_uint_16)((rc*red_1 + gc*green_1
 80.2330 +                                  + bc*blue_1)>>15);
 80.2331 +                     w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
 80.2332 +                         png_ptr->gamma_shift][gray16 >> 8];
 80.2333 +                     rgb_error |= 1;
 80.2334 +                  }
 80.2335 +
 80.2336 +                  *(dp++) = (png_byte)((w>>8) & 0xff);
 80.2337 +                  *(dp++) = (png_byte)(w & 0xff);
 80.2338 +               }
 80.2339 +            }
 80.2340 +            else
 80.2341 +#endif
 80.2342 +            {
 80.2343 +               png_bytep sp = row;
 80.2344 +               png_bytep dp = row;
 80.2345 +               for (i = 0; i < row_width; i++)
 80.2346 +               {
 80.2347 +                  png_uint_16 red, green, blue, gray16;
 80.2348 +
 80.2349 +                  red   = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
 80.2350 +                  green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
 80.2351 +                  blue  = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
 80.2352 +
 80.2353 +                  if (red != green || red != blue)
 80.2354 +                     rgb_error |= 1;
 80.2355 +                  gray16  = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
 80.2356 +                  *(dp++) = (png_byte)((gray16>>8) & 0xff);
 80.2357 +                  *(dp++) = (png_byte)(gray16 & 0xff);
 80.2358 +               }
 80.2359 +            }
 80.2360 +         }
 80.2361 +      }
 80.2362 +      if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
 80.2363 +      {
 80.2364 +         if (row_info->bit_depth == 8)
 80.2365 +         {
 80.2366 +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.2367 +            if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
 80.2368 +            {
 80.2369 +               png_bytep sp = row;
 80.2370 +               png_bytep dp = row;
 80.2371 +               for (i = 0; i < row_width; i++)
 80.2372 +               {
 80.2373 +                  png_byte red   = png_ptr->gamma_to_1[*(sp++)];
 80.2374 +                  png_byte green = png_ptr->gamma_to_1[*(sp++)];
 80.2375 +                  png_byte blue  = png_ptr->gamma_to_1[*(sp++)];
 80.2376 +                  if (red != green || red != blue)
 80.2377 +                     rgb_error |= 1;
 80.2378 +                  *(dp++) =  png_ptr->gamma_from_1
 80.2379 +                             [(rc*red + gc*green + bc*blue)>>15];
 80.2380 +                  *(dp++) = *(sp++);  /* alpha */
 80.2381 +               }
 80.2382 +            }
 80.2383 +            else
 80.2384 +#endif
 80.2385 +            {
 80.2386 +               png_bytep sp = row;
 80.2387 +               png_bytep dp = row;
 80.2388 +               for (i = 0; i < row_width; i++)
 80.2389 +               {
 80.2390 +                  png_byte red   = *(sp++);
 80.2391 +                  png_byte green = *(sp++);
 80.2392 +                  png_byte blue  = *(sp++);
 80.2393 +                  if (red != green || red != blue)
 80.2394 +                     rgb_error |= 1;
 80.2395 +                  *(dp++) =  (png_byte)((rc*red + gc*green + bc*blue)>>15);
 80.2396 +                  *(dp++) = *(sp++);  /* alpha */
 80.2397 +               }
 80.2398 +            }
 80.2399 +         }
 80.2400 +         else /* RGBA bit_depth == 16 */
 80.2401 +         {
 80.2402 +#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.2403 +            if (png_ptr->gamma_16_to_1 != NULL &&
 80.2404 +                png_ptr->gamma_16_from_1 != NULL)
 80.2405 +            {
 80.2406 +               png_bytep sp = row;
 80.2407 +               png_bytep dp = row;
 80.2408 +               for (i = 0; i < row_width; i++)
 80.2409 +               {
 80.2410 +                  png_uint_16 red, green, blue, w;
 80.2411 +
 80.2412 +                  red   = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
 80.2413 +                  green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
 80.2414 +                  blue  = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
 80.2415 +
 80.2416 +                  if (red == green && red == blue)
 80.2417 +                     w = red;
 80.2418 +                  else
 80.2419 +                  {
 80.2420 +                     png_uint_16 red_1   = png_ptr->gamma_16_to_1[(red&0xff) >>
 80.2421 +                                  png_ptr->gamma_shift][red>>8];
 80.2422 +                     png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
 80.2423 +                                  png_ptr->gamma_shift][green>>8];
 80.2424 +                     png_uint_16 blue_1  = png_ptr->gamma_16_to_1[(blue&0xff) >>
 80.2425 +                                  png_ptr->gamma_shift][blue>>8];
 80.2426 +                     png_uint_16 gray16  = (png_uint_16)((rc * red_1
 80.2427 +                                  + gc * green_1 + bc * blue_1)>>15);
 80.2428 +                     w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
 80.2429 +                         png_ptr->gamma_shift][gray16 >> 8];
 80.2430 +                     rgb_error |= 1;
 80.2431 +                  }
 80.2432 +
 80.2433 +                  *(dp++) = (png_byte)((w>>8) & 0xff);
 80.2434 +                  *(dp++) = (png_byte)(w & 0xff);
 80.2435 +                  *(dp++) = *(sp++);  /* alpha */
 80.2436 +                  *(dp++) = *(sp++);
 80.2437 +               }
 80.2438 +            }
 80.2439 +            else
 80.2440 +#endif
 80.2441 +            {
 80.2442 +               png_bytep sp = row;
 80.2443 +               png_bytep dp = row;
 80.2444 +               for (i = 0; i < row_width; i++)
 80.2445 +               {
 80.2446 +                  png_uint_16 red, green, blue, gray16;
 80.2447 +                  red   = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
 80.2448 +                  green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
 80.2449 +                  blue  = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
 80.2450 +                  if (red != green || red != blue)
 80.2451 +                     rgb_error |= 1;
 80.2452 +                  gray16  = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
 80.2453 +                  *(dp++) = (png_byte)((gray16>>8) & 0xff);
 80.2454 +                  *(dp++) = (png_byte)(gray16 & 0xff);
 80.2455 +                  *(dp++) = *(sp++);  /* alpha */
 80.2456 +                  *(dp++) = *(sp++);
 80.2457 +               }
 80.2458 +            }
 80.2459 +         }
 80.2460 +      }
 80.2461 +   row_info->channels -= (png_byte)2;
 80.2462 +      row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
 80.2463 +      row_info->pixel_depth = (png_byte)(row_info->channels *
 80.2464 +         row_info->bit_depth);
 80.2465 +      row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width);
 80.2466 +   }
 80.2467 +   return rgb_error;
 80.2468 +}
 80.2469 +#endif
 80.2470 +
 80.2471 +/* Build a grayscale palette.  Palette is assumed to be 1 << bit_depth
 80.2472 + * large of png_color.  This lets grayscale images be treated as
 80.2473 + * paletted.  Most useful for gamma correction and simplification
 80.2474 + * of code.
 80.2475 + */
 80.2476 +void PNGAPI
 80.2477 +png_build_grayscale_palette(int bit_depth, png_colorp palette)
 80.2478 +{
 80.2479 +   int num_palette;
 80.2480 +   int color_inc;
 80.2481 +   int i;
 80.2482 +   int v;
 80.2483 +
 80.2484 +   png_debug(1, "in png_do_build_grayscale_palette\n");
 80.2485 +   if (palette == NULL)
 80.2486 +      return;
 80.2487 +
 80.2488 +   switch (bit_depth)
 80.2489 +   {
 80.2490 +      case 1:
 80.2491 +         num_palette = 2;
 80.2492 +         color_inc = 0xff;
 80.2493 +         break;
 80.2494 +      case 2:
 80.2495 +         num_palette = 4;
 80.2496 +         color_inc = 0x55;
 80.2497 +         break;
 80.2498 +      case 4:
 80.2499 +         num_palette = 16;
 80.2500 +         color_inc = 0x11;
 80.2501 +         break;
 80.2502 +      case 8:
 80.2503 +         num_palette = 256;
 80.2504 +         color_inc = 1;
 80.2505 +         break;
 80.2506 +      default:
 80.2507 +         num_palette = 0;
 80.2508 +         color_inc = 0;
 80.2509 +         break;
 80.2510 +   }
 80.2511 +
 80.2512 +   for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
 80.2513 +   {
 80.2514 +      palette[i].red = (png_byte)v;
 80.2515 +      palette[i].green = (png_byte)v;
 80.2516 +      palette[i].blue = (png_byte)v;
 80.2517 +   }
 80.2518 +}
 80.2519 +
 80.2520 +/* This function is currently unused.  Do we really need it? */
 80.2521 +#if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
 80.2522 +void /* PRIVATE */
 80.2523 +png_correct_palette(png_structp png_ptr, png_colorp palette,
 80.2524 +   int num_palette)
 80.2525 +{
 80.2526 +   png_debug(1, "in png_correct_palette\n");
 80.2527 +#if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
 80.2528 +    defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
 80.2529 +   if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
 80.2530 +   {
 80.2531 +      png_color back, back_1;
 80.2532 +
 80.2533 +      if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
 80.2534 +      {
 80.2535 +         back.red = png_ptr->gamma_table[png_ptr->background.red];
 80.2536 +         back.green = png_ptr->gamma_table[png_ptr->background.green];
 80.2537 +         back.blue = png_ptr->gamma_table[png_ptr->background.blue];
 80.2538 +
 80.2539 +         back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
 80.2540 +         back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
 80.2541 +         back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
 80.2542 +      }
 80.2543 +      else
 80.2544 +      {
 80.2545 +         double g;
 80.2546 +
 80.2547 +         g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
 80.2548 +
 80.2549 +         if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
 80.2550 +             fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
 80.2551 +         {
 80.2552 +            back.red = png_ptr->background.red;
 80.2553 +            back.green = png_ptr->background.green;
 80.2554 +            back.blue = png_ptr->background.blue;
 80.2555 +         }
 80.2556 +         else
 80.2557 +         {
 80.2558 +            back.red =
 80.2559 +               (png_byte)(pow((double)png_ptr->background.red/255, g) *
 80.2560 +                255.0 + 0.5);
 80.2561 +            back.green =
 80.2562 +               (png_byte)(pow((double)png_ptr->background.green/255, g) *
 80.2563 +                255.0 + 0.5);
 80.2564 +            back.blue =
 80.2565 +               (png_byte)(pow((double)png_ptr->background.blue/255, g) *
 80.2566 +                255.0 + 0.5);
 80.2567 +         }
 80.2568 +
 80.2569 +         g = 1.0 / png_ptr->background_gamma;
 80.2570 +
 80.2571 +         back_1.red =
 80.2572 +            (png_byte)(pow((double)png_ptr->background.red/255, g) *
 80.2573 +             255.0 + 0.5);
 80.2574 +         back_1.green =
 80.2575 +            (png_byte)(pow((double)png_ptr->background.green/255, g) *
 80.2576 +             255.0 + 0.5);
 80.2577 +         back_1.blue =
 80.2578 +            (png_byte)(pow((double)png_ptr->background.blue/255, g) *
 80.2579 +             255.0 + 0.5);
 80.2580 +      }
 80.2581 +
 80.2582 +      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 80.2583 +      {
 80.2584 +         png_uint_32 i;
 80.2585 +
 80.2586 +         for (i = 0; i < (png_uint_32)num_palette; i++)
 80.2587 +         {
 80.2588 +            if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
 80.2589 +            {
 80.2590 +               palette[i] = back;
 80.2591 +            }
 80.2592 +            else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
 80.2593 +            {
 80.2594 +               png_byte v, w;
 80.2595 +
 80.2596 +               v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
 80.2597 +               png_composite(w, v, png_ptr->trans[i], back_1.red);
 80.2598 +               palette[i].red = png_ptr->gamma_from_1[w];
 80.2599 +
 80.2600 +               v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
 80.2601 +               png_composite(w, v, png_ptr->trans[i], back_1.green);
 80.2602 +               palette[i].green = png_ptr->gamma_from_1[w];
 80.2603 +
 80.2604 +               v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
 80.2605 +               png_composite(w, v, png_ptr->trans[i], back_1.blue);
 80.2606 +               palette[i].blue = png_ptr->gamma_from_1[w];
 80.2607 +            }
 80.2608 +            else
 80.2609 +            {
 80.2610 +               palette[i].red = png_ptr->gamma_table[palette[i].red];
 80.2611 +               palette[i].green = png_ptr->gamma_table[palette[i].green];
 80.2612 +               palette[i].blue = png_ptr->gamma_table[palette[i].blue];
 80.2613 +            }
 80.2614 +         }
 80.2615 +      }
 80.2616 +      else
 80.2617 +      {
 80.2618 +         int i;
 80.2619 +
 80.2620 +         for (i = 0; i < num_palette; i++)
 80.2621 +         {
 80.2622 +            if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
 80.2623 +            {
 80.2624 +               palette[i] = back;
 80.2625 +            }
 80.2626 +            else
 80.2627 +            {
 80.2628 +               palette[i].red = png_ptr->gamma_table[palette[i].red];
 80.2629 +               palette[i].green = png_ptr->gamma_table[palette[i].green];
 80.2630 +               palette[i].blue = png_ptr->gamma_table[palette[i].blue];
 80.2631 +            }
 80.2632 +         }
 80.2633 +      }
 80.2634 +   }
 80.2635 +   else
 80.2636 +#endif
 80.2637 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.2638 +   if (png_ptr->transformations & PNG_GAMMA)
 80.2639 +   {
 80.2640 +      int i;
 80.2641 +
 80.2642 +      for (i = 0; i < num_palette; i++)
 80.2643 +      {
 80.2644 +         palette[i].red = png_ptr->gamma_table[palette[i].red];
 80.2645 +         palette[i].green = png_ptr->gamma_table[palette[i].green];
 80.2646 +         palette[i].blue = png_ptr->gamma_table[palette[i].blue];
 80.2647 +      }
 80.2648 +   }
 80.2649 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.2650 +   else
 80.2651 +#endif
 80.2652 +#endif
 80.2653 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.2654 +   if (png_ptr->transformations & PNG_BACKGROUND)
 80.2655 +   {
 80.2656 +      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 80.2657 +      {
 80.2658 +         png_color back;
 80.2659 +
 80.2660 +         back.red   = (png_byte)png_ptr->background.red;
 80.2661 +         back.green = (png_byte)png_ptr->background.green;
 80.2662 +         back.blue  = (png_byte)png_ptr->background.blue;
 80.2663 +
 80.2664 +         for (i = 0; i < (int)png_ptr->num_trans; i++)
 80.2665 +         {
 80.2666 +            if (png_ptr->trans[i] == 0)
 80.2667 +            {
 80.2668 +               palette[i].red = back.red;
 80.2669 +               palette[i].green = back.green;
 80.2670 +               palette[i].blue = back.blue;
 80.2671 +            }
 80.2672 +            else if (png_ptr->trans[i] != 0xff)
 80.2673 +            {
 80.2674 +               png_composite(palette[i].red, png_ptr->palette[i].red,
 80.2675 +                  png_ptr->trans[i], back.red);
 80.2676 +               png_composite(palette[i].green, png_ptr->palette[i].green,
 80.2677 +                  png_ptr->trans[i], back.green);
 80.2678 +               png_composite(palette[i].blue, png_ptr->palette[i].blue,
 80.2679 +                  png_ptr->trans[i], back.blue);
 80.2680 +            }
 80.2681 +         }
 80.2682 +      }
 80.2683 +      else /* assume grayscale palette (what else could it be?) */
 80.2684 +      {
 80.2685 +         int i;
 80.2686 +
 80.2687 +         for (i = 0; i < num_palette; i++)
 80.2688 +         {
 80.2689 +            if (i == (png_byte)png_ptr->trans_values.gray)
 80.2690 +            {
 80.2691 +               palette[i].red = (png_byte)png_ptr->background.red;
 80.2692 +               palette[i].green = (png_byte)png_ptr->background.green;
 80.2693 +               palette[i].blue = (png_byte)png_ptr->background.blue;
 80.2694 +            }
 80.2695 +         }
 80.2696 +      }
 80.2697 +   }
 80.2698 +#endif
 80.2699 +}
 80.2700 +#endif
 80.2701 +
 80.2702 +#if defined(PNG_READ_BACKGROUND_SUPPORTED)
 80.2703 +/* Replace any alpha or transparency with the supplied background color.
 80.2704 + * "background" is already in the screen gamma, while "background_1" is
 80.2705 + * at a gamma of 1.0.  Paletted files have already been taken care of.
 80.2706 + */
 80.2707 +void /* PRIVATE */
 80.2708 +png_do_background(png_row_infop row_info, png_bytep row,
 80.2709 +   png_color_16p trans_values, png_color_16p background
 80.2710 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.2711 +   , png_color_16p background_1,
 80.2712 +   png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
 80.2713 +   png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
 80.2714 +   png_uint_16pp gamma_16_to_1, int gamma_shift
 80.2715 +#endif
 80.2716 +   )
 80.2717 +{
 80.2718 +   png_bytep sp, dp;
 80.2719 +   png_uint_32 i;
 80.2720 +   png_uint_32 row_width=row_info->width;
 80.2721 +   int shift;
 80.2722 +
 80.2723 +   png_debug(1, "in png_do_background\n");
 80.2724 +   if (background != NULL &&
 80.2725 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.2726 +       row != NULL && row_info != NULL &&
 80.2727 +#endif
 80.2728 +      (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
 80.2729 +      (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
 80.2730 +   {
 80.2731 +      switch (row_info->color_type)
 80.2732 +      {
 80.2733 +         case PNG_COLOR_TYPE_GRAY:
 80.2734 +         {
 80.2735 +            switch (row_info->bit_depth)
 80.2736 +            {
 80.2737 +               case 1:
 80.2738 +               {
 80.2739 +                  sp = row;
 80.2740 +                  shift = 7;
 80.2741 +                  for (i = 0; i < row_width; i++)
 80.2742 +                  {
 80.2743 +                     if ((png_uint_16)((*sp >> shift) & 0x01)
 80.2744 +                        == trans_values->gray)
 80.2745 +                     {
 80.2746 +                        *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
 80.2747 +                        *sp |= (png_byte)(background->gray << shift);
 80.2748 +                     }
 80.2749 +                     if (!shift)
 80.2750 +                     {
 80.2751 +                        shift = 7;
 80.2752 +                        sp++;
 80.2753 +                     }
 80.2754 +                     else
 80.2755 +                        shift--;
 80.2756 +                  }
 80.2757 +                  break;
 80.2758 +               }
 80.2759 +               case 2:
 80.2760 +               {
 80.2761 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.2762 +                  if (gamma_table != NULL)
 80.2763 +                  {
 80.2764 +                     sp = row;
 80.2765 +                     shift = 6;
 80.2766 +                     for (i = 0; i < row_width; i++)
 80.2767 +                     {
 80.2768 +                        if ((png_uint_16)((*sp >> shift) & 0x03)
 80.2769 +                            == trans_values->gray)
 80.2770 +                        {
 80.2771 +                           *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
 80.2772 +                           *sp |= (png_byte)(background->gray << shift);
 80.2773 +                        }
 80.2774 +                        else
 80.2775 +                        {
 80.2776 +                           png_byte p = (png_byte)((*sp >> shift) & 0x03);
 80.2777 +                           png_byte g = (png_byte)((gamma_table [p | (p << 2) |
 80.2778 +                               (p << 4) | (p << 6)] >> 6) & 0x03);
 80.2779 +                           *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
 80.2780 +                           *sp |= (png_byte)(g << shift);
 80.2781 +                        }
 80.2782 +                        if (!shift)
 80.2783 +                        {
 80.2784 +                           shift = 6;
 80.2785 +                           sp++;
 80.2786 +                        }
 80.2787 +                        else
 80.2788 +                           shift -= 2;
 80.2789 +                     }
 80.2790 +                  }
 80.2791 +                  else
 80.2792 +#endif
 80.2793 +                  {
 80.2794 +                     sp = row;
 80.2795 +                     shift = 6;
 80.2796 +                     for (i = 0; i < row_width; i++)
 80.2797 +                     {
 80.2798 +                        if ((png_uint_16)((*sp >> shift) & 0x03)
 80.2799 +                            == trans_values->gray)
 80.2800 +                        {
 80.2801 +                           *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
 80.2802 +                           *sp |= (png_byte)(background->gray << shift);
 80.2803 +                        }
 80.2804 +                        if (!shift)
 80.2805 +                        {
 80.2806 +                           shift = 6;
 80.2807 +                           sp++;
 80.2808 +                        }
 80.2809 +                        else
 80.2810 +                           shift -= 2;
 80.2811 +                     }
 80.2812 +                  }
 80.2813 +                  break;
 80.2814 +               }
 80.2815 +               case 4:
 80.2816 +               {
 80.2817 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.2818 +                  if (gamma_table != NULL)
 80.2819 +                  {
 80.2820 +                     sp = row;
 80.2821 +                     shift = 4;
 80.2822 +                     for (i = 0; i < row_width; i++)
 80.2823 +                     {
 80.2824 +                        if ((png_uint_16)((*sp >> shift) & 0x0f)
 80.2825 +                            == trans_values->gray)
 80.2826 +                        {
 80.2827 +                           *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
 80.2828 +                           *sp |= (png_byte)(background->gray << shift);
 80.2829 +                        }
 80.2830 +                        else
 80.2831 +                        {
 80.2832 +                           png_byte p = (png_byte)((*sp >> shift) & 0x0f);
 80.2833 +                           png_byte g = (png_byte)((gamma_table[p |
 80.2834 +                             (p << 4)] >> 4) & 0x0f);
 80.2835 +                           *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
 80.2836 +                           *sp |= (png_byte)(g << shift);
 80.2837 +                        }
 80.2838 +                        if (!shift)
 80.2839 +                        {
 80.2840 +                           shift = 4;
 80.2841 +                           sp++;
 80.2842 +                        }
 80.2843 +                        else
 80.2844 +                           shift -= 4;
 80.2845 +                     }
 80.2846 +                  }
 80.2847 +                  else
 80.2848 +#endif
 80.2849 +                  {
 80.2850 +                     sp = row;
 80.2851 +                     shift = 4;
 80.2852 +                     for (i = 0; i < row_width; i++)
 80.2853 +                     {
 80.2854 +                        if ((png_uint_16)((*sp >> shift) & 0x0f)
 80.2855 +                            == trans_values->gray)
 80.2856 +                        {
 80.2857 +                           *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
 80.2858 +                           *sp |= (png_byte)(background->gray << shift);
 80.2859 +                        }
 80.2860 +                        if (!shift)
 80.2861 +                        {
 80.2862 +                           shift = 4;
 80.2863 +                           sp++;
 80.2864 +                        }
 80.2865 +                        else
 80.2866 +                           shift -= 4;
 80.2867 +                     }
 80.2868 +                  }
 80.2869 +                  break;
 80.2870 +               }
 80.2871 +               case 8:
 80.2872 +               {
 80.2873 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.2874 +                  if (gamma_table != NULL)
 80.2875 +                  {
 80.2876 +                     sp = row;
 80.2877 +                     for (i = 0; i < row_width; i++, sp++)
 80.2878 +                     {
 80.2879 +                        if (*sp == trans_values->gray)
 80.2880 +                        {
 80.2881 +                           *sp = (png_byte)background->gray;
 80.2882 +                        }
 80.2883 +                        else
 80.2884 +                        {
 80.2885 +                           *sp = gamma_table[*sp];
 80.2886 +                        }
 80.2887 +                     }
 80.2888 +                  }
 80.2889 +                  else
 80.2890 +#endif
 80.2891 +                  {
 80.2892 +                     sp = row;
 80.2893 +                     for (i = 0; i < row_width; i++, sp++)
 80.2894 +                     {
 80.2895 +                        if (*sp == trans_values->gray)
 80.2896 +                        {
 80.2897 +                           *sp = (png_byte)background->gray;
 80.2898 +                        }
 80.2899 +                     }
 80.2900 +                  }
 80.2901 +                  break;
 80.2902 +               }
 80.2903 +               case 16:
 80.2904 +               {
 80.2905 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.2906 +                  if (gamma_16 != NULL)
 80.2907 +                  {
 80.2908 +                     sp = row;
 80.2909 +                     for (i = 0; i < row_width; i++, sp += 2)
 80.2910 +                     {
 80.2911 +                        png_uint_16 v;
 80.2912 +
 80.2913 +                        v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
 80.2914 +                        if (v == trans_values->gray)
 80.2915 +                        {
 80.2916 +                           /* background is already in screen gamma */
 80.2917 +                           *sp = (png_byte)((background->gray >> 8) & 0xff);
 80.2918 +                           *(sp + 1) = (png_byte)(background->gray & 0xff);
 80.2919 +                        }
 80.2920 +                        else
 80.2921 +                        {
 80.2922 +                           v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
 80.2923 +                           *sp = (png_byte)((v >> 8) & 0xff);
 80.2924 +                           *(sp + 1) = (png_byte)(v & 0xff);
 80.2925 +                        }
 80.2926 +                     }
 80.2927 +                  }
 80.2928 +                  else
 80.2929 +#endif
 80.2930 +                  {
 80.2931 +                     sp = row;
 80.2932 +                     for (i = 0; i < row_width; i++, sp += 2)
 80.2933 +                     {
 80.2934 +                        png_uint_16 v;
 80.2935 +
 80.2936 +                        v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
 80.2937 +                        if (v == trans_values->gray)
 80.2938 +                        {
 80.2939 +                           *sp = (png_byte)((background->gray >> 8) & 0xff);
 80.2940 +                           *(sp + 1) = (png_byte)(background->gray & 0xff);
 80.2941 +                        }
 80.2942 +                     }
 80.2943 +                  }
 80.2944 +                  break;
 80.2945 +               }
 80.2946 +            }
 80.2947 +            break;
 80.2948 +         }
 80.2949 +         case PNG_COLOR_TYPE_RGB:
 80.2950 +         {
 80.2951 +            if (row_info->bit_depth == 8)
 80.2952 +            {
 80.2953 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.2954 +               if (gamma_table != NULL)
 80.2955 +               {
 80.2956 +                  sp = row;
 80.2957 +                  for (i = 0; i < row_width; i++, sp += 3)
 80.2958 +                  {
 80.2959 +                     if (*sp == trans_values->red &&
 80.2960 +                        *(sp + 1) == trans_values->green &&
 80.2961 +                        *(sp + 2) == trans_values->blue)
 80.2962 +                     {
 80.2963 +                        *sp = (png_byte)background->red;
 80.2964 +                        *(sp + 1) = (png_byte)background->green;
 80.2965 +                        *(sp + 2) = (png_byte)background->blue;
 80.2966 +                     }
 80.2967 +                     else
 80.2968 +                     {
 80.2969 +                        *sp = gamma_table[*sp];
 80.2970 +                        *(sp + 1) = gamma_table[*(sp + 1)];
 80.2971 +                        *(sp + 2) = gamma_table[*(sp + 2)];
 80.2972 +                     }
 80.2973 +                  }
 80.2974 +               }
 80.2975 +               else
 80.2976 +#endif
 80.2977 +               {
 80.2978 +                  sp = row;
 80.2979 +                  for (i = 0; i < row_width; i++, sp += 3)
 80.2980 +                  {
 80.2981 +                     if (*sp == trans_values->red &&
 80.2982 +                        *(sp + 1) == trans_values->green &&
 80.2983 +                        *(sp + 2) == trans_values->blue)
 80.2984 +                     {
 80.2985 +                        *sp = (png_byte)background->red;
 80.2986 +                        *(sp + 1) = (png_byte)background->green;
 80.2987 +                        *(sp + 2) = (png_byte)background->blue;
 80.2988 +                     }
 80.2989 +                  }
 80.2990 +               }
 80.2991 +            }
 80.2992 +            else /* if (row_info->bit_depth == 16) */
 80.2993 +            {
 80.2994 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.2995 +               if (gamma_16 != NULL)
 80.2996 +               {
 80.2997 +                  sp = row;
 80.2998 +                  for (i = 0; i < row_width; i++, sp += 6)
 80.2999 +                  {
 80.3000 +                     png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
 80.3001 +                     png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
 80.3002 +                     png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
 80.3003 +                     if (r == trans_values->red && g == trans_values->green &&
 80.3004 +                        b == trans_values->blue)
 80.3005 +                     {
 80.3006 +                        /* background is already in screen gamma */
 80.3007 +                        *sp = (png_byte)((background->red >> 8) & 0xff);
 80.3008 +                        *(sp + 1) = (png_byte)(background->red & 0xff);
 80.3009 +                        *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
 80.3010 +                        *(sp + 3) = (png_byte)(background->green & 0xff);
 80.3011 +                        *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
 80.3012 +                        *(sp + 5) = (png_byte)(background->blue & 0xff);
 80.3013 +                     }
 80.3014 +                     else
 80.3015 +                     {
 80.3016 +                        png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
 80.3017 +                        *sp = (png_byte)((v >> 8) & 0xff);
 80.3018 +                        *(sp + 1) = (png_byte)(v & 0xff);
 80.3019 +                        v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
 80.3020 +                        *(sp + 2) = (png_byte)((v >> 8) & 0xff);
 80.3021 +                        *(sp + 3) = (png_byte)(v & 0xff);
 80.3022 +                        v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
 80.3023 +                        *(sp + 4) = (png_byte)((v >> 8) & 0xff);
 80.3024 +                        *(sp + 5) = (png_byte)(v & 0xff);
 80.3025 +                     }
 80.3026 +                  }
 80.3027 +               }
 80.3028 +               else
 80.3029 +#endif
 80.3030 +               {
 80.3031 +                  sp = row;
 80.3032 +                  for (i = 0; i < row_width; i++, sp += 6)
 80.3033 +                  {
 80.3034 +                     png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
 80.3035 +                     png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
 80.3036 +                     png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
 80.3037 +
 80.3038 +                     if (r == trans_values->red && g == trans_values->green &&
 80.3039 +                        b == trans_values->blue)
 80.3040 +                     {
 80.3041 +                        *sp = (png_byte)((background->red >> 8) & 0xff);
 80.3042 +                        *(sp + 1) = (png_byte)(background->red & 0xff);
 80.3043 +                        *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
 80.3044 +                        *(sp + 3) = (png_byte)(background->green & 0xff);
 80.3045 +                        *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
 80.3046 +                        *(sp + 5) = (png_byte)(background->blue & 0xff);
 80.3047 +                     }
 80.3048 +                  }
 80.3049 +               }
 80.3050 +            }
 80.3051 +            break;
 80.3052 +         }
 80.3053 +         case PNG_COLOR_TYPE_GRAY_ALPHA:
 80.3054 +         {
 80.3055 +            if (row_info->bit_depth == 8)
 80.3056 +            {
 80.3057 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.3058 +               if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
 80.3059 +                   gamma_table != NULL)
 80.3060 +               {
 80.3061 +                  sp = row;
 80.3062 +                  dp = row;
 80.3063 +                  for (i = 0; i < row_width; i++, sp += 2, dp++)
 80.3064 +                  {
 80.3065 +                     png_uint_16 a = *(sp + 1);
 80.3066 +
 80.3067 +                     if (a == 0xff)
 80.3068 +                     {
 80.3069 +                        *dp = gamma_table[*sp];
 80.3070 +                     }
 80.3071 +                     else if (a == 0)
 80.3072 +                     {
 80.3073 +                        /* background is already in screen gamma */
 80.3074 +                        *dp = (png_byte)background->gray;
 80.3075 +                     }
 80.3076 +                     else
 80.3077 +                     {
 80.3078 +                        png_byte v, w;
 80.3079 +
 80.3080 +                        v = gamma_to_1[*sp];
 80.3081 +                        png_composite(w, v, a, background_1->gray);
 80.3082 +                        *dp = gamma_from_1[w];
 80.3083 +                     }
 80.3084 +                  }
 80.3085 +               }
 80.3086 +               else
 80.3087 +#endif
 80.3088 +               {
 80.3089 +                  sp = row;
 80.3090 +                  dp = row;
 80.3091 +                  for (i = 0; i < row_width; i++, sp += 2, dp++)
 80.3092 +                  {
 80.3093 +                     png_byte a = *(sp + 1);
 80.3094 +
 80.3095 +                     if (a == 0xff)
 80.3096 +                     {
 80.3097 +                        *dp = *sp;
 80.3098 +                     }
 80.3099 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.3100 +                     else if (a == 0)
 80.3101 +                     {
 80.3102 +                        *dp = (png_byte)background->gray;
 80.3103 +                     }
 80.3104 +                     else
 80.3105 +                     {
 80.3106 +                        png_composite(*dp, *sp, a, background_1->gray);
 80.3107 +                     }
 80.3108 +#else
 80.3109 +                     *dp = (png_byte)background->gray;
 80.3110 +#endif
 80.3111 +                  }
 80.3112 +               }
 80.3113 +            }
 80.3114 +            else /* if (png_ptr->bit_depth == 16) */
 80.3115 +            {
 80.3116 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.3117 +               if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
 80.3118 +                   gamma_16_to_1 != NULL)
 80.3119 +               {
 80.3120 +                  sp = row;
 80.3121 +                  dp = row;
 80.3122 +                  for (i = 0; i < row_width; i++, sp += 4, dp += 2)
 80.3123 +                  {
 80.3124 +                     png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
 80.3125 +
 80.3126 +                     if (a == (png_uint_16)0xffff)
 80.3127 +                     {
 80.3128 +                        png_uint_16 v;
 80.3129 +
 80.3130 +                        v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
 80.3131 +                        *dp = (png_byte)((v >> 8) & 0xff);
 80.3132 +                        *(dp + 1) = (png_byte)(v & 0xff);
 80.3133 +                     }
 80.3134 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.3135 +                     else if (a == 0)
 80.3136 +#else
 80.3137 +                     else
 80.3138 +#endif
 80.3139 +                     {
 80.3140 +                        /* background is already in screen gamma */
 80.3141 +                        *dp = (png_byte)((background->gray >> 8) & 0xff);
 80.3142 +                        *(dp + 1) = (png_byte)(background->gray & 0xff);
 80.3143 +                     }
 80.3144 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.3145 +                     else
 80.3146 +                     {
 80.3147 +                        png_uint_16 g, v, w;
 80.3148 +
 80.3149 +                        g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
 80.3150 +                        png_composite_16(v, g, a, background_1->gray);
 80.3151 +                        w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
 80.3152 +                        *dp = (png_byte)((w >> 8) & 0xff);
 80.3153 +                        *(dp + 1) = (png_byte)(w & 0xff);
 80.3154 +                     }
 80.3155 +#endif
 80.3156 +                  }
 80.3157 +               }
 80.3158 +               else
 80.3159 +#endif
 80.3160 +               {
 80.3161 +                  sp = row;
 80.3162 +                  dp = row;
 80.3163 +                  for (i = 0; i < row_width; i++, sp += 4, dp += 2)
 80.3164 +                  {
 80.3165 +                     png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
 80.3166 +                     if (a == (png_uint_16)0xffff)
 80.3167 +                     {
 80.3168 +                        png_memcpy(dp, sp, 2);
 80.3169 +                     }
 80.3170 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.3171 +                     else if (a == 0)
 80.3172 +#else
 80.3173 +                     else
 80.3174 +#endif
 80.3175 +                     {
 80.3176 +                        *dp = (png_byte)((background->gray >> 8) & 0xff);
 80.3177 +                        *(dp + 1) = (png_byte)(background->gray & 0xff);
 80.3178 +                     }
 80.3179 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.3180 +                     else
 80.3181 +                     {
 80.3182 +                        png_uint_16 g, v;
 80.3183 +
 80.3184 +                        g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
 80.3185 +                        png_composite_16(v, g, a, background_1->gray);
 80.3186 +                        *dp = (png_byte)((v >> 8) & 0xff);
 80.3187 +                        *(dp + 1) = (png_byte)(v & 0xff);
 80.3188 +                     }
 80.3189 +#endif
 80.3190 +                  }
 80.3191 +               }
 80.3192 +            }
 80.3193 +            break;
 80.3194 +         }
 80.3195 +         case PNG_COLOR_TYPE_RGB_ALPHA:
 80.3196 +         {
 80.3197 +            if (row_info->bit_depth == 8)
 80.3198 +            {
 80.3199 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.3200 +               if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
 80.3201 +                   gamma_table != NULL)
 80.3202 +               {
 80.3203 +                  sp = row;
 80.3204 +                  dp = row;
 80.3205 +                  for (i = 0; i < row_width; i++, sp += 4, dp += 3)
 80.3206 +                  {
 80.3207 +                     png_byte a = *(sp + 3);
 80.3208 +
 80.3209 +                     if (a == 0xff)
 80.3210 +                     {
 80.3211 +                        *dp = gamma_table[*sp];
 80.3212 +                        *(dp + 1) = gamma_table[*(sp + 1)];
 80.3213 +                        *(dp + 2) = gamma_table[*(sp + 2)];
 80.3214 +                     }
 80.3215 +                     else if (a == 0)
 80.3216 +                     {
 80.3217 +                        /* background is already in screen gamma */
 80.3218 +                        *dp = (png_byte)background->red;
 80.3219 +                        *(dp + 1) = (png_byte)background->green;
 80.3220 +                        *(dp + 2) = (png_byte)background->blue;
 80.3221 +                     }
 80.3222 +                     else
 80.3223 +                     {
 80.3224 +                        png_byte v, w;
 80.3225 +
 80.3226 +                        v = gamma_to_1[*sp];
 80.3227 +                        png_composite(w, v, a, background_1->red);
 80.3228 +                        *dp = gamma_from_1[w];
 80.3229 +                        v = gamma_to_1[*(sp + 1)];
 80.3230 +                        png_composite(w, v, a, background_1->green);
 80.3231 +                        *(dp + 1) = gamma_from_1[w];
 80.3232 +                        v = gamma_to_1[*(sp + 2)];
 80.3233 +                        png_composite(w, v, a, background_1->blue);
 80.3234 +                        *(dp + 2) = gamma_from_1[w];
 80.3235 +                     }
 80.3236 +                  }
 80.3237 +               }
 80.3238 +               else
 80.3239 +#endif
 80.3240 +               {
 80.3241 +                  sp = row;
 80.3242 +                  dp = row;
 80.3243 +                  for (i = 0; i < row_width; i++, sp += 4, dp += 3)
 80.3244 +                  {
 80.3245 +                     png_byte a = *(sp + 3);
 80.3246 +
 80.3247 +                     if (a == 0xff)
 80.3248 +                     {
 80.3249 +                        *dp = *sp;
 80.3250 +                        *(dp + 1) = *(sp + 1);
 80.3251 +                        *(dp + 2) = *(sp + 2);
 80.3252 +                     }
 80.3253 +                     else if (a == 0)
 80.3254 +                     {
 80.3255 +                        *dp = (png_byte)background->red;
 80.3256 +                        *(dp + 1) = (png_byte)background->green;
 80.3257 +                        *(dp + 2) = (png_byte)background->blue;
 80.3258 +                     }
 80.3259 +                     else
 80.3260 +                     {
 80.3261 +                        png_composite(*dp, *sp, a, background->red);
 80.3262 +                        png_composite(*(dp + 1), *(sp + 1), a,
 80.3263 +                           background->green);
 80.3264 +                        png_composite(*(dp + 2), *(sp + 2), a,
 80.3265 +                           background->blue);
 80.3266 +                     }
 80.3267 +                  }
 80.3268 +               }
 80.3269 +            }
 80.3270 +            else /* if (row_info->bit_depth == 16) */
 80.3271 +            {
 80.3272 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.3273 +               if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
 80.3274 +                   gamma_16_to_1 != NULL)
 80.3275 +               {
 80.3276 +                  sp = row;
 80.3277 +                  dp = row;
 80.3278 +                  for (i = 0; i < row_width; i++, sp += 8, dp += 6)
 80.3279 +                  {
 80.3280 +                     png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
 80.3281 +                         << 8) + (png_uint_16)(*(sp + 7)));
 80.3282 +                     if (a == (png_uint_16)0xffff)
 80.3283 +                     {
 80.3284 +                        png_uint_16 v;
 80.3285 +
 80.3286 +                        v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
 80.3287 +                        *dp = (png_byte)((v >> 8) & 0xff);
 80.3288 +                        *(dp + 1) = (png_byte)(v & 0xff);
 80.3289 +                        v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
 80.3290 +                        *(dp + 2) = (png_byte)((v >> 8) & 0xff);
 80.3291 +                        *(dp + 3) = (png_byte)(v & 0xff);
 80.3292 +                        v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
 80.3293 +                        *(dp + 4) = (png_byte)((v >> 8) & 0xff);
 80.3294 +                        *(dp + 5) = (png_byte)(v & 0xff);
 80.3295 +                     }
 80.3296 +                     else if (a == 0)
 80.3297 +                     {
 80.3298 +                        /* background is already in screen gamma */
 80.3299 +                        *dp = (png_byte)((background->red >> 8) & 0xff);
 80.3300 +                        *(dp + 1) = (png_byte)(background->red & 0xff);
 80.3301 +                        *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
 80.3302 +                        *(dp + 3) = (png_byte)(background->green & 0xff);
 80.3303 +                        *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
 80.3304 +                        *(dp + 5) = (png_byte)(background->blue & 0xff);
 80.3305 +                     }
 80.3306 +                     else
 80.3307 +                     {
 80.3308 +                        png_uint_16 v, w, x;
 80.3309 +
 80.3310 +                        v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
 80.3311 +                        png_composite_16(w, v, a, background_1->red);
 80.3312 +                        x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
 80.3313 +                        *dp = (png_byte)((x >> 8) & 0xff);
 80.3314 +                        *(dp + 1) = (png_byte)(x & 0xff);
 80.3315 +                        v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
 80.3316 +                        png_composite_16(w, v, a, background_1->green);
 80.3317 +                        x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
 80.3318 +                        *(dp + 2) = (png_byte)((x >> 8) & 0xff);
 80.3319 +                        *(dp + 3) = (png_byte)(x & 0xff);
 80.3320 +                        v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
 80.3321 +                        png_composite_16(w, v, a, background_1->blue);
 80.3322 +                        x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
 80.3323 +                        *(dp + 4) = (png_byte)((x >> 8) & 0xff);
 80.3324 +                        *(dp + 5) = (png_byte)(x & 0xff);
 80.3325 +                     }
 80.3326 +                  }
 80.3327 +               }
 80.3328 +               else
 80.3329 +#endif
 80.3330 +               {
 80.3331 +                  sp = row;
 80.3332 +                  dp = row;
 80.3333 +                  for (i = 0; i < row_width; i++, sp += 8, dp += 6)
 80.3334 +                  {
 80.3335 +                     png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
 80.3336 +                        << 8) + (png_uint_16)(*(sp + 7)));
 80.3337 +                     if (a == (png_uint_16)0xffff)
 80.3338 +                     {
 80.3339 +                        png_memcpy(dp, sp, 6);
 80.3340 +                     }
 80.3341 +                     else if (a == 0)
 80.3342 +                     {
 80.3343 +                        *dp = (png_byte)((background->red >> 8) & 0xff);
 80.3344 +                        *(dp + 1) = (png_byte)(background->red & 0xff);
 80.3345 +                        *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
 80.3346 +                        *(dp + 3) = (png_byte)(background->green & 0xff);
 80.3347 +                        *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
 80.3348 +                        *(dp + 5) = (png_byte)(background->blue & 0xff);
 80.3349 +                     }
 80.3350 +                     else
 80.3351 +                     {
 80.3352 +                        png_uint_16 v;
 80.3353 +
 80.3354 +                        png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
 80.3355 +                        png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
 80.3356 +                            + *(sp + 3));
 80.3357 +                        png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
 80.3358 +                            + *(sp + 5));
 80.3359 +
 80.3360 +                        png_composite_16(v, r, a, background->red);
 80.3361 +                        *dp = (png_byte)((v >> 8) & 0xff);
 80.3362 +                        *(dp + 1) = (png_byte)(v & 0xff);
 80.3363 +                        png_composite_16(v, g, a, background->green);
 80.3364 +                        *(dp + 2) = (png_byte)((v >> 8) & 0xff);
 80.3365 +                        *(dp + 3) = (png_byte)(v & 0xff);
 80.3366 +                        png_composite_16(v, b, a, background->blue);
 80.3367 +                        *(dp + 4) = (png_byte)((v >> 8) & 0xff);
 80.3368 +                        *(dp + 5) = (png_byte)(v & 0xff);
 80.3369 +                     }
 80.3370 +                  }
 80.3371 +               }
 80.3372 +            }
 80.3373 +            break;
 80.3374 +         }
 80.3375 +      }
 80.3376 +
 80.3377 +      if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
 80.3378 +      {
 80.3379 +         row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
 80.3380 +         row_info->channels--;
 80.3381 +         row_info->pixel_depth = (png_byte)(row_info->channels *
 80.3382 +            row_info->bit_depth);
 80.3383 +         row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width);
 80.3384 +      }
 80.3385 +   }
 80.3386 +}
 80.3387 +#endif
 80.3388 +
 80.3389 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.3390 +/* Gamma correct the image, avoiding the alpha channel.  Make sure
 80.3391 + * you do this after you deal with the transparency issue on grayscale
 80.3392 + * or RGB images. If your bit depth is 8, use gamma_table, if it
 80.3393 + * is 16, use gamma_16_table and gamma_shift.  Build these with
 80.3394 + * build_gamma_table().
 80.3395 + */
 80.3396 +void /* PRIVATE */
 80.3397 +png_do_gamma(png_row_infop row_info, png_bytep row,
 80.3398 +   png_bytep gamma_table, png_uint_16pp gamma_16_table,
 80.3399 +   int gamma_shift)
 80.3400 +{
 80.3401 +   png_bytep sp;
 80.3402 +   png_uint_32 i;
 80.3403 +   png_uint_32 row_width=row_info->width;
 80.3404 +
 80.3405 +   png_debug(1, "in png_do_gamma\n");
 80.3406 +   if (
 80.3407 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.3408 +       row != NULL && row_info != NULL &&
 80.3409 +#endif
 80.3410 +       ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
 80.3411 +        (row_info->bit_depth == 16 && gamma_16_table != NULL)))
 80.3412 +   {
 80.3413 +      switch (row_info->color_type)
 80.3414 +      {
 80.3415 +         case PNG_COLOR_TYPE_RGB:
 80.3416 +         {
 80.3417 +            if (row_info->bit_depth == 8)
 80.3418 +            {
 80.3419 +               sp = row;
 80.3420 +               for (i = 0; i < row_width; i++)
 80.3421 +               {
 80.3422 +                  *sp = gamma_table[*sp];
 80.3423 +                  sp++;
 80.3424 +                  *sp = gamma_table[*sp];
 80.3425 +                  sp++;
 80.3426 +                  *sp = gamma_table[*sp];
 80.3427 +                  sp++;
 80.3428 +               }
 80.3429 +            }
 80.3430 +            else /* if (row_info->bit_depth == 16) */
 80.3431 +            {
 80.3432 +               sp = row;
 80.3433 +               for (i = 0; i < row_width; i++)
 80.3434 +               {
 80.3435 +                  png_uint_16 v;
 80.3436 +
 80.3437 +                  v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
 80.3438 +                  *sp = (png_byte)((v >> 8) & 0xff);
 80.3439 +                  *(sp + 1) = (png_byte)(v & 0xff);
 80.3440 +                  sp += 2;
 80.3441 +                  v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
 80.3442 +                  *sp = (png_byte)((v >> 8) & 0xff);
 80.3443 +                  *(sp + 1) = (png_byte)(v & 0xff);
 80.3444 +                  sp += 2;
 80.3445 +                  v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
 80.3446 +                  *sp = (png_byte)((v >> 8) & 0xff);
 80.3447 +                  *(sp + 1) = (png_byte)(v & 0xff);
 80.3448 +                  sp += 2;
 80.3449 +               }
 80.3450 +            }
 80.3451 +            break;
 80.3452 +         }
 80.3453 +         case PNG_COLOR_TYPE_RGB_ALPHA:
 80.3454 +         {
 80.3455 +            if (row_info->bit_depth == 8)
 80.3456 +            {
 80.3457 +               sp = row;
 80.3458 +               for (i = 0; i < row_width; i++)
 80.3459 +               {
 80.3460 +                  *sp = gamma_table[*sp];
 80.3461 +                  sp++;
 80.3462 +                  *sp = gamma_table[*sp];
 80.3463 +                  sp++;
 80.3464 +                  *sp = gamma_table[*sp];
 80.3465 +                  sp++;
 80.3466 +                  sp++;
 80.3467 +               }
 80.3468 +            }
 80.3469 +            else /* if (row_info->bit_depth == 16) */
 80.3470 +            {
 80.3471 +               sp = row;
 80.3472 +               for (i = 0; i < row_width; i++)
 80.3473 +               {
 80.3474 +                  png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
 80.3475 +                  *sp = (png_byte)((v >> 8) & 0xff);
 80.3476 +                  *(sp + 1) = (png_byte)(v & 0xff);
 80.3477 +                  sp += 2;
 80.3478 +                  v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
 80.3479 +                  *sp = (png_byte)((v >> 8) & 0xff);
 80.3480 +                  *(sp + 1) = (png_byte)(v & 0xff);
 80.3481 +                  sp += 2;
 80.3482 +                  v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
 80.3483 +                  *sp = (png_byte)((v >> 8) & 0xff);
 80.3484 +                  *(sp + 1) = (png_byte)(v & 0xff);
 80.3485 +                  sp += 4;
 80.3486 +               }
 80.3487 +            }
 80.3488 +            break;
 80.3489 +         }
 80.3490 +         case PNG_COLOR_TYPE_GRAY_ALPHA:
 80.3491 +         {
 80.3492 +            if (row_info->bit_depth == 8)
 80.3493 +            {
 80.3494 +               sp = row;
 80.3495 +               for (i = 0; i < row_width; i++)
 80.3496 +               {
 80.3497 +                  *sp = gamma_table[*sp];
 80.3498 +                  sp += 2;
 80.3499 +               }
 80.3500 +            }
 80.3501 +            else /* if (row_info->bit_depth == 16) */
 80.3502 +            {
 80.3503 +               sp = row;
 80.3504 +               for (i = 0; i < row_width; i++)
 80.3505 +               {
 80.3506 +                  png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
 80.3507 +                  *sp = (png_byte)((v >> 8) & 0xff);
 80.3508 +                  *(sp + 1) = (png_byte)(v & 0xff);
 80.3509 +                  sp += 4;
 80.3510 +               }
 80.3511 +            }
 80.3512 +            break;
 80.3513 +         }
 80.3514 +         case PNG_COLOR_TYPE_GRAY:
 80.3515 +         {
 80.3516 +            if (row_info->bit_depth == 2)
 80.3517 +            {
 80.3518 +               sp = row;
 80.3519 +               for (i = 0; i < row_width; i += 4)
 80.3520 +               {
 80.3521 +                  int a = *sp & 0xc0;
 80.3522 +                  int b = *sp & 0x30;
 80.3523 +                  int c = *sp & 0x0c;
 80.3524 +                  int d = *sp & 0x03;
 80.3525 +
 80.3526 +                  *sp = (png_byte)(
 80.3527 +                        ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)])   ) & 0xc0)|
 80.3528 +                        ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
 80.3529 +                        ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
 80.3530 +                        ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
 80.3531 +                  sp++;
 80.3532 +               }
 80.3533 +            }
 80.3534 +            if (row_info->bit_depth == 4)
 80.3535 +            {
 80.3536 +               sp = row;
 80.3537 +               for (i = 0; i < row_width; i += 2)
 80.3538 +               {
 80.3539 +                  int msb = *sp & 0xf0;
 80.3540 +                  int lsb = *sp & 0x0f;
 80.3541 +
 80.3542 +                  *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
 80.3543 +                          | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
 80.3544 +                  sp++;
 80.3545 +               }
 80.3546 +            }
 80.3547 +            else if (row_info->bit_depth == 8)
 80.3548 +            {
 80.3549 +               sp = row;
 80.3550 +               for (i = 0; i < row_width; i++)
 80.3551 +               {
 80.3552 +                  *sp = gamma_table[*sp];
 80.3553 +                  sp++;
 80.3554 +               }
 80.3555 +            }
 80.3556 +            else if (row_info->bit_depth == 16)
 80.3557 +            {
 80.3558 +               sp = row;
 80.3559 +               for (i = 0; i < row_width; i++)
 80.3560 +               {
 80.3561 +                  png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
 80.3562 +                  *sp = (png_byte)((v >> 8) & 0xff);
 80.3563 +                  *(sp + 1) = (png_byte)(v & 0xff);
 80.3564 +                  sp += 2;
 80.3565 +               }
 80.3566 +            }
 80.3567 +            break;
 80.3568 +         }
 80.3569 +      }
 80.3570 +   }
 80.3571 +}
 80.3572 +#endif
 80.3573 +
 80.3574 +#if defined(PNG_READ_EXPAND_SUPPORTED)
 80.3575 +/* Expands a palette row to an RGB or RGBA row depending
 80.3576 + * upon whether you supply trans and num_trans.
 80.3577 + */
 80.3578 +void /* PRIVATE */
 80.3579 +png_do_expand_palette(png_row_infop row_info, png_bytep row,
 80.3580 +   png_colorp palette, png_bytep trans, int num_trans)
 80.3581 +{
 80.3582 +   int shift, value;
 80.3583 +   png_bytep sp, dp;
 80.3584 +   png_uint_32 i;
 80.3585 +   png_uint_32 row_width=row_info->width;
 80.3586 +
 80.3587 +   png_debug(1, "in png_do_expand_palette\n");
 80.3588 +   if (
 80.3589 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.3590 +       row != NULL && row_info != NULL &&
 80.3591 +#endif
 80.3592 +       row_info->color_type == PNG_COLOR_TYPE_PALETTE)
 80.3593 +   {
 80.3594 +      if (row_info->bit_depth < 8)
 80.3595 +      {
 80.3596 +         switch (row_info->bit_depth)
 80.3597 +         {
 80.3598 +            case 1:
 80.3599 +            {
 80.3600 +               sp = row + (png_size_t)((row_width - 1) >> 3);
 80.3601 +               dp = row + (png_size_t)row_width - 1;
 80.3602 +               shift = 7 - (int)((row_width + 7) & 0x07);
 80.3603 +               for (i = 0; i < row_width; i++)
 80.3604 +               {
 80.3605 +                  if ((*sp >> shift) & 0x01)
 80.3606 +                     *dp = 1;
 80.3607 +                  else
 80.3608 +                     *dp = 0;
 80.3609 +                  if (shift == 7)
 80.3610 +                  {
 80.3611 +                     shift = 0;
 80.3612 +                     sp--;
 80.3613 +                  }
 80.3614 +                  else
 80.3615 +                     shift++;
 80.3616 +
 80.3617 +                  dp--;
 80.3618 +               }
 80.3619 +               break;
 80.3620 +            }
 80.3621 +            case 2:
 80.3622 +            {
 80.3623 +               sp = row + (png_size_t)((row_width - 1) >> 2);
 80.3624 +               dp = row + (png_size_t)row_width - 1;
 80.3625 +               shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
 80.3626 +               for (i = 0; i < row_width; i++)
 80.3627 +               {
 80.3628 +                  value = (*sp >> shift) & 0x03;
 80.3629 +                  *dp = (png_byte)value;
 80.3630 +                  if (shift == 6)
 80.3631 +                  {
 80.3632 +                     shift = 0;
 80.3633 +                     sp--;
 80.3634 +                  }
 80.3635 +                  else
 80.3636 +                     shift += 2;
 80.3637 +
 80.3638 +                  dp--;
 80.3639 +               }
 80.3640 +               break;
 80.3641 +            }
 80.3642 +            case 4:
 80.3643 +            {
 80.3644 +               sp = row + (png_size_t)((row_width - 1) >> 1);
 80.3645 +               dp = row + (png_size_t)row_width - 1;
 80.3646 +               shift = (int)((row_width & 0x01) << 2);
 80.3647 +               for (i = 0; i < row_width; i++)
 80.3648 +               {
 80.3649 +                  value = (*sp >> shift) & 0x0f;
 80.3650 +                  *dp = (png_byte)value;
 80.3651 +                  if (shift == 4)
 80.3652 +                  {
 80.3653 +                     shift = 0;
 80.3654 +                     sp--;
 80.3655 +                  }
 80.3656 +                  else
 80.3657 +                     shift += 4;
 80.3658 +
 80.3659 +                  dp--;
 80.3660 +               }
 80.3661 +               break;
 80.3662 +            }
 80.3663 +         }
 80.3664 +         row_info->bit_depth = 8;
 80.3665 +         row_info->pixel_depth = 8;
 80.3666 +         row_info->rowbytes = row_width;
 80.3667 +      }
 80.3668 +      switch (row_info->bit_depth)
 80.3669 +      {
 80.3670 +         case 8:
 80.3671 +         {
 80.3672 +            if (trans != NULL)
 80.3673 +            {
 80.3674 +               sp = row + (png_size_t)row_width - 1;
 80.3675 +               dp = row + (png_size_t)(row_width << 2) - 1;
 80.3676 +
 80.3677 +               for (i = 0; i < row_width; i++)
 80.3678 +               {
 80.3679 +                  if ((int)(*sp) >= num_trans)
 80.3680 +                     *dp-- = 0xff;
 80.3681 +                  else
 80.3682 +                     *dp-- = trans[*sp];
 80.3683 +                  *dp-- = palette[*sp].blue;
 80.3684 +                  *dp-- = palette[*sp].green;
 80.3685 +                  *dp-- = palette[*sp].red;
 80.3686 +                  sp--;
 80.3687 +               }
 80.3688 +               row_info->bit_depth = 8;
 80.3689 +               row_info->pixel_depth = 32;
 80.3690 +               row_info->rowbytes = row_width * 4;
 80.3691 +               row_info->color_type = 6;
 80.3692 +               row_info->channels = 4;
 80.3693 +            }
 80.3694 +            else
 80.3695 +            {
 80.3696 +               sp = row + (png_size_t)row_width - 1;
 80.3697 +               dp = row + (png_size_t)(row_width * 3) - 1;
 80.3698 +
 80.3699 +               for (i = 0; i < row_width; i++)
 80.3700 +               {
 80.3701 +                  *dp-- = palette[*sp].blue;
 80.3702 +                  *dp-- = palette[*sp].green;
 80.3703 +                  *dp-- = palette[*sp].red;
 80.3704 +                  sp--;
 80.3705 +               }
 80.3706 +               row_info->bit_depth = 8;
 80.3707 +               row_info->pixel_depth = 24;
 80.3708 +               row_info->rowbytes = row_width * 3;
 80.3709 +               row_info->color_type = 2;
 80.3710 +               row_info->channels = 3;
 80.3711 +            }
 80.3712 +            break;
 80.3713 +         }
 80.3714 +      }
 80.3715 +   }
 80.3716 +}
 80.3717 +
 80.3718 +/* If the bit depth < 8, it is expanded to 8.  Also, if the already
 80.3719 + * expanded transparency value is supplied, an alpha channel is built.
 80.3720 + */
 80.3721 +void /* PRIVATE */
 80.3722 +png_do_expand(png_row_infop row_info, png_bytep row,
 80.3723 +   png_color_16p trans_value)
 80.3724 +{
 80.3725 +   int shift, value;
 80.3726 +   png_bytep sp, dp;
 80.3727 +   png_uint_32 i;
 80.3728 +   png_uint_32 row_width=row_info->width;
 80.3729 +
 80.3730 +   png_debug(1, "in png_do_expand\n");
 80.3731 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.3732 +   if (row != NULL && row_info != NULL)
 80.3733 +#endif
 80.3734 +   {
 80.3735 +      if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
 80.3736 +      {
 80.3737 +         png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
 80.3738 +
 80.3739 +         if (row_info->bit_depth < 8)
 80.3740 +         {
 80.3741 +            switch (row_info->bit_depth)
 80.3742 +            {
 80.3743 +               case 1:
 80.3744 +               {
 80.3745 +                  gray = (png_uint_16)((gray&0x01)*0xff);
 80.3746 +                  sp = row + (png_size_t)((row_width - 1) >> 3);
 80.3747 +                  dp = row + (png_size_t)row_width - 1;
 80.3748 +                  shift = 7 - (int)((row_width + 7) & 0x07);
 80.3749 +                  for (i = 0; i < row_width; i++)
 80.3750 +                  {
 80.3751 +                     if ((*sp >> shift) & 0x01)
 80.3752 +                        *dp = 0xff;
 80.3753 +                     else
 80.3754 +                        *dp = 0;
 80.3755 +                     if (shift == 7)
 80.3756 +                     {
 80.3757 +                        shift = 0;
 80.3758 +                        sp--;
 80.3759 +                     }
 80.3760 +                     else
 80.3761 +                        shift++;
 80.3762 +
 80.3763 +                     dp--;
 80.3764 +                  }
 80.3765 +                  break;
 80.3766 +               }
 80.3767 +               case 2:
 80.3768 +               {
 80.3769 +                  gray = (png_uint_16)((gray&0x03)*0x55);
 80.3770 +                  sp = row + (png_size_t)((row_width - 1) >> 2);
 80.3771 +                  dp = row + (png_size_t)row_width - 1;
 80.3772 +                  shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
 80.3773 +                  for (i = 0; i < row_width; i++)
 80.3774 +                  {
 80.3775 +                     value = (*sp >> shift) & 0x03;
 80.3776 +                     *dp = (png_byte)(value | (value << 2) | (value << 4) |
 80.3777 +                        (value << 6));
 80.3778 +                     if (shift == 6)
 80.3779 +                     {
 80.3780 +                        shift = 0;
 80.3781 +                        sp--;
 80.3782 +                     }
 80.3783 +                     else
 80.3784 +                        shift += 2;
 80.3785 +
 80.3786 +                     dp--;
 80.3787 +                  }
 80.3788 +                  break;
 80.3789 +               }
 80.3790 +               case 4:
 80.3791 +               {
 80.3792 +                  gray = (png_uint_16)((gray&0x0f)*0x11);
 80.3793 +                  sp = row + (png_size_t)((row_width - 1) >> 1);
 80.3794 +                  dp = row + (png_size_t)row_width - 1;
 80.3795 +                  shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
 80.3796 +                  for (i = 0; i < row_width; i++)
 80.3797 +                  {
 80.3798 +                     value = (*sp >> shift) & 0x0f;
 80.3799 +                     *dp = (png_byte)(value | (value << 4));
 80.3800 +                     if (shift == 4)
 80.3801 +                     {
 80.3802 +                        shift = 0;
 80.3803 +                        sp--;
 80.3804 +                     }
 80.3805 +                     else
 80.3806 +                        shift = 4;
 80.3807 +
 80.3808 +                     dp--;
 80.3809 +                  }
 80.3810 +                  break;
 80.3811 +               }
 80.3812 +            }
 80.3813 +            row_info->bit_depth = 8;
 80.3814 +            row_info->pixel_depth = 8;
 80.3815 +            row_info->rowbytes = row_width;
 80.3816 +         }
 80.3817 +
 80.3818 +         if (trans_value != NULL)
 80.3819 +         {
 80.3820 +            if (row_info->bit_depth == 8)
 80.3821 +            {
 80.3822 +               gray = gray & 0xff;
 80.3823 +               sp = row + (png_size_t)row_width - 1;
 80.3824 +               dp = row + (png_size_t)(row_width << 1) - 1;
 80.3825 +               for (i = 0; i < row_width; i++)
 80.3826 +               {
 80.3827 +                  if (*sp == gray)
 80.3828 +                     *dp-- = 0;
 80.3829 +                  else
 80.3830 +                     *dp-- = 0xff;
 80.3831 +                  *dp-- = *sp--;
 80.3832 +               }
 80.3833 +            }
 80.3834 +            else if (row_info->bit_depth == 16)
 80.3835 +            {
 80.3836 +               png_byte gray_high = (gray >> 8) & 0xff;
 80.3837 +               png_byte gray_low = gray & 0xff;
 80.3838 +               sp = row + row_info->rowbytes - 1;
 80.3839 +               dp = row + (row_info->rowbytes << 1) - 1;
 80.3840 +               for (i = 0; i < row_width; i++)
 80.3841 +               {
 80.3842 +                  if (*(sp - 1) == gray_high && *(sp) == gray_low) 
 80.3843 +                  {
 80.3844 +                     *dp-- = 0;
 80.3845 +                     *dp-- = 0;
 80.3846 +                  }
 80.3847 +                  else
 80.3848 +                  {
 80.3849 +                     *dp-- = 0xff;
 80.3850 +                     *dp-- = 0xff;
 80.3851 +                  }
 80.3852 +                  *dp-- = *sp--;
 80.3853 +                  *dp-- = *sp--;
 80.3854 +               }
 80.3855 +            }
 80.3856 +            row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
 80.3857 +            row_info->channels = 2;
 80.3858 +            row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
 80.3859 +            row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
 80.3860 +               row_width);
 80.3861 +         }
 80.3862 +      }
 80.3863 +      else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
 80.3864 +      {
 80.3865 +         if (row_info->bit_depth == 8)
 80.3866 +         {
 80.3867 +            png_byte red = trans_value->red & 0xff;
 80.3868 +            png_byte green = trans_value->green & 0xff;
 80.3869 +            png_byte blue = trans_value->blue & 0xff;
 80.3870 +            sp = row + (png_size_t)row_info->rowbytes - 1;
 80.3871 +            dp = row + (png_size_t)(row_width << 2) - 1;
 80.3872 +            for (i = 0; i < row_width; i++)
 80.3873 +            {
 80.3874 +               if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
 80.3875 +                  *dp-- = 0;
 80.3876 +               else
 80.3877 +                  *dp-- = 0xff;
 80.3878 +               *dp-- = *sp--;
 80.3879 +               *dp-- = *sp--;
 80.3880 +               *dp-- = *sp--;
 80.3881 +            }
 80.3882 +         }
 80.3883 +         else if (row_info->bit_depth == 16)
 80.3884 +         {
 80.3885 +            png_byte red_high = (trans_value->red >> 8) & 0xff;
 80.3886 +            png_byte green_high = (trans_value->green >> 8) & 0xff;
 80.3887 +            png_byte blue_high = (trans_value->blue >> 8) & 0xff;
 80.3888 +            png_byte red_low = trans_value->red & 0xff;
 80.3889 +            png_byte green_low = trans_value->green & 0xff;
 80.3890 +            png_byte blue_low = trans_value->blue & 0xff;
 80.3891 +            sp = row + row_info->rowbytes - 1;
 80.3892 +            dp = row + (png_size_t)(row_width << 3) - 1;
 80.3893 +            for (i = 0; i < row_width; i++)
 80.3894 +            {
 80.3895 +               if (*(sp - 5) == red_high &&
 80.3896 +                  *(sp - 4) == red_low &&
 80.3897 +                  *(sp - 3) == green_high &&
 80.3898 +                  *(sp - 2) == green_low &&
 80.3899 +                  *(sp - 1) == blue_high &&
 80.3900 +                  *(sp    ) == blue_low)
 80.3901 +               {
 80.3902 +                  *dp-- = 0;
 80.3903 +                  *dp-- = 0;
 80.3904 +               }
 80.3905 +               else
 80.3906 +               {
 80.3907 +                  *dp-- = 0xff;
 80.3908 +                  *dp-- = 0xff;
 80.3909 +               }
 80.3910 +               *dp-- = *sp--;
 80.3911 +               *dp-- = *sp--;
 80.3912 +               *dp-- = *sp--;
 80.3913 +               *dp-- = *sp--;
 80.3914 +               *dp-- = *sp--;
 80.3915 +               *dp-- = *sp--;
 80.3916 +            }
 80.3917 +         }
 80.3918 +         row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
 80.3919 +         row_info->channels = 4;
 80.3920 +         row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
 80.3921 +         row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width);
 80.3922 +      }
 80.3923 +   }
 80.3924 +}
 80.3925 +#endif
 80.3926 +
 80.3927 +#if defined(PNG_READ_DITHER_SUPPORTED)
 80.3928 +void /* PRIVATE */
 80.3929 +png_do_dither(png_row_infop row_info, png_bytep row,
 80.3930 +    png_bytep palette_lookup, png_bytep dither_lookup)
 80.3931 +{
 80.3932 +   png_bytep sp, dp;
 80.3933 +   png_uint_32 i;
 80.3934 +   png_uint_32 row_width=row_info->width;
 80.3935 +
 80.3936 +   png_debug(1, "in png_do_dither\n");
 80.3937 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.3938 +   if (row != NULL && row_info != NULL)
 80.3939 +#endif
 80.3940 +   {
 80.3941 +      if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
 80.3942 +         palette_lookup && row_info->bit_depth == 8)
 80.3943 +      {
 80.3944 +         int r, g, b, p;
 80.3945 +         sp = row;
 80.3946 +         dp = row;
 80.3947 +         for (i = 0; i < row_width; i++)
 80.3948 +         {
 80.3949 +            r = *sp++;
 80.3950 +            g = *sp++;
 80.3951 +            b = *sp++;
 80.3952 +
 80.3953 +            /* this looks real messy, but the compiler will reduce
 80.3954 +               it down to a reasonable formula.  For example, with
 80.3955 +               5 bits per color, we get:
 80.3956 +               p = (((r >> 3) & 0x1f) << 10) |
 80.3957 +                  (((g >> 3) & 0x1f) << 5) |
 80.3958 +                  ((b >> 3) & 0x1f);
 80.3959 +               */
 80.3960 +            p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
 80.3961 +               ((1 << PNG_DITHER_RED_BITS) - 1)) <<
 80.3962 +               (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
 80.3963 +               (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
 80.3964 +               ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
 80.3965 +               (PNG_DITHER_BLUE_BITS)) |
 80.3966 +               ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
 80.3967 +               ((1 << PNG_DITHER_BLUE_BITS) - 1));
 80.3968 +
 80.3969 +            *dp++ = palette_lookup[p];
 80.3970 +         }
 80.3971 +         row_info->color_type = PNG_COLOR_TYPE_PALETTE;
 80.3972 +         row_info->channels = 1;
 80.3973 +         row_info->pixel_depth = row_info->bit_depth;
 80.3974 +         row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width);
 80.3975 +      }
 80.3976 +      else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
 80.3977 +         palette_lookup != NULL && row_info->bit_depth == 8)
 80.3978 +      {
 80.3979 +         int r, g, b, p;
 80.3980 +         sp = row;
 80.3981 +         dp = row;
 80.3982 +         for (i = 0; i < row_width; i++)
 80.3983 +         {
 80.3984 +            r = *sp++;
 80.3985 +            g = *sp++;
 80.3986 +            b = *sp++;
 80.3987 +            sp++;
 80.3988 +
 80.3989 +            p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
 80.3990 +               ((1 << PNG_DITHER_RED_BITS) - 1)) <<
 80.3991 +               (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
 80.3992 +               (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
 80.3993 +               ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
 80.3994 +               (PNG_DITHER_BLUE_BITS)) |
 80.3995 +               ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
 80.3996 +               ((1 << PNG_DITHER_BLUE_BITS) - 1));
 80.3997 +
 80.3998 +            *dp++ = palette_lookup[p];
 80.3999 +         }
 80.4000 +         row_info->color_type = PNG_COLOR_TYPE_PALETTE;
 80.4001 +         row_info->channels = 1;
 80.4002 +         row_info->pixel_depth = row_info->bit_depth;
 80.4003 +         row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width);
 80.4004 +      }
 80.4005 +      else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
 80.4006 +         dither_lookup && row_info->bit_depth == 8)
 80.4007 +      {
 80.4008 +         sp = row;
 80.4009 +         for (i = 0; i < row_width; i++, sp++)
 80.4010 +         {
 80.4011 +            *sp = dither_lookup[*sp];
 80.4012 +         }
 80.4013 +      }
 80.4014 +   }
 80.4015 +}
 80.4016 +#endif
 80.4017 +
 80.4018 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 80.4019 +#if defined(PNG_READ_GAMMA_SUPPORTED)
 80.4020 +static PNG_CONST int png_gamma_shift[] =
 80.4021 +   {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
 80.4022 +
 80.4023 +/* We build the 8- or 16-bit gamma tables here.  Note that for 16-bit
 80.4024 + * tables, we don't make a full table if we are reducing to 8-bit in
 80.4025 + * the future.  Note also how the gamma_16 tables are segmented so that
 80.4026 + * we don't need to allocate > 64K chunks for a full 16-bit table.
 80.4027 + */
 80.4028 +void /* PRIVATE */
 80.4029 +png_build_gamma_table(png_structp png_ptr)
 80.4030 +{
 80.4031 +  png_debug(1, "in png_build_gamma_table\n");
 80.4032 +
 80.4033 +  if (png_ptr->bit_depth <= 8)
 80.4034 +  {
 80.4035 +     int i;
 80.4036 +     double g;
 80.4037 +
 80.4038 +     if (png_ptr->screen_gamma > .000001)
 80.4039 +        g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
 80.4040 +     else
 80.4041 +        g = 1.0;
 80.4042 +
 80.4043 +     png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
 80.4044 +        (png_uint_32)256);
 80.4045 +
 80.4046 +     for (i = 0; i < 256; i++)
 80.4047 +     {
 80.4048 +        png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
 80.4049 +           g) * 255.0 + .5);
 80.4050 +     }
 80.4051 +
 80.4052 +#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
 80.4053 +   defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
 80.4054 +     if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
 80.4055 +     {
 80.4056 +
 80.4057 +        g = 1.0 / (png_ptr->gamma);
 80.4058 +
 80.4059 +        png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
 80.4060 +           (png_uint_32)256);
 80.4061 +
 80.4062 +        for (i = 0; i < 256; i++)
 80.4063 +        {
 80.4064 +           png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
 80.4065 +              g) * 255.0 + .5);
 80.4066 +        }
 80.4067 +
 80.4068 +
 80.4069 +        png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
 80.4070 +           (png_uint_32)256);
 80.4071 +
 80.4072 +        if (png_ptr->screen_gamma > 0.000001)
 80.4073 +           g = 1.0 / png_ptr->screen_gamma;
 80.4074 +        else
 80.4075 +           g = png_ptr->gamma;   /* probably doing rgb_to_gray */
 80.4076 +
 80.4077 +        for (i = 0; i < 256; i++)
 80.4078 +        {
 80.4079 +           png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
 80.4080 +              g) * 255.0 + .5);
 80.4081 +
 80.4082 +        }
 80.4083 +     }
 80.4084 +#endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
 80.4085 +  }
 80.4086 +  else
 80.4087 +  {
 80.4088 +     double g;
 80.4089 +     int i, j, shift, num;
 80.4090 +     int sig_bit;
 80.4091 +     png_uint_32 ig;
 80.4092 +
 80.4093 +     if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
 80.4094 +     {
 80.4095 +        sig_bit = (int)png_ptr->sig_bit.red;
 80.4096 +        if ((int)png_ptr->sig_bit.green > sig_bit)
 80.4097 +           sig_bit = png_ptr->sig_bit.green;
 80.4098 +        if ((int)png_ptr->sig_bit.blue > sig_bit)
 80.4099 +           sig_bit = png_ptr->sig_bit.blue;
 80.4100 +     }
 80.4101 +     else
 80.4102 +     {
 80.4103 +        sig_bit = (int)png_ptr->sig_bit.gray;
 80.4104 +     }
 80.4105 +
 80.4106 +     if (sig_bit > 0)
 80.4107 +        shift = 16 - sig_bit;
 80.4108 +     else
 80.4109 +        shift = 0;
 80.4110 +
 80.4111 +     if (png_ptr->transformations & PNG_16_TO_8)
 80.4112 +     {
 80.4113 +        if (shift < (16 - PNG_MAX_GAMMA_8))
 80.4114 +           shift = (16 - PNG_MAX_GAMMA_8);
 80.4115 +     }
 80.4116 +
 80.4117 +     if (shift > 8)
 80.4118 +        shift = 8;
 80.4119 +     if (shift < 0)
 80.4120 +        shift = 0;
 80.4121 +
 80.4122 +     png_ptr->gamma_shift = (png_byte)shift;
 80.4123 +
 80.4124 +     num = (1 << (8 - shift));
 80.4125 +
 80.4126 +     if (png_ptr->screen_gamma > .000001)
 80.4127 +        g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
 80.4128 +     else
 80.4129 +        g = 1.0;
 80.4130 +
 80.4131 +     png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
 80.4132 +        (png_uint_32)(num * png_sizeof(png_uint_16p)));
 80.4133 +
 80.4134 +     if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
 80.4135 +     {
 80.4136 +        double fin, fout;
 80.4137 +        png_uint_32 last, max;
 80.4138 +
 80.4139 +        for (i = 0; i < num; i++)
 80.4140 +        {
 80.4141 +           png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
 80.4142 +              (png_uint_32)(256 * png_sizeof(png_uint_16)));
 80.4143 +        }
 80.4144 +
 80.4145 +        g = 1.0 / g;
 80.4146 +        last = 0;
 80.4147 +        for (i = 0; i < 256; i++)
 80.4148 +        {
 80.4149 +           fout = ((double)i + 0.5) / 256.0;
 80.4150 +           fin = pow(fout, g);
 80.4151 +           max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
 80.4152 +           while (last <= max)
 80.4153 +           {
 80.4154 +              png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
 80.4155 +                 [(int)(last >> (8 - shift))] = (png_uint_16)(
 80.4156 +                 (png_uint_16)i | ((png_uint_16)i << 8));
 80.4157 +              last++;
 80.4158 +           }
 80.4159 +        }
 80.4160 +        while (last < ((png_uint_32)num << 8))
 80.4161 +        {
 80.4162 +           png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
 80.4163 +              [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
 80.4164 +           last++;
 80.4165 +        }
 80.4166 +     }
 80.4167 +     else
 80.4168 +     {
 80.4169 +        for (i = 0; i < num; i++)
 80.4170 +        {
 80.4171 +           png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
 80.4172 +              (png_uint_32)(256 * png_sizeof(png_uint_16)));
 80.4173 +
 80.4174 +           ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
 80.4175 +           for (j = 0; j < 256; j++)
 80.4176 +           {
 80.4177 +              png_ptr->gamma_16_table[i][j] =
 80.4178 +                 (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
 80.4179 +                    65535.0, g) * 65535.0 + .5);
 80.4180 +           }
 80.4181 +        }
 80.4182 +     }
 80.4183 +
 80.4184 +#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
 80.4185 +   defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
 80.4186 +     if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
 80.4187 +     {
 80.4188 +
 80.4189 +        g = 1.0 / (png_ptr->gamma);
 80.4190 +
 80.4191 +        png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
 80.4192 +           (png_uint_32)(num * png_sizeof(png_uint_16p )));
 80.4193 +
 80.4194 +        for (i = 0; i < num; i++)
 80.4195 +        {
 80.4196 +           png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
 80.4197 +              (png_uint_32)(256 * png_sizeof(png_uint_16)));
 80.4198 +
 80.4199 +           ig = (((png_uint_32)i *
 80.4200 +              (png_uint_32)png_gamma_shift[shift]) >> 4);
 80.4201 +           for (j = 0; j < 256; j++)
 80.4202 +           {
 80.4203 +              png_ptr->gamma_16_to_1[i][j] =
 80.4204 +                 (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
 80.4205 +                    65535.0, g) * 65535.0 + .5);
 80.4206 +           }
 80.4207 +        }
 80.4208 +
 80.4209 +        if (png_ptr->screen_gamma > 0.000001)
 80.4210 +           g = 1.0 / png_ptr->screen_gamma;
 80.4211 +        else
 80.4212 +           g = png_ptr->gamma;   /* probably doing rgb_to_gray */
 80.4213 +
 80.4214 +        png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
 80.4215 +           (png_uint_32)(num * png_sizeof(png_uint_16p)));
 80.4216 +
 80.4217 +        for (i = 0; i < num; i++)
 80.4218 +        {
 80.4219 +           png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
 80.4220 +              (png_uint_32)(256 * png_sizeof(png_uint_16)));
 80.4221 +
 80.4222 +           ig = (((png_uint_32)i *
 80.4223 +              (png_uint_32)png_gamma_shift[shift]) >> 4);
 80.4224 +           for (j = 0; j < 256; j++)
 80.4225 +           {
 80.4226 +              png_ptr->gamma_16_from_1[i][j] =
 80.4227 +                 (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
 80.4228 +                    65535.0, g) * 65535.0 + .5);
 80.4229 +           }
 80.4230 +        }
 80.4231 +     }
 80.4232 +#endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
 80.4233 +  }
 80.4234 +}
 80.4235 +#endif
 80.4236 +/* To do: install integer version of png_build_gamma_table here */
 80.4237 +#endif
 80.4238 +
 80.4239 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
 80.4240 +/* undoes intrapixel differencing  */
 80.4241 +void /* PRIVATE */
 80.4242 +png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
 80.4243 +{
 80.4244 +   png_debug(1, "in png_do_read_intrapixel\n");
 80.4245 +   if (
 80.4246 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 80.4247 +       row != NULL && row_info != NULL &&
 80.4248 +#endif
 80.4249 +       (row_info->color_type & PNG_COLOR_MASK_COLOR))
 80.4250 +   {
 80.4251 +      int bytes_per_pixel;
 80.4252 +      png_uint_32 row_width = row_info->width;
 80.4253 +      if (row_info->bit_depth == 8)
 80.4254 +      {
 80.4255 +         png_bytep rp;
 80.4256 +         png_uint_32 i;
 80.4257 +
 80.4258 +         if (row_info->color_type == PNG_COLOR_TYPE_RGB)
 80.4259 +            bytes_per_pixel = 3;
 80.4260 +         else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
 80.4261 +            bytes_per_pixel = 4;
 80.4262 +         else
 80.4263 +            return;
 80.4264 +
 80.4265 +         for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
 80.4266 +         {
 80.4267 +            *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
 80.4268 +            *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
 80.4269 +         }
 80.4270 +      }
 80.4271 +      else if (row_info->bit_depth == 16)
 80.4272 +      {
 80.4273 +         png_bytep rp;
 80.4274 +         png_uint_32 i;
 80.4275 +
 80.4276 +         if (row_info->color_type == PNG_COLOR_TYPE_RGB)
 80.4277 +            bytes_per_pixel = 6;
 80.4278 +         else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
 80.4279 +            bytes_per_pixel = 8;
 80.4280 +         else
 80.4281 +            return;
 80.4282 +
 80.4283 +         for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
 80.4284 +         {
 80.4285 +            png_uint_32 s0   = (*(rp    ) << 8) | *(rp + 1);
 80.4286 +            png_uint_32 s1   = (*(rp + 2) << 8) | *(rp + 3);
 80.4287 +            png_uint_32 s2   = (*(rp + 4) << 8) | *(rp + 5);
 80.4288 +            png_uint_32 red  = (png_uint_32)((s0 + s1 + 65536L) & 0xffffL);
 80.4289 +            png_uint_32 blue = (png_uint_32)((s2 + s1 + 65536L) & 0xffffL);
 80.4290 +            *(rp  ) = (png_byte)((red >> 8) & 0xff);
 80.4291 +            *(rp+1) = (png_byte)(red & 0xff);
 80.4292 +            *(rp+4) = (png_byte)((blue >> 8) & 0xff);
 80.4293 +            *(rp+5) = (png_byte)(blue & 0xff);
 80.4294 +         }
 80.4295 +      }
 80.4296 +   }
 80.4297 +}
 80.4298 +#endif /* PNG_MNG_FEATURES_SUPPORTED */
 80.4299 +#endif /* PNG_READ_SUPPORTED */
    81.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    81.2 +++ b/libs/libpng/pngrutil.c	Thu Sep 08 06:28:38 2011 +0300
    81.3 @@ -0,0 +1,3234 @@
    81.4 +
    81.5 +/* pngrutil.c - utilities to read a PNG file
    81.6 + *
    81.7 + * Last changed in libpng 1.2.33 [October 31, 2008]
    81.8 + * For conditions of distribution and use, see copyright notice in png.h
    81.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   81.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   81.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   81.12 + *
   81.13 + * This file contains routines that are only called from within
   81.14 + * libpng itself during the course of reading an image.
   81.15 + */
   81.16 +
   81.17 +#define PNG_INTERNAL
   81.18 +#include "png.h"
   81.19 +#if defined(PNG_READ_SUPPORTED)
   81.20 +
   81.21 +#if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
   81.22 +#  define WIN32_WCE_OLD
   81.23 +#endif
   81.24 +
   81.25 +#ifdef PNG_FLOATING_POINT_SUPPORTED
   81.26 +#  if defined(WIN32_WCE_OLD)
   81.27 +/* strtod() function is not supported on WindowsCE */
   81.28 +__inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
   81.29 +{
   81.30 +   double result = 0;
   81.31 +   int len;
   81.32 +   wchar_t *str, *end;
   81.33 +
   81.34 +   len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
   81.35 +   str = (wchar_t *)png_malloc(png_ptr, len * png_sizeof(wchar_t));
   81.36 +   if ( NULL != str )
   81.37 +   {
   81.38 +      MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
   81.39 +      result = wcstod(str, &end);
   81.40 +      len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
   81.41 +      *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
   81.42 +      png_free(png_ptr, str);
   81.43 +   }
   81.44 +   return result;
   81.45 +}
   81.46 +#  else
   81.47 +#    define png_strtod(p,a,b) strtod(a,b)
   81.48 +#  endif
   81.49 +#endif
   81.50 +
   81.51 +png_uint_32 PNGAPI
   81.52 +png_get_uint_31(png_structp png_ptr, png_bytep buf)
   81.53 +{
   81.54 +#ifdef PNG_READ_BIG_ENDIAN_SUPPORTED
   81.55 +   png_uint_32 i = png_get_uint_32(buf);
   81.56 +#else
   81.57 +   /* Avoid an extra function call by inlining the result. */
   81.58 +   png_uint_32 i = ((png_uint_32)(*buf) << 24) +
   81.59 +      ((png_uint_32)(*(buf + 1)) << 16) +
   81.60 +      ((png_uint_32)(*(buf + 2)) << 8) +
   81.61 +      (png_uint_32)(*(buf + 3));
   81.62 +#endif
   81.63 +   if (i > PNG_UINT_31_MAX)
   81.64 +     png_error(png_ptr, "PNG unsigned integer out of range.");
   81.65 +   return (i);
   81.66 +}
   81.67 +#ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
   81.68 +/* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
   81.69 +png_uint_32 PNGAPI
   81.70 +png_get_uint_32(png_bytep buf)
   81.71 +{
   81.72 +   png_uint_32 i = ((png_uint_32)(*buf) << 24) +
   81.73 +      ((png_uint_32)(*(buf + 1)) << 16) +
   81.74 +      ((png_uint_32)(*(buf + 2)) << 8) +
   81.75 +      (png_uint_32)(*(buf + 3));
   81.76 +
   81.77 +   return (i);
   81.78 +}
   81.79 +
   81.80 +/* Grab a signed 32-bit integer from a buffer in big-endian format.  The
   81.81 + * data is stored in the PNG file in two's complement format, and it is
   81.82 + * assumed that the machine format for signed integers is the same. */
   81.83 +png_int_32 PNGAPI
   81.84 +png_get_int_32(png_bytep buf)
   81.85 +{
   81.86 +   png_int_32 i = ((png_int_32)(*buf) << 24) +
   81.87 +      ((png_int_32)(*(buf + 1)) << 16) +
   81.88 +      ((png_int_32)(*(buf + 2)) << 8) +
   81.89 +      (png_int_32)(*(buf + 3));
   81.90 +
   81.91 +   return (i);
   81.92 +}
   81.93 +
   81.94 +/* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
   81.95 +png_uint_16 PNGAPI
   81.96 +png_get_uint_16(png_bytep buf)
   81.97 +{
   81.98 +   png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
   81.99 +      (png_uint_16)(*(buf + 1)));
  81.100 +
  81.101 +   return (i);
  81.102 +}
  81.103 +#endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  81.104 +
  81.105 +/* Read the chunk header (length + type name).
  81.106 + * Put the type name into png_ptr->chunk_name, and return the length.
  81.107 + */
  81.108 +png_uint_32 /* PRIVATE */
  81.109 +png_read_chunk_header(png_structp png_ptr)
  81.110 +{
  81.111 +   png_byte buf[8];
  81.112 +   png_uint_32 length;
  81.113 +
  81.114 +   /* read the length and the chunk name */
  81.115 +   png_read_data(png_ptr, buf, 8);
  81.116 +   length = png_get_uint_31(png_ptr, buf);
  81.117 +
  81.118 +   /* put the chunk name into png_ptr->chunk_name */
  81.119 +   png_memcpy(png_ptr->chunk_name, buf + 4, 4);
  81.120 +
  81.121 +   png_debug2(0, "Reading %s chunk, length = %lu\n",
  81.122 +      png_ptr->chunk_name, length);
  81.123 +
  81.124 +   /* reset the crc and run it over the chunk name */
  81.125 +   png_reset_crc(png_ptr);
  81.126 +   png_calculate_crc(png_ptr, png_ptr->chunk_name, 4);
  81.127 +
  81.128 +   /* check to see if chunk name is valid */
  81.129 +   png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  81.130 +
  81.131 +   return length;
  81.132 +}
  81.133 +
  81.134 +/* Read data, and (optionally) run it through the CRC. */
  81.135 +void /* PRIVATE */
  81.136 +png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  81.137 +{
  81.138 +   if (png_ptr == NULL) return;
  81.139 +   png_read_data(png_ptr, buf, length);
  81.140 +   png_calculate_crc(png_ptr, buf, length);
  81.141 +}
  81.142 +
  81.143 +/* Optionally skip data and then check the CRC.  Depending on whether we
  81.144 +   are reading a ancillary or critical chunk, and how the program has set
  81.145 +   things up, we may calculate the CRC on the data and print a message.
  81.146 +   Returns '1' if there was a CRC error, '0' otherwise. */
  81.147 +int /* PRIVATE */
  81.148 +png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  81.149 +{
  81.150 +   png_size_t i;
  81.151 +   png_size_t istop = png_ptr->zbuf_size;
  81.152 +
  81.153 +   for (i = (png_size_t)skip; i > istop; i -= istop)
  81.154 +   {
  81.155 +      png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  81.156 +   }
  81.157 +   if (i)
  81.158 +   {
  81.159 +      png_crc_read(png_ptr, png_ptr->zbuf, i);
  81.160 +   }
  81.161 +
  81.162 +   if (png_crc_error(png_ptr))
  81.163 +   {
  81.164 +      if (((png_ptr->chunk_name[0] & 0x20) &&                /* Ancillary */
  81.165 +           !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  81.166 +          (!(png_ptr->chunk_name[0] & 0x20) &&             /* Critical  */
  81.167 +          (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  81.168 +      {
  81.169 +         png_chunk_warning(png_ptr, "CRC error");
  81.170 +      }
  81.171 +      else
  81.172 +      {
  81.173 +         png_chunk_error(png_ptr, "CRC error");
  81.174 +      }
  81.175 +      return (1);
  81.176 +   }
  81.177 +
  81.178 +   return (0);
  81.179 +}
  81.180 +
  81.181 +/* Compare the CRC stored in the PNG file with that calculated by libpng from
  81.182 +   the data it has read thus far. */
  81.183 +int /* PRIVATE */
  81.184 +png_crc_error(png_structp png_ptr)
  81.185 +{
  81.186 +   png_byte crc_bytes[4];
  81.187 +   png_uint_32 crc;
  81.188 +   int need_crc = 1;
  81.189 +
  81.190 +   if (png_ptr->chunk_name[0] & 0x20)                     /* ancillary */
  81.191 +   {
  81.192 +      if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  81.193 +          (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  81.194 +         need_crc = 0;
  81.195 +   }
  81.196 +   else                                                    /* critical */
  81.197 +   {
  81.198 +      if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  81.199 +         need_crc = 0;
  81.200 +   }
  81.201 +
  81.202 +   png_read_data(png_ptr, crc_bytes, 4);
  81.203 +
  81.204 +   if (need_crc)
  81.205 +   {
  81.206 +      crc = png_get_uint_32(crc_bytes);
  81.207 +      return ((int)(crc != png_ptr->crc));
  81.208 +   }
  81.209 +   else
  81.210 +      return (0);
  81.211 +}
  81.212 +
  81.213 +#if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  81.214 +    defined(PNG_READ_iCCP_SUPPORTED)
  81.215 +/*
  81.216 + * Decompress trailing data in a chunk.  The assumption is that chunkdata
  81.217 + * points at an allocated area holding the contents of a chunk with a
  81.218 + * trailing compressed part.  What we get back is an allocated area
  81.219 + * holding the original prefix part and an uncompressed version of the
  81.220 + * trailing part (the malloc area passed in is freed).
  81.221 + */
  81.222 +void /* PRIVATE */
  81.223 +png_decompress_chunk(png_structp png_ptr, int comp_type,
  81.224 +                              png_size_t chunklength,
  81.225 +                              png_size_t prefix_size, png_size_t *newlength)
  81.226 +{
  81.227 +   static PNG_CONST char msg[] = "Error decoding compressed text";
  81.228 +   png_charp text;
  81.229 +   png_size_t text_size;
  81.230 +
  81.231 +   if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  81.232 +   {
  81.233 +      int ret = Z_OK;
  81.234 +      png_ptr->zstream.next_in = (png_bytep)(png_ptr->chunkdata + prefix_size);
  81.235 +      png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  81.236 +      png_ptr->zstream.next_out = png_ptr->zbuf;
  81.237 +      png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  81.238 +
  81.239 +      text_size = 0;
  81.240 +      text = NULL;
  81.241 +
  81.242 +      while (png_ptr->zstream.avail_in)
  81.243 +      {
  81.244 +         ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  81.245 +         if (ret != Z_OK && ret != Z_STREAM_END)
  81.246 +         {
  81.247 +            if (png_ptr->zstream.msg != NULL)
  81.248 +               png_warning(png_ptr, png_ptr->zstream.msg);
  81.249 +            else
  81.250 +               png_warning(png_ptr, msg);
  81.251 +            inflateReset(&png_ptr->zstream);
  81.252 +            png_ptr->zstream.avail_in = 0;
  81.253 +
  81.254 +            if (text ==  NULL)
  81.255 +            {
  81.256 +               text_size = prefix_size + png_sizeof(msg) + 1;
  81.257 +               text = (png_charp)png_malloc_warn(png_ptr, text_size);
  81.258 +               if (text ==  NULL)
  81.259 +                 {
  81.260 +                    png_free(png_ptr, png_ptr->chunkdata);
  81.261 +                    png_ptr->chunkdata = NULL;
  81.262 +                    png_error(png_ptr, "Not enough memory to decompress chunk");
  81.263 +                 }
  81.264 +               png_memcpy(text, png_ptr->chunkdata, prefix_size);
  81.265 +            }
  81.266 +
  81.267 +            text[text_size - 1] = 0x00;
  81.268 +
  81.269 +            /* Copy what we can of the error message into the text chunk */
  81.270 +            text_size = (png_size_t)(chunklength -
  81.271 +              (text - png_ptr->chunkdata) - 1);
  81.272 +            if (text_size > png_sizeof(msg))
  81.273 +               text_size = png_sizeof(msg);
  81.274 +            png_memcpy(text + prefix_size, msg, text_size);
  81.275 +            break;
  81.276 +         }
  81.277 +         if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  81.278 +         {
  81.279 +            if (text == NULL)
  81.280 +            {
  81.281 +               text_size = prefix_size +
  81.282 +                   png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  81.283 +               text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  81.284 +               if (text ==  NULL)
  81.285 +               {
  81.286 +                  png_free(png_ptr, png_ptr->chunkdata);
  81.287 +                  png_ptr->chunkdata = NULL;
  81.288 +                  png_error(png_ptr,
  81.289 +                    "Not enough memory to decompress chunk.");
  81.290 +               }
  81.291 +               png_memcpy(text + prefix_size, png_ptr->zbuf,
  81.292 +                    text_size - prefix_size);
  81.293 +               png_memcpy(text, png_ptr->chunkdata, prefix_size);
  81.294 +               *(text + text_size) = 0x00;
  81.295 +            }
  81.296 +            else
  81.297 +            {
  81.298 +               png_charp tmp;
  81.299 +
  81.300 +               tmp = text;
  81.301 +               text = (png_charp)png_malloc_warn(png_ptr,
  81.302 +                  (png_uint_32)(text_size +
  81.303 +                  png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  81.304 +               if (text == NULL)
  81.305 +               {
  81.306 +                  png_free(png_ptr, tmp);
  81.307 +                  png_free(png_ptr, png_ptr->chunkdata);
  81.308 +                  png_ptr->chunkdata = NULL;
  81.309 +                  png_error(png_ptr,
  81.310 +                    "Not enough memory to decompress chunk..");
  81.311 +               }
  81.312 +               png_memcpy(text, tmp, text_size);
  81.313 +               png_free(png_ptr, tmp);
  81.314 +               png_memcpy(text + text_size, png_ptr->zbuf,
  81.315 +                  (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  81.316 +               text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  81.317 +               *(text + text_size) = 0x00;
  81.318 +            }
  81.319 +            if (ret == Z_STREAM_END)
  81.320 +               break;
  81.321 +            else
  81.322 +            {
  81.323 +               png_ptr->zstream.next_out = png_ptr->zbuf;
  81.324 +               png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  81.325 +            }
  81.326 +         }
  81.327 +      }
  81.328 +      if (ret != Z_STREAM_END)
  81.329 +      {
  81.330 +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  81.331 +         char umsg[52];
  81.332 +
  81.333 +         if (ret == Z_BUF_ERROR)
  81.334 +            png_snprintf(umsg, 52,
  81.335 +                "Buffer error in compressed datastream in %s chunk",
  81.336 +                png_ptr->chunk_name);
  81.337 +         else if (ret == Z_DATA_ERROR)
  81.338 +            png_snprintf(umsg, 52,
  81.339 +                "Data error in compressed datastream in %s chunk",
  81.340 +                png_ptr->chunk_name);
  81.341 +         else
  81.342 +            png_snprintf(umsg, 52,
  81.343 +                "Incomplete compressed datastream in %s chunk",
  81.344 +                png_ptr->chunk_name);
  81.345 +         png_warning(png_ptr, umsg);
  81.346 +#else
  81.347 +         png_warning(png_ptr,
  81.348 +            "Incomplete compressed datastream in chunk other than IDAT");
  81.349 +#endif
  81.350 +         text_size = prefix_size;
  81.351 +         if (text ==  NULL)
  81.352 +         {
  81.353 +            text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  81.354 +            if (text == NULL)
  81.355 +              {
  81.356 +                png_free(png_ptr, png_ptr->chunkdata);
  81.357 +                png_ptr->chunkdata = NULL;
  81.358 +                png_error(png_ptr, "Not enough memory for text.");
  81.359 +              }
  81.360 +            png_memcpy(text, png_ptr->chunkdata, prefix_size);
  81.361 +         }
  81.362 +         *(text + text_size) = 0x00;
  81.363 +      }
  81.364 +
  81.365 +      inflateReset(&png_ptr->zstream);
  81.366 +      png_ptr->zstream.avail_in = 0;
  81.367 +
  81.368 +      png_free(png_ptr, png_ptr->chunkdata);
  81.369 +      png_ptr->chunkdata = text;
  81.370 +      *newlength=text_size;
  81.371 +   }
  81.372 +   else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  81.373 +   {
  81.374 +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  81.375 +      char umsg[50];
  81.376 +
  81.377 +      png_snprintf(umsg, 50, "Unknown zTXt compression type %d", comp_type);
  81.378 +      png_warning(png_ptr, umsg);
  81.379 +#else
  81.380 +      png_warning(png_ptr, "Unknown zTXt compression type");
  81.381 +#endif
  81.382 +
  81.383 +      *(png_ptr->chunkdata + prefix_size) = 0x00;
  81.384 +      *newlength = prefix_size;
  81.385 +   }
  81.386 +}
  81.387 +#endif
  81.388 +
  81.389 +/* read and check the IDHR chunk */
  81.390 +void /* PRIVATE */
  81.391 +png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  81.392 +{
  81.393 +   png_byte buf[13];
  81.394 +   png_uint_32 width, height;
  81.395 +   int bit_depth, color_type, compression_type, filter_type;
  81.396 +   int interlace_type;
  81.397 +
  81.398 +   png_debug(1, "in png_handle_IHDR\n");
  81.399 +
  81.400 +   if (png_ptr->mode & PNG_HAVE_IHDR)
  81.401 +      png_error(png_ptr, "Out of place IHDR");
  81.402 +
  81.403 +   /* check the length */
  81.404 +   if (length != 13)
  81.405 +      png_error(png_ptr, "Invalid IHDR chunk");
  81.406 +
  81.407 +   png_ptr->mode |= PNG_HAVE_IHDR;
  81.408 +
  81.409 +   png_crc_read(png_ptr, buf, 13);
  81.410 +   png_crc_finish(png_ptr, 0);
  81.411 +
  81.412 +   width = png_get_uint_31(png_ptr, buf);
  81.413 +   height = png_get_uint_31(png_ptr, buf + 4);
  81.414 +   bit_depth = buf[8];
  81.415 +   color_type = buf[9];
  81.416 +   compression_type = buf[10];
  81.417 +   filter_type = buf[11];
  81.418 +   interlace_type = buf[12];
  81.419 +
  81.420 +   /* set internal variables */
  81.421 +   png_ptr->width = width;
  81.422 +   png_ptr->height = height;
  81.423 +   png_ptr->bit_depth = (png_byte)bit_depth;
  81.424 +   png_ptr->interlaced = (png_byte)interlace_type;
  81.425 +   png_ptr->color_type = (png_byte)color_type;
  81.426 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
  81.427 +   png_ptr->filter_type = (png_byte)filter_type;
  81.428 +#endif
  81.429 +   png_ptr->compression_type = (png_byte)compression_type;
  81.430 +
  81.431 +   /* find number of channels */
  81.432 +   switch (png_ptr->color_type)
  81.433 +   {
  81.434 +      case PNG_COLOR_TYPE_GRAY:
  81.435 +      case PNG_COLOR_TYPE_PALETTE:
  81.436 +         png_ptr->channels = 1;
  81.437 +         break;
  81.438 +      case PNG_COLOR_TYPE_RGB:
  81.439 +         png_ptr->channels = 3;
  81.440 +         break;
  81.441 +      case PNG_COLOR_TYPE_GRAY_ALPHA:
  81.442 +         png_ptr->channels = 2;
  81.443 +         break;
  81.444 +      case PNG_COLOR_TYPE_RGB_ALPHA:
  81.445 +         png_ptr->channels = 4;
  81.446 +         break;
  81.447 +   }
  81.448 +
  81.449 +   /* set up other useful info */
  81.450 +   png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  81.451 +   png_ptr->channels);
  81.452 +   png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width);
  81.453 +   png_debug1(3, "bit_depth = %d\n", png_ptr->bit_depth);
  81.454 +   png_debug1(3, "channels = %d\n", png_ptr->channels);
  81.455 +   png_debug1(3, "rowbytes = %lu\n", png_ptr->rowbytes);
  81.456 +   png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  81.457 +      color_type, interlace_type, compression_type, filter_type);
  81.458 +}
  81.459 +
  81.460 +/* read and check the palette */
  81.461 +void /* PRIVATE */
  81.462 +png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  81.463 +{
  81.464 +   png_color palette[PNG_MAX_PALETTE_LENGTH];
  81.465 +   int num, i;
  81.466 +#ifndef PNG_NO_POINTER_INDEXING
  81.467 +   png_colorp pal_ptr;
  81.468 +#endif
  81.469 +
  81.470 +   png_debug(1, "in png_handle_PLTE\n");
  81.471 +
  81.472 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
  81.473 +      png_error(png_ptr, "Missing IHDR before PLTE");
  81.474 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
  81.475 +   {
  81.476 +      png_warning(png_ptr, "Invalid PLTE after IDAT");
  81.477 +      png_crc_finish(png_ptr, length);
  81.478 +      return;
  81.479 +   }
  81.480 +   else if (png_ptr->mode & PNG_HAVE_PLTE)
  81.481 +      png_error(png_ptr, "Duplicate PLTE chunk");
  81.482 +
  81.483 +   png_ptr->mode |= PNG_HAVE_PLTE;
  81.484 +
  81.485 +   if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  81.486 +   {
  81.487 +      png_warning(png_ptr,
  81.488 +        "Ignoring PLTE chunk in grayscale PNG");
  81.489 +      png_crc_finish(png_ptr, length);
  81.490 +      return;
  81.491 +   }
  81.492 +#if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  81.493 +   if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  81.494 +   {
  81.495 +      png_crc_finish(png_ptr, length);
  81.496 +      return;
  81.497 +   }
  81.498 +#endif
  81.499 +
  81.500 +   if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  81.501 +   {
  81.502 +      if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  81.503 +      {
  81.504 +         png_warning(png_ptr, "Invalid palette chunk");
  81.505 +         png_crc_finish(png_ptr, length);
  81.506 +         return;
  81.507 +      }
  81.508 +      else
  81.509 +      {
  81.510 +         png_error(png_ptr, "Invalid palette chunk");
  81.511 +      }
  81.512 +   }
  81.513 +
  81.514 +   num = (int)length / 3;
  81.515 +
  81.516 +#ifndef PNG_NO_POINTER_INDEXING
  81.517 +   for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  81.518 +   {
  81.519 +      png_byte buf[3];
  81.520 +
  81.521 +      png_crc_read(png_ptr, buf, 3);
  81.522 +      pal_ptr->red = buf[0];
  81.523 +      pal_ptr->green = buf[1];
  81.524 +      pal_ptr->blue = buf[2];
  81.525 +   }
  81.526 +#else
  81.527 +   for (i = 0; i < num; i++)
  81.528 +   {
  81.529 +      png_byte buf[3];
  81.530 +
  81.531 +      png_crc_read(png_ptr, buf, 3);
  81.532 +      /* don't depend upon png_color being any order */
  81.533 +      palette[i].red = buf[0];
  81.534 +      palette[i].green = buf[1];
  81.535 +      palette[i].blue = buf[2];
  81.536 +   }
  81.537 +#endif
  81.538 +
  81.539 +   /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  81.540 +      whatever the normal CRC configuration tells us.  However, if we
  81.541 +      have an RGB image, the PLTE can be considered ancillary, so
  81.542 +      we will act as though it is. */
  81.543 +#if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  81.544 +   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  81.545 +#endif
  81.546 +   {
  81.547 +      png_crc_finish(png_ptr, 0);
  81.548 +   }
  81.549 +#if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  81.550 +   else if (png_crc_error(png_ptr))  /* Only if we have a CRC error */
  81.551 +   {
  81.552 +      /* If we don't want to use the data from an ancillary chunk,
  81.553 +         we have two options: an error abort, or a warning and we
  81.554 +         ignore the data in this chunk (which should be OK, since
  81.555 +         it's considered ancillary for a RGB or RGBA image). */
  81.556 +      if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  81.557 +      {
  81.558 +         if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  81.559 +         {
  81.560 +            png_chunk_error(png_ptr, "CRC error");
  81.561 +         }
  81.562 +         else
  81.563 +         {
  81.564 +            png_chunk_warning(png_ptr, "CRC error");
  81.565 +            return;
  81.566 +         }
  81.567 +      }
  81.568 +      /* Otherwise, we (optionally) emit a warning and use the chunk. */
  81.569 +      else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  81.570 +      {
  81.571 +         png_chunk_warning(png_ptr, "CRC error");
  81.572 +      }
  81.573 +   }
  81.574 +#endif
  81.575 +
  81.576 +   png_set_PLTE(png_ptr, info_ptr, palette, num);
  81.577 +
  81.578 +#if defined(PNG_READ_tRNS_SUPPORTED)
  81.579 +   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  81.580 +   {
  81.581 +      if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  81.582 +      {
  81.583 +         if (png_ptr->num_trans > (png_uint_16)num)
  81.584 +         {
  81.585 +            png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  81.586 +            png_ptr->num_trans = (png_uint_16)num;
  81.587 +         }
  81.588 +         if (info_ptr->num_trans > (png_uint_16)num)
  81.589 +         {
  81.590 +            png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  81.591 +            info_ptr->num_trans = (png_uint_16)num;
  81.592 +         }
  81.593 +      }
  81.594 +   }
  81.595 +#endif
  81.596 +
  81.597 +}
  81.598 +
  81.599 +void /* PRIVATE */
  81.600 +png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  81.601 +{
  81.602 +   png_debug(1, "in png_handle_IEND\n");
  81.603 +
  81.604 +   if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  81.605 +   {
  81.606 +      png_error(png_ptr, "No image in file");
  81.607 +   }
  81.608 +
  81.609 +   png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  81.610 +
  81.611 +   if (length != 0)
  81.612 +   {
  81.613 +      png_warning(png_ptr, "Incorrect IEND chunk length");
  81.614 +   }
  81.615 +   png_crc_finish(png_ptr, length);
  81.616 +
  81.617 +   info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  81.618 +}
  81.619 +
  81.620 +#if defined(PNG_READ_gAMA_SUPPORTED)
  81.621 +void /* PRIVATE */
  81.622 +png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  81.623 +{
  81.624 +   png_fixed_point igamma;
  81.625 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  81.626 +   float file_gamma;
  81.627 +#endif
  81.628 +   png_byte buf[4];
  81.629 +
  81.630 +   png_debug(1, "in png_handle_gAMA\n");
  81.631 +
  81.632 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
  81.633 +      png_error(png_ptr, "Missing IHDR before gAMA");
  81.634 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
  81.635 +   {
  81.636 +      png_warning(png_ptr, "Invalid gAMA after IDAT");
  81.637 +      png_crc_finish(png_ptr, length);
  81.638 +      return;
  81.639 +   }
  81.640 +   else if (png_ptr->mode & PNG_HAVE_PLTE)
  81.641 +      /* Should be an error, but we can cope with it */
  81.642 +      png_warning(png_ptr, "Out of place gAMA chunk");
  81.643 +
  81.644 +   if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  81.645 +#if defined(PNG_READ_sRGB_SUPPORTED)
  81.646 +      && !(info_ptr->valid & PNG_INFO_sRGB)
  81.647 +#endif
  81.648 +      )
  81.649 +   {
  81.650 +      png_warning(png_ptr, "Duplicate gAMA chunk");
  81.651 +      png_crc_finish(png_ptr, length);
  81.652 +      return;
  81.653 +   }
  81.654 +
  81.655 +   if (length != 4)
  81.656 +   {
  81.657 +      png_warning(png_ptr, "Incorrect gAMA chunk length");
  81.658 +      png_crc_finish(png_ptr, length);
  81.659 +      return;
  81.660 +   }
  81.661 +
  81.662 +   png_crc_read(png_ptr, buf, 4);
  81.663 +   if (png_crc_finish(png_ptr, 0))
  81.664 +      return;
  81.665 +
  81.666 +   igamma = (png_fixed_point)png_get_uint_32(buf);
  81.667 +   /* check for zero gamma */
  81.668 +   if (igamma == 0)
  81.669 +      {
  81.670 +         png_warning(png_ptr,
  81.671 +           "Ignoring gAMA chunk with gamma=0");
  81.672 +         return;
  81.673 +      }
  81.674 +
  81.675 +#if defined(PNG_READ_sRGB_SUPPORTED)
  81.676 +   if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  81.677 +      if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  81.678 +      {
  81.679 +         png_warning(png_ptr,
  81.680 +           "Ignoring incorrect gAMA value when sRGB is also present");
  81.681 +#ifndef PNG_NO_CONSOLE_IO
  81.682 +         fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  81.683 +#endif
  81.684 +         return;
  81.685 +      }
  81.686 +#endif /* PNG_READ_sRGB_SUPPORTED */
  81.687 +
  81.688 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  81.689 +   file_gamma = (float)igamma / (float)100000.0;
  81.690 +#  ifdef PNG_READ_GAMMA_SUPPORTED
  81.691 +     png_ptr->gamma = file_gamma;
  81.692 +#  endif
  81.693 +     png_set_gAMA(png_ptr, info_ptr, file_gamma);
  81.694 +#endif
  81.695 +#ifdef PNG_FIXED_POINT_SUPPORTED
  81.696 +   png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  81.697 +#endif
  81.698 +}
  81.699 +#endif
  81.700 +
  81.701 +#if defined(PNG_READ_sBIT_SUPPORTED)
  81.702 +void /* PRIVATE */
  81.703 +png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  81.704 +{
  81.705 +   png_size_t truelen;
  81.706 +   png_byte buf[4];
  81.707 +
  81.708 +   png_debug(1, "in png_handle_sBIT\n");
  81.709 +
  81.710 +   buf[0] = buf[1] = buf[2] = buf[3] = 0;
  81.711 +
  81.712 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
  81.713 +      png_error(png_ptr, "Missing IHDR before sBIT");
  81.714 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
  81.715 +   {
  81.716 +      png_warning(png_ptr, "Invalid sBIT after IDAT");
  81.717 +      png_crc_finish(png_ptr, length);
  81.718 +      return;
  81.719 +   }
  81.720 +   else if (png_ptr->mode & PNG_HAVE_PLTE)
  81.721 +   {
  81.722 +      /* Should be an error, but we can cope with it */
  81.723 +      png_warning(png_ptr, "Out of place sBIT chunk");
  81.724 +   }
  81.725 +   if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  81.726 +   {
  81.727 +      png_warning(png_ptr, "Duplicate sBIT chunk");
  81.728 +      png_crc_finish(png_ptr, length);
  81.729 +      return;
  81.730 +   }
  81.731 +
  81.732 +   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  81.733 +      truelen = 3;
  81.734 +   else
  81.735 +      truelen = (png_size_t)png_ptr->channels;
  81.736 +
  81.737 +   if (length != truelen || length > 4)
  81.738 +   {
  81.739 +      png_warning(png_ptr, "Incorrect sBIT chunk length");
  81.740 +      png_crc_finish(png_ptr, length);
  81.741 +      return;
  81.742 +   }
  81.743 +
  81.744 +   png_crc_read(png_ptr, buf, truelen);
  81.745 +   if (png_crc_finish(png_ptr, 0))
  81.746 +      return;
  81.747 +
  81.748 +   if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  81.749 +   {
  81.750 +      png_ptr->sig_bit.red = buf[0];
  81.751 +      png_ptr->sig_bit.green = buf[1];
  81.752 +      png_ptr->sig_bit.blue = buf[2];
  81.753 +      png_ptr->sig_bit.alpha = buf[3];
  81.754 +   }
  81.755 +   else
  81.756 +   {
  81.757 +      png_ptr->sig_bit.gray = buf[0];
  81.758 +      png_ptr->sig_bit.red = buf[0];
  81.759 +      png_ptr->sig_bit.green = buf[0];
  81.760 +      png_ptr->sig_bit.blue = buf[0];
  81.761 +      png_ptr->sig_bit.alpha = buf[1];
  81.762 +   }
  81.763 +   png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  81.764 +}
  81.765 +#endif
  81.766 +
  81.767 +#if defined(PNG_READ_cHRM_SUPPORTED)
  81.768 +void /* PRIVATE */
  81.769 +png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  81.770 +{
  81.771 +   png_byte buf[32];
  81.772 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  81.773 +   float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  81.774 +#endif
  81.775 +   png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  81.776 +      int_y_green, int_x_blue, int_y_blue;
  81.777 +
  81.778 +   png_uint_32 uint_x, uint_y;
  81.779 +
  81.780 +   png_debug(1, "in png_handle_cHRM\n");
  81.781 +
  81.782 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
  81.783 +      png_error(png_ptr, "Missing IHDR before cHRM");
  81.784 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
  81.785 +   {
  81.786 +      png_warning(png_ptr, "Invalid cHRM after IDAT");
  81.787 +      png_crc_finish(png_ptr, length);
  81.788 +      return;
  81.789 +   }
  81.790 +   else if (png_ptr->mode & PNG_HAVE_PLTE)
  81.791 +      /* Should be an error, but we can cope with it */
  81.792 +      png_warning(png_ptr, "Missing PLTE before cHRM");
  81.793 +
  81.794 +   if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  81.795 +#if defined(PNG_READ_sRGB_SUPPORTED)
  81.796 +      && !(info_ptr->valid & PNG_INFO_sRGB)
  81.797 +#endif
  81.798 +      )
  81.799 +   {
  81.800 +      png_warning(png_ptr, "Duplicate cHRM chunk");
  81.801 +      png_crc_finish(png_ptr, length);
  81.802 +      return;
  81.803 +   }
  81.804 +
  81.805 +   if (length != 32)
  81.806 +   {
  81.807 +      png_warning(png_ptr, "Incorrect cHRM chunk length");
  81.808 +      png_crc_finish(png_ptr, length);
  81.809 +      return;
  81.810 +   }
  81.811 +
  81.812 +   png_crc_read(png_ptr, buf, 32);
  81.813 +   if (png_crc_finish(png_ptr, 0))
  81.814 +      return;
  81.815 +
  81.816 +   uint_x = png_get_uint_32(buf);
  81.817 +   uint_y = png_get_uint_32(buf + 4);
  81.818 +   if (uint_x > 80000L || uint_y > 80000L ||
  81.819 +      uint_x + uint_y > 100000L)
  81.820 +   {
  81.821 +      png_warning(png_ptr, "Invalid cHRM white point");
  81.822 +      return;
  81.823 +   }
  81.824 +   int_x_white = (png_fixed_point)uint_x;
  81.825 +   int_y_white = (png_fixed_point)uint_y;
  81.826 +
  81.827 +   uint_x = png_get_uint_32(buf + 8);
  81.828 +   uint_y = png_get_uint_32(buf + 12);
  81.829 +   if (uint_x + uint_y > 100000L)
  81.830 +   {
  81.831 +      png_warning(png_ptr, "Invalid cHRM red point");
  81.832 +      return;
  81.833 +   }
  81.834 +   int_x_red = (png_fixed_point)uint_x;
  81.835 +   int_y_red = (png_fixed_point)uint_y;
  81.836 +
  81.837 +   uint_x = png_get_uint_32(buf + 16);
  81.838 +   uint_y = png_get_uint_32(buf + 20);
  81.839 +   if (uint_x + uint_y > 100000L)
  81.840 +   {
  81.841 +      png_warning(png_ptr, "Invalid cHRM green point");
  81.842 +      return;
  81.843 +   }
  81.844 +   int_x_green = (png_fixed_point)uint_x;
  81.845 +   int_y_green = (png_fixed_point)uint_y;
  81.846 +
  81.847 +   uint_x = png_get_uint_32(buf + 24);
  81.848 +   uint_y = png_get_uint_32(buf + 28);
  81.849 +   if (uint_x + uint_y > 100000L)
  81.850 +   {
  81.851 +      png_warning(png_ptr, "Invalid cHRM blue point");
  81.852 +      return;
  81.853 +   }
  81.854 +   int_x_blue = (png_fixed_point)uint_x;
  81.855 +   int_y_blue = (png_fixed_point)uint_y;
  81.856 +
  81.857 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  81.858 +   white_x = (float)int_x_white / (float)100000.0;
  81.859 +   white_y = (float)int_y_white / (float)100000.0;
  81.860 +   red_x   = (float)int_x_red   / (float)100000.0;
  81.861 +   red_y   = (float)int_y_red   / (float)100000.0;
  81.862 +   green_x = (float)int_x_green / (float)100000.0;
  81.863 +   green_y = (float)int_y_green / (float)100000.0;
  81.864 +   blue_x  = (float)int_x_blue  / (float)100000.0;
  81.865 +   blue_y  = (float)int_y_blue  / (float)100000.0;
  81.866 +#endif
  81.867 +
  81.868 +#if defined(PNG_READ_sRGB_SUPPORTED)
  81.869 +   if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  81.870 +      {
  81.871 +      if (PNG_OUT_OF_RANGE(int_x_white, 31270,  1000) ||
  81.872 +          PNG_OUT_OF_RANGE(int_y_white, 32900,  1000) ||
  81.873 +          PNG_OUT_OF_RANGE(int_x_red,   64000L, 1000) ||
  81.874 +          PNG_OUT_OF_RANGE(int_y_red,   33000,  1000) ||
  81.875 +          PNG_OUT_OF_RANGE(int_x_green, 30000,  1000) ||
  81.876 +          PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  81.877 +          PNG_OUT_OF_RANGE(int_x_blue,  15000,  1000) ||
  81.878 +          PNG_OUT_OF_RANGE(int_y_blue,   6000,  1000))
  81.879 +         {
  81.880 +            png_warning(png_ptr,
  81.881 +              "Ignoring incorrect cHRM value when sRGB is also present");
  81.882 +#ifndef PNG_NO_CONSOLE_IO
  81.883 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  81.884 +            fprintf(stderr, "wx=%f, wy=%f, rx=%f, ry=%f\n",
  81.885 +               white_x, white_y, red_x, red_y);
  81.886 +            fprintf(stderr, "gx=%f, gy=%f, bx=%f, by=%f\n",
  81.887 +               green_x, green_y, blue_x, blue_y);
  81.888 +#else
  81.889 +            fprintf(stderr, "wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  81.890 +               int_x_white, int_y_white, int_x_red, int_y_red);
  81.891 +            fprintf(stderr, "gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  81.892 +               int_x_green, int_y_green, int_x_blue, int_y_blue);
  81.893 +#endif
  81.894 +#endif /* PNG_NO_CONSOLE_IO */
  81.895 +         }
  81.896 +         return;
  81.897 +      }
  81.898 +#endif /* PNG_READ_sRGB_SUPPORTED */
  81.899 +
  81.900 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  81.901 +   png_set_cHRM(png_ptr, info_ptr,
  81.902 +      white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  81.903 +#endif
  81.904 +#ifdef PNG_FIXED_POINT_SUPPORTED
  81.905 +   png_set_cHRM_fixed(png_ptr, info_ptr,
  81.906 +      int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  81.907 +      int_y_green, int_x_blue, int_y_blue);
  81.908 +#endif
  81.909 +}
  81.910 +#endif
  81.911 +
  81.912 +#if defined(PNG_READ_sRGB_SUPPORTED)
  81.913 +void /* PRIVATE */
  81.914 +png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  81.915 +{
  81.916 +   int intent;
  81.917 +   png_byte buf[1];
  81.918 +
  81.919 +   png_debug(1, "in png_handle_sRGB\n");
  81.920 +
  81.921 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
  81.922 +      png_error(png_ptr, "Missing IHDR before sRGB");
  81.923 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
  81.924 +   {
  81.925 +      png_warning(png_ptr, "Invalid sRGB after IDAT");
  81.926 +      png_crc_finish(png_ptr, length);
  81.927 +      return;
  81.928 +   }
  81.929 +   else if (png_ptr->mode & PNG_HAVE_PLTE)
  81.930 +      /* Should be an error, but we can cope with it */
  81.931 +      png_warning(png_ptr, "Out of place sRGB chunk");
  81.932 +
  81.933 +   if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  81.934 +   {
  81.935 +      png_warning(png_ptr, "Duplicate sRGB chunk");
  81.936 +      png_crc_finish(png_ptr, length);
  81.937 +      return;
  81.938 +   }
  81.939 +
  81.940 +   if (length != 1)
  81.941 +   {
  81.942 +      png_warning(png_ptr, "Incorrect sRGB chunk length");
  81.943 +      png_crc_finish(png_ptr, length);
  81.944 +      return;
  81.945 +   }
  81.946 +
  81.947 +   png_crc_read(png_ptr, buf, 1);
  81.948 +   if (png_crc_finish(png_ptr, 0))
  81.949 +      return;
  81.950 +
  81.951 +   intent = buf[0];
  81.952 +   /* check for bad intent */
  81.953 +   if (intent >= PNG_sRGB_INTENT_LAST)
  81.954 +   {
  81.955 +      png_warning(png_ptr, "Unknown sRGB intent");
  81.956 +      return;
  81.957 +   }
  81.958 +
  81.959 +#if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  81.960 +   if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  81.961 +   {
  81.962 +   png_fixed_point igamma;
  81.963 +#ifdef PNG_FIXED_POINT_SUPPORTED
  81.964 +      igamma=info_ptr->int_gamma;
  81.965 +#else
  81.966 +#  ifdef PNG_FLOATING_POINT_SUPPORTED
  81.967 +      igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  81.968 +#  endif
  81.969 +#endif
  81.970 +      if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  81.971 +      {
  81.972 +         png_warning(png_ptr,
  81.973 +           "Ignoring incorrect gAMA value when sRGB is also present");
  81.974 +#ifndef PNG_NO_CONSOLE_IO
  81.975 +#  ifdef PNG_FIXED_POINT_SUPPORTED
  81.976 +         fprintf(stderr, "incorrect gamma=(%d/100000)\n",
  81.977 +            (int)png_ptr->int_gamma);
  81.978 +#  else
  81.979 +#    ifdef PNG_FLOATING_POINT_SUPPORTED
  81.980 +         fprintf(stderr, "incorrect gamma=%f\n", png_ptr->gamma);
  81.981 +#    endif
  81.982 +#  endif
  81.983 +#endif
  81.984 +      }
  81.985 +   }
  81.986 +#endif /* PNG_READ_gAMA_SUPPORTED */
  81.987 +
  81.988 +#ifdef PNG_READ_cHRM_SUPPORTED
  81.989 +#ifdef PNG_FIXED_POINT_SUPPORTED
  81.990 +   if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  81.991 +      if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270,  1000) ||
  81.992 +          PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900,  1000) ||
  81.993 +          PNG_OUT_OF_RANGE(info_ptr->int_x_red,   64000L, 1000) ||
  81.994 +          PNG_OUT_OF_RANGE(info_ptr->int_y_red,   33000,  1000) ||
  81.995 +          PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000,  1000) ||
  81.996 +          PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  81.997 +          PNG_OUT_OF_RANGE(info_ptr->int_x_blue,  15000,  1000) ||
  81.998 +          PNG_OUT_OF_RANGE(info_ptr->int_y_blue,   6000,  1000))
  81.999 +         {
 81.1000 +            png_warning(png_ptr,
 81.1001 +              "Ignoring incorrect cHRM value when sRGB is also present");
 81.1002 +         }
 81.1003 +#endif /* PNG_FIXED_POINT_SUPPORTED */
 81.1004 +#endif /* PNG_READ_cHRM_SUPPORTED */
 81.1005 +
 81.1006 +   png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
 81.1007 +}
 81.1008 +#endif /* PNG_READ_sRGB_SUPPORTED */
 81.1009 +
 81.1010 +#if defined(PNG_READ_iCCP_SUPPORTED)
 81.1011 +void /* PRIVATE */
 81.1012 +png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1013 +/* Note: this does not properly handle chunks that are > 64K under DOS */
 81.1014 +{
 81.1015 +   png_byte compression_type;
 81.1016 +   png_bytep pC;
 81.1017 +   png_charp profile;
 81.1018 +   png_uint_32 skip = 0;
 81.1019 +   png_uint_32 profile_size, profile_length;
 81.1020 +   png_size_t slength, prefix_length, data_length;
 81.1021 +
 81.1022 +   png_debug(1, "in png_handle_iCCP\n");
 81.1023 +
 81.1024 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1025 +      png_error(png_ptr, "Missing IHDR before iCCP");
 81.1026 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1027 +   {
 81.1028 +      png_warning(png_ptr, "Invalid iCCP after IDAT");
 81.1029 +      png_crc_finish(png_ptr, length);
 81.1030 +      return;
 81.1031 +   }
 81.1032 +   else if (png_ptr->mode & PNG_HAVE_PLTE)
 81.1033 +      /* Should be an error, but we can cope with it */
 81.1034 +      png_warning(png_ptr, "Out of place iCCP chunk");
 81.1035 +
 81.1036 +   if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
 81.1037 +   {
 81.1038 +      png_warning(png_ptr, "Duplicate iCCP chunk");
 81.1039 +      png_crc_finish(png_ptr, length);
 81.1040 +      return;
 81.1041 +   }
 81.1042 +
 81.1043 +#ifdef PNG_MAX_MALLOC_64K
 81.1044 +   if (length > (png_uint_32)65535L)
 81.1045 +   {
 81.1046 +      png_warning(png_ptr, "iCCP chunk too large to fit in memory");
 81.1047 +      skip = length - (png_uint_32)65535L;
 81.1048 +      length = (png_uint_32)65535L;
 81.1049 +   }
 81.1050 +#endif
 81.1051 +
 81.1052 +   png_free(png_ptr, png_ptr->chunkdata);
 81.1053 +   png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
 81.1054 +   slength = (png_size_t)length;
 81.1055 +   png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength);
 81.1056 +
 81.1057 +   if (png_crc_finish(png_ptr, skip))
 81.1058 +   {
 81.1059 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1060 +      png_ptr->chunkdata = NULL;
 81.1061 +      return;
 81.1062 +   }
 81.1063 +
 81.1064 +   png_ptr->chunkdata[slength] = 0x00;
 81.1065 +
 81.1066 +   for (profile = png_ptr->chunkdata; *profile; profile++)
 81.1067 +      /* empty loop to find end of name */ ;
 81.1068 +
 81.1069 +   ++profile;
 81.1070 +
 81.1071 +   /* there should be at least one zero (the compression type byte)
 81.1072 +      following the separator, and we should be on it  */
 81.1073 +   if ( profile >= png_ptr->chunkdata + slength - 1)
 81.1074 +   {
 81.1075 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1076 +      png_ptr->chunkdata = NULL;
 81.1077 +      png_warning(png_ptr, "Malformed iCCP chunk");
 81.1078 +      return;
 81.1079 +   }
 81.1080 +
 81.1081 +   /* compression_type should always be zero */
 81.1082 +   compression_type = *profile++;
 81.1083 +   if (compression_type)
 81.1084 +   {
 81.1085 +      png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
 81.1086 +      compression_type = 0x00;  /* Reset it to zero (libpng-1.0.6 through 1.0.8
 81.1087 +                                 wrote nonzero) */
 81.1088 +   }
 81.1089 +
 81.1090 +   prefix_length = profile - png_ptr->chunkdata;
 81.1091 +   png_decompress_chunk(png_ptr, compression_type,
 81.1092 +     slength, prefix_length, &data_length);
 81.1093 +
 81.1094 +   profile_length = data_length - prefix_length;
 81.1095 +
 81.1096 +   if ( prefix_length > data_length || profile_length < 4)
 81.1097 +   {
 81.1098 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1099 +      png_ptr->chunkdata = NULL;
 81.1100 +      png_warning(png_ptr, "Profile size field missing from iCCP chunk");
 81.1101 +      return;
 81.1102 +   }
 81.1103 +
 81.1104 +   /* Check the profile_size recorded in the first 32 bits of the ICC profile */
 81.1105 +   pC = (png_bytep)(png_ptr->chunkdata + prefix_length);
 81.1106 +   profile_size = ((*(pC    ))<<24) |
 81.1107 +                  ((*(pC + 1))<<16) |
 81.1108 +                  ((*(pC + 2))<< 8) |
 81.1109 +                  ((*(pC + 3))    );
 81.1110 +
 81.1111 +   if (profile_size < profile_length)
 81.1112 +      profile_length = profile_size;
 81.1113 +
 81.1114 +   if (profile_size > profile_length)
 81.1115 +   {
 81.1116 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1117 +      png_ptr->chunkdata = NULL;
 81.1118 +      png_warning(png_ptr, "Ignoring truncated iCCP profile.");
 81.1119 +      return;
 81.1120 +   }
 81.1121 +
 81.1122 +   png_set_iCCP(png_ptr, info_ptr, png_ptr->chunkdata,
 81.1123 +     compression_type, png_ptr->chunkdata + prefix_length, profile_length);
 81.1124 +   png_free(png_ptr, png_ptr->chunkdata);
 81.1125 +   png_ptr->chunkdata = NULL;
 81.1126 +}
 81.1127 +#endif /* PNG_READ_iCCP_SUPPORTED */
 81.1128 +
 81.1129 +#if defined(PNG_READ_sPLT_SUPPORTED)
 81.1130 +void /* PRIVATE */
 81.1131 +png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1132 +/* Note: this does not properly handle chunks that are > 64K under DOS */
 81.1133 +{
 81.1134 +   png_bytep entry_start;
 81.1135 +   png_sPLT_t new_palette;
 81.1136 +#ifdef PNG_NO_POINTER_INDEXING
 81.1137 +   png_sPLT_entryp pp;
 81.1138 +#endif
 81.1139 +   int data_length, entry_size, i;
 81.1140 +   png_uint_32 skip = 0;
 81.1141 +   png_size_t slength;
 81.1142 +
 81.1143 +   png_debug(1, "in png_handle_sPLT\n");
 81.1144 +
 81.1145 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1146 +      png_error(png_ptr, "Missing IHDR before sPLT");
 81.1147 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1148 +   {
 81.1149 +      png_warning(png_ptr, "Invalid sPLT after IDAT");
 81.1150 +      png_crc_finish(png_ptr, length);
 81.1151 +      return;
 81.1152 +   }
 81.1153 +
 81.1154 +#ifdef PNG_MAX_MALLOC_64K
 81.1155 +   if (length > (png_uint_32)65535L)
 81.1156 +   {
 81.1157 +      png_warning(png_ptr, "sPLT chunk too large to fit in memory");
 81.1158 +      skip = length - (png_uint_32)65535L;
 81.1159 +      length = (png_uint_32)65535L;
 81.1160 +   }
 81.1161 +#endif
 81.1162 +
 81.1163 +   png_free(png_ptr, png_ptr->chunkdata);
 81.1164 +   png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
 81.1165 +   slength = (png_size_t)length;
 81.1166 +   png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength);
 81.1167 +
 81.1168 +   if (png_crc_finish(png_ptr, skip))
 81.1169 +   {
 81.1170 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1171 +      png_ptr->chunkdata = NULL;
 81.1172 +      return;
 81.1173 +   }
 81.1174 +
 81.1175 +   png_ptr->chunkdata[slength] = 0x00;
 81.1176 +
 81.1177 +   for (entry_start = (png_bytep)png_ptr->chunkdata; *entry_start; entry_start++)
 81.1178 +      /* empty loop to find end of name */ ;
 81.1179 +   ++entry_start;
 81.1180 +
 81.1181 +   /* a sample depth should follow the separator, and we should be on it  */
 81.1182 +   if (entry_start > (png_bytep)png_ptr->chunkdata + slength - 2)
 81.1183 +   {
 81.1184 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1185 +      png_ptr->chunkdata = NULL;
 81.1186 +      png_warning(png_ptr, "malformed sPLT chunk");
 81.1187 +      return;
 81.1188 +   }
 81.1189 +
 81.1190 +   new_palette.depth = *entry_start++;
 81.1191 +   entry_size = (new_palette.depth == 8 ? 6 : 10);
 81.1192 +   data_length = (slength - (entry_start - (png_bytep)png_ptr->chunkdata));
 81.1193 +
 81.1194 +   /* integrity-check the data length */
 81.1195 +   if (data_length % entry_size)
 81.1196 +   {
 81.1197 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1198 +      png_ptr->chunkdata = NULL;
 81.1199 +      png_warning(png_ptr, "sPLT chunk has bad length");
 81.1200 +      return;
 81.1201 +   }
 81.1202 +
 81.1203 +   new_palette.nentries = (png_int_32) ( data_length / entry_size);
 81.1204 +   if ((png_uint_32) new_palette.nentries >
 81.1205 +       (png_uint_32) (PNG_SIZE_MAX / png_sizeof(png_sPLT_entry)))
 81.1206 +   {
 81.1207 +       png_warning(png_ptr, "sPLT chunk too long");
 81.1208 +       return;
 81.1209 +   }
 81.1210 +   new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
 81.1211 +       png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
 81.1212 +   if (new_palette.entries == NULL)
 81.1213 +   {
 81.1214 +       png_warning(png_ptr, "sPLT chunk requires too much memory");
 81.1215 +       return;
 81.1216 +   }
 81.1217 +
 81.1218 +#ifndef PNG_NO_POINTER_INDEXING
 81.1219 +   for (i = 0; i < new_palette.nentries; i++)
 81.1220 +   {
 81.1221 +      png_sPLT_entryp pp = new_palette.entries + i;
 81.1222 +
 81.1223 +      if (new_palette.depth == 8)
 81.1224 +      {
 81.1225 +          pp->red = *entry_start++;
 81.1226 +          pp->green = *entry_start++;
 81.1227 +          pp->blue = *entry_start++;
 81.1228 +          pp->alpha = *entry_start++;
 81.1229 +      }
 81.1230 +      else
 81.1231 +      {
 81.1232 +          pp->red   = png_get_uint_16(entry_start); entry_start += 2;
 81.1233 +          pp->green = png_get_uint_16(entry_start); entry_start += 2;
 81.1234 +          pp->blue  = png_get_uint_16(entry_start); entry_start += 2;
 81.1235 +          pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
 81.1236 +      }
 81.1237 +      pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
 81.1238 +   }
 81.1239 +#else
 81.1240 +   pp = new_palette.entries;
 81.1241 +   for (i = 0; i < new_palette.nentries; i++)
 81.1242 +   {
 81.1243 +
 81.1244 +      if (new_palette.depth == 8)
 81.1245 +      {
 81.1246 +          pp[i].red   = *entry_start++;
 81.1247 +          pp[i].green = *entry_start++;
 81.1248 +          pp[i].blue  = *entry_start++;
 81.1249 +          pp[i].alpha = *entry_start++;
 81.1250 +      }
 81.1251 +      else
 81.1252 +      {
 81.1253 +          pp[i].red   = png_get_uint_16(entry_start); entry_start += 2;
 81.1254 +          pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
 81.1255 +          pp[i].blue  = png_get_uint_16(entry_start); entry_start += 2;
 81.1256 +          pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
 81.1257 +      }
 81.1258 +      pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
 81.1259 +   }
 81.1260 +#endif
 81.1261 +
 81.1262 +   /* discard all chunk data except the name and stash that */
 81.1263 +   new_palette.name = png_ptr->chunkdata;
 81.1264 +
 81.1265 +   png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
 81.1266 +
 81.1267 +   png_free(png_ptr, png_ptr->chunkdata);
 81.1268 +   png_ptr->chunkdata = NULL;
 81.1269 +   png_free(png_ptr, new_palette.entries);
 81.1270 +}
 81.1271 +#endif /* PNG_READ_sPLT_SUPPORTED */
 81.1272 +
 81.1273 +#if defined(PNG_READ_tRNS_SUPPORTED)
 81.1274 +void /* PRIVATE */
 81.1275 +png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1276 +{
 81.1277 +   png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
 81.1278 +
 81.1279 +   png_debug(1, "in png_handle_tRNS\n");
 81.1280 +
 81.1281 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1282 +      png_error(png_ptr, "Missing IHDR before tRNS");
 81.1283 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1284 +   {
 81.1285 +      png_warning(png_ptr, "Invalid tRNS after IDAT");
 81.1286 +      png_crc_finish(png_ptr, length);
 81.1287 +      return;
 81.1288 +   }
 81.1289 +   else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
 81.1290 +   {
 81.1291 +      png_warning(png_ptr, "Duplicate tRNS chunk");
 81.1292 +      png_crc_finish(png_ptr, length);
 81.1293 +      return;
 81.1294 +   }
 81.1295 +
 81.1296 +   if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
 81.1297 +   {
 81.1298 +      png_byte buf[2];
 81.1299 +
 81.1300 +      if (length != 2)
 81.1301 +      {
 81.1302 +         png_warning(png_ptr, "Incorrect tRNS chunk length");
 81.1303 +         png_crc_finish(png_ptr, length);
 81.1304 +         return;
 81.1305 +      }
 81.1306 +
 81.1307 +      png_crc_read(png_ptr, buf, 2);
 81.1308 +      png_ptr->num_trans = 1;
 81.1309 +      png_ptr->trans_values.gray = png_get_uint_16(buf);
 81.1310 +   }
 81.1311 +   else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
 81.1312 +   {
 81.1313 +      png_byte buf[6];
 81.1314 +
 81.1315 +      if (length != 6)
 81.1316 +      {
 81.1317 +         png_warning(png_ptr, "Incorrect tRNS chunk length");
 81.1318 +         png_crc_finish(png_ptr, length);
 81.1319 +         return;
 81.1320 +      }
 81.1321 +      png_crc_read(png_ptr, buf, (png_size_t)length);
 81.1322 +      png_ptr->num_trans = 1;
 81.1323 +      png_ptr->trans_values.red = png_get_uint_16(buf);
 81.1324 +      png_ptr->trans_values.green = png_get_uint_16(buf + 2);
 81.1325 +      png_ptr->trans_values.blue = png_get_uint_16(buf + 4);
 81.1326 +   }
 81.1327 +   else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 81.1328 +   {
 81.1329 +      if (!(png_ptr->mode & PNG_HAVE_PLTE))
 81.1330 +      {
 81.1331 +         /* Should be an error, but we can cope with it. */
 81.1332 +         png_warning(png_ptr, "Missing PLTE before tRNS");
 81.1333 +      }
 81.1334 +      if (length > (png_uint_32)png_ptr->num_palette ||
 81.1335 +          length > PNG_MAX_PALETTE_LENGTH)
 81.1336 +      {
 81.1337 +         png_warning(png_ptr, "Incorrect tRNS chunk length");
 81.1338 +         png_crc_finish(png_ptr, length);
 81.1339 +         return;
 81.1340 +      }
 81.1341 +      if (length == 0)
 81.1342 +      {
 81.1343 +         png_warning(png_ptr, "Zero length tRNS chunk");
 81.1344 +         png_crc_finish(png_ptr, length);
 81.1345 +         return;
 81.1346 +      }
 81.1347 +      png_crc_read(png_ptr, readbuf, (png_size_t)length);
 81.1348 +      png_ptr->num_trans = (png_uint_16)length;
 81.1349 +   }
 81.1350 +   else
 81.1351 +   {
 81.1352 +      png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
 81.1353 +      png_crc_finish(png_ptr, length);
 81.1354 +      return;
 81.1355 +   }
 81.1356 +
 81.1357 +   if (png_crc_finish(png_ptr, 0))
 81.1358 +   {
 81.1359 +      png_ptr->num_trans = 0;
 81.1360 +      return;
 81.1361 +   }
 81.1362 +
 81.1363 +   png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
 81.1364 +      &(png_ptr->trans_values));
 81.1365 +}
 81.1366 +#endif
 81.1367 +
 81.1368 +#if defined(PNG_READ_bKGD_SUPPORTED)
 81.1369 +void /* PRIVATE */
 81.1370 +png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1371 +{
 81.1372 +   png_size_t truelen;
 81.1373 +   png_byte buf[6];
 81.1374 +
 81.1375 +   png_debug(1, "in png_handle_bKGD\n");
 81.1376 +
 81.1377 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1378 +      png_error(png_ptr, "Missing IHDR before bKGD");
 81.1379 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1380 +   {
 81.1381 +      png_warning(png_ptr, "Invalid bKGD after IDAT");
 81.1382 +      png_crc_finish(png_ptr, length);
 81.1383 +      return;
 81.1384 +   }
 81.1385 +   else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
 81.1386 +            !(png_ptr->mode & PNG_HAVE_PLTE))
 81.1387 +   {
 81.1388 +      png_warning(png_ptr, "Missing PLTE before bKGD");
 81.1389 +      png_crc_finish(png_ptr, length);
 81.1390 +      return;
 81.1391 +   }
 81.1392 +   else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
 81.1393 +   {
 81.1394 +      png_warning(png_ptr, "Duplicate bKGD chunk");
 81.1395 +      png_crc_finish(png_ptr, length);
 81.1396 +      return;
 81.1397 +   }
 81.1398 +
 81.1399 +   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 81.1400 +      truelen = 1;
 81.1401 +   else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
 81.1402 +      truelen = 6;
 81.1403 +   else
 81.1404 +      truelen = 2;
 81.1405 +
 81.1406 +   if (length != truelen)
 81.1407 +   {
 81.1408 +      png_warning(png_ptr, "Incorrect bKGD chunk length");
 81.1409 +      png_crc_finish(png_ptr, length);
 81.1410 +      return;
 81.1411 +   }
 81.1412 +
 81.1413 +   png_crc_read(png_ptr, buf, truelen);
 81.1414 +   if (png_crc_finish(png_ptr, 0))
 81.1415 +      return;
 81.1416 +
 81.1417 +   /* We convert the index value into RGB components so that we can allow
 81.1418 +    * arbitrary RGB values for background when we have transparency, and
 81.1419 +    * so it is easy to determine the RGB values of the background color
 81.1420 +    * from the info_ptr struct. */
 81.1421 +   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 81.1422 +   {
 81.1423 +      png_ptr->background.index = buf[0];
 81.1424 +      if (info_ptr && info_ptr->num_palette)
 81.1425 +      {
 81.1426 +          if (buf[0] > info_ptr->num_palette)
 81.1427 +          {
 81.1428 +             png_warning(png_ptr, "Incorrect bKGD chunk index value");
 81.1429 +             return;
 81.1430 +          }
 81.1431 +          png_ptr->background.red =
 81.1432 +             (png_uint_16)png_ptr->palette[buf[0]].red;
 81.1433 +          png_ptr->background.green =
 81.1434 +             (png_uint_16)png_ptr->palette[buf[0]].green;
 81.1435 +          png_ptr->background.blue =
 81.1436 +             (png_uint_16)png_ptr->palette[buf[0]].blue;
 81.1437 +      }
 81.1438 +   }
 81.1439 +   else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
 81.1440 +   {
 81.1441 +      png_ptr->background.red =
 81.1442 +      png_ptr->background.green =
 81.1443 +      png_ptr->background.blue =
 81.1444 +      png_ptr->background.gray = png_get_uint_16(buf);
 81.1445 +   }
 81.1446 +   else
 81.1447 +   {
 81.1448 +      png_ptr->background.red = png_get_uint_16(buf);
 81.1449 +      png_ptr->background.green = png_get_uint_16(buf + 2);
 81.1450 +      png_ptr->background.blue = png_get_uint_16(buf + 4);
 81.1451 +   }
 81.1452 +
 81.1453 +   png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
 81.1454 +}
 81.1455 +#endif
 81.1456 +
 81.1457 +#if defined(PNG_READ_hIST_SUPPORTED)
 81.1458 +void /* PRIVATE */
 81.1459 +png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1460 +{
 81.1461 +   unsigned int num, i;
 81.1462 +   png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
 81.1463 +
 81.1464 +   png_debug(1, "in png_handle_hIST\n");
 81.1465 +
 81.1466 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1467 +      png_error(png_ptr, "Missing IHDR before hIST");
 81.1468 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1469 +   {
 81.1470 +      png_warning(png_ptr, "Invalid hIST after IDAT");
 81.1471 +      png_crc_finish(png_ptr, length);
 81.1472 +      return;
 81.1473 +   }
 81.1474 +   else if (!(png_ptr->mode & PNG_HAVE_PLTE))
 81.1475 +   {
 81.1476 +      png_warning(png_ptr, "Missing PLTE before hIST");
 81.1477 +      png_crc_finish(png_ptr, length);
 81.1478 +      return;
 81.1479 +   }
 81.1480 +   else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
 81.1481 +   {
 81.1482 +      png_warning(png_ptr, "Duplicate hIST chunk");
 81.1483 +      png_crc_finish(png_ptr, length);
 81.1484 +      return;
 81.1485 +   }
 81.1486 +
 81.1487 +   num = length / 2 ;
 81.1488 +   if (num != (unsigned int) png_ptr->num_palette || num >
 81.1489 +      (unsigned int) PNG_MAX_PALETTE_LENGTH)
 81.1490 +   {
 81.1491 +      png_warning(png_ptr, "Incorrect hIST chunk length");
 81.1492 +      png_crc_finish(png_ptr, length);
 81.1493 +      return;
 81.1494 +   }
 81.1495 +
 81.1496 +   for (i = 0; i < num; i++)
 81.1497 +   {
 81.1498 +      png_byte buf[2];
 81.1499 +
 81.1500 +      png_crc_read(png_ptr, buf, 2);
 81.1501 +      readbuf[i] = png_get_uint_16(buf);
 81.1502 +   }
 81.1503 +
 81.1504 +   if (png_crc_finish(png_ptr, 0))
 81.1505 +      return;
 81.1506 +
 81.1507 +   png_set_hIST(png_ptr, info_ptr, readbuf);
 81.1508 +}
 81.1509 +#endif
 81.1510 +
 81.1511 +#if defined(PNG_READ_pHYs_SUPPORTED)
 81.1512 +void /* PRIVATE */
 81.1513 +png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1514 +{
 81.1515 +   png_byte buf[9];
 81.1516 +   png_uint_32 res_x, res_y;
 81.1517 +   int unit_type;
 81.1518 +
 81.1519 +   png_debug(1, "in png_handle_pHYs\n");
 81.1520 +
 81.1521 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1522 +      png_error(png_ptr, "Missing IHDR before pHYs");
 81.1523 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1524 +   {
 81.1525 +      png_warning(png_ptr, "Invalid pHYs after IDAT");
 81.1526 +      png_crc_finish(png_ptr, length);
 81.1527 +      return;
 81.1528 +   }
 81.1529 +   else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
 81.1530 +   {
 81.1531 +      png_warning(png_ptr, "Duplicate pHYs chunk");
 81.1532 +      png_crc_finish(png_ptr, length);
 81.1533 +      return;
 81.1534 +   }
 81.1535 +
 81.1536 +   if (length != 9)
 81.1537 +   {
 81.1538 +      png_warning(png_ptr, "Incorrect pHYs chunk length");
 81.1539 +      png_crc_finish(png_ptr, length);
 81.1540 +      return;
 81.1541 +   }
 81.1542 +
 81.1543 +   png_crc_read(png_ptr, buf, 9);
 81.1544 +   if (png_crc_finish(png_ptr, 0))
 81.1545 +      return;
 81.1546 +
 81.1547 +   res_x = png_get_uint_32(buf);
 81.1548 +   res_y = png_get_uint_32(buf + 4);
 81.1549 +   unit_type = buf[8];
 81.1550 +   png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
 81.1551 +}
 81.1552 +#endif
 81.1553 +
 81.1554 +#if defined(PNG_READ_oFFs_SUPPORTED)
 81.1555 +void /* PRIVATE */
 81.1556 +png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1557 +{
 81.1558 +   png_byte buf[9];
 81.1559 +   png_int_32 offset_x, offset_y;
 81.1560 +   int unit_type;
 81.1561 +
 81.1562 +   png_debug(1, "in png_handle_oFFs\n");
 81.1563 +
 81.1564 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1565 +      png_error(png_ptr, "Missing IHDR before oFFs");
 81.1566 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1567 +   {
 81.1568 +      png_warning(png_ptr, "Invalid oFFs after IDAT");
 81.1569 +      png_crc_finish(png_ptr, length);
 81.1570 +      return;
 81.1571 +   }
 81.1572 +   else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
 81.1573 +   {
 81.1574 +      png_warning(png_ptr, "Duplicate oFFs chunk");
 81.1575 +      png_crc_finish(png_ptr, length);
 81.1576 +      return;
 81.1577 +   }
 81.1578 +
 81.1579 +   if (length != 9)
 81.1580 +   {
 81.1581 +      png_warning(png_ptr, "Incorrect oFFs chunk length");
 81.1582 +      png_crc_finish(png_ptr, length);
 81.1583 +      return;
 81.1584 +   }
 81.1585 +
 81.1586 +   png_crc_read(png_ptr, buf, 9);
 81.1587 +   if (png_crc_finish(png_ptr, 0))
 81.1588 +      return;
 81.1589 +
 81.1590 +   offset_x = png_get_int_32(buf);
 81.1591 +   offset_y = png_get_int_32(buf + 4);
 81.1592 +   unit_type = buf[8];
 81.1593 +   png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
 81.1594 +}
 81.1595 +#endif
 81.1596 +
 81.1597 +#if defined(PNG_READ_pCAL_SUPPORTED)
 81.1598 +/* read the pCAL chunk (described in the PNG Extensions document) */
 81.1599 +void /* PRIVATE */
 81.1600 +png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1601 +{
 81.1602 +   png_int_32 X0, X1;
 81.1603 +   png_byte type, nparams;
 81.1604 +   png_charp buf, units, endptr;
 81.1605 +   png_charpp params;
 81.1606 +   png_size_t slength;
 81.1607 +   int i;
 81.1608 +
 81.1609 +   png_debug(1, "in png_handle_pCAL\n");
 81.1610 +
 81.1611 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1612 +      png_error(png_ptr, "Missing IHDR before pCAL");
 81.1613 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1614 +   {
 81.1615 +      png_warning(png_ptr, "Invalid pCAL after IDAT");
 81.1616 +      png_crc_finish(png_ptr, length);
 81.1617 +      return;
 81.1618 +   }
 81.1619 +   else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
 81.1620 +   {
 81.1621 +      png_warning(png_ptr, "Duplicate pCAL chunk");
 81.1622 +      png_crc_finish(png_ptr, length);
 81.1623 +      return;
 81.1624 +   }
 81.1625 +
 81.1626 +   png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
 81.1627 +      length + 1);
 81.1628 +   png_free(png_ptr, png_ptr->chunkdata);
 81.1629 +   png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
 81.1630 +   if (png_ptr->chunkdata == NULL)
 81.1631 +     {
 81.1632 +       png_warning(png_ptr, "No memory for pCAL purpose.");
 81.1633 +       return;
 81.1634 +     }
 81.1635 +   slength = (png_size_t)length;
 81.1636 +   png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength);
 81.1637 +
 81.1638 +   if (png_crc_finish(png_ptr, 0))
 81.1639 +   {
 81.1640 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1641 +      png_ptr->chunkdata = NULL;
 81.1642 +      return;
 81.1643 +   }
 81.1644 +
 81.1645 +   png_ptr->chunkdata[slength] = 0x00; /* null terminate the last string */
 81.1646 +
 81.1647 +   png_debug(3, "Finding end of pCAL purpose string\n");
 81.1648 +   for (buf = png_ptr->chunkdata; *buf; buf++)
 81.1649 +      /* empty loop */ ;
 81.1650 +
 81.1651 +   endptr = png_ptr->chunkdata + slength;
 81.1652 +
 81.1653 +   /* We need to have at least 12 bytes after the purpose string
 81.1654 +      in order to get the parameter information. */
 81.1655 +   if (endptr <= buf + 12)
 81.1656 +   {
 81.1657 +      png_warning(png_ptr, "Invalid pCAL data");
 81.1658 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1659 +      png_ptr->chunkdata = NULL;
 81.1660 +      return;
 81.1661 +   }
 81.1662 +
 81.1663 +   png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
 81.1664 +   X0 = png_get_int_32((png_bytep)buf+1);
 81.1665 +   X1 = png_get_int_32((png_bytep)buf+5);
 81.1666 +   type = buf[9];
 81.1667 +   nparams = buf[10];
 81.1668 +   units = buf + 11;
 81.1669 +
 81.1670 +   png_debug(3, "Checking pCAL equation type and number of parameters\n");
 81.1671 +   /* Check that we have the right number of parameters for known
 81.1672 +      equation types. */
 81.1673 +   if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
 81.1674 +       (type == PNG_EQUATION_BASE_E && nparams != 3) ||
 81.1675 +       (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
 81.1676 +       (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
 81.1677 +   {
 81.1678 +      png_warning(png_ptr, "Invalid pCAL parameters for equation type");
 81.1679 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1680 +      png_ptr->chunkdata = NULL;
 81.1681 +      return;
 81.1682 +   }
 81.1683 +   else if (type >= PNG_EQUATION_LAST)
 81.1684 +   {
 81.1685 +      png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
 81.1686 +   }
 81.1687 +
 81.1688 +   for (buf = units; *buf; buf++)
 81.1689 +      /* Empty loop to move past the units string. */ ;
 81.1690 +
 81.1691 +   png_debug(3, "Allocating pCAL parameters array\n");
 81.1692 +   params = (png_charpp)png_malloc_warn(png_ptr,
 81.1693 +      (png_uint_32)(nparams * png_sizeof(png_charp))) ;
 81.1694 +   if (params == NULL)
 81.1695 +     {
 81.1696 +       png_free(png_ptr, png_ptr->chunkdata);
 81.1697 +       png_ptr->chunkdata = NULL;
 81.1698 +       png_warning(png_ptr, "No memory for pCAL params.");
 81.1699 +       return;
 81.1700 +     }
 81.1701 +
 81.1702 +   /* Get pointers to the start of each parameter string. */
 81.1703 +   for (i = 0; i < (int)nparams; i++)
 81.1704 +   {
 81.1705 +      buf++; /* Skip the null string terminator from previous parameter. */
 81.1706 +
 81.1707 +      png_debug1(3, "Reading pCAL parameter %d\n", i);
 81.1708 +      for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
 81.1709 +         /* Empty loop to move past each parameter string */ ;
 81.1710 +
 81.1711 +      /* Make sure we haven't run out of data yet */
 81.1712 +      if (buf > endptr)
 81.1713 +      {
 81.1714 +         png_warning(png_ptr, "Invalid pCAL data");
 81.1715 +         png_free(png_ptr, png_ptr->chunkdata);
 81.1716 +         png_ptr->chunkdata = NULL;
 81.1717 +         png_free(png_ptr, params);
 81.1718 +         return;
 81.1719 +      }
 81.1720 +   }
 81.1721 +
 81.1722 +   png_set_pCAL(png_ptr, info_ptr, png_ptr->chunkdata, X0, X1, type, nparams,
 81.1723 +      units, params);
 81.1724 +
 81.1725 +   png_free(png_ptr, png_ptr->chunkdata);
 81.1726 +   png_ptr->chunkdata = NULL;
 81.1727 +   png_free(png_ptr, params);
 81.1728 +}
 81.1729 +#endif
 81.1730 +
 81.1731 +#if defined(PNG_READ_sCAL_SUPPORTED)
 81.1732 +/* read the sCAL chunk */
 81.1733 +void /* PRIVATE */
 81.1734 +png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1735 +{
 81.1736 +   png_charp ep;
 81.1737 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 81.1738 +   double width, height;
 81.1739 +   png_charp vp;
 81.1740 +#else
 81.1741 +#ifdef PNG_FIXED_POINT_SUPPORTED
 81.1742 +   png_charp swidth, sheight;
 81.1743 +#endif
 81.1744 +#endif
 81.1745 +   png_size_t slength;
 81.1746 +
 81.1747 +   png_debug(1, "in png_handle_sCAL\n");
 81.1748 +
 81.1749 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1750 +      png_error(png_ptr, "Missing IHDR before sCAL");
 81.1751 +   else if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1752 +   {
 81.1753 +      png_warning(png_ptr, "Invalid sCAL after IDAT");
 81.1754 +      png_crc_finish(png_ptr, length);
 81.1755 +      return;
 81.1756 +   }
 81.1757 +   else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
 81.1758 +   {
 81.1759 +      png_warning(png_ptr, "Duplicate sCAL chunk");
 81.1760 +      png_crc_finish(png_ptr, length);
 81.1761 +      return;
 81.1762 +   }
 81.1763 +
 81.1764 +   png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
 81.1765 +      length + 1);
 81.1766 +   png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
 81.1767 +   if (png_ptr->chunkdata == NULL)
 81.1768 +   {
 81.1769 +      png_warning(png_ptr, "Out of memory while processing sCAL chunk");
 81.1770 +      return;
 81.1771 +   }
 81.1772 +   slength = (png_size_t)length;
 81.1773 +   png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength);
 81.1774 +
 81.1775 +   if (png_crc_finish(png_ptr, 0))
 81.1776 +   {
 81.1777 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1778 +      png_ptr->chunkdata = NULL;
 81.1779 +      return;
 81.1780 +   }
 81.1781 +
 81.1782 +   png_ptr->chunkdata[slength] = 0x00; /* null terminate the last string */
 81.1783 +
 81.1784 +   ep = png_ptr->chunkdata + 1;        /* skip unit byte */
 81.1785 +
 81.1786 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 81.1787 +   width = png_strtod(png_ptr, ep, &vp);
 81.1788 +   if (*vp)
 81.1789 +   {
 81.1790 +      png_warning(png_ptr, "malformed width string in sCAL chunk");
 81.1791 +      return;
 81.1792 +   }
 81.1793 +#else
 81.1794 +#ifdef PNG_FIXED_POINT_SUPPORTED
 81.1795 +   swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
 81.1796 +   if (swidth == NULL)
 81.1797 +   {
 81.1798 +      png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
 81.1799 +      return;
 81.1800 +   }
 81.1801 +   png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
 81.1802 +#endif
 81.1803 +#endif
 81.1804 +
 81.1805 +   for (ep = png_ptr->chunkdata; *ep; ep++)
 81.1806 +      /* empty loop */ ;
 81.1807 +   ep++;
 81.1808 +
 81.1809 +   if (png_ptr->chunkdata + slength < ep)
 81.1810 +   {
 81.1811 +      png_warning(png_ptr, "Truncated sCAL chunk");
 81.1812 +#if defined(PNG_FIXED_POINT_SUPPORTED) && \
 81.1813 +    !defined(PNG_FLOATING_POINT_SUPPORTED)
 81.1814 +      png_free(png_ptr, swidth);
 81.1815 +#endif
 81.1816 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1817 +      png_ptr->chunkdata = NULL;
 81.1818 +      return;
 81.1819 +   }
 81.1820 +
 81.1821 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 81.1822 +   height = png_strtod(png_ptr, ep, &vp);
 81.1823 +   if (*vp)
 81.1824 +   {
 81.1825 +      png_warning(png_ptr, "malformed height string in sCAL chunk");
 81.1826 +      return;
 81.1827 +   }
 81.1828 +#else
 81.1829 +#ifdef PNG_FIXED_POINT_SUPPORTED
 81.1830 +   sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
 81.1831 +   if (sheight == NULL)
 81.1832 +   {
 81.1833 +      png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
 81.1834 +      return;
 81.1835 +   }
 81.1836 +   png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
 81.1837 +#endif
 81.1838 +#endif
 81.1839 +
 81.1840 +   if (png_ptr->chunkdata + slength < ep
 81.1841 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 81.1842 +      || width <= 0. || height <= 0.
 81.1843 +#endif
 81.1844 +      )
 81.1845 +   {
 81.1846 +      png_warning(png_ptr, "Invalid sCAL data");
 81.1847 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1848 +      png_ptr->chunkdata = NULL;
 81.1849 +#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
 81.1850 +      png_free(png_ptr, swidth);
 81.1851 +      png_free(png_ptr, sheight);
 81.1852 +#endif
 81.1853 +      return;
 81.1854 +   }
 81.1855 +
 81.1856 +
 81.1857 +#ifdef PNG_FLOATING_POINT_SUPPORTED
 81.1858 +   png_set_sCAL(png_ptr, info_ptr, png_ptr->chunkdata[0], width, height);
 81.1859 +#else
 81.1860 +#ifdef PNG_FIXED_POINT_SUPPORTED
 81.1861 +   png_set_sCAL_s(png_ptr, info_ptr, png_ptr->chunkdata[0], swidth, sheight);
 81.1862 +#endif
 81.1863 +#endif
 81.1864 +
 81.1865 +   png_free(png_ptr, png_ptr->chunkdata);
 81.1866 +   png_ptr->chunkdata = NULL;
 81.1867 +#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
 81.1868 +   png_free(png_ptr, swidth);
 81.1869 +   png_free(png_ptr, sheight);
 81.1870 +#endif
 81.1871 +}
 81.1872 +#endif
 81.1873 +
 81.1874 +#if defined(PNG_READ_tIME_SUPPORTED)
 81.1875 +void /* PRIVATE */
 81.1876 +png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1877 +{
 81.1878 +   png_byte buf[7];
 81.1879 +   png_time mod_time;
 81.1880 +
 81.1881 +   png_debug(1, "in png_handle_tIME\n");
 81.1882 +
 81.1883 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1884 +      png_error(png_ptr, "Out of place tIME chunk");
 81.1885 +   else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
 81.1886 +   {
 81.1887 +      png_warning(png_ptr, "Duplicate tIME chunk");
 81.1888 +      png_crc_finish(png_ptr, length);
 81.1889 +      return;
 81.1890 +   }
 81.1891 +
 81.1892 +   if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1893 +      png_ptr->mode |= PNG_AFTER_IDAT;
 81.1894 +
 81.1895 +   if (length != 7)
 81.1896 +   {
 81.1897 +      png_warning(png_ptr, "Incorrect tIME chunk length");
 81.1898 +      png_crc_finish(png_ptr, length);
 81.1899 +      return;
 81.1900 +   }
 81.1901 +
 81.1902 +   png_crc_read(png_ptr, buf, 7);
 81.1903 +   if (png_crc_finish(png_ptr, 0))
 81.1904 +      return;
 81.1905 +
 81.1906 +   mod_time.second = buf[6];
 81.1907 +   mod_time.minute = buf[5];
 81.1908 +   mod_time.hour = buf[4];
 81.1909 +   mod_time.day = buf[3];
 81.1910 +   mod_time.month = buf[2];
 81.1911 +   mod_time.year = png_get_uint_16(buf);
 81.1912 +
 81.1913 +   png_set_tIME(png_ptr, info_ptr, &mod_time);
 81.1914 +}
 81.1915 +#endif
 81.1916 +
 81.1917 +#if defined(PNG_READ_tEXt_SUPPORTED)
 81.1918 +/* Note: this does not properly handle chunks that are > 64K under DOS */
 81.1919 +void /* PRIVATE */
 81.1920 +png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.1921 +{
 81.1922 +   png_textp text_ptr;
 81.1923 +   png_charp key;
 81.1924 +   png_charp text;
 81.1925 +   png_uint_32 skip = 0;
 81.1926 +   png_size_t slength;
 81.1927 +   int ret;
 81.1928 +
 81.1929 +   png_debug(1, "in png_handle_tEXt\n");
 81.1930 +
 81.1931 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.1932 +      png_error(png_ptr, "Missing IHDR before tEXt");
 81.1933 +
 81.1934 +   if (png_ptr->mode & PNG_HAVE_IDAT)
 81.1935 +      png_ptr->mode |= PNG_AFTER_IDAT;
 81.1936 +
 81.1937 +#ifdef PNG_MAX_MALLOC_64K
 81.1938 +   if (length > (png_uint_32)65535L)
 81.1939 +   {
 81.1940 +      png_warning(png_ptr, "tEXt chunk too large to fit in memory");
 81.1941 +      skip = length - (png_uint_32)65535L;
 81.1942 +      length = (png_uint_32)65535L;
 81.1943 +   }
 81.1944 +#endif
 81.1945 +
 81.1946 +   png_free(png_ptr, png_ptr->chunkdata);
 81.1947 +   png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
 81.1948 +   if (png_ptr->chunkdata == NULL)
 81.1949 +   {
 81.1950 +     png_warning(png_ptr, "No memory to process text chunk.");
 81.1951 +     return;
 81.1952 +   }
 81.1953 +   slength = (png_size_t)length;
 81.1954 +   png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength);
 81.1955 +
 81.1956 +   if (png_crc_finish(png_ptr, skip))
 81.1957 +   {
 81.1958 +      png_free(png_ptr, png_ptr->chunkdata);
 81.1959 +      png_ptr->chunkdata = NULL;
 81.1960 +      return;
 81.1961 +   }
 81.1962 +
 81.1963 +   key = png_ptr->chunkdata;
 81.1964 +   key[slength] = 0x00;
 81.1965 +
 81.1966 +   for (text = key; *text; text++)
 81.1967 +      /* empty loop to find end of key */ ;
 81.1968 +
 81.1969 +   if (text != key + slength)
 81.1970 +      text++;
 81.1971 +
 81.1972 +   text_ptr = (png_textp)png_malloc_warn(png_ptr,
 81.1973 +      (png_uint_32)png_sizeof(png_text));
 81.1974 +   if (text_ptr == NULL)
 81.1975 +   {
 81.1976 +     png_warning(png_ptr, "Not enough memory to process text chunk.");
 81.1977 +     png_free(png_ptr, png_ptr->chunkdata);
 81.1978 +     png_ptr->chunkdata = NULL;
 81.1979 +     return;
 81.1980 +   }
 81.1981 +   text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
 81.1982 +   text_ptr->key = key;
 81.1983 +#ifdef PNG_iTXt_SUPPORTED
 81.1984 +   text_ptr->lang = NULL;
 81.1985 +   text_ptr->lang_key = NULL;
 81.1986 +   text_ptr->itxt_length = 0;
 81.1987 +#endif
 81.1988 +   text_ptr->text = text;
 81.1989 +   text_ptr->text_length = png_strlen(text);
 81.1990 +
 81.1991 +   ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
 81.1992 +
 81.1993 +   png_free(png_ptr, png_ptr->chunkdata);
 81.1994 +   png_ptr->chunkdata = NULL;
 81.1995 +   png_free(png_ptr, text_ptr);
 81.1996 +   if (ret)
 81.1997 +     png_warning(png_ptr, "Insufficient memory to process text chunk.");
 81.1998 +}
 81.1999 +#endif
 81.2000 +
 81.2001 +#if defined(PNG_READ_zTXt_SUPPORTED)
 81.2002 +/* note: this does not correctly handle chunks that are > 64K under DOS */
 81.2003 +void /* PRIVATE */
 81.2004 +png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.2005 +{
 81.2006 +   png_textp text_ptr;
 81.2007 +   png_charp text;
 81.2008 +   int comp_type;
 81.2009 +   int ret;
 81.2010 +   png_size_t slength, prefix_len, data_len;
 81.2011 +
 81.2012 +   png_debug(1, "in png_handle_zTXt\n");
 81.2013 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.2014 +      png_error(png_ptr, "Missing IHDR before zTXt");
 81.2015 +
 81.2016 +   if (png_ptr->mode & PNG_HAVE_IDAT)
 81.2017 +      png_ptr->mode |= PNG_AFTER_IDAT;
 81.2018 +
 81.2019 +#ifdef PNG_MAX_MALLOC_64K
 81.2020 +   /* We will no doubt have problems with chunks even half this size, but
 81.2021 +      there is no hard and fast rule to tell us where to stop. */
 81.2022 +   if (length > (png_uint_32)65535L)
 81.2023 +   {
 81.2024 +     png_warning(png_ptr, "zTXt chunk too large to fit in memory");
 81.2025 +     png_crc_finish(png_ptr, length);
 81.2026 +     return;
 81.2027 +   }
 81.2028 +#endif
 81.2029 +
 81.2030 +   png_free(png_ptr, png_ptr->chunkdata);
 81.2031 +   png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
 81.2032 +   if (png_ptr->chunkdata == NULL)
 81.2033 +   {
 81.2034 +     png_warning(png_ptr, "Out of memory processing zTXt chunk.");
 81.2035 +     return;
 81.2036 +   }
 81.2037 +   slength = (png_size_t)length;
 81.2038 +   png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength);
 81.2039 +   if (png_crc_finish(png_ptr, 0))
 81.2040 +   {
 81.2041 +      png_free(png_ptr, png_ptr->chunkdata);
 81.2042 +      png_ptr->chunkdata = NULL;
 81.2043 +      return;
 81.2044 +   }
 81.2045 +
 81.2046 +   png_ptr->chunkdata[slength] = 0x00;
 81.2047 +
 81.2048 +   for (text = png_ptr->chunkdata; *text; text++)
 81.2049 +      /* empty loop */ ;
 81.2050 +
 81.2051 +   /* zTXt must have some text after the chunkdataword */
 81.2052 +   if (text >= png_ptr->chunkdata + slength - 2)
 81.2053 +   {
 81.2054 +      png_warning(png_ptr, "Truncated zTXt chunk");
 81.2055 +      png_free(png_ptr, png_ptr->chunkdata);
 81.2056 +      png_ptr->chunkdata = NULL;
 81.2057 +      return;
 81.2058 +   }
 81.2059 +   else
 81.2060 +   {
 81.2061 +       comp_type = *(++text);
 81.2062 +       if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
 81.2063 +       {
 81.2064 +          png_warning(png_ptr, "Unknown compression type in zTXt chunk");
 81.2065 +          comp_type = PNG_TEXT_COMPRESSION_zTXt;
 81.2066 +       }
 81.2067 +       text++;        /* skip the compression_method byte */
 81.2068 +   }
 81.2069 +   prefix_len = text - png_ptr->chunkdata;
 81.2070 +
 81.2071 +   png_decompress_chunk(png_ptr, comp_type,
 81.2072 +     (png_size_t)length, prefix_len, &data_len);
 81.2073 +
 81.2074 +   text_ptr = (png_textp)png_malloc_warn(png_ptr,
 81.2075 +      (png_uint_32)png_sizeof(png_text));
 81.2076 +   if (text_ptr == NULL)
 81.2077 +   {
 81.2078 +     png_warning(png_ptr, "Not enough memory to process zTXt chunk.");
 81.2079 +     png_free(png_ptr, png_ptr->chunkdata);
 81.2080 +     png_ptr->chunkdata = NULL;
 81.2081 +     return;
 81.2082 +   }
 81.2083 +   text_ptr->compression = comp_type;
 81.2084 +   text_ptr->key = png_ptr->chunkdata;
 81.2085 +#ifdef PNG_iTXt_SUPPORTED
 81.2086 +   text_ptr->lang = NULL;
 81.2087 +   text_ptr->lang_key = NULL;
 81.2088 +   text_ptr->itxt_length = 0;
 81.2089 +#endif
 81.2090 +   text_ptr->text = png_ptr->chunkdata + prefix_len;
 81.2091 +   text_ptr->text_length = data_len;
 81.2092 +
 81.2093 +   ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
 81.2094 +
 81.2095 +   png_free(png_ptr, text_ptr);
 81.2096 +   png_free(png_ptr, png_ptr->chunkdata);
 81.2097 +   png_ptr->chunkdata = NULL;
 81.2098 +   if (ret)
 81.2099 +     png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
 81.2100 +}
 81.2101 +#endif
 81.2102 +
 81.2103 +#if defined(PNG_READ_iTXt_SUPPORTED)
 81.2104 +/* note: this does not correctly handle chunks that are > 64K under DOS */
 81.2105 +void /* PRIVATE */
 81.2106 +png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.2107 +{
 81.2108 +   png_textp text_ptr;
 81.2109 +   png_charp key, lang, text, lang_key;
 81.2110 +   int comp_flag;
 81.2111 +   int comp_type = 0;
 81.2112 +   int ret;
 81.2113 +   png_size_t slength, prefix_len, data_len;
 81.2114 +
 81.2115 +   png_debug(1, "in png_handle_iTXt\n");
 81.2116 +
 81.2117 +   if (!(png_ptr->mode & PNG_HAVE_IHDR))
 81.2118 +      png_error(png_ptr, "Missing IHDR before iTXt");
 81.2119 +
 81.2120 +   if (png_ptr->mode & PNG_HAVE_IDAT)
 81.2121 +      png_ptr->mode |= PNG_AFTER_IDAT;
 81.2122 +
 81.2123 +#ifdef PNG_MAX_MALLOC_64K
 81.2124 +   /* We will no doubt have problems with chunks even half this size, but
 81.2125 +      there is no hard and fast rule to tell us where to stop. */
 81.2126 +   if (length > (png_uint_32)65535L)
 81.2127 +   {
 81.2128 +     png_warning(png_ptr, "iTXt chunk too large to fit in memory");
 81.2129 +     png_crc_finish(png_ptr, length);
 81.2130 +     return;
 81.2131 +   }
 81.2132 +#endif
 81.2133 +
 81.2134 +   png_free(png_ptr, png_ptr->chunkdata);
 81.2135 +   png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
 81.2136 +   if (png_ptr->chunkdata == NULL)
 81.2137 +   {
 81.2138 +     png_warning(png_ptr, "No memory to process iTXt chunk.");
 81.2139 +     return;
 81.2140 +   }
 81.2141 +   slength = (png_size_t)length;
 81.2142 +   png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength);
 81.2143 +   if (png_crc_finish(png_ptr, 0))
 81.2144 +   {
 81.2145 +      png_free(png_ptr, png_ptr->chunkdata);
 81.2146 +      png_ptr->chunkdata = NULL;
 81.2147 +      return;
 81.2148 +   }
 81.2149 +
 81.2150 +   png_ptr->chunkdata[slength] = 0x00;
 81.2151 +
 81.2152 +   for (lang = png_ptr->chunkdata; *lang; lang++)
 81.2153 +      /* empty loop */ ;
 81.2154 +   lang++;        /* skip NUL separator */
 81.2155 +
 81.2156 +   /* iTXt must have a language tag (possibly empty), two compression bytes,
 81.2157 +      translated keyword (possibly empty), and possibly some text after the
 81.2158 +      keyword */
 81.2159 +
 81.2160 +   if (lang >= png_ptr->chunkdata + slength - 3)
 81.2161 +   {
 81.2162 +      png_warning(png_ptr, "Truncated iTXt chunk");
 81.2163 +      png_free(png_ptr, png_ptr->chunkdata);
 81.2164 +      png_ptr->chunkdata = NULL;
 81.2165 +      return;
 81.2166 +   }
 81.2167 +   else
 81.2168 +   {
 81.2169 +       comp_flag = *lang++;
 81.2170 +       comp_type = *lang++;
 81.2171 +   }
 81.2172 +
 81.2173 +   for (lang_key = lang; *lang_key; lang_key++)
 81.2174 +      /* empty loop */ ;
 81.2175 +   lang_key++;        /* skip NUL separator */
 81.2176 +
 81.2177 +   if (lang_key >= png_ptr->chunkdata + slength)
 81.2178 +   {
 81.2179 +      png_warning(png_ptr, "Truncated iTXt chunk");
 81.2180 +      png_free(png_ptr, png_ptr->chunkdata);
 81.2181 +      png_ptr->chunkdata = NULL;
 81.2182 +      return;
 81.2183 +   }
 81.2184 +
 81.2185 +   for (text = lang_key; *text; text++)
 81.2186 +      /* empty loop */ ;
 81.2187 +   text++;        /* skip NUL separator */
 81.2188 +   if (text >= png_ptr->chunkdata + slength)
 81.2189 +   {
 81.2190 +      png_warning(png_ptr, "Malformed iTXt chunk");
 81.2191 +      png_free(png_ptr, png_ptr->chunkdata);
 81.2192 +      png_ptr->chunkdata = NULL;
 81.2193 +      return;
 81.2194 +   }
 81.2195 +
 81.2196 +   prefix_len = text - png_ptr->chunkdata;
 81.2197 +
 81.2198 +   key=png_ptr->chunkdata;
 81.2199 +   if (comp_flag)
 81.2200 +       png_decompress_chunk(png_ptr, comp_type,
 81.2201 +         (size_t)length, prefix_len, &data_len);
 81.2202 +   else
 81.2203 +       data_len = png_strlen(png_ptr->chunkdata + prefix_len);
 81.2204 +   text_ptr = (png_textp)png_malloc_warn(png_ptr,
 81.2205 +      (png_uint_32)png_sizeof(png_text));
 81.2206 +   if (text_ptr == NULL)
 81.2207 +   {
 81.2208 +     png_warning(png_ptr, "Not enough memory to process iTXt chunk.");
 81.2209 +     png_free(png_ptr, png_ptr->chunkdata);
 81.2210 +     png_ptr->chunkdata = NULL;
 81.2211 +     return;
 81.2212 +   }
 81.2213 +   text_ptr->compression = (int)comp_flag + 1;
 81.2214 +   text_ptr->lang_key = png_ptr->chunkdata + (lang_key - key);
 81.2215 +   text_ptr->lang = png_ptr->chunkdata + (lang - key);
 81.2216 +   text_ptr->itxt_length = data_len;
 81.2217 +   text_ptr->text_length = 0;
 81.2218 +   text_ptr->key = png_ptr->chunkdata;
 81.2219 +   text_ptr->text = png_ptr->chunkdata + prefix_len;
 81.2220 +
 81.2221 +   ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
 81.2222 +
 81.2223 +   png_free(png_ptr, text_ptr);
 81.2224 +   png_free(png_ptr, png_ptr->chunkdata);
 81.2225 +   png_ptr->chunkdata = NULL;
 81.2226 +   if (ret)
 81.2227 +     png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
 81.2228 +}
 81.2229 +#endif
 81.2230 +
 81.2231 +/* This function is called when we haven't found a handler for a
 81.2232 +   chunk.  If there isn't a problem with the chunk itself (ie bad
 81.2233 +   chunk name, CRC, or a critical chunk), the chunk is silently ignored
 81.2234 +   -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
 81.2235 +   case it will be saved away to be written out later. */
 81.2236 +void /* PRIVATE */
 81.2237 +png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 81.2238 +{
 81.2239 +   png_uint_32 skip = 0;
 81.2240 +
 81.2241 +   png_debug(1, "in png_handle_unknown\n");
 81.2242 +
 81.2243 +   if (png_ptr->mode & PNG_HAVE_IDAT)
 81.2244 +   {
 81.2245 +#ifdef PNG_USE_LOCAL_ARRAYS
 81.2246 +      PNG_CONST PNG_IDAT;
 81.2247 +#endif
 81.2248 +      if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))  /* not an IDAT */
 81.2249 +         png_ptr->mode |= PNG_AFTER_IDAT;
 81.2250 +   }
 81.2251 +
 81.2252 +   if (!(png_ptr->chunk_name[0] & 0x20))
 81.2253 +   {
 81.2254 +#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
 81.2255 +      if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
 81.2256 +           PNG_HANDLE_CHUNK_ALWAYS
 81.2257 +#if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
 81.2258 +           && png_ptr->read_user_chunk_fn == NULL
 81.2259 +#endif
 81.2260 +        )
 81.2261 +#endif
 81.2262 +          png_chunk_error(png_ptr, "unknown critical chunk");
 81.2263 +   }
 81.2264 +
 81.2265 +#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
 81.2266 +   if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
 81.2267 +       (png_ptr->read_user_chunk_fn != NULL))
 81.2268 +   {
 81.2269 +#ifdef PNG_MAX_MALLOC_64K
 81.2270 +       if (length > (png_uint_32)65535L)
 81.2271 +       {
 81.2272 +           png_warning(png_ptr, "unknown chunk too large to fit in memory");
 81.2273 +           skip = length - (png_uint_32)65535L;
 81.2274 +           length = (png_uint_32)65535L;
 81.2275 +       }
 81.2276 +#endif
 81.2277 +       png_memcpy((png_charp)png_ptr->unknown_chunk.name,
 81.2278 +                  (png_charp)png_ptr->chunk_name, 
 81.2279 +                  png_sizeof(png_ptr->unknown_chunk.name));
 81.2280 +       png_ptr->unknown_chunk.name[png_sizeof(png_ptr->unknown_chunk.name)-1] = '\0';
 81.2281 +       png_ptr->unknown_chunk.size = (png_size_t)length;
 81.2282 +       if (length == 0)
 81.2283 +         png_ptr->unknown_chunk.data = NULL;
 81.2284 +       else
 81.2285 +       {
 81.2286 +         png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
 81.2287 +         png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
 81.2288 +       }
 81.2289 +#if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
 81.2290 +       if (png_ptr->read_user_chunk_fn != NULL)
 81.2291 +       {
 81.2292 +          /* callback to user unknown chunk handler */
 81.2293 +          int ret;
 81.2294 +          ret = (*(png_ptr->read_user_chunk_fn))
 81.2295 +            (png_ptr, &png_ptr->unknown_chunk);
 81.2296 +          if (ret < 0)
 81.2297 +             png_chunk_error(png_ptr, "error in user chunk");
 81.2298 +          if (ret == 0)
 81.2299 +          {
 81.2300 +             if (!(png_ptr->chunk_name[0] & 0x20))
 81.2301 +                if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
 81.2302 +                     PNG_HANDLE_CHUNK_ALWAYS)
 81.2303 +                   png_chunk_error(png_ptr, "unknown critical chunk");
 81.2304 +             png_set_unknown_chunks(png_ptr, info_ptr,
 81.2305 +               &png_ptr->unknown_chunk, 1);
 81.2306 +          }
 81.2307 +       }
 81.2308 +       else
 81.2309 +#endif
 81.2310 +       png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
 81.2311 +       png_free(png_ptr, png_ptr->unknown_chunk.data);
 81.2312 +       png_ptr->unknown_chunk.data = NULL;
 81.2313 +   }
 81.2314 +   else
 81.2315 +#endif
 81.2316 +      skip = length;
 81.2317 +
 81.2318 +   png_crc_finish(png_ptr, skip);
 81.2319 +
 81.2320 +#if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
 81.2321 +   info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
 81.2322 +#endif
 81.2323 +}
 81.2324 +
 81.2325 +/* This function is called to verify that a chunk name is valid.
 81.2326 +   This function can't have the "critical chunk check" incorporated
 81.2327 +   into it, since in the future we will need to be able to call user
 81.2328 +   functions to handle unknown critical chunks after we check that
 81.2329 +   the chunk name itself is valid. */
 81.2330 +
 81.2331 +#define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
 81.2332 +
 81.2333 +void /* PRIVATE */
 81.2334 +png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
 81.2335 +{
 81.2336 +   png_debug(1, "in png_check_chunk_name\n");
 81.2337 +   if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
 81.2338 +       isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
 81.2339 +   {
 81.2340 +      png_chunk_error(png_ptr, "invalid chunk type");
 81.2341 +   }
 81.2342 +}
 81.2343 +
 81.2344 +/* Combines the row recently read in with the existing pixels in the
 81.2345 +   row.  This routine takes care of alpha and transparency if requested.
 81.2346 +   This routine also handles the two methods of progressive display
 81.2347 +   of interlaced images, depending on the mask value.
 81.2348 +   The mask value describes which pixels are to be combined with
 81.2349 +   the row.  The pattern always repeats every 8 pixels, so just 8
 81.2350 +   bits are needed.  A one indicates the pixel is to be combined,
 81.2351 +   a zero indicates the pixel is to be skipped.  This is in addition
 81.2352 +   to any alpha or transparency value associated with the pixel.  If
 81.2353 +   you want all pixels to be combined, pass 0xff (255) in mask.  */
 81.2354 +
 81.2355 +void /* PRIVATE */
 81.2356 +png_combine_row(png_structp png_ptr, png_bytep row, int mask)
 81.2357 +{
 81.2358 +   png_debug(1, "in png_combine_row\n");
 81.2359 +   if (mask == 0xff)
 81.2360 +   {
 81.2361 +      png_memcpy(row, png_ptr->row_buf + 1,
 81.2362 +         PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
 81.2363 +   }
 81.2364 +   else
 81.2365 +   {
 81.2366 +      switch (png_ptr->row_info.pixel_depth)
 81.2367 +      {
 81.2368 +         case 1:
 81.2369 +         {
 81.2370 +            png_bytep sp = png_ptr->row_buf + 1;
 81.2371 +            png_bytep dp = row;
 81.2372 +            int s_inc, s_start, s_end;
 81.2373 +            int m = 0x80;
 81.2374 +            int shift;
 81.2375 +            png_uint_32 i;
 81.2376 +            png_uint_32 row_width = png_ptr->width;
 81.2377 +
 81.2378 +#if defined(PNG_READ_PACKSWAP_SUPPORTED)
 81.2379 +            if (png_ptr->transformations & PNG_PACKSWAP)
 81.2380 +            {
 81.2381 +                s_start = 0;
 81.2382 +                s_end = 7;
 81.2383 +                s_inc = 1;
 81.2384 +            }
 81.2385 +            else
 81.2386 +#endif
 81.2387 +            {
 81.2388 +                s_start = 7;
 81.2389 +                s_end = 0;
 81.2390 +                s_inc = -1;
 81.2391 +            }
 81.2392 +
 81.2393 +            shift = s_start;
 81.2394 +
 81.2395 +            for (i = 0; i < row_width; i++)
 81.2396 +            {
 81.2397 +               if (m & mask)
 81.2398 +               {
 81.2399 +                  int value;
 81.2400 +
 81.2401 +                  value = (*sp >> shift) & 0x01;
 81.2402 +                  *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
 81.2403 +                  *dp |= (png_byte)(value << shift);
 81.2404 +               }
 81.2405 +
 81.2406 +               if (shift == s_end)
 81.2407 +               {
 81.2408 +                  shift = s_start;
 81.2409 +                  sp++;
 81.2410 +                  dp++;
 81.2411 +               }
 81.2412 +               else
 81.2413 +                  shift += s_inc;
 81.2414 +
 81.2415 +               if (m == 1)
 81.2416 +                  m = 0x80;
 81.2417 +               else
 81.2418 +                  m >>= 1;
 81.2419 +            }
 81.2420 +            break;
 81.2421 +         }
 81.2422 +         case 2:
 81.2423 +         {
 81.2424 +            png_bytep sp = png_ptr->row_buf + 1;
 81.2425 +            png_bytep dp = row;
 81.2426 +            int s_start, s_end, s_inc;
 81.2427 +            int m = 0x80;
 81.2428 +            int shift;
 81.2429 +            png_uint_32 i;
 81.2430 +            png_uint_32 row_width = png_ptr->width;
 81.2431 +            int value;
 81.2432 +
 81.2433 +#if defined(PNG_READ_PACKSWAP_SUPPORTED)
 81.2434 +            if (png_ptr->transformations & PNG_PACKSWAP)
 81.2435 +            {
 81.2436 +               s_start = 0;
 81.2437 +               s_end = 6;
 81.2438 +               s_inc = 2;
 81.2439 +            }
 81.2440 +            else
 81.2441 +#endif
 81.2442 +            {
 81.2443 +               s_start = 6;
 81.2444 +               s_end = 0;
 81.2445 +               s_inc = -2;
 81.2446 +            }
 81.2447 +
 81.2448 +            shift = s_start;
 81.2449 +
 81.2450 +            for (i = 0; i < row_width; i++)
 81.2451 +            {
 81.2452 +               if (m & mask)
 81.2453 +               {
 81.2454 +                  value = (*sp >> shift) & 0x03;
 81.2455 +                  *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
 81.2456 +                  *dp |= (png_byte)(value << shift);
 81.2457 +               }
 81.2458 +
 81.2459 +               if (shift == s_end)
 81.2460 +               {
 81.2461 +                  shift = s_start;
 81.2462 +                  sp++;
 81.2463 +                  dp++;
 81.2464 +               }
 81.2465 +               else
 81.2466 +                  shift += s_inc;
 81.2467 +               if (m == 1)
 81.2468 +                  m = 0x80;
 81.2469 +               else
 81.2470 +                  m >>= 1;
 81.2471 +            }
 81.2472 +            break;
 81.2473 +         }
 81.2474 +         case 4:
 81.2475 +         {
 81.2476 +            png_bytep sp = png_ptr->row_buf + 1;
 81.2477 +            png_bytep dp = row;
 81.2478 +            int s_start, s_end, s_inc;
 81.2479 +            int m = 0x80;
 81.2480 +            int shift;
 81.2481 +            png_uint_32 i;
 81.2482 +            png_uint_32 row_width = png_ptr->width;
 81.2483 +            int value;
 81.2484 +
 81.2485 +#if defined(PNG_READ_PACKSWAP_SUPPORTED)
 81.2486 +            if (png_ptr->transformations & PNG_PACKSWAP)
 81.2487 +            {
 81.2488 +               s_start = 0;
 81.2489 +               s_end = 4;
 81.2490 +               s_inc = 4;
 81.2491 +            }
 81.2492 +            else
 81.2493 +#endif
 81.2494 +            {
 81.2495 +               s_start = 4;
 81.2496 +               s_end = 0;
 81.2497 +               s_inc = -4;
 81.2498 +            }
 81.2499 +            shift = s_start;
 81.2500 +
 81.2501 +            for (i = 0; i < row_width; i++)
 81.2502 +            {
 81.2503 +               if (m & mask)
 81.2504 +               {
 81.2505 +                  value = (*sp >> shift) & 0xf;
 81.2506 +                  *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
 81.2507 +                  *dp |= (png_byte)(value << shift);
 81.2508 +               }
 81.2509 +
 81.2510 +               if (shift == s_end)
 81.2511 +               {
 81.2512 +                  shift = s_start;
 81.2513 +                  sp++;
 81.2514 +                  dp++;
 81.2515 +               }
 81.2516 +               else
 81.2517 +                  shift += s_inc;
 81.2518 +               if (m == 1)
 81.2519 +                  m = 0x80;
 81.2520 +               else
 81.2521 +                  m >>= 1;
 81.2522 +            }
 81.2523 +            break;
 81.2524 +         }
 81.2525 +         default:
 81.2526 +         {
 81.2527 +            png_bytep sp = png_ptr->row_buf + 1;
 81.2528 +            png_bytep dp = row;
 81.2529 +            png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
 81.2530 +            png_uint_32 i;
 81.2531 +            png_uint_32 row_width = png_ptr->width;
 81.2532 +            png_byte m = 0x80;
 81.2533 +
 81.2534 +
 81.2535 +            for (i = 0; i < row_width; i++)
 81.2536 +            {
 81.2537 +               if (m & mask)
 81.2538 +               {
 81.2539 +                  png_memcpy(dp, sp, pixel_bytes);
 81.2540 +               }
 81.2541 +
 81.2542 +               sp += pixel_bytes;
 81.2543 +               dp += pixel_bytes;
 81.2544 +
 81.2545 +               if (m == 1)
 81.2546 +                  m = 0x80;
 81.2547 +               else
 81.2548 +                  m >>= 1;
 81.2549 +            }
 81.2550 +            break;
 81.2551 +         }
 81.2552 +      }
 81.2553 +   }
 81.2554 +}
 81.2555 +
 81.2556 +#ifdef PNG_READ_INTERLACING_SUPPORTED
 81.2557 +/* OLD pre-1.0.9 interface:
 81.2558 +void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
 81.2559 +   png_uint_32 transformations)
 81.2560 + */
 81.2561 +void /* PRIVATE */
 81.2562 +png_do_read_interlace(png_structp png_ptr)
 81.2563 +{
 81.2564 +   png_row_infop row_info = &(png_ptr->row_info);
 81.2565 +   png_bytep row = png_ptr->row_buf + 1;
 81.2566 +   int pass = png_ptr->pass;
 81.2567 +   png_uint_32 transformations = png_ptr->transformations;
 81.2568 +#ifdef PNG_USE_LOCAL_ARRAYS
 81.2569 +   /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
 81.2570 +   /* offset to next interlace block */
 81.2571 +   PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
 81.2572 +#endif
 81.2573 +
 81.2574 +   png_debug(1, "in png_do_read_interlace\n");
 81.2575 +   if (row != NULL && row_info != NULL)
 81.2576 +   {
 81.2577 +      png_uint_32 final_width;
 81.2578 +
 81.2579 +      final_width = row_info->width * png_pass_inc[pass];
 81.2580 +
 81.2581 +      switch (row_info->pixel_depth)
 81.2582 +      {
 81.2583 +         case 1:
 81.2584 +         {
 81.2585 +            png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
 81.2586 +            png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
 81.2587 +            int sshift, dshift;
 81.2588 +            int s_start, s_end, s_inc;
 81.2589 +            int jstop = png_pass_inc[pass];
 81.2590 +            png_byte v;
 81.2591 +            png_uint_32 i;
 81.2592 +            int j;
 81.2593 +
 81.2594 +#if defined(PNG_READ_PACKSWAP_SUPPORTED)
 81.2595 +            if (transformations & PNG_PACKSWAP)
 81.2596 +            {
 81.2597 +                sshift = (int)((row_info->width + 7) & 0x07);
 81.2598 +                dshift = (int)((final_width + 7) & 0x07);
 81.2599 +                s_start = 7;
 81.2600 +                s_end = 0;
 81.2601 +                s_inc = -1;
 81.2602 +            }
 81.2603 +            else
 81.2604 +#endif
 81.2605 +            {
 81.2606 +                sshift = 7 - (int)((row_info->width + 7) & 0x07);
 81.2607 +                dshift = 7 - (int)((final_width + 7) & 0x07);
 81.2608 +                s_start = 0;
 81.2609 +                s_end = 7;
 81.2610 +                s_inc = 1;
 81.2611 +            }
 81.2612 +
 81.2613 +            for (i = 0; i < row_info->width; i++)
 81.2614 +            {
 81.2615 +               v = (png_byte)((*sp >> sshift) & 0x01);
 81.2616 +               for (j = 0; j < jstop; j++)
 81.2617 +               {
 81.2618 +                  *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
 81.2619 +                  *dp |= (png_byte)(v << dshift);
 81.2620 +                  if (dshift == s_end)
 81.2621 +                  {
 81.2622 +                     dshift = s_start;
 81.2623 +                     dp--;
 81.2624 +                  }
 81.2625 +                  else
 81.2626 +                     dshift += s_inc;
 81.2627 +               }
 81.2628 +               if (sshift == s_end)
 81.2629 +               {
 81.2630 +                  sshift = s_start;
 81.2631 +                  sp--;
 81.2632 +               }
 81.2633 +               else
 81.2634 +                  sshift += s_inc;
 81.2635 +            }
 81.2636 +            break;
 81.2637 +         }
 81.2638 +         case 2:
 81.2639 +         {
 81.2640 +            png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
 81.2641 +            png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
 81.2642 +            int sshift, dshift;
 81.2643 +            int s_start, s_end, s_inc;
 81.2644 +            int jstop = png_pass_inc[pass];
 81.2645 +            png_uint_32 i;
 81.2646 +
 81.2647 +#if defined(PNG_READ_PACKSWAP_SUPPORTED)
 81.2648 +            if (transformations & PNG_PACKSWAP)
 81.2649 +            {
 81.2650 +               sshift = (int)(((row_info->width + 3) & 0x03) << 1);
 81.2651 +               dshift = (int)(((final_width + 3) & 0x03) << 1);
 81.2652 +               s_start = 6;
 81.2653 +               s_end = 0;
 81.2654 +               s_inc = -2;
 81.2655 +            }
 81.2656 +            else
 81.2657 +#endif
 81.2658 +            {
 81.2659 +               sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
 81.2660 +               dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
 81.2661 +               s_start = 0;
 81.2662 +               s_end = 6;
 81.2663 +               s_inc = 2;
 81.2664 +            }
 81.2665 +
 81.2666 +            for (i = 0; i < row_info->width; i++)
 81.2667 +            {
 81.2668 +               png_byte v;
 81.2669 +               int j;
 81.2670 +
 81.2671 +               v = (png_byte)((*sp >> sshift) & 0x03);
 81.2672 +               for (j = 0; j < jstop; j++)
 81.2673 +               {
 81.2674 +                  *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
 81.2675 +                  *dp |= (png_byte)(v << dshift);
 81.2676 +                  if (dshift == s_end)
 81.2677 +                  {
 81.2678 +                     dshift = s_start;
 81.2679 +                     dp--;
 81.2680 +                  }
 81.2681 +                  else
 81.2682 +                     dshift += s_inc;
 81.2683 +               }
 81.2684 +               if (sshift == s_end)
 81.2685 +               {
 81.2686 +                  sshift = s_start;
 81.2687 +                  sp--;
 81.2688 +               }
 81.2689 +               else
 81.2690 +                  sshift += s_inc;
 81.2691 +            }
 81.2692 +            break;
 81.2693 +         }
 81.2694 +         case 4:
 81.2695 +         {
 81.2696 +            png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
 81.2697 +            png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
 81.2698 +            int sshift, dshift;
 81.2699 +            int s_start, s_end, s_inc;
 81.2700 +            png_uint_32 i;
 81.2701 +            int jstop = png_pass_inc[pass];
 81.2702 +
 81.2703 +#if defined(PNG_READ_PACKSWAP_SUPPORTED)
 81.2704 +            if (transformations & PNG_PACKSWAP)
 81.2705 +            {
 81.2706 +               sshift = (int)(((row_info->width + 1) & 0x01) << 2);
 81.2707 +               dshift = (int)(((final_width + 1) & 0x01) << 2);
 81.2708 +               s_start = 4;
 81.2709 +               s_end = 0;
 81.2710 +               s_inc = -4;
 81.2711 +            }
 81.2712 +            else
 81.2713 +#endif
 81.2714 +            {
 81.2715 +               sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
 81.2716 +               dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
 81.2717 +               s_start = 0;
 81.2718 +               s_end = 4;
 81.2719 +               s_inc = 4;
 81.2720 +            }
 81.2721 +
 81.2722 +            for (i = 0; i < row_info->width; i++)
 81.2723 +            {
 81.2724 +               png_byte v = (png_byte)((*sp >> sshift) & 0xf);
 81.2725 +               int j;
 81.2726 +
 81.2727 +               for (j = 0; j < jstop; j++)
 81.2728 +               {
 81.2729 +                  *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
 81.2730 +                  *dp |= (png_byte)(v << dshift);
 81.2731 +                  if (dshift == s_end)
 81.2732 +                  {
 81.2733 +                     dshift = s_start;
 81.2734 +                     dp--;
 81.2735 +                  }
 81.2736 +                  else
 81.2737 +                     dshift += s_inc;
 81.2738 +               }
 81.2739 +               if (sshift == s_end)
 81.2740 +               {
 81.2741 +                  sshift = s_start;
 81.2742 +                  sp--;
 81.2743 +               }
 81.2744 +               else
 81.2745 +                  sshift += s_inc;
 81.2746 +            }
 81.2747 +            break;
 81.2748 +         }
 81.2749 +         default:
 81.2750 +         {
 81.2751 +            png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
 81.2752 +            png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
 81.2753 +            png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
 81.2754 +
 81.2755 +            int jstop = png_pass_inc[pass];
 81.2756 +            png_uint_32 i;
 81.2757 +
 81.2758 +            for (i = 0; i < row_info->width; i++)
 81.2759 +            {
 81.2760 +               png_byte v[8];
 81.2761 +               int j;
 81.2762 +
 81.2763 +               png_memcpy(v, sp, pixel_bytes);
 81.2764 +               for (j = 0; j < jstop; j++)
 81.2765 +               {
 81.2766 +                  png_memcpy(dp, v, pixel_bytes);
 81.2767 +                  dp -= pixel_bytes;
 81.2768 +               }
 81.2769 +               sp -= pixel_bytes;
 81.2770 +            }
 81.2771 +            break;
 81.2772 +         }
 81.2773 +      }
 81.2774 +      row_info->width = final_width;
 81.2775 +      row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
 81.2776 +   }
 81.2777 +#if !defined(PNG_READ_PACKSWAP_SUPPORTED)
 81.2778 +   transformations = transformations; /* silence compiler warning */
 81.2779 +#endif
 81.2780 +}
 81.2781 +#endif /* PNG_READ_INTERLACING_SUPPORTED */
 81.2782 +
 81.2783 +void /* PRIVATE */
 81.2784 +png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
 81.2785 +   png_bytep prev_row, int filter)
 81.2786 +{
 81.2787 +   png_debug(1, "in png_read_filter_row\n");
 81.2788 +   png_debug2(2, "row = %lu, filter = %d\n", png_ptr->row_number, filter);
 81.2789 +   switch (filter)
 81.2790 +   {
 81.2791 +      case PNG_FILTER_VALUE_NONE:
 81.2792 +         break;
 81.2793 +      case PNG_FILTER_VALUE_SUB:
 81.2794 +      {
 81.2795 +         png_uint_32 i;
 81.2796 +         png_uint_32 istop = row_info->rowbytes;
 81.2797 +         png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
 81.2798 +         png_bytep rp = row + bpp;
 81.2799 +         png_bytep lp = row;
 81.2800 +
 81.2801 +         for (i = bpp; i < istop; i++)
 81.2802 +         {
 81.2803 +            *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
 81.2804 +            rp++;
 81.2805 +         }
 81.2806 +         break;
 81.2807 +      }
 81.2808 +      case PNG_FILTER_VALUE_UP:
 81.2809 +      {
 81.2810 +         png_uint_32 i;
 81.2811 +         png_uint_32 istop = row_info->rowbytes;
 81.2812 +         png_bytep rp = row;
 81.2813 +         png_bytep pp = prev_row;
 81.2814 +
 81.2815 +         for (i = 0; i < istop; i++)
 81.2816 +         {
 81.2817 +            *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
 81.2818 +            rp++;
 81.2819 +         }
 81.2820 +         break;
 81.2821 +      }
 81.2822 +      case PNG_FILTER_VALUE_AVG:
 81.2823 +      {
 81.2824 +         png_uint_32 i;
 81.2825 +         png_bytep rp = row;
 81.2826 +         png_bytep pp = prev_row;
 81.2827 +         png_bytep lp = row;
 81.2828 +         png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
 81.2829 +         png_uint_32 istop = row_info->rowbytes - bpp;
 81.2830 +
 81.2831 +         for (i = 0; i < bpp; i++)
 81.2832 +         {
 81.2833 +            *rp = (png_byte)(((int)(*rp) +
 81.2834 +               ((int)(*pp++) / 2 )) & 0xff);
 81.2835 +            rp++;
 81.2836 +         }
 81.2837 +
 81.2838 +         for (i = 0; i < istop; i++)
 81.2839 +         {
 81.2840 +            *rp = (png_byte)(((int)(*rp) +
 81.2841 +               (int)(*pp++ + *lp++) / 2 ) & 0xff);
 81.2842 +            rp++;
 81.2843 +         }
 81.2844 +         break;
 81.2845 +      }
 81.2846 +      case PNG_FILTER_VALUE_PAETH:
 81.2847 +      {
 81.2848 +         png_uint_32 i;
 81.2849 +         png_bytep rp = row;
 81.2850 +         png_bytep pp = prev_row;
 81.2851 +         png_bytep lp = row;
 81.2852 +         png_bytep cp = prev_row;
 81.2853 +         png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
 81.2854 +         png_uint_32 istop=row_info->rowbytes - bpp;
 81.2855 +
 81.2856 +         for (i = 0; i < bpp; i++)
 81.2857 +         {
 81.2858 +            *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
 81.2859 +            rp++;
 81.2860 +         }
 81.2861 +
 81.2862 +         for (i = 0; i < istop; i++)   /* use leftover rp,pp */
 81.2863 +         {
 81.2864 +            int a, b, c, pa, pb, pc, p;
 81.2865 +
 81.2866 +            a = *lp++;
 81.2867 +            b = *pp++;
 81.2868 +            c = *cp++;
 81.2869 +
 81.2870 +            p = b - c;
 81.2871 +            pc = a - c;
 81.2872 +
 81.2873 +#ifdef PNG_USE_ABS
 81.2874 +            pa = abs(p);
 81.2875 +            pb = abs(pc);
 81.2876 +            pc = abs(p + pc);
 81.2877 +#else
 81.2878 +            pa = p < 0 ? -p : p;
 81.2879 +            pb = pc < 0 ? -pc : pc;
 81.2880 +            pc = (p + pc) < 0 ? -(p + pc) : p + pc;
 81.2881 +#endif
 81.2882 +
 81.2883 +            /*
 81.2884 +               if (pa <= pb && pa <= pc)
 81.2885 +                  p = a;
 81.2886 +               else if (pb <= pc)
 81.2887 +                  p = b;
 81.2888 +               else
 81.2889 +                  p = c;
 81.2890 +             */
 81.2891 +
 81.2892 +            p = (pa <= pb && pa <= pc) ? a : (pb <= pc) ? b : c;
 81.2893 +
 81.2894 +            *rp = (png_byte)(((int)(*rp) + p) & 0xff);
 81.2895 +            rp++;
 81.2896 +         }
 81.2897 +         break;
 81.2898 +      }
 81.2899 +      default:
 81.2900 +         png_warning(png_ptr, "Ignoring bad adaptive filter type");
 81.2901 +         *row = 0;
 81.2902 +         break;
 81.2903 +   }
 81.2904 +}
 81.2905 +
 81.2906 +void /* PRIVATE */
 81.2907 +png_read_finish_row(png_structp png_ptr)
 81.2908 +{
 81.2909 +#ifdef PNG_USE_LOCAL_ARRAYS
 81.2910 +#ifdef PNG_READ_INTERLACING_SUPPORTED
 81.2911 +   /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
 81.2912 +
 81.2913 +   /* start of interlace block */
 81.2914 +   PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
 81.2915 +
 81.2916 +   /* offset to next interlace block */
 81.2917 +   PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
 81.2918 +
 81.2919 +   /* start of interlace block in the y direction */
 81.2920 +   PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
 81.2921 +
 81.2922 +   /* offset to next interlace block in the y direction */
 81.2923 +   PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
 81.2924 +#endif /* PNG_READ_INTERLACING_SUPPORTED */
 81.2925 +#endif
 81.2926 +
 81.2927 +   png_debug(1, "in png_read_finish_row\n");
 81.2928 +   png_ptr->row_number++;
 81.2929 +   if (png_ptr->row_number < png_ptr->num_rows)
 81.2930 +      return;
 81.2931 +
 81.2932 +#ifdef PNG_READ_INTERLACING_SUPPORTED
 81.2933 +   if (png_ptr->interlaced)
 81.2934 +   {
 81.2935 +      png_ptr->row_number = 0;
 81.2936 +      png_memset_check(png_ptr, png_ptr->prev_row, 0,
 81.2937 +         png_ptr->rowbytes + 1);
 81.2938 +      do
 81.2939 +      {
 81.2940 +         png_ptr->pass++;
 81.2941 +         if (png_ptr->pass >= 7)
 81.2942 +            break;
 81.2943 +         png_ptr->iwidth = (png_ptr->width +
 81.2944 +            png_pass_inc[png_ptr->pass] - 1 -
 81.2945 +            png_pass_start[png_ptr->pass]) /
 81.2946 +            png_pass_inc[png_ptr->pass];
 81.2947 +
 81.2948 +         png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
 81.2949 +            png_ptr->iwidth) + 1;
 81.2950 +
 81.2951 +         if (!(png_ptr->transformations & PNG_INTERLACE))
 81.2952 +         {
 81.2953 +            png_ptr->num_rows = (png_ptr->height +
 81.2954 +               png_pass_yinc[png_ptr->pass] - 1 -
 81.2955 +               png_pass_ystart[png_ptr->pass]) /
 81.2956 +               png_pass_yinc[png_ptr->pass];
 81.2957 +            if (!(png_ptr->num_rows))
 81.2958 +               continue;
 81.2959 +         }
 81.2960 +         else  /* if (png_ptr->transformations & PNG_INTERLACE) */
 81.2961 +            break;
 81.2962 +      } while (png_ptr->iwidth == 0);
 81.2963 +
 81.2964 +      if (png_ptr->pass < 7)
 81.2965 +         return;
 81.2966 +   }
 81.2967 +#endif /* PNG_READ_INTERLACING_SUPPORTED */
 81.2968 +
 81.2969 +   if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
 81.2970 +   {
 81.2971 +#ifdef PNG_USE_LOCAL_ARRAYS
 81.2972 +      PNG_CONST PNG_IDAT;
 81.2973 +#endif
 81.2974 +      char extra;
 81.2975 +      int ret;
 81.2976 +
 81.2977 +      png_ptr->zstream.next_out = (Byte *)&extra;
 81.2978 +      png_ptr->zstream.avail_out = (uInt)1;
 81.2979 +      for (;;)
 81.2980 +      {
 81.2981 +         if (!(png_ptr->zstream.avail_in))
 81.2982 +         {
 81.2983 +            while (!png_ptr->idat_size)
 81.2984 +            {
 81.2985 +               png_byte chunk_length[4];
 81.2986 +
 81.2987 +               png_crc_finish(png_ptr, 0);
 81.2988 +
 81.2989 +               png_read_data(png_ptr, chunk_length, 4);
 81.2990 +               png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
 81.2991 +               png_reset_crc(png_ptr);
 81.2992 +               png_crc_read(png_ptr, png_ptr->chunk_name, 4);
 81.2993 +               if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
 81.2994 +                  png_error(png_ptr, "Not enough image data");
 81.2995 +
 81.2996 +            }
 81.2997 +            png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
 81.2998 +            png_ptr->zstream.next_in = png_ptr->zbuf;
 81.2999 +            if (png_ptr->zbuf_size > png_ptr->idat_size)
 81.3000 +               png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
 81.3001 +            png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
 81.3002 +            png_ptr->idat_size -= png_ptr->zstream.avail_in;
 81.3003 +         }
 81.3004 +         ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
 81.3005 +         if (ret == Z_STREAM_END)
 81.3006 +         {
 81.3007 +            if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
 81.3008 +               png_ptr->idat_size)
 81.3009 +               png_warning(png_ptr, "Extra compressed data");
 81.3010 +            png_ptr->mode |= PNG_AFTER_IDAT;
 81.3011 +            png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
 81.3012 +            break;
 81.3013 +         }
 81.3014 +         if (ret != Z_OK)
 81.3015 +            png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
 81.3016 +                      "Decompression Error");
 81.3017 +
 81.3018 +         if (!(png_ptr->zstream.avail_out))
 81.3019 +         {
 81.3020 +            png_warning(png_ptr, "Extra compressed data.");
 81.3021 +            png_ptr->mode |= PNG_AFTER_IDAT;
 81.3022 +            png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
 81.3023 +            break;
 81.3024 +         }
 81.3025 +
 81.3026 +      }
 81.3027 +      png_ptr->zstream.avail_out = 0;
 81.3028 +   }
 81.3029 +
 81.3030 +   if (png_ptr->idat_size || png_ptr->zstream.avail_in)
 81.3031 +      png_warning(png_ptr, "Extra compression data");
 81.3032 +
 81.3033 +   inflateReset(&png_ptr->zstream);
 81.3034 +
 81.3035 +   png_ptr->mode |= PNG_AFTER_IDAT;
 81.3036 +}
 81.3037 +
 81.3038 +void /* PRIVATE */
 81.3039 +png_read_start_row(png_structp png_ptr)
 81.3040 +{
 81.3041 +#ifdef PNG_USE_LOCAL_ARRAYS
 81.3042 +#ifdef PNG_READ_INTERLACING_SUPPORTED
 81.3043 +   /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
 81.3044 +
 81.3045 +   /* start of interlace block */
 81.3046 +   PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
 81.3047 +
 81.3048 +   /* offset to next interlace block */
 81.3049 +   PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
 81.3050 +
 81.3051 +   /* start of interlace block in the y direction */
 81.3052 +   PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
 81.3053 +
 81.3054 +   /* offset to next interlace block in the y direction */
 81.3055 +   PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
 81.3056 +#endif
 81.3057 +#endif
 81.3058 +
 81.3059 +   int max_pixel_depth;
 81.3060 +   png_size_t row_bytes;
 81.3061 +
 81.3062 +   png_debug(1, "in png_read_start_row\n");
 81.3063 +   png_ptr->zstream.avail_in = 0;
 81.3064 +   png_init_read_transformations(png_ptr);
 81.3065 +#ifdef PNG_READ_INTERLACING_SUPPORTED
 81.3066 +   if (png_ptr->interlaced)
 81.3067 +   {
 81.3068 +      if (!(png_ptr->transformations & PNG_INTERLACE))
 81.3069 +         png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
 81.3070 +            png_pass_ystart[0]) / png_pass_yinc[0];
 81.3071 +      else
 81.3072 +         png_ptr->num_rows = png_ptr->height;
 81.3073 +
 81.3074 +      png_ptr->iwidth = (png_ptr->width +
 81.3075 +         png_pass_inc[png_ptr->pass] - 1 -
 81.3076 +         png_pass_start[png_ptr->pass]) /
 81.3077 +         png_pass_inc[png_ptr->pass];
 81.3078 +
 81.3079 +         png_ptr->irowbytes =
 81.3080 +            PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1;
 81.3081 +   }
 81.3082 +   else
 81.3083 +#endif /* PNG_READ_INTERLACING_SUPPORTED */
 81.3084 +   {
 81.3085 +      png_ptr->num_rows = png_ptr->height;
 81.3086 +      png_ptr->iwidth = png_ptr->width;
 81.3087 +      png_ptr->irowbytes = png_ptr->rowbytes + 1;
 81.3088 +   }
 81.3089 +   max_pixel_depth = png_ptr->pixel_depth;
 81.3090 +
 81.3091 +#if defined(PNG_READ_PACK_SUPPORTED)
 81.3092 +   if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
 81.3093 +      max_pixel_depth = 8;
 81.3094 +#endif
 81.3095 +
 81.3096 +#if defined(PNG_READ_EXPAND_SUPPORTED)
 81.3097 +   if (png_ptr->transformations & PNG_EXPAND)
 81.3098 +   {
 81.3099 +      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 81.3100 +      {
 81.3101 +         if (png_ptr->num_trans)
 81.3102 +            max_pixel_depth = 32;
 81.3103 +         else
 81.3104 +            max_pixel_depth = 24;
 81.3105 +      }
 81.3106 +      else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
 81.3107 +      {
 81.3108 +         if (max_pixel_depth < 8)
 81.3109 +            max_pixel_depth = 8;
 81.3110 +         if (png_ptr->num_trans)
 81.3111 +            max_pixel_depth *= 2;
 81.3112 +      }
 81.3113 +      else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
 81.3114 +      {
 81.3115 +         if (png_ptr->num_trans)
 81.3116 +         {
 81.3117 +            max_pixel_depth *= 4;
 81.3118 +            max_pixel_depth /= 3;
 81.3119 +         }
 81.3120 +      }
 81.3121 +   }
 81.3122 +#endif
 81.3123 +
 81.3124 +#if defined(PNG_READ_FILLER_SUPPORTED)
 81.3125 +   if (png_ptr->transformations & (PNG_FILLER))
 81.3126 +   {
 81.3127 +      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 81.3128 +         max_pixel_depth = 32;
 81.3129 +      else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
 81.3130 +      {
 81.3131 +         if (max_pixel_depth <= 8)
 81.3132 +            max_pixel_depth = 16;
 81.3133 +         else
 81.3134 +            max_pixel_depth = 32;
 81.3135 +      }
 81.3136 +      else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
 81.3137 +      {
 81.3138 +         if (max_pixel_depth <= 32)
 81.3139 +            max_pixel_depth = 32;
 81.3140 +         else
 81.3141 +            max_pixel_depth = 64;
 81.3142 +      }
 81.3143 +   }
 81.3144 +#endif
 81.3145 +
 81.3146 +#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
 81.3147 +   if (png_ptr->transformations & PNG_GRAY_TO_RGB)
 81.3148 +   {
 81.3149 +      if (
 81.3150 +#if defined(PNG_READ_EXPAND_SUPPORTED)
 81.3151 +        (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
 81.3152 +#endif
 81.3153 +#if defined(PNG_READ_FILLER_SUPPORTED)
 81.3154 +        (png_ptr->transformations & (PNG_FILLER)) ||
 81.3155 +#endif
 81.3156 +        png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
 81.3157 +      {
 81.3158 +         if (max_pixel_depth <= 16)
 81.3159 +            max_pixel_depth = 32;
 81.3160 +         else
 81.3161 +            max_pixel_depth = 64;
 81.3162 +      }
 81.3163 +      else
 81.3164 +      {
 81.3165 +         if (max_pixel_depth <= 8)
 81.3166 +           {
 81.3167 +             if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
 81.3168 +               max_pixel_depth = 32;
 81.3169 +             else
 81.3170 +               max_pixel_depth = 24;
 81.3171 +           }
 81.3172 +         else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
 81.3173 +            max_pixel_depth = 64;
 81.3174 +         else
 81.3175 +            max_pixel_depth = 48;
 81.3176 +      }
 81.3177 +   }
 81.3178 +#endif
 81.3179 +
 81.3180 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
 81.3181 +defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
 81.3182 +   if (png_ptr->transformations & PNG_USER_TRANSFORM)
 81.3183 +     {
 81.3184 +       int user_pixel_depth = png_ptr->user_transform_depth*
 81.3185 +         png_ptr->user_transform_channels;
 81.3186 +       if (user_pixel_depth > max_pixel_depth)
 81.3187 +         max_pixel_depth=user_pixel_depth;
 81.3188 +     }
 81.3189 +#endif
 81.3190 +
 81.3191 +   /* align the width on the next larger 8 pixels.  Mainly used
 81.3192 +      for interlacing */
 81.3193 +   row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
 81.3194 +   /* calculate the maximum bytes needed, adding a byte and a pixel
 81.3195 +      for safety's sake */
 81.3196 +   row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
 81.3197 +      1 + ((max_pixel_depth + 7) >> 3);
 81.3198 +#ifdef PNG_MAX_MALLOC_64K
 81.3199 +   if (row_bytes > (png_uint_32)65536L)
 81.3200 +      png_error(png_ptr, "This image requires a row greater than 64KB");
 81.3201 +#endif
 81.3202 +
 81.3203 +   if (row_bytes + 64 > png_ptr->old_big_row_buf_size)
 81.3204 +   {
 81.3205 +     png_free(png_ptr, png_ptr->big_row_buf);
 81.3206 +     png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
 81.3207 +     png_ptr->row_buf = png_ptr->big_row_buf+32;
 81.3208 +     png_ptr->old_big_row_buf_size = row_bytes+64;
 81.3209 +   }
 81.3210 +
 81.3211 +#ifdef PNG_MAX_MALLOC_64K
 81.3212 +   if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
 81.3213 +      png_error(png_ptr, "This image requires a row greater than 64KB");
 81.3214 +#endif
 81.3215 +   if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
 81.3216 +      png_error(png_ptr, "Row has too many bytes to allocate in memory.");
 81.3217 +
 81.3218 +   if (png_ptr->rowbytes+1 > png_ptr->old_prev_row_size)
 81.3219 +   {
 81.3220 +     png_free(png_ptr, png_ptr->prev_row);
 81.3221 +     png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
 81.3222 +        png_ptr->rowbytes + 1));
 81.3223 +     png_ptr->old_prev_row_size = png_ptr->rowbytes+1;
 81.3224 +   }
 81.3225 +
 81.3226 +   png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
 81.3227 +
 81.3228 +   png_debug1(3, "width = %lu,\n", png_ptr->width);
 81.3229 +   png_debug1(3, "height = %lu,\n", png_ptr->height);
 81.3230 +   png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
 81.3231 +   png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
 81.3232 +   png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
 81.3233 +   png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
 81.3234 +
 81.3235 +   png_ptr->flags |= PNG_FLAG_ROW_INIT;
 81.3236 +}
 81.3237 +#endif /* PNG_READ_SUPPORTED */
    82.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    82.2 +++ b/libs/libpng/pngset.c	Thu Sep 08 06:28:38 2011 +0300
    82.3 @@ -0,0 +1,1293 @@
    82.4 +
    82.5 +/* pngset.c - storage of image information into info struct
    82.6 + *
    82.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    82.8 + * For conditions of distribution and use, see copyright notice in png.h
    82.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   82.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   82.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   82.12 + *
   82.13 + * The functions here are used during reads to store data from the file
   82.14 + * into the info struct, and during writes to store application data
   82.15 + * into the info struct for writing into the file.  This abstracts the
   82.16 + * info struct and allows us to change the structure in the future.
   82.17 + */
   82.18 +
   82.19 +#define PNG_INTERNAL
   82.20 +#include "png.h"
   82.21 +#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
   82.22 +
   82.23 +#if defined(PNG_bKGD_SUPPORTED)
   82.24 +void PNGAPI
   82.25 +png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
   82.26 +{
   82.27 +   png_debug1(1, "in %s storage function\n", "bKGD");
   82.28 +   if (png_ptr == NULL || info_ptr == NULL)
   82.29 +      return;
   82.30 +
   82.31 +   png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
   82.32 +   info_ptr->valid |= PNG_INFO_bKGD;
   82.33 +}
   82.34 +#endif
   82.35 +
   82.36 +#if defined(PNG_cHRM_SUPPORTED)
   82.37 +#ifdef PNG_FLOATING_POINT_SUPPORTED
   82.38 +void PNGAPI
   82.39 +png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
   82.40 +   double white_x, double white_y, double red_x, double red_y,
   82.41 +   double green_x, double green_y, double blue_x, double blue_y)
   82.42 +{
   82.43 +   png_debug1(1, "in %s storage function\n", "cHRM");
   82.44 +   if (png_ptr == NULL || info_ptr == NULL)
   82.45 +      return;
   82.46 +   if (!(white_x || white_y || red_x || red_y || green_x || green_y ||
   82.47 +       blue_x || blue_y))
   82.48 +   {
   82.49 +      png_warning(png_ptr,
   82.50 +        "Ignoring attempt to set all-zero chromaticity values");
   82.51 +      return;
   82.52 +   }
   82.53 +   if (white_x < 0.0 || white_y < 0.0 ||
   82.54 +         red_x < 0.0 ||   red_y < 0.0 ||
   82.55 +       green_x < 0.0 || green_y < 0.0 ||
   82.56 +        blue_x < 0.0 ||  blue_y < 0.0)
   82.57 +   {
   82.58 +      png_warning(png_ptr,
   82.59 +        "Ignoring attempt to set negative chromaticity value");
   82.60 +      return;
   82.61 +   }
   82.62 +   if (white_x > 21474.83 || white_y > 21474.83 ||
   82.63 +         red_x > 21474.83 ||   red_y > 21474.83 ||
   82.64 +       green_x > 21474.83 || green_y > 21474.83 ||
   82.65 +        blue_x > 21474.83 ||  blue_y > 21474.83)
   82.66 +   {
   82.67 +      png_warning(png_ptr,
   82.68 +        "Ignoring attempt to set chromaticity value exceeding 21474.83");
   82.69 +      return;
   82.70 +   }
   82.71 +
   82.72 +   info_ptr->x_white = (float)white_x;
   82.73 +   info_ptr->y_white = (float)white_y;
   82.74 +   info_ptr->x_red   = (float)red_x;
   82.75 +   info_ptr->y_red   = (float)red_y;
   82.76 +   info_ptr->x_green = (float)green_x;
   82.77 +   info_ptr->y_green = (float)green_y;
   82.78 +   info_ptr->x_blue  = (float)blue_x;
   82.79 +   info_ptr->y_blue  = (float)blue_y;
   82.80 +#ifdef PNG_FIXED_POINT_SUPPORTED
   82.81 +   info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
   82.82 +   info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
   82.83 +   info_ptr->int_x_red   = (png_fixed_point)(  red_x*100000.+0.5);
   82.84 +   info_ptr->int_y_red   = (png_fixed_point)(  red_y*100000.+0.5);
   82.85 +   info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
   82.86 +   info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
   82.87 +   info_ptr->int_x_blue  = (png_fixed_point)( blue_x*100000.+0.5);
   82.88 +   info_ptr->int_y_blue  = (png_fixed_point)( blue_y*100000.+0.5);
   82.89 +#endif
   82.90 +   info_ptr->valid |= PNG_INFO_cHRM;
   82.91 +}
   82.92 +#endif
   82.93 +#ifdef PNG_FIXED_POINT_SUPPORTED
   82.94 +void PNGAPI
   82.95 +png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
   82.96 +   png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
   82.97 +   png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
   82.98 +   png_fixed_point blue_x, png_fixed_point blue_y)
   82.99 +{
  82.100 +   png_debug1(1, "in %s storage function\n", "cHRM");
  82.101 +   if (png_ptr == NULL || info_ptr == NULL)
  82.102 +      return;
  82.103 +
  82.104 +   if (!(white_x || white_y || red_x || red_y || green_x || green_y ||
  82.105 +       blue_x || blue_y))
  82.106 +   {
  82.107 +      png_warning(png_ptr,
  82.108 +        "Ignoring attempt to set all-zero chromaticity values");
  82.109 +      return;
  82.110 +   }
  82.111 +   if (white_x < 0 || white_y < 0 ||
  82.112 +         red_x < 0 ||   red_y < 0 ||
  82.113 +       green_x < 0 || green_y < 0 ||
  82.114 +        blue_x < 0 ||  blue_y < 0)
  82.115 +   {
  82.116 +      png_warning(png_ptr,
  82.117 +        "Ignoring attempt to set negative chromaticity value");
  82.118 +      return;
  82.119 +   }
  82.120 +   if (white_x > (png_fixed_point) PNG_UINT_31_MAX ||
  82.121 +       white_y > (png_fixed_point) PNG_UINT_31_MAX ||
  82.122 +         red_x > (png_fixed_point) PNG_UINT_31_MAX ||
  82.123 +         red_y > (png_fixed_point) PNG_UINT_31_MAX ||
  82.124 +       green_x > (png_fixed_point) PNG_UINT_31_MAX ||
  82.125 +       green_y > (png_fixed_point) PNG_UINT_31_MAX ||
  82.126 +        blue_x > (png_fixed_point) PNG_UINT_31_MAX ||
  82.127 +        blue_y > (png_fixed_point) PNG_UINT_31_MAX )
  82.128 +   {
  82.129 +      png_warning(png_ptr,
  82.130 +        "Ignoring attempt to set chromaticity value exceeding 21474.83");
  82.131 +      return;
  82.132 +   }
  82.133 +   info_ptr->int_x_white = white_x;
  82.134 +   info_ptr->int_y_white = white_y;
  82.135 +   info_ptr->int_x_red   = red_x;
  82.136 +   info_ptr->int_y_red   = red_y;
  82.137 +   info_ptr->int_x_green = green_x;
  82.138 +   info_ptr->int_y_green = green_y;
  82.139 +   info_ptr->int_x_blue  = blue_x;
  82.140 +   info_ptr->int_y_blue  = blue_y;
  82.141 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  82.142 +   info_ptr->x_white = (float)(white_x/100000.);
  82.143 +   info_ptr->y_white = (float)(white_y/100000.);
  82.144 +   info_ptr->x_red   = (float)(  red_x/100000.);
  82.145 +   info_ptr->y_red   = (float)(  red_y/100000.);
  82.146 +   info_ptr->x_green = (float)(green_x/100000.);
  82.147 +   info_ptr->y_green = (float)(green_y/100000.);
  82.148 +   info_ptr->x_blue  = (float)( blue_x/100000.);
  82.149 +   info_ptr->y_blue  = (float)( blue_y/100000.);
  82.150 +#endif
  82.151 +   info_ptr->valid |= PNG_INFO_cHRM;
  82.152 +}
  82.153 +#endif
  82.154 +#endif
  82.155 +
  82.156 +#if defined(PNG_gAMA_SUPPORTED)
  82.157 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  82.158 +void PNGAPI
  82.159 +png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  82.160 +{
  82.161 +   double gamma;
  82.162 +   png_debug1(1, "in %s storage function\n", "gAMA");
  82.163 +   if (png_ptr == NULL || info_ptr == NULL)
  82.164 +      return;
  82.165 +
  82.166 +   /* Check for overflow */
  82.167 +   if (file_gamma > 21474.83)
  82.168 +   {
  82.169 +      png_warning(png_ptr, "Limiting gamma to 21474.83");
  82.170 +      gamma=21474.83;
  82.171 +   }
  82.172 +   else
  82.173 +      gamma = file_gamma;
  82.174 +   info_ptr->gamma = (float)gamma;
  82.175 +#ifdef PNG_FIXED_POINT_SUPPORTED
  82.176 +   info_ptr->int_gamma = (int)(gamma*100000.+.5);
  82.177 +#endif
  82.178 +   info_ptr->valid |= PNG_INFO_gAMA;
  82.179 +   if (gamma == 0.0)
  82.180 +      png_warning(png_ptr, "Setting gamma=0");
  82.181 +}
  82.182 +#endif
  82.183 +void PNGAPI
  82.184 +png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  82.185 +   int_gamma)
  82.186 +{
  82.187 +   png_fixed_point gamma;
  82.188 +
  82.189 +   png_debug1(1, "in %s storage function\n", "gAMA");
  82.190 +   if (png_ptr == NULL || info_ptr == NULL)
  82.191 +      return;
  82.192 +
  82.193 +   if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  82.194 +   {
  82.195 +     png_warning(png_ptr, "Limiting gamma to 21474.83");
  82.196 +     gamma=PNG_UINT_31_MAX;
  82.197 +   }
  82.198 +   else
  82.199 +   {
  82.200 +     if (int_gamma < 0)
  82.201 +     {
  82.202 +       png_warning(png_ptr, "Setting negative gamma to zero");
  82.203 +       gamma = 0;
  82.204 +     }
  82.205 +     else
  82.206 +       gamma = int_gamma;
  82.207 +   }
  82.208 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  82.209 +   info_ptr->gamma = (float)(gamma/100000.);
  82.210 +#endif
  82.211 +#ifdef PNG_FIXED_POINT_SUPPORTED
  82.212 +   info_ptr->int_gamma = gamma;
  82.213 +#endif
  82.214 +   info_ptr->valid |= PNG_INFO_gAMA;
  82.215 +   if (gamma == 0)
  82.216 +      png_warning(png_ptr, "Setting gamma=0");
  82.217 +}
  82.218 +#endif
  82.219 +
  82.220 +#if defined(PNG_hIST_SUPPORTED)
  82.221 +void PNGAPI
  82.222 +png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  82.223 +{
  82.224 +   int i;
  82.225 +
  82.226 +   png_debug1(1, "in %s storage function\n", "hIST");
  82.227 +   if (png_ptr == NULL || info_ptr == NULL)
  82.228 +      return;
  82.229 +   if (info_ptr->num_palette == 0 || info_ptr->num_palette
  82.230 +       > PNG_MAX_PALETTE_LENGTH)
  82.231 +   {
  82.232 +       png_warning(png_ptr,
  82.233 +          "Invalid palette size, hIST allocation skipped.");
  82.234 +       return;
  82.235 +   }
  82.236 +
  82.237 +#ifdef PNG_FREE_ME_SUPPORTED
  82.238 +   png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  82.239 +#endif
  82.240 +   /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  82.241 +      1.2.1 */
  82.242 +   png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  82.243 +      (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof(png_uint_16)));
  82.244 +   if (png_ptr->hist == NULL)
  82.245 +     {
  82.246 +       png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  82.247 +       return;
  82.248 +     }
  82.249 +
  82.250 +   for (i = 0; i < info_ptr->num_palette; i++)
  82.251 +       png_ptr->hist[i] = hist[i];
  82.252 +   info_ptr->hist = png_ptr->hist;
  82.253 +   info_ptr->valid |= PNG_INFO_hIST;
  82.254 +
  82.255 +#ifdef PNG_FREE_ME_SUPPORTED
  82.256 +   info_ptr->free_me |= PNG_FREE_HIST;
  82.257 +#else
  82.258 +   png_ptr->flags |= PNG_FLAG_FREE_HIST;
  82.259 +#endif
  82.260 +}
  82.261 +#endif
  82.262 +
  82.263 +void PNGAPI
  82.264 +png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  82.265 +   png_uint_32 width, png_uint_32 height, int bit_depth,
  82.266 +   int color_type, int interlace_type, int compression_type,
  82.267 +   int filter_type)
  82.268 +{
  82.269 +   png_debug1(1, "in %s storage function\n", "IHDR");
  82.270 +   if (png_ptr == NULL || info_ptr == NULL)
  82.271 +      return;
  82.272 +
  82.273 +   /* check for width and height valid values */
  82.274 +   if (width == 0 || height == 0)
  82.275 +      png_error(png_ptr, "Image width or height is zero in IHDR");
  82.276 +#ifdef PNG_SET_USER_LIMITS_SUPPORTED
  82.277 +   if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  82.278 +      png_error(png_ptr, "image size exceeds user limits in IHDR");
  82.279 +#else
  82.280 +   if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  82.281 +      png_error(png_ptr, "image size exceeds user limits in IHDR");
  82.282 +#endif
  82.283 +   if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  82.284 +      png_error(png_ptr, "Invalid image size in IHDR");
  82.285 +   if ( width > (PNG_UINT_32_MAX
  82.286 +                 >> 3)      /* 8-byte RGBA pixels */
  82.287 +                 - 64       /* bigrowbuf hack */
  82.288 +                 - 1        /* filter byte */
  82.289 +                 - 7*8      /* rounding of width to multiple of 8 pixels */
  82.290 +                 - 8)       /* extra max_pixel_depth pad */
  82.291 +      png_warning(png_ptr, "Width is too large for libpng to process pixels");
  82.292 +
  82.293 +   /* check other values */
  82.294 +   if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  82.295 +      bit_depth != 8 && bit_depth != 16)
  82.296 +      png_error(png_ptr, "Invalid bit depth in IHDR");
  82.297 +
  82.298 +   if (color_type < 0 || color_type == 1 ||
  82.299 +      color_type == 5 || color_type > 6)
  82.300 +      png_error(png_ptr, "Invalid color type in IHDR");
  82.301 +
  82.302 +   if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  82.303 +       ((color_type == PNG_COLOR_TYPE_RGB ||
  82.304 +         color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  82.305 +         color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  82.306 +      png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  82.307 +
  82.308 +   if (interlace_type >= PNG_INTERLACE_LAST)
  82.309 +      png_error(png_ptr, "Unknown interlace method in IHDR");
  82.310 +
  82.311 +   if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  82.312 +      png_error(png_ptr, "Unknown compression method in IHDR");
  82.313 +
  82.314 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
  82.315 +   /* Accept filter_method 64 (intrapixel differencing) only if
  82.316 +    * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  82.317 +    * 2. Libpng did not read a PNG signature (this filter_method is only
  82.318 +    *    used in PNG datastreams that are embedded in MNG datastreams) and
  82.319 +    * 3. The application called png_permit_mng_features with a mask that
  82.320 +    *    included PNG_FLAG_MNG_FILTER_64 and
  82.321 +    * 4. The filter_method is 64 and
  82.322 +    * 5. The color_type is RGB or RGBA
  82.323 +    */
  82.324 +   if ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  82.325 +      png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
  82.326 +   if (filter_type != PNG_FILTER_TYPE_BASE)
  82.327 +   {
  82.328 +     if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  82.329 +        (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  82.330 +        ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  82.331 +        (color_type == PNG_COLOR_TYPE_RGB ||
  82.332 +         color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  82.333 +        png_error(png_ptr, "Unknown filter method in IHDR");
  82.334 +     if (png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  82.335 +        png_warning(png_ptr, "Invalid filter method in IHDR");
  82.336 +   }
  82.337 +#else
  82.338 +   if (filter_type != PNG_FILTER_TYPE_BASE)
  82.339 +      png_error(png_ptr, "Unknown filter method in IHDR");
  82.340 +#endif
  82.341 +
  82.342 +   info_ptr->width = width;
  82.343 +   info_ptr->height = height;
  82.344 +   info_ptr->bit_depth = (png_byte)bit_depth;
  82.345 +   info_ptr->color_type =(png_byte) color_type;
  82.346 +   info_ptr->compression_type = (png_byte)compression_type;
  82.347 +   info_ptr->filter_type = (png_byte)filter_type;
  82.348 +   info_ptr->interlace_type = (png_byte)interlace_type;
  82.349 +   if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  82.350 +      info_ptr->channels = 1;
  82.351 +   else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  82.352 +      info_ptr->channels = 3;
  82.353 +   else
  82.354 +      info_ptr->channels = 1;
  82.355 +   if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  82.356 +      info_ptr->channels++;
  82.357 +   info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  82.358 +
  82.359 +   /* check for potential overflow */
  82.360 +   if (width > (PNG_UINT_32_MAX
  82.361 +                 >> 3)      /* 8-byte RGBA pixels */
  82.362 +                 - 64       /* bigrowbuf hack */
  82.363 +                 - 1        /* filter byte */
  82.364 +                 - 7*8      /* rounding of width to multiple of 8 pixels */
  82.365 +                 - 8)       /* extra max_pixel_depth pad */
  82.366 +      info_ptr->rowbytes = (png_size_t)0;
  82.367 +   else
  82.368 +      info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width);
  82.369 +}
  82.370 +
  82.371 +#if defined(PNG_oFFs_SUPPORTED)
  82.372 +void PNGAPI
  82.373 +png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  82.374 +   png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  82.375 +{
  82.376 +   png_debug1(1, "in %s storage function\n", "oFFs");
  82.377 +   if (png_ptr == NULL || info_ptr == NULL)
  82.378 +      return;
  82.379 +
  82.380 +   info_ptr->x_offset = offset_x;
  82.381 +   info_ptr->y_offset = offset_y;
  82.382 +   info_ptr->offset_unit_type = (png_byte)unit_type;
  82.383 +   info_ptr->valid |= PNG_INFO_oFFs;
  82.384 +}
  82.385 +#endif
  82.386 +
  82.387 +#if defined(PNG_pCAL_SUPPORTED)
  82.388 +void PNGAPI
  82.389 +png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  82.390 +   png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  82.391 +   png_charp units, png_charpp params)
  82.392 +{
  82.393 +   png_uint_32 length;
  82.394 +   int i;
  82.395 +
  82.396 +   png_debug1(1, "in %s storage function\n", "pCAL");
  82.397 +   if (png_ptr == NULL || info_ptr == NULL)
  82.398 +      return;
  82.399 +
  82.400 +   length = png_strlen(purpose) + 1;
  82.401 +   png_debug1(3, "allocating purpose for info (%lu bytes)\n",
  82.402 +     (unsigned long)length);
  82.403 +   info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  82.404 +   if (info_ptr->pcal_purpose == NULL)
  82.405 +   {
  82.406 +       png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  82.407 +      return;
  82.408 +   }
  82.409 +   png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  82.410 +
  82.411 +   png_debug(3, "storing X0, X1, type, and nparams in info\n");
  82.412 +   info_ptr->pcal_X0 = X0;
  82.413 +   info_ptr->pcal_X1 = X1;
  82.414 +   info_ptr->pcal_type = (png_byte)type;
  82.415 +   info_ptr->pcal_nparams = (png_byte)nparams;
  82.416 +
  82.417 +   length = png_strlen(units) + 1;
  82.418 +   png_debug1(3, "allocating units for info (%lu bytes)\n",
  82.419 +     (unsigned long)length);
  82.420 +   info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  82.421 +   if (info_ptr->pcal_units == NULL)
  82.422 +   {
  82.423 +       png_warning(png_ptr, "Insufficient memory for pCAL units.");
  82.424 +      return;
  82.425 +   }
  82.426 +   png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  82.427 +
  82.428 +   info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  82.429 +      (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  82.430 +   if (info_ptr->pcal_params == NULL)
  82.431 +   {
  82.432 +       png_warning(png_ptr, "Insufficient memory for pCAL params.");
  82.433 +      return;
  82.434 +   }
  82.435 +
  82.436 +   info_ptr->pcal_params[nparams] = NULL;
  82.437 +
  82.438 +   for (i = 0; i < nparams; i++)
  82.439 +   {
  82.440 +      length = png_strlen(params[i]) + 1;
  82.441 +      png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i,
  82.442 +        (unsigned long)length);
  82.443 +      info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  82.444 +      if (info_ptr->pcal_params[i] == NULL)
  82.445 +      {
  82.446 +          png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  82.447 +          return;
  82.448 +      }
  82.449 +      png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  82.450 +   }
  82.451 +
  82.452 +   info_ptr->valid |= PNG_INFO_pCAL;
  82.453 +#ifdef PNG_FREE_ME_SUPPORTED
  82.454 +   info_ptr->free_me |= PNG_FREE_PCAL;
  82.455 +#endif
  82.456 +}
  82.457 +#endif
  82.458 +
  82.459 +#if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  82.460 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  82.461 +void PNGAPI
  82.462 +png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  82.463 +             int unit, double width, double height)
  82.464 +{
  82.465 +   png_debug1(1, "in %s storage function\n", "sCAL");
  82.466 +   if (png_ptr == NULL || info_ptr == NULL)
  82.467 +      return;
  82.468 +
  82.469 +   info_ptr->scal_unit = (png_byte)unit;
  82.470 +   info_ptr->scal_pixel_width = width;
  82.471 +   info_ptr->scal_pixel_height = height;
  82.472 +
  82.473 +   info_ptr->valid |= PNG_INFO_sCAL;
  82.474 +}
  82.475 +#else
  82.476 +#ifdef PNG_FIXED_POINT_SUPPORTED
  82.477 +void PNGAPI
  82.478 +png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  82.479 +             int unit, png_charp swidth, png_charp sheight)
  82.480 +{
  82.481 +   png_uint_32 length;
  82.482 +
  82.483 +   png_debug1(1, "in %s storage function\n", "sCAL");
  82.484 +   if (png_ptr == NULL || info_ptr == NULL)
  82.485 +      return;
  82.486 +
  82.487 +   info_ptr->scal_unit = (png_byte)unit;
  82.488 +
  82.489 +   length = png_strlen(swidth) + 1;
  82.490 +   png_debug1(3, "allocating unit for info (%u bytes)\n",
  82.491 +      (unsigned int)length);
  82.492 +   info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  82.493 +   if (info_ptr->scal_s_width == NULL)
  82.494 +   {
  82.495 +      png_warning(png_ptr,
  82.496 +       "Memory allocation failed while processing sCAL.");
  82.497 +      return;
  82.498 +   }
  82.499 +   png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  82.500 +
  82.501 +   length = png_strlen(sheight) + 1;
  82.502 +   png_debug1(3, "allocating unit for info (%u bytes)\n",
  82.503 +      (unsigned int)length);
  82.504 +   info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  82.505 +   if (info_ptr->scal_s_height == NULL)
  82.506 +   {
  82.507 +      png_free (png_ptr, info_ptr->scal_s_width);
  82.508 +      info_ptr->scal_s_width = NULL;
  82.509 +      png_warning(png_ptr,
  82.510 +       "Memory allocation failed while processing sCAL.");
  82.511 +      return;
  82.512 +   }
  82.513 +   png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  82.514 +   info_ptr->valid |= PNG_INFO_sCAL;
  82.515 +#ifdef PNG_FREE_ME_SUPPORTED
  82.516 +   info_ptr->free_me |= PNG_FREE_SCAL;
  82.517 +#endif
  82.518 +}
  82.519 +#endif
  82.520 +#endif
  82.521 +#endif
  82.522 +
  82.523 +#if defined(PNG_pHYs_SUPPORTED)
  82.524 +void PNGAPI
  82.525 +png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  82.526 +   png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  82.527 +{
  82.528 +   png_debug1(1, "in %s storage function\n", "pHYs");
  82.529 +   if (png_ptr == NULL || info_ptr == NULL)
  82.530 +      return;
  82.531 +
  82.532 +   info_ptr->x_pixels_per_unit = res_x;
  82.533 +   info_ptr->y_pixels_per_unit = res_y;
  82.534 +   info_ptr->phys_unit_type = (png_byte)unit_type;
  82.535 +   info_ptr->valid |= PNG_INFO_pHYs;
  82.536 +}
  82.537 +#endif
  82.538 +
  82.539 +void PNGAPI
  82.540 +png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  82.541 +   png_colorp palette, int num_palette)
  82.542 +{
  82.543 +
  82.544 +   png_debug1(1, "in %s storage function\n", "PLTE");
  82.545 +   if (png_ptr == NULL || info_ptr == NULL)
  82.546 +      return;
  82.547 +
  82.548 +   if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  82.549 +     {
  82.550 +       if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  82.551 +         png_error(png_ptr, "Invalid palette length");
  82.552 +       else
  82.553 +       {
  82.554 +         png_warning(png_ptr, "Invalid palette length");
  82.555 +         return;
  82.556 +       }
  82.557 +     }
  82.558 +
  82.559 +   /*
  82.560 +    * It may not actually be necessary to set png_ptr->palette here;
  82.561 +    * we do it for backward compatibility with the way the png_handle_tRNS
  82.562 +    * function used to do the allocation.
  82.563 +    */
  82.564 +#ifdef PNG_FREE_ME_SUPPORTED
  82.565 +   png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  82.566 +#endif
  82.567 +
  82.568 +   /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  82.569 +      of num_palette entries,
  82.570 +      in case of an invalid PNG file that has too-large sample values. */
  82.571 +   png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  82.572 +      PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  82.573 +   png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  82.574 +      png_sizeof(png_color));
  82.575 +   png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof(png_color));
  82.576 +   info_ptr->palette = png_ptr->palette;
  82.577 +   info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  82.578 +
  82.579 +#ifdef PNG_FREE_ME_SUPPORTED
  82.580 +   info_ptr->free_me |= PNG_FREE_PLTE;
  82.581 +#else
  82.582 +   png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  82.583 +#endif
  82.584 +
  82.585 +   info_ptr->valid |= PNG_INFO_PLTE;
  82.586 +}
  82.587 +
  82.588 +#if defined(PNG_sBIT_SUPPORTED)
  82.589 +void PNGAPI
  82.590 +png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  82.591 +   png_color_8p sig_bit)
  82.592 +{
  82.593 +   png_debug1(1, "in %s storage function\n", "sBIT");
  82.594 +   if (png_ptr == NULL || info_ptr == NULL)
  82.595 +      return;
  82.596 +
  82.597 +   png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof(png_color_8));
  82.598 +   info_ptr->valid |= PNG_INFO_sBIT;
  82.599 +}
  82.600 +#endif
  82.601 +
  82.602 +#if defined(PNG_sRGB_SUPPORTED)
  82.603 +void PNGAPI
  82.604 +png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  82.605 +{
  82.606 +   png_debug1(1, "in %s storage function\n", "sRGB");
  82.607 +   if (png_ptr == NULL || info_ptr == NULL)
  82.608 +      return;
  82.609 +
  82.610 +   info_ptr->srgb_intent = (png_byte)intent;
  82.611 +   info_ptr->valid |= PNG_INFO_sRGB;
  82.612 +}
  82.613 +
  82.614 +void PNGAPI
  82.615 +png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  82.616 +   int intent)
  82.617 +{
  82.618 +#if defined(PNG_gAMA_SUPPORTED)
  82.619 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  82.620 +   float file_gamma;
  82.621 +#endif
  82.622 +#ifdef PNG_FIXED_POINT_SUPPORTED
  82.623 +   png_fixed_point int_file_gamma;
  82.624 +#endif
  82.625 +#endif
  82.626 +#if defined(PNG_cHRM_SUPPORTED)
  82.627 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  82.628 +   float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  82.629 +#endif
  82.630 +#ifdef PNG_FIXED_POINT_SUPPORTED
  82.631 +   png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  82.632 +      int_green_y, int_blue_x, int_blue_y;
  82.633 +#endif
  82.634 +#endif
  82.635 +   png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  82.636 +   if (png_ptr == NULL || info_ptr == NULL)
  82.637 +      return;
  82.638 +
  82.639 +   png_set_sRGB(png_ptr, info_ptr, intent);
  82.640 +
  82.641 +#if defined(PNG_gAMA_SUPPORTED)
  82.642 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  82.643 +   file_gamma = (float).45455;
  82.644 +   png_set_gAMA(png_ptr, info_ptr, file_gamma);
  82.645 +#endif
  82.646 +#ifdef PNG_FIXED_POINT_SUPPORTED
  82.647 +   int_file_gamma = 45455L;
  82.648 +   png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  82.649 +#endif
  82.650 +#endif
  82.651 +
  82.652 +#if defined(PNG_cHRM_SUPPORTED)
  82.653 +#ifdef PNG_FIXED_POINT_SUPPORTED
  82.654 +   int_white_x = 31270L;
  82.655 +   int_white_y = 32900L;
  82.656 +   int_red_x   = 64000L;
  82.657 +   int_red_y   = 33000L;
  82.658 +   int_green_x = 30000L;
  82.659 +   int_green_y = 60000L;
  82.660 +   int_blue_x  = 15000L;
  82.661 +   int_blue_y  =  6000L;
  82.662 +
  82.663 +   png_set_cHRM_fixed(png_ptr, info_ptr,
  82.664 +      int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  82.665 +      int_blue_x, int_blue_y);
  82.666 +#endif
  82.667 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  82.668 +   white_x = (float).3127;
  82.669 +   white_y = (float).3290;
  82.670 +   red_x   = (float).64;
  82.671 +   red_y   = (float).33;
  82.672 +   green_x = (float).30;
  82.673 +   green_y = (float).60;
  82.674 +   blue_x  = (float).15;
  82.675 +   blue_y  = (float).06;
  82.676 +
  82.677 +   png_set_cHRM(png_ptr, info_ptr,
  82.678 +      white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  82.679 +#endif
  82.680 +#endif
  82.681 +}
  82.682 +#endif
  82.683 +
  82.684 +
  82.685 +#if defined(PNG_iCCP_SUPPORTED)
  82.686 +void PNGAPI
  82.687 +png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  82.688 +             png_charp name, int compression_type,
  82.689 +             png_charp profile, png_uint_32 proflen)
  82.690 +{
  82.691 +   png_charp new_iccp_name;
  82.692 +   png_charp new_iccp_profile;
  82.693 +   png_uint_32 length;
  82.694 +
  82.695 +   png_debug1(1, "in %s storage function\n", "iCCP");
  82.696 +   if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  82.697 +      return;
  82.698 +
  82.699 +   length = png_strlen(name)+1;
  82.700 +   new_iccp_name = (png_charp)png_malloc_warn(png_ptr, length);
  82.701 +   if (new_iccp_name == NULL)
  82.702 +   {
  82.703 +      png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  82.704 +      return;
  82.705 +   }
  82.706 +   png_memcpy(new_iccp_name, name, length);
  82.707 +   new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  82.708 +   if (new_iccp_profile == NULL)
  82.709 +   {
  82.710 +      png_free (png_ptr, new_iccp_name);
  82.711 +      png_warning(png_ptr,
  82.712 +      "Insufficient memory to process iCCP profile.");
  82.713 +      return;
  82.714 +   }
  82.715 +   png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  82.716 +
  82.717 +   png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  82.718 +
  82.719 +   info_ptr->iccp_proflen = proflen;
  82.720 +   info_ptr->iccp_name = new_iccp_name;
  82.721 +   info_ptr->iccp_profile = new_iccp_profile;
  82.722 +   /* Compression is always zero but is here so the API and info structure
  82.723 +    * does not have to change if we introduce multiple compression types */
  82.724 +   info_ptr->iccp_compression = (png_byte)compression_type;
  82.725 +#ifdef PNG_FREE_ME_SUPPORTED
  82.726 +   info_ptr->free_me |= PNG_FREE_ICCP;
  82.727 +#endif
  82.728 +   info_ptr->valid |= PNG_INFO_iCCP;
  82.729 +}
  82.730 +#endif
  82.731 +
  82.732 +#if defined(PNG_TEXT_SUPPORTED)
  82.733 +void PNGAPI
  82.734 +png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  82.735 +   int num_text)
  82.736 +{
  82.737 +   int ret;
  82.738 +   ret = png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  82.739 +   if (ret)
  82.740 +     png_error(png_ptr, "Insufficient memory to store text");
  82.741 +}
  82.742 +
  82.743 +int /* PRIVATE */
  82.744 +png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  82.745 +   int num_text)
  82.746 +{
  82.747 +   int i;
  82.748 +
  82.749 +   png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  82.750 +      "text" : (png_const_charp)png_ptr->chunk_name));
  82.751 +
  82.752 +   if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  82.753 +      return(0);
  82.754 +
  82.755 +   /* Make sure we have enough space in the "text" array in info_struct
  82.756 +    * to hold all of the incoming text_ptr objects.
  82.757 +    */
  82.758 +   if (info_ptr->num_text + num_text > info_ptr->max_text)
  82.759 +   {
  82.760 +      if (info_ptr->text != NULL)
  82.761 +      {
  82.762 +         png_textp old_text;
  82.763 +         int old_max;
  82.764 +
  82.765 +         old_max = info_ptr->max_text;
  82.766 +         info_ptr->max_text = info_ptr->num_text + num_text + 8;
  82.767 +         old_text = info_ptr->text;
  82.768 +         info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  82.769 +            (png_uint_32)(info_ptr->max_text * png_sizeof(png_text)));
  82.770 +         if (info_ptr->text == NULL)
  82.771 +           {
  82.772 +             png_free(png_ptr, old_text);
  82.773 +             return(1);
  82.774 +           }
  82.775 +         png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  82.776 +            png_sizeof(png_text)));
  82.777 +         png_free(png_ptr, old_text);
  82.778 +      }
  82.779 +      else
  82.780 +      {
  82.781 +         info_ptr->max_text = num_text + 8;
  82.782 +         info_ptr->num_text = 0;
  82.783 +         info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  82.784 +            (png_uint_32)(info_ptr->max_text * png_sizeof(png_text)));
  82.785 +         if (info_ptr->text == NULL)
  82.786 +           return(1);
  82.787 +#ifdef PNG_FREE_ME_SUPPORTED
  82.788 +         info_ptr->free_me |= PNG_FREE_TEXT;
  82.789 +#endif
  82.790 +      }
  82.791 +      png_debug1(3, "allocated %d entries for info_ptr->text\n",
  82.792 +         info_ptr->max_text);
  82.793 +   }
  82.794 +   for (i = 0; i < num_text; i++)
  82.795 +   {
  82.796 +      png_size_t text_length, key_len;
  82.797 +      png_size_t lang_len, lang_key_len;
  82.798 +      png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  82.799 +
  82.800 +      if (text_ptr[i].key == NULL)
  82.801 +          continue;
  82.802 +
  82.803 +      key_len = png_strlen(text_ptr[i].key);
  82.804 +
  82.805 +      if (text_ptr[i].compression <= 0)
  82.806 +      {
  82.807 +        lang_len = 0;
  82.808 +        lang_key_len = 0;
  82.809 +      }
  82.810 +      else
  82.811 +#ifdef PNG_iTXt_SUPPORTED
  82.812 +      {
  82.813 +        /* set iTXt data */
  82.814 +        if (text_ptr[i].lang != NULL)
  82.815 +          lang_len = png_strlen(text_ptr[i].lang);
  82.816 +        else
  82.817 +          lang_len = 0;
  82.818 +        if (text_ptr[i].lang_key != NULL)
  82.819 +          lang_key_len = png_strlen(text_ptr[i].lang_key);
  82.820 +        else
  82.821 +          lang_key_len = 0;
  82.822 +      }
  82.823 +#else
  82.824 +      {
  82.825 +        png_warning(png_ptr, "iTXt chunk not supported.");
  82.826 +        continue;
  82.827 +      }
  82.828 +#endif
  82.829 +
  82.830 +      if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  82.831 +      {
  82.832 +         text_length = 0;
  82.833 +#ifdef PNG_iTXt_SUPPORTED
  82.834 +         if (text_ptr[i].compression > 0)
  82.835 +            textp->compression = PNG_ITXT_COMPRESSION_NONE;
  82.836 +         else
  82.837 +#endif
  82.838 +            textp->compression = PNG_TEXT_COMPRESSION_NONE;
  82.839 +      }
  82.840 +      else
  82.841 +      {
  82.842 +         text_length = png_strlen(text_ptr[i].text);
  82.843 +         textp->compression = text_ptr[i].compression;
  82.844 +      }
  82.845 +
  82.846 +      textp->key = (png_charp)png_malloc_warn(png_ptr,
  82.847 +         (png_uint_32)
  82.848 +         (key_len + text_length + lang_len + lang_key_len + 4));
  82.849 +      if (textp->key == NULL)
  82.850 +        return(1);
  82.851 +      png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  82.852 +         (png_uint_32)
  82.853 +         (key_len + lang_len + lang_key_len + text_length + 4),
  82.854 +         (int)textp->key);
  82.855 +
  82.856 +      png_memcpy(textp->key, text_ptr[i].key,
  82.857 +         (png_size_t)(key_len));
  82.858 +      *(textp->key + key_len) = '\0';
  82.859 +#ifdef PNG_iTXt_SUPPORTED
  82.860 +      if (text_ptr[i].compression > 0)
  82.861 +      {
  82.862 +         textp->lang = textp->key + key_len + 1;
  82.863 +         png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  82.864 +         *(textp->lang + lang_len) = '\0';
  82.865 +         textp->lang_key = textp->lang + lang_len + 1;
  82.866 +         png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  82.867 +         *(textp->lang_key + lang_key_len) = '\0';
  82.868 +         textp->text = textp->lang_key + lang_key_len + 1;
  82.869 +      }
  82.870 +      else
  82.871 +#endif
  82.872 +      {
  82.873 +#ifdef PNG_iTXt_SUPPORTED
  82.874 +         textp->lang=NULL;
  82.875 +         textp->lang_key=NULL;
  82.876 +#endif
  82.877 +         textp->text = textp->key + key_len + 1;
  82.878 +      }
  82.879 +      if (text_length)
  82.880 +         png_memcpy(textp->text, text_ptr[i].text,
  82.881 +            (png_size_t)(text_length));
  82.882 +      *(textp->text + text_length) = '\0';
  82.883 +
  82.884 +#ifdef PNG_iTXt_SUPPORTED
  82.885 +      if (textp->compression > 0)
  82.886 +      {
  82.887 +         textp->text_length = 0;
  82.888 +         textp->itxt_length = text_length;
  82.889 +      }
  82.890 +      else
  82.891 +#endif
  82.892 +      {
  82.893 +         textp->text_length = text_length;
  82.894 +#ifdef PNG_iTXt_SUPPORTED
  82.895 +         textp->itxt_length = 0;
  82.896 +#endif
  82.897 +      }
  82.898 +      info_ptr->num_text++;
  82.899 +      png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  82.900 +   }
  82.901 +   return(0);
  82.902 +}
  82.903 +#endif
  82.904 +
  82.905 +#if defined(PNG_tIME_SUPPORTED)
  82.906 +void PNGAPI
  82.907 +png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  82.908 +{
  82.909 +   png_debug1(1, "in %s storage function\n", "tIME");
  82.910 +   if (png_ptr == NULL || info_ptr == NULL ||
  82.911 +       (png_ptr->mode & PNG_WROTE_tIME))
  82.912 +      return;
  82.913 +
  82.914 +   png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof(png_time));
  82.915 +   info_ptr->valid |= PNG_INFO_tIME;
  82.916 +}
  82.917 +#endif
  82.918 +
  82.919 +#if defined(PNG_tRNS_SUPPORTED)
  82.920 +void PNGAPI
  82.921 +png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  82.922 +   png_bytep trans, int num_trans, png_color_16p trans_values)
  82.923 +{
  82.924 +   png_debug1(1, "in %s storage function\n", "tRNS");
  82.925 +   if (png_ptr == NULL || info_ptr == NULL)
  82.926 +      return;
  82.927 +
  82.928 +   if (trans != NULL)
  82.929 +   {
  82.930 +       /*
  82.931 +        * It may not actually be necessary to set png_ptr->trans here;
  82.932 +        * we do it for backward compatibility with the way the png_handle_tRNS
  82.933 +        * function used to do the allocation.
  82.934 +        */
  82.935 +
  82.936 +#ifdef PNG_FREE_ME_SUPPORTED
  82.937 +       png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  82.938 +#endif
  82.939 +
  82.940 +       /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  82.941 +       png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  82.942 +           (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  82.943 +       if (num_trans > 0 && num_trans <= PNG_MAX_PALETTE_LENGTH)
  82.944 +         png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  82.945 +   }
  82.946 +
  82.947 +   if (trans_values != NULL)
  82.948 +   {
  82.949 +      int sample_max = (1 << info_ptr->bit_depth);
  82.950 +      if ((info_ptr->color_type == PNG_COLOR_TYPE_GRAY &&
  82.951 +          (int)trans_values->gray > sample_max) ||
  82.952 +          (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
  82.953 +          ((int)trans_values->red > sample_max ||
  82.954 +          (int)trans_values->green > sample_max ||
  82.955 +          (int)trans_values->blue > sample_max)))
  82.956 +        png_warning(png_ptr,
  82.957 +           "tRNS chunk has out-of-range samples for bit_depth");
  82.958 +      png_memcpy(&(info_ptr->trans_values), trans_values,
  82.959 +         png_sizeof(png_color_16));
  82.960 +      if (num_trans == 0)
  82.961 +        num_trans = 1;
  82.962 +   }
  82.963 +
  82.964 +   info_ptr->num_trans = (png_uint_16)num_trans;
  82.965 +   if (num_trans != 0)
  82.966 +   {
  82.967 +      info_ptr->valid |= PNG_INFO_tRNS;
  82.968 +#ifdef PNG_FREE_ME_SUPPORTED
  82.969 +      info_ptr->free_me |= PNG_FREE_TRNS;
  82.970 +#else
  82.971 +      png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  82.972 +#endif
  82.973 +   }
  82.974 +}
  82.975 +#endif
  82.976 +
  82.977 +#if defined(PNG_sPLT_SUPPORTED)
  82.978 +void PNGAPI
  82.979 +png_set_sPLT(png_structp png_ptr,
  82.980 +             png_infop info_ptr, png_sPLT_tp entries, int nentries)
  82.981 +/*
  82.982 + *  entries        - array of png_sPLT_t structures
  82.983 + *                   to be added to the list of palettes
  82.984 + *                   in the info structure.
  82.985 + *  nentries       - number of palette structures to be
  82.986 + *                   added.
  82.987 + */
  82.988 +{
  82.989 +    png_sPLT_tp np;
  82.990 +    int i;
  82.991 +
  82.992 +    if (png_ptr == NULL || info_ptr == NULL)
  82.993 +       return;
  82.994 +
  82.995 +    np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  82.996 +        (info_ptr->splt_palettes_num + nentries) *
  82.997 +        (png_uint_32)png_sizeof(png_sPLT_t));
  82.998 +    if (np == NULL)
  82.999 +    {
 82.1000 +      png_warning(png_ptr, "No memory for sPLT palettes.");
 82.1001 +      return;
 82.1002 +    }
 82.1003 +
 82.1004 +    png_memcpy(np, info_ptr->splt_palettes,
 82.1005 +           info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
 82.1006 +    png_free(png_ptr, info_ptr->splt_palettes);
 82.1007 +    info_ptr->splt_palettes=NULL;
 82.1008 +
 82.1009 +    for (i = 0; i < nentries; i++)
 82.1010 +    {
 82.1011 +        png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
 82.1012 +        png_sPLT_tp from = entries + i;
 82.1013 +        png_uint_32 length;
 82.1014 +
 82.1015 +        length = png_strlen(from->name) + 1;
 82.1016 +        to->name = (png_charp)png_malloc_warn(png_ptr, length);
 82.1017 +        if (to->name == NULL)
 82.1018 +        {
 82.1019 +           png_warning(png_ptr,
 82.1020 +             "Out of memory while processing sPLT chunk");
 82.1021 +           continue;
 82.1022 +        }
 82.1023 +        png_memcpy(to->name, from->name, length);
 82.1024 +        to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
 82.1025 +            (png_uint_32)(from->nentries * png_sizeof(png_sPLT_entry)));
 82.1026 +        if (to->entries == NULL)
 82.1027 +        {
 82.1028 +           png_warning(png_ptr,
 82.1029 +             "Out of memory while processing sPLT chunk");
 82.1030 +           png_free(png_ptr, to->name);
 82.1031 +           to->name = NULL;
 82.1032 +           continue;
 82.1033 +        }
 82.1034 +        png_memcpy(to->entries, from->entries,
 82.1035 +            from->nentries * png_sizeof(png_sPLT_entry));
 82.1036 +        to->nentries = from->nentries;
 82.1037 +        to->depth = from->depth;
 82.1038 +    }
 82.1039 +
 82.1040 +    info_ptr->splt_palettes = np;
 82.1041 +    info_ptr->splt_palettes_num += nentries;
 82.1042 +    info_ptr->valid |= PNG_INFO_sPLT;
 82.1043 +#ifdef PNG_FREE_ME_SUPPORTED
 82.1044 +    info_ptr->free_me |= PNG_FREE_SPLT;
 82.1045 +#endif
 82.1046 +}
 82.1047 +#endif /* PNG_sPLT_SUPPORTED */
 82.1048 +
 82.1049 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
 82.1050 +void PNGAPI
 82.1051 +png_set_unknown_chunks(png_structp png_ptr,
 82.1052 +   png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
 82.1053 +{
 82.1054 +    png_unknown_chunkp np;
 82.1055 +    int i;
 82.1056 +
 82.1057 +    if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
 82.1058 +        return;
 82.1059 +
 82.1060 +    np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
 82.1061 +        (png_uint_32)((info_ptr->unknown_chunks_num + num_unknowns) *
 82.1062 +        png_sizeof(png_unknown_chunk)));
 82.1063 +    if (np == NULL)
 82.1064 +    {
 82.1065 +       png_warning(png_ptr,
 82.1066 +          "Out of memory while processing unknown chunk.");
 82.1067 +       return;
 82.1068 +    }
 82.1069 +
 82.1070 +    png_memcpy(np, info_ptr->unknown_chunks,
 82.1071 +           info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
 82.1072 +    png_free(png_ptr, info_ptr->unknown_chunks);
 82.1073 +    info_ptr->unknown_chunks=NULL;
 82.1074 +
 82.1075 +    for (i = 0; i < num_unknowns; i++)
 82.1076 +    {
 82.1077 +       png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
 82.1078 +       png_unknown_chunkp from = unknowns + i;
 82.1079 +
 82.1080 +       png_memcpy((png_charp)to->name, 
 82.1081 +                  (png_charp)from->name, 
 82.1082 +                  png_sizeof(from->name));
 82.1083 +       to->name[png_sizeof(to->name)-1] = '\0';
 82.1084 +       to->size = from->size;
 82.1085 +       /* note our location in the read or write sequence */
 82.1086 +       to->location = (png_byte)(png_ptr->mode & 0xff);
 82.1087 +
 82.1088 +       if (from->size == 0)
 82.1089 +          to->data=NULL;
 82.1090 +       else
 82.1091 +       {
 82.1092 +          to->data = (png_bytep)png_malloc_warn(png_ptr,
 82.1093 +            (png_uint_32)from->size);
 82.1094 +          if (to->data == NULL)
 82.1095 +          {
 82.1096 +             png_warning(png_ptr,
 82.1097 +              "Out of memory while processing unknown chunk.");
 82.1098 +             to->size = 0;
 82.1099 +          }
 82.1100 +          else
 82.1101 +             png_memcpy(to->data, from->data, from->size);
 82.1102 +       }
 82.1103 +    }
 82.1104 +
 82.1105 +    info_ptr->unknown_chunks = np;
 82.1106 +    info_ptr->unknown_chunks_num += num_unknowns;
 82.1107 +#ifdef PNG_FREE_ME_SUPPORTED
 82.1108 +    info_ptr->free_me |= PNG_FREE_UNKN;
 82.1109 +#endif
 82.1110 +}
 82.1111 +void PNGAPI
 82.1112 +png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
 82.1113 +   int chunk, int location)
 82.1114 +{
 82.1115 +   if (png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
 82.1116 +         (int)info_ptr->unknown_chunks_num)
 82.1117 +      info_ptr->unknown_chunks[chunk].location = (png_byte)location;
 82.1118 +}
 82.1119 +#endif
 82.1120 +
 82.1121 +#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
 82.1122 +#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
 82.1123 +    defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
 82.1124 +void PNGAPI
 82.1125 +png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
 82.1126 +{
 82.1127 +   /* This function is deprecated in favor of png_permit_mng_features()
 82.1128 +      and will be removed from libpng-1.3.0 */
 82.1129 +   png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
 82.1130 +   if (png_ptr == NULL)
 82.1131 +      return;
 82.1132 +   png_ptr->mng_features_permitted = (png_byte)
 82.1133 +     ((png_ptr->mng_features_permitted & (~PNG_FLAG_MNG_EMPTY_PLTE)) |
 82.1134 +     ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
 82.1135 +}
 82.1136 +#endif
 82.1137 +#endif
 82.1138 +
 82.1139 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
 82.1140 +png_uint_32 PNGAPI
 82.1141 +png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
 82.1142 +{
 82.1143 +   png_debug(1, "in png_permit_mng_features\n");
 82.1144 +   if (png_ptr == NULL)
 82.1145 +      return (png_uint_32)0;
 82.1146 +   png_ptr->mng_features_permitted =
 82.1147 +     (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
 82.1148 +   return (png_uint_32)png_ptr->mng_features_permitted;
 82.1149 +}
 82.1150 +#endif
 82.1151 +
 82.1152 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
 82.1153 +void PNGAPI
 82.1154 +png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
 82.1155 +   chunk_list, int num_chunks)
 82.1156 +{
 82.1157 +    png_bytep new_list, p;
 82.1158 +    int i, old_num_chunks;
 82.1159 +    if (png_ptr == NULL)
 82.1160 +       return;
 82.1161 +    if (num_chunks == 0)
 82.1162 +    {
 82.1163 +      if (keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
 82.1164 +        png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
 82.1165 +      else
 82.1166 +        png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
 82.1167 +
 82.1168 +      if (keep == PNG_HANDLE_CHUNK_ALWAYS)
 82.1169 +        png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
 82.1170 +      else
 82.1171 +        png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
 82.1172 +      return;
 82.1173 +    }
 82.1174 +    if (chunk_list == NULL)
 82.1175 +      return;
 82.1176 +    old_num_chunks = png_ptr->num_chunk_list;
 82.1177 +    new_list=(png_bytep)png_malloc(png_ptr,
 82.1178 +       (png_uint_32)
 82.1179 +       (5*(num_chunks + old_num_chunks)));
 82.1180 +    if (png_ptr->chunk_list != NULL)
 82.1181 +    {
 82.1182 +       png_memcpy(new_list, png_ptr->chunk_list,
 82.1183 +          (png_size_t)(5*old_num_chunks));
 82.1184 +       png_free(png_ptr, png_ptr->chunk_list);
 82.1185 +       png_ptr->chunk_list=NULL;
 82.1186 +    }
 82.1187 +    png_memcpy(new_list + 5*old_num_chunks, chunk_list,
 82.1188 +       (png_size_t)(5*num_chunks));
 82.1189 +    for (p = new_list + 5*old_num_chunks + 4, i = 0; i<num_chunks; i++, p += 5)
 82.1190 +       *p=(png_byte)keep;
 82.1191 +    png_ptr->num_chunk_list = old_num_chunks + num_chunks;
 82.1192 +    png_ptr->chunk_list = new_list;
 82.1193 +#ifdef PNG_FREE_ME_SUPPORTED
 82.1194 +    png_ptr->free_me |= PNG_FREE_LIST;
 82.1195 +#endif
 82.1196 +}
 82.1197 +#endif
 82.1198 +
 82.1199 +#if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
 82.1200 +void PNGAPI
 82.1201 +png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
 82.1202 +   png_user_chunk_ptr read_user_chunk_fn)
 82.1203 +{
 82.1204 +   png_debug(1, "in png_set_read_user_chunk_fn\n");
 82.1205 +   if (png_ptr == NULL)
 82.1206 +      return;
 82.1207 +   png_ptr->read_user_chunk_fn = read_user_chunk_fn;
 82.1208 +   png_ptr->user_chunk_ptr = user_chunk_ptr;
 82.1209 +}
 82.1210 +#endif
 82.1211 +
 82.1212 +#if defined(PNG_INFO_IMAGE_SUPPORTED)
 82.1213 +void PNGAPI
 82.1214 +png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
 82.1215 +{
 82.1216 +   png_debug1(1, "in %s storage function\n", "rows");
 82.1217 +
 82.1218 +   if (png_ptr == NULL || info_ptr == NULL)
 82.1219 +      return;
 82.1220 +
 82.1221 +   if (info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
 82.1222 +      png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
 82.1223 +   info_ptr->row_pointers = row_pointers;
 82.1224 +   if (row_pointers)
 82.1225 +      info_ptr->valid |= PNG_INFO_IDAT;
 82.1226 +}
 82.1227 +#endif
 82.1228 +
 82.1229 +#ifdef PNG_WRITE_SUPPORTED
 82.1230 +void PNGAPI
 82.1231 +png_set_compression_buffer_size(png_structp png_ptr,
 82.1232 +    png_uint_32 size)
 82.1233 +{
 82.1234 +    if (png_ptr == NULL)
 82.1235 +       return;
 82.1236 +    png_free(png_ptr, png_ptr->zbuf);
 82.1237 +    png_ptr->zbuf_size = (png_size_t)size;
 82.1238 +    png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
 82.1239 +    png_ptr->zstream.next_out = png_ptr->zbuf;
 82.1240 +    png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
 82.1241 +}
 82.1242 +#endif
 82.1243 +
 82.1244 +void PNGAPI
 82.1245 +png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
 82.1246 +{
 82.1247 +   if (png_ptr && info_ptr)
 82.1248 +      info_ptr->valid &= ~mask;
 82.1249 +}
 82.1250 +
 82.1251 +
 82.1252 +#ifndef PNG_1_0_X
 82.1253 +#ifdef PNG_ASSEMBLER_CODE_SUPPORTED
 82.1254 +/* function was added to libpng 1.2.0 and should always exist by default */
 82.1255 +void PNGAPI
 82.1256 +png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
 82.1257 +{
 82.1258 +/* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
 82.1259 +    if (png_ptr != NULL)
 82.1260 +    png_ptr->asm_flags = 0;
 82.1261 +    asm_flags = asm_flags; /* Quiet the compiler */
 82.1262 +}
 82.1263 +
 82.1264 +/* this function was added to libpng 1.2.0 */
 82.1265 +void PNGAPI
 82.1266 +png_set_mmx_thresholds (png_structp png_ptr,
 82.1267 +                        png_byte mmx_bitdepth_threshold,
 82.1268 +                        png_uint_32 mmx_rowbytes_threshold)
 82.1269 +{
 82.1270 +/* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
 82.1271 +    if (png_ptr == NULL)
 82.1272 +       return;
 82.1273 +    /* Quiet the compiler */
 82.1274 +    mmx_bitdepth_threshold = mmx_bitdepth_threshold;
 82.1275 +    mmx_rowbytes_threshold = mmx_rowbytes_threshold;
 82.1276 +}
 82.1277 +#endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
 82.1278 +
 82.1279 +#ifdef PNG_SET_USER_LIMITS_SUPPORTED
 82.1280 +/* this function was added to libpng 1.2.6 */
 82.1281 +void PNGAPI
 82.1282 +png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
 82.1283 +    png_uint_32 user_height_max)
 82.1284 +{
 82.1285 +    /* Images with dimensions larger than these limits will be
 82.1286 +     * rejected by png_set_IHDR().  To accept any PNG datastream
 82.1287 +     * regardless of dimensions, set both limits to 0x7ffffffL.
 82.1288 +     */
 82.1289 +    if (png_ptr == NULL) return;
 82.1290 +    png_ptr->user_width_max = user_width_max;
 82.1291 +    png_ptr->user_height_max = user_height_max;
 82.1292 +}
 82.1293 +#endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
 82.1294 +
 82.1295 +#endif /* ?PNG_1_0_X */
 82.1296 +#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
    83.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    83.2 +++ b/libs/libpng/pngtrans.c	Thu Sep 08 06:28:38 2011 +0300
    83.3 @@ -0,0 +1,662 @@
    83.4 +
    83.5 +/* pngtrans.c - transforms the data in a row (used by both readers and writers)
    83.6 + *
    83.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    83.8 + * For conditions of distribution and use, see copyright notice in png.h
    83.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   83.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   83.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   83.12 + */
   83.13 +
   83.14 +#define PNG_INTERNAL
   83.15 +#include "png.h"
   83.16 +#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
   83.17 +
   83.18 +#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
   83.19 +/* turn on BGR-to-RGB mapping */
   83.20 +void PNGAPI
   83.21 +png_set_bgr(png_structp png_ptr)
   83.22 +{
   83.23 +   png_debug(1, "in png_set_bgr\n");
   83.24 +   if (png_ptr == NULL) return;
   83.25 +   png_ptr->transformations |= PNG_BGR;
   83.26 +}
   83.27 +#endif
   83.28 +
   83.29 +#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
   83.30 +/* turn on 16 bit byte swapping */
   83.31 +void PNGAPI
   83.32 +png_set_swap(png_structp png_ptr)
   83.33 +{
   83.34 +   png_debug(1, "in png_set_swap\n");
   83.35 +   if (png_ptr == NULL) return;
   83.36 +   if (png_ptr->bit_depth == 16)
   83.37 +      png_ptr->transformations |= PNG_SWAP_BYTES;
   83.38 +}
   83.39 +#endif
   83.40 +
   83.41 +#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
   83.42 +/* turn on pixel packing */
   83.43 +void PNGAPI
   83.44 +png_set_packing(png_structp png_ptr)
   83.45 +{
   83.46 +   png_debug(1, "in png_set_packing\n");
   83.47 +   if (png_ptr == NULL) return;
   83.48 +   if (png_ptr->bit_depth < 8)
   83.49 +   {
   83.50 +      png_ptr->transformations |= PNG_PACK;
   83.51 +      png_ptr->usr_bit_depth = 8;
   83.52 +   }
   83.53 +}
   83.54 +#endif
   83.55 +
   83.56 +#if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
   83.57 +/* turn on packed pixel swapping */
   83.58 +void PNGAPI
   83.59 +png_set_packswap(png_structp png_ptr)
   83.60 +{
   83.61 +   png_debug(1, "in png_set_packswap\n");
   83.62 +   if (png_ptr == NULL) return;
   83.63 +   if (png_ptr->bit_depth < 8)
   83.64 +      png_ptr->transformations |= PNG_PACKSWAP;
   83.65 +}
   83.66 +#endif
   83.67 +
   83.68 +#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
   83.69 +void PNGAPI
   83.70 +png_set_shift(png_structp png_ptr, png_color_8p true_bits)
   83.71 +{
   83.72 +   png_debug(1, "in png_set_shift\n");
   83.73 +   if (png_ptr == NULL) return;
   83.74 +   png_ptr->transformations |= PNG_SHIFT;
   83.75 +   png_ptr->shift = *true_bits;
   83.76 +}
   83.77 +#endif
   83.78 +
   83.79 +#if defined(PNG_READ_INTERLACING_SUPPORTED) || \
   83.80 +    defined(PNG_WRITE_INTERLACING_SUPPORTED)
   83.81 +int PNGAPI
   83.82 +png_set_interlace_handling(png_structp png_ptr)
   83.83 +{
   83.84 +   png_debug(1, "in png_set_interlace handling\n");
   83.85 +   if (png_ptr && png_ptr->interlaced)
   83.86 +   {
   83.87 +      png_ptr->transformations |= PNG_INTERLACE;
   83.88 +      return (7);
   83.89 +   }
   83.90 +
   83.91 +   return (1);
   83.92 +}
   83.93 +#endif
   83.94 +
   83.95 +#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
   83.96 +/* Add a filler byte on read, or remove a filler or alpha byte on write.
   83.97 + * The filler type has changed in v0.95 to allow future 2-byte fillers
   83.98 + * for 48-bit input data, as well as to avoid problems with some compilers
   83.99 + * that don't like bytes as parameters.
  83.100 + */
  83.101 +void PNGAPI
  83.102 +png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  83.103 +{
  83.104 +   png_debug(1, "in png_set_filler\n");
  83.105 +   if (png_ptr == NULL) return;
  83.106 +   png_ptr->transformations |= PNG_FILLER;
  83.107 +   png_ptr->filler = (png_byte)filler;
  83.108 +   if (filler_loc == PNG_FILLER_AFTER)
  83.109 +      png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  83.110 +   else
  83.111 +      png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  83.112 +
  83.113 +   /* This should probably go in the "do_read_filler" routine.
  83.114 +    * I attempted to do that in libpng-1.0.1a but that caused problems
  83.115 +    * so I restored it in libpng-1.0.2a
  83.116 +   */
  83.117 +
  83.118 +   if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  83.119 +   {
  83.120 +      png_ptr->usr_channels = 4;
  83.121 +   }
  83.122 +
  83.123 +   /* Also I added this in libpng-1.0.2a (what happens when we expand
  83.124 +    * a less-than-8-bit grayscale to GA? */
  83.125 +
  83.126 +   if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  83.127 +   {
  83.128 +      png_ptr->usr_channels = 2;
  83.129 +   }
  83.130 +}
  83.131 +
  83.132 +#if !defined(PNG_1_0_X)
  83.133 +/* Added to libpng-1.2.7 */
  83.134 +void PNGAPI
  83.135 +png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  83.136 +{
  83.137 +   png_debug(1, "in png_set_add_alpha\n");
  83.138 +   if (png_ptr == NULL) return;
  83.139 +   png_set_filler(png_ptr, filler, filler_loc);
  83.140 +   png_ptr->transformations |= PNG_ADD_ALPHA;
  83.141 +}
  83.142 +#endif
  83.143 +
  83.144 +#endif
  83.145 +
  83.146 +#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  83.147 +    defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  83.148 +void PNGAPI
  83.149 +png_set_swap_alpha(png_structp png_ptr)
  83.150 +{
  83.151 +   png_debug(1, "in png_set_swap_alpha\n");
  83.152 +   if (png_ptr == NULL) return;
  83.153 +   png_ptr->transformations |= PNG_SWAP_ALPHA;
  83.154 +}
  83.155 +#endif
  83.156 +
  83.157 +#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  83.158 +    defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  83.159 +void PNGAPI
  83.160 +png_set_invert_alpha(png_structp png_ptr)
  83.161 +{
  83.162 +   png_debug(1, "in png_set_invert_alpha\n");
  83.163 +   if (png_ptr == NULL) return;
  83.164 +   png_ptr->transformations |= PNG_INVERT_ALPHA;
  83.165 +}
  83.166 +#endif
  83.167 +
  83.168 +#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  83.169 +void PNGAPI
  83.170 +png_set_invert_mono(png_structp png_ptr)
  83.171 +{
  83.172 +   png_debug(1, "in png_set_invert_mono\n");
  83.173 +   if (png_ptr == NULL) return;
  83.174 +   png_ptr->transformations |= PNG_INVERT_MONO;
  83.175 +}
  83.176 +
  83.177 +/* invert monochrome grayscale data */
  83.178 +void /* PRIVATE */
  83.179 +png_do_invert(png_row_infop row_info, png_bytep row)
  83.180 +{
  83.181 +   png_debug(1, "in png_do_invert\n");
  83.182 +  /* This test removed from libpng version 1.0.13 and 1.2.0:
  83.183 +   *   if (row_info->bit_depth == 1 &&
  83.184 +   */
  83.185 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
  83.186 +   if (row == NULL || row_info == NULL)
  83.187 +     return;
  83.188 +#endif
  83.189 +   if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  83.190 +   {
  83.191 +      png_bytep rp = row;
  83.192 +      png_uint_32 i;
  83.193 +      png_uint_32 istop = row_info->rowbytes;
  83.194 +
  83.195 +      for (i = 0; i < istop; i++)
  83.196 +      {
  83.197 +         *rp = (png_byte)(~(*rp));
  83.198 +         rp++;
  83.199 +      }
  83.200 +   }
  83.201 +   else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  83.202 +      row_info->bit_depth == 8)
  83.203 +   {
  83.204 +      png_bytep rp = row;
  83.205 +      png_uint_32 i;
  83.206 +      png_uint_32 istop = row_info->rowbytes;
  83.207 +
  83.208 +      for (i = 0; i < istop; i+=2)
  83.209 +      {
  83.210 +         *rp = (png_byte)(~(*rp));
  83.211 +         rp+=2;
  83.212 +      }
  83.213 +   }
  83.214 +   else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  83.215 +      row_info->bit_depth == 16)
  83.216 +   {
  83.217 +      png_bytep rp = row;
  83.218 +      png_uint_32 i;
  83.219 +      png_uint_32 istop = row_info->rowbytes;
  83.220 +
  83.221 +      for (i = 0; i < istop; i+=4)
  83.222 +      {
  83.223 +         *rp = (png_byte)(~(*rp));
  83.224 +         *(rp+1) = (png_byte)(~(*(rp+1)));
  83.225 +         rp+=4;
  83.226 +      }
  83.227 +   }
  83.228 +}
  83.229 +#endif
  83.230 +
  83.231 +#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  83.232 +/* swaps byte order on 16 bit depth images */
  83.233 +void /* PRIVATE */
  83.234 +png_do_swap(png_row_infop row_info, png_bytep row)
  83.235 +{
  83.236 +   png_debug(1, "in png_do_swap\n");
  83.237 +   if (
  83.238 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
  83.239 +       row != NULL && row_info != NULL &&
  83.240 +#endif
  83.241 +       row_info->bit_depth == 16)
  83.242 +   {
  83.243 +      png_bytep rp = row;
  83.244 +      png_uint_32 i;
  83.245 +      png_uint_32 istop= row_info->width * row_info->channels;
  83.246 +
  83.247 +      for (i = 0; i < istop; i++, rp += 2)
  83.248 +      {
  83.249 +         png_byte t = *rp;
  83.250 +         *rp = *(rp + 1);
  83.251 +         *(rp + 1) = t;
  83.252 +      }
  83.253 +   }
  83.254 +}
  83.255 +#endif
  83.256 +
  83.257 +#if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  83.258 +static PNG_CONST png_byte onebppswaptable[256] = {
  83.259 +   0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  83.260 +   0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  83.261 +   0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  83.262 +   0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  83.263 +   0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  83.264 +   0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  83.265 +   0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  83.266 +   0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  83.267 +   0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  83.268 +   0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  83.269 +   0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  83.270 +   0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  83.271 +   0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  83.272 +   0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  83.273 +   0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  83.274 +   0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  83.275 +   0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  83.276 +   0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  83.277 +   0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  83.278 +   0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  83.279 +   0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  83.280 +   0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  83.281 +   0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  83.282 +   0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  83.283 +   0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  83.284 +   0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  83.285 +   0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  83.286 +   0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  83.287 +   0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  83.288 +   0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  83.289 +   0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  83.290 +   0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  83.291 +};
  83.292 +
  83.293 +static PNG_CONST png_byte twobppswaptable[256] = {
  83.294 +   0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  83.295 +   0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  83.296 +   0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  83.297 +   0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  83.298 +   0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  83.299 +   0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  83.300 +   0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  83.301 +   0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  83.302 +   0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  83.303 +   0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  83.304 +   0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  83.305 +   0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  83.306 +   0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  83.307 +   0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  83.308 +   0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  83.309 +   0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  83.310 +   0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  83.311 +   0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  83.312 +   0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  83.313 +   0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  83.314 +   0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  83.315 +   0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  83.316 +   0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  83.317 +   0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  83.318 +   0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  83.319 +   0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  83.320 +   0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  83.321 +   0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  83.322 +   0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  83.323 +   0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  83.324 +   0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  83.325 +   0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  83.326 +};
  83.327 +
  83.328 +static PNG_CONST png_byte fourbppswaptable[256] = {
  83.329 +   0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  83.330 +   0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  83.331 +   0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  83.332 +   0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  83.333 +   0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  83.334 +   0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  83.335 +   0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  83.336 +   0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  83.337 +   0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  83.338 +   0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  83.339 +   0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  83.340 +   0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  83.341 +   0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  83.342 +   0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  83.343 +   0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  83.344 +   0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  83.345 +   0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  83.346 +   0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  83.347 +   0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  83.348 +   0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  83.349 +   0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  83.350 +   0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  83.351 +   0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  83.352 +   0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  83.353 +   0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  83.354 +   0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  83.355 +   0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  83.356 +   0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  83.357 +   0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  83.358 +   0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  83.359 +   0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  83.360 +   0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  83.361 +};
  83.362 +
  83.363 +/* swaps pixel packing order within bytes */
  83.364 +void /* PRIVATE */
  83.365 +png_do_packswap(png_row_infop row_info, png_bytep row)
  83.366 +{
  83.367 +   png_debug(1, "in png_do_packswap\n");
  83.368 +   if (
  83.369 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
  83.370 +       row != NULL && row_info != NULL &&
  83.371 +#endif
  83.372 +       row_info->bit_depth < 8)
  83.373 +   {
  83.374 +      png_bytep rp, end, table;
  83.375 +
  83.376 +      end = row + row_info->rowbytes;
  83.377 +
  83.378 +      if (row_info->bit_depth == 1)
  83.379 +         table = (png_bytep)onebppswaptable;
  83.380 +      else if (row_info->bit_depth == 2)
  83.381 +         table = (png_bytep)twobppswaptable;
  83.382 +      else if (row_info->bit_depth == 4)
  83.383 +         table = (png_bytep)fourbppswaptable;
  83.384 +      else
  83.385 +         return;
  83.386 +
  83.387 +      for (rp = row; rp < end; rp++)
  83.388 +         *rp = table[*rp];
  83.389 +   }
  83.390 +}
  83.391 +#endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  83.392 +
  83.393 +#if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  83.394 +    defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  83.395 +/* remove filler or alpha byte(s) */
  83.396 +void /* PRIVATE */
  83.397 +png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  83.398 +{
  83.399 +   png_debug(1, "in png_do_strip_filler\n");
  83.400 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
  83.401 +   if (row != NULL && row_info != NULL)
  83.402 +#endif
  83.403 +   {
  83.404 +      png_bytep sp=row;
  83.405 +      png_bytep dp=row;
  83.406 +      png_uint_32 row_width=row_info->width;
  83.407 +      png_uint_32 i;
  83.408 +
  83.409 +      if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  83.410 +         (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  83.411 +         (flags & PNG_FLAG_STRIP_ALPHA))) &&
  83.412 +         row_info->channels == 4)
  83.413 +      {
  83.414 +         if (row_info->bit_depth == 8)
  83.415 +         {
  83.416 +            /* This converts from RGBX or RGBA to RGB */
  83.417 +            if (flags & PNG_FLAG_FILLER_AFTER)
  83.418 +            {
  83.419 +               dp+=3; sp+=4;
  83.420 +               for (i = 1; i < row_width; i++)
  83.421 +               {
  83.422 +                  *dp++ = *sp++;
  83.423 +                  *dp++ = *sp++;
  83.424 +                  *dp++ = *sp++;
  83.425 +                  sp++;
  83.426 +               }
  83.427 +            }
  83.428 +            /* This converts from XRGB or ARGB to RGB */
  83.429 +            else
  83.430 +            {
  83.431 +               for (i = 0; i < row_width; i++)
  83.432 +               {
  83.433 +                  sp++;
  83.434 +                  *dp++ = *sp++;
  83.435 +                  *dp++ = *sp++;
  83.436 +                  *dp++ = *sp++;
  83.437 +               }
  83.438 +            }
  83.439 +            row_info->pixel_depth = 24;
  83.440 +            row_info->rowbytes = row_width * 3;
  83.441 +         }
  83.442 +         else /* if (row_info->bit_depth == 16) */
  83.443 +         {
  83.444 +            if (flags & PNG_FLAG_FILLER_AFTER)
  83.445 +            {
  83.446 +               /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  83.447 +               sp += 8; dp += 6;
  83.448 +               for (i = 1; i < row_width; i++)
  83.449 +               {
  83.450 +                  /* This could be (although png_memcpy is probably slower):
  83.451 +                  png_memcpy(dp, sp, 6);
  83.452 +                  sp += 8;
  83.453 +                  dp += 6;
  83.454 +                  */
  83.455 +
  83.456 +                  *dp++ = *sp++;
  83.457 +                  *dp++ = *sp++;
  83.458 +                  *dp++ = *sp++;
  83.459 +                  *dp++ = *sp++;
  83.460 +                  *dp++ = *sp++;
  83.461 +                  *dp++ = *sp++;
  83.462 +                  sp += 2;
  83.463 +               }
  83.464 +            }
  83.465 +            else
  83.466 +            {
  83.467 +               /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  83.468 +               for (i = 0; i < row_width; i++)
  83.469 +               {
  83.470 +                  /* This could be (although png_memcpy is probably slower):
  83.471 +                  png_memcpy(dp, sp, 6);
  83.472 +                  sp += 8;
  83.473 +                  dp += 6;
  83.474 +                  */
  83.475 +
  83.476 +                  sp+=2;
  83.477 +                  *dp++ = *sp++;
  83.478 +                  *dp++ = *sp++;
  83.479 +                  *dp++ = *sp++;
  83.480 +                  *dp++ = *sp++;
  83.481 +                  *dp++ = *sp++;
  83.482 +                  *dp++ = *sp++;
  83.483 +               }
  83.484 +            }
  83.485 +            row_info->pixel_depth = 48;
  83.486 +            row_info->rowbytes = row_width * 6;
  83.487 +         }
  83.488 +         row_info->channels = 3;
  83.489 +      }
  83.490 +      else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  83.491 +         (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  83.492 +         (flags & PNG_FLAG_STRIP_ALPHA))) &&
  83.493 +          row_info->channels == 2)
  83.494 +      {
  83.495 +         if (row_info->bit_depth == 8)
  83.496 +         {
  83.497 +            /* This converts from GX or GA to G */
  83.498 +            if (flags & PNG_FLAG_FILLER_AFTER)
  83.499 +            {
  83.500 +               for (i = 0; i < row_width; i++)
  83.501 +               {
  83.502 +                  *dp++ = *sp++;
  83.503 +                  sp++;
  83.504 +               }
  83.505 +            }
  83.506 +            /* This converts from XG or AG to G */
  83.507 +            else
  83.508 +            {
  83.509 +               for (i = 0; i < row_width; i++)
  83.510 +               {
  83.511 +                  sp++;
  83.512 +                  *dp++ = *sp++;
  83.513 +               }
  83.514 +            }
  83.515 +            row_info->pixel_depth = 8;
  83.516 +            row_info->rowbytes = row_width;
  83.517 +         }
  83.518 +         else /* if (row_info->bit_depth == 16) */
  83.519 +         {
  83.520 +            if (flags & PNG_FLAG_FILLER_AFTER)
  83.521 +            {
  83.522 +               /* This converts from GGXX or GGAA to GG */
  83.523 +               sp += 4; dp += 2;
  83.524 +               for (i = 1; i < row_width; i++)
  83.525 +               {
  83.526 +                  *dp++ = *sp++;
  83.527 +                  *dp++ = *sp++;
  83.528 +                  sp += 2;
  83.529 +               }
  83.530 +            }
  83.531 +            else
  83.532 +            {
  83.533 +               /* This converts from XXGG or AAGG to GG */
  83.534 +               for (i = 0; i < row_width; i++)
  83.535 +               {
  83.536 +                  sp += 2;
  83.537 +                  *dp++ = *sp++;
  83.538 +                  *dp++ = *sp++;
  83.539 +               }
  83.540 +            }
  83.541 +            row_info->pixel_depth = 16;
  83.542 +            row_info->rowbytes = row_width * 2;
  83.543 +         }
  83.544 +         row_info->channels = 1;
  83.545 +      }
  83.546 +      if (flags & PNG_FLAG_STRIP_ALPHA)
  83.547 +        row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  83.548 +   }
  83.549 +}
  83.550 +#endif
  83.551 +
  83.552 +#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  83.553 +/* swaps red and blue bytes within a pixel */
  83.554 +void /* PRIVATE */
  83.555 +png_do_bgr(png_row_infop row_info, png_bytep row)
  83.556 +{
  83.557 +   png_debug(1, "in png_do_bgr\n");
  83.558 +   if (
  83.559 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
  83.560 +       row != NULL && row_info != NULL &&
  83.561 +#endif
  83.562 +       (row_info->color_type & PNG_COLOR_MASK_COLOR))
  83.563 +   {
  83.564 +      png_uint_32 row_width = row_info->width;
  83.565 +      if (row_info->bit_depth == 8)
  83.566 +      {
  83.567 +         if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  83.568 +         {
  83.569 +            png_bytep rp;
  83.570 +            png_uint_32 i;
  83.571 +
  83.572 +            for (i = 0, rp = row; i < row_width; i++, rp += 3)
  83.573 +            {
  83.574 +               png_byte save = *rp;
  83.575 +               *rp = *(rp + 2);
  83.576 +               *(rp + 2) = save;
  83.577 +            }
  83.578 +         }
  83.579 +         else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  83.580 +         {
  83.581 +            png_bytep rp;
  83.582 +            png_uint_32 i;
  83.583 +
  83.584 +            for (i = 0, rp = row; i < row_width; i++, rp += 4)
  83.585 +            {
  83.586 +               png_byte save = *rp;
  83.587 +               *rp = *(rp + 2);
  83.588 +               *(rp + 2) = save;
  83.589 +            }
  83.590 +         }
  83.591 +      }
  83.592 +      else if (row_info->bit_depth == 16)
  83.593 +      {
  83.594 +         if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  83.595 +         {
  83.596 +            png_bytep rp;
  83.597 +            png_uint_32 i;
  83.598 +
  83.599 +            for (i = 0, rp = row; i < row_width; i++, rp += 6)
  83.600 +            {
  83.601 +               png_byte save = *rp;
  83.602 +               *rp = *(rp + 4);
  83.603 +               *(rp + 4) = save;
  83.604 +               save = *(rp + 1);
  83.605 +               *(rp + 1) = *(rp + 5);
  83.606 +               *(rp + 5) = save;
  83.607 +            }
  83.608 +         }
  83.609 +         else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  83.610 +         {
  83.611 +            png_bytep rp;
  83.612 +            png_uint_32 i;
  83.613 +
  83.614 +            for (i = 0, rp = row; i < row_width; i++, rp += 8)
  83.615 +            {
  83.616 +               png_byte save = *rp;
  83.617 +               *rp = *(rp + 4);
  83.618 +               *(rp + 4) = save;
  83.619 +               save = *(rp + 1);
  83.620 +               *(rp + 1) = *(rp + 5);
  83.621 +               *(rp + 5) = save;
  83.622 +            }
  83.623 +         }
  83.624 +      }
  83.625 +   }
  83.626 +}
  83.627 +#endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  83.628 +
  83.629 +#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  83.630 +    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  83.631 +    defined(PNG_LEGACY_SUPPORTED)
  83.632 +void PNGAPI
  83.633 +png_set_user_transform_info(png_structp png_ptr, png_voidp
  83.634 +   user_transform_ptr, int user_transform_depth, int user_transform_channels)
  83.635 +{
  83.636 +   png_debug(1, "in png_set_user_transform_info\n");
  83.637 +   if (png_ptr == NULL) return;
  83.638 +#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  83.639 +   png_ptr->user_transform_ptr = user_transform_ptr;
  83.640 +   png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  83.641 +   png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  83.642 +#else
  83.643 +   if (user_transform_ptr || user_transform_depth || user_transform_channels)
  83.644 +      png_warning(png_ptr,
  83.645 +        "This version of libpng does not support user transform info");
  83.646 +#endif
  83.647 +}
  83.648 +#endif
  83.649 +
  83.650 +/* This function returns a pointer to the user_transform_ptr associated with
  83.651 + * the user transform functions.  The application should free any memory
  83.652 + * associated with this pointer before png_write_destroy and png_read_destroy
  83.653 + * are called.
  83.654 + */
  83.655 +png_voidp PNGAPI
  83.656 +png_get_user_transform_ptr(png_structp png_ptr)
  83.657 +{
  83.658 +   if (png_ptr == NULL) return (NULL);
  83.659 +#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  83.660 +   return ((png_voidp)png_ptr->user_transform_ptr);
  83.661 +#else
  83.662 +   return (NULL);
  83.663 +#endif
  83.664 +}
  83.665 +#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
    84.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    84.2 +++ b/libs/libpng/pngvcrd.c	Thu Sep 08 06:28:38 2011 +0300
    84.3 @@ -0,0 +1,1 @@
    84.4 +/* pnggvrd.c was removed from libpng-1.2.20. */
    85.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    85.2 +++ b/libs/libpng/pngwio.c	Thu Sep 08 06:28:38 2011 +0300
    85.3 @@ -0,0 +1,234 @@
    85.4 +
    85.5 +/* pngwio.c - functions for data output
    85.6 + *
    85.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    85.8 + * For conditions of distribution and use, see copyright notice in png.h
    85.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   85.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   85.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   85.12 + *
   85.13 + * This file provides a location for all output.  Users who need
   85.14 + * special handling are expected to write functions that have the same
   85.15 + * arguments as these and perform similar functions, but that possibly
   85.16 + * use different output methods.  Note that you shouldn't change these
   85.17 + * functions, but rather write replacement functions and then change
   85.18 + * them at run time with png_set_write_fn(...).
   85.19 + */
   85.20 +
   85.21 +#define PNG_INTERNAL
   85.22 +#include "png.h"
   85.23 +#ifdef PNG_WRITE_SUPPORTED
   85.24 +
   85.25 +/* Write the data to whatever output you are using.  The default routine
   85.26 +   writes to a file pointer.  Note that this routine sometimes gets called
   85.27 +   with very small lengths, so you should implement some kind of simple
   85.28 +   buffering if you are using unbuffered writes.  This should never be asked
   85.29 +   to write more than 64K on a 16 bit machine.  */
   85.30 +
   85.31 +void /* PRIVATE */
   85.32 +png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
   85.33 +{
   85.34 +   if (png_ptr->write_data_fn != NULL )
   85.35 +      (*(png_ptr->write_data_fn))(png_ptr, data, length);
   85.36 +   else
   85.37 +      png_error(png_ptr, "Call to NULL write function");
   85.38 +}
   85.39 +
   85.40 +#if !defined(PNG_NO_STDIO)
   85.41 +/* This is the function that does the actual writing of data.  If you are
   85.42 +   not writing to a standard C stream, you should create a replacement
   85.43 +   write_data function and use it at run time with png_set_write_fn(), rather
   85.44 +   than changing the library. */
   85.45 +#ifndef USE_FAR_KEYWORD
   85.46 +void PNGAPI
   85.47 +png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
   85.48 +{
   85.49 +   png_uint_32 check;
   85.50 +
   85.51 +   if (png_ptr == NULL) return;
   85.52 +#if defined(_WIN32_WCE)
   85.53 +   if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
   85.54 +      check = 0;
   85.55 +#else
   85.56 +   check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
   85.57 +#endif
   85.58 +   if (check != length)
   85.59 +      png_error(png_ptr, "Write Error");
   85.60 +}
   85.61 +#else
   85.62 +/* this is the model-independent version. Since the standard I/O library
   85.63 +   can't handle far buffers in the medium and small models, we have to copy
   85.64 +   the data.
   85.65 +*/
   85.66 +
   85.67 +#define NEAR_BUF_SIZE 1024
   85.68 +#define MIN(a,b) (a <= b ? a : b)
   85.69 +
   85.70 +void PNGAPI
   85.71 +png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
   85.72 +{
   85.73 +   png_uint_32 check;
   85.74 +   png_byte *near_data;  /* Needs to be "png_byte *" instead of "png_bytep" */
   85.75 +   png_FILE_p io_ptr;
   85.76 +
   85.77 +   if (png_ptr == NULL) return;
   85.78 +   /* Check if data really is near. If so, use usual code. */
   85.79 +   near_data = (png_byte *)CVT_PTR_NOCHECK(data);
   85.80 +   io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
   85.81 +   if ((png_bytep)near_data == data)
   85.82 +   {
   85.83 +#if defined(_WIN32_WCE)
   85.84 +      if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
   85.85 +         check = 0;
   85.86 +#else
   85.87 +      check = fwrite(near_data, 1, length, io_ptr);
   85.88 +#endif
   85.89 +   }
   85.90 +   else
   85.91 +   {
   85.92 +      png_byte buf[NEAR_BUF_SIZE];
   85.93 +      png_size_t written, remaining, err;
   85.94 +      check = 0;
   85.95 +      remaining = length;
   85.96 +      do
   85.97 +      {
   85.98 +         written = MIN(NEAR_BUF_SIZE, remaining);
   85.99 +         png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  85.100 +#if defined(_WIN32_WCE)
  85.101 +         if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  85.102 +            err = 0;
  85.103 +#else
  85.104 +         err = fwrite(buf, 1, written, io_ptr);
  85.105 +#endif
  85.106 +         if (err != written)
  85.107 +            break;
  85.108 +         else
  85.109 +            check += err;
  85.110 +         data += written;
  85.111 +         remaining -= written;
  85.112 +      }
  85.113 +      while (remaining != 0);
  85.114 +   }
  85.115 +   if (check != length)
  85.116 +      png_error(png_ptr, "Write Error");
  85.117 +}
  85.118 +
  85.119 +#endif
  85.120 +#endif
  85.121 +
  85.122 +/* This function is called to output any data pending writing (normally
  85.123 +   to disk).  After png_flush is called, there should be no data pending
  85.124 +   writing in any buffers. */
  85.125 +#if defined(PNG_WRITE_FLUSH_SUPPORTED)
  85.126 +void /* PRIVATE */
  85.127 +png_flush(png_structp png_ptr)
  85.128 +{
  85.129 +   if (png_ptr->output_flush_fn != NULL)
  85.130 +      (*(png_ptr->output_flush_fn))(png_ptr);
  85.131 +}
  85.132 +
  85.133 +#if !defined(PNG_NO_STDIO)
  85.134 +void PNGAPI
  85.135 +png_default_flush(png_structp png_ptr)
  85.136 +{
  85.137 +#if !defined(_WIN32_WCE)
  85.138 +   png_FILE_p io_ptr;
  85.139 +#endif
  85.140 +   if (png_ptr == NULL) return;
  85.141 +#if !defined(_WIN32_WCE)
  85.142 +   io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  85.143 +   if (io_ptr != NULL)
  85.144 +      fflush(io_ptr);
  85.145 +#endif
  85.146 +}
  85.147 +#endif
  85.148 +#endif
  85.149 +
  85.150 +/* This function allows the application to supply new output functions for
  85.151 +   libpng if standard C streams aren't being used.
  85.152 +
  85.153 +   This function takes as its arguments:
  85.154 +   png_ptr       - pointer to a png output data structure
  85.155 +   io_ptr        - pointer to user supplied structure containing info about
  85.156 +                   the output functions.  May be NULL.
  85.157 +   write_data_fn - pointer to a new output function that takes as its
  85.158 +                   arguments a pointer to a png_struct, a pointer to
  85.159 +                   data to be written, and a 32-bit unsigned int that is
  85.160 +                   the number of bytes to be written.  The new write
  85.161 +                   function should call png_error(png_ptr, "Error msg")
  85.162 +                   to exit and output any fatal error messages.
  85.163 +   flush_data_fn - pointer to a new flush function that takes as its
  85.164 +                   arguments a pointer to a png_struct.  After a call to
  85.165 +                   the flush function, there should be no data in any buffers
  85.166 +                   or pending transmission.  If the output method doesn't do
  85.167 +                   any buffering of ouput, a function prototype must still be
  85.168 +                   supplied although it doesn't have to do anything.  If
  85.169 +                   PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  85.170 +                   time, output_flush_fn will be ignored, although it must be
  85.171 +                   supplied for compatibility. */
  85.172 +void PNGAPI
  85.173 +png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  85.174 +   png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  85.175 +{
  85.176 +   if (png_ptr == NULL) return;
  85.177 +   png_ptr->io_ptr = io_ptr;
  85.178 +
  85.179 +#if !defined(PNG_NO_STDIO)
  85.180 +   if (write_data_fn != NULL)
  85.181 +      png_ptr->write_data_fn = write_data_fn;
  85.182 +   else
  85.183 +      png_ptr->write_data_fn = png_default_write_data;
  85.184 +#else
  85.185 +   png_ptr->write_data_fn = write_data_fn;
  85.186 +#endif
  85.187 +
  85.188 +#if defined(PNG_WRITE_FLUSH_SUPPORTED)
  85.189 +#if !defined(PNG_NO_STDIO)
  85.190 +   if (output_flush_fn != NULL)
  85.191 +      png_ptr->output_flush_fn = output_flush_fn;
  85.192 +   else
  85.193 +      png_ptr->output_flush_fn = png_default_flush;
  85.194 +#else
  85.195 +   png_ptr->output_flush_fn = output_flush_fn;
  85.196 +#endif
  85.197 +#endif /* PNG_WRITE_FLUSH_SUPPORTED */
  85.198 +
  85.199 +   /* It is an error to read while writing a png file */
  85.200 +   if (png_ptr->read_data_fn != NULL)
  85.201 +   {
  85.202 +      png_ptr->read_data_fn = NULL;
  85.203 +      png_warning(png_ptr,
  85.204 +         "Attempted to set both read_data_fn and write_data_fn in");
  85.205 +      png_warning(png_ptr,
  85.206 +         "the same structure.  Resetting read_data_fn to NULL.");
  85.207 +   }
  85.208 +}
  85.209 +
  85.210 +#if defined(USE_FAR_KEYWORD)
  85.211 +#if defined(_MSC_VER)
  85.212 +void *png_far_to_near(png_structp png_ptr, png_voidp ptr, int check)
  85.213 +{
  85.214 +   void *near_ptr;
  85.215 +   void FAR *far_ptr;
  85.216 +   FP_OFF(near_ptr) = FP_OFF(ptr);
  85.217 +   far_ptr = (void FAR *)near_ptr;
  85.218 +   if (check != 0)
  85.219 +      if (FP_SEG(ptr) != FP_SEG(far_ptr))
  85.220 +         png_error(png_ptr, "segment lost in conversion");
  85.221 +   return(near_ptr);
  85.222 +}
  85.223 +#  else
  85.224 +void *png_far_to_near(png_structp png_ptr, png_voidp ptr, int check)
  85.225 +{
  85.226 +   void *near_ptr;
  85.227 +   void FAR *far_ptr;
  85.228 +   near_ptr = (void FAR *)ptr;
  85.229 +   far_ptr = (void FAR *)near_ptr;
  85.230 +   if (check != 0)
  85.231 +      if (far_ptr != ptr)
  85.232 +         png_error(png_ptr, "segment lost in conversion");
  85.233 +   return(near_ptr);
  85.234 +}
  85.235 +#   endif
  85.236 +#   endif
  85.237 +#endif /* PNG_WRITE_SUPPORTED */
    86.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    86.2 +++ b/libs/libpng/pngwrite.c	Thu Sep 08 06:28:38 2011 +0300
    86.3 @@ -0,0 +1,1547 @@
    86.4 +
    86.5 +/* pngwrite.c - general routines to write a PNG file
    86.6 + *
    86.7 + * Last changed in libpng 1.2.31 [August 19, 2008]
    86.8 + * For conditions of distribution and use, see copyright notice in png.h
    86.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   86.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   86.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   86.12 + */
   86.13 +
   86.14 +/* get internal access to png.h */
   86.15 +#define PNG_INTERNAL
   86.16 +#include "png.h"
   86.17 +#ifdef PNG_WRITE_SUPPORTED
   86.18 +
   86.19 +/* Writes all the PNG information.  This is the suggested way to use the
   86.20 + * library.  If you have a new chunk to add, make a function to write it,
   86.21 + * and put it in the correct location here.  If you want the chunk written
   86.22 + * after the image data, put it in png_write_end().  I strongly encourage
   86.23 + * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
   86.24 + * the chunk, as that will keep the code from breaking if you want to just
   86.25 + * write a plain PNG file.  If you have long comments, I suggest writing
   86.26 + * them in png_write_end(), and compressing them.
   86.27 + */
   86.28 +void PNGAPI
   86.29 +png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
   86.30 +{
   86.31 +   png_debug(1, "in png_write_info_before_PLTE\n");
   86.32 +   if (png_ptr == NULL || info_ptr == NULL)
   86.33 +      return;
   86.34 +   if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
   86.35 +   {
   86.36 +   png_write_sig(png_ptr); /* write PNG signature */
   86.37 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
   86.38 +   if ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
   86.39 +   {
   86.40 +      png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
   86.41 +      png_ptr->mng_features_permitted=0;
   86.42 +   }
   86.43 +#endif
   86.44 +   /* write IHDR information. */
   86.45 +   png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
   86.46 +      info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
   86.47 +      info_ptr->filter_type,
   86.48 +#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
   86.49 +      info_ptr->interlace_type);
   86.50 +#else
   86.51 +      0);
   86.52 +#endif
   86.53 +   /* the rest of these check to see if the valid field has the appropriate
   86.54 +      flag set, and if it does, writes the chunk. */
   86.55 +#if defined(PNG_WRITE_gAMA_SUPPORTED)
   86.56 +   if (info_ptr->valid & PNG_INFO_gAMA)
   86.57 +   {
   86.58 +#  ifdef PNG_FLOATING_POINT_SUPPORTED
   86.59 +      png_write_gAMA(png_ptr, info_ptr->gamma);
   86.60 +#else
   86.61 +#ifdef PNG_FIXED_POINT_SUPPORTED
   86.62 +      png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
   86.63 +#  endif
   86.64 +#endif
   86.65 +   }
   86.66 +#endif
   86.67 +#if defined(PNG_WRITE_sRGB_SUPPORTED)
   86.68 +   if (info_ptr->valid & PNG_INFO_sRGB)
   86.69 +      png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
   86.70 +#endif
   86.71 +#if defined(PNG_WRITE_iCCP_SUPPORTED)
   86.72 +   if (info_ptr->valid & PNG_INFO_iCCP)
   86.73 +      png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
   86.74 +                     info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
   86.75 +#endif
   86.76 +#if defined(PNG_WRITE_sBIT_SUPPORTED)
   86.77 +   if (info_ptr->valid & PNG_INFO_sBIT)
   86.78 +      png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
   86.79 +#endif
   86.80 +#if defined(PNG_WRITE_cHRM_SUPPORTED)
   86.81 +   if (info_ptr->valid & PNG_INFO_cHRM)
   86.82 +   {
   86.83 +#ifdef PNG_FLOATING_POINT_SUPPORTED
   86.84 +      png_write_cHRM(png_ptr,
   86.85 +         info_ptr->x_white, info_ptr->y_white,
   86.86 +         info_ptr->x_red, info_ptr->y_red,
   86.87 +         info_ptr->x_green, info_ptr->y_green,
   86.88 +         info_ptr->x_blue, info_ptr->y_blue);
   86.89 +#else
   86.90 +#  ifdef PNG_FIXED_POINT_SUPPORTED
   86.91 +      png_write_cHRM_fixed(png_ptr,
   86.92 +         info_ptr->int_x_white, info_ptr->int_y_white,
   86.93 +         info_ptr->int_x_red, info_ptr->int_y_red,
   86.94 +         info_ptr->int_x_green, info_ptr->int_y_green,
   86.95 +         info_ptr->int_x_blue, info_ptr->int_y_blue);
   86.96 +#  endif
   86.97 +#endif
   86.98 +   }
   86.99 +#endif
  86.100 +#if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  86.101 +   if (info_ptr->unknown_chunks_num)
  86.102 +   {
  86.103 +       png_unknown_chunk *up;
  86.104 +
  86.105 +       png_debug(5, "writing extra chunks\n");
  86.106 +
  86.107 +       for (up = info_ptr->unknown_chunks;
  86.108 +            up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  86.109 +            up++)
  86.110 +       {
  86.111 +         int keep=png_handle_as_unknown(png_ptr, up->name);
  86.112 +         if (keep != PNG_HANDLE_CHUNK_NEVER &&
  86.113 +            up->location && !(up->location & PNG_HAVE_PLTE) &&
  86.114 +            !(up->location & PNG_HAVE_IDAT) &&
  86.115 +            ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  86.116 +            (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  86.117 +         {
  86.118 +            if (up->size == 0)
  86.119 +               png_warning(png_ptr, "Writing zero-length unknown chunk");
  86.120 +            png_write_chunk(png_ptr, up->name, up->data, up->size);
  86.121 +         }
  86.122 +       }
  86.123 +   }
  86.124 +#endif
  86.125 +      png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  86.126 +   }
  86.127 +}
  86.128 +
  86.129 +void PNGAPI
  86.130 +png_write_info(png_structp png_ptr, png_infop info_ptr)
  86.131 +{
  86.132 +#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  86.133 +   int i;
  86.134 +#endif
  86.135 +
  86.136 +   png_debug(1, "in png_write_info\n");
  86.137 +
  86.138 +   if (png_ptr == NULL || info_ptr == NULL)
  86.139 +      return;
  86.140 +
  86.141 +   png_write_info_before_PLTE(png_ptr, info_ptr);
  86.142 +
  86.143 +   if (info_ptr->valid & PNG_INFO_PLTE)
  86.144 +      png_write_PLTE(png_ptr, info_ptr->palette,
  86.145 +         (png_uint_32)info_ptr->num_palette);
  86.146 +   else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  86.147 +      png_error(png_ptr, "Valid palette required for paletted images");
  86.148 +
  86.149 +#if defined(PNG_WRITE_tRNS_SUPPORTED)
  86.150 +   if (info_ptr->valid & PNG_INFO_tRNS)
  86.151 +      {
  86.152 +#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  86.153 +         /* invert the alpha channel (in tRNS) */
  86.154 +         if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  86.155 +            info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  86.156 +         {
  86.157 +            int j;
  86.158 +            for (j=0; j<(int)info_ptr->num_trans; j++)
  86.159 +               info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  86.160 +         }
  86.161 +#endif
  86.162 +      png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  86.163 +         info_ptr->num_trans, info_ptr->color_type);
  86.164 +      }
  86.165 +#endif
  86.166 +#if defined(PNG_WRITE_bKGD_SUPPORTED)
  86.167 +   if (info_ptr->valid & PNG_INFO_bKGD)
  86.168 +      png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  86.169 +#endif
  86.170 +#if defined(PNG_WRITE_hIST_SUPPORTED)
  86.171 +   if (info_ptr->valid & PNG_INFO_hIST)
  86.172 +      png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  86.173 +#endif
  86.174 +#if defined(PNG_WRITE_oFFs_SUPPORTED)
  86.175 +   if (info_ptr->valid & PNG_INFO_oFFs)
  86.176 +      png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  86.177 +         info_ptr->offset_unit_type);
  86.178 +#endif
  86.179 +#if defined(PNG_WRITE_pCAL_SUPPORTED)
  86.180 +   if (info_ptr->valid & PNG_INFO_pCAL)
  86.181 +      png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  86.182 +         info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  86.183 +         info_ptr->pcal_units, info_ptr->pcal_params);
  86.184 +#endif
  86.185 +#if defined(PNG_WRITE_sCAL_SUPPORTED)
  86.186 +   if (info_ptr->valid & PNG_INFO_sCAL)
  86.187 +#if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  86.188 +      png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  86.189 +          info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  86.190 +#else
  86.191 +#ifdef PNG_FIXED_POINT_SUPPORTED
  86.192 +      png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  86.193 +          info_ptr->scal_s_width, info_ptr->scal_s_height);
  86.194 +#else
  86.195 +      png_warning(png_ptr,
  86.196 +          "png_write_sCAL not supported; sCAL chunk not written.");
  86.197 +#endif
  86.198 +#endif
  86.199 +#endif
  86.200 +#if defined(PNG_WRITE_pHYs_SUPPORTED)
  86.201 +   if (info_ptr->valid & PNG_INFO_pHYs)
  86.202 +      png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  86.203 +         info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  86.204 +#endif
  86.205 +#if defined(PNG_WRITE_tIME_SUPPORTED)
  86.206 +   if (info_ptr->valid & PNG_INFO_tIME)
  86.207 +   {
  86.208 +      png_write_tIME(png_ptr, &(info_ptr->mod_time));
  86.209 +      png_ptr->mode |= PNG_WROTE_tIME;
  86.210 +   }
  86.211 +#endif
  86.212 +#if defined(PNG_WRITE_sPLT_SUPPORTED)
  86.213 +   if (info_ptr->valid & PNG_INFO_sPLT)
  86.214 +     for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  86.215 +       png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  86.216 +#endif
  86.217 +#if defined(PNG_WRITE_TEXT_SUPPORTED)
  86.218 +   /* Check to see if we need to write text chunks */
  86.219 +   for (i = 0; i < info_ptr->num_text; i++)
  86.220 +   {
  86.221 +      png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  86.222 +         info_ptr->text[i].compression);
  86.223 +      /* an internationalized chunk? */
  86.224 +      if (info_ptr->text[i].compression > 0)
  86.225 +      {
  86.226 +#if defined(PNG_WRITE_iTXt_SUPPORTED)
  86.227 +          /* write international chunk */
  86.228 +          png_write_iTXt(png_ptr,
  86.229 +                         info_ptr->text[i].compression,
  86.230 +                         info_ptr->text[i].key,
  86.231 +                         info_ptr->text[i].lang,
  86.232 +                         info_ptr->text[i].lang_key,
  86.233 +                         info_ptr->text[i].text);
  86.234 +#else
  86.235 +          png_warning(png_ptr, "Unable to write international text");
  86.236 +#endif
  86.237 +          /* Mark this chunk as written */
  86.238 +          info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  86.239 +      }
  86.240 +      /* If we want a compressed text chunk */
  86.241 +      else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  86.242 +      {
  86.243 +#if defined(PNG_WRITE_zTXt_SUPPORTED)
  86.244 +         /* write compressed chunk */
  86.245 +         png_write_zTXt(png_ptr, info_ptr->text[i].key,
  86.246 +            info_ptr->text[i].text, 0,
  86.247 +            info_ptr->text[i].compression);
  86.248 +#else
  86.249 +         png_warning(png_ptr, "Unable to write compressed text");
  86.250 +#endif
  86.251 +         /* Mark this chunk as written */
  86.252 +         info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  86.253 +      }
  86.254 +      else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  86.255 +      {
  86.256 +#if defined(PNG_WRITE_tEXt_SUPPORTED)
  86.257 +         /* write uncompressed chunk */
  86.258 +         png_write_tEXt(png_ptr, info_ptr->text[i].key,
  86.259 +                         info_ptr->text[i].text,
  86.260 +                         0);
  86.261 +#else
  86.262 +         png_warning(png_ptr, "Unable to write uncompressed text");
  86.263 +#endif
  86.264 +         /* Mark this chunk as written */
  86.265 +         info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  86.266 +      }
  86.267 +   }
  86.268 +#endif
  86.269 +#if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  86.270 +   if (info_ptr->unknown_chunks_num)
  86.271 +   {
  86.272 +       png_unknown_chunk *up;
  86.273 +
  86.274 +       png_debug(5, "writing extra chunks\n");
  86.275 +
  86.276 +       for (up = info_ptr->unknown_chunks;
  86.277 +            up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  86.278 +            up++)
  86.279 +       {
  86.280 +         int keep=png_handle_as_unknown(png_ptr, up->name);
  86.281 +         if (keep != PNG_HANDLE_CHUNK_NEVER &&
  86.282 +            up->location && (up->location & PNG_HAVE_PLTE) &&
  86.283 +            !(up->location & PNG_HAVE_IDAT) &&
  86.284 +            ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  86.285 +            (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  86.286 +         {
  86.287 +            png_write_chunk(png_ptr, up->name, up->data, up->size);
  86.288 +         }
  86.289 +       }
  86.290 +   }
  86.291 +#endif
  86.292 +}
  86.293 +
  86.294 +/* Writes the end of the PNG file.  If you don't want to write comments or
  86.295 + * time information, you can pass NULL for info.  If you already wrote these
  86.296 + * in png_write_info(), do not write them again here.  If you have long
  86.297 + * comments, I suggest writing them here, and compressing them.
  86.298 + */
  86.299 +void PNGAPI
  86.300 +png_write_end(png_structp png_ptr, png_infop info_ptr)
  86.301 +{
  86.302 +   png_debug(1, "in png_write_end\n");
  86.303 +   if (png_ptr == NULL)
  86.304 +      return;
  86.305 +   if (!(png_ptr->mode & PNG_HAVE_IDAT))
  86.306 +      png_error(png_ptr, "No IDATs written into file");
  86.307 +
  86.308 +   /* see if user wants us to write information chunks */
  86.309 +   if (info_ptr != NULL)
  86.310 +   {
  86.311 +#if defined(PNG_WRITE_TEXT_SUPPORTED)
  86.312 +      int i; /* local index variable */
  86.313 +#endif
  86.314 +#if defined(PNG_WRITE_tIME_SUPPORTED)
  86.315 +      /* check to see if user has supplied a time chunk */
  86.316 +      if ((info_ptr->valid & PNG_INFO_tIME) &&
  86.317 +         !(png_ptr->mode & PNG_WROTE_tIME))
  86.318 +         png_write_tIME(png_ptr, &(info_ptr->mod_time));
  86.319 +#endif
  86.320 +#if defined(PNG_WRITE_TEXT_SUPPORTED)
  86.321 +      /* loop through comment chunks */
  86.322 +      for (i = 0; i < info_ptr->num_text; i++)
  86.323 +      {
  86.324 +         png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  86.325 +            info_ptr->text[i].compression);
  86.326 +         /* an internationalized chunk? */
  86.327 +         if (info_ptr->text[i].compression > 0)
  86.328 +         {
  86.329 +#if defined(PNG_WRITE_iTXt_SUPPORTED)
  86.330 +             /* write international chunk */
  86.331 +             png_write_iTXt(png_ptr,
  86.332 +                         info_ptr->text[i].compression,
  86.333 +                         info_ptr->text[i].key,
  86.334 +                         info_ptr->text[i].lang,
  86.335 +                         info_ptr->text[i].lang_key,
  86.336 +                         info_ptr->text[i].text);
  86.337 +#else
  86.338 +             png_warning(png_ptr, "Unable to write international text");
  86.339 +#endif
  86.340 +             /* Mark this chunk as written */
  86.341 +             info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  86.342 +         }
  86.343 +         else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  86.344 +         {
  86.345 +#if defined(PNG_WRITE_zTXt_SUPPORTED)
  86.346 +            /* write compressed chunk */
  86.347 +            png_write_zTXt(png_ptr, info_ptr->text[i].key,
  86.348 +               info_ptr->text[i].text, 0,
  86.349 +               info_ptr->text[i].compression);
  86.350 +#else
  86.351 +            png_warning(png_ptr, "Unable to write compressed text");
  86.352 +#endif
  86.353 +            /* Mark this chunk as written */
  86.354 +            info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  86.355 +         }
  86.356 +         else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  86.357 +         {
  86.358 +#if defined(PNG_WRITE_tEXt_SUPPORTED)
  86.359 +            /* write uncompressed chunk */
  86.360 +            png_write_tEXt(png_ptr, info_ptr->text[i].key,
  86.361 +               info_ptr->text[i].text, 0);
  86.362 +#else
  86.363 +            png_warning(png_ptr, "Unable to write uncompressed text");
  86.364 +#endif
  86.365 +
  86.366 +            /* Mark this chunk as written */
  86.367 +            info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  86.368 +         }
  86.369 +      }
  86.370 +#endif
  86.371 +#if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  86.372 +   if (info_ptr->unknown_chunks_num)
  86.373 +   {
  86.374 +       png_unknown_chunk *up;
  86.375 +
  86.376 +       png_debug(5, "writing extra chunks\n");
  86.377 +
  86.378 +       for (up = info_ptr->unknown_chunks;
  86.379 +            up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  86.380 +            up++)
  86.381 +       {
  86.382 +         int keep=png_handle_as_unknown(png_ptr, up->name);
  86.383 +         if (keep != PNG_HANDLE_CHUNK_NEVER &&
  86.384 +            up->location && (up->location & PNG_AFTER_IDAT) &&
  86.385 +            ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  86.386 +            (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  86.387 +         {
  86.388 +            png_write_chunk(png_ptr, up->name, up->data, up->size);
  86.389 +         }
  86.390 +       }
  86.391 +   }
  86.392 +#endif
  86.393 +   }
  86.394 +
  86.395 +   png_ptr->mode |= PNG_AFTER_IDAT;
  86.396 +
  86.397 +   /* write end of PNG file */
  86.398 +   png_write_IEND(png_ptr);
  86.399 +   /* This flush, added in libpng-1.0.8, removed from libpng-1.0.9beta03,
  86.400 +    * and restored again in libpng-1.2.30, may cause some applications that
  86.401 +    * do not set png_ptr->output_flush_fn to crash.  If your application
  86.402 +    * experiences a problem, please try building libpng with
  86.403 +    * PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED defined, and report the event to
  86.404 +    * png-mng-implement at lists.sf.net .  This kludge will be removed
  86.405 +    * from libpng-1.4.0.
  86.406 +    */
  86.407 +#if defined(PNG_WRITE_FLUSH_SUPPORTED) && \
  86.408 +    defined(PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED)
  86.409 +   png_flush(png_ptr);
  86.410 +#endif
  86.411 +}
  86.412 +
  86.413 +#if defined(PNG_WRITE_tIME_SUPPORTED)
  86.414 +#if !defined(_WIN32_WCE)
  86.415 +/* "time.h" functions are not supported on WindowsCE */
  86.416 +void PNGAPI
  86.417 +png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  86.418 +{
  86.419 +   png_debug(1, "in png_convert_from_struct_tm\n");
  86.420 +   ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  86.421 +   ptime->month = (png_byte)(ttime->tm_mon + 1);
  86.422 +   ptime->day = (png_byte)ttime->tm_mday;
  86.423 +   ptime->hour = (png_byte)ttime->tm_hour;
  86.424 +   ptime->minute = (png_byte)ttime->tm_min;
  86.425 +   ptime->second = (png_byte)ttime->tm_sec;
  86.426 +}
  86.427 +
  86.428 +void PNGAPI
  86.429 +png_convert_from_time_t(png_timep ptime, time_t ttime)
  86.430 +{
  86.431 +   struct tm *tbuf;
  86.432 +
  86.433 +   png_debug(1, "in png_convert_from_time_t\n");
  86.434 +   tbuf = gmtime(&ttime);
  86.435 +   png_convert_from_struct_tm(ptime, tbuf);
  86.436 +}
  86.437 +#endif
  86.438 +#endif
  86.439 +
  86.440 +/* Initialize png_ptr structure, and allocate any memory needed */
  86.441 +png_structp PNGAPI
  86.442 +png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  86.443 +   png_error_ptr error_fn, png_error_ptr warn_fn)
  86.444 +{
  86.445 +#ifdef PNG_USER_MEM_SUPPORTED
  86.446 +   return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  86.447 +      warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  86.448 +}
  86.449 +
  86.450 +/* Alternate initialize png_ptr structure, and allocate any memory needed */
  86.451 +png_structp PNGAPI
  86.452 +png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  86.453 +   png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  86.454 +   png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  86.455 +{
  86.456 +#endif /* PNG_USER_MEM_SUPPORTED */
  86.457 +#ifdef PNG_SETJMP_SUPPORTED
  86.458 +    volatile
  86.459 +#endif
  86.460 +    png_structp png_ptr;
  86.461 +#ifdef PNG_SETJMP_SUPPORTED
  86.462 +#ifdef USE_FAR_KEYWORD
  86.463 +   jmp_buf jmpbuf;
  86.464 +#endif
  86.465 +#endif
  86.466 +   int i;
  86.467 +   png_debug(1, "in png_create_write_struct\n");
  86.468 +#ifdef PNG_USER_MEM_SUPPORTED
  86.469 +   png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  86.470 +      (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  86.471 +#else
  86.472 +   png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  86.473 +#endif /* PNG_USER_MEM_SUPPORTED */
  86.474 +   if (png_ptr == NULL)
  86.475 +      return (NULL);
  86.476 +
  86.477 +   /* added at libpng-1.2.6 */
  86.478 +#ifdef PNG_SET_USER_LIMITS_SUPPORTED
  86.479 +   png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  86.480 +   png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  86.481 +#endif
  86.482 +
  86.483 +#ifdef PNG_SETJMP_SUPPORTED
  86.484 +#ifdef USE_FAR_KEYWORD
  86.485 +   if (setjmp(jmpbuf))
  86.486 +#else
  86.487 +   if (setjmp(png_ptr->jmpbuf))
  86.488 +#endif
  86.489 +   {
  86.490 +      png_free(png_ptr, png_ptr->zbuf);
  86.491 +       png_ptr->zbuf=NULL;
  86.492 +      png_destroy_struct(png_ptr);
  86.493 +      return (NULL);
  86.494 +   }
  86.495 +#ifdef USE_FAR_KEYWORD
  86.496 +   png_memcpy(png_ptr->jmpbuf, jmpbuf, png_sizeof(jmp_buf));
  86.497 +#endif
  86.498 +#endif
  86.499 +
  86.500 +#ifdef PNG_USER_MEM_SUPPORTED
  86.501 +   png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  86.502 +#endif /* PNG_USER_MEM_SUPPORTED */
  86.503 +   png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  86.504 +
  86.505 +   if (user_png_ver)
  86.506 +   {
  86.507 +     i=0;
  86.508 +     do
  86.509 +     {
  86.510 +       if (user_png_ver[i] != png_libpng_ver[i])
  86.511 +          png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  86.512 +     } while (png_libpng_ver[i++]);
  86.513 +   }
  86.514 +
  86.515 +   if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  86.516 +   {
  86.517 +     /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  86.518 +      * we must recompile any applications that use any older library version.
  86.519 +      * For versions after libpng 1.0, we will be compatible, so we need
  86.520 +      * only check the first digit.
  86.521 +      */
  86.522 +     if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  86.523 +         (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  86.524 +         (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  86.525 +     {
  86.526 +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  86.527 +        char msg[80];
  86.528 +        if (user_png_ver)
  86.529 +        {
  86.530 +          png_snprintf(msg, 80,
  86.531 +             "Application was compiled with png.h from libpng-%.20s",
  86.532 +             user_png_ver);
  86.533 +          png_warning(png_ptr, msg);
  86.534 +        }
  86.535 +        png_snprintf(msg, 80,
  86.536 +           "Application  is  running with png.c from libpng-%.20s",
  86.537 +           png_libpng_ver);
  86.538 +        png_warning(png_ptr, msg);
  86.539 +#endif
  86.540 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
  86.541 +        png_ptr->flags=0;
  86.542 +#endif
  86.543 +        png_error(png_ptr,
  86.544 +           "Incompatible libpng version in application and library");
  86.545 +     }
  86.546 +   }
  86.547 +
  86.548 +   /* initialize zbuf - compression buffer */
  86.549 +   png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  86.550 +   png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  86.551 +      (png_uint_32)png_ptr->zbuf_size);
  86.552 +
  86.553 +   png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  86.554 +      png_flush_ptr_NULL);
  86.555 +
  86.556 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  86.557 +   png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  86.558 +      1, png_doublep_NULL, png_doublep_NULL);
  86.559 +#endif
  86.560 +
  86.561 +#ifdef PNG_SETJMP_SUPPORTED
  86.562 +/* Applications that neglect to set up their own setjmp() and then encounter
  86.563 +   a png_error() will longjmp here.  Since the jmpbuf is then meaningless we
  86.564 +   abort instead of returning. */
  86.565 +#ifdef USE_FAR_KEYWORD
  86.566 +   if (setjmp(jmpbuf))
  86.567 +      PNG_ABORT();
  86.568 +   png_memcpy(png_ptr->jmpbuf, jmpbuf, png_sizeof(jmp_buf));
  86.569 +#else
  86.570 +   if (setjmp(png_ptr->jmpbuf))
  86.571 +      PNG_ABORT();
  86.572 +#endif
  86.573 +#endif
  86.574 +   return (png_ptr);
  86.575 +}
  86.576 +
  86.577 +/* Initialize png_ptr structure, and allocate any memory needed */
  86.578 +#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  86.579 +/* Deprecated. */
  86.580 +#undef png_write_init
  86.581 +void PNGAPI
  86.582 +png_write_init(png_structp png_ptr)
  86.583 +{
  86.584 +   /* We only come here via pre-1.0.7-compiled applications */
  86.585 +   png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  86.586 +}
  86.587 +
  86.588 +void PNGAPI
  86.589 +png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  86.590 +   png_size_t png_struct_size, png_size_t png_info_size)
  86.591 +{
  86.592 +   /* We only come here via pre-1.0.12-compiled applications */
  86.593 +   if (png_ptr == NULL) return;
  86.594 +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  86.595 +   if (png_sizeof(png_struct) > png_struct_size ||
  86.596 +      png_sizeof(png_info) > png_info_size)
  86.597 +   {
  86.598 +      char msg[80];
  86.599 +      png_ptr->warning_fn=NULL;
  86.600 +      if (user_png_ver)
  86.601 +      {
  86.602 +        png_snprintf(msg, 80,
  86.603 +           "Application was compiled with png.h from libpng-%.20s",
  86.604 +           user_png_ver);
  86.605 +        png_warning(png_ptr, msg);
  86.606 +      }
  86.607 +      png_snprintf(msg, 80,
  86.608 +         "Application  is  running with png.c from libpng-%.20s",
  86.609 +         png_libpng_ver);
  86.610 +      png_warning(png_ptr, msg);
  86.611 +   }
  86.612 +#endif
  86.613 +   if (png_sizeof(png_struct) > png_struct_size)
  86.614 +     {
  86.615 +       png_ptr->error_fn=NULL;
  86.616 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
  86.617 +       png_ptr->flags=0;
  86.618 +#endif
  86.619 +       png_error(png_ptr,
  86.620 +       "The png struct allocated by the application for writing is too small.");
  86.621 +     }
  86.622 +   if (png_sizeof(png_info) > png_info_size)
  86.623 +     {
  86.624 +       png_ptr->error_fn=NULL;
  86.625 +#ifdef PNG_ERROR_NUMBERS_SUPPORTED
  86.626 +       png_ptr->flags=0;
  86.627 +#endif
  86.628 +       png_error(png_ptr,
  86.629 +       "The info struct allocated by the application for writing is too small.");
  86.630 +     }
  86.631 +   png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  86.632 +}
  86.633 +#endif /* PNG_1_0_X || PNG_1_2_X */
  86.634 +
  86.635 +
  86.636 +void PNGAPI
  86.637 +png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  86.638 +   png_size_t png_struct_size)
  86.639 +{
  86.640 +   png_structp png_ptr=*ptr_ptr;
  86.641 +#ifdef PNG_SETJMP_SUPPORTED
  86.642 +   jmp_buf tmp_jmp; /* to save current jump buffer */
  86.643 +#endif
  86.644 +
  86.645 +   int i = 0;
  86.646 +
  86.647 +   if (png_ptr == NULL)
  86.648 +      return;
  86.649 +
  86.650 +   do
  86.651 +   {
  86.652 +     if (user_png_ver[i] != png_libpng_ver[i])
  86.653 +     {
  86.654 +#ifdef PNG_LEGACY_SUPPORTED
  86.655 +       png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  86.656 +#else
  86.657 +       png_ptr->warning_fn=NULL;
  86.658 +       png_warning(png_ptr,
  86.659 + "Application uses deprecated png_write_init() and should be recompiled.");
  86.660 +       break;
  86.661 +#endif
  86.662 +     }
  86.663 +   } while (png_libpng_ver[i++]);
  86.664 +
  86.665 +   png_debug(1, "in png_write_init_3\n");
  86.666 +
  86.667 +#ifdef PNG_SETJMP_SUPPORTED
  86.668 +   /* save jump buffer and error functions */
  86.669 +   png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  86.670 +#endif
  86.671 +
  86.672 +   if (png_sizeof(png_struct) > png_struct_size)
  86.673 +     {
  86.674 +       png_destroy_struct(png_ptr);
  86.675 +       png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  86.676 +       *ptr_ptr = png_ptr;
  86.677 +     }
  86.678 +
  86.679 +   /* reset all variables to 0 */
  86.680 +   png_memset(png_ptr, 0, png_sizeof(png_struct));
  86.681 +
  86.682 +   /* added at libpng-1.2.6 */
  86.683 +#ifdef PNG_SET_USER_LIMITS_SUPPORTED
  86.684 +   png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  86.685 +   png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  86.686 +#endif
  86.687 +
  86.688 +#ifdef PNG_SETJMP_SUPPORTED
  86.689 +   /* restore jump buffer */
  86.690 +   png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
  86.691 +#endif
  86.692 +
  86.693 +   png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  86.694 +      png_flush_ptr_NULL);
  86.695 +
  86.696 +   /* initialize zbuf - compression buffer */
  86.697 +   png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  86.698 +   png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  86.699 +      (png_uint_32)png_ptr->zbuf_size);
  86.700 +
  86.701 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  86.702 +   png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  86.703 +      1, png_doublep_NULL, png_doublep_NULL);
  86.704 +#endif
  86.705 +}
  86.706 +
  86.707 +/* Write a few rows of image data.  If the image is interlaced,
  86.708 + * either you will have to write the 7 sub images, or, if you
  86.709 + * have called png_set_interlace_handling(), you will have to
  86.710 + * "write" the image seven times.
  86.711 + */
  86.712 +void PNGAPI
  86.713 +png_write_rows(png_structp png_ptr, png_bytepp row,
  86.714 +   png_uint_32 num_rows)
  86.715 +{
  86.716 +   png_uint_32 i; /* row counter */
  86.717 +   png_bytepp rp; /* row pointer */
  86.718 +
  86.719 +   png_debug(1, "in png_write_rows\n");
  86.720 +
  86.721 +   if (png_ptr == NULL)
  86.722 +      return;
  86.723 +
  86.724 +   /* loop through the rows */
  86.725 +   for (i = 0, rp = row; i < num_rows; i++, rp++)
  86.726 +   {
  86.727 +      png_write_row(png_ptr, *rp);
  86.728 +   }
  86.729 +}
  86.730 +
  86.731 +/* Write the image.  You only need to call this function once, even
  86.732 + * if you are writing an interlaced image.
  86.733 + */
  86.734 +void PNGAPI
  86.735 +png_write_image(png_structp png_ptr, png_bytepp image)
  86.736 +{
  86.737 +   png_uint_32 i; /* row index */
  86.738 +   int pass, num_pass; /* pass variables */
  86.739 +   png_bytepp rp; /* points to current row */
  86.740 +
  86.741 +   if (png_ptr == NULL)
  86.742 +      return;
  86.743 +
  86.744 +   png_debug(1, "in png_write_image\n");
  86.745 +#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  86.746 +   /* intialize interlace handling.  If image is not interlaced,
  86.747 +      this will set pass to 1 */
  86.748 +   num_pass = png_set_interlace_handling(png_ptr);
  86.749 +#else
  86.750 +   num_pass = 1;
  86.751 +#endif
  86.752 +   /* loop through passes */
  86.753 +   for (pass = 0; pass < num_pass; pass++)
  86.754 +   {
  86.755 +      /* loop through image */
  86.756 +      for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  86.757 +      {
  86.758 +         png_write_row(png_ptr, *rp);
  86.759 +      }
  86.760 +   }
  86.761 +}
  86.762 +
  86.763 +/* called by user to write a row of image data */
  86.764 +void PNGAPI
  86.765 +png_write_row(png_structp png_ptr, png_bytep row)
  86.766 +{
  86.767 +   if (png_ptr == NULL)
  86.768 +      return;
  86.769 +   png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  86.770 +      png_ptr->row_number, png_ptr->pass);
  86.771 +
  86.772 +   /* initialize transformations and other stuff if first time */
  86.773 +   if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  86.774 +   {
  86.775 +   /* make sure we wrote the header info */
  86.776 +   if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  86.777 +      png_error(png_ptr,
  86.778 +         "png_write_info was never called before png_write_row.");
  86.779 +
  86.780 +   /* check for transforms that have been set but were defined out */
  86.781 +#if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  86.782 +   if (png_ptr->transformations & PNG_INVERT_MONO)
  86.783 +      png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  86.784 +#endif
  86.785 +#if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  86.786 +   if (png_ptr->transformations & PNG_FILLER)
  86.787 +      png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  86.788 +#endif
  86.789 +#if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  86.790 +   if (png_ptr->transformations & PNG_PACKSWAP)
  86.791 +      png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  86.792 +#endif
  86.793 +#if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  86.794 +   if (png_ptr->transformations & PNG_PACK)
  86.795 +      png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  86.796 +#endif
  86.797 +#if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  86.798 +   if (png_ptr->transformations & PNG_SHIFT)
  86.799 +      png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  86.800 +#endif
  86.801 +#if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  86.802 +   if (png_ptr->transformations & PNG_BGR)
  86.803 +      png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  86.804 +#endif
  86.805 +#if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  86.806 +   if (png_ptr->transformations & PNG_SWAP_BYTES)
  86.807 +      png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  86.808 +#endif
  86.809 +
  86.810 +      png_write_start_row(png_ptr);
  86.811 +   }
  86.812 +
  86.813 +#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  86.814 +   /* if interlaced and not interested in row, return */
  86.815 +   if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  86.816 +   {
  86.817 +      switch (png_ptr->pass)
  86.818 +      {
  86.819 +         case 0:
  86.820 +            if (png_ptr->row_number & 0x07)
  86.821 +            {
  86.822 +               png_write_finish_row(png_ptr);
  86.823 +               return;
  86.824 +            }
  86.825 +            break;
  86.826 +         case 1:
  86.827 +            if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  86.828 +            {
  86.829 +               png_write_finish_row(png_ptr);
  86.830 +               return;
  86.831 +            }
  86.832 +            break;
  86.833 +         case 2:
  86.834 +            if ((png_ptr->row_number & 0x07) != 4)
  86.835 +            {
  86.836 +               png_write_finish_row(png_ptr);
  86.837 +               return;
  86.838 +            }
  86.839 +            break;
  86.840 +         case 3:
  86.841 +            if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  86.842 +            {
  86.843 +               png_write_finish_row(png_ptr);
  86.844 +               return;
  86.845 +            }
  86.846 +            break;
  86.847 +         case 4:
  86.848 +            if ((png_ptr->row_number & 0x03) != 2)
  86.849 +            {
  86.850 +               png_write_finish_row(png_ptr);
  86.851 +               return;
  86.852 +            }
  86.853 +            break;
  86.854 +         case 5:
  86.855 +            if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  86.856 +            {
  86.857 +               png_write_finish_row(png_ptr);
  86.858 +               return;
  86.859 +            }
  86.860 +            break;
  86.861 +         case 6:
  86.862 +            if (!(png_ptr->row_number & 0x01))
  86.863 +            {
  86.864 +               png_write_finish_row(png_ptr);
  86.865 +               return;
  86.866 +            }
  86.867 +            break;
  86.868 +      }
  86.869 +   }
  86.870 +#endif
  86.871 +
  86.872 +   /* set up row info for transformations */
  86.873 +   png_ptr->row_info.color_type = png_ptr->color_type;
  86.874 +   png_ptr->row_info.width = png_ptr->usr_width;
  86.875 +   png_ptr->row_info.channels = png_ptr->usr_channels;
  86.876 +   png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  86.877 +   png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  86.878 +      png_ptr->row_info.channels);
  86.879 +
  86.880 +   png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  86.881 +      png_ptr->row_info.width);
  86.882 +
  86.883 +   png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  86.884 +   png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  86.885 +   png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  86.886 +   png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  86.887 +   png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  86.888 +   png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  86.889 +
  86.890 +   /* Copy user's row into buffer, leaving room for filter byte. */
  86.891 +   png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  86.892 +      png_ptr->row_info.rowbytes);
  86.893 +
  86.894 +#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  86.895 +   /* handle interlacing */
  86.896 +   if (png_ptr->interlaced && png_ptr->pass < 6 &&
  86.897 +      (png_ptr->transformations & PNG_INTERLACE))
  86.898 +   {
  86.899 +      png_do_write_interlace(&(png_ptr->row_info),
  86.900 +         png_ptr->row_buf + 1, png_ptr->pass);
  86.901 +      /* this should always get caught above, but still ... */
  86.902 +      if (!(png_ptr->row_info.width))
  86.903 +      {
  86.904 +         png_write_finish_row(png_ptr);
  86.905 +         return;
  86.906 +      }
  86.907 +   }
  86.908 +#endif
  86.909 +
  86.910 +   /* handle other transformations */
  86.911 +   if (png_ptr->transformations)
  86.912 +      png_do_write_transformations(png_ptr);
  86.913 +
  86.914 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
  86.915 +   /* Write filter_method 64 (intrapixel differencing) only if
  86.916 +    * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  86.917 +    * 2. Libpng did not write a PNG signature (this filter_method is only
  86.918 +    *    used in PNG datastreams that are embedded in MNG datastreams) and
  86.919 +    * 3. The application called png_permit_mng_features with a mask that
  86.920 +    *    included PNG_FLAG_MNG_FILTER_64 and
  86.921 +    * 4. The filter_method is 64 and
  86.922 +    * 5. The color_type is RGB or RGBA
  86.923 +    */
  86.924 +   if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  86.925 +      (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  86.926 +   {
  86.927 +      /* Intrapixel differencing */
  86.928 +      png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  86.929 +   }
  86.930 +#endif
  86.931 +
  86.932 +   /* Find a filter if necessary, filter the row and write it out. */
  86.933 +   png_write_find_filter(png_ptr, &(png_ptr->row_info));
  86.934 +
  86.935 +   if (png_ptr->write_row_fn != NULL)
  86.936 +      (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  86.937 +}
  86.938 +
  86.939 +#if defined(PNG_WRITE_FLUSH_SUPPORTED)
  86.940 +/* Set the automatic flush interval or 0 to turn flushing off */
  86.941 +void PNGAPI
  86.942 +png_set_flush(png_structp png_ptr, int nrows)
  86.943 +{
  86.944 +   png_debug(1, "in png_set_flush\n");
  86.945 +   if (png_ptr == NULL)
  86.946 +      return;
  86.947 +   png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  86.948 +}
  86.949 +
  86.950 +/* flush the current output buffers now */
  86.951 +void PNGAPI
  86.952 +png_write_flush(png_structp png_ptr)
  86.953 +{
  86.954 +   int wrote_IDAT;
  86.955 +
  86.956 +   png_debug(1, "in png_write_flush\n");
  86.957 +   if (png_ptr == NULL)
  86.958 +      return;
  86.959 +   /* We have already written out all of the data */
  86.960 +   if (png_ptr->row_number >= png_ptr->num_rows)
  86.961 +     return;
  86.962 +
  86.963 +   do
  86.964 +   {
  86.965 +      int ret;
  86.966 +
  86.967 +      /* compress the data */
  86.968 +      ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  86.969 +      wrote_IDAT = 0;
  86.970 +
  86.971 +      /* check for compression errors */
  86.972 +      if (ret != Z_OK)
  86.973 +      {
  86.974 +         if (png_ptr->zstream.msg != NULL)
  86.975 +            png_error(png_ptr, png_ptr->zstream.msg);
  86.976 +         else
  86.977 +            png_error(png_ptr, "zlib error");
  86.978 +      }
  86.979 +
  86.980 +      if (!(png_ptr->zstream.avail_out))
  86.981 +      {
  86.982 +         /* write the IDAT and reset the zlib output buffer */
  86.983 +         png_write_IDAT(png_ptr, png_ptr->zbuf,
  86.984 +                        png_ptr->zbuf_size);
  86.985 +         png_ptr->zstream.next_out = png_ptr->zbuf;
  86.986 +         png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  86.987 +         wrote_IDAT = 1;
  86.988 +      }
  86.989 +   } while(wrote_IDAT == 1);
  86.990 +
  86.991 +   /* If there is any data left to be output, write it into a new IDAT */
  86.992 +   if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  86.993 +   {
  86.994 +      /* write the IDAT and reset the zlib output buffer */
  86.995 +      png_write_IDAT(png_ptr, png_ptr->zbuf,
  86.996 +                     png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  86.997 +      png_ptr->zstream.next_out = png_ptr->zbuf;
  86.998 +      png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  86.999 +   }
 86.1000 +   png_ptr->flush_rows = 0;
 86.1001 +   png_flush(png_ptr);
 86.1002 +}
 86.1003 +#endif /* PNG_WRITE_FLUSH_SUPPORTED */
 86.1004 +
 86.1005 +/* free all memory used by the write */
 86.1006 +void PNGAPI
 86.1007 +png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
 86.1008 +{
 86.1009 +   png_structp png_ptr = NULL;
 86.1010 +   png_infop info_ptr = NULL;
 86.1011 +#ifdef PNG_USER_MEM_SUPPORTED
 86.1012 +   png_free_ptr free_fn = NULL;
 86.1013 +   png_voidp mem_ptr = NULL;
 86.1014 +#endif
 86.1015 +
 86.1016 +   png_debug(1, "in png_destroy_write_struct\n");
 86.1017 +   if (png_ptr_ptr != NULL)
 86.1018 +   {
 86.1019 +      png_ptr = *png_ptr_ptr;
 86.1020 +#ifdef PNG_USER_MEM_SUPPORTED
 86.1021 +      free_fn = png_ptr->free_fn;
 86.1022 +      mem_ptr = png_ptr->mem_ptr;
 86.1023 +#endif
 86.1024 +   }
 86.1025 +
 86.1026 +#ifdef PNG_USER_MEM_SUPPORTED
 86.1027 +   if (png_ptr != NULL)
 86.1028 +   {
 86.1029 +      free_fn = png_ptr->free_fn;
 86.1030 +      mem_ptr = png_ptr->mem_ptr;
 86.1031 +   }
 86.1032 +#endif
 86.1033 +
 86.1034 +   if (info_ptr_ptr != NULL)
 86.1035 +      info_ptr = *info_ptr_ptr;
 86.1036 +
 86.1037 +   if (info_ptr != NULL)
 86.1038 +   {
 86.1039 +      if (png_ptr != NULL)
 86.1040 +      {
 86.1041 +        png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
 86.1042 +
 86.1043 +#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
 86.1044 +        if (png_ptr->num_chunk_list)
 86.1045 +        {
 86.1046 +           png_free(png_ptr, png_ptr->chunk_list);
 86.1047 +           png_ptr->chunk_list=NULL;
 86.1048 +           png_ptr->num_chunk_list = 0;
 86.1049 +        }
 86.1050 +#endif
 86.1051 +      }
 86.1052 +
 86.1053 +#ifdef PNG_USER_MEM_SUPPORTED
 86.1054 +      png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
 86.1055 +         (png_voidp)mem_ptr);
 86.1056 +#else
 86.1057 +      png_destroy_struct((png_voidp)info_ptr);
 86.1058 +#endif
 86.1059 +      *info_ptr_ptr = NULL;
 86.1060 +   }
 86.1061 +
 86.1062 +   if (png_ptr != NULL)
 86.1063 +   {
 86.1064 +      png_write_destroy(png_ptr);
 86.1065 +#ifdef PNG_USER_MEM_SUPPORTED
 86.1066 +      png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
 86.1067 +         (png_voidp)mem_ptr);
 86.1068 +#else
 86.1069 +      png_destroy_struct((png_voidp)png_ptr);
 86.1070 +#endif
 86.1071 +      *png_ptr_ptr = NULL;
 86.1072 +   }
 86.1073 +}
 86.1074 +
 86.1075 +
 86.1076 +/* Free any memory used in png_ptr struct (old method) */
 86.1077 +void /* PRIVATE */
 86.1078 +png_write_destroy(png_structp png_ptr)
 86.1079 +{
 86.1080 +#ifdef PNG_SETJMP_SUPPORTED
 86.1081 +   jmp_buf tmp_jmp; /* save jump buffer */
 86.1082 +#endif
 86.1083 +   png_error_ptr error_fn;
 86.1084 +   png_error_ptr warning_fn;
 86.1085 +   png_voidp error_ptr;
 86.1086 +#ifdef PNG_USER_MEM_SUPPORTED
 86.1087 +   png_free_ptr free_fn;
 86.1088 +#endif
 86.1089 +
 86.1090 +   png_debug(1, "in png_write_destroy\n");
 86.1091 +   /* free any memory zlib uses */
 86.1092 +   deflateEnd(&png_ptr->zstream);
 86.1093 +
 86.1094 +   /* free our memory.  png_free checks NULL for us. */
 86.1095 +   png_free(png_ptr, png_ptr->zbuf);
 86.1096 +   png_free(png_ptr, png_ptr->row_buf);
 86.1097 +#ifndef PNG_NO_WRITE_FILTER
 86.1098 +   png_free(png_ptr, png_ptr->prev_row);
 86.1099 +   png_free(png_ptr, png_ptr->sub_row);
 86.1100 +   png_free(png_ptr, png_ptr->up_row);
 86.1101 +   png_free(png_ptr, png_ptr->avg_row);
 86.1102 +   png_free(png_ptr, png_ptr->paeth_row);
 86.1103 +#endif
 86.1104 +
 86.1105 +#if defined(PNG_TIME_RFC1123_SUPPORTED)
 86.1106 +   png_free(png_ptr, png_ptr->time_buffer);
 86.1107 +#endif
 86.1108 +
 86.1109 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 86.1110 +   png_free(png_ptr, png_ptr->prev_filters);
 86.1111 +   png_free(png_ptr, png_ptr->filter_weights);
 86.1112 +   png_free(png_ptr, png_ptr->inv_filter_weights);
 86.1113 +   png_free(png_ptr, png_ptr->filter_costs);
 86.1114 +   png_free(png_ptr, png_ptr->inv_filter_costs);
 86.1115 +#endif
 86.1116 +
 86.1117 +#ifdef PNG_SETJMP_SUPPORTED
 86.1118 +   /* reset structure */
 86.1119 +   png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
 86.1120 +#endif
 86.1121 +
 86.1122 +   error_fn = png_ptr->error_fn;
 86.1123 +   warning_fn = png_ptr->warning_fn;
 86.1124 +   error_ptr = png_ptr->error_ptr;
 86.1125 +#ifdef PNG_USER_MEM_SUPPORTED
 86.1126 +   free_fn = png_ptr->free_fn;
 86.1127 +#endif
 86.1128 +
 86.1129 +   png_memset(png_ptr, 0, png_sizeof(png_struct));
 86.1130 +
 86.1131 +   png_ptr->error_fn = error_fn;
 86.1132 +   png_ptr->warning_fn = warning_fn;
 86.1133 +   png_ptr->error_ptr = error_ptr;
 86.1134 +#ifdef PNG_USER_MEM_SUPPORTED
 86.1135 +   png_ptr->free_fn = free_fn;
 86.1136 +#endif
 86.1137 +
 86.1138 +#ifdef PNG_SETJMP_SUPPORTED
 86.1139 +   png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
 86.1140 +#endif
 86.1141 +}
 86.1142 +
 86.1143 +/* Allow the application to select one or more row filters to use. */
 86.1144 +void PNGAPI
 86.1145 +png_set_filter(png_structp png_ptr, int method, int filters)
 86.1146 +{
 86.1147 +   png_debug(1, "in png_set_filter\n");
 86.1148 +   if (png_ptr == NULL)
 86.1149 +      return;
 86.1150 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
 86.1151 +   if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
 86.1152 +      (method == PNG_INTRAPIXEL_DIFFERENCING))
 86.1153 +         method = PNG_FILTER_TYPE_BASE;
 86.1154 +#endif
 86.1155 +   if (method == PNG_FILTER_TYPE_BASE)
 86.1156 +   {
 86.1157 +      switch (filters & (PNG_ALL_FILTERS | 0x07))
 86.1158 +      {
 86.1159 +#ifndef PNG_NO_WRITE_FILTER
 86.1160 +         case 5:
 86.1161 +         case 6:
 86.1162 +         case 7: png_warning(png_ptr, "Unknown row filter for method 0");
 86.1163 +#endif /* PNG_NO_WRITE_FILTER */
 86.1164 +         case PNG_FILTER_VALUE_NONE:
 86.1165 +              png_ptr->do_filter=PNG_FILTER_NONE; break;
 86.1166 +#ifndef PNG_NO_WRITE_FILTER
 86.1167 +         case PNG_FILTER_VALUE_SUB:
 86.1168 +              png_ptr->do_filter=PNG_FILTER_SUB; break;
 86.1169 +         case PNG_FILTER_VALUE_UP:
 86.1170 +              png_ptr->do_filter=PNG_FILTER_UP; break;
 86.1171 +         case PNG_FILTER_VALUE_AVG:
 86.1172 +              png_ptr->do_filter=PNG_FILTER_AVG; break;
 86.1173 +         case PNG_FILTER_VALUE_PAETH:
 86.1174 +              png_ptr->do_filter=PNG_FILTER_PAETH; break;
 86.1175 +         default: png_ptr->do_filter = (png_byte)filters; break;
 86.1176 +#else
 86.1177 +         default: png_warning(png_ptr, "Unknown row filter for method 0");
 86.1178 +#endif /* PNG_NO_WRITE_FILTER */
 86.1179 +      }
 86.1180 +
 86.1181 +      /* If we have allocated the row_buf, this means we have already started
 86.1182 +       * with the image and we should have allocated all of the filter buffers
 86.1183 +       * that have been selected.  If prev_row isn't already allocated, then
 86.1184 +       * it is too late to start using the filters that need it, since we
 86.1185 +       * will be missing the data in the previous row.  If an application
 86.1186 +       * wants to start and stop using particular filters during compression,
 86.1187 +       * it should start out with all of the filters, and then add and
 86.1188 +       * remove them after the start of compression.
 86.1189 +       */
 86.1190 +      if (png_ptr->row_buf != NULL)
 86.1191 +      {
 86.1192 +#ifndef PNG_NO_WRITE_FILTER
 86.1193 +         if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
 86.1194 +         {
 86.1195 +            png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
 86.1196 +              (png_ptr->rowbytes + 1));
 86.1197 +            png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
 86.1198 +         }
 86.1199 +
 86.1200 +         if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
 86.1201 +         {
 86.1202 +            if (png_ptr->prev_row == NULL)
 86.1203 +            {
 86.1204 +               png_warning(png_ptr, "Can't add Up filter after starting");
 86.1205 +               png_ptr->do_filter &= ~PNG_FILTER_UP;
 86.1206 +            }
 86.1207 +            else
 86.1208 +            {
 86.1209 +               png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
 86.1210 +                  (png_ptr->rowbytes + 1));
 86.1211 +               png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
 86.1212 +            }
 86.1213 +         }
 86.1214 +
 86.1215 +         if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
 86.1216 +         {
 86.1217 +            if (png_ptr->prev_row == NULL)
 86.1218 +            {
 86.1219 +               png_warning(png_ptr, "Can't add Average filter after starting");
 86.1220 +               png_ptr->do_filter &= ~PNG_FILTER_AVG;
 86.1221 +            }
 86.1222 +            else
 86.1223 +            {
 86.1224 +               png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
 86.1225 +                  (png_ptr->rowbytes + 1));
 86.1226 +               png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
 86.1227 +            }
 86.1228 +         }
 86.1229 +
 86.1230 +         if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
 86.1231 +             png_ptr->paeth_row == NULL)
 86.1232 +         {
 86.1233 +            if (png_ptr->prev_row == NULL)
 86.1234 +            {
 86.1235 +               png_warning(png_ptr, "Can't add Paeth filter after starting");
 86.1236 +               png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
 86.1237 +            }
 86.1238 +            else
 86.1239 +            {
 86.1240 +               png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
 86.1241 +                  (png_ptr->rowbytes + 1));
 86.1242 +               png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
 86.1243 +            }
 86.1244 +         }
 86.1245 +
 86.1246 +         if (png_ptr->do_filter == PNG_NO_FILTERS)
 86.1247 +#endif /* PNG_NO_WRITE_FILTER */
 86.1248 +            png_ptr->do_filter = PNG_FILTER_NONE;
 86.1249 +      }
 86.1250 +   }
 86.1251 +   else
 86.1252 +      png_error(png_ptr, "Unknown custom filter method");
 86.1253 +}
 86.1254 +
 86.1255 +/* This allows us to influence the way in which libpng chooses the "best"
 86.1256 + * filter for the current scanline.  While the "minimum-sum-of-absolute-
 86.1257 + * differences metric is relatively fast and effective, there is some
 86.1258 + * question as to whether it can be improved upon by trying to keep the
 86.1259 + * filtered data going to zlib more consistent, hopefully resulting in
 86.1260 + * better compression.
 86.1261 + */
 86.1262 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)      /* GRR 970116 */
 86.1263 +void PNGAPI
 86.1264 +png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
 86.1265 +   int num_weights, png_doublep filter_weights,
 86.1266 +   png_doublep filter_costs)
 86.1267 +{
 86.1268 +   int i;
 86.1269 +
 86.1270 +   png_debug(1, "in png_set_filter_heuristics\n");
 86.1271 +   if (png_ptr == NULL)
 86.1272 +      return;
 86.1273 +   if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
 86.1274 +   {
 86.1275 +      png_warning(png_ptr, "Unknown filter heuristic method");
 86.1276 +      return;
 86.1277 +   }
 86.1278 +
 86.1279 +   if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
 86.1280 +   {
 86.1281 +      heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
 86.1282 +   }
 86.1283 +
 86.1284 +   if (num_weights < 0 || filter_weights == NULL ||
 86.1285 +      heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
 86.1286 +   {
 86.1287 +      num_weights = 0;
 86.1288 +   }
 86.1289 +
 86.1290 +   png_ptr->num_prev_filters = (png_byte)num_weights;
 86.1291 +   png_ptr->heuristic_method = (png_byte)heuristic_method;
 86.1292 +
 86.1293 +   if (num_weights > 0)
 86.1294 +   {
 86.1295 +      if (png_ptr->prev_filters == NULL)
 86.1296 +      {
 86.1297 +         png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
 86.1298 +            (png_uint_32)(png_sizeof(png_byte) * num_weights));
 86.1299 +
 86.1300 +         /* To make sure that the weighting starts out fairly */
 86.1301 +         for (i = 0; i < num_weights; i++)
 86.1302 +         {
 86.1303 +            png_ptr->prev_filters[i] = 255;
 86.1304 +         }
 86.1305 +      }
 86.1306 +
 86.1307 +      if (png_ptr->filter_weights == NULL)
 86.1308 +      {
 86.1309 +         png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
 86.1310 +            (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
 86.1311 +
 86.1312 +         png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
 86.1313 +            (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
 86.1314 +         for (i = 0; i < num_weights; i++)
 86.1315 +         {
 86.1316 +            png_ptr->inv_filter_weights[i] =
 86.1317 +            png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
 86.1318 +         }
 86.1319 +      }
 86.1320 +
 86.1321 +      for (i = 0; i < num_weights; i++)
 86.1322 +      {
 86.1323 +         if (filter_weights[i] < 0.0)
 86.1324 +         {
 86.1325 +            png_ptr->inv_filter_weights[i] =
 86.1326 +            png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
 86.1327 +         }
 86.1328 +         else
 86.1329 +         {
 86.1330 +            png_ptr->inv_filter_weights[i] =
 86.1331 +               (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
 86.1332 +            png_ptr->filter_weights[i] =
 86.1333 +               (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
 86.1334 +         }
 86.1335 +      }
 86.1336 +   }
 86.1337 +
 86.1338 +   /* If, in the future, there are other filter methods, this would
 86.1339 +    * need to be based on png_ptr->filter.
 86.1340 +    */
 86.1341 +   if (png_ptr->filter_costs == NULL)
 86.1342 +   {
 86.1343 +      png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
 86.1344 +         (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
 86.1345 +
 86.1346 +      png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
 86.1347 +         (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
 86.1348 +
 86.1349 +      for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
 86.1350 +      {
 86.1351 +         png_ptr->inv_filter_costs[i] =
 86.1352 +         png_ptr->filter_costs[i] = PNG_COST_FACTOR;
 86.1353 +      }
 86.1354 +   }
 86.1355 +
 86.1356 +   /* Here is where we set the relative costs of the different filters.  We
 86.1357 +    * should take the desired compression level into account when setting
 86.1358 +    * the costs, so that Paeth, for instance, has a high relative cost at low
 86.1359 +    * compression levels, while it has a lower relative cost at higher
 86.1360 +    * compression settings.  The filter types are in order of increasing
 86.1361 +    * relative cost, so it would be possible to do this with an algorithm.
 86.1362 +    */
 86.1363 +   for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
 86.1364 +   {
 86.1365 +      if (filter_costs == NULL || filter_costs[i] < 0.0)
 86.1366 +      {
 86.1367 +         png_ptr->inv_filter_costs[i] =
 86.1368 +         png_ptr->filter_costs[i] = PNG_COST_FACTOR;
 86.1369 +      }
 86.1370 +      else if (filter_costs[i] >= 1.0)
 86.1371 +      {
 86.1372 +         png_ptr->inv_filter_costs[i] =
 86.1373 +            (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
 86.1374 +         png_ptr->filter_costs[i] =
 86.1375 +            (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
 86.1376 +      }
 86.1377 +   }
 86.1378 +}
 86.1379 +#endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
 86.1380 +
 86.1381 +void PNGAPI
 86.1382 +png_set_compression_level(png_structp png_ptr, int level)
 86.1383 +{
 86.1384 +   png_debug(1, "in png_set_compression_level\n");
 86.1385 +   if (png_ptr == NULL)
 86.1386 +      return;
 86.1387 +   png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
 86.1388 +   png_ptr->zlib_level = level;
 86.1389 +}
 86.1390 +
 86.1391 +void PNGAPI
 86.1392 +png_set_compression_mem_level(png_structp png_ptr, int mem_level)
 86.1393 +{
 86.1394 +   png_debug(1, "in png_set_compression_mem_level\n");
 86.1395 +   if (png_ptr == NULL)
 86.1396 +      return;
 86.1397 +   png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
 86.1398 +   png_ptr->zlib_mem_level = mem_level;
 86.1399 +}
 86.1400 +
 86.1401 +void PNGAPI
 86.1402 +png_set_compression_strategy(png_structp png_ptr, int strategy)
 86.1403 +{
 86.1404 +   png_debug(1, "in png_set_compression_strategy\n");
 86.1405 +   if (png_ptr == NULL)
 86.1406 +      return;
 86.1407 +   png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
 86.1408 +   png_ptr->zlib_strategy = strategy;
 86.1409 +}
 86.1410 +
 86.1411 +void PNGAPI
 86.1412 +png_set_compression_window_bits(png_structp png_ptr, int window_bits)
 86.1413 +{
 86.1414 +   if (png_ptr == NULL)
 86.1415 +      return;
 86.1416 +   if (window_bits > 15)
 86.1417 +      png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
 86.1418 +   else if (window_bits < 8)
 86.1419 +      png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
 86.1420 +#ifndef WBITS_8_OK
 86.1421 +   /* avoid libpng bug with 256-byte windows */
 86.1422 +   if (window_bits == 8)
 86.1423 +     {
 86.1424 +       png_warning(png_ptr, "Compression window is being reset to 512");
 86.1425 +       window_bits=9;
 86.1426 +     }
 86.1427 +#endif
 86.1428 +   png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
 86.1429 +   png_ptr->zlib_window_bits = window_bits;
 86.1430 +}
 86.1431 +
 86.1432 +void PNGAPI
 86.1433 +png_set_compression_method(png_structp png_ptr, int method)
 86.1434 +{
 86.1435 +   png_debug(1, "in png_set_compression_method\n");
 86.1436 +   if (png_ptr == NULL)
 86.1437 +      return;
 86.1438 +   if (method != 8)
 86.1439 +      png_warning(png_ptr, "Only compression method 8 is supported by PNG");
 86.1440 +   png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
 86.1441 +   png_ptr->zlib_method = method;
 86.1442 +}
 86.1443 +
 86.1444 +void PNGAPI
 86.1445 +png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
 86.1446 +{
 86.1447 +   if (png_ptr == NULL)
 86.1448 +      return;
 86.1449 +   png_ptr->write_row_fn = write_row_fn;
 86.1450 +}
 86.1451 +
 86.1452 +#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
 86.1453 +void PNGAPI
 86.1454 +png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
 86.1455 +   write_user_transform_fn)
 86.1456 +{
 86.1457 +   png_debug(1, "in png_set_write_user_transform_fn\n");
 86.1458 +   if (png_ptr == NULL)
 86.1459 +      return;
 86.1460 +   png_ptr->transformations |= PNG_USER_TRANSFORM;
 86.1461 +   png_ptr->write_user_transform_fn = write_user_transform_fn;
 86.1462 +}
 86.1463 +#endif
 86.1464 +
 86.1465 +
 86.1466 +#if defined(PNG_INFO_IMAGE_SUPPORTED)
 86.1467 +void PNGAPI
 86.1468 +png_write_png(png_structp png_ptr, png_infop info_ptr,
 86.1469 +              int transforms, voidp params)
 86.1470 +{
 86.1471 +   if (png_ptr == NULL || info_ptr == NULL)
 86.1472 +      return;
 86.1473 +#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
 86.1474 +   /* invert the alpha channel from opacity to transparency */
 86.1475 +   if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
 86.1476 +       png_set_invert_alpha(png_ptr);
 86.1477 +#endif
 86.1478 +
 86.1479 +   /* Write the file header information. */
 86.1480 +   png_write_info(png_ptr, info_ptr);
 86.1481 +
 86.1482 +   /* ------ these transformations don't touch the info structure ------- */
 86.1483 +
 86.1484 +#if defined(PNG_WRITE_INVERT_SUPPORTED)
 86.1485 +   /* invert monochrome pixels */
 86.1486 +   if (transforms & PNG_TRANSFORM_INVERT_MONO)
 86.1487 +       png_set_invert_mono(png_ptr);
 86.1488 +#endif
 86.1489 +
 86.1490 +#if defined(PNG_WRITE_SHIFT_SUPPORTED)
 86.1491 +   /* Shift the pixels up to a legal bit depth and fill in
 86.1492 +    * as appropriate to correctly scale the image.
 86.1493 +    */
 86.1494 +   if ((transforms & PNG_TRANSFORM_SHIFT)
 86.1495 +               && (info_ptr->valid & PNG_INFO_sBIT))
 86.1496 +       png_set_shift(png_ptr, &info_ptr->sig_bit);
 86.1497 +#endif
 86.1498 +
 86.1499 +#if defined(PNG_WRITE_PACK_SUPPORTED)
 86.1500 +   /* pack pixels into bytes */
 86.1501 +   if (transforms & PNG_TRANSFORM_PACKING)
 86.1502 +       png_set_packing(png_ptr);
 86.1503 +#endif
 86.1504 +
 86.1505 +#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
 86.1506 +   /* swap location of alpha bytes from ARGB to RGBA */
 86.1507 +   if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
 86.1508 +       png_set_swap_alpha(png_ptr);
 86.1509 +#endif
 86.1510 +
 86.1511 +#if defined(PNG_WRITE_FILLER_SUPPORTED)
 86.1512 +   /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
 86.1513 +    * RGB (4 channels -> 3 channels). The second parameter is not used.
 86.1514 +    */
 86.1515 +   if (transforms & PNG_TRANSFORM_STRIP_FILLER)
 86.1516 +       png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
 86.1517 +#endif
 86.1518 +
 86.1519 +#if defined(PNG_WRITE_BGR_SUPPORTED)
 86.1520 +   /* flip BGR pixels to RGB */
 86.1521 +   if (transforms & PNG_TRANSFORM_BGR)
 86.1522 +       png_set_bgr(png_ptr);
 86.1523 +#endif
 86.1524 +
 86.1525 +#if defined(PNG_WRITE_SWAP_SUPPORTED)
 86.1526 +   /* swap bytes of 16-bit files to most significant byte first */
 86.1527 +   if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
 86.1528 +       png_set_swap(png_ptr);
 86.1529 +#endif
 86.1530 +
 86.1531 +#if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
 86.1532 +   /* swap bits of 1, 2, 4 bit packed pixel formats */
 86.1533 +   if (transforms & PNG_TRANSFORM_PACKSWAP)
 86.1534 +       png_set_packswap(png_ptr);
 86.1535 +#endif
 86.1536 +
 86.1537 +   /* ----------------------- end of transformations ------------------- */
 86.1538 +
 86.1539 +   /* write the bits */
 86.1540 +   if (info_ptr->valid & PNG_INFO_IDAT)
 86.1541 +       png_write_image(png_ptr, info_ptr->row_pointers);
 86.1542 +
 86.1543 +   /* It is REQUIRED to call this to finish writing the rest of the file */
 86.1544 +   png_write_end(png_ptr, info_ptr);
 86.1545 +
 86.1546 +   transforms = transforms; /* quiet compiler warnings */
 86.1547 +   params = params;
 86.1548 +}
 86.1549 +#endif
 86.1550 +#endif /* PNG_WRITE_SUPPORTED */
    87.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    87.2 +++ b/libs/libpng/pngwtran.c	Thu Sep 08 06:28:38 2011 +0300
    87.3 @@ -0,0 +1,572 @@
    87.4 +
    87.5 +/* pngwtran.c - transforms the data in a row for PNG writers
    87.6 + *
    87.7 + * Last changed in libpng 1.2.9 April 14, 2006
    87.8 + * For conditions of distribution and use, see copyright notice in png.h
    87.9 + * Copyright (c) 1998-2006 Glenn Randers-Pehrson
   87.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   87.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   87.12 + */
   87.13 +
   87.14 +#define PNG_INTERNAL
   87.15 +#include "png.h"
   87.16 +#ifdef PNG_WRITE_SUPPORTED
   87.17 +
   87.18 +/* Transform the data according to the user's wishes.  The order of
   87.19 + * transformations is significant.
   87.20 + */
   87.21 +void /* PRIVATE */
   87.22 +png_do_write_transformations(png_structp png_ptr)
   87.23 +{
   87.24 +   png_debug(1, "in png_do_write_transformations\n");
   87.25 +
   87.26 +   if (png_ptr == NULL)
   87.27 +      return;
   87.28 +
   87.29 +#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
   87.30 +   if (png_ptr->transformations & PNG_USER_TRANSFORM)
   87.31 +      if (png_ptr->write_user_transform_fn != NULL)
   87.32 +        (*(png_ptr->write_user_transform_fn)) /* user write transform function */
   87.33 +          (png_ptr,                    /* png_ptr */
   87.34 +           &(png_ptr->row_info),       /* row_info:     */
   87.35 +             /*  png_uint_32 width;          width of row */
   87.36 +             /*  png_uint_32 rowbytes;       number of bytes in row */
   87.37 +             /*  png_byte color_type;        color type of pixels */
   87.38 +             /*  png_byte bit_depth;         bit depth of samples */
   87.39 +             /*  png_byte channels;          number of channels (1-4) */
   87.40 +             /*  png_byte pixel_depth;       bits per pixel (depth*channels) */
   87.41 +           png_ptr->row_buf + 1);      /* start of pixel data for row */
   87.42 +#endif
   87.43 +#if defined(PNG_WRITE_FILLER_SUPPORTED)
   87.44 +   if (png_ptr->transformations & PNG_FILLER)
   87.45 +      png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
   87.46 +         png_ptr->flags);
   87.47 +#endif
   87.48 +#if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
   87.49 +   if (png_ptr->transformations & PNG_PACKSWAP)
   87.50 +      png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
   87.51 +#endif
   87.52 +#if defined(PNG_WRITE_PACK_SUPPORTED)
   87.53 +   if (png_ptr->transformations & PNG_PACK)
   87.54 +      png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
   87.55 +         (png_uint_32)png_ptr->bit_depth);
   87.56 +#endif
   87.57 +#if defined(PNG_WRITE_SWAP_SUPPORTED)
   87.58 +   if (png_ptr->transformations & PNG_SWAP_BYTES)
   87.59 +      png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
   87.60 +#endif
   87.61 +#if defined(PNG_WRITE_SHIFT_SUPPORTED)
   87.62 +   if (png_ptr->transformations & PNG_SHIFT)
   87.63 +      png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
   87.64 +         &(png_ptr->shift));
   87.65 +#endif
   87.66 +#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
   87.67 +   if (png_ptr->transformations & PNG_SWAP_ALPHA)
   87.68 +      png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
   87.69 +#endif
   87.70 +#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
   87.71 +   if (png_ptr->transformations & PNG_INVERT_ALPHA)
   87.72 +      png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
   87.73 +#endif
   87.74 +#if defined(PNG_WRITE_BGR_SUPPORTED)
   87.75 +   if (png_ptr->transformations & PNG_BGR)
   87.76 +      png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
   87.77 +#endif
   87.78 +#if defined(PNG_WRITE_INVERT_SUPPORTED)
   87.79 +   if (png_ptr->transformations & PNG_INVERT_MONO)
   87.80 +      png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
   87.81 +#endif
   87.82 +}
   87.83 +
   87.84 +#if defined(PNG_WRITE_PACK_SUPPORTED)
   87.85 +/* Pack pixels into bytes.  Pass the true bit depth in bit_depth.  The
   87.86 + * row_info bit depth should be 8 (one pixel per byte).  The channels
   87.87 + * should be 1 (this only happens on grayscale and paletted images).
   87.88 + */
   87.89 +void /* PRIVATE */
   87.90 +png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
   87.91 +{
   87.92 +   png_debug(1, "in png_do_pack\n");
   87.93 +   if (row_info->bit_depth == 8 &&
   87.94 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
   87.95 +       row != NULL && row_info != NULL &&
   87.96 +#endif
   87.97 +      row_info->channels == 1)
   87.98 +   {
   87.99 +      switch ((int)bit_depth)
  87.100 +      {
  87.101 +         case 1:
  87.102 +         {
  87.103 +            png_bytep sp, dp;
  87.104 +            int mask, v;
  87.105 +            png_uint_32 i;
  87.106 +            png_uint_32 row_width = row_info->width;
  87.107 +
  87.108 +            sp = row;
  87.109 +            dp = row;
  87.110 +            mask = 0x80;
  87.111 +            v = 0;
  87.112 +
  87.113 +            for (i = 0; i < row_width; i++)
  87.114 +            {
  87.115 +               if (*sp != 0)
  87.116 +                  v |= mask;
  87.117 +               sp++;
  87.118 +               if (mask > 1)
  87.119 +                  mask >>= 1;
  87.120 +               else
  87.121 +               {
  87.122 +                  mask = 0x80;
  87.123 +                  *dp = (png_byte)v;
  87.124 +                  dp++;
  87.125 +                  v = 0;
  87.126 +               }
  87.127 +            }
  87.128 +            if (mask != 0x80)
  87.129 +               *dp = (png_byte)v;
  87.130 +            break;
  87.131 +         }
  87.132 +         case 2:
  87.133 +         {
  87.134 +            png_bytep sp, dp;
  87.135 +            int shift, v;
  87.136 +            png_uint_32 i;
  87.137 +            png_uint_32 row_width = row_info->width;
  87.138 +
  87.139 +            sp = row;
  87.140 +            dp = row;
  87.141 +            shift = 6;
  87.142 +            v = 0;
  87.143 +            for (i = 0; i < row_width; i++)
  87.144 +            {
  87.145 +               png_byte value;
  87.146 +
  87.147 +               value = (png_byte)(*sp & 0x03);
  87.148 +               v |= (value << shift);
  87.149 +               if (shift == 0)
  87.150 +               {
  87.151 +                  shift = 6;
  87.152 +                  *dp = (png_byte)v;
  87.153 +                  dp++;
  87.154 +                  v = 0;
  87.155 +               }
  87.156 +               else
  87.157 +                  shift -= 2;
  87.158 +               sp++;
  87.159 +            }
  87.160 +            if (shift != 6)
  87.161 +               *dp = (png_byte)v;
  87.162 +            break;
  87.163 +         }
  87.164 +         case 4:
  87.165 +         {
  87.166 +            png_bytep sp, dp;
  87.167 +            int shift, v;
  87.168 +            png_uint_32 i;
  87.169 +            png_uint_32 row_width = row_info->width;
  87.170 +
  87.171 +            sp = row;
  87.172 +            dp = row;
  87.173 +            shift = 4;
  87.174 +            v = 0;
  87.175 +            for (i = 0; i < row_width; i++)
  87.176 +            {
  87.177 +               png_byte value;
  87.178 +
  87.179 +               value = (png_byte)(*sp & 0x0f);
  87.180 +               v |= (value << shift);
  87.181 +
  87.182 +               if (shift == 0)
  87.183 +               {
  87.184 +                  shift = 4;
  87.185 +                  *dp = (png_byte)v;
  87.186 +                  dp++;
  87.187 +                  v = 0;
  87.188 +               }
  87.189 +               else
  87.190 +                  shift -= 4;
  87.191 +
  87.192 +               sp++;
  87.193 +            }
  87.194 +            if (shift != 4)
  87.195 +               *dp = (png_byte)v;
  87.196 +            break;
  87.197 +         }
  87.198 +      }
  87.199 +      row_info->bit_depth = (png_byte)bit_depth;
  87.200 +      row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  87.201 +      row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  87.202 +         row_info->width);
  87.203 +   }
  87.204 +}
  87.205 +#endif
  87.206 +
  87.207 +#if defined(PNG_WRITE_SHIFT_SUPPORTED)
  87.208 +/* Shift pixel values to take advantage of whole range.  Pass the
  87.209 + * true number of bits in bit_depth.  The row should be packed
  87.210 + * according to row_info->bit_depth.  Thus, if you had a row of
  87.211 + * bit depth 4, but the pixels only had values from 0 to 7, you
  87.212 + * would pass 3 as bit_depth, and this routine would translate the
  87.213 + * data to 0 to 15.
  87.214 + */
  87.215 +void /* PRIVATE */
  87.216 +png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  87.217 +{
  87.218 +   png_debug(1, "in png_do_shift\n");
  87.219 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
  87.220 +   if (row != NULL && row_info != NULL &&
  87.221 +#else
  87.222 +   if (
  87.223 +#endif
  87.224 +      row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  87.225 +   {
  87.226 +      int shift_start[4], shift_dec[4];
  87.227 +      int channels = 0;
  87.228 +
  87.229 +      if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  87.230 +      {
  87.231 +         shift_start[channels] = row_info->bit_depth - bit_depth->red;
  87.232 +         shift_dec[channels] = bit_depth->red;
  87.233 +         channels++;
  87.234 +         shift_start[channels] = row_info->bit_depth - bit_depth->green;
  87.235 +         shift_dec[channels] = bit_depth->green;
  87.236 +         channels++;
  87.237 +         shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  87.238 +         shift_dec[channels] = bit_depth->blue;
  87.239 +         channels++;
  87.240 +      }
  87.241 +      else
  87.242 +      {
  87.243 +         shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  87.244 +         shift_dec[channels] = bit_depth->gray;
  87.245 +         channels++;
  87.246 +      }
  87.247 +      if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  87.248 +      {
  87.249 +         shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  87.250 +         shift_dec[channels] = bit_depth->alpha;
  87.251 +         channels++;
  87.252 +      }
  87.253 +
  87.254 +      /* with low row depths, could only be grayscale, so one channel */
  87.255 +      if (row_info->bit_depth < 8)
  87.256 +      {
  87.257 +         png_bytep bp = row;
  87.258 +         png_uint_32 i;
  87.259 +         png_byte mask;
  87.260 +         png_uint_32 row_bytes = row_info->rowbytes;
  87.261 +
  87.262 +         if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  87.263 +            mask = 0x55;
  87.264 +         else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  87.265 +            mask = 0x11;
  87.266 +         else
  87.267 +            mask = 0xff;
  87.268 +
  87.269 +         for (i = 0; i < row_bytes; i++, bp++)
  87.270 +         {
  87.271 +            png_uint_16 v;
  87.272 +            int j;
  87.273 +
  87.274 +            v = *bp;
  87.275 +            *bp = 0;
  87.276 +            for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  87.277 +            {
  87.278 +               if (j > 0)
  87.279 +                  *bp |= (png_byte)((v << j) & 0xff);
  87.280 +               else
  87.281 +                  *bp |= (png_byte)((v >> (-j)) & mask);
  87.282 +            }
  87.283 +         }
  87.284 +      }
  87.285 +      else if (row_info->bit_depth == 8)
  87.286 +      {
  87.287 +         png_bytep bp = row;
  87.288 +         png_uint_32 i;
  87.289 +         png_uint_32 istop = channels * row_info->width;
  87.290 +
  87.291 +         for (i = 0; i < istop; i++, bp++)
  87.292 +         {
  87.293 +
  87.294 +            png_uint_16 v;
  87.295 +            int j;
  87.296 +            int c = (int)(i%channels);
  87.297 +
  87.298 +            v = *bp;
  87.299 +            *bp = 0;
  87.300 +            for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  87.301 +            {
  87.302 +               if (j > 0)
  87.303 +                  *bp |= (png_byte)((v << j) & 0xff);
  87.304 +               else
  87.305 +                  *bp |= (png_byte)((v >> (-j)) & 0xff);
  87.306 +            }
  87.307 +         }
  87.308 +      }
  87.309 +      else
  87.310 +      {
  87.311 +         png_bytep bp;
  87.312 +         png_uint_32 i;
  87.313 +         png_uint_32 istop = channels * row_info->width;
  87.314 +
  87.315 +         for (bp = row, i = 0; i < istop; i++)
  87.316 +         {
  87.317 +            int c = (int)(i%channels);
  87.318 +            png_uint_16 value, v;
  87.319 +            int j;
  87.320 +
  87.321 +            v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  87.322 +            value = 0;
  87.323 +            for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  87.324 +            {
  87.325 +               if (j > 0)
  87.326 +                  value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  87.327 +               else
  87.328 +                  value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  87.329 +            }
  87.330 +            *bp++ = (png_byte)(value >> 8);
  87.331 +            *bp++ = (png_byte)(value & 0xff);
  87.332 +         }
  87.333 +      }
  87.334 +   }
  87.335 +}
  87.336 +#endif
  87.337 +
  87.338 +#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  87.339 +void /* PRIVATE */
  87.340 +png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  87.341 +{
  87.342 +   png_debug(1, "in png_do_write_swap_alpha\n");
  87.343 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
  87.344 +   if (row != NULL && row_info != NULL)
  87.345 +#endif
  87.346 +   {
  87.347 +      if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  87.348 +      {
  87.349 +         /* This converts from ARGB to RGBA */
  87.350 +         if (row_info->bit_depth == 8)
  87.351 +         {
  87.352 +            png_bytep sp, dp;
  87.353 +            png_uint_32 i;
  87.354 +            png_uint_32 row_width = row_info->width;
  87.355 +            for (i = 0, sp = dp = row; i < row_width; i++)
  87.356 +            {
  87.357 +               png_byte save = *(sp++);
  87.358 +               *(dp++) = *(sp++);
  87.359 +               *(dp++) = *(sp++);
  87.360 +               *(dp++) = *(sp++);
  87.361 +               *(dp++) = save;
  87.362 +            }
  87.363 +         }
  87.364 +         /* This converts from AARRGGBB to RRGGBBAA */
  87.365 +         else
  87.366 +         {
  87.367 +            png_bytep sp, dp;
  87.368 +            png_uint_32 i;
  87.369 +            png_uint_32 row_width = row_info->width;
  87.370 +
  87.371 +            for (i = 0, sp = dp = row; i < row_width; i++)
  87.372 +            {
  87.373 +               png_byte save[2];
  87.374 +               save[0] = *(sp++);
  87.375 +               save[1] = *(sp++);
  87.376 +               *(dp++) = *(sp++);
  87.377 +               *(dp++) = *(sp++);
  87.378 +               *(dp++) = *(sp++);
  87.379 +               *(dp++) = *(sp++);
  87.380 +               *(dp++) = *(sp++);
  87.381 +               *(dp++) = *(sp++);
  87.382 +               *(dp++) = save[0];
  87.383 +               *(dp++) = save[1];
  87.384 +            }
  87.385 +         }
  87.386 +      }
  87.387 +      else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  87.388 +      {
  87.389 +         /* This converts from AG to GA */
  87.390 +         if (row_info->bit_depth == 8)
  87.391 +         {
  87.392 +            png_bytep sp, dp;
  87.393 +            png_uint_32 i;
  87.394 +            png_uint_32 row_width = row_info->width;
  87.395 +
  87.396 +            for (i = 0, sp = dp = row; i < row_width; i++)
  87.397 +            {
  87.398 +               png_byte save = *(sp++);
  87.399 +               *(dp++) = *(sp++);
  87.400 +               *(dp++) = save;
  87.401 +            }
  87.402 +         }
  87.403 +         /* This converts from AAGG to GGAA */
  87.404 +         else
  87.405 +         {
  87.406 +            png_bytep sp, dp;
  87.407 +            png_uint_32 i;
  87.408 +            png_uint_32 row_width = row_info->width;
  87.409 +
  87.410 +            for (i = 0, sp = dp = row; i < row_width; i++)
  87.411 +            {
  87.412 +               png_byte save[2];
  87.413 +               save[0] = *(sp++);
  87.414 +               save[1] = *(sp++);
  87.415 +               *(dp++) = *(sp++);
  87.416 +               *(dp++) = *(sp++);
  87.417 +               *(dp++) = save[0];
  87.418 +               *(dp++) = save[1];
  87.419 +            }
  87.420 +         }
  87.421 +      }
  87.422 +   }
  87.423 +}
  87.424 +#endif
  87.425 +
  87.426 +#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  87.427 +void /* PRIVATE */
  87.428 +png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  87.429 +{
  87.430 +   png_debug(1, "in png_do_write_invert_alpha\n");
  87.431 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
  87.432 +   if (row != NULL && row_info != NULL)
  87.433 +#endif
  87.434 +   {
  87.435 +      if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  87.436 +      {
  87.437 +         /* This inverts the alpha channel in RGBA */
  87.438 +         if (row_info->bit_depth == 8)
  87.439 +         {
  87.440 +            png_bytep sp, dp;
  87.441 +            png_uint_32 i;
  87.442 +            png_uint_32 row_width = row_info->width;
  87.443 +            for (i = 0, sp = dp = row; i < row_width; i++)
  87.444 +            {
  87.445 +               /* does nothing
  87.446 +               *(dp++) = *(sp++);
  87.447 +               *(dp++) = *(sp++);
  87.448 +               *(dp++) = *(sp++);
  87.449 +               */
  87.450 +               sp+=3; dp = sp;
  87.451 +               *(dp++) = (png_byte)(255 - *(sp++));
  87.452 +            }
  87.453 +         }
  87.454 +         /* This inverts the alpha channel in RRGGBBAA */
  87.455 +         else
  87.456 +         {
  87.457 +            png_bytep sp, dp;
  87.458 +            png_uint_32 i;
  87.459 +            png_uint_32 row_width = row_info->width;
  87.460 +
  87.461 +            for (i = 0, sp = dp = row; i < row_width; i++)
  87.462 +            {
  87.463 +               /* does nothing
  87.464 +               *(dp++) = *(sp++);
  87.465 +               *(dp++) = *(sp++);
  87.466 +               *(dp++) = *(sp++);
  87.467 +               *(dp++) = *(sp++);
  87.468 +               *(dp++) = *(sp++);
  87.469 +               *(dp++) = *(sp++);
  87.470 +               */
  87.471 +               sp+=6; dp = sp;
  87.472 +               *(dp++) = (png_byte)(255 - *(sp++));
  87.473 +               *(dp++) = (png_byte)(255 - *(sp++));
  87.474 +            }
  87.475 +         }
  87.476 +      }
  87.477 +      else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  87.478 +      {
  87.479 +         /* This inverts the alpha channel in GA */
  87.480 +         if (row_info->bit_depth == 8)
  87.481 +         {
  87.482 +            png_bytep sp, dp;
  87.483 +            png_uint_32 i;
  87.484 +            png_uint_32 row_width = row_info->width;
  87.485 +
  87.486 +            for (i = 0, sp = dp = row; i < row_width; i++)
  87.487 +            {
  87.488 +               *(dp++) = *(sp++);
  87.489 +               *(dp++) = (png_byte)(255 - *(sp++));
  87.490 +            }
  87.491 +         }
  87.492 +         /* This inverts the alpha channel in GGAA */
  87.493 +         else
  87.494 +         {
  87.495 +            png_bytep sp, dp;
  87.496 +            png_uint_32 i;
  87.497 +            png_uint_32 row_width = row_info->width;
  87.498 +
  87.499 +            for (i = 0, sp = dp = row; i < row_width; i++)
  87.500 +            {
  87.501 +               /* does nothing
  87.502 +               *(dp++) = *(sp++);
  87.503 +               *(dp++) = *(sp++);
  87.504 +               */
  87.505 +               sp+=2; dp = sp;
  87.506 +               *(dp++) = (png_byte)(255 - *(sp++));
  87.507 +               *(dp++) = (png_byte)(255 - *(sp++));
  87.508 +            }
  87.509 +         }
  87.510 +      }
  87.511 +   }
  87.512 +}
  87.513 +#endif
  87.514 +
  87.515 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
  87.516 +/* undoes intrapixel differencing  */
  87.517 +void /* PRIVATE */
  87.518 +png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  87.519 +{
  87.520 +   png_debug(1, "in png_do_write_intrapixel\n");
  87.521 +   if (
  87.522 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
  87.523 +       row != NULL && row_info != NULL &&
  87.524 +#endif
  87.525 +       (row_info->color_type & PNG_COLOR_MASK_COLOR))
  87.526 +   {
  87.527 +      int bytes_per_pixel;
  87.528 +      png_uint_32 row_width = row_info->width;
  87.529 +      if (row_info->bit_depth == 8)
  87.530 +      {
  87.531 +         png_bytep rp;
  87.532 +         png_uint_32 i;
  87.533 +
  87.534 +         if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  87.535 +            bytes_per_pixel = 3;
  87.536 +         else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  87.537 +            bytes_per_pixel = 4;
  87.538 +         else
  87.539 +            return;
  87.540 +
  87.541 +         for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  87.542 +         {
  87.543 +            *(rp)   = (png_byte)((*rp     - *(rp+1))&0xff);
  87.544 +            *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  87.545 +         }
  87.546 +      }
  87.547 +      else if (row_info->bit_depth == 16)
  87.548 +      {
  87.549 +         png_bytep rp;
  87.550 +         png_uint_32 i;
  87.551 +
  87.552 +         if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  87.553 +            bytes_per_pixel = 6;
  87.554 +         else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  87.555 +            bytes_per_pixel = 8;
  87.556 +         else
  87.557 +            return;
  87.558 +
  87.559 +         for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  87.560 +         {
  87.561 +            png_uint_32 s0   = (*(rp  ) << 8) | *(rp+1);
  87.562 +            png_uint_32 s1   = (*(rp+2) << 8) | *(rp+3);
  87.563 +            png_uint_32 s2   = (*(rp+4) << 8) | *(rp+5);
  87.564 +            png_uint_32 red  = (png_uint_32)((s0 - s1) & 0xffffL);
  87.565 +            png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL);
  87.566 +            *(rp  ) = (png_byte)((red >> 8) & 0xff);
  87.567 +            *(rp+1) = (png_byte)(red & 0xff);
  87.568 +            *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  87.569 +            *(rp+5) = (png_byte)(blue & 0xff);
  87.570 +         }
  87.571 +      }
  87.572 +   }
  87.573 +}
  87.574 +#endif /* PNG_MNG_FEATURES_SUPPORTED */
  87.575 +#endif /* PNG_WRITE_SUPPORTED */
    88.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    88.2 +++ b/libs/libpng/pngwutil.c	Thu Sep 08 06:28:38 2011 +0300
    88.3 @@ -0,0 +1,2827 @@
    88.4 +
    88.5 +/* pngwutil.c - utilities to write a PNG file
    88.6 + *
    88.7 + * Last changed in libpng 1.2.30 [August 15, 2008]
    88.8 + * For conditions of distribution and use, see copyright notice in png.h
    88.9 + * Copyright (c) 1998-2008 Glenn Randers-Pehrson
   88.10 + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
   88.11 + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
   88.12 + */
   88.13 +
   88.14 +#define PNG_INTERNAL
   88.15 +#include "png.h"
   88.16 +#ifdef PNG_WRITE_SUPPORTED
   88.17 +
   88.18 +/* Place a 32-bit number into a buffer in PNG byte order.  We work
   88.19 + * with unsigned numbers for convenience, although one supported
   88.20 + * ancillary chunk uses signed (two's complement) numbers.
   88.21 + */
   88.22 +void PNGAPI
   88.23 +png_save_uint_32(png_bytep buf, png_uint_32 i)
   88.24 +{
   88.25 +   buf[0] = (png_byte)((i >> 24) & 0xff);
   88.26 +   buf[1] = (png_byte)((i >> 16) & 0xff);
   88.27 +   buf[2] = (png_byte)((i >> 8) & 0xff);
   88.28 +   buf[3] = (png_byte)(i & 0xff);
   88.29 +}
   88.30 +
   88.31 +/* The png_save_int_32 function assumes integers are stored in two's
   88.32 + * complement format.  If this isn't the case, then this routine needs to
   88.33 + * be modified to write data in two's complement format.
   88.34 + */
   88.35 +void PNGAPI
   88.36 +png_save_int_32(png_bytep buf, png_int_32 i)
   88.37 +{
   88.38 +   buf[0] = (png_byte)((i >> 24) & 0xff);
   88.39 +   buf[1] = (png_byte)((i >> 16) & 0xff);
   88.40 +   buf[2] = (png_byte)((i >> 8) & 0xff);
   88.41 +   buf[3] = (png_byte)(i & 0xff);
   88.42 +}
   88.43 +
   88.44 +/* Place a 16-bit number into a buffer in PNG byte order.
   88.45 + * The parameter is declared unsigned int, not png_uint_16,
   88.46 + * just to avoid potential problems on pre-ANSI C compilers.
   88.47 + */
   88.48 +void PNGAPI
   88.49 +png_save_uint_16(png_bytep buf, unsigned int i)
   88.50 +{
   88.51 +   buf[0] = (png_byte)((i >> 8) & 0xff);
   88.52 +   buf[1] = (png_byte)(i & 0xff);
   88.53 +}
   88.54 +
   88.55 +/* Simple function to write the signature.  If we have already written
   88.56 + * the magic bytes of the signature, or more likely, the PNG stream is
   88.57 + * being embedded into another stream and doesn't need its own signature,
   88.58 + * we should call png_set_sig_bytes() to tell libpng how many of the
   88.59 + * bytes have already been written.
   88.60 + */
   88.61 +void /* PRIVATE */
   88.62 +png_write_sig(png_structp png_ptr)
   88.63 +{
   88.64 +   png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
   88.65 +
   88.66 +   /* write the rest of the 8 byte signature */
   88.67 +   png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
   88.68 +      (png_size_t)(8 - png_ptr->sig_bytes));
   88.69 +   if (png_ptr->sig_bytes < 3)
   88.70 +      png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
   88.71 +}
   88.72 +
   88.73 +/* Write a PNG chunk all at once.  The type is an array of ASCII characters
   88.74 + * representing the chunk name.  The array must be at least 4 bytes in
   88.75 + * length, and does not need to be null terminated.  To be safe, pass the
   88.76 + * pre-defined chunk names here, and if you need a new one, define it
   88.77 + * where the others are defined.  The length is the length of the data.
   88.78 + * All the data must be present.  If that is not possible, use the
   88.79 + * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
   88.80 + * functions instead.
   88.81 + */
   88.82 +void PNGAPI
   88.83 +png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
   88.84 +   png_bytep data, png_size_t length)
   88.85 +{
   88.86 +   if (png_ptr == NULL) return;
   88.87 +   png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
   88.88 +   png_write_chunk_data(png_ptr, data, (png_size_t)length);
   88.89 +   png_write_chunk_end(png_ptr);
   88.90 +}
   88.91 +
   88.92 +/* Write the start of a PNG chunk.  The type is the chunk type.
   88.93 + * The total_length is the sum of the lengths of all the data you will be
   88.94 + * passing in png_write_chunk_data().
   88.95 + */
   88.96 +void PNGAPI
   88.97 +png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
   88.98 +   png_uint_32 length)
   88.99 +{
  88.100 +   png_byte buf[8];
  88.101 +
  88.102 +   png_debug2(0, "Writing %s chunk, length = %lu\n", chunk_name,
  88.103 +      (unsigned long)length);
  88.104 +   if (png_ptr == NULL) return;
  88.105 +
  88.106 +   /* write the length and the chunk name */
  88.107 +   png_save_uint_32(buf, length);
  88.108 +   png_memcpy(buf + 4, chunk_name, 4);
  88.109 +   png_write_data(png_ptr, buf, (png_size_t)8);
  88.110 +   /* put the chunk name into png_ptr->chunk_name */
  88.111 +   png_memcpy(png_ptr->chunk_name, chunk_name, 4);
  88.112 +   /* reset the crc and run it over the chunk name */
  88.113 +   png_reset_crc(png_ptr);
  88.114 +   png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  88.115 +}
  88.116 +
  88.117 +/* Write the data of a PNG chunk started with png_write_chunk_start().
  88.118 + * Note that multiple calls to this function are allowed, and that the
  88.119 + * sum of the lengths from these calls *must* add up to the total_length
  88.120 + * given to png_write_chunk_start().
  88.121 + */
  88.122 +void PNGAPI
  88.123 +png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  88.124 +{
  88.125 +   /* write the data, and run the CRC over it */
  88.126 +   if (png_ptr == NULL) return;
  88.127 +   if (data != NULL && length > 0)
  88.128 +   {
  88.129 +      png_write_data(png_ptr, data, length);
  88.130 +      /* update the CRC after writing the data,
  88.131 +       * in case that the user I/O routine alters it.
  88.132 +       */
  88.133 +      png_calculate_crc(png_ptr, data, length);
  88.134 +   }
  88.135 +}
  88.136 +
  88.137 +/* Finish a chunk started with png_write_chunk_start(). */
  88.138 +void PNGAPI
  88.139 +png_write_chunk_end(png_structp png_ptr)
  88.140 +{
  88.141 +   png_byte buf[4];
  88.142 +
  88.143 +   if (png_ptr == NULL) return;
  88.144 +
  88.145 +   /* write the crc in a single operation */
  88.146 +   png_save_uint_32(buf, png_ptr->crc);
  88.147 +
  88.148 +   png_write_data(png_ptr, buf, (png_size_t)4);
  88.149 +}
  88.150 +
  88.151 +#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  88.152 +/*
  88.153 + * This pair of functions encapsulates the operation of (a) compressing a
  88.154 + * text string, and (b) issuing it later as a series of chunk data writes.
  88.155 + * The compression_state structure is shared context for these functions
  88.156 + * set up by the caller in order to make the whole mess thread-safe.
  88.157 + */
  88.158 +
  88.159 +typedef struct
  88.160 +{
  88.161 +    char *input;   /* the uncompressed input data */
  88.162 +    int input_len;   /* its length */
  88.163 +    int num_output_ptr; /* number of output pointers used */
  88.164 +    int max_output_ptr; /* size of output_ptr */
  88.165 +    png_charpp output_ptr; /* array of pointers to output */
  88.166 +} compression_state;
  88.167 +
  88.168 +/* compress given text into storage in the png_ptr structure */
  88.169 +static int /* PRIVATE */
  88.170 +png_text_compress(png_structp png_ptr,
  88.171 +        png_charp text, png_size_t text_len, int compression,
  88.172 +        compression_state *comp)
  88.173 +{
  88.174 +   int ret;
  88.175 +
  88.176 +   comp->num_output_ptr = 0;
  88.177 +   comp->max_output_ptr = 0;
  88.178 +   comp->output_ptr = NULL;
  88.179 +   comp->input = NULL;
  88.180 +   comp->input_len = 0;
  88.181 +
  88.182 +   /* we may just want to pass the text right through */
  88.183 +   if (compression == PNG_TEXT_COMPRESSION_NONE)
  88.184 +   {
  88.185 +       comp->input = text;
  88.186 +       comp->input_len = text_len;
  88.187 +       return((int)text_len);
  88.188 +   }
  88.189 +
  88.190 +   if (compression >= PNG_TEXT_COMPRESSION_LAST)
  88.191 +   {
  88.192 +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  88.193 +      char msg[50];
  88.194 +      png_snprintf(msg, 50, "Unknown compression type %d", compression);
  88.195 +      png_warning(png_ptr, msg);
  88.196 +#else
  88.197 +      png_warning(png_ptr, "Unknown compression type");
  88.198 +#endif
  88.199 +   }
  88.200 +
  88.201 +   /* We can't write the chunk until we find out how much data we have,
  88.202 +    * which means we need to run the compressor first and save the
  88.203 +    * output.  This shouldn't be a problem, as the vast majority of
  88.204 +    * comments should be reasonable, but we will set up an array of
  88.205 +    * malloc'd pointers to be sure.
  88.206 +    *
  88.207 +    * If we knew the application was well behaved, we could simplify this
  88.208 +    * greatly by assuming we can always malloc an output buffer large
  88.209 +    * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  88.210 +    * and malloc this directly.  The only time this would be a bad idea is
  88.211 +    * if we can't malloc more than 64K and we have 64K of random input
  88.212 +    * data, or if the input string is incredibly large (although this
  88.213 +    * wouldn't cause a failure, just a slowdown due to swapping).
  88.214 +    */
  88.215 +
  88.216 +   /* set up the compression buffers */
  88.217 +   png_ptr->zstream.avail_in = (uInt)text_len;
  88.218 +   png_ptr->zstream.next_in = (Bytef *)text;
  88.219 +   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  88.220 +   png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  88.221 +
  88.222 +   /* this is the same compression loop as in png_write_row() */
  88.223 +   do
  88.224 +   {
  88.225 +      /* compress the data */
  88.226 +      ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  88.227 +      if (ret != Z_OK)
  88.228 +      {
  88.229 +         /* error */
  88.230 +         if (png_ptr->zstream.msg != NULL)
  88.231 +            png_error(png_ptr, png_ptr->zstream.msg);
  88.232 +         else
  88.233 +            png_error(png_ptr, "zlib error");
  88.234 +      }
  88.235 +      /* check to see if we need more room */
  88.236 +      if (!(png_ptr->zstream.avail_out))
  88.237 +      {
  88.238 +         /* make sure the output array has room */
  88.239 +         if (comp->num_output_ptr >= comp->max_output_ptr)
  88.240 +         {
  88.241 +            int old_max;
  88.242 +
  88.243 +            old_max = comp->max_output_ptr;
  88.244 +            comp->max_output_ptr = comp->num_output_ptr + 4;
  88.245 +            if (comp->output_ptr != NULL)
  88.246 +            {
  88.247 +               png_charpp old_ptr;
  88.248 +
  88.249 +               old_ptr = comp->output_ptr;
  88.250 +               comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  88.251 +                  (png_uint_32)
  88.252 +                  (comp->max_output_ptr * png_sizeof(png_charpp)));
  88.253 +               png_memcpy(comp->output_ptr, old_ptr, old_max
  88.254 +                  * png_sizeof(png_charp));
  88.255 +               png_free(png_ptr, old_ptr);
  88.256 +            }
  88.257 +            else
  88.258 +               comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  88.259 +                  (png_uint_32)
  88.260 +                  (comp->max_output_ptr * png_sizeof(png_charp)));
  88.261 +         }
  88.262 +
  88.263 +         /* save the data */
  88.264 +         comp->output_ptr[comp->num_output_ptr] =
  88.265 +            (png_charp)png_malloc(png_ptr,
  88.266 +            (png_uint_32)png_ptr->zbuf_size);
  88.267 +         png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  88.268 +            png_ptr->zbuf_size);
  88.269 +         comp->num_output_ptr++;
  88.270 +
  88.271 +         /* and reset the buffer */
  88.272 +         png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  88.273 +         png_ptr->zstream.next_out = png_ptr->zbuf;
  88.274 +      }
  88.275 +   /* continue until we don't have any more to compress */
  88.276 +   } while (png_ptr->zstream.avail_in);
  88.277 +
  88.278 +   /* finish the compression */
  88.279 +   do
  88.280 +   {
  88.281 +      /* tell zlib we are finished */
  88.282 +      ret = deflate(&png_ptr->zstream, Z_FINISH);
  88.283 +
  88.284 +      if (ret == Z_OK)
  88.285 +      {
  88.286 +         /* check to see if we need more room */
  88.287 +         if (!(png_ptr->zstream.avail_out))
  88.288 +         {
  88.289 +            /* check to make sure our output array has room */
  88.290 +            if (comp->num_output_ptr >= comp->max_output_ptr)
  88.291 +            {
  88.292 +               int old_max;
  88.293 +
  88.294 +               old_max = comp->max_output_ptr;
  88.295 +               comp->max_output_ptr = comp->num_output_ptr + 4;
  88.296 +               if (comp->output_ptr != NULL)
  88.297 +               {
  88.298 +                  png_charpp old_ptr;
  88.299 +
  88.300 +                  old_ptr = comp->output_ptr;
  88.301 +                  /* This could be optimized to realloc() */
  88.302 +                  comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  88.303 +                     (png_uint_32)(comp->max_output_ptr *
  88.304 +                     png_sizeof(png_charp)));
  88.305 +                  png_memcpy(comp->output_ptr, old_ptr,
  88.306 +                     old_max * png_sizeof(png_charp));
  88.307 +                  png_free(png_ptr, old_ptr);
  88.308 +               }
  88.309 +               else
  88.310 +                  comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  88.311 +                     (png_uint_32)(comp->max_output_ptr *
  88.312 +                     png_sizeof(png_charp)));
  88.313 +            }
  88.314 +
  88.315 +            /* save off the data */
  88.316 +            comp->output_ptr[comp->num_output_ptr] =
  88.317 +               (png_charp)png_malloc(png_ptr,
  88.318 +               (png_uint_32)png_ptr->zbuf_size);
  88.319 +            png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  88.320 +               png_ptr->zbuf_size);
  88.321 +            comp->num_output_ptr++;
  88.322 +
  88.323 +            /* and reset the buffer pointers */
  88.324 +            png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  88.325 +            png_ptr->zstream.next_out = png_ptr->zbuf;
  88.326 +         }
  88.327 +      }
  88.328 +      else if (ret != Z_STREAM_END)
  88.329 +      {
  88.330 +         /* we got an error */
  88.331 +         if (png_ptr->zstream.msg != NULL)
  88.332 +            png_error(png_ptr, png_ptr->zstream.msg);
  88.333 +         else
  88.334 +            png_error(png_ptr, "zlib error");
  88.335 +      }
  88.336 +   } while (ret != Z_STREAM_END);
  88.337 +
  88.338 +   /* text length is number of buffers plus last buffer */
  88.339 +   text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  88.340 +   if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  88.341 +      text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  88.342 +
  88.343 +   return((int)text_len);
  88.344 +}
  88.345 +
  88.346 +/* ship the compressed text out via chunk writes */
  88.347 +static void /* PRIVATE */
  88.348 +png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  88.349 +{
  88.350 +   int i;
  88.351 +
  88.352 +   /* handle the no-compression case */
  88.353 +   if (comp->input)
  88.354 +   {
  88.355 +       png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  88.356 +                            (png_size_t)comp->input_len);
  88.357 +       return;
  88.358 +   }
  88.359 +
  88.360 +   /* write saved output buffers, if any */
  88.361 +   for (i = 0; i < comp->num_output_ptr; i++)
  88.362 +   {
  88.363 +      png_write_chunk_data(png_ptr, (png_bytep)comp->output_ptr[i],
  88.364 +         (png_size_t)png_ptr->zbuf_size);
  88.365 +      png_free(png_ptr, comp->output_ptr[i]);
  88.366 +       comp->output_ptr[i]=NULL;
  88.367 +   }
  88.368 +   if (comp->max_output_ptr != 0)
  88.369 +      png_free(png_ptr, comp->output_ptr);
  88.370 +       comp->output_ptr=NULL;
  88.371 +   /* write anything left in zbuf */
  88.372 +   if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  88.373 +      png_write_chunk_data(png_ptr, png_ptr->zbuf,
  88.374 +         (png_size_t)(png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  88.375 +
  88.376 +   /* reset zlib for another zTXt/iTXt or image data */
  88.377 +   deflateReset(&png_ptr->zstream);
  88.378 +   png_ptr->zstream.data_type = Z_BINARY;
  88.379 +}
  88.380 +#endif
  88.381 +
  88.382 +/* Write the IHDR chunk, and update the png_struct with the necessary
  88.383 + * information.  Note that the rest of this code depends upon this
  88.384 + * information being correct.
  88.385 + */
  88.386 +void /* PRIVATE */
  88.387 +png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  88.388 +   int bit_depth, int color_type, int compression_type, int filter_type,
  88.389 +   int interlace_type)
  88.390 +{
  88.391 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.392 +   PNG_IHDR;
  88.393 +#endif
  88.394 +   int ret;
  88.395 +
  88.396 +   png_byte buf[13]; /* buffer to store the IHDR info */
  88.397 +
  88.398 +   png_debug(1, "in png_write_IHDR\n");
  88.399 +   /* Check that we have valid input data from the application info */
  88.400 +   switch (color_type)
  88.401 +   {
  88.402 +      case PNG_COLOR_TYPE_GRAY:
  88.403 +         switch (bit_depth)
  88.404 +         {
  88.405 +            case 1:
  88.406 +            case 2:
  88.407 +            case 4:
  88.408 +            case 8:
  88.409 +            case 16: png_ptr->channels = 1; break;
  88.410 +            default: png_error(png_ptr, "Invalid bit depth for grayscale image");
  88.411 +         }
  88.412 +         break;
  88.413 +      case PNG_COLOR_TYPE_RGB:
  88.414 +         if (bit_depth != 8 && bit_depth != 16)
  88.415 +            png_error(png_ptr, "Invalid bit depth for RGB image");
  88.416 +         png_ptr->channels = 3;
  88.417 +         break;
  88.418 +      case PNG_COLOR_TYPE_PALETTE:
  88.419 +         switch (bit_depth)
  88.420 +         {
  88.421 +            case 1:
  88.422 +            case 2:
  88.423 +            case 4:
  88.424 +            case 8: png_ptr->channels = 1; break;
  88.425 +            default: png_error(png_ptr, "Invalid bit depth for paletted image");
  88.426 +         }
  88.427 +         break;
  88.428 +      case PNG_COLOR_TYPE_GRAY_ALPHA:
  88.429 +         if (bit_depth != 8 && bit_depth != 16)
  88.430 +            png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  88.431 +         png_ptr->channels = 2;
  88.432 +         break;
  88.433 +      case PNG_COLOR_TYPE_RGB_ALPHA:
  88.434 +         if (bit_depth != 8 && bit_depth != 16)
  88.435 +            png_error(png_ptr, "Invalid bit depth for RGBA image");
  88.436 +         png_ptr->channels = 4;
  88.437 +         break;
  88.438 +      default:
  88.439 +         png_error(png_ptr, "Invalid image color type specified");
  88.440 +   }
  88.441 +
  88.442 +   if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  88.443 +   {
  88.444 +      png_warning(png_ptr, "Invalid compression type specified");
  88.445 +      compression_type = PNG_COMPRESSION_TYPE_BASE;
  88.446 +   }
  88.447 +
  88.448 +   /* Write filter_method 64 (intrapixel differencing) only if
  88.449 +    * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  88.450 +    * 2. Libpng did not write a PNG signature (this filter_method is only
  88.451 +    *    used in PNG datastreams that are embedded in MNG datastreams) and
  88.452 +    * 3. The application called png_permit_mng_features with a mask that
  88.453 +    *    included PNG_FLAG_MNG_FILTER_64 and
  88.454 +    * 4. The filter_method is 64 and
  88.455 +    * 5. The color_type is RGB or RGBA
  88.456 +    */
  88.457 +   if (
  88.458 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
  88.459 +      !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  88.460 +      ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  88.461 +      (color_type == PNG_COLOR_TYPE_RGB ||
  88.462 +       color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  88.463 +      (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  88.464 +#endif
  88.465 +      filter_type != PNG_FILTER_TYPE_BASE)
  88.466 +   {
  88.467 +      png_warning(png_ptr, "Invalid filter type specified");
  88.468 +      filter_type = PNG_FILTER_TYPE_BASE;
  88.469 +   }
  88.470 +
  88.471 +#ifdef PNG_WRITE_INTERLACING_SUPPORTED
  88.472 +   if (interlace_type != PNG_INTERLACE_NONE &&
  88.473 +      interlace_type != PNG_INTERLACE_ADAM7)
  88.474 +   {
  88.475 +      png_warning(png_ptr, "Invalid interlace type specified");
  88.476 +      interlace_type = PNG_INTERLACE_ADAM7;
  88.477 +   }
  88.478 +#else
  88.479 +   interlace_type=PNG_INTERLACE_NONE;
  88.480 +#endif
  88.481 +
  88.482 +   /* save off the relevent information */
  88.483 +   png_ptr->bit_depth = (png_byte)bit_depth;
  88.484 +   png_ptr->color_type = (png_byte)color_type;
  88.485 +   png_ptr->interlaced = (png_byte)interlace_type;
  88.486 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
  88.487 +   png_ptr->filter_type = (png_byte)filter_type;
  88.488 +#endif
  88.489 +   png_ptr->compression_type = (png_byte)compression_type;
  88.490 +   png_ptr->width = width;
  88.491 +   png_ptr->height = height;
  88.492 +
  88.493 +   png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  88.494 +   png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  88.495 +   /* set the usr info, so any transformations can modify it */
  88.496 +   png_ptr->usr_width = png_ptr->width;
  88.497 +   png_ptr->usr_bit_depth = png_ptr->bit_depth;
  88.498 +   png_ptr->usr_channels = png_ptr->channels;
  88.499 +
  88.500 +   /* pack the header information into the buffer */
  88.501 +   png_save_uint_32(buf, width);
  88.502 +   png_save_uint_32(buf + 4, height);
  88.503 +   buf[8] = (png_byte)bit_depth;
  88.504 +   buf[9] = (png_byte)color_type;
  88.505 +   buf[10] = (png_byte)compression_type;
  88.506 +   buf[11] = (png_byte)filter_type;
  88.507 +   buf[12] = (png_byte)interlace_type;
  88.508 +
  88.509 +   /* write the chunk */
  88.510 +   png_write_chunk(png_ptr, (png_bytep)png_IHDR, buf, (png_size_t)13);
  88.511 +
  88.512 +   /* initialize zlib with PNG info */
  88.513 +   png_ptr->zstream.zalloc = png_zalloc;
  88.514 +   png_ptr->zstream.zfree = png_zfree;
  88.515 +   png_ptr->zstream.opaque = (voidpf)png_ptr;
  88.516 +   if (!(png_ptr->do_filter))
  88.517 +   {
  88.518 +      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  88.519 +         png_ptr->bit_depth < 8)
  88.520 +         png_ptr->do_filter = PNG_FILTER_NONE;
  88.521 +      else
  88.522 +         png_ptr->do_filter = PNG_ALL_FILTERS;
  88.523 +   }
  88.524 +   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  88.525 +   {
  88.526 +      if (png_ptr->do_filter != PNG_FILTER_NONE)
  88.527 +         png_ptr->zlib_strategy = Z_FILTERED;
  88.528 +      else
  88.529 +         png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  88.530 +   }
  88.531 +   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  88.532 +      png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  88.533 +   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  88.534 +      png_ptr->zlib_mem_level = 8;
  88.535 +   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  88.536 +      png_ptr->zlib_window_bits = 15;
  88.537 +   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  88.538 +      png_ptr->zlib_method = 8;
  88.539 +   ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  88.540 +         png_ptr->zlib_method, png_ptr->zlib_window_bits,
  88.541 +         png_ptr->zlib_mem_level, png_ptr->zlib_strategy);
  88.542 +   if (ret != Z_OK)
  88.543 +   {
  88.544 +      if (ret == Z_VERSION_ERROR) png_error(png_ptr,
  88.545 +          "zlib failed to initialize compressor -- version error");
  88.546 +      if (ret == Z_STREAM_ERROR) png_error(png_ptr,
  88.547 +           "zlib failed to initialize compressor -- stream error");
  88.548 +      if (ret == Z_MEM_ERROR) png_error(png_ptr,
  88.549 +           "zlib failed to initialize compressor -- mem error");
  88.550 +      png_error(png_ptr, "zlib failed to initialize compressor");
  88.551 +   }
  88.552 +   png_ptr->zstream.next_out = png_ptr->zbuf;
  88.553 +   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  88.554 +   /* libpng is not interested in zstream.data_type */
  88.555 +   /* set it to a predefined value, to avoid its evaluation inside zlib */
  88.556 +   png_ptr->zstream.data_type = Z_BINARY;
  88.557 +
  88.558 +   png_ptr->mode = PNG_HAVE_IHDR;
  88.559 +}
  88.560 +
  88.561 +/* write the palette.  We are careful not to trust png_color to be in the
  88.562 + * correct order for PNG, so people can redefine it to any convenient
  88.563 + * structure.
  88.564 + */
  88.565 +void /* PRIVATE */
  88.566 +png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  88.567 +{
  88.568 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.569 +   PNG_PLTE;
  88.570 +#endif
  88.571 +   png_uint_32 i;
  88.572 +   png_colorp pal_ptr;
  88.573 +   png_byte buf[3];
  88.574 +
  88.575 +   png_debug(1, "in png_write_PLTE\n");
  88.576 +   if ((
  88.577 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
  88.578 +        !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  88.579 +#endif
  88.580 +        num_pal == 0) || num_pal > 256)
  88.581 +   {
  88.582 +     if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  88.583 +     {
  88.584 +        png_error(png_ptr, "Invalid number of colors in palette");
  88.585 +     }
  88.586 +     else
  88.587 +     {
  88.588 +        png_warning(png_ptr, "Invalid number of colors in palette");
  88.589 +        return;
  88.590 +     }
  88.591 +   }
  88.592 +
  88.593 +   if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  88.594 +   {
  88.595 +      png_warning(png_ptr,
  88.596 +        "Ignoring request to write a PLTE chunk in grayscale PNG");
  88.597 +      return;
  88.598 +   }
  88.599 +
  88.600 +   png_ptr->num_palette = (png_uint_16)num_pal;
  88.601 +   png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  88.602 +
  88.603 +   png_write_chunk_start(png_ptr, (png_bytep)png_PLTE,
  88.604 +     (png_uint_32)(num_pal * 3));
  88.605 +#ifndef PNG_NO_POINTER_INDEXING
  88.606 +   for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  88.607 +   {
  88.608 +      buf[0] = pal_ptr->red;
  88.609 +      buf[1] = pal_ptr->green;
  88.610 +      buf[2] = pal_ptr->blue;
  88.611 +      png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  88.612 +   }
  88.613 +#else
  88.614 +   /* This is a little slower but some buggy compilers need to do this instead */
  88.615 +   pal_ptr=palette;
  88.616 +   for (i = 0; i < num_pal; i++)
  88.617 +   {
  88.618 +      buf[0] = pal_ptr[i].red;
  88.619 +      buf[1] = pal_ptr[i].green;
  88.620 +      buf[2] = pal_ptr[i].blue;
  88.621 +      png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  88.622 +   }
  88.623 +#endif
  88.624 +   png_write_chunk_end(png_ptr);
  88.625 +   png_ptr->mode |= PNG_HAVE_PLTE;
  88.626 +}
  88.627 +
  88.628 +/* write an IDAT chunk */
  88.629 +void /* PRIVATE */
  88.630 +png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  88.631 +{
  88.632 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.633 +   PNG_IDAT;
  88.634 +#endif
  88.635 +   png_debug(1, "in png_write_IDAT\n");
  88.636 +
  88.637 +   /* Optimize the CMF field in the zlib stream. */
  88.638 +   /* This hack of the zlib stream is compliant to the stream specification. */
  88.639 +   if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  88.640 +       png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  88.641 +   {
  88.642 +      unsigned int z_cmf = data[0];  /* zlib compression method and flags */
  88.643 +      if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  88.644 +      {
  88.645 +         /* Avoid memory underflows and multiplication overflows. */
  88.646 +         /* The conditions below are practically always satisfied;
  88.647 +            however, they still must be checked. */
  88.648 +         if (length >= 2 &&
  88.649 +             png_ptr->height < 16384 && png_ptr->width < 16384)
  88.650 +         {
  88.651 +            png_uint_32 uncompressed_idat_size = png_ptr->height *
  88.652 +               ((png_ptr->width *
  88.653 +               png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  88.654 +            unsigned int z_cinfo = z_cmf >> 4;
  88.655 +            unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  88.656 +            while (uncompressed_idat_size <= half_z_window_size &&
  88.657 +                   half_z_window_size >= 256)
  88.658 +            {
  88.659 +               z_cinfo--;
  88.660 +               half_z_window_size >>= 1;
  88.661 +            }
  88.662 +            z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  88.663 +            if (data[0] != (png_byte)z_cmf)
  88.664 +            {
  88.665 +               data[0] = (png_byte)z_cmf;
  88.666 +               data[1] &= 0xe0;
  88.667 +               data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  88.668 +            }
  88.669 +         }
  88.670 +      }
  88.671 +      else
  88.672 +         png_error(png_ptr,
  88.673 +            "Invalid zlib compression method or flags in IDAT");
  88.674 +   }
  88.675 +
  88.676 +   png_write_chunk(png_ptr, (png_bytep)png_IDAT, data, length);
  88.677 +   png_ptr->mode |= PNG_HAVE_IDAT;
  88.678 +}
  88.679 +
  88.680 +/* write an IEND chunk */
  88.681 +void /* PRIVATE */
  88.682 +png_write_IEND(png_structp png_ptr)
  88.683 +{
  88.684 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.685 +   PNG_IEND;
  88.686 +#endif
  88.687 +   png_debug(1, "in png_write_IEND\n");
  88.688 +   png_write_chunk(png_ptr, (png_bytep)png_IEND, png_bytep_NULL,
  88.689 +     (png_size_t)0);
  88.690 +   png_ptr->mode |= PNG_HAVE_IEND;
  88.691 +}
  88.692 +
  88.693 +#if defined(PNG_WRITE_gAMA_SUPPORTED)
  88.694 +/* write a gAMA chunk */
  88.695 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  88.696 +void /* PRIVATE */
  88.697 +png_write_gAMA(png_structp png_ptr, double file_gamma)
  88.698 +{
  88.699 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.700 +   PNG_gAMA;
  88.701 +#endif
  88.702 +   png_uint_32 igamma;
  88.703 +   png_byte buf[4];
  88.704 +
  88.705 +   png_debug(1, "in png_write_gAMA\n");
  88.706 +   /* file_gamma is saved in 1/100,000ths */
  88.707 +   igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  88.708 +   png_save_uint_32(buf, igamma);
  88.709 +   png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4);
  88.710 +}
  88.711 +#endif
  88.712 +#ifdef PNG_FIXED_POINT_SUPPORTED
  88.713 +void /* PRIVATE */
  88.714 +png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  88.715 +{
  88.716 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.717 +   PNG_gAMA;
  88.718 +#endif
  88.719 +   png_byte buf[4];
  88.720 +
  88.721 +   png_debug(1, "in png_write_gAMA\n");
  88.722 +   /* file_gamma is saved in 1/100,000ths */
  88.723 +   png_save_uint_32(buf, (png_uint_32)file_gamma);
  88.724 +   png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4);
  88.725 +}
  88.726 +#endif
  88.727 +#endif
  88.728 +
  88.729 +#if defined(PNG_WRITE_sRGB_SUPPORTED)
  88.730 +/* write a sRGB chunk */
  88.731 +void /* PRIVATE */
  88.732 +png_write_sRGB(png_structp png_ptr, int srgb_intent)
  88.733 +{
  88.734 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.735 +   PNG_sRGB;
  88.736 +#endif
  88.737 +   png_byte buf[1];
  88.738 +
  88.739 +   png_debug(1, "in png_write_sRGB\n");
  88.740 +   if (srgb_intent >= PNG_sRGB_INTENT_LAST)
  88.741 +         png_warning(png_ptr,
  88.742 +            "Invalid sRGB rendering intent specified");
  88.743 +   buf[0]=(png_byte)srgb_intent;
  88.744 +   png_write_chunk(png_ptr, (png_bytep)png_sRGB, buf, (png_size_t)1);
  88.745 +}
  88.746 +#endif
  88.747 +
  88.748 +#if defined(PNG_WRITE_iCCP_SUPPORTED)
  88.749 +/* write an iCCP chunk */
  88.750 +void /* PRIVATE */
  88.751 +png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  88.752 +   png_charp profile, int profile_len)
  88.753 +{
  88.754 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.755 +   PNG_iCCP;
  88.756 +#endif
  88.757 +   png_size_t name_len;
  88.758 +   png_charp new_name;
  88.759 +   compression_state comp;
  88.760 +   int embedded_profile_len = 0;
  88.761 +
  88.762 +   png_debug(1, "in png_write_iCCP\n");
  88.763 +
  88.764 +   comp.num_output_ptr = 0;
  88.765 +   comp.max_output_ptr = 0;
  88.766 +   comp.output_ptr = NULL;
  88.767 +   comp.input = NULL;
  88.768 +   comp.input_len = 0;
  88.769 +
  88.770 +   if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  88.771 +      &new_name)) == 0)
  88.772 +   {
  88.773 +      png_warning(png_ptr, "Empty keyword in iCCP chunk");
  88.774 +      return;
  88.775 +   }
  88.776 +
  88.777 +   if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  88.778 +      png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  88.779 +
  88.780 +   if (profile == NULL)
  88.781 +      profile_len = 0;
  88.782 +
  88.783 +   if (profile_len > 3)
  88.784 +      embedded_profile_len =
  88.785 +          ((*( (png_bytep)profile    ))<<24) |
  88.786 +          ((*( (png_bytep)profile + 1))<<16) |
  88.787 +          ((*( (png_bytep)profile + 2))<< 8) |
  88.788 +          ((*( (png_bytep)profile + 3))    );
  88.789 +
  88.790 +   if (profile_len < embedded_profile_len)
  88.791 +   {
  88.792 +      png_warning(png_ptr,
  88.793 +        "Embedded profile length too large in iCCP chunk");
  88.794 +      return;
  88.795 +   }
  88.796 +
  88.797 +   if (profile_len > embedded_profile_len)
  88.798 +   {
  88.799 +      png_warning(png_ptr,
  88.800 +        "Truncating profile to actual length in iCCP chunk");
  88.801 +      profile_len = embedded_profile_len;
  88.802 +   }
  88.803 +
  88.804 +   if (profile_len)
  88.805 +      profile_len = png_text_compress(png_ptr, profile,
  88.806 +        (png_size_t)profile_len, PNG_COMPRESSION_TYPE_BASE, &comp);
  88.807 +
  88.808 +   /* make sure we include the NULL after the name and the compression type */
  88.809 +   png_write_chunk_start(png_ptr, (png_bytep)png_iCCP,
  88.810 +          (png_uint_32)(name_len + profile_len + 2));
  88.811 +   new_name[name_len + 1] = 0x00;
  88.812 +   png_write_chunk_data(png_ptr, (png_bytep)new_name,
  88.813 +     (png_size_t)(name_len + 2));
  88.814 +
  88.815 +   if (profile_len)
  88.816 +      png_write_compressed_data_out(png_ptr, &comp);
  88.817 +
  88.818 +   png_write_chunk_end(png_ptr);
  88.819 +   png_free(png_ptr, new_name);
  88.820 +}
  88.821 +#endif
  88.822 +
  88.823 +#if defined(PNG_WRITE_sPLT_SUPPORTED)
  88.824 +/* write a sPLT chunk */
  88.825 +void /* PRIVATE */
  88.826 +png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  88.827 +{
  88.828 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.829 +   PNG_sPLT;
  88.830 +#endif
  88.831 +   png_size_t name_len;
  88.832 +   png_charp new_name;
  88.833 +   png_byte entrybuf[10];
  88.834 +   int entry_size = (spalette->depth == 8 ? 6 : 10);
  88.835 +   int palette_size = entry_size * spalette->nentries;
  88.836 +   png_sPLT_entryp ep;
  88.837 +#ifdef PNG_NO_POINTER_INDEXING
  88.838 +   int i;
  88.839 +#endif
  88.840 +
  88.841 +   png_debug(1, "in png_write_sPLT\n");
  88.842 +   if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  88.843 +      spalette->name, &new_name))==0)
  88.844 +   {
  88.845 +      png_warning(png_ptr, "Empty keyword in sPLT chunk");
  88.846 +      return;
  88.847 +   }
  88.848 +
  88.849 +   /* make sure we include the NULL after the name */
  88.850 +   png_write_chunk_start(png_ptr, (png_bytep)png_sPLT,
  88.851 +     (png_uint_32)(name_len + 2 + palette_size));
  88.852 +   png_write_chunk_data(png_ptr, (png_bytep)new_name,
  88.853 +     (png_size_t)(name_len + 1));
  88.854 +   png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, (png_size_t)1);
  88.855 +
  88.856 +   /* loop through each palette entry, writing appropriately */
  88.857 +#ifndef PNG_NO_POINTER_INDEXING
  88.858 +   for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
  88.859 +   {
  88.860 +      if (spalette->depth == 8)
  88.861 +      {
  88.862 +          entrybuf[0] = (png_byte)ep->red;
  88.863 +          entrybuf[1] = (png_byte)ep->green;
  88.864 +          entrybuf[2] = (png_byte)ep->blue;
  88.865 +          entrybuf[3] = (png_byte)ep->alpha;
  88.866 +          png_save_uint_16(entrybuf + 4, ep->frequency);
  88.867 +      }
  88.868 +      else
  88.869 +      {
  88.870 +          png_save_uint_16(entrybuf + 0, ep->red);
  88.871 +          png_save_uint_16(entrybuf + 2, ep->green);
  88.872 +          png_save_uint_16(entrybuf + 4, ep->blue);
  88.873 +          png_save_uint_16(entrybuf + 6, ep->alpha);
  88.874 +          png_save_uint_16(entrybuf + 8, ep->frequency);
  88.875 +      }
  88.876 +      png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  88.877 +   }
  88.878 +#else
  88.879 +   ep=spalette->entries;
  88.880 +   for (i=0; i>spalette->nentries; i++)
  88.881 +   {
  88.882 +      if (spalette->depth == 8)
  88.883 +      {
  88.884 +          entrybuf[0] = (png_byte)ep[i].red;
  88.885 +          entrybuf[1] = (png_byte)ep[i].green;
  88.886 +          entrybuf[2] = (png_byte)ep[i].blue;
  88.887 +          entrybuf[3] = (png_byte)ep[i].alpha;
  88.888 +          png_save_uint_16(entrybuf + 4, ep[i].frequency);
  88.889 +      }
  88.890 +      else
  88.891 +      {
  88.892 +          png_save_uint_16(entrybuf + 0, ep[i].red);
  88.893 +          png_save_uint_16(entrybuf + 2, ep[i].green);
  88.894 +          png_save_uint_16(entrybuf + 4, ep[i].blue);
  88.895 +          png_save_uint_16(entrybuf + 6, ep[i].alpha);
  88.896 +          png_save_uint_16(entrybuf + 8, ep[i].frequency);
  88.897 +      }
  88.898 +      png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  88.899 +   }
  88.900 +#endif
  88.901 +
  88.902 +   png_write_chunk_end(png_ptr);
  88.903 +   png_free(png_ptr, new_name);
  88.904 +}
  88.905 +#endif
  88.906 +
  88.907 +#if defined(PNG_WRITE_sBIT_SUPPORTED)
  88.908 +/* write the sBIT chunk */
  88.909 +void /* PRIVATE */
  88.910 +png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  88.911 +{
  88.912 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.913 +   PNG_sBIT;
  88.914 +#endif
  88.915 +   png_byte buf[4];
  88.916 +   png_size_t size;
  88.917 +
  88.918 +   png_debug(1, "in png_write_sBIT\n");
  88.919 +   /* make sure we don't depend upon the order of PNG_COLOR_8 */
  88.920 +   if (color_type & PNG_COLOR_MASK_COLOR)
  88.921 +   {
  88.922 +      png_byte maxbits;
  88.923 +
  88.924 +      maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  88.925 +                png_ptr->usr_bit_depth);
  88.926 +      if (sbit->red == 0 || sbit->red > maxbits ||
  88.927 +          sbit->green == 0 || sbit->green > maxbits ||
  88.928 +          sbit->blue == 0 || sbit->blue > maxbits)
  88.929 +      {
  88.930 +         png_warning(png_ptr, "Invalid sBIT depth specified");
  88.931 +         return;
  88.932 +      }
  88.933 +      buf[0] = sbit->red;
  88.934 +      buf[1] = sbit->green;
  88.935 +      buf[2] = sbit->blue;
  88.936 +      size = 3;
  88.937 +   }
  88.938 +   else
  88.939 +   {
  88.940 +      if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  88.941 +      {
  88.942 +         png_warning(png_ptr, "Invalid sBIT depth specified");
  88.943 +         return;
  88.944 +      }
  88.945 +      buf[0] = sbit->gray;
  88.946 +      size = 1;
  88.947 +   }
  88.948 +
  88.949 +   if (color_type & PNG_COLOR_MASK_ALPHA)
  88.950 +   {
  88.951 +      if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  88.952 +      {
  88.953 +         png_warning(png_ptr, "Invalid sBIT depth specified");
  88.954 +         return;
  88.955 +      }
  88.956 +      buf[size++] = sbit->alpha;
  88.957 +   }
  88.958 +
  88.959 +   png_write_chunk(png_ptr, (png_bytep)png_sBIT, buf, size);
  88.960 +}
  88.961 +#endif
  88.962 +
  88.963 +#if defined(PNG_WRITE_cHRM_SUPPORTED)
  88.964 +/* write the cHRM chunk */
  88.965 +#ifdef PNG_FLOATING_POINT_SUPPORTED
  88.966 +void /* PRIVATE */
  88.967 +png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  88.968 +   double red_x, double red_y, double green_x, double green_y,
  88.969 +   double blue_x, double blue_y)
  88.970 +{
  88.971 +#ifdef PNG_USE_LOCAL_ARRAYS
  88.972 +   PNG_cHRM;
  88.973 +#endif
  88.974 +   png_byte buf[32];
  88.975 +   png_uint_32 itemp;
  88.976 +
  88.977 +   png_debug(1, "in png_write_cHRM\n");
  88.978 +   /* each value is saved in 1/100,000ths */
  88.979 +   if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  88.980 +       white_x + white_y > 1.0)
  88.981 +   {
  88.982 +      png_warning(png_ptr, "Invalid cHRM white point specified");
  88.983 +#if !defined(PNG_NO_CONSOLE_IO)
  88.984 +      fprintf(stderr, "white_x=%f, white_y=%f\n", white_x, white_y);
  88.985 +#endif
  88.986 +      return;
  88.987 +   }
  88.988 +   itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  88.989 +   png_save_uint_32(buf, itemp);
  88.990 +   itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  88.991 +   png_save_uint_32(buf + 4, itemp);
  88.992 +
  88.993 +   if (red_x < 0 ||  red_y < 0 || red_x + red_y > 1.0)
  88.994 +   {
  88.995 +      png_warning(png_ptr, "Invalid cHRM red point specified");
  88.996 +      return;
  88.997 +   }
  88.998 +   itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  88.999 +   png_save_uint_32(buf + 8, itemp);
 88.1000 +   itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
 88.1001 +   png_save_uint_32(buf + 12, itemp);
 88.1002 +
 88.1003 +   if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
 88.1004 +   {
 88.1005 +      png_warning(png_ptr, "Invalid cHRM green point specified");
 88.1006 +      return;
 88.1007 +   }
 88.1008 +   itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
 88.1009 +   png_save_uint_32(buf + 16, itemp);
 88.1010 +   itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
 88.1011 +   png_save_uint_32(buf + 20, itemp);
 88.1012 +
 88.1013 +   if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
 88.1014 +   {
 88.1015 +      png_warning(png_ptr, "Invalid cHRM blue point specified");
 88.1016 +      return;
 88.1017 +   }
 88.1018 +   itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
 88.1019 +   png_save_uint_32(buf + 24, itemp);
 88.1020 +   itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
 88.1021 +   png_save_uint_32(buf + 28, itemp);
 88.1022 +
 88.1023 +   png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32);
 88.1024 +}
 88.1025 +#endif
 88.1026 +#ifdef PNG_FIXED_POINT_SUPPORTED
 88.1027 +void /* PRIVATE */
 88.1028 +png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
 88.1029 +   png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
 88.1030 +   png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
 88.1031 +   png_fixed_point blue_y)
 88.1032 +{
 88.1033 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1034 +   PNG_cHRM;
 88.1035 +#endif
 88.1036 +   png_byte buf[32];
 88.1037 +
 88.1038 +   png_debug(1, "in png_write_cHRM\n");
 88.1039 +   /* each value is saved in 1/100,000ths */
 88.1040 +   if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
 88.1041 +   {
 88.1042 +      png_warning(png_ptr, "Invalid fixed cHRM white point specified");
 88.1043 +#if !defined(PNG_NO_CONSOLE_IO)
 88.1044 +      fprintf(stderr, "white_x=%ld, white_y=%ld\n", (unsigned long)white_x,
 88.1045 +        (unsigned long)white_y);
 88.1046 +#endif
 88.1047 +      return;
 88.1048 +   }
 88.1049 +   png_save_uint_32(buf, (png_uint_32)white_x);
 88.1050 +   png_save_uint_32(buf + 4, (png_uint_32)white_y);
 88.1051 +
 88.1052 +   if (red_x + red_y > 100000L)
 88.1053 +   {
 88.1054 +      png_warning(png_ptr, "Invalid cHRM fixed red point specified");
 88.1055 +      return;
 88.1056 +   }
 88.1057 +   png_save_uint_32(buf + 8, (png_uint_32)red_x);
 88.1058 +   png_save_uint_32(buf + 12, (png_uint_32)red_y);
 88.1059 +
 88.1060 +   if (green_x + green_y > 100000L)
 88.1061 +   {
 88.1062 +      png_warning(png_ptr, "Invalid fixed cHRM green point specified");
 88.1063 +      return;
 88.1064 +   }
 88.1065 +   png_save_uint_32(buf + 16, (png_uint_32)green_x);
 88.1066 +   png_save_uint_32(buf + 20, (png_uint_32)green_y);
 88.1067 +
 88.1068 +   if (blue_x + blue_y > 100000L)
 88.1069 +   {
 88.1070 +      png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
 88.1071 +      return;
 88.1072 +   }
 88.1073 +   png_save_uint_32(buf + 24, (png_uint_32)blue_x);
 88.1074 +   png_save_uint_32(buf + 28, (png_uint_32)blue_y);
 88.1075 +
 88.1076 +   png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32);
 88.1077 +}
 88.1078 +#endif
 88.1079 +#endif
 88.1080 +
 88.1081 +#if defined(PNG_WRITE_tRNS_SUPPORTED)
 88.1082 +/* write the tRNS chunk */
 88.1083 +void /* PRIVATE */
 88.1084 +png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
 88.1085 +   int num_trans, int color_type)
 88.1086 +{
 88.1087 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1088 +   PNG_tRNS;
 88.1089 +#endif
 88.1090 +   png_byte buf[6];
 88.1091 +
 88.1092 +   png_debug(1, "in png_write_tRNS\n");
 88.1093 +   if (color_type == PNG_COLOR_TYPE_PALETTE)
 88.1094 +   {
 88.1095 +      if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
 88.1096 +      {
 88.1097 +         png_warning(png_ptr, "Invalid number of transparent colors specified");
 88.1098 +         return;
 88.1099 +      }
 88.1100 +      /* write the chunk out as it is */
 88.1101 +      png_write_chunk(png_ptr, (png_bytep)png_tRNS, trans,
 88.1102 +        (png_size_t)num_trans);
 88.1103 +   }
 88.1104 +   else if (color_type == PNG_COLOR_TYPE_GRAY)
 88.1105 +   {
 88.1106 +      /* one 16 bit value */
 88.1107 +      if (tran->gray >= (1 << png_ptr->bit_depth))
 88.1108 +      {
 88.1109 +         png_warning(png_ptr,
 88.1110 +           "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
 88.1111 +         return;
 88.1112 +      }
 88.1113 +      png_save_uint_16(buf, tran->gray);
 88.1114 +      png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)2);
 88.1115 +   }
 88.1116 +   else if (color_type == PNG_COLOR_TYPE_RGB)
 88.1117 +   {
 88.1118 +      /* three 16 bit values */
 88.1119 +      png_save_uint_16(buf, tran->red);
 88.1120 +      png_save_uint_16(buf + 2, tran->green);
 88.1121 +      png_save_uint_16(buf + 4, tran->blue);
 88.1122 +      if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
 88.1123 +      {
 88.1124 +         png_warning(png_ptr,
 88.1125 +           "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
 88.1126 +         return;
 88.1127 +      }
 88.1128 +      png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)6);
 88.1129 +   }
 88.1130 +   else
 88.1131 +   {
 88.1132 +      png_warning(png_ptr, "Can't write tRNS with an alpha channel");
 88.1133 +   }
 88.1134 +}
 88.1135 +#endif
 88.1136 +
 88.1137 +#if defined(PNG_WRITE_bKGD_SUPPORTED)
 88.1138 +/* write the background chunk */
 88.1139 +void /* PRIVATE */
 88.1140 +png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
 88.1141 +{
 88.1142 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1143 +   PNG_bKGD;
 88.1144 +#endif
 88.1145 +   png_byte buf[6];
 88.1146 +
 88.1147 +   png_debug(1, "in png_write_bKGD\n");
 88.1148 +   if (color_type == PNG_COLOR_TYPE_PALETTE)
 88.1149 +   {
 88.1150 +      if (
 88.1151 +#if defined(PNG_MNG_FEATURES_SUPPORTED)
 88.1152 +          (png_ptr->num_palette ||
 88.1153 +          (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
 88.1154 +#endif
 88.1155 +         back->index > png_ptr->num_palette)
 88.1156 +      {
 88.1157 +         png_warning(png_ptr, "Invalid background palette index");
 88.1158 +         return;
 88.1159 +      }
 88.1160 +      buf[0] = back->index;
 88.1161 +      png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)1);
 88.1162 +   }
 88.1163 +   else if (color_type & PNG_COLOR_MASK_COLOR)
 88.1164 +   {
 88.1165 +      png_save_uint_16(buf, back->red);
 88.1166 +      png_save_uint_16(buf + 2, back->green);
 88.1167 +      png_save_uint_16(buf + 4, back->blue);
 88.1168 +      if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
 88.1169 +      {
 88.1170 +         png_warning(png_ptr,
 88.1171 +           "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
 88.1172 +         return;
 88.1173 +      }
 88.1174 +      png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)6);
 88.1175 +   }
 88.1176 +   else
 88.1177 +   {
 88.1178 +      if (back->gray >= (1 << png_ptr->bit_depth))
 88.1179 +      {
 88.1180 +         png_warning(png_ptr,
 88.1181 +           "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
 88.1182 +         return;
 88.1183 +      }
 88.1184 +      png_save_uint_16(buf, back->gray);
 88.1185 +      png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)2);
 88.1186 +   }
 88.1187 +}
 88.1188 +#endif
 88.1189 +
 88.1190 +#if defined(PNG_WRITE_hIST_SUPPORTED)
 88.1191 +/* write the histogram */
 88.1192 +void /* PRIVATE */
 88.1193 +png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
 88.1194 +{
 88.1195 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1196 +   PNG_hIST;
 88.1197 +#endif
 88.1198 +   int i;
 88.1199 +   png_byte buf[3];
 88.1200 +
 88.1201 +   png_debug(1, "in png_write_hIST\n");
 88.1202 +   if (num_hist > (int)png_ptr->num_palette)
 88.1203 +   {
 88.1204 +      png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
 88.1205 +         png_ptr->num_palette);
 88.1206 +      png_warning(png_ptr, "Invalid number of histogram entries specified");
 88.1207 +      return;
 88.1208 +   }
 88.1209 +
 88.1210 +   png_write_chunk_start(png_ptr, (png_bytep)png_hIST,
 88.1211 +     (png_uint_32)(num_hist * 2));
 88.1212 +   for (i = 0; i < num_hist; i++)
 88.1213 +   {
 88.1214 +      png_save_uint_16(buf, hist[i]);
 88.1215 +      png_write_chunk_data(png_ptr, buf, (png_size_t)2);
 88.1216 +   }
 88.1217 +   png_write_chunk_end(png_ptr);
 88.1218 +}
 88.1219 +#endif
 88.1220 +
 88.1221 +#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
 88.1222 +    defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
 88.1223 +/* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
 88.1224 + * and if invalid, correct the keyword rather than discarding the entire
 88.1225 + * chunk.  The PNG 1.0 specification requires keywords 1-79 characters in
 88.1226 + * length, forbids leading or trailing whitespace, multiple internal spaces,
 88.1227 + * and the non-break space (0x80) from ISO 8859-1.  Returns keyword length.
 88.1228 + *
 88.1229 + * The new_key is allocated to hold the corrected keyword and must be freed
 88.1230 + * by the calling routine.  This avoids problems with trying to write to
 88.1231 + * static keywords without having to have duplicate copies of the strings.
 88.1232 + */
 88.1233 +png_size_t /* PRIVATE */
 88.1234 +png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
 88.1235 +{
 88.1236 +   png_size_t key_len;
 88.1237 +   png_charp kp, dp;
 88.1238 +   int kflag;
 88.1239 +   int kwarn=0;
 88.1240 +
 88.1241 +   png_debug(1, "in png_check_keyword\n");
 88.1242 +   *new_key = NULL;
 88.1243 +
 88.1244 +   if (key == NULL || (key_len = png_strlen(key)) == 0)
 88.1245 +   {
 88.1246 +      png_warning(png_ptr, "zero length keyword");
 88.1247 +      return ((png_size_t)0);
 88.1248 +   }
 88.1249 +
 88.1250 +   png_debug1(2, "Keyword to be checked is '%s'\n", key);
 88.1251 +
 88.1252 +   *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
 88.1253 +   if (*new_key == NULL)
 88.1254 +   {
 88.1255 +      png_warning(png_ptr, "Out of memory while procesing keyword");
 88.1256 +      return ((png_size_t)0);
 88.1257 +   }
 88.1258 +
 88.1259 +   /* Replace non-printing characters with a blank and print a warning */
 88.1260 +   for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
 88.1261 +   {
 88.1262 +      if ((png_byte)*kp < 0x20 ||
 88.1263 +         ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
 88.1264 +      {
 88.1265 +#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
 88.1266 +         char msg[40];
 88.1267 +
 88.1268 +         png_snprintf(msg, 40,
 88.1269 +           "invalid keyword character 0x%02X", (png_byte)*kp);
 88.1270 +         png_warning(png_ptr, msg);
 88.1271 +#else
 88.1272 +         png_warning(png_ptr, "invalid character in keyword");
 88.1273 +#endif
 88.1274 +         *dp = ' ';
 88.1275 +      }
 88.1276 +      else
 88.1277 +      {
 88.1278 +         *dp = *kp;
 88.1279 +      }
 88.1280 +   }
 88.1281 +   *dp = '\0';
 88.1282 +
 88.1283 +   /* Remove any trailing white space. */
 88.1284 +   kp = *new_key + key_len - 1;
 88.1285 +   if (*kp == ' ')
 88.1286 +   {
 88.1287 +      png_warning(png_ptr, "trailing spaces removed from keyword");
 88.1288 +
 88.1289 +      while (*kp == ' ')
 88.1290 +      {
 88.1291 +        *(kp--) = '\0';
 88.1292 +        key_len--;
 88.1293 +      }
 88.1294 +   }
 88.1295 +
 88.1296 +   /* Remove any leading white space. */
 88.1297 +   kp = *new_key;
 88.1298 +   if (*kp == ' ')
 88.1299 +   {
 88.1300 +      png_warning(png_ptr, "leading spaces removed from keyword");
 88.1301 +
 88.1302 +      while (*kp == ' ')
 88.1303 +      {
 88.1304 +        kp++;
 88.1305 +        key_len--;
 88.1306 +      }
 88.1307 +   }
 88.1308 +
 88.1309 +   png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
 88.1310 +
 88.1311 +   /* Remove multiple internal spaces. */
 88.1312 +   for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
 88.1313 +   {
 88.1314 +      if (*kp == ' ' && kflag == 0)
 88.1315 +      {
 88.1316 +         *(dp++) = *kp;
 88.1317 +         kflag = 1;
 88.1318 +      }
 88.1319 +      else if (*kp == ' ')
 88.1320 +      {
 88.1321 +         key_len--;
 88.1322 +         kwarn=1;
 88.1323 +      }
 88.1324 +      else
 88.1325 +      {
 88.1326 +         *(dp++) = *kp;
 88.1327 +         kflag = 0;
 88.1328 +      }
 88.1329 +   }
 88.1330 +   *dp = '\0';
 88.1331 +   if (kwarn)
 88.1332 +      png_warning(png_ptr, "extra interior spaces removed from keyword");
 88.1333 +
 88.1334 +   if (key_len == 0)
 88.1335 +   {
 88.1336 +      png_free(png_ptr, *new_key);
 88.1337 +       *new_key=NULL;
 88.1338 +      png_warning(png_ptr, "Zero length keyword");
 88.1339 +   }
 88.1340 +
 88.1341 +   if (key_len > 79)
 88.1342 +   {
 88.1343 +      png_warning(png_ptr, "keyword length must be 1 - 79 characters");
 88.1344 +      new_key[79] = '\0';
 88.1345 +      key_len = 79;
 88.1346 +   }
 88.1347 +
 88.1348 +   return (key_len);
 88.1349 +}
 88.1350 +#endif
 88.1351 +
 88.1352 +#if defined(PNG_WRITE_tEXt_SUPPORTED)
 88.1353 +/* write a tEXt chunk */
 88.1354 +void /* PRIVATE */
 88.1355 +png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
 88.1356 +   png_size_t text_len)
 88.1357 +{
 88.1358 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1359 +   PNG_tEXt;
 88.1360 +#endif
 88.1361 +   png_size_t key_len;
 88.1362 +   png_charp new_key;
 88.1363 +
 88.1364 +   png_debug(1, "in png_write_tEXt\n");
 88.1365 +   if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
 88.1366 +   {
 88.1367 +      png_warning(png_ptr, "Empty keyword in tEXt chunk");
 88.1368 +      return;
 88.1369 +   }
 88.1370 +
 88.1371 +   if (text == NULL || *text == '\0')
 88.1372 +      text_len = 0;
 88.1373 +   else
 88.1374 +      text_len = png_strlen(text);
 88.1375 +
 88.1376 +   /* make sure we include the 0 after the key */
 88.1377 +   png_write_chunk_start(png_ptr, (png_bytep)png_tEXt,
 88.1378 +      (png_uint_32)(key_len + text_len + 1));
 88.1379 +   /*
 88.1380 +    * We leave it to the application to meet PNG-1.0 requirements on the
 88.1381 +    * contents of the text.  PNG-1.0 through PNG-1.2 discourage the use of
 88.1382 +    * any non-Latin-1 characters except for NEWLINE.  ISO PNG will forbid them.
 88.1383 +    * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
 88.1384 +    */
 88.1385 +   png_write_chunk_data(png_ptr, (png_bytep)new_key,
 88.1386 +     (png_size_t)(key_len + 1));
 88.1387 +   if (text_len)
 88.1388 +      png_write_chunk_data(png_ptr, (png_bytep)text, (png_size_t)text_len);
 88.1389 +
 88.1390 +   png_write_chunk_end(png_ptr);
 88.1391 +   png_free(png_ptr, new_key);
 88.1392 +}
 88.1393 +#endif
 88.1394 +
 88.1395 +#if defined(PNG_WRITE_zTXt_SUPPORTED)
 88.1396 +/* write a compressed text chunk */
 88.1397 +void /* PRIVATE */
 88.1398 +png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
 88.1399 +   png_size_t text_len, int compression)
 88.1400 +{
 88.1401 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1402 +   PNG_zTXt;
 88.1403 +#endif
 88.1404 +   png_size_t key_len;
 88.1405 +   char buf[1];
 88.1406 +   png_charp new_key;
 88.1407 +   compression_state comp;
 88.1408 +
 88.1409 +   png_debug(1, "in png_write_zTXt\n");
 88.1410 +
 88.1411 +   comp.num_output_ptr = 0;
 88.1412 +   comp.max_output_ptr = 0;
 88.1413 +   comp.output_ptr = NULL;
 88.1414 +   comp.input = NULL;
 88.1415 +   comp.input_len = 0;
 88.1416 +
 88.1417 +   if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
 88.1418 +   {
 88.1419 +      png_warning(png_ptr, "Empty keyword in zTXt chunk");
 88.1420 +      png_free(png_ptr, new_key);
 88.1421 +      return;
 88.1422 +   }
 88.1423 +
 88.1424 +   if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
 88.1425 +   {
 88.1426 +      png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
 88.1427 +      png_free(png_ptr, new_key);
 88.1428 +      return;
 88.1429 +   }
 88.1430 +
 88.1431 +   text_len = png_strlen(text);
 88.1432 +
 88.1433 +   /* compute the compressed data; do it now for the length */
 88.1434 +   text_len = png_text_compress(png_ptr, text, text_len, compression,
 88.1435 +       &comp);
 88.1436 +
 88.1437 +   /* write start of chunk */
 88.1438 +   png_write_chunk_start(png_ptr, (png_bytep)png_zTXt,
 88.1439 +     (png_uint_32)(key_len+text_len + 2));
 88.1440 +   /* write key */
 88.1441 +   png_write_chunk_data(png_ptr, (png_bytep)new_key,
 88.1442 +     (png_size_t)(key_len + 1));
 88.1443 +   png_free(png_ptr, new_key);
 88.1444 +
 88.1445 +   buf[0] = (png_byte)compression;
 88.1446 +   /* write compression */
 88.1447 +   png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
 88.1448 +   /* write the compressed data */
 88.1449 +   png_write_compressed_data_out(png_ptr, &comp);
 88.1450 +
 88.1451 +   /* close the chunk */
 88.1452 +   png_write_chunk_end(png_ptr);
 88.1453 +}
 88.1454 +#endif
 88.1455 +
 88.1456 +#if defined(PNG_WRITE_iTXt_SUPPORTED)
 88.1457 +/* write an iTXt chunk */
 88.1458 +void /* PRIVATE */
 88.1459 +png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
 88.1460 +    png_charp lang, png_charp lang_key, png_charp text)
 88.1461 +{
 88.1462 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1463 +   PNG_iTXt;
 88.1464 +#endif
 88.1465 +   png_size_t lang_len, key_len, lang_key_len, text_len;
 88.1466 +   png_charp new_lang, new_key;
 88.1467 +   png_byte cbuf[2];
 88.1468 +   compression_state comp;
 88.1469 +
 88.1470 +   png_debug(1, "in png_write_iTXt\n");
 88.1471 +
 88.1472 +   comp.num_output_ptr = 0;
 88.1473 +   comp.max_output_ptr = 0;
 88.1474 +   comp.output_ptr = NULL;
 88.1475 +   comp.input = NULL;
 88.1476 +
 88.1477 +   if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
 88.1478 +   {
 88.1479 +      png_warning(png_ptr, "Empty keyword in iTXt chunk");
 88.1480 +      return;
 88.1481 +   }
 88.1482 +   if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
 88.1483 +   {
 88.1484 +      png_warning(png_ptr, "Empty language field in iTXt chunk");
 88.1485 +      new_lang = NULL;
 88.1486 +      lang_len = 0;
 88.1487 +   }
 88.1488 +
 88.1489 +   if (lang_key == NULL)
 88.1490 +     lang_key_len = 0;
 88.1491 +   else
 88.1492 +     lang_key_len = png_strlen(lang_key);
 88.1493 +
 88.1494 +   if (text == NULL)
 88.1495 +      text_len = 0;
 88.1496 +   else
 88.1497 +     text_len = png_strlen(text);
 88.1498 +
 88.1499 +   /* compute the compressed data; do it now for the length */
 88.1500 +   text_len = png_text_compress(png_ptr, text, text_len, compression-2,
 88.1501 +      &comp);
 88.1502 +
 88.1503 +
 88.1504 +   /* make sure we include the compression flag, the compression byte,
 88.1505 +    * and the NULs after the key, lang, and lang_key parts */
 88.1506 +
 88.1507 +   png_write_chunk_start(png_ptr, (png_bytep)png_iTXt,
 88.1508 +          (png_uint_32)(
 88.1509 +        5 /* comp byte, comp flag, terminators for key, lang and lang_key */
 88.1510 +        + key_len
 88.1511 +        + lang_len
 88.1512 +        + lang_key_len
 88.1513 +        + text_len));
 88.1514 +
 88.1515 +   /*
 88.1516 +    * We leave it to the application to meet PNG-1.0 requirements on the
 88.1517 +    * contents of the text.  PNG-1.0 through PNG-1.2 discourage the use of
 88.1518 +    * any non-Latin-1 characters except for NEWLINE.  ISO PNG will forbid them.
 88.1519 +    * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
 88.1520 +    */
 88.1521 +   png_write_chunk_data(png_ptr, (png_bytep)new_key,
 88.1522 +     (png_size_t)(key_len + 1));
 88.1523 +
 88.1524 +   /* set the compression flag */
 88.1525 +   if (compression == PNG_ITXT_COMPRESSION_NONE || \
 88.1526 +       compression == PNG_TEXT_COMPRESSION_NONE)
 88.1527 +       cbuf[0] = 0;
 88.1528 +   else /* compression == PNG_ITXT_COMPRESSION_zTXt */
 88.1529 +       cbuf[0] = 1;
 88.1530 +   /* set the compression method */
 88.1531 +   cbuf[1] = 0;
 88.1532 +   png_write_chunk_data(png_ptr, cbuf, (png_size_t)2);
 88.1533 +
 88.1534 +   cbuf[0] = 0;
 88.1535 +   png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf),
 88.1536 +     (png_size_t)(lang_len + 1));
 88.1537 +   png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf),
 88.1538 +     (png_size_t)(lang_key_len + 1));
 88.1539 +   png_write_compressed_data_out(png_ptr, &comp);
 88.1540 +
 88.1541 +   png_write_chunk_end(png_ptr);
 88.1542 +   png_free(png_ptr, new_key);
 88.1543 +   png_free(png_ptr, new_lang);
 88.1544 +}
 88.1545 +#endif
 88.1546 +
 88.1547 +#if defined(PNG_WRITE_oFFs_SUPPORTED)
 88.1548 +/* write the oFFs chunk */
 88.1549 +void /* PRIVATE */
 88.1550 +png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
 88.1551 +   int unit_type)
 88.1552 +{
 88.1553 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1554 +   PNG_oFFs;
 88.1555 +#endif
 88.1556 +   png_byte buf[9];
 88.1557 +
 88.1558 +   png_debug(1, "in png_write_oFFs\n");
 88.1559 +   if (unit_type >= PNG_OFFSET_LAST)
 88.1560 +      png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
 88.1561 +
 88.1562 +   png_save_int_32(buf, x_offset);
 88.1563 +   png_save_int_32(buf + 4, y_offset);
 88.1564 +   buf[8] = (png_byte)unit_type;
 88.1565 +
 88.1566 +   png_write_chunk(png_ptr, (png_bytep)png_oFFs, buf, (png_size_t)9);
 88.1567 +}
 88.1568 +#endif
 88.1569 +#if defined(PNG_WRITE_pCAL_SUPPORTED)
 88.1570 +/* write the pCAL chunk (described in the PNG extensions document) */
 88.1571 +void /* PRIVATE */
 88.1572 +png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
 88.1573 +   png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
 88.1574 +{
 88.1575 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1576 +   PNG_pCAL;
 88.1577 +#endif
 88.1578 +   png_size_t purpose_len, units_len, total_len;
 88.1579 +   png_uint_32p params_len;
 88.1580 +   png_byte buf[10];
 88.1581 +   png_charp new_purpose;
 88.1582 +   int i;
 88.1583 +
 88.1584 +   png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
 88.1585 +   if (type >= PNG_EQUATION_LAST)
 88.1586 +      png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
 88.1587 +
 88.1588 +   purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
 88.1589 +   png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
 88.1590 +   units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
 88.1591 +   png_debug1(3, "pCAL units length = %d\n", (int)units_len);
 88.1592 +   total_len = purpose_len + units_len + 10;
 88.1593 +
 88.1594 +   params_len = (png_uint_32p)png_malloc(png_ptr,
 88.1595 +      (png_uint_32)(nparams * png_sizeof(png_uint_32)));
 88.1596 +
 88.1597 +   /* Find the length of each parameter, making sure we don't count the
 88.1598 +      null terminator for the last parameter. */
 88.1599 +   for (i = 0; i < nparams; i++)
 88.1600 +   {
 88.1601 +      params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
 88.1602 +      png_debug2(3, "pCAL parameter %d length = %lu\n", i,
 88.1603 +        (unsigned long) params_len[i]);
 88.1604 +      total_len += (png_size_t)params_len[i];
 88.1605 +   }
 88.1606 +
 88.1607 +   png_debug1(3, "pCAL total length = %d\n", (int)total_len);
 88.1608 +   png_write_chunk_start(png_ptr, (png_bytep)png_pCAL, (png_uint_32)total_len);
 88.1609 +   png_write_chunk_data(png_ptr, (png_bytep)new_purpose,
 88.1610 +     (png_size_t)purpose_len);
 88.1611 +   png_save_int_32(buf, X0);
 88.1612 +   png_save_int_32(buf + 4, X1);
 88.1613 +   buf[8] = (png_byte)type;
 88.1614 +   buf[9] = (png_byte)nparams;
 88.1615 +   png_write_chunk_data(png_ptr, buf, (png_size_t)10);
 88.1616 +   png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
 88.1617 +
 88.1618 +   png_free(png_ptr, new_purpose);
 88.1619 +
 88.1620 +   for (i = 0; i < nparams; i++)
 88.1621 +   {
 88.1622 +      png_write_chunk_data(png_ptr, (png_bytep)params[i],
 88.1623 +         (png_size_t)params_len[i]);
 88.1624 +   }
 88.1625 +
 88.1626 +   png_free(png_ptr, params_len);
 88.1627 +   png_write_chunk_end(png_ptr);
 88.1628 +}
 88.1629 +#endif
 88.1630 +
 88.1631 +#if defined(PNG_WRITE_sCAL_SUPPORTED)
 88.1632 +/* write the sCAL chunk */
 88.1633 +#if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
 88.1634 +void /* PRIVATE */
 88.1635 +png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
 88.1636 +{
 88.1637 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1638 +   PNG_sCAL;
 88.1639 +#endif
 88.1640 +   char buf[64];
 88.1641 +   png_size_t total_len;
 88.1642 +
 88.1643 +   png_debug(1, "in png_write_sCAL\n");
 88.1644 +
 88.1645 +   buf[0] = (char)unit;
 88.1646 +#if defined(_WIN32_WCE)
 88.1647 +/* sprintf() function is not supported on WindowsCE */
 88.1648 +   {
 88.1649 +      wchar_t wc_buf[32];
 88.1650 +      size_t wc_len;
 88.1651 +      swprintf(wc_buf, TEXT("%12.12e"), width);
 88.1652 +      wc_len = wcslen(wc_buf);
 88.1653 +      WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
 88.1654 +      total_len = wc_len + 2;
 88.1655 +      swprintf(wc_buf, TEXT("%12.12e"), height);
 88.1656 +      wc_len = wcslen(wc_buf);
 88.1657 +      WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
 88.1658 +         NULL, NULL);
 88.1659 +      total_len += wc_len;
 88.1660 +   }
 88.1661 +#else
 88.1662 +   png_snprintf(buf + 1, 63, "%12.12e", width);
 88.1663 +   total_len = 1 + png_strlen(buf + 1) + 1;
 88.1664 +   png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
 88.1665 +   total_len += png_strlen(buf + total_len);
 88.1666 +#endif
 88.1667 +
 88.1668 +   png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
 88.1669 +   png_write_chunk(png_ptr, (png_bytep)png_sCAL, (png_bytep)buf, total_len);
 88.1670 +}
 88.1671 +#else
 88.1672 +#ifdef PNG_FIXED_POINT_SUPPORTED
 88.1673 +void /* PRIVATE */
 88.1674 +png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
 88.1675 +   png_charp height)
 88.1676 +{
 88.1677 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1678 +   PNG_sCAL;
 88.1679 +#endif
 88.1680 +   png_byte buf[64];
 88.1681 +   png_size_t wlen, hlen, total_len;
 88.1682 +
 88.1683 +   png_debug(1, "in png_write_sCAL_s\n");
 88.1684 +
 88.1685 +   wlen = png_strlen(width);
 88.1686 +   hlen = png_strlen(height);
 88.1687 +   total_len = wlen + hlen + 2;
 88.1688 +   if (total_len > 64)
 88.1689 +   {
 88.1690 +      png_warning(png_ptr, "Can't write sCAL (buffer too small)");
 88.1691 +      return;
 88.1692 +   }
 88.1693 +
 88.1694 +   buf[0] = (png_byte)unit;
 88.1695 +   png_memcpy(buf + 1, width, wlen + 1);      /* append the '\0' here */
 88.1696 +   png_memcpy(buf + wlen + 2, height, hlen);  /* do NOT append the '\0' here */
 88.1697 +
 88.1698 +   png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
 88.1699 +   png_write_chunk(png_ptr, (png_bytep)png_sCAL, buf, total_len);
 88.1700 +}
 88.1701 +#endif
 88.1702 +#endif
 88.1703 +#endif
 88.1704 +
 88.1705 +#if defined(PNG_WRITE_pHYs_SUPPORTED)
 88.1706 +/* write the pHYs chunk */
 88.1707 +void /* PRIVATE */
 88.1708 +png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
 88.1709 +   png_uint_32 y_pixels_per_unit,
 88.1710 +   int unit_type)
 88.1711 +{
 88.1712 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1713 +   PNG_pHYs;
 88.1714 +#endif
 88.1715 +   png_byte buf[9];
 88.1716 +
 88.1717 +   png_debug(1, "in png_write_pHYs\n");
 88.1718 +   if (unit_type >= PNG_RESOLUTION_LAST)
 88.1719 +      png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
 88.1720 +
 88.1721 +   png_save_uint_32(buf, x_pixels_per_unit);
 88.1722 +   png_save_uint_32(buf + 4, y_pixels_per_unit);
 88.1723 +   buf[8] = (png_byte)unit_type;
 88.1724 +
 88.1725 +   png_write_chunk(png_ptr, (png_bytep)png_pHYs, buf, (png_size_t)9);
 88.1726 +}
 88.1727 +#endif
 88.1728 +
 88.1729 +#if defined(PNG_WRITE_tIME_SUPPORTED)
 88.1730 +/* Write the tIME chunk.  Use either png_convert_from_struct_tm()
 88.1731 + * or png_convert_from_time_t(), or fill in the structure yourself.
 88.1732 + */
 88.1733 +void /* PRIVATE */
 88.1734 +png_write_tIME(png_structp png_ptr, png_timep mod_time)
 88.1735 +{
 88.1736 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1737 +   PNG_tIME;
 88.1738 +#endif
 88.1739 +   png_byte buf[7];
 88.1740 +
 88.1741 +   png_debug(1, "in png_write_tIME\n");
 88.1742 +   if (mod_time->month  > 12 || mod_time->month  < 1 ||
 88.1743 +       mod_time->day    > 31 || mod_time->day    < 1 ||
 88.1744 +       mod_time->hour   > 23 || mod_time->second > 60)
 88.1745 +   {
 88.1746 +      png_warning(png_ptr, "Invalid time specified for tIME chunk");
 88.1747 +      return;
 88.1748 +   }
 88.1749 +
 88.1750 +   png_save_uint_16(buf, mod_time->year);
 88.1751 +   buf[2] = mod_time->month;
 88.1752 +   buf[3] = mod_time->day;
 88.1753 +   buf[4] = mod_time->hour;
 88.1754 +   buf[5] = mod_time->minute;
 88.1755 +   buf[6] = mod_time->second;
 88.1756 +
 88.1757 +   png_write_chunk(png_ptr, (png_bytep)png_tIME, buf, (png_size_t)7);
 88.1758 +}
 88.1759 +#endif
 88.1760 +
 88.1761 +/* initializes the row writing capability of libpng */
 88.1762 +void /* PRIVATE */
 88.1763 +png_write_start_row(png_structp png_ptr)
 88.1764 +{
 88.1765 +#ifdef PNG_WRITE_INTERLACING_SUPPORTED
 88.1766 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1767 +   /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
 88.1768 +
 88.1769 +   /* start of interlace block */
 88.1770 +   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
 88.1771 +
 88.1772 +   /* offset to next interlace block */
 88.1773 +   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
 88.1774 +
 88.1775 +   /* start of interlace block in the y direction */
 88.1776 +   int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
 88.1777 +
 88.1778 +   /* offset to next interlace block in the y direction */
 88.1779 +   int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
 88.1780 +#endif
 88.1781 +#endif
 88.1782 +
 88.1783 +   png_size_t buf_size;
 88.1784 +
 88.1785 +   png_debug(1, "in png_write_start_row\n");
 88.1786 +   buf_size = (png_size_t)(PNG_ROWBYTES(
 88.1787 +      png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1);
 88.1788 +
 88.1789 +   /* set up row buffer */
 88.1790 +   png_ptr->row_buf = (png_bytep)png_malloc(png_ptr,
 88.1791 +     (png_uint_32)buf_size);
 88.1792 +   png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
 88.1793 +
 88.1794 +#ifndef PNG_NO_WRITE_FILTER
 88.1795 +   /* set up filtering buffer, if using this filter */
 88.1796 +   if (png_ptr->do_filter & PNG_FILTER_SUB)
 88.1797 +   {
 88.1798 +      png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
 88.1799 +         (png_uint_32)(png_ptr->rowbytes + 1));
 88.1800 +      png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
 88.1801 +   }
 88.1802 +
 88.1803 +   /* We only need to keep the previous row if we are using one of these. */
 88.1804 +   if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
 88.1805 +   {
 88.1806 +     /* set up previous row buffer */
 88.1807 +      png_ptr->prev_row = (png_bytep)png_malloc(png_ptr,
 88.1808 +        (png_uint_32)buf_size);
 88.1809 +      png_memset(png_ptr->prev_row, 0, buf_size);
 88.1810 +
 88.1811 +      if (png_ptr->do_filter & PNG_FILTER_UP)
 88.1812 +      {
 88.1813 +         png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
 88.1814 +           (png_uint_32)(png_ptr->rowbytes + 1));
 88.1815 +         png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
 88.1816 +      }
 88.1817 +
 88.1818 +      if (png_ptr->do_filter & PNG_FILTER_AVG)
 88.1819 +      {
 88.1820 +         png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
 88.1821 +           (png_uint_32)(png_ptr->rowbytes + 1));
 88.1822 +         png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
 88.1823 +      }
 88.1824 +
 88.1825 +      if (png_ptr->do_filter & PNG_FILTER_PAETH)
 88.1826 +      {
 88.1827 +         png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
 88.1828 +           (png_uint_32)(png_ptr->rowbytes + 1));
 88.1829 +         png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
 88.1830 +      }
 88.1831 +   }
 88.1832 +#endif /* PNG_NO_WRITE_FILTER */
 88.1833 +
 88.1834 +#ifdef PNG_WRITE_INTERLACING_SUPPORTED
 88.1835 +   /* if interlaced, we need to set up width and height of pass */
 88.1836 +   if (png_ptr->interlaced)
 88.1837 +   {
 88.1838 +      if (!(png_ptr->transformations & PNG_INTERLACE))
 88.1839 +      {
 88.1840 +         png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
 88.1841 +            png_pass_ystart[0]) / png_pass_yinc[0];
 88.1842 +         png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
 88.1843 +            png_pass_start[0]) / png_pass_inc[0];
 88.1844 +      }
 88.1845 +      else
 88.1846 +      {
 88.1847 +         png_ptr->num_rows = png_ptr->height;
 88.1848 +         png_ptr->usr_width = png_ptr->width;
 88.1849 +      }
 88.1850 +   }
 88.1851 +   else
 88.1852 +#endif
 88.1853 +   {
 88.1854 +      png_ptr->num_rows = png_ptr->height;
 88.1855 +      png_ptr->usr_width = png_ptr->width;
 88.1856 +   }
 88.1857 +   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
 88.1858 +   png_ptr->zstream.next_out = png_ptr->zbuf;
 88.1859 +}
 88.1860 +
 88.1861 +/* Internal use only.  Called when finished processing a row of data. */
 88.1862 +void /* PRIVATE */
 88.1863 +png_write_finish_row(png_structp png_ptr)
 88.1864 +{
 88.1865 +#ifdef PNG_WRITE_INTERLACING_SUPPORTED
 88.1866 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1867 +   /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
 88.1868 +
 88.1869 +   /* start of interlace block */
 88.1870 +   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
 88.1871 +
 88.1872 +   /* offset to next interlace block */
 88.1873 +   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
 88.1874 +
 88.1875 +   /* start of interlace block in the y direction */
 88.1876 +   int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
 88.1877 +
 88.1878 +   /* offset to next interlace block in the y direction */
 88.1879 +   int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
 88.1880 +#endif
 88.1881 +#endif
 88.1882 +
 88.1883 +   int ret;
 88.1884 +
 88.1885 +   png_debug(1, "in png_write_finish_row\n");
 88.1886 +   /* next row */
 88.1887 +   png_ptr->row_number++;
 88.1888 +
 88.1889 +   /* see if we are done */
 88.1890 +   if (png_ptr->row_number < png_ptr->num_rows)
 88.1891 +      return;
 88.1892 +
 88.1893 +#ifdef PNG_WRITE_INTERLACING_SUPPORTED
 88.1894 +   /* if interlaced, go to next pass */
 88.1895 +   if (png_ptr->interlaced)
 88.1896 +   {
 88.1897 +      png_ptr->row_number = 0;
 88.1898 +      if (png_ptr->transformations & PNG_INTERLACE)
 88.1899 +      {
 88.1900 +         png_ptr->pass++;
 88.1901 +      }
 88.1902 +      else
 88.1903 +      {
 88.1904 +         /* loop until we find a non-zero width or height pass */
 88.1905 +         do
 88.1906 +         {
 88.1907 +            png_ptr->pass++;
 88.1908 +            if (png_ptr->pass >= 7)
 88.1909 +               break;
 88.1910 +            png_ptr->usr_width = (png_ptr->width +
 88.1911 +               png_pass_inc[png_ptr->pass] - 1 -
 88.1912 +               png_pass_start[png_ptr->pass]) /
 88.1913 +               png_pass_inc[png_ptr->pass];
 88.1914 +            png_ptr->num_rows = (png_ptr->height +
 88.1915 +               png_pass_yinc[png_ptr->pass] - 1 -
 88.1916 +               png_pass_ystart[png_ptr->pass]) /
 88.1917 +               png_pass_yinc[png_ptr->pass];
 88.1918 +            if (png_ptr->transformations & PNG_INTERLACE)
 88.1919 +               break;
 88.1920 +         } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
 88.1921 +
 88.1922 +      }
 88.1923 +
 88.1924 +      /* reset the row above the image for the next pass */
 88.1925 +      if (png_ptr->pass < 7)
 88.1926 +      {
 88.1927 +         if (png_ptr->prev_row != NULL)
 88.1928 +            png_memset(png_ptr->prev_row, 0,
 88.1929 +               (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
 88.1930 +               png_ptr->usr_bit_depth, png_ptr->width)) + 1);
 88.1931 +         return;
 88.1932 +      }
 88.1933 +   }
 88.1934 +#endif
 88.1935 +
 88.1936 +   /* if we get here, we've just written the last row, so we need
 88.1937 +      to flush the compressor */
 88.1938 +   do
 88.1939 +   {
 88.1940 +      /* tell the compressor we are done */
 88.1941 +      ret = deflate(&png_ptr->zstream, Z_FINISH);
 88.1942 +      /* check for an error */
 88.1943 +      if (ret == Z_OK)
 88.1944 +      {
 88.1945 +         /* check to see if we need more room */
 88.1946 +         if (!(png_ptr->zstream.avail_out))
 88.1947 +         {
 88.1948 +            png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
 88.1949 +            png_ptr->zstream.next_out = png_ptr->zbuf;
 88.1950 +            png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
 88.1951 +         }
 88.1952 +      }
 88.1953 +      else if (ret != Z_STREAM_END)
 88.1954 +      {
 88.1955 +         if (png_ptr->zstream.msg != NULL)
 88.1956 +            png_error(png_ptr, png_ptr->zstream.msg);
 88.1957 +         else
 88.1958 +            png_error(png_ptr, "zlib error");
 88.1959 +      }
 88.1960 +   } while (ret != Z_STREAM_END);
 88.1961 +
 88.1962 +   /* write any extra space */
 88.1963 +   if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
 88.1964 +   {
 88.1965 +      png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
 88.1966 +         png_ptr->zstream.avail_out);
 88.1967 +   }
 88.1968 +
 88.1969 +   deflateReset(&png_ptr->zstream);
 88.1970 +   png_ptr->zstream.data_type = Z_BINARY;
 88.1971 +}
 88.1972 +
 88.1973 +#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
 88.1974 +/* Pick out the correct pixels for the interlace pass.
 88.1975 + * The basic idea here is to go through the row with a source
 88.1976 + * pointer and a destination pointer (sp and dp), and copy the
 88.1977 + * correct pixels for the pass.  As the row gets compacted,
 88.1978 + * sp will always be >= dp, so we should never overwrite anything.
 88.1979 + * See the default: case for the easiest code to understand.
 88.1980 + */
 88.1981 +void /* PRIVATE */
 88.1982 +png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
 88.1983 +{
 88.1984 +#ifdef PNG_USE_LOCAL_ARRAYS
 88.1985 +   /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
 88.1986 +
 88.1987 +   /* start of interlace block */
 88.1988 +   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
 88.1989 +
 88.1990 +   /* offset to next interlace block */
 88.1991 +   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
 88.1992 +#endif
 88.1993 +
 88.1994 +   png_debug(1, "in png_do_write_interlace\n");
 88.1995 +   /* we don't have to do anything on the last pass (6) */
 88.1996 +#if defined(PNG_USELESS_TESTS_SUPPORTED)
 88.1997 +   if (row != NULL && row_info != NULL && pass < 6)
 88.1998 +#else
 88.1999 +   if (pass < 6)
 88.2000 +#endif
 88.2001 +   {
 88.2002 +      /* each pixel depth is handled separately */
 88.2003 +      switch (row_info->pixel_depth)
 88.2004 +      {
 88.2005 +         case 1:
 88.2006 +         {
 88.2007 +            png_bytep sp;
 88.2008 +            png_bytep dp;
 88.2009 +            int shift;
 88.2010 +            int d;
 88.2011 +            int value;
 88.2012 +            png_uint_32 i;
 88.2013 +            png_uint_32 row_width = row_info->width;
 88.2014 +
 88.2015 +            dp = row;
 88.2016 +            d = 0;
 88.2017 +            shift = 7;
 88.2018 +            for (i = png_pass_start[pass]; i < row_width;
 88.2019 +               i += png_pass_inc[pass])
 88.2020 +            {
 88.2021 +               sp = row + (png_size_t)(i >> 3);
 88.2022 +               value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
 88.2023 +               d |= (value << shift);
 88.2024 +
 88.2025 +               if (shift == 0)
 88.2026 +               {
 88.2027 +                  shift = 7;
 88.2028 +                  *dp++ = (png_byte)d;
 88.2029 +                  d = 0;
 88.2030 +               }
 88.2031 +               else
 88.2032 +                  shift--;
 88.2033 +
 88.2034 +            }
 88.2035 +            if (shift != 7)
 88.2036 +               *dp = (png_byte)d;
 88.2037 +            break;
 88.2038 +         }
 88.2039 +         case 2:
 88.2040 +         {
 88.2041 +            png_bytep sp;
 88.2042 +            png_bytep dp;
 88.2043 +            int shift;
 88.2044 +            int d;
 88.2045 +            int value;
 88.2046 +            png_uint_32 i;
 88.2047 +            png_uint_32 row_width = row_info->width;
 88.2048 +
 88.2049 +            dp = row;
 88.2050 +            shift = 6;
 88.2051 +            d = 0;
 88.2052 +            for (i = png_pass_start[pass]; i < row_width;
 88.2053 +               i += png_pass_inc[pass])
 88.2054 +            {
 88.2055 +               sp = row + (png_size_t)(i >> 2);
 88.2056 +               value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
 88.2057 +               d |= (value << shift);
 88.2058 +
 88.2059 +               if (shift == 0)
 88.2060 +               {
 88.2061 +                  shift = 6;
 88.2062 +                  *dp++ = (png_byte)d;
 88.2063 +                  d = 0;
 88.2064 +               }
 88.2065 +               else
 88.2066 +                  shift -= 2;
 88.2067 +            }
 88.2068 +            if (shift != 6)
 88.2069 +                   *dp = (png_byte)d;
 88.2070 +            break;
 88.2071 +         }
 88.2072 +         case 4:
 88.2073 +         {
 88.2074 +            png_bytep sp;
 88.2075 +            png_bytep dp;
 88.2076 +            int shift;
 88.2077 +            int d;
 88.2078 +            int value;
 88.2079 +            png_uint_32 i;
 88.2080 +            png_uint_32 row_width = row_info->width;
 88.2081 +
 88.2082 +            dp = row;
 88.2083 +            shift = 4;
 88.2084 +            d = 0;
 88.2085 +            for (i = png_pass_start[pass]; i < row_width;
 88.2086 +               i += png_pass_inc[pass])
 88.2087 +            {
 88.2088 +               sp = row + (png_size_t)(i >> 1);
 88.2089 +               value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
 88.2090 +               d |= (value << shift);
 88.2091 +
 88.2092 +               if (shift == 0)
 88.2093 +               {
 88.2094 +                  shift = 4;
 88.2095 +                  *dp++ = (png_byte)d;
 88.2096 +                  d = 0;
 88.2097 +               }
 88.2098 +               else
 88.2099 +                  shift -= 4;
 88.2100 +            }
 88.2101 +            if (shift != 4)
 88.2102 +               *dp = (png_byte)d;
 88.2103 +            break;
 88.2104 +         }
 88.2105 +         default:
 88.2106 +         {
 88.2107 +            png_bytep sp;
 88.2108 +            png_bytep dp;
 88.2109 +            png_uint_32 i;
 88.2110 +            png_uint_32 row_width = row_info->width;
 88.2111 +            png_size_t pixel_bytes;
 88.2112 +
 88.2113 +            /* start at the beginning */
 88.2114 +            dp = row;
 88.2115 +            /* find out how many bytes each pixel takes up */
 88.2116 +            pixel_bytes = (row_info->pixel_depth >> 3);
 88.2117 +            /* loop through the row, only looking at the pixels that
 88.2118 +               matter */
 88.2119 +            for (i = png_pass_start[pass]; i < row_width;
 88.2120 +               i += png_pass_inc[pass])
 88.2121 +            {
 88.2122 +               /* find out where the original pixel is */
 88.2123 +               sp = row + (png_size_t)i * pixel_bytes;
 88.2124 +               /* move the pixel */
 88.2125 +               if (dp != sp)
 88.2126 +                  png_memcpy(dp, sp, pixel_bytes);
 88.2127 +               /* next pixel */
 88.2128 +               dp += pixel_bytes;
 88.2129 +            }
 88.2130 +            break;
 88.2131 +         }
 88.2132 +      }
 88.2133 +      /* set new row width */
 88.2134 +      row_info->width = (row_info->width +
 88.2135 +         png_pass_inc[pass] - 1 -
 88.2136 +         png_pass_start[pass]) /
 88.2137 +         png_pass_inc[pass];
 88.2138 +         row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
 88.2139 +            row_info->width);
 88.2140 +   }
 88.2141 +}
 88.2142 +#endif
 88.2143 +
 88.2144 +/* This filters the row, chooses which filter to use, if it has not already
 88.2145 + * been specified by the application, and then writes the row out with the
 88.2146 + * chosen filter.
 88.2147 + */
 88.2148 +#define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
 88.2149 +#define PNG_HISHIFT 10
 88.2150 +#define PNG_LOMASK ((png_uint_32)0xffffL)
 88.2151 +#define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
 88.2152 +void /* PRIVATE */
 88.2153 +png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
 88.2154 +{
 88.2155 +   png_bytep best_row;
 88.2156 +#ifndef PNG_NO_WRITE_FILTER
 88.2157 +   png_bytep prev_row, row_buf;
 88.2158 +   png_uint_32 mins, bpp;
 88.2159 +   png_byte filter_to_do = png_ptr->do_filter;
 88.2160 +   png_uint_32 row_bytes = row_info->rowbytes;
 88.2161 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2162 +   int num_p_filters = (int)png_ptr->num_prev_filters;
 88.2163 +#endif
 88.2164 +
 88.2165 +   png_debug(1, "in png_write_find_filter\n");
 88.2166 +   /* find out how many bytes offset each pixel is */
 88.2167 +   bpp = (row_info->pixel_depth + 7) >> 3;
 88.2168 +
 88.2169 +   prev_row = png_ptr->prev_row;
 88.2170 +#endif
 88.2171 +   best_row = png_ptr->row_buf;
 88.2172 +#ifndef PNG_NO_WRITE_FILTER
 88.2173 +   row_buf = best_row;
 88.2174 +   mins = PNG_MAXSUM;
 88.2175 +
 88.2176 +   /* The prediction method we use is to find which method provides the
 88.2177 +    * smallest value when summing the absolute values of the distances
 88.2178 +    * from zero, using anything >= 128 as negative numbers.  This is known
 88.2179 +    * as the "minimum sum of absolute differences" heuristic.  Other
 88.2180 +    * heuristics are the "weighted minimum sum of absolute differences"
 88.2181 +    * (experimental and can in theory improve compression), and the "zlib
 88.2182 +    * predictive" method (not implemented yet), which does test compressions
 88.2183 +    * of lines using different filter methods, and then chooses the
 88.2184 +    * (series of) filter(s) that give minimum compressed data size (VERY
 88.2185 +    * computationally expensive).
 88.2186 +    *
 88.2187 +    * GRR 980525:  consider also
 88.2188 +    *   (1) minimum sum of absolute differences from running average (i.e.,
 88.2189 +    *       keep running sum of non-absolute differences & count of bytes)
 88.2190 +    *       [track dispersion, too?  restart average if dispersion too large?]
 88.2191 +    *  (1b) minimum sum of absolute differences from sliding average, probably
 88.2192 +    *       with window size <= deflate window (usually 32K)
 88.2193 +    *   (2) minimum sum of squared differences from zero or running average
 88.2194 +    *       (i.e., ~ root-mean-square approach)
 88.2195 +    */
 88.2196 +
 88.2197 +
 88.2198 +   /* We don't need to test the 'no filter' case if this is the only filter
 88.2199 +    * that has been chosen, as it doesn't actually do anything to the data.
 88.2200 +    */
 88.2201 +   if ((filter_to_do & PNG_FILTER_NONE) &&
 88.2202 +       filter_to_do != PNG_FILTER_NONE)
 88.2203 +   {
 88.2204 +      png_bytep rp;
 88.2205 +      png_uint_32 sum = 0;
 88.2206 +      png_uint_32 i;
 88.2207 +      int v;
 88.2208 +
 88.2209 +      for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
 88.2210 +      {
 88.2211 +         v = *rp;
 88.2212 +         sum += (v < 128) ? v : 256 - v;
 88.2213 +      }
 88.2214 +
 88.2215 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2216 +      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
 88.2217 +      {
 88.2218 +         png_uint_32 sumhi, sumlo;
 88.2219 +         int j;
 88.2220 +         sumlo = sum & PNG_LOMASK;
 88.2221 +         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
 88.2222 +
 88.2223 +         /* Reduce the sum if we match any of the previous rows */
 88.2224 +         for (j = 0; j < num_p_filters; j++)
 88.2225 +         {
 88.2226 +            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
 88.2227 +            {
 88.2228 +               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
 88.2229 +                  PNG_WEIGHT_SHIFT;
 88.2230 +               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
 88.2231 +                  PNG_WEIGHT_SHIFT;
 88.2232 +            }
 88.2233 +         }
 88.2234 +
 88.2235 +         /* Factor in the cost of this filter (this is here for completeness,
 88.2236 +          * but it makes no sense to have a "cost" for the NONE filter, as
 88.2237 +          * it has the minimum possible computational cost - none).
 88.2238 +          */
 88.2239 +         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
 88.2240 +            PNG_COST_SHIFT;
 88.2241 +         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
 88.2242 +            PNG_COST_SHIFT;
 88.2243 +
 88.2244 +         if (sumhi > PNG_HIMASK)
 88.2245 +            sum = PNG_MAXSUM;
 88.2246 +         else
 88.2247 +            sum = (sumhi << PNG_HISHIFT) + sumlo;
 88.2248 +      }
 88.2249 +#endif
 88.2250 +      mins = sum;
 88.2251 +   }
 88.2252 +
 88.2253 +   /* sub filter */
 88.2254 +   if (filter_to_do == PNG_FILTER_SUB)
 88.2255 +   /* it's the only filter so no testing is needed */
 88.2256 +   {
 88.2257 +      png_bytep rp, lp, dp;
 88.2258 +      png_uint_32 i;
 88.2259 +      for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
 88.2260 +           i++, rp++, dp++)
 88.2261 +      {
 88.2262 +         *dp = *rp;
 88.2263 +      }
 88.2264 +      for (lp = row_buf + 1; i < row_bytes;
 88.2265 +         i++, rp++, lp++, dp++)
 88.2266 +      {
 88.2267 +         *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
 88.2268 +      }
 88.2269 +      best_row = png_ptr->sub_row;
 88.2270 +   }
 88.2271 +
 88.2272 +   else if (filter_to_do & PNG_FILTER_SUB)
 88.2273 +   {
 88.2274 +      png_bytep rp, dp, lp;
 88.2275 +      png_uint_32 sum = 0, lmins = mins;
 88.2276 +      png_uint_32 i;
 88.2277 +      int v;
 88.2278 +
 88.2279 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2280 +      /* We temporarily increase the "minimum sum" by the factor we
 88.2281 +       * would reduce the sum of this filter, so that we can do the
 88.2282 +       * early exit comparison without scaling the sum each time.
 88.2283 +       */
 88.2284 +      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
 88.2285 +      {
 88.2286 +         int j;
 88.2287 +         png_uint_32 lmhi, lmlo;
 88.2288 +         lmlo = lmins & PNG_LOMASK;
 88.2289 +         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
 88.2290 +
 88.2291 +         for (j = 0; j < num_p_filters; j++)
 88.2292 +         {
 88.2293 +            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
 88.2294 +            {
 88.2295 +               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
 88.2296 +                  PNG_WEIGHT_SHIFT;
 88.2297 +               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
 88.2298 +                  PNG_WEIGHT_SHIFT;
 88.2299 +            }
 88.2300 +         }
 88.2301 +
 88.2302 +         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
 88.2303 +            PNG_COST_SHIFT;
 88.2304 +         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
 88.2305 +            PNG_COST_SHIFT;
 88.2306 +
 88.2307 +         if (lmhi > PNG_HIMASK)
 88.2308 +            lmins = PNG_MAXSUM;
 88.2309 +         else
 88.2310 +            lmins = (lmhi << PNG_HISHIFT) + lmlo;
 88.2311 +      }
 88.2312 +#endif
 88.2313 +
 88.2314 +      for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
 88.2315 +           i++, rp++, dp++)
 88.2316 +      {
 88.2317 +         v = *dp = *rp;
 88.2318 +
 88.2319 +         sum += (v < 128) ? v : 256 - v;
 88.2320 +      }
 88.2321 +      for (lp = row_buf + 1; i < row_bytes;
 88.2322 +         i++, rp++, lp++, dp++)
 88.2323 +      {
 88.2324 +         v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
 88.2325 +
 88.2326 +         sum += (v < 128) ? v : 256 - v;
 88.2327 +
 88.2328 +         if (sum > lmins)  /* We are already worse, don't continue. */
 88.2329 +            break;
 88.2330 +      }
 88.2331 +
 88.2332 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2333 +      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
 88.2334 +      {
 88.2335 +         int j;
 88.2336 +         png_uint_32 sumhi, sumlo;
 88.2337 +         sumlo = sum & PNG_LOMASK;
 88.2338 +         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
 88.2339 +
 88.2340 +         for (j = 0; j < num_p_filters; j++)
 88.2341 +         {
 88.2342 +            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
 88.2343 +            {
 88.2344 +               sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
 88.2345 +                  PNG_WEIGHT_SHIFT;
 88.2346 +               sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
 88.2347 +                  PNG_WEIGHT_SHIFT;
 88.2348 +            }
 88.2349 +         }
 88.2350 +
 88.2351 +         sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
 88.2352 +            PNG_COST_SHIFT;
 88.2353 +         sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
 88.2354 +            PNG_COST_SHIFT;
 88.2355 +
 88.2356 +         if (sumhi > PNG_HIMASK)
 88.2357 +            sum = PNG_MAXSUM;
 88.2358 +         else
 88.2359 +            sum = (sumhi << PNG_HISHIFT) + sumlo;
 88.2360 +      }
 88.2361 +#endif
 88.2362 +
 88.2363 +      if (sum < mins)
 88.2364 +      {
 88.2365 +         mins = sum;
 88.2366 +         best_row = png_ptr->sub_row;
 88.2367 +      }
 88.2368 +   }
 88.2369 +
 88.2370 +   /* up filter */
 88.2371 +   if (filter_to_do == PNG_FILTER_UP)
 88.2372 +   {
 88.2373 +      png_bytep rp, dp, pp;
 88.2374 +      png_uint_32 i;
 88.2375 +
 88.2376 +      for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
 88.2377 +           pp = prev_row + 1; i < row_bytes;
 88.2378 +           i++, rp++, pp++, dp++)
 88.2379 +      {
 88.2380 +         *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
 88.2381 +      }
 88.2382 +      best_row = png_ptr->up_row;
 88.2383 +   }
 88.2384 +
 88.2385 +   else if (filter_to_do & PNG_FILTER_UP)
 88.2386 +   {
 88.2387 +      png_bytep rp, dp, pp;
 88.2388 +      png_uint_32 sum = 0, lmins = mins;
 88.2389 +      png_uint_32 i;
 88.2390 +      int v;
 88.2391 +
 88.2392 +
 88.2393 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2394 +      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
 88.2395 +      {
 88.2396 +         int j;
 88.2397 +         png_uint_32 lmhi, lmlo;
 88.2398 +         lmlo = lmins & PNG_LOMASK;
 88.2399 +         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
 88.2400 +
 88.2401 +         for (j = 0; j < num_p_filters; j++)
 88.2402 +         {
 88.2403 +            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
 88.2404 +            {
 88.2405 +               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
 88.2406 +                  PNG_WEIGHT_SHIFT;
 88.2407 +               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
 88.2408 +                  PNG_WEIGHT_SHIFT;
 88.2409 +            }
 88.2410 +         }
 88.2411 +
 88.2412 +         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
 88.2413 +            PNG_COST_SHIFT;
 88.2414 +         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
 88.2415 +            PNG_COST_SHIFT;
 88.2416 +
 88.2417 +         if (lmhi > PNG_HIMASK)
 88.2418 +            lmins = PNG_MAXSUM;
 88.2419 +         else
 88.2420 +            lmins = (lmhi << PNG_HISHIFT) + lmlo;
 88.2421 +      }
 88.2422 +#endif
 88.2423 +
 88.2424 +      for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
 88.2425 +           pp = prev_row + 1; i < row_bytes; i++)
 88.2426 +      {
 88.2427 +         v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
 88.2428 +
 88.2429 +         sum += (v < 128) ? v : 256 - v;
 88.2430 +
 88.2431 +         if (sum > lmins)  /* We are already worse, don't continue. */
 88.2432 +            break;
 88.2433 +      }
 88.2434 +
 88.2435 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2436 +      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
 88.2437 +      {
 88.2438 +         int j;
 88.2439 +         png_uint_32 sumhi, sumlo;
 88.2440 +         sumlo = sum & PNG_LOMASK;
 88.2441 +         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
 88.2442 +
 88.2443 +         for (j = 0; j < num_p_filters; j++)
 88.2444 +         {
 88.2445 +            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
 88.2446 +            {
 88.2447 +               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
 88.2448 +                  PNG_WEIGHT_SHIFT;
 88.2449 +               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
 88.2450 +                  PNG_WEIGHT_SHIFT;
 88.2451 +            }
 88.2452 +         }
 88.2453 +
 88.2454 +         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
 88.2455 +            PNG_COST_SHIFT;
 88.2456 +         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
 88.2457 +            PNG_COST_SHIFT;
 88.2458 +
 88.2459 +         if (sumhi > PNG_HIMASK)
 88.2460 +            sum = PNG_MAXSUM;
 88.2461 +         else
 88.2462 +            sum = (sumhi << PNG_HISHIFT) + sumlo;
 88.2463 +      }
 88.2464 +#endif
 88.2465 +
 88.2466 +      if (sum < mins)
 88.2467 +      {
 88.2468 +         mins = sum;
 88.2469 +         best_row = png_ptr->up_row;
 88.2470 +      }
 88.2471 +   }
 88.2472 +
 88.2473 +   /* avg filter */
 88.2474 +   if (filter_to_do == PNG_FILTER_AVG)
 88.2475 +   {
 88.2476 +      png_bytep rp, dp, pp, lp;
 88.2477 +      png_uint_32 i;
 88.2478 +      for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
 88.2479 +           pp = prev_row + 1; i < bpp; i++)
 88.2480 +      {
 88.2481 +         *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
 88.2482 +      }
 88.2483 +      for (lp = row_buf + 1; i < row_bytes; i++)
 88.2484 +      {
 88.2485 +         *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
 88.2486 +                 & 0xff);
 88.2487 +      }
 88.2488 +      best_row = png_ptr->avg_row;
 88.2489 +   }
 88.2490 +
 88.2491 +   else if (filter_to_do & PNG_FILTER_AVG)
 88.2492 +   {
 88.2493 +      png_bytep rp, dp, pp, lp;
 88.2494 +      png_uint_32 sum = 0, lmins = mins;
 88.2495 +      png_uint_32 i;
 88.2496 +      int v;
 88.2497 +
 88.2498 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2499 +      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
 88.2500 +      {
 88.2501 +         int j;
 88.2502 +         png_uint_32 lmhi, lmlo;
 88.2503 +         lmlo = lmins & PNG_LOMASK;
 88.2504 +         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
 88.2505 +
 88.2506 +         for (j = 0; j < num_p_filters; j++)
 88.2507 +         {
 88.2508 +            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
 88.2509 +            {
 88.2510 +               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
 88.2511 +                  PNG_WEIGHT_SHIFT;
 88.2512 +               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
 88.2513 +                  PNG_WEIGHT_SHIFT;
 88.2514 +            }
 88.2515 +         }
 88.2516 +
 88.2517 +         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
 88.2518 +            PNG_COST_SHIFT;
 88.2519 +         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
 88.2520 +            PNG_COST_SHIFT;
 88.2521 +
 88.2522 +         if (lmhi > PNG_HIMASK)
 88.2523 +            lmins = PNG_MAXSUM;
 88.2524 +         else
 88.2525 +            lmins = (lmhi << PNG_HISHIFT) + lmlo;
 88.2526 +      }
 88.2527 +#endif
 88.2528 +
 88.2529 +      for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
 88.2530 +           pp = prev_row + 1; i < bpp; i++)
 88.2531 +      {
 88.2532 +         v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
 88.2533 +
 88.2534 +         sum += (v < 128) ? v : 256 - v;
 88.2535 +      }
 88.2536 +      for (lp = row_buf + 1; i < row_bytes; i++)
 88.2537 +      {
 88.2538 +         v = *dp++ =
 88.2539 +          (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
 88.2540 +
 88.2541 +         sum += (v < 128) ? v : 256 - v;
 88.2542 +
 88.2543 +         if (sum > lmins)  /* We are already worse, don't continue. */
 88.2544 +            break;
 88.2545 +      }
 88.2546 +
 88.2547 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2548 +      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
 88.2549 +      {
 88.2550 +         int j;
 88.2551 +         png_uint_32 sumhi, sumlo;
 88.2552 +         sumlo = sum & PNG_LOMASK;
 88.2553 +         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
 88.2554 +
 88.2555 +         for (j = 0; j < num_p_filters; j++)
 88.2556 +         {
 88.2557 +            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
 88.2558 +            {
 88.2559 +               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
 88.2560 +                  PNG_WEIGHT_SHIFT;
 88.2561 +               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
 88.2562 +                  PNG_WEIGHT_SHIFT;
 88.2563 +            }
 88.2564 +         }
 88.2565 +
 88.2566 +         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
 88.2567 +            PNG_COST_SHIFT;
 88.2568 +         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
 88.2569 +            PNG_COST_SHIFT;
 88.2570 +
 88.2571 +         if (sumhi > PNG_HIMASK)
 88.2572 +            sum = PNG_MAXSUM;
 88.2573 +         else
 88.2574 +            sum = (sumhi << PNG_HISHIFT) + sumlo;
 88.2575 +      }
 88.2576 +#endif
 88.2577 +
 88.2578 +      if (sum < mins)
 88.2579 +      {
 88.2580 +         mins = sum;
 88.2581 +         best_row = png_ptr->avg_row;
 88.2582 +      }
 88.2583 +   }
 88.2584 +
 88.2585 +   /* Paeth filter */
 88.2586 +   if (filter_to_do == PNG_FILTER_PAETH)
 88.2587 +   {
 88.2588 +      png_bytep rp, dp, pp, cp, lp;
 88.2589 +      png_uint_32 i;
 88.2590 +      for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
 88.2591 +           pp = prev_row + 1; i < bpp; i++)
 88.2592 +      {
 88.2593 +         *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
 88.2594 +      }
 88.2595 +
 88.2596 +      for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
 88.2597 +      {
 88.2598 +         int a, b, c, pa, pb, pc, p;
 88.2599 +
 88.2600 +         b = *pp++;
 88.2601 +         c = *cp++;
 88.2602 +         a = *lp++;
 88.2603 +
 88.2604 +         p = b - c;
 88.2605 +         pc = a - c;
 88.2606 +
 88.2607 +#ifdef PNG_USE_ABS
 88.2608 +         pa = abs(p);
 88.2609 +         pb = abs(pc);
 88.2610 +         pc = abs(p + pc);
 88.2611 +#else
 88.2612 +         pa = p < 0 ? -p : p;
 88.2613 +         pb = pc < 0 ? -pc : pc;
 88.2614 +         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
 88.2615 +#endif
 88.2616 +
 88.2617 +         p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
 88.2618 +
 88.2619 +         *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
 88.2620 +      }
 88.2621 +      best_row = png_ptr->paeth_row;
 88.2622 +   }
 88.2623 +
 88.2624 +   else if (filter_to_do & PNG_FILTER_PAETH)
 88.2625 +   {
 88.2626 +      png_bytep rp, dp, pp, cp, lp;
 88.2627 +      png_uint_32 sum = 0, lmins = mins;
 88.2628 +      png_uint_32 i;
 88.2629 +      int v;
 88.2630 +
 88.2631 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2632 +      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
 88.2633 +      {
 88.2634 +         int j;
 88.2635 +         png_uint_32 lmhi, lmlo;
 88.2636 +         lmlo = lmins & PNG_LOMASK;
 88.2637 +         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
 88.2638 +
 88.2639 +         for (j = 0; j < num_p_filters; j++)
 88.2640 +         {
 88.2641 +            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
 88.2642 +            {
 88.2643 +               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
 88.2644 +                  PNG_WEIGHT_SHIFT;
 88.2645 +               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
 88.2646 +                  PNG_WEIGHT_SHIFT;
 88.2647 +            }
 88.2648 +         }
 88.2649 +
 88.2650 +         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
 88.2651 +            PNG_COST_SHIFT;
 88.2652 +         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
 88.2653 +            PNG_COST_SHIFT;
 88.2654 +
 88.2655 +         if (lmhi > PNG_HIMASK)
 88.2656 +            lmins = PNG_MAXSUM;
 88.2657 +         else
 88.2658 +            lmins = (lmhi << PNG_HISHIFT) + lmlo;
 88.2659 +      }
 88.2660 +#endif
 88.2661 +
 88.2662 +      for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
 88.2663 +           pp = prev_row + 1; i < bpp; i++)
 88.2664 +      {
 88.2665 +         v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
 88.2666 +
 88.2667 +         sum += (v < 128) ? v : 256 - v;
 88.2668 +      }
 88.2669 +
 88.2670 +      for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
 88.2671 +      {
 88.2672 +         int a, b, c, pa, pb, pc, p;
 88.2673 +
 88.2674 +         b = *pp++;
 88.2675 +         c = *cp++;
 88.2676 +         a = *lp++;
 88.2677 +
 88.2678 +#ifndef PNG_SLOW_PAETH
 88.2679 +         p = b - c;
 88.2680 +         pc = a - c;
 88.2681 +#ifdef PNG_USE_ABS
 88.2682 +         pa = abs(p);
 88.2683 +         pb = abs(pc);
 88.2684 +         pc = abs(p + pc);
 88.2685 +#else
 88.2686 +         pa = p < 0 ? -p : p;
 88.2687 +         pb = pc < 0 ? -pc : pc;
 88.2688 +         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
 88.2689 +#endif
 88.2690 +         p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
 88.2691 +#else /* PNG_SLOW_PAETH */
 88.2692 +         p = a + b - c;
 88.2693 +         pa = abs(p - a);
 88.2694 +         pb = abs(p - b);
 88.2695 +         pc = abs(p - c);
 88.2696 +         if (pa <= pb && pa <= pc)
 88.2697 +            p = a;
 88.2698 +         else if (pb <= pc)
 88.2699 +            p = b;
 88.2700 +         else
 88.2701 +            p = c;
 88.2702 +#endif /* PNG_SLOW_PAETH */
 88.2703 +
 88.2704 +         v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
 88.2705 +
 88.2706 +         sum += (v < 128) ? v : 256 - v;
 88.2707 +
 88.2708 +         if (sum > lmins)  /* We are already worse, don't continue. */
 88.2709 +            break;
 88.2710 +      }
 88.2711 +
 88.2712 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2713 +      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
 88.2714 +      {
 88.2715 +         int j;
 88.2716 +         png_uint_32 sumhi, sumlo;
 88.2717 +         sumlo = sum & PNG_LOMASK;
 88.2718 +         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
 88.2719 +
 88.2720 +         for (j = 0; j < num_p_filters; j++)
 88.2721 +         {
 88.2722 +            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
 88.2723 +            {
 88.2724 +               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
 88.2725 +                  PNG_WEIGHT_SHIFT;
 88.2726 +               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
 88.2727 +                  PNG_WEIGHT_SHIFT;
 88.2728 +            }
 88.2729 +         }
 88.2730 +
 88.2731 +         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
 88.2732 +            PNG_COST_SHIFT;
 88.2733 +         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
 88.2734 +            PNG_COST_SHIFT;
 88.2735 +
 88.2736 +         if (sumhi > PNG_HIMASK)
 88.2737 +            sum = PNG_MAXSUM;
 88.2738 +         else
 88.2739 +            sum = (sumhi << PNG_HISHIFT) + sumlo;
 88.2740 +      }
 88.2741 +#endif
 88.2742 +
 88.2743 +      if (sum < mins)
 88.2744 +      {
 88.2745 +         best_row = png_ptr->paeth_row;
 88.2746 +      }
 88.2747 +   }
 88.2748 +#endif /* PNG_NO_WRITE_FILTER */
 88.2749 +   /* Do the actual writing of the filtered row data from the chosen filter. */
 88.2750 +
 88.2751 +   png_write_filtered_row(png_ptr, best_row);
 88.2752 +
 88.2753 +#ifndef PNG_NO_WRITE_FILTER
 88.2754 +#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
 88.2755 +   /* Save the type of filter we picked this time for future calculations */
 88.2756 +   if (png_ptr->num_prev_filters > 0)
 88.2757 +   {
 88.2758 +      int j;
 88.2759 +      for (j = 1; j < num_p_filters; j++)
 88.2760 +      {
 88.2761 +         png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
 88.2762 +      }
 88.2763 +      png_ptr->prev_filters[j] = best_row[0];
 88.2764 +   }
 88.2765 +#endif
 88.2766 +#endif /* PNG_NO_WRITE_FILTER */
 88.2767 +}
 88.2768 +
 88.2769 +
 88.2770 +/* Do the actual writing of a previously filtered row. */
 88.2771 +void /* PRIVATE */
 88.2772 +png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
 88.2773 +{
 88.2774 +   png_debug(1, "in png_write_filtered_row\n");
 88.2775 +   png_debug1(2, "filter = %d\n", filtered_row[0]);
 88.2776 +   /* set up the zlib input buffer */
 88.2777 +
 88.2778 +   png_ptr->zstream.next_in = filtered_row;
 88.2779 +   png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
 88.2780 +   /* repeat until we have compressed all the data */
 88.2781 +   do
 88.2782 +   {
 88.2783 +      int ret; /* return of zlib */
 88.2784 +
 88.2785 +      /* compress the data */
 88.2786 +      ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
 88.2787 +      /* check for compression errors */
 88.2788 +      if (ret != Z_OK)
 88.2789 +      {
 88.2790 +         if (png_ptr->zstream.msg != NULL)
 88.2791 +            png_error(png_ptr, png_ptr->zstream.msg);
 88.2792 +         else
 88.2793 +            png_error(png_ptr, "zlib error");
 88.2794 +      }
 88.2795 +
 88.2796 +      /* see if it is time to write another IDAT */
 88.2797 +      if (!(png_ptr->zstream.avail_out))
 88.2798 +      {
 88.2799 +         /* write the IDAT and reset the zlib output buffer */
 88.2800 +         png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
 88.2801 +         png_ptr->zstream.next_out = png_ptr->zbuf;
 88.2802 +         png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
 88.2803 +      }
 88.2804 +   /* repeat until all data has been compressed */
 88.2805 +   } while (png_ptr->zstream.avail_in);
 88.2806 +
 88.2807 +   /* swap the current and previous rows */
 88.2808 +   if (png_ptr->prev_row != NULL)
 88.2809 +   {
 88.2810 +      png_bytep tptr;
 88.2811 +
 88.2812 +      tptr = png_ptr->prev_row;
 88.2813 +      png_ptr->prev_row = png_ptr->row_buf;
 88.2814 +      png_ptr->row_buf = tptr;
 88.2815 +   }
 88.2816 +
 88.2817 +   /* finish row - updates counters and flushes zlib if last row */
 88.2818 +   png_write_finish_row(png_ptr);
 88.2819 +
 88.2820 +#if defined(PNG_WRITE_FLUSH_SUPPORTED)
 88.2821 +   png_ptr->flush_rows++;
 88.2822 +
 88.2823 +   if (png_ptr->flush_dist > 0 &&
 88.2824 +       png_ptr->flush_rows >= png_ptr->flush_dist)
 88.2825 +   {
 88.2826 +      png_write_flush(png_ptr);
 88.2827 +   }
 88.2828 +#endif
 88.2829 +}
 88.2830 +#endif /* PNG_WRITE_SUPPORTED */
    89.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    89.2 +++ b/libs/zlib/adler32.c	Thu Sep 08 06:28:38 2011 +0300
    89.3 @@ -0,0 +1,149 @@
    89.4 +/* adler32.c -- compute the Adler-32 checksum of a data stream
    89.5 + * Copyright (C) 1995-2004 Mark Adler
    89.6 + * For conditions of distribution and use, see copyright notice in zlib.h
    89.7 + */
    89.8 +
    89.9 +/* @(#) $Id$ */
   89.10 +
   89.11 +#define ZLIB_INTERNAL
   89.12 +#include "zlib.h"
   89.13 +
   89.14 +#define BASE 65521UL    /* largest prime smaller than 65536 */
   89.15 +#define NMAX 5552
   89.16 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
   89.17 +
   89.18 +#define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}
   89.19 +#define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);
   89.20 +#define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);
   89.21 +#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
   89.22 +#define DO16(buf)   DO8(buf,0); DO8(buf,8);
   89.23 +
   89.24 +/* use NO_DIVIDE if your processor does not do division in hardware */
   89.25 +#ifdef NO_DIVIDE
   89.26 +#  define MOD(a) \
   89.27 +    do { \
   89.28 +        if (a >= (BASE << 16)) a -= (BASE << 16); \
   89.29 +        if (a >= (BASE << 15)) a -= (BASE << 15); \
   89.30 +        if (a >= (BASE << 14)) a -= (BASE << 14); \
   89.31 +        if (a >= (BASE << 13)) a -= (BASE << 13); \
   89.32 +        if (a >= (BASE << 12)) a -= (BASE << 12); \
   89.33 +        if (a >= (BASE << 11)) a -= (BASE << 11); \
   89.34 +        if (a >= (BASE << 10)) a -= (BASE << 10); \
   89.35 +        if (a >= (BASE << 9)) a -= (BASE << 9); \
   89.36 +        if (a >= (BASE << 8)) a -= (BASE << 8); \
   89.37 +        if (a >= (BASE << 7)) a -= (BASE << 7); \
   89.38 +        if (a >= (BASE << 6)) a -= (BASE << 6); \
   89.39 +        if (a >= (BASE << 5)) a -= (BASE << 5); \
   89.40 +        if (a >= (BASE << 4)) a -= (BASE << 4); \
   89.41 +        if (a >= (BASE << 3)) a -= (BASE << 3); \
   89.42 +        if (a >= (BASE << 2)) a -= (BASE << 2); \
   89.43 +        if (a >= (BASE << 1)) a -= (BASE << 1); \
   89.44 +        if (a >= BASE) a -= BASE; \
   89.45 +    } while (0)
   89.46 +#  define MOD4(a) \
   89.47 +    do { \
   89.48 +        if (a >= (BASE << 4)) a -= (BASE << 4); \
   89.49 +        if (a >= (BASE << 3)) a -= (BASE << 3); \
   89.50 +        if (a >= (BASE << 2)) a -= (BASE << 2); \
   89.51 +        if (a >= (BASE << 1)) a -= (BASE << 1); \
   89.52 +        if (a >= BASE) a -= BASE; \
   89.53 +    } while (0)
   89.54 +#else
   89.55 +#  define MOD(a) a %= BASE
   89.56 +#  define MOD4(a) a %= BASE
   89.57 +#endif
   89.58 +
   89.59 +/* ========================================================================= */
   89.60 +uLong ZEXPORT adler32(adler, buf, len)
   89.61 +    uLong adler;
   89.62 +    const Bytef *buf;
   89.63 +    uInt len;
   89.64 +{
   89.65 +    unsigned long sum2;
   89.66 +    unsigned n;
   89.67 +
   89.68 +    /* split Adler-32 into component sums */
   89.69 +    sum2 = (adler >> 16) & 0xffff;
   89.70 +    adler &= 0xffff;
   89.71 +
   89.72 +    /* in case user likes doing a byte at a time, keep it fast */
   89.73 +    if (len == 1) {
   89.74 +        adler += buf[0];
   89.75 +        if (adler >= BASE)
   89.76 +            adler -= BASE;
   89.77 +        sum2 += adler;
   89.78 +        if (sum2 >= BASE)
   89.79 +            sum2 -= BASE;
   89.80 +        return adler | (sum2 << 16);
   89.81 +    }
   89.82 +
   89.83 +    /* initial Adler-32 value (deferred check for len == 1 speed) */
   89.84 +    if (buf == Z_NULL)
   89.85 +        return 1L;
   89.86 +
   89.87 +    /* in case short lengths are provided, keep it somewhat fast */
   89.88 +    if (len < 16) {
   89.89 +        while (len--) {
   89.90 +            adler += *buf++;
   89.91 +            sum2 += adler;
   89.92 +        }
   89.93 +        if (adler >= BASE)
   89.94 +            adler -= BASE;
   89.95 +        MOD4(sum2);             /* only added so many BASE's */
   89.96 +        return adler | (sum2 << 16);
   89.97 +    }
   89.98 +
   89.99 +    /* do length NMAX blocks -- requires just one modulo operation */
  89.100 +    while (len >= NMAX) {
  89.101 +        len -= NMAX;
  89.102 +        n = NMAX / 16;          /* NMAX is divisible by 16 */
  89.103 +        do {
  89.104 +            DO16(buf);          /* 16 sums unrolled */
  89.105 +            buf += 16;
  89.106 +        } while (--n);
  89.107 +        MOD(adler);
  89.108 +        MOD(sum2);
  89.109 +    }
  89.110 +
  89.111 +    /* do remaining bytes (less than NMAX, still just one modulo) */
  89.112 +    if (len) {                  /* avoid modulos if none remaining */
  89.113 +        while (len >= 16) {
  89.114 +            len -= 16;
  89.115 +            DO16(buf);
  89.116 +            buf += 16;
  89.117 +        }
  89.118 +        while (len--) {
  89.119 +            adler += *buf++;
  89.120 +            sum2 += adler;
  89.121 +        }
  89.122 +        MOD(adler);
  89.123 +        MOD(sum2);
  89.124 +    }
  89.125 +
  89.126 +    /* return recombined sums */
  89.127 +    return adler | (sum2 << 16);
  89.128 +}
  89.129 +
  89.130 +/* ========================================================================= */
  89.131 +uLong ZEXPORT adler32_combine(adler1, adler2, len2)
  89.132 +    uLong adler1;
  89.133 +    uLong adler2;
  89.134 +    z_off_t len2;
  89.135 +{
  89.136 +    unsigned long sum1;
  89.137 +    unsigned long sum2;
  89.138 +    unsigned rem;
  89.139 +
  89.140 +    /* the derivation of this formula is left as an exercise for the reader */
  89.141 +    rem = (unsigned)(len2 % BASE);
  89.142 +    sum1 = adler1 & 0xffff;
  89.143 +    sum2 = rem * sum1;
  89.144 +    MOD(sum2);
  89.145 +    sum1 += (adler2 & 0xffff) + BASE - 1;
  89.146 +    sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  89.147 +    if (sum1 > BASE) sum1 -= BASE;
  89.148 +    if (sum1 > BASE) sum1 -= BASE;
  89.149 +    if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  89.150 +    if (sum2 > BASE) sum2 -= BASE;
  89.151 +    return sum1 | (sum2 << 16);
  89.152 +}
    90.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    90.2 +++ b/libs/zlib/compress.c	Thu Sep 08 06:28:38 2011 +0300
    90.3 @@ -0,0 +1,79 @@
    90.4 +/* compress.c -- compress a memory buffer
    90.5 + * Copyright (C) 1995-2003 Jean-loup Gailly.
    90.6 + * For conditions of distribution and use, see copyright notice in zlib.h
    90.7 + */
    90.8 +
    90.9 +/* @(#) $Id$ */
   90.10 +
   90.11 +#define ZLIB_INTERNAL
   90.12 +#include "zlib.h"
   90.13 +
   90.14 +/* ===========================================================================
   90.15 +     Compresses the source buffer into the destination buffer. The level
   90.16 +   parameter has the same meaning as in deflateInit.  sourceLen is the byte
   90.17 +   length of the source buffer. Upon entry, destLen is the total size of the
   90.18 +   destination buffer, which must be at least 0.1% larger than sourceLen plus
   90.19 +   12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
   90.20 +
   90.21 +     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
   90.22 +   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
   90.23 +   Z_STREAM_ERROR if the level parameter is invalid.
   90.24 +*/
   90.25 +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
   90.26 +    Bytef *dest;
   90.27 +    uLongf *destLen;
   90.28 +    const Bytef *source;
   90.29 +    uLong sourceLen;
   90.30 +    int level;
   90.31 +{
   90.32 +    z_stream stream;
   90.33 +    int err;
   90.34 +
   90.35 +    stream.next_in = (Bytef*)source;
   90.36 +    stream.avail_in = (uInt)sourceLen;
   90.37 +#ifdef MAXSEG_64K
   90.38 +    /* Check for source > 64K on 16-bit machine: */
   90.39 +    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
   90.40 +#endif
   90.41 +    stream.next_out = dest;
   90.42 +    stream.avail_out = (uInt)*destLen;
   90.43 +    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
   90.44 +
   90.45 +    stream.zalloc = (alloc_func)0;
   90.46 +    stream.zfree = (free_func)0;
   90.47 +    stream.opaque = (voidpf)0;
   90.48 +
   90.49 +    err = deflateInit(&stream, level);
   90.50 +    if (err != Z_OK) return err;
   90.51 +
   90.52 +    err = deflate(&stream, Z_FINISH);
   90.53 +    if (err != Z_STREAM_END) {
   90.54 +        deflateEnd(&stream);
   90.55 +        return err == Z_OK ? Z_BUF_ERROR : err;
   90.56 +    }
   90.57 +    *destLen = stream.total_out;
   90.58 +
   90.59 +    err = deflateEnd(&stream);
   90.60 +    return err;
   90.61 +}
   90.62 +
   90.63 +/* ===========================================================================
   90.64 + */
   90.65 +int ZEXPORT compress (dest, destLen, source, sourceLen)
   90.66 +    Bytef *dest;
   90.67 +    uLongf *destLen;
   90.68 +    const Bytef *source;
   90.69 +    uLong sourceLen;
   90.70 +{
   90.71 +    return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
   90.72 +}
   90.73 +
   90.74 +/* ===========================================================================
   90.75 +     If the default memLevel or windowBits for deflateInit() is changed, then
   90.76 +   this function needs to be updated.
   90.77 + */
   90.78 +uLong ZEXPORT compressBound (sourceLen)
   90.79 +    uLong sourceLen;
   90.80 +{
   90.81 +    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
   90.82 +}
    91.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    91.2 +++ b/libs/zlib/crc32.c	Thu Sep 08 06:28:38 2011 +0300
    91.3 @@ -0,0 +1,423 @@
    91.4 +/* crc32.c -- compute the CRC-32 of a data stream
    91.5 + * Copyright (C) 1995-2005 Mark Adler
    91.6 + * For conditions of distribution and use, see copyright notice in zlib.h
    91.7 + *
    91.8 + * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
    91.9 + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
   91.10 + * tables for updating the shift register in one step with three exclusive-ors
   91.11 + * instead of four steps with four exclusive-ors.  This results in about a
   91.12 + * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
   91.13 + */
   91.14 +
   91.15 +/* @(#) $Id$ */
   91.16 +
   91.17 +/*
   91.18 +  Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
   91.19 +  protection on the static variables used to control the first-use generation
   91.20 +  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should
   91.21 +  first call get_crc_table() to initialize the tables before allowing more than
   91.22 +  one thread to use crc32().
   91.23 + */
   91.24 +
   91.25 +#ifdef MAKECRCH
   91.26 +#  include <stdio.h>
   91.27 +#  ifndef DYNAMIC_CRC_TABLE
   91.28 +#    define DYNAMIC_CRC_TABLE
   91.29 +#  endif /* !DYNAMIC_CRC_TABLE */
   91.30 +#endif /* MAKECRCH */
   91.31 +
   91.32 +#include "zutil.h"      /* for STDC and FAR definitions */
   91.33 +
   91.34 +#define local static
   91.35 +
   91.36 +/* Find a four-byte integer type for crc32_little() and crc32_big(). */
   91.37 +#ifndef NOBYFOUR
   91.38 +#  ifdef STDC           /* need ANSI C limits.h to determine sizes */
   91.39 +#    include <limits.h>
   91.40 +#    define BYFOUR
   91.41 +#    if (UINT_MAX == 0xffffffffUL)
   91.42 +       typedef unsigned int u4;
   91.43 +#    else
   91.44 +#      if (ULONG_MAX == 0xffffffffUL)
   91.45 +         typedef unsigned long u4;
   91.46 +#      else
   91.47 +#        if (USHRT_MAX == 0xffffffffUL)
   91.48 +           typedef unsigned short u4;
   91.49 +#        else
   91.50 +#          undef BYFOUR     /* can't find a four-byte integer type! */
   91.51 +#        endif
   91.52 +#      endif
   91.53 +#    endif
   91.54 +#  endif /* STDC */
   91.55 +#endif /* !NOBYFOUR */
   91.56 +
   91.57 +/* Definitions for doing the crc four data bytes at a time. */
   91.58 +#ifdef BYFOUR
   91.59 +#  define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
   91.60 +                (((w)&0xff00)<<8)+(((w)&0xff)<<24))
   91.61 +   local unsigned long crc32_little OF((unsigned long,
   91.62 +                        const unsigned char FAR *, unsigned));
   91.63 +   local unsigned long crc32_big OF((unsigned long,
   91.64 +                        const unsigned char FAR *, unsigned));
   91.65 +#  define TBLS 8
   91.66 +#else
   91.67 +#  define TBLS 1
   91.68 +#endif /* BYFOUR */
   91.69 +
   91.70 +/* Local functions for crc concatenation */
   91.71 +local unsigned long gf2_matrix_times OF((unsigned long *mat,
   91.72 +                                         unsigned long vec));
   91.73 +local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
   91.74 +
   91.75 +#ifdef DYNAMIC_CRC_TABLE
   91.76 +
   91.77 +local volatile int crc_table_empty = 1;
   91.78 +local unsigned long FAR crc_table[TBLS][256];
   91.79 +local void make_crc_table OF((void));
   91.80 +#ifdef MAKECRCH
   91.81 +   local void write_table OF((FILE *, const unsigned long FAR *));
   91.82 +#endif /* MAKECRCH */
   91.83 +/*
   91.84 +  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
   91.85 +  x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
   91.86 +
   91.87 +  Polynomials over GF(2) are represented in binary, one bit per coefficient,
   91.88 +  with the lowest powers in the most significant bit.  Then adding polynomials
   91.89 +  is just exclusive-or, and multiplying a polynomial by x is a right shift by
   91.90 +  one.  If we call the above polynomial p, and represent a byte as the
   91.91 +  polynomial q, also with the lowest power in the most significant bit (so the
   91.92 +  byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
   91.93 +  where a mod b means the remainder after dividing a by b.
   91.94 +
   91.95 +  This calculation is done using the shift-register method of multiplying and
   91.96 +  taking the remainder.  The register is initialized to zero, and for each
   91.97 +  incoming bit, x^32 is added mod p to the register if the bit is a one (where
   91.98 +  x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
   91.99 +  x (which is shifting right by one and adding x^32 mod p if the bit shifted
  91.100 +  out is a one).  We start with the highest power (least significant bit) of
  91.101 +  q and repeat for all eight bits of q.
  91.102 +
  91.103 +  The first table is simply the CRC of all possible eight bit values.  This is
  91.104 +  all the information needed to generate CRCs on data a byte at a time for all
  91.105 +  combinations of CRC register values and incoming bytes.  The remaining tables
  91.106 +  allow for word-at-a-time CRC calculation for both big-endian and little-
  91.107 +  endian machines, where a word is four bytes.
  91.108 +*/
  91.109 +local void make_crc_table()
  91.110 +{
  91.111 +    unsigned long c;
  91.112 +    int n, k;
  91.113 +    unsigned long poly;                 /* polynomial exclusive-or pattern */
  91.114 +    /* terms of polynomial defining this crc (except x^32): */
  91.115 +    static volatile int first = 1;      /* flag to limit concurrent making */
  91.116 +    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  91.117 +
  91.118 +    /* See if another task is already doing this (not thread-safe, but better
  91.119 +       than nothing -- significantly reduces duration of vulnerability in
  91.120 +       case the advice about DYNAMIC_CRC_TABLE is ignored) */
  91.121 +    if (first) {
  91.122 +        first = 0;
  91.123 +
  91.124 +        /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  91.125 +        poly = 0UL;
  91.126 +        for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  91.127 +            poly |= 1UL << (31 - p[n]);
  91.128 +
  91.129 +        /* generate a crc for every 8-bit value */
  91.130 +        for (n = 0; n < 256; n++) {
  91.131 +            c = (unsigned long)n;
  91.132 +            for (k = 0; k < 8; k++)
  91.133 +                c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  91.134 +            crc_table[0][n] = c;
  91.135 +        }
  91.136 +
  91.137 +#ifdef BYFOUR
  91.138 +        /* generate crc for each value followed by one, two, and three zeros,
  91.139 +           and then the byte reversal of those as well as the first table */
  91.140 +        for (n = 0; n < 256; n++) {
  91.141 +            c = crc_table[0][n];
  91.142 +            crc_table[4][n] = REV(c);
  91.143 +            for (k = 1; k < 4; k++) {
  91.144 +                c = crc_table[0][c & 0xff] ^ (c >> 8);
  91.145 +                crc_table[k][n] = c;
  91.146 +                crc_table[k + 4][n] = REV(c);
  91.147 +            }
  91.148 +        }
  91.149 +#endif /* BYFOUR */
  91.150 +
  91.151 +        crc_table_empty = 0;
  91.152 +    }
  91.153 +    else {      /* not first */
  91.154 +        /* wait for the other guy to finish (not efficient, but rare) */
  91.155 +        while (crc_table_empty)
  91.156 +            ;
  91.157 +    }
  91.158 +
  91.159 +#ifdef MAKECRCH
  91.160 +    /* write out CRC tables to crc32.h */
  91.161 +    {
  91.162 +        FILE *out;
  91.163 +
  91.164 +        out = fopen("crc32.h", "w");
  91.165 +        if (out == NULL) return;
  91.166 +        fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  91.167 +        fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  91.168 +        fprintf(out, "local const unsigned long FAR ");
  91.169 +        fprintf(out, "crc_table[TBLS][256] =\n{\n  {\n");
  91.170 +        write_table(out, crc_table[0]);
  91.171 +#  ifdef BYFOUR
  91.172 +        fprintf(out, "#ifdef BYFOUR\n");
  91.173 +        for (k = 1; k < 8; k++) {
  91.174 +            fprintf(out, "  },\n  {\n");
  91.175 +            write_table(out, crc_table[k]);
  91.176 +        }
  91.177 +        fprintf(out, "#endif\n");
  91.178 +#  endif /* BYFOUR */
  91.179 +        fprintf(out, "  }\n};\n");
  91.180 +        fclose(out);
  91.181 +    }
  91.182 +#endif /* MAKECRCH */
  91.183 +}
  91.184 +
  91.185 +#ifdef MAKECRCH
  91.186 +local void write_table(out, table)
  91.187 +    FILE *out;
  91.188 +    const unsigned long FAR *table;
  91.189 +{
  91.190 +    int n;
  91.191 +
  91.192 +    for (n = 0; n < 256; n++)
  91.193 +        fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ", table[n],
  91.194 +                n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  91.195 +}
  91.196 +#endif /* MAKECRCH */
  91.197 +
  91.198 +#else /* !DYNAMIC_CRC_TABLE */
  91.199 +/* ========================================================================
  91.200 + * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  91.201 + */
  91.202 +#include "crc32.h"
  91.203 +#endif /* DYNAMIC_CRC_TABLE */
  91.204 +
  91.205 +/* =========================================================================
  91.206 + * This function can be used by asm versions of crc32()
  91.207 + */
  91.208 +const unsigned long FAR * ZEXPORT get_crc_table()
  91.209 +{
  91.210 +#ifdef DYNAMIC_CRC_TABLE
  91.211 +    if (crc_table_empty)
  91.212 +        make_crc_table();
  91.213 +#endif /* DYNAMIC_CRC_TABLE */
  91.214 +    return (const unsigned long FAR *)crc_table;
  91.215 +}
  91.216 +
  91.217 +/* ========================================================================= */
  91.218 +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  91.219 +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  91.220 +
  91.221 +/* ========================================================================= */
  91.222 +unsigned long ZEXPORT crc32(crc, buf, len)
  91.223 +    unsigned long crc;
  91.224 +    const unsigned char FAR *buf;
  91.225 +    unsigned len;
  91.226 +{
  91.227 +    if (buf == Z_NULL) return 0UL;
  91.228 +
  91.229 +#ifdef DYNAMIC_CRC_TABLE
  91.230 +    if (crc_table_empty)
  91.231 +        make_crc_table();
  91.232 +#endif /* DYNAMIC_CRC_TABLE */
  91.233 +
  91.234 +#ifdef BYFOUR
  91.235 +    if (sizeof(void *) == sizeof(ptrdiff_t)) {
  91.236 +        u4 endian;
  91.237 +
  91.238 +        endian = 1;
  91.239 +        if (*((unsigned char *)(&endian)))
  91.240 +            return crc32_little(crc, buf, len);
  91.241 +        else
  91.242 +            return crc32_big(crc, buf, len);
  91.243 +    }
  91.244 +#endif /* BYFOUR */
  91.245 +    crc = crc ^ 0xffffffffUL;
  91.246 +    while (len >= 8) {
  91.247 +        DO8;
  91.248 +        len -= 8;
  91.249 +    }
  91.250 +    if (len) do {
  91.251 +        DO1;
  91.252 +    } while (--len);
  91.253 +    return crc ^ 0xffffffffUL;
  91.254 +}
  91.255 +
  91.256 +#ifdef BYFOUR
  91.257 +
  91.258 +/* ========================================================================= */
  91.259 +#define DOLIT4 c ^= *buf4++; \
  91.260 +        c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  91.261 +            crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  91.262 +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  91.263 +
  91.264 +/* ========================================================================= */
  91.265 +local unsigned long crc32_little(crc, buf, len)
  91.266 +    unsigned long crc;
  91.267 +    const unsigned char FAR *buf;
  91.268 +    unsigned len;
  91.269 +{
  91.270 +    register u4 c;
  91.271 +    register const u4 FAR *buf4;
  91.272 +
  91.273 +    c = (u4)crc;
  91.274 +    c = ~c;
  91.275 +    while (len && ((ptrdiff_t)buf & 3)) {
  91.276 +        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  91.277 +        len--;
  91.278 +    }
  91.279 +
  91.280 +    buf4 = (const u4 FAR *)(const void FAR *)buf;
  91.281 +    while (len >= 32) {
  91.282 +        DOLIT32;
  91.283 +        len -= 32;
  91.284 +    }
  91.285 +    while (len >= 4) {
  91.286 +        DOLIT4;
  91.287 +        len -= 4;
  91.288 +    }
  91.289 +    buf = (const unsigned char FAR *)buf4;
  91.290 +
  91.291 +    if (len) do {
  91.292 +        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  91.293 +    } while (--len);
  91.294 +    c = ~c;
  91.295 +    return (unsigned long)c;
  91.296 +}
  91.297 +
  91.298 +/* ========================================================================= */
  91.299 +#define DOBIG4 c ^= *++buf4; \
  91.300 +        c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  91.301 +            crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  91.302 +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  91.303 +
  91.304 +/* ========================================================================= */
  91.305 +local unsigned long crc32_big(crc, buf, len)
  91.306 +    unsigned long crc;
  91.307 +    const unsigned char FAR *buf;
  91.308 +    unsigned len;
  91.309 +{
  91.310 +    register u4 c;
  91.311 +    register const u4 FAR *buf4;
  91.312 +
  91.313 +    c = REV((u4)crc);
  91.314 +    c = ~c;
  91.315 +    while (len && ((ptrdiff_t)buf & 3)) {
  91.316 +        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  91.317 +        len--;
  91.318 +    }
  91.319 +
  91.320 +    buf4 = (const u4 FAR *)(const void FAR *)buf;
  91.321 +    buf4--;
  91.322 +    while (len >= 32) {
  91.323 +        DOBIG32;
  91.324 +        len -= 32;
  91.325 +    }
  91.326 +    while (len >= 4) {
  91.327 +        DOBIG4;
  91.328 +        len -= 4;
  91.329 +    }
  91.330 +    buf4++;
  91.331 +    buf = (const unsigned char FAR *)buf4;
  91.332 +
  91.333 +    if (len) do {
  91.334 +        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  91.335 +    } while (--len);
  91.336 +    c = ~c;
  91.337 +    return (unsigned long)(REV(c));
  91.338 +}
  91.339 +
  91.340 +#endif /* BYFOUR */
  91.341 +
  91.342 +#define GF2_DIM 32      /* dimension of GF(2) vectors (length of CRC) */
  91.343 +
  91.344 +/* ========================================================================= */
  91.345 +local unsigned long gf2_matrix_times(mat, vec)
  91.346 +    unsigned long *mat;
  91.347 +    unsigned long vec;
  91.348 +{
  91.349 +    unsigned long sum;
  91.350 +
  91.351 +    sum = 0;
  91.352 +    while (vec) {
  91.353 +        if (vec & 1)
  91.354 +            sum ^= *mat;
  91.355 +        vec >>= 1;
  91.356 +        mat++;
  91.357 +    }
  91.358 +    return sum;
  91.359 +}
  91.360 +
  91.361 +/* ========================================================================= */
  91.362 +local void gf2_matrix_square(square, mat)
  91.363 +    unsigned long *square;
  91.364 +    unsigned long *mat;
  91.365 +{
  91.366 +    int n;
  91.367 +
  91.368 +    for (n = 0; n < GF2_DIM; n++)
  91.369 +        square[n] = gf2_matrix_times(mat, mat[n]);
  91.370 +}
  91.371 +
  91.372 +/* ========================================================================= */
  91.373 +uLong ZEXPORT crc32_combine(crc1, crc2, len2)
  91.374 +    uLong crc1;
  91.375 +    uLong crc2;
  91.376 +    z_off_t len2;
  91.377 +{
  91.378 +    int n;
  91.379 +    unsigned long row;
  91.380 +    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */
  91.381 +    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */
  91.382 +
  91.383 +    /* degenerate case */
  91.384 +    if (len2 == 0)
  91.385 +        return crc1;
  91.386 +
  91.387 +    /* put operator for one zero bit in odd */
  91.388 +    odd[0] = 0xedb88320L;           /* CRC-32 polynomial */
  91.389 +    row = 1;
  91.390 +    for (n = 1; n < GF2_DIM; n++) {
  91.391 +        odd[n] = row;
  91.392 +        row <<= 1;
  91.393 +    }
  91.394 +
  91.395 +    /* put operator for two zero bits in even */
  91.396 +    gf2_matrix_square(even, odd);
  91.397 +
  91.398 +    /* put operator for four zero bits in odd */
  91.399 +    gf2_matrix_square(odd, even);
  91.400 +
  91.401 +    /* apply len2 zeros to crc1 (first square will put the operator for one
  91.402 +       zero byte, eight zero bits, in even) */
  91.403 +    do {
  91.404 +        /* apply zeros operator for this bit of len2 */
  91.405 +        gf2_matrix_square(even, odd);
  91.406 +        if (len2 & 1)
  91.407 +            crc1 = gf2_matrix_times(even, crc1);
  91.408 +        len2 >>= 1;
  91.409 +
  91.410 +        /* if no more bits set, then done */
  91.411 +        if (len2 == 0)
  91.412 +            break;
  91.413 +
  91.414 +        /* another iteration of the loop with odd and even swapped */
  91.415 +        gf2_matrix_square(odd, even);
  91.416 +        if (len2 & 1)
  91.417 +            crc1 = gf2_matrix_times(odd, crc1);
  91.418 +        len2 >>= 1;
  91.419 +
  91.420 +        /* if no more bits set, then done */
  91.421 +    } while (len2 != 0);
  91.422 +
  91.423 +    /* return combined crc */
  91.424 +    crc1 ^= crc2;
  91.425 +    return crc1;
  91.426 +}
    92.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    92.2 +++ b/libs/zlib/crc32.h	Thu Sep 08 06:28:38 2011 +0300
    92.3 @@ -0,0 +1,441 @@
    92.4 +/* crc32.h -- tables for rapid CRC calculation
    92.5 + * Generated automatically by crc32.c
    92.6 + */
    92.7 +
    92.8 +local const unsigned long FAR crc_table[TBLS][256] =
    92.9 +{
   92.10 +  {
   92.11 +    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
   92.12 +    0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
   92.13 +    0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
   92.14 +    0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
   92.15 +    0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
   92.16 +    0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
   92.17 +    0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
   92.18 +    0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
   92.19 +    0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
   92.20 +    0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
   92.21 +    0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
   92.22 +    0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
   92.23 +    0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
   92.24 +    0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
   92.25 +    0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
   92.26 +    0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
   92.27 +    0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
   92.28 +    0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
   92.29 +    0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
   92.30 +    0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
   92.31 +    0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
   92.32 +    0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
   92.33 +    0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
   92.34 +    0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
   92.35 +    0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
   92.36 +    0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
   92.37 +    0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
   92.38 +    0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
   92.39 +    0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
   92.40 +    0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
   92.41 +    0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
   92.42 +    0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
   92.43 +    0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
   92.44 +    0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
   92.45 +    0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
   92.46 +    0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
   92.47 +    0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
   92.48 +    0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
   92.49 +    0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
   92.50 +    0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
   92.51 +    0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
   92.52 +    0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
   92.53 +    0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
   92.54 +    0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
   92.55 +    0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
   92.56 +    0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
   92.57 +    0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
   92.58 +    0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
   92.59 +    0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
   92.60 +    0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
   92.61 +    0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
   92.62 +    0x2d02ef8dUL
   92.63 +#ifdef BYFOUR
   92.64 +  },
   92.65 +  {
   92.66 +    0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
   92.67 +    0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
   92.68 +    0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
   92.69 +    0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
   92.70 +    0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
   92.71 +    0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
   92.72 +    0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
   92.73 +    0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
   92.74 +    0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
   92.75 +    0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
   92.76 +    0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
   92.77 +    0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
   92.78 +    0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
   92.79 +    0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
   92.80 +    0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
   92.81 +    0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
   92.82 +    0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
   92.83 +    0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
   92.84 +    0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
   92.85 +    0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
   92.86 +    0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
   92.87 +    0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
   92.88 +    0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
   92.89 +    0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
   92.90 +    0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
   92.91 +    0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
   92.92 +    0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
   92.93 +    0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
   92.94 +    0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
   92.95 +    0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
   92.96 +    0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
   92.97 +    0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
   92.98 +    0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
   92.99 +    0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  92.100 +    0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  92.101 +    0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  92.102 +    0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  92.103 +    0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  92.104 +    0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  92.105 +    0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  92.106 +    0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  92.107 +    0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  92.108 +    0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  92.109 +    0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  92.110 +    0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  92.111 +    0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  92.112 +    0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  92.113 +    0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  92.114 +    0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  92.115 +    0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  92.116 +    0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  92.117 +    0x9324fd72UL
  92.118 +  },
  92.119 +  {
  92.120 +    0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  92.121 +    0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  92.122 +    0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  92.123 +    0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  92.124 +    0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  92.125 +    0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  92.126 +    0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  92.127 +    0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  92.128 +    0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  92.129 +    0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  92.130 +    0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  92.131 +    0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  92.132 +    0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  92.133 +    0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  92.134 +    0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  92.135 +    0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  92.136 +    0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  92.137 +    0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  92.138 +    0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  92.139 +    0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  92.140 +    0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  92.141 +    0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  92.142 +    0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  92.143 +    0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  92.144 +    0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  92.145 +    0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  92.146 +    0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  92.147 +    0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  92.148 +    0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  92.149 +    0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  92.150 +    0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  92.151 +    0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  92.152 +    0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  92.153 +    0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  92.154 +    0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  92.155 +    0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  92.156 +    0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  92.157 +    0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  92.158 +    0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  92.159 +    0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  92.160 +    0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  92.161 +    0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  92.162 +    0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  92.163 +    0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  92.164 +    0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  92.165 +    0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  92.166 +    0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  92.167 +    0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  92.168 +    0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  92.169 +    0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  92.170 +    0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  92.171 +    0xbe9834edUL
  92.172 +  },
  92.173 +  {
  92.174 +    0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  92.175 +    0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  92.176 +    0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  92.177 +    0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  92.178 +    0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  92.179 +    0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  92.180 +    0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  92.181 +    0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  92.182 +    0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  92.183 +    0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  92.184 +    0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  92.185 +    0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  92.186 +    0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  92.187 +    0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  92.188 +    0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  92.189 +    0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  92.190 +    0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  92.191 +    0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  92.192 +    0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  92.193 +    0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  92.194 +    0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  92.195 +    0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  92.196 +    0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  92.197 +    0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  92.198 +    0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  92.199 +    0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  92.200 +    0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  92.201 +    0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  92.202 +    0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  92.203 +    0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  92.204 +    0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  92.205 +    0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  92.206 +    0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  92.207 +    0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  92.208 +    0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  92.209 +    0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  92.210 +    0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  92.211 +    0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  92.212 +    0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  92.213 +    0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  92.214 +    0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  92.215 +    0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  92.216 +    0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  92.217 +    0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  92.218 +    0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  92.219 +    0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  92.220 +    0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  92.221 +    0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  92.222 +    0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  92.223 +    0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  92.224 +    0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  92.225 +    0xde0506f1UL
  92.226 +  },
  92.227 +  {
  92.228 +    0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  92.229 +    0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  92.230 +    0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  92.231 +    0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  92.232 +    0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  92.233 +    0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  92.234 +    0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  92.235 +    0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  92.236 +    0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  92.237 +    0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  92.238 +    0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  92.239 +    0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  92.240 +    0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  92.241 +    0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  92.242 +    0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  92.243 +    0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  92.244 +    0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  92.245 +    0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  92.246 +    0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  92.247 +    0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  92.248 +    0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  92.249 +    0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  92.250 +    0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  92.251 +    0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  92.252 +    0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  92.253 +    0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  92.254 +    0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  92.255 +    0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  92.256 +    0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  92.257 +    0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  92.258 +    0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  92.259 +    0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  92.260 +    0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  92.261 +    0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  92.262 +    0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  92.263 +    0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  92.264 +    0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  92.265 +    0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  92.266 +    0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  92.267 +    0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  92.268 +    0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  92.269 +    0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  92.270 +    0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  92.271 +    0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  92.272 +    0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  92.273 +    0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  92.274 +    0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  92.275 +    0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  92.276 +    0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  92.277 +    0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  92.278 +    0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  92.279 +    0x8def022dUL
  92.280 +  },
  92.281 +  {
  92.282 +    0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  92.283 +    0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  92.284 +    0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  92.285 +    0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  92.286 +    0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  92.287 +    0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  92.288 +    0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  92.289 +    0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  92.290 +    0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  92.291 +    0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  92.292 +    0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  92.293 +    0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  92.294 +    0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  92.295 +    0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  92.296 +    0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  92.297 +    0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  92.298 +    0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  92.299 +    0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  92.300 +    0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  92.301 +    0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  92.302 +    0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  92.303 +    0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  92.304 +    0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  92.305 +    0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  92.306 +    0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  92.307 +    0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  92.308 +    0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  92.309 +    0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  92.310 +    0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  92.311 +    0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  92.312 +    0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  92.313 +    0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  92.314 +    0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  92.315 +    0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  92.316 +    0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  92.317 +    0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  92.318 +    0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  92.319 +    0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  92.320 +    0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  92.321 +    0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  92.322 +    0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  92.323 +    0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  92.324 +    0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  92.325 +    0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  92.326 +    0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  92.327 +    0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  92.328 +    0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  92.329 +    0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  92.330 +    0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  92.331 +    0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  92.332 +    0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  92.333 +    0x72fd2493UL
  92.334 +  },
  92.335 +  {
  92.336 +    0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  92.337 +    0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  92.338 +    0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  92.339 +    0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  92.340 +    0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  92.341 +    0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  92.342 +    0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  92.343 +    0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  92.344 +    0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  92.345 +    0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  92.346 +    0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  92.347 +    0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  92.348 +    0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  92.349 +    0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  92.350 +    0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  92.351 +    0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  92.352 +    0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  92.353 +    0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  92.354 +    0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  92.355 +    0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  92.356 +    0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  92.357 +    0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  92.358 +    0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  92.359 +    0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  92.360 +    0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  92.361 +    0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  92.362 +    0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  92.363 +    0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  92.364 +    0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  92.365 +    0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  92.366 +    0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  92.367 +    0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  92.368 +    0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  92.369 +    0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  92.370 +    0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  92.371 +    0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  92.372 +    0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  92.373 +    0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  92.374 +    0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  92.375 +    0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  92.376 +    0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  92.377 +    0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  92.378 +    0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  92.379 +    0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  92.380 +    0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  92.381 +    0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  92.382 +    0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  92.383 +    0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  92.384 +    0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  92.385 +    0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  92.386 +    0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  92.387 +    0xed3498beUL
  92.388 +  },
  92.389 +  {
  92.390 +    0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  92.391 +    0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  92.392 +    0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  92.393 +    0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  92.394 +    0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  92.395 +    0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  92.396 +    0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  92.397 +    0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  92.398 +    0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  92.399 +    0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  92.400 +    0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  92.401 +    0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  92.402 +    0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  92.403 +    0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  92.404 +    0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  92.405 +    0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  92.406 +    0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  92.407 +    0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  92.408 +    0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  92.409 +    0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  92.410 +    0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  92.411 +    0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  92.412 +    0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  92.413 +    0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  92.414 +    0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  92.415 +    0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  92.416 +    0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  92.417 +    0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  92.418 +    0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  92.419 +    0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  92.420 +    0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  92.421 +    0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  92.422 +    0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  92.423 +    0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  92.424 +    0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  92.425 +    0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  92.426 +    0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  92.427 +    0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  92.428 +    0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  92.429 +    0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  92.430 +    0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  92.431 +    0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  92.432 +    0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  92.433 +    0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  92.434 +    0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  92.435 +    0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  92.436 +    0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  92.437 +    0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  92.438 +    0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  92.439 +    0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  92.440 +    0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  92.441 +    0xf10605deUL
  92.442 +#endif
  92.443 +  }
  92.444 +};
    93.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    93.2 +++ b/libs/zlib/deflate.c	Thu Sep 08 06:28:38 2011 +0300
    93.3 @@ -0,0 +1,1736 @@
    93.4 +/* deflate.c -- compress data using the deflation algorithm
    93.5 + * Copyright (C) 1995-2005 Jean-loup Gailly.
    93.6 + * For conditions of distribution and use, see copyright notice in zlib.h
    93.7 + */
    93.8 +
    93.9 +/*
   93.10 + *  ALGORITHM
   93.11 + *
   93.12 + *      The "deflation" process depends on being able to identify portions
   93.13 + *      of the input text which are identical to earlier input (within a
   93.14 + *      sliding window trailing behind the input currently being processed).
   93.15 + *
   93.16 + *      The most straightforward technique turns out to be the fastest for
   93.17 + *      most input files: try all possible matches and select the longest.
   93.18 + *      The key feature of this algorithm is that insertions into the string
   93.19 + *      dictionary are very simple and thus fast, and deletions are avoided
   93.20 + *      completely. Insertions are performed at each input character, whereas
   93.21 + *      string matches are performed only when the previous match ends. So it
   93.22 + *      is preferable to spend more time in matches to allow very fast string
   93.23 + *      insertions and avoid deletions. The matching algorithm for small
   93.24 + *      strings is inspired from that of Rabin & Karp. A brute force approach
   93.25 + *      is used to find longer strings when a small match has been found.
   93.26 + *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
   93.27 + *      (by Leonid Broukhis).
   93.28 + *         A previous version of this file used a more sophisticated algorithm
   93.29 + *      (by Fiala and Greene) which is guaranteed to run in linear amortized
   93.30 + *      time, but has a larger average cost, uses more memory and is patented.
   93.31 + *      However the F&G algorithm may be faster for some highly redundant
   93.32 + *      files if the parameter max_chain_length (described below) is too large.
   93.33 + *
   93.34 + *  ACKNOWLEDGEMENTS
   93.35 + *
   93.36 + *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
   93.37 + *      I found it in 'freeze' written by Leonid Broukhis.
   93.38 + *      Thanks to many people for bug reports and testing.
   93.39 + *
   93.40 + *  REFERENCES
   93.41 + *
   93.42 + *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
   93.43 + *      Available in http://www.ietf.org/rfc/rfc1951.txt
   93.44 + *
   93.45 + *      A description of the Rabin and Karp algorithm is given in the book
   93.46 + *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
   93.47 + *
   93.48 + *      Fiala,E.R., and Greene,D.H.
   93.49 + *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
   93.50 + *
   93.51 + */
   93.52 +
   93.53 +/* @(#) $Id$ */
   93.54 +
   93.55 +#include "deflate.h"
   93.56 +
   93.57 +const char deflate_copyright[] =
   93.58 +   " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
   93.59 +/*
   93.60 +  If you use the zlib library in a product, an acknowledgment is welcome
   93.61 +  in the documentation of your product. If for some reason you cannot
   93.62 +  include such an acknowledgment, I would appreciate that you keep this
   93.63 +  copyright string in the executable of your product.
   93.64 + */
   93.65 +
   93.66 +/* ===========================================================================
   93.67 + *  Function prototypes.
   93.68 + */
   93.69 +typedef enum {
   93.70 +    need_more,      /* block not completed, need more input or more output */
   93.71 +    block_done,     /* block flush performed */
   93.72 +    finish_started, /* finish started, need only more output at next deflate */
   93.73 +    finish_done     /* finish done, accept no more input or output */
   93.74 +} block_state;
   93.75 +
   93.76 +typedef block_state (*compress_func) OF((deflate_state *s, int flush));
   93.77 +/* Compression function. Returns the block state after the call. */
   93.78 +
   93.79 +local void fill_window    OF((deflate_state *s));
   93.80 +local block_state deflate_stored OF((deflate_state *s, int flush));
   93.81 +local block_state deflate_fast   OF((deflate_state *s, int flush));
   93.82 +#ifndef FASTEST
   93.83 +local block_state deflate_slow   OF((deflate_state *s, int flush));
   93.84 +#endif
   93.85 +local void lm_init        OF((deflate_state *s));
   93.86 +local void putShortMSB    OF((deflate_state *s, uInt b));
   93.87 +local void flush_pending  OF((z_streamp strm));
   93.88 +local int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));
   93.89 +#ifndef FASTEST
   93.90 +#ifdef ASMV
   93.91 +      void match_init OF((void)); /* asm code initialization */
   93.92 +      uInt longest_match  OF((deflate_state *s, IPos cur_match));
   93.93 +#else
   93.94 +local uInt longest_match  OF((deflate_state *s, IPos cur_match));
   93.95 +#endif
   93.96 +#endif
   93.97 +local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
   93.98 +
   93.99 +#ifdef DEBUG
  93.100 +local  void check_match OF((deflate_state *s, IPos start, IPos match,
  93.101 +                            int length));
  93.102 +#endif
  93.103 +
  93.104 +/* ===========================================================================
  93.105 + * Local data
  93.106 + */
  93.107 +
  93.108 +#define NIL 0
  93.109 +/* Tail of hash chains */
  93.110 +
  93.111 +#ifndef TOO_FAR
  93.112 +#  define TOO_FAR 4096
  93.113 +#endif
  93.114 +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  93.115 +
  93.116 +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  93.117 +/* Minimum amount of lookahead, except at the end of the input file.
  93.118 + * See deflate.c for comments about the MIN_MATCH+1.
  93.119 + */
  93.120 +
  93.121 +/* Values for max_lazy_match, good_match and max_chain_length, depending on
  93.122 + * the desired pack level (0..9). The values given below have been tuned to
  93.123 + * exclude worst case performance for pathological files. Better values may be
  93.124 + * found for specific files.
  93.125 + */
  93.126 +typedef struct config_s {
  93.127 +   ush good_length; /* reduce lazy search above this match length */
  93.128 +   ush max_lazy;    /* do not perform lazy search above this match length */
  93.129 +   ush nice_length; /* quit search above this match length */
  93.130 +   ush max_chain;
  93.131 +   compress_func func;
  93.132 +} config;
  93.133 +
  93.134 +#ifdef FASTEST
  93.135 +local const config configuration_table[2] = {
  93.136 +/*      good lazy nice chain */
  93.137 +/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
  93.138 +/* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
  93.139 +#else
  93.140 +local const config configuration_table[10] = {
  93.141 +/*      good lazy nice chain */
  93.142 +/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
  93.143 +/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
  93.144 +/* 2 */ {4,    5, 16,    8, deflate_fast},
  93.145 +/* 3 */ {4,    6, 32,   32, deflate_fast},
  93.146 +
  93.147 +/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
  93.148 +/* 5 */ {8,   16, 32,   32, deflate_slow},
  93.149 +/* 6 */ {8,   16, 128, 128, deflate_slow},
  93.150 +/* 7 */ {8,   32, 128, 256, deflate_slow},
  93.151 +/* 8 */ {32, 128, 258, 1024, deflate_slow},
  93.152 +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  93.153 +#endif
  93.154 +
  93.155 +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  93.156 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  93.157 + * meaning.
  93.158 + */
  93.159 +
  93.160 +#define EQUAL 0
  93.161 +/* result of memcmp for equal strings */
  93.162 +
  93.163 +#ifndef NO_DUMMY_DECL
  93.164 +struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  93.165 +#endif
  93.166 +
  93.167 +/* ===========================================================================
  93.168 + * Update a hash value with the given input byte
  93.169 + * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
  93.170 + *    input characters, so that a running hash key can be computed from the
  93.171 + *    previous key instead of complete recalculation each time.
  93.172 + */
  93.173 +#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  93.174 +
  93.175 +
  93.176 +/* ===========================================================================
  93.177 + * Insert string str in the dictionary and set match_head to the previous head
  93.178 + * of the hash chain (the most recent string with same hash key). Return
  93.179 + * the previous length of the hash chain.
  93.180 + * If this file is compiled with -DFASTEST, the compression level is forced
  93.181 + * to 1, and no hash chains are maintained.
  93.182 + * IN  assertion: all calls to to INSERT_STRING are made with consecutive
  93.183 + *    input characters and the first MIN_MATCH bytes of str are valid
  93.184 + *    (except for the last MIN_MATCH-1 bytes of the input file).
  93.185 + */
  93.186 +#ifdef FASTEST
  93.187 +#define INSERT_STRING(s, str, match_head) \
  93.188 +   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  93.189 +    match_head = s->head[s->ins_h], \
  93.190 +    s->head[s->ins_h] = (Pos)(str))
  93.191 +#else
  93.192 +#define INSERT_STRING(s, str, match_head) \
  93.193 +   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  93.194 +    match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  93.195 +    s->head[s->ins_h] = (Pos)(str))
  93.196 +#endif
  93.197 +
  93.198 +/* ===========================================================================
  93.199 + * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  93.200 + * prev[] will be initialized on the fly.
  93.201 + */
  93.202 +#define CLEAR_HASH(s) \
  93.203 +    s->head[s->hash_size-1] = NIL; \
  93.204 +    zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  93.205 +
  93.206 +/* ========================================================================= */
  93.207 +int ZEXPORT deflateInit_(strm, level, version, stream_size)
  93.208 +    z_streamp strm;
  93.209 +    int level;
  93.210 +    const char *version;
  93.211 +    int stream_size;
  93.212 +{
  93.213 +    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  93.214 +                         Z_DEFAULT_STRATEGY, version, stream_size);
  93.215 +    /* To do: ignore strm->next_in if we use it as window */
  93.216 +}
  93.217 +
  93.218 +/* ========================================================================= */
  93.219 +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
  93.220 +                  version, stream_size)
  93.221 +    z_streamp strm;
  93.222 +    int  level;
  93.223 +    int  method;
  93.224 +    int  windowBits;
  93.225 +    int  memLevel;
  93.226 +    int  strategy;
  93.227 +    const char *version;
  93.228 +    int stream_size;
  93.229 +{
  93.230 +    deflate_state *s;
  93.231 +    int wrap = 1;
  93.232 +    static const char my_version[] = ZLIB_VERSION;
  93.233 +
  93.234 +    ushf *overlay;
  93.235 +    /* We overlay pending_buf and d_buf+l_buf. This works since the average
  93.236 +     * output size for (length,distance) codes is <= 24 bits.
  93.237 +     */
  93.238 +
  93.239 +    if (version == Z_NULL || version[0] != my_version[0] ||
  93.240 +        stream_size != sizeof(z_stream)) {
  93.241 +        return Z_VERSION_ERROR;
  93.242 +    }
  93.243 +    if (strm == Z_NULL) return Z_STREAM_ERROR;
  93.244 +
  93.245 +    strm->msg = Z_NULL;
  93.246 +    if (strm->zalloc == (alloc_func)0) {
  93.247 +        strm->zalloc = zcalloc;
  93.248 +        strm->opaque = (voidpf)0;
  93.249 +    }
  93.250 +    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  93.251 +
  93.252 +#ifdef FASTEST
  93.253 +    if (level != 0) level = 1;
  93.254 +#else
  93.255 +    if (level == Z_DEFAULT_COMPRESSION) level = 6;
  93.256 +#endif
  93.257 +
  93.258 +    if (windowBits < 0) { /* suppress zlib wrapper */
  93.259 +        wrap = 0;
  93.260 +        windowBits = -windowBits;
  93.261 +    }
  93.262 +#ifdef GZIP
  93.263 +    else if (windowBits > 15) {
  93.264 +        wrap = 2;       /* write gzip wrapper instead */
  93.265 +        windowBits -= 16;
  93.266 +    }
  93.267 +#endif
  93.268 +    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  93.269 +        windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  93.270 +        strategy < 0 || strategy > Z_FIXED) {
  93.271 +        return Z_STREAM_ERROR;
  93.272 +    }
  93.273 +    if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
  93.274 +    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  93.275 +    if (s == Z_NULL) return Z_MEM_ERROR;
  93.276 +    strm->state = (struct internal_state FAR *)s;
  93.277 +    s->strm = strm;
  93.278 +
  93.279 +    s->wrap = wrap;
  93.280 +    s->gzhead = Z_NULL;
  93.281 +    s->w_bits = windowBits;
  93.282 +    s->w_size = 1 << s->w_bits;
  93.283 +    s->w_mask = s->w_size - 1;
  93.284 +
  93.285 +    s->hash_bits = memLevel + 7;
  93.286 +    s->hash_size = 1 << s->hash_bits;
  93.287 +    s->hash_mask = s->hash_size - 1;
  93.288 +    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  93.289 +
  93.290 +    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  93.291 +    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
  93.292 +    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
  93.293 +
  93.294 +    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  93.295 +
  93.296 +    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  93.297 +    s->pending_buf = (uchf *) overlay;
  93.298 +    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  93.299 +
  93.300 +    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  93.301 +        s->pending_buf == Z_NULL) {
  93.302 +        s->status = FINISH_STATE;
  93.303 +        strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  93.304 +        deflateEnd (strm);
  93.305 +        return Z_MEM_ERROR;
  93.306 +    }
  93.307 +    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  93.308 +    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  93.309 +
  93.310 +    s->level = level;
  93.311 +    s->strategy = strategy;
  93.312 +    s->method = (Byte)method;
  93.313 +
  93.314 +    return deflateReset(strm);
  93.315 +}
  93.316 +
  93.317 +/* ========================================================================= */
  93.318 +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
  93.319 +    z_streamp strm;
  93.320 +    const Bytef *dictionary;
  93.321 +    uInt  dictLength;
  93.322 +{
  93.323 +    deflate_state *s;
  93.324 +    uInt length = dictLength;
  93.325 +    uInt n;
  93.326 +    IPos hash_head = 0;
  93.327 +
  93.328 +    if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  93.329 +        strm->state->wrap == 2 ||
  93.330 +        (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  93.331 +        return Z_STREAM_ERROR;
  93.332 +
  93.333 +    s = strm->state;
  93.334 +    if (s->wrap)
  93.335 +        strm->adler = adler32(strm->adler, dictionary, dictLength);
  93.336 +
  93.337 +    if (length < MIN_MATCH) return Z_OK;
  93.338 +    if (length > MAX_DIST(s)) {
  93.339 +        length = MAX_DIST(s);
  93.340 +        dictionary += dictLength - length; /* use the tail of the dictionary */
  93.341 +    }
  93.342 +    zmemcpy(s->window, dictionary, length);
  93.343 +    s->strstart = length;
  93.344 +    s->block_start = (long)length;
  93.345 +
  93.346 +    /* Insert all strings in the hash table (except for the last two bytes).
  93.347 +     * s->lookahead stays null, so s->ins_h will be recomputed at the next
  93.348 +     * call of fill_window.
  93.349 +     */
  93.350 +    s->ins_h = s->window[0];
  93.351 +    UPDATE_HASH(s, s->ins_h, s->window[1]);
  93.352 +    for (n = 0; n <= length - MIN_MATCH; n++) {
  93.353 +        INSERT_STRING(s, n, hash_head);
  93.354 +    }
  93.355 +    if (hash_head) hash_head = 0;  /* to make compiler happy */
  93.356 +    return Z_OK;
  93.357 +}
  93.358 +
  93.359 +/* ========================================================================= */
  93.360 +int ZEXPORT deflateReset (strm)
  93.361 +    z_streamp strm;
  93.362 +{
  93.363 +    deflate_state *s;
  93.364 +
  93.365 +    if (strm == Z_NULL || strm->state == Z_NULL ||
  93.366 +        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  93.367 +        return Z_STREAM_ERROR;
  93.368 +    }
  93.369 +
  93.370 +    strm->total_in = strm->total_out = 0;
  93.371 +    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  93.372 +    strm->data_type = Z_UNKNOWN;
  93.373 +
  93.374 +    s = (deflate_state *)strm->state;
  93.375 +    s->pending = 0;
  93.376 +    s->pending_out = s->pending_buf;
  93.377 +
  93.378 +    if (s->wrap < 0) {
  93.379 +        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  93.380 +    }
  93.381 +    s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  93.382 +    strm->adler =
  93.383 +#ifdef GZIP
  93.384 +        s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  93.385 +#endif
  93.386 +        adler32(0L, Z_NULL, 0);
  93.387 +    s->last_flush = Z_NO_FLUSH;
  93.388 +
  93.389 +    _tr_init(s);
  93.390 +    lm_init(s);
  93.391 +
  93.392 +    return Z_OK;
  93.393 +}
  93.394 +
  93.395 +/* ========================================================================= */
  93.396 +int ZEXPORT deflateSetHeader (strm, head)
  93.397 +    z_streamp strm;
  93.398 +    gz_headerp head;
  93.399 +{
  93.400 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  93.401 +    if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  93.402 +    strm->state->gzhead = head;
  93.403 +    return Z_OK;
  93.404 +}
  93.405 +
  93.406 +/* ========================================================================= */
  93.407 +int ZEXPORT deflatePrime (strm, bits, value)
  93.408 +    z_streamp strm;
  93.409 +    int bits;
  93.410 +    int value;
  93.411 +{
  93.412 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  93.413 +    strm->state->bi_valid = bits;
  93.414 +    strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  93.415 +    return Z_OK;
  93.416 +}
  93.417 +
  93.418 +/* ========================================================================= */
  93.419 +int ZEXPORT deflateParams(strm, level, strategy)
  93.420 +    z_streamp strm;
  93.421 +    int level;
  93.422 +    int strategy;
  93.423 +{
  93.424 +    deflate_state *s;
  93.425 +    compress_func func;
  93.426 +    int err = Z_OK;
  93.427 +
  93.428 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  93.429 +    s = strm->state;
  93.430 +
  93.431 +#ifdef FASTEST
  93.432 +    if (level != 0) level = 1;
  93.433 +#else
  93.434 +    if (level == Z_DEFAULT_COMPRESSION) level = 6;
  93.435 +#endif
  93.436 +    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  93.437 +        return Z_STREAM_ERROR;
  93.438 +    }
  93.439 +    func = configuration_table[s->level].func;
  93.440 +
  93.441 +    if (func != configuration_table[level].func && strm->total_in != 0) {
  93.442 +        /* Flush the last buffer: */
  93.443 +        err = deflate(strm, Z_PARTIAL_FLUSH);
  93.444 +    }
  93.445 +    if (s->level != level) {
  93.446 +        s->level = level;
  93.447 +        s->max_lazy_match   = configuration_table[level].max_lazy;
  93.448 +        s->good_match       = configuration_table[level].good_length;
  93.449 +        s->nice_match       = configuration_table[level].nice_length;
  93.450 +        s->max_chain_length = configuration_table[level].max_chain;
  93.451 +    }
  93.452 +    s->strategy = strategy;
  93.453 +    return err;
  93.454 +}
  93.455 +
  93.456 +/* ========================================================================= */
  93.457 +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
  93.458 +    z_streamp strm;
  93.459 +    int good_length;
  93.460 +    int max_lazy;
  93.461 +    int nice_length;
  93.462 +    int max_chain;
  93.463 +{
  93.464 +    deflate_state *s;
  93.465 +
  93.466 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  93.467 +    s = strm->state;
  93.468 +    s->good_match = good_length;
  93.469 +    s->max_lazy_match = max_lazy;
  93.470 +    s->nice_match = nice_length;
  93.471 +    s->max_chain_length = max_chain;
  93.472 +    return Z_OK;
  93.473 +}
  93.474 +
  93.475 +/* =========================================================================
  93.476 + * For the default windowBits of 15 and memLevel of 8, this function returns
  93.477 + * a close to exact, as well as small, upper bound on the compressed size.
  93.478 + * They are coded as constants here for a reason--if the #define's are
  93.479 + * changed, then this function needs to be changed as well.  The return
  93.480 + * value for 15 and 8 only works for those exact settings.
  93.481 + *
  93.482 + * For any setting other than those defaults for windowBits and memLevel,
  93.483 + * the value returned is a conservative worst case for the maximum expansion
  93.484 + * resulting from using fixed blocks instead of stored blocks, which deflate
  93.485 + * can emit on compressed data for some combinations of the parameters.
  93.486 + *
  93.487 + * This function could be more sophisticated to provide closer upper bounds
  93.488 + * for every combination of windowBits and memLevel, as well as wrap.
  93.489 + * But even the conservative upper bound of about 14% expansion does not
  93.490 + * seem onerous for output buffer allocation.
  93.491 + */
  93.492 +uLong ZEXPORT deflateBound(strm, sourceLen)
  93.493 +    z_streamp strm;
  93.494 +    uLong sourceLen;
  93.495 +{
  93.496 +    deflate_state *s;
  93.497 +    uLong destLen;
  93.498 +
  93.499 +    /* conservative upper bound */
  93.500 +    destLen = sourceLen +
  93.501 +              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  93.502 +
  93.503 +    /* if can't get parameters, return conservative bound */
  93.504 +    if (strm == Z_NULL || strm->state == Z_NULL)
  93.505 +        return destLen;
  93.506 +
  93.507 +    /* if not default parameters, return conservative bound */
  93.508 +    s = strm->state;
  93.509 +    if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  93.510 +        return destLen;
  93.511 +
  93.512 +    /* default settings: return tight bound for that case */
  93.513 +    return compressBound(sourceLen);
  93.514 +}
  93.515 +
  93.516 +/* =========================================================================
  93.517 + * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  93.518 + * IN assertion: the stream state is correct and there is enough room in
  93.519 + * pending_buf.
  93.520 + */
  93.521 +local void putShortMSB (s, b)
  93.522 +    deflate_state *s;
  93.523 +    uInt b;
  93.524 +{
  93.525 +    put_byte(s, (Byte)(b >> 8));
  93.526 +    put_byte(s, (Byte)(b & 0xff));
  93.527 +}
  93.528 +
  93.529 +/* =========================================================================
  93.530 + * Flush as much pending output as possible. All deflate() output goes
  93.531 + * through this function so some applications may wish to modify it
  93.532 + * to avoid allocating a large strm->next_out buffer and copying into it.
  93.533 + * (See also read_buf()).
  93.534 + */
  93.535 +local void flush_pending(strm)
  93.536 +    z_streamp strm;
  93.537 +{
  93.538 +    unsigned len = strm->state->pending;
  93.539 +
  93.540 +    if (len > strm->avail_out) len = strm->avail_out;
  93.541 +    if (len == 0) return;
  93.542 +
  93.543 +    zmemcpy(strm->next_out, strm->state->pending_out, len);
  93.544 +    strm->next_out  += len;
  93.545 +    strm->state->pending_out  += len;
  93.546 +    strm->total_out += len;
  93.547 +    strm->avail_out  -= len;
  93.548 +    strm->state->pending -= len;
  93.549 +    if (strm->state->pending == 0) {
  93.550 +        strm->state->pending_out = strm->state->pending_buf;
  93.551 +    }
  93.552 +}
  93.553 +
  93.554 +/* ========================================================================= */
  93.555 +int ZEXPORT deflate (strm, flush)
  93.556 +    z_streamp strm;
  93.557 +    int flush;
  93.558 +{
  93.559 +    int old_flush; /* value of flush param for previous deflate call */
  93.560 +    deflate_state *s;
  93.561 +
  93.562 +    if (strm == Z_NULL || strm->state == Z_NULL ||
  93.563 +        flush > Z_FINISH || flush < 0) {
  93.564 +        return Z_STREAM_ERROR;
  93.565 +    }
  93.566 +    s = strm->state;
  93.567 +
  93.568 +    if (strm->next_out == Z_NULL ||
  93.569 +        (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  93.570 +        (s->status == FINISH_STATE && flush != Z_FINISH)) {
  93.571 +        ERR_RETURN(strm, Z_STREAM_ERROR);
  93.572 +    }
  93.573 +    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  93.574 +
  93.575 +    s->strm = strm; /* just in case */
  93.576 +    old_flush = s->last_flush;
  93.577 +    s->last_flush = flush;
  93.578 +
  93.579 +    /* Write the header */
  93.580 +    if (s->status == INIT_STATE) {
  93.581 +#ifdef GZIP
  93.582 +        if (s->wrap == 2) {
  93.583 +            strm->adler = crc32(0L, Z_NULL, 0);
  93.584 +            put_byte(s, 31);
  93.585 +            put_byte(s, 139);
  93.586 +            put_byte(s, 8);
  93.587 +            if (s->gzhead == NULL) {
  93.588 +                put_byte(s, 0);
  93.589 +                put_byte(s, 0);
  93.590 +                put_byte(s, 0);
  93.591 +                put_byte(s, 0);
  93.592 +                put_byte(s, 0);
  93.593 +                put_byte(s, s->level == 9 ? 2 :
  93.594 +                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  93.595 +                             4 : 0));
  93.596 +                put_byte(s, OS_CODE);
  93.597 +                s->status = BUSY_STATE;
  93.598 +            }
  93.599 +            else {
  93.600 +                put_byte(s, (s->gzhead->text ? 1 : 0) +
  93.601 +                            (s->gzhead->hcrc ? 2 : 0) +
  93.602 +                            (s->gzhead->extra == Z_NULL ? 0 : 4) +
  93.603 +                            (s->gzhead->name == Z_NULL ? 0 : 8) +
  93.604 +                            (s->gzhead->comment == Z_NULL ? 0 : 16)
  93.605 +                        );
  93.606 +                put_byte(s, (Byte)(s->gzhead->time & 0xff));
  93.607 +                put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  93.608 +                put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  93.609 +                put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  93.610 +                put_byte(s, s->level == 9 ? 2 :
  93.611 +                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  93.612 +                             4 : 0));
  93.613 +                put_byte(s, s->gzhead->os & 0xff);
  93.614 +                if (s->gzhead->extra != NULL) {
  93.615 +                    put_byte(s, s->gzhead->extra_len & 0xff);
  93.616 +                    put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  93.617 +                }
  93.618 +                if (s->gzhead->hcrc)
  93.619 +                    strm->adler = crc32(strm->adler, s->pending_buf,
  93.620 +                                        s->pending);
  93.621 +                s->gzindex = 0;
  93.622 +                s->status = EXTRA_STATE;
  93.623 +            }
  93.624 +        }
  93.625 +        else
  93.626 +#endif
  93.627 +        {
  93.628 +            uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  93.629 +            uInt level_flags;
  93.630 +
  93.631 +            if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  93.632 +                level_flags = 0;
  93.633 +            else if (s->level < 6)
  93.634 +                level_flags = 1;
  93.635 +            else if (s->level == 6)
  93.636 +                level_flags = 2;
  93.637 +            else
  93.638 +                level_flags = 3;
  93.639 +            header |= (level_flags << 6);
  93.640 +            if (s->strstart != 0) header |= PRESET_DICT;
  93.641 +            header += 31 - (header % 31);
  93.642 +
  93.643 +            s->status = BUSY_STATE;
  93.644 +            putShortMSB(s, header);
  93.645 +
  93.646 +            /* Save the adler32 of the preset dictionary: */
  93.647 +            if (s->strstart != 0) {
  93.648 +                putShortMSB(s, (uInt)(strm->adler >> 16));
  93.649 +                putShortMSB(s, (uInt)(strm->adler & 0xffff));
  93.650 +            }
  93.651 +            strm->adler = adler32(0L, Z_NULL, 0);
  93.652 +        }
  93.653 +    }
  93.654 +#ifdef GZIP
  93.655 +    if (s->status == EXTRA_STATE) {
  93.656 +        if (s->gzhead->extra != NULL) {
  93.657 +            uInt beg = s->pending;  /* start of bytes to update crc */
  93.658 +
  93.659 +            while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  93.660 +                if (s->pending == s->pending_buf_size) {
  93.661 +                    if (s->gzhead->hcrc && s->pending > beg)
  93.662 +                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
  93.663 +                                            s->pending - beg);
  93.664 +                    flush_pending(strm);
  93.665 +                    beg = s->pending;
  93.666 +                    if (s->pending == s->pending_buf_size)
  93.667 +                        break;
  93.668 +                }
  93.669 +                put_byte(s, s->gzhead->extra[s->gzindex]);
  93.670 +                s->gzindex++;
  93.671 +            }
  93.672 +            if (s->gzhead->hcrc && s->pending > beg)
  93.673 +                strm->adler = crc32(strm->adler, s->pending_buf + beg,
  93.674 +                                    s->pending - beg);
  93.675 +            if (s->gzindex == s->gzhead->extra_len) {
  93.676 +                s->gzindex = 0;
  93.677 +                s->status = NAME_STATE;
  93.678 +            }
  93.679 +        }
  93.680 +        else
  93.681 +            s->status = NAME_STATE;
  93.682 +    }
  93.683 +    if (s->status == NAME_STATE) {
  93.684 +        if (s->gzhead->name != NULL) {
  93.685 +            uInt beg = s->pending;  /* start of bytes to update crc */
  93.686 +            int val;
  93.687 +
  93.688 +            do {
  93.689 +                if (s->pending == s->pending_buf_size) {
  93.690 +                    if (s->gzhead->hcrc && s->pending > beg)
  93.691 +                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
  93.692 +                                            s->pending - beg);
  93.693 +                    flush_pending(strm);
  93.694 +                    beg = s->pending;
  93.695 +                    if (s->pending == s->pending_buf_size) {
  93.696 +                        val = 1;
  93.697 +                        break;
  93.698 +                    }
  93.699 +                }
  93.700 +                val = s->gzhead->name[s->gzindex++];
  93.701 +                put_byte(s, val);
  93.702 +            } while (val != 0);
  93.703 +            if (s->gzhead->hcrc && s->pending > beg)
  93.704 +                strm->adler = crc32(strm->adler, s->pending_buf + beg,
  93.705 +                                    s->pending - beg);
  93.706 +            if (val == 0) {
  93.707 +                s->gzindex = 0;
  93.708 +                s->status = COMMENT_STATE;
  93.709 +            }
  93.710 +        }
  93.711 +        else
  93.712 +            s->status = COMMENT_STATE;
  93.713 +    }
  93.714 +    if (s->status == COMMENT_STATE) {
  93.715 +        if (s->gzhead->comment != NULL) {
  93.716 +            uInt beg = s->pending;  /* start of bytes to update crc */
  93.717 +            int val;
  93.718 +
  93.719 +            do {
  93.720 +                if (s->pending == s->pending_buf_size) {
  93.721 +                    if (s->gzhead->hcrc && s->pending > beg)
  93.722 +                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
  93.723 +                                            s->pending - beg);
  93.724 +                    flush_pending(strm);
  93.725 +                    beg = s->pending;
  93.726 +                    if (s->pending == s->pending_buf_size) {
  93.727 +                        val = 1;
  93.728 +                        break;
  93.729 +                    }
  93.730 +                }
  93.731 +                val = s->gzhead->comment[s->gzindex++];
  93.732 +                put_byte(s, val);
  93.733 +            } while (val != 0);
  93.734 +            if (s->gzhead->hcrc && s->pending > beg)
  93.735 +                strm->adler = crc32(strm->adler, s->pending_buf + beg,
  93.736 +                                    s->pending - beg);
  93.737 +            if (val == 0)
  93.738 +                s->status = HCRC_STATE;
  93.739 +        }
  93.740 +        else
  93.741 +            s->status = HCRC_STATE;
  93.742 +    }
  93.743 +    if (s->status == HCRC_STATE) {
  93.744 +        if (s->gzhead->hcrc) {
  93.745 +            if (s->pending + 2 > s->pending_buf_size)
  93.746 +                flush_pending(strm);
  93.747 +            if (s->pending + 2 <= s->pending_buf_size) {
  93.748 +                put_byte(s, (Byte)(strm->adler & 0xff));
  93.749 +                put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  93.750 +                strm->adler = crc32(0L, Z_NULL, 0);
  93.751 +                s->status = BUSY_STATE;
  93.752 +            }
  93.753 +        }
  93.754 +        else
  93.755 +            s->status = BUSY_STATE;
  93.756 +    }
  93.757 +#endif
  93.758 +
  93.759 +    /* Flush as much pending output as possible */
  93.760 +    if (s->pending != 0) {
  93.761 +        flush_pending(strm);
  93.762 +        if (strm->avail_out == 0) {
  93.763 +            /* Since avail_out is 0, deflate will be called again with
  93.764 +             * more output space, but possibly with both pending and
  93.765 +             * avail_in equal to zero. There won't be anything to do,
  93.766 +             * but this is not an error situation so make sure we
  93.767 +             * return OK instead of BUF_ERROR at next call of deflate:
  93.768 +             */
  93.769 +            s->last_flush = -1;
  93.770 +            return Z_OK;
  93.771 +        }
  93.772 +
  93.773 +    /* Make sure there is something to do and avoid duplicate consecutive
  93.774 +     * flushes. For repeated and useless calls with Z_FINISH, we keep
  93.775 +     * returning Z_STREAM_END instead of Z_BUF_ERROR.
  93.776 +     */
  93.777 +    } else if (strm->avail_in == 0 && flush <= old_flush &&
  93.778 +               flush != Z_FINISH) {
  93.779 +        ERR_RETURN(strm, Z_BUF_ERROR);
  93.780 +    }
  93.781 +
  93.782 +    /* User must not provide more input after the first FINISH: */
  93.783 +    if (s->status == FINISH_STATE && strm->avail_in != 0) {
  93.784 +        ERR_RETURN(strm, Z_BUF_ERROR);
  93.785 +    }
  93.786 +
  93.787 +    /* Start a new block or continue the current one.
  93.788 +     */
  93.789 +    if (strm->avail_in != 0 || s->lookahead != 0 ||
  93.790 +        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  93.791 +        block_state bstate;
  93.792 +
  93.793 +        bstate = (*(configuration_table[s->level].func))(s, flush);
  93.794 +
  93.795 +        if (bstate == finish_started || bstate == finish_done) {
  93.796 +            s->status = FINISH_STATE;
  93.797 +        }
  93.798 +        if (bstate == need_more || bstate == finish_started) {
  93.799 +            if (strm->avail_out == 0) {
  93.800 +                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  93.801 +            }
  93.802 +            return Z_OK;
  93.803 +            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  93.804 +             * of deflate should use the same flush parameter to make sure
  93.805 +             * that the flush is complete. So we don't have to output an
  93.806 +             * empty block here, this will be done at next call. This also
  93.807 +             * ensures that for a very small output buffer, we emit at most
  93.808 +             * one empty block.
  93.809 +             */
  93.810 +        }
  93.811 +        if (bstate == block_done) {
  93.812 +            if (flush == Z_PARTIAL_FLUSH) {
  93.813 +                _tr_align(s);
  93.814 +            } else { /* FULL_FLUSH or SYNC_FLUSH */
  93.815 +                _tr_stored_block(s, (char*)0, 0L, 0);
  93.816 +                /* For a full flush, this empty block will be recognized
  93.817 +                 * as a special marker by inflate_sync().
  93.818 +                 */
  93.819 +                if (flush == Z_FULL_FLUSH) {
  93.820 +                    CLEAR_HASH(s);             /* forget history */
  93.821 +                }
  93.822 +            }
  93.823 +            flush_pending(strm);
  93.824 +            if (strm->avail_out == 0) {
  93.825 +              s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  93.826 +              return Z_OK;
  93.827 +            }
  93.828 +        }
  93.829 +    }
  93.830 +    Assert(strm->avail_out > 0, "bug2");
  93.831 +
  93.832 +    if (flush != Z_FINISH) return Z_OK;
  93.833 +    if (s->wrap <= 0) return Z_STREAM_END;
  93.834 +
  93.835 +    /* Write the trailer */
  93.836 +#ifdef GZIP
  93.837 +    if (s->wrap == 2) {
  93.838 +        put_byte(s, (Byte)(strm->adler & 0xff));
  93.839 +        put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  93.840 +        put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  93.841 +        put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  93.842 +        put_byte(s, (Byte)(strm->total_in & 0xff));
  93.843 +        put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  93.844 +        put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  93.845 +        put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  93.846 +    }
  93.847 +    else
  93.848 +#endif
  93.849 +    {
  93.850 +        putShortMSB(s, (uInt)(strm->adler >> 16));
  93.851 +        putShortMSB(s, (uInt)(strm->adler & 0xffff));
  93.852 +    }
  93.853 +    flush_pending(strm);
  93.854 +    /* If avail_out is zero, the application will call deflate again
  93.855 +     * to flush the rest.
  93.856 +     */
  93.857 +    if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  93.858 +    return s->pending != 0 ? Z_OK : Z_STREAM_END;
  93.859 +}
  93.860 +
  93.861 +/* ========================================================================= */
  93.862 +int ZEXPORT deflateEnd (strm)
  93.863 +    z_streamp strm;
  93.864 +{
  93.865 +    int status;
  93.866 +
  93.867 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  93.868 +
  93.869 +    status = strm->state->status;
  93.870 +    if (status != INIT_STATE &&
  93.871 +        status != EXTRA_STATE &&
  93.872 +        status != NAME_STATE &&
  93.873 +        status != COMMENT_STATE &&
  93.874 +        status != HCRC_STATE &&
  93.875 +        status != BUSY_STATE &&
  93.876 +        status != FINISH_STATE) {
  93.877 +      return Z_STREAM_ERROR;
  93.878 +    }
  93.879 +
  93.880 +    /* Deallocate in reverse order of allocations: */
  93.881 +    TRY_FREE(strm, strm->state->pending_buf);
  93.882 +    TRY_FREE(strm, strm->state->head);
  93.883 +    TRY_FREE(strm, strm->state->prev);
  93.884 +    TRY_FREE(strm, strm->state->window);
  93.885 +
  93.886 +    ZFREE(strm, strm->state);
  93.887 +    strm->state = Z_NULL;
  93.888 +
  93.889 +    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  93.890 +}
  93.891 +
  93.892 +/* =========================================================================
  93.893 + * Copy the source state to the destination state.
  93.894 + * To simplify the source, this is not supported for 16-bit MSDOS (which
  93.895 + * doesn't have enough memory anyway to duplicate compression states).
  93.896 + */
  93.897 +int ZEXPORT deflateCopy (dest, source)
  93.898 +    z_streamp dest;
  93.899 +    z_streamp source;
  93.900 +{
  93.901 +#ifdef MAXSEG_64K
  93.902 +    return Z_STREAM_ERROR;
  93.903 +#else
  93.904 +    deflate_state *ds;
  93.905 +    deflate_state *ss;
  93.906 +    ushf *overlay;
  93.907 +
  93.908 +
  93.909 +    if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  93.910 +        return Z_STREAM_ERROR;
  93.911 +    }
  93.912 +
  93.913 +    ss = source->state;
  93.914 +
  93.915 +    zmemcpy(dest, source, sizeof(z_stream));
  93.916 +
  93.917 +    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  93.918 +    if (ds == Z_NULL) return Z_MEM_ERROR;
  93.919 +    dest->state = (struct internal_state FAR *) ds;
  93.920 +    zmemcpy(ds, ss, sizeof(deflate_state));
  93.921 +    ds->strm = dest;
  93.922 +
  93.923 +    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  93.924 +    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
  93.925 +    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
  93.926 +    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  93.927 +    ds->pending_buf = (uchf *) overlay;
  93.928 +
  93.929 +    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  93.930 +        ds->pending_buf == Z_NULL) {
  93.931 +        deflateEnd (dest);
  93.932 +        return Z_MEM_ERROR;
  93.933 +    }
  93.934 +    /* following zmemcpy do not work for 16-bit MSDOS */
  93.935 +    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  93.936 +    zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  93.937 +    zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  93.938 +    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  93.939 +
  93.940 +    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  93.941 +    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  93.942 +    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  93.943 +
  93.944 +    ds->l_desc.dyn_tree = ds->dyn_ltree;
  93.945 +    ds->d_desc.dyn_tree = ds->dyn_dtree;
  93.946 +    ds->bl_desc.dyn_tree = ds->bl_tree;
  93.947 +
  93.948 +    return Z_OK;
  93.949 +#endif /* MAXSEG_64K */
  93.950 +}
  93.951 +
  93.952 +/* ===========================================================================
  93.953 + * Read a new buffer from the current input stream, update the adler32
  93.954 + * and total number of bytes read.  All deflate() input goes through
  93.955 + * this function so some applications may wish to modify it to avoid
  93.956 + * allocating a large strm->next_in buffer and copying from it.
  93.957 + * (See also flush_pending()).
  93.958 + */
  93.959 +local int read_buf(strm, buf, size)
  93.960 +    z_streamp strm;
  93.961 +    Bytef *buf;
  93.962 +    unsigned size;
  93.963 +{
  93.964 +    unsigned len = strm->avail_in;
  93.965 +
  93.966 +    if (len > size) len = size;
  93.967 +    if (len == 0) return 0;
  93.968 +
  93.969 +    strm->avail_in  -= len;
  93.970 +
  93.971 +    if (strm->state->wrap == 1) {
  93.972 +        strm->adler = adler32(strm->adler, strm->next_in, len);
  93.973 +    }
  93.974 +#ifdef GZIP
  93.975 +    else if (strm->state->wrap == 2) {
  93.976 +        strm->adler = crc32(strm->adler, strm->next_in, len);
  93.977 +    }
  93.978 +#endif
  93.979 +    zmemcpy(buf, strm->next_in, len);
  93.980 +    strm->next_in  += len;
  93.981 +    strm->total_in += len;
  93.982 +
  93.983 +    return (int)len;
  93.984 +}
  93.985 +
  93.986 +/* ===========================================================================
  93.987 + * Initialize the "longest match" routines for a new zlib stream
  93.988 + */
  93.989 +local void lm_init (s)
  93.990 +    deflate_state *s;
  93.991 +{
  93.992 +    s->window_size = (ulg)2L*s->w_size;
  93.993 +
  93.994 +    CLEAR_HASH(s);
  93.995 +
  93.996 +    /* Set the default configuration parameters:
  93.997 +     */
  93.998 +    s->max_lazy_match   = configuration_table[s->level].max_lazy;
  93.999 +    s->good_match       = configuration_table[s->level].good_length;
 93.1000 +    s->nice_match       = configuration_table[s->level].nice_length;
 93.1001 +    s->max_chain_length = configuration_table[s->level].max_chain;
 93.1002 +
 93.1003 +    s->strstart = 0;
 93.1004 +    s->block_start = 0L;
 93.1005 +    s->lookahead = 0;
 93.1006 +    s->match_length = s->prev_length = MIN_MATCH-1;
 93.1007 +    s->match_available = 0;
 93.1008 +    s->ins_h = 0;
 93.1009 +#ifndef FASTEST
 93.1010 +#ifdef ASMV
 93.1011 +    match_init(); /* initialize the asm code */
 93.1012 +#endif
 93.1013 +#endif
 93.1014 +}
 93.1015 +
 93.1016 +#ifndef FASTEST
 93.1017 +/* ===========================================================================
 93.1018 + * Set match_start to the longest match starting at the given string and
 93.1019 + * return its length. Matches shorter or equal to prev_length are discarded,
 93.1020 + * in which case the result is equal to prev_length and match_start is
 93.1021 + * garbage.
 93.1022 + * IN assertions: cur_match is the head of the hash chain for the current
 93.1023 + *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
 93.1024 + * OUT assertion: the match length is not greater than s->lookahead.
 93.1025 + */
 93.1026 +#ifndef ASMV
 93.1027 +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
 93.1028 + * match.S. The code will be functionally equivalent.
 93.1029 + */
 93.1030 +local uInt longest_match(s, cur_match)
 93.1031 +    deflate_state *s;
 93.1032 +    IPos cur_match;                             /* current match */
 93.1033 +{
 93.1034 +    unsigned chain_length = s->max_chain_length;/* max hash chain length */
 93.1035 +    register Bytef *scan = s->window + s->strstart; /* current string */
 93.1036 +    register Bytef *match;                       /* matched string */
 93.1037 +    register int len;                           /* length of current match */
 93.1038 +    int best_len = s->prev_length;              /* best match length so far */
 93.1039 +    int nice_match = s->nice_match;             /* stop if match long enough */
 93.1040 +    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
 93.1041 +        s->strstart - (IPos)MAX_DIST(s) : NIL;
 93.1042 +    /* Stop when cur_match becomes <= limit. To simplify the code,
 93.1043 +     * we prevent matches with the string of window index 0.
 93.1044 +     */
 93.1045 +    Posf *prev = s->prev;
 93.1046 +    uInt wmask = s->w_mask;
 93.1047 +
 93.1048 +#ifdef UNALIGNED_OK
 93.1049 +    /* Compare two bytes at a time. Note: this is not always beneficial.
 93.1050 +     * Try with and without -DUNALIGNED_OK to check.
 93.1051 +     */
 93.1052 +    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
 93.1053 +    register ush scan_start = *(ushf*)scan;
 93.1054 +    register ush scan_end   = *(ushf*)(scan+best_len-1);
 93.1055 +#else
 93.1056 +    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
 93.1057 +    register Byte scan_end1  = scan[best_len-1];
 93.1058 +    register Byte scan_end   = scan[best_len];
 93.1059 +#endif
 93.1060 +
 93.1061 +    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
 93.1062 +     * It is easy to get rid of this optimization if necessary.
 93.1063 +     */
 93.1064 +    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
 93.1065 +
 93.1066 +    /* Do not waste too much time if we already have a good match: */
 93.1067 +    if (s->prev_length >= s->good_match) {
 93.1068 +        chain_length >>= 2;
 93.1069 +    }
 93.1070 +    /* Do not look for matches beyond the end of the input. This is necessary
 93.1071 +     * to make deflate deterministic.
 93.1072 +     */
 93.1073 +    if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
 93.1074 +
 93.1075 +    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
 93.1076 +
 93.1077 +    do {
 93.1078 +        Assert(cur_match < s->strstart, "no future");
 93.1079 +        match = s->window + cur_match;
 93.1080 +
 93.1081 +        /* Skip to next match if the match length cannot increase
 93.1082 +         * or if the match length is less than 2.  Note that the checks below
 93.1083 +         * for insufficient lookahead only occur occasionally for performance
 93.1084 +         * reasons.  Therefore uninitialized memory will be accessed, and
 93.1085 +         * conditional jumps will be made that depend on those values.
 93.1086 +         * However the length of the match is limited to the lookahead, so
 93.1087 +         * the output of deflate is not affected by the uninitialized values.
 93.1088 +         */
 93.1089 +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
 93.1090 +        /* This code assumes sizeof(unsigned short) == 2. Do not use
 93.1091 +         * UNALIGNED_OK if your compiler uses a different size.
 93.1092 +         */
 93.1093 +        if (*(ushf*)(match+best_len-1) != scan_end ||
 93.1094 +            *(ushf*)match != scan_start) continue;
 93.1095 +
 93.1096 +        /* It is not necessary to compare scan[2] and match[2] since they are
 93.1097 +         * always equal when the other bytes match, given that the hash keys
 93.1098 +         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
 93.1099 +         * strstart+3, +5, ... up to strstart+257. We check for insufficient
 93.1100 +         * lookahead only every 4th comparison; the 128th check will be made
 93.1101 +         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
 93.1102 +         * necessary to put more guard bytes at the end of the window, or
 93.1103 +         * to check more often for insufficient lookahead.
 93.1104 +         */
 93.1105 +        Assert(scan[2] == match[2], "scan[2]?");
 93.1106 +        scan++, match++;
 93.1107 +        do {
 93.1108 +        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
 93.1109 +                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
 93.1110 +                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
 93.1111 +                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
 93.1112 +                 scan < strend);
 93.1113 +        /* The funny "do {}" generates better code on most compilers */
 93.1114 +
 93.1115 +        /* Here, scan <= window+strstart+257 */
 93.1116 +        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
 93.1117 +        if (*scan == *match) scan++;
 93.1118 +
 93.1119 +        len = (MAX_MATCH - 1) - (int)(strend-scan);
 93.1120 +        scan = strend - (MAX_MATCH-1);
 93.1121 +
 93.1122 +#else /* UNALIGNED_OK */
 93.1123 +
 93.1124 +        if (match[best_len]   != scan_end  ||
 93.1125 +            match[best_len-1] != scan_end1 ||
 93.1126 +            *match            != *scan     ||
 93.1127 +            *++match          != scan[1])      continue;
 93.1128 +
 93.1129 +        /* The check at best_len-1 can be removed because it will be made
 93.1130 +         * again later. (This heuristic is not always a win.)
 93.1131 +         * It is not necessary to compare scan[2] and match[2] since they
 93.1132 +         * are always equal when the other bytes match, given that
 93.1133 +         * the hash keys are equal and that HASH_BITS >= 8.
 93.1134 +         */
 93.1135 +        scan += 2, match++;
 93.1136 +        Assert(*scan == *match, "match[2]?");
 93.1137 +
 93.1138 +        /* We check for insufficient lookahead only every 8th comparison;
 93.1139 +         * the 256th check will be made at strstart+258.
 93.1140 +         */
 93.1141 +        do {
 93.1142 +        } while (*++scan == *++match && *++scan == *++match &&
 93.1143 +                 *++scan == *++match && *++scan == *++match &&
 93.1144 +                 *++scan == *++match && *++scan == *++match &&
 93.1145 +                 *++scan == *++match && *++scan == *++match &&
 93.1146 +                 scan < strend);
 93.1147 +
 93.1148 +        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
 93.1149 +
 93.1150 +        len = MAX_MATCH - (int)(strend - scan);
 93.1151 +        scan = strend - MAX_MATCH;
 93.1152 +
 93.1153 +#endif /* UNALIGNED_OK */
 93.1154 +
 93.1155 +        if (len > best_len) {
 93.1156 +            s->match_start = cur_match;
 93.1157 +            best_len = len;
 93.1158 +            if (len >= nice_match) break;
 93.1159 +#ifdef UNALIGNED_OK
 93.1160 +            scan_end = *(ushf*)(scan+best_len-1);
 93.1161 +#else
 93.1162 +            scan_end1  = scan[best_len-1];
 93.1163 +            scan_end   = scan[best_len];
 93.1164 +#endif
 93.1165 +        }
 93.1166 +    } while ((cur_match = prev[cur_match & wmask]) > limit
 93.1167 +             && --chain_length != 0);
 93.1168 +
 93.1169 +    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
 93.1170 +    return s->lookahead;
 93.1171 +}
 93.1172 +#endif /* ASMV */
 93.1173 +#endif /* FASTEST */
 93.1174 +
 93.1175 +/* ---------------------------------------------------------------------------
 93.1176 + * Optimized version for level == 1 or strategy == Z_RLE only
 93.1177 + */
 93.1178 +local uInt longest_match_fast(s, cur_match)
 93.1179 +    deflate_state *s;
 93.1180 +    IPos cur_match;                             /* current match */
 93.1181 +{
 93.1182 +    register Bytef *scan = s->window + s->strstart; /* current string */
 93.1183 +    register Bytef *match;                       /* matched string */
 93.1184 +    register int len;                           /* length of current match */
 93.1185 +    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
 93.1186 +
 93.1187 +    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
 93.1188 +     * It is easy to get rid of this optimization if necessary.
 93.1189 +     */
 93.1190 +    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
 93.1191 +
 93.1192 +    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
 93.1193 +
 93.1194 +    Assert(cur_match < s->strstart, "no future");
 93.1195 +
 93.1196 +    match = s->window + cur_match;
 93.1197 +
 93.1198 +    /* Return failure if the match length is less than 2:
 93.1199 +     */
 93.1200 +    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
 93.1201 +
 93.1202 +    /* The check at best_len-1 can be removed because it will be made
 93.1203 +     * again later. (This heuristic is not always a win.)
 93.1204 +     * It is not necessary to compare scan[2] and match[2] since they
 93.1205 +     * are always equal when the other bytes match, given that
 93.1206 +     * the hash keys are equal and that HASH_BITS >= 8.
 93.1207 +     */
 93.1208 +    scan += 2, match += 2;
 93.1209 +    Assert(*scan == *match, "match[2]?");
 93.1210 +
 93.1211 +    /* We check for insufficient lookahead only every 8th comparison;
 93.1212 +     * the 256th check will be made at strstart+258.
 93.1213 +     */
 93.1214 +    do {
 93.1215 +    } while (*++scan == *++match && *++scan == *++match &&
 93.1216 +             *++scan == *++match && *++scan == *++match &&
 93.1217 +             *++scan == *++match && *++scan == *++match &&
 93.1218 +             *++scan == *++match && *++scan == *++match &&
 93.1219 +             scan < strend);
 93.1220 +
 93.1221 +    Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
 93.1222 +
 93.1223 +    len = MAX_MATCH - (int)(strend - scan);
 93.1224 +
 93.1225 +    if (len < MIN_MATCH) return MIN_MATCH - 1;
 93.1226 +
 93.1227 +    s->match_start = cur_match;
 93.1228 +    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
 93.1229 +}
 93.1230 +
 93.1231 +#ifdef DEBUG
 93.1232 +/* ===========================================================================
 93.1233 + * Check that the match at match_start is indeed a match.
 93.1234 + */
 93.1235 +local void check_match(s, start, match, length)
 93.1236 +    deflate_state *s;
 93.1237 +    IPos start, match;
 93.1238 +    int length;
 93.1239 +{
 93.1240 +    /* check that the match is indeed a match */
 93.1241 +    if (zmemcmp(s->window + match,
 93.1242 +                s->window + start, length) != EQUAL) {
 93.1243 +        fprintf(stderr, " start %u, match %u, length %d\n",
 93.1244 +                start, match, length);
 93.1245 +        do {
 93.1246 +            fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
 93.1247 +        } while (--length != 0);
 93.1248 +        z_error("invalid match");
 93.1249 +    }
 93.1250 +    if (z_verbose > 1) {
 93.1251 +        fprintf(stderr,"\\[%d,%d]", start-match, length);
 93.1252 +        do { putc(s->window[start++], stderr); } while (--length != 0);
 93.1253 +    }
 93.1254 +}
 93.1255 +#else
 93.1256 +#  define check_match(s, start, match, length)
 93.1257 +#endif /* DEBUG */
 93.1258 +
 93.1259 +/* ===========================================================================
 93.1260 + * Fill the window when the lookahead becomes insufficient.
 93.1261 + * Updates strstart and lookahead.
 93.1262 + *
 93.1263 + * IN assertion: lookahead < MIN_LOOKAHEAD
 93.1264 + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
 93.1265 + *    At least one byte has been read, or avail_in == 0; reads are
 93.1266 + *    performed for at least two bytes (required for the zip translate_eol
 93.1267 + *    option -- not supported here).
 93.1268 + */
 93.1269 +local void fill_window(s)
 93.1270 +    deflate_state *s;
 93.1271 +{
 93.1272 +    register unsigned n, m;
 93.1273 +    register Posf *p;
 93.1274 +    unsigned more;    /* Amount of free space at the end of the window. */
 93.1275 +    uInt wsize = s->w_size;
 93.1276 +
 93.1277 +    do {
 93.1278 +        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
 93.1279 +
 93.1280 +        /* Deal with !@#$% 64K limit: */
 93.1281 +        if (sizeof(int) <= 2) {
 93.1282 +            if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
 93.1283 +                more = wsize;
 93.1284 +
 93.1285 +            } else if (more == (unsigned)(-1)) {
 93.1286 +                /* Very unlikely, but possible on 16 bit machine if
 93.1287 +                 * strstart == 0 && lookahead == 1 (input done a byte at time)
 93.1288 +                 */
 93.1289 +                more--;
 93.1290 +            }
 93.1291 +        }
 93.1292 +
 93.1293 +        /* If the window is almost full and there is insufficient lookahead,
 93.1294 +         * move the upper half to the lower one to make room in the upper half.
 93.1295 +         */
 93.1296 +        if (s->strstart >= wsize+MAX_DIST(s)) {
 93.1297 +
 93.1298 +            zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
 93.1299 +            s->match_start -= wsize;
 93.1300 +            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
 93.1301 +            s->block_start -= (long) wsize;
 93.1302 +
 93.1303 +            /* Slide the hash table (could be avoided with 32 bit values
 93.1304 +               at the expense of memory usage). We slide even when level == 0
 93.1305 +               to keep the hash table consistent if we switch back to level > 0
 93.1306 +               later. (Using level 0 permanently is not an optimal usage of
 93.1307 +               zlib, so we don't care about this pathological case.)
 93.1308 +             */
 93.1309 +            /* %%% avoid this when Z_RLE */
 93.1310 +            n = s->hash_size;
 93.1311 +            p = &s->head[n];
 93.1312 +            do {
 93.1313 +                m = *--p;
 93.1314 +                *p = (Pos)(m >= wsize ? m-wsize : NIL);
 93.1315 +            } while (--n);
 93.1316 +
 93.1317 +            n = wsize;
 93.1318 +#ifndef FASTEST
 93.1319 +            p = &s->prev[n];
 93.1320 +            do {
 93.1321 +                m = *--p;
 93.1322 +                *p = (Pos)(m >= wsize ? m-wsize : NIL);
 93.1323 +                /* If n is not on any hash chain, prev[n] is garbage but
 93.1324 +                 * its value will never be used.
 93.1325 +                 */
 93.1326 +            } while (--n);
 93.1327 +#endif
 93.1328 +            more += wsize;
 93.1329 +        }
 93.1330 +        if (s->strm->avail_in == 0) return;
 93.1331 +
 93.1332 +        /* If there was no sliding:
 93.1333 +         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
 93.1334 +         *    more == window_size - lookahead - strstart
 93.1335 +         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
 93.1336 +         * => more >= window_size - 2*WSIZE + 2
 93.1337 +         * In the BIG_MEM or MMAP case (not yet supported),
 93.1338 +         *   window_size == input_size + MIN_LOOKAHEAD  &&
 93.1339 +         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
 93.1340 +         * Otherwise, window_size == 2*WSIZE so more >= 2.
 93.1341 +         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
 93.1342 +         */
 93.1343 +        Assert(more >= 2, "more < 2");
 93.1344 +
 93.1345 +        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
 93.1346 +        s->lookahead += n;
 93.1347 +
 93.1348 +        /* Initialize the hash value now that we have some input: */
 93.1349 +        if (s->lookahead >= MIN_MATCH) {
 93.1350 +            s->ins_h = s->window[s->strstart];
 93.1351 +            UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
 93.1352 +#if MIN_MATCH != 3
 93.1353 +            Call UPDATE_HASH() MIN_MATCH-3 more times
 93.1354 +#endif
 93.1355 +        }
 93.1356 +        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
 93.1357 +         * but this is not important since only literal bytes will be emitted.
 93.1358 +         */
 93.1359 +
 93.1360 +    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
 93.1361 +}
 93.1362 +
 93.1363 +/* ===========================================================================
 93.1364 + * Flush the current block, with given end-of-file flag.
 93.1365 + * IN assertion: strstart is set to the end of the current match.
 93.1366 + */
 93.1367 +#define FLUSH_BLOCK_ONLY(s, eof) { \
 93.1368 +   _tr_flush_block(s, (s->block_start >= 0L ? \
 93.1369 +                   (charf *)&s->window[(unsigned)s->block_start] : \
 93.1370 +                   (charf *)Z_NULL), \
 93.1371 +                (ulg)((long)s->strstart - s->block_start), \
 93.1372 +                (eof)); \
 93.1373 +   s->block_start = s->strstart; \
 93.1374 +   flush_pending(s->strm); \
 93.1375 +   Tracev((stderr,"[FLUSH]")); \
 93.1376 +}
 93.1377 +
 93.1378 +/* Same but force premature exit if necessary. */
 93.1379 +#define FLUSH_BLOCK(s, eof) { \
 93.1380 +   FLUSH_BLOCK_ONLY(s, eof); \
 93.1381 +   if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
 93.1382 +}
 93.1383 +
 93.1384 +/* ===========================================================================
 93.1385 + * Copy without compression as much as possible from the input stream, return
 93.1386 + * the current block state.
 93.1387 + * This function does not insert new strings in the dictionary since
 93.1388 + * uncompressible data is probably not useful. This function is used
 93.1389 + * only for the level=0 compression option.
 93.1390 + * NOTE: this function should be optimized to avoid extra copying from
 93.1391 + * window to pending_buf.
 93.1392 + */
 93.1393 +local block_state deflate_stored(s, flush)
 93.1394 +    deflate_state *s;
 93.1395 +    int flush;
 93.1396 +{
 93.1397 +    /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
 93.1398 +     * to pending_buf_size, and each stored block has a 5 byte header:
 93.1399 +     */
 93.1400 +    ulg max_block_size = 0xffff;
 93.1401 +    ulg max_start;
 93.1402 +
 93.1403 +    if (max_block_size > s->pending_buf_size - 5) {
 93.1404 +        max_block_size = s->pending_buf_size - 5;
 93.1405 +    }
 93.1406 +
 93.1407 +    /* Copy as much as possible from input to output: */
 93.1408 +    for (;;) {
 93.1409 +        /* Fill the window as much as possible: */
 93.1410 +        if (s->lookahead <= 1) {
 93.1411 +
 93.1412 +            Assert(s->strstart < s->w_size+MAX_DIST(s) ||
 93.1413 +                   s->block_start >= (long)s->w_size, "slide too late");
 93.1414 +
 93.1415 +            fill_window(s);
 93.1416 +            if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
 93.1417 +
 93.1418 +            if (s->lookahead == 0) break; /* flush the current block */
 93.1419 +        }
 93.1420 +        Assert(s->block_start >= 0L, "block gone");
 93.1421 +
 93.1422 +        s->strstart += s->lookahead;
 93.1423 +        s->lookahead = 0;
 93.1424 +
 93.1425 +        /* Emit a stored block if pending_buf will be full: */
 93.1426 +        max_start = s->block_start + max_block_size;
 93.1427 +        if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
 93.1428 +            /* strstart == 0 is possible when wraparound on 16-bit machine */
 93.1429 +            s->lookahead = (uInt)(s->strstart - max_start);
 93.1430 +            s->strstart = (uInt)max_start;
 93.1431 +            FLUSH_BLOCK(s, 0);
 93.1432 +        }
 93.1433 +        /* Flush if we may have to slide, otherwise block_start may become
 93.1434 +         * negative and the data will be gone:
 93.1435 +         */
 93.1436 +        if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
 93.1437 +            FLUSH_BLOCK(s, 0);
 93.1438 +        }
 93.1439 +    }
 93.1440 +    FLUSH_BLOCK(s, flush == Z_FINISH);
 93.1441 +    return flush == Z_FINISH ? finish_done : block_done;
 93.1442 +}
 93.1443 +
 93.1444 +/* ===========================================================================
 93.1445 + * Compress as much as possible from the input stream, return the current
 93.1446 + * block state.
 93.1447 + * This function does not perform lazy evaluation of matches and inserts
 93.1448 + * new strings in the dictionary only for unmatched strings or for short
 93.1449 + * matches. It is used only for the fast compression options.
 93.1450 + */
 93.1451 +local block_state deflate_fast(s, flush)
 93.1452 +    deflate_state *s;
 93.1453 +    int flush;
 93.1454 +{
 93.1455 +    IPos hash_head = NIL; /* head of the hash chain */
 93.1456 +    int bflush;           /* set if current block must be flushed */
 93.1457 +
 93.1458 +    for (;;) {
 93.1459 +        /* Make sure that we always have enough lookahead, except
 93.1460 +         * at the end of the input file. We need MAX_MATCH bytes
 93.1461 +         * for the next match, plus MIN_MATCH bytes to insert the
 93.1462 +         * string following the next match.
 93.1463 +         */
 93.1464 +        if (s->lookahead < MIN_LOOKAHEAD) {
 93.1465 +            fill_window(s);
 93.1466 +            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
 93.1467 +                return need_more;
 93.1468 +            }
 93.1469 +            if (s->lookahead == 0) break; /* flush the current block */
 93.1470 +        }
 93.1471 +
 93.1472 +        /* Insert the string window[strstart .. strstart+2] in the
 93.1473 +         * dictionary, and set hash_head to the head of the hash chain:
 93.1474 +         */
 93.1475 +        if (s->lookahead >= MIN_MATCH) {
 93.1476 +            INSERT_STRING(s, s->strstart, hash_head);
 93.1477 +        }
 93.1478 +
 93.1479 +        /* Find the longest match, discarding those <= prev_length.
 93.1480 +         * At this point we have always match_length < MIN_MATCH
 93.1481 +         */
 93.1482 +        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
 93.1483 +            /* To simplify the code, we prevent matches with the string
 93.1484 +             * of window index 0 (in particular we have to avoid a match
 93.1485 +             * of the string with itself at the start of the input file).
 93.1486 +             */
 93.1487 +#ifdef FASTEST
 93.1488 +            if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
 93.1489 +                (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
 93.1490 +                s->match_length = longest_match_fast (s, hash_head);
 93.1491 +            }
 93.1492 +#else
 93.1493 +            if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
 93.1494 +                s->match_length = longest_match (s, hash_head);
 93.1495 +            } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
 93.1496 +                s->match_length = longest_match_fast (s, hash_head);
 93.1497 +            }
 93.1498 +#endif
 93.1499 +            /* longest_match() or longest_match_fast() sets match_start */
 93.1500 +        }
 93.1501 +        if (s->match_length >= MIN_MATCH) {
 93.1502 +            check_match(s, s->strstart, s->match_start, s->match_length);
 93.1503 +
 93.1504 +            _tr_tally_dist(s, s->strstart - s->match_start,
 93.1505 +                           s->match_length - MIN_MATCH, bflush);
 93.1506 +
 93.1507 +            s->lookahead -= s->match_length;
 93.1508 +
 93.1509 +            /* Insert new strings in the hash table only if the match length
 93.1510 +             * is not too large. This saves time but degrades compression.
 93.1511 +             */
 93.1512 +#ifndef FASTEST
 93.1513 +            if (s->match_length <= s->max_insert_length &&
 93.1514 +                s->lookahead >= MIN_MATCH) {
 93.1515 +                s->match_length--; /* string at strstart already in table */
 93.1516 +                do {
 93.1517 +                    s->strstart++;
 93.1518 +                    INSERT_STRING(s, s->strstart, hash_head);
 93.1519 +                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are
 93.1520 +                     * always MIN_MATCH bytes ahead.
 93.1521 +                     */
 93.1522 +                } while (--s->match_length != 0);
 93.1523 +                s->strstart++;
 93.1524 +            } else
 93.1525 +#endif
 93.1526 +            {
 93.1527 +                s->strstart += s->match_length;
 93.1528 +                s->match_length = 0;
 93.1529 +                s->ins_h = s->window[s->strstart];
 93.1530 +                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
 93.1531 +#if MIN_MATCH != 3
 93.1532 +                Call UPDATE_HASH() MIN_MATCH-3 more times
 93.1533 +#endif
 93.1534 +                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
 93.1535 +                 * matter since it will be recomputed at next deflate call.
 93.1536 +                 */
 93.1537 +            }
 93.1538 +        } else {
 93.1539 +            /* No match, output a literal byte */
 93.1540 +            Tracevv((stderr,"%c", s->window[s->strstart]));
 93.1541 +            _tr_tally_lit (s, s->window[s->strstart], bflush);
 93.1542 +            s->lookahead--;
 93.1543 +            s->strstart++;
 93.1544 +        }
 93.1545 +        if (bflush) FLUSH_BLOCK(s, 0);
 93.1546 +    }
 93.1547 +    FLUSH_BLOCK(s, flush == Z_FINISH);
 93.1548 +    return flush == Z_FINISH ? finish_done : block_done;
 93.1549 +}
 93.1550 +
 93.1551 +#ifndef FASTEST
 93.1552 +/* ===========================================================================
 93.1553 + * Same as above, but achieves better compression. We use a lazy
 93.1554 + * evaluation for matches: a match is finally adopted only if there is
 93.1555 + * no better match at the next window position.
 93.1556 + */
 93.1557 +local block_state deflate_slow(s, flush)
 93.1558 +    deflate_state *s;
 93.1559 +    int flush;
 93.1560 +{
 93.1561 +    IPos hash_head = NIL;    /* head of hash chain */
 93.1562 +    int bflush;              /* set if current block must be flushed */
 93.1563 +
 93.1564 +    /* Process the input block. */
 93.1565 +    for (;;) {
 93.1566 +        /* Make sure that we always have enough lookahead, except
 93.1567 +         * at the end of the input file. We need MAX_MATCH bytes
 93.1568 +         * for the next match, plus MIN_MATCH bytes to insert the
 93.1569 +         * string following the next match.
 93.1570 +         */
 93.1571 +        if (s->lookahead < MIN_LOOKAHEAD) {
 93.1572 +            fill_window(s);
 93.1573 +            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
 93.1574 +                return need_more;
 93.1575 +            }
 93.1576 +            if (s->lookahead == 0) break; /* flush the current block */
 93.1577 +        }
 93.1578 +
 93.1579 +        /* Insert the string window[strstart .. strstart+2] in the
 93.1580 +         * dictionary, and set hash_head to the head of the hash chain:
 93.1581 +         */
 93.1582 +        if (s->lookahead >= MIN_MATCH) {
 93.1583 +            INSERT_STRING(s, s->strstart, hash_head);
 93.1584 +        }
 93.1585 +
 93.1586 +        /* Find the longest match, discarding those <= prev_length.
 93.1587 +         */
 93.1588 +        s->prev_length = s->match_length, s->prev_match = s->match_start;
 93.1589 +        s->match_length = MIN_MATCH-1;
 93.1590 +
 93.1591 +        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
 93.1592 +            s->strstart - hash_head <= MAX_DIST(s)) {
 93.1593 +            /* To simplify the code, we prevent matches with the string
 93.1594 +             * of window index 0 (in particular we have to avoid a match
 93.1595 +             * of the string with itself at the start of the input file).
 93.1596 +             */
 93.1597 +            if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
 93.1598 +                s->match_length = longest_match (s, hash_head);
 93.1599 +            } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
 93.1600 +                s->match_length = longest_match_fast (s, hash_head);
 93.1601 +            }
 93.1602 +            /* longest_match() or longest_match_fast() sets match_start */
 93.1603 +
 93.1604 +            if (s->match_length <= 5 && (s->strategy == Z_FILTERED
 93.1605 +#if TOO_FAR <= 32767
 93.1606 +                || (s->match_length == MIN_MATCH &&
 93.1607 +                    s->strstart - s->match_start > TOO_FAR)
 93.1608 +#endif
 93.1609 +                )) {
 93.1610 +
 93.1611 +                /* If prev_match is also MIN_MATCH, match_start is garbage
 93.1612 +                 * but we will ignore the current match anyway.
 93.1613 +                 */
 93.1614 +                s->match_length = MIN_MATCH-1;
 93.1615 +            }
 93.1616 +        }
 93.1617 +        /* If there was a match at the previous step and the current
 93.1618 +         * match is not better, output the previous match:
 93.1619 +         */
 93.1620 +        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
 93.1621 +            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
 93.1622 +            /* Do not insert strings in hash table beyond this. */
 93.1623 +
 93.1624 +            check_match(s, s->strstart-1, s->prev_match, s->prev_length);
 93.1625 +
 93.1626 +            _tr_tally_dist(s, s->strstart -1 - s->prev_match,
 93.1627 +                           s->prev_length - MIN_MATCH, bflush);
 93.1628 +
 93.1629 +            /* Insert in hash table all strings up to the end of the match.
 93.1630 +             * strstart-1 and strstart are already inserted. If there is not
 93.1631 +             * enough lookahead, the last two strings are not inserted in
 93.1632 +             * the hash table.
 93.1633 +             */
 93.1634 +            s->lookahead -= s->prev_length-1;
 93.1635 +            s->prev_length -= 2;
 93.1636 +            do {
 93.1637 +                if (++s->strstart <= max_insert) {
 93.1638 +                    INSERT_STRING(s, s->strstart, hash_head);
 93.1639 +                }
 93.1640 +            } while (--s->prev_length != 0);
 93.1641 +            s->match_available = 0;
 93.1642 +            s->match_length = MIN_MATCH-1;
 93.1643 +            s->strstart++;
 93.1644 +
 93.1645 +            if (bflush) FLUSH_BLOCK(s, 0);
 93.1646 +
 93.1647 +        } else if (s->match_available) {
 93.1648 +            /* If there was no match at the previous position, output a
 93.1649 +             * single literal. If there was a match but the current match
 93.1650 +             * is longer, truncate the previous match to a single literal.
 93.1651 +             */
 93.1652 +            Tracevv((stderr,"%c", s->window[s->strstart-1]));
 93.1653 +            _tr_tally_lit(s, s->window[s->strstart-1], bflush);
 93.1654 +            if (bflush) {
 93.1655 +                FLUSH_BLOCK_ONLY(s, 0);
 93.1656 +            }
 93.1657 +            s->strstart++;
 93.1658 +            s->lookahead--;
 93.1659 +            if (s->strm->avail_out == 0) return need_more;
 93.1660 +        } else {
 93.1661 +            /* There is no previous match to compare with, wait for
 93.1662 +             * the next step to decide.
 93.1663 +             */
 93.1664 +            s->match_available = 1;
 93.1665 +            s->strstart++;
 93.1666 +            s->lookahead--;
 93.1667 +        }
 93.1668 +    }
 93.1669 +    Assert (flush != Z_NO_FLUSH, "no flush?");
 93.1670 +    if (s->match_available) {
 93.1671 +        Tracevv((stderr,"%c", s->window[s->strstart-1]));
 93.1672 +        _tr_tally_lit(s, s->window[s->strstart-1], bflush);
 93.1673 +        s->match_available = 0;
 93.1674 +    }
 93.1675 +    FLUSH_BLOCK(s, flush == Z_FINISH);
 93.1676 +    return flush == Z_FINISH ? finish_done : block_done;
 93.1677 +}
 93.1678 +#endif /* FASTEST */
 93.1679 +
 93.1680 +#if 0
 93.1681 +/* ===========================================================================
 93.1682 + * For Z_RLE, simply look for runs of bytes, generate matches only of distance
 93.1683 + * one.  Do not maintain a hash table.  (It will be regenerated if this run of
 93.1684 + * deflate switches away from Z_RLE.)
 93.1685 + */
 93.1686 +local block_state deflate_rle(s, flush)
 93.1687 +    deflate_state *s;
 93.1688 +    int flush;
 93.1689 +{
 93.1690 +    int bflush;         /* set if current block must be flushed */
 93.1691 +    uInt run;           /* length of run */
 93.1692 +    uInt max;           /* maximum length of run */
 93.1693 +    uInt prev;          /* byte at distance one to match */
 93.1694 +    Bytef *scan;        /* scan for end of run */
 93.1695 +
 93.1696 +    for (;;) {
 93.1697 +        /* Make sure that we always have enough lookahead, except
 93.1698 +         * at the end of the input file. We need MAX_MATCH bytes
 93.1699 +         * for the longest encodable run.
 93.1700 +         */
 93.1701 +        if (s->lookahead < MAX_MATCH) {
 93.1702 +            fill_window(s);
 93.1703 +            if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
 93.1704 +                return need_more;
 93.1705 +            }
 93.1706 +            if (s->lookahead == 0) break; /* flush the current block */
 93.1707 +        }
 93.1708 +
 93.1709 +        /* See how many times the previous byte repeats */
 93.1710 +        run = 0;
 93.1711 +        if (s->strstart > 0) {      /* if there is a previous byte, that is */
 93.1712 +            max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
 93.1713 +            scan = s->window + s->strstart - 1;
 93.1714 +            prev = *scan++;
 93.1715 +            do {
 93.1716 +                if (*scan++ != prev)
 93.1717 +                    break;
 93.1718 +            } while (++run < max);
 93.1719 +        }
 93.1720 +
 93.1721 +        /* Emit match if have run of MIN_MATCH or longer, else emit literal */
 93.1722 +        if (run >= MIN_MATCH) {
 93.1723 +            check_match(s, s->strstart, s->strstart - 1, run);
 93.1724 +            _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
 93.1725 +            s->lookahead -= run;
 93.1726 +            s->strstart += run;
 93.1727 +        } else {
 93.1728 +            /* No match, output a literal byte */
 93.1729 +            Tracevv((stderr,"%c", s->window[s->strstart]));
 93.1730 +            _tr_tally_lit (s, s->window[s->strstart], bflush);
 93.1731 +            s->lookahead--;
 93.1732 +            s->strstart++;
 93.1733 +        }
 93.1734 +        if (bflush) FLUSH_BLOCK(s, 0);
 93.1735 +    }
 93.1736 +    FLUSH_BLOCK(s, flush == Z_FINISH);
 93.1737 +    return flush == Z_FINISH ? finish_done : block_done;
 93.1738 +}
 93.1739 +#endif
    94.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    94.2 +++ b/libs/zlib/deflate.h	Thu Sep 08 06:28:38 2011 +0300
    94.3 @@ -0,0 +1,331 @@
    94.4 +/* deflate.h -- internal compression state
    94.5 + * Copyright (C) 1995-2004 Jean-loup Gailly
    94.6 + * For conditions of distribution and use, see copyright notice in zlib.h
    94.7 + */
    94.8 +
    94.9 +/* WARNING: this file should *not* be used by applications. It is
   94.10 +   part of the implementation of the compression library and is
   94.11 +   subject to change. Applications should only use zlib.h.
   94.12 + */
   94.13 +
   94.14 +/* @(#) $Id$ */
   94.15 +
   94.16 +#ifndef DEFLATE_H
   94.17 +#define DEFLATE_H
   94.18 +
   94.19 +#include "zutil.h"
   94.20 +
   94.21 +/* define NO_GZIP when compiling if you want to disable gzip header and
   94.22 +   trailer creation by deflate().  NO_GZIP would be used to avoid linking in
   94.23 +   the crc code when it is not needed.  For shared libraries, gzip encoding
   94.24 +   should be left enabled. */
   94.25 +#ifndef NO_GZIP
   94.26 +#  define GZIP
   94.27 +#endif
   94.28 +
   94.29 +/* ===========================================================================
   94.30 + * Internal compression state.
   94.31 + */
   94.32 +
   94.33 +#define LENGTH_CODES 29
   94.34 +/* number of length codes, not counting the special END_BLOCK code */
   94.35 +
   94.36 +#define LITERALS  256
   94.37 +/* number of literal bytes 0..255 */
   94.38 +
   94.39 +#define L_CODES (LITERALS+1+LENGTH_CODES)
   94.40 +/* number of Literal or Length codes, including the END_BLOCK code */
   94.41 +
   94.42 +#define D_CODES   30
   94.43 +/* number of distance codes */
   94.44 +
   94.45 +#define BL_CODES  19
   94.46 +/* number of codes used to transfer the bit lengths */
   94.47 +
   94.48 +#define HEAP_SIZE (2*L_CODES+1)
   94.49 +/* maximum heap size */
   94.50 +
   94.51 +#define MAX_BITS 15
   94.52 +/* All codes must not exceed MAX_BITS bits */
   94.53 +
   94.54 +#define INIT_STATE    42
   94.55 +#define EXTRA_STATE   69
   94.56 +#define NAME_STATE    73
   94.57 +#define COMMENT_STATE 91
   94.58 +#define HCRC_STATE   103
   94.59 +#define BUSY_STATE   113
   94.60 +#define FINISH_STATE 666
   94.61 +/* Stream status */
   94.62 +
   94.63 +
   94.64 +/* Data structure describing a single value and its code string. */
   94.65 +typedef struct ct_data_s {
   94.66 +    union {
   94.67 +        ush  freq;       /* frequency count */
   94.68 +        ush  code;       /* bit string */
   94.69 +    } fc;
   94.70 +    union {
   94.71 +        ush  dad;        /* father node in Huffman tree */
   94.72 +        ush  len;        /* length of bit string */
   94.73 +    } dl;
   94.74 +} FAR ct_data;
   94.75 +
   94.76 +#define Freq fc.freq
   94.77 +#define Code fc.code
   94.78 +#define Dad  dl.dad
   94.79 +#define Len  dl.len
   94.80 +
   94.81 +typedef struct static_tree_desc_s  static_tree_desc;
   94.82 +
   94.83 +typedef struct tree_desc_s {
   94.84 +    ct_data *dyn_tree;           /* the dynamic tree */
   94.85 +    int     max_code;            /* largest code with non zero frequency */
   94.86 +    static_tree_desc *stat_desc; /* the corresponding static tree */
   94.87 +} FAR tree_desc;
   94.88 +
   94.89 +typedef ush Pos;
   94.90 +typedef Pos FAR Posf;
   94.91 +typedef unsigned IPos;
   94.92 +
   94.93 +/* A Pos is an index in the character window. We use short instead of int to
   94.94 + * save space in the various tables. IPos is used only for parameter passing.
   94.95 + */
   94.96 +
   94.97 +typedef struct internal_state {
   94.98 +    z_streamp strm;      /* pointer back to this zlib stream */
   94.99 +    int   status;        /* as the name implies */
  94.100 +    Bytef *pending_buf;  /* output still pending */
  94.101 +    ulg   pending_buf_size; /* size of pending_buf */
  94.102 +    Bytef *pending_out;  /* next pending byte to output to the stream */
  94.103 +    uInt   pending;      /* nb of bytes in the pending buffer */
  94.104 +    int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */
  94.105 +    gz_headerp  gzhead;  /* gzip header information to write */
  94.106 +    uInt   gzindex;      /* where in extra, name, or comment */
  94.107 +    Byte  method;        /* STORED (for zip only) or DEFLATED */
  94.108 +    int   last_flush;    /* value of flush param for previous deflate call */
  94.109 +
  94.110 +                /* used by deflate.c: */
  94.111 +
  94.112 +    uInt  w_size;        /* LZ77 window size (32K by default) */
  94.113 +    uInt  w_bits;        /* log2(w_size)  (8..16) */
  94.114 +    uInt  w_mask;        /* w_size - 1 */
  94.115 +
  94.116 +    Bytef *window;
  94.117 +    /* Sliding window. Input bytes are read into the second half of the window,
  94.118 +     * and move to the first half later to keep a dictionary of at least wSize
  94.119 +     * bytes. With this organization, matches are limited to a distance of
  94.120 +     * wSize-MAX_MATCH bytes, but this ensures that IO is always
  94.121 +     * performed with a length multiple of the block size. Also, it limits
  94.122 +     * the window size to 64K, which is quite useful on MSDOS.
  94.123 +     * To do: use the user input buffer as sliding window.
  94.124 +     */
  94.125 +
  94.126 +    ulg window_size;
  94.127 +    /* Actual size of window: 2*wSize, except when the user input buffer
  94.128 +     * is directly used as sliding window.
  94.129 +     */
  94.130 +
  94.131 +    Posf *prev;
  94.132 +    /* Link to older string with same hash index. To limit the size of this
  94.133 +     * array to 64K, this link is maintained only for the last 32K strings.
  94.134 +     * An index in this array is thus a window index modulo 32K.
  94.135 +     */
  94.136 +
  94.137 +    Posf *head; /* Heads of the hash chains or NIL. */
  94.138 +
  94.139 +    uInt  ins_h;          /* hash index of string to be inserted */
  94.140 +    uInt  hash_size;      /* number of elements in hash table */
  94.141 +    uInt  hash_bits;      /* log2(hash_size) */
  94.142 +    uInt  hash_mask;      /* hash_size-1 */
  94.143 +
  94.144 +    uInt  hash_shift;
  94.145 +    /* Number of bits by which ins_h must be shifted at each input
  94.146 +     * step. It must be such that after MIN_MATCH steps, the oldest
  94.147 +     * byte no longer takes part in the hash key, that is:
  94.148 +     *   hash_shift * MIN_MATCH >= hash_bits
  94.149 +     */
  94.150 +
  94.151 +    long block_start;
  94.152 +    /* Window position at the beginning of the current output block. Gets
  94.153 +     * negative when the window is moved backwards.
  94.154 +     */
  94.155 +
  94.156 +    uInt match_length;           /* length of best match */
  94.157 +    IPos prev_match;             /* previous match */
  94.158 +    int match_available;         /* set if previous match exists */
  94.159 +    uInt strstart;               /* start of string to insert */
  94.160 +    uInt match_start;            /* start of matching string */
  94.161 +    uInt lookahead;              /* number of valid bytes ahead in window */
  94.162 +
  94.163 +    uInt prev_length;
  94.164 +    /* Length of the best match at previous step. Matches not greater than this
  94.165 +     * are discarded. This is used in the lazy match evaluation.
  94.166 +     */
  94.167 +
  94.168 +    uInt max_chain_length;
  94.169 +    /* To speed up deflation, hash chains are never searched beyond this
  94.170 +     * length.  A higher limit improves compression ratio but degrades the
  94.171 +     * speed.
  94.172 +     */
  94.173 +
  94.174 +    uInt max_lazy_match;
  94.175 +    /* Attempt to find a better match only when the current match is strictly
  94.176 +     * smaller than this value. This mechanism is used only for compression
  94.177 +     * levels >= 4.
  94.178 +     */
  94.179 +#   define max_insert_length  max_lazy_match
  94.180 +    /* Insert new strings in the hash table only if the match length is not
  94.181 +     * greater than this length. This saves time but degrades compression.
  94.182 +     * max_insert_length is used only for compression levels <= 3.
  94.183 +     */
  94.184 +
  94.185 +    int level;    /* compression level (1..9) */
  94.186 +    int strategy; /* favor or force Huffman coding*/
  94.187 +
  94.188 +    uInt good_match;
  94.189 +    /* Use a faster search when the previous match is longer than this */
  94.190 +
  94.191 +    int nice_match; /* Stop searching when current match exceeds this */
  94.192 +
  94.193 +                /* used by trees.c: */
  94.194 +    /* Didn't use ct_data typedef below to supress compiler warning */
  94.195 +    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
  94.196 +    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  94.197 +    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
  94.198 +
  94.199 +    struct tree_desc_s l_desc;               /* desc. for literal tree */
  94.200 +    struct tree_desc_s d_desc;               /* desc. for distance tree */
  94.201 +    struct tree_desc_s bl_desc;              /* desc. for bit length tree */
  94.202 +
  94.203 +    ush bl_count[MAX_BITS+1];
  94.204 +    /* number of codes at each bit length for an optimal tree */
  94.205 +
  94.206 +    int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
  94.207 +    int heap_len;               /* number of elements in the heap */
  94.208 +    int heap_max;               /* element of largest frequency */
  94.209 +    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  94.210 +     * The same heap array is used to build all trees.
  94.211 +     */
  94.212 +
  94.213 +    uch depth[2*L_CODES+1];
  94.214 +    /* Depth of each subtree used as tie breaker for trees of equal frequency
  94.215 +     */
  94.216 +
  94.217 +    uchf *l_buf;          /* buffer for literals or lengths */
  94.218 +
  94.219 +    uInt  lit_bufsize;
  94.220 +    /* Size of match buffer for literals/lengths.  There are 4 reasons for
  94.221 +     * limiting lit_bufsize to 64K:
  94.222 +     *   - frequencies can be kept in 16 bit counters
  94.223 +     *   - if compression is not successful for the first block, all input
  94.224 +     *     data is still in the window so we can still emit a stored block even
  94.225 +     *     when input comes from standard input.  (This can also be done for
  94.226 +     *     all blocks if lit_bufsize is not greater than 32K.)
  94.227 +     *   - if compression is not successful for a file smaller than 64K, we can
  94.228 +     *     even emit a stored file instead of a stored block (saving 5 bytes).
  94.229 +     *     This is applicable only for zip (not gzip or zlib).
  94.230 +     *   - creating new Huffman trees less frequently may not provide fast
  94.231 +     *     adaptation to changes in the input data statistics. (Take for
  94.232 +     *     example a binary file with poorly compressible code followed by
  94.233 +     *     a highly compressible string table.) Smaller buffer sizes give
  94.234 +     *     fast adaptation but have of course the overhead of transmitting
  94.235 +     *     trees more frequently.
  94.236 +     *   - I can't count above 4
  94.237 +     */
  94.238 +
  94.239 +    uInt last_lit;      /* running index in l_buf */
  94.240 +
  94.241 +    ushf *d_buf;
  94.242 +    /* Buffer for distances. To simplify the code, d_buf and l_buf have
  94.243 +     * the same number of elements. To use different lengths, an extra flag
  94.244 +     * array would be necessary.
  94.245 +     */
  94.246 +
  94.247 +    ulg opt_len;        /* bit length of current block with optimal trees */
  94.248 +    ulg static_len;     /* bit length of current block with static trees */
  94.249 +    uInt matches;       /* number of string matches in current block */
  94.250 +    int last_eob_len;   /* bit length of EOB code for last block */
  94.251 +
  94.252 +#ifdef DEBUG
  94.253 +    ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  94.254 +    ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */
  94.255 +#endif
  94.256 +
  94.257 +    ush bi_buf;
  94.258 +    /* Output buffer. bits are inserted starting at the bottom (least
  94.259 +     * significant bits).
  94.260 +     */
  94.261 +    int bi_valid;
  94.262 +    /* Number of valid bits in bi_buf.  All bits above the last valid bit
  94.263 +     * are always zero.
  94.264 +     */
  94.265 +
  94.266 +} FAR deflate_state;
  94.267 +
  94.268 +/* Output a byte on the stream.
  94.269 + * IN assertion: there is enough room in pending_buf.
  94.270 + */
  94.271 +#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  94.272 +
  94.273 +
  94.274 +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  94.275 +/* Minimum amount of lookahead, except at the end of the input file.
  94.276 + * See deflate.c for comments about the MIN_MATCH+1.
  94.277 + */
  94.278 +
  94.279 +#define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)
  94.280 +/* In order to simplify the code, particularly on 16 bit machines, match
  94.281 + * distances are limited to MAX_DIST instead of WSIZE.
  94.282 + */
  94.283 +
  94.284 +        /* in trees.c */
  94.285 +void _tr_init         OF((deflate_state *s));
  94.286 +int  _tr_tally        OF((deflate_state *s, unsigned dist, unsigned lc));
  94.287 +void _tr_flush_block  OF((deflate_state *s, charf *buf, ulg stored_len,
  94.288 +                          int eof));
  94.289 +void _tr_align        OF((deflate_state *s));
  94.290 +void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  94.291 +                          int eof));
  94.292 +
  94.293 +#define d_code(dist) \
  94.294 +   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  94.295 +/* Mapping from a distance to a distance code. dist is the distance - 1 and
  94.296 + * must not have side effects. _dist_code[256] and _dist_code[257] are never
  94.297 + * used.
  94.298 + */
  94.299 +
  94.300 +#ifndef DEBUG
  94.301 +/* Inline versions of _tr_tally for speed: */
  94.302 +
  94.303 +#if defined(GEN_TREES_H) || !defined(STDC)
  94.304 +  extern uch _length_code[];
  94.305 +  extern uch _dist_code[];
  94.306 +#else
  94.307 +  extern const uch _length_code[];
  94.308 +  extern const uch _dist_code[];
  94.309 +#endif
  94.310 +
  94.311 +# define _tr_tally_lit(s, c, flush) \
  94.312 +  { uch cc = (c); \
  94.313 +    s->d_buf[s->last_lit] = 0; \
  94.314 +    s->l_buf[s->last_lit++] = cc; \
  94.315 +    s->dyn_ltree[cc].Freq++; \
  94.316 +    flush = (s->last_lit == s->lit_bufsize-1); \
  94.317 +   }
  94.318 +# define _tr_tally_dist(s, distance, length, flush) \
  94.319 +  { uch len = (length); \
  94.320 +    ush dist = (distance); \
  94.321 +    s->d_buf[s->last_lit] = dist; \
  94.322 +    s->l_buf[s->last_lit++] = len; \
  94.323 +    dist--; \
  94.324 +    s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  94.325 +    s->dyn_dtree[d_code(dist)].Freq++; \
  94.326 +    flush = (s->last_lit == s->lit_bufsize-1); \
  94.327 +  }
  94.328 +#else
  94.329 +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  94.330 +# define _tr_tally_dist(s, distance, length, flush) \
  94.331 +              flush = _tr_tally(s, distance, length)
  94.332 +#endif
  94.333 +
  94.334 +#endif /* DEFLATE_H */
    95.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    95.2 +++ b/libs/zlib/gzio.c	Thu Sep 08 06:28:38 2011 +0300
    95.3 @@ -0,0 +1,1026 @@
    95.4 +/* gzio.c -- IO on .gz files
    95.5 + * Copyright (C) 1995-2005 Jean-loup Gailly.
    95.6 + * For conditions of distribution and use, see copyright notice in zlib.h
    95.7 + *
    95.8 + * Compile this file with -DNO_GZCOMPRESS to avoid the compression code.
    95.9 + */
   95.10 +
   95.11 +/* @(#) $Id$ */
   95.12 +
   95.13 +#include <stdio.h>
   95.14 +
   95.15 +#include "zutil.h"
   95.16 +
   95.17 +#ifdef NO_DEFLATE       /* for compatibility with old definition */
   95.18 +#  define NO_GZCOMPRESS
   95.19 +#endif
   95.20 +
   95.21 +#ifndef NO_DUMMY_DECL
   95.22 +struct internal_state {int dummy;}; /* for buggy compilers */
   95.23 +#endif
   95.24 +
   95.25 +#ifndef Z_BUFSIZE
   95.26 +#  ifdef MAXSEG_64K
   95.27 +#    define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */
   95.28 +#  else
   95.29 +#    define Z_BUFSIZE 16384
   95.30 +#  endif
   95.31 +#endif
   95.32 +#ifndef Z_PRINTF_BUFSIZE
   95.33 +#  define Z_PRINTF_BUFSIZE 4096
   95.34 +#endif
   95.35 +
   95.36 +#ifdef __MVS__
   95.37 +#  pragma map (fdopen , "\174\174FDOPEN")
   95.38 +   FILE *fdopen(int, const char *);
   95.39 +#endif
   95.40 +
   95.41 +#ifndef STDC
   95.42 +extern voidp  malloc OF((uInt size));
   95.43 +extern void   free   OF((voidpf ptr));
   95.44 +#endif
   95.45 +
   95.46 +#define ALLOC(size) malloc(size)
   95.47 +#define TRYFREE(p) {if (p) free(p);}
   95.48 +
   95.49 +static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
   95.50 +
   95.51 +/* gzip flag byte */
   95.52 +#define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
   95.53 +#define HEAD_CRC     0x02 /* bit 1 set: header CRC present */
   95.54 +#define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
   95.55 +#define ORIG_NAME    0x08 /* bit 3 set: original file name present */
   95.56 +#define COMMENT      0x10 /* bit 4 set: file comment present */
   95.57 +#define RESERVED     0xE0 /* bits 5..7: reserved */
   95.58 +
   95.59 +typedef struct gz_stream {
   95.60 +    z_stream stream;
   95.61 +    int      z_err;   /* error code for last stream operation */
   95.62 +    int      z_eof;   /* set if end of input file */
   95.63 +    FILE     *file;   /* .gz file */
   95.64 +    Byte     *inbuf;  /* input buffer */
   95.65 +    Byte     *outbuf; /* output buffer */
   95.66 +    uLong    crc;     /* crc32 of uncompressed data */
   95.67 +    char     *msg;    /* error message */
   95.68 +    char     *path;   /* path name for debugging only */
   95.69 +    int      transparent; /* 1 if input file is not a .gz file */
   95.70 +    char     mode;    /* 'w' or 'r' */
   95.71 +    z_off_t  start;   /* start of compressed data in file (header skipped) */
   95.72 +    z_off_t  in;      /* bytes into deflate or inflate */
   95.73 +    z_off_t  out;     /* bytes out of deflate or inflate */
   95.74 +    int      back;    /* one character push-back */
   95.75 +    int      last;    /* true if push-back is last character */
   95.76 +} gz_stream;
   95.77 +
   95.78 +
   95.79 +local gzFile gz_open      OF((const char *path, const char *mode, int  fd));
   95.80 +local int do_flush        OF((gzFile file, int flush));
   95.81 +local int    get_byte     OF((gz_stream *s));
   95.82 +local void   check_header OF((gz_stream *s));
   95.83 +local int    destroy      OF((gz_stream *s));
   95.84 +local void   putLong      OF((FILE *file, uLong x));
   95.85 +local uLong  getLong      OF((gz_stream *s));
   95.86 +
   95.87 +/* ===========================================================================
   95.88 +     Opens a gzip (.gz) file for reading or writing. The mode parameter
   95.89 +   is as in fopen ("rb" or "wb"). The file is given either by file descriptor
   95.90 +   or path name (if fd == -1).
   95.91 +     gz_open returns NULL if the file could not be opened or if there was
   95.92 +   insufficient memory to allocate the (de)compression state; errno
   95.93 +   can be checked to distinguish the two cases (if errno is zero, the
   95.94 +   zlib error is Z_MEM_ERROR).
   95.95 +*/
   95.96 +local gzFile gz_open (path, mode, fd)
   95.97 +    const char *path;
   95.98 +    const char *mode;
   95.99 +    int  fd;
  95.100 +{
  95.101 +    int err;
  95.102 +    int level = Z_DEFAULT_COMPRESSION; /* compression level */
  95.103 +    int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */
  95.104 +    char *p = (char*)mode;
  95.105 +    gz_stream *s;
  95.106 +    char fmode[80]; /* copy of mode, without the compression level */
  95.107 +    char *m = fmode;
  95.108 +
  95.109 +    if (!path || !mode) return Z_NULL;
  95.110 +
  95.111 +    s = (gz_stream *)ALLOC(sizeof(gz_stream));
  95.112 +    if (!s) return Z_NULL;
  95.113 +
  95.114 +    s->stream.zalloc = (alloc_func)0;
  95.115 +    s->stream.zfree = (free_func)0;
  95.116 +    s->stream.opaque = (voidpf)0;
  95.117 +    s->stream.next_in = s->inbuf = Z_NULL;
  95.118 +    s->stream.next_out = s->outbuf = Z_NULL;
  95.119 +    s->stream.avail_in = s->stream.avail_out = 0;
  95.120 +    s->file = NULL;
  95.121 +    s->z_err = Z_OK;
  95.122 +    s->z_eof = 0;
  95.123 +    s->in = 0;
  95.124 +    s->out = 0;
  95.125 +    s->back = EOF;
  95.126 +    s->crc = crc32(0L, Z_NULL, 0);
  95.127 +    s->msg = NULL;
  95.128 +    s->transparent = 0;
  95.129 +
  95.130 +    s->path = (char*)ALLOC(strlen(path)+1);
  95.131 +    if (s->path == NULL) {
  95.132 +        return destroy(s), (gzFile)Z_NULL;
  95.133 +    }
  95.134 +    strcpy(s->path, path); /* do this early for debugging */
  95.135 +
  95.136 +    s->mode = '\0';
  95.137 +    do {
  95.138 +        if (*p == 'r') s->mode = 'r';
  95.139 +        if (*p == 'w' || *p == 'a') s->mode = 'w';
  95.140 +        if (*p >= '0' && *p <= '9') {
  95.141 +            level = *p - '0';
  95.142 +        } else if (*p == 'f') {
  95.143 +          strategy = Z_FILTERED;
  95.144 +        } else if (*p == 'h') {
  95.145 +          strategy = Z_HUFFMAN_ONLY;
  95.146 +        } else if (*p == 'R') {
  95.147 +          strategy = Z_RLE;
  95.148 +        } else {
  95.149 +            *m++ = *p; /* copy the mode */
  95.150 +        }
  95.151 +    } while (*p++ && m != fmode + sizeof(fmode));
  95.152 +    if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
  95.153 +
  95.154 +    if (s->mode == 'w') {
  95.155 +#ifdef NO_GZCOMPRESS
  95.156 +        err = Z_STREAM_ERROR;
  95.157 +#else
  95.158 +        err = deflateInit2(&(s->stream), level,
  95.159 +                           Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy);
  95.160 +        /* windowBits is passed < 0 to suppress zlib header */
  95.161 +
  95.162 +        s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
  95.163 +#endif
  95.164 +        if (err != Z_OK || s->outbuf == Z_NULL) {
  95.165 +            return destroy(s), (gzFile)Z_NULL;
  95.166 +        }
  95.167 +    } else {
  95.168 +        s->stream.next_in  = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
  95.169 +
  95.170 +        err = inflateInit2(&(s->stream), -MAX_WBITS);
  95.171 +        /* windowBits is passed < 0 to tell that there is no zlib header.
  95.172 +         * Note that in this case inflate *requires* an extra "dummy" byte
  95.173 +         * after the compressed stream in order to complete decompression and
  95.174 +         * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are
  95.175 +         * present after the compressed stream.
  95.176 +         */
  95.177 +        if (err != Z_OK || s->inbuf == Z_NULL) {
  95.178 +            return destroy(s), (gzFile)Z_NULL;
  95.179 +        }
  95.180 +    }
  95.181 +    s->stream.avail_out = Z_BUFSIZE;
  95.182 +
  95.183 +    errno = 0;
  95.184 +    s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode);
  95.185 +
  95.186 +    if (s->file == NULL) {
  95.187 +        return destroy(s), (gzFile)Z_NULL;
  95.188 +    }
  95.189 +    if (s->mode == 'w') {
  95.190 +        /* Write a very simple .gz header:
  95.191 +         */
  95.192 +        fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
  95.193 +             Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
  95.194 +        s->start = 10L;
  95.195 +        /* We use 10L instead of ftell(s->file) to because ftell causes an
  95.196 +         * fflush on some systems. This version of the library doesn't use
  95.197 +         * start anyway in write mode, so this initialization is not
  95.198 +         * necessary.
  95.199 +         */
  95.200 +    } else {
  95.201 +        check_header(s); /* skip the .gz header */
  95.202 +        s->start = ftell(s->file) - s->stream.avail_in;
  95.203 +    }
  95.204 +
  95.205 +    return (gzFile)s;
  95.206 +}
  95.207 +
  95.208 +/* ===========================================================================
  95.209 +     Opens a gzip (.gz) file for reading or writing.
  95.210 +*/
  95.211 +gzFile ZEXPORT gzopen (path, mode)
  95.212 +    const char *path;
  95.213 +    const char *mode;
  95.214 +{
  95.215 +    return gz_open (path, mode, -1);
  95.216 +}
  95.217 +
  95.218 +/* ===========================================================================
  95.219 +     Associate a gzFile with the file descriptor fd. fd is not dup'ed here
  95.220 +   to mimic the behavio(u)r of fdopen.
  95.221 +*/
  95.222 +gzFile ZEXPORT gzdopen (fd, mode)
  95.223 +    int fd;
  95.224 +    const char *mode;
  95.225 +{
  95.226 +    char name[46];      /* allow for up to 128-bit integers */
  95.227 +
  95.228 +    if (fd < 0) return (gzFile)Z_NULL;
  95.229 +    sprintf(name, "<fd:%d>", fd); /* for debugging */
  95.230 +
  95.231 +    return gz_open (name, mode, fd);
  95.232 +}
  95.233 +
  95.234 +/* ===========================================================================
  95.235 + * Update the compression level and strategy
  95.236 + */
  95.237 +int ZEXPORT gzsetparams (file, level, strategy)
  95.238 +    gzFile file;
  95.239 +    int level;
  95.240 +    int strategy;
  95.241 +{
  95.242 +    gz_stream *s = (gz_stream*)file;
  95.243 +
  95.244 +    if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
  95.245 +
  95.246 +    /* Make room to allow flushing */
  95.247 +    if (s->stream.avail_out == 0) {
  95.248 +
  95.249 +        s->stream.next_out = s->outbuf;
  95.250 +        if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
  95.251 +            s->z_err = Z_ERRNO;
  95.252 +        }
  95.253 +        s->stream.avail_out = Z_BUFSIZE;
  95.254 +    }
  95.255 +
  95.256 +    return deflateParams (&(s->stream), level, strategy);
  95.257 +}
  95.258 +
  95.259 +/* ===========================================================================
  95.260 +     Read a byte from a gz_stream; update next_in and avail_in. Return EOF
  95.261 +   for end of file.
  95.262 +   IN assertion: the stream s has been sucessfully opened for reading.
  95.263 +*/
  95.264 +local int get_byte(s)
  95.265 +    gz_stream *s;
  95.266 +{
  95.267 +    if (s->z_eof) return EOF;
  95.268 +    if (s->stream.avail_in == 0) {
  95.269 +        errno = 0;
  95.270 +        s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
  95.271 +        if (s->stream.avail_in == 0) {
  95.272 +            s->z_eof = 1;
  95.273 +            if (ferror(s->file)) s->z_err = Z_ERRNO;
  95.274 +            return EOF;
  95.275 +        }
  95.276 +        s->stream.next_in = s->inbuf;
  95.277 +    }
  95.278 +    s->stream.avail_in--;
  95.279 +    return *(s->stream.next_in)++;
  95.280 +}
  95.281 +
  95.282 +/* ===========================================================================
  95.283 +      Check the gzip header of a gz_stream opened for reading. Set the stream
  95.284 +    mode to transparent if the gzip magic header is not present; set s->err
  95.285 +    to Z_DATA_ERROR if the magic header is present but the rest of the header
  95.286 +    is incorrect.
  95.287 +    IN assertion: the stream s has already been created sucessfully;
  95.288 +       s->stream.avail_in is zero for the first time, but may be non-zero
  95.289 +       for concatenated .gz files.
  95.290 +*/
  95.291 +local void check_header(s)
  95.292 +    gz_stream *s;
  95.293 +{
  95.294 +    int method; /* method byte */
  95.295 +    int flags;  /* flags byte */
  95.296 +    uInt len;
  95.297 +    int c;
  95.298 +
  95.299 +    /* Assure two bytes in the buffer so we can peek ahead -- handle case
  95.300 +       where first byte of header is at the end of the buffer after the last
  95.301 +       gzip segment */
  95.302 +    len = s->stream.avail_in;
  95.303 +    if (len < 2) {
  95.304 +        if (len) s->inbuf[0] = s->stream.next_in[0];
  95.305 +        errno = 0;
  95.306 +        len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file);
  95.307 +        if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO;
  95.308 +        s->stream.avail_in += len;
  95.309 +        s->stream.next_in = s->inbuf;
  95.310 +        if (s->stream.avail_in < 2) {
  95.311 +            s->transparent = s->stream.avail_in;
  95.312 +            return;
  95.313 +        }
  95.314 +    }
  95.315 +
  95.316 +    /* Peek ahead to check the gzip magic header */
  95.317 +    if (s->stream.next_in[0] != gz_magic[0] ||
  95.318 +        s->stream.next_in[1] != gz_magic[1]) {
  95.319 +        s->transparent = 1;
  95.320 +        return;
  95.321 +    }
  95.322 +    s->stream.avail_in -= 2;
  95.323 +    s->stream.next_in += 2;
  95.324 +
  95.325 +    /* Check the rest of the gzip header */
  95.326 +    method = get_byte(s);
  95.327 +    flags = get_byte(s);
  95.328 +    if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
  95.329 +        s->z_err = Z_DATA_ERROR;
  95.330 +        return;
  95.331 +    }
  95.332 +
  95.333 +    /* Discard time, xflags and OS code: */
  95.334 +    for (len = 0; len < 6; len++) (void)get_byte(s);
  95.335 +
  95.336 +    if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
  95.337 +        len  =  (uInt)get_byte(s);
  95.338 +        len += ((uInt)get_byte(s))<<8;
  95.339 +        /* len is garbage if EOF but the loop below will quit anyway */
  95.340 +        while (len-- != 0 && get_byte(s) != EOF) ;
  95.341 +    }
  95.342 +    if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
  95.343 +        while ((c = get_byte(s)) != 0 && c != EOF) ;
  95.344 +    }
  95.345 +    if ((flags & COMMENT) != 0) {   /* skip the .gz file comment */
  95.346 +        while ((c = get_byte(s)) != 0 && c != EOF) ;
  95.347 +    }
  95.348 +    if ((flags & HEAD_CRC) != 0) {  /* skip the header crc */
  95.349 +        for (len = 0; len < 2; len++) (void)get_byte(s);
  95.350 +    }
  95.351 +    s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
  95.352 +}
  95.353 +
  95.354 + /* ===========================================================================
  95.355 + * Cleanup then free the given gz_stream. Return a zlib error code.
  95.356 +   Try freeing in the reverse order of allocations.
  95.357 + */
  95.358 +local int destroy (s)
  95.359 +    gz_stream *s;
  95.360 +{
  95.361 +    int err = Z_OK;
  95.362 +
  95.363 +    if (!s) return Z_STREAM_ERROR;
  95.364 +
  95.365 +    TRYFREE(s->msg);
  95.366 +
  95.367 +    if (s->stream.state != NULL) {
  95.368 +        if (s->mode == 'w') {
  95.369 +#ifdef NO_GZCOMPRESS
  95.370 +            err = Z_STREAM_ERROR;
  95.371 +#else
  95.372 +            err = deflateEnd(&(s->stream));
  95.373 +#endif
  95.374 +        } else if (s->mode == 'r') {
  95.375 +            err = inflateEnd(&(s->stream));
  95.376 +        }
  95.377 +    }
  95.378 +    if (s->file != NULL && fclose(s->file)) {
  95.379 +#ifdef ESPIPE
  95.380 +        if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */
  95.381 +#endif
  95.382 +            err = Z_ERRNO;
  95.383 +    }
  95.384 +    if (s->z_err < 0) err = s->z_err;
  95.385 +
  95.386 +    TRYFREE(s->inbuf);
  95.387 +    TRYFREE(s->outbuf);
  95.388 +    TRYFREE(s->path);
  95.389 +    TRYFREE(s);
  95.390 +    return err;
  95.391 +}
  95.392 +
  95.393 +/* ===========================================================================
  95.394 +     Reads the given number of uncompressed bytes from the compressed file.
  95.395 +   gzread returns the number of bytes actually read (0 for end of file).
  95.396 +*/
  95.397 +int ZEXPORT gzread (file, buf, len)
  95.398 +    gzFile file;
  95.399 +    voidp buf;
  95.400 +    unsigned len;
  95.401 +{
  95.402 +    gz_stream *s = (gz_stream*)file;
  95.403 +    Bytef *start = (Bytef*)buf; /* starting point for crc computation */
  95.404 +    Byte  *next_out; /* == stream.next_out but not forced far (for MSDOS) */
  95.405 +
  95.406 +    if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
  95.407 +
  95.408 +    if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
  95.409 +    if (s->z_err == Z_STREAM_END) return 0;  /* EOF */
  95.410 +
  95.411 +    next_out = (Byte*)buf;
  95.412 +    s->stream.next_out = (Bytef*)buf;
  95.413 +    s->stream.avail_out = len;
  95.414 +
  95.415 +    if (s->stream.avail_out && s->back != EOF) {
  95.416 +        *next_out++ = s->back;
  95.417 +        s->stream.next_out++;
  95.418 +        s->stream.avail_out--;
  95.419 +        s->back = EOF;
  95.420 +        s->out++;
  95.421 +        start++;
  95.422 +        if (s->last) {
  95.423 +            s->z_err = Z_STREAM_END;
  95.424 +            return 1;
  95.425 +        }
  95.426 +    }
  95.427 +
  95.428 +    while (s->stream.avail_out != 0) {
  95.429 +
  95.430 +        if (s->transparent) {
  95.431 +            /* Copy first the lookahead bytes: */
  95.432 +            uInt n = s->stream.avail_in;
  95.433 +            if (n > s->stream.avail_out) n = s->stream.avail_out;
  95.434 +            if (n > 0) {
  95.435 +                zmemcpy(s->stream.next_out, s->stream.next_in, n);
  95.436 +                next_out += n;
  95.437 +                s->stream.next_out = next_out;
  95.438 +                s->stream.next_in   += n;
  95.439 +                s->stream.avail_out -= n;
  95.440 +                s->stream.avail_in  -= n;
  95.441 +            }
  95.442 +            if (s->stream.avail_out > 0) {
  95.443 +                s->stream.avail_out -=
  95.444 +                    (uInt)fread(next_out, 1, s->stream.avail_out, s->file);
  95.445 +            }
  95.446 +            len -= s->stream.avail_out;
  95.447 +            s->in  += len;
  95.448 +            s->out += len;
  95.449 +            if (len == 0) s->z_eof = 1;
  95.450 +            return (int)len;
  95.451 +        }
  95.452 +        if (s->stream.avail_in == 0 && !s->z_eof) {
  95.453 +
  95.454 +            errno = 0;
  95.455 +            s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
  95.456 +            if (s->stream.avail_in == 0) {
  95.457 +                s->z_eof = 1;
  95.458 +                if (ferror(s->file)) {
  95.459 +                    s->z_err = Z_ERRNO;
  95.460 +                    break;
  95.461 +                }
  95.462 +            }
  95.463 +            s->stream.next_in = s->inbuf;
  95.464 +        }
  95.465 +        s->in += s->stream.avail_in;
  95.466 +        s->out += s->stream.avail_out;
  95.467 +        s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
  95.468 +        s->in -= s->stream.avail_in;
  95.469 +        s->out -= s->stream.avail_out;
  95.470 +
  95.471 +        if (s->z_err == Z_STREAM_END) {
  95.472 +            /* Check CRC and original size */
  95.473 +            s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
  95.474 +            start = s->stream.next_out;
  95.475 +
  95.476 +            if (getLong(s) != s->crc) {
  95.477 +                s->z_err = Z_DATA_ERROR;
  95.478 +            } else {
  95.479 +                (void)getLong(s);
  95.480 +                /* The uncompressed length returned by above getlong() may be
  95.481 +                 * different from s->out in case of concatenated .gz files.
  95.482 +                 * Check for such files:
  95.483 +                 */
  95.484 +                check_header(s);
  95.485 +                if (s->z_err == Z_OK) {
  95.486 +                    inflateReset(&(s->stream));
  95.487 +                    s->crc = crc32(0L, Z_NULL, 0);
  95.488 +                }
  95.489 +            }
  95.490 +        }
  95.491 +        if (s->z_err != Z_OK || s->z_eof) break;
  95.492 +    }
  95.493 +    s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
  95.494 +
  95.495 +    if (len == s->stream.avail_out &&
  95.496 +        (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO))
  95.497 +        return -1;
  95.498 +    return (int)(len - s->stream.avail_out);
  95.499 +}
  95.500 +
  95.501 +
  95.502 +/* ===========================================================================
  95.503 +      Reads one byte from the compressed file. gzgetc returns this byte
  95.504 +   or -1 in case of end of file or error.
  95.505 +*/
  95.506 +int ZEXPORT gzgetc(file)
  95.507 +    gzFile file;
  95.508 +{
  95.509 +    unsigned char c;
  95.510 +
  95.511 +    return gzread(file, &c, 1) == 1 ? c : -1;
  95.512 +}
  95.513 +
  95.514 +
  95.515 +/* ===========================================================================
  95.516 +      Push one byte back onto the stream.
  95.517 +*/
  95.518 +int ZEXPORT gzungetc(c, file)
  95.519 +    int c;
  95.520 +    gzFile file;
  95.521 +{
  95.522 +    gz_stream *s = (gz_stream*)file;
  95.523 +
  95.524 +    if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF;
  95.525 +    s->back = c;
  95.526 +    s->out--;
  95.527 +    s->last = (s->z_err == Z_STREAM_END);
  95.528 +    if (s->last) s->z_err = Z_OK;
  95.529 +    s->z_eof = 0;
  95.530 +    return c;
  95.531 +}
  95.532 +
  95.533 +
  95.534 +/* ===========================================================================
  95.535 +      Reads bytes from the compressed file until len-1 characters are
  95.536 +   read, or a newline character is read and transferred to buf, or an
  95.537 +   end-of-file condition is encountered.  The string is then terminated
  95.538 +   with a null character.
  95.539 +      gzgets returns buf, or Z_NULL in case of error.
  95.540 +
  95.541 +      The current implementation is not optimized at all.
  95.542 +*/
  95.543 +char * ZEXPORT gzgets(file, buf, len)
  95.544 +    gzFile file;
  95.545 +    char *buf;
  95.546 +    int len;
  95.547 +{
  95.548 +    char *b = buf;
  95.549 +    if (buf == Z_NULL || len <= 0) return Z_NULL;
  95.550 +
  95.551 +    while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ;
  95.552 +    *buf = '\0';
  95.553 +    return b == buf && len > 0 ? Z_NULL : b;
  95.554 +}
  95.555 +
  95.556 +
  95.557 +#ifndef NO_GZCOMPRESS
  95.558 +/* ===========================================================================
  95.559 +     Writes the given number of uncompressed bytes into the compressed file.
  95.560 +   gzwrite returns the number of bytes actually written (0 in case of error).
  95.561 +*/
  95.562 +int ZEXPORT gzwrite (file, buf, len)
  95.563 +    gzFile file;
  95.564 +    voidpc buf;
  95.565 +    unsigned len;
  95.566 +{
  95.567 +    gz_stream *s = (gz_stream*)file;
  95.568 +
  95.569 +    if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
  95.570 +
  95.571 +    s->stream.next_in = (Bytef*)buf;
  95.572 +    s->stream.avail_in = len;
  95.573 +
  95.574 +    while (s->stream.avail_in != 0) {
  95.575 +
  95.576 +        if (s->stream.avail_out == 0) {
  95.577 +
  95.578 +            s->stream.next_out = s->outbuf;
  95.579 +            if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
  95.580 +                s->z_err = Z_ERRNO;
  95.581 +                break;
  95.582 +            }
  95.583 +            s->stream.avail_out = Z_BUFSIZE;
  95.584 +        }
  95.585 +        s->in += s->stream.avail_in;
  95.586 +        s->out += s->stream.avail_out;
  95.587 +        s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
  95.588 +        s->in -= s->stream.avail_in;
  95.589 +        s->out -= s->stream.avail_out;
  95.590 +        if (s->z_err != Z_OK) break;
  95.591 +    }
  95.592 +    s->crc = crc32(s->crc, (const Bytef *)buf, len);
  95.593 +
  95.594 +    return (int)(len - s->stream.avail_in);
  95.595 +}
  95.596 +
  95.597 +
  95.598 +/* ===========================================================================
  95.599 +     Converts, formats, and writes the args to the compressed file under
  95.600 +   control of the format string, as in fprintf. gzprintf returns the number of
  95.601 +   uncompressed bytes actually written (0 in case of error).
  95.602 +*/
  95.603 +#ifdef STDC
  95.604 +#include <stdarg.h>
  95.605 +
  95.606 +int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...)
  95.607 +{
  95.608 +    char buf[Z_PRINTF_BUFSIZE];
  95.609 +    va_list va;
  95.610 +    int len;
  95.611 +
  95.612 +    buf[sizeof(buf) - 1] = 0;
  95.613 +    va_start(va, format);
  95.614 +#ifdef NO_vsnprintf
  95.615 +#  ifdef HAS_vsprintf_void
  95.616 +    (void)vsprintf(buf, format, va);
  95.617 +    va_end(va);
  95.618 +    for (len = 0; len < sizeof(buf); len++)
  95.619 +        if (buf[len] == 0) break;
  95.620 +#  else
  95.621 +    len = vsprintf(buf, format, va);
  95.622 +    va_end(va);
  95.623 +#  endif
  95.624 +#else
  95.625 +#  ifdef HAS_vsnprintf_void
  95.626 +    (void)vsnprintf(buf, sizeof(buf), format, va);
  95.627 +    va_end(va);
  95.628 +    len = strlen(buf);
  95.629 +#  else
  95.630 +    len = vsnprintf(buf, sizeof(buf), format, va);
  95.631 +    va_end(va);
  95.632 +#  endif
  95.633 +#endif
  95.634 +    if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0)
  95.635 +        return 0;
  95.636 +    return gzwrite(file, buf, (unsigned)len);
  95.637 +}
  95.638 +#else /* not ANSI C */
  95.639 +
  95.640 +int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
  95.641 +                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
  95.642 +    gzFile file;
  95.643 +    const char *format;
  95.644 +    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
  95.645 +        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
  95.646 +{
  95.647 +    char buf[Z_PRINTF_BUFSIZE];
  95.648 +    int len;
  95.649 +
  95.650 +    buf[sizeof(buf) - 1] = 0;
  95.651 +#ifdef NO_snprintf
  95.652 +#  ifdef HAS_sprintf_void
  95.653 +    sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
  95.654 +            a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
  95.655 +    for (len = 0; len < sizeof(buf); len++)
  95.656 +        if (buf[len] == 0) break;
  95.657 +#  else
  95.658 +    len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
  95.659 +                a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
  95.660 +#  endif
  95.661 +#else
  95.662 +#  ifdef HAS_snprintf_void
  95.663 +    snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
  95.664 +             a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
  95.665 +    len = strlen(buf);
  95.666 +#  else
  95.667 +    len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
  95.668 +                 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
  95.669 +#  endif
  95.670 +#endif
  95.671 +    if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0)
  95.672 +        return 0;
  95.673 +    return gzwrite(file, buf, len);
  95.674 +}
  95.675 +#endif
  95.676 +
  95.677 +/* ===========================================================================
  95.678 +      Writes c, converted to an unsigned char, into the compressed file.
  95.679 +   gzputc returns the value that was written, or -1 in case of error.
  95.680 +*/
  95.681 +int ZEXPORT gzputc(file, c)
  95.682 +    gzFile file;
  95.683 +    int c;
  95.684 +{
  95.685 +    unsigned char cc = (unsigned char) c; /* required for big endian systems */
  95.686 +
  95.687 +    return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1;
  95.688 +}
  95.689 +
  95.690 +
  95.691 +/* ===========================================================================
  95.692 +      Writes the given null-terminated string to the compressed file, excluding
  95.693 +   the terminating null character.
  95.694 +      gzputs returns the number of characters written, or -1 in case of error.
  95.695 +*/
  95.696 +int ZEXPORT gzputs(file, s)
  95.697 +    gzFile file;
  95.698 +    const char *s;
  95.699 +{
  95.700 +    return gzwrite(file, (char*)s, (unsigned)strlen(s));
  95.701 +}
  95.702 +
  95.703 +
  95.704 +/* ===========================================================================
  95.705 +     Flushes all pending output into the compressed file. The parameter
  95.706 +   flush is as in the deflate() function.
  95.707 +*/
  95.708 +local int do_flush (file, flush)
  95.709 +    gzFile file;
  95.710 +    int flush;
  95.711 +{
  95.712 +    uInt len;
  95.713 +    int done = 0;
  95.714 +    gz_stream *s = (gz_stream*)file;
  95.715 +
  95.716 +    if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
  95.717 +
  95.718 +    s->stream.avail_in = 0; /* should be zero already anyway */
  95.719 +
  95.720 +    for (;;) {
  95.721 +        len = Z_BUFSIZE - s->stream.avail_out;
  95.722 +
  95.723 +        if (len != 0) {
  95.724 +            if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) {
  95.725 +                s->z_err = Z_ERRNO;
  95.726 +                return Z_ERRNO;
  95.727 +            }
  95.728 +            s->stream.next_out = s->outbuf;
  95.729 +            s->stream.avail_out = Z_BUFSIZE;
  95.730 +        }
  95.731 +        if (done) break;
  95.732 +        s->out += s->stream.avail_out;
  95.733 +        s->z_err = deflate(&(s->stream), flush);
  95.734 +        s->out -= s->stream.avail_out;
  95.735 +
  95.736 +        /* Ignore the second of two consecutive flushes: */
  95.737 +        if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK;
  95.738 +
  95.739 +        /* deflate has finished flushing only when it hasn't used up
  95.740 +         * all the available space in the output buffer:
  95.741 +         */
  95.742 +        done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
  95.743 +
  95.744 +        if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
  95.745 +    }
  95.746 +    return  s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
  95.747 +}
  95.748 +
  95.749 +int ZEXPORT gzflush (file, flush)
  95.750 +     gzFile file;
  95.751 +     int flush;
  95.752 +{
  95.753 +    gz_stream *s = (gz_stream*)file;
  95.754 +    int err = do_flush (file, flush);
  95.755 +
  95.756 +    if (err) return err;
  95.757 +    fflush(s->file);
  95.758 +    return  s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
  95.759 +}
  95.760 +#endif /* NO_GZCOMPRESS */
  95.761 +
  95.762 +/* ===========================================================================
  95.763 +      Sets the starting position for the next gzread or gzwrite on the given
  95.764 +   compressed file. The offset represents a number of bytes in the
  95.765 +      gzseek returns the resulting offset location as measured in bytes from
  95.766 +   the beginning of the uncompressed stream, or -1 in case of error.
  95.767 +      SEEK_END is not implemented, returns error.
  95.768 +      In this version of the library, gzseek can be extremely slow.
  95.769 +*/
  95.770 +z_off_t ZEXPORT gzseek (file, offset, whence)
  95.771 +    gzFile file;
  95.772 +    z_off_t offset;
  95.773 +    int whence;
  95.774 +{
  95.775 +    gz_stream *s = (gz_stream*)file;
  95.776 +
  95.777 +    if (s == NULL || whence == SEEK_END ||
  95.778 +        s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) {
  95.779 +        return -1L;
  95.780 +    }
  95.781 +
  95.782 +    if (s->mode == 'w') {
  95.783 +#ifdef NO_GZCOMPRESS
  95.784 +        return -1L;
  95.785 +#else
  95.786 +        if (whence == SEEK_SET) {
  95.787 +            offset -= s->in;
  95.788 +        }
  95.789 +        if (offset < 0) return -1L;
  95.790 +
  95.791 +        /* At this point, offset is the number of zero bytes to write. */
  95.792 +        if (s->inbuf == Z_NULL) {
  95.793 +            s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */
  95.794 +            if (s->inbuf == Z_NULL) return -1L;
  95.795 +            zmemzero(s->inbuf, Z_BUFSIZE);
  95.796 +        }
  95.797 +        while (offset > 0)  {
  95.798 +            uInt size = Z_BUFSIZE;
  95.799 +            if (offset < Z_BUFSIZE) size = (uInt)offset;
  95.800 +
  95.801 +            size = gzwrite(file, s->inbuf, size);
  95.802 +            if (size == 0) return -1L;
  95.803 +
  95.804 +            offset -= size;
  95.805 +        }
  95.806 +        return s->in;
  95.807 +#endif
  95.808 +    }
  95.809 +    /* Rest of function is for reading only */
  95.810 +
  95.811 +    /* compute absolute position */
  95.812 +    if (whence == SEEK_CUR) {
  95.813 +        offset += s->out;
  95.814 +    }
  95.815 +    if (offset < 0) return -1L;
  95.816 +
  95.817 +    if (s->transparent) {
  95.818 +        /* map to fseek */
  95.819 +        s->back = EOF;
  95.820 +        s->stream.avail_in = 0;
  95.821 +        s->stream.next_in = s->inbuf;
  95.822 +        if (fseek(s->file, offset, SEEK_SET) < 0) return -1L;
  95.823 +
  95.824 +        s->in = s->out = offset;
  95.825 +        return offset;
  95.826 +    }
  95.827 +
  95.828 +    /* For a negative seek, rewind and use positive seek */
  95.829 +    if (offset >= s->out) {
  95.830 +        offset -= s->out;
  95.831 +    } else if (gzrewind(file) < 0) {
  95.832 +        return -1L;
  95.833 +    }
  95.834 +    /* offset is now the number of bytes to skip. */
  95.835 +
  95.836 +    if (offset != 0 && s->outbuf == Z_NULL) {
  95.837 +        s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
  95.838 +        if (s->outbuf == Z_NULL) return -1L;
  95.839 +    }
  95.840 +    if (offset && s->back != EOF) {
  95.841 +        s->back = EOF;
  95.842 +        s->out++;
  95.843 +        offset--;
  95.844 +        if (s->last) s->z_err = Z_STREAM_END;
  95.845 +    }
  95.846 +    while (offset > 0)  {
  95.847 +        int size = Z_BUFSIZE;
  95.848 +        if (offset < Z_BUFSIZE) size = (int)offset;
  95.849 +
  95.850 +        size = gzread(file, s->outbuf, (uInt)size);
  95.851 +        if (size <= 0) return -1L;
  95.852 +        offset -= size;
  95.853 +    }
  95.854 +    return s->out;
  95.855 +}
  95.856 +
  95.857 +/* ===========================================================================
  95.858 +     Rewinds input file.
  95.859 +*/
  95.860 +int ZEXPORT gzrewind (file)
  95.861 +    gzFile file;
  95.862 +{
  95.863 +    gz_stream *s = (gz_stream*)file;
  95.864 +
  95.865 +    if (s == NULL || s->mode != 'r') return -1;
  95.866 +
  95.867 +    s->z_err = Z_OK;
  95.868 +    s->z_eof = 0;
  95.869 +    s->back = EOF;
  95.870 +    s->stream.avail_in = 0;
  95.871 +    s->stream.next_in = s->inbuf;
  95.872 +    s->crc = crc32(0L, Z_NULL, 0);
  95.873 +    if (!s->transparent) (void)inflateReset(&s->stream);
  95.874 +    s->in = 0;
  95.875 +    s->out = 0;
  95.876 +    return fseek(s->file, s->start, SEEK_SET);
  95.877 +}
  95.878 +
  95.879 +/* ===========================================================================
  95.880 +     Returns the starting position for the next gzread or gzwrite on the
  95.881 +   given compressed file. This position represents a number of bytes in the
  95.882 +   uncompressed data stream.
  95.883 +*/
  95.884 +z_off_t ZEXPORT gztell (file)
  95.885 +    gzFile file;
  95.886 +{
  95.887 +    return gzseek(file, 0L, SEEK_CUR);
  95.888 +}
  95.889 +
  95.890 +/* ===========================================================================
  95.891 +     Returns 1 when EOF has previously been detected reading the given
  95.892 +   input stream, otherwise zero.
  95.893 +*/
  95.894 +int ZEXPORT gzeof (file)
  95.895 +    gzFile file;
  95.896 +{
  95.897 +    gz_stream *s = (gz_stream*)file;
  95.898 +
  95.899 +    /* With concatenated compressed files that can have embedded
  95.900 +     * crc trailers, z_eof is no longer the only/best indicator of EOF
  95.901 +     * on a gz_stream. Handle end-of-stream error explicitly here.
  95.902 +     */
  95.903 +    if (s == NULL || s->mode != 'r') return 0;
  95.904 +    if (s->z_eof) return 1;
  95.905 +    return s->z_err == Z_STREAM_END;
  95.906 +}
  95.907 +
  95.908 +/* ===========================================================================
  95.909 +     Returns 1 if reading and doing so transparently, otherwise zero.
  95.910 +*/
  95.911 +int ZEXPORT gzdirect (file)
  95.912 +    gzFile file;
  95.913 +{
  95.914 +    gz_stream *s = (gz_stream*)file;
  95.915 +
  95.916 +    if (s == NULL || s->mode != 'r') return 0;
  95.917 +    return s->transparent;
  95.918 +}
  95.919 +
  95.920 +/* ===========================================================================
  95.921 +   Outputs a long in LSB order to the given file
  95.922 +*/
  95.923 +local void putLong (file, x)
  95.924 +    FILE *file;
  95.925 +    uLong x;
  95.926 +{
  95.927 +    int n;
  95.928 +    for (n = 0; n < 4; n++) {
  95.929 +        fputc((int)(x & 0xff), file);
  95.930 +        x >>= 8;
  95.931 +    }
  95.932 +}
  95.933 +
  95.934 +/* ===========================================================================
  95.935 +   Reads a long in LSB order from the given gz_stream. Sets z_err in case
  95.936 +   of error.
  95.937 +*/
  95.938 +local uLong getLong (s)
  95.939 +    gz_stream *s;
  95.940 +{
  95.941 +    uLong x = (uLong)get_byte(s);
  95.942 +    int c;
  95.943 +
  95.944 +    x += ((uLong)get_byte(s))<<8;
  95.945 +    x += ((uLong)get_byte(s))<<16;
  95.946 +    c = get_byte(s);
  95.947 +    if (c == EOF) s->z_err = Z_DATA_ERROR;
  95.948 +    x += ((uLong)c)<<24;
  95.949 +    return x;
  95.950 +}
  95.951 +
  95.952 +/* ===========================================================================
  95.953 +     Flushes all pending output if necessary, closes the compressed file
  95.954 +   and deallocates all the (de)compression state.
  95.955 +*/
  95.956 +int ZEXPORT gzclose (file)
  95.957 +    gzFile file;
  95.958 +{
  95.959 +    gz_stream *s = (gz_stream*)file;
  95.960 +
  95.961 +    if (s == NULL) return Z_STREAM_ERROR;
  95.962 +
  95.963 +    if (s->mode == 'w') {
  95.964 +#ifdef NO_GZCOMPRESS
  95.965 +        return Z_STREAM_ERROR;
  95.966 +#else
  95.967 +        if (do_flush (file, Z_FINISH) != Z_OK)
  95.968 +            return destroy((gz_stream*)file);
  95.969 +
  95.970 +        putLong (s->file, s->crc);
  95.971 +        putLong (s->file, (uLong)(s->in & 0xffffffff));
  95.972 +#endif
  95.973 +    }
  95.974 +    return destroy((gz_stream*)file);
  95.975 +}
  95.976 +
  95.977 +#ifdef STDC
  95.978 +#  define zstrerror(errnum) strerror(errnum)
  95.979 +#else
  95.980 +#  define zstrerror(errnum) ""
  95.981 +#endif
  95.982 +
  95.983 +/* ===========================================================================
  95.984 +     Returns the error message for the last error which occurred on the
  95.985 +   given compressed file. errnum is set to zlib error number. If an
  95.986 +   error occurred in the file system and not in the compression library,
  95.987 +   errnum is set to Z_ERRNO and the application may consult errno
  95.988 +   to get the exact error code.
  95.989 +*/
  95.990 +const char * ZEXPORT gzerror (file, errnum)
  95.991 +    gzFile file;
  95.992 +    int *errnum;
  95.993 +{
  95.994 +    char *m;
  95.995 +    gz_stream *s = (gz_stream*)file;
  95.996 +
  95.997 +    if (s == NULL) {
  95.998 +        *errnum = Z_STREAM_ERROR;
  95.999 +        return (const char*)ERR_MSG(Z_STREAM_ERROR);
 95.1000 +    }
 95.1001 +    *errnum = s->z_err;
 95.1002 +    if (*errnum == Z_OK) return (const char*)"";
 95.1003 +
 95.1004 +    m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg);
 95.1005 +
 95.1006 +    if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
 95.1007 +
 95.1008 +    TRYFREE(s->msg);
 95.1009 +    s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3);
 95.1010 +    if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR);
 95.1011 +    strcpy(s->msg, s->path);
 95.1012 +    strcat(s->msg, ": ");
 95.1013 +    strcat(s->msg, m);
 95.1014 +    return (const char*)s->msg;
 95.1015 +}
 95.1016 +
 95.1017 +/* ===========================================================================
 95.1018 +     Clear the error and end-of-file flags, and do the same for the real file.
 95.1019 +*/
 95.1020 +void ZEXPORT gzclearerr (file)
 95.1021 +    gzFile file;
 95.1022 +{
 95.1023 +    gz_stream *s = (gz_stream*)file;
 95.1024 +
 95.1025 +    if (s == NULL) return;
 95.1026 +    if (s->z_err != Z_STREAM_END) s->z_err = Z_OK;
 95.1027 +    s->z_eof = 0;
 95.1028 +    clearerr(s->file);
 95.1029 +}
    96.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    96.2 +++ b/libs/zlib/infback.c	Thu Sep 08 06:28:38 2011 +0300
    96.3 @@ -0,0 +1,623 @@
    96.4 +/* infback.c -- inflate using a call-back interface
    96.5 + * Copyright (C) 1995-2005 Mark Adler
    96.6 + * For conditions of distribution and use, see copyright notice in zlib.h
    96.7 + */
    96.8 +
    96.9 +/*
   96.10 +   This code is largely copied from inflate.c.  Normally either infback.o or
   96.11 +   inflate.o would be linked into an application--not both.  The interface
   96.12 +   with inffast.c is retained so that optimized assembler-coded versions of
   96.13 +   inflate_fast() can be used with either inflate.c or infback.c.
   96.14 + */
   96.15 +
   96.16 +#include "zutil.h"
   96.17 +#include "inftrees.h"
   96.18 +#include "inflate.h"
   96.19 +#include "inffast.h"
   96.20 +
   96.21 +/* function prototypes */
   96.22 +local void fixedtables OF((struct inflate_state FAR *state));
   96.23 +
   96.24 +/*
   96.25 +   strm provides memory allocation functions in zalloc and zfree, or
   96.26 +   Z_NULL to use the library memory allocation functions.
   96.27 +
   96.28 +   windowBits is in the range 8..15, and window is a user-supplied
   96.29 +   window and output buffer that is 2**windowBits bytes.
   96.30 + */
   96.31 +int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
   96.32 +z_streamp strm;
   96.33 +int windowBits;
   96.34 +unsigned char FAR *window;
   96.35 +const char *version;
   96.36 +int stream_size;
   96.37 +{
   96.38 +    struct inflate_state FAR *state;
   96.39 +
   96.40 +    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
   96.41 +        stream_size != (int)(sizeof(z_stream)))
   96.42 +        return Z_VERSION_ERROR;
   96.43 +    if (strm == Z_NULL || window == Z_NULL ||
   96.44 +        windowBits < 8 || windowBits > 15)
   96.45 +        return Z_STREAM_ERROR;
   96.46 +    strm->msg = Z_NULL;                 /* in case we return an error */
   96.47 +    if (strm->zalloc == (alloc_func)0) {
   96.48 +        strm->zalloc = zcalloc;
   96.49 +        strm->opaque = (voidpf)0;
   96.50 +    }
   96.51 +    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
   96.52 +    state = (struct inflate_state FAR *)ZALLOC(strm, 1,
   96.53 +                                               sizeof(struct inflate_state));
   96.54 +    if (state == Z_NULL) return Z_MEM_ERROR;
   96.55 +    Tracev((stderr, "inflate: allocated\n"));
   96.56 +    strm->state = (struct internal_state FAR *)state;
   96.57 +    state->dmax = 32768U;
   96.58 +    state->wbits = windowBits;
   96.59 +    state->wsize = 1U << windowBits;
   96.60 +    state->window = window;
   96.61 +    state->write = 0;
   96.62 +    state->whave = 0;
   96.63 +    return Z_OK;
   96.64 +}
   96.65 +
   96.66 +/*
   96.67 +   Return state with length and distance decoding tables and index sizes set to
   96.68 +   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
   96.69 +   If BUILDFIXED is defined, then instead this routine builds the tables the
   96.70 +   first time it's called, and returns those tables the first time and
   96.71 +   thereafter.  This reduces the size of the code by about 2K bytes, in
   96.72 +   exchange for a little execution time.  However, BUILDFIXED should not be
   96.73 +   used for threaded applications, since the rewriting of the tables and virgin
   96.74 +   may not be thread-safe.
   96.75 + */
   96.76 +local void fixedtables(state)
   96.77 +struct inflate_state FAR *state;
   96.78 +{
   96.79 +#ifdef BUILDFIXED
   96.80 +    static int virgin = 1;
   96.81 +    static code *lenfix, *distfix;
   96.82 +    static code fixed[544];
   96.83 +
   96.84 +    /* build fixed huffman tables if first call (may not be thread safe) */
   96.85 +    if (virgin) {
   96.86 +        unsigned sym, bits;
   96.87 +        static code *next;
   96.88 +
   96.89 +        /* literal/length table */
   96.90 +        sym = 0;
   96.91 +        while (sym < 144) state->lens[sym++] = 8;
   96.92 +        while (sym < 256) state->lens[sym++] = 9;
   96.93 +        while (sym < 280) state->lens[sym++] = 7;
   96.94 +        while (sym < 288) state->lens[sym++] = 8;
   96.95 +        next = fixed;
   96.96 +        lenfix = next;
   96.97 +        bits = 9;
   96.98 +        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
   96.99 +
  96.100 +        /* distance table */
  96.101 +        sym = 0;
  96.102 +        while (sym < 32) state->lens[sym++] = 5;
  96.103 +        distfix = next;
  96.104 +        bits = 5;
  96.105 +        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  96.106 +
  96.107 +        /* do this just once */
  96.108 +        virgin = 0;
  96.109 +    }
  96.110 +#else /* !BUILDFIXED */
  96.111 +#   include "inffixed.h"
  96.112 +#endif /* BUILDFIXED */
  96.113 +    state->lencode = lenfix;
  96.114 +    state->lenbits = 9;
  96.115 +    state->distcode = distfix;
  96.116 +    state->distbits = 5;
  96.117 +}
  96.118 +
  96.119 +/* Macros for inflateBack(): */
  96.120 +
  96.121 +/* Load returned state from inflate_fast() */
  96.122 +#define LOAD() \
  96.123 +    do { \
  96.124 +        put = strm->next_out; \
  96.125 +        left = strm->avail_out; \
  96.126 +        next = strm->next_in; \
  96.127 +        have = strm->avail_in; \
  96.128 +        hold = state->hold; \
  96.129 +        bits = state->bits; \
  96.130 +    } while (0)
  96.131 +
  96.132 +/* Set state from registers for inflate_fast() */
  96.133 +#define RESTORE() \
  96.134 +    do { \
  96.135 +        strm->next_out = put; \
  96.136 +        strm->avail_out = left; \
  96.137 +        strm->next_in = next; \
  96.138 +        strm->avail_in = have; \
  96.139 +        state->hold = hold; \
  96.140 +        state->bits = bits; \
  96.141 +    } while (0)
  96.142 +
  96.143 +/* Clear the input bit accumulator */
  96.144 +#define INITBITS() \
  96.145 +    do { \
  96.146 +        hold = 0; \
  96.147 +        bits = 0; \
  96.148 +    } while (0)
  96.149 +
  96.150 +/* Assure that some input is available.  If input is requested, but denied,
  96.151 +   then return a Z_BUF_ERROR from inflateBack(). */
  96.152 +#define PULL() \
  96.153 +    do { \
  96.154 +        if (have == 0) { \
  96.155 +            have = in(in_desc, &next); \
  96.156 +            if (have == 0) { \
  96.157 +                next = Z_NULL; \
  96.158 +                ret = Z_BUF_ERROR; \
  96.159 +                goto inf_leave; \
  96.160 +            } \
  96.161 +        } \
  96.162 +    } while (0)
  96.163 +
  96.164 +/* Get a byte of input into the bit accumulator, or return from inflateBack()
  96.165 +   with an error if there is no input available. */
  96.166 +#define PULLBYTE() \
  96.167 +    do { \
  96.168 +        PULL(); \
  96.169 +        have--; \
  96.170 +        hold += (unsigned long)(*next++) << bits; \
  96.171 +        bits += 8; \
  96.172 +    } while (0)
  96.173 +
  96.174 +/* Assure that there are at least n bits in the bit accumulator.  If there is
  96.175 +   not enough available input to do that, then return from inflateBack() with
  96.176 +   an error. */
  96.177 +#define NEEDBITS(n) \
  96.178 +    do { \
  96.179 +        while (bits < (unsigned)(n)) \
  96.180 +            PULLBYTE(); \
  96.181 +    } while (0)
  96.182 +
  96.183 +/* Return the low n bits of the bit accumulator (n < 16) */
  96.184 +#define BITS(n) \
  96.185 +    ((unsigned)hold & ((1U << (n)) - 1))
  96.186 +
  96.187 +/* Remove n bits from the bit accumulator */
  96.188 +#define DROPBITS(n) \
  96.189 +    do { \
  96.190 +        hold >>= (n); \
  96.191 +        bits -= (unsigned)(n); \
  96.192 +    } while (0)
  96.193 +
  96.194 +/* Remove zero to seven bits as needed to go to a byte boundary */
  96.195 +#define BYTEBITS() \
  96.196 +    do { \
  96.197 +        hold >>= bits & 7; \
  96.198 +        bits -= bits & 7; \
  96.199 +    } while (0)
  96.200 +
  96.201 +/* Assure that some output space is available, by writing out the window
  96.202 +   if it's full.  If the write fails, return from inflateBack() with a
  96.203 +   Z_BUF_ERROR. */
  96.204 +#define ROOM() \
  96.205 +    do { \
  96.206 +        if (left == 0) { \
  96.207 +            put = state->window; \
  96.208 +            left = state->wsize; \
  96.209 +            state->whave = left; \
  96.210 +            if (out(out_desc, put, left)) { \
  96.211 +                ret = Z_BUF_ERROR; \
  96.212 +                goto inf_leave; \
  96.213 +            } \
  96.214 +        } \
  96.215 +    } while (0)
  96.216 +
  96.217 +/*
  96.218 +   strm provides the memory allocation functions and window buffer on input,
  96.219 +   and provides information on the unused input on return.  For Z_DATA_ERROR
  96.220 +   returns, strm will also provide an error message.
  96.221 +
  96.222 +   in() and out() are the call-back input and output functions.  When
  96.223 +   inflateBack() needs more input, it calls in().  When inflateBack() has
  96.224 +   filled the window with output, or when it completes with data in the
  96.225 +   window, it calls out() to write out the data.  The application must not
  96.226 +   change the provided input until in() is called again or inflateBack()
  96.227 +   returns.  The application must not change the window/output buffer until
  96.228 +   inflateBack() returns.
  96.229 +
  96.230 +   in() and out() are called with a descriptor parameter provided in the
  96.231 +   inflateBack() call.  This parameter can be a structure that provides the
  96.232 +   information required to do the read or write, as well as accumulated
  96.233 +   information on the input and output such as totals and check values.
  96.234 +
  96.235 +   in() should return zero on failure.  out() should return non-zero on
  96.236 +   failure.  If either in() or out() fails, than inflateBack() returns a
  96.237 +   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it
  96.238 +   was in() or out() that caused in the error.  Otherwise,  inflateBack()
  96.239 +   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
  96.240 +   error, or Z_MEM_ERROR if it could not allocate memory for the state.
  96.241 +   inflateBack() can also return Z_STREAM_ERROR if the input parameters
  96.242 +   are not correct, i.e. strm is Z_NULL or the state was not initialized.
  96.243 + */
  96.244 +int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
  96.245 +z_streamp strm;
  96.246 +in_func in;
  96.247 +void FAR *in_desc;
  96.248 +out_func out;
  96.249 +void FAR *out_desc;
  96.250 +{
  96.251 +    struct inflate_state FAR *state;
  96.252 +    unsigned char FAR *next;    /* next input */
  96.253 +    unsigned char FAR *put;     /* next output */
  96.254 +    unsigned have, left;        /* available input and output */
  96.255 +    unsigned long hold;         /* bit buffer */
  96.256 +    unsigned bits;              /* bits in bit buffer */
  96.257 +    unsigned copy;              /* number of stored or match bytes to copy */
  96.258 +    unsigned char FAR *from;    /* where to copy match bytes from */
  96.259 +    code this;                  /* current decoding table entry */
  96.260 +    code last;                  /* parent table entry */
  96.261 +    unsigned len;               /* length to copy for repeats, bits to drop */
  96.262 +    int ret;                    /* return code */
  96.263 +    static const unsigned short order[19] = /* permutation of code lengths */
  96.264 +        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  96.265 +
  96.266 +    /* Check that the strm exists and that the state was initialized */
  96.267 +    if (strm == Z_NULL || strm->state == Z_NULL)
  96.268 +        return Z_STREAM_ERROR;
  96.269 +    state = (struct inflate_state FAR *)strm->state;
  96.270 +
  96.271 +    /* Reset the state */
  96.272 +    strm->msg = Z_NULL;
  96.273 +    state->mode = TYPE;
  96.274 +    state->last = 0;
  96.275 +    state->whave = 0;
  96.276 +    next = strm->next_in;
  96.277 +    have = next != Z_NULL ? strm->avail_in : 0;
  96.278 +    hold = 0;
  96.279 +    bits = 0;
  96.280 +    put = state->window;
  96.281 +    left = state->wsize;
  96.282 +
  96.283 +    /* Inflate until end of block marked as last */
  96.284 +    for (;;)
  96.285 +        switch (state->mode) {
  96.286 +        case TYPE:
  96.287 +            /* determine and dispatch block type */
  96.288 +            if (state->last) {
  96.289 +                BYTEBITS();
  96.290 +                state->mode = DONE;
  96.291 +                break;
  96.292 +            }
  96.293 +            NEEDBITS(3);
  96.294 +            state->last = BITS(1);
  96.295 +            DROPBITS(1);
  96.296 +            switch (BITS(2)) {
  96.297 +            case 0:                             /* stored block */
  96.298 +                Tracev((stderr, "inflate:     stored block%s\n",
  96.299 +                        state->last ? " (last)" : ""));
  96.300 +                state->mode = STORED;
  96.301 +                break;
  96.302 +            case 1:                             /* fixed block */
  96.303 +                fixedtables(state);
  96.304 +                Tracev((stderr, "inflate:     fixed codes block%s\n",
  96.305 +                        state->last ? " (last)" : ""));
  96.306 +                state->mode = LEN;              /* decode codes */
  96.307 +                break;
  96.308 +            case 2:                             /* dynamic block */
  96.309 +                Tracev((stderr, "inflate:     dynamic codes block%s\n",
  96.310 +                        state->last ? " (last)" : ""));
  96.311 +                state->mode = TABLE;
  96.312 +                break;
  96.313 +            case 3:
  96.314 +                strm->msg = (char *)"invalid block type";
  96.315 +                state->mode = BAD;
  96.316 +            }
  96.317 +            DROPBITS(2);
  96.318 +            break;
  96.319 +
  96.320 +        case STORED:
  96.321 +            /* get and verify stored block length */
  96.322 +            BYTEBITS();                         /* go to byte boundary */
  96.323 +            NEEDBITS(32);
  96.324 +            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  96.325 +                strm->msg = (char *)"invalid stored block lengths";
  96.326 +                state->mode = BAD;
  96.327 +                break;
  96.328 +            }
  96.329 +            state->length = (unsigned)hold & 0xffff;
  96.330 +            Tracev((stderr, "inflate:       stored length %u\n",
  96.331 +                    state->length));
  96.332 +            INITBITS();
  96.333 +
  96.334 +            /* copy stored block from input to output */
  96.335 +            while (state->length != 0) {
  96.336 +                copy = state->length;
  96.337 +                PULL();
  96.338 +                ROOM();
  96.339 +                if (copy > have) copy = have;
  96.340 +                if (copy > left) copy = left;
  96.341 +                zmemcpy(put, next, copy);
  96.342 +                have -= copy;
  96.343 +                next += copy;
  96.344 +                left -= copy;
  96.345 +                put += copy;
  96.346 +                state->length -= copy;
  96.347 +            }
  96.348 +            Tracev((stderr, "inflate:       stored end\n"));
  96.349 +            state->mode = TYPE;
  96.350 +            break;
  96.351 +
  96.352 +        case TABLE:
  96.353 +            /* get dynamic table entries descriptor */
  96.354 +            NEEDBITS(14);
  96.355 +            state->nlen = BITS(5) + 257;
  96.356 +            DROPBITS(5);
  96.357 +            state->ndist = BITS(5) + 1;
  96.358 +            DROPBITS(5);
  96.359 +            state->ncode = BITS(4) + 4;
  96.360 +            DROPBITS(4);
  96.361 +#ifndef PKZIP_BUG_WORKAROUND
  96.362 +            if (state->nlen > 286 || state->ndist > 30) {
  96.363 +                strm->msg = (char *)"too many length or distance symbols";
  96.364 +                state->mode = BAD;
  96.365 +                break;
  96.366 +            }
  96.367 +#endif
  96.368 +            Tracev((stderr, "inflate:       table sizes ok\n"));
  96.369 +
  96.370 +            /* get code length code lengths (not a typo) */
  96.371 +            state->have = 0;
  96.372 +            while (state->have < state->ncode) {
  96.373 +                NEEDBITS(3);
  96.374 +                state->lens[order[state->have++]] = (unsigned short)BITS(3);
  96.375 +                DROPBITS(3);
  96.376 +            }
  96.377 +            while (state->have < 19)
  96.378 +                state->lens[order[state->have++]] = 0;
  96.379 +            state->next = state->codes;
  96.380 +            state->lencode = (code const FAR *)(state->next);
  96.381 +            state->lenbits = 7;
  96.382 +            ret = inflate_table(CODES, state->lens, 19, &(state->next),
  96.383 +                                &(state->lenbits), state->work);
  96.384 +            if (ret) {
  96.385 +                strm->msg = (char *)"invalid code lengths set";
  96.386 +                state->mode = BAD;
  96.387 +                break;
  96.388 +            }
  96.389 +            Tracev((stderr, "inflate:       code lengths ok\n"));
  96.390 +
  96.391 +            /* get length and distance code code lengths */
  96.392 +            state->have = 0;
  96.393 +            while (state->have < state->nlen + state->ndist) {
  96.394 +                for (;;) {
  96.395 +                    this = state->lencode[BITS(state->lenbits)];
  96.396 +                    if ((unsigned)(this.bits) <= bits) break;
  96.397 +                    PULLBYTE();
  96.398 +                }
  96.399 +                if (this.val < 16) {
  96.400 +                    NEEDBITS(this.bits);
  96.401 +                    DROPBITS(this.bits);
  96.402 +                    state->lens[state->have++] = this.val;
  96.403 +                }
  96.404 +                else {
  96.405 +                    if (this.val == 16) {
  96.406 +                        NEEDBITS(this.bits + 2);
  96.407 +                        DROPBITS(this.bits);
  96.408 +                        if (state->have == 0) {
  96.409 +                            strm->msg = (char *)"invalid bit length repeat";
  96.410 +                            state->mode = BAD;
  96.411 +                            break;
  96.412 +                        }
  96.413 +                        len = (unsigned)(state->lens[state->have - 1]);
  96.414 +                        copy = 3 + BITS(2);
  96.415 +                        DROPBITS(2);
  96.416 +                    }
  96.417 +                    else if (this.val == 17) {
  96.418 +                        NEEDBITS(this.bits + 3);
  96.419 +                        DROPBITS(this.bits);
  96.420 +                        len = 0;
  96.421 +                        copy = 3 + BITS(3);
  96.422 +                        DROPBITS(3);
  96.423 +                    }
  96.424 +                    else {
  96.425 +                        NEEDBITS(this.bits + 7);
  96.426 +                        DROPBITS(this.bits);
  96.427 +                        len = 0;
  96.428 +                        copy = 11 + BITS(7);
  96.429 +                        DROPBITS(7);
  96.430 +                    }
  96.431 +                    if (state->have + copy > state->nlen + state->ndist) {
  96.432 +                        strm->msg = (char *)"invalid bit length repeat";
  96.433 +                        state->mode = BAD;
  96.434 +                        break;
  96.435 +                    }
  96.436 +                    while (copy--)
  96.437 +                        state->lens[state->have++] = (unsigned short)len;
  96.438 +                }
  96.439 +            }
  96.440 +
  96.441 +            /* handle error breaks in while */
  96.442 +            if (state->mode == BAD) break;
  96.443 +
  96.444 +            /* build code tables */
  96.445 +            state->next = state->codes;
  96.446 +            state->lencode = (code const FAR *)(state->next);
  96.447 +            state->lenbits = 9;
  96.448 +            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  96.449 +                                &(state->lenbits), state->work);
  96.450 +            if (ret) {
  96.451 +                strm->msg = (char *)"invalid literal/lengths set";
  96.452 +                state->mode = BAD;
  96.453 +                break;
  96.454 +            }
  96.455 +            state->distcode = (code const FAR *)(state->next);
  96.456 +            state->distbits = 6;
  96.457 +            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  96.458 +                            &(state->next), &(state->distbits), state->work);
  96.459 +            if (ret) {
  96.460 +                strm->msg = (char *)"invalid distances set";
  96.461 +                state->mode = BAD;
  96.462 +                break;
  96.463 +            }
  96.464 +            Tracev((stderr, "inflate:       codes ok\n"));
  96.465 +            state->mode = LEN;
  96.466 +
  96.467 +        case LEN:
  96.468 +            /* use inflate_fast() if we have enough input and output */
  96.469 +            if (have >= 6 && left >= 258) {
  96.470 +                RESTORE();
  96.471 +                if (state->whave < state->wsize)
  96.472 +                    state->whave = state->wsize - left;
  96.473 +                inflate_fast(strm, state->wsize);
  96.474 +                LOAD();
  96.475 +                break;
  96.476 +            }
  96.477 +
  96.478 +            /* get a literal, length, or end-of-block code */
  96.479 +            for (;;) {
  96.480 +                this = state->lencode[BITS(state->lenbits)];
  96.481 +                if ((unsigned)(this.bits) <= bits) break;
  96.482 +                PULLBYTE();
  96.483 +            }
  96.484 +            if (this.op && (this.op & 0xf0) == 0) {
  96.485 +                last = this;
  96.486 +                for (;;) {
  96.487 +                    this = state->lencode[last.val +
  96.488 +                            (BITS(last.bits + last.op) >> last.bits)];
  96.489 +                    if ((unsigned)(last.bits + this.bits) <= bits) break;
  96.490 +                    PULLBYTE();
  96.491 +                }
  96.492 +                DROPBITS(last.bits);
  96.493 +            }
  96.494 +            DROPBITS(this.bits);
  96.495 +            state->length = (unsigned)this.val;
  96.496 +
  96.497 +            /* process literal */
  96.498 +            if (this.op == 0) {
  96.499 +                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
  96.500 +                        "inflate:         literal '%c'\n" :
  96.501 +                        "inflate:         literal 0x%02x\n", this.val));
  96.502 +                ROOM();
  96.503 +                *put++ = (unsigned char)(state->length);
  96.504 +                left--;
  96.505 +                state->mode = LEN;
  96.506 +                break;
  96.507 +            }
  96.508 +
  96.509 +            /* process end of block */
  96.510 +            if (this.op & 32) {
  96.511 +                Tracevv((stderr, "inflate:         end of block\n"));
  96.512 +                state->mode = TYPE;
  96.513 +                break;
  96.514 +            }
  96.515 +
  96.516 +            /* invalid code */
  96.517 +            if (this.op & 64) {
  96.518 +                strm->msg = (char *)"invalid literal/length code";
  96.519 +                state->mode = BAD;
  96.520 +                break;
  96.521 +            }
  96.522 +
  96.523 +            /* length code -- get extra bits, if any */
  96.524 +            state->extra = (unsigned)(this.op) & 15;
  96.525 +            if (state->extra != 0) {
  96.526 +                NEEDBITS(state->extra);
  96.527 +                state->length += BITS(state->extra);
  96.528 +                DROPBITS(state->extra);
  96.529 +            }
  96.530 +            Tracevv((stderr, "inflate:         length %u\n", state->length));
  96.531 +
  96.532 +            /* get distance code */
  96.533 +            for (;;) {
  96.534 +                this = state->distcode[BITS(state->distbits)];
  96.535 +                if ((unsigned)(this.bits) <= bits) break;
  96.536 +                PULLBYTE();
  96.537 +            }
  96.538 +            if ((this.op & 0xf0) == 0) {
  96.539 +                last = this;
  96.540 +                for (;;) {
  96.541 +                    this = state->distcode[last.val +
  96.542 +                            (BITS(last.bits + last.op) >> last.bits)];
  96.543 +                    if ((unsigned)(last.bits + this.bits) <= bits) break;
  96.544 +                    PULLBYTE();
  96.545 +                }
  96.546 +                DROPBITS(last.bits);
  96.547 +            }
  96.548 +            DROPBITS(this.bits);
  96.549 +            if (this.op & 64) {
  96.550 +                strm->msg = (char *)"invalid distance code";
  96.551 +                state->mode = BAD;
  96.552 +                break;
  96.553 +            }
  96.554 +            state->offset = (unsigned)this.val;
  96.555 +
  96.556 +            /* get distance extra bits, if any */
  96.557 +            state->extra = (unsigned)(this.op) & 15;
  96.558 +            if (state->extra != 0) {
  96.559 +                NEEDBITS(state->extra);
  96.560 +                state->offset += BITS(state->extra);
  96.561 +                DROPBITS(state->extra);
  96.562 +            }
  96.563 +            if (state->offset > state->wsize - (state->whave < state->wsize ?
  96.564 +                                                left : 0)) {
  96.565 +                strm->msg = (char *)"invalid distance too far back";
  96.566 +                state->mode = BAD;
  96.567 +                break;
  96.568 +            }
  96.569 +            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
  96.570 +
  96.571 +            /* copy match from window to output */
  96.572 +            do {
  96.573 +                ROOM();
  96.574 +                copy = state->wsize - state->offset;
  96.575 +                if (copy < left) {
  96.576 +                    from = put + copy;
  96.577 +                    copy = left - copy;
  96.578 +                }
  96.579 +                else {
  96.580 +                    from = put - state->offset;
  96.581 +                    copy = left;
  96.582 +                }
  96.583 +                if (copy > state->length) copy = state->length;
  96.584 +                state->length -= copy;
  96.585 +                left -= copy;
  96.586 +                do {
  96.587 +                    *put++ = *from++;
  96.588 +                } while (--copy);
  96.589 +            } while (state->length != 0);
  96.590 +            break;
  96.591 +
  96.592 +        case DONE:
  96.593 +            /* inflate stream terminated properly -- write leftover output */
  96.594 +            ret = Z_STREAM_END;
  96.595 +            if (left < state->wsize) {
  96.596 +                if (out(out_desc, state->window, state->wsize - left))
  96.597 +                    ret = Z_BUF_ERROR;
  96.598 +            }
  96.599 +            goto inf_leave;
  96.600 +
  96.601 +        case BAD:
  96.602 +            ret = Z_DATA_ERROR;
  96.603 +            goto inf_leave;
  96.604 +
  96.605 +        default:                /* can't happen, but makes compilers happy */
  96.606 +            ret = Z_STREAM_ERROR;
  96.607 +            goto inf_leave;
  96.608 +        }
  96.609 +
  96.610 +    /* Return unused input */
  96.611 +  inf_leave:
  96.612 +    strm->next_in = next;
  96.613 +    strm->avail_in = have;
  96.614 +    return ret;
  96.615 +}
  96.616 +
  96.617 +int ZEXPORT inflateBackEnd(strm)
  96.618 +z_streamp strm;
  96.619 +{
  96.620 +    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  96.621 +        return Z_STREAM_ERROR;
  96.622 +    ZFREE(strm, strm->state);
  96.623 +    strm->state = Z_NULL;
  96.624 +    Tracev((stderr, "inflate: end\n"));
  96.625 +    return Z_OK;
  96.626 +}
    97.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    97.2 +++ b/libs/zlib/inffast.c	Thu Sep 08 06:28:38 2011 +0300
    97.3 @@ -0,0 +1,318 @@
    97.4 +/* inffast.c -- fast decoding
    97.5 + * Copyright (C) 1995-2004 Mark Adler
    97.6 + * For conditions of distribution and use, see copyright notice in zlib.h
    97.7 + */
    97.8 +
    97.9 +#include "zutil.h"
   97.10 +#include "inftrees.h"
   97.11 +#include "inflate.h"
   97.12 +#include "inffast.h"
   97.13 +
   97.14 +#ifndef ASMINF
   97.15 +
   97.16 +/* Allow machine dependent optimization for post-increment or pre-increment.
   97.17 +   Based on testing to date,
   97.18 +   Pre-increment preferred for:
   97.19 +   - PowerPC G3 (Adler)
   97.20 +   - MIPS R5000 (Randers-Pehrson)
   97.21 +   Post-increment preferred for:
   97.22 +   - none
   97.23 +   No measurable difference:
   97.24 +   - Pentium III (Anderson)
   97.25 +   - M68060 (Nikl)
   97.26 + */
   97.27 +#ifdef POSTINC
   97.28 +#  define OFF 0
   97.29 +#  define PUP(a) *(a)++
   97.30 +#else
   97.31 +#  define OFF 1
   97.32 +#  define PUP(a) *++(a)
   97.33 +#endif
   97.34 +
   97.35 +/*
   97.36 +   Decode literal, length, and distance codes and write out the resulting
   97.37 +   literal and match bytes until either not enough input or output is
   97.38 +   available, an end-of-block is encountered, or a data error is encountered.
   97.39 +   When large enough input and output buffers are supplied to inflate(), for
   97.40 +   example, a 16K input buffer and a 64K output buffer, more than 95% of the
   97.41 +   inflate execution time is spent in this routine.
   97.42 +
   97.43 +   Entry assumptions:
   97.44 +
   97.45 +        state->mode == LEN
   97.46 +        strm->avail_in >= 6
   97.47 +        strm->avail_out >= 258
   97.48 +        start >= strm->avail_out
   97.49 +        state->bits < 8
   97.50 +
   97.51 +   On return, state->mode is one of:
   97.52 +
   97.53 +        LEN -- ran out of enough output space or enough available input
   97.54 +        TYPE -- reached end of block code, inflate() to interpret next block
   97.55 +        BAD -- error in block data
   97.56 +
   97.57 +   Notes:
   97.58 +
   97.59 +    - The maximum input bits used by a length/distance pair is 15 bits for the
   97.60 +      length code, 5 bits for the length extra, 15 bits for the distance code,
   97.61 +      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
   97.62 +      Therefore if strm->avail_in >= 6, then there is enough input to avoid
   97.63 +      checking for available input while decoding.
   97.64 +
   97.65 +    - The maximum bytes that a single length/distance pair can output is 258
   97.66 +      bytes, which is the maximum length that can be coded.  inflate_fast()
   97.67 +      requires strm->avail_out >= 258 for each loop to avoid checking for
   97.68 +      output space.
   97.69 + */
   97.70 +void inflate_fast(strm, start)
   97.71 +z_streamp strm;
   97.72 +unsigned start;         /* inflate()'s starting value for strm->avail_out */
   97.73 +{
   97.74 +    struct inflate_state FAR *state;
   97.75 +    unsigned char FAR *in;      /* local strm->next_in */
   97.76 +    unsigned char FAR *last;    /* while in < last, enough input available */
   97.77 +    unsigned char FAR *out;     /* local strm->next_out */
   97.78 +    unsigned char FAR *beg;     /* inflate()'s initial strm->next_out */
   97.79 +    unsigned char FAR *end;     /* while out < end, enough space available */
   97.80 +#ifdef INFLATE_STRICT
   97.81 +    unsigned dmax;              /* maximum distance from zlib header */
   97.82 +#endif
   97.83 +    unsigned wsize;             /* window size or zero if not using window */
   97.84 +    unsigned whave;             /* valid bytes in the window */
   97.85 +    unsigned write;             /* window write index */
   97.86 +    unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */
   97.87 +    unsigned long hold;         /* local strm->hold */
   97.88 +    unsigned bits;              /* local strm->bits */
   97.89 +    code const FAR *lcode;      /* local strm->lencode */
   97.90 +    code const FAR *dcode;      /* local strm->distcode */
   97.91 +    unsigned lmask;             /* mask for first level of length codes */
   97.92 +    unsigned dmask;             /* mask for first level of distance codes */
   97.93 +    code this;                  /* retrieved table entry */
   97.94 +    unsigned op;                /* code bits, operation, extra bits, or */
   97.95 +                                /*  window position, window bytes to copy */
   97.96 +    unsigned len;               /* match length, unused bytes */
   97.97 +    unsigned dist;              /* match distance */
   97.98 +    unsigned char FAR *from;    /* where to copy match from */
   97.99 +
  97.100 +    /* copy state to local variables */
  97.101 +    state = (struct inflate_state FAR *)strm->state;
  97.102 +    in = strm->next_in - OFF;
  97.103 +    last = in + (strm->avail_in - 5);
  97.104 +    out = strm->next_out - OFF;
  97.105 +    beg = out - (start - strm->avail_out);
  97.106 +    end = out + (strm->avail_out - 257);
  97.107 +#ifdef INFLATE_STRICT
  97.108 +    dmax = state->dmax;
  97.109 +#endif
  97.110 +    wsize = state->wsize;
  97.111 +    whave = state->whave;
  97.112 +    write = state->write;
  97.113 +    window = state->window;
  97.114 +    hold = state->hold;
  97.115 +    bits = state->bits;
  97.116 +    lcode = state->lencode;
  97.117 +    dcode = state->distcode;
  97.118 +    lmask = (1U << state->lenbits) - 1;
  97.119 +    dmask = (1U << state->distbits) - 1;
  97.120 +
  97.121 +    /* decode literals and length/distances until end-of-block or not enough
  97.122 +       input data or output space */
  97.123 +    do {
  97.124 +        if (bits < 15) {
  97.125 +            hold += (unsigned long)(PUP(in)) << bits;
  97.126 +            bits += 8;
  97.127 +            hold += (unsigned long)(PUP(in)) << bits;
  97.128 +            bits += 8;
  97.129 +        }
  97.130 +        this = lcode[hold & lmask];
  97.131 +      dolen:
  97.132 +        op = (unsigned)(this.bits);
  97.133 +        hold >>= op;
  97.134 +        bits -= op;
  97.135 +        op = (unsigned)(this.op);
  97.136 +        if (op == 0) {                          /* literal */
  97.137 +            Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
  97.138 +                    "inflate:         literal '%c'\n" :
  97.139 +                    "inflate:         literal 0x%02x\n", this.val));
  97.140 +            PUP(out) = (unsigned char)(this.val);
  97.141 +        }
  97.142 +        else if (op & 16) {                     /* length base */
  97.143 +            len = (unsigned)(this.val);
  97.144 +            op &= 15;                           /* number of extra bits */
  97.145 +            if (op) {
  97.146 +                if (bits < op) {
  97.147 +                    hold += (unsigned long)(PUP(in)) << bits;
  97.148 +                    bits += 8;
  97.149 +                }
  97.150 +                len += (unsigned)hold & ((1U << op) - 1);
  97.151 +                hold >>= op;
  97.152 +                bits -= op;
  97.153 +            }
  97.154 +            Tracevv((stderr, "inflate:         length %u\n", len));
  97.155 +            if (bits < 15) {
  97.156 +                hold += (unsigned long)(PUP(in)) << bits;
  97.157 +                bits += 8;
  97.158 +                hold += (unsigned long)(PUP(in)) << bits;
  97.159 +                bits += 8;
  97.160 +            }
  97.161 +            this = dcode[hold & dmask];
  97.162 +          dodist:
  97.163 +            op = (unsigned)(this.bits);
  97.164 +            hold >>= op;
  97.165 +            bits -= op;
  97.166 +            op = (unsigned)(this.op);
  97.167 +            if (op & 16) {                      /* distance base */
  97.168 +                dist = (unsigned)(this.val);
  97.169 +                op &= 15;                       /* number of extra bits */
  97.170 +                if (bits < op) {
  97.171 +                    hold += (unsigned long)(PUP(in)) << bits;
  97.172 +                    bits += 8;
  97.173 +                    if (bits < op) {
  97.174 +                        hold += (unsigned long)(PUP(in)) << bits;
  97.175 +                        bits += 8;
  97.176 +                    }
  97.177 +                }
  97.178 +                dist += (unsigned)hold & ((1U << op) - 1);
  97.179 +#ifdef INFLATE_STRICT
  97.180 +                if (dist > dmax) {
  97.181 +                    strm->msg = (char *)"invalid distance too far back";
  97.182 +                    state->mode = BAD;
  97.183 +                    break;
  97.184 +                }
  97.185 +#endif
  97.186 +                hold >>= op;
  97.187 +                bits -= op;
  97.188 +                Tracevv((stderr, "inflate:         distance %u\n", dist));
  97.189 +                op = (unsigned)(out - beg);     /* max distance in output */
  97.190 +                if (dist > op) {                /* see if copy from window */
  97.191 +                    op = dist - op;             /* distance back in window */
  97.192 +                    if (op > whave) {
  97.193 +                        strm->msg = (char *)"invalid distance too far back";
  97.194 +                        state->mode = BAD;
  97.195 +                        break;
  97.196 +                    }
  97.197 +                    from = window - OFF;
  97.198 +                    if (write == 0) {           /* very common case */
  97.199 +                        from += wsize - op;
  97.200 +                        if (op < len) {         /* some from window */
  97.201 +                            len -= op;
  97.202 +                            do {
  97.203 +                                PUP(out) = PUP(from);
  97.204 +                            } while (--op);
  97.205 +                            from = out - dist;  /* rest from output */
  97.206 +                        }
  97.207 +                    }
  97.208 +                    else if (write < op) {      /* wrap around window */
  97.209 +                        from += wsize + write - op;
  97.210 +                        op -= write;
  97.211 +                        if (op < len) {         /* some from end of window */
  97.212 +                            len -= op;
  97.213 +                            do {
  97.214 +                                PUP(out) = PUP(from);
  97.215 +                            } while (--op);
  97.216 +                            from = window - OFF;
  97.217 +                            if (write < len) {  /* some from start of window */
  97.218 +                                op = write;
  97.219 +                                len -= op;
  97.220 +                                do {
  97.221 +                                    PUP(out) = PUP(from);
  97.222 +                                } while (--op);
  97.223 +                                from = out - dist;      /* rest from output */
  97.224 +                            }
  97.225 +                        }
  97.226 +                    }
  97.227 +                    else {                      /* contiguous in window */
  97.228 +                        from += write - op;
  97.229 +                        if (op < len) {         /* some from window */
  97.230 +                            len -= op;
  97.231 +                            do {
  97.232 +                                PUP(out) = PUP(from);
  97.233 +                            } while (--op);
  97.234 +                            from = out - dist;  /* rest from output */
  97.235 +                        }
  97.236 +                    }
  97.237 +                    while (len > 2) {
  97.238 +                        PUP(out) = PUP(from);
  97.239 +                        PUP(out) = PUP(from);
  97.240 +                        PUP(out) = PUP(from);
  97.241 +                        len -= 3;
  97.242 +                    }
  97.243 +                    if (len) {
  97.244 +                        PUP(out) = PUP(from);
  97.245 +                        if (len > 1)
  97.246 +                            PUP(out) = PUP(from);
  97.247 +                    }
  97.248 +                }
  97.249 +                else {
  97.250 +                    from = out - dist;          /* copy direct from output */
  97.251 +                    do {                        /* minimum length is three */
  97.252 +                        PUP(out) = PUP(from);
  97.253 +                        PUP(out) = PUP(from);
  97.254 +                        PUP(out) = PUP(from);
  97.255 +                        len -= 3;
  97.256 +                    } while (len > 2);
  97.257 +                    if (len) {
  97.258 +                        PUP(out) = PUP(from);
  97.259 +                        if (len > 1)
  97.260 +                            PUP(out) = PUP(from);
  97.261 +                    }
  97.262 +                }
  97.263 +            }
  97.264 +            else if ((op & 64) == 0) {          /* 2nd level distance code */
  97.265 +                this = dcode[this.val + (hold & ((1U << op) - 1))];
  97.266 +                goto dodist;
  97.267 +            }
  97.268 +            else {
  97.269 +                strm->msg = (char *)"invalid distance code";
  97.270 +                state->mode = BAD;
  97.271 +                break;
  97.272 +            }
  97.273 +        }
  97.274 +        else if ((op & 64) == 0) {              /* 2nd level length code */
  97.275 +            this = lcode[this.val + (hold & ((1U << op) - 1))];
  97.276 +            goto dolen;
  97.277 +        }
  97.278 +        else if (op & 32) {                     /* end-of-block */
  97.279 +            Tracevv((stderr, "inflate:         end of block\n"));
  97.280 +            state->mode = TYPE;
  97.281 +            break;
  97.282 +        }
  97.283 +        else {
  97.284 +            strm->msg = (char *)"invalid literal/length code";
  97.285 +            state->mode = BAD;
  97.286 +            break;
  97.287 +        }
  97.288 +    } while (in < last && out < end);
  97.289 +
  97.290 +    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  97.291 +    len = bits >> 3;
  97.292 +    in -= len;
  97.293 +    bits -= len << 3;
  97.294 +    hold &= (1U << bits) - 1;
  97.295 +
  97.296 +    /* update state and return */
  97.297 +    strm->next_in = in + OFF;
  97.298 +    strm->next_out = out + OFF;
  97.299 +    strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  97.300 +    strm->avail_out = (unsigned)(out < end ?
  97.301 +                                 257 + (end - out) : 257 - (out - end));
  97.302 +    state->hold = hold;
  97.303 +    state->bits = bits;
  97.304 +    return;
  97.305 +}
  97.306 +
  97.307 +/*
  97.308 +   inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  97.309 +   - Using bit fields for code structure
  97.310 +   - Different op definition to avoid & for extra bits (do & for table bits)
  97.311 +   - Three separate decoding do-loops for direct, window, and write == 0
  97.312 +   - Special case for distance > 1 copies to do overlapped load and store copy
  97.313 +   - Explicit branch predictions (based on measured branch probabilities)
  97.314 +   - Deferring match copy and interspersed it with decoding subsequent codes
  97.315 +   - Swapping literal/length else
  97.316 +   - Swapping window/direct else
  97.317 +   - Larger unrolled copy loops (three is about right)
  97.318 +   - Moving len -= 3 statement into middle of loop
  97.319 + */
  97.320 +
  97.321 +#endif /* !ASMINF */
    98.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    98.2 +++ b/libs/zlib/inffast.h	Thu Sep 08 06:28:38 2011 +0300
    98.3 @@ -0,0 +1,11 @@
    98.4 +/* inffast.h -- header to use inffast.c
    98.5 + * Copyright (C) 1995-2003 Mark Adler
    98.6 + * For conditions of distribution and use, see copyright notice in zlib.h
    98.7 + */
    98.8 +
    98.9 +/* WARNING: this file should *not* be used by applications. It is
   98.10 +   part of the implementation of the compression library and is
   98.11 +   subject to change. Applications should only use zlib.h.
   98.12 + */
   98.13 +
   98.14 +void inflate_fast OF((z_streamp strm, unsigned start));
    99.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    99.2 +++ b/libs/zlib/inffixed.h	Thu Sep 08 06:28:38 2011 +0300
    99.3 @@ -0,0 +1,94 @@
    99.4 +    /* inffixed.h -- table for decoding fixed codes
    99.5 +     * Generated automatically by makefixed().
    99.6 +     */
    99.7 +
    99.8 +    /* WARNING: this file should *not* be used by applications. It
    99.9 +       is part of the implementation of the compression library and
   99.10 +       is subject to change. Applications should only use zlib.h.
   99.11 +     */
   99.12 +
   99.13 +    static const code lenfix[512] = {
   99.14 +        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
   99.15 +        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
   99.16 +        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
   99.17 +        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
   99.18 +        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
   99.19 +        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
   99.20 +        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
   99.21 +        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
   99.22 +        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
   99.23 +        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
   99.24 +        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
   99.25 +        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
   99.26 +        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
   99.27 +        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
   99.28 +        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
   99.29 +        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
   99.30 +        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
   99.31 +        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
   99.32 +        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
   99.33 +        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
   99.34 +        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
   99.35 +        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
   99.36 +        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
   99.37 +        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
   99.38 +        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
   99.39 +        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
   99.40 +        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
   99.41 +        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
   99.42 +        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
   99.43 +        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
   99.44 +        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
   99.45 +        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
   99.46 +        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
   99.47 +        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
   99.48 +        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
   99.49 +        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
   99.50 +        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
   99.51 +        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
   99.52 +        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
   99.53 +        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
   99.54 +        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
   99.55 +        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
   99.56 +        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
   99.57 +        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
   99.58 +        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
   99.59 +        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
   99.60 +        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
   99.61 +        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
   99.62 +        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
   99.63 +        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
   99.64 +        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
   99.65 +        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
   99.66 +        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
   99.67 +        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
   99.68 +        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
   99.69 +        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
   99.70 +        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
   99.71 +        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
   99.72 +        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
   99.73 +        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
   99.74 +        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
   99.75 +        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
   99.76 +        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
   99.77 +        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
   99.78 +        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
   99.79 +        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
   99.80 +        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
   99.81 +        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
   99.82 +        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
   99.83 +        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
   99.84 +        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
   99.85 +        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
   99.86 +        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
   99.87 +        {0,9,255}
   99.88 +    };
   99.89 +
   99.90 +    static const code distfix[32] = {
   99.91 +        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
   99.92 +        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
   99.93 +        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
   99.94 +        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
   99.95 +        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
   99.96 +        {22,5,193},{64,5,0}
   99.97 +    };
   100.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   100.2 +++ b/libs/zlib/inflate.c	Thu Sep 08 06:28:38 2011 +0300
   100.3 @@ -0,0 +1,1368 @@
   100.4 +/* inflate.c -- zlib decompression
   100.5 + * Copyright (C) 1995-2005 Mark Adler
   100.6 + * For conditions of distribution and use, see copyright notice in zlib.h
   100.7 + */
   100.8 +
   100.9 +/*
  100.10 + * Change history:
  100.11 + *
  100.12 + * 1.2.beta0    24 Nov 2002
  100.13 + * - First version -- complete rewrite of inflate to simplify code, avoid
  100.14 + *   creation of window when not needed, minimize use of window when it is
  100.15 + *   needed, make inffast.c even faster, implement gzip decoding, and to
  100.16 + *   improve code readability and style over the previous zlib inflate code
  100.17 + *
  100.18 + * 1.2.beta1    25 Nov 2002
  100.19 + * - Use pointers for available input and output checking in inffast.c
  100.20 + * - Remove input and output counters in inffast.c
  100.21 + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  100.22 + * - Remove unnecessary second byte pull from length extra in inffast.c
  100.23 + * - Unroll direct copy to three copies per loop in inffast.c
  100.24 + *
  100.25 + * 1.2.beta2    4 Dec 2002
  100.26 + * - Change external routine names to reduce potential conflicts
  100.27 + * - Correct filename to inffixed.h for fixed tables in inflate.c
  100.28 + * - Make hbuf[] unsigned char to match parameter type in inflate.c
  100.29 + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  100.30 + *   to avoid negation problem on Alphas (64 bit) in inflate.c
  100.31 + *
  100.32 + * 1.2.beta3    22 Dec 2002
  100.33 + * - Add comments on state->bits assertion in inffast.c
  100.34 + * - Add comments on op field in inftrees.h
  100.35 + * - Fix bug in reuse of allocated window after inflateReset()
  100.36 + * - Remove bit fields--back to byte structure for speed
  100.37 + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  100.38 + * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  100.39 + * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  100.40 + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  100.41 + * - Use local copies of stream next and avail values, as well as local bit
  100.42 + *   buffer and bit count in inflate()--for speed when inflate_fast() not used
  100.43 + *
  100.44 + * 1.2.beta4    1 Jan 2003
  100.45 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  100.46 + * - Move a comment on output buffer sizes from inffast.c to inflate.c
  100.47 + * - Add comments in inffast.c to introduce the inflate_fast() routine
  100.48 + * - Rearrange window copies in inflate_fast() for speed and simplification
  100.49 + * - Unroll last copy for window match in inflate_fast()
  100.50 + * - Use local copies of window variables in inflate_fast() for speed
  100.51 + * - Pull out common write == 0 case for speed in inflate_fast()
  100.52 + * - Make op and len in inflate_fast() unsigned for consistency
  100.53 + * - Add FAR to lcode and dcode declarations in inflate_fast()
  100.54 + * - Simplified bad distance check in inflate_fast()
  100.55 + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  100.56 + *   source file infback.c to provide a call-back interface to inflate for
  100.57 + *   programs like gzip and unzip -- uses window as output buffer to avoid
  100.58 + *   window copying
  100.59 + *
  100.60 + * 1.2.beta5    1 Jan 2003
  100.61 + * - Improved inflateBack() interface to allow the caller to provide initial
  100.62 + *   input in strm.
  100.63 + * - Fixed stored blocks bug in inflateBack()
  100.64 + *
  100.65 + * 1.2.beta6    4 Jan 2003
  100.66 + * - Added comments in inffast.c on effectiveness of POSTINC
  100.67 + * - Typecasting all around to reduce compiler warnings
  100.68 + * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  100.69 + *   make compilers happy
  100.70 + * - Changed type of window in inflateBackInit() to unsigned char *
  100.71 + *
  100.72 + * 1.2.beta7    27 Jan 2003
  100.73 + * - Changed many types to unsigned or unsigned short to avoid warnings
  100.74 + * - Added inflateCopy() function
  100.75 + *
  100.76 + * 1.2.0        9 Mar 2003
  100.77 + * - Changed inflateBack() interface to provide separate opaque descriptors
  100.78 + *   for the in() and out() functions
  100.79 + * - Changed inflateBack() argument and in_func typedef to swap the length
  100.80 + *   and buffer address return values for the input function
  100.81 + * - Check next_in and next_out for Z_NULL on entry to inflate()
  100.82 + *
  100.83 + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  100.84 + */
  100.85 +
  100.86 +#include "zutil.h"
  100.87 +#include "inftrees.h"
  100.88 +#include "inflate.h"
  100.89 +#include "inffast.h"
  100.90 +
  100.91 +#ifdef MAKEFIXED
  100.92 +#  ifndef BUILDFIXED
  100.93 +#    define BUILDFIXED
  100.94 +#  endif
  100.95 +#endif
  100.96 +
  100.97 +/* function prototypes */
  100.98 +local void fixedtables OF((struct inflate_state FAR *state));
  100.99 +local int updatewindow OF((z_streamp strm, unsigned out));
 100.100 +#ifdef BUILDFIXED
 100.101 +   void makefixed OF((void));
 100.102 +#endif
 100.103 +local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
 100.104 +                              unsigned len));
 100.105 +
 100.106 +int ZEXPORT inflateReset(strm)
 100.107 +z_streamp strm;
 100.108 +{
 100.109 +    struct inflate_state FAR *state;
 100.110 +
 100.111 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
 100.112 +    state = (struct inflate_state FAR *)strm->state;
 100.113 +    strm->total_in = strm->total_out = state->total = 0;
 100.114 +    strm->msg = Z_NULL;
 100.115 +    strm->adler = 1;        /* to support ill-conceived Java test suite */
 100.116 +    state->mode = HEAD;
 100.117 +    state->last = 0;
 100.118 +    state->havedict = 0;
 100.119 +    state->dmax = 32768U;
 100.120 +    state->head = Z_NULL;
 100.121 +    state->wsize = 0;
 100.122 +    state->whave = 0;
 100.123 +    state->write = 0;
 100.124 +    state->hold = 0;
 100.125 +    state->bits = 0;
 100.126 +    state->lencode = state->distcode = state->next = state->codes;
 100.127 +    Tracev((stderr, "inflate: reset\n"));
 100.128 +    return Z_OK;
 100.129 +}
 100.130 +
 100.131 +int ZEXPORT inflatePrime(strm, bits, value)
 100.132 +z_streamp strm;
 100.133 +int bits;
 100.134 +int value;
 100.135 +{
 100.136 +    struct inflate_state FAR *state;
 100.137 +
 100.138 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
 100.139 +    state = (struct inflate_state FAR *)strm->state;
 100.140 +    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
 100.141 +    value &= (1L << bits) - 1;
 100.142 +    state->hold += value << state->bits;
 100.143 +    state->bits += bits;
 100.144 +    return Z_OK;
 100.145 +}
 100.146 +
 100.147 +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
 100.148 +z_streamp strm;
 100.149 +int windowBits;
 100.150 +const char *version;
 100.151 +int stream_size;
 100.152 +{
 100.153 +    struct inflate_state FAR *state;
 100.154 +
 100.155 +    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
 100.156 +        stream_size != (int)(sizeof(z_stream)))
 100.157 +        return Z_VERSION_ERROR;
 100.158 +    if (strm == Z_NULL) return Z_STREAM_ERROR;
 100.159 +    strm->msg = Z_NULL;                 /* in case we return an error */
 100.160 +    if (strm->zalloc == (alloc_func)0) {
 100.161 +        strm->zalloc = zcalloc;
 100.162 +        strm->opaque = (voidpf)0;
 100.163 +    }
 100.164 +    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
 100.165 +    state = (struct inflate_state FAR *)
 100.166 +            ZALLOC(strm, 1, sizeof(struct inflate_state));
 100.167 +    if (state == Z_NULL) return Z_MEM_ERROR;
 100.168 +    Tracev((stderr, "inflate: allocated\n"));
 100.169 +    strm->state = (struct internal_state FAR *)state;
 100.170 +    if (windowBits < 0) {
 100.171 +        state->wrap = 0;
 100.172 +        windowBits = -windowBits;
 100.173 +    }
 100.174 +    else {
 100.175 +        state->wrap = (windowBits >> 4) + 1;
 100.176 +#ifdef GUNZIP
 100.177 +        if (windowBits < 48) windowBits &= 15;
 100.178 +#endif
 100.179 +    }
 100.180 +    if (windowBits < 8 || windowBits > 15) {
 100.181 +        ZFREE(strm, state);
 100.182 +        strm->state = Z_NULL;
 100.183 +        return Z_STREAM_ERROR;
 100.184 +    }
 100.185 +    state->wbits = (unsigned)windowBits;
 100.186 +    state->window = Z_NULL;
 100.187 +    return inflateReset(strm);
 100.188 +}
 100.189 +
 100.190 +int ZEXPORT inflateInit_(strm, version, stream_size)
 100.191 +z_streamp strm;
 100.192 +const char *version;
 100.193 +int stream_size;
 100.194 +{
 100.195 +    return inflateInit2_(strm, DEF_WBITS, version, stream_size);
 100.196 +}
 100.197 +
 100.198 +/*
 100.199 +   Return state with length and distance decoding tables and index sizes set to
 100.200 +   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
 100.201 +   If BUILDFIXED is defined, then instead this routine builds the tables the
 100.202 +   first time it's called, and returns those tables the first time and
 100.203 +   thereafter.  This reduces the size of the code by about 2K bytes, in
 100.204 +   exchange for a little execution time.  However, BUILDFIXED should not be
 100.205 +   used for threaded applications, since the rewriting of the tables and virgin
 100.206 +   may not be thread-safe.
 100.207 + */
 100.208 +local void fixedtables(state)
 100.209 +struct inflate_state FAR *state;
 100.210 +{
 100.211 +#ifdef BUILDFIXED
 100.212 +    static int virgin = 1;
 100.213 +    static code *lenfix, *distfix;
 100.214 +    static code fixed[544];
 100.215 +
 100.216 +    /* build fixed huffman tables if first call (may not be thread safe) */
 100.217 +    if (virgin) {
 100.218 +        unsigned sym, bits;
 100.219 +        static code *next;
 100.220 +
 100.221 +        /* literal/length table */
 100.222 +        sym = 0;
 100.223 +        while (sym < 144) state->lens[sym++] = 8;
 100.224 +        while (sym < 256) state->lens[sym++] = 9;
 100.225 +        while (sym < 280) state->lens[sym++] = 7;
 100.226 +        while (sym < 288) state->lens[sym++] = 8;
 100.227 +        next = fixed;
 100.228 +        lenfix = next;
 100.229 +        bits = 9;
 100.230 +        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
 100.231 +
 100.232 +        /* distance table */
 100.233 +        sym = 0;
 100.234 +        while (sym < 32) state->lens[sym++] = 5;
 100.235 +        distfix = next;
 100.236 +        bits = 5;
 100.237 +        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
 100.238 +
 100.239 +        /* do this just once */
 100.240 +        virgin = 0;
 100.241 +    }
 100.242 +#else /* !BUILDFIXED */
 100.243 +#   include "inffixed.h"
 100.244 +#endif /* BUILDFIXED */
 100.245 +    state->lencode = lenfix;
 100.246 +    state->lenbits = 9;
 100.247 +    state->distcode = distfix;
 100.248 +    state->distbits = 5;
 100.249 +}
 100.250 +
 100.251 +#ifdef MAKEFIXED
 100.252 +#include <stdio.h>
 100.253 +
 100.254 +/*
 100.255 +   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
 100.256 +   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
 100.257 +   those tables to stdout, which would be piped to inffixed.h.  A small program
 100.258 +   can simply call makefixed to do this:
 100.259 +
 100.260 +    void makefixed(void);
 100.261 +
 100.262 +    int main(void)
 100.263 +    {
 100.264 +        makefixed();
 100.265 +        return 0;
 100.266 +    }
 100.267 +
 100.268 +   Then that can be linked with zlib built with MAKEFIXED defined and run:
 100.269 +
 100.270 +    a.out > inffixed.h
 100.271 + */
 100.272 +void makefixed()
 100.273 +{
 100.274 +    unsigned low, size;
 100.275 +    struct inflate_state state;
 100.276 +
 100.277 +    fixedtables(&state);
 100.278 +    puts("    /* inffixed.h -- table for decoding fixed codes");
 100.279 +    puts("     * Generated automatically by makefixed().");
 100.280 +    puts("     */");
 100.281 +    puts("");
 100.282 +    puts("    /* WARNING: this file should *not* be used by applications.");
 100.283 +    puts("       It is part of the implementation of this library and is");
 100.284 +    puts("       subject to change. Applications should only use zlib.h.");
 100.285 +    puts("     */");
 100.286 +    puts("");
 100.287 +    size = 1U << 9;
 100.288 +    printf("    static const code lenfix[%u] = {", size);
 100.289 +    low = 0;
 100.290 +    for (;;) {
 100.291 +        if ((low % 7) == 0) printf("\n        ");
 100.292 +        printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
 100.293 +               state.lencode[low].val);
 100.294 +        if (++low == size) break;
 100.295 +        putchar(',');
 100.296 +    }
 100.297 +    puts("\n    };");
 100.298 +    size = 1U << 5;
 100.299 +    printf("\n    static const code distfix[%u] = {", size);
 100.300 +    low = 0;
 100.301 +    for (;;) {
 100.302 +        if ((low % 6) == 0) printf("\n        ");
 100.303 +        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
 100.304 +               state.distcode[low].val);
 100.305 +        if (++low == size) break;
 100.306 +        putchar(',');
 100.307 +    }
 100.308 +    puts("\n    };");
 100.309 +}
 100.310 +#endif /* MAKEFIXED */
 100.311 +
 100.312 +/*
 100.313 +   Update the window with the last wsize (normally 32K) bytes written before
 100.314 +   returning.  If window does not exist yet, create it.  This is only called
 100.315 +   when a window is already in use, or when output has been written during this
 100.316 +   inflate call, but the end of the deflate stream has not been reached yet.
 100.317 +   It is also called to create a window for dictionary data when a dictionary
 100.318 +   is loaded.
 100.319 +
 100.320 +   Providing output buffers larger than 32K to inflate() should provide a speed
 100.321 +   advantage, since only the last 32K of output is copied to the sliding window
 100.322 +   upon return from inflate(), and since all distances after the first 32K of
 100.323 +   output will fall in the output data, making match copies simpler and faster.
 100.324 +   The advantage may be dependent on the size of the processor's data caches.
 100.325 + */
 100.326 +local int updatewindow(strm, out)
 100.327 +z_streamp strm;
 100.328 +unsigned out;
 100.329 +{
 100.330 +    struct inflate_state FAR *state;
 100.331 +    unsigned copy, dist;
 100.332 +
 100.333 +    state = (struct inflate_state FAR *)strm->state;
 100.334 +
 100.335 +    /* if it hasn't been done already, allocate space for the window */
 100.336 +    if (state->window == Z_NULL) {
 100.337 +        state->window = (unsigned char FAR *)
 100.338 +                        ZALLOC(strm, 1U << state->wbits,
 100.339 +                               sizeof(unsigned char));
 100.340 +        if (state->window == Z_NULL) return 1;
 100.341 +    }
 100.342 +
 100.343 +    /* if window not in use yet, initialize */
 100.344 +    if (state->wsize == 0) {
 100.345 +        state->wsize = 1U << state->wbits;
 100.346 +        state->write = 0;
 100.347 +        state->whave = 0;
 100.348 +    }
 100.349 +
 100.350 +    /* copy state->wsize or less output bytes into the circular window */
 100.351 +    copy = out - strm->avail_out;
 100.352 +    if (copy >= state->wsize) {
 100.353 +        zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
 100.354 +        state->write = 0;
 100.355 +        state->whave = state->wsize;
 100.356 +    }
 100.357 +    else {
 100.358 +        dist = state->wsize - state->write;
 100.359 +        if (dist > copy) dist = copy;
 100.360 +        zmemcpy(state->window + state->write, strm->next_out - copy, dist);
 100.361 +        copy -= dist;
 100.362 +        if (copy) {
 100.363 +            zmemcpy(state->window, strm->next_out - copy, copy);
 100.364 +            state->write = copy;
 100.365 +            state->whave = state->wsize;
 100.366 +        }
 100.367 +        else {
 100.368 +            state->write += dist;
 100.369 +            if (state->write == state->wsize) state->write = 0;
 100.370 +            if (state->whave < state->wsize) state->whave += dist;
 100.371 +        }
 100.372 +    }
 100.373 +    return 0;
 100.374 +}
 100.375 +
 100.376 +/* Macros for inflate(): */
 100.377 +
 100.378 +/* check function to use adler32() for zlib or crc32() for gzip */
 100.379 +#ifdef GUNZIP
 100.380 +#  define UPDATE(check, buf, len) \
 100.381 +    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
 100.382 +#else
 100.383 +#  define UPDATE(check, buf, len) adler32(check, buf, len)
 100.384 +#endif
 100.385 +
 100.386 +/* check macros for header crc */
 100.387 +#ifdef GUNZIP
 100.388 +#  define CRC2(check, word) \
 100.389 +    do { \
 100.390 +        hbuf[0] = (unsigned char)(word); \
 100.391 +        hbuf[1] = (unsigned char)((word) >> 8); \
 100.392 +        check = crc32(check, hbuf, 2); \
 100.393 +    } while (0)
 100.394 +
 100.395 +#  define CRC4(check, word) \
 100.396 +    do { \
 100.397 +        hbuf[0] = (unsigned char)(word); \
 100.398 +        hbuf[1] = (unsigned char)((word) >> 8); \
 100.399 +        hbuf[2] = (unsigned char)((word) >> 16); \
 100.400 +        hbuf[3] = (unsigned char)((word) >> 24); \
 100.401 +        check = crc32(check, hbuf, 4); \
 100.402 +    } while (0)
 100.403 +#endif
 100.404 +
 100.405 +/* Load registers with state in inflate() for speed */
 100.406 +#define LOAD() \
 100.407 +    do { \
 100.408 +        put = strm->next_out; \
 100.409 +        left = strm->avail_out; \
 100.410 +        next = strm->next_in; \
 100.411 +        have = strm->avail_in; \
 100.412 +        hold = state->hold; \
 100.413 +        bits = state->bits; \
 100.414 +    } while (0)
 100.415 +
 100.416 +/* Restore state from registers in inflate() */
 100.417 +#define RESTORE() \
 100.418 +    do { \
 100.419 +        strm->next_out = put; \
 100.420 +        strm->avail_out = left; \
 100.421 +        strm->next_in = next; \
 100.422 +        strm->avail_in = have; \
 100.423 +        state->hold = hold; \
 100.424 +        state->bits = bits; \
 100.425 +    } while (0)
 100.426 +
 100.427 +/* Clear the input bit accumulator */
 100.428 +#define INITBITS() \
 100.429 +    do { \
 100.430 +        hold = 0; \
 100.431 +        bits = 0; \
 100.432 +    } while (0)
 100.433 +
 100.434 +/* Get a byte of input into the bit accumulator, or return from inflate()
 100.435 +   if there is no input available. */
 100.436 +#define PULLBYTE() \
 100.437 +    do { \
 100.438 +        if (have == 0) goto inf_leave; \
 100.439 +        have--; \
 100.440 +        hold += (unsigned long)(*next++) << bits; \
 100.441 +        bits += 8; \
 100.442 +    } while (0)
 100.443 +
 100.444 +/* Assure that there are at least n bits in the bit accumulator.  If there is
 100.445 +   not enough available input to do that, then return from inflate(). */
 100.446 +#define NEEDBITS(n) \
 100.447 +    do { \
 100.448 +        while (bits < (unsigned)(n)) \
 100.449 +            PULLBYTE(); \
 100.450 +    } while (0)
 100.451 +
 100.452 +/* Return the low n bits of the bit accumulator (n < 16) */
 100.453 +#define BITS(n) \
 100.454 +    ((unsigned)hold & ((1U << (n)) - 1))
 100.455 +
 100.456 +/* Remove n bits from the bit accumulator */
 100.457 +#define DROPBITS(n) \
 100.458 +    do { \
 100.459 +        hold >>= (n); \
 100.460 +        bits -= (unsigned)(n); \
 100.461 +    } while (0)
 100.462 +
 100.463 +/* Remove zero to seven bits as needed to go to a byte boundary */
 100.464 +#define BYTEBITS() \
 100.465 +    do { \
 100.466 +        hold >>= bits & 7; \
 100.467 +        bits -= bits & 7; \
 100.468 +    } while (0)
 100.469 +
 100.470 +/* Reverse the bytes in a 32-bit value */
 100.471 +#define REVERSE(q) \
 100.472 +    ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
 100.473 +     (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
 100.474 +
 100.475 +/*
 100.476 +   inflate() uses a state machine to process as much input data and generate as
 100.477 +   much output data as possible before returning.  The state machine is
 100.478 +   structured roughly as follows:
 100.479 +
 100.480 +    for (;;) switch (state) {
 100.481 +    ...
 100.482 +    case STATEn:
 100.483 +        if (not enough input data or output space to make progress)
 100.484 +            return;
 100.485 +        ... make progress ...
 100.486 +        state = STATEm;
 100.487 +        break;
 100.488 +    ...
 100.489 +    }
 100.490 +
 100.491 +   so when inflate() is called again, the same case is attempted again, and
 100.492 +   if the appropriate resources are provided, the machine proceeds to the
 100.493 +   next state.  The NEEDBITS() macro is usually the way the state evaluates
 100.494 +   whether it can proceed or should return.  NEEDBITS() does the return if
 100.495 +   the requested bits are not available.  The typical use of the BITS macros
 100.496 +   is:
 100.497 +
 100.498 +        NEEDBITS(n);
 100.499 +        ... do something with BITS(n) ...
 100.500 +        DROPBITS(n);
 100.501 +
 100.502 +   where NEEDBITS(n) either returns from inflate() if there isn't enough
 100.503 +   input left to load n bits into the accumulator, or it continues.  BITS(n)
 100.504 +   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
 100.505 +   the low n bits off the accumulator.  INITBITS() clears the accumulator
 100.506 +   and sets the number of available bits to zero.  BYTEBITS() discards just
 100.507 +   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
 100.508 +   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
 100.509 +
 100.510 +   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
 100.511 +   if there is no input available.  The decoding of variable length codes uses
 100.512 +   PULLBYTE() directly in order to pull just enough bytes to decode the next
 100.513 +   code, and no more.
 100.514 +
 100.515 +   Some states loop until they get enough input, making sure that enough
 100.516 +   state information is maintained to continue the loop where it left off
 100.517 +   if NEEDBITS() returns in the loop.  For example, want, need, and keep
 100.518 +   would all have to actually be part of the saved state in case NEEDBITS()
 100.519 +   returns:
 100.520 +
 100.521 +    case STATEw:
 100.522 +        while (want < need) {
 100.523 +            NEEDBITS(n);
 100.524 +            keep[want++] = BITS(n);
 100.525 +            DROPBITS(n);
 100.526 +        }
 100.527 +        state = STATEx;
 100.528 +    case STATEx:
 100.529 +
 100.530 +   As shown above, if the next state is also the next case, then the break
 100.531 +   is omitted.
 100.532 +
 100.533 +   A state may also return if there is not enough output space available to
 100.534 +   complete that state.  Those states are copying stored data, writing a
 100.535 +   literal byte, and copying a matching string.
 100.536 +
 100.537 +   When returning, a "goto inf_leave" is used to update the total counters,
 100.538 +   update the check value, and determine whether any progress has been made
 100.539 +   during that inflate() call in order to return the proper return code.
 100.540 +   Progress is defined as a change in either strm->avail_in or strm->avail_out.
 100.541 +   When there is a window, goto inf_leave will update the window with the last
 100.542 +   output written.  If a goto inf_leave occurs in the middle of decompression
 100.543 +   and there is no window currently, goto inf_leave will create one and copy
 100.544 +   output to the window for the next call of inflate().
 100.545 +
 100.546 +   In this implementation, the flush parameter of inflate() only affects the
 100.547 +   return code (per zlib.h).  inflate() always writes as much as possible to
 100.548 +   strm->next_out, given the space available and the provided input--the effect
 100.549 +   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
 100.550 +   the allocation of and copying into a sliding window until necessary, which
 100.551 +   provides the effect documented in zlib.h for Z_FINISH when the entire input
 100.552 +   stream available.  So the only thing the flush parameter actually does is:
 100.553 +   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
 100.554 +   will return Z_BUF_ERROR if it has not reached the end of the stream.
 100.555 + */
 100.556 +
 100.557 +int ZEXPORT inflate(strm, flush)
 100.558 +z_streamp strm;
 100.559 +int flush;
 100.560 +{
 100.561 +    struct inflate_state FAR *state;
 100.562 +    unsigned char FAR *next;    /* next input */
 100.563 +    unsigned char FAR *put;     /* next output */
 100.564 +    unsigned have, left;        /* available input and output */
 100.565 +    unsigned long hold;         /* bit buffer */
 100.566 +    unsigned bits;              /* bits in bit buffer */
 100.567 +    unsigned in, out;           /* save starting available input and output */
 100.568 +    unsigned copy;              /* number of stored or match bytes to copy */
 100.569 +    unsigned char FAR *from;    /* where to copy match bytes from */
 100.570 +    code this;                  /* current decoding table entry */
 100.571 +    code last;                  /* parent table entry */
 100.572 +    unsigned len;               /* length to copy for repeats, bits to drop */
 100.573 +    int ret;                    /* return code */
 100.574 +#ifdef GUNZIP
 100.575 +    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
 100.576 +#endif
 100.577 +    static const unsigned short order[19] = /* permutation of code lengths */
 100.578 +        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
 100.579 +
 100.580 +    if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
 100.581 +        (strm->next_in == Z_NULL && strm->avail_in != 0))
 100.582 +        return Z_STREAM_ERROR;
 100.583 +
 100.584 +    state = (struct inflate_state FAR *)strm->state;
 100.585 +    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
 100.586 +    LOAD();
 100.587 +    in = have;
 100.588 +    out = left;
 100.589 +    ret = Z_OK;
 100.590 +    for (;;)
 100.591 +        switch (state->mode) {
 100.592 +        case HEAD:
 100.593 +            if (state->wrap == 0) {
 100.594 +                state->mode = TYPEDO;
 100.595 +                break;
 100.596 +            }
 100.597 +            NEEDBITS(16);
 100.598 +#ifdef GUNZIP
 100.599 +            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
 100.600 +                state->check = crc32(0L, Z_NULL, 0);
 100.601 +                CRC2(state->check, hold);
 100.602 +                INITBITS();
 100.603 +                state->mode = FLAGS;
 100.604 +                break;
 100.605 +            }
 100.606 +            state->flags = 0;           /* expect zlib header */
 100.607 +            if (state->head != Z_NULL)
 100.608 +                state->head->done = -1;
 100.609 +            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
 100.610 +#else
 100.611 +            if (
 100.612 +#endif
 100.613 +                ((BITS(8) << 8) + (hold >> 8)) % 31) {
 100.614 +                strm->msg = (char *)"incorrect header check";
 100.615 +                state->mode = BAD;
 100.616 +                break;
 100.617 +            }
 100.618 +            if (BITS(4) != Z_DEFLATED) {
 100.619 +                strm->msg = (char *)"unknown compression method";
 100.620 +                state->mode = BAD;
 100.621 +                break;
 100.622 +            }
 100.623 +            DROPBITS(4);
 100.624 +            len = BITS(4) + 8;
 100.625 +            if (len > state->wbits) {
 100.626 +                strm->msg = (char *)"invalid window size";
 100.627 +                state->mode = BAD;
 100.628 +                break;
 100.629 +            }
 100.630 +            state->dmax = 1U << len;
 100.631 +            Tracev((stderr, "inflate:   zlib header ok\n"));
 100.632 +            strm->adler = state->check = adler32(0L, Z_NULL, 0);
 100.633 +            state->mode = hold & 0x200 ? DICTID : TYPE;
 100.634 +            INITBITS();
 100.635 +            break;
 100.636 +#ifdef GUNZIP
 100.637 +        case FLAGS:
 100.638 +            NEEDBITS(16);
 100.639 +            state->flags = (int)(hold);
 100.640 +            if ((state->flags & 0xff) != Z_DEFLATED) {
 100.641 +                strm->msg = (char *)"unknown compression method";
 100.642 +                state->mode = BAD;
 100.643 +                break;
 100.644 +            }
 100.645 +            if (state->flags & 0xe000) {
 100.646 +                strm->msg = (char *)"unknown header flags set";
 100.647 +                state->mode = BAD;
 100.648 +                break;
 100.649 +            }
 100.650 +            if (state->head != Z_NULL)
 100.651 +                state->head->text = (int)((hold >> 8) & 1);
 100.652 +            if (state->flags & 0x0200) CRC2(state->check, hold);
 100.653 +            INITBITS();
 100.654 +            state->mode = TIME;
 100.655 +        case TIME:
 100.656 +            NEEDBITS(32);
 100.657 +            if (state->head != Z_NULL)
 100.658 +                state->head->time = hold;
 100.659 +            if (state->flags & 0x0200) CRC4(state->check, hold);
 100.660 +            INITBITS();
 100.661 +            state->mode = OS;
 100.662 +        case OS:
 100.663 +            NEEDBITS(16);
 100.664 +            if (state->head != Z_NULL) {
 100.665 +                state->head->xflags = (int)(hold & 0xff);
 100.666 +                state->head->os = (int)(hold >> 8);
 100.667 +            }
 100.668 +            if (state->flags & 0x0200) CRC2(state->check, hold);
 100.669 +            INITBITS();
 100.670 +            state->mode = EXLEN;
 100.671 +        case EXLEN:
 100.672 +            if (state->flags & 0x0400) {
 100.673 +                NEEDBITS(16);
 100.674 +                state->length = (unsigned)(hold);
 100.675 +                if (state->head != Z_NULL)
 100.676 +                    state->head->extra_len = (unsigned)hold;
 100.677 +                if (state->flags & 0x0200) CRC2(state->check, hold);
 100.678 +                INITBITS();
 100.679 +            }
 100.680 +            else if (state->head != Z_NULL)
 100.681 +                state->head->extra = Z_NULL;
 100.682 +            state->mode = EXTRA;
 100.683 +        case EXTRA:
 100.684 +            if (state->flags & 0x0400) {
 100.685 +                copy = state->length;
 100.686 +                if (copy > have) copy = have;
 100.687 +                if (copy) {
 100.688 +                    if (state->head != Z_NULL &&
 100.689 +                        state->head->extra != Z_NULL) {
 100.690 +                        len = state->head->extra_len - state->length;
 100.691 +                        zmemcpy(state->head->extra + len, next,
 100.692 +                                len + copy > state->head->extra_max ?
 100.693 +                                state->head->extra_max - len : copy);
 100.694 +                    }
 100.695 +                    if (state->flags & 0x0200)
 100.696 +                        state->check = crc32(state->check, next, copy);
 100.697 +                    have -= copy;
 100.698 +                    next += copy;
 100.699 +                    state->length -= copy;
 100.700 +                }
 100.701 +                if (state->length) goto inf_leave;
 100.702 +            }
 100.703 +            state->length = 0;
 100.704 +            state->mode = NAME;
 100.705 +        case NAME:
 100.706 +            if (state->flags & 0x0800) {
 100.707 +                if (have == 0) goto inf_leave;
 100.708 +                copy = 0;
 100.709 +                do {
 100.710 +                    len = (unsigned)(next[copy++]);
 100.711 +                    if (state->head != Z_NULL &&
 100.712 +                            state->head->name != Z_NULL &&
 100.713 +                            state->length < state->head->name_max)
 100.714 +                        state->head->name[state->length++] = len;
 100.715 +                } while (len && copy < have);
 100.716 +                if (state->flags & 0x0200)
 100.717 +                    state->check = crc32(state->check, next, copy);
 100.718 +                have -= copy;
 100.719 +                next += copy;
 100.720 +                if (len) goto inf_leave;
 100.721 +            }
 100.722 +            else if (state->head != Z_NULL)
 100.723 +                state->head->name = Z_NULL;
 100.724 +            state->length = 0;
 100.725 +            state->mode = COMMENT;
 100.726 +        case COMMENT:
 100.727 +            if (state->flags & 0x1000) {
 100.728 +                if (have == 0) goto inf_leave;
 100.729 +                copy = 0;
 100.730 +                do {
 100.731 +                    len = (unsigned)(next[copy++]);
 100.732 +                    if (state->head != Z_NULL &&
 100.733 +                            state->head->comment != Z_NULL &&
 100.734 +                            state->length < state->head->comm_max)
 100.735 +                        state->head->comment[state->length++] = len;
 100.736 +                } while (len && copy < have);
 100.737 +                if (state->flags & 0x0200)
 100.738 +                    state->check = crc32(state->check, next, copy);
 100.739 +                have -= copy;
 100.740 +                next += copy;
 100.741 +                if (len) goto inf_leave;
 100.742 +            }
 100.743 +            else if (state->head != Z_NULL)
 100.744 +                state->head->comment = Z_NULL;
 100.745 +            state->mode = HCRC;
 100.746 +        case HCRC:
 100.747 +            if (state->flags & 0x0200) {
 100.748 +                NEEDBITS(16);
 100.749 +                if (hold != (state->check & 0xffff)) {
 100.750 +                    strm->msg = (char *)"header crc mismatch";
 100.751 +                    state->mode = BAD;
 100.752 +                    break;
 100.753 +                }
 100.754 +                INITBITS();
 100.755 +            }
 100.756 +            if (state->head != Z_NULL) {
 100.757 +                state->head->hcrc = (int)((state->flags >> 9) & 1);
 100.758 +                state->head->done = 1;
 100.759 +            }
 100.760 +            strm->adler = state->check = crc32(0L, Z_NULL, 0);
 100.761 +            state->mode = TYPE;
 100.762 +            break;
 100.763 +#endif
 100.764 +        case DICTID:
 100.765 +            NEEDBITS(32);
 100.766 +            strm->adler = state->check = REVERSE(hold);
 100.767 +            INITBITS();
 100.768 +            state->mode = DICT;
 100.769 +        case DICT:
 100.770 +            if (state->havedict == 0) {
 100.771 +                RESTORE();
 100.772 +                return Z_NEED_DICT;
 100.773 +            }
 100.774 +            strm->adler = state->check = adler32(0L, Z_NULL, 0);
 100.775 +            state->mode = TYPE;
 100.776 +        case TYPE:
 100.777 +            if (flush == Z_BLOCK) goto inf_leave;
 100.778 +        case TYPEDO:
 100.779 +            if (state->last) {
 100.780 +                BYTEBITS();
 100.781 +                state->mode = CHECK;
 100.782 +                break;
 100.783 +            }
 100.784 +            NEEDBITS(3);
 100.785 +            state->last = BITS(1);
 100.786 +            DROPBITS(1);
 100.787 +            switch (BITS(2)) {
 100.788 +            case 0:                             /* stored block */
 100.789 +                Tracev((stderr, "inflate:     stored block%s\n",
 100.790 +                        state->last ? " (last)" : ""));
 100.791 +                state->mode = STORED;
 100.792 +                break;
 100.793 +            case 1:                             /* fixed block */
 100.794 +                fixedtables(state);
 100.795 +                Tracev((stderr, "inflate:     fixed codes block%s\n",
 100.796 +                        state->last ? " (last)" : ""));
 100.797 +                state->mode = LEN;              /* decode codes */
 100.798 +                break;
 100.799 +            case 2:                             /* dynamic block */
 100.800 +                Tracev((stderr, "inflate:     dynamic codes block%s\n",
 100.801 +                        state->last ? " (last)" : ""));
 100.802 +                state->mode = TABLE;
 100.803 +                break;
 100.804 +            case 3:
 100.805 +                strm->msg = (char *)"invalid block type";
 100.806 +                state->mode = BAD;
 100.807 +            }
 100.808 +            DROPBITS(2);
 100.809 +            break;
 100.810 +        case STORED:
 100.811 +            BYTEBITS();                         /* go to byte boundary */
 100.812 +            NEEDBITS(32);
 100.813 +            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
 100.814 +                strm->msg = (char *)"invalid stored block lengths";
 100.815 +                state->mode = BAD;
 100.816 +                break;
 100.817 +            }
 100.818 +            state->length = (unsigned)hold & 0xffff;
 100.819 +            Tracev((stderr, "inflate:       stored length %u\n",
 100.820 +                    state->length));
 100.821 +            INITBITS();
 100.822 +            state->mode = COPY;
 100.823 +        case COPY:
 100.824 +            copy = state->length;
 100.825 +            if (copy) {
 100.826 +                if (copy > have) copy = have;
 100.827 +                if (copy > left) copy = left;
 100.828 +                if (copy == 0) goto inf_leave;
 100.829 +                zmemcpy(put, next, copy);
 100.830 +                have -= copy;
 100.831 +                next += copy;
 100.832 +                left -= copy;
 100.833 +                put += copy;
 100.834 +                state->length -= copy;
 100.835 +                break;
 100.836 +            }
 100.837 +            Tracev((stderr, "inflate:       stored end\n"));
 100.838 +            state->mode = TYPE;
 100.839 +            break;
 100.840 +        case TABLE:
 100.841 +            NEEDBITS(14);
 100.842 +            state->nlen = BITS(5) + 257;
 100.843 +            DROPBITS(5);
 100.844 +            state->ndist = BITS(5) + 1;
 100.845 +            DROPBITS(5);
 100.846 +            state->ncode = BITS(4) + 4;
 100.847 +            DROPBITS(4);
 100.848 +#ifndef PKZIP_BUG_WORKAROUND
 100.849 +            if (state->nlen > 286 || state->ndist > 30) {
 100.850 +                strm->msg = (char *)"too many length or distance symbols";
 100.851 +                state->mode = BAD;
 100.852 +                break;
 100.853 +            }
 100.854 +#endif
 100.855 +            Tracev((stderr, "inflate:       table sizes ok\n"));
 100.856 +            state->have = 0;
 100.857 +            state->mode = LENLENS;
 100.858 +        case LENLENS:
 100.859 +            while (state->have < state->ncode) {
 100.860 +                NEEDBITS(3);
 100.861 +                state->lens[order[state->have++]] = (unsigned short)BITS(3);
 100.862 +                DROPBITS(3);
 100.863 +            }
 100.864 +            while (state->have < 19)
 100.865 +                state->lens[order[state->have++]] = 0;
 100.866 +            state->next = state->codes;
 100.867 +            state->lencode = (code const FAR *)(state->next);
 100.868 +            state->lenbits = 7;
 100.869 +            ret = inflate_table(CODES, state->lens, 19, &(state->next),
 100.870 +                                &(state->lenbits), state->work);
 100.871 +            if (ret) {
 100.872 +                strm->msg = (char *)"invalid code lengths set";
 100.873 +                state->mode = BAD;
 100.874 +                break;
 100.875 +            }
 100.876 +            Tracev((stderr, "inflate:       code lengths ok\n"));
 100.877 +            state->have = 0;
 100.878 +            state->mode = CODELENS;
 100.879 +        case CODELENS:
 100.880 +            while (state->have < state->nlen + state->ndist) {
 100.881 +                for (;;) {
 100.882 +                    this = state->lencode[BITS(state->lenbits)];
 100.883 +                    if ((unsigned)(this.bits) <= bits) break;
 100.884 +                    PULLBYTE();
 100.885 +                }
 100.886 +                if (this.val < 16) {
 100.887 +                    NEEDBITS(this.bits);
 100.888 +                    DROPBITS(this.bits);
 100.889 +                    state->lens[state->have++] = this.val;
 100.890 +                }
 100.891 +                else {
 100.892 +                    if (this.val == 16) {
 100.893 +                        NEEDBITS(this.bits + 2);
 100.894 +                        DROPBITS(this.bits);
 100.895 +                        if (state->have == 0) {
 100.896 +                            strm->msg = (char *)"invalid bit length repeat";
 100.897 +                            state->mode = BAD;
 100.898 +                            break;
 100.899 +                        }
 100.900 +                        len = state->lens[state->have - 1];
 100.901 +                        copy = 3 + BITS(2);
 100.902 +                        DROPBITS(2);
 100.903 +                    }
 100.904 +                    else if (this.val == 17) {
 100.905 +                        NEEDBITS(this.bits + 3);
 100.906 +                        DROPBITS(this.bits);
 100.907 +                        len = 0;
 100.908 +                        copy = 3 + BITS(3);
 100.909 +                        DROPBITS(3);
 100.910 +                    }
 100.911 +                    else {
 100.912 +                        NEEDBITS(this.bits + 7);
 100.913 +                        DROPBITS(this.bits);
 100.914 +                        len = 0;
 100.915 +                        copy = 11 + BITS(7);
 100.916 +                        DROPBITS(7);
 100.917 +                    }
 100.918 +                    if (state->have + copy > state->nlen + state->ndist) {
 100.919 +                        strm->msg = (char *)"invalid bit length repeat";
 100.920 +                        state->mode = BAD;
 100.921 +                        break;
 100.922 +                    }
 100.923 +                    while (copy--)
 100.924 +                        state->lens[state->have++] = (unsigned short)len;
 100.925 +                }
 100.926 +            }
 100.927 +
 100.928 +            /* handle error breaks in while */
 100.929 +            if (state->mode == BAD) break;
 100.930 +
 100.931 +            /* build code tables */
 100.932 +            state->next = state->codes;
 100.933 +            state->lencode = (code const FAR *)(state->next);
 100.934 +            state->lenbits = 9;
 100.935 +            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
 100.936 +                                &(state->lenbits), state->work);
 100.937 +            if (ret) {
 100.938 +                strm->msg = (char *)"invalid literal/lengths set";
 100.939 +                state->mode = BAD;
 100.940 +                break;
 100.941 +            }
 100.942 +            state->distcode = (code const FAR *)(state->next);
 100.943 +            state->distbits = 6;
 100.944 +            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
 100.945 +                            &(state->next), &(state->distbits), state->work);
 100.946 +            if (ret) {
 100.947 +                strm->msg = (char *)"invalid distances set";
 100.948 +                state->mode = BAD;
 100.949 +                break;
 100.950 +            }
 100.951 +            Tracev((stderr, "inflate:       codes ok\n"));
 100.952 +            state->mode = LEN;
 100.953 +        case LEN:
 100.954 +            if (have >= 6 && left >= 258) {
 100.955 +                RESTORE();
 100.956 +                inflate_fast(strm, out);
 100.957 +                LOAD();
 100.958 +                break;
 100.959 +            }
 100.960 +            for (;;) {
 100.961 +                this = state->lencode[BITS(state->lenbits)];
 100.962 +                if ((unsigned)(this.bits) <= bits) break;
 100.963 +                PULLBYTE();
 100.964 +            }
 100.965 +            if (this.op && (this.op & 0xf0) == 0) {
 100.966 +                last = this;
 100.967 +                for (;;) {
 100.968 +                    this = state->lencode[last.val +
 100.969 +                            (BITS(last.bits + last.op) >> last.bits)];
 100.970 +                    if ((unsigned)(last.bits + this.bits) <= bits) break;
 100.971 +                    PULLBYTE();
 100.972 +                }
 100.973 +                DROPBITS(last.bits);
 100.974 +            }
 100.975 +            DROPBITS(this.bits);
 100.976 +            state->length = (unsigned)this.val;
 100.977 +            if ((int)(this.op) == 0) {
 100.978 +                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
 100.979 +                        "inflate:         literal '%c'\n" :
 100.980 +                        "inflate:         literal 0x%02x\n", this.val));
 100.981 +                state->mode = LIT;
 100.982 +                break;
 100.983 +            }
 100.984 +            if (this.op & 32) {
 100.985 +                Tracevv((stderr, "inflate:         end of block\n"));
 100.986 +                state->mode = TYPE;
 100.987 +                break;
 100.988 +            }
 100.989 +            if (this.op & 64) {
 100.990 +                strm->msg = (char *)"invalid literal/length code";
 100.991 +                state->mode = BAD;
 100.992 +                break;
 100.993 +            }
 100.994 +            state->extra = (unsigned)(this.op) & 15;
 100.995 +            state->mode = LENEXT;
 100.996 +        case LENEXT:
 100.997 +            if (state->extra) {
 100.998 +                NEEDBITS(state->extra);
 100.999 +                state->length += BITS(state->extra);
100.1000 +                DROPBITS(state->extra);
100.1001 +            }
100.1002 +            Tracevv((stderr, "inflate:         length %u\n", state->length));
100.1003 +            state->mode = DIST;
100.1004 +        case DIST:
100.1005 +            for (;;) {
100.1006 +                this = state->distcode[BITS(state->distbits)];
100.1007 +                if ((unsigned)(this.bits) <= bits) break;
100.1008 +                PULLBYTE();
100.1009 +            }
100.1010 +            if ((this.op & 0xf0) == 0) {
100.1011 +                last = this;
100.1012 +                for (;;) {
100.1013 +                    this = state->distcode[last.val +
100.1014 +                            (BITS(last.bits + last.op) >> last.bits)];
100.1015 +                    if ((unsigned)(last.bits + this.bits) <= bits) break;
100.1016 +                    PULLBYTE();
100.1017 +                }
100.1018 +                DROPBITS(last.bits);
100.1019 +            }
100.1020 +            DROPBITS(this.bits);
100.1021 +            if (this.op & 64) {
100.1022 +                strm->msg = (char *)"invalid distance code";
100.1023 +                state->mode = BAD;
100.1024 +                break;
100.1025 +            }
100.1026 +            state->offset = (unsigned)this.val;
100.1027 +            state->extra = (unsigned)(this.op) & 15;
100.1028 +            state->mode = DISTEXT;
100.1029 +        case DISTEXT:
100.1030 +            if (state->extra) {
100.1031 +                NEEDBITS(state->extra);
100.1032 +                state->offset += BITS(state->extra);
100.1033 +                DROPBITS(state->extra);
100.1034 +            }
100.1035 +#ifdef INFLATE_STRICT
100.1036 +            if (state->offset > state->dmax) {
100.1037 +                strm->msg = (char *)"invalid distance too far back";
100.1038 +                state->mode = BAD;
100.1039 +                break;
100.1040 +            }
100.1041 +#endif
100.1042 +            if (state->offset > state->whave + out - left) {
100.1043 +                strm->msg = (char *)"invalid distance too far back";
100.1044 +                state->mode = BAD;
100.1045 +                break;
100.1046 +            }
100.1047 +            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
100.1048 +            state->mode = MATCH;
100.1049 +        case MATCH:
100.1050 +            if (left == 0) goto inf_leave;
100.1051 +            copy = out - left;
100.1052 +            if (state->offset > copy) {         /* copy from window */
100.1053 +                copy = state->offset - copy;
100.1054 +                if (copy > state->write) {
100.1055 +                    copy -= state->write;
100.1056 +                    from = state->window + (state->wsize - copy);
100.1057 +                }
100.1058 +                else
100.1059 +                    from = state->window + (state->write - copy);
100.1060 +                if (copy > state->length) copy = state->length;
100.1061 +            }
100.1062 +            else {                              /* copy from output */
100.1063 +                from = put - state->offset;
100.1064 +                copy = state->length;
100.1065 +            }
100.1066 +            if (copy > left) copy = left;
100.1067 +            left -= copy;
100.1068 +            state->length -= copy;
100.1069 +            do {
100.1070 +                *put++ = *from++;
100.1071 +            } while (--copy);
100.1072 +            if (state->length == 0) state->mode = LEN;
100.1073 +            break;
100.1074 +        case LIT:
100.1075 +            if (left == 0) goto inf_leave;
100.1076 +            *put++ = (unsigned char)(state->length);
100.1077 +            left--;
100.1078 +            state->mode = LEN;
100.1079 +            break;
100.1080 +        case CHECK:
100.1081 +            if (state->wrap) {
100.1082 +                NEEDBITS(32);
100.1083 +                out -= left;
100.1084 +                strm->total_out += out;
100.1085 +                state->total += out;
100.1086 +                if (out)
100.1087 +                    strm->adler = state->check =
100.1088 +                        UPDATE(state->check, put - out, out);
100.1089 +                out = left;
100.1090 +                if ((
100.1091 +#ifdef GUNZIP
100.1092 +                     state->flags ? hold :
100.1093 +#endif
100.1094 +                     REVERSE(hold)) != state->check) {
100.1095 +                    strm->msg = (char *)"incorrect data check";
100.1096 +                    state->mode = BAD;
100.1097 +                    break;
100.1098 +                }
100.1099 +                INITBITS();
100.1100 +                Tracev((stderr, "inflate:   check matches trailer\n"));
100.1101 +            }
100.1102 +#ifdef GUNZIP
100.1103 +            state->mode = LENGTH;
100.1104 +        case LENGTH:
100.1105 +            if (state->wrap && state->flags) {
100.1106 +                NEEDBITS(32);
100.1107 +                if (hold != (state->total & 0xffffffffUL)) {
100.1108 +                    strm->msg = (char *)"incorrect length check";
100.1109 +                    state->mode = BAD;
100.1110 +                    break;
100.1111 +                }
100.1112 +                INITBITS();
100.1113 +                Tracev((stderr, "inflate:   length matches trailer\n"));
100.1114 +            }
100.1115 +#endif
100.1116 +            state->mode = DONE;
100.1117 +        case DONE:
100.1118 +            ret = Z_STREAM_END;
100.1119 +            goto inf_leave;
100.1120 +        case BAD:
100.1121 +            ret = Z_DATA_ERROR;
100.1122 +            goto inf_leave;
100.1123 +        case MEM:
100.1124 +            return Z_MEM_ERROR;
100.1125 +        case SYNC:
100.1126 +        default:
100.1127 +            return Z_STREAM_ERROR;
100.1128 +        }
100.1129 +
100.1130 +    /*
100.1131 +       Return from inflate(), updating the total counts and the check value.
100.1132 +       If there was no progress during the inflate() call, return a buffer
100.1133 +       error.  Call updatewindow() to create and/or update the window state.
100.1134 +       Note: a memory error from inflate() is non-recoverable.
100.1135 +     */
100.1136 +  inf_leave:
100.1137 +    RESTORE();
100.1138 +    if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
100.1139 +        if (updatewindow(strm, out)) {
100.1140 +            state->mode = MEM;
100.1141 +            return Z_MEM_ERROR;
100.1142 +        }
100.1143 +    in -= strm->avail_in;
100.1144 +    out -= strm->avail_out;
100.1145 +    strm->total_in += in;
100.1146 +    strm->total_out += out;
100.1147 +    state->total += out;
100.1148 +    if (state->wrap && out)
100.1149 +        strm->adler = state->check =
100.1150 +            UPDATE(state->check, strm->next_out - out, out);
100.1151 +    strm->data_type = state->bits + (state->last ? 64 : 0) +
100.1152 +                      (state->mode == TYPE ? 128 : 0);
100.1153 +    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
100.1154 +        ret = Z_BUF_ERROR;
100.1155 +    return ret;
100.1156 +}
100.1157 +
100.1158 +int ZEXPORT inflateEnd(strm)
100.1159 +z_streamp strm;
100.1160 +{
100.1161 +    struct inflate_state FAR *state;
100.1162 +    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
100.1163 +        return Z_STREAM_ERROR;
100.1164 +    state = (struct inflate_state FAR *)strm->state;
100.1165 +    if (state->window != Z_NULL) ZFREE(strm, state->window);
100.1166 +    ZFREE(strm, strm->state);
100.1167 +    strm->state = Z_NULL;
100.1168 +    Tracev((stderr, "inflate: end\n"));
100.1169 +    return Z_OK;
100.1170 +}
100.1171 +
100.1172 +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
100.1173 +z_streamp strm;
100.1174 +const Bytef *dictionary;
100.1175 +uInt dictLength;
100.1176 +{
100.1177 +    struct inflate_state FAR *state;
100.1178 +    unsigned long id;
100.1179 +
100.1180 +    /* check state */
100.1181 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
100.1182 +    state = (struct inflate_state FAR *)strm->state;
100.1183 +    if (state->wrap != 0 && state->mode != DICT)
100.1184 +        return Z_STREAM_ERROR;
100.1185 +
100.1186 +    /* check for correct dictionary id */
100.1187 +    if (state->mode == DICT) {
100.1188 +        id = adler32(0L, Z_NULL, 0);
100.1189 +        id = adler32(id, dictionary, dictLength);
100.1190 +        if (id != state->check)
100.1191 +            return Z_DATA_ERROR;
100.1192 +    }
100.1193 +
100.1194 +    /* copy dictionary to window */
100.1195 +    if (updatewindow(strm, strm->avail_out)) {
100.1196 +        state->mode = MEM;
100.1197 +        return Z_MEM_ERROR;
100.1198 +    }
100.1199 +    if (dictLength > state->wsize) {
100.1200 +        zmemcpy(state->window, dictionary + dictLength - state->wsize,
100.1201 +                state->wsize);
100.1202 +        state->whave = state->wsize;
100.1203 +    }
100.1204 +    else {
100.1205 +        zmemcpy(state->window + state->wsize - dictLength, dictionary,
100.1206 +                dictLength);
100.1207 +        state->whave = dictLength;
100.1208 +    }
100.1209 +    state->havedict = 1;
100.1210 +    Tracev((stderr, "inflate:   dictionary set\n"));
100.1211 +    return Z_OK;
100.1212 +}
100.1213 +
100.1214 +int ZEXPORT inflateGetHeader(strm, head)
100.1215 +z_streamp strm;
100.1216 +gz_headerp head;
100.1217 +{
100.1218 +    struct inflate_state FAR *state;
100.1219 +
100.1220 +    /* check state */
100.1221 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
100.1222 +    state = (struct inflate_state FAR *)strm->state;
100.1223 +    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
100.1224 +
100.1225 +    /* save header structure */
100.1226 +    state->head = head;
100.1227 +    head->done = 0;
100.1228 +    return Z_OK;
100.1229 +}
100.1230 +
100.1231 +/*
100.1232 +   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
100.1233 +   or when out of input.  When called, *have is the number of pattern bytes
100.1234 +   found in order so far, in 0..3.  On return *have is updated to the new
100.1235 +   state.  If on return *have equals four, then the pattern was found and the
100.1236 +   return value is how many bytes were read including the last byte of the
100.1237 +   pattern.  If *have is less than four, then the pattern has not been found
100.1238 +   yet and the return value is len.  In the latter case, syncsearch() can be
100.1239 +   called again with more data and the *have state.  *have is initialized to
100.1240 +   zero for the first call.
100.1241 + */
100.1242 +local unsigned syncsearch(have, buf, len)
100.1243 +unsigned FAR *have;
100.1244 +unsigned char FAR *buf;
100.1245 +unsigned len;
100.1246 +{
100.1247 +    unsigned got;
100.1248 +    unsigned next;
100.1249 +
100.1250 +    got = *have;
100.1251 +    next = 0;
100.1252 +    while (next < len && got < 4) {
100.1253 +        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
100.1254 +            got++;
100.1255 +        else if (buf[next])
100.1256 +            got = 0;
100.1257 +        else
100.1258 +            got = 4 - got;
100.1259 +        next++;
100.1260 +    }
100.1261 +    *have = got;
100.1262 +    return next;
100.1263 +}
100.1264 +
100.1265 +int ZEXPORT inflateSync(strm)
100.1266 +z_streamp strm;
100.1267 +{
100.1268 +    unsigned len;               /* number of bytes to look at or looked at */
100.1269 +    unsigned long in, out;      /* temporary to save total_in and total_out */
100.1270 +    unsigned char buf[4];       /* to restore bit buffer to byte string */
100.1271 +    struct inflate_state FAR *state;
100.1272 +
100.1273 +    /* check parameters */
100.1274 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
100.1275 +    state = (struct inflate_state FAR *)strm->state;
100.1276 +    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
100.1277 +
100.1278 +    /* if first time, start search in bit buffer */
100.1279 +    if (state->mode != SYNC) {
100.1280 +        state->mode = SYNC;
100.1281 +        state->hold <<= state->bits & 7;
100.1282 +        state->bits -= state->bits & 7;
100.1283 +        len = 0;
100.1284 +        while (state->bits >= 8) {
100.1285 +            buf[len++] = (unsigned char)(state->hold);
100.1286 +            state->hold >>= 8;
100.1287 +            state->bits -= 8;
100.1288 +        }
100.1289 +        state->have = 0;
100.1290 +        syncsearch(&(state->have), buf, len);
100.1291 +    }
100.1292 +
100.1293 +    /* search available input */
100.1294 +    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
100.1295 +    strm->avail_in -= len;
100.1296 +    strm->next_in += len;
100.1297 +    strm->total_in += len;
100.1298 +
100.1299 +    /* return no joy or set up to restart inflate() on a new block */
100.1300 +    if (state->have != 4) return Z_DATA_ERROR;
100.1301 +    in = strm->total_in;  out = strm->total_out;
100.1302 +    inflateReset(strm);
100.1303 +    strm->total_in = in;  strm->total_out = out;
100.1304 +    state->mode = TYPE;
100.1305 +    return Z_OK;
100.1306 +}
100.1307 +
100.1308 +/*
100.1309 +   Returns true if inflate is currently at the end of a block generated by
100.1310 +   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
100.1311 +   implementation to provide an additional safety check. PPP uses
100.1312 +   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
100.1313 +   block. When decompressing, PPP checks that at the end of input packet,
100.1314 +   inflate is waiting for these length bytes.
100.1315 + */
100.1316 +int ZEXPORT inflateSyncPoint(strm)
100.1317 +z_streamp strm;
100.1318 +{
100.1319 +    struct inflate_state FAR *state;
100.1320 +
100.1321 +    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
100.1322 +    state = (struct inflate_state FAR *)strm->state;
100.1323 +    return state->mode == STORED && state->bits == 0;
100.1324 +}
100.1325 +
100.1326 +int ZEXPORT inflateCopy(dest, source)
100.1327 +z_streamp dest;
100.1328 +z_streamp source;
100.1329 +{
100.1330 +    struct inflate_state FAR *state;
100.1331 +    struct inflate_state FAR *copy;
100.1332 +    unsigned char FAR *window;
100.1333 +    unsigned wsize;
100.1334 +
100.1335 +    /* check input */
100.1336 +    if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
100.1337 +        source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
100.1338 +        return Z_STREAM_ERROR;
100.1339 +    state = (struct inflate_state FAR *)source->state;
100.1340 +
100.1341 +    /* allocate space */
100.1342 +    copy = (struct inflate_state FAR *)
100.1343 +           ZALLOC(source, 1, sizeof(struct inflate_state));
100.1344 +    if (copy == Z_NULL) return Z_MEM_ERROR;
100.1345 +    window = Z_NULL;
100.1346 +    if (state->window != Z_NULL) {
100.1347 +        window = (unsigned char FAR *)
100.1348 +                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
100.1349 +        if (window == Z_NULL) {
100.1350 +            ZFREE(source, copy);
100.1351 +            return Z_MEM_ERROR;
100.1352 +        }
100.1353 +    }
100.1354 +
100.1355 +    /* copy state */
100.1356 +    zmemcpy(dest, source, sizeof(z_stream));
100.1357 +    zmemcpy(copy, state, sizeof(struct inflate_state));
100.1358 +    if (state->lencode >= state->codes &&
100.1359 +        state->lencode <= state->codes + ENOUGH - 1) {
100.1360 +        copy->lencode = copy->codes + (state->lencode - state->codes);
100.1361 +        copy->distcode = copy->codes + (state->distcode - state->codes);
100.1362 +    }
100.1363 +    copy->next = copy->codes + (state->next - state->codes);
100.1364 +    if (window != Z_NULL) {
100.1365 +        wsize = 1U << state->wbits;
100.1366 +        zmemcpy(window, state->window, wsize);
100.1367 +    }
100.1368 +    copy->window = window;
100.1369 +    dest->state = (struct internal_state FAR *)copy;
100.1370 +    return Z_OK;
100.1371 +}
   101.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   101.2 +++ b/libs/zlib/inflate.h	Thu Sep 08 06:28:38 2011 +0300
   101.3 @@ -0,0 +1,115 @@
   101.4 +/* inflate.h -- internal inflate state definition
   101.5 + * Copyright (C) 1995-2004 Mark Adler
   101.6 + * For conditions of distribution and use, see copyright notice in zlib.h
   101.7 + */
   101.8 +
   101.9 +/* WARNING: this file should *not* be used by applications. It is
  101.10 +   part of the implementation of the compression library and is
  101.11 +   subject to change. Applications should only use zlib.h.
  101.12 + */
  101.13 +
  101.14 +/* define NO_GZIP when compiling if you want to disable gzip header and
  101.15 +   trailer decoding by inflate().  NO_GZIP would be used to avoid linking in
  101.16 +   the crc code when it is not needed.  For shared libraries, gzip decoding
  101.17 +   should be left enabled. */
  101.18 +#ifndef NO_GZIP
  101.19 +#  define GUNZIP
  101.20 +#endif
  101.21 +
  101.22 +/* Possible inflate modes between inflate() calls */
  101.23 +typedef enum {
  101.24 +    HEAD,       /* i: waiting for magic header */
  101.25 +    FLAGS,      /* i: waiting for method and flags (gzip) */
  101.26 +    TIME,       /* i: waiting for modification time (gzip) */
  101.27 +    OS,         /* i: waiting for extra flags and operating system (gzip) */
  101.28 +    EXLEN,      /* i: waiting for extra length (gzip) */
  101.29 +    EXTRA,      /* i: waiting for extra bytes (gzip) */
  101.30 +    NAME,       /* i: waiting for end of file name (gzip) */
  101.31 +    COMMENT,    /* i: waiting for end of comment (gzip) */
  101.32 +    HCRC,       /* i: waiting for header crc (gzip) */
  101.33 +    DICTID,     /* i: waiting for dictionary check value */
  101.34 +    DICT,       /* waiting for inflateSetDictionary() call */
  101.35 +        TYPE,       /* i: waiting for type bits, including last-flag bit */
  101.36 +        TYPEDO,     /* i: same, but skip check to exit inflate on new block */
  101.37 +        STORED,     /* i: waiting for stored size (length and complement) */
  101.38 +        COPY,       /* i/o: waiting for input or output to copy stored block */
  101.39 +        TABLE,      /* i: waiting for dynamic block table lengths */
  101.40 +        LENLENS,    /* i: waiting for code length code lengths */
  101.41 +        CODELENS,   /* i: waiting for length/lit and distance code lengths */
  101.42 +            LEN,        /* i: waiting for length/lit code */
  101.43 +            LENEXT,     /* i: waiting for length extra bits */
  101.44 +            DIST,       /* i: waiting for distance code */
  101.45 +            DISTEXT,    /* i: waiting for distance extra bits */
  101.46 +            MATCH,      /* o: waiting for output space to copy string */
  101.47 +            LIT,        /* o: waiting for output space to write literal */
  101.48 +    CHECK,      /* i: waiting for 32-bit check value */
  101.49 +    LENGTH,     /* i: waiting for 32-bit length (gzip) */
  101.50 +    DONE,       /* finished check, done -- remain here until reset */
  101.51 +    BAD,        /* got a data error -- remain here until reset */
  101.52 +    MEM,        /* got an inflate() memory error -- remain here until reset */
  101.53 +    SYNC        /* looking for synchronization bytes to restart inflate() */
  101.54 +} inflate_mode;
  101.55 +
  101.56 +/*
  101.57 +    State transitions between above modes -
  101.58 +
  101.59 +    (most modes can go to the BAD or MEM mode -- not shown for clarity)
  101.60 +
  101.61 +    Process header:
  101.62 +        HEAD -> (gzip) or (zlib)
  101.63 +        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  101.64 +        NAME -> COMMENT -> HCRC -> TYPE
  101.65 +        (zlib) -> DICTID or TYPE
  101.66 +        DICTID -> DICT -> TYPE
  101.67 +    Read deflate blocks:
  101.68 +            TYPE -> STORED or TABLE or LEN or CHECK
  101.69 +            STORED -> COPY -> TYPE
  101.70 +            TABLE -> LENLENS -> CODELENS -> LEN
  101.71 +    Read deflate codes:
  101.72 +                LEN -> LENEXT or LIT or TYPE
  101.73 +                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  101.74 +                LIT -> LEN
  101.75 +    Process trailer:
  101.76 +        CHECK -> LENGTH -> DONE
  101.77 + */
  101.78 +
  101.79 +/* state maintained between inflate() calls.  Approximately 7K bytes. */
  101.80 +struct inflate_state {
  101.81 +    inflate_mode mode;          /* current inflate mode */
  101.82 +    int last;                   /* true if processing last block */
  101.83 +    int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip */
  101.84 +    int havedict;               /* true if dictionary provided */
  101.85 +    int flags;                  /* gzip header method and flags (0 if zlib) */
  101.86 +    unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */
  101.87 +    unsigned long check;        /* protected copy of check value */
  101.88 +    unsigned long total;        /* protected copy of output count */
  101.89 +    gz_headerp head;            /* where to save gzip header information */
  101.90 +        /* sliding window */
  101.91 +    unsigned wbits;             /* log base 2 of requested window size */
  101.92 +    unsigned wsize;             /* window size or zero if not using window */
  101.93 +    unsigned whave;             /* valid bytes in the window */
  101.94 +    unsigned write;             /* window write index */
  101.95 +    unsigned char FAR *window;  /* allocated sliding window, if needed */
  101.96 +        /* bit accumulator */
  101.97 +    unsigned long hold;         /* input bit accumulator */
  101.98 +    unsigned bits;              /* number of bits in "in" */
  101.99 +        /* for string and stored block copying */
 101.100 +    unsigned length;            /* literal or length of data to copy */
 101.101 +    unsigned offset;            /* distance back to copy string from */
 101.102 +        /* for table and code decoding */
 101.103 +    unsigned extra;             /* extra bits needed */
 101.104 +        /* fixed and dynamic code tables */
 101.105 +    code const FAR *lencode;    /* starting table for length/literal codes */
 101.106 +    code const FAR *distcode;   /* starting table for distance codes */
 101.107 +    unsigned lenbits;           /* index bits for lencode */
 101.108 +    unsigned distbits;          /* index bits for distcode */
 101.109 +        /* dynamic table building */
 101.110 +    unsigned ncode;             /* number of code length code lengths */
 101.111 +    unsigned nlen;              /* number of length code lengths */
 101.112 +    unsigned ndist;             /* number of distance code lengths */
 101.113 +    unsigned have;              /* number of code lengths in lens[] */
 101.114 +    code FAR *next;             /* next available space in codes[] */
 101.115 +    unsigned short lens[320];   /* temporary storage for code lengths */
 101.116 +    unsigned short work[288];   /* work area for code table building */
 101.117 +    code codes[ENOUGH];         /* space for code tables */
 101.118 +};
   102.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   102.2 +++ b/libs/zlib/inftrees.c	Thu Sep 08 06:28:38 2011 +0300
   102.3 @@ -0,0 +1,329 @@
   102.4 +/* inftrees.c -- generate Huffman trees for efficient decoding
   102.5 + * Copyright (C) 1995-2005 Mark Adler
   102.6 + * For conditions of distribution and use, see copyright notice in zlib.h
   102.7 + */
   102.8 +
   102.9 +#include "zutil.h"
  102.10 +#include "inftrees.h"
  102.11 +
  102.12 +#define MAXBITS 15
  102.13 +
  102.14 +const char inflate_copyright[] =
  102.15 +   " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  102.16 +/*
  102.17 +  If you use the zlib library in a product, an acknowledgment is welcome
  102.18 +  in the documentation of your product. If for some reason you cannot
  102.19 +  include such an acknowledgment, I would appreciate that you keep this
  102.20 +  copyright string in the executable of your product.
  102.21 + */
  102.22 +
  102.23 +/*
  102.24 +   Build a set of tables to decode the provided canonical Huffman code.
  102.25 +   The code lengths are lens[0..codes-1].  The result starts at *table,
  102.26 +   whose indices are 0..2^bits-1.  work is a writable array of at least
  102.27 +   lens shorts, which is used as a work area.  type is the type of code
  102.28 +   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
  102.29 +   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
  102.30 +   on return points to the next available entry's address.  bits is the
  102.31 +   requested root table index bits, and on return it is the actual root
  102.32 +   table index bits.  It will differ if the request is greater than the
  102.33 +   longest code or if it is less than the shortest code.
  102.34 + */
  102.35 +int inflate_table(type, lens, codes, table, bits, work)
  102.36 +codetype type;
  102.37 +unsigned short FAR *lens;
  102.38 +unsigned codes;
  102.39 +code FAR * FAR *table;
  102.40 +unsigned FAR *bits;
  102.41 +unsigned short FAR *work;
  102.42 +{
  102.43 +    unsigned len;               /* a code's length in bits */
  102.44 +    unsigned sym;               /* index of code symbols */
  102.45 +    unsigned min, max;          /* minimum and maximum code lengths */
  102.46 +    unsigned root;              /* number of index bits for root table */
  102.47 +    unsigned curr;              /* number of index bits for current table */
  102.48 +    unsigned drop;              /* code bits to drop for sub-table */
  102.49 +    int left;                   /* number of prefix codes available */
  102.50 +    unsigned used;              /* code entries in table used */
  102.51 +    unsigned huff;              /* Huffman code */
  102.52 +    unsigned incr;              /* for incrementing code, index */
  102.53 +    unsigned fill;              /* index for replicating entries */
  102.54 +    unsigned low;               /* low bits for current root entry */
  102.55 +    unsigned mask;              /* mask for low root bits */
  102.56 +    code this;                  /* table entry for duplication */
  102.57 +    code FAR *next;             /* next available space in table */
  102.58 +    const unsigned short FAR *base;     /* base value table to use */
  102.59 +    const unsigned short FAR *extra;    /* extra bits table to use */
  102.60 +    int end;                    /* use base and extra for symbol > end */
  102.61 +    unsigned short count[MAXBITS+1];    /* number of codes of each length */
  102.62 +    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
  102.63 +    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  102.64 +        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  102.65 +        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  102.66 +    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  102.67 +        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  102.68 +        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  102.69 +    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  102.70 +        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  102.71 +        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  102.72 +        8193, 12289, 16385, 24577, 0, 0};
  102.73 +    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  102.74 +        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  102.75 +        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  102.76 +        28, 28, 29, 29, 64, 64};
  102.77 +
  102.78 +    /*
  102.79 +       Process a set of code lengths to create a canonical Huffman code.  The
  102.80 +       code lengths are lens[0..codes-1].  Each length corresponds to the
  102.81 +       symbols 0..codes-1.  The Huffman code is generated by first sorting the
  102.82 +       symbols by length from short to long, and retaining the symbol order
  102.83 +       for codes with equal lengths.  Then the code starts with all zero bits
  102.84 +       for the first code of the shortest length, and the codes are integer
  102.85 +       increments for the same length, and zeros are appended as the length
  102.86 +       increases.  For the deflate format, these bits are stored backwards
  102.87 +       from their more natural integer increment ordering, and so when the
  102.88 +       decoding tables are built in the large loop below, the integer codes
  102.89 +       are incremented backwards.
  102.90 +
  102.91 +       This routine assumes, but does not check, that all of the entries in
  102.92 +       lens[] are in the range 0..MAXBITS.  The caller must assure this.
  102.93 +       1..MAXBITS is interpreted as that code length.  zero means that that
  102.94 +       symbol does not occur in this code.
  102.95 +
  102.96 +       The codes are sorted by computing a count of codes for each length,
  102.97 +       creating from that a table of starting indices for each length in the
  102.98 +       sorted table, and then entering the symbols in order in the sorted
  102.99 +       table.  The sorted table is work[], with that space being provided by
 102.100 +       the caller.
 102.101 +
 102.102 +       The length counts are used for other purposes as well, i.e. finding
 102.103 +       the minimum and maximum length codes, determining if there are any
 102.104 +       codes at all, checking for a valid set of lengths, and looking ahead
 102.105 +       at length counts to determine sub-table sizes when building the
 102.106 +       decoding tables.
 102.107 +     */
 102.108 +
 102.109 +    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
 102.110 +    for (len = 0; len <= MAXBITS; len++)
 102.111 +        count[len] = 0;
 102.112 +    for (sym = 0; sym < codes; sym++)
 102.113 +        count[lens[sym]]++;
 102.114 +
 102.115 +    /* bound code lengths, force root to be within code lengths */
 102.116 +    root = *bits;
 102.117 +    for (max = MAXBITS; max >= 1; max--)
 102.118 +        if (count[max] != 0) break;
 102.119 +    if (root > max) root = max;
 102.120 +    if (max == 0) {                     /* no symbols to code at all */
 102.121 +        this.op = (unsigned char)64;    /* invalid code marker */
 102.122 +        this.bits = (unsigned char)1;
 102.123 +        this.val = (unsigned short)0;
 102.124 +        *(*table)++ = this;             /* make a table to force an error */
 102.125 +        *(*table)++ = this;
 102.126 +        *bits = 1;
 102.127 +        return 0;     /* no symbols, but wait for decoding to report error */
 102.128 +    }
 102.129 +    for (min = 1; min <= MAXBITS; min++)
 102.130 +        if (count[min] != 0) break;
 102.131 +    if (root < min) root = min;
 102.132 +
 102.133 +    /* check for an over-subscribed or incomplete set of lengths */
 102.134 +    left = 1;
 102.135 +    for (len = 1; len <= MAXBITS; len++) {
 102.136 +        left <<= 1;
 102.137 +        left -= count[len];
 102.138 +        if (left < 0) return -1;        /* over-subscribed */
 102.139 +    }
 102.140 +    if (left > 0 && (type == CODES || max != 1))
 102.141 +        return -1;                      /* incomplete set */
 102.142 +
 102.143 +    /* generate offsets into symbol table for each length for sorting */
 102.144 +    offs[1] = 0;
 102.145 +    for (len = 1; len < MAXBITS; len++)
 102.146 +        offs[len + 1] = offs[len] + count[len];
 102.147 +
 102.148 +    /* sort symbols by length, by symbol order within each length */
 102.149 +    for (sym = 0; sym < codes; sym++)
 102.150 +        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
 102.151 +
 102.152 +    /*
 102.153 +       Create and fill in decoding tables.  In this loop, the table being
 102.154 +       filled is at next and has curr index bits.  The code being used is huff
 102.155 +       with length len.  That code is converted to an index by dropping drop
 102.156 +       bits off of the bottom.  For codes where len is less than drop + curr,
 102.157 +       those top drop + curr - len bits are incremented through all values to
 102.158 +       fill the table with replicated entries.
 102.159 +
 102.160 +       root is the number of index bits for the root table.  When len exceeds
 102.161 +       root, sub-tables are created pointed to by the root entry with an index
 102.162 +       of the low root bits of huff.  This is saved in low to check for when a
 102.163 +       new sub-table should be started.  drop is zero when the root table is
 102.164 +       being filled, and drop is root when sub-tables are being filled.
 102.165 +
 102.166 +       When a new sub-table is needed, it is necessary to look ahead in the
 102.167 +       code lengths to determine what size sub-table is needed.  The length
 102.168 +       counts are used for this, and so count[] is decremented as codes are
 102.169 +       entered in the tables.
 102.170 +
 102.171 +       used keeps track of how many table entries have been allocated from the
 102.172 +       provided *table space.  It is checked when a LENS table is being made
 102.173 +       against the space in *table, ENOUGH, minus the maximum space needed by
 102.174 +       the worst case distance code, MAXD.  This should never happen, but the
 102.175 +       sufficiency of ENOUGH has not been proven exhaustively, hence the check.
 102.176 +       This assumes that when type == LENS, bits == 9.
 102.177 +
 102.178 +       sym increments through all symbols, and the loop terminates when
 102.179 +       all codes of length max, i.e. all codes, have been processed.  This
 102.180 +       routine permits incomplete codes, so another loop after this one fills
 102.181 +       in the rest of the decoding tables with invalid code markers.
 102.182 +     */
 102.183 +
 102.184 +    /* set up for code type */
 102.185 +    switch (type) {
 102.186 +    case CODES:
 102.187 +        base = extra = work;    /* dummy value--not used */
 102.188 +        end = 19;
 102.189 +        break;
 102.190 +    case LENS:
 102.191 +        base = lbase;
 102.192 +        base -= 257;
 102.193 +        extra = lext;
 102.194 +        extra -= 257;
 102.195 +        end = 256;
 102.196 +        break;
 102.197 +    default:            /* DISTS */
 102.198 +        base = dbase;
 102.199 +        extra = dext;
 102.200 +        end = -1;
 102.201 +    }
 102.202 +
 102.203 +    /* initialize state for loop */
 102.204 +    huff = 0;                   /* starting code */
 102.205 +    sym = 0;                    /* starting code symbol */
 102.206 +    len = min;                  /* starting code length */
 102.207 +    next = *table;              /* current table to fill in */
 102.208 +    curr = root;                /* current table index bits */
 102.209 +    drop = 0;                   /* current bits to drop from code for index */
 102.210 +    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
 102.211 +    used = 1U << root;          /* use root table entries */
 102.212 +    mask = used - 1;            /* mask for comparing low */
 102.213 +
 102.214 +    /* check available table space */
 102.215 +    if (type == LENS && used >= ENOUGH - MAXD)
 102.216 +        return 1;
 102.217 +
 102.218 +    /* process all codes and make table entries */
 102.219 +    for (;;) {
 102.220 +        /* create table entry */
 102.221 +        this.bits = (unsigned char)(len - drop);
 102.222 +        if ((int)(work[sym]) < end) {
 102.223 +            this.op = (unsigned char)0;
 102.224 +            this.val = work[sym];
 102.225 +        }
 102.226 +        else if ((int)(work[sym]) > end) {
 102.227 +            this.op = (unsigned char)(extra[work[sym]]);
 102.228 +            this.val = base[work[sym]];
 102.229 +        }
 102.230 +        else {
 102.231 +            this.op = (unsigned char)(32 + 64);         /* end of block */
 102.232 +            this.val = 0;
 102.233 +        }
 102.234 +
 102.235 +        /* replicate for those indices with low len bits equal to huff */
 102.236 +        incr = 1U << (len - drop);
 102.237 +        fill = 1U << curr;
 102.238 +        min = fill;                 /* save offset to next table */
 102.239 +        do {
 102.240 +            fill -= incr;
 102.241 +            next[(huff >> drop) + fill] = this;
 102.242 +        } while (fill != 0);
 102.243 +
 102.244 +        /* backwards increment the len-bit code huff */
 102.245 +        incr = 1U << (len - 1);
 102.246 +        while (huff & incr)
 102.247 +            incr >>= 1;
 102.248 +        if (incr != 0) {
 102.249 +            huff &= incr - 1;
 102.250 +            huff += incr;
 102.251 +        }
 102.252 +        else
 102.253 +            huff = 0;
 102.254 +
 102.255 +        /* go to next symbol, update count, len */
 102.256 +        sym++;
 102.257 +        if (--(count[len]) == 0) {
 102.258 +            if (len == max) break;
 102.259 +            len = lens[work[sym]];
 102.260 +        }
 102.261 +
 102.262 +        /* create new sub-table if needed */
 102.263 +        if (len > root && (huff & mask) != low) {
 102.264 +            /* if first time, transition to sub-tables */
 102.265 +            if (drop == 0)
 102.266 +                drop = root;
 102.267 +
 102.268 +            /* increment past last table */
 102.269 +            next += min;            /* here min is 1 << curr */
 102.270 +
 102.271 +            /* determine length of next table */
 102.272 +            curr = len - drop;
 102.273 +            left = (int)(1 << curr);
 102.274 +            while (curr + drop < max) {
 102.275 +                left -= count[curr + drop];
 102.276 +                if (left <= 0) break;
 102.277 +                curr++;
 102.278 +                left <<= 1;
 102.279 +            }
 102.280 +
 102.281 +            /* check for enough space */
 102.282 +            used += 1U << curr;
 102.283 +            if (type == LENS && used >= ENOUGH - MAXD)
 102.284 +                return 1;
 102.285 +
 102.286 +            /* point entry in root table to sub-table */
 102.287 +            low = huff & mask;
 102.288 +            (*table)[low].op = (unsigned char)curr;
 102.289 +            (*table)[low].bits = (unsigned char)root;
 102.290 +            (*table)[low].val = (unsigned short)(next - *table);
 102.291 +        }
 102.292 +    }
 102.293 +
 102.294 +    /*
 102.295 +       Fill in rest of table for incomplete codes.  This loop is similar to the
 102.296 +       loop above in incrementing huff for table indices.  It is assumed that
 102.297 +       len is equal to curr + drop, so there is no loop needed to increment
 102.298 +       through high index bits.  When the current sub-table is filled, the loop
 102.299 +       drops back to the root table to fill in any remaining entries there.
 102.300 +     */
 102.301 +    this.op = (unsigned char)64;                /* invalid code marker */
 102.302 +    this.bits = (unsigned char)(len - drop);
 102.303 +    this.val = (unsigned short)0;
 102.304 +    while (huff != 0) {
 102.305 +        /* when done with sub-table, drop back to root table */
 102.306 +        if (drop != 0 && (huff & mask) != low) {
 102.307 +            drop = 0;
 102.308 +            len = root;
 102.309 +            next = *table;
 102.310 +            this.bits = (unsigned char)len;
 102.311 +        }
 102.312 +
 102.313 +        /* put invalid code marker in table */
 102.314 +        next[huff >> drop] = this;
 102.315 +
 102.316 +        /* backwards increment the len-bit code huff */
 102.317 +        incr = 1U << (len - 1);
 102.318 +        while (huff & incr)
 102.319 +            incr >>= 1;
 102.320 +        if (incr != 0) {
 102.321 +            huff &= incr - 1;
 102.322 +            huff += incr;
 102.323 +        }
 102.324 +        else
 102.325 +            huff = 0;
 102.326 +    }
 102.327 +
 102.328 +    /* set return parameters */
 102.329 +    *table += used;
 102.330 +    *bits = root;
 102.331 +    return 0;
 102.332 +}
   103.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   103.2 +++ b/libs/zlib/inftrees.h	Thu Sep 08 06:28:38 2011 +0300
   103.3 @@ -0,0 +1,55 @@
   103.4 +/* inftrees.h -- header to use inftrees.c
   103.5 + * Copyright (C) 1995-2005 Mark Adler
   103.6 + * For conditions of distribution and use, see copyright notice in zlib.h
   103.7 + */
   103.8 +
   103.9 +/* WARNING: this file should *not* be used by applications. It is
  103.10 +   part of the implementation of the compression library and is
  103.11 +   subject to change. Applications should only use zlib.h.
  103.12 + */
  103.13 +
  103.14 +/* Structure for decoding tables.  Each entry provides either the
  103.15 +   information needed to do the operation requested by the code that
  103.16 +   indexed that table entry, or it provides a pointer to another
  103.17 +   table that indexes more bits of the code.  op indicates whether
  103.18 +   the entry is a pointer to another table, a literal, a length or
  103.19 +   distance, an end-of-block, or an invalid code.  For a table
  103.20 +   pointer, the low four bits of op is the number of index bits of
  103.21 +   that table.  For a length or distance, the low four bits of op
  103.22 +   is the number of extra bits to get after the code.  bits is
  103.23 +   the number of bits in this code or part of the code to drop off
  103.24 +   of the bit buffer.  val is the actual byte to output in the case
  103.25 +   of a literal, the base length or distance, or the offset from
  103.26 +   the current table to the next table.  Each entry is four bytes. */
  103.27 +typedef struct {
  103.28 +    unsigned char op;           /* operation, extra bits, table bits */
  103.29 +    unsigned char bits;         /* bits in this part of the code */
  103.30 +    unsigned short val;         /* offset in table or code value */
  103.31 +} code;
  103.32 +
  103.33 +/* op values as set by inflate_table():
  103.34 +    00000000 - literal
  103.35 +    0000tttt - table link, tttt != 0 is the number of table index bits
  103.36 +    0001eeee - length or distance, eeee is the number of extra bits
  103.37 +    01100000 - end of block
  103.38 +    01000000 - invalid code
  103.39 + */
  103.40 +
  103.41 +/* Maximum size of dynamic tree.  The maximum found in a long but non-
  103.42 +   exhaustive search was 1444 code structures (852 for length/literals
  103.43 +   and 592 for distances, the latter actually the result of an
  103.44 +   exhaustive search).  The true maximum is not known, but the value
  103.45 +   below is more than safe. */
  103.46 +#define ENOUGH 2048
  103.47 +#define MAXD 592
  103.48 +
  103.49 +/* Type of code to build for inftable() */
  103.50 +typedef enum {
  103.51 +    CODES,
  103.52 +    LENS,
  103.53 +    DISTS
  103.54 +} codetype;
  103.55 +
  103.56 +extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  103.57 +                             unsigned codes, code FAR * FAR *table,
  103.58 +                             unsigned FAR *bits, unsigned short FAR *work));
   104.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   104.2 +++ b/libs/zlib/trees.c	Thu Sep 08 06:28:38 2011 +0300
   104.3 @@ -0,0 +1,1219 @@
   104.4 +/* trees.c -- output deflated data using Huffman coding
   104.5 + * Copyright (C) 1995-2005 Jean-loup Gailly
   104.6 + * For conditions of distribution and use, see copyright notice in zlib.h
   104.7 + */
   104.8 +
   104.9 +/*
  104.10 + *  ALGORITHM
  104.11 + *
  104.12 + *      The "deflation" process uses several Huffman trees. The more
  104.13 + *      common source values are represented by shorter bit sequences.
  104.14 + *
  104.15 + *      Each code tree is stored in a compressed form which is itself
  104.16 + * a Huffman encoding of the lengths of all the code strings (in
  104.17 + * ascending order by source values).  The actual code strings are
  104.18 + * reconstructed from the lengths in the inflate process, as described
  104.19 + * in the deflate specification.
  104.20 + *
  104.21 + *  REFERENCES
  104.22 + *
  104.23 + *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  104.24 + *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  104.25 + *
  104.26 + *      Storer, James A.
  104.27 + *          Data Compression:  Methods and Theory, pp. 49-50.
  104.28 + *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
  104.29 + *
  104.30 + *      Sedgewick, R.
  104.31 + *          Algorithms, p290.
  104.32 + *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
  104.33 + */
  104.34 +
  104.35 +/* @(#) $Id$ */
  104.36 +
  104.37 +/* #define GEN_TREES_H */
  104.38 +
  104.39 +#include "deflate.h"
  104.40 +
  104.41 +#ifdef DEBUG
  104.42 +#  include <ctype.h>
  104.43 +#endif
  104.44 +
  104.45 +/* ===========================================================================
  104.46 + * Constants
  104.47 + */
  104.48 +
  104.49 +#define MAX_BL_BITS 7
  104.50 +/* Bit length codes must not exceed MAX_BL_BITS bits */
  104.51 +
  104.52 +#define END_BLOCK 256
  104.53 +/* end of block literal code */
  104.54 +
  104.55 +#define REP_3_6      16
  104.56 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */
  104.57 +
  104.58 +#define REPZ_3_10    17
  104.59 +/* repeat a zero length 3-10 times  (3 bits of repeat count) */
  104.60 +
  104.61 +#define REPZ_11_138  18
  104.62 +/* repeat a zero length 11-138 times  (7 bits of repeat count) */
  104.63 +
  104.64 +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  104.65 +   = {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};
  104.66 +
  104.67 +local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  104.68 +   = {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};
  104.69 +
  104.70 +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  104.71 +   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  104.72 +
  104.73 +local const uch bl_order[BL_CODES]
  104.74 +   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  104.75 +/* The lengths of the bit length codes are sent in order of decreasing
  104.76 + * probability, to avoid transmitting the lengths for unused bit length codes.
  104.77 + */
  104.78 +
  104.79 +#define Buf_size (8 * 2*sizeof(char))
  104.80 +/* Number of bits used within bi_buf. (bi_buf might be implemented on
  104.81 + * more than 16 bits on some systems.)
  104.82 + */
  104.83 +
  104.84 +/* ===========================================================================
  104.85 + * Local data. These are initialized only once.
  104.86 + */
  104.87 +
  104.88 +#define DIST_CODE_LEN  512 /* see definition of array dist_code below */
  104.89 +
  104.90 +#if defined(GEN_TREES_H) || !defined(STDC)
  104.91 +/* non ANSI compilers may not accept trees.h */
  104.92 +
  104.93 +local ct_data static_ltree[L_CODES+2];
  104.94 +/* The static literal tree. Since the bit lengths are imposed, there is no
  104.95 + * need for the L_CODES extra codes used during heap construction. However
  104.96 + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  104.97 + * below).
  104.98 + */
  104.99 +
 104.100 +local ct_data static_dtree[D_CODES];
 104.101 +/* The static distance tree. (Actually a trivial tree since all codes use
 104.102 + * 5 bits.)
 104.103 + */
 104.104 +
 104.105 +uch _dist_code[DIST_CODE_LEN];
 104.106 +/* Distance codes. The first 256 values correspond to the distances
 104.107 + * 3 .. 258, the last 256 values correspond to the top 8 bits of
 104.108 + * the 15 bit distances.
 104.109 + */
 104.110 +
 104.111 +uch _length_code[MAX_MATCH-MIN_MATCH+1];
 104.112 +/* length code for each normalized match length (0 == MIN_MATCH) */
 104.113 +
 104.114 +local int base_length[LENGTH_CODES];
 104.115 +/* First normalized length for each code (0 = MIN_MATCH) */
 104.116 +
 104.117 +local int base_dist[D_CODES];
 104.118 +/* First normalized distance for each code (0 = distance of 1) */
 104.119 +
 104.120 +#else
 104.121 +#  include "trees.h"
 104.122 +#endif /* GEN_TREES_H */
 104.123 +
 104.124 +struct static_tree_desc_s {
 104.125 +    const ct_data *static_tree;  /* static tree or NULL */
 104.126 +    const intf *extra_bits;      /* extra bits for each code or NULL */
 104.127 +    int     extra_base;          /* base index for extra_bits */
 104.128 +    int     elems;               /* max number of elements in the tree */
 104.129 +    int     max_length;          /* max bit length for the codes */
 104.130 +};
 104.131 +
 104.132 +local static_tree_desc  static_l_desc =
 104.133 +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
 104.134 +
 104.135 +local static_tree_desc  static_d_desc =
 104.136 +{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
 104.137 +
 104.138 +local static_tree_desc  static_bl_desc =
 104.139 +{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
 104.140 +
 104.141 +/* ===========================================================================
 104.142 + * Local (static) routines in this file.
 104.143 + */
 104.144 +
 104.145 +local void tr_static_init OF((void));
 104.146 +local void init_block     OF((deflate_state *s));
 104.147 +local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
 104.148 +local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
 104.149 +local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
 104.150 +local void build_tree     OF((deflate_state *s, tree_desc *desc));
 104.151 +local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
 104.152 +local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
 104.153 +local int  build_bl_tree  OF((deflate_state *s));
 104.154 +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
 104.155 +                              int blcodes));
 104.156 +local void compress_block OF((deflate_state *s, ct_data *ltree,
 104.157 +                              ct_data *dtree));
 104.158 +local void set_data_type  OF((deflate_state *s));
 104.159 +local unsigned bi_reverse OF((unsigned value, int length));
 104.160 +local void bi_windup      OF((deflate_state *s));
 104.161 +local void bi_flush       OF((deflate_state *s));
 104.162 +local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
 104.163 +                              int header));
 104.164 +
 104.165 +#ifdef GEN_TREES_H
 104.166 +local void gen_trees_header OF((void));
 104.167 +#endif
 104.168 +
 104.169 +#ifndef DEBUG
 104.170 +#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
 104.171 +   /* Send a code of the given tree. c and tree must not have side effects */
 104.172 +
 104.173 +#else /* DEBUG */
 104.174 +#  define send_code(s, c, tree) \
 104.175 +     { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
 104.176 +       send_bits(s, tree[c].Code, tree[c].Len); }
 104.177 +#endif
 104.178 +
 104.179 +/* ===========================================================================
 104.180 + * Output a short LSB first on the stream.
 104.181 + * IN assertion: there is enough room in pendingBuf.
 104.182 + */
 104.183 +#define put_short(s, w) { \
 104.184 +    put_byte(s, (uch)((w) & 0xff)); \
 104.185 +    put_byte(s, (uch)((ush)(w) >> 8)); \
 104.186 +}
 104.187 +
 104.188 +/* ===========================================================================
 104.189 + * Send a value on a given number of bits.
 104.190 + * IN assertion: length <= 16 and value fits in length bits.
 104.191 + */
 104.192 +#ifdef DEBUG
 104.193 +local void send_bits      OF((deflate_state *s, int value, int length));
 104.194 +
 104.195 +local void send_bits(s, value, length)
 104.196 +    deflate_state *s;
 104.197 +    int value;  /* value to send */
 104.198 +    int length; /* number of bits */
 104.199 +{
 104.200 +    Tracevv((stderr," l %2d v %4x ", length, value));
 104.201 +    Assert(length > 0 && length <= 15, "invalid length");
 104.202 +    s->bits_sent += (ulg)length;
 104.203 +
 104.204 +    /* If not enough room in bi_buf, use (valid) bits from bi_buf and
 104.205 +     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
 104.206 +     * unused bits in value.
 104.207 +     */
 104.208 +    if (s->bi_valid > (int)Buf_size - length) {
 104.209 +        s->bi_buf |= (value << s->bi_valid);
 104.210 +        put_short(s, s->bi_buf);
 104.211 +        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
 104.212 +        s->bi_valid += length - Buf_size;
 104.213 +    } else {
 104.214 +        s->bi_buf |= value << s->bi_valid;
 104.215 +        s->bi_valid += length;
 104.216 +    }
 104.217 +}
 104.218 +#else /* !DEBUG */
 104.219 +
 104.220 +#define send_bits(s, value, length) \
 104.221 +{ int len = length;\
 104.222 +  if (s->bi_valid > (int)Buf_size - len) {\
 104.223 +    int val = value;\
 104.224 +    s->bi_buf |= (val << s->bi_valid);\
 104.225 +    put_short(s, s->bi_buf);\
 104.226 +    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
 104.227 +    s->bi_valid += len - Buf_size;\
 104.228 +  } else {\
 104.229 +    s->bi_buf |= (value) << s->bi_valid;\
 104.230 +    s->bi_valid += len;\
 104.231 +  }\
 104.232 +}
 104.233 +#endif /* DEBUG */
 104.234 +
 104.235 +
 104.236 +/* the arguments must not have side effects */
 104.237 +
 104.238 +/* ===========================================================================
 104.239 + * Initialize the various 'constant' tables.
 104.240 + */
 104.241 +local void tr_static_init()
 104.242 +{
 104.243 +#if defined(GEN_TREES_H) || !defined(STDC)
 104.244 +    static int static_init_done = 0;
 104.245 +    int n;        /* iterates over tree elements */
 104.246 +    int bits;     /* bit counter */
 104.247 +    int length;   /* length value */
 104.248 +    int code;     /* code value */
 104.249 +    int dist;     /* distance index */
 104.250 +    ush bl_count[MAX_BITS+1];
 104.251 +    /* number of codes at each bit length for an optimal tree */
 104.252 +
 104.253 +    if (static_init_done) return;
 104.254 +
 104.255 +    /* For some embedded targets, global variables are not initialized: */
 104.256 +    static_l_desc.static_tree = static_ltree;
 104.257 +    static_l_desc.extra_bits = extra_lbits;
 104.258 +    static_d_desc.static_tree = static_dtree;
 104.259 +    static_d_desc.extra_bits = extra_dbits;
 104.260 +    static_bl_desc.extra_bits = extra_blbits;
 104.261 +
 104.262 +    /* Initialize the mapping length (0..255) -> length code (0..28) */
 104.263 +    length = 0;
 104.264 +    for (code = 0; code < LENGTH_CODES-1; code++) {
 104.265 +        base_length[code] = length;
 104.266 +        for (n = 0; n < (1<<extra_lbits[code]); n++) {
 104.267 +            _length_code[length++] = (uch)code;
 104.268 +        }
 104.269 +    }
 104.270 +    Assert (length == 256, "tr_static_init: length != 256");
 104.271 +    /* Note that the length 255 (match length 258) can be represented
 104.272 +     * in two different ways: code 284 + 5 bits or code 285, so we
 104.273 +     * overwrite length_code[255] to use the best encoding:
 104.274 +     */
 104.275 +    _length_code[length-1] = (uch)code;
 104.276 +
 104.277 +    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
 104.278 +    dist = 0;
 104.279 +    for (code = 0 ; code < 16; code++) {
 104.280 +        base_dist[code] = dist;
 104.281 +        for (n = 0; n < (1<<extra_dbits[code]); n++) {
 104.282 +            _dist_code[dist++] = (uch)code;
 104.283 +        }
 104.284 +    }
 104.285 +    Assert (dist == 256, "tr_static_init: dist != 256");
 104.286 +    dist >>= 7; /* from now on, all distances are divided by 128 */
 104.287 +    for ( ; code < D_CODES; code++) {
 104.288 +        base_dist[code] = dist << 7;
 104.289 +        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
 104.290 +            _dist_code[256 + dist++] = (uch)code;
 104.291 +        }
 104.292 +    }
 104.293 +    Assert (dist == 256, "tr_static_init: 256+dist != 512");
 104.294 +
 104.295 +    /* Construct the codes of the static literal tree */
 104.296 +    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
 104.297 +    n = 0;
 104.298 +    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
 104.299 +    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
 104.300 +    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
 104.301 +    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
 104.302 +    /* Codes 286 and 287 do not exist, but we must include them in the
 104.303 +     * tree construction to get a canonical Huffman tree (longest code
 104.304 +     * all ones)
 104.305 +     */
 104.306 +    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
 104.307 +
 104.308 +    /* The static distance tree is trivial: */
 104.309 +    for (n = 0; n < D_CODES; n++) {
 104.310 +        static_dtree[n].Len = 5;
 104.311 +        static_dtree[n].Code = bi_reverse((unsigned)n, 5);
 104.312 +    }
 104.313 +    static_init_done = 1;
 104.314 +
 104.315 +#  ifdef GEN_TREES_H
 104.316 +    gen_trees_header();
 104.317 +#  endif
 104.318 +#endif /* defined(GEN_TREES_H) || !defined(STDC) */
 104.319 +}
 104.320 +
 104.321 +/* ===========================================================================
 104.322 + * Genererate the file trees.h describing the static trees.
 104.323 + */
 104.324 +#ifdef GEN_TREES_H
 104.325 +#  ifndef DEBUG
 104.326 +#    include <stdio.h>
 104.327 +#  endif
 104.328 +
 104.329 +#  define SEPARATOR(i, last, width) \
 104.330 +      ((i) == (last)? "\n};\n\n" :    \
 104.331 +       ((i) % (width) == (width)-1 ? ",\n" : ", "))
 104.332 +
 104.333 +void gen_trees_header()
 104.334 +{
 104.335 +    FILE *header = fopen("trees.h", "w");
 104.336 +    int i;
 104.337 +
 104.338 +    Assert (header != NULL, "Can't open trees.h");
 104.339 +    fprintf(header,
 104.340 +            "/* header created automatically with -DGEN_TREES_H */\n\n");
 104.341 +
 104.342 +    fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
 104.343 +    for (i = 0; i < L_CODES+2; i++) {
 104.344 +        fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
 104.345 +                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
 104.346 +    }
 104.347 +
 104.348 +    fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
 104.349 +    for (i = 0; i < D_CODES; i++) {
 104.350 +        fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
 104.351 +                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
 104.352 +    }
 104.353 +
 104.354 +    fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
 104.355 +    for (i = 0; i < DIST_CODE_LEN; i++) {
 104.356 +        fprintf(header, "%2u%s", _dist_code[i],
 104.357 +                SEPARATOR(i, DIST_CODE_LEN-1, 20));
 104.358 +    }
 104.359 +
 104.360 +    fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
 104.361 +    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
 104.362 +        fprintf(header, "%2u%s", _length_code[i],
 104.363 +                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
 104.364 +    }
 104.365 +
 104.366 +    fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
 104.367 +    for (i = 0; i < LENGTH_CODES; i++) {
 104.368 +        fprintf(header, "%1u%s", base_length[i],
 104.369 +                SEPARATOR(i, LENGTH_CODES-1, 20));
 104.370 +    }
 104.371 +
 104.372 +    fprintf(header, "local const int base_dist[D_CODES] = {\n");
 104.373 +    for (i = 0; i < D_CODES; i++) {
 104.374 +        fprintf(header, "%5u%s", base_dist[i],
 104.375 +                SEPARATOR(i, D_CODES-1, 10));
 104.376 +    }
 104.377 +
 104.378 +    fclose(header);
 104.379 +}
 104.380 +#endif /* GEN_TREES_H */
 104.381 +
 104.382 +/* ===========================================================================
 104.383 + * Initialize the tree data structures for a new zlib stream.
 104.384 + */
 104.385 +void _tr_init(s)
 104.386 +    deflate_state *s;
 104.387 +{
 104.388 +    tr_static_init();
 104.389 +
 104.390 +    s->l_desc.dyn_tree = s->dyn_ltree;
 104.391 +    s->l_desc.stat_desc = &static_l_desc;
 104.392 +
 104.393 +    s->d_desc.dyn_tree = s->dyn_dtree;
 104.394 +    s->d_desc.stat_desc = &static_d_desc;
 104.395 +
 104.396 +    s->bl_desc.dyn_tree = s->bl_tree;
 104.397 +    s->bl_desc.stat_desc = &static_bl_desc;
 104.398 +
 104.399 +    s->bi_buf = 0;
 104.400 +    s->bi_valid = 0;
 104.401 +    s->last_eob_len = 8; /* enough lookahead for inflate */
 104.402 +#ifdef DEBUG
 104.403 +    s->compressed_len = 0L;
 104.404 +    s->bits_sent = 0L;
 104.405 +#endif
 104.406 +
 104.407 +    /* Initialize the first block of the first file: */
 104.408 +    init_block(s);
 104.409 +}
 104.410 +
 104.411 +/* ===========================================================================
 104.412 + * Initialize a new block.
 104.413 + */
 104.414 +local void init_block(s)
 104.415 +    deflate_state *s;
 104.416 +{
 104.417 +    int n; /* iterates over tree elements */
 104.418 +
 104.419 +    /* Initialize the trees. */
 104.420 +    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
 104.421 +    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
 104.422 +    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
 104.423 +
 104.424 +    s->dyn_ltree[END_BLOCK].Freq = 1;
 104.425 +    s->opt_len = s->static_len = 0L;
 104.426 +    s->last_lit = s->matches = 0;
 104.427 +}
 104.428 +
 104.429 +#define SMALLEST 1
 104.430 +/* Index within the heap array of least frequent node in the Huffman tree */
 104.431 +
 104.432 +
 104.433 +/* ===========================================================================
 104.434 + * Remove the smallest element from the heap and recreate the heap with
 104.435 + * one less element. Updates heap and heap_len.
 104.436 + */
 104.437 +#define pqremove(s, tree, top) \
 104.438 +{\
 104.439 +    top = s->heap[SMALLEST]; \
 104.440 +    s->heap[SMALLEST] = s->heap[s->heap_len--]; \
 104.441 +    pqdownheap(s, tree, SMALLEST); \
 104.442 +}
 104.443 +
 104.444 +/* ===========================================================================
 104.445 + * Compares to subtrees, using the tree depth as tie breaker when
 104.446 + * the subtrees have equal frequency. This minimizes the worst case length.
 104.447 + */
 104.448 +#define smaller(tree, n, m, depth) \
 104.449 +   (tree[n].Freq < tree[m].Freq || \
 104.450 +   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
 104.451 +
 104.452 +/* ===========================================================================
 104.453 + * Restore the heap property by moving down the tree starting at node k,
 104.454 + * exchanging a node with the smallest of its two sons if necessary, stopping
 104.455 + * when the heap property is re-established (each father smaller than its
 104.456 + * two sons).
 104.457 + */
 104.458 +local void pqdownheap(s, tree, k)
 104.459 +    deflate_state *s;
 104.460 +    ct_data *tree;  /* the tree to restore */
 104.461 +    int k;               /* node to move down */
 104.462 +{
 104.463 +    int v = s->heap[k];
 104.464 +    int j = k << 1;  /* left son of k */
 104.465 +    while (j <= s->heap_len) {
 104.466 +        /* Set j to the smallest of the two sons: */
 104.467 +        if (j < s->heap_len &&
 104.468 +            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
 104.469 +            j++;
 104.470 +        }
 104.471 +        /* Exit if v is smaller than both sons */
 104.472 +        if (smaller(tree, v, s->heap[j], s->depth)) break;
 104.473 +
 104.474 +        /* Exchange v with the smallest son */
 104.475 +        s->heap[k] = s->heap[j];  k = j;
 104.476 +
 104.477 +        /* And continue down the tree, setting j to the left son of k */
 104.478 +        j <<= 1;
 104.479 +    }
 104.480 +    s->heap[k] = v;
 104.481 +}
 104.482 +
 104.483 +/* ===========================================================================
 104.484 + * Compute the optimal bit lengths for a tree and update the total bit length
 104.485 + * for the current block.
 104.486 + * IN assertion: the fields freq and dad are set, heap[heap_max] and
 104.487 + *    above are the tree nodes sorted by increasing frequency.
 104.488 + * OUT assertions: the field len is set to the optimal bit length, the
 104.489 + *     array bl_count contains the frequencies for each bit length.
 104.490 + *     The length opt_len is updated; static_len is also updated if stree is
 104.491 + *     not null.
 104.492 + */
 104.493 +local void gen_bitlen(s, desc)
 104.494 +    deflate_state *s;
 104.495 +    tree_desc *desc;    /* the tree descriptor */
 104.496 +{
 104.497 +    ct_data *tree        = desc->dyn_tree;
 104.498 +    int max_code         = desc->max_code;
 104.499 +    const ct_data *stree = desc->stat_desc->static_tree;
 104.500 +    const intf *extra    = desc->stat_desc->extra_bits;
 104.501 +    int base             = desc->stat_desc->extra_base;
 104.502 +    int max_length       = desc->stat_desc->max_length;
 104.503 +    int h;              /* heap index */
 104.504 +    int n, m;           /* iterate over the tree elements */
 104.505 +    int bits;           /* bit length */
 104.506 +    int xbits;          /* extra bits */
 104.507 +    ush f;              /* frequency */
 104.508 +    int overflow = 0;   /* number of elements with bit length too large */
 104.509 +
 104.510 +    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
 104.511 +
 104.512 +    /* In a first pass, compute the optimal bit lengths (which may
 104.513 +     * overflow in the case of the bit length tree).
 104.514 +     */
 104.515 +    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
 104.516 +
 104.517 +    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
 104.518 +        n = s->heap[h];
 104.519 +        bits = tree[tree[n].Dad].Len + 1;
 104.520 +        if (bits > max_length) bits = max_length, overflow++;
 104.521 +        tree[n].Len = (ush)bits;
 104.522 +        /* We overwrite tree[n].Dad which is no longer needed */
 104.523 +
 104.524 +        if (n > max_code) continue; /* not a leaf node */
 104.525 +
 104.526 +        s->bl_count[bits]++;
 104.527 +        xbits = 0;
 104.528 +        if (n >= base) xbits = extra[n-base];
 104.529 +        f = tree[n].Freq;
 104.530 +        s->opt_len += (ulg)f * (bits + xbits);
 104.531 +        if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
 104.532 +    }
 104.533 +    if (overflow == 0) return;
 104.534 +
 104.535 +    Trace((stderr,"\nbit length overflow\n"));
 104.536 +    /* This happens for example on obj2 and pic of the Calgary corpus */
 104.537 +
 104.538 +    /* Find the first bit length which could increase: */
 104.539 +    do {
 104.540 +        bits = max_length-1;
 104.541 +        while (s->bl_count[bits] == 0) bits--;
 104.542 +        s->bl_count[bits]--;      /* move one leaf down the tree */
 104.543 +        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
 104.544 +        s->bl_count[max_length]--;
 104.545 +        /* The brother of the overflow item also moves one step up,
 104.546 +         * but this does not affect bl_count[max_length]
 104.547 +         */
 104.548 +        overflow -= 2;
 104.549 +    } while (overflow > 0);
 104.550 +
 104.551 +    /* Now recompute all bit lengths, scanning in increasing frequency.
 104.552 +     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
 104.553 +     * lengths instead of fixing only the wrong ones. This idea is taken
 104.554 +     * from 'ar' written by Haruhiko Okumura.)
 104.555 +     */
 104.556 +    for (bits = max_length; bits != 0; bits--) {
 104.557 +        n = s->bl_count[bits];
 104.558 +        while (n != 0) {
 104.559 +            m = s->heap[--h];
 104.560 +            if (m > max_code) continue;
 104.561 +            if ((unsigned) tree[m].Len != (unsigned) bits) {
 104.562 +                Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
 104.563 +                s->opt_len += ((long)bits - (long)tree[m].Len)
 104.564 +                              *(long)tree[m].Freq;
 104.565 +                tree[m].Len = (ush)bits;
 104.566 +            }
 104.567 +            n--;
 104.568 +        }
 104.569 +    }
 104.570 +}
 104.571 +
 104.572 +/* ===========================================================================
 104.573 + * Generate the codes for a given tree and bit counts (which need not be
 104.574 + * optimal).
 104.575 + * IN assertion: the array bl_count contains the bit length statistics for
 104.576 + * the given tree and the field len is set for all tree elements.
 104.577 + * OUT assertion: the field code is set for all tree elements of non
 104.578 + *     zero code length.
 104.579 + */
 104.580 +local void gen_codes (tree, max_code, bl_count)
 104.581 +    ct_data *tree;             /* the tree to decorate */
 104.582 +    int max_code;              /* largest code with non zero frequency */
 104.583 +    ushf *bl_count;            /* number of codes at each bit length */
 104.584 +{
 104.585 +    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
 104.586 +    ush code = 0;              /* running code value */
 104.587 +    int bits;                  /* bit index */
 104.588 +    int n;                     /* code index */
 104.589 +
 104.590 +    /* The distribution counts are first used to generate the code values
 104.591 +     * without bit reversal.
 104.592 +     */
 104.593 +    for (bits = 1; bits <= MAX_BITS; bits++) {
 104.594 +        next_code[bits] = code = (code + bl_count[bits-1]) << 1;
 104.595 +    }
 104.596 +    /* Check that the bit counts in bl_count are consistent. The last code
 104.597 +     * must be all ones.
 104.598 +     */
 104.599 +    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
 104.600 +            "inconsistent bit counts");
 104.601 +    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
 104.602 +
 104.603 +    for (n = 0;  n <= max_code; n++) {
 104.604 +        int len = tree[n].Len;
 104.605 +        if (len == 0) continue;
 104.606 +        /* Now reverse the bits */
 104.607 +        tree[n].Code = bi_reverse(next_code[len]++, len);
 104.608 +
 104.609 +        Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
 104.610 +             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
 104.611 +    }
 104.612 +}
 104.613 +
 104.614 +/* ===========================================================================
 104.615 + * Construct one Huffman tree and assigns the code bit strings and lengths.
 104.616 + * Update the total bit length for the current block.
 104.617 + * IN assertion: the field freq is set for all tree elements.
 104.618 + * OUT assertions: the fields len and code are set to the optimal bit length
 104.619 + *     and corresponding code. The length opt_len is updated; static_len is
 104.620 + *     also updated if stree is not null. The field max_code is set.
 104.621 + */
 104.622 +local void build_tree(s, desc)
 104.623 +    deflate_state *s;
 104.624 +    tree_desc *desc; /* the tree descriptor */
 104.625 +{
 104.626 +    ct_data *tree         = desc->dyn_tree;
 104.627 +    const ct_data *stree  = desc->stat_desc->static_tree;
 104.628 +    int elems             = desc->stat_desc->elems;
 104.629 +    int n, m;          /* iterate over heap elements */
 104.630 +    int max_code = -1; /* largest code with non zero frequency */
 104.631 +    int node;          /* new node being created */
 104.632 +
 104.633 +    /* Construct the initial heap, with least frequent element in
 104.634 +     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
 104.635 +     * heap[0] is not used.
 104.636 +     */
 104.637 +    s->heap_len = 0, s->heap_max = HEAP_SIZE;
 104.638 +
 104.639 +    for (n = 0; n < elems; n++) {
 104.640 +        if (tree[n].Freq != 0) {
 104.641 +            s->heap[++(s->heap_len)] = max_code = n;
 104.642 +            s->depth[n] = 0;
 104.643 +        } else {
 104.644 +            tree[n].Len = 0;
 104.645 +        }
 104.646 +    }
 104.647 +
 104.648 +    /* The pkzip format requires that at least one distance code exists,
 104.649 +     * and that at least one bit should be sent even if there is only one
 104.650 +     * possible code. So to avoid special checks later on we force at least
 104.651 +     * two codes of non zero frequency.
 104.652 +     */
 104.653 +    while (s->heap_len < 2) {
 104.654 +        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
 104.655 +        tree[node].Freq = 1;
 104.656 +        s->depth[node] = 0;
 104.657 +        s->opt_len--; if (stree) s->static_len -= stree[node].Len;
 104.658 +        /* node is 0 or 1 so it does not have extra bits */
 104.659 +    }
 104.660 +    desc->max_code = max_code;
 104.661 +
 104.662 +    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
 104.663 +     * establish sub-heaps of increasing lengths:
 104.664 +     */
 104.665 +    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
 104.666 +
 104.667 +    /* Construct the Huffman tree by repeatedly combining the least two
 104.668 +     * frequent nodes.
 104.669 +     */
 104.670 +    node = elems;              /* next internal node of the tree */
 104.671 +    do {
 104.672 +        pqremove(s, tree, n);  /* n = node of least frequency */
 104.673 +        m = s->heap[SMALLEST]; /* m = node of next least frequency */
 104.674 +
 104.675 +        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
 104.676 +        s->heap[--(s->heap_max)] = m;
 104.677 +
 104.678 +        /* Create a new node father of n and m */
 104.679 +        tree[node].Freq = tree[n].Freq + tree[m].Freq;
 104.680 +        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
 104.681 +                                s->depth[n] : s->depth[m]) + 1);
 104.682 +        tree[n].Dad = tree[m].Dad = (ush)node;
 104.683 +#ifdef DUMP_BL_TREE
 104.684 +        if (tree == s->bl_tree) {
 104.685 +            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
 104.686 +                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
 104.687 +        }
 104.688 +#endif
 104.689 +        /* and insert the new node in the heap */
 104.690 +        s->heap[SMALLEST] = node++;
 104.691 +        pqdownheap(s, tree, SMALLEST);
 104.692 +
 104.693 +    } while (s->heap_len >= 2);
 104.694 +
 104.695 +    s->heap[--(s->heap_max)] = s->heap[SMALLEST];
 104.696 +
 104.697 +    /* At this point, the fields freq and dad are set. We can now
 104.698 +     * generate the bit lengths.
 104.699 +     */
 104.700 +    gen_bitlen(s, (tree_desc *)desc);
 104.701 +
 104.702 +    /* The field len is now set, we can generate the bit codes */
 104.703 +    gen_codes ((ct_data *)tree, max_code, s->bl_count);
 104.704 +}
 104.705 +
 104.706 +/* ===========================================================================
 104.707 + * Scan a literal or distance tree to determine the frequencies of the codes
 104.708 + * in the bit length tree.
 104.709 + */
 104.710 +local void scan_tree (s, tree, max_code)
 104.711 +    deflate_state *s;
 104.712 +    ct_data *tree;   /* the tree to be scanned */
 104.713 +    int max_code;    /* and its largest code of non zero frequency */
 104.714 +{
 104.715 +    int n;                     /* iterates over all tree elements */
 104.716 +    int prevlen = -1;          /* last emitted length */
 104.717 +    int curlen;                /* length of current code */
 104.718 +    int nextlen = tree[0].Len; /* length of next code */
 104.719 +    int count = 0;             /* repeat count of the current code */
 104.720 +    int max_count = 7;         /* max repeat count */
 104.721 +    int min_count = 4;         /* min repeat count */
 104.722 +
 104.723 +    if (nextlen == 0) max_count = 138, min_count = 3;
 104.724 +    tree[max_code+1].Len = (ush)0xffff; /* guard */
 104.725 +
 104.726 +    for (n = 0; n <= max_code; n++) {
 104.727 +        curlen = nextlen; nextlen = tree[n+1].Len;
 104.728 +        if (++count < max_count && curlen == nextlen) {
 104.729 +            continue;
 104.730 +        } else if (count < min_count) {
 104.731 +            s->bl_tree[curlen].Freq += count;
 104.732 +        } else if (curlen != 0) {
 104.733 +            if (curlen != prevlen) s->bl_tree[curlen].Freq++;
 104.734 +            s->bl_tree[REP_3_6].Freq++;
 104.735 +        } else if (count <= 10) {
 104.736 +            s->bl_tree[REPZ_3_10].Freq++;
 104.737 +        } else {
 104.738 +            s->bl_tree[REPZ_11_138].Freq++;
 104.739 +        }
 104.740 +        count = 0; prevlen = curlen;
 104.741 +        if (nextlen == 0) {
 104.742 +            max_count = 138, min_count = 3;
 104.743 +        } else if (curlen == nextlen) {
 104.744 +            max_count = 6, min_count = 3;
 104.745 +        } else {
 104.746 +            max_count = 7, min_count = 4;
 104.747 +        }
 104.748 +    }
 104.749 +}
 104.750 +
 104.751 +/* ===========================================================================
 104.752 + * Send a literal or distance tree in compressed form, using the codes in
 104.753 + * bl_tree.
 104.754 + */
 104.755 +local void send_tree (s, tree, max_code)
 104.756 +    deflate_state *s;
 104.757 +    ct_data *tree; /* the tree to be scanned */
 104.758 +    int max_code;       /* and its largest code of non zero frequency */
 104.759 +{
 104.760 +    int n;                     /* iterates over all tree elements */
 104.761 +    int prevlen = -1;          /* last emitted length */
 104.762 +    int curlen;                /* length of current code */
 104.763 +    int nextlen = tree[0].Len; /* length of next code */
 104.764 +    int count = 0;             /* repeat count of the current code */
 104.765 +    int max_count = 7;         /* max repeat count */
 104.766 +    int min_count = 4;         /* min repeat count */
 104.767 +
 104.768 +    /* tree[max_code+1].Len = -1; */  /* guard already set */
 104.769 +    if (nextlen == 0) max_count = 138, min_count = 3;
 104.770 +
 104.771 +    for (n = 0; n <= max_code; n++) {
 104.772 +        curlen = nextlen; nextlen = tree[n+1].Len;
 104.773 +        if (++count < max_count && curlen == nextlen) {
 104.774 +            continue;
 104.775 +        } else if (count < min_count) {
 104.776 +            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
 104.777 +
 104.778 +        } else if (curlen != 0) {
 104.779 +            if (curlen != prevlen) {
 104.780 +                send_code(s, curlen, s->bl_tree); count--;
 104.781 +            }
 104.782 +            Assert(count >= 3 && count <= 6, " 3_6?");
 104.783 +            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
 104.784 +
 104.785 +        } else if (count <= 10) {
 104.786 +            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
 104.787 +
 104.788 +        } else {
 104.789 +            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
 104.790 +        }
 104.791 +        count = 0; prevlen = curlen;
 104.792 +        if (nextlen == 0) {
 104.793 +            max_count = 138, min_count = 3;
 104.794 +        } else if (curlen == nextlen) {
 104.795 +            max_count = 6, min_count = 3;
 104.796 +        } else {
 104.797 +            max_count = 7, min_count = 4;
 104.798 +        }
 104.799 +    }
 104.800 +}
 104.801 +
 104.802 +/* ===========================================================================
 104.803 + * Construct the Huffman tree for the bit lengths and return the index in
 104.804 + * bl_order of the last bit length code to send.
 104.805 + */
 104.806 +local int build_bl_tree(s)
 104.807 +    deflate_state *s;
 104.808 +{
 104.809 +    int max_blindex;  /* index of last bit length code of non zero freq */
 104.810 +
 104.811 +    /* Determine the bit length frequencies for literal and distance trees */
 104.812 +    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
 104.813 +    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
 104.814 +
 104.815 +    /* Build the bit length tree: */
 104.816 +    build_tree(s, (tree_desc *)(&(s->bl_desc)));
 104.817 +    /* opt_len now includes the length of the tree representations, except
 104.818 +     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
 104.819 +     */
 104.820 +
 104.821 +    /* Determine the number of bit length codes to send. The pkzip format
 104.822 +     * requires that at least 4 bit length codes be sent. (appnote.txt says
 104.823 +     * 3 but the actual value used is 4.)
 104.824 +     */
 104.825 +    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
 104.826 +        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
 104.827 +    }
 104.828 +    /* Update opt_len to include the bit length tree and counts */
 104.829 +    s->opt_len += 3*(max_blindex+1) + 5+5+4;
 104.830 +    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
 104.831 +            s->opt_len, s->static_len));
 104.832 +
 104.833 +    return max_blindex;
 104.834 +}
 104.835 +
 104.836 +/* ===========================================================================
 104.837 + * Send the header for a block using dynamic Huffman trees: the counts, the
 104.838 + * lengths of the bit length codes, the literal tree and the distance tree.
 104.839 + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
 104.840 + */
 104.841 +local void send_all_trees(s, lcodes, dcodes, blcodes)
 104.842 +    deflate_state *s;
 104.843 +    int lcodes, dcodes, blcodes; /* number of codes for each tree */
 104.844 +{
 104.845 +    int rank;                    /* index in bl_order */
 104.846 +
 104.847 +    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
 104.848 +    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
 104.849 +            "too many codes");
 104.850 +    Tracev((stderr, "\nbl counts: "));
 104.851 +    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
 104.852 +    send_bits(s, dcodes-1,   5);
 104.853 +    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
 104.854 +    for (rank = 0; rank < blcodes; rank++) {
 104.855 +        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
 104.856 +        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
 104.857 +    }
 104.858 +    Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
 104.859 +
 104.860 +    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
 104.861 +    Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
 104.862 +
 104.863 +    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
 104.864 +    Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
 104.865 +}
 104.866 +
 104.867 +/* ===========================================================================
 104.868 + * Send a stored block
 104.869 + */
 104.870 +void _tr_stored_block(s, buf, stored_len, eof)
 104.871 +    deflate_state *s;
 104.872 +    charf *buf;       /* input block */
 104.873 +    ulg stored_len;   /* length of input block */
 104.874 +    int eof;          /* true if this is the last block for a file */
 104.875 +{
 104.876 +    send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
 104.877 +#ifdef DEBUG
 104.878 +    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
 104.879 +    s->compressed_len += (stored_len + 4) << 3;
 104.880 +#endif
 104.881 +    copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
 104.882 +}
 104.883 +
 104.884 +/* ===========================================================================
 104.885 + * Send one empty static block to give enough lookahead for inflate.
 104.886 + * This takes 10 bits, of which 7 may remain in the bit buffer.
 104.887 + * The current inflate code requires 9 bits of lookahead. If the
 104.888 + * last two codes for the previous block (real code plus EOB) were coded
 104.889 + * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
 104.890 + * the last real code. In this case we send two empty static blocks instead
 104.891 + * of one. (There are no problems if the previous block is stored or fixed.)
 104.892 + * To simplify the code, we assume the worst case of last real code encoded
 104.893 + * on one bit only.
 104.894 + */
 104.895 +void _tr_align(s)
 104.896 +    deflate_state *s;
 104.897 +{
 104.898 +    send_bits(s, STATIC_TREES<<1, 3);
 104.899 +    send_code(s, END_BLOCK, static_ltree);
 104.900 +#ifdef DEBUG
 104.901 +    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
 104.902 +#endif
 104.903 +    bi_flush(s);
 104.904 +    /* Of the 10 bits for the empty block, we have already sent
 104.905 +     * (10 - bi_valid) bits. The lookahead for the last real code (before
 104.906 +     * the EOB of the previous block) was thus at least one plus the length
 104.907 +     * of the EOB plus what we have just sent of the empty static block.
 104.908 +     */
 104.909 +    if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
 104.910 +        send_bits(s, STATIC_TREES<<1, 3);
 104.911 +        send_code(s, END_BLOCK, static_ltree);
 104.912 +#ifdef DEBUG
 104.913 +        s->compressed_len += 10L;
 104.914 +#endif
 104.915 +        bi_flush(s);
 104.916 +    }
 104.917 +    s->last_eob_len = 7;
 104.918 +}
 104.919 +
 104.920 +/* ===========================================================================
 104.921 + * Determine the best encoding for the current block: dynamic trees, static
 104.922 + * trees or store, and output the encoded block to the zip file.
 104.923 + */
 104.924 +void _tr_flush_block(s, buf, stored_len, eof)
 104.925 +    deflate_state *s;
 104.926 +    charf *buf;       /* input block, or NULL if too old */
 104.927 +    ulg stored_len;   /* length of input block */
 104.928 +    int eof;          /* true if this is the last block for a file */
 104.929 +{
 104.930 +    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
 104.931 +    int max_blindex = 0;  /* index of last bit length code of non zero freq */
 104.932 +
 104.933 +    /* Build the Huffman trees unless a stored block is forced */
 104.934 +    if (s->level > 0) {
 104.935 +
 104.936 +        /* Check if the file is binary or text */
 104.937 +        if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
 104.938 +            set_data_type(s);
 104.939 +
 104.940 +        /* Construct the literal and distance trees */
 104.941 +        build_tree(s, (tree_desc *)(&(s->l_desc)));
 104.942 +        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
 104.943 +                s->static_len));
 104.944 +
 104.945 +        build_tree(s, (tree_desc *)(&(s->d_desc)));
 104.946 +        Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
 104.947 +                s->static_len));
 104.948 +        /* At this point, opt_len and static_len are the total bit lengths of
 104.949 +         * the compressed block data, excluding the tree representations.
 104.950 +         */
 104.951 +
 104.952 +        /* Build the bit length tree for the above two trees, and get the index
 104.953 +         * in bl_order of the last bit length code to send.
 104.954 +         */
 104.955 +        max_blindex = build_bl_tree(s);
 104.956 +
 104.957 +        /* Determine the best encoding. Compute the block lengths in bytes. */
 104.958 +        opt_lenb = (s->opt_len+3+7)>>3;
 104.959 +        static_lenb = (s->static_len+3+7)>>3;
 104.960 +
 104.961 +        Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
 104.962 +                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
 104.963 +                s->last_lit));
 104.964 +
 104.965 +        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
 104.966 +
 104.967 +    } else {
 104.968 +        Assert(buf != (char*)0, "lost buf");
 104.969 +        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
 104.970 +    }
 104.971 +
 104.972 +#ifdef FORCE_STORED
 104.973 +    if (buf != (char*)0) { /* force stored block */
 104.974 +#else
 104.975 +    if (stored_len+4 <= opt_lenb && buf != (char*)0) {
 104.976 +                       /* 4: two words for the lengths */
 104.977 +#endif
 104.978 +        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
 104.979 +         * Otherwise we can't have processed more than WSIZE input bytes since
 104.980 +         * the last block flush, because compression would have been
 104.981 +         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
 104.982 +         * transform a block into a stored block.
 104.983 +         */
 104.984 +        _tr_stored_block(s, buf, stored_len, eof);
 104.985 +
 104.986 +#ifdef FORCE_STATIC
 104.987 +    } else if (static_lenb >= 0) { /* force static trees */
 104.988 +#else
 104.989 +    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
 104.990 +#endif
 104.991 +        send_bits(s, (STATIC_TREES<<1)+eof, 3);
 104.992 +        compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
 104.993 +#ifdef DEBUG
 104.994 +        s->compressed_len += 3 + s->static_len;
 104.995 +#endif
 104.996 +    } else {
 104.997 +        send_bits(s, (DYN_TREES<<1)+eof, 3);
 104.998 +        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
 104.999 +                       max_blindex+1);
104.1000 +        compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
104.1001 +#ifdef DEBUG
104.1002 +        s->compressed_len += 3 + s->opt_len;
104.1003 +#endif
104.1004 +    }
104.1005 +    Assert (s->compressed_len == s->bits_sent, "bad compressed size");
104.1006 +    /* The above check is made mod 2^32, for files larger than 512 MB
104.1007 +     * and uLong implemented on 32 bits.
104.1008 +     */
104.1009 +    init_block(s);
104.1010 +
104.1011 +    if (eof) {
104.1012 +        bi_windup(s);
104.1013 +#ifdef DEBUG
104.1014 +        s->compressed_len += 7;  /* align on byte boundary */
104.1015 +#endif
104.1016 +    }
104.1017 +    Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
104.1018 +           s->compressed_len-7*eof));
104.1019 +}
104.1020 +
104.1021 +/* ===========================================================================
104.1022 + * Save the match info and tally the frequency counts. Return true if
104.1023 + * the current block must be flushed.
104.1024 + */
104.1025 +int _tr_tally (s, dist, lc)
104.1026 +    deflate_state *s;
104.1027 +    unsigned dist;  /* distance of matched string */
104.1028 +    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
104.1029 +{
104.1030 +    s->d_buf[s->last_lit] = (ush)dist;
104.1031 +    s->l_buf[s->last_lit++] = (uch)lc;
104.1032 +    if (dist == 0) {
104.1033 +        /* lc is the unmatched char */
104.1034 +        s->dyn_ltree[lc].Freq++;
104.1035 +    } else {
104.1036 +        s->matches++;
104.1037 +        /* Here, lc is the match length - MIN_MATCH */
104.1038 +        dist--;             /* dist = match distance - 1 */
104.1039 +        Assert((ush)dist < (ush)MAX_DIST(s) &&
104.1040 +               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
104.1041 +               (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
104.1042 +
104.1043 +        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
104.1044 +        s->dyn_dtree[d_code(dist)].Freq++;
104.1045 +    }
104.1046 +
104.1047 +#ifdef TRUNCATE_BLOCK
104.1048 +    /* Try to guess if it is profitable to stop the current block here */
104.1049 +    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
104.1050 +        /* Compute an upper bound for the compressed length */
104.1051 +        ulg out_length = (ulg)s->last_lit*8L;
104.1052 +        ulg in_length = (ulg)((long)s->strstart - s->block_start);
104.1053 +        int dcode;
104.1054 +        for (dcode = 0; dcode < D_CODES; dcode++) {
104.1055 +            out_length += (ulg)s->dyn_dtree[dcode].Freq *
104.1056 +                (5L+extra_dbits[dcode]);
104.1057 +        }
104.1058 +        out_length >>= 3;
104.1059 +        Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
104.1060 +               s->last_lit, in_length, out_length,
104.1061 +               100L - out_length*100L/in_length));
104.1062 +        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
104.1063 +    }
104.1064 +#endif
104.1065 +    return (s->last_lit == s->lit_bufsize-1);
104.1066 +    /* We avoid equality with lit_bufsize because of wraparound at 64K
104.1067 +     * on 16 bit machines and because stored blocks are restricted to
104.1068 +     * 64K-1 bytes.
104.1069 +     */
104.1070 +}
104.1071 +
104.1072 +/* ===========================================================================
104.1073 + * Send the block data compressed using the given Huffman trees
104.1074 + */
104.1075 +local void compress_block(s, ltree, dtree)
104.1076 +    deflate_state *s;
104.1077 +    ct_data *ltree; /* literal tree */
104.1078 +    ct_data *dtree; /* distance tree */
104.1079 +{
104.1080 +    unsigned dist;      /* distance of matched string */
104.1081 +    int lc;             /* match length or unmatched char (if dist == 0) */
104.1082 +    unsigned lx = 0;    /* running index in l_buf */
104.1083 +    unsigned code;      /* the code to send */
104.1084 +    int extra;          /* number of extra bits to send */
104.1085 +
104.1086 +    if (s->last_lit != 0) do {
104.1087 +        dist = s->d_buf[lx];
104.1088 +        lc = s->l_buf[lx++];
104.1089 +        if (dist == 0) {
104.1090 +            send_code(s, lc, ltree); /* send a literal byte */
104.1091 +            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
104.1092 +        } else {
104.1093 +            /* Here, lc is the match length - MIN_MATCH */
104.1094 +            code = _length_code[lc];
104.1095 +            send_code(s, code+LITERALS+1, ltree); /* send the length code */
104.1096 +            extra = extra_lbits[code];
104.1097 +            if (extra != 0) {
104.1098 +                lc -= base_length[code];
104.1099 +                send_bits(s, lc, extra);       /* send the extra length bits */
104.1100 +            }
104.1101 +            dist--; /* dist is now the match distance - 1 */
104.1102 +            code = d_code(dist);
104.1103 +            Assert (code < D_CODES, "bad d_code");
104.1104 +
104.1105 +            send_code(s, code, dtree);       /* send the distance code */
104.1106 +            extra = extra_dbits[code];
104.1107 +            if (extra != 0) {
104.1108 +                dist -= base_dist[code];
104.1109 +                send_bits(s, dist, extra);   /* send the extra distance bits */
104.1110 +            }
104.1111 +        } /* literal or match pair ? */
104.1112 +
104.1113 +        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
104.1114 +        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
104.1115 +               "pendingBuf overflow");
104.1116 +
104.1117 +    } while (lx < s->last_lit);
104.1118 +
104.1119 +    send_code(s, END_BLOCK, ltree);
104.1120 +    s->last_eob_len = ltree[END_BLOCK].Len;
104.1121 +}
104.1122 +
104.1123 +/* ===========================================================================
104.1124 + * Set the data type to BINARY or TEXT, using a crude approximation:
104.1125 + * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
104.1126 + * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
104.1127 + * IN assertion: the fields Freq of dyn_ltree are set.
104.1128 + */
104.1129 +local void set_data_type(s)
104.1130 +    deflate_state *s;
104.1131 +{
104.1132 +    int n;
104.1133 +
104.1134 +    for (n = 0; n < 9; n++)
104.1135 +        if (s->dyn_ltree[n].Freq != 0)
104.1136 +            break;
104.1137 +    if (n == 9)
104.1138 +        for (n = 14; n < 32; n++)
104.1139 +            if (s->dyn_ltree[n].Freq != 0)
104.1140 +                break;
104.1141 +    s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
104.1142 +}
104.1143 +
104.1144 +/* ===========================================================================
104.1145 + * Reverse the first len bits of a code, using straightforward code (a faster
104.1146 + * method would use a table)
104.1147 + * IN assertion: 1 <= len <= 15
104.1148 + */
104.1149 +local unsigned bi_reverse(code, len)
104.1150 +    unsigned code; /* the value to invert */
104.1151 +    int len;       /* its bit length */
104.1152 +{
104.1153 +    register unsigned res = 0;
104.1154 +    do {
104.1155 +        res |= code & 1;
104.1156 +        code >>= 1, res <<= 1;
104.1157 +    } while (--len > 0);
104.1158 +    return res >> 1;
104.1159 +}
104.1160 +
104.1161 +/* ===========================================================================
104.1162 + * Flush the bit buffer, keeping at most 7 bits in it.
104.1163 + */
104.1164 +local void bi_flush(s)
104.1165 +    deflate_state *s;
104.1166 +{
104.1167 +    if (s->bi_valid == 16) {
104.1168 +        put_short(s, s->bi_buf);
104.1169 +        s->bi_buf = 0;
104.1170 +        s->bi_valid = 0;
104.1171 +    } else if (s->bi_valid >= 8) {
104.1172 +        put_byte(s, (Byte)s->bi_buf);
104.1173 +        s->bi_buf >>= 8;
104.1174 +        s->bi_valid -= 8;
104.1175 +    }
104.1176 +}
104.1177 +
104.1178 +/* ===========================================================================
104.1179 + * Flush the bit buffer and align the output on a byte boundary
104.1180 + */
104.1181 +local void bi_windup(s)
104.1182 +    deflate_state *s;
104.1183 +{
104.1184 +    if (s->bi_valid > 8) {
104.1185 +        put_short(s, s->bi_buf);
104.1186 +    } else if (s->bi_valid > 0) {
104.1187 +        put_byte(s, (Byte)s->bi_buf);
104.1188 +    }
104.1189 +    s->bi_buf = 0;
104.1190 +    s->bi_valid = 0;
104.1191 +#ifdef DEBUG
104.1192 +    s->bits_sent = (s->bits_sent+7) & ~7;
104.1193 +#endif
104.1194 +}
104.1195 +
104.1196 +/* ===========================================================================
104.1197 + * Copy a stored block, storing first the length and its
104.1198 + * one's complement if requested.
104.1199 + */
104.1200 +local void copy_block(s, buf, len, header)
104.1201 +    deflate_state *s;
104.1202 +    charf    *buf;    /* the input data */
104.1203 +    unsigned len;     /* its length */
104.1204 +    int      header;  /* true if block header must be written */
104.1205 +{
104.1206 +    bi_windup(s);        /* align on byte boundary */
104.1207 +    s->last_eob_len = 8; /* enough lookahead for inflate */
104.1208 +
104.1209 +    if (header) {
104.1210 +        put_short(s, (ush)len);
104.1211 +        put_short(s, (ush)~len);
104.1212 +#ifdef DEBUG
104.1213 +        s->bits_sent += 2*16;
104.1214 +#endif
104.1215 +    }
104.1216 +#ifdef DEBUG
104.1217 +    s->bits_sent += (ulg)len<<3;
104.1218 +#endif
104.1219 +    while (len--) {
104.1220 +        put_byte(s, *buf++);
104.1221 +    }
104.1222 +}
   105.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   105.2 +++ b/libs/zlib/trees.h	Thu Sep 08 06:28:38 2011 +0300
   105.3 @@ -0,0 +1,128 @@
   105.4 +/* header created automatically with -DGEN_TREES_H */
   105.5 +
   105.6 +local const ct_data static_ltree[L_CODES+2] = {
   105.7 +{{ 12},{  8}}, {{140},{  8}}, {{ 76},{  8}}, {{204},{  8}}, {{ 44},{  8}},
   105.8 +{{172},{  8}}, {{108},{  8}}, {{236},{  8}}, {{ 28},{  8}}, {{156},{  8}},
   105.9 +{{ 92},{  8}}, {{220},{  8}}, {{ 60},{  8}}, {{188},{  8}}, {{124},{  8}},
  105.10 +{{252},{  8}}, {{  2},{  8}}, {{130},{  8}}, {{ 66},{  8}}, {{194},{  8}},
  105.11 +{{ 34},{  8}}, {{162},{  8}}, {{ 98},{  8}}, {{226},{  8}}, {{ 18},{  8}},
  105.12 +{{146},{  8}}, {{ 82},{  8}}, {{210},{  8}}, {{ 50},{  8}}, {{178},{  8}},
  105.13 +{{114},{  8}}, {{242},{  8}}, {{ 10},{  8}}, {{138},{  8}}, {{ 74},{  8}},
  105.14 +{{202},{  8}}, {{ 42},{  8}}, {{170},{  8}}, {{106},{  8}}, {{234},{  8}},
  105.15 +{{ 26},{  8}}, {{154},{  8}}, {{ 90},{  8}}, {{218},{  8}}, {{ 58},{  8}},
  105.16 +{{186},{  8}}, {{122},{  8}}, {{250},{  8}}, {{  6},{  8}}, {{134},{  8}},
  105.17 +{{ 70},{  8}}, {{198},{  8}}, {{ 38},{  8}}, {{166},{  8}}, {{102},{  8}},
  105.18 +{{230},{  8}}, {{ 22},{  8}}, {{150},{  8}}, {{ 86},{  8}}, {{214},{  8}},
  105.19 +{{ 54},{  8}}, {{182},{  8}}, {{118},{  8}}, {{246},{  8}}, {{ 14},{  8}},
  105.20 +{{142},{  8}}, {{ 78},{  8}}, {{206},{  8}}, {{ 46},{  8}}, {{174},{  8}},
  105.21 +{{110},{  8}}, {{238},{  8}}, {{ 30},{  8}}, {{158},{  8}}, {{ 94},{  8}},
  105.22 +{{222},{  8}}, {{ 62},{  8}}, {{190},{  8}}, {{126},{  8}}, {{254},{  8}},
  105.23 +{{  1},{  8}}, {{129},{  8}}, {{ 65},{  8}}, {{193},{  8}}, {{ 33},{  8}},
  105.24 +{{161},{  8}}, {{ 97},{  8}}, {{225},{  8}}, {{ 17},{  8}}, {{145},{  8}},
  105.25 +{{ 81},{  8}}, {{209},{  8}}, {{ 49},{  8}}, {{177},{  8}}, {{113},{  8}},
  105.26 +{{241},{  8}}, {{  9},{  8}}, {{137},{  8}}, {{ 73},{  8}}, {{201},{  8}},
  105.27 +{{ 41},{  8}}, {{169},{  8}}, {{105},{  8}}, {{233},{  8}}, {{ 25},{  8}},
  105.28 +{{153},{  8}}, {{ 89},{  8}}, {{217},{  8}}, {{ 57},{  8}}, {{185},{  8}},
  105.29 +{{121},{  8}}, {{249},{  8}}, {{  5},{  8}}, {{133},{  8}}, {{ 69},{  8}},
  105.30 +{{197},{  8}}, {{ 37},{  8}}, {{165},{  8}}, {{101},{  8}}, {{229},{  8}},
  105.31 +{{ 21},{  8}}, {{149},{  8}}, {{ 85},{  8}}, {{213},{  8}}, {{ 53},{  8}},
  105.32 +{{181},{  8}}, {{117},{  8}}, {{245},{  8}}, {{ 13},{  8}}, {{141},{  8}},
  105.33 +{{ 77},{  8}}, {{205},{  8}}, {{ 45},{  8}}, {{173},{  8}}, {{109},{  8}},
  105.34 +{{237},{  8}}, {{ 29},{  8}}, {{157},{  8}}, {{ 93},{  8}}, {{221},{  8}},
  105.35 +{{ 61},{  8}}, {{189},{  8}}, {{125},{  8}}, {{253},{  8}}, {{ 19},{  9}},
  105.36 +{{275},{  9}}, {{147},{  9}}, {{403},{  9}}, {{ 83},{  9}}, {{339},{  9}},
  105.37 +{{211},{  9}}, {{467},{  9}}, {{ 51},{  9}}, {{307},{  9}}, {{179},{  9}},
  105.38 +{{435},{  9}}, {{115},{  9}}, {{371},{  9}}, {{243},{  9}}, {{499},{  9}},
  105.39 +{{ 11},{  9}}, {{267},{  9}}, {{139},{  9}}, {{395},{  9}}, {{ 75},{  9}},
  105.40 +{{331},{  9}}, {{203},{  9}}, {{459},{  9}}, {{ 43},{  9}}, {{299},{  9}},
  105.41 +{{171},{  9}}, {{427},{  9}}, {{107},{  9}}, {{363},{  9}}, {{235},{  9}},
  105.42 +{{491},{  9}}, {{ 27},{  9}}, {{283},{  9}}, {{155},{  9}}, {{411},{  9}},
  105.43 +{{ 91},{  9}}, {{347},{  9}}, {{219},{  9}}, {{475},{  9}}, {{ 59},{  9}},
  105.44 +{{315},{  9}}, {{187},{  9}}, {{443},{  9}}, {{123},{  9}}, {{379},{  9}},
  105.45 +{{251},{  9}}, {{507},{  9}}, {{  7},{  9}}, {{263},{  9}}, {{135},{  9}},
  105.46 +{{391},{  9}}, {{ 71},{  9}}, {{327},{  9}}, {{199},{  9}}, {{455},{  9}},
  105.47 +{{ 39},{  9}}, {{295},{  9}}, {{167},{  9}}, {{423},{  9}}, {{103},{  9}},
  105.48 +{{359},{  9}}, {{231},{  9}}, {{487},{  9}}, {{ 23},{  9}}, {{279},{  9}},
  105.49 +{{151},{  9}}, {{407},{  9}}, {{ 87},{  9}}, {{343},{  9}}, {{215},{  9}},
  105.50 +{{471},{  9}}, {{ 55},{  9}}, {{311},{  9}}, {{183},{  9}}, {{439},{  9}},
  105.51 +{{119},{  9}}, {{375},{  9}}, {{247},{  9}}, {{503},{  9}}, {{ 15},{  9}},
  105.52 +{{271},{  9}}, {{143},{  9}}, {{399},{  9}}, {{ 79},{  9}}, {{335},{  9}},
  105.53 +{{207},{  9}}, {{463},{  9}}, {{ 47},{  9}}, {{303},{  9}}, {{175},{  9}},
  105.54 +{{431},{  9}}, {{111},{  9}}, {{367},{  9}}, {{239},{  9}}, {{495},{  9}},
  105.55 +{{ 31},{  9}}, {{287},{  9}}, {{159},{  9}}, {{415},{  9}}, {{ 95},{  9}},
  105.56 +{{351},{  9}}, {{223},{  9}}, {{479},{  9}}, {{ 63},{  9}}, {{319},{  9}},
  105.57 +{{191},{  9}}, {{447},{  9}}, {{127},{  9}}, {{383},{  9}}, {{255},{  9}},
  105.58 +{{511},{  9}}, {{  0},{  7}}, {{ 64},{  7}}, {{ 32},{  7}}, {{ 96},{  7}},
  105.59 +{{ 16},{  7}}, {{ 80},{  7}}, {{ 48},{  7}}, {{112},{  7}}, {{  8},{  7}},
  105.60 +{{ 72},{  7}}, {{ 40},{  7}}, {{104},{  7}}, {{ 24},{  7}}, {{ 88},{  7}},
  105.61 +{{ 56},{  7}}, {{120},{  7}}, {{  4},{  7}}, {{ 68},{  7}}, {{ 36},{  7}},
  105.62 +{{100},{  7}}, {{ 20},{  7}}, {{ 84},{  7}}, {{ 52},{  7}}, {{116},{  7}},
  105.63 +{{  3},{  8}}, {{131},{  8}}, {{ 67},{  8}}, {{195},{  8}}, {{ 35},{  8}},
  105.64 +{{163},{  8}}, {{ 99},{  8}}, {{227},{  8}}
  105.65 +};
  105.66 +
  105.67 +local const ct_data static_dtree[D_CODES] = {
  105.68 +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  105.69 +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  105.70 +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  105.71 +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  105.72 +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  105.73 +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  105.74 +};
  105.75 +
  105.76 +const uch _dist_code[DIST_CODE_LEN] = {
  105.77 + 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
  105.78 + 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
  105.79 +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  105.80 +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  105.81 +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  105.82 +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  105.83 +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  105.84 +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  105.85 +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  105.86 +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  105.87 +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  105.88 +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  105.89 +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,
  105.90 +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  105.91 +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  105.92 +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  105.93 +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  105.94 +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  105.95 +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  105.96 +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  105.97 +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  105.98 +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  105.99 +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
 105.100 +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
 105.101 +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
 105.102 +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
 105.103 +};
 105.104 +
 105.105 +const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
 105.106 + 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
 105.107 +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
 105.108 +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
 105.109 +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
 105.110 +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
 105.111 +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
 105.112 +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
 105.113 +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
 105.114 +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
 105.115 +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
 105.116 +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
 105.117 +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
 105.118 +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
 105.119 +};
 105.120 +
 105.121 +local const int base_length[LENGTH_CODES] = {
 105.122 +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
 105.123 +64, 80, 96, 112, 128, 160, 192, 224, 0
 105.124 +};
 105.125 +
 105.126 +local const int base_dist[D_CODES] = {
 105.127 +    0,     1,     2,     3,     4,     6,     8,    12,    16,    24,
 105.128 +   32,    48,    64,    96,   128,   192,   256,   384,   512,   768,
 105.129 + 1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576
 105.130 +};
 105.131 +
   106.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   106.2 +++ b/libs/zlib/uncompr.c	Thu Sep 08 06:28:38 2011 +0300
   106.3 @@ -0,0 +1,61 @@
   106.4 +/* uncompr.c -- decompress a memory buffer
   106.5 + * Copyright (C) 1995-2003 Jean-loup Gailly.
   106.6 + * For conditions of distribution and use, see copyright notice in zlib.h
   106.7 + */
   106.8 +
   106.9 +/* @(#) $Id$ */
  106.10 +
  106.11 +#define ZLIB_INTERNAL
  106.12 +#include "zlib.h"
  106.13 +
  106.14 +/* ===========================================================================
  106.15 +     Decompresses the source buffer into the destination buffer.  sourceLen is
  106.16 +   the byte length of the source buffer. Upon entry, destLen is the total
  106.17 +   size of the destination buffer, which must be large enough to hold the
  106.18 +   entire uncompressed data. (The size of the uncompressed data must have
  106.19 +   been saved previously by the compressor and transmitted to the decompressor
  106.20 +   by some mechanism outside the scope of this compression library.)
  106.21 +   Upon exit, destLen is the actual size of the compressed buffer.
  106.22 +     This function can be used to decompress a whole file at once if the
  106.23 +   input file is mmap'ed.
  106.24 +
  106.25 +     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  106.26 +   enough memory, Z_BUF_ERROR if there was not enough room in the output
  106.27 +   buffer, or Z_DATA_ERROR if the input data was corrupted.
  106.28 +*/
  106.29 +int ZEXPORT uncompress (dest, destLen, source, sourceLen)
  106.30 +    Bytef *dest;
  106.31 +    uLongf *destLen;
  106.32 +    const Bytef *source;
  106.33 +    uLong sourceLen;
  106.34 +{
  106.35 +    z_stream stream;
  106.36 +    int err;
  106.37 +
  106.38 +    stream.next_in = (Bytef*)source;
  106.39 +    stream.avail_in = (uInt)sourceLen;
  106.40 +    /* Check for source > 64K on 16-bit machine: */
  106.41 +    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  106.42 +
  106.43 +    stream.next_out = dest;
  106.44 +    stream.avail_out = (uInt)*destLen;
  106.45 +    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  106.46 +
  106.47 +    stream.zalloc = (alloc_func)0;
  106.48 +    stream.zfree = (free_func)0;
  106.49 +
  106.50 +    err = inflateInit(&stream);
  106.51 +    if (err != Z_OK) return err;
  106.52 +
  106.53 +    err = inflate(&stream, Z_FINISH);
  106.54 +    if (err != Z_STREAM_END) {
  106.55 +        inflateEnd(&stream);
  106.56 +        if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
  106.57 +            return Z_DATA_ERROR;
  106.58 +        return err;
  106.59 +    }
  106.60 +    *destLen = stream.total_out;
  106.61 +
  106.62 +    err = inflateEnd(&stream);
  106.63 +    return err;
  106.64 +}
   107.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   107.2 +++ b/libs/zlib/zconf.h	Thu Sep 08 06:28:38 2011 +0300
   107.3 @@ -0,0 +1,332 @@
   107.4 +/* zconf.h -- configuration of the zlib compression library
   107.5 + * Copyright (C) 1995-2005 Jean-loup Gailly.
   107.6 + * For conditions of distribution and use, see copyright notice in zlib.h
   107.7 + */
   107.8 +
   107.9 +/* @(#) $Id$ */
  107.10 +
  107.11 +#ifndef ZCONF_H
  107.12 +#define ZCONF_H
  107.13 +
  107.14 +/*
  107.15 + * If you *really* need a unique prefix for all types and library functions,
  107.16 + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  107.17 + */
  107.18 +#ifdef Z_PREFIX
  107.19 +#  define deflateInit_          z_deflateInit_
  107.20 +#  define deflate               z_deflate
  107.21 +#  define deflateEnd            z_deflateEnd
  107.22 +#  define inflateInit_          z_inflateInit_
  107.23 +#  define inflate               z_inflate
  107.24 +#  define inflateEnd            z_inflateEnd
  107.25 +#  define deflateInit2_         z_deflateInit2_
  107.26 +#  define deflateSetDictionary  z_deflateSetDictionary
  107.27 +#  define deflateCopy           z_deflateCopy
  107.28 +#  define deflateReset          z_deflateReset
  107.29 +#  define deflateParams         z_deflateParams
  107.30 +#  define deflateBound          z_deflateBound
  107.31 +#  define deflatePrime          z_deflatePrime
  107.32 +#  define inflateInit2_         z_inflateInit2_
  107.33 +#  define inflateSetDictionary  z_inflateSetDictionary
  107.34 +#  define inflateSync           z_inflateSync
  107.35 +#  define inflateSyncPoint      z_inflateSyncPoint
  107.36 +#  define inflateCopy           z_inflateCopy
  107.37 +#  define inflateReset          z_inflateReset
  107.38 +#  define inflateBack           z_inflateBack
  107.39 +#  define inflateBackEnd        z_inflateBackEnd
  107.40 +#  define compress              z_compress
  107.41 +#  define compress2             z_compress2
  107.42 +#  define compressBound         z_compressBound
  107.43 +#  define uncompress            z_uncompress
  107.44 +#  define adler32               z_adler32
  107.45 +#  define crc32                 z_crc32
  107.46 +#  define get_crc_table         z_get_crc_table
  107.47 +#  define zError                z_zError
  107.48 +
  107.49 +#  define alloc_func            z_alloc_func
  107.50 +#  define free_func             z_free_func
  107.51 +#  define in_func               z_in_func
  107.52 +#  define out_func              z_out_func
  107.53 +#  define Byte                  z_Byte
  107.54 +#  define uInt                  z_uInt
  107.55 +#  define uLong                 z_uLong
  107.56 +#  define Bytef                 z_Bytef
  107.57 +#  define charf                 z_charf
  107.58 +#  define intf                  z_intf
  107.59 +#  define uIntf                 z_uIntf
  107.60 +#  define uLongf                z_uLongf
  107.61 +#  define voidpf                z_voidpf
  107.62 +#  define voidp                 z_voidp
  107.63 +#endif
  107.64 +
  107.65 +#if defined(__MSDOS__) && !defined(MSDOS)
  107.66 +#  define MSDOS
  107.67 +#endif
  107.68 +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  107.69 +#  define OS2
  107.70 +#endif
  107.71 +#if defined(_WINDOWS) && !defined(WINDOWS)
  107.72 +#  define WINDOWS
  107.73 +#endif
  107.74 +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  107.75 +#  ifndef WIN32
  107.76 +#    define WIN32
  107.77 +#  endif
  107.78 +#endif
  107.79 +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  107.80 +#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  107.81 +#    ifndef SYS16BIT
  107.82 +#      define SYS16BIT
  107.83 +#    endif
  107.84 +#  endif
  107.85 +#endif
  107.86 +
  107.87 +/*
  107.88 + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  107.89 + * than 64k bytes at a time (needed on systems with 16-bit int).
  107.90 + */
  107.91 +#ifdef SYS16BIT
  107.92 +#  define MAXSEG_64K
  107.93 +#endif
  107.94 +#ifdef MSDOS
  107.95 +#  define UNALIGNED_OK
  107.96 +#endif
  107.97 +
  107.98 +#ifdef __STDC_VERSION__
  107.99 +#  ifndef STDC
 107.100 +#    define STDC
 107.101 +#  endif
 107.102 +#  if __STDC_VERSION__ >= 199901L
 107.103 +#    ifndef STDC99
 107.104 +#      define STDC99
 107.105 +#    endif
 107.106 +#  endif
 107.107 +#endif
 107.108 +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
 107.109 +#  define STDC
 107.110 +#endif
 107.111 +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
 107.112 +#  define STDC
 107.113 +#endif
 107.114 +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
 107.115 +#  define STDC
 107.116 +#endif
 107.117 +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
 107.118 +#  define STDC
 107.119 +#endif
 107.120 +
 107.121 +#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
 107.122 +#  define STDC
 107.123 +#endif
 107.124 +
 107.125 +#ifndef STDC
 107.126 +#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
 107.127 +#    define const       /* note: need a more gentle solution here */
 107.128 +#  endif
 107.129 +#endif
 107.130 +
 107.131 +/* Some Mac compilers merge all .h files incorrectly: */
 107.132 +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
 107.133 +#  define NO_DUMMY_DECL
 107.134 +#endif
 107.135 +
 107.136 +/* Maximum value for memLevel in deflateInit2 */
 107.137 +#ifndef MAX_MEM_LEVEL
 107.138 +#  ifdef MAXSEG_64K
 107.139 +#    define MAX_MEM_LEVEL 8
 107.140 +#  else
 107.141 +#    define MAX_MEM_LEVEL 9
 107.142 +#  endif
 107.143 +#endif
 107.144 +
 107.145 +/* Maximum value for windowBits in deflateInit2 and inflateInit2.
 107.146 + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
 107.147 + * created by gzip. (Files created by minigzip can still be extracted by
 107.148 + * gzip.)
 107.149 + */
 107.150 +#ifndef MAX_WBITS
 107.151 +#  define MAX_WBITS   15 /* 32K LZ77 window */
 107.152 +#endif
 107.153 +
 107.154 +/* The memory requirements for deflate are (in bytes):
 107.155 +            (1 << (windowBits+2)) +  (1 << (memLevel+9))
 107.156 + that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
 107.157 + plus a few kilobytes for small objects. For example, if you want to reduce
 107.158 + the default memory requirements from 256K to 128K, compile with
 107.159 +     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
 107.160 + Of course this will generally degrade compression (there's no free lunch).
 107.161 +
 107.162 +   The memory requirements for inflate are (in bytes) 1 << windowBits
 107.163 + that is, 32K for windowBits=15 (default value) plus a few kilobytes
 107.164 + for small objects.
 107.165 +*/
 107.166 +
 107.167 +                        /* Type declarations */
 107.168 +
 107.169 +#ifndef OF /* function prototypes */
 107.170 +#  ifdef STDC
 107.171 +#    define OF(args)  args
 107.172 +#  else
 107.173 +#    define OF(args)  ()
 107.174 +#  endif
 107.175 +#endif
 107.176 +
 107.177 +/* The following definitions for FAR are needed only for MSDOS mixed
 107.178 + * model programming (small or medium model with some far allocations).
 107.179 + * This was tested only with MSC; for other MSDOS compilers you may have
 107.180 + * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
 107.181 + * just define FAR to be empty.
 107.182 + */
 107.183 +#ifdef SYS16BIT
 107.184 +#  if defined(M_I86SM) || defined(M_I86MM)
 107.185 +     /* MSC small or medium model */
 107.186 +#    define SMALL_MEDIUM
 107.187 +#    ifdef _MSC_VER
 107.188 +#      define FAR _far
 107.189 +#    else
 107.190 +#      define FAR far
 107.191 +#    endif
 107.192 +#  endif
 107.193 +#  if (defined(__SMALL__) || defined(__MEDIUM__))
 107.194 +     /* Turbo C small or medium model */
 107.195 +#    define SMALL_MEDIUM
 107.196 +#    ifdef __BORLANDC__
 107.197 +#      define FAR _far
 107.198 +#    else
 107.199 +#      define FAR far
 107.200 +#    endif
 107.201 +#  endif
 107.202 +#endif
 107.203 +
 107.204 +#if defined(WINDOWS) || defined(WIN32)
 107.205 +   /* If building or using zlib as a DLL, define ZLIB_DLL.
 107.206 +    * This is not mandatory, but it offers a little performance increase.
 107.207 +    */
 107.208 +#  ifdef ZLIB_DLL
 107.209 +#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
 107.210 +#      ifdef ZLIB_INTERNAL
 107.211 +#        define ZEXTERN extern __declspec(dllexport)
 107.212 +#      else
 107.213 +#        define ZEXTERN extern __declspec(dllimport)
 107.214 +#      endif
 107.215 +#    endif
 107.216 +#  endif  /* ZLIB_DLL */
 107.217 +   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
 107.218 +    * define ZLIB_WINAPI.
 107.219 +    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
 107.220 +    */
 107.221 +#  ifdef ZLIB_WINAPI
 107.222 +#    ifdef FAR
 107.223 +#      undef FAR
 107.224 +#    endif
 107.225 +#    include <windows.h>
 107.226 +     /* No need for _export, use ZLIB.DEF instead. */
 107.227 +     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
 107.228 +#    define ZEXPORT WINAPI
 107.229 +#    ifdef WIN32
 107.230 +#      define ZEXPORTVA WINAPIV
 107.231 +#    else
 107.232 +#      define ZEXPORTVA FAR CDECL
 107.233 +#    endif
 107.234 +#  endif
 107.235 +#endif
 107.236 +
 107.237 +#if defined (__BEOS__)
 107.238 +#  ifdef ZLIB_DLL
 107.239 +#    ifdef ZLIB_INTERNAL
 107.240 +#      define ZEXPORT   __declspec(dllexport)
 107.241 +#      define ZEXPORTVA __declspec(dllexport)
 107.242 +#    else
 107.243 +#      define ZEXPORT   __declspec(dllimport)
 107.244 +#      define ZEXPORTVA __declspec(dllimport)
 107.245 +#    endif
 107.246 +#  endif
 107.247 +#endif
 107.248 +
 107.249 +#ifndef ZEXTERN
 107.250 +#  define ZEXTERN extern
 107.251 +#endif
 107.252 +#ifndef ZEXPORT
 107.253 +#  define ZEXPORT
 107.254 +#endif
 107.255 +#ifndef ZEXPORTVA
 107.256 +#  define ZEXPORTVA
 107.257 +#endif
 107.258 +
 107.259 +#ifndef FAR
 107.260 +#  define FAR
 107.261 +#endif
 107.262 +
 107.263 +#if !defined(__MACTYPES__)
 107.264 +typedef unsigned char  Byte;  /* 8 bits */
 107.265 +#endif
 107.266 +typedef unsigned int   uInt;  /* 16 bits or more */
 107.267 +typedef unsigned long  uLong; /* 32 bits or more */
 107.268 +
 107.269 +#ifdef SMALL_MEDIUM
 107.270 +   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
 107.271 +#  define Bytef Byte FAR
 107.272 +#else
 107.273 +   typedef Byte  FAR Bytef;
 107.274 +#endif
 107.275 +typedef char  FAR charf;
 107.276 +typedef int   FAR intf;
 107.277 +typedef uInt  FAR uIntf;
 107.278 +typedef uLong FAR uLongf;
 107.279 +
 107.280 +#ifdef STDC
 107.281 +   typedef void const *voidpc;
 107.282 +   typedef void FAR   *voidpf;
 107.283 +   typedef void       *voidp;
 107.284 +#else
 107.285 +   typedef Byte const *voidpc;
 107.286 +   typedef Byte FAR   *voidpf;
 107.287 +   typedef Byte       *voidp;
 107.288 +#endif
 107.289 +
 107.290 +#if 0           /* HAVE_UNISTD_H -- this line is updated by ./configure */
 107.291 +#  include <sys/types.h> /* for off_t */
 107.292 +#  include <unistd.h>    /* for SEEK_* and off_t */
 107.293 +#  ifdef VMS
 107.294 +#    include <unixio.h>   /* for off_t */
 107.295 +#  endif
 107.296 +#  define z_off_t off_t
 107.297 +#endif
 107.298 +#ifndef SEEK_SET
 107.299 +#  define SEEK_SET        0       /* Seek from beginning of file.  */
 107.300 +#  define SEEK_CUR        1       /* Seek from current position.  */
 107.301 +#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
 107.302 +#endif
 107.303 +#ifndef z_off_t
 107.304 +#  define z_off_t long
 107.305 +#endif
 107.306 +
 107.307 +#if defined(__OS400__)
 107.308 +#  define NO_vsnprintf
 107.309 +#endif
 107.310 +
 107.311 +#if defined(__MVS__)
 107.312 +#  define NO_vsnprintf
 107.313 +#  ifdef FAR
 107.314 +#    undef FAR
 107.315 +#  endif
 107.316 +#endif
 107.317 +
 107.318 +/* MVS linker does not support external names larger than 8 bytes */
 107.319 +#if defined(__MVS__)
 107.320 +#   pragma map(deflateInit_,"DEIN")
 107.321 +#   pragma map(deflateInit2_,"DEIN2")
 107.322 +#   pragma map(deflateEnd,"DEEND")
 107.323 +#   pragma map(deflateBound,"DEBND")
 107.324 +#   pragma map(inflateInit_,"ININ")
 107.325 +#   pragma map(inflateInit2_,"ININ2")
 107.326 +#   pragma map(inflateEnd,"INEND")
 107.327 +#   pragma map(inflateSync,"INSY")
 107.328 +#   pragma map(inflateSetDictionary,"INSEDI")
 107.329 +#   pragma map(compressBound,"CMBND")
 107.330 +#   pragma map(inflate_table,"INTABL")
 107.331 +#   pragma map(inflate_fast,"INFA")
 107.332 +#   pragma map(inflate_copyright,"INCOPY")
 107.333 +#endif
 107.334 +
 107.335 +#endif /* ZCONF_H */
   108.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   108.2 +++ b/libs/zlib/zlib.h	Thu Sep 08 06:28:38 2011 +0300
   108.3 @@ -0,0 +1,1357 @@
   108.4 +/* zlib.h -- interface of the 'zlib' general purpose compression library
   108.5 +  version 1.2.3, July 18th, 2005
   108.6 +
   108.7 +  Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler
   108.8 +
   108.9 +  This software is provided 'as-is', without any express or implied
  108.10 +  warranty.  In no event will the authors be held liable for any damages
  108.11 +  arising from the use of this software.
  108.12 +
  108.13 +  Permission is granted to anyone to use this software for any purpose,
  108.14 +  including commercial applications, and to alter it and redistribute it
  108.15 +  freely, subject to the following restrictions:
  108.16 +
  108.17 +  1. The origin of this software must not be misrepresented; you must not
  108.18 +     claim that you wrote the original software. If you use this software
  108.19 +     in a product, an acknowledgment in the product documentation would be
  108.20 +     appreciated but is not required.
  108.21 +  2. Altered source versions must be plainly marked as such, and must not be
  108.22 +     misrepresented as being the original software.
  108.23 +  3. This notice may not be removed or altered from any source distribution.
  108.24 +
  108.25 +  Jean-loup Gailly        Mark Adler
  108.26 +  jloup@gzip.org          madler@alumni.caltech.edu
  108.27 +
  108.28 +
  108.29 +  The data format used by the zlib library is described by RFCs (Request for
  108.30 +  Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt
  108.31 +  (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
  108.32 +*/
  108.33 +
  108.34 +#ifndef ZLIB_H
  108.35 +#define ZLIB_H
  108.36 +
  108.37 +#include "zconf.h"
  108.38 +
  108.39 +#ifdef __cplusplus
  108.40 +extern "C" {
  108.41 +#endif
  108.42 +
  108.43 +#define ZLIB_VERSION "1.2.3"
  108.44 +#define ZLIB_VERNUM 0x1230
  108.45 +
  108.46 +/*
  108.47 +     The 'zlib' compression library provides in-memory compression and
  108.48 +  decompression functions, including integrity checks of the uncompressed
  108.49 +  data.  This version of the library supports only one compression method
  108.50 +  (deflation) but other algorithms will be added later and will have the same
  108.51 +  stream interface.
  108.52 +
  108.53 +     Compression can be done in a single step if the buffers are large
  108.54 +  enough (for example if an input file is mmap'ed), or can be done by
  108.55 +  repeated calls of the compression function.  In the latter case, the
  108.56 +  application must provide more input and/or consume the output
  108.57 +  (providing more output space) before each call.
  108.58 +
  108.59 +     The compressed data format used by default by the in-memory functions is
  108.60 +  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  108.61 +  around a deflate stream, which is itself documented in RFC 1951.
  108.62 +
  108.63 +     The library also supports reading and writing files in gzip (.gz) format
  108.64 +  with an interface similar to that of stdio using the functions that start
  108.65 +  with "gz".  The gzip format is different from the zlib format.  gzip is a
  108.66 +  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  108.67 +
  108.68 +     This library can optionally read and write gzip streams in memory as well.
  108.69 +
  108.70 +     The zlib format was designed to be compact and fast for use in memory
  108.71 +  and on communications channels.  The gzip format was designed for single-
  108.72 +  file compression on file systems, has a larger header than zlib to maintain
  108.73 +  directory information, and uses a different, slower check method than zlib.
  108.74 +
  108.75 +     The library does not install any signal handler. The decoder checks
  108.76 +  the consistency of the compressed data, so the library should never
  108.77 +  crash even in case of corrupted input.
  108.78 +*/
  108.79 +
  108.80 +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  108.81 +typedef void   (*free_func)  OF((voidpf opaque, voidpf address));
  108.82 +
  108.83 +struct internal_state;
  108.84 +
  108.85 +typedef struct z_stream_s {
  108.86 +    Bytef    *next_in;  /* next input byte */
  108.87 +    uInt     avail_in;  /* number of bytes available at next_in */
  108.88 +    uLong    total_in;  /* total nb of input bytes read so far */
  108.89 +
  108.90 +    Bytef    *next_out; /* next output byte should be put there */
  108.91 +    uInt     avail_out; /* remaining free space at next_out */
  108.92 +    uLong    total_out; /* total nb of bytes output so far */
  108.93 +
  108.94 +    char     *msg;      /* last error message, NULL if no error */
  108.95 +    struct internal_state FAR *state; /* not visible by applications */
  108.96 +
  108.97 +    alloc_func zalloc;  /* used to allocate the internal state */
  108.98 +    free_func  zfree;   /* used to free the internal state */
  108.99 +    voidpf     opaque;  /* private data object passed to zalloc and zfree */
 108.100 +
 108.101 +    int     data_type;  /* best guess about the data type: binary or text */
 108.102 +    uLong   adler;      /* adler32 value of the uncompressed data */
 108.103 +    uLong   reserved;   /* reserved for future use */
 108.104 +} z_stream;
 108.105 +
 108.106 +typedef z_stream FAR *z_streamp;
 108.107 +
 108.108 +/*
 108.109 +     gzip header information passed to and from zlib routines.  See RFC 1952
 108.110 +  for more details on the meanings of these fields.
 108.111 +*/
 108.112 +typedef struct gz_header_s {
 108.113 +    int     text;       /* true if compressed data believed to be text */
 108.114 +    uLong   time;       /* modification time */
 108.115 +    int     xflags;     /* extra flags (not used when writing a gzip file) */
 108.116 +    int     os;         /* operating system */
 108.117 +    Bytef   *extra;     /* pointer to extra field or Z_NULL if none */
 108.118 +    uInt    extra_len;  /* extra field length (valid if extra != Z_NULL) */
 108.119 +    uInt    extra_max;  /* space at extra (only when reading header) */
 108.120 +    Bytef   *name;      /* pointer to zero-terminated file name or Z_NULL */
 108.121 +    uInt    name_max;   /* space at name (only when reading header) */
 108.122 +    Bytef   *comment;   /* pointer to zero-terminated comment or Z_NULL */
 108.123 +    uInt    comm_max;   /* space at comment (only when reading header) */
 108.124 +    int     hcrc;       /* true if there was or will be a header crc */
 108.125 +    int     done;       /* true when done reading gzip header (not used
 108.126 +                           when writing a gzip file) */
 108.127 +} gz_header;
 108.128 +
 108.129 +typedef gz_header FAR *gz_headerp;
 108.130 +
 108.131 +/*
 108.132 +   The application must update next_in and avail_in when avail_in has
 108.133 +   dropped to zero. It must update next_out and avail_out when avail_out
 108.134 +   has dropped to zero. The application must initialize zalloc, zfree and
 108.135 +   opaque before calling the init function. All other fields are set by the
 108.136 +   compression library and must not be updated by the application.
 108.137 +
 108.138 +   The opaque value provided by the application will be passed as the first
 108.139 +   parameter for calls of zalloc and zfree. This can be useful for custom
 108.140 +   memory management. The compression library attaches no meaning to the
 108.141 +   opaque value.
 108.142 +
 108.143 +   zalloc must return Z_NULL if there is not enough memory for the object.
 108.144 +   If zlib is used in a multi-threaded application, zalloc and zfree must be
 108.145 +   thread safe.
 108.146 +
 108.147 +   On 16-bit systems, the functions zalloc and zfree must be able to allocate
 108.148 +   exactly 65536 bytes, but will not be required to allocate more than this
 108.149 +   if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
 108.150 +   pointers returned by zalloc for objects of exactly 65536 bytes *must*
 108.151 +   have their offset normalized to zero. The default allocation function
 108.152 +   provided by this library ensures this (see zutil.c). To reduce memory
 108.153 +   requirements and avoid any allocation of 64K objects, at the expense of
 108.154 +   compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
 108.155 +
 108.156 +   The fields total_in and total_out can be used for statistics or
 108.157 +   progress reports. After compression, total_in holds the total size of
 108.158 +   the uncompressed data and may be saved for use in the decompressor
 108.159 +   (particularly if the decompressor wants to decompress everything in
 108.160 +   a single step).
 108.161 +*/
 108.162 +
 108.163 +                        /* constants */
 108.164 +
 108.165 +#define Z_NO_FLUSH      0
 108.166 +#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
 108.167 +#define Z_SYNC_FLUSH    2
 108.168 +#define Z_FULL_FLUSH    3
 108.169 +#define Z_FINISH        4
 108.170 +#define Z_BLOCK         5
 108.171 +/* Allowed flush values; see deflate() and inflate() below for details */
 108.172 +
 108.173 +#define Z_OK            0
 108.174 +#define Z_STREAM_END    1
 108.175 +#define Z_NEED_DICT     2
 108.176 +#define Z_ERRNO        (-1)
 108.177 +#define Z_STREAM_ERROR (-2)
 108.178 +#define Z_DATA_ERROR   (-3)
 108.179 +#define Z_MEM_ERROR    (-4)
 108.180 +#define Z_BUF_ERROR    (-5)
 108.181 +#define Z_VERSION_ERROR (-6)
 108.182 +/* Return codes for the compression/decompression functions. Negative
 108.183 + * values are errors, positive values are used for special but normal events.
 108.184 + */
 108.185 +
 108.186 +#define Z_NO_COMPRESSION         0
 108.187 +#define Z_BEST_SPEED             1
 108.188 +#define Z_BEST_COMPRESSION       9
 108.189 +#define Z_DEFAULT_COMPRESSION  (-1)
 108.190 +/* compression levels */
 108.191 +
 108.192 +#define Z_FILTERED            1
 108.193 +#define Z_HUFFMAN_ONLY        2
 108.194 +#define Z_RLE                 3
 108.195 +#define Z_FIXED               4
 108.196 +#define Z_DEFAULT_STRATEGY    0
 108.197 +/* compression strategy; see deflateInit2() below for details */
 108.198 +
 108.199 +#define Z_BINARY   0
 108.200 +#define Z_TEXT     1
 108.201 +#define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */
 108.202 +#define Z_UNKNOWN  2
 108.203 +/* Possible values of the data_type field (though see inflate()) */
 108.204 +
 108.205 +#define Z_DEFLATED   8
 108.206 +/* The deflate compression method (the only one supported in this version) */
 108.207 +
 108.208 +#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
 108.209 +
 108.210 +#define zlib_version zlibVersion()
 108.211 +/* for compatibility with versions < 1.0.2 */
 108.212 +
 108.213 +                        /* basic functions */
 108.214 +
 108.215 +ZEXTERN const char * ZEXPORT zlibVersion OF((void));
 108.216 +/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
 108.217 +   If the first character differs, the library code actually used is
 108.218 +   not compatible with the zlib.h header file used by the application.
 108.219 +   This check is automatically made by deflateInit and inflateInit.
 108.220 + */
 108.221 +
 108.222 +/*
 108.223 +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
 108.224 +
 108.225 +     Initializes the internal stream state for compression. The fields
 108.226 +   zalloc, zfree and opaque must be initialized before by the caller.
 108.227 +   If zalloc and zfree are set to Z_NULL, deflateInit updates them to
 108.228 +   use default allocation functions.
 108.229 +
 108.230 +     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
 108.231 +   1 gives best speed, 9 gives best compression, 0 gives no compression at
 108.232 +   all (the input data is simply copied a block at a time).
 108.233 +   Z_DEFAULT_COMPRESSION requests a default compromise between speed and
 108.234 +   compression (currently equivalent to level 6).
 108.235 +
 108.236 +     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
 108.237 +   enough memory, Z_STREAM_ERROR if level is not a valid compression level,
 108.238 +   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
 108.239 +   with the version assumed by the caller (ZLIB_VERSION).
 108.240 +   msg is set to null if there is no error message.  deflateInit does not
 108.241 +   perform any compression: this will be done by deflate().
 108.242 +*/
 108.243 +
 108.244 +
 108.245 +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
 108.246 +/*
 108.247 +    deflate compresses as much data as possible, and stops when the input
 108.248 +  buffer becomes empty or the output buffer becomes full. It may introduce some
 108.249 +  output latency (reading input without producing any output) except when
 108.250 +  forced to flush.
 108.251 +
 108.252 +    The detailed semantics are as follows. deflate performs one or both of the
 108.253 +  following actions:
 108.254 +
 108.255 +  - Compress more input starting at next_in and update next_in and avail_in
 108.256 +    accordingly. If not all input can be processed (because there is not
 108.257 +    enough room in the output buffer), next_in and avail_in are updated and
 108.258 +    processing will resume at this point for the next call of deflate().
 108.259 +
 108.260 +  - Provide more output starting at next_out and update next_out and avail_out
 108.261 +    accordingly. This action is forced if the parameter flush is non zero.
 108.262 +    Forcing flush frequently degrades the compression ratio, so this parameter
 108.263 +    should be set only when necessary (in interactive applications).
 108.264 +    Some output may be provided even if flush is not set.
 108.265 +
 108.266 +  Before the call of deflate(), the application should ensure that at least
 108.267 +  one of the actions is possible, by providing more input and/or consuming
 108.268 +  more output, and updating avail_in or avail_out accordingly; avail_out
 108.269 +  should never be zero before the call. The application can consume the
 108.270 +  compressed output when it wants, for example when the output buffer is full
 108.271 +  (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
 108.272 +  and with zero avail_out, it must be called again after making room in the
 108.273 +  output buffer because there might be more output pending.
 108.274 +
 108.275 +    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
 108.276 +  decide how much data to accumualte before producing output, in order to
 108.277 +  maximize compression.
 108.278 +
 108.279 +    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
 108.280 +  flushed to the output buffer and the output is aligned on a byte boundary, so
 108.281 +  that the decompressor can get all input data available so far. (In particular
 108.282 +  avail_in is zero after the call if enough output space has been provided
 108.283 +  before the call.)  Flushing may degrade compression for some compression
 108.284 +  algorithms and so it should be used only when necessary.
 108.285 +
 108.286 +    If flush is set to Z_FULL_FLUSH, all output is flushed as with
 108.287 +  Z_SYNC_FLUSH, and the compression state is reset so that decompression can
 108.288 +  restart from this point if previous compressed data has been damaged or if
 108.289 +  random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
 108.290 +  compression.
 108.291 +
 108.292 +    If deflate returns with avail_out == 0, this function must be called again
 108.293 +  with the same value of the flush parameter and more output space (updated
 108.294 +  avail_out), until the flush is complete (deflate returns with non-zero
 108.295 +  avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
 108.296 +  avail_out is greater than six to avoid repeated flush markers due to
 108.297 +  avail_out == 0 on return.
 108.298 +
 108.299 +    If the parameter flush is set to Z_FINISH, pending input is processed,
 108.300 +  pending output is flushed and deflate returns with Z_STREAM_END if there
 108.301 +  was enough output space; if deflate returns with Z_OK, this function must be
 108.302 +  called again with Z_FINISH and more output space (updated avail_out) but no
 108.303 +  more input data, until it returns with Z_STREAM_END or an error. After
 108.304 +  deflate has returned Z_STREAM_END, the only possible operations on the
 108.305 +  stream are deflateReset or deflateEnd.
 108.306 +
 108.307 +    Z_FINISH can be used immediately after deflateInit if all the compression
 108.308 +  is to be done in a single step. In this case, avail_out must be at least
 108.309 +  the value returned by deflateBound (see below). If deflate does not return
 108.310 +  Z_STREAM_END, then it must be called again as described above.
 108.311 +
 108.312 +    deflate() sets strm->adler to the adler32 checksum of all input read
 108.313 +  so far (that is, total_in bytes).
 108.314 +
 108.315 +    deflate() may update strm->data_type if it can make a good guess about
 108.316 +  the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
 108.317 +  binary. This field is only for information purposes and does not affect
 108.318 +  the compression algorithm in any manner.
 108.319 +
 108.320 +    deflate() returns Z_OK if some progress has been made (more input
 108.321 +  processed or more output produced), Z_STREAM_END if all input has been
 108.322 +  consumed and all output has been produced (only when flush is set to
 108.323 +  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
 108.324 +  if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
 108.325 +  (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
 108.326 +  fatal, and deflate() can be called again with more input and more output
 108.327 +  space to continue compressing.
 108.328 +*/
 108.329 +
 108.330 +
 108.331 +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
 108.332 +/*
 108.333 +     All dynamically allocated data structures for this stream are freed.
 108.334 +   This function discards any unprocessed input and does not flush any
 108.335 +   pending output.
 108.336 +
 108.337 +     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
 108.338 +   stream state was inconsistent, Z_DATA_ERROR if the stream was freed
 108.339 +   prematurely (some input or output was discarded). In the error case,
 108.340 +   msg may be set but then points to a static string (which must not be
 108.341 +   deallocated).
 108.342 +*/
 108.343 +
 108.344 +
 108.345 +/*
 108.346 +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
 108.347 +
 108.348 +     Initializes the internal stream state for decompression. The fields
 108.349 +   next_in, avail_in, zalloc, zfree and opaque must be initialized before by
 108.350 +   the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
 108.351 +   value depends on the compression method), inflateInit determines the
 108.352 +   compression method from the zlib header and allocates all data structures
 108.353 +   accordingly; otherwise the allocation will be deferred to the first call of
 108.354 +   inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
 108.355 +   use default allocation functions.
 108.356 +
 108.357 +     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
 108.358 +   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
 108.359 +   version assumed by the caller.  msg is set to null if there is no error
 108.360 +   message. inflateInit does not perform any decompression apart from reading
 108.361 +   the zlib header if present: this will be done by inflate().  (So next_in and
 108.362 +   avail_in may be modified, but next_out and avail_out are unchanged.)
 108.363 +*/
 108.364 +
 108.365 +
 108.366 +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
 108.367 +/*
 108.368 +    inflate decompresses as much data as possible, and stops when the input
 108.369 +  buffer becomes empty or the output buffer becomes full. It may introduce
 108.370 +  some output latency (reading input without producing any output) except when
 108.371 +  forced to flush.
 108.372 +
 108.373 +  The detailed semantics are as follows. inflate performs one or both of the
 108.374 +  following actions:
 108.375 +
 108.376 +  - Decompress more input starting at next_in and update next_in and avail_in
 108.377 +    accordingly. If not all input can be processed (because there is not
 108.378 +    enough room in the output buffer), next_in is updated and processing
 108.379 +    will resume at this point for the next call of inflate().
 108.380 +
 108.381 +  - Provide more output starting at next_out and update next_out and avail_out
 108.382 +    accordingly.  inflate() provides as much output as possible, until there
 108.383 +    is no more input data or no more space in the output buffer (see below
 108.384 +    about the flush parameter).
 108.385 +
 108.386 +  Before the call of inflate(), the application should ensure that at least
 108.387 +  one of the actions is possible, by providing more input and/or consuming
 108.388 +  more output, and updating the next_* and avail_* values accordingly.
 108.389 +  The application can consume the uncompressed output when it wants, for
 108.390 +  example when the output buffer is full (avail_out == 0), or after each
 108.391 +  call of inflate(). If inflate returns Z_OK and with zero avail_out, it
 108.392 +  must be called again after making room in the output buffer because there
 108.393 +  might be more output pending.
 108.394 +
 108.395 +    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
 108.396 +  Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
 108.397 +  output as possible to the output buffer. Z_BLOCK requests that inflate() stop
 108.398 +  if and when it gets to the next deflate block boundary. When decoding the
 108.399 +  zlib or gzip format, this will cause inflate() to return immediately after
 108.400 +  the header and before the first block. When doing a raw inflate, inflate()
 108.401 +  will go ahead and process the first block, and will return when it gets to
 108.402 +  the end of that block, or when it runs out of data.
 108.403 +
 108.404 +    The Z_BLOCK option assists in appending to or combining deflate streams.
 108.405 +  Also to assist in this, on return inflate() will set strm->data_type to the
 108.406 +  number of unused bits in the last byte taken from strm->next_in, plus 64
 108.407 +  if inflate() is currently decoding the last block in the deflate stream,
 108.408 +  plus 128 if inflate() returned immediately after decoding an end-of-block
 108.409 +  code or decoding the complete header up to just before the first byte of the
 108.410 +  deflate stream. The end-of-block will not be indicated until all of the
 108.411 +  uncompressed data from that block has been written to strm->next_out.  The
 108.412 +  number of unused bits may in general be greater than seven, except when
 108.413 +  bit 7 of data_type is set, in which case the number of unused bits will be
 108.414 +  less than eight.
 108.415 +
 108.416 +    inflate() should normally be called until it returns Z_STREAM_END or an
 108.417 +  error. However if all decompression is to be performed in a single step
 108.418 +  (a single call of inflate), the parameter flush should be set to
 108.419 +  Z_FINISH. In this case all pending input is processed and all pending
 108.420 +  output is flushed; avail_out must be large enough to hold all the
 108.421 +  uncompressed data. (The size of the uncompressed data may have been saved
 108.422 +  by the compressor for this purpose.) The next operation on this stream must
 108.423 +  be inflateEnd to deallocate the decompression state. The use of Z_FINISH
 108.424 +  is never required, but can be used to inform inflate that a faster approach
 108.425 +  may be used for the single inflate() call.
 108.426 +
 108.427 +     In this implementation, inflate() always flushes as much output as
 108.428 +  possible to the output buffer, and always uses the faster approach on the
 108.429 +  first call. So the only effect of the flush parameter in this implementation
 108.430 +  is on the return value of inflate(), as noted below, or when it returns early
 108.431 +  because Z_BLOCK is used.
 108.432 +
 108.433 +     If a preset dictionary is needed after this call (see inflateSetDictionary
 108.434 +  below), inflate sets strm->adler to the adler32 checksum of the dictionary
 108.435 +  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
 108.436 +  strm->adler to the adler32 checksum of all output produced so far (that is,
 108.437 +  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
 108.438 +  below. At the end of the stream, inflate() checks that its computed adler32
 108.439 +  checksum is equal to that saved by the compressor and returns Z_STREAM_END
 108.440 +  only if the checksum is correct.
 108.441 +
 108.442 +    inflate() will decompress and check either zlib-wrapped or gzip-wrapped
 108.443 +  deflate data.  The header type is detected automatically.  Any information
 108.444 +  contained in the gzip header is not retained, so applications that need that
 108.445 +  information should instead use raw inflate, see inflateInit2() below, or
 108.446 +  inflateBack() and perform their own processing of the gzip header and
 108.447 +  trailer.
 108.448 +
 108.449 +    inflate() returns Z_OK if some progress has been made (more input processed
 108.450 +  or more output produced), Z_STREAM_END if the end of the compressed data has
 108.451 +  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
 108.452 +  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
 108.453 +  corrupted (input stream not conforming to the zlib format or incorrect check
 108.454 +  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
 108.455 +  if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
 108.456 +  Z_BUF_ERROR if no progress is possible or if there was not enough room in the
 108.457 +  output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
 108.458 +  inflate() can be called again with more input and more output space to
 108.459 +  continue decompressing. If Z_DATA_ERROR is returned, the application may then
 108.460 +  call inflateSync() to look for a good compression block if a partial recovery
 108.461 +  of the data is desired.
 108.462 +*/
 108.463 +
 108.464 +
 108.465 +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
 108.466 +/*
 108.467 +     All dynamically allocated data structures for this stream are freed.
 108.468 +   This function discards any unprocessed input and does not flush any
 108.469 +   pending output.
 108.470 +
 108.471 +     inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
 108.472 +   was inconsistent. In the error case, msg may be set but then points to a
 108.473 +   static string (which must not be deallocated).
 108.474 +*/
 108.475 +
 108.476 +                        /* Advanced functions */
 108.477 +
 108.478 +/*
 108.479 +    The following functions are needed only in some special applications.
 108.480 +*/
 108.481 +
 108.482 +/*
 108.483 +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
 108.484 +                                     int  level,
 108.485 +                                     int  method,
 108.486 +                                     int  windowBits,
 108.487 +                                     int  memLevel,
 108.488 +                                     int  strategy));
 108.489 +
 108.490 +     This is another version of deflateInit with more compression options. The
 108.491 +   fields next_in, zalloc, zfree and opaque must be initialized before by
 108.492 +   the caller.
 108.493 +
 108.494 +     The method parameter is the compression method. It must be Z_DEFLATED in
 108.495 +   this version of the library.
 108.496 +
 108.497 +     The windowBits parameter is the base two logarithm of the window size
 108.498 +   (the size of the history buffer). It should be in the range 8..15 for this
 108.499 +   version of the library. Larger values of this parameter result in better
 108.500 +   compression at the expense of memory usage. The default value is 15 if
 108.501 +   deflateInit is used instead.
 108.502 +
 108.503 +     windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
 108.504 +   determines the window size. deflate() will then generate raw deflate data
 108.505 +   with no zlib header or trailer, and will not compute an adler32 check value.
 108.506 +
 108.507 +     windowBits can also be greater than 15 for optional gzip encoding. Add
 108.508 +   16 to windowBits to write a simple gzip header and trailer around the
 108.509 +   compressed data instead of a zlib wrapper. The gzip header will have no
 108.510 +   file name, no extra data, no comment, no modification time (set to zero),
 108.511 +   no header crc, and the operating system will be set to 255 (unknown).  If a
 108.512 +   gzip stream is being written, strm->adler is a crc32 instead of an adler32.
 108.513 +
 108.514 +     The memLevel parameter specifies how much memory should be allocated
 108.515 +   for the internal compression state. memLevel=1 uses minimum memory but
 108.516 +   is slow and reduces compression ratio; memLevel=9 uses maximum memory
 108.517 +   for optimal speed. The default value is 8. See zconf.h for total memory
 108.518 +   usage as a function of windowBits and memLevel.
 108.519 +
 108.520 +     The strategy parameter is used to tune the compression algorithm. Use the
 108.521 +   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
 108.522 +   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
 108.523 +   string match), or Z_RLE to limit match distances to one (run-length
 108.524 +   encoding). Filtered data consists mostly of small values with a somewhat
 108.525 +   random distribution. In this case, the compression algorithm is tuned to
 108.526 +   compress them better. The effect of Z_FILTERED is to force more Huffman
 108.527 +   coding and less string matching; it is somewhat intermediate between
 108.528 +   Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
 108.529 +   Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
 108.530 +   parameter only affects the compression ratio but not the correctness of the
 108.531 +   compressed output even if it is not set appropriately.  Z_FIXED prevents the
 108.532 +   use of dynamic Huffman codes, allowing for a simpler decoder for special
 108.533 +   applications.
 108.534 +
 108.535 +      deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
 108.536 +   memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
 108.537 +   method). msg is set to null if there is no error message.  deflateInit2 does
 108.538 +   not perform any compression: this will be done by deflate().
 108.539 +*/
 108.540 +
 108.541 +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
 108.542 +                                             const Bytef *dictionary,
 108.543 +                                             uInt  dictLength));
 108.544 +/*
 108.545 +     Initializes the compression dictionary from the given byte sequence
 108.546 +   without producing any compressed output. This function must be called
 108.547 +   immediately after deflateInit, deflateInit2 or deflateReset, before any
 108.548 +   call of deflate. The compressor and decompressor must use exactly the same
 108.549 +   dictionary (see inflateSetDictionary).
 108.550 +
 108.551 +     The dictionary should consist of strings (byte sequences) that are likely
 108.552 +   to be encountered later in the data to be compressed, with the most commonly
 108.553 +   used strings preferably put towards the end of the dictionary. Using a
 108.554 +   dictionary is most useful when the data to be compressed is short and can be
 108.555 +   predicted with good accuracy; the data can then be compressed better than
 108.556 +   with the default empty dictionary.
 108.557 +
 108.558 +     Depending on the size of the compression data structures selected by
 108.559 +   deflateInit or deflateInit2, a part of the dictionary may in effect be
 108.560 +   discarded, for example if the dictionary is larger than the window size in
 108.561 +   deflate or deflate2. Thus the strings most likely to be useful should be
 108.562 +   put at the end of the dictionary, not at the front. In addition, the
 108.563 +   current implementation of deflate will use at most the window size minus
 108.564 +   262 bytes of the provided dictionary.
 108.565 +
 108.566 +     Upon return of this function, strm->adler is set to the adler32 value
 108.567 +   of the dictionary; the decompressor may later use this value to determine
 108.568 +   which dictionary has been used by the compressor. (The adler32 value
 108.569 +   applies to the whole dictionary even if only a subset of the dictionary is
 108.570 +   actually used by the compressor.) If a raw deflate was requested, then the
 108.571 +   adler32 value is not computed and strm->adler is not set.
 108.572 +
 108.573 +     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
 108.574 +   parameter is invalid (such as NULL dictionary) or the stream state is
 108.575 +   inconsistent (for example if deflate has already been called for this stream
 108.576 +   or if the compression method is bsort). deflateSetDictionary does not
 108.577 +   perform any compression: this will be done by deflate().
 108.578 +*/
 108.579 +
 108.580 +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
 108.581 +                                    z_streamp source));
 108.582 +/*
 108.583 +     Sets the destination stream as a complete copy of the source stream.
 108.584 +
 108.585 +     This function can be useful when several compression strategies will be
 108.586 +   tried, for example when there are several ways of pre-processing the input
 108.587 +   data with a filter. The streams that will be discarded should then be freed
 108.588 +   by calling deflateEnd.  Note that deflateCopy duplicates the internal
 108.589 +   compression state which can be quite large, so this strategy is slow and
 108.590 +   can consume lots of memory.
 108.591 +
 108.592 +     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
 108.593 +   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
 108.594 +   (such as zalloc being NULL). msg is left unchanged in both source and
 108.595 +   destination.
 108.596 +*/
 108.597 +
 108.598 +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
 108.599 +/*
 108.600 +     This function is equivalent to deflateEnd followed by deflateInit,
 108.601 +   but does not free and reallocate all the internal compression state.
 108.602 +   The stream will keep the same compression level and any other attributes
 108.603 +   that may have been set by deflateInit2.
 108.604 +
 108.605 +      deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
 108.606 +   stream state was inconsistent (such as zalloc or state being NULL).
 108.607 +*/
 108.608 +
 108.609 +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
 108.610 +                                      int level,
 108.611 +                                      int strategy));
 108.612 +/*
 108.613 +     Dynamically update the compression level and compression strategy.  The
 108.614 +   interpretation of level and strategy is as in deflateInit2.  This can be
 108.615 +   used to switch between compression and straight copy of the input data, or
 108.616 +   to switch to a different kind of input data requiring a different
 108.617 +   strategy. If the compression level is changed, the input available so far
 108.618 +   is compressed with the old level (and may be flushed); the new level will
 108.619 +   take effect only at the next call of deflate().
 108.620 +
 108.621 +     Before the call of deflateParams, the stream state must be set as for
 108.622 +   a call of deflate(), since the currently available input may have to
 108.623 +   be compressed and flushed. In particular, strm->avail_out must be non-zero.
 108.624 +
 108.625 +     deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
 108.626 +   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
 108.627 +   if strm->avail_out was zero.
 108.628 +*/
 108.629 +
 108.630 +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
 108.631 +                                    int good_length,
 108.632 +                                    int max_lazy,
 108.633 +                                    int nice_length,
 108.634 +                                    int max_chain));
 108.635 +/*
 108.636 +     Fine tune deflate's internal compression parameters.  This should only be
 108.637 +   used by someone who understands the algorithm used by zlib's deflate for
 108.638 +   searching for the best matching string, and even then only by the most
 108.639 +   fanatic optimizer trying to squeeze out the last compressed bit for their
 108.640 +   specific input data.  Read the deflate.c source code for the meaning of the
 108.641 +   max_lazy, good_length, nice_length, and max_chain parameters.
 108.642 +
 108.643 +     deflateTune() can be called after deflateInit() or deflateInit2(), and
 108.644 +   returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
 108.645 + */
 108.646 +
 108.647 +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
 108.648 +                                       uLong sourceLen));
 108.649 +/*
 108.650 +     deflateBound() returns an upper bound on the compressed size after
 108.651 +   deflation of sourceLen bytes.  It must be called after deflateInit()
 108.652 +   or deflateInit2().  This would be used to allocate an output buffer
 108.653 +   for deflation in a single pass, and so would be called before deflate().
 108.654 +*/
 108.655 +
 108.656 +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
 108.657 +                                     int bits,
 108.658 +                                     int value));
 108.659 +/*
 108.660 +     deflatePrime() inserts bits in the deflate output stream.  The intent
 108.661 +  is that this function is used to start off the deflate output with the
 108.662 +  bits leftover from a previous deflate stream when appending to it.  As such,
 108.663 +  this function can only be used for raw deflate, and must be used before the
 108.664 +  first deflate() call after a deflateInit2() or deflateReset().  bits must be
 108.665 +  less than or equal to 16, and that many of the least significant bits of
 108.666 +  value will be inserted in the output.
 108.667 +
 108.668 +      deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
 108.669 +   stream state was inconsistent.
 108.670 +*/
 108.671 +
 108.672 +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
 108.673 +                                         gz_headerp head));
 108.674 +/*
 108.675 +      deflateSetHeader() provides gzip header information for when a gzip
 108.676 +   stream is requested by deflateInit2().  deflateSetHeader() may be called
 108.677 +   after deflateInit2() or deflateReset() and before the first call of
 108.678 +   deflate().  The text, time, os, extra field, name, and comment information
 108.679 +   in the provided gz_header structure are written to the gzip header (xflag is
 108.680 +   ignored -- the extra flags are set according to the compression level).  The
 108.681 +   caller must assure that, if not Z_NULL, name and comment are terminated with
 108.682 +   a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
 108.683 +   available there.  If hcrc is true, a gzip header crc is included.  Note that
 108.684 +   the current versions of the command-line version of gzip (up through version
 108.685 +   1.3.x) do not support header crc's, and will report that it is a "multi-part
 108.686 +   gzip file" and give up.
 108.687 +
 108.688 +      If deflateSetHeader is not used, the default gzip header has text false,
 108.689 +   the time set to zero, and os set to 255, with no extra, name, or comment
 108.690 +   fields.  The gzip header is returned to the default state by deflateReset().
 108.691 +
 108.692 +      deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
 108.693 +   stream state was inconsistent.
 108.694 +*/
 108.695 +
 108.696 +/*
 108.697 +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
 108.698 +                                     int  windowBits));
 108.699 +
 108.700 +     This is another version of inflateInit with an extra parameter. The
 108.701 +   fields next_in, avail_in, zalloc, zfree and opaque must be initialized
 108.702 +   before by the caller.
 108.703 +
 108.704 +     The windowBits parameter is the base two logarithm of the maximum window
 108.705 +   size (the size of the history buffer).  It should be in the range 8..15 for
 108.706 +   this version of the library. The default value is 15 if inflateInit is used
 108.707 +   instead. windowBits must be greater than or equal to the windowBits value
 108.708 +   provided to deflateInit2() while compressing, or it must be equal to 15 if
 108.709 +   deflateInit2() was not used. If a compressed stream with a larger window
 108.710 +   size is given as input, inflate() will return with the error code
 108.711 +   Z_DATA_ERROR instead of trying to allocate a larger window.
 108.712 +
 108.713 +     windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
 108.714 +   determines the window size. inflate() will then process raw deflate data,
 108.715 +   not looking for a zlib or gzip header, not generating a check value, and not
 108.716 +   looking for any check values for comparison at the end of the stream. This
 108.717 +   is for use with other formats that use the deflate compressed data format
 108.718 +   such as zip.  Those formats provide their own check values. If a custom
 108.719 +   format is developed using the raw deflate format for compressed data, it is
 108.720 +   recommended that a check value such as an adler32 or a crc32 be applied to
 108.721 +   the uncompressed data as is done in the zlib, gzip, and zip formats.  For
 108.722 +   most applications, the zlib format should be used as is. Note that comments
 108.723 +   above on the use in deflateInit2() applies to the magnitude of windowBits.
 108.724 +
 108.725 +     windowBits can also be greater than 15 for optional gzip decoding. Add
 108.726 +   32 to windowBits to enable zlib and gzip decoding with automatic header
 108.727 +   detection, or add 16 to decode only the gzip format (the zlib format will
 108.728 +   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is
 108.729 +   a crc32 instead of an adler32.
 108.730 +
 108.731 +     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
 108.732 +   memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
 108.733 +   is set to null if there is no error message.  inflateInit2 does not perform
 108.734 +   any decompression apart from reading the zlib header if present: this will
 108.735 +   be done by inflate(). (So next_in and avail_in may be modified, but next_out
 108.736 +   and avail_out are unchanged.)
 108.737 +*/
 108.738 +
 108.739 +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
 108.740 +                                             const Bytef *dictionary,
 108.741 +                                             uInt  dictLength));
 108.742 +/*
 108.743 +     Initializes the decompression dictionary from the given uncompressed byte
 108.744 +   sequence. This function must be called immediately after a call of inflate,
 108.745 +   if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
 108.746 +   can be determined from the adler32 value returned by that call of inflate.
 108.747 +   The compressor and decompressor must use exactly the same dictionary (see
 108.748 +   deflateSetDictionary).  For raw inflate, this function can be called
 108.749 +   immediately after inflateInit2() or inflateReset() and before any call of
 108.750 +   inflate() to set the dictionary.  The application must insure that the
 108.751 +   dictionary that was used for compression is provided.
 108.752 +
 108.753 +     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
 108.754 +   parameter is invalid (such as NULL dictionary) or the stream state is
 108.755 +   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
 108.756 +   expected one (incorrect adler32 value). inflateSetDictionary does not
 108.757 +   perform any decompression: this will be done by subsequent calls of
 108.758 +   inflate().
 108.759 +*/
 108.760 +
 108.761 +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
 108.762 +/*
 108.763 +    Skips invalid compressed data until a full flush point (see above the
 108.764 +  description of deflate with Z_FULL_FLUSH) can be found, or until all
 108.765 +  available input is skipped. No output is provided.
 108.766 +
 108.767 +    inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
 108.768 +  if no more input was provided, Z_DATA_ERROR if no flush point has been found,
 108.769 +  or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
 108.770 +  case, the application may save the current current value of total_in which
 108.771 +  indicates where valid compressed data was found. In the error case, the
 108.772 +  application may repeatedly call inflateSync, providing more input each time,
 108.773 +  until success or end of the input data.
 108.774 +*/
 108.775 +
 108.776 +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
 108.777 +                                    z_streamp source));
 108.778 +/*
 108.779 +     Sets the destination stream as a complete copy of the source stream.
 108.780 +
 108.781 +     This function can be useful when randomly accessing a large stream.  The
 108.782 +   first pass through the stream can periodically record the inflate state,
 108.783 +   allowing restarting inflate at those points when randomly accessing the
 108.784 +   stream.
 108.785 +
 108.786 +     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
 108.787 +   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
 108.788 +   (such as zalloc being NULL). msg is left unchanged in both source and
 108.789 +   destination.
 108.790 +*/
 108.791 +
 108.792 +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
 108.793 +/*
 108.794 +     This function is equivalent to inflateEnd followed by inflateInit,
 108.795 +   but does not free and reallocate all the internal decompression state.
 108.796 +   The stream will keep attributes that may have been set by inflateInit2.
 108.797 +
 108.798 +      inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
 108.799 +   stream state was inconsistent (such as zalloc or state being NULL).
 108.800 +*/
 108.801 +
 108.802 +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
 108.803 +                                     int bits,
 108.804 +                                     int value));
 108.805 +/*
 108.806 +     This function inserts bits in the inflate input stream.  The intent is
 108.807 +  that this function is used to start inflating at a bit position in the
 108.808 +  middle of a byte.  The provided bits will be used before any bytes are used
 108.809 +  from next_in.  This function should only be used with raw inflate, and
 108.810 +  should be used before the first inflate() call after inflateInit2() or
 108.811 +  inflateReset().  bits must be less than or equal to 16, and that many of the
 108.812 +  least significant bits of value will be inserted in the input.
 108.813 +
 108.814 +      inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
 108.815 +   stream state was inconsistent.
 108.816 +*/
 108.817 +
 108.818 +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
 108.819 +                                         gz_headerp head));
 108.820 +/*
 108.821 +      inflateGetHeader() requests that gzip header information be stored in the
 108.822 +   provided gz_header structure.  inflateGetHeader() may be called after
 108.823 +   inflateInit2() or inflateReset(), and before the first call of inflate().
 108.824 +   As inflate() processes the gzip stream, head->done is zero until the header
 108.825 +   is completed, at which time head->done is set to one.  If a zlib stream is
 108.826 +   being decoded, then head->done is set to -1 to indicate that there will be
 108.827 +   no gzip header information forthcoming.  Note that Z_BLOCK can be used to
 108.828 +   force inflate() to return immediately after header processing is complete
 108.829 +   and before any actual data is decompressed.
 108.830 +
 108.831 +      The text, time, xflags, and os fields are filled in with the gzip header
 108.832 +   contents.  hcrc is set to true if there is a header CRC.  (The header CRC
 108.833 +   was valid if done is set to one.)  If extra is not Z_NULL, then extra_max
 108.834 +   contains the maximum number of bytes to write to extra.  Once done is true,
 108.835 +   extra_len contains the actual extra field length, and extra contains the
 108.836 +   extra field, or that field truncated if extra_max is less than extra_len.
 108.837 +   If name is not Z_NULL, then up to name_max characters are written there,
 108.838 +   terminated with a zero unless the length is greater than name_max.  If
 108.839 +   comment is not Z_NULL, then up to comm_max characters are written there,
 108.840 +   terminated with a zero unless the length is greater than comm_max.  When
 108.841 +   any of extra, name, or comment are not Z_NULL and the respective field is
 108.842 +   not present in the header, then that field is set to Z_NULL to signal its
 108.843 +   absence.  This allows the use of deflateSetHeader() with the returned
 108.844 +   structure to duplicate the header.  However if those fields are set to
 108.845 +   allocated memory, then the application will need to save those pointers
 108.846 +   elsewhere so that they can be eventually freed.
 108.847 +
 108.848 +      If inflateGetHeader is not used, then the header information is simply
 108.849 +   discarded.  The header is always checked for validity, including the header
 108.850 +   CRC if present.  inflateReset() will reset the process to discard the header
 108.851 +   information.  The application would need to call inflateGetHeader() again to
 108.852 +   retrieve the header from the next gzip stream.
 108.853 +
 108.854 +      inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
 108.855 +   stream state was inconsistent.
 108.856 +*/
 108.857 +
 108.858 +/*
 108.859 +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
 108.860 +                                        unsigned char FAR *window));
 108.861 +
 108.862 +     Initialize the internal stream state for decompression using inflateBack()
 108.863 +   calls.  The fields zalloc, zfree and opaque in strm must be initialized
 108.864 +   before the call.  If zalloc and zfree are Z_NULL, then the default library-
 108.865 +   derived memory allocation routines are used.  windowBits is the base two
 108.866 +   logarithm of the window size, in the range 8..15.  window is a caller
 108.867 +   supplied buffer of that size.  Except for special applications where it is
 108.868 +   assured that deflate was used with small window sizes, windowBits must be 15
 108.869 +   and a 32K byte window must be supplied to be able to decompress general
 108.870 +   deflate streams.
 108.871 +
 108.872 +     See inflateBack() for the usage of these routines.
 108.873 +
 108.874 +     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
 108.875 +   the paramaters are invalid, Z_MEM_ERROR if the internal state could not
 108.876 +   be allocated, or Z_VERSION_ERROR if the version of the library does not
 108.877 +   match the version of the header file.
 108.878 +*/
 108.879 +
 108.880 +typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
 108.881 +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
 108.882 +
 108.883 +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
 108.884 +                                    in_func in, void FAR *in_desc,
 108.885 +                                    out_func out, void FAR *out_desc));
 108.886 +/*
 108.887 +     inflateBack() does a raw inflate with a single call using a call-back
 108.888 +   interface for input and output.  This is more efficient than inflate() for
 108.889 +   file i/o applications in that it avoids copying between the output and the
 108.890 +   sliding window by simply making the window itself the output buffer.  This
 108.891 +   function trusts the application to not change the output buffer passed by
 108.892 +   the output function, at least until inflateBack() returns.
 108.893 +
 108.894 +     inflateBackInit() must be called first to allocate the internal state
 108.895 +   and to initialize the state with the user-provided window buffer.
 108.896 +   inflateBack() may then be used multiple times to inflate a complete, raw
 108.897 +   deflate stream with each call.  inflateBackEnd() is then called to free
 108.898 +   the allocated state.
 108.899 +
 108.900 +     A raw deflate stream is one with no zlib or gzip header or trailer.
 108.901 +   This routine would normally be used in a utility that reads zip or gzip
 108.902 +   files and writes out uncompressed files.  The utility would decode the
 108.903 +   header and process the trailer on its own, hence this routine expects
 108.904 +   only the raw deflate stream to decompress.  This is different from the
 108.905 +   normal behavior of inflate(), which expects either a zlib or gzip header and
 108.906 +   trailer around the deflate stream.
 108.907 +
 108.908 +     inflateBack() uses two subroutines supplied by the caller that are then
 108.909 +   called by inflateBack() for input and output.  inflateBack() calls those
 108.910 +   routines until it reads a complete deflate stream and writes out all of the
 108.911 +   uncompressed data, or until it encounters an error.  The function's
 108.912 +   parameters and return types are defined above in the in_func and out_func
 108.913 +   typedefs.  inflateBack() will call in(in_desc, &buf) which should return the
 108.914 +   number of bytes of provided input, and a pointer to that input in buf.  If
 108.915 +   there is no input available, in() must return zero--buf is ignored in that
 108.916 +   case--and inflateBack() will return a buffer error.  inflateBack() will call
 108.917 +   out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].  out()
 108.918 +   should return zero on success, or non-zero on failure.  If out() returns
 108.919 +   non-zero, inflateBack() will return with an error.  Neither in() nor out()
 108.920 +   are permitted to change the contents of the window provided to
 108.921 +   inflateBackInit(), which is also the buffer that out() uses to write from.
 108.922 +   The length written by out() will be at most the window size.  Any non-zero
 108.923 +   amount of input may be provided by in().
 108.924 +
 108.925 +     For convenience, inflateBack() can be provided input on the first call by
 108.926 +   setting strm->next_in and strm->avail_in.  If that input is exhausted, then
 108.927 +   in() will be called.  Therefore strm->next_in must be initialized before
 108.928 +   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called
 108.929 +   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in
 108.930 +   must also be initialized, and then if strm->avail_in is not zero, input will
 108.931 +   initially be taken from strm->next_in[0 .. strm->avail_in - 1].
 108.932 +
 108.933 +     The in_desc and out_desc parameters of inflateBack() is passed as the
 108.934 +   first parameter of in() and out() respectively when they are called.  These
 108.935 +   descriptors can be optionally used to pass any information that the caller-
 108.936 +   supplied in() and out() functions need to do their job.
 108.937 +
 108.938 +     On return, inflateBack() will set strm->next_in and strm->avail_in to
 108.939 +   pass back any unused input that was provided by the last in() call.  The
 108.940 +   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
 108.941 +   if in() or out() returned an error, Z_DATA_ERROR if there was a format
 108.942 +   error in the deflate stream (in which case strm->msg is set to indicate the
 108.943 +   nature of the error), or Z_STREAM_ERROR if the stream was not properly
 108.944 +   initialized.  In the case of Z_BUF_ERROR, an input or output error can be
 108.945 +   distinguished using strm->next_in which will be Z_NULL only if in() returned
 108.946 +   an error.  If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
 108.947 +   out() returning non-zero.  (in() will always be called before out(), so
 108.948 +   strm->next_in is assured to be defined if out() returns non-zero.)  Note
 108.949 +   that inflateBack() cannot return Z_OK.
 108.950 +*/
 108.951 +
 108.952 +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
 108.953 +/*
 108.954 +     All memory allocated by inflateBackInit() is freed.
 108.955 +
 108.956 +     inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
 108.957 +   state was inconsistent.
 108.958 +*/
 108.959 +
 108.960 +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
 108.961 +/* Return flags indicating compile-time options.
 108.962 +
 108.963 +    Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
 108.964 +     1.0: size of uInt
 108.965 +     3.2: size of uLong
 108.966 +     5.4: size of voidpf (pointer)
 108.967 +     7.6: size of z_off_t
 108.968 +
 108.969 +    Compiler, assembler, and debug options:
 108.970 +     8: DEBUG
 108.971 +     9: ASMV or ASMINF -- use ASM code
 108.972 +     10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
 108.973 +     11: 0 (reserved)
 108.974 +
 108.975 +    One-time table building (smaller code, but not thread-safe if true):
 108.976 +     12: BUILDFIXED -- build static block decoding tables when needed
 108.977 +     13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
 108.978 +     14,15: 0 (reserved)
 108.979 +
 108.980 +    Library content (indicates missing functionality):
 108.981 +     16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
 108.982 +                          deflate code when not needed)
 108.983 +     17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
 108.984 +                    and decode gzip streams (to avoid linking crc code)
 108.985 +     18-19: 0 (reserved)
 108.986 +
 108.987 +    Operation variations (changes in library functionality):
 108.988 +     20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
 108.989 +     21: FASTEST -- deflate algorithm with only one, lowest compression level
 108.990 +     22,23: 0 (reserved)
 108.991 +
 108.992 +    The sprintf variant used by gzprintf (zero is best):
 108.993 +     24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
 108.994 +     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
 108.995 +     26: 0 = returns value, 1 = void -- 1 means inferred string length returned
 108.996 +
 108.997 +    Remainder:
 108.998 +     27-31: 0 (reserved)
 108.999 + */
108.1000 +
108.1001 +
108.1002 +                        /* utility functions */
108.1003 +
108.1004 +/*
108.1005 +     The following utility functions are implemented on top of the
108.1006 +   basic stream-oriented functions. To simplify the interface, some
108.1007 +   default options are assumed (compression level and memory usage,
108.1008 +   standard memory allocation functions). The source code of these
108.1009 +   utility functions can easily be modified if you need special options.
108.1010 +*/
108.1011 +
108.1012 +ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
108.1013 +                                 const Bytef *source, uLong sourceLen));
108.1014 +/*
108.1015 +     Compresses the source buffer into the destination buffer.  sourceLen is
108.1016 +   the byte length of the source buffer. Upon entry, destLen is the total
108.1017 +   size of the destination buffer, which must be at least the value returned
108.1018 +   by compressBound(sourceLen). Upon exit, destLen is the actual size of the
108.1019 +   compressed buffer.
108.1020 +     This function can be used to compress a whole file at once if the
108.1021 +   input file is mmap'ed.
108.1022 +     compress returns Z_OK if success, Z_MEM_ERROR if there was not
108.1023 +   enough memory, Z_BUF_ERROR if there was not enough room in the output
108.1024 +   buffer.
108.1025 +*/
108.1026 +
108.1027 +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
108.1028 +                                  const Bytef *source, uLong sourceLen,
108.1029 +                                  int level));
108.1030 +/*
108.1031 +     Compresses the source buffer into the destination buffer. The level
108.1032 +   parameter has the same meaning as in deflateInit.  sourceLen is the byte
108.1033 +   length of the source buffer. Upon entry, destLen is the total size of the
108.1034 +   destination buffer, which must be at least the value returned by
108.1035 +   compressBound(sourceLen). Upon exit, destLen is the actual size of the
108.1036 +   compressed buffer.
108.1037 +
108.1038 +     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
108.1039 +   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
108.1040 +   Z_STREAM_ERROR if the level parameter is invalid.
108.1041 +*/
108.1042 +
108.1043 +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
108.1044 +/*
108.1045 +     compressBound() returns an upper bound on the compressed size after
108.1046 +   compress() or compress2() on sourceLen bytes.  It would be used before
108.1047 +   a compress() or compress2() call to allocate the destination buffer.
108.1048 +*/
108.1049 +
108.1050 +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
108.1051 +                                   const Bytef *source, uLong sourceLen));
108.1052 +/*
108.1053 +     Decompresses the source buffer into the destination buffer.  sourceLen is
108.1054 +   the byte length of the source buffer. Upon entry, destLen is the total
108.1055 +   size of the destination buffer, which must be large enough to hold the
108.1056 +   entire uncompressed data. (The size of the uncompressed data must have
108.1057 +   been saved previously by the compressor and transmitted to the decompressor
108.1058 +   by some mechanism outside the scope of this compression library.)
108.1059 +   Upon exit, destLen is the actual size of the compressed buffer.
108.1060 +     This function can be used to decompress a whole file at once if the
108.1061 +   input file is mmap'ed.
108.1062 +
108.1063 +     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
108.1064 +   enough memory, Z_BUF_ERROR if there was not enough room in the output
108.1065 +   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
108.1066 +*/
108.1067 +
108.1068 +
108.1069 +typedef voidp gzFile;
108.1070 +
108.1071 +ZEXTERN gzFile ZEXPORT gzopen  OF((const char *path, const char *mode));
108.1072 +/*
108.1073 +     Opens a gzip (.gz) file for reading or writing. The mode parameter
108.1074 +   is as in fopen ("rb" or "wb") but can also include a compression level
108.1075 +   ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
108.1076 +   Huffman only compression as in "wb1h", or 'R' for run-length encoding
108.1077 +   as in "wb1R". (See the description of deflateInit2 for more information
108.1078 +   about the strategy parameter.)
108.1079 +
108.1080 +     gzopen can be used to read a file which is not in gzip format; in this
108.1081 +   case gzread will directly read from the file without decompression.
108.1082 +
108.1083 +     gzopen returns NULL if the file could not be opened or if there was
108.1084 +   insufficient memory to allocate the (de)compression state; errno
108.1085 +   can be checked to distinguish the two cases (if errno is zero, the
108.1086 +   zlib error is Z_MEM_ERROR).  */
108.1087 +
108.1088 +ZEXTERN gzFile ZEXPORT gzdopen  OF((int fd, const char *mode));
108.1089 +/*
108.1090 +     gzdopen() associates a gzFile with the file descriptor fd.  File
108.1091 +   descriptors are obtained from calls like open, dup, creat, pipe or
108.1092 +   fileno (in the file has been previously opened with fopen).
108.1093 +   The mode parameter is as in gzopen.
108.1094 +     The next call of gzclose on the returned gzFile will also close the
108.1095 +   file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
108.1096 +   descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
108.1097 +     gzdopen returns NULL if there was insufficient memory to allocate
108.1098 +   the (de)compression state.
108.1099 +*/
108.1100 +
108.1101 +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
108.1102 +/*
108.1103 +     Dynamically update the compression level or strategy. See the description
108.1104 +   of deflateInit2 for the meaning of these parameters.
108.1105 +     gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
108.1106 +   opened for writing.
108.1107 +*/
108.1108 +
108.1109 +ZEXTERN int ZEXPORT    gzread  OF((gzFile file, voidp buf, unsigned len));
108.1110 +/*
108.1111 +     Reads the given number of uncompressed bytes from the compressed file.
108.1112 +   If the input file was not in gzip format, gzread copies the given number
108.1113 +   of bytes into the buffer.
108.1114 +     gzread returns the number of uncompressed bytes actually read (0 for
108.1115 +   end of file, -1 for error). */
108.1116 +
108.1117 +ZEXTERN int ZEXPORT    gzwrite OF((gzFile file,
108.1118 +                                   voidpc buf, unsigned len));
108.1119 +/*
108.1120 +     Writes the given number of uncompressed bytes into the compressed file.
108.1121 +   gzwrite returns the number of uncompressed bytes actually written
108.1122 +   (0 in case of error).
108.1123 +*/
108.1124 +
108.1125 +ZEXTERN int ZEXPORTVA   gzprintf OF((gzFile file, const char *format, ...));
108.1126 +/*
108.1127 +     Converts, formats, and writes the args to the compressed file under
108.1128 +   control of the format string, as in fprintf. gzprintf returns the number of
108.1129 +   uncompressed bytes actually written (0 in case of error).  The number of
108.1130 +   uncompressed bytes written is limited to 4095. The caller should assure that
108.1131 +   this limit is not exceeded. If it is exceeded, then gzprintf() will return
108.1132 +   return an error (0) with nothing written. In this case, there may also be a
108.1133 +   buffer overflow with unpredictable consequences, which is possible only if
108.1134 +   zlib was compiled with the insecure functions sprintf() or vsprintf()
108.1135 +   because the secure snprintf() or vsnprintf() functions were not available.
108.1136 +*/
108.1137 +
108.1138 +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
108.1139 +/*
108.1140 +      Writes the given null-terminated string to the compressed file, excluding
108.1141 +   the terminating null character.
108.1142 +      gzputs returns the number of characters written, or -1 in case of error.
108.1143 +*/
108.1144 +
108.1145 +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
108.1146 +/*
108.1147 +      Reads bytes from the compressed file until len-1 characters are read, or
108.1148 +   a newline character is read and transferred to buf, or an end-of-file
108.1149 +   condition is encountered.  The string is then terminated with a null
108.1150 +   character.
108.1151 +      gzgets returns buf, or Z_NULL in case of error.
108.1152 +*/
108.1153 +
108.1154 +ZEXTERN int ZEXPORT    gzputc OF((gzFile file, int c));
108.1155 +/*
108.1156 +      Writes c, converted to an unsigned char, into the compressed file.
108.1157 +   gzputc returns the value that was written, or -1 in case of error.
108.1158 +*/
108.1159 +
108.1160 +ZEXTERN int ZEXPORT    gzgetc OF((gzFile file));
108.1161 +/*
108.1162 +      Reads one byte from the compressed file. gzgetc returns this byte
108.1163 +   or -1 in case of end of file or error.
108.1164 +*/
108.1165 +
108.1166 +ZEXTERN int ZEXPORT    gzungetc OF((int c, gzFile file));
108.1167 +/*
108.1168 +      Push one character back onto the stream to be read again later.
108.1169 +   Only one character of push-back is allowed.  gzungetc() returns the
108.1170 +   character pushed, or -1 on failure.  gzungetc() will fail if a
108.1171 +   character has been pushed but not read yet, or if c is -1. The pushed
108.1172 +   character will be discarded if the stream is repositioned with gzseek()
108.1173 +   or gzrewind().
108.1174 +*/
108.1175 +
108.1176 +ZEXTERN int ZEXPORT    gzflush OF((gzFile file, int flush));
108.1177 +/*
108.1178 +     Flushes all pending output into the compressed file. The parameter
108.1179 +   flush is as in the deflate() function. The return value is the zlib
108.1180 +   error number (see function gzerror below). gzflush returns Z_OK if
108.1181 +   the flush parameter is Z_FINISH and all output could be flushed.
108.1182 +     gzflush should be called only when strictly necessary because it can
108.1183 +   degrade compression.
108.1184 +*/
108.1185 +
108.1186 +ZEXTERN z_off_t ZEXPORT    gzseek OF((gzFile file,
108.1187 +                                      z_off_t offset, int whence));
108.1188 +/*
108.1189 +      Sets the starting position for the next gzread or gzwrite on the
108.1190 +   given compressed file. The offset represents a number of bytes in the
108.1191 +   uncompressed data stream. The whence parameter is defined as in lseek(2);
108.1192 +   the value SEEK_END is not supported.
108.1193 +     If the file is opened for reading, this function is emulated but can be
108.1194 +   extremely slow. If the file is opened for writing, only forward seeks are
108.1195 +   supported; gzseek then compresses a sequence of zeroes up to the new
108.1196 +   starting position.
108.1197 +
108.1198 +      gzseek returns the resulting offset location as measured in bytes from
108.1199 +   the beginning of the uncompressed stream, or -1 in case of error, in
108.1200 +   particular if the file is opened for writing and the new starting position
108.1201 +   would be before the current position.
108.1202 +*/
108.1203 +
108.1204 +ZEXTERN int ZEXPORT    gzrewind OF((gzFile file));
108.1205 +/*
108.1206 +     Rewinds the given file. This function is supported only for reading.
108.1207 +
108.1208 +   gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
108.1209 +*/
108.1210 +
108.1211 +ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
108.1212 +/*
108.1213 +     Returns the starting position for the next gzread or gzwrite on the
108.1214 +   given compressed file. This position represents a number of bytes in the
108.1215 +   uncompressed data stream.
108.1216 +
108.1217 +   gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
108.1218 +*/
108.1219 +
108.1220 +ZEXTERN int ZEXPORT gzeof OF((gzFile file));
108.1221 +/*
108.1222 +     Returns 1 when EOF has previously been detected reading the given
108.1223 +   input stream, otherwise zero.
108.1224 +*/
108.1225 +
108.1226 +ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
108.1227 +/*
108.1228 +     Returns 1 if file is being read directly without decompression, otherwise
108.1229 +   zero.
108.1230 +*/
108.1231 +
108.1232 +ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
108.1233 +/*
108.1234 +     Flushes all pending output if necessary, closes the compressed file
108.1235 +   and deallocates all the (de)compression state. The return value is the zlib
108.1236 +   error number (see function gzerror below).
108.1237 +*/
108.1238 +
108.1239 +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
108.1240 +/*
108.1241 +     Returns the error message for the last error which occurred on the
108.1242 +   given compressed file. errnum is set to zlib error number. If an
108.1243 +   error occurred in the file system and not in the compression library,
108.1244 +   errnum is set to Z_ERRNO and the application may consult errno
108.1245 +   to get the exact error code.
108.1246 +*/
108.1247 +
108.1248 +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
108.1249 +/*
108.1250 +     Clears the error and end-of-file flags for file. This is analogous to the
108.1251 +   clearerr() function in stdio. This is useful for continuing to read a gzip
108.1252 +   file that is being written concurrently.
108.1253 +*/
108.1254 +
108.1255 +                        /* checksum functions */
108.1256 +
108.1257 +/*
108.1258 +     These functions are not related to compression but are exported
108.1259 +   anyway because they might be useful in applications using the
108.1260 +   compression library.
108.1261 +*/
108.1262 +
108.1263 +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
108.1264 +/*
108.1265 +     Update a running Adler-32 checksum with the bytes buf[0..len-1] and
108.1266 +   return the updated checksum. If buf is NULL, this function returns
108.1267 +   the required initial value for the checksum.
108.1268 +   An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
108.1269 +   much faster. Usage example:
108.1270 +
108.1271 +     uLong adler = adler32(0L, Z_NULL, 0);
108.1272 +
108.1273 +     while (read_buffer(buffer, length) != EOF) {
108.1274 +       adler = adler32(adler, buffer, length);
108.1275 +     }
108.1276 +     if (adler != original_adler) error();
108.1277 +*/
108.1278 +
108.1279 +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
108.1280 +                                          z_off_t len2));
108.1281 +/*
108.1282 +     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1
108.1283 +   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
108.1284 +   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of
108.1285 +   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
108.1286 +*/
108.1287 +
108.1288 +ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
108.1289 +/*
108.1290 +     Update a running CRC-32 with the bytes buf[0..len-1] and return the
108.1291 +   updated CRC-32. If buf is NULL, this function returns the required initial
108.1292 +   value for the for the crc. Pre- and post-conditioning (one's complement) is
108.1293 +   performed within this function so it shouldn't be done by the application.
108.1294 +   Usage example:
108.1295 +
108.1296 +     uLong crc = crc32(0L, Z_NULL, 0);
108.1297 +
108.1298 +     while (read_buffer(buffer, length) != EOF) {
108.1299 +       crc = crc32(crc, buffer, length);
108.1300 +     }
108.1301 +     if (crc != original_crc) error();
108.1302 +*/
108.1303 +
108.1304 +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
108.1305 +
108.1306 +/*
108.1307 +     Combine two CRC-32 check values into one.  For two sequences of bytes,
108.1308 +   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
108.1309 +   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32
108.1310 +   check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
108.1311 +   len2.
108.1312 +*/
108.1313 +
108.1314 +
108.1315 +                        /* various hacks, don't look :) */
108.1316 +
108.1317 +/* deflateInit and inflateInit are macros to allow checking the zlib version
108.1318 + * and the compiler's view of z_stream:
108.1319 + */
108.1320 +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
108.1321 +                                     const char *version, int stream_size));
108.1322 +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
108.1323 +                                     const char *version, int stream_size));
108.1324 +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,
108.1325 +                                      int windowBits, int memLevel,
108.1326 +                                      int strategy, const char *version,
108.1327 +                                      int stream_size));
108.1328 +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,
108.1329 +                                      const char *version, int stream_size));
108.1330 +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
108.1331 +                                         unsigned char FAR *window,
108.1332 +                                         const char *version,
108.1333 +                                         int stream_size));
108.1334 +#define deflateInit(strm, level) \
108.1335 +        deflateInit_((strm), (level),       ZLIB_VERSION, sizeof(z_stream))
108.1336 +#define inflateInit(strm) \
108.1337 +        inflateInit_((strm),                ZLIB_VERSION, sizeof(z_stream))
108.1338 +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
108.1339 +        deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
108.1340 +                      (strategy),           ZLIB_VERSION, sizeof(z_stream))
108.1341 +#define inflateInit2(strm, windowBits) \
108.1342 +        inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
108.1343 +#define inflateBackInit(strm, windowBits, window) \
108.1344 +        inflateBackInit_((strm), (windowBits), (window), \
108.1345 +        ZLIB_VERSION, sizeof(z_stream))
108.1346 +
108.1347 +
108.1348 +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
108.1349 +    struct internal_state {int dummy;}; /* hack for buggy compilers */
108.1350 +#endif
108.1351 +
108.1352 +ZEXTERN const char   * ZEXPORT zError           OF((int));
108.1353 +ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp z));
108.1354 +ZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));
108.1355 +
108.1356 +#ifdef __cplusplus
108.1357 +}
108.1358 +#endif
108.1359 +
108.1360 +#endif /* ZLIB_H */
   109.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   109.2 +++ b/libs/zlib/zutil.c	Thu Sep 08 06:28:38 2011 +0300
   109.3 @@ -0,0 +1,318 @@
   109.4 +/* zutil.c -- target dependent utility functions for the compression library
   109.5 + * Copyright (C) 1995-2005 Jean-loup Gailly.
   109.6 + * For conditions of distribution and use, see copyright notice in zlib.h
   109.7 + */
   109.8 +
   109.9 +/* @(#) $Id$ */
  109.10 +
  109.11 +#include "zutil.h"
  109.12 +
  109.13 +#ifndef NO_DUMMY_DECL
  109.14 +struct internal_state      {int dummy;}; /* for buggy compilers */
  109.15 +#endif
  109.16 +
  109.17 +const char * const z_errmsg[10] = {
  109.18 +"need dictionary",     /* Z_NEED_DICT       2  */
  109.19 +"stream end",          /* Z_STREAM_END      1  */
  109.20 +"",                    /* Z_OK              0  */
  109.21 +"file error",          /* Z_ERRNO         (-1) */
  109.22 +"stream error",        /* Z_STREAM_ERROR  (-2) */
  109.23 +"data error",          /* Z_DATA_ERROR    (-3) */
  109.24 +"insufficient memory", /* Z_MEM_ERROR     (-4) */
  109.25 +"buffer error",        /* Z_BUF_ERROR     (-5) */
  109.26 +"incompatible version",/* Z_VERSION_ERROR (-6) */
  109.27 +""};
  109.28 +
  109.29 +
  109.30 +const char * ZEXPORT zlibVersion()
  109.31 +{
  109.32 +    return ZLIB_VERSION;
  109.33 +}
  109.34 +
  109.35 +uLong ZEXPORT zlibCompileFlags()
  109.36 +{
  109.37 +    uLong flags;
  109.38 +
  109.39 +    flags = 0;
  109.40 +    switch (sizeof(uInt)) {
  109.41 +    case 2:     break;
  109.42 +    case 4:     flags += 1;     break;
  109.43 +    case 8:     flags += 2;     break;
  109.44 +    default:    flags += 3;
  109.45 +    }
  109.46 +    switch (sizeof(uLong)) {
  109.47 +    case 2:     break;
  109.48 +    case 4:     flags += 1 << 2;        break;
  109.49 +    case 8:     flags += 2 << 2;        break;
  109.50 +    default:    flags += 3 << 2;
  109.51 +    }
  109.52 +    switch (sizeof(voidpf)) {
  109.53 +    case 2:     break;
  109.54 +    case 4:     flags += 1 << 4;        break;
  109.55 +    case 8:     flags += 2 << 4;        break;
  109.56 +    default:    flags += 3 << 4;
  109.57 +    }
  109.58 +    switch (sizeof(z_off_t)) {
  109.59 +    case 2:     break;
  109.60 +    case 4:     flags += 1 << 6;        break;
  109.61 +    case 8:     flags += 2 << 6;        break;
  109.62 +    default:    flags += 3 << 6;
  109.63 +    }
  109.64 +#ifdef DEBUG
  109.65 +    flags += 1 << 8;
  109.66 +#endif
  109.67 +#if defined(ASMV) || defined(ASMINF)
  109.68 +    flags += 1 << 9;
  109.69 +#endif
  109.70 +#ifdef ZLIB_WINAPI
  109.71 +    flags += 1 << 10;
  109.72 +#endif
  109.73 +#ifdef BUILDFIXED
  109.74 +    flags += 1 << 12;
  109.75 +#endif
  109.76 +#ifdef DYNAMIC_CRC_TABLE
  109.77 +    flags += 1 << 13;
  109.78 +#endif
  109.79 +#ifdef NO_GZCOMPRESS
  109.80 +    flags += 1L << 16;
  109.81 +#endif
  109.82 +#ifdef NO_GZIP
  109.83 +    flags += 1L << 17;
  109.84 +#endif
  109.85 +#ifdef PKZIP_BUG_WORKAROUND
  109.86 +    flags += 1L << 20;
  109.87 +#endif
  109.88 +#ifdef FASTEST
  109.89 +    flags += 1L << 21;
  109.90 +#endif
  109.91 +#ifdef STDC
  109.92 +#  ifdef NO_vsnprintf
  109.93 +        flags += 1L << 25;
  109.94 +#    ifdef HAS_vsprintf_void
  109.95 +        flags += 1L << 26;
  109.96 +#    endif
  109.97 +#  else
  109.98 +#    ifdef HAS_vsnprintf_void
  109.99 +        flags += 1L << 26;
 109.100 +#    endif
 109.101 +#  endif
 109.102 +#else
 109.103 +        flags += 1L << 24;
 109.104 +#  ifdef NO_snprintf
 109.105 +        flags += 1L << 25;
 109.106 +#    ifdef HAS_sprintf_void
 109.107 +        flags += 1L << 26;
 109.108 +#    endif
 109.109 +#  else
 109.110 +#    ifdef HAS_snprintf_void
 109.111 +        flags += 1L << 26;
 109.112 +#    endif
 109.113 +#  endif
 109.114 +#endif
 109.115 +    return flags;
 109.116 +}
 109.117 +
 109.118 +#ifdef DEBUG
 109.119 +
 109.120 +#  ifndef verbose
 109.121 +#    define verbose 0
 109.122 +#  endif
 109.123 +int z_verbose = verbose;
 109.124 +
 109.125 +void z_error (m)
 109.126 +    char *m;
 109.127 +{
 109.128 +    fprintf(stderr, "%s\n", m);
 109.129 +    exit(1);
 109.130 +}
 109.131 +#endif
 109.132 +
 109.133 +/* exported to allow conversion of error code to string for compress() and
 109.134 + * uncompress()
 109.135 + */
 109.136 +const char * ZEXPORT zError(err)
 109.137 +    int err;
 109.138 +{
 109.139 +    return ERR_MSG(err);
 109.140 +}
 109.141 +
 109.142 +#if defined(_WIN32_WCE)
 109.143 +    /* The Microsoft C Run-Time Library for Windows CE doesn't have
 109.144 +     * errno.  We define it as a global variable to simplify porting.
 109.145 +     * Its value is always 0 and should not be used.
 109.146 +     */
 109.147 +    int errno = 0;
 109.148 +#endif
 109.149 +
 109.150 +#ifndef HAVE_MEMCPY
 109.151 +
 109.152 +void zmemcpy(dest, source, len)
 109.153 +    Bytef* dest;
 109.154 +    const Bytef* source;
 109.155 +    uInt  len;
 109.156 +{
 109.157 +    if (len == 0) return;
 109.158 +    do {
 109.159 +        *dest++ = *source++; /* ??? to be unrolled */
 109.160 +    } while (--len != 0);
 109.161 +}
 109.162 +
 109.163 +int zmemcmp(s1, s2, len)
 109.164 +    const Bytef* s1;
 109.165 +    const Bytef* s2;
 109.166 +    uInt  len;
 109.167 +{
 109.168 +    uInt j;
 109.169 +
 109.170 +    for (j = 0; j < len; j++) {
 109.171 +        if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
 109.172 +    }
 109.173 +    return 0;
 109.174 +}
 109.175 +
 109.176 +void zmemzero(dest, len)
 109.177 +    Bytef* dest;
 109.178 +    uInt  len;
 109.179 +{
 109.180 +    if (len == 0) return;
 109.181 +    do {
 109.182 +        *dest++ = 0;  /* ??? to be unrolled */
 109.183 +    } while (--len != 0);
 109.184 +}
 109.185 +#endif
 109.186 +
 109.187 +
 109.188 +#ifdef SYS16BIT
 109.189 +
 109.190 +#ifdef __TURBOC__
 109.191 +/* Turbo C in 16-bit mode */
 109.192 +
 109.193 +#  define MY_ZCALLOC
 109.194 +
 109.195 +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
 109.196 + * and farmalloc(64K) returns a pointer with an offset of 8, so we
 109.197 + * must fix the pointer. Warning: the pointer must be put back to its
 109.198 + * original form in order to free it, use zcfree().
 109.199 + */
 109.200 +
 109.201 +#define MAX_PTR 10
 109.202 +/* 10*64K = 640K */
 109.203 +
 109.204 +local int next_ptr = 0;
 109.205 +
 109.206 +typedef struct ptr_table_s {
 109.207 +    voidpf org_ptr;
 109.208 +    voidpf new_ptr;
 109.209 +} ptr_table;
 109.210 +
 109.211 +local ptr_table table[MAX_PTR];
 109.212 +/* This table is used to remember the original form of pointers
 109.213 + * to large buffers (64K). Such pointers are normalized with a zero offset.
 109.214 + * Since MSDOS is not a preemptive multitasking OS, this table is not
 109.215 + * protected from concurrent access. This hack doesn't work anyway on
 109.216 + * a protected system like OS/2. Use Microsoft C instead.
 109.217 + */
 109.218 +
 109.219 +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
 109.220 +{
 109.221 +    voidpf buf = opaque; /* just to make some compilers happy */
 109.222 +    ulg bsize = (ulg)items*size;
 109.223 +
 109.224 +    /* If we allocate less than 65520 bytes, we assume that farmalloc
 109.225 +     * will return a usable pointer which doesn't have to be normalized.
 109.226 +     */
 109.227 +    if (bsize < 65520L) {
 109.228 +        buf = farmalloc(bsize);
 109.229 +        if (*(ush*)&buf != 0) return buf;
 109.230 +    } else {
 109.231 +        buf = farmalloc(bsize + 16L);
 109.232 +    }
 109.233 +    if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
 109.234 +    table[next_ptr].org_ptr = buf;
 109.235 +
 109.236 +    /* Normalize the pointer to seg:0 */
 109.237 +    *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
 109.238 +    *(ush*)&buf = 0;
 109.239 +    table[next_ptr++].new_ptr = buf;
 109.240 +    return buf;
 109.241 +}
 109.242 +
 109.243 +void  zcfree (voidpf opaque, voidpf ptr)
 109.244 +{
 109.245 +    int n;
 109.246 +    if (*(ush*)&ptr != 0) { /* object < 64K */
 109.247 +        farfree(ptr);
 109.248 +        return;
 109.249 +    }
 109.250 +    /* Find the original pointer */
 109.251 +    for (n = 0; n < next_ptr; n++) {
 109.252 +        if (ptr != table[n].new_ptr) continue;
 109.253 +
 109.254 +        farfree(table[n].org_ptr);
 109.255 +        while (++n < next_ptr) {
 109.256 +            table[n-1] = table[n];
 109.257 +        }
 109.258 +        next_ptr--;
 109.259 +        return;
 109.260 +    }
 109.261 +    ptr = opaque; /* just to make some compilers happy */
 109.262 +    Assert(0, "zcfree: ptr not found");
 109.263 +}
 109.264 +
 109.265 +#endif /* __TURBOC__ */
 109.266 +
 109.267 +
 109.268 +#ifdef M_I86
 109.269 +/* Microsoft C in 16-bit mode */
 109.270 +
 109.271 +#  define MY_ZCALLOC
 109.272 +
 109.273 +#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
 109.274 +#  define _halloc  halloc
 109.275 +#  define _hfree   hfree
 109.276 +#endif
 109.277 +
 109.278 +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
 109.279 +{
 109.280 +    if (opaque) opaque = 0; /* to make compiler happy */
 109.281 +    return _halloc((long)items, size);
 109.282 +}
 109.283 +
 109.284 +void  zcfree (voidpf opaque, voidpf ptr)
 109.285 +{
 109.286 +    if (opaque) opaque = 0; /* to make compiler happy */
 109.287 +    _hfree(ptr);
 109.288 +}
 109.289 +
 109.290 +#endif /* M_I86 */
 109.291 +
 109.292 +#endif /* SYS16BIT */
 109.293 +
 109.294 +
 109.295 +#ifndef MY_ZCALLOC /* Any system without a special alloc function */
 109.296 +
 109.297 +#ifndef STDC
 109.298 +extern voidp  malloc OF((uInt size));
 109.299 +extern voidp  calloc OF((uInt items, uInt size));
 109.300 +extern void   free   OF((voidpf ptr));
 109.301 +#endif
 109.302 +
 109.303 +voidpf zcalloc (opaque, items, size)
 109.304 +    voidpf opaque;
 109.305 +    unsigned items;
 109.306 +    unsigned size;
 109.307 +{
 109.308 +    if (opaque) items += size - size; /* make compiler happy */
 109.309 +    return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
 109.310 +                              (voidpf)calloc(items, size);
 109.311 +}
 109.312 +
 109.313 +void  zcfree (opaque, ptr)
 109.314 +    voidpf opaque;
 109.315 +    voidpf ptr;
 109.316 +{
 109.317 +    free(ptr);
 109.318 +    if (opaque) return; /* make compiler happy */
 109.319 +}
 109.320 +
 109.321 +#endif /* MY_ZCALLOC */
   110.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
   110.2 +++ b/libs/zlib/zutil.h	Thu Sep 08 06:28:38 2011 +0300
   110.3 @@ -0,0 +1,269 @@
   110.4 +/* zutil.h -- internal interface and configuration of the compression library
   110.5 + * Copyright (C) 1995-2005 Jean-loup Gailly.
   110.6 + * For conditions of distribution and use, see copyright notice in zlib.h
   110.7 + */
   110.8 +
   110.9 +/* WARNING: this file should *not* be used by applications. It is
  110.10 +   part of the implementation of the compression library and is
  110.11 +   subject to change. Applications should only use zlib.h.
  110.12 + */
  110.13 +
  110.14 +/* @(#) $Id$ */
  110.15 +
  110.16 +#ifndef ZUTIL_H
  110.17 +#define ZUTIL_H
  110.18 +
  110.19 +#define ZLIB_INTERNAL
  110.20 +#include "zlib.h"
  110.21 +
  110.22 +#ifdef STDC
  110.23 +#  ifndef _WIN32_WCE
  110.24 +#    include <stddef.h>
  110.25 +#  endif
  110.26 +#  include <string.h>
  110.27 +#  include <stdlib.h>
  110.28 +#endif
  110.29 +#ifdef NO_ERRNO_H
  110.30 +#   ifdef _WIN32_WCE
  110.31 +      /* The Microsoft C Run-Time Library for Windows CE doesn't have
  110.32 +       * errno.  We define it as a global variable to simplify porting.
  110.33 +       * Its value is always 0 and should not be used.  We rename it to
  110.34 +       * avoid conflict with other libraries that use the same workaround.
  110.35 +       */
  110.36 +#     define errno z_errno
  110.37 +#   endif
  110.38 +    extern int errno;
  110.39 +#else
  110.40 +#  ifndef _WIN32_WCE
  110.41 +#    include <errno.h>
  110.42 +#  endif
  110.43 +#endif
  110.44 +
  110.45 +#ifndef local
  110.46 +#  define local static
  110.47 +#endif
  110.48 +/* compile with -Dlocal if your debugger can't find static symbols */
  110.49 +
  110.50 +typedef unsigned char  uch;
  110.51 +typedef uch FAR uchf;
  110.52 +typedef unsigned short ush;
  110.53 +typedef ush FAR ushf;
  110.54 +typedef unsigned long  ulg;
  110.55 +
  110.56 +extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  110.57 +/* (size given to avoid silly warnings with Visual C++) */
  110.58 +
  110.59 +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  110.60 +
  110.61 +#define ERR_RETURN(strm,err) \
  110.62 +  return (strm->msg = (char*)ERR_MSG(err), (err))
  110.63 +/* To be used only when the state is known to be valid */
  110.64 +
  110.65 +        /* common constants */
  110.66 +
  110.67 +#ifndef DEF_WBITS
  110.68 +#  define DEF_WBITS MAX_WBITS
  110.69 +#endif
  110.70 +/* default windowBits for decompression. MAX_WBITS is for compression only */
  110.71 +
  110.72 +#if MAX_MEM_LEVEL >= 8
  110.73 +#  define DEF_MEM_LEVEL 8
  110.74 +#else
  110.75 +#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
  110.76 +#endif
  110.77 +/* default memLevel */
  110.78 +
  110.79 +#define STORED_BLOCK 0
  110.80 +#define STATIC_TREES 1
  110.81 +#define DYN_TREES    2
  110.82 +/* The three kinds of block type */
  110.83 +
  110.84 +#define MIN_MATCH  3
  110.85 +#define MAX_MATCH  258
  110.86 +/* The minimum and maximum match lengths */
  110.87 +
  110.88 +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  110.89 +
  110.90 +        /* target dependencies */
  110.91 +
  110.92 +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  110.93 +#  define OS_CODE  0x00
  110.94 +#  if defined(__TURBOC__) || defined(__BORLANDC__)
  110.95 +#    if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  110.96 +       /* Allow compilation with ANSI keywords only enabled */
  110.97 +       void _Cdecl farfree( void *block );
  110.98 +       void *_Cdecl farmalloc( unsigned long nbytes );
  110.99 +#    else
 110.100 +#      include <alloc.h>
 110.101 +#    endif
 110.102 +#  else /* MSC or DJGPP */
 110.103 +#    include <malloc.h>
 110.104 +#  endif
 110.105 +#endif
 110.106 +
 110.107 +#ifdef AMIGA
 110.108 +#  define OS_CODE  0x01
 110.109 +#endif
 110.110 +
 110.111 +#if defined(VAXC) || defined(VMS)
 110.112 +#  define OS_CODE  0x02
 110.113 +#  define F_OPEN(name, mode) \
 110.114 +     fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
 110.115 +#endif
 110.116 +
 110.117 +#if defined(ATARI) || defined(atarist)
 110.118 +#  define OS_CODE  0x05
 110.119 +#endif
 110.120 +
 110.121 +#ifdef OS2
 110.122 +#  define OS_CODE  0x06
 110.123 +#  ifdef M_I86
 110.124 +     #include <malloc.h>
 110.125 +#  endif
 110.126 +#endif
 110.127 +
 110.128 +#if defined(MACOS) || defined(TARGET_OS_MAC)
 110.129 +#  define OS_CODE  0x07
 110.130 +#  if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
 110.131 +#    include <unix.h> /* for fdopen */
 110.132 +#  else
 110.133 +#    ifndef fdopen
 110.134 +#      define fdopen(fd,mode) NULL /* No fdopen() */
 110.135 +#    endif
 110.136 +#  endif
 110.137 +#endif
 110.138 +
 110.139 +#ifdef TOPS20
 110.140 +#  define OS_CODE  0x0a
 110.141 +#endif
 110.142 +
 110.143 +#ifdef WIN32
 110.144 +#  ifndef __CYGWIN__  /* Cygwin is Unix, not Win32 */
 110.145 +#    define OS_CODE  0x0b
 110.146 +#  endif
 110.147 +#endif
 110.148 +
 110.149 +#ifdef __50SERIES /* Prime/PRIMOS */
 110.150 +#  define OS_CODE  0x0f
 110.151 +#endif
 110.152 +
 110.153 +#if defined(_BEOS_) || defined(RISCOS)
 110.154 +#  define fdopen(fd,mode) NULL /* No fdopen() */
 110.155 +#endif
 110.156 +
 110.157 +#if (defined(_MSC_VER) && (_MSC_VER > 600))
 110.158 +#  if defined(_WIN32_WCE)
 110.159 +#    define fdopen(fd,mode) NULL /* No fdopen() */
 110.160 +#    ifndef _PTRDIFF_T_DEFINED
 110.161 +       typedef int ptrdiff_t;
 110.162 +#      define _PTRDIFF_T_DEFINED
 110.163 +#    endif
 110.164 +#  else
 110.165 +#    define fdopen(fd,type)  _fdopen(fd,type)
 110.166 +#  endif
 110.167 +#endif
 110.168 +
 110.169 +        /* common defaults */
 110.170 +
 110.171 +#ifndef OS_CODE
 110.172 +#  define OS_CODE  0x03  /* assume Unix */
 110.173 +#endif
 110.174 +
 110.175 +#ifndef F_OPEN
 110.176 +#  define F_OPEN(name, mode) fopen((name), (mode))
 110.177 +#endif
 110.178 +
 110.179 +         /* functions */
 110.180 +
 110.181 +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
 110.182 +#  ifndef HAVE_VSNPRINTF
 110.183 +#    define HAVE_VSNPRINTF
 110.184 +#  endif
 110.185 +#endif
 110.186 +#if defined(__CYGWIN__)
 110.187 +#  ifndef HAVE_VSNPRINTF
 110.188 +#    define HAVE_VSNPRINTF
 110.189 +#  endif
 110.190 +#endif
 110.191 +#ifndef HAVE_VSNPRINTF
 110.192 +#  ifdef MSDOS
 110.193 +     /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
 110.194 +        but for now we just assume it doesn't. */
 110.195 +#    define NO_vsnprintf
 110.196 +#  endif
 110.197 +#  ifdef __TURBOC__
 110.198 +#    define NO_vsnprintf
 110.199 +#  endif
 110.200 +#  ifdef WIN32
 110.201 +     /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
 110.202 +#    if !defined(vsnprintf) && !defined(NO_vsnprintf)
 110.203 +#      define vsnprintf _vsnprintf
 110.204 +#    endif
 110.205 +#  endif
 110.206 +#  ifdef __SASC
 110.207 +#    define NO_vsnprintf
 110.208 +#  endif
 110.209 +#endif
 110.210 +#ifdef VMS
 110.211 +#  define NO_vsnprintf
 110.212 +#endif
 110.213 +
 110.214 +#if defined(pyr)
 110.215 +#  define NO_MEMCPY
 110.216 +#endif
 110.217 +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
 110.218 + /* Use our own functions for small and medium model with MSC <= 5.0.
 110.219 +  * You may have to use the same strategy for Borland C (untested).
 110.220 +  * The __SC__ check is for Symantec.
 110.221 +  */
 110.222 +#  define NO_MEMCPY
 110.223 +#endif
 110.224 +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
 110.225 +#  define HAVE_MEMCPY
 110.226 +#endif
 110.227 +#ifdef HAVE_MEMCPY
 110.228 +#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */
 110.229 +#    define zmemcpy _fmemcpy
 110.230 +#    define zmemcmp _fmemcmp
 110.231 +#    define zmemzero(dest, len) _fmemset(dest, 0, len)
 110.232 +#  else
 110.233 +#    define zmemcpy memcpy
 110.234 +#    define zmemcmp memcmp
 110.235 +#    define zmemzero(dest, len) memset(dest, 0, len)
 110.236 +#  endif
 110.237 +#else
 110.238 +   extern void zmemcpy  OF((Bytef* dest, const Bytef* source, uInt len));
 110.239 +   extern int  zmemcmp  OF((const Bytef* s1, const Bytef* s2, uInt len));
 110.240 +   extern void zmemzero OF((Bytef* dest, uInt len));
 110.241 +#endif
 110.242 +
 110.243 +/* Diagnostic functions */
 110.244 +#ifdef DEBUG
 110.245 +#  include <stdio.h>
 110.246 +   extern int z_verbose;
 110.247 +   extern void z_error    OF((char *m));
 110.248 +#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
 110.249 +#  define Trace(x) {if (z_verbose>=0) fprintf x ;}
 110.250 +#  define Tracev(x) {if (z_verbose>0) fprintf x ;}
 110.251 +#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}
 110.252 +#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
 110.253 +#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
 110.254 +#else
 110.255 +#  define Assert(cond,msg)
 110.256 +#  define Trace(x)
 110.257 +#  define Tracev(x)
 110.258 +#  define Tracevv(x)
 110.259 +#  define Tracec(c,x)
 110.260 +#  define Tracecv(c,x)
 110.261 +#endif
 110.262 +
 110.263 +
 110.264 +voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
 110.265 +void   zcfree  OF((voidpf opaque, voidpf ptr));
 110.266 +
 110.267 +#define ZALLOC(strm, items, size) \
 110.268 +           (*((strm)->zalloc))((strm)->opaque, (items), (size))
 110.269 +#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
 110.270 +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
 110.271 +
 110.272 +#endif /* ZUTIL_H */
   111.1 --- a/src/istereo.c	Thu Sep 08 04:23:56 2011 +0300
   111.2 +++ b/src/istereo.c	Thu Sep 08 06:28:38 2011 +0300
   111.3 @@ -18,8 +18,8 @@
   111.4  static unsigned int get_shader_program(const char *vfile, const char *pfile);
   111.5  static float get_sec(void);
   111.6  
   111.7 -unsigned int prog;
   111.8 -unsigned int tex;
   111.9 +unsigned int prog, prog_tunnel, prog_text;
  111.10 +unsigned int tex, tex_stones, tex_normal, tex_text;
  111.11  
  111.12  int view_xsz, view_ysz;
  111.13  
  111.14 @@ -46,7 +46,7 @@
  111.15  		return -1;
  111.16  	}
  111.17  
  111.18 -	if(!(tex = load_texture(find_resource("tiles.ppm", 0, 0)))) {
  111.19 +	if(!(tex = load_texture(find_resource("tiles.jpg", 0, 0)))) {
  111.20  		fprintf(stderr, "failed to load texture\n");
  111.21  		return -1;
  111.22  	}
   112.1 --- a/src/tex.c	Thu Sep 08 04:23:56 2011 +0300
   112.2 +++ b/src/tex.c	Thu Sep 08 06:28:38 2011 +0300
   112.3 @@ -5,56 +5,19 @@
   112.4  #include "opengl.h"
   112.5  #include "tex.h"
   112.6  #include "config.h"
   112.7 +#include "imago2.h"
   112.8  
   112.9  unsigned int load_texture(const char *fname)
  112.10  {
  112.11 +	int xsz, ysz;
  112.12  	unsigned int tex;
  112.13 -	FILE *fp;
  112.14 -	unsigned char *pixels;
  112.15 -	int xsz, ysz, sz, i;
  112.16 -	char buf[512];
  112.17 +	void *pixels;
  112.18  
  112.19 -	if(!(fp = fopen(fname, "r"))) {
  112.20 -		fprintf(stderr, "failed to open texture: %s: %s\n", fname, strerror(errno));
  112.21 +	if(!(pixels = img_load_pixels(fname, &xsz, &ysz, IMG_FMT_RGBA32))) {
  112.22 +		fprintf(stderr, "failed to load image: %s\n", fname);
  112.23  		return 0;
  112.24  	}
  112.25  
  112.26 -	if(!fgets(buf, sizeof buf, fp) || buf[0] != 'P' || buf[1] != '6') {
  112.27 -		fprintf(stderr, "invalid format (1): %s\n", fname);
  112.28 -		fclose(fp);
  112.29 -		return 0;
  112.30 -	}
  112.31 -	if(!fgets(buf, sizeof buf, fp) || sscanf(buf, "%d %d", &xsz, &ysz) != 2) {
  112.32 -		fprintf(stderr, "invalid format (2): %s\n", fname);
  112.33 -		fclose(fp);
  112.34 -		return 0;
  112.35 -	}
  112.36 -	fgets(buf, sizeof buf, fp);
  112.37 -
  112.38 -	sz = xsz * ysz * 4;
  112.39 -	if(!(pixels = malloc(sz))) {
  112.40 -		fprintf(stderr, "failed to allocate %d bytes\n", sz);
  112.41 -		fclose(fp);
  112.42 -		return 0;
  112.43 -	}
  112.44 -	for(i=0; i<sz; i++) {
  112.45 -		int c;
  112.46 -
  112.47 -		if(i % 4 == 3) {
  112.48 -			pixels[i] = 255;
  112.49 -			continue;
  112.50 -		}
  112.51 -
  112.52 -		if((c = fgetc(fp)) == -1) {
  112.53 -			fprintf(stderr, "partial read: %s\n", fname);
  112.54 -			free(pixels);
  112.55 -			fclose(fp);
  112.56 -			return 0;
  112.57 -		}
  112.58 -		pixels[i] = c;
  112.59 -	}
  112.60 -	fclose(fp);
  112.61 -
  112.62  	glGenTextures(1, &tex);
  112.63  	glBindTexture(GL_TEXTURE_2D, tex);
  112.64  	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  112.65 @@ -62,7 +25,7 @@
  112.66  	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  112.67  	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  112.68  	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, xsz, ysz, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  112.69 -	free(pixels);
  112.70 +	img_free_pixels(pixels);
  112.71  
  112.72  	return tex;
  112.73  }