/src/FreeImage/Source/LibJPEG/libjpeg.txt

https://bitbucket.org/cabalistic/ogredeps/ · Plain Text · 3085 lines · 2576 code · 509 blank · 0 comment · 0 complexity · 38da6f995510b093dc35a44e292db67a MD5 · raw file

Large files are truncated click here to view the full file

  1. USING THE IJG JPEG LIBRARY
  2. Copyright (C) 1994-2011, Thomas G. Lane, Guido Vollbeding.
  3. This file is part of the Independent JPEG Group's software.
  4. For conditions of distribution and use, see the accompanying README file.
  5. This file describes how to use the IJG JPEG library within an application
  6. program. Read it if you want to write a program that uses the library.
  7. The file example.c provides heavily commented skeleton code for calling the
  8. JPEG library. Also see jpeglib.h (the include file to be used by application
  9. programs) for full details about data structures and function parameter lists.
  10. The library source code, of course, is the ultimate reference.
  11. Note that there have been *major* changes from the application interface
  12. presented by IJG version 4 and earlier versions. The old design had several
  13. inherent limitations, and it had accumulated a lot of cruft as we added
  14. features while trying to minimize application-interface changes. We have
  15. sacrificed backward compatibility in the version 5 rewrite, but we think the
  16. improvements justify this.
  17. TABLE OF CONTENTS
  18. -----------------
  19. Overview:
  20. Functions provided by the library
  21. Outline of typical usage
  22. Basic library usage:
  23. Data formats
  24. Compression details
  25. Decompression details
  26. Mechanics of usage: include files, linking, etc
  27. Advanced features:
  28. Compression parameter selection
  29. Decompression parameter selection
  30. Special color spaces
  31. Error handling
  32. Compressed data handling (source and destination managers)
  33. I/O suspension
  34. Progressive JPEG support
  35. Buffered-image mode
  36. Abbreviated datastreams and multiple images
  37. Special markers
  38. Raw (downsampled) image data
  39. Really raw data: DCT coefficients
  40. Progress monitoring
  41. Memory management
  42. Memory usage
  43. Library compile-time options
  44. Portability considerations
  45. Notes for MS-DOS implementors
  46. You should read at least the overview and basic usage sections before trying
  47. to program with the library. The sections on advanced features can be read
  48. if and when you need them.
  49. OVERVIEW
  50. ========
  51. Functions provided by the library
  52. ---------------------------------
  53. The IJG JPEG library provides C code to read and write JPEG-compressed image
  54. files. The surrounding application program receives or supplies image data a
  55. scanline at a time, using a straightforward uncompressed image format. All
  56. details of color conversion and other preprocessing/postprocessing can be
  57. handled by the library.
  58. The library includes a substantial amount of code that is not covered by the
  59. JPEG standard but is necessary for typical applications of JPEG. These
  60. functions preprocess the image before JPEG compression or postprocess it after
  61. decompression. They include colorspace conversion, downsampling/upsampling,
  62. and color quantization. The application indirectly selects use of this code
  63. by specifying the format in which it wishes to supply or receive image data.
  64. For example, if colormapped output is requested, then the decompression
  65. library automatically invokes color quantization.
  66. A wide range of quality vs. speed tradeoffs are possible in JPEG processing,
  67. and even more so in decompression postprocessing. The decompression library
  68. provides multiple implementations that cover most of the useful tradeoffs,
  69. ranging from very-high-quality down to fast-preview operation. On the
  70. compression side we have generally not provided low-quality choices, since
  71. compression is normally less time-critical. It should be understood that the
  72. low-quality modes may not meet the JPEG standard's accuracy requirements;
  73. nonetheless, they are useful for viewers.
  74. A word about functions *not* provided by the library. We handle a subset of
  75. the ISO JPEG standard; most baseline, extended-sequential, and progressive
  76. JPEG processes are supported. (Our subset includes all features now in common
  77. use.) Unsupported ISO options include:
  78. * Hierarchical storage
  79. * Lossless JPEG
  80. * DNL marker
  81. * Nonintegral subsampling ratios
  82. We support both 8- and 12-bit data precision, but this is a compile-time
  83. choice rather than a run-time choice; hence it is difficult to use both
  84. precisions in a single application.
  85. By itself, the library handles only interchange JPEG datastreams --- in
  86. particular the widely used JFIF file format. The library can be used by
  87. surrounding code to process interchange or abbreviated JPEG datastreams that
  88. are embedded in more complex file formats. (For example, this library is
  89. used by the free LIBTIFF library to support JPEG compression in TIFF.)
  90. Outline of typical usage
  91. ------------------------
  92. The rough outline of a JPEG compression operation is:
  93. Allocate and initialize a JPEG compression object
  94. Specify the destination for the compressed data (eg, a file)
  95. Set parameters for compression, including image size & colorspace
  96. jpeg_start_compress(...);
  97. while (scan lines remain to be written)
  98. jpeg_write_scanlines(...);
  99. jpeg_finish_compress(...);
  100. Release the JPEG compression object
  101. A JPEG compression object holds parameters and working state for the JPEG
  102. library. We make creation/destruction of the object separate from starting
  103. or finishing compression of an image; the same object can be re-used for a
  104. series of image compression operations. This makes it easy to re-use the
  105. same parameter settings for a sequence of images. Re-use of a JPEG object
  106. also has important implications for processing abbreviated JPEG datastreams,
  107. as discussed later.
  108. The image data to be compressed is supplied to jpeg_write_scanlines() from
  109. in-memory buffers. If the application is doing file-to-file compression,
  110. reading image data from the source file is the application's responsibility.
  111. The library emits compressed data by calling a "data destination manager",
  112. which typically will write the data into a file; but the application can
  113. provide its own destination manager to do something else.
  114. Similarly, the rough outline of a JPEG decompression operation is:
  115. Allocate and initialize a JPEG decompression object
  116. Specify the source of the compressed data (eg, a file)
  117. Call jpeg_read_header() to obtain image info
  118. Set parameters for decompression
  119. jpeg_start_decompress(...);
  120. while (scan lines remain to be read)
  121. jpeg_read_scanlines(...);
  122. jpeg_finish_decompress(...);
  123. Release the JPEG decompression object
  124. This is comparable to the compression outline except that reading the
  125. datastream header is a separate step. This is helpful because information
  126. about the image's size, colorspace, etc is available when the application
  127. selects decompression parameters. For example, the application can choose an
  128. output scaling ratio that will fit the image into the available screen size.
  129. The decompression library obtains compressed data by calling a data source
  130. manager, which typically will read the data from a file; but other behaviors
  131. can be obtained with a custom source manager. Decompressed data is delivered
  132. into in-memory buffers passed to jpeg_read_scanlines().
  133. It is possible to abort an incomplete compression or decompression operation
  134. by calling jpeg_abort(); or, if you do not need to retain the JPEG object,
  135. simply release it by calling jpeg_destroy().
  136. JPEG compression and decompression objects are two separate struct types.
  137. However, they share some common fields, and certain routines such as
  138. jpeg_destroy() can work on either type of object.
  139. The JPEG library has no static variables: all state is in the compression
  140. or decompression object. Therefore it is possible to process multiple
  141. compression and decompression operations concurrently, using multiple JPEG
  142. objects.
  143. Both compression and decompression can be done in an incremental memory-to-
  144. memory fashion, if suitable source/destination managers are used. See the
  145. section on "I/O suspension" for more details.
  146. BASIC LIBRARY USAGE
  147. ===================
  148. Data formats
  149. ------------
  150. Before diving into procedural details, it is helpful to understand the
  151. image data format that the JPEG library expects or returns.
  152. The standard input image format is a rectangular array of pixels, with each
  153. pixel having the same number of "component" or "sample" values (color
  154. channels). You must specify how many components there are and the colorspace
  155. interpretation of the components. Most applications will use RGB data
  156. (three components per pixel) or grayscale data (one component per pixel).
  157. PLEASE NOTE THAT RGB DATA IS THREE SAMPLES PER PIXEL, GRAYSCALE ONLY ONE.
  158. A remarkable number of people manage to miss this, only to find that their
  159. programs don't work with grayscale JPEG files.
  160. There is no provision for colormapped input. JPEG files are always full-color
  161. or full grayscale (or sometimes another colorspace such as CMYK). You can
  162. feed in a colormapped image by expanding it to full-color format. However
  163. JPEG often doesn't work very well with source data that has been colormapped,
  164. because of dithering noise. This is discussed in more detail in the JPEG FAQ
  165. and the other references mentioned in the README file.
  166. Pixels are stored by scanlines, with each scanline running from left to
  167. right. The component values for each pixel are adjacent in the row; for
  168. example, R,G,B,R,G,B,R,G,B,... for 24-bit RGB color. Each scanline is an
  169. array of data type JSAMPLE --- which is typically "unsigned char", unless
  170. you've changed jmorecfg.h. (You can also change the RGB pixel layout, say
  171. to B,G,R order, by modifying jmorecfg.h. But see the restrictions listed in
  172. that file before doing so.)
  173. A 2-D array of pixels is formed by making a list of pointers to the starts of
  174. scanlines; so the scanlines need not be physically adjacent in memory. Even
  175. if you process just one scanline at a time, you must make a one-element
  176. pointer array to conform to this structure. Pointers to JSAMPLE rows are of
  177. type JSAMPROW, and the pointer to the pointer array is of type JSAMPARRAY.
  178. The library accepts or supplies one or more complete scanlines per call.
  179. It is not possible to process part of a row at a time. Scanlines are always
  180. processed top-to-bottom. You can process an entire image in one call if you
  181. have it all in memory, but usually it's simplest to process one scanline at
  182. a time.
  183. For best results, source data values should have the precision specified by
  184. BITS_IN_JSAMPLE (normally 8 bits). For instance, if you choose to compress
  185. data that's only 6 bits/channel, you should left-justify each value in a
  186. byte before passing it to the compressor. If you need to compress data
  187. that has more than 8 bits/channel, compile with BITS_IN_JSAMPLE = 12.
  188. (See "Library compile-time options", later.)
  189. The data format returned by the decompressor is the same in all details,
  190. except that colormapped output is supported. (Again, a JPEG file is never
  191. colormapped. But you can ask the decompressor to perform on-the-fly color
  192. quantization to deliver colormapped output.) If you request colormapped
  193. output then the returned data array contains a single JSAMPLE per pixel;
  194. its value is an index into a color map. The color map is represented as
  195. a 2-D JSAMPARRAY in which each row holds the values of one color component,
  196. that is, colormap[i][j] is the value of the i'th color component for pixel
  197. value (map index) j. Note that since the colormap indexes are stored in
  198. JSAMPLEs, the maximum number of colors is limited by the size of JSAMPLE
  199. (ie, at most 256 colors for an 8-bit JPEG library).
  200. Compression details
  201. -------------------
  202. Here we revisit the JPEG compression outline given in the overview.
  203. 1. Allocate and initialize a JPEG compression object.
  204. A JPEG compression object is a "struct jpeg_compress_struct". (It also has
  205. a bunch of subsidiary structures which are allocated via malloc(), but the
  206. application doesn't control those directly.) This struct can be just a local
  207. variable in the calling routine, if a single routine is going to execute the
  208. whole JPEG compression sequence. Otherwise it can be static or allocated
  209. from malloc().
  210. You will also need a structure representing a JPEG error handler. The part
  211. of this that the library cares about is a "struct jpeg_error_mgr". If you
  212. are providing your own error handler, you'll typically want to embed the
  213. jpeg_error_mgr struct in a larger structure; this is discussed later under
  214. "Error handling". For now we'll assume you are just using the default error
  215. handler. The default error handler will print JPEG error/warning messages
  216. on stderr, and it will call exit() if a fatal error occurs.
  217. You must initialize the error handler structure, store a pointer to it into
  218. the JPEG object's "err" field, and then call jpeg_create_compress() to
  219. initialize the rest of the JPEG object.
  220. Typical code for this step, if you are using the default error handler, is
  221. struct jpeg_compress_struct cinfo;
  222. struct jpeg_error_mgr jerr;
  223. ...
  224. cinfo.err = jpeg_std_error(&jerr);
  225. jpeg_create_compress(&cinfo);
  226. jpeg_create_compress allocates a small amount of memory, so it could fail
  227. if you are out of memory. In that case it will exit via the error handler;
  228. that's why the error handler must be initialized first.
  229. 2. Specify the destination for the compressed data (eg, a file).
  230. As previously mentioned, the JPEG library delivers compressed data to a
  231. "data destination" module. The library includes one data destination
  232. module which knows how to write to a stdio stream. You can use your own
  233. destination module if you want to do something else, as discussed later.
  234. If you use the standard destination module, you must open the target stdio
  235. stream beforehand. Typical code for this step looks like:
  236. FILE * outfile;
  237. ...
  238. if ((outfile = fopen(filename, "wb")) == NULL) {
  239. fprintf(stderr, "can't open %s\n", filename);
  240. exit(1);
  241. }
  242. jpeg_stdio_dest(&cinfo, outfile);
  243. where the last line invokes the standard destination module.
  244. WARNING: it is critical that the binary compressed data be delivered to the
  245. output file unchanged. On non-Unix systems the stdio library may perform
  246. newline translation or otherwise corrupt binary data. To suppress this
  247. behavior, you may need to use a "b" option to fopen (as shown above), or use
  248. setmode() or another routine to put the stdio stream in binary mode. See
  249. cjpeg.c and djpeg.c for code that has been found to work on many systems.
  250. You can select the data destination after setting other parameters (step 3),
  251. if that's more convenient. You may not change the destination between
  252. calling jpeg_start_compress() and jpeg_finish_compress().
  253. 3. Set parameters for compression, including image size & colorspace.
  254. You must supply information about the source image by setting the following
  255. fields in the JPEG object (cinfo structure):
  256. image_width Width of image, in pixels
  257. image_height Height of image, in pixels
  258. input_components Number of color channels (samples per pixel)
  259. in_color_space Color space of source image
  260. The image dimensions are, hopefully, obvious. JPEG supports image dimensions
  261. of 1 to 64K pixels in either direction. The input color space is typically
  262. RGB or grayscale, and input_components is 3 or 1 accordingly. (See "Special
  263. color spaces", later, for more info.) The in_color_space field must be
  264. assigned one of the J_COLOR_SPACE enum constants, typically JCS_RGB or
  265. JCS_GRAYSCALE.
  266. JPEG has a large number of compression parameters that determine how the
  267. image is encoded. Most applications don't need or want to know about all
  268. these parameters. You can set all the parameters to reasonable defaults by
  269. calling jpeg_set_defaults(); then, if there are particular values you want
  270. to change, you can do so after that. The "Compression parameter selection"
  271. section tells about all the parameters.
  272. You must set in_color_space correctly before calling jpeg_set_defaults(),
  273. because the defaults depend on the source image colorspace. However the
  274. other three source image parameters need not be valid until you call
  275. jpeg_start_compress(). There's no harm in calling jpeg_set_defaults() more
  276. than once, if that happens to be convenient.
  277. Typical code for a 24-bit RGB source image is
  278. cinfo.image_width = Width; /* image width and height, in pixels */
  279. cinfo.image_height = Height;
  280. cinfo.input_components = 3; /* # of color components per pixel */
  281. cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
  282. jpeg_set_defaults(&cinfo);
  283. /* Make optional parameter settings here */
  284. 4. jpeg_start_compress(...);
  285. After you have established the data destination and set all the necessary
  286. source image info and other parameters, call jpeg_start_compress() to begin
  287. a compression cycle. This will initialize internal state, allocate working
  288. storage, and emit the first few bytes of the JPEG datastream header.
  289. Typical code:
  290. jpeg_start_compress(&cinfo, TRUE);
  291. The "TRUE" parameter ensures that a complete JPEG interchange datastream
  292. will be written. This is appropriate in most cases. If you think you might
  293. want to use an abbreviated datastream, read the section on abbreviated
  294. datastreams, below.
  295. Once you have called jpeg_start_compress(), you may not alter any JPEG
  296. parameters or other fields of the JPEG object until you have completed
  297. the compression cycle.
  298. 5. while (scan lines remain to be written)
  299. jpeg_write_scanlines(...);
  300. Now write all the required image data by calling jpeg_write_scanlines()
  301. one or more times. You can pass one or more scanlines in each call, up
  302. to the total image height. In most applications it is convenient to pass
  303. just one or a few scanlines at a time. The expected format for the passed
  304. data is discussed under "Data formats", above.
  305. Image data should be written in top-to-bottom scanline order. The JPEG spec
  306. contains some weasel wording about how top and bottom are application-defined
  307. terms (a curious interpretation of the English language...) but if you want
  308. your files to be compatible with everyone else's, you WILL use top-to-bottom
  309. order. If the source data must be read in bottom-to-top order, you can use
  310. the JPEG library's virtual array mechanism to invert the data efficiently.
  311. Examples of this can be found in the sample application cjpeg.
  312. The library maintains a count of the number of scanlines written so far
  313. in the next_scanline field of the JPEG object. Usually you can just use
  314. this variable as the loop counter, so that the loop test looks like
  315. "while (cinfo.next_scanline < cinfo.image_height)".
  316. Code for this step depends heavily on the way that you store the source data.
  317. example.c shows the following code for the case of a full-size 2-D source
  318. array containing 3-byte RGB pixels:
  319. JSAMPROW row_pointer[1]; /* pointer to a single row */
  320. int row_stride; /* physical row width in buffer */
  321. row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */
  322. while (cinfo.next_scanline < cinfo.image_height) {
  323. row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
  324. jpeg_write_scanlines(&cinfo, row_pointer, 1);
  325. }
  326. jpeg_write_scanlines() returns the number of scanlines actually written.
  327. This will normally be equal to the number passed in, so you can usually
  328. ignore the return value. It is different in just two cases:
  329. * If you try to write more scanlines than the declared image height,
  330. the additional scanlines are ignored.
  331. * If you use a suspending data destination manager, output buffer overrun
  332. will cause the compressor to return before accepting all the passed lines.
  333. This feature is discussed under "I/O suspension", below. The normal
  334. stdio destination manager will NOT cause this to happen.
  335. In any case, the return value is the same as the change in the value of
  336. next_scanline.
  337. 6. jpeg_finish_compress(...);
  338. After all the image data has been written, call jpeg_finish_compress() to
  339. complete the compression cycle. This step is ESSENTIAL to ensure that the
  340. last bufferload of data is written to the data destination.
  341. jpeg_finish_compress() also releases working memory associated with the JPEG
  342. object.
  343. Typical code:
  344. jpeg_finish_compress(&cinfo);
  345. If using the stdio destination manager, don't forget to close the output
  346. stdio stream (if necessary) afterwards.
  347. If you have requested a multi-pass operating mode, such as Huffman code
  348. optimization, jpeg_finish_compress() will perform the additional passes using
  349. data buffered by the first pass. In this case jpeg_finish_compress() may take
  350. quite a while to complete. With the default compression parameters, this will
  351. not happen.
  352. It is an error to call jpeg_finish_compress() before writing the necessary
  353. total number of scanlines. If you wish to abort compression, call
  354. jpeg_abort() as discussed below.
  355. After completing a compression cycle, you may dispose of the JPEG object
  356. as discussed next, or you may use it to compress another image. In that case
  357. return to step 2, 3, or 4 as appropriate. If you do not change the
  358. destination manager, the new datastream will be written to the same target.
  359. If you do not change any JPEG parameters, the new datastream will be written
  360. with the same parameters as before. Note that you can change the input image
  361. dimensions freely between cycles, but if you change the input colorspace, you
  362. should call jpeg_set_defaults() to adjust for the new colorspace; and then
  363. you'll need to repeat all of step 3.
  364. 7. Release the JPEG compression object.
  365. When you are done with a JPEG compression object, destroy it by calling
  366. jpeg_destroy_compress(). This will free all subsidiary memory (regardless of
  367. the previous state of the object). Or you can call jpeg_destroy(), which
  368. works for either compression or decompression objects --- this may be more
  369. convenient if you are sharing code between compression and decompression
  370. cases. (Actually, these routines are equivalent except for the declared type
  371. of the passed pointer. To avoid gripes from ANSI C compilers, jpeg_destroy()
  372. should be passed a j_common_ptr.)
  373. If you allocated the jpeg_compress_struct structure from malloc(), freeing
  374. it is your responsibility --- jpeg_destroy() won't. Ditto for the error
  375. handler structure.
  376. Typical code:
  377. jpeg_destroy_compress(&cinfo);
  378. 8. Aborting.
  379. If you decide to abort a compression cycle before finishing, you can clean up
  380. in either of two ways:
  381. * If you don't need the JPEG object any more, just call
  382. jpeg_destroy_compress() or jpeg_destroy() to release memory. This is
  383. legitimate at any point after calling jpeg_create_compress() --- in fact,
  384. it's safe even if jpeg_create_compress() fails.
  385. * If you want to re-use the JPEG object, call jpeg_abort_compress(), or call
  386. jpeg_abort() which works on both compression and decompression objects.
  387. This will return the object to an idle state, releasing any working memory.
  388. jpeg_abort() is allowed at any time after successful object creation.
  389. Note that cleaning up the data destination, if required, is your
  390. responsibility; neither of these routines will call term_destination().
  391. (See "Compressed data handling", below, for more about that.)
  392. jpeg_destroy() and jpeg_abort() are the only safe calls to make on a JPEG
  393. object that has reported an error by calling error_exit (see "Error handling"
  394. for more info). The internal state of such an object is likely to be out of
  395. whack. Either of these two routines will return the object to a known state.
  396. Decompression details
  397. ---------------------
  398. Here we revisit the JPEG decompression outline given in the overview.
  399. 1. Allocate and initialize a JPEG decompression object.
  400. This is just like initialization for compression, as discussed above,
  401. except that the object is a "struct jpeg_decompress_struct" and you
  402. call jpeg_create_decompress(). Error handling is exactly the same.
  403. Typical code:
  404. struct jpeg_decompress_struct cinfo;
  405. struct jpeg_error_mgr jerr;
  406. ...
  407. cinfo.err = jpeg_std_error(&jerr);
  408. jpeg_create_decompress(&cinfo);
  409. (Both here and in the IJG code, we usually use variable name "cinfo" for
  410. both compression and decompression objects.)
  411. 2. Specify the source of the compressed data (eg, a file).
  412. As previously mentioned, the JPEG library reads compressed data from a "data
  413. source" module. The library includes one data source module which knows how
  414. to read from a stdio stream. You can use your own source module if you want
  415. to do something else, as discussed later.
  416. If you use the standard source module, you must open the source stdio stream
  417. beforehand. Typical code for this step looks like:
  418. FILE * infile;
  419. ...
  420. if ((infile = fopen(filename, "rb")) == NULL) {
  421. fprintf(stderr, "can't open %s\n", filename);
  422. exit(1);
  423. }
  424. jpeg_stdio_src(&cinfo, infile);
  425. where the last line invokes the standard source module.
  426. WARNING: it is critical that the binary compressed data be read unchanged.
  427. On non-Unix systems the stdio library may perform newline translation or
  428. otherwise corrupt binary data. To suppress this behavior, you may need to use
  429. a "b" option to fopen (as shown above), or use setmode() or another routine to
  430. put the stdio stream in binary mode. See cjpeg.c and djpeg.c for code that
  431. has been found to work on many systems.
  432. You may not change the data source between calling jpeg_read_header() and
  433. jpeg_finish_decompress(). If you wish to read a series of JPEG images from
  434. a single source file, you should repeat the jpeg_read_header() to
  435. jpeg_finish_decompress() sequence without reinitializing either the JPEG
  436. object or the data source module; this prevents buffered input data from
  437. being discarded.
  438. 3. Call jpeg_read_header() to obtain image info.
  439. Typical code for this step is just
  440. jpeg_read_header(&cinfo, TRUE);
  441. This will read the source datastream header markers, up to the beginning
  442. of the compressed data proper. On return, the image dimensions and other
  443. info have been stored in the JPEG object. The application may wish to
  444. consult this information before selecting decompression parameters.
  445. More complex code is necessary if
  446. * A suspending data source is used --- in that case jpeg_read_header()
  447. may return before it has read all the header data. See "I/O suspension",
  448. below. The normal stdio source manager will NOT cause this to happen.
  449. * Abbreviated JPEG files are to be processed --- see the section on
  450. abbreviated datastreams. Standard applications that deal only in
  451. interchange JPEG files need not be concerned with this case either.
  452. It is permissible to stop at this point if you just wanted to find out the
  453. image dimensions and other header info for a JPEG file. In that case,
  454. call jpeg_destroy() when you are done with the JPEG object, or call
  455. jpeg_abort() to return it to an idle state before selecting a new data
  456. source and reading another header.
  457. 4. Set parameters for decompression.
  458. jpeg_read_header() sets appropriate default decompression parameters based on
  459. the properties of the image (in particular, its colorspace). However, you
  460. may well want to alter these defaults before beginning the decompression.
  461. For example, the default is to produce full color output from a color file.
  462. If you want colormapped output you must ask for it. Other options allow the
  463. returned image to be scaled and allow various speed/quality tradeoffs to be
  464. selected. "Decompression parameter selection", below, gives details.
  465. If the defaults are appropriate, nothing need be done at this step.
  466. Note that all default values are set by each call to jpeg_read_header().
  467. If you reuse a decompression object, you cannot expect your parameter
  468. settings to be preserved across cycles, as you can for compression.
  469. You must set desired parameter values each time.
  470. 5. jpeg_start_decompress(...);
  471. Once the parameter values are satisfactory, call jpeg_start_decompress() to
  472. begin decompression. This will initialize internal state, allocate working
  473. memory, and prepare for returning data.
  474. Typical code is just
  475. jpeg_start_decompress(&cinfo);
  476. If you have requested a multi-pass operating mode, such as 2-pass color
  477. quantization, jpeg_start_decompress() will do everything needed before data
  478. output can begin. In this case jpeg_start_decompress() may take quite a while
  479. to complete. With a single-scan (non progressive) JPEG file and default
  480. decompression parameters, this will not happen; jpeg_start_decompress() will
  481. return quickly.
  482. After this call, the final output image dimensions, including any requested
  483. scaling, are available in the JPEG object; so is the selected colormap, if
  484. colormapped output has been requested. Useful fields include
  485. output_width image width and height, as scaled
  486. output_height
  487. out_color_components # of color components in out_color_space
  488. output_components # of color components returned per pixel
  489. colormap the selected colormap, if any
  490. actual_number_of_colors number of entries in colormap
  491. output_components is 1 (a colormap index) when quantizing colors; otherwise it
  492. equals out_color_components. It is the number of JSAMPLE values that will be
  493. emitted per pixel in the output arrays.
  494. Typically you will need to allocate data buffers to hold the incoming image.
  495. You will need output_width * output_components JSAMPLEs per scanline in your
  496. output buffer, and a total of output_height scanlines will be returned.
  497. Note: if you are using the JPEG library's internal memory manager to allocate
  498. data buffers (as djpeg does), then the manager's protocol requires that you
  499. request large buffers *before* calling jpeg_start_decompress(). This is a
  500. little tricky since the output_XXX fields are not normally valid then. You
  501. can make them valid by calling jpeg_calc_output_dimensions() after setting the
  502. relevant parameters (scaling, output color space, and quantization flag).
  503. 6. while (scan lines remain to be read)
  504. jpeg_read_scanlines(...);
  505. Now you can read the decompressed image data by calling jpeg_read_scanlines()
  506. one or more times. At each call, you pass in the maximum number of scanlines
  507. to be read (ie, the height of your working buffer); jpeg_read_scanlines()
  508. will return up to that many lines. The return value is the number of lines
  509. actually read. The format of the returned data is discussed under "Data
  510. formats", above. Don't forget that grayscale and color JPEGs will return
  511. different data formats!
  512. Image data is returned in top-to-bottom scanline order. If you must write
  513. out the image in bottom-to-top order, you can use the JPEG library's virtual
  514. array mechanism to invert the data efficiently. Examples of this can be
  515. found in the sample application djpeg.
  516. The library maintains a count of the number of scanlines returned so far
  517. in the output_scanline field of the JPEG object. Usually you can just use
  518. this variable as the loop counter, so that the loop test looks like
  519. "while (cinfo.output_scanline < cinfo.output_height)". (Note that the test
  520. should NOT be against image_height, unless you never use scaling. The
  521. image_height field is the height of the original unscaled image.)
  522. The return value always equals the change in the value of output_scanline.
  523. If you don't use a suspending data source, it is safe to assume that
  524. jpeg_read_scanlines() reads at least one scanline per call, until the
  525. bottom of the image has been reached.
  526. If you use a buffer larger than one scanline, it is NOT safe to assume that
  527. jpeg_read_scanlines() fills it. (The current implementation returns only a
  528. few scanlines per call, no matter how large a buffer you pass.) So you must
  529. always provide a loop that calls jpeg_read_scanlines() repeatedly until the
  530. whole image has been read.
  531. 7. jpeg_finish_decompress(...);
  532. After all the image data has been read, call jpeg_finish_decompress() to
  533. complete the decompression cycle. This causes working memory associated
  534. with the JPEG object to be released.
  535. Typical code:
  536. jpeg_finish_decompress(&cinfo);
  537. If using the stdio source manager, don't forget to close the source stdio
  538. stream if necessary.
  539. It is an error to call jpeg_finish_decompress() before reading the correct
  540. total number of scanlines. If you wish to abort decompression, call
  541. jpeg_abort() as discussed below.
  542. After completing a decompression cycle, you may dispose of the JPEG object as
  543. discussed next, or you may use it to decompress another image. In that case
  544. return to step 2 or 3 as appropriate. If you do not change the source
  545. manager, the next image will be read from the same source.
  546. 8. Release the JPEG decompression object.
  547. When you are done with a JPEG decompression object, destroy it by calling
  548. jpeg_destroy_decompress() or jpeg_destroy(). The previous discussion of
  549. destroying compression objects applies here too.
  550. Typical code:
  551. jpeg_destroy_decompress(&cinfo);
  552. 9. Aborting.
  553. You can abort a decompression cycle by calling jpeg_destroy_decompress() or
  554. jpeg_destroy() if you don't need the JPEG object any more, or
  555. jpeg_abort_decompress() or jpeg_abort() if you want to reuse the object.
  556. The previous discussion of aborting compression cycles applies here too.
  557. Mechanics of usage: include files, linking, etc
  558. -----------------------------------------------
  559. Applications using the JPEG library should include the header file jpeglib.h
  560. to obtain declarations of data types and routines. Before including
  561. jpeglib.h, include system headers that define at least the typedefs FILE and
  562. size_t. On ANSI-conforming systems, including <stdio.h> is sufficient; on
  563. older Unix systems, you may need <sys/types.h> to define size_t.
  564. If the application needs to refer to individual JPEG library error codes, also
  565. include jerror.h to define those symbols.
  566. jpeglib.h indirectly includes the files jconfig.h and jmorecfg.h. If you are
  567. installing the JPEG header files in a system directory, you will want to
  568. install all four files: jpeglib.h, jerror.h, jconfig.h, jmorecfg.h.
  569. The most convenient way to include the JPEG code into your executable program
  570. is to prepare a library file ("libjpeg.a", or a corresponding name on non-Unix
  571. machines) and reference it at your link step. If you use only half of the
  572. library (only compression or only decompression), only that much code will be
  573. included from the library, unless your linker is hopelessly brain-damaged.
  574. The supplied makefiles build libjpeg.a automatically (see install.txt).
  575. While you can build the JPEG library as a shared library if the whim strikes
  576. you, we don't really recommend it. The trouble with shared libraries is that
  577. at some point you'll probably try to substitute a new version of the library
  578. without recompiling the calling applications. That generally doesn't work
  579. because the parameter struct declarations usually change with each new
  580. version. In other words, the library's API is *not* guaranteed binary
  581. compatible across versions; we only try to ensure source-code compatibility.
  582. (In hindsight, it might have been smarter to hide the parameter structs from
  583. applications and introduce a ton of access functions instead. Too late now,
  584. however.)
  585. On some systems your application may need to set up a signal handler to ensure
  586. that temporary files are deleted if the program is interrupted. This is most
  587. critical if you are on MS-DOS and use the jmemdos.c memory manager back end;
  588. it will try to grab extended memory for temp files, and that space will NOT be
  589. freed automatically. See cjpeg.c or djpeg.c for an example signal handler.
  590. It may be worth pointing out that the core JPEG library does not actually
  591. require the stdio library: only the default source/destination managers and
  592. error handler need it. You can use the library in a stdio-less environment
  593. if you replace those modules and use jmemnobs.c (or another memory manager of
  594. your own devising). More info about the minimum system library requirements
  595. may be found in jinclude.h.
  596. ADVANCED FEATURES
  597. =================
  598. Compression parameter selection
  599. -------------------------------
  600. This section describes all the optional parameters you can set for JPEG
  601. compression, as well as the "helper" routines provided to assist in this
  602. task. Proper setting of some parameters requires detailed understanding
  603. of the JPEG standard; if you don't know what a parameter is for, it's best
  604. not to mess with it! See REFERENCES in the README file for pointers to
  605. more info about JPEG.
  606. It's a good idea to call jpeg_set_defaults() first, even if you plan to set
  607. all the parameters; that way your code is more likely to work with future JPEG
  608. libraries that have additional parameters. For the same reason, we recommend
  609. you use a helper routine where one is provided, in preference to twiddling
  610. cinfo fields directly.
  611. The helper routines are:
  612. jpeg_set_defaults (j_compress_ptr cinfo)
  613. This routine sets all JPEG parameters to reasonable defaults, using
  614. only the input image's color space (field in_color_space, which must
  615. already be set in cinfo). Many applications will only need to use
  616. this routine and perhaps jpeg_set_quality().
  617. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  618. Sets the JPEG file's colorspace (field jpeg_color_space) as specified,
  619. and sets other color-space-dependent parameters appropriately. See
  620. "Special color spaces", below, before using this. A large number of
  621. parameters, including all per-component parameters, are set by this
  622. routine; if you want to twiddle individual parameters you should call
  623. jpeg_set_colorspace() before rather than after.
  624. jpeg_default_colorspace (j_compress_ptr cinfo)
  625. Selects an appropriate JPEG colorspace based on cinfo->in_color_space,
  626. and calls jpeg_set_colorspace(). This is actually a subroutine of
  627. jpeg_set_defaults(). It's broken out in case you want to change
  628. just the colorspace-dependent JPEG parameters.
  629. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  630. Constructs JPEG quantization tables appropriate for the indicated
  631. quality setting. The quality value is expressed on the 0..100 scale
  632. recommended by IJG (cjpeg's "-quality" switch uses this routine).
  633. Note that the exact mapping from quality values to tables may change
  634. in future IJG releases as more is learned about DCT quantization.
  635. If the force_baseline parameter is TRUE, then the quantization table
  636. entries are constrained to the range 1..255 for full JPEG baseline
  637. compatibility. In the current implementation, this only makes a
  638. difference for quality settings below 25, and it effectively prevents
  639. very small/low quality files from being generated. The IJG decoder
  640. is capable of reading the non-baseline files generated at low quality
  641. settings when force_baseline is FALSE, but other decoders may not be.
  642. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  643. boolean force_baseline)
  644. Same as jpeg_set_quality() except that the generated tables are the
  645. sample tables given in the JPEC spec section K.1, multiplied by the
  646. specified scale factor (which is expressed as a percentage; thus
  647. scale_factor = 100 reproduces the spec's tables). Note that larger
  648. scale factors give lower quality. This entry point is useful for
  649. conforming to the Adobe PostScript DCT conventions, but we do not
  650. recommend linear scaling as a user-visible quality scale otherwise.
  651. force_baseline again constrains the computed table entries to 1..255.
  652. int jpeg_quality_scaling (int quality)
  653. Converts a value on the IJG-recommended quality scale to a linear
  654. scaling percentage. Note that this routine may change or go away
  655. in future releases --- IJG may choose to adopt a scaling method that
  656. can't be expressed as a simple scalar multiplier, in which case the
  657. premise of this routine collapses. Caveat user.
  658. jpeg_default_qtables (j_compress_ptr cinfo, boolean force_baseline)
  659. Set default quantization tables with linear q_scale_factor[] values
  660. (see below).
  661. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  662. const unsigned int *basic_table,
  663. int scale_factor, boolean force_baseline)
  664. Allows an arbitrary quantization table to be created. which_tbl
  665. indicates which table slot to fill. basic_table points to an array
  666. of 64 unsigned ints given in normal array order. These values are
  667. multiplied by scale_factor/100 and then clamped to the range 1..65535
  668. (or to 1..255 if force_baseline is TRUE).
  669. CAUTION: prior to library version 6a, jpeg_add_quant_table expected
  670. the basic table to be given in JPEG zigzag order. If you need to
  671. write code that works with either older or newer versions of this
  672. routine, you must check the library version number. Something like
  673. "#if JPEG_LIB_VERSION >= 61" is the right test.
  674. jpeg_simple_progression (j_compress_ptr cinfo)
  675. Generates a default scan script for writing a progressive-JPEG file.
  676. This is the recommended method of creating a progressive file,
  677. unless you want to make a custom scan sequence. You must ensure that
  678. the JPEG color space is set correctly before calling this routine.
  679. Compression parameters (cinfo fields) include:
  680. int block_size
  681. Set DCT block size. All N from 1 to 16 are possible.
  682. Default is 8 (baseline format).
  683. Larger values produce higher compression,
  684. smaller values produce higher quality.
  685. An exact DCT stage is possible with 1 or 2.
  686. With the default quality of 75 and default Luminance qtable
  687. the DCT+Quantization stage is lossless for value 1.
  688. Note that values other than 8 require a SmartScale capable decoder,
  689. introduced with IJG JPEG 8. Setting the block_size parameter for
  690. compression works with version 8c and later.
  691. J_DCT_METHOD dct_method
  692. Selects the algorithm used for the DCT step. Choices are:
  693. JDCT_ISLOW: slow but accurate integer algorithm
  694. JDCT_IFAST: faster, less accurate integer method
  695. JDCT_FLOAT: floating-point method
  696. JDCT_DEFAULT: default method (normally JDCT_ISLOW)
  697. JDCT_FASTEST: fastest method (normally JDCT_IFAST)
  698. The FLOAT method is very slightly more accurate than the ISLOW method,
  699. but may give different results on different machines due to varying
  700. roundoff behavior. The integer methods should give the same results
  701. on all machines. On machines with sufficiently fast FP hardware, the
  702. floating-point method may also be the fastest. The IFAST method is
  703. considerably less accurate than the other two; its use is not
  704. recommended if high quality is a concern. JDCT_DEFAULT and
  705. JDCT_FASTEST are macros configurable by each installation.
  706. unsigned int scale_num, scale_denom
  707. Scale the image by the fraction scale_num/scale_denom. Default is
  708. 1/1, or no scaling. Currently, the supported scaling ratios are
  709. M/N with all N from 1 to 16, where M is the destination DCT size,
  710. which is 8 by default (see block_size parameter above).
  711. (The library design allows for arbitrary scaling ratios but this
  712. is not likely to be implemented any time soon.)
  713. J_COLOR_SPACE jpeg_color_space
  714. int num_components
  715. The JPEG color space and corresponding number of components; see
  716. "Special color spaces", below, for more info. We recommend using
  717. jpeg_set_color_space() if you want to change these.
  718. boolean optimize_coding
  719. TRUE causes the compressor to compute optimal Huffman coding tables
  720. for the image. This requires an extra pass over the data and
  721. therefore costs a good deal of space and time. The default is
  722. FALSE, which tells the compressor to use the supplied or default
  723. Huffman tables. In most cases optimal tables save only a few percent
  724. of file size compared to the default tables. Note that when this is
  725. TRUE, you need not supply Huffman tables at all, and any you do
  726. supply will be overwritten.
  727. unsigned int restart_interval
  728. int restart_in_rows
  729. To emit restart markers in the JPEG file, set one of these nonzero.
  730. Set restart_interval to specify the exact interval in MCU blocks.
  731. Set restart_in_rows to specify the interval in MCU rows. (If
  732. restart_in_rows is not 0, then restart_interval is set after the
  733. image width in MCUs is computed.) Defaults are zero (no restarts).
  734. One restart marker per MCU row is often a good choice.
  735. NOTE: the overhead of restart markers is higher in grayscale JPEG
  736. files than in color files, and MUCH higher in progressive JPEGs.
  737. If you use restarts, you may want to use larger intervals in those
  738. cases.
  739. const jpeg_scan_info * scan_info
  740. int num_scans
  741. By default, scan_info is NULL; this causes the compressor to write a
  742. single-scan sequential JPEG file. If not NULL, scan_info points to
  743. an array of scan definition records of length num_scans. The
  744. compressor will then write a JPEG file having one scan for each scan
  745. definition record. This is used to generate noninterleaved or
  746. progressive JPEG files. The library checks that the scan array
  747. defines a valid JPEG scan sequence. (jpeg_simple_progression creates
  748. a suitable scan definition array for progressive JPEG.) This is
  749. discussed further under "Progressive JPEG support".
  750. boolean do_fancy_downsampling
  751. If TRUE, use direct DCT scaling with DCT size > 8 for downsampling
  752. of chroma components.
  753. If FALSE, use only DCT size <= 8 and simple separate downsampling.
  754. Default is TRUE.
  755. For better image stability in multiple generation compression cycles
  756. it is preferable that this value matches the corresponding
  757. do_fancy_upsampling value in decompression.
  758. int smoothing_factor
  759. If non-zero, the input image is smoothed; the value should be 1 for
  760. minimal smoothing to 100 for maximum smoothing. Consult jcsample.c
  761. for details of the smoothing algorithm. The default is zero.
  762. boolean write_JFIF_header
  763. If TRUE, a JFIF APP0 marker is emitted. jpeg_set_defaults() and
  764. jpeg_set_colorspace() set this TRUE if a JFIF-legal JPEG color space
  765. (ie, YCbCr or grayscale) is selected, otherwise FALSE.
  766. UINT8 JFIF_major_version
  767. UINT8 JFIF_minor_version
  768. The version number to be written into the JFIF marker.
  769. jpeg_set_defaults() initializes the version to 1.01 (major=minor=1).
  770. You should set it to 1.02 (major=1, minor=2) if you plan to write
  771. any JFIF 1.02 extension markers.
  772. UINT8 density_unit
  773. UINT16 X_density
  774. UINT16 Y_density
  775. The resolution information to be written into the JFIF marker;
  776. not used otherwise. density_unit may be 0 for unknown,
  777. 1 for dots/inch, or 2 for dots/cm. The default values are 0,1,1
  778. indicating square pixels of unknown size.
  779. boolean write_Adobe_marker
  780. If TRUE, an Adobe APP14 marker is emitted. jpeg_set_defaults() and
  781. jpeg_set_colorspace() set this TRUE if JPEG color space RGB, CMYK,
  782. or YCCK is selected, otherwise FALSE. It is generally a bad idea
  783. to set both write_JFIF_header and write_Adobe_marker. In fact,
  784. you probably shouldn't change the default settings at all --- the
  785. default behavior ensures that the JPEG file's color space can be
  786. recognized by the decoder.
  787. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]
  788. Pointers to coefficient quantization tables, one per table slot,
  789. or NULL if no table is defined for a slot. Usually these should
  790. be set via one of the above helper routines; jpeg_add_quant_table()
  791. is general enough to define any quantization table. The other
  792. routines will set up table slot 0 for luminance quality and table
  793. slot 1 for chrominance.
  794. int q_scale_factor[NUM_QUANT_TBLS]
  795. Linear quantization scaling factors (percentage, initialized 100)
  796. for use with jpeg_default_qtables().
  797. See rdswitch.c and cjpeg.c for an example of usage.
  798. Note that the q_scale_factor[] fields are the "linear" scales, so you
  799. have to convert from user-defined ratings via jpeg_quality_scaling().
  800. Here is an example code which corresponds to cjpeg -quality 90,70:
  801. jpeg_set_defaults(cinfo);
  802. /* Set luminance quality 90. */
  803. cinfo->q_scale_factor[0] = jpeg_quality_scaling(90);
  804. /* Set chrominance quality 70. */
  805. cinfo->q_scale_factor[1] = jpeg_quality_scaling(70);
  806. jpeg_default_qtables(cinfo, force_baseline);
  807. CAUTION: You must also set 1x1 subsampling for efficient separate
  808. color quality selection, since the default value used by library
  809. is 2x2:
  810. cinfo->comp_info[0].v_samp_factor = 1;
  811. cinfo->comp_info[0].h_samp_factor = 1;
  812. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]
  813. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]
  814. Pointers to Huffman coding tables, one per table slot, or NULL if
  815. no table is defined for a slot. Slots 0 and 1 are filled with the
  816. JPEG sample tables by jpeg_set_defaults(). If you need to allocate
  817. more table structures, jpeg_alloc_huff_table() may be used.
  818. Note that optimal Huffman tables can be computed for an image
  819. by setting optimize_coding, as discussed above; there's seldom
  820. any need to mess with providing your own Huffman tables.
  821. The actual dimensions of the JPEG image that will be written to the file are
  822. given by the following fields. These are computed from the input image
  823. dimensions and the compression parameters by jpeg_start_compress(). You can
  824. also call jpeg_calc_jpeg_dimensions() to obtain the values that will result
  825. from the current parameter settings. This can be useful if you are trying
  826. to pick a scaling ratio that will get close to a desired target size.
  827. JDIMENSION jpeg_width Actual dimensions of output image.
  828. JDIMENSION jpeg_height
  829. Per-component parameters are stored in the struct cinfo.comp_info[i] for
  830. component number i. Note that components here refer to components of the
  831. JPEG color space, *not* the source image color space. A suitably large
  832. comp_info[] array is allocated by jpeg_set_defaults(); if you choose not
  833. to use that routine, it's up to you to allocate the array.
  834. int component_id
  835. The one-byte identifier code to be recorded in the JPEG file for
  836. this component. For the standard color spaces, we recommend you
  837. leave the default values alone.
  838. int h_samp_factor
  839. int v_samp_factor
  840. Horizontal and vertical sampling factors for the component; must
  841. be 1..4 according to the JPEG standard. Note that larger sampling
  842. factors indicate a higher-resolution component; many people find
  843. this behavior quite unintuitive. The default values are 2,2 for
  844. luminance components and 1,1 for chrominance components, except
  845. for grayscale where 1,1 is used.
  846. int quant_tbl_no
  847. Quantization table number for component. The default value is
  848. 0 for luminance components and 1 for chrominance components.
  849. int dc_tbl_no
  850. int ac_tbl_no
  851. DC and AC entropy coding table numbers. The default values are
  852. 0 for luminance components and 1 for chrominance components.
  853. int component_index
  854. Must equal the component's index in comp_info[]. (Beginning in
  855. release v6, the compressor library will