home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / gd201.zip / gd-2.0.1 / gd_jpeg.c < prev    next >
C/C++ Source or Header  |  2001-04-03  |  25KB  |  853 lines

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