home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume29 / jpeg / part09 < prev    next >
Text File  |  1992-03-24  |  54KB  |  1,384 lines

  1. Newsgroups: comp.sources.misc
  2. From: jpeg-info@uunet.uu.net (Independent JPEG Group)
  3. Subject:  v29i009:  jpeg - JPEG image compression, Part09/18
  4. Message-ID: <1992Mar24.144804.18668@sparky.imd.sterling.com>
  5. X-Md4-Signature: 6cd9ed3c2c2bdfc1893b6903d1fc8f56
  6. Date: Tue, 24 Mar 1992 14:48:04 GMT
  7. Approved: kent@sparky.imd.sterling.com
  8.  
  9. Submitted-by: jpeg-info@uunet.uu.net (Independent JPEG Group)
  10. Posting-number: Volume 29, Issue 9
  11. Archive-name: jpeg/part09
  12. Environment: UNIX, VMS, MS-DOS, Mac, Amiga, Cray
  13.  
  14. #! /bin/sh
  15. # into a shell via "sh file" or similar.  To overwrite existing files,
  16. # type "sh file -c".
  17. # The tool that generated this appeared in the comp.sources.unix newsgroup;
  18. # send mail to comp-sources-unix@uunet.uu.net if you want that tool.
  19. # Contents:  example.c jmemnobs.c jquant1.c
  20. # Wrapped by kent@sparky on Mon Mar 23 16:02:46 1992
  21. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  22. echo If this archive is complete, you will see the following message:
  23. echo '          "shar: End of archive 9 (of 18)."'
  24. if test -f 'example.c' -a "${1}" != "-c" ; then 
  25.   echo shar: Will not clobber existing file \"'example.c'\"
  26. else
  27.   echo shar: Extracting \"'example.c'\" \(26472 characters\)
  28.   sed "s/^X//" >'example.c' <<'END_OF_FILE'
  29. X/*
  30. X * example.c
  31. X *
  32. X * This file is not actually part of the JPEG software.  Rather, it provides
  33. X * a skeleton that may be useful for constructing applications that use the
  34. X * JPEG software as subroutines.  This code will NOT do anything useful as is.
  35. X *
  36. X * This file illustrates how to use the JPEG code as a subroutine library
  37. X * to read or write JPEG image files.  We assume here that you are not
  38. X * merely interested in converting the image to yet another image file format
  39. X * (if you are, you should be adding another I/O module to cjpeg/djpeg, not
  40. X * constructing a new application).  Instead, we show how to pass the
  41. X * decompressed image data into or out of routines that you provide.  For
  42. X * example, a viewer program might use the JPEG decompressor together with
  43. X * routines that write the decompressed image directly to a display.
  44. X *
  45. X * We present these routines in the same coding style used in the JPEG code
  46. X * (ANSI function definitions, etc); but you are of course free to code your
  47. X * routines in a different style if you prefer.
  48. X */
  49. X
  50. X/*
  51. X * Include file for declaring JPEG data structures.
  52. X * This file also includes some system headers like <stdio.h>;
  53. X * if you prefer, you can include "jconfig.h" and "jpegdata.h" instead.
  54. X */
  55. X
  56. X#include "jinclude.h"
  57. X
  58. X/*
  59. X * <setjmp.h> is used for the optional error recovery mechanism shown in
  60. X * the second part of the example.
  61. X */
  62. X
  63. X#include <setjmp.h>
  64. X
  65. X
  66. X
  67. X/******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/
  68. X
  69. X/* This half of the example shows how to feed data into the JPEG compressor.
  70. X * We present a minimal version that does not worry about refinements such
  71. X * as error recovery (the JPEG code will just exit() if it gets an error).
  72. X */
  73. X
  74. X
  75. X/*
  76. X * To supply the image data for compression, you must define three routines
  77. X * input_init, get_input_row, and input_term.  These routines will be called
  78. X * from the JPEG compressor via function pointer values that you store in the
  79. X * cinfo data structure; hence they need not be globally visible and the exact
  80. X * names don't matter.  (In fact, the "METHODDEF" macro expands to "static" if
  81. X * you use the unmodified JPEG include files.)
  82. X *
  83. X * The input file reading modules (jrdppm.c, jrdgif.c, jrdtarga.c, etc) may be
  84. X * useful examples of what these routines should actually do, although each of
  85. X * them is encrusted with a lot of specialized code for its own file format.
  86. X */
  87. X
  88. X
  89. XMETHODDEF void
  90. Xinput_init (compress_info_ptr cinfo)
  91. X/* Initialize for input; return image size and component data. */
  92. X{
  93. X  /* This routine must return five pieces of information about the incoming
  94. X   * image, and must do any setup needed for the get_input_row routine.
  95. X   * The image information is returned in fields of the cinfo struct.
  96. X   * (If you don't care about modularity, you could initialize these fields
  97. X   * in the main JPEG calling routine, and make this routine be a no-op.)
  98. X   * We show some example values here.
  99. X   */
  100. X  cinfo->image_width = 640;        /* width in pixels */
  101. X  cinfo->image_height = 480;        /* height in pixels */
  102. X  /* JPEG views an image as being a rectangular array of pixels, with each
  103. X   * pixel having the same number of "component" values (color channels).
  104. X   * You must specify how many components there are and the colorspace
  105. X   * interpretation of the components.  Most applications will use RGB data or
  106. X   * grayscale data.  If you want to use something else, you'll need to study
  107. X   * and perhaps modify jcdeflts.c, jccolor.c, and jdcolor.c.
  108. X   */
  109. X  cinfo->input_components = 3;        /* or 1 for grayscale */
  110. X  cinfo->in_color_space = CS_RGB;    /* or CS_GRAYSCALE for grayscale */
  111. X  cinfo->data_precision = 8;        /* bits per pixel component value */
  112. X  /* In the current JPEG software, data_precision must be set equal to
  113. X   * BITS_IN_JSAMPLE, which is 8 unless you twiddle jconfig.h.  Future
  114. X   * versions might allow you to say either 8 or 12 if compiled with
  115. X   * 12-bit JSAMPLEs, or up to 16 in lossless mode.  In any case,
  116. X   * it is up to you to scale incoming pixel values to the range
  117. X   *   0 .. (1<<data_precision)-1.
  118. X   * If your image data format is fixed at a byte per component,
  119. X   * then saying "8" is probably the best long-term solution.
  120. X   */
  121. X}
  122. X
  123. X
  124. X/*
  125. X * This function is called repeatedly and must supply the next row of pixels
  126. X * on each call.  The rows MUST be returned in top-to-bottom order if you want
  127. X * your JPEG files to be compatible with everyone else's.  (If you cannot
  128. X * readily read your data in that order, you'll need an intermediate array to
  129. X * hold the image.  See jrdtarga.c or jrdrle.c for examples of handling
  130. X * bottom-to-top source data using the JPEG code's portable mechanisms.)
  131. X * The data is to be returned into a 2-D array of JSAMPLEs, indexed as
  132. X *        JSAMPLE pixel_row[component][column]
  133. X * where component runs from 0 to cinfo->input_components-1, and column runs
  134. X * from 0 to cinfo->image_width-1 (column 0 is left edge of image).  Note that
  135. X * this is actually an array of pointers to arrays rather than a true 2D array,
  136. X * since C does not support variable-size multidimensional arrays.
  137. X * JSAMPLE is typically typedef'd as "unsigned char".
  138. X */
  139. X
  140. X
  141. XMETHODDEF void
  142. Xget_input_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
  143. X/* Read next row of pixels into pixel_row[][] */
  144. X{
  145. X  /* This example shows how you might read RGB data (3 components)
  146. X   * from an input file in which the data is stored 3 bytes per pixel
  147. X   * in left-to-right, top-to-bottom order.
  148. X   */
  149. X  register FILE * infile = cinfo->input_file;
  150. X  register JSAMPROW ptr0, ptr1, ptr2;
  151. X  register long col;
  152. X  
  153. X  ptr0 = pixel_row[0];
  154. X  ptr1 = pixel_row[1];
  155. X  ptr2 = pixel_row[2];
  156. X  for (col = 0; col < cinfo->image_width; col++) {
  157. X    *ptr0++ = (JSAMPLE) getc(infile); /* red */
  158. X    *ptr1++ = (JSAMPLE) getc(infile); /* green */
  159. X    *ptr2++ = (JSAMPLE) getc(infile); /* blue */
  160. X  }
  161. X}
  162. X
  163. X
  164. XMETHODDEF void
  165. Xinput_term (compress_info_ptr cinfo)
  166. X/* Finish up at the end of the input */
  167. X{
  168. X  /* This termination routine will very often have no work to do, */
  169. X  /* but you must provide it anyway. */
  170. X  /* Note that the JPEG code will only call it during successful exit; */
  171. X  /* if you want it called during error exit, you gotta do that yourself. */
  172. X}
  173. X
  174. X
  175. X/*
  176. X * That's it for the routines that deal with reading the input image data.
  177. X * Now we have overall control and parameter selection routines.
  178. X */
  179. X
  180. X
  181. X/*
  182. X * This routine must determine what output JPEG file format is to be written,
  183. X * and make any other compression parameter changes that are desirable.
  184. X * This routine gets control after the input file header has been read
  185. X * (i.e., right after input_init has been called).  You could combine its
  186. X * functions into input_init, or even into the main control routine, but
  187. X * if you have several different input_init routines, it's a definite win
  188. X * to keep this separate.  You MUST supply this routine even if it's a no-op.
  189. X */
  190. X
  191. XMETHODDEF void
  192. Xc_ui_method_selection (compress_info_ptr cinfo)
  193. X{
  194. X  /* If the input is gray scale, generate a monochrome JPEG file. */
  195. X  if (cinfo->in_color_space == CS_GRAYSCALE)
  196. X    j_monochrome_default(cinfo);
  197. X  /* For now, always select JFIF output format. */
  198. X  jselwjfif(cinfo);
  199. X}
  200. X
  201. X
  202. X/*
  203. X * OK, here is the main function that actually causes everything to happen.
  204. X * We assume here that the target filename is supplied by the caller of this
  205. X * routine, and that all JPEG compression parameters can be default values.
  206. X */
  207. X
  208. XGLOBAL void
  209. Xwrite_JPEG_file (char * filename)
  210. X{
  211. X  /* These three structs contain JPEG parameters and working data.
  212. X   * They must survive for the duration of parameter setup and one
  213. X   * call to jpeg_compress; typically, making them local data in the
  214. X   * calling routine is the best strategy.
  215. X   */
  216. X  struct compress_info_struct cinfo;
  217. X  struct compress_methods_struct c_methods;
  218. X  struct external_methods_struct e_methods;
  219. X
  220. X  /* Initialize the system-dependent method pointers. */
  221. X  cinfo.methods = &c_methods;    /* links to method structs */
  222. X  cinfo.emethods = &e_methods;
  223. X  /* Here we use the default JPEG error handler, which will just print
  224. X   * an error message on stderr and call exit().  See the second half of
  225. X   * this file for an example of more graceful error recovery.
  226. X   */
  227. X  jselerror(&e_methods);    /* select std error/trace message routines */
  228. X  /* Here we use the standard memory manager provided with the JPEG code.
  229. X   * In some cases you might want to replace the memory manager, or at
  230. X   * least the system-dependent part of it, with your own code.
  231. X   */
  232. X  jselmemmgr(&e_methods);    /* select std memory allocation routines */
  233. X  /* If the compressor requires full-image buffers (for entropy-coding
  234. X   * optimization or a noninterleaved JPEG file), it will create temporary
  235. X   * files for anything that doesn't fit within the maximum-memory setting.
  236. X   * (Note that temp files are NOT needed if you use the default parameters.)
  237. X   * You can change the default maximum-memory setting by changing
  238. X   * e_methods.max_memory_to_use after jselmemmgr returns.
  239. X   * On some systems you may also need to set up a signal handler to
  240. X   * ensure that temporary files are deleted if the program is interrupted.
  241. X   * (This is most important if you are on MS-DOS and use the jmemdos.c
  242. X   * memory manager back end; it will try to grab extended memory for
  243. X   * temp files, and that space will NOT be freed automatically.)
  244. X   * See jcmain.c or jdmain.c for an example signal handler.
  245. X   */
  246. X
  247. X  /* Here, set up pointers to your own routines for input data handling
  248. X   * and post-init parameter selection.
  249. X   */
  250. X  c_methods.input_init = input_init;
  251. X  c_methods.get_input_row = get_input_row;
  252. X  c_methods.input_term = input_term;
  253. X  c_methods.c_ui_method_selection = c_ui_method_selection;
  254. X
  255. X  /* Set up default JPEG parameters in the cinfo data structure. */
  256. X  j_c_defaults(&cinfo, 75, FALSE);
  257. X  /* Note: 75 is the recommended default quality level; you may instead pass
  258. X   * a user-specified quality level.  Be aware that values below 25 will cause
  259. X   * non-baseline JPEG files to be created (and a warning message to that
  260. X   * effect to be emitted on stderr).  This won't bother our decoder, but some
  261. X   * commercial JPEG implementations may choke on non-baseline JPEG files.
  262. X   * If you want to force baseline compatibility, pass TRUE instead of FALSE.
  263. X   * (If non-baseline files are fine, but you could do without that warning
  264. X   * message, set e_methods.trace_level to -1.)
  265. X   */
  266. X
  267. X  /* At this point you can modify the default parameters set by j_c_defaults
  268. X   * as needed.  For a minimal implementation, you shouldn't need to change
  269. X   * anything.  See jcmain.c for some examples of what you might change.
  270. X   */
  271. X
  272. X  /* Select the input and output files.
  273. X   * Note that cinfo.input_file is only used if your input reading routines
  274. X   * use it; otherwise, you can just make it NULL.
  275. X   * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
  276. X   * requires it in order to write binary files.
  277. X   */
  278. X
  279. X  cinfo.input_file = NULL;    /* if no actual input file involved */
  280. X
  281. X  if ((cinfo.output_file = fopen(filename, "wb")) == NULL) {
  282. X    fprintf(stderr, "can't open %s\n", filename);
  283. X    exit(1);
  284. X  }
  285. X
  286. X  /* Here we go! */
  287. X  jpeg_compress(&cinfo);
  288. X
  289. X  /* That's it, son.  Nothin' else to do, except close files. */
  290. X  /* Here we assume only the output file need be closed. */
  291. X  fclose(cinfo.output_file);
  292. X
  293. X  /* Note: if you want to compress more than one image, we recommend you
  294. X   * repeat this whole routine.  You MUST repeat the j_c_defaults()/alter
  295. X   * parameters/jpeg_compress() sequence, as some data structures allocated
  296. X   * in j_c_defaults are freed upon exit from jpeg_compress.
  297. X   */
  298. X}
  299. X
  300. X
  301. X
  302. X/******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
  303. X
  304. X/* This half of the example shows how to read data from the JPEG decompressor.
  305. X * It's a little more refined than the above in that we show how to do your
  306. X * own error recovery.  If you don't care about that, you don't need these
  307. X * next two routines.
  308. X */
  309. X
  310. X
  311. X/*
  312. X * These routines replace the default trace/error routines included with the
  313. X * JPEG code.  The example trace_message routine shown here is actually the
  314. X * same as the standard one, but you could modify it if you don't want messages
  315. X * sent to stderr.  The example error_exit routine is set up to return
  316. X * control to read_JPEG_file() rather than calling exit().  You can use the
  317. X * same routines for both compression and decompression error recovery.
  318. X */
  319. X
  320. X/* These static variables are needed by the error routines. */
  321. Xstatic jmp_buf setjmp_buffer;    /* for return to caller */
  322. Xstatic external_methods_ptr emethods; /* needed for access to message_parm */
  323. X
  324. X
  325. X/* This routine is used for any and all trace, debug, or error printouts
  326. X * from the JPEG code.  The parameter is a printf format string; up to 8
  327. X * integer data values for the format string have been stored in the
  328. X * message_parm[] field of the external_methods struct.
  329. X */
  330. X
  331. XMETHODDEF void
  332. Xtrace_message (const char *msgtext)
  333. X{
  334. X  fprintf(stderr, msgtext,
  335. X      emethods->message_parm[0], emethods->message_parm[1],
  336. X      emethods->message_parm[2], emethods->message_parm[3],
  337. X      emethods->message_parm[4], emethods->message_parm[5],
  338. X      emethods->message_parm[6], emethods->message_parm[7]);
  339. X  fprintf(stderr, "\n");    /* there is no \n in the format string! */
  340. X}
  341. X
  342. X/*
  343. X * The error_exit() routine should not return to its caller.  The default
  344. X * routine calls exit(), but here we assume that we want to return to
  345. X * read_JPEG_data, which has set up a setjmp context for the purpose.
  346. X * You should make sure that the free_all method is called, either within
  347. X * error_exit or after the return to the outer-level routine.
  348. X */
  349. X
  350. XMETHODDEF void
  351. Xerror_exit (const char *msgtext)
  352. X{
  353. X  trace_message(msgtext);    /* report the error message */
  354. X  (*emethods->free_all) ();    /* clean up memory allocation & temp files */
  355. X  longjmp(setjmp_buffer, 1);    /* return control to outer routine */
  356. X}
  357. X
  358. X
  359. X
  360. X/*
  361. X * To accept the image data from decompression, you must define four routines
  362. X * output_init, put_color_map, put_pixel_rows, and output_term.
  363. X *
  364. X * You must understand the distinction between full color output mode
  365. X * (N independent color components) and colormapped output mode (a single
  366. X * output component representing an index into a color map).  You should use
  367. X * colormapped mode to write to a colormapped display screen or output file.
  368. X * Colormapped mode is also useful for reducing grayscale output to a small
  369. X * number of gray levels: when using the 1-pass quantizer on grayscale data,
  370. X * the colormap entries will be evenly spaced from 0 to MAX_JSAMPLE, so you
  371. X * can regard the indexes are directly representing gray levels at reduced
  372. X * precision.  In any other case, you should not depend on the colormap
  373. X * entries having any particular order.
  374. X * To get colormapped output, set cinfo->quantize_colors to TRUE and set
  375. X * cinfo->desired_number_of_colors to the maximum number of entries in the
  376. X * colormap.  This can be done either in your main routine or in
  377. X * d_ui_method_selection.  For grayscale quantization, also set
  378. X * cinfo->two_pass_quantize to FALSE to ensure the 1-pass quantizer is used
  379. X * (presently this is the default, but it may not be so in the future).
  380. X *
  381. X * The output file writing modules (jwrppm.c, jwrgif.c, jwrtarga.c, etc) may be
  382. X * useful examples of what these routines should actually do, although each of
  383. X * them is encrusted with a lot of specialized code for its own file format.
  384. X */
  385. X
  386. X
  387. XMETHODDEF void
  388. Xoutput_init (decompress_info_ptr cinfo)
  389. X/* This routine should do any setup required */
  390. X{
  391. X  /* This routine can initialize for output based on the data passed in cinfo.
  392. X   * Useful fields include:
  393. X   *    image_width, image_height    Pretty obvious, I hope.
  394. X   *    data_precision            bits per pixel value; typically 8.
  395. X   *    out_color_space            output colorspace previously requested
  396. X   *    color_out_comps            number of color components in same
  397. X   *    final_out_comps            number of components actually output
  398. X   * final_out_comps is 1 if quantize_colors is true, else it is equal to
  399. X   * color_out_comps.
  400. X   *
  401. X   * If you have requested color quantization, the colormap is NOT yet set.
  402. X   * You may wish to defer output initialization until put_color_map is called.
  403. X   */
  404. X}
  405. X
  406. X
  407. X/*
  408. X * This routine is called if and only if you have set cinfo->quantize_colors
  409. X * to TRUE.  It is given the selected colormap and can complete any required
  410. X * initialization.  This call will occur after output_init and before any
  411. X * calls to put_pixel_rows.  Note that the colormap pointer is also placed
  412. X * in a cinfo field, whence it can be used by put_pixel_rows or output_term.
  413. X * num_colors will be less than or equal to desired_number_of_colors.
  414. X *
  415. X * The colormap data is supplied as a 2-D array of JSAMPLEs, indexed as
  416. X *        JSAMPLE colormap[component][indexvalue]
  417. X * where component runs from 0 to cinfo->color_out_comps-1, and indexvalue
  418. X * runs from 0 to num_colors-1.  Note that this is actually an array of
  419. X * pointers to arrays rather than a true 2D array, since C does not support
  420. X * variable-size multidimensional arrays.
  421. X * JSAMPLE is typically typedef'd as "unsigned char".  If you want your code
  422. X * to be as portable as the JPEG code proper, you should always access JSAMPLE
  423. X * values with the GETJSAMPLE() macro, which will do the right thing if the
  424. X * machine has only signed chars.
  425. X */
  426. X
  427. XMETHODDEF void
  428. Xput_color_map (decompress_info_ptr cinfo, int num_colors, JSAMPARRAY colormap)
  429. X/* Write the color map */
  430. X{
  431. X  /* You need not provide this routine if you always set cinfo->quantize_colors
  432. X   * FALSE; but a safer practice is to provide it and have it just print an
  433. X   * error message, like this:
  434. X   */
  435. X  fprintf(stderr, "put_color_map called: there's a bug here somewhere!\n");
  436. X}
  437. X
  438. X
  439. X/*
  440. X * This function is called repeatedly, with a few more rows of pixels supplied
  441. X * on each call.  With the current JPEG code, some multiple of 8 rows will be
  442. X * passed on each call except the last, but it is extremely bad form to depend
  443. X * on this.  You CAN assume num_rows > 0.
  444. X * The data is supplied in top-to-bottom row order (the standard order within
  445. X * a JPEG file).  If you cannot readily use the data in that order, you'll
  446. X * need an intermediate array to hold the image.  See jwrrle.c for an example
  447. X * of outputting data in bottom-to-top order.
  448. X *
  449. X * The data is supplied as a 3-D array of JSAMPLEs, indexed as
  450. X *        JSAMPLE pixel_data[component][row][column]
  451. X * where component runs from 0 to cinfo->final_out_comps-1, row runs from 0 to
  452. X * num_rows-1, and column runs from 0 to cinfo->image_width-1 (column 0 is
  453. X * left edge of image).  Note that this is actually an array of pointers to
  454. X * pointers to arrays rather than a true 3D array, since C does not support
  455. X * variable-size multidimensional arrays.
  456. X * JSAMPLE is typically typedef'd as "unsigned char".  If you want your code
  457. X * to be as portable as the JPEG code proper, you should always access JSAMPLE
  458. X * values with the GETJSAMPLE() macro, which will do the right thing if the
  459. X * machine has only signed chars.
  460. X *
  461. X * If quantize_colors is true, then there is only one component, and its values
  462. X * are indexes into the previously supplied colormap.  Otherwise the values
  463. X * are actual data in your selected output colorspace.
  464. X */
  465. X
  466. X
  467. XMETHODDEF void
  468. Xput_pixel_rows (decompress_info_ptr cinfo, int num_rows, JSAMPIMAGE pixel_data)
  469. X/* Write some rows of output data */
  470. X{
  471. X  /* This example shows how you might write full-color RGB data (3 components)
  472. X   * to an output file in which the data is stored 3 bytes per pixel.
  473. X   */
  474. X  register FILE * outfile = cinfo->output_file;
  475. X  register JSAMPROW ptr0, ptr1, ptr2;
  476. X  register long col;
  477. X  register int row;
  478. X  
  479. X  for (row = 0; row < num_rows; row++) {
  480. X    ptr0 = pixel_data[0][row];
  481. X    ptr1 = pixel_data[1][row];
  482. X    ptr2 = pixel_data[2][row];
  483. X    for (col = 0; col < cinfo->image_width; col++) {
  484. X      putc(GETJSAMPLE(*ptr0), outfile);    /* red */
  485. X      ptr0++;
  486. X      putc(GETJSAMPLE(*ptr1), outfile);    /* green */
  487. X      ptr1++;
  488. X      putc(GETJSAMPLE(*ptr2), outfile);    /* blue */
  489. X      ptr2++;
  490. X    }
  491. X  }
  492. X}
  493. X
  494. X
  495. XMETHODDEF void
  496. Xoutput_term (decompress_info_ptr cinfo)
  497. X/* Finish up at the end of the output */
  498. X{
  499. X  /* This termination routine may not need to do anything. */
  500. X  /* Note that the JPEG code will only call it during successful exit; */
  501. X  /* if you want it called during error exit, you gotta do that yourself. */
  502. X}
  503. X
  504. X
  505. X/*
  506. X * That's it for the routines that deal with writing the output image.
  507. X * Now we have overall control and parameter selection routines.
  508. X */
  509. X
  510. X
  511. X/*
  512. X * This routine gets control after the JPEG file header has been read;
  513. X * at this point the image size and colorspace are known.
  514. X * The routine must determine what output routines are to be used, and make
  515. X * any decompression parameter changes that are desirable.  For example,
  516. X * if it is found that the JPEG file is grayscale, you might want to do
  517. X * things differently than if it is color.  You can also delay setting
  518. X * quantize_colors and associated options until this point. 
  519. X *
  520. X * j_d_defaults initializes out_color_space to CS_RGB.  If you want grayscale
  521. X * output you should set out_color_space to CS_GRAYSCALE.  Note that you can
  522. X * force grayscale output from a color JPEG file (though not vice versa).
  523. X */
  524. X
  525. XMETHODDEF void
  526. Xd_ui_method_selection (decompress_info_ptr cinfo)
  527. X{
  528. X  /* if grayscale input, force grayscale output; */
  529. X  /* else leave the output colorspace as set by main routine. */
  530. X  if (cinfo->jpeg_color_space == CS_GRAYSCALE)
  531. X    cinfo->out_color_space = CS_GRAYSCALE;
  532. X
  533. X  /* select output routines */
  534. X  cinfo->methods->output_init = output_init;
  535. X  cinfo->methods->put_color_map = put_color_map;
  536. X  cinfo->methods->put_pixel_rows = put_pixel_rows;
  537. X  cinfo->methods->output_term = output_term;
  538. X}
  539. X
  540. X
  541. X/*
  542. X * OK, here is the main function that actually causes everything to happen.
  543. X * We assume here that the JPEG filename is supplied by the caller of this
  544. X * routine, and that all decompression parameters can be default values.
  545. X * The routine returns 1 if successful, 0 if not.
  546. X */
  547. X
  548. XGLOBAL int
  549. Xread_JPEG_file (char * filename)
  550. X{
  551. X  /* These three structs contain JPEG parameters and working data.
  552. X   * They must survive for the duration of parameter setup and one
  553. X   * call to jpeg_decompress; typically, making them local data in the
  554. X   * calling routine is the best strategy.
  555. X   */
  556. X  struct decompress_info_struct cinfo;
  557. X  struct decompress_methods_struct dc_methods;
  558. X  struct external_methods_struct e_methods;
  559. X
  560. X  /* Select the input and output files.
  561. X   * In this example we want to open the input file before doing anything else,
  562. X   * so that the setjmp() error recovery below can assume the file is open.
  563. X   * Note that cinfo.output_file is only used if your output handling routines
  564. X   * use it; otherwise, you can just make it NULL.
  565. X   * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
  566. X   * requires it in order to read binary files.
  567. X   */
  568. X
  569. X  if ((cinfo.input_file = fopen(filename, "rb")) == NULL) {
  570. X    fprintf(stderr, "can't open %s\n", filename);
  571. X    return 0;
  572. X  }
  573. X
  574. X  cinfo.output_file = NULL;    /* if no actual output file involved */
  575. X
  576. X  /* Initialize the system-dependent method pointers. */
  577. X  cinfo.methods = &dc_methods;    /* links to method structs */
  578. X  cinfo.emethods = &e_methods;
  579. X  /* Here we supply our own error handler; compare to use of standard error
  580. X   * handler in the previous write_JPEG_file example.
  581. X   */
  582. X  emethods = &e_methods;    /* save struct addr for possible access */
  583. X  e_methods.error_exit = error_exit; /* supply error-exit routine */
  584. X  e_methods.trace_message = trace_message; /* supply trace-message routine */
  585. X
  586. X  /* prepare setjmp context for possible exit from error_exit */
  587. X  if (setjmp(setjmp_buffer)) {
  588. X    /* If we get here, the JPEG code has signaled an error.
  589. X     * Memory allocation has already been cleaned up (see free_all call in
  590. X     * error_exit), but we need to close the input file before returning.
  591. X     * You might also need to close an output file, etc.
  592. X     */
  593. X    fclose(cinfo.input_file);
  594. X    return 0;
  595. X  }
  596. X
  597. X  /* Here we use the standard memory manager provided with the JPEG code.
  598. X   * In some cases you might want to replace the memory manager, or at
  599. X   * least the system-dependent part of it, with your own code.
  600. X   */
  601. X  jselmemmgr(&e_methods);    /* select std memory allocation routines */
  602. X  /* If the decompressor requires full-image buffers (for two-pass color
  603. X   * quantization or a noninterleaved JPEG file), it will create temporary
  604. X   * files for anything that doesn't fit within the maximum-memory setting.
  605. X   * You can change the default maximum-memory setting by changing
  606. X   * e_methods.max_memory_to_use after jselmemmgr returns.
  607. X   * On some systems you may also need to set up a signal handler to
  608. X   * ensure that temporary files are deleted if the program is interrupted.
  609. X   * (This is most important if you are on MS-DOS and use the jmemdos.c
  610. X   * memory manager back end; it will try to grab extended memory for
  611. X   * temp files, and that space will NOT be freed automatically.)
  612. X   * See jcmain.c or jdmain.c for an example signal handler.
  613. X   */
  614. X
  615. X  /* Here, set up the pointer to your own routine for post-header-reading
  616. X   * parameter selection.  You could also initialize the pointers to the
  617. X   * output data handling routines here, if they are not dependent on the
  618. X   * image type.
  619. X   */
  620. X  dc_methods.d_ui_method_selection = d_ui_method_selection;
  621. X
  622. X  /* Set up default decompression parameters. */
  623. X  j_d_defaults(&cinfo, TRUE);
  624. X  /* TRUE indicates that an input buffer should be allocated.
  625. X   * In unusual cases you may want to allocate the input buffer yourself;
  626. X   * see jddeflts.c for commentary.
  627. X   */
  628. X
  629. X  /* At this point you can modify the default parameters set by j_d_defaults
  630. X   * as needed; for example, you can request color quantization or force
  631. X   * grayscale output.  See jdmain.c for examples of what you might change.
  632. X   */
  633. X
  634. X  /* Set up to read a JFIF or baseline-JPEG file. */
  635. X  /* This is the only JPEG file format currently supported. */
  636. X  jselrjfif(&cinfo);
  637. X
  638. X  /* Here we go! */
  639. X  jpeg_decompress(&cinfo);
  640. X
  641. X  /* That's it, son.  Nothin' else to do, except close files. */
  642. X  /* Here we assume only the input file need be closed. */
  643. X  fclose(cinfo.input_file);
  644. X
  645. X  return 1;            /* indicate success */
  646. X
  647. X  /* Note: if you want to decompress more than one image, we recommend you
  648. X   * repeat this whole routine.  You MUST repeat the j_d_defaults()/alter
  649. X   * parameters/jpeg_decompress() sequence, as some data structures allocated
  650. X   * in j_d_defaults are freed upon exit from jpeg_decompress.
  651. X   */
  652. X}
  653. END_OF_FILE
  654.   if test 26472 -ne `wc -c <'example.c'`; then
  655.     echo shar: \"'example.c'\" unpacked with wrong size!
  656.   fi
  657.   # end of 'example.c'
  658. fi
  659. if test -f 'jmemnobs.c' -a "${1}" != "-c" ; then 
  660.   echo shar: Will not clobber existing file \"'jmemnobs.c'\"
  661. else
  662.   echo shar: Extracting \"'jmemnobs.c'\" \(2263 characters\)
  663.   sed "s/^X//" >'jmemnobs.c' <<'END_OF_FILE'
  664. X/*
  665. X * jmemnobs.c  (jmemsys.c)
  666. X *
  667. X * Copyright (C) 1992, Thomas G. Lane.
  668. X * This file is part of the Independent JPEG Group's software.
  669. X * For conditions of distribution and use, see the accompanying README file.
  670. X *
  671. X * This file provides a really simple implementation of the system-
  672. X * dependent portion of the JPEG memory manager.  This implementation
  673. X * assumes that no backing-store files are needed: all required space
  674. X * can be obtained from malloc().
  675. X * This is very portable in the sense that it'll compile on almost anything,
  676. X * but you'd better have lots of main memory (or virtual memory) if you want
  677. X * to process big images.
  678. X * Note that the max_memory_to_use option is ignored by this implementation.
  679. X */
  680. X
  681. X#include "jinclude.h"
  682. X#include "jmemsys.h"
  683. X
  684. X#ifdef INCLUDES_ARE_ANSI
  685. X#include <stdlib.h>        /* to declare malloc(), free() */
  686. X#else
  687. Xextern void * malloc PP((size_t size));
  688. Xextern void free PP((void *ptr));
  689. X#endif
  690. X
  691. X
  692. Xstatic external_methods_ptr methods; /* saved for access to error_exit */
  693. X
  694. X
  695. X/*
  696. X * Memory allocation and freeing are controlled by the regular library
  697. X * routines malloc() and free().
  698. X */
  699. X
  700. XGLOBAL void *
  701. Xjget_small (size_t sizeofobject)
  702. X{
  703. X  return (void *) malloc(sizeofobject);
  704. X}
  705. X
  706. XGLOBAL void
  707. Xjfree_small (void * object)
  708. X{
  709. X  free(object);
  710. X}
  711. X
  712. X/*
  713. X * We assume NEED_FAR_POINTERS is not defined and so the separate entry points
  714. X * jget_large, jfree_large are not needed.
  715. X */
  716. X
  717. X
  718. X/*
  719. X * This routine computes the total memory space available for allocation.
  720. X * Here we always say, "we got all you want bud!"
  721. X */
  722. X
  723. XGLOBAL long
  724. Xjmem_available (long min_bytes_needed, long max_bytes_needed)
  725. X{
  726. X  return max_bytes_needed;
  727. X}
  728. X
  729. X
  730. X/*
  731. X * Backing store (temporary file) management.
  732. X * This should never be called and we just error out.
  733. X */
  734. X
  735. XGLOBAL void
  736. Xjopen_backing_store (backing_store_ptr info, long total_bytes_needed)
  737. X{
  738. X  ERREXIT(methods, "Backing store not supported");
  739. X}
  740. X
  741. X
  742. X/*
  743. X * These routines take care of any system-dependent initialization and
  744. X * cleanup required.  Keep in mind that jmem_term may be called more than
  745. X * once.
  746. X */
  747. X
  748. XGLOBAL void
  749. Xjmem_init (external_methods_ptr emethods)
  750. X{
  751. X  methods = emethods;        /* save struct addr for error exit access */
  752. X  emethods->max_memory_to_use = 0;
  753. X}
  754. X
  755. XGLOBAL void
  756. Xjmem_term (void)
  757. X{
  758. X  /* no work */
  759. X}
  760. END_OF_FILE
  761.   if test 2263 -ne `wc -c <'jmemnobs.c'`; then
  762.     echo shar: \"'jmemnobs.c'\" unpacked with wrong size!
  763.   fi
  764.   # end of 'jmemnobs.c'
  765. fi
  766. if test -f 'jquant1.c' -a "${1}" != "-c" ; then 
  767.   echo shar: Will not clobber existing file \"'jquant1.c'\"
  768. else
  769.   echo shar: Extracting \"'jquant1.c'\" \(21850 characters\)
  770.   sed "s/^X//" >'jquant1.c' <<'END_OF_FILE'
  771. X/*
  772. X * jquant1.c
  773. X *
  774. X * Copyright (C) 1991, 1992, Thomas G. Lane.
  775. X * This file is part of the Independent JPEG Group's software.
  776. X * For conditions of distribution and use, see the accompanying README file.
  777. X *
  778. X * This file contains 1-pass color quantization (color mapping) routines.
  779. X * These routines are invoked via the methods color_quantize
  780. X * and color_quant_init/term.
  781. X */
  782. X
  783. X#include "jinclude.h"
  784. X
  785. X#ifdef QUANT_1PASS_SUPPORTED
  786. X
  787. X
  788. X/*
  789. X * The main purpose of 1-pass quantization is to provide a fast, if not very
  790. X * high quality, colormapped output capability.  A 2-pass quantizer usually
  791. X * gives better visual quality; however, for quantized grayscale output this
  792. X * quantizer is perfectly adequate.  Dithering is highly recommended with this
  793. X * quantizer, though you can turn it off if you really want to.
  794. X *
  795. X * This implementation quantizes in the output colorspace.  This has a couple
  796. X * of disadvantages: each pixel must be individually color-converted, and if
  797. X * the color conversion includes gamma correction then quantization is done in
  798. X * a nonlinear space, which is less desirable.  The major advantage is that
  799. X * with the usual output color spaces (RGB, grayscale) an orthogonal grid of
  800. X * representative colors can be used, thus permitting the very simple and fast
  801. X * color lookup scheme used here.  The standard JPEG colorspace (YCbCr) cannot
  802. X * be effectively handled this way, because only about a quarter of an
  803. X * orthogonal grid would fall within the gamut of realizable colors.  Another
  804. X * advantage is that when the user wants quantized grayscale output from a
  805. X * color JPEG file, this quantizer can provide a high-quality result with no
  806. X * special hacking.
  807. X *
  808. X * The gamma-correction problem could be eliminated by adjusting the grid
  809. X * spacing to counteract the gamma correction applied by color_convert.
  810. X * At this writing, gamma correction is not implemented by jdcolor, so
  811. X * nothing is done here.
  812. X *
  813. X * In 1-pass quantization the colormap must be chosen in advance of seeing the
  814. X * image.  We use a map consisting of all combinations of Ncolors[i] color
  815. X * values for the i'th component.  The Ncolors[] values are chosen so that
  816. X * their product, the total number of colors, is no more than that requested.
  817. X * (In most cases, the product will be somewhat less.)
  818. X *
  819. X * Since the colormap is orthogonal, the representative value for each color
  820. X * component can be determined without considering the other components;
  821. X * then these indexes can be combined into a colormap index by a standard
  822. X * N-dimensional-array-subscript calculation.  Most of the arithmetic involved
  823. X * can be precalculated and stored in the lookup table colorindex[].
  824. X * colorindex[i][j] maps pixel value j in component i to the nearest
  825. X * representative value (grid plane) for that component; this index is
  826. X * multiplied by the array stride for component i, so that the
  827. X * index of the colormap entry closest to a given pixel value is just
  828. X *    sum( colorindex[component-number][pixel-component-value] )
  829. X * Aside from being fast, this scheme allows for variable spacing between
  830. X * representative values with no additional lookup cost.
  831. X */
  832. X
  833. X
  834. X#define MAX_COMPONENTS 4    /* max components I can handle */
  835. X
  836. Xstatic JSAMPARRAY colormap;    /* The actual color map */
  837. X/* colormap[i][j] = value of i'th color component for output pixel value j */
  838. X
  839. Xstatic JSAMPARRAY colorindex;    /* Precomputed mapping for speed */
  840. X/* colorindex[i][j] = index of color closest to pixel value j in component i,
  841. X * premultiplied as described above.  Since colormap indexes must fit into
  842. X * JSAMPLEs, the entries of this array will too.
  843. X */
  844. X
  845. Xstatic JSAMPARRAY input_buffer;    /* color conversion workspace */
  846. X/* Since our input data is presented in the JPEG colorspace, we have to call
  847. X * color_convert to get it into the output colorspace.  input_buffer is a
  848. X * one-row-high workspace for the result of color_convert.
  849. X */
  850. X
  851. X
  852. X/* Declarations for Floyd-Steinberg dithering.
  853. X *
  854. X * Errors are accumulated into the arrays evenrowerrs[] and oddrowerrs[].
  855. X * These have resolutions of 1/16th of a pixel count.  The error at a given
  856. X * pixel is propagated to its unprocessed neighbors using the standard F-S
  857. X * fractions,
  858. X *        ...    (here)    7/16
  859. X *        3/16    5/16    1/16
  860. X * We work left-to-right on even rows, right-to-left on odd rows.
  861. X *
  862. X * In each of the xxxrowerrs[] arrays, indexing is [component#][position].
  863. X * We provide (#columns + 2) entries per component; the extra entry at each
  864. X * end saves us from special-casing the first and last pixels.
  865. X * In evenrowerrs[], the entries for a component are stored left-to-right, but
  866. X * in oddrowerrs[] they are stored right-to-left.  This means we always
  867. X * process the current row's error entries in increasing order and the next
  868. X * row's error entries in decreasing order, regardless of whether we are
  869. X * working L-to-R or R-to-L in the pixel data!
  870. X *
  871. X * Note: on a wide image, we might not have enough room in a PC's near data
  872. X * segment to hold the error arrays; so they are allocated with alloc_medium.
  873. X */
  874. X
  875. X#ifdef EIGHT_BIT_SAMPLES
  876. Xtypedef INT16 FSERROR;        /* 16 bits should be enough */
  877. X#else
  878. Xtypedef INT32 FSERROR;        /* may need more than 16 bits? */
  879. X#endif
  880. X
  881. Xtypedef FSERROR FAR *FSERRPTR;    /* pointer to error array (in FAR storage!) */
  882. X
  883. Xstatic FSERRPTR evenrowerrs[MAX_COMPONENTS]; /* errors for even rows */
  884. Xstatic FSERRPTR oddrowerrs[MAX_COMPONENTS];  /* errors for odd rows */
  885. Xstatic boolean on_odd_row;    /* flag to remember which row we are on */
  886. X
  887. X
  888. X/*
  889. X * Policy-making subroutines for color_quant_init: these routines determine
  890. X * the colormap to be used.  The rest of the module only assumes that the
  891. X * colormap is orthogonal.
  892. X *
  893. X *  * select_ncolors decides how to divvy up the available colors
  894. X *    among the components.
  895. X *  * output_value defines the set of representative values for a component.
  896. X *  * largest_input_value defines the mapping from input values to
  897. X *    representative values for a component.
  898. X * Note that the latter two routines may impose different policies for
  899. X * different components, though this is not currently done.
  900. X */
  901. X
  902. X
  903. XLOCAL int
  904. Xselect_ncolors (decompress_info_ptr cinfo, int Ncolors[])
  905. X/* Determine allocation of desired colors to components, */
  906. X/* and fill in Ncolors[] array to indicate choice. */
  907. X/* Return value is total number of colors (product of Ncolors[] values). */
  908. X{
  909. X  int nc = cinfo->color_out_comps; /* number of color components */
  910. X  int max_colors = cinfo->desired_number_of_colors;
  911. X  int total_colors, iroot, i;
  912. X  long temp;
  913. X  boolean changed;
  914. X
  915. X  /* We can allocate at least the nc'th root of max_colors per component. */
  916. X  /* Compute floor(nc'th root of max_colors). */
  917. X  iroot = 1;
  918. X  do {
  919. X    iroot++;
  920. X    temp = iroot;        /* set temp = iroot ** nc */
  921. X    for (i = 1; i < nc; i++)
  922. X      temp *= iroot;
  923. X  } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  924. X  iroot--;            /* now iroot = floor(root) */
  925. X
  926. X  /* Must have at least 2 color values per component */
  927. X  if (iroot < 2)
  928. X    ERREXIT1(cinfo->emethods, "Cannot quantize to fewer than %d colors",
  929. X         (int) temp);
  930. X
  931. X  if (cinfo->out_color_space == CS_RGB && nc == 3) {
  932. X    /* We provide a special policy for quantizing in RGB space.
  933. X     * If 256 colors are requested, we allocate 8 red, 8 green, 4 blue levels;
  934. X     * this corresponds to the common 3/3/2-bit scheme.  For other totals,
  935. X     * the counts are set so that the number of colors allocated to each
  936. X     * component are roughly in the proportion R 3, G 4, B 2.
  937. X     * For low color counts, it's easier to hardwire the optimal choices
  938. X     * than try to tweak the algorithm to generate them.
  939. X     */
  940. X    if (max_colors == 256) {
  941. X      Ncolors[0] = 8;  Ncolors[1] = 8;  Ncolors[2] = 4;
  942. X      return 256;
  943. X    }
  944. X    if (max_colors < 12) {
  945. X      /* Fixed mapping for 8 colors */
  946. X      Ncolors[0] = Ncolors[1] = Ncolors[2] = 2;
  947. X    } else if (max_colors < 18) {
  948. X      /* Fixed mapping for 12 colors */
  949. X      Ncolors[0] = 2;  Ncolors[1] = 3;  Ncolors[2] = 2;
  950. X    } else if (max_colors < 24) {
  951. X      /* Fixed mapping for 18 colors */
  952. X      Ncolors[0] = 3;  Ncolors[1] = 3;  Ncolors[2] = 2;
  953. X    } else if (max_colors < 27) {
  954. X      /* Fixed mapping for 24 colors */
  955. X      Ncolors[0] = 3;  Ncolors[1] = 4;  Ncolors[2] = 2;
  956. X    } else if (max_colors < 36) {
  957. X      /* Fixed mapping for 27 colors */
  958. X      Ncolors[0] = 3;  Ncolors[1] = 3;  Ncolors[2] = 3;
  959. X    } else {
  960. X      /* these weights are readily derived with a little algebra */
  961. X      Ncolors[0] = (iroot * 266) >> 8; /* R weight is 1.0400 */
  962. X      Ncolors[1] = (iroot * 355) >> 8; /* G weight is 1.3867 */
  963. X      Ncolors[2] = (iroot * 177) >> 8; /* B weight is 0.6934 */
  964. X    }
  965. X    total_colors = Ncolors[0] * Ncolors[1] * Ncolors[2];
  966. X    /* The above computation produces "floor" values, so we may be able to
  967. X     * increment the count for one or more components without exceeding
  968. X     * max_colors.  We try in the order B, G, R.
  969. X     */
  970. X    do {
  971. X      changed = FALSE;
  972. X      for (i = 2; i >= 0; i--) {
  973. X    /* calculate new total_colors if Ncolors[i] is incremented */
  974. X    temp = total_colors / Ncolors[i];
  975. X    temp *= Ncolors[i]+1;    /* done in long arith to avoid oflo */
  976. X    if (temp <= (long) max_colors) {
  977. X      Ncolors[i]++;        /* OK, apply the increment */
  978. X      total_colors = (int) temp;
  979. X      changed = TRUE;
  980. X    }
  981. X      }
  982. X    } while (changed);        /* loop until no increment is possible */
  983. X  } else {
  984. X    /* For any colorspace besides RGB, treat all the components equally. */
  985. X
  986. X    /* Initialize to iroot color values for each component */
  987. X    total_colors = 1;
  988. X    for (i = 0; i < nc; i++) {
  989. X      Ncolors[i] = iroot;
  990. X      total_colors *= iroot;
  991. X    }
  992. X    /* We may be able to increment the count for one or more components without
  993. X     * exceeding max_colors, though we know not all can be incremented.
  994. X     */
  995. X    for (i = 0; i < nc; i++) {
  996. X      /* calculate new total_colors if Ncolors[i] is incremented */
  997. X      temp = total_colors / Ncolors[i];
  998. X      temp *= Ncolors[i]+1;    /* done in long arith to avoid oflo */
  999. X      if (temp > (long) max_colors)
  1000. X    break;            /* won't fit, done */
  1001. X      Ncolors[i]++;        /* OK, apply the increment */
  1002. X      total_colors = (int) temp;
  1003. X    }
  1004. X  }
  1005. X
  1006. X  return total_colors;
  1007. X}
  1008. X
  1009. X
  1010. XLOCAL int
  1011. Xoutput_value (decompress_info_ptr cinfo, int ci, int j, int maxj)
  1012. X/* Return j'th output value, where j will range from 0 to maxj */
  1013. X/* The output values must fall in 0..MAXJSAMPLE in increasing order */
  1014. X{
  1015. X  /* We always provide values 0 and MAXJSAMPLE for each component;
  1016. X   * any additional values are equally spaced between these limits.
  1017. X   * (Forcing the upper and lower values to the limits ensures that
  1018. X   * dithering can't produce a color outside the selected gamut.)
  1019. X   */
  1020. X  return (j * MAXJSAMPLE + maxj/2) / maxj;
  1021. X}
  1022. X
  1023. X
  1024. XLOCAL int
  1025. Xlargest_input_value (decompress_info_ptr cinfo, int ci, int j, int maxj)
  1026. X/* Return largest input value that should map to j'th output value */
  1027. X/* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  1028. X{
  1029. X  /* Breakpoints are halfway between values returned by output_value */
  1030. X  return ((2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj);
  1031. X}
  1032. X
  1033. X
  1034. X/*
  1035. X * Initialize for one-pass color quantization.
  1036. X */
  1037. X
  1038. XMETHODDEF void
  1039. Xcolor_quant_init (decompress_info_ptr cinfo)
  1040. X{
  1041. X  int total_colors;        /* Number of distinct output colors */
  1042. X  int Ncolors[MAX_COMPONENTS];    /* # of values alloced to each component */
  1043. X  int i,j,k, nci, blksize, blkdist, ptr, val;
  1044. X
  1045. X  /* Make sure my internal arrays won't overflow */
  1046. X  if (cinfo->num_components > MAX_COMPONENTS ||
  1047. X      cinfo->color_out_comps > MAX_COMPONENTS)
  1048. X    ERREXIT1(cinfo->emethods, "Cannot quantize more than %d color components",
  1049. X         MAX_COMPONENTS);
  1050. X  /* Make sure colormap indexes can be represented by JSAMPLEs */
  1051. X  if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  1052. X    ERREXIT1(cinfo->emethods, "Cannot request more than %d quantized colors",
  1053. X         MAXJSAMPLE+1);
  1054. X
  1055. X  /* Select number of colors for each component */
  1056. X  total_colors = select_ncolors(cinfo, Ncolors);
  1057. X
  1058. X  /* Report selected color counts */
  1059. X  if (cinfo->color_out_comps == 3)
  1060. X    TRACEMS4(cinfo->emethods, 1, "Quantizing to %d = %d*%d*%d colors",
  1061. X         total_colors, Ncolors[0], Ncolors[1], Ncolors[2]);
  1062. X  else
  1063. X    TRACEMS1(cinfo->emethods, 1, "Quantizing to %d colors", total_colors);
  1064. X
  1065. X  /* Allocate and fill in the colormap and color index. */
  1066. X  /* The colors are ordered in the map in standard row-major order, */
  1067. X  /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  1068. X
  1069. X  colormap = (*cinfo->emethods->alloc_small_sarray)
  1070. X        ((long) total_colors, (long) cinfo->color_out_comps);
  1071. X  colorindex = (*cinfo->emethods->alloc_small_sarray)
  1072. X        ((long) (MAXJSAMPLE+1), (long) cinfo->color_out_comps);
  1073. X
  1074. X  /* blksize is number of adjacent repeated entries for a component */
  1075. X  /* blkdist is distance between groups of identical entries for a component */
  1076. X  blkdist = total_colors;
  1077. X
  1078. X  for (i = 0; i < cinfo->color_out_comps; i++) {
  1079. X    /* fill in colormap entries for i'th color component */
  1080. X    nci = Ncolors[i];        /* # of distinct values for this color */
  1081. X    blksize = blkdist / nci;
  1082. X    for (j = 0; j < nci; j++) {
  1083. X      /* Compute j'th output value (out of nci) for component */
  1084. X      val = output_value(cinfo, i, j, nci-1);
  1085. X      /* Fill in all colormap entries that have this value of this component */
  1086. X      for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  1087. X    /* fill in blksize entries beginning at ptr */
  1088. X    for (k = 0; k < blksize; k++)
  1089. X      colormap[i][ptr+k] = (JSAMPLE) val;
  1090. X      }
  1091. X    }
  1092. X    blkdist = blksize;        /* blksize of this color is blkdist of next */
  1093. X
  1094. X    /* fill in colorindex entries for i'th color component */
  1095. X    /* in loop, val = index of current output value, */
  1096. X    /* and k = largest j that maps to current val */
  1097. X    val = 0;
  1098. X    k = largest_input_value(cinfo, i, 0, nci-1);
  1099. X    for (j = 0; j <= MAXJSAMPLE; j++) {
  1100. X      while (j > k)        /* advance val if past boundary */
  1101. X    k = largest_input_value(cinfo, i, ++val, nci-1);
  1102. X      /* premultiply so that no multiplication needed in main processing */
  1103. X      colorindex[i][j] = (JSAMPLE) (val * blksize);
  1104. X    }
  1105. X  }
  1106. X
  1107. X  /* Pass the colormap to the output module. */
  1108. X  /* NB: the output module may continue to use the colormap until shutdown. */
  1109. X  cinfo->colormap = colormap;
  1110. X  cinfo->actual_number_of_colors = total_colors;
  1111. X  (*cinfo->methods->put_color_map) (cinfo, total_colors, colormap);
  1112. X
  1113. X  /* Allocate workspace to hold one row of color-converted data */
  1114. X  input_buffer = (*cinfo->emethods->alloc_small_sarray)
  1115. X            (cinfo->image_width, (long) cinfo->color_out_comps);
  1116. X
  1117. X  /* Allocate Floyd-Steinberg workspace if necessary */
  1118. X  if (cinfo->use_dithering) {
  1119. X    size_t arraysize = (size_t) ((cinfo->image_width + 2L) * SIZEOF(FSERROR));
  1120. X
  1121. X    for (i = 0; i < cinfo->color_out_comps; i++) {
  1122. X      evenrowerrs[i] = (FSERRPTR) (*cinfo->emethods->alloc_medium) (arraysize);
  1123. X      oddrowerrs[i]  = (FSERRPTR) (*cinfo->emethods->alloc_medium) (arraysize);
  1124. X      /* we only need to zero the forward contribution for current row. */
  1125. X      jzero_far((void FAR *) evenrowerrs[i], arraysize);
  1126. X    }
  1127. X    on_odd_row = FALSE;
  1128. X  }
  1129. X}
  1130. X
  1131. X
  1132. X/*
  1133. X * Subroutines for color conversion methods.
  1134. X */
  1135. X
  1136. XLOCAL void
  1137. Xdo_color_conversion (decompress_info_ptr cinfo, JSAMPIMAGE input_data, int row)
  1138. X/* Convert the indicated row of the input data into output colorspace */
  1139. X/* in input_buffer.  This requires a little trickery since color_convert */
  1140. X/* expects to deal with 3-D arrays; fortunately we can fake it out */
  1141. X/* at fairly low cost. */
  1142. X{
  1143. X  short ci;
  1144. X  JSAMPARRAY input_hack[MAX_COMPONENTS];
  1145. X  JSAMPARRAY output_hack[MAX_COMPONENTS];
  1146. X
  1147. X  /* create JSAMPIMAGE pointing at specified row of input_data */
  1148. X  for (ci = 0; ci < cinfo->num_components; ci++)
  1149. X    input_hack[ci] = input_data[ci] + row;
  1150. X  /* Create JSAMPIMAGE pointing at input_buffer */
  1151. X  for (ci = 0; ci < cinfo->color_out_comps; ci++)
  1152. X    output_hack[ci] = &(input_buffer[ci]);
  1153. X
  1154. X  (*cinfo->methods->color_convert) (cinfo, 1, cinfo->image_width,
  1155. X                    input_hack, output_hack);
  1156. X}
  1157. X
  1158. X
  1159. X/*
  1160. X * Map some rows of pixels to the output colormapped representation.
  1161. X */
  1162. X
  1163. XMETHODDEF void
  1164. Xcolor_quantize (decompress_info_ptr cinfo, int num_rows,
  1165. X        JSAMPIMAGE input_data, JSAMPARRAY output_data)
  1166. X/* General case, no dithering */
  1167. X{
  1168. X  register int pixcode, ci;
  1169. X  register JSAMPROW ptrout;
  1170. X  register long col;
  1171. X  int row;
  1172. X  long width = cinfo->image_width;
  1173. X  register int nc = cinfo->color_out_comps;  
  1174. X
  1175. X  for (row = 0; row < num_rows; row++) {
  1176. X    do_color_conversion(cinfo, input_data, row);
  1177. X    ptrout = output_data[row];
  1178. X    for (col = 0; col < width; col++) {
  1179. X      pixcode = 0;
  1180. X      for (ci = 0; ci < nc; ci++) {
  1181. X    pixcode += GETJSAMPLE(colorindex[ci]
  1182. X                  [GETJSAMPLE(input_buffer[ci][col])]);
  1183. X      }
  1184. X      *ptrout++ = (JSAMPLE) pixcode;
  1185. X    }
  1186. X  }
  1187. X}
  1188. X
  1189. X
  1190. XMETHODDEF void
  1191. Xcolor_quantize3 (decompress_info_ptr cinfo, int num_rows,
  1192. X         JSAMPIMAGE input_data, JSAMPARRAY output_data)
  1193. X/* Fast path for color_out_comps==3, no dithering */
  1194. X{
  1195. X  register int pixcode;
  1196. X  register JSAMPROW ptr0, ptr1, ptr2, ptrout;
  1197. X  register long col;
  1198. X  int row;
  1199. X  long width = cinfo->image_width;
  1200. X
  1201. X  for (row = 0; row < num_rows; row++) {
  1202. X    do_color_conversion(cinfo, input_data, row);
  1203. X    ptr0 = input_buffer[0];
  1204. X    ptr1 = input_buffer[1];
  1205. X    ptr2 = input_buffer[2];
  1206. X    ptrout = output_data[row];
  1207. X    for (col = width; col > 0; col--) {
  1208. X      pixcode  = GETJSAMPLE(colorindex[0][GETJSAMPLE(*ptr0++)]);
  1209. X      pixcode += GETJSAMPLE(colorindex[1][GETJSAMPLE(*ptr1++)]);
  1210. X      pixcode += GETJSAMPLE(colorindex[2][GETJSAMPLE(*ptr2++)]);
  1211. X      *ptrout++ = (JSAMPLE) pixcode;
  1212. X    }
  1213. X  }
  1214. X}
  1215. X
  1216. X
  1217. XMETHODDEF void
  1218. Xcolor_quantize_dither (decompress_info_ptr cinfo, int num_rows,
  1219. X               JSAMPIMAGE input_data, JSAMPARRAY output_data)
  1220. X/* General case, with Floyd-Steinberg dithering */
  1221. X{
  1222. X  register FSERROR val;
  1223. X  FSERROR two_val;
  1224. X  register FSERRPTR thisrowerr, nextrowerr;
  1225. X  register JSAMPROW input_ptr;
  1226. X  register JSAMPROW output_ptr;
  1227. X  JSAMPROW colorindex_ci;
  1228. X  JSAMPROW colormap_ci;
  1229. X  register int pixcode;
  1230. X  int dir;            /* 1 for left-to-right, -1 for right-to-left */
  1231. X  int ci;
  1232. X  int nc = cinfo->color_out_comps;
  1233. X  int row;
  1234. X  long col_counter;
  1235. X  long width = cinfo->image_width;
  1236. X
  1237. X  for (row = 0; row < num_rows; row++) {
  1238. X    do_color_conversion(cinfo, input_data, row);
  1239. X    /* Initialize output values to 0 so can process components separately */
  1240. X    jzero_far((void FAR *) output_data[row],
  1241. X          (size_t) (width * SIZEOF(JSAMPLE)));
  1242. X    for (ci = 0; ci < nc; ci++) {
  1243. X      if (on_odd_row) {
  1244. X    /* work right to left in this row */
  1245. X    dir = -1;
  1246. X    input_ptr = input_buffer[ci] + (width-1);
  1247. X    output_ptr = output_data[row] + (width-1);
  1248. X    thisrowerr = oddrowerrs[ci] + 1;
  1249. X    nextrowerr = evenrowerrs[ci] + width;
  1250. X      } else {
  1251. X    /* work left to right in this row */
  1252. X    dir = 1;
  1253. X    input_ptr = input_buffer[ci];
  1254. X    output_ptr = output_data[row];
  1255. X    thisrowerr = evenrowerrs[ci] + 1;
  1256. X    nextrowerr = oddrowerrs[ci] + width;
  1257. X      }
  1258. X      colorindex_ci = colorindex[ci];
  1259. X      colormap_ci = colormap[ci];
  1260. X      *nextrowerr = 0;        /* need only initialize this one entry */
  1261. X      for (col_counter = width; col_counter > 0; col_counter--) {
  1262. X    /* Compute pixel value + accumulated error for this component */
  1263. X    val = (((FSERROR) GETJSAMPLE(*input_ptr)) << 4) + *thisrowerr;
  1264. X    if (val < 0) val = 0;    /* must watch for range overflow! */
  1265. X    else {
  1266. X      val += 8;        /* divide by 16 with proper rounding */
  1267. X      val >>= 4;
  1268. X      if (val > MAXJSAMPLE) val = MAXJSAMPLE;
  1269. X    }
  1270. X    /* Select output value, accumulate into output code for this pixel */
  1271. X    pixcode = GETJSAMPLE(*output_ptr);
  1272. X    pixcode += GETJSAMPLE(colorindex_ci[val]);
  1273. X    *output_ptr = (JSAMPLE) pixcode;
  1274. X    /* Compute actual representation error at this pixel */
  1275. X    /* Note: we can do this even though we don't yet have the final */
  1276. X    /* value of pixcode, because the colormap is orthogonal. */
  1277. X    val -= (FSERROR) GETJSAMPLE(colormap_ci[pixcode]);
  1278. X    /* Propagate error to (same component of) adjacent pixels */
  1279. X    /* Remember that nextrowerr entries are in reverse order! */
  1280. X    two_val = val * 2;
  1281. X    nextrowerr[-1]  = val; /* not +=, since not initialized yet */
  1282. X    val += two_val;        /* form error * 3 */
  1283. X    nextrowerr[ 1] += val;
  1284. X    val += two_val;        /* form error * 5 */
  1285. X    nextrowerr[ 0] += val;
  1286. X    val += two_val;        /* form error * 7 */
  1287. X    thisrowerr[ 1] += val;
  1288. X    input_ptr += dir;    /* advance input ptr to next column */
  1289. X    output_ptr += dir;    /* advance output ptr to next column */
  1290. X    thisrowerr++;        /* cur-row error ptr advances to right */
  1291. X    nextrowerr--;        /* next-row error ptr advances to left */
  1292. X      }
  1293. X    }
  1294. X    on_odd_row = (on_odd_row ? FALSE : TRUE);
  1295. X  }
  1296. X}
  1297. X
  1298. X
  1299. X/*
  1300. X * Finish up at the end of the file.
  1301. X */
  1302. X
  1303. XMETHODDEF void
  1304. Xcolor_quant_term (decompress_info_ptr cinfo)
  1305. X{
  1306. X  /* no work (we let free_all release the workspace) */
  1307. X  /* Note that we *mustn't* free the colormap before free_all, */
  1308. X  /* since output module may use it! */
  1309. X}
  1310. X
  1311. X
  1312. X/*
  1313. X * Prescan some rows of pixels.
  1314. X * Not used in one-pass case.
  1315. X */
  1316. X
  1317. XMETHODDEF void
  1318. Xcolor_quant_prescan (decompress_info_ptr cinfo, int num_rows,
  1319. X             JSAMPIMAGE image_data, JSAMPARRAY workspace)
  1320. X{
  1321. X  ERREXIT(cinfo->emethods, "Should not get here!");
  1322. X}
  1323. X
  1324. X
  1325. X/*
  1326. X * Do two-pass quantization.
  1327. X * Not used in one-pass case.
  1328. X */
  1329. X
  1330. XMETHODDEF void
  1331. Xcolor_quant_doit (decompress_info_ptr cinfo, quantize_caller_ptr source_method)
  1332. X{
  1333. X  ERREXIT(cinfo->emethods, "Should not get here!");
  1334. X}
  1335. X
  1336. X
  1337. X/*
  1338. X * The method selection routine for 1-pass color quantization.
  1339. X */
  1340. X
  1341. XGLOBAL void
  1342. Xjsel1quantize (decompress_info_ptr cinfo)
  1343. X{
  1344. X  if (! cinfo->two_pass_quantize) {
  1345. X    cinfo->methods->color_quant_init = color_quant_init;
  1346. X    if (cinfo->use_dithering) {
  1347. X      cinfo->methods->color_quantize = color_quantize_dither;
  1348. X    } else {
  1349. X      if (cinfo->color_out_comps == 3)
  1350. X    cinfo->methods->color_quantize = color_quantize3;
  1351. X      else
  1352. X    cinfo->methods->color_quantize = color_quantize;
  1353. X    }
  1354. X    cinfo->methods->color_quant_prescan = color_quant_prescan;
  1355. X    cinfo->methods->color_quant_doit = color_quant_doit;
  1356. X    cinfo->methods->color_quant_term = color_quant_term;
  1357. X  }
  1358. X}
  1359. X
  1360. X#endif /* QUANT_1PASS_SUPPORTED */
  1361. END_OF_FILE
  1362.   if test 21850 -ne `wc -c <'jquant1.c'`; then
  1363.     echo shar: \"'jquant1.c'\" unpacked with wrong size!
  1364.   fi
  1365.   # end of 'jquant1.c'
  1366. fi
  1367. echo shar: End of archive 9 \(of 18\).
  1368. cp /dev/null ark9isdone
  1369. MISSING=""
  1370. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ; do
  1371.     if test ! -f ark${I}isdone ; then
  1372.     MISSING="${MISSING} ${I}"
  1373.     fi
  1374. done
  1375. if test "${MISSING}" = "" ; then
  1376.     echo You have unpacked all 18 archives.
  1377.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1378. else
  1379.     echo You still must unpack the following archives:
  1380.     echo "        " ${MISSING}
  1381. fi
  1382. exit 0
  1383. exit 0 # Just in case...
  1384.