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