1 : /*
2 : * gd_jpeg.c: Read and write JPEG (JFIF) format image files using the
3 : * gd graphics library (http://www.boutell.com/gd/).
4 : *
5 : * This software is based in part on the work of the Independent JPEG
6 : * Group. For more information on the IJG JPEG software (and JPEG
7 : * documentation, etc.), see ftp://ftp.uu.net/graphics/jpeg/.
8 : *
9 : * NOTE: IJG 12-bit JSAMPLE (BITS_IN_JSAMPLE == 12) mode is not
10 : * supported at all on read in gd 2.0, and is not supported on write
11 : * except for palette images, which is sort of pointless (TBB). Even that
12 : * has never been tested according to DB.
13 : *
14 : * Copyright 2000 Doug Becker, mailto:thebeckers@home.com
15 : *
16 : * Modification 4/18/00 TBB: JPEG_DEBUG rather than just DEBUG,
17 : * so VC++ builds don't spew to standard output, causing
18 : * major CGI brain damage
19 : *
20 : * 2.0.10: more efficient gdImageCreateFromJpegCtx, thanks to
21 : * Christian Aberger
22 : */
23 :
24 : #include <stdio.h>
25 : #include <stdlib.h>
26 : #include <setjmp.h>
27 : #include <limits.h>
28 : #include <string.h>
29 :
30 : #include "gd.h"
31 : /* TBB: move this up so include files are not brought in */
32 : /* JCE: arrange HAVE_LIBJPEG so that it can be set in gd.h */
33 : #ifdef HAVE_LIBJPEG
34 : #include "gdhelpers.h"
35 : #undef HAVE_STDLIB_H
36 :
37 : /* 1.8.1: remove dependency on jinclude.h */
38 : #include "jpeglib.h"
39 : #include "jerror.h"
40 :
41 : static const char *const GD_JPEG_VERSION = "1.0";
42 :
43 : typedef struct _jmpbuf_wrapper
44 : {
45 : jmp_buf jmpbuf;
46 : int ignore_warning;
47 : } jmpbuf_wrapper;
48 :
49 : static long php_jpeg_emit_message(j_common_ptr jpeg_info, int level)
50 131 : {
51 : char message[JMSG_LENGTH_MAX];
52 : jmpbuf_wrapper *jmpbufw;
53 131 : int ignore_warning = 0;
54 :
55 131 : jmpbufw = (jmpbuf_wrapper *) jpeg_info->client_data;
56 :
57 131 : if (jmpbufw != 0) {
58 131 : ignore_warning = jmpbufw->ignore_warning;
59 : }
60 :
61 131 : (jpeg_info->err->format_message)(jpeg_info,message);
62 :
63 : /* It is a warning message */
64 131 : if (level < 0) {
65 : /* display only the 1st warning, as would do a default libjpeg
66 : * unless strace_level >= 3
67 : */
68 0 : if ((jpeg_info->err->num_warnings == 0) || (jpeg_info->err->trace_level >= 3)) {
69 0 : php_gd_error_ex(ignore_warning ? E_NOTICE : E_WARNING, "gd-jpeg, libjpeg: recoverable error: %s\n", message);
70 : }
71 :
72 0 : jpeg_info->err->num_warnings++;
73 : } else {
74 : /* strace msg, Show it if trace_level >= level. */
75 131 : if (jpeg_info->err->trace_level >= level) {
76 0 : php_gd_error_ex(E_NOTICE, "gd-jpeg, libjpeg: strace message: %s\n", message);
77 : }
78 : }
79 131 : return 1;
80 : }
81 :
82 :
83 :
84 : /* Called by the IJG JPEG library upon encountering a fatal error */
85 : static void fatal_jpeg_error (j_common_ptr cinfo)
86 0 : {
87 : jmpbuf_wrapper *jmpbufw;
88 :
89 0 : php_gd_error("gd-jpeg: JPEG library reports unrecoverable error: ");
90 0 : (*cinfo->err->output_message) (cinfo);
91 :
92 0 : jmpbufw = (jmpbuf_wrapper *) cinfo->client_data;
93 0 : jpeg_destroy (cinfo);
94 :
95 0 : if (jmpbufw != 0) {
96 0 : longjmp (jmpbufw->jmpbuf, 1);
97 : php_gd_error_ex(E_ERROR, "gd-jpeg: EXTREMELY fatal error: longjmp returned control; terminating");
98 : } else {
99 0 : php_gd_error_ex(E_ERROR, "gd-jpeg: EXTREMELY fatal error: jmpbuf unrecoverable; terminating");
100 : }
101 :
102 0 : exit (99);
103 : }
104 :
105 : /*
106 : * Write IM to OUTFILE as a JFIF-formatted JPEG image, using quality
107 : * QUALITY. If QUALITY is in the range 0-100, increasing values
108 : * represent higher quality but also larger image size. If QUALITY is
109 : * negative, the IJG JPEG library's default quality is used (which
110 : * should be near optimal for many applications). See the IJG JPEG
111 : * library documentation for more details.
112 : */
113 :
114 : void gdImageJpeg (gdImagePtr im, FILE * outFile, int quality)
115 0 : {
116 0 : gdIOCtx *out = gdNewFileCtx (outFile);
117 0 : gdImageJpegCtx (im, out, quality);
118 0 : out->gd_free (out);
119 0 : }
120 :
121 : void *gdImageJpegPtr (gdImagePtr im, int *size, int quality)
122 0 : {
123 : void *rv;
124 0 : gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
125 0 : gdImageJpegCtx (im, out, quality);
126 0 : rv = gdDPExtractData (out, size);
127 0 : out->gd_free (out);
128 :
129 0 : return rv;
130 : }
131 :
132 : void jpeg_gdIOCtx_dest (j_compress_ptr cinfo, gdIOCtx * outfile);
133 :
134 : void gdImageJpegCtx (gdImagePtr im, gdIOCtx * outfile, int quality)
135 8 : {
136 : struct jpeg_compress_struct cinfo;
137 : struct jpeg_error_mgr jerr;
138 : int i, j, jidx;
139 : /* volatile so we can gdFree it on return from longjmp */
140 8 : volatile JSAMPROW row = 0;
141 : JSAMPROW rowptr[1];
142 : jmpbuf_wrapper jmpbufw;
143 : JDIMENSION nlines;
144 : char comment[255];
145 :
146 8 : memset (&cinfo, 0, sizeof (cinfo));
147 8 : memset (&jerr, 0, sizeof (jerr));
148 :
149 8 : cinfo.err = jpeg_std_error (&jerr);
150 8 : cinfo.client_data = &jmpbufw;
151 8 : if (setjmp (jmpbufw.jmpbuf) != 0) {
152 : /* we're here courtesy of longjmp */
153 0 : if (row) {
154 0 : gdFree (row);
155 : }
156 0 : return;
157 : }
158 :
159 8 : cinfo.err->error_exit = fatal_jpeg_error;
160 :
161 8 : jpeg_create_compress (&cinfo);
162 :
163 8 : cinfo.image_width = im->sx;
164 8 : cinfo.image_height = im->sy;
165 8 : cinfo.input_components = 3; /* # of color components per pixel */
166 8 : cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
167 8 : jpeg_set_defaults (&cinfo);
168 8 : if (quality >= 0) {
169 0 : jpeg_set_quality (&cinfo, quality, TRUE);
170 : }
171 :
172 : /* If user requests interlace, translate that to progressive JPEG */
173 8 : if (gdImageGetInterlaced (im)) {
174 0 : jpeg_simple_progression (&cinfo);
175 : }
176 :
177 8 : jpeg_gdIOCtx_dest (&cinfo, outfile);
178 :
179 8 : row = (JSAMPROW) safe_emalloc(cinfo.image_width * cinfo.input_components, sizeof(JSAMPLE), 0);
180 8 : memset(row, 0, cinfo.image_width * cinfo.input_components * sizeof(JSAMPLE));
181 8 : rowptr[0] = row;
182 :
183 8 : jpeg_start_compress (&cinfo, TRUE);
184 :
185 8 : if (quality >= 0) {
186 0 : snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), quality = %d\n", GD_JPEG_VERSION, JPEG_LIB_VERSION, quality);
187 : } else {
188 8 : snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), default quality\n", GD_JPEG_VERSION, JPEG_LIB_VERSION);
189 : }
190 8 : jpeg_write_marker (&cinfo, JPEG_COM, (unsigned char *) comment, (unsigned int) strlen (comment));
191 8 : if (im->trueColor) {
192 :
193 : #if BITS_IN_JSAMPLE == 12
194 : php_gd_error("gd-jpeg: error: jpeg library was compiled for 12-bit precision. This is mostly useless, because JPEGs on the web are 8-bit and such versions of the jpeg library won't read or write them. GD doesn't support these unusual images. Edit your jmorecfg.h file to specify the correct precision and completely 'make clean' and 'make install' libjpeg again. Sorry");
195 : goto error;
196 : #endif /* BITS_IN_JSAMPLE == 12 */
197 :
198 632 : for (i = 0; i < im->sy; i++) {
199 142124 : for (jidx = 0, j = 0; j < im->sx; j++) {
200 141497 : int val = im->tpixels[i][j];
201 :
202 141497 : row[jidx++] = gdTrueColorGetRed (val);
203 141497 : row[jidx++] = gdTrueColorGetGreen (val);
204 141497 : row[jidx++] = gdTrueColorGetBlue (val);
205 : }
206 :
207 627 : nlines = jpeg_write_scanlines (&cinfo, rowptr, 1);
208 627 : if (nlines != 1) {
209 0 : php_gd_error_ex(E_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines);
210 : }
211 : }
212 : } else {
213 384 : for (i = 0; i < im->sy; i++) {
214 74042 : for (jidx = 0, j = 0; j < im->sx; j++) {
215 73661 : int idx = im->pixels[i][j];
216 :
217 : /* NB: Although gd RGB values are ints, their max value is
218 : * 255 (see the documentation for gdImageColorAllocate())
219 : * -- perfect for 8-bit JPEG encoding (which is the norm)
220 : */
221 : #if BITS_IN_JSAMPLE == 8
222 73661 : row[jidx++] = im->red[idx];
223 73661 : row[jidx++] = im->green[idx];
224 73661 : row[jidx++] = im->blue[idx];
225 : #elif BITS_IN_JSAMPLE == 12
226 : row[jidx++] = im->red[idx] << 4;
227 : row[jidx++] = im->green[idx] << 4;
228 : row[jidx++] = im->blue[idx] << 4;
229 : #else
230 : #error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12
231 : #endif
232 : }
233 :
234 381 : nlines = jpeg_write_scanlines (&cinfo, rowptr, 1);
235 381 : if (nlines != 1) {
236 0 : php_gd_error_ex(E_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines);
237 : }
238 : }
239 : }
240 :
241 8 : jpeg_finish_compress (&cinfo);
242 8 : jpeg_destroy_compress (&cinfo);
243 8 : gdFree (row);
244 : }
245 :
246 : gdImagePtr gdImageCreateFromJpeg (FILE * inFile, int ignore_warning)
247 5 : {
248 : gdImagePtr im;
249 5 : gdIOCtx *in = gdNewFileCtx(inFile);
250 5 : im = gdImageCreateFromJpegCtx(in, ignore_warning);
251 5 : in->gd_free (in);
252 :
253 5 : return im;
254 : }
255 :
256 : gdImagePtr gdImageCreateFromJpegPtr (int size, void *data, int ignore_warning)
257 0 : {
258 : gdImagePtr im;
259 0 : gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0);
260 0 : im = gdImageCreateFromJpegCtx(in, ignore_warning);
261 0 : in->gd_free(in);
262 :
263 0 : return im;
264 : }
265 :
266 : void jpeg_gdIOCtx_src (j_decompress_ptr cinfo, gdIOCtx * infile);
267 :
268 : static int CMYKToRGB(int c, int m, int y, int k, int inverted);
269 :
270 :
271 : /*
272 : * Create a gd-format image from the JPEG-format INFILE. Returns the
273 : * image, or NULL upon error.
274 : */
275 : gdImagePtr gdImageCreateFromJpegCtx (gdIOCtx * infile, int ignore_warning)
276 5 : {
277 : struct jpeg_decompress_struct cinfo;
278 : struct jpeg_error_mgr jerr;
279 : jmpbuf_wrapper jmpbufw;
280 : /* volatile so we can gdFree them after longjmp */
281 5 : volatile JSAMPROW row = 0;
282 5 : volatile gdImagePtr im = 0;
283 : JSAMPROW rowptr[1];
284 : unsigned int i, j;
285 : int retval;
286 : JDIMENSION nrows;
287 5 : int channels = 3;
288 5 : int inverted = 0;
289 :
290 5 : memset (&cinfo, 0, sizeof (cinfo));
291 5 : memset (&jerr, 0, sizeof (jerr));
292 :
293 5 : jmpbufw.ignore_warning = ignore_warning;
294 :
295 5 : cinfo.err = jpeg_std_error (&jerr);
296 5 : cinfo.client_data = &jmpbufw;
297 :
298 5 : cinfo.err->emit_message = (void (*)(j_common_ptr,int)) php_jpeg_emit_message;
299 :
300 5 : if (setjmp (jmpbufw.jmpbuf) != 0) {
301 : /* we're here courtesy of longjmp */
302 0 : if (row) {
303 0 : gdFree (row);
304 : }
305 0 : if (im) {
306 0 : gdImageDestroy (im);
307 : }
308 0 : return 0;
309 : }
310 :
311 5 : cinfo.err->error_exit = fatal_jpeg_error;
312 :
313 5 : jpeg_create_decompress (&cinfo);
314 :
315 5 : jpeg_gdIOCtx_src (&cinfo, infile);
316 :
317 : /* 2.0.22: save the APP14 marker to check for Adobe Photoshop CMYK files with inverted components. */
318 5 : jpeg_save_markers(&cinfo, JPEG_APP0 + 14, 256);
319 :
320 5 : retval = jpeg_read_header (&cinfo, TRUE);
321 5 : if (retval != JPEG_HEADER_OK) {
322 0 : php_gd_error_ex(E_WARNING, "gd-jpeg: warning: jpeg_read_header returned %d, expected %d", retval, JPEG_HEADER_OK);
323 : }
324 :
325 5 : if (cinfo.image_height > INT_MAX) {
326 0 : php_gd_error_ex(E_WARNING, "gd-jpeg: warning: JPEG image height (%u) is greater than INT_MAX (%d) (and thus greater than gd can handle)", cinfo.image_height, INT_MAX);
327 : }
328 :
329 5 : if (cinfo.image_width > INT_MAX) {
330 0 : php_gd_error_ex(E_WARNING, "gd-jpeg: warning: JPEG image width (%u) is greater than INT_MAX (%d) (and thus greater than gd can handle)", cinfo.image_width, INT_MAX);
331 : }
332 :
333 5 : im = gdImageCreateTrueColor ((int) cinfo.image_width, (int) cinfo.image_height);
334 5 : if (im == 0) {
335 0 : php_gd_error("gd-jpeg error: cannot allocate gdImage struct");
336 0 : goto error;
337 : }
338 :
339 : /* 2.0.22: very basic support for reading CMYK colorspace files. Nice for
340 : * thumbnails but there's no support for fussy adjustment of the
341 : * assumed properties of inks and paper. */
342 5 : if ((cinfo.jpeg_color_space == JCS_CMYK) || (cinfo.jpeg_color_space == JCS_YCCK)) {
343 0 : cinfo.out_color_space = JCS_CMYK;
344 : } else {
345 5 : cinfo.out_color_space = JCS_RGB;
346 : }
347 :
348 5 : if (jpeg_start_decompress (&cinfo) != TRUE) {
349 0 : php_gd_error("gd-jpeg: warning: jpeg_start_decompress reports suspended data source");
350 : }
351 :
352 : /* REMOVED by TBB 2/12/01. This field of the structure is
353 : * documented as private, and sure enough it's gone in the
354 : * latest libjpeg, replaced by something else. Unfortunately
355 : * there is still no right way to find out if the file was
356 : * progressive or not; just declare your intent before you
357 : * write one by calling gdImageInterlace(im, 1) yourself.
358 : * After all, we're not really supposed to rework JPEGs and
359 : * write them out again anyway. Lossy compression, remember?
360 : */
361 : #if 0
362 : gdImageInterlace (im, cinfo.progressive_mode != 0);
363 : #endif
364 :
365 5 : if (cinfo.out_color_space == JCS_RGB) {
366 5 : if (cinfo.output_components != 3) {
367 0 : php_gd_error_ex(E_WARNING, "gd-jpeg: error: JPEG color quantization request resulted in output_components == %d (expected 3 for RGB)", cinfo.output_components);
368 0 : goto error;
369 : }
370 5 : channels = 3;
371 0 : } else if (cinfo.out_color_space == JCS_CMYK) {
372 : jpeg_saved_marker_ptr marker;
373 0 : if (cinfo.output_components != 4) {
374 0 : php_gd_error_ex(E_WARNING, "gd-jpeg: error: JPEG color quantization request resulted in output_components == %d (expected 4 for CMYK)", cinfo.output_components);
375 0 : goto error;
376 : }
377 0 : channels = 4;
378 0 : marker = cinfo.marker_list;
379 0 : while (marker) {
380 0 : if ((marker->marker == (JPEG_APP0 + 14)) && (marker->data_length >= 12) && (!strncmp((const char *) marker->data, "Adobe", 5))) {
381 0 : inverted = 1;
382 0 : break;
383 : }
384 0 : marker = marker->next;
385 : }
386 : } else {
387 0 : php_gd_error_ex(E_WARNING, "gd-jpeg: error: unexpected colorspace.");
388 0 : goto error;
389 : }
390 :
391 : #if BITS_IN_JSAMPLE == 12
392 : php_gd_error("gd-jpeg: error: jpeg library was compiled for 12-bit precision. This is mostly useless, because JPEGs on the web are 8-bit and such versions of the jpeg library won't read or write them. GD doesn't support these unusual images. Edit your jmorecfg.h file to specify the correct precision and completely 'make clean' and 'make install' libjpeg again. Sorry.");
393 : goto error;
394 : #endif /* BITS_IN_JSAMPLE == 12 */
395 :
396 5 : row = safe_emalloc(cinfo.output_width * channels, sizeof(JSAMPLE), 0);
397 5 : memset(row, 0, cinfo.output_width * channels * sizeof(JSAMPLE));
398 5 : rowptr[0] = row;
399 :
400 5 : if (cinfo.out_color_space == JCS_CMYK) {
401 0 : for (i = 0; i < cinfo.output_height; i++) {
402 0 : register JSAMPROW currow = row;
403 0 : register int *tpix = im->tpixels[i];
404 0 : nrows = jpeg_read_scanlines (&cinfo, rowptr, 1);
405 0 : if (nrows != 1) {
406 0 : php_gd_error_ex(E_WARNING, "gd-jpeg: error: jpeg_read_scanlines returns %u, expected 1", nrows);
407 0 : goto error;
408 : }
409 0 : for (j = 0; j < cinfo.output_width; j++, currow += 4, tpix++) {
410 0 : *tpix = CMYKToRGB (currow[0], currow[1], currow[2], currow[3], inverted);
411 : }
412 : }
413 : } else {
414 1104 : for (i = 0; i < cinfo.output_height; i++) {
415 1099 : register JSAMPROW currow = row;
416 1099 : register int *tpix = im->tpixels[i];
417 1099 : nrows = jpeg_read_scanlines (&cinfo, rowptr, 1);
418 1099 : if (nrows != 1) {
419 0 : php_gd_error_ex(E_WARNING, "gd-jpeg: error: jpeg_read_scanlines returns %u, expected 1", nrows);
420 0 : goto error;
421 : }
422 268868 : for (j = 0; j < cinfo.output_width; j++, currow += 3, tpix++) {
423 267769 : *tpix = gdTrueColor (currow[0], currow[1], currow[2]);
424 : }
425 : }
426 : }
427 :
428 5 : if (jpeg_finish_decompress (&cinfo) != TRUE) {
429 0 : php_gd_error("gd-jpeg: warning: jpeg_finish_decompress reports suspended data source");
430 : }
431 5 : if (!ignore_warning) {
432 5 : if (cinfo.err->num_warnings > 0) {
433 0 : goto error;
434 : }
435 : }
436 :
437 5 : jpeg_destroy_decompress (&cinfo);
438 5 : gdFree (row);
439 :
440 5 : return im;
441 :
442 0 : error:
443 0 : jpeg_destroy_decompress (&cinfo);
444 0 : if (row) {
445 0 : gdFree (row);
446 : }
447 0 : if (im) {
448 0 : gdImageDestroy (im);
449 : }
450 0 : return 0;
451 : }
452 :
453 : /* A very basic conversion approach, TBB */
454 : static int CMYKToRGB(int c, int m, int y, int k, int inverted)
455 0 : {
456 0 : if (inverted) {
457 0 : c = 255 - c;
458 0 : m = 255 - m;
459 0 : y = 255 - y;
460 0 : k = 255 - k;
461 : }
462 0 : return gdTrueColor((255 - c) * (255 - k) / 255, (255 - m) * (255 - k) / 255, (255 - y) * (255 - k) / 255);
463 : }
464 :
465 : /*
466 : * gdIOCtx JPEG data sources and sinks, T. Boutell
467 : * almost a simple global replace from T. Lane's stdio versions.
468 : *
469 : */
470 :
471 : /* Different versions of libjpeg use either 'jboolean' or 'boolean', and
472 : some platforms define 'boolean', and so forth. Deal with this
473 : madness by typedeffing 'safeboolean' to 'boolean' if HAVE_BOOLEAN
474 : is already set, because this is the test that libjpeg uses.
475 : Otherwise, typedef it to int, because that's what libjpeg does
476 : if HAVE_BOOLEAN is not defined. -TBB */
477 :
478 : #ifdef HAVE_BOOLEAN
479 : typedef boolean safeboolean;
480 : #else
481 : typedef int safeboolean;
482 : #endif /* HAVE_BOOLEAN */
483 :
484 : /* Expanded data source object for gdIOCtx input */
485 :
486 : typedef struct
487 : {
488 : struct jpeg_source_mgr pub; /* public fields */
489 :
490 : gdIOCtx *infile; /* source stream */
491 : unsigned char *buffer; /* start of buffer */
492 : safeboolean start_of_file; /* have we gotten any data yet? */
493 : } my_source_mgr;
494 :
495 : typedef my_source_mgr *my_src_ptr;
496 :
497 : #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
498 :
499 : /*
500 : * Initialize source --- called by jpeg_read_header
501 : * before any data is actually read.
502 : */
503 :
504 : void init_source (j_decompress_ptr cinfo)
505 5 : {
506 5 : my_src_ptr src = (my_src_ptr) cinfo->src;
507 :
508 : /* We reset the empty-input-file flag for each image,
509 : * but we don't clear the input buffer.
510 : * This is correct behavior for reading a series of images from one source.
511 : */
512 5 : src->start_of_file = TRUE;
513 5 : }
514 :
515 :
516 : /*
517 : * Fill the input buffer --- called whenever buffer is emptied.
518 : *
519 : * In typical applications, this should read fresh data into the buffer
520 : * (ignoring the current state of next_input_byte & bytes_in_buffer),
521 : * reset the pointer & count to the start of the buffer, and return TRUE
522 : * indicating that the buffer has been reloaded. It is not necessary to
523 : * fill the buffer entirely, only to obtain at least one more byte.
524 : *
525 : * There is no such thing as an EOF return. If the end of the file has been
526 : * reached, the routine has a choice of ERREXIT() or inserting fake data into
527 : * the buffer. In most cases, generating a warning message and inserting a
528 : * fake EOI marker is the best course of action --- this will allow the
529 : * decompressor to output however much of the image is there. However,
530 : * the resulting error message is misleading if the real problem is an empty
531 : * input file, so we handle that case specially.
532 : *
533 : * In applications that need to be able to suspend compression due to input
534 : * not being available yet, a FALSE return indicates that no more data can be
535 : * obtained right now, but more may be forthcoming later. In this situation,
536 : * the decompressor will return to its caller (with an indication of the
537 : * number of scanlines it has read, if any). The application should resume
538 : * decompression after it has loaded more data into the input buffer. Note
539 : * that there are substantial restrictions on the use of suspension --- see
540 : * the documentation.
541 : *
542 : * When suspending, the decompressor will back up to a convenient restart point
543 : * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
544 : * indicate where the restart point will be if the current call returns FALSE.
545 : * Data beyond this point must be rescanned after resumption, so move it to
546 : * the front of the buffer rather than discarding it.
547 : */
548 :
549 : #define END_JPEG_SEQUENCE "\r\n[*]--:END JPEG:--[*]\r\n"
550 :
551 : safeboolean fill_input_buffer (j_decompress_ptr cinfo)
552 5 : {
553 5 : my_src_ptr src = (my_src_ptr) cinfo->src;
554 : /* 2.0.12: signed size. Thanks to Geert Jansen */
555 5 : ssize_t nbytes = 0;
556 :
557 : /* ssize_t got; */
558 : /* char *s; */
559 5 : memset(src->buffer, 0, INPUT_BUF_SIZE);
560 :
561 15 : while (nbytes < INPUT_BUF_SIZE) {
562 10 : int got = gdGetBuf(src->buffer + nbytes, INPUT_BUF_SIZE - nbytes, src->infile);
563 :
564 10 : if (got == EOF || got == 0) {
565 : /* EOF or error. If we got any data, don't worry about it. If we didn't, then this is unexpected. */
566 5 : if (!nbytes) {
567 0 : nbytes = -1;
568 : }
569 5 : break;
570 : }
571 5 : nbytes += got;
572 : }
573 :
574 5 : if (nbytes <= 0) {
575 0 : if (src->start_of_file) { /* Treat empty input file as fatal error */
576 0 : ERREXIT (cinfo, JERR_INPUT_EMPTY);
577 : }
578 0 : WARNMS (cinfo, JWRN_JPEG_EOF);
579 : /* Insert a fake EOI marker */
580 0 : src->buffer[0] = (unsigned char) 0xFF;
581 0 : src->buffer[1] = (unsigned char) JPEG_EOI;
582 0 : nbytes = 2;
583 : }
584 :
585 5 : src->pub.next_input_byte = src->buffer;
586 5 : src->pub.bytes_in_buffer = nbytes;
587 5 : src->start_of_file = FALSE;
588 :
589 5 : return TRUE;
590 : }
591 :
592 :
593 : /*
594 : * Skip data --- used to skip over a potentially large amount of
595 : * uninteresting data (such as an APPn marker).
596 : *
597 : * Writers of suspendable-input applications must note that skip_input_data
598 : * is not granted the right to give a suspension return. If the skip extends
599 : * beyond the data currently in the buffer, the buffer can be marked empty so
600 : * that the next read will cause a fill_input_buffer call that can suspend.
601 : * Arranging for additional bytes to be discarded before reloading the input
602 : * buffer is the application writer's problem.
603 : */
604 :
605 : void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
606 1 : {
607 1 : my_src_ptr src = (my_src_ptr) cinfo->src;
608 :
609 : /* Just a dumb implementation for now. Not clear that being smart is worth
610 : * any trouble anyway --- large skips are infrequent.
611 : */
612 1 : if (num_bytes > 0) {
613 2 : while (num_bytes > (long) src->pub.bytes_in_buffer) {
614 0 : num_bytes -= (long) src->pub.bytes_in_buffer;
615 0 : (void) fill_input_buffer (cinfo);
616 : /* note we assume that fill_input_buffer will never return FALSE,
617 : * so suspension need not be handled.
618 : */
619 : }
620 1 : src->pub.next_input_byte += (size_t) num_bytes;
621 1 : src->pub.bytes_in_buffer -= (size_t) num_bytes;
622 : }
623 1 : }
624 :
625 :
626 : /*
627 : * An additional method that can be provided by data source modules is the
628 : * resync_to_restart method for error recovery in the presence of RST markers.
629 : * For the moment, this source module just uses the default resync method
630 : * provided by the JPEG library. That method assumes that no backtracking
631 : * is possible.
632 : */
633 :
634 :
635 : /*
636 : * Terminate source --- called by jpeg_finish_decompress
637 : * after all data has been read. Often a no-op.
638 : *
639 : * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
640 : * application must deal with any cleanup that should happen even
641 : * for error exit.
642 : */
643 :
644 : void term_source (j_decompress_ptr cinfo)
645 5 : {
646 : #if 0
647 : * never used */
648 : my_src_ptr src = (my_src_ptr) cinfo->src;
649 : #endif
650 5 : }
651 :
652 :
653 : /*
654 : * Prepare for input from a gdIOCtx stream.
655 : * The caller must have already opened the stream, and is responsible
656 : * for closing it after finishing decompression.
657 : */
658 :
659 : void jpeg_gdIOCtx_src (j_decompress_ptr cinfo, gdIOCtx * infile)
660 5 : {
661 : my_src_ptr src;
662 :
663 : /* The source object and input buffer are made permanent so that a series
664 : * of JPEG images can be read from the same file by calling jpeg_gdIOCtx_src
665 : * only before the first one. (If we discarded the buffer at the end of
666 : * one image, we'd likely lose the start of the next one.)
667 : * This makes it unsafe to use this manager and a different source
668 : * manager serially with the same JPEG object. Caveat programmer.
669 : */
670 5 : if (cinfo->src == NULL) { /* first time for this JPEG object? */
671 5 : cinfo->src = (struct jpeg_source_mgr *)
672 : (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (my_source_mgr));
673 5 : src = (my_src_ptr) cinfo->src;
674 5 : src->buffer = (unsigned char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, INPUT_BUF_SIZE * sizeof (unsigned char));
675 :
676 : }
677 :
678 5 : src = (my_src_ptr) cinfo->src;
679 5 : src->pub.init_source = init_source;
680 5 : src->pub.fill_input_buffer = fill_input_buffer;
681 5 : src->pub.skip_input_data = skip_input_data;
682 5 : src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
683 5 : src->pub.term_source = term_source;
684 5 : src->infile = infile;
685 5 : src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
686 5 : src->pub.next_input_byte = NULL; /* until buffer loaded */
687 5 : }
688 :
689 : /* Expanded data destination object for stdio output */
690 :
691 : typedef struct
692 : {
693 : struct jpeg_destination_mgr pub; /* public fields */
694 : gdIOCtx *outfile; /* target stream */
695 : unsigned char *buffer; /* start of buffer */
696 : } my_destination_mgr;
697 :
698 : typedef my_destination_mgr *my_dest_ptr;
699 :
700 : #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
701 :
702 : /*
703 : * Initialize destination --- called by jpeg_start_compress
704 : * before any data is actually written.
705 : */
706 :
707 : void init_destination (j_compress_ptr cinfo)
708 8 : {
709 8 : my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
710 :
711 : /* Allocate the output buffer --- it will be released when done with image */
712 8 : dest->buffer = (unsigned char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, OUTPUT_BUF_SIZE * sizeof (unsigned char));
713 :
714 8 : dest->pub.next_output_byte = dest->buffer;
715 8 : dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
716 8 : }
717 :
718 :
719 : /*
720 : * Empty the output buffer --- called whenever buffer fills up.
721 : *
722 : * In typical applications, this should write the entire output buffer
723 : * (ignoring the current state of next_output_byte & free_in_buffer),
724 : * reset the pointer & count to the start of the buffer, and return TRUE
725 : * indicating that the buffer has been dumped.
726 : *
727 : * In applications that need to be able to suspend compression due to output
728 : * overrun, a FALSE return indicates that the buffer cannot be emptied now.
729 : * In this situation, the compressor will return to its caller (possibly with
730 : * an indication that it has not accepted all the supplied scanlines). The
731 : * application should resume compression after it has made more room in the
732 : * output buffer. Note that there are substantial restrictions on the use of
733 : * suspension --- see the documentation.
734 : *
735 : * When suspending, the compressor will back up to a convenient restart point
736 : * (typically the start of the current MCU). next_output_byte & free_in_buffer
737 : * indicate where the restart point will be if the current call returns FALSE.
738 : * Data beyond this point will be regenerated after resumption, so do not
739 : * write it out when emptying the buffer externally.
740 : */
741 :
742 : safeboolean empty_output_buffer (j_compress_ptr cinfo)
743 0 : {
744 0 : my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
745 :
746 0 : if (gdPutBuf (dest->buffer, OUTPUT_BUF_SIZE, dest->outfile) != (size_t) OUTPUT_BUF_SIZE) {
747 0 : ERREXIT (cinfo, JERR_FILE_WRITE);
748 : }
749 :
750 0 : dest->pub.next_output_byte = dest->buffer;
751 0 : dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
752 :
753 0 : return TRUE;
754 : }
755 :
756 :
757 : /*
758 : * Terminate destination --- called by jpeg_finish_compress
759 : * after all data has been written. Usually needs to flush buffer.
760 : *
761 : * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
762 : * application must deal with any cleanup that should happen even
763 : * for error exit.
764 : */
765 :
766 : void term_destination (j_compress_ptr cinfo)
767 8 : {
768 8 : my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
769 8 : size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
770 :
771 : /* Write any data remaining in the buffer */
772 8 : if (datacount > 0 && ((size_t)gdPutBuf (dest->buffer, datacount, dest->outfile) != datacount)) {
773 0 : ERREXIT (cinfo, JERR_FILE_WRITE);
774 : }
775 8 : }
776 :
777 :
778 : /*
779 : * Prepare for output to a stdio stream.
780 : * The caller must have already opened the stream, and is responsible
781 : * for closing it after finishing compression.
782 : */
783 :
784 : void jpeg_gdIOCtx_dest (j_compress_ptr cinfo, gdIOCtx * outfile)
785 8 : {
786 : my_dest_ptr dest;
787 :
788 : /* The destination object is made permanent so that multiple JPEG images
789 : * can be written to the same file without re-executing jpeg_stdio_dest.
790 : * This makes it dangerous to use this manager and a different destination
791 : * manager serially with the same JPEG object, because their private object
792 : * sizes may be different. Caveat programmer.
793 : */
794 8 : if (cinfo->dest == NULL) { /* first time for this JPEG object? */
795 8 : cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (my_destination_mgr));
796 : }
797 :
798 8 : dest = (my_dest_ptr) cinfo->dest;
799 8 : dest->pub.init_destination = init_destination;
800 8 : dest->pub.empty_output_buffer = empty_output_buffer;
801 8 : dest->pub.term_destination = term_destination;
802 8 : dest->outfile = outfile;
803 8 : }
804 :
805 : #endif /* HAVE_JPEG */
|