libjpeg.doc
Upload User: zlh9724
Upload Date: 2007-01-04
Package Size: 1991k
Code Size: 141k
Category:

Browser Client

Development Platform:

Unix_Linux

  1. free_in_buffer must be set to a positive value when TRUE is
  2. returned.  A FALSE return should only be used when I/O suspension is
  3. desired (this operating mode is discussed in the next section).
  4. term_destination (j_compress_ptr cinfo)
  5. Terminate destination --- called by jpeg_finish_compress() after all
  6. data has been written.  In most applications, this must flush any
  7. data remaining in the buffer.  Use either next_output_byte or
  8. free_in_buffer to determine how much data is in the buffer.
  9. term_destination() is NOT called by jpeg_abort() or jpeg_destroy().  If you
  10. want the destination manager to be cleaned up during an abort, you must do it
  11. yourself.
  12. You will also need code to create a jpeg_destination_mgr struct, fill in its
  13. method pointers, and insert a pointer to the struct into the "dest" field of
  14. the JPEG compression object.  This can be done in-line in your setup code if
  15. you like, but it's probably cleaner to provide a separate routine similar to
  16. the jpeg_stdio_dest() routine of the supplied destination manager.
  17. Decompression source managers follow a parallel design, but with some
  18. additional frammishes.  The source manager struct contains a pointer and count
  19. defining the next byte to read from the work buffer and the number of bytes
  20. remaining:
  21. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  22. size_t bytes_in_buffer;         /* # of bytes remaining in buffer */
  23. The library increments the pointer and decrements the count until the buffer
  24. is emptied.  The manager's fill_input_buffer method must reset the pointer and
  25. count.  In most applications, the manager must remember the buffer's starting
  26. address and total size in private fields not visible to the library.
  27. A data source manager provides five methods:
  28. init_source (j_decompress_ptr cinfo)
  29. Initialize source.  This is called by jpeg_read_header() before any
  30. data is actually read.  Unlike init_destination(), it may leave
  31. bytes_in_buffer set to 0 (in which case a fill_input_buffer() call
  32. will occur immediately).
  33. fill_input_buffer (j_decompress_ptr cinfo)
  34. This is called whenever bytes_in_buffer has reached zero and more
  35. data is wanted.  In typical applications, it should read fresh data
  36. into the buffer (ignoring the current state of next_input_byte and
  37. bytes_in_buffer), reset the pointer & count to the start of the
  38. buffer, and return TRUE indicating that the buffer has been reloaded.
  39. It is not necessary to fill the buffer entirely, only to obtain at
  40. least one more byte.  bytes_in_buffer MUST be set to a positive value
  41. if TRUE is returned.  A FALSE return should only be used when I/O
  42. suspension is desired (this mode is discussed in the next section).
  43. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  44. Skip num_bytes worth of data.  The buffer pointer and count should
  45. be advanced over num_bytes input bytes, refilling the buffer as
  46. needed.  This is used to skip over a potentially large amount of
  47. uninteresting data (such as an APPn marker).  In some applications
  48. it may be possible to optimize away the reading of the skipped data,
  49. but it's not clear that being smart is worth much trouble; large
  50. skips are uncommon.  bytes_in_buffer may be zero on return.
  51. A zero or negative skip count should be treated as a no-op.
  52. resync_to_restart (j_decompress_ptr cinfo, int desired)
  53. This routine is called only when the decompressor has failed to find
  54. a restart (RSTn) marker where one is expected.  Its mission is to
  55. find a suitable point for resuming decompression.  For most
  56. applications, we recommend that you just use the default resync
  57. procedure, jpeg_resync_to_restart().  However, if you are able to back
  58. up in the input data stream, or if you have a-priori knowledge about
  59. the likely location of restart markers, you may be able to do better.
  60. Read the read_restart_marker() and jpeg_resync_to_restart() routines
  61. in jdmarker.c if you think you'd like to implement your own resync
  62. procedure.
  63. term_source (j_decompress_ptr cinfo)
  64. Terminate source --- called by jpeg_finish_decompress() after all
  65. data has been read.  Often a no-op.
  66. For both fill_input_buffer() and skip_input_data(), there is no such thing
  67. as an EOF return.  If the end of the file has been reached, the routine has
  68. a choice of exiting via ERREXIT() or inserting fake data into the buffer.
  69. In most cases, generating a warning message and inserting a fake EOI marker
  70. is the best course of action --- this will allow the decompressor to output
  71. however much of the image is there.  In pathological cases, the decompressor
  72. may swallow the EOI and again demand data ... just keep feeding it fake EOIs.
  73. jdatasrc.c illustrates the recommended error recovery behavior.
  74. term_source() is NOT called by jpeg_abort() or jpeg_destroy().  If you want
  75. the source manager to be cleaned up during an abort, you must do it yourself.
  76. You will also need code to create a jpeg_source_mgr struct, fill in its method
  77. pointers, and insert a pointer to the struct into the "src" field of the JPEG
  78. decompression object.  This can be done in-line in your setup code if you
  79. like, but it's probably cleaner to provide a separate routine similar to the
  80. jpeg_stdio_src() routine of the supplied source manager.
  81. For more information, consult the stdio source and destination managers
  82. in jdatasrc.c and jdatadst.c.
  83. I/O suspension
  84. --------------
  85. Some applications need to use the JPEG library as an incremental memory-to-
  86. memory filter: when the compressed data buffer is filled or emptied, they want
  87. control to return to the outer loop, rather than expecting that the buffer can
  88. be emptied or reloaded within the data source/destination manager subroutine.
  89. The library supports this need by providing an "I/O suspension" mode, which we
  90. describe in this section.
  91. The I/O suspension mode is not a panacea: nothing is guaranteed about the
  92. maximum amount of time spent in any one call to the library, so it will not
  93. eliminate response-time problems in single-threaded applications.  If you
  94. need guaranteed response time, we suggest you "bite the bullet" and implement
  95. a real multi-tasking capability.
  96. To use I/O suspension, cooperation is needed between the calling application
  97. and the data source or destination manager; you will always need a custom
  98. source/destination manager.  (Please read the previous section if you haven't
  99. already.)  The basic idea is that the empty_output_buffer() or
  100. fill_input_buffer() routine is a no-op, merely returning FALSE to indicate
  101. that it has done nothing.  Upon seeing this, the JPEG library suspends
  102. operation and returns to its caller.  The surrounding application is
  103. responsible for emptying or refilling the work buffer before calling the
  104. JPEG library again.
  105. Compression suspension:
  106. For compression suspension, use an empty_output_buffer() routine that returns
  107. FALSE; typically it will not do anything else.  This will cause the
  108. compressor to return to the caller of jpeg_write_scanlines(), with the return
  109. value indicating that not all the supplied scanlines have been accepted.
  110. The application must make more room in the output buffer, adjust the output
  111. buffer pointer/count appropriately, and then call jpeg_write_scanlines()
  112. again, pointing to the first unconsumed scanline.
  113. When forced to suspend, the compressor will backtrack to a convenient stopping
  114. point (usually the start of the current MCU); it will regenerate some output
  115. data when restarted.  Therefore, although empty_output_buffer() is only
  116. called when the buffer is filled, you should NOT write out the entire buffer
  117. after a suspension.  Write only the data up to the current position of
  118. next_output_byte/free_in_buffer.  The data beyond that point will be
  119. regenerated after resumption.
  120. Because of the backtracking behavior, a good-size output buffer is essential
  121. for efficiency; you don't want the compressor to suspend often.  (In fact, an
  122. overly small buffer could lead to infinite looping, if a single MCU required
  123. more data than would fit in the buffer.)  We recommend a buffer of at least
  124. several Kbytes.  You may want to insert explicit code to ensure that you don't
  125. call jpeg_write_scanlines() unless there is a reasonable amount of space in
  126. the output buffer; in other words, flush the buffer before trying to compress
  127. more data.
  128. The compressor does not allow suspension while it is trying to write JPEG
  129. markers at the beginning and end of the file.  This means that:
  130.   * At the beginning of a compression operation, there must be enough free
  131.     space in the output buffer to hold the header markers (typically 600 or
  132.     so bytes).  The recommended buffer size is bigger than this anyway, so
  133.     this is not a problem as long as you start with an empty buffer.  However,
  134.     this restriction might catch you if you insert large special markers, such
  135.     as a JFIF thumbnail image, without flushing the buffer afterwards.
  136.   * When you call jpeg_finish_compress(), there must be enough space in the
  137.     output buffer to emit any buffered data and the final EOI marker.  In the
  138.     current implementation, half a dozen bytes should suffice for this, but
  139.     for safety's sake we recommend ensuring that at least 100 bytes are free
  140.     before calling jpeg_finish_compress().
  141. A more significant restriction is that jpeg_finish_compress() cannot suspend.
  142. This means you cannot use suspension with multi-pass operating modes, namely
  143. Huffman code optimization and multiple-scan output.  Those modes write the
  144. whole file during jpeg_finish_compress(), which will certainly result in
  145. buffer overrun.  (Note that this restriction applies only to compression,
  146. not decompression.  The decompressor supports input suspension in all of its
  147. operating modes.)
  148. Decompression suspension:
  149. For decompression suspension, use a fill_input_buffer() routine that simply
  150. returns FALSE (except perhaps during error recovery, as discussed below).
  151. This will cause the decompressor to return to its caller with an indication
  152. that suspension has occurred.  This can happen at four places:
  153.   * jpeg_read_header(): will return JPEG_SUSPENDED.
  154.   * jpeg_start_decompress(): will return FALSE, rather than its usual TRUE.
  155.   * jpeg_read_scanlines(): will return the number of scanlines already
  156. completed (possibly 0).
  157.   * jpeg_finish_decompress(): will return FALSE, rather than its usual TRUE.
  158. The surrounding application must recognize these cases, load more data into
  159. the input buffer, and repeat the call.  In the case of jpeg_read_scanlines(),
  160. increment the passed pointers past any scanlines successfully read.
  161. Just as with compression, the decompressor will typically backtrack to a
  162. convenient restart point before suspending.  When fill_input_buffer() is
  163. called, next_input_byte/bytes_in_buffer point to the current restart point,
  164. which is where the decompressor will backtrack to if FALSE is returned.
  165. The data beyond that position must NOT be discarded if you suspend; it needs
  166. to be re-read upon resumption.  In most implementations, you'll need to shift
  167. this data down to the start of your work buffer and then load more data after
  168. it.  Again, this behavior means that a several-Kbyte work buffer is essential
  169. for decent performance; furthermore, you should load a reasonable amount of
  170. new data before resuming decompression.  (If you loaded, say, only one new
  171. byte each time around, you could waste a LOT of cycles.)
  172. The skip_input_data() source manager routine requires special care in a
  173. suspension scenario.  This routine is NOT granted the ability to suspend the
  174. decompressor; it can decrement bytes_in_buffer to zero, but no more.  If the
  175. requested skip distance exceeds the amount of data currently in the input
  176. buffer, then skip_input_data() must set bytes_in_buffer to zero and record the
  177. additional skip distance somewhere else.  The decompressor will immediately
  178. call fill_input_buffer(), which should return FALSE, which will cause a
  179. suspension return.  The surrounding application must then arrange to discard
  180. the recorded number of bytes before it resumes loading the input buffer.
  181. (Yes, this design is rather baroque, but it avoids complexity in the far more
  182. common case where a non-suspending source manager is used.)
  183. If the input data has been exhausted, we recommend that you emit a warning
  184. and insert dummy EOI markers just as a non-suspending data source manager
  185. would do.  This can be handled either in the surrounding application logic or
  186. within fill_input_buffer(); the latter is probably more efficient.  If
  187. fill_input_buffer() knows that no more data is available, it can set the
  188. pointer/count to point to a dummy EOI marker and then return TRUE just as
  189. though it had read more data in a non-suspending situation.
  190. The decompressor does not attempt to suspend within any JPEG marker; it will
  191. backtrack to the start of the marker.  Hence the input buffer must be large
  192. enough to hold the longest marker in the file.  We recommend at least a 2K
  193. buffer.  The buffer would need to be 64K to allow for arbitrary COM or APPn
  194. markers, but the decompressor does not actually try to read these; it just
  195. skips them by calling skip_input_data().  If you provide a special marker
  196. handling routine that does look at such markers, coping with buffer overflow
  197. is your problem.  Ordinary JPEG markers should normally not exceed a few
  198. hundred bytes each (DHT tables are typically the longest).  For robustness
  199. against damaged marker length counts, you may wish to insert a test in your
  200. application for the case that the input buffer is completely full and yet the
  201. decoder has suspended without consuming any data --- otherwise, if this
  202. situation did occur, it would lead to an endless loop.
  203. Multiple-buffer management:
  204. In some applications it is desirable to store the compressed data in a linked
  205. list of buffer areas, so as to avoid data copying.  This can be handled by
  206. having empty_output_buffer() or fill_input_buffer() set the pointer and count
  207. to reference the next available buffer; FALSE is returned only if no more
  208. buffers are available.  Although seemingly straightforward, there is a
  209. pitfall in this approach: the backtrack that occurs when FALSE is returned
  210. could back up into an earlier buffer.  For example, when fill_input_buffer()
  211. is called, the current pointer & count indicate the backtrack restart point.
  212. Since fill_input_buffer() will set the pointer and count to refer to a new
  213. buffer, the restart position must be saved somewhere else.  Suppose a second
  214. call to fill_input_buffer() occurs in the same library call, and no
  215. additional input data is available, so fill_input_buffer must return FALSE.
  216. If the JPEG library has not moved the pointer/count forward in the current
  217. buffer, then *the correct restart point is the saved position in the prior
  218. buffer*.  Prior buffers may be discarded only after the library establishes
  219. a restart point within a later buffer.  Similar remarks apply for output into
  220. a chain of buffers.
  221. The library will never attempt to backtrack over a skip_input_data() call,
  222. so any skipped data can be permanently discarded.  You still have to deal
  223. with the case of skipping not-yet-received data, however.
  224. It's much simpler to use only a single buffer; when fill_input_buffer() is
  225. called, move any unconsumed data (beyond the current pointer/count) down to
  226. the beginning of this buffer and then load new data into the remaining buffer
  227. space.  This approach requires a little more data copying but is far easier
  228. to get right.
  229. Progressive JPEG support
  230. ------------------------
  231. Progressive JPEG rearranges the stored data into a series of scans of
  232. increasing quality.  In situations where a JPEG file is transmitted across a
  233. slow communications link, a decoder can generate a low-quality image very
  234. quickly from the first scan, then gradually improve the displayed quality as
  235. more scans are received.  The final image after all scans are complete is
  236. identical to that of a regular (sequential) JPEG file of the same quality
  237. setting.  Progressive JPEG files are often slightly smaller than equivalent
  238. sequential JPEG files, but the possibility of incremental display is the main
  239. reason for using progressive JPEG.
  240. The IJG encoder library generates progressive JPEG files when given a
  241. suitable "scan script" defining how to divide the data into scans.
  242. Creation of progressive JPEG files is otherwise transparent to the encoder.
  243. Progressive JPEG files can also be read transparently by the decoder library.
  244. If the decoding application simply uses the library as defined above, it
  245. will receive a final decoded image without any indication that the file was
  246. progressive.  Of course, this approach does not allow incremental display.
  247. To perform incremental display, an application needs to use the decoder
  248. library's "buffered-image" mode, in which it receives a decoded image
  249. multiple times.
  250. Each displayed scan requires about as much work to decode as a full JPEG
  251. image of the same size, so the decoder must be fairly fast in relation to the
  252. data transmission rate in order to make incremental display useful.  However,
  253. it is possible to skip displaying the image and simply add the incoming bits
  254. to the decoder's coefficient buffer.  This is fast because only Huffman
  255. decoding need be done, not IDCT, upsampling, colorspace conversion, etc.
  256. The IJG decoder library allows the application to switch dynamically between
  257. displaying the image and simply absorbing the incoming bits.  A properly
  258. coded application can automatically adapt the number of display passes to
  259. suit the time available as the image is received.  Also, a final
  260. higher-quality display cycle can be performed from the buffered data after
  261. the end of the file is reached.
  262. Progressive compression:
  263. To create a progressive JPEG file (or a multiple-scan sequential JPEG file),
  264. set the scan_info cinfo field to point to an array of scan descriptors, and
  265. perform compression as usual.  Instead of constructing your own scan list,
  266. you can call the jpeg_simple_progression() helper routine to create a
  267. recommended progression sequence; this method should be used by all
  268. applications that don't want to get involved in the nitty-gritty of
  269. progressive scan sequence design.  (If you want to provide user control of
  270. scan sequences, you may wish to borrow the scan script reading code found
  271. in rdswitch.c, so that you can read scan script files just like cjpeg's.)
  272. When scan_info is not NULL, the compression library will store DCT'd data
  273. into a buffer array as jpeg_write_scanlines() is called, and will emit all
  274. the requested scans during jpeg_finish_compress().  This implies that
  275. multiple-scan output cannot be created with a suspending data destination
  276. manager, since jpeg_finish_compress() does not support suspension.  We
  277. should also note that the compressor currently forces Huffman optimization
  278. mode when creating a progressive JPEG file, because the default Huffman
  279. tables are unsuitable for progressive files.
  280. Progressive decompression:
  281. When buffered-image mode is not used, the decoder library will read all of
  282. a multi-scan file during jpeg_start_decompress(), so that it can provide a
  283. final decoded image.  (Here "multi-scan" means either progressive or
  284. multi-scan sequential.)  This makes multi-scan files transparent to the
  285. decoding application.  However, existing applications that used suspending
  286. input with version 5 of the IJG library will need to be modified to check
  287. for a suspension return from jpeg_start_decompress().
  288. To perform incremental display, an application must use the library's
  289. buffered-image mode.  This is described in the next section.
  290. Buffered-image mode
  291. -------------------
  292. In buffered-image mode, the library stores the partially decoded image in a
  293. coefficient buffer, from which it can be read out as many times as desired.
  294. This mode is typically used for incremental display of progressive JPEG files,
  295. but it can be used with any JPEG file.  Each scan of a progressive JPEG file
  296. adds more data (more detail) to the buffered image.  The application can
  297. display in lockstep with the source file (one display pass per input scan),
  298. or it can allow input processing to outrun display processing.  By making
  299. input and display processing run independently, it is possible for the
  300. application to adapt progressive display to a wide range of data transmission
  301. rates.
  302. The basic control flow for buffered-image decoding is
  303. jpeg_create_decompress()
  304. set data source
  305. jpeg_read_header()
  306. set overall decompression parameters
  307. cinfo.buffered_image = TRUE; /* select buffered-image mode */
  308. jpeg_start_decompress()
  309. for (each output pass) {
  310.     adjust output decompression parameters if required
  311.     jpeg_start_output() /* start a new output pass */
  312.     for (all scanlines in image) {
  313.         jpeg_read_scanlines()
  314.         display scanlines
  315.     }
  316.     jpeg_finish_output() /* terminate output pass */
  317. }
  318. jpeg_finish_decompress()
  319. jpeg_destroy_decompress()
  320. This differs from ordinary unbuffered decoding in that there is an additional
  321. level of looping.  The application can choose how many output passes to make
  322. and how to display each pass.
  323. The simplest approach to displaying progressive images is to do one display
  324. pass for each scan appearing in the input file.  In this case the outer loop
  325. condition is typically
  326. while (! jpeg_input_complete(&cinfo))
  327. and the start-output call should read
  328. jpeg_start_output(&cinfo, cinfo.input_scan_number);
  329. The second parameter to jpeg_start_output() indicates which scan of the input
  330. file is to be displayed; the scans are numbered starting at 1 for this
  331. purpose.  (You can use a loop counter starting at 1 if you like, but using
  332. the library's input scan counter is easier.)  The library automatically reads
  333. data as necessary to complete each requested scan, and jpeg_finish_output()
  334. advances to the next scan or end-of-image marker (hence input_scan_number
  335. will be incremented by the time control arrives back at jpeg_start_output()).
  336. With this technique, data is read from the input file only as needed, and
  337. input and output processing run in lockstep.
  338. After reading the final scan and reaching the end of the input file, the
  339. buffered image remains available; it can be read additional times by
  340. repeating the jpeg_start_output()/jpeg_read_scanlines()/jpeg_finish_output()
  341. sequence.  For example, a useful technique is to use fast one-pass color
  342. quantization for display passes made while the image is arriving, followed by
  343. a final display pass using two-pass quantization for highest quality.  This
  344. is done by changing the library parameters before the final output pass.
  345. Changing parameters between passes is discussed in detail below.
  346. In general the last scan of a progressive file cannot be recognized as such
  347. until after it is read, so a post-input display pass is the best approach if
  348. you want special processing in the final pass.
  349. When done with the image, be sure to call jpeg_finish_decompress() to release
  350. the buffered image (or just use jpeg_destroy_decompress()).
  351. If input data arrives faster than it can be displayed, the application can
  352. cause the library to decode input data in advance of what's needed to produce
  353. output.  This is done by calling the routine jpeg_consume_input().
  354. The return value is one of the following:
  355. JPEG_REACHED_SOS:    reached an SOS marker (the start of a new scan)
  356. JPEG_REACHED_EOI:    reached the EOI marker (end of image)
  357. JPEG_ROW_COMPLETED:  completed reading one MCU row of compressed data
  358. JPEG_SCAN_COMPLETED: completed reading last MCU row of current scan
  359. JPEG_SUSPENDED:      suspended before completing any of the above
  360. (JPEG_SUSPENDED can occur only if a suspending data source is used.)  This
  361. routine can be called at any time after initializing the JPEG object.  It
  362. reads some additional data and returns when one of the indicated significant
  363. events occurs.  (If called after the EOI marker is reached, it will
  364. immediately return JPEG_REACHED_EOI without attempting to read more data.)
  365. The library's output processing will automatically call jpeg_consume_input()
  366. whenever the output processing overtakes the input; thus, simple lockstep
  367. display requires no direct calls to jpeg_consume_input().  But by adding
  368. calls to jpeg_consume_input(), you can absorb data in advance of what is
  369. being displayed.  This has two benefits:
  370.   * You can limit buildup of unprocessed data in your input buffer.
  371.   * You can eliminate extra display passes by paying attention to the
  372.     state of the library's input processing.
  373. The first of these benefits only requires interspersing calls to
  374. jpeg_consume_input() with your display operations and any other processing
  375. you may be doing.  To avoid wasting cycles due to backtracking, it's best to
  376. call jpeg_consume_input() only after a hundred or so new bytes have arrived.
  377. This is discussed further under "I/O suspension", above.  (Note: the JPEG
  378. library currently is not thread-safe.  You must not call jpeg_consume_input()
  379. from one thread of control if a different library routine is working on the
  380. same JPEG object in another thread.)
  381. When input arrives fast enough that more than one new scan is available
  382. before you start a new output pass, you may as well skip the output pass
  383. corresponding to the completed scan.  This occurs for free if you pass
  384. cinfo.input_scan_number as the target scan number to jpeg_start_output().
  385. The input_scan_number field is simply the index of the scan currently being
  386. consumed by the input processor.  You can ensure that this is up-to-date by
  387. emptying the input buffer just before calling jpeg_start_output(): call
  388. jpeg_consume_input() repeatedly until it returns JPEG_SUSPENDED or
  389. JPEG_REACHED_EOI.
  390. The target scan number passed to jpeg_start_output() is saved in the
  391. cinfo.output_scan_number field.  The library's output processing calls
  392. jpeg_consume_input() whenever the current input scan number and row within
  393. the scan is less than or equal to the current output scan number and row.
  394. Thus, input processing can "get ahead" of the output processing but is not
  395. allowed to "fall behind".  You can achieve several different effects by
  396. manipulating this interlock rule.  For example, if you pass a target scan
  397. number greater than the current input scan number, the output processor will
  398. wait until that scan starts to arrive before producing any output.  (To avoid
  399. an infinite loop, the target scan number is automatically reset to the last
  400. scan number when the end of image is reached.  Thus, if you specify a large
  401. target scan number, the library will just absorb the entire input file and
  402. then perform an output pass.  This is effectively the same as what
  403. jpeg_start_decompress() does when you don't select buffered-image mode.)
  404. When you pass a target scan number equal to the current input scan number,
  405. the image is displayed no faster than the current input scan arrives.  The
  406. final possibility is to pass a target scan number less than the current input
  407. scan number; this disables the input/output interlock and causes the output
  408. processor to simply display whatever it finds in the image buffer, without
  409. waiting for input.  (However, the library will not accept a target scan
  410. number less than one, so you can't avoid waiting for the first scan.)
  411. When using jpeg_consume_input(), you'll typically want to be sure that you
  412. perform a final output pass after receiving all the data; otherwise your last
  413. display may not be full quality across the whole screen.  So the right outer
  414. loop logic is something like this:
  415. do {
  416.     absorb any waiting input by calling jpeg_consume_input()
  417.     final_pass = jpeg_input_complete(&cinfo);
  418.     adjust output decompression parameters if required
  419.     jpeg_start_output(&cinfo, cinfo.input_scan_number);
  420.     ...
  421.     jpeg_finish_output()
  422. } while (! final_pass);
  423. rather than quitting as soon as jpeg_input_complete() returns TRUE.  This
  424. arrangement makes it simple to use higher-quality decoding parameters
  425. for the final pass.  But if you don't want to use special parameters for
  426. the final pass, the right loop logic is like this:
  427. for (;;) {
  428.     absorb any waiting input by calling jpeg_consume_input()
  429.     jpeg_start_output(&cinfo, cinfo.input_scan_number);
  430.     ...
  431.     jpeg_finish_output()
  432.     if (jpeg_input_complete(&cinfo) &&
  433.         cinfo.input_scan_number == cinfo.output_scan_number)
  434.       break;
  435. }
  436. In this case you don't need to know in advance whether an output pass is
  437. the last one, so it's not necessary to have reached EOF before starting the
  438. final output pass; rather, what you want to test is whether the output pass
  439. was performed in sync with the final input scan.  This form of the loop
  440. will avoid an extra output pass whenever the decoder is able (or nearly
  441. able) to keep up with the incoming data.
  442. When the data transmission speed is high, you might begin a display pass,
  443. then find that much or all of the image has arrived before you can complete
  444. the pass.  (You can detect this by noting the JPEG_REACHED_EOI return code
  445. from jpeg_consume_input(), or equivalently by testing jpeg_input_complete().)
  446. In this situation you may wish to abort the current display pass and start a
  447. new one using the newly arrived information.  To do so, just call
  448. jpeg_finish_output() and then start a new pass with jpeg_start_output().
  449. A variant strategy is to abort and restart display if more than one complete
  450. scan arrives during an output pass; this can be detected by noting
  451. JPEG_REACHED_SOS returns and/or examining cinfo.input_scan_number.  This
  452. idea should be employed with caution, however, since the display process
  453. might never get to the bottom of the image before being aborted, resulting
  454. in the lower part of the screen being several passes worse than the upper.
  455. In most cases it's probably best to abort an output pass only if the whole
  456. file has arrived and you want to begin the final output pass immediately.
  457. When receiving data across a communication link, we recommend always using
  458. the current input scan number for the output target scan number; if a
  459. higher-quality final pass is to be done, it should be started (aborting any
  460. incomplete output pass) as soon as the end of file is received.  However,
  461. many other strategies are possible.  For example, the application can examine
  462. the parameters of the current input scan and decide whether to display it or
  463. not.  If the scan contains only chroma data, one might choose not to use it
  464. as the target scan, expecting that the scan will be small and will arrive
  465. quickly.  To skip to the next scan, call jpeg_consume_input() until it
  466. returns JPEG_REACHED_SOS or JPEG_REACHED_EOI.  Or just use the next higher
  467. number as the target scan for jpeg_start_output(); but that method doesn't
  468. let you inspect the next scan's parameters before deciding to display it.
  469. In buffered-image mode, jpeg_start_decompress() never performs input and
  470. thus never suspends.  An application that uses input suspension with
  471. buffered-image mode must be prepared for suspension returns from these
  472. routines:
  473. * jpeg_start_output() performs input only if you request 2-pass quantization
  474.   and the target scan isn't fully read yet.  (This is discussed below.)
  475. * jpeg_read_scanlines(), as always, returns the number of scanlines that it
  476.   was able to produce before suspending.
  477. * jpeg_finish_output() will read any markers following the target scan,
  478.   up to the end of the image or the SOS marker that begins another scan.
  479.   (But it reads no input if jpeg_consume_input() has already reached the
  480.   end of the image or a SOS marker beyond the target output scan.)
  481. * jpeg_finish_decompress() will read until the end of image, and thus can
  482.   suspend if the end hasn't already been reached (as can be tested by
  483.   calling jpeg_input_complete()).
  484. jpeg_start_output(), jpeg_finish_output(), and jpeg_finish_decompress()
  485. all return TRUE if they completed their tasks, FALSE if they had to suspend.
  486. In the event of a FALSE return, the application must load more input data
  487. and repeat the call.  Applications that use non-suspending data sources need
  488. not check the return values of these three routines.
  489. It is possible to change decoding parameters between output passes in the
  490. buffered-image mode.  The decoder library currently supports only very
  491. limited changes of parameters.  ONLY THE FOLLOWING parameter changes are
  492. allowed after jpeg_start_decompress() is called:
  493. * dct_method can be changed before each call to jpeg_start_output().
  494.   For example, one could use a fast DCT method for early scans, changing
  495.   to a higher quality method for the final scan.
  496. * dither_mode can be changed before each call to jpeg_start_output();
  497.   of course this has no impact if not using color quantization.  Typically
  498.   one would use ordered dither for initial passes, then switch to
  499.   Floyd-Steinberg dither for the final pass.  Caution: changing dither mode
  500.   can cause more memory to be allocated by the library.  Although the amount
  501.   of memory involved is not large (a scanline or so), it may cause the
  502.   initial max_memory_to_use specification to be exceeded, which in the worst
  503.   case would result in an out-of-memory failure.
  504. * do_block_smoothing can be changed before each call to jpeg_start_output().
  505.   This setting is relevant only when decoding a progressive JPEG image.
  506.   During the first DC-only scan, block smoothing provides a very "fuzzy" look
  507.   instead of the very "blocky" look seen without it; which is better seems a
  508.   matter of personal taste.  But block smoothing is nearly always a win
  509.   during later stages, especially when decoding a successive-approximation
  510.   image: smoothing helps to hide the slight blockiness that otherwise shows
  511.   up on smooth gradients until the lowest coefficient bits are sent.
  512. * Color quantization mode can be changed under the rules described below.
  513.   You *cannot* change between full-color and quantized output (because that
  514.   would alter the required I/O buffer sizes), but you can change which
  515.   quantization method is used.
  516. When generating color-quantized output, changing quantization method is a
  517. very useful way of switching between high-speed and high-quality display.
  518. The library allows you to change among its three quantization methods:
  519. 1. Single-pass quantization to a fixed color cube.
  520.    Selected by cinfo.two_pass_quantize = FALSE and cinfo.colormap = NULL.
  521. 2. Single-pass quantization to an application-supplied colormap.
  522.    Selected by setting cinfo.colormap to point to the colormap (the value of
  523.    two_pass_quantize is ignored); also set cinfo.actual_number_of_colors.
  524. 3. Two-pass quantization to a colormap chosen specifically for the image.
  525.    Selected by cinfo.two_pass_quantize = TRUE and cinfo.colormap = NULL.
  526.    (This is the default setting selected by jpeg_read_header, but it is
  527.    probably NOT what you want for the first pass of progressive display!)
  528. These methods offer successively better quality and lesser speed.  However,
  529. only the first method is available for quantizing in non-RGB color spaces.
  530. IMPORTANT: because the different quantizer methods have very different
  531. working-storage requirements, the library requires you to indicate which
  532. one(s) you intend to use before you call jpeg_start_decompress().  (If we did
  533. not require this, the max_memory_to_use setting would be a complete fiction.)
  534. You do this by setting one or more of these three cinfo fields to TRUE:
  535. enable_1pass_quant Fixed color cube colormap
  536. enable_external_quant Externally-supplied colormap
  537. enable_2pass_quant Two-pass custom colormap
  538. All three are initialized FALSE by jpeg_read_header().  But
  539. jpeg_start_decompress() automatically sets TRUE the one selected by the
  540. current two_pass_quantize and colormap settings, so you only need to set the
  541. enable flags for any other quantization methods you plan to change to later.
  542. After setting the enable flags correctly at jpeg_start_decompress() time, you
  543. can change to any enabled quantization method by setting two_pass_quantize
  544. and colormap properly just before calling jpeg_start_output().  The following
  545. special rules apply:
  546. 1. You must explicitly set cinfo.colormap to NULL when switching to 1-pass
  547.    or 2-pass mode from a different mode, or when you want the 2-pass
  548.    quantizer to be re-run to generate a new colormap.
  549. 2. To switch to an external colormap, or to change to a different external
  550.    colormap than was used on the prior pass, you must call
  551.    jpeg_new_colormap() after setting cinfo.colormap.
  552. NOTE: if you want to use the same colormap as was used in the prior pass,
  553. you should not do either of these things.  This will save some nontrivial
  554. switchover costs.
  555. (These requirements exist because cinfo.colormap will always be non-NULL
  556. after completing a prior output pass, since both the 1-pass and 2-pass
  557. quantizers set it to point to their output colormaps.  Thus you have to
  558. do one of these two things to notify the library that something has changed.
  559. Yup, it's a bit klugy, but it's necessary to do it this way for backwards
  560. compatibility.)
  561. Note that in buffered-image mode, the library generates any requested colormap
  562. during jpeg_start_output(), not during jpeg_start_decompress().
  563. When using two-pass quantization, jpeg_start_output() makes a pass over the
  564. buffered image to determine the optimum color map; it therefore may take a
  565. significant amount of time, whereas ordinarily it does little work.  The
  566. progress monitor hook is called during this pass, if defined.  It is also
  567. important to realize that if the specified target scan number is greater than
  568. or equal to the current input scan number, jpeg_start_output() will attempt
  569. to consume input as it makes this pass.  If you use a suspending data source,
  570. you need to check for a FALSE return from jpeg_start_output() under these
  571. conditions.  The combination of 2-pass quantization and a not-yet-fully-read
  572. target scan is the only case in which jpeg_start_output() will consume input.
  573. Application authors who support buffered-image mode may be tempted to use it
  574. for all JPEG images, even single-scan ones.  This will work, but it is
  575. inefficient: there is no need to create an image-sized coefficient buffer for
  576. single-scan images.  Requesting buffered-image mode for such an image wastes
  577. memory.  Worse, it can cost time on large images, since the buffered data has
  578. to be swapped out or written to a temporary file.  If you are concerned about
  579. maximum performance on baseline JPEG files, you should use buffered-image
  580. mode only when the incoming file actually has multiple scans.  This can be
  581. tested by calling jpeg_has_multiple_scans(), which will return a correct
  582. result at any time after jpeg_read_header() completes.
  583. It is also worth noting that when you use jpeg_consume_input() to let input
  584. processing get ahead of output processing, the resulting pattern of access to
  585. the coefficient buffer is quite nonsequential.  It's best to use the memory
  586. manager jmemnobs.c if you can (ie, if you have enough real or virtual main
  587. memory).  If not, at least make sure that max_memory_to_use is set as high as
  588. possible.  If the JPEG memory manager has to use a temporary file, you will
  589. probably see a lot of disk traffic and poor performance.  (This could be
  590. improved with additional work on the memory manager, but we haven't gotten
  591. around to it yet.)
  592. In some applications it may be convenient to use jpeg_consume_input() for all
  593. input processing, including reading the initial markers; that is, you may
  594. wish to call jpeg_consume_input() instead of jpeg_read_header() during
  595. startup.  This works, but note that you must check for JPEG_REACHED_SOS and
  596. JPEG_REACHED_EOI return codes as the equivalent of jpeg_read_header's codes.
  597. Once the first SOS marker has been reached, you must call
  598. jpeg_start_decompress() before jpeg_consume_input() will consume more input;
  599. it'll just keep returning JPEG_REACHED_SOS until you do.  If you read a
  600. tables-only file this way, jpeg_consume_input() will return JPEG_REACHED_EOI
  601. without ever returning JPEG_REACHED_SOS; be sure to check for this case.
  602. If this happens, the decompressor will not read any more input until you call
  603. jpeg_abort() to reset it.  It is OK to call jpeg_consume_input() even when not
  604. using buffered-image mode, but in that case it's basically a no-op after the
  605. initial markers have been read: it will just return JPEG_SUSPENDED.
  606. Abbreviated datastreams and multiple images
  607. -------------------------------------------
  608. A JPEG compression or decompression object can be reused to process multiple
  609. images.  This saves a small amount of time per image by eliminating the
  610. "create" and "destroy" operations, but that isn't the real purpose of the
  611. feature.  Rather, reuse of an object provides support for abbreviated JPEG
  612. datastreams.  Object reuse can also simplify processing a series of images in
  613. a single input or output file.  This section explains these features.
  614. A JPEG file normally contains several hundred bytes worth of quantization
  615. and Huffman tables.  In a situation where many images will be stored or
  616. transmitted with identical tables, this may represent an annoying overhead.
  617. The JPEG standard therefore permits tables to be omitted.  The standard
  618. defines three classes of JPEG datastreams:
  619.   * "Interchange" datastreams contain an image and all tables needed to decode
  620.      the image.  These are the usual kind of JPEG file.
  621.   * "Abbreviated image" datastreams contain an image, but are missing some or
  622.     all of the tables needed to decode that image.
  623.   * "Abbreviated table specification" (henceforth "tables-only") datastreams
  624.     contain only table specifications.
  625. To decode an abbreviated image, it is necessary to load the missing table(s)
  626. into the decoder beforehand.  This can be accomplished by reading a separate
  627. tables-only file.  A variant scheme uses a series of images in which the first
  628. image is an interchange (complete) datastream, while subsequent ones are
  629. abbreviated and rely on the tables loaded by the first image.  It is assumed
  630. that once the decoder has read a table, it will remember that table until a
  631. new definition for the same table number is encountered.
  632. It is the application designer's responsibility to figure out how to associate
  633. the correct tables with an abbreviated image.  While abbreviated datastreams
  634. can be useful in a closed environment, their use is strongly discouraged in
  635. any situation where data exchange with other applications might be needed.
  636. Caveat designer.
  637. The JPEG library provides support for reading and writing any combination of
  638. tables-only datastreams and abbreviated images.  In both compression and
  639. decompression objects, a quantization or Huffman table will be retained for
  640. the lifetime of the object, unless it is overwritten by a new table definition.
  641. To create abbreviated image datastreams, it is only necessary to tell the
  642. compressor not to emit some or all of the tables it is using.  Each
  643. quantization and Huffman table struct contains a boolean field "sent_table",
  644. which normally is initialized to FALSE.  For each table used by the image, the
  645. header-writing process emits the table and sets sent_table = TRUE unless it is
  646. already TRUE.  (In normal usage, this prevents outputting the same table
  647. definition multiple times, as would otherwise occur because the chroma
  648. components typically share tables.)  Thus, setting this field to TRUE before
  649. calling jpeg_start_compress() will prevent the table from being written at
  650. all.
  651. If you want to create a "pure" abbreviated image file containing no tables,
  652. just call "jpeg_suppress_tables(&cinfo, TRUE)" after constructing all the
  653. tables.  If you want to emit some but not all tables, you'll need to set the
  654. individual sent_table fields directly.
  655. To create an abbreviated image, you must also call jpeg_start_compress()
  656. with a second parameter of FALSE, not TRUE.  Otherwise jpeg_start_compress()
  657. will force all the sent_table fields to FALSE.  (This is a safety feature to
  658. prevent abbreviated images from being created accidentally.)
  659. To create a tables-only file, perform the same parameter setup that you
  660. normally would, but instead of calling jpeg_start_compress() and so on, call
  661. jpeg_write_tables(&cinfo).  This will write an abbreviated datastream
  662. containing only SOI, DQT and/or DHT markers, and EOI.  All the quantization
  663. and Huffman tables that are currently defined in the compression object will
  664. be emitted unless their sent_tables flag is already TRUE, and then all the
  665. sent_tables flags will be set TRUE.
  666. A sure-fire way to create matching tables-only and abbreviated image files
  667. is to proceed as follows:
  668. create JPEG compression object
  669. set JPEG parameters
  670. set destination to tables-only file
  671. jpeg_write_tables(&cinfo);
  672. set destination to image file
  673. jpeg_start_compress(&cinfo, FALSE);
  674. write data...
  675. jpeg_finish_compress(&cinfo);
  676. Since the JPEG parameters are not altered between writing the table file and
  677. the abbreviated image file, the same tables are sure to be used.  Of course,
  678. you can repeat the jpeg_start_compress() ... jpeg_finish_compress() sequence
  679. many times to produce many abbreviated image files matching the table file.
  680. You cannot suppress output of the computed Huffman tables when Huffman
  681. optimization is selected.  (If you could, there'd be no way to decode the
  682. image...)  Generally, you don't want to set optimize_coding = TRUE when
  683. you are trying to produce abbreviated files.
  684. In some cases you might want to compress an image using tables which are
  685. not stored in the application, but are defined in an interchange or
  686. tables-only file readable by the application.  This can be done by setting up
  687. a JPEG decompression object to read the specification file, then copying the
  688. tables into your compression object.
  689. To read abbreviated image files, you simply need to load the proper tables
  690. into the decompression object before trying to read the abbreviated image.
  691. If the proper tables are stored in the application program, you can just
  692. allocate the table structs and fill in their contents directly.  More commonly
  693. you'd want to read the tables from a tables-only file.  The jpeg_read_header()
  694. call is sufficient to read a tables-only file.  You must pass a second
  695. parameter of FALSE to indicate that you do not require an image to be present.
  696. Thus, the typical scenario is
  697. create JPEG decompression object
  698. set source to tables-only file
  699. jpeg_read_header(&cinfo, FALSE);
  700. set source to abbreviated image file
  701. jpeg_read_header(&cinfo, TRUE);
  702. set decompression parameters
  703. jpeg_start_decompress(&cinfo);
  704. read data...
  705. jpeg_finish_decompress(&cinfo);
  706. In some cases, you may want to read a file without knowing whether it contains
  707. an image or just tables.  In that case, pass FALSE and check the return value
  708. from jpeg_read_header(): it will be JPEG_HEADER_OK if an image was found,
  709. JPEG_HEADER_TABLES_ONLY if only tables were found.  (A third return value,
  710. JPEG_SUSPENDED, is possible when using a suspending data source manager.)
  711. Note that jpeg_read_header() will not complain if you read an abbreviated
  712. image for which you haven't loaded the missing tables; the missing-table check
  713. occurs later, in jpeg_start_decompress().
  714. It is possible to read a series of images from a single source file by
  715. repeating the jpeg_read_header() ... jpeg_finish_decompress() sequence,
  716. without releasing/recreating the JPEG object or the data source module.
  717. (If you did reinitialize, any partial bufferload left in the data source
  718. buffer at the end of one image would be discarded, causing you to lose the
  719. start of the next image.)  When you use this method, stored tables are
  720. automatically carried forward, so some of the images can be abbreviated images
  721. that depend on tables from earlier images.
  722. If you intend to write a series of images into a single destination file,
  723. you might want to make a specialized data destination module that doesn't
  724. flush the output buffer at term_destination() time.  This would speed things
  725. up by some trifling amount.  Of course, you'd need to remember to flush the
  726. buffer after the last image.  You can make the later images be abbreviated
  727. ones by passing FALSE to jpeg_start_compress().
  728. Special markers
  729. ---------------
  730. Some applications may need to insert or extract special data in the JPEG
  731. datastream.  The JPEG standard provides marker types "COM" (comment) and
  732. "APP0" through "APP15" (application) to hold application-specific data.
  733. Unfortunately, the use of these markers is not specified by the standard.
  734. COM markers are fairly widely used to hold user-supplied text.  The JFIF file
  735. format spec uses APP0 markers with specified initial strings to hold certain
  736. data.  Adobe applications use APP14 markers beginning with the string "Adobe"
  737. for miscellaneous data.  Other APPn markers are rarely seen, but might
  738. contain almost anything.
  739. If you wish to store user-supplied text, we recommend you use COM markers
  740. and place readable 7-bit ASCII text in them.  Newline conventions are not
  741. standardized --- expect to find LF (Unix style), CR/LF (DOS style), or CR
  742. (Mac style).  A robust COM reader should be able to cope with random binary
  743. garbage, including nulls, since some applications generate COM markers
  744. containing non-ASCII junk.  (But yours should not be one of them.)
  745. For program-supplied data, use an APPn marker, and be sure to begin it with an
  746. identifying string so that you can tell whether the marker is actually yours.
  747. It's probably best to avoid using APP0 or APP14 for any private markers.
  748. (NOTE: the upcoming SPIFF standard will use APP8 markers; we recommend you
  749. not use APP8 markers for any private purposes, either.)
  750. Keep in mind that at most 65533 bytes can be put into one marker, but you
  751. can have as many markers as you like.
  752. By default, the IJG compression library will write a JFIF APP0 marker if the
  753. selected JPEG colorspace is grayscale or YCbCr, or an Adobe APP14 marker if
  754. the selected colorspace is RGB, CMYK, or YCCK.  You can disable this, but
  755. we don't recommend it.  The decompression library will recognize JFIF and
  756. Adobe markers and will set the JPEG colorspace properly when one is found.
  757. You can write special markers immediately following the datastream header by
  758. calling jpeg_write_marker() after jpeg_start_compress() and before the first
  759. call to jpeg_write_scanlines().  When you do this, the markers appear after
  760. the SOI and the JFIF APP0 and Adobe APP14 markers (if written), but before
  761. all else.  Specify the marker type parameter as "JPEG_COM" for COM or
  762. "JPEG_APP0 + n" for APPn.  (Actually, jpeg_write_marker will let you write
  763. any marker type, but we don't recommend writing any other kinds of marker.)
  764. For example, to write a user comment string pointed to by comment_text:
  765. jpeg_write_marker(cinfo, JPEG_COM, comment_text, strlen(comment_text));
  766. Or if you prefer to synthesize the marker byte sequence yourself, you can
  767. just cram it straight into the data destination module.
  768. For decompression, you can supply your own routine to process COM or APPn
  769. markers by calling jpeg_set_marker_processor().  Usually you'd call this
  770. after creating a decompression object and before calling jpeg_read_header(),
  771. because the markers of interest will normally be scanned by jpeg_read_header.
  772. Once you've supplied a routine, it will be used for the life of that
  773. decompression object.  A separate routine may be registered for COM and for
  774. each APPn marker code.
  775. A marker processor routine must have the signature
  776. boolean jpeg_marker_parser_method (j_decompress_ptr cinfo)
  777. Although the marker code is not explicitly passed, the routine can find it
  778. in cinfo->unread_marker.  At the time of call, the marker proper has been
  779. read from the data source module.  The processor routine is responsible for
  780. reading the marker length word and the remaining parameter bytes, if any.
  781. Return TRUE to indicate success.  (FALSE should be returned only if you are
  782. using a suspending data source and it tells you to suspend.  See the standard
  783. marker processors in jdmarker.c for appropriate coding methods if you need to
  784. use a suspending data source.)
  785. If you override the default APP0 or APP14 processors, it is up to you to
  786. recognize JFIF and Adobe markers if you want colorspace recognition to occur
  787. properly.  We recommend copying and extending the default processors if you
  788. want to do that.
  789. A simple example of an external COM processor can be found in djpeg.c.
  790. Raw (downsampled) image data
  791. ----------------------------
  792. Some applications need to supply already-downsampled image data to the JPEG
  793. compressor, or to receive raw downsampled data from the decompressor.  The
  794. library supports this requirement by allowing the application to write or
  795. read raw data, bypassing the normal preprocessing or postprocessing steps.
  796. The interface is different from the standard one and is somewhat harder to
  797. use.  If your interest is merely in bypassing color conversion, we recommend
  798. that you use the standard interface and simply set jpeg_color_space =
  799. in_color_space (or jpeg_color_space = out_color_space for decompression).
  800. The mechanism described in this section is necessary only to supply or
  801. receive downsampled image data, in which not all components have the same
  802. dimensions.
  803. To compress raw data, you must supply the data in the colorspace to be used
  804. in the JPEG file (please read the earlier section on Special color spaces)
  805. and downsampled to the sampling factors specified in the JPEG parameters.
  806. You must supply the data in the format used internally by the JPEG library,
  807. namely a JSAMPIMAGE array.  This is an array of pointers to two-dimensional
  808. arrays, each of type JSAMPARRAY.  Each 2-D array holds the values for one
  809. color component.  This structure is necessary since the components are of
  810. different sizes.  If the image dimensions are not a multiple of the MCU size,
  811. you must also pad the data correctly (usually, this is done by replicating
  812. the last column and/or row).  The data must be padded to a multiple of a DCT
  813. block in each component: that is, each downsampled row must contain a
  814. multiple of 8 valid samples, and there must be a multiple of 8 sample rows
  815. for each component.  (For applications such as conversion of digital TV
  816. images, the standard image size is usually a multiple of the DCT block size,
  817. so that no padding need actually be done.)
  818. The procedure for compression of raw data is basically the same as normal
  819. compression, except that you call jpeg_write_raw_data() in place of
  820. jpeg_write_scanlines().  Before calling jpeg_start_compress(), you must do
  821. the following:
  822.   * Set cinfo->raw_data_in to TRUE.  (It is set FALSE by jpeg_set_defaults().)
  823.     This notifies the library that you will be supplying raw data.
  824.   * Ensure jpeg_color_space is correct --- an explicit jpeg_set_colorspace()
  825.     call is a good idea.  Note that since color conversion is bypassed,
  826.     in_color_space is ignored, except that jpeg_set_defaults() uses it to
  827.     choose the default jpeg_color_space setting.
  828.   * Ensure the sampling factors, cinfo->comp_info[i].h_samp_factor and
  829.     cinfo->comp_info[i].v_samp_factor, are correct.  Since these indicate the
  830.     dimensions of the data you are supplying, it's wise to set them
  831.     explicitly, rather than assuming the library's defaults are what you want.
  832. To pass raw data to the library, call jpeg_write_raw_data() in place of
  833. jpeg_write_scanlines().  The two routines work similarly except that
  834. jpeg_write_raw_data takes a JSAMPIMAGE data array rather than JSAMPARRAY.
  835. The scanlines count passed to and returned from jpeg_write_raw_data is
  836. measured in terms of the component with the largest v_samp_factor.
  837. jpeg_write_raw_data() processes one MCU row per call, which is to say
  838. v_samp_factor*DCTSIZE sample rows of each component.  The passed num_lines
  839. value must be at least max_v_samp_factor*DCTSIZE, and the return value will
  840. be exactly that amount (or possibly some multiple of that amount, in future
  841. library versions).  This is true even on the last call at the bottom of the
  842. image; don't forget to pad your data as necessary.
  843. The required dimensions of the supplied data can be computed for each
  844. component as
  845. cinfo->comp_info[i].width_in_blocks*DCTSIZE  samples per row
  846. cinfo->comp_info[i].height_in_blocks*DCTSIZE rows in image
  847. after jpeg_start_compress() has initialized those fields.  If the valid data
  848. is smaller than this, it must be padded appropriately.  For some sampling
  849. factors and image sizes, additional dummy DCT blocks are inserted to make
  850. the image a multiple of the MCU dimensions.  The library creates such dummy
  851. blocks itself; it does not read them from your supplied data.  Therefore you
  852. need never pad by more than DCTSIZE samples.  An example may help here.
  853. Assume 2h2v downsampling of YCbCr data, that is
  854. cinfo->comp_info[0].h_samp_factor = 2 for Y
  855. cinfo->comp_info[0].v_samp_factor = 2
  856. cinfo->comp_info[1].h_samp_factor = 1 for Cb
  857. cinfo->comp_info[1].v_samp_factor = 1
  858. cinfo->comp_info[2].h_samp_factor = 1 for Cr
  859. cinfo->comp_info[2].v_samp_factor = 1
  860. and suppose that the nominal image dimensions (cinfo->image_width and
  861. cinfo->image_height) are 101x101 pixels.  Then jpeg_start_compress() will
  862. compute downsampled_width = 101 and width_in_blocks = 13 for Y,
  863. downsampled_width = 51 and width_in_blocks = 7 for Cb and Cr (and the same
  864. for the height fields).  You must pad the Y data to at least 13*8 = 104
  865. columns and rows, the Cb/Cr data to at least 7*8 = 56 columns and rows.  The
  866. MCU height is max_v_samp_factor = 2 DCT rows so you must pass at least 16
  867. scanlines on each call to jpeg_write_raw_data(), which is to say 16 actual
  868. sample rows of Y and 8 each of Cb and Cr.  A total of 7 MCU rows are needed,
  869. so you must pass a total of 7*16 = 112 "scanlines".  The last DCT block row
  870. of Y data is dummy, so it doesn't matter what you pass for it in the data
  871. arrays, but the scanlines count must total up to 112 so that all of the Cb
  872. and Cr data gets passed.
  873. Output suspension is supported with raw-data compression: if the data
  874. destination module suspends, jpeg_write_raw_data() will return 0.
  875. In this case the same data rows must be passed again on the next call.
  876. Decompression with raw data output implies bypassing all postprocessing:
  877. you cannot ask for rescaling or color quantization, for instance.  More
  878. seriously, you must deal with the color space and sampling factors present in
  879. the incoming file.  If your application only handles, say, 2h1v YCbCr data,
  880. you must check for and fail on other color spaces or other sampling factors.
  881. The library will not convert to a different color space for you.
  882. To obtain raw data output, set cinfo->raw_data_out = TRUE before
  883. jpeg_start_decompress() (it is set FALSE by jpeg_read_header()).  Be sure to
  884. verify that the color space and sampling factors are ones you can handle.
  885. Then call jpeg_read_raw_data() in place of jpeg_read_scanlines().  The
  886. decompression process is otherwise the same as usual.
  887. jpeg_read_raw_data() returns one MCU row per call, and thus you must pass a
  888. buffer of at least max_v_samp_factor*DCTSIZE scanlines (scanline counting is
  889. the same as for raw-data compression).  The buffer you pass must be large
  890. enough to hold the actual data plus padding to DCT-block boundaries.  As with
  891. compression, any entirely dummy DCT blocks are not processed so you need not
  892. allocate space for them, but the total scanline count includes them.  The
  893. above example of computing buffer dimensions for raw-data compression is
  894. equally valid for decompression.
  895. Input suspension is supported with raw-data decompression: if the data source
  896. module suspends, jpeg_read_raw_data() will return 0.  You can also use
  897. buffered-image mode to read raw data in multiple passes.
  898. Really raw data: DCT coefficients
  899. ---------------------------------
  900. It is possible to read or write the contents of a JPEG file as raw DCT
  901. coefficients.  This facility is mainly intended for use in lossless
  902. transcoding between different JPEG file formats.  Other possible applications
  903. include lossless cropping of a JPEG image, lossless reassembly of a
  904. multi-strip or multi-tile TIFF/JPEG file into a single JPEG datastream, etc.
  905. To read the contents of a JPEG file as DCT coefficients, open the file and do
  906. jpeg_read_header() as usual.  But instead of calling jpeg_start_decompress()
  907. and jpeg_read_scanlines(), call jpeg_read_coefficients().  This will read the
  908. entire image into a set of virtual coefficient-block arrays, one array per
  909. component.  The return value is a pointer to an array of virtual-array
  910. descriptors.  Each virtual array can be accessed directly using the JPEG
  911. memory manager's access_virt_barray method (see Memory management, below,
  912. and also read structure.doc's discussion of virtual array handling).  Or,
  913. for simple transcoding to a different JPEG file format, the array list can
  914. just be handed directly to jpeg_write_coefficients().
  915. When you are done using the virtual arrays, call jpeg_finish_decompress()
  916. to release the array storage and return the decompression object to an idle
  917. state; or just call jpeg_destroy() if you don't need to reuse the object.
  918. If you use a suspending data source, jpeg_read_coefficients() will return
  919. NULL if it is forced to suspend; a non-NULL return value indicates successful
  920. completion.  You need not test for a NULL return value when using a
  921. non-suspending data source.
  922. Each block in the block arrays contains quantized coefficient values in
  923. normal array order (not JPEG zigzag order).  The block arrays contain only
  924. DCT blocks containing real data; any entirely-dummy blocks added to fill out
  925. interleaved MCUs at the right or bottom edges of the image are discarded
  926. during reading and are not stored in the block arrays.  (The size of each
  927. block array can be determined from the width_in_blocks and height_in_blocks
  928. fields of the component's comp_info entry.)  This is also the data format
  929. expected by jpeg_write_coefficients().
  930. To write the contents of a JPEG file as DCT coefficients, you must provide
  931. the DCT coefficients stored in virtual block arrays.  You can either pass
  932. block arrays read from an input JPEG file by jpeg_read_coefficients(), or
  933. allocate virtual arrays from the JPEG compression object and fill them
  934. yourself.  In either case, jpeg_write_coefficients() is substituted for
  935. jpeg_start_compress() and jpeg_write_scanlines().  Thus the sequence is
  936.   * Create compression object
  937.   * Set all compression parameters as necessary
  938.   * Request virtual arrays if needed
  939.   * jpeg_write_coefficients()
  940.   * jpeg_finish_compress()
  941.   * Destroy or re-use compression object
  942. jpeg_write_coefficients() is passed a pointer to an array of virtual block
  943. array descriptors; the number of arrays is equal to cinfo.num_components.
  944. The virtual arrays need only have been requested, not realized, before
  945. jpeg_write_coefficients() is called.  A side-effect of
  946. jpeg_write_coefficients() is to realize any virtual arrays that have been
  947. requested from the compression object's memory manager.  Thus, when obtaining
  948. the virtual arrays from the compression object, you should fill the arrays
  949. after calling jpeg_write_coefficients().  The data is actually written out
  950. when you call jpeg_finish_compress(); jpeg_write_coefficients() only writes
  951. the file header.
  952. When writing raw DCT coefficients, it is crucial that the JPEG quantization
  953. tables and sampling factors match the way the data was encoded, or the
  954. resulting file will be invalid.  For transcoding from an existing JPEG file,
  955. we recommend using jpeg_copy_critical_parameters().  This routine initializes
  956. all the compression parameters to default values (like jpeg_set_defaults()),
  957. then copies the critical information from a source decompression object.
  958. The decompression object should have just been used to read the entire
  959. JPEG input file --- that is, it should be awaiting jpeg_finish_decompress().
  960. jpeg_write_coefficients() marks all tables stored in the compression object
  961. as needing to be written to the output file (thus, it acts like
  962. jpeg_start_compress(cinfo, TRUE)).  This is for safety's sake, to avoid
  963. emitting abbreviated JPEG files by accident.  If you really want to emit an
  964. abbreviated JPEG file, call jpeg_suppress_tables(), or set the tables'
  965. individual sent_table flags, between calling jpeg_write_coefficients() and
  966. jpeg_finish_compress().
  967. Progress monitoring
  968. -------------------
  969. Some applications may need to regain control from the JPEG library every so
  970. often.  The typical use of this feature is to produce a percent-done bar or
  971. other progress display.  (For a simple example, see cjpeg.c or djpeg.c.)
  972. Although you do get control back frequently during the data-transferring pass
  973. (the jpeg_read_scanlines or jpeg_write_scanlines loop), any additional passes
  974. will occur inside jpeg_finish_compress or jpeg_start_decompress; those
  975. routines may take a long time to execute, and you don't get control back
  976. until they are done.
  977. You can define a progress-monitor routine which will be called periodically
  978. by the library.  No guarantees are made about how often this call will occur,
  979. so we don't recommend you use it for mouse tracking or anything like that.
  980. At present, a call will occur once per MCU row, scanline, or sample row
  981. group, whichever unit is convenient for the current processing mode; so the
  982. wider the image, the longer the time between calls.  During the data
  983. transferring pass, only one call occurs per call of jpeg_read_scanlines or
  984. jpeg_write_scanlines, so don't pass a large number of scanlines at once if
  985. you want fine resolution in the progress count.  (If you really need to use
  986. the callback mechanism for time-critical tasks like mouse tracking, you could
  987. insert additional calls inside some of the library's inner loops.)
  988. To establish a progress-monitor callback, create a struct jpeg_progress_mgr,
  989. fill in its progress_monitor field with a pointer to your callback routine,
  990. and set cinfo->progress to point to the struct.  The callback will be called
  991. whenever cinfo->progress is non-NULL.  (This pointer is set to NULL by
  992. jpeg_create_compress or jpeg_create_decompress; the library will not change
  993. it thereafter.  So if you allocate dynamic storage for the progress struct,
  994. make sure it will live as long as the JPEG object does.  Allocating from the
  995. JPEG memory manager with lifetime JPOOL_PERMANENT will work nicely.)  You
  996. can use the same callback routine for both compression and decompression.
  997. The jpeg_progress_mgr struct contains four fields which are set by the library:
  998. long pass_counter; /* work units completed in this pass */
  999. long pass_limit; /* total number of work units in this pass */
  1000. int completed_passes; /* passes completed so far */
  1001. int total_passes; /* total number of passes expected */
  1002. During any one pass, pass_counter increases from 0 up to (not including)
  1003. pass_limit; the step size is usually but not necessarily 1.  The pass_limit
  1004. value may change from one pass to another.  The expected total number of
  1005. passes is in total_passes, and the number of passes already completed is in
  1006. completed_passes.  Thus the fraction of work completed may be estimated as
  1007. completed_passes + (pass_counter/pass_limit)
  1008. --------------------------------------------
  1009. total_passes
  1010. ignoring the fact that the passes may not be equal amounts of work.
  1011. When decompressing, pass_limit can even change within a pass, because it
  1012. depends on the number of scans in the JPEG file, which isn't always known in
  1013. advance.  The computed fraction-of-work-done may jump suddenly (if the library
  1014. discovers it has overestimated the number of scans) or even decrease (in the
  1015. opposite case).  It is not wise to put great faith in the work estimate.
  1016. When using the decompressor's buffered-image mode, the progress monitor work
  1017. estimate is likely to be completely unhelpful, because the library has no way
  1018. to know how many output passes will be demanded of it.  Currently, the library
  1019. sets total_passes based on the assumption that there will be one more output
  1020. pass if the input file end hasn't yet been read (jpeg_input_complete() isn't
  1021. TRUE), but no more output passes if the file end has been reached when the
  1022. output pass is started.  This means that total_passes will rise as additional
  1023. output passes are requested.  If you have a way of determining the input file
  1024. size, estimating progress based on the fraction of the file that's been read
  1025. will probably be more useful than using the library's value.
  1026. Memory management
  1027. -----------------
  1028. This section covers some key facts about the JPEG library's built-in memory
  1029. manager.  For more info, please read structure.doc's section about the memory
  1030. manager, and consult the source code if necessary.
  1031. All memory and temporary file allocation within the library is done via the
  1032. memory manager.  If necessary, you can replace the "back end" of the memory
  1033. manager to control allocation yourself (for example, if you don't want the
  1034. library to use malloc() and free() for some reason).
  1035. Some data is allocated "permanently" and will not be freed until the JPEG
  1036. object is destroyed.  Most data is allocated "per image" and is freed by
  1037. jpeg_finish_compress, jpeg_finish_decompress, or jpeg_abort.  You can call the
  1038. memory manager yourself to allocate structures that will automatically be
  1039. freed at these times.  Typical code for this is
  1040.   ptr = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, size);
  1041. Use JPOOL_PERMANENT to get storage that lasts as long as the JPEG object.
  1042. Use alloc_large instead of alloc_small for anything bigger than a few Kbytes.
  1043. There are also alloc_sarray and alloc_barray routines that automatically
  1044. build 2-D sample or block arrays.
  1045. The library's minimum space requirements to process an image depend on the
  1046. image's width, but not on its height, because the library ordinarily works
  1047. with "strip" buffers that are as wide as the image but just a few rows high.
  1048. Some operating modes (eg, two-pass color quantization) require full-image
  1049. buffers.  Such buffers are treated as "virtual arrays": only the current strip
  1050. need be in memory, and the rest can be swapped out to a temporary file.
  1051. If you use the simplest memory manager back end (jmemnobs.c), then no
  1052. temporary files are used; virtual arrays are simply malloc()'d.  Images bigger
  1053. than memory can be processed only if your system supports virtual memory.
  1054. The other memory manager back ends support temporary files of various flavors
  1055. and thus work in machines without virtual memory.  They may also be useful on
  1056. Unix machines if you need to process images that exceed available swap space.
  1057. When using temporary files, the library will make the in-memory buffers for
  1058. its virtual arrays just big enough to stay within a "maximum memory" setting.
  1059. Your application can set this limit by setting cinfo->mem->max_memory_to_use
  1060. after creating the JPEG object.  (Of course, there is still a minimum size for
  1061. the buffers, so the max-memory setting is effective only if it is bigger than
  1062. the minimum space needed.)  If you allocate any large structures yourself, you
  1063. must allocate them before jpeg_start_compress() or jpeg_start_decompress() in
  1064. order to have them counted against the max memory limit.  Also keep in mind
  1065. that space allocated with alloc_small() is ignored, on the assumption that
  1066. it's too small to be worth worrying about; so a reasonable safety margin
  1067. should be left when setting max_memory_to_use.
  1068. If you use the jmemname.c or jmemdos.c memory manager back end, it is
  1069. important to clean up the JPEG object properly to ensure that the temporary
  1070. files get deleted.  (This is especially crucial with jmemdos.c, where the
  1071. "temporary files" may be extended-memory segments; if they are not freed,
  1072. DOS will require a reboot to recover the memory.)  Thus, with these memory
  1073. managers, it's a good idea to provide a signal handler that will trap any
  1074. early exit from your program.  The handler should call either jpeg_abort()
  1075. or jpeg_destroy() for any active JPEG objects.  A handler is not needed with
  1076. jmemnobs.c, and shouldn't be necessary with jmemansi.c either, since the C
  1077. library is supposed to take care of deleting files made with tmpfile().
  1078. Library compile-time options
  1079. ----------------------------
  1080. A number of compile-time options are available by modifying jmorecfg.h.
  1081. The JPEG standard provides for both the baseline 8-bit DCT process and
  1082. a 12-bit DCT process.  12-bit lossy JPEG is supported if you define
  1083. BITS_IN_JSAMPLE as 12 rather than 8.  Note that this causes JSAMPLE to be
  1084. larger than a char, so it affects the surrounding application's image data.
  1085. The sample applications cjpeg and djpeg can support 12-bit mode only for PPM
  1086. and GIF file formats; you must disable the other file formats to compile a
  1087. 12-bit cjpeg or djpeg.  (install.doc has more information about that.)
  1088. At present, a 12-bit library can handle *only* 12-bit images, not both
  1089. precisions.  (If you need to include both 8- and 12-bit libraries in a single
  1090. application, you could probably do it by defining NEED_SHORT_EXTERNAL_NAMES
  1091. for just one of the copies.  You'd have to access the 8-bit and 12-bit copies
  1092. from separate application source files.  This is untested ... if you try it,
  1093. we'd like to hear whether it works!)
  1094. Note that a 12-bit library always compresses in Huffman optimization mode,
  1095. in order to generate valid Huffman tables.  This is necessary because our
  1096. default Huffman tables only cover 8-bit data.  If you need to output 12-bit
  1097. files in one pass, you'll have to supply suitable default Huffman tables.
  1098. The maximum number of components (color channels) in the image is determined
  1099. by MAX_COMPONENTS.  The JPEG standard allows up to 255 components, but we
  1100. expect that few applications will need more than four or so.
  1101. On machines with unusual data type sizes, you may be able to improve
  1102. performance or reduce memory space by tweaking the various typedefs in
  1103. jmorecfg.h.  In particular, on some RISC CPUs, access to arrays of "short"s
  1104. is quite slow; consider trading memory for speed by making JCOEF, INT16, and
  1105. UINT16 be "int" or "unsigned int".  UINT8 is also a candidate to become int.
  1106. You probably don't want to make JSAMPLE be int unless you have lots of memory
  1107. to burn.
  1108. You can reduce the size of the library by compiling out various optional
  1109. functions.  To do this, undefine xxx_SUPPORTED symbols as necessary.
  1110. Portability considerations
  1111. --------------------------
  1112. The JPEG library has been written to be extremely portable; the sample
  1113. applications cjpeg and djpeg are slightly less so.  This section summarizes
  1114. the design goals in this area.  (If you encounter any bugs that cause the
  1115. library to be less portable than is claimed here, we'd appreciate hearing
  1116. about them.)
  1117. The code works fine on both ANSI and pre-ANSI C compilers, using any of the
  1118. popular system include file setups, and some not-so-popular ones too.  See
  1119. install.doc for configuration procedures.
  1120. The code is not dependent on the exact sizes of the C data types.  As
  1121. distributed, we make the assumptions that
  1122. char is at least 8 bits wide
  1123. short is at least 16 bits wide
  1124. int is at least 16 bits wide
  1125. long is at least 32 bits wide
  1126. (These are the minimum requirements of the ANSI C standard.)  Wider types will
  1127. work fine, although memory may be used inefficiently if char is much larger
  1128. than 8 bits or short is much bigger than 16 bits.  The code should work
  1129. equally well with 16- or 32-bit ints.
  1130. In a system where these assumptions are not met, you may be able to make the
  1131. code work by modifying the typedefs in jmorecfg.h.  However, you will probably
  1132. have difficulty if int is less than 16 bits wide, since references to plain
  1133. int abound in the code.
  1134. char can be either signed or unsigned, although the code runs faster if an
  1135. unsigned char type is available.  If char is wider than 8 bits, you will need
  1136. to redefine JOCTET and/or provide custom data source/destination managers so
  1137. that JOCTET represents exactly 8 bits of data on external storage.
  1138. The JPEG library proper does not assume ASCII representation of characters.
  1139. But some of the image file I/O modules in cjpeg/djpeg do have ASCII
  1140. dependencies in file-header manipulation; so does cjpeg's select_file_type()
  1141. routine.
  1142. The JPEG library does not rely heavily on the C library.  In particular, C
  1143. stdio is used only by the data source/destination modules and the error
  1144. handler, all of which are application-replaceable.  (cjpeg/djpeg are more
  1145. heavily dependent on stdio.)  malloc and free are called only from the memory
  1146. manager "back end" module, so you can use a different memory allocator by
  1147. replacing that one file.
  1148. The code generally assumes that C names must be unique in the first 15
  1149. characters.  However, global function names can be made unique in the
  1150. first 6 characters by defining NEED_SHORT_EXTERNAL_NAMES.
  1151. More info about porting the code may be gleaned by reading jconfig.doc,
  1152. jmorecfg.h, and jinclude.h.
  1153. Notes for MS-DOS implementors
  1154. -----------------------------
  1155. The IJG code is designed to work efficiently in 80x86 "small" or "medium"
  1156. memory models (i.e., data pointers are 16 bits unless explicitly declared
  1157. "far"; code pointers can be either size).  You may be able to use small
  1158. model to compile cjpeg or djpeg by itself, but you will probably have to use
  1159. medium model for any larger application.  This won't make much difference in
  1160. performance.  You *will* take a noticeable performance hit if you use a
  1161. large-data memory model (perhaps 10%-25%), and you should avoid "huge" model
  1162. if at all possible.
  1163. The JPEG library typically needs 2Kb-3Kb of stack space.  It will also
  1164. malloc about 20K-30K of near heap space while executing (and lots of far
  1165. heap, but that doesn't count in this calculation).  This figure will vary
  1166. depending on selected operating mode, and to a lesser extent on image size.
  1167. There is also about 5Kb-6Kb of constant data which will be allocated in the
  1168. near data segment (about 4Kb of this is the error message table).
  1169. Thus you have perhaps 20K available for other modules' static data and near
  1170. heap space before you need to go to a larger memory model.  The C library's
  1171. static data will account for several K of this, but that still leaves a good
  1172. deal for your needs.  (If you are tight on space, you could reduce the sizes
  1173. of the I/O buffers allocated by jdatasrc.c and jdatadst.c, say from 4K to
  1174. 1K.  Another possibility is to move the error message table to far memory;
  1175. this should be doable with only localized hacking on jerror.c.)
  1176. About 2K of the near heap space is "permanent" memory that will not be
  1177. released until you destroy the JPEG object.  This is only an issue if you
  1178. save a JPEG object between compression or decompression operations.
  1179. Far data space may also be a tight resource when you are dealing with large
  1180. images.  The most memory-intensive case is decompression with two-pass color
  1181. quantization, or single-pass quantization to an externally supplied color
  1182. map.  This requires a 128Kb color lookup table plus strip buffers amounting
  1183. to about 50 bytes per column for typical sampling ratios (eg, about 32000
  1184. bytes for a 640-pixel-wide image).  You may not be able to process wide
  1185. images if you have large data structures of your own.
  1186. Of course, all of these concerns vanish if you use a 32-bit flat-memory-model
  1187. compiler, such as DJGPP or Watcom C.  We highly recommend flat model if you
  1188. can use it; the JPEG library is significantly faster in flat model.