Back to index

tetex-bin  3.0
gd_jpeg.c
Go to the documentation of this file.
00001 /*
00002  * gd_jpeg.c: Read and write JPEG (JFIF) format image files using the
00003  * gd graphics library (http://www.boutell.com/gd/).
00004  * 
00005  * This software is based in part on the work of the Independent JPEG
00006  * Group.  For more information on the IJG JPEG software (and JPEG
00007  * documentation, etc.), see ftp://ftp.uu.net/graphics/jpeg/.
00008  *
00009  * NOTE: IJG 12-bit JSAMPLE (BITS_IN_JSAMPLE == 12) mode is not
00010  * supported at all on read in gd 2.0, and is not supported on write
00011  * except for palette images, which is sort of pointless (TBB). Even that
00012  * has never been tested according to DB.
00013  *
00014  * Copyright 2000 Doug Becker, mailto:thebeckers@home.com
00015  *
00016  * Modification 4/18/00 TBB: JPEG_DEBUG rather than just DEBUG,
00017  * so VC++ builds don't spew to standard output, causing
00018  * major CGI brain damage
00019  *
00020  * 2.0.10: more efficient gdImageCreateFromJpegCtx, thanks to
00021  * Christian Aberger 
00022  */
00023 
00024 #ifdef HAVE_CONFIG_H
00025 #include "config.h"
00026 #endif
00027 
00028 #include <stdio.h>
00029 #include <stdlib.h>
00030 #include <setjmp.h>
00031 #include <limits.h>
00032 #include <string.h>
00033 
00034 #include "gd.h"
00035 /* TBB: move this up so include files are not brought in */
00036 /* JCE: arrange HAVE_LIBJPEG so that it can be set in gd.h */
00037 #ifdef HAVE_LIBJPEG
00038 #include "gdhelpers.h"
00039 
00040 /* JCE undef two symbols that we don't need anymore but which are
00041    may be defined in config.h from ./configure but which are
00042    redefined incompatibly in jpeglib.h */
00043 #undef HAVE_STDDEF_H
00044 #undef HAVE_STDLIB_H
00045 
00046 /* 1.8.1: remove dependency on jinclude.h */
00047 #include "jpeglib.h"
00048 #include "jerror.h"
00049 
00050 static const char *const GD_JPEG_VERSION = "1.0";
00051 
00052 typedef struct _jmpbuf_wrapper
00053 {
00054   jmp_buf jmpbuf;
00055 }
00056 jmpbuf_wrapper;
00057 
00058 /* Called by the IJG JPEG library upon encountering a fatal error */
00059 static void
00060 fatal_jpeg_error (j_common_ptr cinfo)
00061 {
00062   jmpbuf_wrapper *jmpbufw;
00063 
00064   fprintf (stderr, "gd-jpeg: JPEG library reports unrecoverable error: ");
00065   (*cinfo->err->output_message) (cinfo);
00066   fflush (stderr);
00067 
00068   jmpbufw = (jmpbuf_wrapper *) cinfo->client_data;
00069   jpeg_destroy (cinfo);
00070 
00071   if (jmpbufw != 0)
00072     {
00073       longjmp (jmpbufw->jmpbuf, 1);
00074       fprintf (stderr, "gd-jpeg: EXTREMELY fatal error: longjmp"
00075               " returned control; terminating\n");
00076     }
00077   else
00078     {
00079       fprintf (stderr, "gd-jpeg: EXTREMELY fatal error: jmpbuf"
00080               " unrecoverable; terminating\n");
00081     }
00082 
00083   fflush (stderr);
00084   exit (99);
00085 }
00086 
00087 /*
00088  * Write IM to OUTFILE as a JFIF-formatted JPEG image, using quality
00089  * QUALITY.  If QUALITY is in the range 0-100, increasing values
00090  * represent higher quality but also larger image size.  If QUALITY is
00091  * negative, the IJG JPEG library's default quality is used (which
00092  * should be near optimal for many applications).  See the IJG JPEG
00093  * library documentation for more details.  */
00094 
00095 BGD_DECLARE(void) gdImageJpeg (gdImagePtr im, FILE * outFile, int quality)
00096 {
00097   gdIOCtx *out = gdNewFileCtx (outFile);
00098   gdImageJpegCtx (im, out, quality);
00099   out->gd_free (out);
00100 }
00101 
00102 BGD_DECLARE(void *) gdImageJpegPtr (gdImagePtr im, int *size, int quality)
00103 {
00104   void *rv;
00105   gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
00106   gdImageJpegCtx (im, out, quality);
00107   rv = gdDPExtractData (out, size);
00108   out->gd_free (out);
00109   return rv;
00110 }
00111 
00112 void jpeg_gdIOCtx_dest (j_compress_ptr cinfo, gdIOCtx * outfile);
00113 
00114 BGD_DECLARE(void) gdImageJpegCtx (gdImagePtr im, gdIOCtx * outfile, int quality)
00115 {
00116   struct jpeg_compress_struct cinfo;
00117   struct jpeg_error_mgr jerr;
00118   int i, j, jidx;
00119   /* volatile so we can gdFree it on return from longjmp */
00120   volatile JSAMPROW row = 0;
00121   JSAMPROW rowptr[1];
00122   jmpbuf_wrapper jmpbufw;
00123   JDIMENSION nlines;
00124   char comment[255];
00125 
00126 #ifdef JPEG_DEBUG
00127   printf ("gd-jpeg: gd JPEG version %s\n", GD_JPEG_VERSION);
00128   printf ("gd-jpeg: JPEG library version %d, %d-bit sample values\n",
00129          JPEG_LIB_VERSION, BITS_IN_JSAMPLE);
00130   if (!im->trueColor)
00131     {
00132       for (i = 0; i < im->colorsTotal; i++)
00133        {
00134          if (!im->open[i])
00135            printf ("gd-jpeg: gd colormap index %d: (%d, %d, %d)\n", i,
00136                   im->red[i], im->green[i], im->blue[i]);
00137        }
00138     }
00139 #endif /* JPEG_DEBUG */
00140 
00141   memset (&cinfo, 0, sizeof (cinfo));
00142   memset (&jerr, 0, sizeof (jerr));
00143 
00144   cinfo.err = jpeg_std_error (&jerr);
00145   cinfo.client_data = &jmpbufw;
00146   if (setjmp (jmpbufw.jmpbuf) != 0)
00147     {
00148       /* we're here courtesy of longjmp */
00149       if (row)
00150        gdFree (row);
00151       return;
00152     }
00153 
00154   cinfo.err->error_exit = fatal_jpeg_error;
00155 
00156   jpeg_create_compress (&cinfo);
00157 
00158   cinfo.image_width = im->sx;
00159   cinfo.image_height = im->sy;
00160   cinfo.input_components = 3;      /* # of color components per pixel */
00161   cinfo.in_color_space = JCS_RGB;  /* colorspace of input image */
00162   jpeg_set_defaults (&cinfo);
00163   if (quality >= 0)
00164     jpeg_set_quality (&cinfo, quality, TRUE);
00165 
00166   /* If user requests interlace, translate that to progressive JPEG */
00167   if (gdImageGetInterlaced (im))
00168     {
00169 #ifdef JPEG_DEBUG
00170       printf ("gd-jpeg: interlace set, outputting progressive"
00171              " JPEG image\n");
00172 #endif
00173       jpeg_simple_progression (&cinfo);
00174     }
00175 
00176   jpeg_gdIOCtx_dest (&cinfo, outfile);
00177 
00178   row = (JSAMPROW) gdCalloc (1, cinfo.image_width * cinfo.input_components
00179                           * sizeof (JSAMPLE));
00180   if (row == 0)
00181     {
00182       fprintf (stderr, "gd-jpeg: error: unable to allocate JPEG row "
00183               "structure: gdCalloc returns NULL\n");
00184       jpeg_destroy_compress (&cinfo);
00185       return;
00186     }
00187 
00188   rowptr[0] = row;
00189 
00190   jpeg_start_compress (&cinfo, TRUE);
00191 
00192   sprintf (comment, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d),",
00193           GD_JPEG_VERSION, JPEG_LIB_VERSION);
00194   if (quality >= 0)
00195     sprintf (comment + strlen (comment), " quality = %d\n", quality);
00196   else
00197     strcat (comment + strlen (comment), " default quality\n");
00198   jpeg_write_marker (&cinfo, JPEG_COM, (unsigned char *) comment,
00199                    (unsigned int) strlen (comment));
00200   if (im->trueColor)
00201     {
00202 #if BITS_IN_JSAMPLE == 12
00203       fprintf (stderr,
00204               "gd-jpeg: error: jpeg library was compiled for 12-bit\n"
00205               "precision. This is mostly useless, because JPEGs on the web are\n"
00206               "8-bit and such versions of the jpeg library won't read or write\n"
00207               "them. GD doesn't support these unusual images. Edit your\n"
00208               "jmorecfg.h file to specify the correct precision and completely\n"
00209               "'make clean' and 'make install' libjpeg again. Sorry.\n");
00210       goto error;
00211 #endif /* BITS_IN_JSAMPLE == 12 */
00212       for (i = 0; i < im->sy; i++)
00213        {
00214          for (jidx = 0, j = 0; j < im->sx; j++)
00215            {
00216              int val = im->tpixels[i][j];
00217              row[jidx++] = gdTrueColorGetRed (val);
00218              row[jidx++] = gdTrueColorGetGreen (val);
00219              row[jidx++] = gdTrueColorGetBlue (val);
00220            }
00221 
00222          nlines = jpeg_write_scanlines (&cinfo, rowptr, 1);
00223          if (nlines != 1)
00224            fprintf (stderr, "gd_jpeg: warning: jpeg_write_scanlines"
00225                    " returns %u -- expected 1\n", nlines);
00226        }
00227     }
00228   else
00229     {
00230       for (i = 0; i < im->sy; i++)
00231        {
00232          for (jidx = 0, j = 0; j < im->sx; j++)
00233            {
00234              int idx = im->pixels[i][j];
00235 
00236              /*
00237               * NB: Although gd RGB values are ints, their max value is
00238               * 255 (see the documentation for gdImageColorAllocate())
00239               * -- perfect for 8-bit JPEG encoding (which is the norm)
00240               */
00241 #if BITS_IN_JSAMPLE == 8
00242              row[jidx++] = im->red[idx];
00243              row[jidx++] = im->green[idx];
00244              row[jidx++] = im->blue[idx];
00245 #elif BITS_IN_JSAMPLE == 12
00246              row[jidx++] = im->red[idx] << 4;
00247              row[jidx++] = im->green[idx] << 4;
00248              row[jidx++] = im->blue[idx] << 4;
00249 #else
00250 #error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12
00251 #endif
00252            }
00253 
00254          nlines = jpeg_write_scanlines (&cinfo, rowptr, 1);
00255          if (nlines != 1)
00256            fprintf (stderr, "gd_jpeg: warning: jpeg_write_scanlines"
00257                    " returns %u -- expected 1\n", nlines);
00258        }
00259     }
00260   jpeg_finish_compress (&cinfo);
00261   jpeg_destroy_compress (&cinfo);
00262   gdFree (row);
00263 }
00264 
00265 BGD_DECLARE(gdImagePtr) gdImageCreateFromJpeg (FILE * inFile)
00266 {
00267   gdImagePtr im;
00268   gdIOCtx *in = gdNewFileCtx (inFile);
00269   im = gdImageCreateFromJpegCtx (in);
00270   in->gd_free (in);
00271   return im;
00272 }
00273 
00274 BGD_DECLARE(gdImagePtr) gdImageCreateFromJpegPtr (int size, void *data)
00275 {
00276   gdImagePtr im;
00277   gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0);
00278   im = gdImageCreateFromJpegCtx (in);
00279   in->gd_free (in);
00280   return im;
00281 }
00282 
00283 void jpeg_gdIOCtx_src (j_decompress_ptr cinfo, gdIOCtx * infile);
00284 
00285 static int CMYKToRGB (int c, int m, int y, int k, int inverted);
00286 
00287 /* 
00288  * Create a gd-format image from the JPEG-format INFILE.  Returns the
00289  * image, or NULL upon error.
00290  */
00291 BGD_DECLARE(gdImagePtr) gdImageCreateFromJpegCtx (gdIOCtx * infile)
00292 {
00293   struct jpeg_decompress_struct cinfo;
00294   struct jpeg_error_mgr jerr;
00295   jmpbuf_wrapper jmpbufw;
00296   /* volatile so we can gdFree them after longjmp */
00297   volatile JSAMPROW row = 0;
00298   volatile gdImagePtr im = 0;
00299   JSAMPROW rowptr[1];
00300   int i, j, retval;
00301   JDIMENSION nrows;
00302   int channels = 3;
00303   int inverted = 0;
00304 #ifdef JPEG_DEBUG
00305   printf ("gd-jpeg: gd JPEG version %s\n", GD_JPEG_VERSION);
00306   printf ("gd-jpeg: JPEG library version %d, %d-bit sample values\n",
00307          JPEG_LIB_VERSION, BITS_IN_JSAMPLE);
00308 #endif
00309 
00310   memset (&cinfo, 0, sizeof (cinfo));
00311   memset (&jerr, 0, sizeof (jerr));
00312 
00313   cinfo.err = jpeg_std_error (&jerr);
00314   cinfo.client_data = &jmpbufw;
00315   if (setjmp (jmpbufw.jmpbuf) != 0)
00316     {
00317       /* we're here courtesy of longjmp */
00318       if (row)
00319        gdFree (row);
00320       if (im)
00321        gdImageDestroy (im);
00322       return 0;
00323     }
00324 
00325   cinfo.err->error_exit = fatal_jpeg_error;
00326 
00327   jpeg_create_decompress (&cinfo);
00328 
00329   jpeg_gdIOCtx_src (&cinfo, infile);
00330 
00331   /* 2.0.22: save the APP14 marker to check for Adobe Photoshop CMYK
00332      files with inverted components. */
00333   jpeg_save_markers (&cinfo, JPEG_APP0 + 14, 256);
00334 
00335   retval = jpeg_read_header (&cinfo, TRUE);
00336   if (retval != JPEG_HEADER_OK)
00337     fprintf (stderr, "gd-jpeg: warning: jpeg_read_header returns"
00338             " %d, expected %d\n", retval, JPEG_HEADER_OK);
00339 
00340   if (cinfo.image_height > INT_MAX)
00341     fprintf (stderr, "gd-jpeg: warning: JPEG image height (%u) is"
00342             " greater than INT_MAX (%d) (and thus greater than"
00343             " gd can handle)", cinfo.image_height, INT_MAX);
00344 
00345   if (cinfo.image_width > INT_MAX)
00346     fprintf (stderr, "gd-jpeg: warning: JPEG image width (%u) is"
00347             " greater than INT_MAX (%d) (and thus greater than"
00348             " gd can handle)\n", cinfo.image_width, INT_MAX);
00349 
00350   im = gdImageCreateTrueColor ((int) cinfo.image_width,
00351                             (int) cinfo.image_height);
00352   if (im == 0)
00353     {
00354       fprintf (stderr, "gd-jpeg error: cannot allocate gdImage" " struct\n");
00355       goto error;
00356     }
00357   /* 2.0.22: very basic support for reading CMYK colorspace files. Nice for
00358      thumbnails but there's no support for fussy adjustment of the
00359      assumed properties of inks and paper. */
00360   if ((cinfo.jpeg_color_space == JCS_CMYK) ||
00361       (cinfo.jpeg_color_space == JCS_YCCK))
00362     {
00363       cinfo.out_color_space = JCS_CMYK;
00364     }
00365   else
00366     {
00367       cinfo.out_color_space = JCS_RGB;
00368     }
00369 
00370   if (jpeg_start_decompress (&cinfo) != TRUE)
00371     fprintf (stderr, "gd-jpeg: warning: jpeg_start_decompress"
00372             " reports suspended data source\n");
00373 
00374 #ifdef JPEG_DEBUG
00375   printf ("gd-jpeg: JPEG image information:");
00376   if (cinfo.saw_JFIF_marker)
00377     printf (" JFIF version %d.%.2d",
00378            (int) cinfo.JFIF_major_version, (int) cinfo.JFIF_minor_version);
00379   else if (cinfo.saw_Adobe_marker)
00380     printf (" Adobe format");
00381   else
00382     printf (" UNKNOWN format");
00383 
00384   printf (" %ux%u (raw) / %ux%u (scaled) %d-bit", cinfo.image_width,
00385          cinfo.image_height, cinfo.output_width,
00386          cinfo.output_height, cinfo.data_precision);
00387   printf (" %s", (cinfo.progressive_mode ? "progressive" : "baseline"));
00388   printf (" image, %d quantized colors, ", cinfo.actual_number_of_colors);
00389 
00390   switch (cinfo.jpeg_color_space)
00391     {
00392     case JCS_GRAYSCALE:
00393       printf ("grayscale");
00394       break;
00395 
00396     case JCS_RGB:
00397       printf ("RGB");
00398       break;
00399 
00400     case JCS_YCbCr:
00401       printf ("YCbCr (a.k.a. YUV)");
00402       break;
00403 
00404     case JCS_CMYK:
00405       printf ("CMYK");
00406       break;
00407 
00408     case JCS_YCCK:
00409       printf ("YCbCrK");
00410       break;
00411 
00412     default:
00413       printf ("UNKNOWN (value: %d)", (int) cinfo.jpeg_color_space);
00414       break;
00415     }
00416   printf (" colorspace\n");
00417   fflush (stdout);
00418 #endif /* JPEG_DEBUG */
00419 
00420   /* REMOVED by TBB 2/12/01. This field of the structure is
00421      documented as private, and sure enough it's gone in the
00422      latest libjpeg, replaced by something else. Unfortunately
00423      there is still no right way to find out if the file was
00424      progressive or not; just declare your intent before you
00425      write one by calling gdImageInterlace(im, 1) yourself. 
00426      After all, we're not really supposed to rework JPEGs and
00427      write them out again anyway. Lossy compression, remember? */
00428 #if 0
00429   gdImageInterlace (im, cinfo.progressive_mode != 0);
00430 #endif
00431   if (cinfo.out_color_space == JCS_RGB)
00432     {
00433       if (cinfo.output_components != 3)
00434        {
00435          fprintf (stderr, "gd-jpeg: error: JPEG color quantization"
00436                  " request resulted in output_components == %d"
00437                  " (expected 3 for RGB)\n", cinfo.output_components);
00438          goto error;
00439        }
00440       channels = 3;
00441     }
00442   else if (cinfo.out_color_space == JCS_CMYK)
00443     {
00444       jpeg_saved_marker_ptr marker;
00445       if (cinfo.output_components != 4)
00446        {
00447          fprintf (stderr, "gd-jpeg: error: JPEG color quantization"
00448                  " request resulted in output_components == %d"
00449                  " (expected 4 for CMYK)\n", cinfo.output_components);
00450          goto error;
00451        }
00452       channels = 4;
00453       marker = cinfo.marker_list;
00454       while (marker)
00455        {
00456          if ((marker->marker == (JPEG_APP0 + 14)) &&
00457              (marker->data_length >= 12)
00458              && (!strncmp ((const char *) marker->data, "Adobe", 5)))
00459            {
00460              inverted = 1;
00461              break;
00462            }
00463          marker = marker->next;
00464        }
00465     }
00466   else
00467     {
00468       fprintf (stderr, "gd-jpeg: error: unexpected colorspace\n");
00469       goto error;
00470     }
00471 #if BITS_IN_JSAMPLE == 12
00472   fprintf (stderr, "gd-jpeg: error: jpeg library was compiled for 12-bit\n"
00473           "precision. This is mostly useless, because JPEGs on the web are\n"
00474           "8-bit and such versions of the jpeg library won't read or write\n"
00475           "them. GD doesn't support these unusual images. Edit your\n"
00476           "jmorecfg.h file to specify the correct precision and completely\n"
00477           "'make clean' and 'make install' libjpeg again. Sorry.\n");
00478   goto error;
00479 #endif /* BITS_IN_JSAMPLE == 12 */
00480 
00481   row = gdCalloc (cinfo.output_width * channels, sizeof (JSAMPLE));
00482   if (row == 0)
00483     {
00484       fprintf (stderr, "gd-jpeg: error: unable to allocate row for"
00485               " JPEG scanline: gdCalloc returns NULL\n");
00486       goto error;
00487     }
00488   rowptr[0] = row;
00489   if (cinfo.out_color_space == JCS_CMYK)
00490     {
00491       for (i = 0; i < cinfo.output_height; i++)
00492        {
00493          register JSAMPROW currow = row;
00494          register int *tpix = im->tpixels[i];
00495          nrows = jpeg_read_scanlines (&cinfo, rowptr, 1);
00496          if (nrows != 1)
00497            {
00498              fprintf (stderr, "gd-jpeg: error: jpeg_read_scanlines"
00499                      " returns %u, expected 1\n", nrows);
00500              goto error;
00501            }
00502          for (j = 0; j < cinfo.output_width; j++, currow += 4, tpix++)
00503            {
00504              *tpix =
00505               CMYKToRGB (currow[0], currow[1], currow[2], currow[3],
00506                         inverted);
00507            }
00508        }
00509     }
00510   else
00511     {
00512       for (i = 0; i < cinfo.output_height; i++)
00513        {
00514          register JSAMPROW currow = row;
00515          register int *tpix = im->tpixels[i];
00516          nrows = jpeg_read_scanlines (&cinfo, rowptr, 1);
00517          if (nrows != 1)
00518            {
00519              fprintf (stderr, "gd-jpeg: error: jpeg_read_scanlines"
00520                      " returns %u, expected 1\n", nrows);
00521              goto error;
00522            }
00523          for (j = 0; j < cinfo.output_width; j++, currow += 3, tpix++)
00524            {
00525              *tpix = gdTrueColor (currow[0], currow[1], currow[2]);
00526            }
00527        }
00528     }
00529   if (jpeg_finish_decompress (&cinfo) != TRUE)
00530     fprintf (stderr, "gd-jpeg: warning: jpeg_finish_decompress"
00531             " reports suspended data source\n");
00532   /* TBB 2.0.29: we should do our best to read whatever we can read, and a 
00533     warning is a warning. A fatal error on warnings doesn't make sense. */
00534 #if 0
00535   /* This was originally added by Truxton Fulton */
00536   if (cinfo.err->num_warnings > 0)
00537     goto error;
00538 #endif
00539 
00540   jpeg_destroy_decompress (&cinfo);
00541   gdFree (row);
00542   return im;
00543 
00544 error:
00545   jpeg_destroy_decompress (&cinfo);
00546   if (row)
00547     gdFree (row);
00548   if (im)
00549     gdImageDestroy (im);
00550   return 0;
00551 }
00552 
00553 /* A very basic conversion approach, TBB */
00554 
00555 static int
00556 CMYKToRGB (int c, int m, int y, int k, int inverted)
00557 {
00558   if (inverted)
00559     {
00560       c = 255 - c;
00561       m = 255 - m;
00562       y = 255 - y;
00563       k = 255 - k;
00564     }
00565   return gdTrueColor ((255 - c) * (255 - k) / 255,
00566                     (255 - m) * (255 - k) / 255,
00567                     (255 - y) * (255 - k) / 255);
00568 #if 0
00569   if (inverted)
00570     {
00571       c = 255 - c;
00572       m = 255 - m;
00573       y = 255 - y;
00574       k = 255 - k;
00575     }
00576   c = c * (255 - k) / 255 + k;
00577   if (c > 255)
00578     {
00579       c = 255;
00580     }
00581   if (c < 0)
00582     {
00583       c = 0;
00584     }
00585   m = m * (255 - k) / 255 + k;
00586   if (m > 255)
00587     {
00588       m = 255;
00589     }
00590   if (m < 0)
00591     {
00592       m = 0;
00593     }
00594   y = y * (255 - k) / 255 + k;
00595   if (y > 255)
00596     {
00597       y = 255;
00598     }
00599   if (y < 0)
00600     {
00601       y = 0;
00602     }
00603   c = 255 - c;
00604   m = 255 - m;
00605   y = 255 - y;
00606   return gdTrueColor (c, m, y);
00607 #endif
00608 }
00609 
00610 /*
00611 
00612  * gdIOCtx JPEG data sources and sinks, T. Boutell
00613  * almost a simple global replace from T. Lane's stdio versions.
00614  *
00615  */
00616 
00617 /* Different versions of libjpeg use either 'jboolean' or 'boolean', and
00618    some platforms define 'boolean', and so forth. Deal with this
00619    madness by typedeffing 'safeboolean' to 'boolean' if HAVE_BOOLEAN
00620    is already set, because this is the test that libjpeg uses.
00621    Otherwise, typedef it to int, because that's what libjpeg does
00622    if HAVE_BOOLEAN is not defined. -TBB */
00623 
00624 #ifdef HAVE_BOOLEAN
00625 typedef boolean safeboolean;
00626 #else
00627 typedef int safeboolean;
00628 #endif /* HAVE_BOOLEAN */
00629 
00630 /* Expanded data source object for gdIOCtx input */
00631 
00632 typedef struct
00633 {
00634   struct jpeg_source_mgr pub;      /* public fields */
00635 
00636   gdIOCtx *infile;          /* source stream */
00637   unsigned char *buffer;    /* start of buffer */
00638   safeboolean start_of_file;       /* have we gotten any data yet? */
00639 
00640 }
00641 my_source_mgr;
00642 
00643 typedef my_source_mgr *my_src_ptr;
00644 
00645 #define INPUT_BUF_SIZE  4096       /* choose an efficiently fread'able size */
00646 
00647 /*
00648  * Initialize source --- called by jpeg_read_header
00649  * before any data is actually read.
00650  */
00651 
00652 void
00653 init_source (j_decompress_ptr cinfo)
00654 {
00655   my_src_ptr src = (my_src_ptr) cinfo->src;
00656 
00657   /* We reset the empty-input-file flag for each image,
00658    * but we don't clear the input buffer.
00659    * This is correct behavior for reading a series of images from one source.
00660    */
00661   src->start_of_file = TRUE;
00662 }
00663 
00664 
00665 /*
00666  * Fill the input buffer --- called whenever buffer is emptied.
00667  *
00668  * In typical applications, this should read fresh data into the buffer
00669  * (ignoring the current state of next_input_byte & bytes_in_buffer),
00670  * reset the pointer & count to the start of the buffer, and return TRUE
00671  * indicating that the buffer has been reloaded.  It is not necessary to
00672  * fill the buffer entirely, only to obtain at least one more byte.
00673  *
00674  * There is no such thing as an EOF return.  If the end of the file has been
00675  * reached, the routine has a choice of ERREXIT() or inserting fake data into
00676  * the buffer.  In most cases, generating a warning message and inserting a
00677  * fake EOI marker is the best course of action --- this will allow the
00678  * decompressor to output however much of the image is there.  However,
00679  * the resulting error message is misleading if the real problem is an empty
00680  * input file, so we handle that case specially.
00681  *
00682  * In applications that need to be able to suspend compression due to input
00683  * not being available yet, a FALSE return indicates that no more data can be
00684  * obtained right now, but more may be forthcoming later.  In this situation,
00685  * the decompressor will return to its caller (with an indication of the
00686  * number of scanlines it has read, if any).  The application should resume
00687  * decompression after it has loaded more data into the input buffer.  Note
00688  * that there are substantial restrictions on the use of suspension --- see
00689  * the documentation.
00690  *
00691  * When suspending, the decompressor will back up to a convenient restart point
00692  * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
00693  * indicate where the restart point will be if the current call returns FALSE.
00694  * Data beyond this point must be rescanned after resumption, so move it to
00695  * the front of the buffer rather than discarding it.
00696  */
00697 
00698 #define END_JPEG_SEQUENCE "\r\n[*]--:END JPEG:--[*]\r\n"
00699 safeboolean
00700 fill_input_buffer (j_decompress_ptr cinfo)
00701 {
00702   my_src_ptr src = (my_src_ptr) cinfo->src;
00703   /* 2.0.12: signed size. Thanks to Geert Jansen */
00704   /* 2.0.14: some platforms (mingw-msys) don't have ssize_t. Call 
00705      an int an int. */
00706   int nbytes = 0;
00707   memset (src->buffer, 0, INPUT_BUF_SIZE);
00708 
00709   while (nbytes < INPUT_BUF_SIZE)
00710     {
00711 
00712       int got = gdGetBuf (src->buffer + nbytes,
00713                        INPUT_BUF_SIZE - nbytes,
00714                        src->infile);
00715 
00716       if ((got == EOF) || (got == 0))
00717        {
00718 
00719          /* EOF or error. If we got any data, don't worry about it.
00720             If we didn't, then this is unexpected. */
00721          if (!nbytes)
00722            {
00723 
00724              nbytes = -1;
00725 
00726            }
00727 
00728          break;
00729 
00730        }
00731 
00732       nbytes += got;
00733 
00734     }
00735 
00736   if (nbytes <= 0)
00737     {
00738       if (src->start_of_file)      /* Treat empty input file as fatal error */
00739        ERREXIT (cinfo, JERR_INPUT_EMPTY);
00740       WARNMS (cinfo, JWRN_JPEG_EOF);
00741       /* Insert a fake EOI marker */
00742       src->buffer[0] = (unsigned char) 0xFF;
00743       src->buffer[1] = (unsigned char) JPEG_EOI;
00744       nbytes = 2;
00745     }
00746 
00747   src->pub.next_input_byte = src->buffer;
00748   src->pub.bytes_in_buffer = nbytes;
00749   src->start_of_file = FALSE;
00750 
00751   return TRUE;
00752 }
00753 
00754 
00755 /*
00756  * Skip data --- used to skip over a potentially large amount of
00757  * uninteresting data (such as an APPn marker).
00758  *
00759  * Writers of suspendable-input applications must note that skip_input_data
00760  * is not granted the right to give a suspension return.  If the skip extends
00761  * beyond the data currently in the buffer, the buffer can be marked empty so
00762  * that the next read will cause a fill_input_buffer call that can suspend.
00763  * Arranging for additional bytes to be discarded before reloading the input
00764  * buffer is the application writer's problem.
00765  */
00766 
00767 void
00768 skip_input_data (j_decompress_ptr cinfo, long num_bytes)
00769 {
00770   my_src_ptr src = (my_src_ptr) cinfo->src;
00771 
00772   /* Just a dumb implementation for now. Not clear that being smart is worth
00773    * any trouble anyway --- large skips are infrequent.
00774    */
00775   if (num_bytes > 0)
00776     {
00777       while (num_bytes > (long) src->pub.bytes_in_buffer)
00778        {
00779          num_bytes -= (long) src->pub.bytes_in_buffer;
00780          (void) fill_input_buffer (cinfo);
00781          /* note we assume that fill_input_buffer will never return FALSE,
00782           * so suspension need not be handled.
00783           */
00784        }
00785       src->pub.next_input_byte += (size_t) num_bytes;
00786       src->pub.bytes_in_buffer -= (size_t) num_bytes;
00787     }
00788 }
00789 
00790 
00791 /*
00792  * An additional method that can be provided by data source modules is the
00793  * resync_to_restart method for error recovery in the presence of RST markers.
00794  * For the moment, this source module just uses the default resync method
00795  * provided by the JPEG library.  That method assumes that no backtracking
00796  * is possible.
00797  */
00798 
00799 
00800 /*
00801  * Terminate source --- called by jpeg_finish_decompress
00802  * after all data has been read.  Often a no-op.
00803  *
00804  * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
00805  * application must deal with any cleanup that should happen even
00806  * for error exit.
00807  */
00808 
00809 void
00810 term_source (j_decompress_ptr cinfo)
00811 {
00812 
00813 #if 0
00814 /* never used */
00815   my_src_ptr src = (my_src_ptr) cinfo->src;
00816 
00817 #endif
00818 }
00819 
00820 
00821 /*
00822  * Prepare for input from a gdIOCtx stream.
00823  * The caller must have already opened the stream, and is responsible
00824  * for closing it after finishing decompression.
00825  */
00826 
00827 void
00828 jpeg_gdIOCtx_src (j_decompress_ptr cinfo, gdIOCtx * infile)
00829 {
00830   my_src_ptr src;
00831 
00832   /* The source object and input buffer are made permanent so that a series
00833    * of JPEG images can be read from the same file by calling jpeg_gdIOCtx_src
00834    * only before the first one.  (If we discarded the buffer at the end of
00835    * one image, we'd likely lose the start of the next one.)
00836    * This makes it unsafe to use this manager and a different source
00837    * manager serially with the same JPEG object.  Caveat programmer.
00838    */
00839   if (cinfo->src == NULL)
00840     {                       /* first time for this JPEG object? */
00841       cinfo->src = (struct jpeg_source_mgr *)
00842        (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
00843                                 sizeof (my_source_mgr));
00844       src = (my_src_ptr) cinfo->src;
00845       src->buffer = (unsigned char *)
00846        (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
00847                                 INPUT_BUF_SIZE * sizeof (unsigned char));
00848 
00849     }
00850 
00851   src = (my_src_ptr) cinfo->src;
00852   src->pub.init_source = init_source;
00853   src->pub.fill_input_buffer = fill_input_buffer;
00854   src->pub.skip_input_data = skip_input_data;
00855   src->pub.resync_to_restart = jpeg_resync_to_restart;  /* use default method */
00856   src->pub.term_source = term_source;
00857   src->infile = infile;
00858   src->pub.bytes_in_buffer = 0;    /* forces fill_input_buffer on first read */
00859   src->pub.next_input_byte = NULL; /* until buffer loaded */
00860 }
00861 
00862 /* Expanded data destination object for stdio output */
00863 
00864 typedef struct
00865 {
00866   struct jpeg_destination_mgr pub; /* public fields */
00867   gdIOCtx *outfile;         /* target stream */
00868   unsigned char *buffer;    /* start of buffer */
00869 }
00870 my_destination_mgr;
00871 
00872 typedef my_destination_mgr *my_dest_ptr;
00873 
00874 #define OUTPUT_BUF_SIZE  4096      /* choose an efficiently fwrite'able size */
00875 
00876 /*
00877  * Initialize destination --- called by jpeg_start_compress
00878  * before any data is actually written.
00879  */
00880 
00881 void
00882 init_destination (j_compress_ptr cinfo)
00883 {
00884   my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
00885 
00886   /* Allocate the output buffer --- it will be released when done with image */
00887   dest->buffer = (unsigned char *)
00888     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
00889                             OUTPUT_BUF_SIZE * sizeof (unsigned char));
00890 
00891   dest->pub.next_output_byte = dest->buffer;
00892   dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
00893 }
00894 
00895 
00896 /*
00897  * Empty the output buffer --- called whenever buffer fills up.
00898  *
00899  * In typical applications, this should write the entire output buffer
00900  * (ignoring the current state of next_output_byte & free_in_buffer),
00901  * reset the pointer & count to the start of the buffer, and return TRUE
00902  * indicating that the buffer has been dumped.
00903  *
00904  * In applications that need to be able to suspend compression due to output
00905  * overrun, a FALSE return indicates that the buffer cannot be emptied now.
00906  * In this situation, the compressor will return to its caller (possibly with
00907  * an indication that it has not accepted all the supplied scanlines).  The
00908  * application should resume compression after it has made more room in the
00909  * output buffer.  Note that there are substantial restrictions on the use of
00910  * suspension --- see the documentation.
00911  *
00912  * When suspending, the compressor will back up to a convenient restart point
00913  * (typically the start of the current MCU). next_output_byte & free_in_buffer
00914  * indicate where the restart point will be if the current call returns FALSE.
00915  * Data beyond this point will be regenerated after resumption, so do not
00916  * write it out when emptying the buffer externally.
00917  */
00918 
00919 safeboolean
00920 empty_output_buffer (j_compress_ptr cinfo)
00921 {
00922   my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
00923 
00924   if (gdPutBuf (dest->buffer, OUTPUT_BUF_SIZE, dest->outfile) !=
00925       (size_t) OUTPUT_BUF_SIZE)
00926     ERREXIT (cinfo, JERR_FILE_WRITE);
00927 
00928   dest->pub.next_output_byte = dest->buffer;
00929   dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
00930 
00931   return TRUE;
00932 }
00933 
00934 
00935 /*
00936  * Terminate destination --- called by jpeg_finish_compress
00937  * after all data has been written.  Usually needs to flush buffer.
00938  *
00939  * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
00940  * application must deal with any cleanup that should happen even
00941  * for error exit.
00942  */
00943 
00944 void
00945 term_destination (j_compress_ptr cinfo)
00946 {
00947   my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
00948   size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
00949 
00950   /* Write any data remaining in the buffer */
00951   if (datacount > 0)
00952     {
00953       if (gdPutBuf (dest->buffer, datacount, dest->outfile) != datacount)
00954        ERREXIT (cinfo, JERR_FILE_WRITE);
00955     }
00956 }
00957 
00958 
00959 /*
00960  * Prepare for output to a stdio stream.
00961  * The caller must have already opened the stream, and is responsible
00962  * for closing it after finishing compression.
00963  */
00964 
00965 void
00966 jpeg_gdIOCtx_dest (j_compress_ptr cinfo, gdIOCtx * outfile)
00967 {
00968   my_dest_ptr dest;
00969 
00970   /* The destination object is made permanent so that multiple JPEG images
00971    * can be written to the same file without re-executing jpeg_stdio_dest.
00972    * This makes it dangerous to use this manager and a different destination
00973    * manager serially with the same JPEG object, because their private object
00974    * sizes may be different.  Caveat programmer.
00975    */
00976   if (cinfo->dest == NULL)
00977     {                       /* first time for this JPEG object? */
00978       cinfo->dest = (struct jpeg_destination_mgr *)
00979        (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
00980                                 sizeof (my_destination_mgr));
00981     }
00982 
00983   dest = (my_dest_ptr) cinfo->dest;
00984   dest->pub.init_destination = init_destination;
00985   dest->pub.empty_output_buffer = empty_output_buffer;
00986   dest->pub.term_destination = term_destination;
00987   dest->outfile = outfile;
00988 }
00989 
00990 #endif /* HAVE_LIBJPEG */