xref: /PHP-7.2/ext/gd/libgd/gd_gd2.c (revision 7ad94a01)
1 /*
2    * gd_gd2.c
3    *
4    * Implements the I/O and support for the GD2 format.
5    *
6    * Changing the definition of GD2_DBG (below) will cause copious messages
7    * to be displayed while it processes requests.
8    *
9    * Designed, Written & Copyright 1999, Philip Warner.
10    *
11  */
12 
13 #include <stdio.h>
14 #include <errno.h>
15 #include <math.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include "gd.h"
19 #include "gd_errors.h"
20 #include "gdhelpers.h"
21 
22 #include <zlib.h>
23 
24 #define TRUE 1
25 #define FALSE 0
26 
27 /* 2.11: not part of the API, as the save routine can figure it out
28  *	from im->trueColor, and the load routine doesn't need to tell
29  *	the end user the saved format. NOTE: adding 2 is assumed
30  *	to result in the correct format value for truecolor!
31 */
32 #define GD2_FMT_TRUECOLOR_RAW 3
33 #define GD2_FMT_TRUECOLOR_COMPRESSED 4
34 
35 #define gd2_compressed(fmt) (((fmt) == GD2_FMT_COMPRESSED) || ((fmt) == GD2_FMT_TRUECOLOR_COMPRESSED))
36 #define gd2_truecolor(fmt) (((fmt) == GD2_FMT_TRUECOLOR_RAW) || ((fmt) == GD2_FMT_TRUECOLOR_COMPRESSED))
37 
38 /* Use this for commenting out debug-print statements. */
39 /* Just use the first '#define' to allow all the prints... */
40 /* #define GD2_DBG(s) (s) */
41 #define GD2_DBG(s)
42 
43 typedef struct
44 {
45 	int offset;
46 	int size;
47 } t_chunk_info;
48 
49 extern int _gdGetColors(gdIOCtx * in, gdImagePtr im, int gd2xFlag);
50 extern void _gdPutColors(gdImagePtr im, gdIOCtx * out);
51 
52 /* */
53 /* Read the extra info in the gd2 header. */
54 /* */
_gd2GetHeader(gdIOCtxPtr in,int * sx,int * sy,int * cs,int * vers,int * fmt,int * ncx,int * ncy,t_chunk_info ** chunkIdx)55 static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx)
56 {
57 	int i;
58 	int ch;
59 	char id[5];
60 	t_chunk_info *cidx;
61 	int sidx;
62 	int nc;
63 
64 	GD2_DBG(gd_error("Reading gd2 header info"));
65 
66 	for (i = 0; i < 4; i++) {
67 		ch = gdGetC(in);
68 		if (ch == EOF) {
69 			goto fail1;
70 		}
71 		id[i] = ch;
72 	}
73 	id[4] = 0;
74 
75 	GD2_DBG(gd_error("Got file code: %s", id));
76 
77 	/* Equiv. of 'magick'.  */
78 	if (strcmp(id, GD2_ID) != 0) {
79 		GD2_DBG(gd_error("Not a valid gd2 file"));
80 		goto fail1;
81 	}
82 
83 	/* Version */
84 	if (gdGetWord(vers, in) != 1) {
85 		goto fail1;
86 	}
87 	GD2_DBG(gd_error("Version: %d", *vers));
88 
89 	if ((*vers != 1) && (*vers != 2)) {
90 		GD2_DBG(gd_error("Bad version: %d", *vers));
91 		goto fail1;
92 	}
93 
94 	/* Image Size */
95 	if (!gdGetWord(sx, in)) {
96 		GD2_DBG(gd_error("Could not get x-size"));
97 		goto fail1;
98 	}
99 	if (!gdGetWord(sy, in)) {
100 		GD2_DBG(gd_error("Could not get y-size"));
101 		goto fail1;
102 	}
103 	GD2_DBG(gd_error("Image is %dx%d", *sx, *sy));
104 
105 	/* Chunk Size (pixels, not bytes!) */
106 	if (gdGetWord(cs, in) != 1) {
107 		goto fail1;
108 	}
109 	GD2_DBG(gd_error("ChunkSize: %d", *cs));
110 
111 	if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
112 		GD2_DBG(gd_error("Bad chunk size: %d", *cs));
113 		goto fail1;
114 	}
115 
116 	/* Data Format */
117 	if (gdGetWord(fmt, in) != 1) {
118 		goto fail1;
119 	}
120 	GD2_DBG(gd_error("Format: %d", *fmt));
121 
122 	if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
123 		GD2_DBG(gd_error("Bad data format: %d", *fmt));
124 		goto fail1;
125 	}
126 
127 	/* # of chunks wide */
128 	if (gdGetWord(ncx, in) != 1) {
129 		goto fail1;
130 	}
131 	GD2_DBG(gd_error("%d Chunks Wide", *ncx));
132 
133 	/* # of chunks high */
134 	if (gdGetWord(ncy, in) != 1) {
135 		goto fail1;
136 	}
137 	GD2_DBG(gd_error("%d Chunks vertically", *ncy));
138 
139 	if (gd2_compressed(*fmt)) {
140 		if (*ncx <= 0 || *ncy <= 0 || *ncx > INT_MAX / *ncy) {
141 			GD2_DBG(printf ("Illegal chunk counts: %d * %d\n", *ncx, *ncy));
142 			goto fail1;
143 		}
144 		nc = (*ncx) * (*ncy);
145 		GD2_DBG(gd_error("Reading %d chunk index entries", nc));
146 		if (overflow2(sizeof(t_chunk_info), nc)) {
147 			goto fail1;
148 		}
149 		sidx = sizeof(t_chunk_info) * nc;
150 		if (sidx <= 0) {
151 			goto fail1;
152 		}
153 		cidx = gdCalloc(sidx, 1);
154 		if (cidx == NULL) {
155 			goto fail1;
156 		}
157 
158 		for (i = 0; i < nc; i++) {
159 			if (gdGetInt(&cidx[i].offset, in) != 1) {
160 				gdFree(cidx);
161 				goto fail1;
162 			}
163 			if (gdGetInt(&cidx[i].size, in) != 1) {
164 				gdFree(cidx);
165 				goto fail1;
166 			}
167 			if (cidx[i].offset < 0 || cidx[i].size < 0) {
168 				gdFree(cidx);
169 				goto fail1;
170 			}
171 		}
172 		*chunkIdx = cidx;
173 	}
174 
175 	GD2_DBG(gd_error("gd2 header complete"));
176 
177 	return 1;
178 
179 fail1:
180 	return 0;
181 }
182 
_gd2CreateFromFile(gdIOCtxPtr in,int * sx,int * sy,int * cs,int * vers,int * fmt,int * ncx,int * ncy,t_chunk_info ** cidx)183 static gdImagePtr _gd2CreateFromFile (gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** cidx)
184 {
185 	gdImagePtr im;
186 
187 	if (_gd2GetHeader (in, sx, sy, cs, vers, fmt, ncx, ncy, cidx) != 1) {
188 		GD2_DBG(gd_error("Bad GD2 header"));
189 		goto fail1;
190 	}
191 
192 	if (gd2_truecolor(*fmt)) {
193 		im = gdImageCreateTrueColor(*sx, *sy);
194 	} else {
195 		im = gdImageCreate(*sx, *sy);
196 	}
197 	if (im == NULL) {
198 		GD2_DBG(gd_error("Could not create gdImage"));
199 		goto fail2;
200 	}
201 
202 	if (!_gdGetColors(in, im, (*vers) == 2)) {
203 		GD2_DBG(gd_error("Could not read color palette"));
204 		goto fail3;
205 	}
206 	GD2_DBG(gd_error("Image palette completed: %d colours", im->colorsTotal));
207 
208 	return im;
209 
210 fail3:
211 	gdImageDestroy(im);
212 fail2:
213 	gdFree(*cidx);
214 fail1:
215 	return 0;
216 }
217 
_gd2ReadChunk(int offset,char * compBuf,int compSize,char * chunkBuf,uLongf * chunkLen,gdIOCtx * in)218 static int _gd2ReadChunk (int offset, char *compBuf, int compSize, char *chunkBuf, uLongf * chunkLen, gdIOCtx * in)
219 {
220 	int zerr;
221 
222 	if (gdTell(in) != offset) {
223 		GD2_DBG(gd_error("Positioning in file to %d", offset));
224 		gdSeek(in, offset);
225 	} else {
226 		GD2_DBG(gd_error("Already Positioned in file to %d", offset));
227 	}
228 
229 	/* Read and uncompress an entire chunk. */
230 	GD2_DBG(gd_error("Reading file"));
231 	if (gdGetBuf(compBuf, compSize, in) != compSize) {
232 		return FALSE;
233 	}
234 	GD2_DBG(gd_error("Got %d bytes. Uncompressing into buffer of %d bytes", compSize, (int)*chunkLen));
235 	zerr = uncompress((unsigned char *) chunkBuf, chunkLen, (unsigned char *) compBuf, compSize);
236 	if (zerr != Z_OK) {
237 		GD2_DBG(gd_error("Error %d from uncompress", zerr));
238 		return FALSE;
239 	}
240 	GD2_DBG(gd_error("Got chunk"));
241 
242 	return TRUE;
243 }
244 
gdImageCreateFromGd2(FILE * inFile)245 gdImagePtr gdImageCreateFromGd2 (FILE * inFile)
246 {
247 	gdIOCtx *in = gdNewFileCtx(inFile);
248 	gdImagePtr im;
249 
250 	im = gdImageCreateFromGd2Ctx(in);
251 
252 	in->gd_free(in);
253 
254 	return im;
255 }
256 
gdImageCreateFromGd2Ptr(int size,void * data)257 gdImagePtr gdImageCreateFromGd2Ptr (int size, void *data)
258 {
259 	gdImagePtr im;
260 	gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0);
261 	im = gdImageCreateFromGd2Ctx(in);
262 	in->gd_free(in);
263 
264 	return im;
265 }
266 
gdImageCreateFromGd2Ctx(gdIOCtxPtr in)267 gdImagePtr gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
268 {
269 	int sx, sy;
270 	int i;
271 	int ncx, ncy, nc, cs, cx, cy;
272 	int x, y, ylo, yhi, xlo, xhi;
273 	int vers, fmt;
274 	t_chunk_info *chunkIdx = NULL;	/* So we can gdFree it with impunity. */
275 	unsigned char *chunkBuf = NULL;	/* So we can gdFree it with impunity. */
276 	int chunkNum = 0;
277 	int chunkMax = 0;
278 	uLongf chunkLen;
279 	int chunkPos = 0;
280 	int compMax = 0;
281 	int bytesPerPixel;
282 	char *compBuf = NULL;		/* So we can gdFree it with impunity. */
283 
284 	gdImagePtr im;
285 
286 	/* Get the header */
287 	if (!(im = _gd2CreateFromFile(in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx))) {
288 		 return 0;
289 	}
290 
291 	bytesPerPixel = im->trueColor ? 4 : 1;
292 	nc = ncx * ncy;
293 
294 	if (gd2_compressed(fmt)) {
295 		/* Find the maximum compressed chunk size. */
296 		compMax = 0;
297 		for (i = 0; (i < nc); i++) {
298 			if (chunkIdx[i].size > compMax) {
299 				compMax = chunkIdx[i].size;
300 			}
301 		}
302 		compMax++;
303 
304 		/* Allocate buffers */
305 		chunkMax = cs * bytesPerPixel * cs;
306 		if (chunkMax <= 0) {
307 			return 0;
308 		}
309 		chunkBuf = gdCalloc(chunkMax, 1);
310 		compBuf = gdCalloc(compMax, 1);
311 
312 		GD2_DBG(gd_error("Largest compressed chunk is %d bytes", compMax));
313 	}
314 
315 	/* Read the data... */
316 	for (cy = 0; (cy < ncy); cy++) {
317 		for (cx = 0; (cx < ncx); cx++) {
318 			ylo = cy * cs;
319 			yhi = ylo + cs;
320 			if (yhi > im->sy) {
321 				yhi = im->sy;
322 			}
323 
324 			GD2_DBG(gd_error("Processing Chunk %d (%d, %d), y from %d to %d", chunkNum, cx, cy, ylo, yhi));
325 
326 			if (gd2_compressed(fmt)) {
327 				chunkLen = chunkMax;
328 
329 				if (!_gd2ReadChunk(chunkIdx[chunkNum].offset, compBuf, chunkIdx[chunkNum].size, (char *) chunkBuf, &chunkLen, in)) {
330 					GD2_DBG(gd_error("Error reading comproessed chunk"));
331 					goto fail2;
332 				}
333 
334 				chunkPos = 0;
335 			}
336 
337 			for (y = ylo; (y < yhi); y++) {
338 				xlo = cx * cs;
339 				xhi = xlo + cs;
340 				if (xhi > im->sx) {
341 					xhi = im->sx;
342 				}
343 
344 				if (!gd2_compressed(fmt)) {
345 					for (x = xlo; x < xhi; x++) {
346 						if (im->trueColor) {
347 							if (!gdGetInt(&im->tpixels[y][x], in)) {
348 								gd_error("gd2: EOF while reading\n");
349 								gdImageDestroy(im);
350 								return NULL;
351 							}
352 						} else {
353 							int ch;
354 							if (!gdGetByte(&ch, in)) {
355 								gd_error("gd2: EOF while reading\n");
356 								gdImageDestroy(im);
357 								return NULL;
358 							}
359 							im->pixels[y][x] = ch;
360 						}
361 					}
362 				} else {
363 					for (x = xlo; x < xhi; x++) {
364 						if (im->trueColor) {
365 							/* 2.0.1: work around a gcc bug by being verbose. TBB */
366 							int a = chunkBuf[chunkPos++] << 24;
367 							int r = chunkBuf[chunkPos++] << 16;
368 							int g = chunkBuf[chunkPos++] << 8;
369 							int b = chunkBuf[chunkPos++];
370 							im->tpixels[y][x] = a + r + g + b;
371 						} else {
372 							im->pixels[y][x] = chunkBuf[chunkPos++];
373 						}
374 					}
375 				}
376 			}
377 			chunkNum++;
378 		}
379 	}
380 
381 	GD2_DBG(gd_error("Freeing memory"));
382 
383 	if (chunkBuf) {
384 		gdFree(chunkBuf);
385 	}
386 	if (compBuf) {
387 		gdFree(compBuf);
388 	}
389 	if (chunkIdx) {
390 		gdFree(chunkIdx);
391 	}
392 
393 	GD2_DBG(gd_error("Done"));
394 
395 	return im;
396 
397 fail2:
398 	gdImageDestroy(im);
399 	if (chunkBuf) {
400 		gdFree(chunkBuf);
401 	}
402 	if (compBuf) {
403 		gdFree(compBuf);
404 	}
405 	if (chunkIdx) {
406 		gdFree(chunkIdx);
407 	}
408 
409 	return 0;
410 }
411 
gdImageCreateFromGd2PartPtr(int size,void * data,int srcx,int srcy,int w,int h)412 gdImagePtr gdImageCreateFromGd2PartPtr (int size, void *data, int srcx, int srcy, int w, int h)
413 {
414 	gdImagePtr im;
415 	gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0);
416 	im = gdImageCreateFromGd2PartCtx(in, srcx, srcy, w, h);
417 	in->gd_free(in);
418 
419 	return im;
420 }
421 
gdImageCreateFromGd2Part(FILE * inFile,int srcx,int srcy,int w,int h)422 gdImagePtr gdImageCreateFromGd2Part (FILE * inFile, int srcx, int srcy, int w, int h)
423 {
424 	gdImagePtr im;
425 	gdIOCtx *in = gdNewFileCtx(inFile);
426 
427 	im = gdImageCreateFromGd2PartCtx(in, srcx, srcy, w, h);
428 
429 	in->gd_free(in);
430 
431 	return im;
432 }
433 
gdImageCreateFromGd2PartCtx(gdIOCtx * in,int srcx,int srcy,int w,int h)434 gdImagePtr gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h)
435 {
436 	int scx, scy, ecx, ecy, fsx, fsy;
437 	int nc, ncx, ncy, cs, cx, cy;
438 	int x, y, ylo, yhi, xlo, xhi;
439 	int dstart, dpos;
440 	int i;
441 	/* 2.0.12: unsigned is correct; fixes problems with color munging. Thanks to Steven Brown. */
442 	unsigned int ch;
443 	int vers, fmt;
444 	t_chunk_info *chunkIdx = NULL;
445 	unsigned char *chunkBuf = NULL;
446 	int chunkNum;
447 	int chunkMax = 0;
448 	uLongf chunkLen;
449 	int chunkPos = 0;
450 	int compMax;
451 	char *compBuf = NULL;
452 
453 	gdImagePtr im;
454 
455 	if (w<1 || h <1) {
456 		return 0;
457 	}
458 
459 	/* The next few lines are basically copied from gd2CreateFromFile
460 	 * we change the file size, so don't want to use the code directly.
461 	 * but we do need to know the file size.
462 	 */
463 	if (_gd2GetHeader(in, &fsx, &fsy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx) != 1) {
464 		goto fail1;
465 	}
466 
467 	GD2_DBG(gd_error("File size is %dx%d", fsx, fsy));
468 
469 	/* This is the difference - make a file based on size of chunks. */
470 	if (gd2_truecolor(fmt)) {
471 		im = gdImageCreateTrueColor(w, h);
472 	} else {
473 		im = gdImageCreate(w, h);
474 	}
475 	if (im == NULL) {
476 		goto fail1;
477 	}
478 
479 	if (!_gdGetColors(in, im, vers == 2)) {
480 		goto fail2;
481 	}
482 	GD2_DBG(gd_error("Image palette completed: %d colours", im->colorsTotal));
483 
484 	/* Process the header info */
485 	nc = ncx * ncy;
486 
487 	if (gd2_compressed(fmt)) {
488 		/* Find the maximum compressed chunk size. */
489 		compMax = 0;
490 		for (i = 0; (i < nc); i++) {
491 			if (chunkIdx[i].size > compMax) {
492 				compMax = chunkIdx[i].size;
493 			}
494 		}
495 		compMax++;
496 
497 		if (im->trueColor) {
498 			chunkMax = cs * cs * 4;
499 		} else {
500 			chunkMax = cs * cs;
501 		}
502 		if (chunkMax <= 0) {
503 			goto fail2;
504 		}
505 
506 		chunkBuf = gdCalloc(chunkMax, 1);
507 		compBuf = gdCalloc(compMax, 1);
508 	}
509 
510 	/* Work out start/end chunks */
511 	scx = srcx / cs;
512 	scy = srcy / cs;
513 	if (scx < 0) {
514 		scx = 0;
515 	}
516 	if (scy < 0) {
517 		scy = 0;
518 	}
519 
520 	ecx = (srcx + w) / cs;
521 	ecy = (srcy + h) / cs;
522 	if (ecx >= ncx) {
523 		ecx = ncx - 1;
524 	}
525 	if (ecy >= ncy) {
526 		ecy = ncy - 1;
527 	}
528 
529 	/* Remember file position of image data. */
530 	dstart = gdTell(in);
531 	GD2_DBG(gd_error("Data starts at %d", dstart));
532 
533 	/* Loop through the chunks. */
534 	for (cy = scy; (cy <= ecy); cy++) {
535 		ylo = cy * cs;
536 		yhi = ylo + cs;
537 		if (yhi > fsy) {
538 			yhi = fsy;
539 		}
540 
541 		for (cx = scx; cx <= ecx; cx++) {
542 
543 			xlo = cx * cs;
544 			xhi = xlo + cs;
545 			if (xhi > fsx) {
546 				xhi = fsx;
547 			}
548 
549 			GD2_DBG(gd_error("Processing Chunk (%d, %d), from %d to %d", cx, cy, ylo, yhi));
550 
551 			if (!gd2_compressed(fmt)) {
552 				GD2_DBG(gd_error("Using raw format data"));
553 				if (im->trueColor) {
554 					dpos = (cy * (cs * fsx) * 4 + cx * cs * (yhi - ylo) * 4) + dstart;
555 				} else {
556 					dpos = cy * (cs * fsx) + cx * cs * (yhi - ylo) + dstart;
557 				}
558 
559 				/* gd 2.0.11: gdSeek returns TRUE on success, not 0. Longstanding bug. 01/16/03 */
560 				if (!gdSeek(in, dpos)) {
561 					gd_error_ex(E_WARNING, "Error from seek: %d", errno);
562 					goto fail2;
563 				}
564 				GD2_DBG(gd_error("Reading (%d, %d) from position %d", cx, cy, dpos - dstart));
565 			} else {
566 				chunkNum = cx + cy * ncx;
567 
568 				chunkLen = chunkMax;
569 				if (!_gd2ReadChunk (chunkIdx[chunkNum].offset, compBuf, chunkIdx[chunkNum].size, (char *)chunkBuf, &chunkLen, in)) {
570 					gd_error("Error reading comproessed chunk");
571 					goto fail2;
572 				}
573 				chunkPos = 0;
574 				GD2_DBG(gd_error("Reading (%d, %d) from chunk %d", cx, cy, chunkNum));
575 			}
576 
577 			GD2_DBG(gd_error("   into (%d, %d) - (%d, %d)", xlo, ylo, xhi, yhi));
578 
579 			for (y = ylo; (y < yhi); y++) {
580 				for (x = xlo; x < xhi; x++) {
581 					if (!gd2_compressed(fmt)) {
582 						if (im->trueColor) {
583 							if (!gdGetInt((int *)&ch, in)) {
584 								ch = 0;
585 							}
586 						} else {
587 							ch = gdGetC(in);
588 							if ((int)ch == EOF) {
589 								ch = 0;
590 							}
591 						}
592 					} else {
593 						if (im->trueColor) {
594 							ch = chunkBuf[chunkPos++];
595 							ch = (ch << 8) + chunkBuf[chunkPos++];
596 							ch = (ch << 8) + chunkBuf[chunkPos++];
597 							ch = (ch << 8) + chunkBuf[chunkPos++];
598 						} else {
599 							ch = chunkBuf[chunkPos++];
600 						}
601 					}
602 
603 					/* Only use a point that is in the image. */
604 					if ((x >= srcx) && (x < (srcx + w)) && (x < fsx) && (x >= 0) && (y >= srcy) && (y < (srcy + h)) && (y < fsy) && (y >= 0)) {
605 						if (im->trueColor) {
606 							im->tpixels[y - srcy][x - srcx] = ch;
607 						} else {
608 							im->pixels[y - srcy][x - srcx] = ch;
609 						}
610 					}
611 				}
612 			}
613 		}
614 	}
615 
616 	if (chunkBuf) {
617 		gdFree(chunkBuf);
618 	}
619 	if (compBuf) {
620 		gdFree(compBuf);
621 	}
622 	if (chunkIdx) {
623 		gdFree(chunkIdx);
624 	}
625 
626 	return im;
627 
628 fail2:
629 	gdImageDestroy(im);
630 fail1:
631 	if (chunkBuf) {
632 		gdFree(chunkBuf);
633 	}
634 	if (compBuf) {
635 		gdFree(compBuf);
636 	}
637 	if (chunkIdx) {
638 		gdFree(chunkIdx);
639 	}
640 
641 	return 0;
642 }
643 
_gd2PutHeader(gdImagePtr im,gdIOCtx * out,int cs,int fmt,int cx,int cy)644 static void _gd2PutHeader (gdImagePtr im, gdIOCtx * out, int cs, int fmt, int cx, int cy)
645 {
646 	int i;
647 
648 	/* Send the gd2 id, to verify file format. */
649 	for (i = 0; i < 4; i++) {
650 		gdPutC((unsigned char) (GD2_ID[i]), out);
651 	}
652 
653 	/* We put the version info first, so future versions can easily change header info. */
654 
655 	gdPutWord(GD2_VERS, out);
656 	gdPutWord(im->sx, out);
657 	gdPutWord(im->sy, out);
658 	gdPutWord(cs, out);
659 	gdPutWord(fmt, out);
660 	gdPutWord(cx, out);
661 	gdPutWord(cy, out);
662 }
663 
_gdImageGd2(gdImagePtr im,gdIOCtx * out,int cs,int fmt)664 static void _gdImageGd2 (gdImagePtr im, gdIOCtx * out, int cs, int fmt)
665 {
666 	int ncx, ncy, cx, cy;
667 	int x, y, ylo, yhi, xlo, xhi;
668 	int chunkLen;
669 	int chunkNum = 0;
670 	char *chunkData = NULL;	/* So we can gdFree it with impunity. */
671 	char *compData = NULL;	/* So we can gdFree it with impunity. */
672 	uLongf compLen;
673 	int idxPos = 0;
674 	int idxSize;
675 	t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */
676 	int posSave;
677 	int bytesPerPixel = im->trueColor ? 4 : 1;
678 	int compMax = 0;
679 
680 	/* Force fmt to a valid value since we don't return anything. */
681 	if ((fmt != GD2_FMT_RAW) && (fmt != GD2_FMT_COMPRESSED)) {
682 		fmt = GD2_FMT_COMPRESSED;
683 	}
684 	if (im->trueColor) {
685 		fmt += 2;
686 	}
687 	/* Make sure chunk size is valid. These are arbitrary values; 64 because it seems
688 	 * a little silly to expect performance improvements on a 64x64 bit scale, and
689 	 * 4096 because we buffer one chunk, and a 16MB buffer seems a little large - it may be
690 	 * OK for one user, but for another to read it, they require the buffer.
691 	 */
692 	if (cs == 0) {
693 		cs = GD2_CHUNKSIZE;
694 	} else if (cs < GD2_CHUNKSIZE_MIN) {
695 		cs = GD2_CHUNKSIZE_MIN;
696 	} else if (cs > GD2_CHUNKSIZE_MAX) {
697 		cs = GD2_CHUNKSIZE_MAX;
698 	}
699 
700 	/* Work out number of chunks. */
701 	ncx = (im->sx + cs - 1) / cs;
702 	ncy = (im->sy + cs - 1) / cs;
703 
704 	/* Write the standard header. */
705 	_gd2PutHeader (im, out, cs, fmt, ncx, ncy);
706 
707 	if (gd2_compressed(fmt)) {
708 		/* Work out size of buffer for compressed data, If CHUNKSIZE is large,
709 	 	 * then these will be large!
710 	 	 */
711 
712 		/* The zlib notes say output buffer size should be (input size) * 1.01 * 12
713 		 * - we'll use 1.02 to be paranoid.
714 		 */
715 		compMax = (int)(cs * bytesPerPixel * cs * 1.02f) + 12;
716 
717 		/* Allocate the buffers.  */
718 		chunkData = safe_emalloc(cs * bytesPerPixel, cs, 0);
719 		memset(chunkData, 0, cs * bytesPerPixel * cs);
720 		if (compMax <= 0) {
721 			goto fail;
722 		}
723 		compData = gdCalloc(compMax, 1);
724 
725 		/* Save the file position of chunk index, and allocate enough space for
726 		 * each chunk_info block .
727 		 */
728 		idxPos = gdTell(out);
729 		idxSize = ncx * ncy * sizeof(t_chunk_info);
730 		GD2_DBG(gd_error("Index size is %d", idxSize));
731 		gdSeek(out, idxPos + idxSize);
732 
733 		chunkIdx = safe_emalloc(idxSize, sizeof(t_chunk_info), 0);
734 		memset(chunkIdx, 0, idxSize * sizeof(t_chunk_info));
735 	}
736 
737 	_gdPutColors (im, out);
738 
739 	GD2_DBG(gd_error("Size: %dx%d", im->sx, im->sy));
740 	GD2_DBG(gd_error("Chunks: %dx%d", ncx, ncy));
741 
742 	for (cy = 0; (cy < ncy); cy++) {
743 		for (cx = 0; (cx < ncx); cx++) {
744 			ylo = cy * cs;
745 			yhi = ylo + cs;
746 			if (yhi > im->sy) {
747 				yhi = im->sy;
748 			}
749 
750 			GD2_DBG(gd_error("Processing Chunk (%dx%d), y from %d to %d", cx, cy, ylo, yhi));
751 			chunkLen = 0;
752 			for (y = ylo; (y < yhi); y++) {
753 				GD2_DBG(gd_error("y=%d: ",y));
754 				xlo = cx * cs;
755 				xhi = xlo + cs;
756 				if (xhi > im->sx) {
757 					xhi = im->sx;
758 				}
759 
760 				if (gd2_compressed(fmt)) {
761 					for (x = xlo; x < xhi; x++) {
762 						GD2_DBG(gd_error("%d...",x));
763 						if (im->trueColor) {
764 							int p = im->tpixels[y][x];
765 							chunkData[chunkLen++] = gdTrueColorGetAlpha(p);
766 							chunkData[chunkLen++] = gdTrueColorGetRed(p);
767 							chunkData[chunkLen++] = gdTrueColorGetGreen(p);
768 							chunkData[chunkLen++] = gdTrueColorGetBlue(p);
769 						} else {
770 							chunkData[chunkLen++] = im->pixels[y][x];
771 						}
772 					}
773 				} else {
774 					for (x = xlo; x < xhi; x++) {
775 						GD2_DBG(gd_error("%d, ",x));
776 
777 						if (im->trueColor) {
778 							gdPutInt(im->tpixels[y][x], out);
779 						} else {
780 							gdPutC((unsigned char) im->pixels[y][x], out);
781 						}
782 					}
783 				}
784 				GD2_DBG(gd_error("y=%d done.",y));
785 			}
786 
787 			if (gd2_compressed(fmt)) {
788 				compLen = compMax;
789 				if (compress((unsigned char *) &compData[0], &compLen, (unsigned char *) &chunkData[0], chunkLen) != Z_OK) {
790 					gd_error("Error from compressing");
791 				} else {
792 					chunkIdx[chunkNum].offset = gdTell(out);
793 					chunkIdx[chunkNum++].size = compLen;
794 					GD2_DBG(gd_error("Chunk %d size %d offset %d", chunkNum, chunkIdx[chunkNum - 1].size, chunkIdx[chunkNum - 1].offset));
795 
796 					if (gdPutBuf (compData, compLen, out) <= 0) {
797 						/* Any alternate suggestions for handling this? */
798 						gd_error_ex(E_WARNING, "Error %d on write", errno);
799 					}
800 				}
801 			}
802 		}
803     	}
804 
805 	if (gd2_compressed(fmt)) {
806 		/* Save the position, write the index, restore position (paranoia). */
807 		GD2_DBG(gd_error("Seeking %d to write index", idxPos));
808 		posSave = gdTell(out);
809 		gdSeek(out, idxPos);
810 		GD2_DBG(gd_error("Writing index"));
811 		for (x = 0; x < chunkNum; x++) {
812 			GD2_DBG(gd_error("Chunk %d size %d offset %d", x, chunkIdx[x].size, chunkIdx[x].offset));
813 			gdPutInt(chunkIdx[x].offset, out);
814 			gdPutInt(chunkIdx[x].size, out);
815 		}
816 		gdSeek(out, posSave);
817 	}
818 fail:
819 	GD2_DBG(gd_error("Freeing memory"));
820 	if (chunkData) {
821 		gdFree(chunkData);
822 	}
823 	if (compData) {
824 		gdFree(compData);
825 	}
826 	if (chunkIdx) {
827 		gdFree(chunkIdx);
828 	}
829 	GD2_DBG(gd_error("Done"));
830 }
831 
gdImageGd2(gdImagePtr im,FILE * outFile,int cs,int fmt)832 void gdImageGd2 (gdImagePtr im, FILE * outFile, int cs, int fmt)
833 {
834 	gdIOCtx *out = gdNewFileCtx(outFile);
835 
836 	_gdImageGd2(im, out, cs, fmt);
837 
838 	out->gd_free(out);
839 }
840 
gdImageGd2Ptr(gdImagePtr im,int cs,int fmt,int * size)841 void *gdImageGd2Ptr (gdImagePtr im, int cs, int fmt, int *size)
842 {
843 	void *rv;
844 	gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
845 
846 	_gdImageGd2(im, out, cs, fmt);
847 	rv = gdDPExtractData(out, size);
848 	out->gd_free(out);
849 
850 	return rv;
851 }
852