home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume44 / jpeg / part02 / libjpeg.doc.B next >
Text File  |  1994-09-26  |  60KB  |  1,072 lines

  1.  
  2. JDIMENSION output_width        Actual dimensions of output image.
  3. JDIMENSION output_height
  4. int out_color_components    Number of color components in out_color_space.
  5. int output_components        Number of color components returned.
  6. int rec_outbuf_height        Recommended height of scanline buffer.
  7.  
  8. When quantizing colors, output_components is 1, indicating a single color map
  9. index per pixel.  Otherwise it equals out_color_components.  The output arrays
  10. are required to be output_width * output_components JSAMPLEs wide.
  11.  
  12. rec_outbuf_height is the recommended minimum height (in scanlines) of the
  13. buffer passed to jpeg_read_scanlines().  If the buffer is smaller, the
  14. library will still work, but time will be wasted due to unnecessary data
  15. copying.  In high-quality modes, rec_outbuf_height is always 1, but some
  16. faster, lower-quality modes set it to larger values (typically 2 to 4).
  17. If you are going to ask for a high-speed processing mode, you may as well
  18. go to the trouble of honoring rec_outbuf_height so as to avoid data copying.
  19.  
  20.  
  21. Special color spaces
  22. --------------------
  23.  
  24. The JPEG standard itself is "color blind" and doesn't specify any particular
  25. color space.  It is customary to convert color data to a luminance/chrominance
  26. color space before compressing, since this permits greater compression.  The
  27. existing de-facto JPEG file format standards specify YCbCr or grayscale data
  28. (JFIF), or grayscale, RGB, YCbCr, CMYK, or YCCK (Adobe).  For special
  29. applications such as multispectral images, other color spaces can be used,
  30. but it must be understood that such files will be unportable.
  31.  
  32. The JPEG library can handle the most common colorspace conversions (namely
  33. RGB <=> YCbCr and CMYK <=> YCCK).  It can also deal with data of an unknown
  34. color space, passing it through without conversion.  If you deal extensively
  35. with an unusual color space, you can easily extend the library to understand
  36. additional color spaces and perform appropriate conversions.
  37.  
  38. For compression, the source data's color space is specified by field
  39. in_color_space.  This is transformed to the JPEG file's color space given
  40. by jpeg_color_space.  jpeg_set_defaults() chooses a reasonable JPEG color
  41. space depending on in_color_space, but you can override this by calling
  42. jpeg_set_colorspace().  Of course you must select a supported transformation.
  43. jccolor.c currently supports the following transformations:
  44.     RGB => YCbCr
  45.     RGB => GRAYSCALE
  46.     YCbCr => GRAYSCALE
  47.     CMYK => YCCK
  48. plus the null transforms: GRAYSCALE => GRAYSCALE, RGB => RGB,
  49. YCbCr => YCbCr, CMYK => CMYK, YCCK => YCCK, and UNKNOWN => UNKNOWN.
  50.  
  51. The de-facto file format standards (JFIF and Adobe) specify APPn markers that
  52. indicate the color space of the JPEG file.  It is important to ensure that
  53. these are written correctly, or omitted if the JPEG file's color space is not
  54. one of the ones supported by the de-facto standards.  jpeg_set_colorspace()
  55. will set the compression parameters to include or omit the APPn markers
  56. properly, so long as it is told the truth about the JPEG color space.
  57. For example, if you are writing some random 3-component color space without
  58. conversion, don't try to fake out the library by setting in_color_space and
  59. jpeg_color_space to JCS_YCbCr; use JCS_UNKNOWN.  You may want to write an
  60. APPn marker of your own devising to identify the colorspace --- see "Special
  61. markers", below.
  62.  
  63. When told that the color space is UNKNOWN, the library will default to using
  64. luminance-quality compression parameters for all color components.  You may
  65. well want to change these parameters.  See the source code for
  66. jpeg_set_colorspace(), in jcparam.c, for details.
  67.  
  68. For decompression, the JPEG file's color space is given in jpeg_color_space,
  69. and this is transformed to the output color space out_color_space.
  70. jpeg_read_header's setting of jpeg_color_space can be relied on if the file
  71. conforms to JFIF or Adobe conventions, but otherwise it is no better than a
  72. guess.  If you know the JPEG file's color space for certain, you can override
  73. jpeg_read_header's guess by setting jpeg_color_space.  jpeg_read_header also
  74. selects a default output color space based on (its guess of) jpeg_color_space;
  75. set out_color_space to override this.  Again, you must select a supported
  76. transformation.  jdcolor.c currently supports
  77.     YCbCr => GRAYSCALE
  78.     YCbCr => RGB
  79.     YCCK => CMYK
  80. as well as the null transforms.
  81.  
  82. The two-pass color quantizer, jquant2.c, is specialized to handle RGB data
  83. (it weights distances appropriately for RGB colors).  You'll need to modify
  84. the code if you want to use it for non-RGB output color spaces.  Note that
  85. jquant2.c is used to map to an application-supplied colormap as well as for
  86. the normal two-pass colormap selection process.
  87.  
  88. CAUTION: it appears that Adobe Photoshop writes inverted data in CMYK JPEG
  89. files: 0 represents 100% ink coverage, rather than 0% ink as you'd expect.
  90. This is arguably a bug in Photoshop, but if you need to work with Photoshop
  91. CMYK files, you will have to deal with it in your application.  We cannot
  92. "fix" this in the library by inverting the data during the CMYK<=>YCCK
  93. transform, because that would break other applications, notably Ghostscript.
  94. Photoshop versions prior to 3.0 write EPS files containing JPEG-encoded CMYK
  95. data in the same inverted-YCCK representation used in bare JPEG files, but
  96. the surrounding PostScript code performs an inversion using the PS image
  97. operator.  I am told that Photoshop 3.0 will write uninverted YCCK in
  98. EPS/JPEG files, and will omit the PS-level inversion.  (But the data
  99. polarity used in bare JPEG files will not change in 3.0.)  In either case,
  100. the JPEG library must not invert the data itself, or else Ghostscript would
  101. read these EPS files incorrectly.
  102.  
  103.  
  104. Error handling
  105. --------------
  106.  
  107. When the default error handler is used, any error detected inside the JPEG
  108. routines will cause a message to be printed on stderr, followed by exit().
  109. You can supply your own error handling routines to override this behavior
  110. and to control the treatment of nonfatal warnings and trace/debug messages.
  111. The file example.c illustrates the most common case, which is to have the
  112. application regain control after an error rather than exiting.
  113.  
  114. The JPEG library never writes any message directly; it always goes through
  115. the error handling routines.  Three classes of messages are recognized:
  116.   * Fatal errors: the library cannot continue.
  117.   * Warnings: the library can continue, but the data is corrupt, and a
  118.     damaged output image is likely to result.
  119.   * Trace/informational messages.  These come with a trace level indicating
  120.     the importance of the message; you can control the verbosity of the
  121.     program by adjusting the maximum trace level that will be displayed.
  122.  
  123. You may, if you wish, simply replace the entire JPEG error handling module
  124. (jerror.c) with your own code.  However, you can avoid code duplication by
  125. only replacing some of the routines depending on the behavior you need.
  126. This is accomplished by calling jpeg_std_error() as usual, but then overriding
  127. some of the method pointers in the jpeg_error_mgr struct, as illustrated by
  128. example.c.
  129.  
  130. All of the error handling routines will receive a pointer to the JPEG object
  131. (a j_common_ptr which points to either a jpeg_compress_struct or a
  132. jpeg_decompress_struct; if you need to tell which, test the is_decompressor
  133. field).  This struct includes a pointer to the error manager struct in its
  134. "err" field.  Frequently, custom error handler routines will need to access
  135. additional data which is not known to the JPEG library or the standard error
  136. handler.  The most convenient way to do this is to embed either the JPEG
  137. object or the jpeg_error_mgr struct in a larger structure that contains
  138. additional fields; then casting the passed pointer provides access to the
  139. additional fields.  Again, see example.c for one way to do it.
  140.  
  141. The individual methods that you might wish to override are:
  142.  
  143. error_exit (j_common_ptr cinfo)
  144.     Receives control for a fatal error.  Information sufficient to
  145.     generate the error message has been stored in cinfo->err; call
  146.     output_message to display it.  Control must NOT return to the caller;
  147.     generally this routine will exit() or longjmp() somewhere.
  148.     Typically you would override this routine to get rid of the exit()
  149.     default behavior.  Note that if you continue processing, you should
  150.     clean up the JPEG object with jpeg_abort() or jpeg_destroy().
  151.  
  152. output_message (j_common_ptr cinfo)
  153.     Actual output of any JPEG message.  Override this to send messages
  154.     somewhere other than stderr.  Note that this method does not know
  155.     how to generate a message, only where to send it.
  156.  
  157. format_message (j_common_ptr cinfo, char * buffer)
  158.     Constructs a readable error message string based on the error info
  159.     stored in cinfo->err.  This method is called by output_message.  Few
  160.     applications should need to override this method.  One possible
  161.     reason for doing so is to implement dynamic switching of error message
  162.     language.
  163.  
  164. emit_message (j_common_ptr cinfo, int msg_level)
  165.     Decide whether or not to emit a warning or trace message; if so,
  166.     calls output_message.  The main reason for overriding this method
  167.     would be to abort on warnings.  msg_level is -1 for warnings,
  168.     0 and up for trace messages.
  169.  
  170. Only error_exit() and emit_message() are called from the rest of the JPEG
  171. library; the other two are internal to the error handler.
  172.  
  173. The actual message texts are stored in an array of strings which is pointed to
  174. by the field err->jpeg_message_table.  The messages are numbered from 0 to
  175. err->last_jpeg_message, and it is these code numbers that are used in the
  176. JPEG library code.  You could replace the message texts (for instance, with
  177. messages in French or German) by changing the message table pointer.  See
  178. jerror.h for the default texts.  CAUTION: this table will almost certainly
  179. change or grow from one library version to the next.
  180.  
  181. It may be useful for an application to add its own message texts that are
  182. handled by the same mechanism.  The error handler supports a second "add-on"
  183. message table for this purpose.  To define an addon table, set the pointer
  184. err->addon_message_table and the message numbers err->first_addon_message and
  185. err->last_addon_message.  If you number the addon messages beginning at 1000
  186. or so, you won't have to worry about conflicts with the library's built-in
  187. messages.  See the sample applications cjpeg/djpeg for an example of using
  188. addon messages (the addon messages are defined in cderror.h).
  189.  
  190. Actual invocation of the error handler is done via macros defined in jerror.h:
  191.     ERREXITn(...)    for fatal errors
  192.     WARNMSn(...)    for corrupt-data warnings
  193.     TRACEMSn(...)    for trace and informational messages.
  194. These macros store the message code and any additional parameters into the
  195. error handler struct, then invoke the error_exit() or emit_message() method.
  196. The variants of each macro are for varying numbers of additional parameters.
  197. The additional parameters are inserted into the generated message using
  198. standard printf() format codes.
  199.  
  200. See jerror.h and jerror.c for further details.
  201.  
  202.  
  203. Compressed data handling (source and destination managers)
  204. ----------------------------------------------------------
  205.  
  206. The JPEG compression library sends its compressed data to a "destination
  207. manager" module.  The default destination manager just writes the data to a
  208. stdio stream, but you can provide your own manager to do something else.
  209. Similarly, the decompression library calls a "source manager" to obtain the
  210. compressed data; you can provide your own source manager if you want the data
  211. to come from somewhere other than a stdio stream.
  212.  
  213. In both cases, compressed data is processed a bufferload at a time: the
  214. destination or source manager provides a work buffer, and the library invokes
  215. the manager only when the buffer is filled or emptied.  (You could define a
  216. one-character buffer to force the manager to be invoked for each byte, but
  217. that would be rather inefficient.)  The buffer's size and location are
  218. controlled by the manager, not by the library.  For example, if you desired to
  219. decompress a JPEG datastream that was all in memory, you could just make the
  220. buffer pointer and length point to the original data in memory.  Then the
  221. buffer-reload procedure would be invoked only if the decompressor ran off the
  222. end of the datastream, which would indicate an erroneous datastream.
  223.  
  224. The work buffer is defined as an array of datatype JOCTET, which is generally
  225. "char" or "unsigned char".  On a machine where char is not exactly 8 bits
  226. wide, you must define JOCTET as a wider data type and then modify the data
  227. source and destination modules to transcribe the work arrays into 8-bit units
  228. on external storage.
  229.  
  230. A data destination manager struct contains a pointer and count defining the
  231. next byte to write in the work buffer and the remaining free space:
  232.  
  233.     JOCTET * next_output_byte;  /* => next byte to write in buffer */
  234.     size_t free_in_buffer;      /* # of byte spaces remaining in buffer */
  235.  
  236. The library increments the pointer and decrements the count until the buffer
  237. is filled.  The manager's empty_output_buffer method must reset the pointer
  238. and count.  The manager is expected to remember the buffer's starting address
  239. and total size in private fields not visible to the library.
  240.  
  241. A data destination manager provides three methods:
  242.  
  243. init_destination (j_compress_ptr cinfo)
  244.     Initialize destination.  This is called by jpeg_start_compress()
  245.     before any data is actually written.  It must initialize
  246.     next_output_byte and free_in_buffer.  free_in_buffer must be
  247.     initialized to a positive value.
  248.  
  249. empty_output_buffer (j_compress_ptr cinfo)
  250.     This is called whenever the buffer has filled (free_in_buffer
  251.     reaches zero).  In typical applications, it should write out the
  252.     *entire* buffer (use the saved start address and buffer length;
  253.     ignore the current state of next_output_byte and free_in_buffer).
  254.     Then reset the pointer & count to the start of the buffer, and
  255.     return TRUE indicating that the buffer has been dumped.
  256.     free_in_buffer must be set to a positive value when TRUE is
  257.     returned.  A FALSE return should only be used when I/O suspension is
  258.     desired (this operating mode is discussed in the next section).
  259.  
  260. term_destination (j_compress_ptr cinfo)
  261.     Terminate destination --- called by jpeg_finish_compress() after all
  262.     data has been written.  In most applications, this must flush any
  263.     data remaining in the buffer.  Use either next_output_byte or
  264.     free_in_buffer to determine how much data is in the buffer.
  265.  
  266. term_destination() is NOT called by jpeg_abort() or jpeg_destroy().  If you
  267. want the destination manager to be cleaned up during an abort, you must do it
  268. yourself.
  269.  
  270. You will also need code to create a jpeg_destination_mgr struct, fill in its
  271. method pointers, and insert a pointer to the struct into the "dest" field of
  272. the JPEG compression object.  This can be done in-line in your setup code if
  273. you like, but it's probably cleaner to provide a separate routine similar to
  274. the jpeg_stdio_dest() routine of the supplied destination manager.
  275.  
  276. Decompression source managers follow a parallel design, but with some
  277. additional frammishes.  The source manager struct contains a pointer and count
  278. defining the next byte to read from the work buffer and the number of bytes
  279. remaining:
  280.  
  281.     const JOCTET * next_input_byte; /* => next byte to read from buffer */
  282.     size_t bytes_in_buffer;         /* # of bytes remaining in buffer */
  283.  
  284. The library increments the pointer and decrements the count until the buffer
  285. is emptied.  The manager's fill_input_buffer method must reset the pointer and
  286. count.  In most applications, the manager must remember the buffer's starting
  287. address and total size in private fields not visible to the library.
  288.  
  289. A data source manager provides five methods:
  290.  
  291. init_source (j_decompress_ptr cinfo)
  292.     Initialize source.  This is called by jpeg_read_header() before any
  293.     data is actually read.  Unlike init_destination(), it may leave
  294.     bytes_in_buffer set to 0 (in which case a fill_input_buffer() call
  295.     will occur immediately).
  296.  
  297. fill_input_buffer (j_decompress_ptr cinfo)
  298.     This is called whenever bytes_in_buffer has reached zero and more
  299.     data is wanted.  In typical applications, it should read fresh data
  300.     into the buffer (ignoring the current state of next_input_byte and
  301.     bytes_in_buffer), reset the pointer & count to the start of the
  302.     buffer, and return TRUE indicating that the buffer has been reloaded.
  303.     It is not necessary to fill the buffer entirely, only to obtain at
  304.     least one more byte.  bytes_in_buffer MUST be set to a positive value
  305.     if TRUE is returned.  A FALSE return should only be used when I/O
  306.     suspension is desired (this mode is discussed in the next section).
  307.  
  308. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  309.     Skip num_bytes worth of data.  The buffer pointer and count should
  310.     be advanced over num_bytes input bytes, refilling the buffer as
  311.     needed.  This is used to skip over a potentially large amount of
  312.     uninteresting data (such as an APPn marker).  In some applications
  313.     it may be possible to optimize away the reading of the skipped data,
  314.     but it's not clear that being smart is worth much trouble; large
  315.     skips are uncommon.  bytes_in_buffer may be zero on return.
  316.     A zero or negative skip count should be treated as a no-op.
  317.  
  318. resync_to_restart (j_decompress_ptr cinfo)
  319.     This routine is called only when the decompressor has failed to find
  320.     a restart (RSTn) marker where one is expected.  Its mission is to
  321.     find a suitable point for resuming decompression.  For most
  322.     applications, we recommend that you just use the default resync
  323.     procedure, jpeg_resync_to_restart().  However, if you are able to back
  324.     up in the input data stream, or if you have a-priori knowledge about
  325.     the likely location of restart markers, you may be able to do better.
  326.     Read the read_restart_marker() and jpeg_resync_to_restart() routines
  327.     in jdmarker.c if you think you'd like to implement your own resync
  328.     procedure.
  329.  
  330. term_source (j_decompress_ptr cinfo)
  331.     Terminate source --- called by jpeg_finish_decompress() after all
  332.     data has been read.  Often a no-op.
  333.  
  334. For both fill_input_buffer() and skip_input_data(), there is no such thing
  335. as an EOF return.  If the end of the file has been reached, the routine has
  336. a choice of exiting via ERREXIT() or inserting fake data into the buffer.
  337. In most cases, generating a warning message and inserting a fake EOI marker
  338. is the best course of action --- this will allow the decompressor to output
  339. however much of the image is there.  In pathological cases, the decompressor
  340. may swallow the EOI and again demand data ... just keep feeding it fake EOIs.
  341. jdatasrc.c illustrates the recommended error recovery behavior.
  342.  
  343. term_source() is NOT called by jpeg_abort() or jpeg_destroy().  If you want
  344. the source manager to be cleaned up during an abort, you must do it yourself.
  345.  
  346. You will also need code to create a jpeg_source_mgr struct, fill in its method
  347. pointers, and insert a pointer to the struct into the "src" field of the JPEG
  348. decompression object.  This can be done in-line in your setup code if you
  349. like, but it's probably cleaner to provide a separate routine similar to the
  350. jpeg_stdio_src() routine of the supplied source manager.
  351.  
  352. For more information, consult the stdio source and destination managers
  353. in jdatasrc.c and jdatadst.c.
  354.  
  355.  
  356. I/O suspension
  357. --------------
  358.  
  359. Some applications need to use the JPEG library as an incremental memory-to-
  360. memory filter: when the compressed data buffer is filled or emptied, they want
  361. control to return to the outer loop, rather than expecting that the buffer can
  362. be flushed or reloaded within the data source/destination manager subroutine.
  363. The library supports this need by providing an "I/O suspension" mode, which we
  364. describe in this section.
  365.  
  366. The I/O suspension mode is a limited solution: it works only in the simplest
  367. operating modes (namely single-pass processing of single-scan JPEG files), and
  368. it has several other restrictions which are documented below.  Furthermore,
  369. nothing is guaranteed about the maximum amount of time spent in any one call
  370. to the library, so a single-threaded application may still have response-time
  371. problems.  If you need multi-pass processing or guaranteed response time, we
  372. suggest you "bite the bullet" and implement a real multi-tasking capability.
  373.  
  374. To use I/O suspension, cooperation is needed between the calling application
  375. and the data source or destination manager; you will always need a custom
  376. source/destination manager.  (Please read the previous section if you haven't
  377. already.)  The basic idea is that the empty_output_buffer() or
  378. fill_input_buffer() routine is a no-op, merely returning FALSE to indicate
  379. that it has done nothing.  Upon seeing this, the JPEG library suspends
  380. operation and returns to its caller.  The surrounding application is
  381. responsible for emptying or refilling the work buffer before calling the JPEG
  382. library again.
  383.  
  384. Compression suspension:
  385.  
  386. For compression suspension, use an empty_output_buffer() routine that
  387. returns FALSE; typically it will not do anything else.  This will cause the
  388. compressor to return to the caller of jpeg_write_scanlines(), with the
  389. return value indicating that not all the supplied scanlines have been
  390. accepted.  The application must make more room in the output buffer, adjust
  391. the buffer pointer/count appropriately, and then call jpeg_write_scanlines()
  392. again, pointing to the first unconsumed scanline.
  393.  
  394. When forced to suspend, the compressor will backtrack to a convenient stopping
  395. point (usually the start of the current MCU); it will regenerate some output
  396. data when restarted.  Therefore, although empty_output_buffer() is only called
  397. when the buffer is filled, you should NOT dump out the entire buffer, only the
  398. data up to the current position of next_output_byte/free_in_buffer.  The data
  399. beyond that point will be regenerated after resumption.
  400.  
  401. Because of the backtracking behavior, a good-size output buffer is essential
  402. for efficiency; you don't want the compressor to suspend often.  (In fact, an
  403. overly small buffer could lead to infinite looping, if a single MCU required
  404. more data than would fit in the buffer.)  We recommend a buffer of at least
  405. several Kbytes.  You may want to insert explicit code to ensure that you don't
  406. call jpeg_write_scanlines() unless there is a reasonable amount of space in
  407. the output buffer; in other words, flush the buffer before trying to compress
  408. more data.
  409.  
  410. The JPEG compressor does not support suspension while it is trying to write
  411. JPEG markers at the beginning and end of the file.  This means that
  412.   * At the beginning of a compression operation, there must be enough free
  413.     space in the output buffer to hold the header markers (typically 600 or
  414.     so bytes).  The recommended buffer size is bigger than this anyway, so
  415.     this is not a problem as long as you start with an empty buffer.  However,
  416.     this restriction might catch you if you insert large special markers, such
  417.     as a JFIF thumbnail image.
  418.   * When you call jpeg_finish_compress(), there must be enough space in the
  419.     output buffer to emit any buffered data and the final EOI marker.  In the
  420.     current implementation, half a dozen bytes should suffice for this, but
  421.     for safety's sake we recommend ensuring that at least 100 bytes are free
  422.     before calling jpeg_finish_compress().
  423. Furthermore, since jpeg_finish_compress() cannot suspend, you cannot request
  424. multi-pass operating modes such as Huffman code optimization or multiple-scan
  425. output.  That would imply that a large amount of data would be written inside
  426. jpeg_finish_compress(), which would certainly trigger a buffer overrun.
  427.  
  428. Decompression suspension:
  429.  
  430. For decompression suspension, use a fill_input_buffer() routine that simply
  431. returns FALSE (except perhaps during error recovery, as discussed below).
  432. This will cause the decompressor to return to its caller with an indication
  433. that suspension has occurred.  This can happen at three places:
  434.   * jpeg_read_header(): will return JPEG_SUSPENDED.
  435.   * jpeg_read_scanlines(): will return the number of scanlines already
  436.     completed (possibly 0).
  437.   * jpeg_finish_decompress(): will return FALSE, rather than its usual TRUE.
  438. The surrounding application must recognize these cases, load more data into
  439. the input buffer, and repeat the call.  In the case of jpeg_read_scanlines(),
  440. adjust the passed pointers to reflect any scanlines successfully read.
  441.  
  442. Just as with compression, the decompressor will typically backtrack to a
  443. convenient restart point before suspending.  The data beyond the current
  444. position of next_input_byte/bytes_in_buffer must NOT be discarded; it will
  445. be re-read upon resumption.  In most implementations, you'll need to shift
  446. this data down to the start of your work buffer and then load more data
  447. after it.  Again, this behavior means that a several-Kbyte work buffer is
  448. essential for decent performance; furthermore, you should load a reasonable
  449. amount of new data before resuming decompression.  (If you loaded, say,
  450. only one new byte each time around, you could waste a LOT of cycles.)
  451.  
  452. The skip_input_data() source manager routine requires special care in a
  453. suspension scenario.  This routine is NOT granted the ability to suspend the
  454. decompressor; it can decrement bytes_in_buffer to zero, but no more.  If the
  455. requested skip distance exceeds the amount of data currently in the input
  456. buffer, then skip_input_data() must set bytes_in_buffer to zero and record the
  457. additional skip distance somewhere else.  The decompressor will immediately
  458. call fill_input_buffer(), which will return FALSE, which will cause a
  459. suspension return.  The surrounding application must then arrange to discard
  460. the right number of bytes before it resumes loading the input buffer.  (Yes,
  461. this design is rather baroque, but it avoids complexity in the far more common
  462. case where a non-suspending source manager is used.)
  463.  
  464. If the input data has been exhausted, we recommend that you emit a warning
  465. and insert dummy EOI markers just as a non-suspending data source manager
  466. would do.  This can be handled either in the surrounding application logic or
  467. within fill_input_buffer(); the latter is probably more efficient.  If
  468. fill_input_buffer() knows that no more data is available, it can set the
  469. pointer/count to point to a dummy EOI marker and then return TRUE just as
  470. though it had read more data in a non-suspending situation.
  471.  
  472. The decompressor does not support suspension within jpeg_start_decompress().
  473. This means that you cannot use suspension with any multi-pass processing mode
  474. (eg, two-pass color quantization or multiple-scan JPEG files).  In single-pass
  475. modes, jpeg_start_decompress() reads no data and thus need never suspend.
  476.  
  477. The decompressor does not attempt to suspend within any JPEG marker; it will
  478. backtrack to the start of the marker.  Hence the input buffer must be large
  479. enough to hold the longest marker in the file.  We recommend at least a 2K
  480. buffer.  The buffer would need to be 64K to allow for arbitrary COM or APPn
  481. markers, but the decompressor does not actually try to read these; it just
  482. skips them by calling skip_input_data().  If you provide a special marker
  483. handling routine that does look at such markers, coping with buffer overflow
  484. is your problem.  Ordinary JPEG markers should normally not exceed a few
  485. hundred bytes each (DHT tables are typically the longest).  For robustness
  486. against damaged marker length counts, you may wish to insert a test in your
  487. application for the case that the input buffer is completely full and yet the
  488. decoder has suspended without consuming any data --- otherwise, if this
  489. situation did occur, it would lead to an endless loop.
  490.  
  491.  
  492. Abbreviated datastreams and multiple images
  493. -------------------------------------------
  494.  
  495. A JPEG compression or decompression object can be reused to process multiple
  496. images.  This saves a small amount of time per image by eliminating the
  497. "create" and "destroy" operations, but that isn't the real purpose of the
  498. feature.  Rather, reuse of an object provides support for abbreviated JPEG
  499. datastreams.  Object reuse can also simplify processing a series of images in
  500. a single input or output file.  This section explains these features.
  501.  
  502. A JPEG file normally contains several hundred bytes worth of quantization
  503. and Huffman tables.  In a situation where many images will be stored or
  504. transmitted with identical tables, this may represent an annoying overhead.
  505. The JPEG standard therefore permits tables to be omitted.  The standard
  506. defines three classes of JPEG datastreams:
  507.   * "Interchange" datastreams contain an image and all tables needed to decode
  508.      the image.  These are the usual kind of JPEG file.
  509.   * "Abbreviated image" datastreams contain an image, but are missing some or
  510.     all of the tables needed to decode that image.
  511.   * "Abbreviated table specification" (henceforth "tables-only") datastreams
  512.     contain only table specifications.
  513. To decode an abbreviated image, it is necessary to load the missing table(s)
  514. into the decoder beforehand.  This can be accomplished by reading a separate
  515. tables-only file.  A variant scheme uses a series of images in which the first
  516. image is an interchange (complete) datastream, while subsequent ones are
  517. abbreviated and rely on the tables loaded by the first image.  It is assumed
  518. that once the decoder has read a table, it will remember that table until a
  519. new definition for the same table number is encountered.
  520.  
  521. It is the application designer's responsibility to figure out how to associate
  522. the correct tables with an abbreviated image.  While abbreviated datastreams
  523. can be useful in a closed environment, their use is strongly discouraged in
  524. any situation where data exchange with other applications might be needed.
  525. Caveat designer.
  526.  
  527. The JPEG library provides support for reading and writing any combination of
  528. tables-only datastreams and abbreviated images.  In both compression and
  529. decompression objects, a quantization or Huffman table will be retained for
  530. the lifetime of the object, unless it is overwritten by a new table definition.
  531.  
  532.  
  533. To create abbreviated image datastreams, it is only necessary to tell the
  534. compressor not to emit some or all of the tables it is using.  Each
  535. quantization and Huffman table struct contains a boolean field "sent_table",
  536. which normally is initialized to FALSE.  For each table used by the image, the
  537. header-writing process emits the table and sets sent_table = TRUE unless it is
  538. already TRUE.  (In normal usage, this prevents outputting the same table
  539. definition multiple times, as would otherwise occur because the chroma
  540. components typically share tables.)  Thus, setting this field to TRUE before
  541. calling jpeg_start_compress() will prevent the table from being written at
  542. all.
  543.  
  544. If you want to create a "pure" abbreviated image file containing no tables,
  545. just call "jpeg_suppress_tables(&cinfo, TRUE)" after constructing all the
  546. tables.  If you want to emit some but not all tables, you'll need to set the
  547. individual sent_table fields directly.
  548.  
  549. To create an abbreviated image, you must also call jpeg_start_compress()
  550. with a second parameter of FALSE, not TRUE.  Otherwise jpeg_start_compress()
  551. will force all the sent_table fields to FALSE.  (This is a safety feature to
  552. prevent abbreviated images from being created accidentally.)
  553.  
  554. To create a tables-only file, perform the same parameter setup that you
  555. normally would, but instead of calling jpeg_start_compress() and so on, call
  556. jpeg_write_tables(&cinfo).  This will write an abbreviated datastream
  557. containing only SOI, DQT and/or DHT markers, and EOI.  All the quantization
  558. and Huffman tables that are currently defined in the compression object will
  559. be emitted unless their sent_tables flag is already TRUE, and then all the
  560. sent_tables flags will be set TRUE.
  561.  
  562. A sure-fire way to create matching tables-only and abbreviated image files
  563. is to proceed as follows:
  564.  
  565.     create JPEG compression object
  566.     set JPEG parameters
  567.     set destination to tables-only file
  568.     jpeg_write_tables(&cinfo);
  569.     set destination to image file
  570.     jpeg_start_compress(&cinfo, FALSE);
  571.     write data...
  572.     jpeg_finish_compress(&cinfo);
  573.  
  574. Since the JPEG parameters are not altered between writing the table file and
  575. the abbreviated image file, the same tables are sure to be used.  Of course,
  576. you can repeat the jpeg_start_compress() ... jpeg_finish_compress() sequence
  577. many times to produce many abbreviated image files matching the table file.
  578.  
  579. You cannot suppress output of the computed Huffman tables when Huffman
  580. optimization is selected.  (If you could, there'd be no way to decode the
  581. image...)  Generally, you don't want to set optimize_coding = TRUE when
  582. you are trying to produce abbreviated files.
  583.  
  584. In some cases you might want to compress an image using tables which are
  585. not stored in the application, but are defined in an interchange or
  586. tables-only file readable by the application.  This can be done by setting up
  587. a JPEG decompression object to read the specification file, then copying the
  588. tables into your compression object.
  589.  
  590.  
  591. To read abbreviated image files, you simply need to load the proper tables
  592. into the decompression object before trying to read the abbreviated image.
  593. If the proper tables are stored in the application program, you can just
  594. allocate the table structs and fill in their contents directly.  More commonly
  595. you'd want to read the tables from a tables-only file.  The jpeg_read_header()
  596. call is sufficient to read a tables-only file.  You must pass a second
  597. parameter of FALSE to indicate that you do not require an image to be present.
  598. Thus, the typical scenario is
  599.  
  600.     create JPEG decompression object
  601.     set source to tables-only file
  602.     jpeg_read_header(&cinfo, FALSE);
  603.     set source to abbreviated image file
  604.     jpeg_read_header(&cinfo, TRUE);
  605.     set decompression parameters
  606.     jpeg_start_decompress(&cinfo);
  607.     read data...
  608.     jpeg_finish_decompress(&cinfo);
  609.  
  610. In some cases, you may want to read a file without knowing whether it contains
  611. an image or just tables.  In that case, pass FALSE and check the return value
  612. from jpeg_read_header(): it will be JPEG_HEADER_OK if an image was found,
  613. JPEG_HEADER_TABLES_ONLY if only tables were found.  (A third return value,
  614. JPEG_SUSPENDED, is possible when using a suspending data source manager.)
  615. Note that jpeg_read_header() will not complain if you read an abbreviated
  616. image for which you haven't loaded the missing tables; the missing-table check
  617. occurs in jpeg_start_decompress().
  618.  
  619.  
  620. It is possible to read a series of images from a single source file by
  621. repeating the jpeg_read_header() ... jpeg_finish_decompress() sequence,
  622. without releasing/recreating the JPEG object or the data source module.
  623. (If you did reinitialize, any partial bufferload left in the data source
  624. buffer at the end of one image would be discarded, causing you to lose the
  625. start of the next image.)  When you use this method, stored tables are
  626. automatically carried forward, so some of the images can be abbreviated images
  627. that depend on tables from earlier images.
  628.  
  629. If you intend to write a series of images into a single destination file,
  630. you might want to make a specialized data destination module that doesn't
  631. flush the output buffer at term_destination() time.  This would speed things
  632. up by some trifling amount.  Of course, you'd need to remember to flush the
  633. buffer after the last image.  You can make the later images be abbreviated
  634. ones by passing FALSE to jpeg_start_compress().
  635.  
  636.  
  637. Special markers
  638. ---------------
  639.  
  640. Some applications may need to insert or extract special data in the JPEG
  641. datastream.  The JPEG standard provides marker types "COM" (comment) and
  642. "APP0" through "APP15" (application) to hold application-specific data.
  643. Unfortunately, the use of these markers is not specified by the standard.
  644. COM markers are fairly widely used to hold user-supplied text.  The JFIF file
  645. format spec uses APP0 markers with specified initial strings to hold certain
  646. data.  Adobe applications use APP14 markers beginning with the string "Adobe"
  647. for miscellaneous data.  Other APPn markers are rarely seen, but might
  648. contain almost anything.
  649.  
  650. If you wish to store user-supplied text, we recommend you use COM markers
  651. and place readable 7-bit ASCII text in them.  Newline conventions are not
  652. standardized --- expect to find LF (Unix style), CR/LF (DOS style), or CR
  653. (Mac style).  A robust COM reader should be able to cope with random binary
  654. garbage, including nulls, since some applications generate COM markers
  655. containing non-ASCII junk.  (But yours should not be one of them.)
  656.  
  657. For program-supplied data, use an APPn marker, and be sure to begin it with an
  658. identifying string so that you can tell whether the marker is actually yours.
  659. It's probably best to avoid using APP0 or APP14 for any private markers.
  660.  
  661. Keep in mind that at most 65533 bytes can be put into one marker, but you
  662. can have as many markers as you like.
  663.  
  664. By default, the JPEG compression library will write a JFIF APP0 marker if the
  665. selected JPEG colorspace is grayscale or YCbCr, or an Adobe APP14 marker if
  666. the selected colorspace is RGB, CMYK, or YCCK.  You can disable this, but
  667. we don't recommend it.  The decompression library will recognize JFIF and
  668. Adobe markers and will set the JPEG colorspace properly when one is found.
  669.  
  670. You can write special markers immediately following the datastream header by
  671. calling jpeg_write_marker() after jpeg_start_compress() and before the first
  672. call to jpeg_write_scanlines().  When you do this, the markers appear after
  673. the SOI and the JFIF APP0 and Adobe APP14 markers (if written), but before
  674. all else.  Write the marker type parameter as "JPEG_COM" for COM or
  675. "JPEG_APP0 + n" for APPn.  (Actually, jpeg_write_marker will let you write
  676. any marker type, but we don't recommend writing any other kinds of marker.)
  677. For example, to write a user comment string pointed to by comment_text:
  678.     jpeg_write_marker(cinfo, JPEG_COM, comment_text, strlen(comment_text));
  679. Or if you prefer to synthesize the marker byte sequence yourself, you can
  680. just cram it straight into the data destination module.
  681.  
  682. For decompression, you can supply your own routine to process COM or APPn
  683. markers by calling jpeg_set_marker_processor().  Usually you'd call this
  684. after creating a decompression object and before calling jpeg_read_header(),
  685. because the markers of interest will normally be scanned by jpeg_read_header.
  686. Once you've supplied a routine, it will be used for the life of that
  687. decompression object.  A separate routine may be registered for COM and for
  688. each APPn marker code.
  689.  
  690. A marker processor routine must have the signature
  691.     boolean jpeg_marker_parser_method (j_decompress_ptr cinfo)
  692. Although the marker code is not explicitly passed, the routine can find it
  693. in cinfo->unread_marker.  At the time of call, the marker proper has been
  694. read from the data source module.  The processor routine is responsible for
  695. reading the marker length word and the remaining parameter bytes, if any.
  696. Return TRUE to indicate success.  (FALSE should be returned only if you are
  697. using a suspending data source and it tells you to suspend.  See the standard
  698. marker processors in jdmarker.c for appropriate coding methods if you need to
  699. use a suspending data source.)
  700.  
  701. If you override the default APP0 or APP14 processors, it is up to you to
  702. recognize JFIF and Adobe markers if you want colorspace recognition to occur
  703. properly.  We recommend copying and extending the default processors if you
  704. want to do that.
  705.  
  706. A simple example of an external COM processor can be found in djpeg.c.
  707.  
  708.  
  709. Raw (downsampled) image data
  710. ----------------------------
  711.  
  712. Some applications need to supply already-downsampled image data to the JPEG
  713. compressor, or to receive raw downsampled data from the decompressor.  The
  714. library supports this requirement by allowing the application to write or
  715. read raw data, bypassing the normal preprocessing or postprocessing steps.
  716. The interface is different from the standard one and is somewhat harder to
  717. use.  If your interest is merely in bypassing color conversion, we recommend
  718. that you use the standard interface and simply set jpeg_color_space =
  719. in_color_space (or jpeg_color_space = out_color_space for decompression).
  720. The mechanism described in this section is necessary only to supply or
  721. receive downsampled image data, in which not all components have the same
  722. dimensions.
  723.  
  724.  
  725. To compress raw data, you must supply the data in the colorspace to be used
  726. in the JPEG file (please read the earlier section on Special color spaces)
  727. and downsampled to the sampling factors specified in the JPEG parameters.
  728. You must supply the data in the format used internally by the JPEG library,
  729. namely a JSAMPIMAGE array.  This is an array of pointers to two-dimensional
  730. arrays, each of type JSAMPARRAY.  Each 2-D array holds the values for one
  731. color component.  This structure is necessary since the components are of
  732. different sizes.  If the image dimensions are not a multiple of the MCU size,
  733. you must also pad the data correctly (usually, this is done by replicating
  734. the last column and/or row).  The data must be padded to a multiple of a DCT
  735. block in each component: that is, each downsampled row must contain a
  736. multiple of 8 valid samples, and there must be a multiple of 8 sample rows
  737. for each component.  (For applications such as conversion of digital TV
  738. images, the standard image size is usually a multiple of the DCT block size,
  739. so that no padding need actually be done.)
  740.  
  741. The procedure for compression of raw data is basically the same as normal
  742. compression, except that you call jpeg_write_raw_data() in place of
  743. jpeg_write_scanlines().  Before calling jpeg_start_compress(), you must do
  744. the following:
  745.   * Set cinfo->raw_data_in to TRUE.  (It is set FALSE by jpeg_set_defaults().)
  746.     This notifies the library that you will be supplying raw data.
  747.   * Ensure jpeg_color_space is correct --- an explicit jpeg_set_colorspace()
  748.     call is a good idea.  Note that since color conversion is bypassed,
  749.     in_color_space is ignored, except that jpeg_set_defaults() uses it to
  750.     choose the default jpeg_color_space setting.
  751.   * Ensure the sampling factors, cinfo->comp_info[i].h_samp_factor and
  752.     cinfo->comp_info[i].v_samp_factor, are correct.  Since these indicate the
  753.     dimensions of the data you are supplying, it's wise to set them
  754.     explicitly, rather than assuming the library's defaults are what you want.
  755.  
  756. To pass raw data to the library, call jpeg_write_raw_data() in place of
  757. jpeg_write_scanlines().  The two routines work similarly except that
  758. jpeg_write_raw_data takes a JSAMPIMAGE data array rather than JSAMPARRAY.
  759. The scanlines count passed to and returned from jpeg_write_raw_data is
  760. measured in terms of the component with the largest v_samp_factor.
  761.  
  762. jpeg_write_raw_data() processes one MCU row per call, which is to say
  763. v_samp_factor*DCTSIZE sample rows of each component.  The passed num_lines
  764. value must be at least max_v_samp_factor*DCTSIZE, and the return value will
  765. be exactly that amount (or possibly some multiple of that amount, in future
  766. library versions).  This is true even on the last call at the bottom of the
  767. image; don't forget to pad your data as necessary.
  768.  
  769. The required dimensions of the supplied data can be computed for each
  770. component as
  771.     cinfo->comp_info[i].width_in_blocks*DCTSIZE  samples per row
  772.     cinfo->comp_info[i].height_in_blocks*DCTSIZE rows in image
  773. after jpeg_start_compress() has initialized those fields.  If the valid data
  774. is smaller than this, it must be padded appropriately.  For some sampling
  775. factors and image sizes, additional dummy DCT blocks are inserted to make
  776. the image a multiple of the MCU dimensions.  The library creates such dummy
  777. blocks itself; it does not read them from your supplied data.  Therefore you
  778. need never pad by more than DCTSIZE samples.  An example may help here.
  779. Assume 2h2v downsampling of YCbCr data, that is
  780.     cinfo->comp_info[0].h_samp_factor = 2        for Y
  781.     cinfo->comp_info[0].v_samp_factor = 2
  782.     cinfo->comp_info[1].h_samp_factor = 1        for Cb
  783.     cinfo->comp_info[1].v_samp_factor = 1
  784.     cinfo->comp_info[2].h_samp_factor = 1        for Cr
  785.     cinfo->comp_info[2].v_samp_factor = 1
  786. and suppose that the nominal image dimensions (cinfo->image_width and
  787. cinfo->image_height) are 101x101 pixels.  Then jpeg_start_compress() will
  788. compute downsampled_width = 101 and width_in_blocks = 13 for Y,
  789. downsampled_width = 51 and width_in_blocks = 7 for Cb and Cr (and the same
  790. for the height fields).  You must pad the Y data to at least 13*8 = 104
  791. columns and rows, the Cb/Cr data to at least 7*8 = 56 columns and rows.  The
  792. MCU height is max_v_samp_factor = 2 DCT rows so you must pass at least 16
  793. scanlines on each call to jpeg_write_raw_data(), which is to say 16 actual
  794. sample rows of Y and 8 each of Cb and Cr.  A total of 7 MCU rows are needed,
  795. so you must pass a total of 7*16 = 112 "scanlines".  The last DCT block row
  796. of Y data is dummy, so it doesn't matter what you pass for it in the data
  797. arrays, but the scanlines count must total up to 112 so that all of the Cb
  798. and Cr data gets passed.
  799.  
  800. Currently, output suspension is not supported with raw data output: an error
  801. will result if the data destination module tries to suspend.
  802.  
  803.  
  804. Decompression with raw data output implies bypassing all postprocessing:
  805. you cannot ask for color quantization, for instance.  More seriously, you must
  806. deal with the color space and sampling factors present in the incoming file.
  807. If your application only handles, say, 2h1v YCbCr data, you must check for
  808. and fail on other color spaces or other sampling factors.
  809.  
  810. To obtain raw data output, set cinfo->raw_data_out = TRUE before
  811. jpeg_start_decompress() (it is set FALSE by jpeg_read_header()).  Be sure to
  812. verify that the color space and sampling factors are ones you can handle.
  813. Then call jpeg_read_raw_data() in place of jpeg_read_scanlines().  The
  814. decompression process is otherwise the same as usual.
  815.  
  816. jpeg_read_raw_data() returns one MCU row per call, and thus you must pass a
  817. buffer of at least max_v_samp_factor*DCTSIZE scanlines (scanline counting is
  818. the same as for raw-data compression).  The buffer you pass must be large
  819. enough to hold the actual data plus padding to DCT-block boundaries.  As with
  820. compression, any entirely dummy DCT blocks are not processed so you need not
  821. allocate space for them, but the total scanline count includes them.  The
  822. above example of computing buffer dimensions for raw-data compression is
  823. equally valid for decompression.
  824.  
  825. Input suspension is supported with raw-data decompression: if the data source
  826. module suspends, jpeg_read_raw_data() will return 0.
  827.  
  828.  
  829. Progress monitoring
  830. -------------------
  831.  
  832. Some applications may need to regain control from the JPEG library every so
  833. often.  The typical use of this feature is to produce a percent-done bar or
  834. other progress display.  (For a simple example, see cjpeg.c or djpeg.c.)
  835. Although you do get control back frequently during the data-transferring pass
  836. (the jpeg_read_scanlines or jpeg_write_scanlines loop), any additional passes
  837. will occur inside jpeg_finish_compress or jpeg_start_decompress; those
  838. routines may take a long time to execute, and you don't get control back
  839. until they are done.
  840.  
  841. You can define a progress-monitor routine which will be called periodically
  842. by the library.  No guarantees are made about how often this call will occur,
  843. so we don't recommend you use it for mouse tracking or anything like that.
  844. At present, a call will occur once per MCU row, scanline, or sample row
  845. group, whichever unit is convenient for the current processing mode; so the
  846. wider the image, the longer the time between calls.  (During the data
  847. transferring pass, only one call occurs per call of jpeg_read_scanlines or
  848. jpeg_write_scanlines, so don't pass a large number of scanlines at once if
  849. you want fine resolution in the progress count.)
  850.  
  851. To establish a progress-monitor callback, create a struct jpeg_progress_mgr,
  852. fill in its progress_monitor field with a pointer to your callback routine,
  853. and set cinfo->progress to point to the struct.  The callback will be called
  854. whenever cinfo->progress is non-NULL.  (This pointer is set to NULL by
  855. jpeg_create_compress or jpeg_create_decompress; the library will not change
  856. it thereafter.  So if you allocate dynamic storage for the progress struct,
  857. make sure it will live as long as the JPEG object does.  Allocating from the
  858. JPEG memory manager with lifetime JPOOL_PERMANENT will work nicely.)  You
  859. can use the same callback routine for both compression and decompression.
  860.  
  861. The jpeg_progress_mgr struct contains four fields which are set by the library:
  862.     long pass_counter;    /* work units completed in this pass */
  863.     long pass_limit;    /* total number of work units in this pass */
  864.     int completed_passes;    /* passes completed so far */
  865.     int total_passes;    /* total number of passes expected */
  866. During any one pass, pass_counter increases from 0 up to (not including)
  867. pass_limit; the step size is not necessarily 1.  Both the step size and the
  868. limit may differ from one pass to another.  The expected total number of
  869. passes is in total_passes, and the number of passes already completed is in
  870. completed_passes.  Thus the fraction of work completed may be estimated as
  871.         completed_passes + (pass_counter/pass_limit)
  872.         --------------------------------------------
  873.                 total_passes
  874. ignoring the fact that the passes may not be equal amounts of work.
  875.  
  876. When decompressing, the total_passes value is not trustworthy, because it
  877. depends on the number of scans in the JPEG file, which isn't always known in
  878. advance.  In the current implementation, completed_passes may jump by more
  879. than one when dealing with a multiple-scan input file.  About all that is
  880. really safe to assume is that when completed_passes = total_passes - 1, the
  881. current pass will be the last one.
  882.  
  883. If you really need to use the callback mechanism for time-critical tasks
  884. like mouse tracking, you could insert additional calls inside some of the
  885. library's inner loops.
  886.  
  887.  
  888. Memory management
  889. -----------------
  890.  
  891. This section covers some key facts about the JPEG library's built-in memory
  892. manager.  For more info, please read structure.doc's section about the memory
  893. manager, and consult the source code if necessary.
  894.  
  895. All memory and temporary file allocation within the library is done via the
  896. memory manager.  If necessary, you can replace the "back end" of the memory
  897. manager to control allocation yourself (for example, if you don't want the
  898. library to use malloc() and free() for some reason).
  899.  
  900. Some data is allocated "permanently" and will not be freed until the JPEG
  901. object is destroyed.  Most data is allocated "per image" and is freed by
  902. jpeg_finish_compress, jpeg_finish_decompress, or jpeg_abort.  You can call the
  903. memory manager yourself to allocate structures that will automatically be
  904. freed at these times.  Typical code for this is
  905.   ptr = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, size);
  906. Use JPOOL_PERMANENT to get storage that lasts as long as the JPEG object.
  907. Use alloc_large instead of alloc_small for anything bigger than a few Kbytes.
  908. There are also alloc_sarray and alloc_barray routines that automatically
  909. build 2-D sample or block arrays.
  910.  
  911. The library's minimum space requirements to process an image depend on the
  912. image's width, but not on its height, because the library ordinarily works
  913. with "strip" buffers that are as wide as the image but just a few rows high.
  914. Some operating modes (eg, two-pass color quantization) require full-image
  915. buffers.  Such buffers are treated as "virtual arrays": only the current strip
  916. need be in memory, and the rest can be swapped out to a temporary file.
  917.  
  918. If you use the simplest memory manager back end (jmemnobs.c), then no
  919. temporary files are used; virtual arrays are simply malloc()'d.  Images bigger
  920. than memory can be processed only if your system supports virtual memory.
  921. The other memory manager back ends support temporary files of various flavors
  922. and thus work in machines without virtual memory.  They may also be useful on
  923. Unix machines if you need to process images that exceed available swap space.
  924.  
  925. When using temporary files, the library will make the in-memory buffers for
  926. its virtual arrays just big enough to stay within a "maximum memory" setting.
  927. Your application can set this limit by setting cinfo->mem->max_memory_to_use
  928. after creating the JPEG object.  (Of course, there is still a minimum size for
  929. the buffers, so the max-memory setting is effective only if it is bigger than
  930. the minimum space needed.)  If you allocate any large structures yourself, you
  931. must allocate them before jpeg_start_compress() or jpeg_start_decompress() in
  932. order to have them counted against the max memory limit.  Also keep in mind
  933. that space allocated with alloc_small() is ignored, on the assumption that
  934. it's too small to be worth worrying about.
  935.  
  936. If you use the jmemname.c or jmemdos.c memory manager back end, it is
  937. important to clean up the JPEG object properly to ensure that the temporary
  938. files get deleted.  (This is especially crucial with jmemdos.c, where the
  939. "temporary files" may be extended-memory segments; if they are not freed,
  940. DOS will require a reboot to recover the memory.)  Thus, with these memory
  941. managers, it's a good idea to provide a signal handler that will trap any
  942. early exit from your program.  The handler should call either jpeg_abort()
  943. or jpeg_destroy() for any active JPEG objects.  A handler is not needed with
  944. jmemnobs.c, and shouldn't be necessary with jmemansi.c either, since the C
  945. library is supposed to take care of deleting files made with tmpfile().
  946.  
  947.  
  948. Library compile-time options
  949. ----------------------------
  950.  
  951. A number of compile-time options are available by modifying jmorecfg.h.
  952.  
  953. The JPEG standard provides for both the baseline 8-bit DCT process and
  954. a 12-bit DCT process.  12-bit lossy JPEG is supported if you define
  955. BITS_IN_JSAMPLE as 12 rather than 8.  Note that this causes JSAMPLE to be
  956. larger than a char, so it affects the surrounding application's image data.
  957. At present, a 12-bit library can handle *only* 12-bit images, not both
  958. precisions.  (If you need to include both 8- and 12-bit libraries in a
  959. single application, you could probably do it by defining
  960. NEED_SHORT_EXTERNAL_NAMES for just one of the copies.  You'd have to access
  961. the 8-bit and 12-bit copies from separate application source files.  This is
  962. untested ... if you try it, we'd like to hear whether it works!)
  963.  
  964. The maximum number of components (color channels) in the image is determined
  965. by MAX_COMPONENTS.  The JPEG standard allows up to 255 components, but we
  966. expect that few applications will need more than four or so.
  967.  
  968. On machines with unusual data type sizes, you may be able to improve
  969. performance or reduce memory space by tweaking the various typedefs in
  970. jmorecfg.h.  In particular, on some RISC CPUs, access to arrays of "short"s
  971. is quite slow; consider trading memory for speed by making JCOEF, INT16, and
  972. UINT16 be "int" or "unsigned int".  UINT8 is also a candidate to become int.
  973. You probably don't want to make JSAMPLE be int unless you have lots of memory
  974. to burn.
  975.  
  976. You can reduce the size of the library by compiling out various optional
  977. functions.  To do this, undefine xxx_SUPPORTED symbols as necessary.
  978.  
  979.  
  980. Portability considerations
  981. --------------------------
  982.  
  983. The JPEG library has been written to be extremely portable; the sample
  984. applications cjpeg and djpeg are slightly less so.  This section summarizes
  985. the design goals in this area.  (If you encounter any bugs that cause the
  986. library to be less portable than is claimed here, we'd appreciate hearing
  987. about them.)
  988.  
  989. The code works fine on both ANSI and pre-ANSI C compilers, using any of the
  990. popular system include file setups, and some not-so-popular ones too.  See
  991. install.doc for configuration procedures.
  992.  
  993. The code is not dependent on the exact sizes of the C data types.  As
  994. distributed, we make the assumptions that
  995.     char    is at least 8 bits wide
  996.     short    is at least 16 bits wide
  997.     int    is at least 16 bits wide
  998.     long    is at least 32 bits wide
  999. (These are the minimum requirements of the ANSI C standard.)  Wider types will
  1000. work fine, although memory may be used inefficiently if char is much larger
  1001. than 8 bits or short is much bigger than 16 bits.  The code should work
  1002. equally well with 16- or 32-bit ints.
  1003.  
  1004. In a system where these assumptions are not met, you may be able to make the
  1005. code work by modifying the typedefs in jmorecfg.h.  However, you will probably
  1006. have difficulty if int is less than 16 bits wide, since references to plain
  1007. int abound in the code.
  1008.  
  1009. char can be either signed or unsigned, although the code runs faster if an
  1010. unsigned char type is available.  If char is wider than 8 bits, you will need
  1011. to redefine JOCTET and/or provide custom data source/destination managers so
  1012. that JOCTET represents exactly 8 bits of data on external storage.
  1013.  
  1014. The JPEG library proper does not assume ASCII representation of characters.
  1015. But some of the image file I/O modules in cjpeg/djpeg do have ASCII
  1016. dependencies in file-header manipulation; so does cjpeg's select_file_type()
  1017. routine.
  1018.  
  1019. The JPEG library does not rely heavily on the C library.  In particular, C
  1020. stdio is used only by the data source/destination modules and the error
  1021. handler, all of which are application-replaceable.  (cjpeg/djpeg are more
  1022. heavily dependent on stdio.)  malloc and free are called only from the memory
  1023. manager "back end" module, so you can use a different memory allocator by
  1024. replacing that one file.
  1025.  
  1026. The code generally assumes that C names must be unique in the first 15
  1027. characters.  However, global function names can be made unique in the
  1028. first 6 characters by defining NEED_SHORT_EXTERNAL_NAMES.
  1029.  
  1030. More info about porting the code may be gleaned by reading jconfig.doc,
  1031. jmorecfg.h, and jinclude.h.
  1032.  
  1033.  
  1034. Notes for MS-DOS implementors
  1035. -----------------------------
  1036.  
  1037. The IJG code is designed to work efficiently in 80x86 "small" or "medium"
  1038. memory models (i.e., data pointers are 16 bits unless explicitly declared
  1039. "far"; code pointers can be either size).  You may be able to use small
  1040. model to compile cjpeg or djpeg by itself, but you will probably have to use
  1041. medium model for any larger application.  This won't make much difference in
  1042. performance.  You *will* take a noticeable performance hit if you use a
  1043. large-data memory model (perhaps 10%-25%), and you should avoid "huge" model
  1044. if at all possible.
  1045.  
  1046. The JPEG library typically needs 2Kb-3Kb of stack space.  It will also
  1047. malloc about 20K-30K of near heap space while executing (and lots of far
  1048. heap, but that doesn't count in this calculation).  This figure will vary
  1049. depending on selected operating mode, and to a lesser extent on image size.
  1050. Thus you have perhaps 25K available for static data and other modules' near
  1051. heap space before you need to go to a larger memory model.  The C library's
  1052. static data will account for several K of this, but that still leaves a good
  1053. deal for your needs.  (If you are tight on space, you could reduce the sizes
  1054. of the I/O buffers allocated by jdatasrc.c and jdatadst.c, say from 4K to
  1055. 1K.)
  1056.  
  1057. About 2K of the near heap space is "permanent" memory that will not be
  1058. released until you destroy the JPEG object.  This is only an issue if you
  1059. save a JPEG object between compression or decompression operations.
  1060.  
  1061. Far data space may also be a tight resource when you are dealing with large
  1062. images.  The most memory-intensive case is decompression with two-pass color
  1063. quantization, or single-pass quantization to an externally supplied color
  1064. map.  This requires a 128Kb color lookup table plus strip buffers amounting
  1065. to about 50 bytes per column for typical sampling ratios (eg, about 32000
  1066. bytes for a 640-pixel-wide image).  You may not be able to process wide
  1067. images if you have large data structures of your own.
  1068.  
  1069. Of course, all of these concerns vanish if you use a 32-bit flat-memory-model
  1070. compiler, such as DJGPP or Watcom C.  We highly recommend flat model if you
  1071. can use it; the JPEG library is significantly faster in flat model.
  1072.