xref: /plan9/sys/src/cmd/gs/jpeg/libjpeg.doc (revision 593dc095aefb2a85c828727bbfa9da139a49bdf4)
17dd7cddfSDavid du ColombierUSING THE IJG JPEG LIBRARY
27dd7cddfSDavid du Colombier
3*593dc095SDavid du ColombierCopyright (C) 1994-1998, Thomas G. Lane.
47dd7cddfSDavid du ColombierThis file is part of the Independent JPEG Group's software.
57dd7cddfSDavid du ColombierFor conditions of distribution and use, see the accompanying README file.
67dd7cddfSDavid du Colombier
77dd7cddfSDavid du Colombier
87dd7cddfSDavid du ColombierThis file describes how to use the IJG JPEG library within an application
97dd7cddfSDavid du Colombierprogram.  Read it if you want to write a program that uses the library.
107dd7cddfSDavid du Colombier
117dd7cddfSDavid du ColombierThe file example.c provides heavily commented skeleton code for calling the
127dd7cddfSDavid du ColombierJPEG library.  Also see jpeglib.h (the include file to be used by application
137dd7cddfSDavid du Colombierprograms) for full details about data structures and function parameter lists.
147dd7cddfSDavid du ColombierThe library source code, of course, is the ultimate reference.
157dd7cddfSDavid du Colombier
167dd7cddfSDavid du ColombierNote that there have been *major* changes from the application interface
177dd7cddfSDavid du Colombierpresented by IJG version 4 and earlier versions.  The old design had several
187dd7cddfSDavid du Colombierinherent limitations, and it had accumulated a lot of cruft as we added
197dd7cddfSDavid du Colombierfeatures while trying to minimize application-interface changes.  We have
207dd7cddfSDavid du Colombiersacrificed backward compatibility in the version 5 rewrite, but we think the
217dd7cddfSDavid du Colombierimprovements justify this.
227dd7cddfSDavid du Colombier
237dd7cddfSDavid du Colombier
247dd7cddfSDavid du ColombierTABLE OF CONTENTS
257dd7cddfSDavid du Colombier-----------------
267dd7cddfSDavid du Colombier
277dd7cddfSDavid du ColombierOverview:
287dd7cddfSDavid du Colombier	Functions provided by the library
297dd7cddfSDavid du Colombier	Outline of typical usage
307dd7cddfSDavid du ColombierBasic library usage:
317dd7cddfSDavid du Colombier	Data formats
327dd7cddfSDavid du Colombier	Compression details
337dd7cddfSDavid du Colombier	Decompression details
347dd7cddfSDavid du Colombier	Mechanics of usage: include files, linking, etc
357dd7cddfSDavid du ColombierAdvanced features:
367dd7cddfSDavid du Colombier	Compression parameter selection
377dd7cddfSDavid du Colombier	Decompression parameter selection
387dd7cddfSDavid du Colombier	Special color spaces
397dd7cddfSDavid du Colombier	Error handling
407dd7cddfSDavid du Colombier	Compressed data handling (source and destination managers)
417dd7cddfSDavid du Colombier	I/O suspension
427dd7cddfSDavid du Colombier	Progressive JPEG support
437dd7cddfSDavid du Colombier	Buffered-image mode
447dd7cddfSDavid du Colombier	Abbreviated datastreams and multiple images
457dd7cddfSDavid du Colombier	Special markers
467dd7cddfSDavid du Colombier	Raw (downsampled) image data
477dd7cddfSDavid du Colombier	Really raw data: DCT coefficients
487dd7cddfSDavid du Colombier	Progress monitoring
497dd7cddfSDavid du Colombier	Memory management
50*593dc095SDavid du Colombier	Memory usage
517dd7cddfSDavid du Colombier	Library compile-time options
527dd7cddfSDavid du Colombier	Portability considerations
537dd7cddfSDavid du Colombier	Notes for MS-DOS implementors
547dd7cddfSDavid du Colombier
557dd7cddfSDavid du ColombierYou should read at least the overview and basic usage sections before trying
567dd7cddfSDavid du Colombierto program with the library.  The sections on advanced features can be read
577dd7cddfSDavid du Colombierif and when you need them.
587dd7cddfSDavid du Colombier
597dd7cddfSDavid du Colombier
607dd7cddfSDavid du ColombierOVERVIEW
617dd7cddfSDavid du Colombier========
627dd7cddfSDavid du Colombier
637dd7cddfSDavid du ColombierFunctions provided by the library
647dd7cddfSDavid du Colombier---------------------------------
657dd7cddfSDavid du Colombier
667dd7cddfSDavid du ColombierThe IJG JPEG library provides C code to read and write JPEG-compressed image
677dd7cddfSDavid du Colombierfiles.  The surrounding application program receives or supplies image data a
687dd7cddfSDavid du Colombierscanline at a time, using a straightforward uncompressed image format.  All
697dd7cddfSDavid du Colombierdetails of color conversion and other preprocessing/postprocessing can be
707dd7cddfSDavid du Colombierhandled by the library.
717dd7cddfSDavid du Colombier
727dd7cddfSDavid du ColombierThe library includes a substantial amount of code that is not covered by the
737dd7cddfSDavid du ColombierJPEG standard but is necessary for typical applications of JPEG.  These
747dd7cddfSDavid du Colombierfunctions preprocess the image before JPEG compression or postprocess it after
757dd7cddfSDavid du Colombierdecompression.  They include colorspace conversion, downsampling/upsampling,
767dd7cddfSDavid du Colombierand color quantization.  The application indirectly selects use of this code
777dd7cddfSDavid du Colombierby specifying the format in which it wishes to supply or receive image data.
787dd7cddfSDavid du ColombierFor example, if colormapped output is requested, then the decompression
797dd7cddfSDavid du Colombierlibrary automatically invokes color quantization.
807dd7cddfSDavid du Colombier
817dd7cddfSDavid du ColombierA wide range of quality vs. speed tradeoffs are possible in JPEG processing,
827dd7cddfSDavid du Colombierand even more so in decompression postprocessing.  The decompression library
837dd7cddfSDavid du Colombierprovides multiple implementations that cover most of the useful tradeoffs,
847dd7cddfSDavid du Colombierranging from very-high-quality down to fast-preview operation.  On the
857dd7cddfSDavid du Colombiercompression side we have generally not provided low-quality choices, since
867dd7cddfSDavid du Colombiercompression is normally less time-critical.  It should be understood that the
877dd7cddfSDavid du Colombierlow-quality modes may not meet the JPEG standard's accuracy requirements;
887dd7cddfSDavid du Colombiernonetheless, they are useful for viewers.
897dd7cddfSDavid du Colombier
907dd7cddfSDavid du ColombierA word about functions *not* provided by the library.  We handle a subset of
917dd7cddfSDavid du Colombierthe ISO JPEG standard; most baseline, extended-sequential, and progressive
927dd7cddfSDavid du ColombierJPEG processes are supported.  (Our subset includes all features now in common
937dd7cddfSDavid du Colombieruse.)  Unsupported ISO options include:
947dd7cddfSDavid du Colombier	* Hierarchical storage
957dd7cddfSDavid du Colombier	* Lossless JPEG
967dd7cddfSDavid du Colombier	* Arithmetic entropy coding (unsupported for legal reasons)
977dd7cddfSDavid du Colombier	* DNL marker
987dd7cddfSDavid du Colombier	* Nonintegral subsampling ratios
997dd7cddfSDavid du ColombierWe support both 8- and 12-bit data precision, but this is a compile-time
1007dd7cddfSDavid du Colombierchoice rather than a run-time choice; hence it is difficult to use both
1017dd7cddfSDavid du Colombierprecisions in a single application.
1027dd7cddfSDavid du Colombier
1037dd7cddfSDavid du ColombierBy itself, the library handles only interchange JPEG datastreams --- in
1047dd7cddfSDavid du Colombierparticular the widely used JFIF file format.  The library can be used by
1057dd7cddfSDavid du Colombiersurrounding code to process interchange or abbreviated JPEG datastreams that
1067dd7cddfSDavid du Colombierare embedded in more complex file formats.  (For example, this library is
1077dd7cddfSDavid du Colombierused by the free LIBTIFF library to support JPEG compression in TIFF.)
1087dd7cddfSDavid du Colombier
1097dd7cddfSDavid du Colombier
1107dd7cddfSDavid du ColombierOutline of typical usage
1117dd7cddfSDavid du Colombier------------------------
1127dd7cddfSDavid du Colombier
1137dd7cddfSDavid du ColombierThe rough outline of a JPEG compression operation is:
1147dd7cddfSDavid du Colombier
1157dd7cddfSDavid du Colombier	Allocate and initialize a JPEG compression object
1167dd7cddfSDavid du Colombier	Specify the destination for the compressed data (eg, a file)
1177dd7cddfSDavid du Colombier	Set parameters for compression, including image size & colorspace
1187dd7cddfSDavid du Colombier	jpeg_start_compress(...);
1197dd7cddfSDavid du Colombier	while (scan lines remain to be written)
1207dd7cddfSDavid du Colombier		jpeg_write_scanlines(...);
1217dd7cddfSDavid du Colombier	jpeg_finish_compress(...);
1227dd7cddfSDavid du Colombier	Release the JPEG compression object
1237dd7cddfSDavid du Colombier
1247dd7cddfSDavid du ColombierA JPEG compression object holds parameters and working state for the JPEG
1257dd7cddfSDavid du Colombierlibrary.  We make creation/destruction of the object separate from starting
1267dd7cddfSDavid du Colombieror finishing compression of an image; the same object can be re-used for a
1277dd7cddfSDavid du Colombierseries of image compression operations.  This makes it easy to re-use the
1287dd7cddfSDavid du Colombiersame parameter settings for a sequence of images.  Re-use of a JPEG object
1297dd7cddfSDavid du Colombieralso has important implications for processing abbreviated JPEG datastreams,
1307dd7cddfSDavid du Colombieras discussed later.
1317dd7cddfSDavid du Colombier
1327dd7cddfSDavid du ColombierThe image data to be compressed is supplied to jpeg_write_scanlines() from
1337dd7cddfSDavid du Colombierin-memory buffers.  If the application is doing file-to-file compression,
1347dd7cddfSDavid du Colombierreading image data from the source file is the application's responsibility.
1357dd7cddfSDavid du ColombierThe library emits compressed data by calling a "data destination manager",
1367dd7cddfSDavid du Colombierwhich typically will write the data into a file; but the application can
1377dd7cddfSDavid du Colombierprovide its own destination manager to do something else.
1387dd7cddfSDavid du Colombier
1397dd7cddfSDavid du ColombierSimilarly, the rough outline of a JPEG decompression operation is:
1407dd7cddfSDavid du Colombier
1417dd7cddfSDavid du Colombier	Allocate and initialize a JPEG decompression object
1427dd7cddfSDavid du Colombier	Specify the source of the compressed data (eg, a file)
1437dd7cddfSDavid du Colombier	Call jpeg_read_header() to obtain image info
1447dd7cddfSDavid du Colombier	Set parameters for decompression
1457dd7cddfSDavid du Colombier	jpeg_start_decompress(...);
1467dd7cddfSDavid du Colombier	while (scan lines remain to be read)
1477dd7cddfSDavid du Colombier		jpeg_read_scanlines(...);
1487dd7cddfSDavid du Colombier	jpeg_finish_decompress(...);
1497dd7cddfSDavid du Colombier	Release the JPEG decompression object
1507dd7cddfSDavid du Colombier
1517dd7cddfSDavid du ColombierThis is comparable to the compression outline except that reading the
1527dd7cddfSDavid du Colombierdatastream header is a separate step.  This is helpful because information
1537dd7cddfSDavid du Colombierabout the image's size, colorspace, etc is available when the application
1547dd7cddfSDavid du Colombierselects decompression parameters.  For example, the application can choose an
1557dd7cddfSDavid du Colombieroutput scaling ratio that will fit the image into the available screen size.
1567dd7cddfSDavid du Colombier
1577dd7cddfSDavid du ColombierThe decompression library obtains compressed data by calling a data source
1587dd7cddfSDavid du Colombiermanager, which typically will read the data from a file; but other behaviors
1597dd7cddfSDavid du Colombiercan be obtained with a custom source manager.  Decompressed data is delivered
1607dd7cddfSDavid du Colombierinto in-memory buffers passed to jpeg_read_scanlines().
1617dd7cddfSDavid du Colombier
1627dd7cddfSDavid du ColombierIt is possible to abort an incomplete compression or decompression operation
1637dd7cddfSDavid du Colombierby calling jpeg_abort(); or, if you do not need to retain the JPEG object,
1647dd7cddfSDavid du Colombiersimply release it by calling jpeg_destroy().
1657dd7cddfSDavid du Colombier
1667dd7cddfSDavid du ColombierJPEG compression and decompression objects are two separate struct types.
1677dd7cddfSDavid du ColombierHowever, they share some common fields, and certain routines such as
1687dd7cddfSDavid du Colombierjpeg_destroy() can work on either type of object.
1697dd7cddfSDavid du Colombier
1707dd7cddfSDavid du ColombierThe JPEG library has no static variables: all state is in the compression
1717dd7cddfSDavid du Colombieror decompression object.  Therefore it is possible to process multiple
1727dd7cddfSDavid du Colombiercompression and decompression operations concurrently, using multiple JPEG
1737dd7cddfSDavid du Colombierobjects.
1747dd7cddfSDavid du Colombier
1757dd7cddfSDavid du ColombierBoth compression and decompression can be done in an incremental memory-to-
1767dd7cddfSDavid du Colombiermemory fashion, if suitable source/destination managers are used.  See the
1777dd7cddfSDavid du Colombiersection on "I/O suspension" for more details.
1787dd7cddfSDavid du Colombier
1797dd7cddfSDavid du Colombier
1807dd7cddfSDavid du ColombierBASIC LIBRARY USAGE
1817dd7cddfSDavid du Colombier===================
1827dd7cddfSDavid du Colombier
1837dd7cddfSDavid du ColombierData formats
1847dd7cddfSDavid du Colombier------------
1857dd7cddfSDavid du Colombier
1867dd7cddfSDavid du ColombierBefore diving into procedural details, it is helpful to understand the
1877dd7cddfSDavid du Colombierimage data format that the JPEG library expects or returns.
1887dd7cddfSDavid du Colombier
1897dd7cddfSDavid du ColombierThe standard input image format is a rectangular array of pixels, with each
1907dd7cddfSDavid du Colombierpixel having the same number of "component" or "sample" values (color
1917dd7cddfSDavid du Colombierchannels).  You must specify how many components there are and the colorspace
1927dd7cddfSDavid du Colombierinterpretation of the components.  Most applications will use RGB data
1937dd7cddfSDavid du Colombier(three components per pixel) or grayscale data (one component per pixel).
1947dd7cddfSDavid du ColombierPLEASE NOTE THAT RGB DATA IS THREE SAMPLES PER PIXEL, GRAYSCALE ONLY ONE.
1957dd7cddfSDavid du ColombierA remarkable number of people manage to miss this, only to find that their
1967dd7cddfSDavid du Colombierprograms don't work with grayscale JPEG files.
1977dd7cddfSDavid du Colombier
1987dd7cddfSDavid du ColombierThere is no provision for colormapped input.  JPEG files are always full-color
1997dd7cddfSDavid du Colombieror full grayscale (or sometimes another colorspace such as CMYK).  You can
2007dd7cddfSDavid du Colombierfeed in a colormapped image by expanding it to full-color format.  However
2017dd7cddfSDavid du ColombierJPEG often doesn't work very well with source data that has been colormapped,
2027dd7cddfSDavid du Colombierbecause of dithering noise.  This is discussed in more detail in the JPEG FAQ
2037dd7cddfSDavid du Colombierand the other references mentioned in the README file.
2047dd7cddfSDavid du Colombier
2057dd7cddfSDavid du ColombierPixels are stored by scanlines, with each scanline running from left to
2067dd7cddfSDavid du Colombierright.  The component values for each pixel are adjacent in the row; for
2077dd7cddfSDavid du Colombierexample, R,G,B,R,G,B,R,G,B,... for 24-bit RGB color.  Each scanline is an
2087dd7cddfSDavid du Colombierarray of data type JSAMPLE --- which is typically "unsigned char", unless
2097dd7cddfSDavid du Colombieryou've changed jmorecfg.h.  (You can also change the RGB pixel layout, say
2107dd7cddfSDavid du Colombierto B,G,R order, by modifying jmorecfg.h.  But see the restrictions listed in
2117dd7cddfSDavid du Colombierthat file before doing so.)
2127dd7cddfSDavid du Colombier
2137dd7cddfSDavid du ColombierA 2-D array of pixels is formed by making a list of pointers to the starts of
2147dd7cddfSDavid du Colombierscanlines; so the scanlines need not be physically adjacent in memory.  Even
2157dd7cddfSDavid du Colombierif you process just one scanline at a time, you must make a one-element
2167dd7cddfSDavid du Colombierpointer array to conform to this structure.  Pointers to JSAMPLE rows are of
2177dd7cddfSDavid du Colombiertype JSAMPROW, and the pointer to the pointer array is of type JSAMPARRAY.
2187dd7cddfSDavid du Colombier
2197dd7cddfSDavid du ColombierThe library accepts or supplies one or more complete scanlines per call.
2207dd7cddfSDavid du ColombierIt is not possible to process part of a row at a time.  Scanlines are always
2217dd7cddfSDavid du Colombierprocessed top-to-bottom.  You can process an entire image in one call if you
2227dd7cddfSDavid du Colombierhave it all in memory, but usually it's simplest to process one scanline at
2237dd7cddfSDavid du Colombiera time.
2247dd7cddfSDavid du Colombier
2257dd7cddfSDavid du ColombierFor best results, source data values should have the precision specified by
2267dd7cddfSDavid du ColombierBITS_IN_JSAMPLE (normally 8 bits).  For instance, if you choose to compress
2277dd7cddfSDavid du Colombierdata that's only 6 bits/channel, you should left-justify each value in a
2287dd7cddfSDavid du Colombierbyte before passing it to the compressor.  If you need to compress data
2297dd7cddfSDavid du Colombierthat has more than 8 bits/channel, compile with BITS_IN_JSAMPLE = 12.
2307dd7cddfSDavid du Colombier(See "Library compile-time options", later.)
2317dd7cddfSDavid du Colombier
2327dd7cddfSDavid du Colombier
2337dd7cddfSDavid du ColombierThe data format returned by the decompressor is the same in all details,
2347dd7cddfSDavid du Colombierexcept that colormapped output is supported.  (Again, a JPEG file is never
2357dd7cddfSDavid du Colombiercolormapped.  But you can ask the decompressor to perform on-the-fly color
2367dd7cddfSDavid du Colombierquantization to deliver colormapped output.)  If you request colormapped
2377dd7cddfSDavid du Colombieroutput then the returned data array contains a single JSAMPLE per pixel;
2387dd7cddfSDavid du Colombierits value is an index into a color map.  The color map is represented as
2397dd7cddfSDavid du Colombiera 2-D JSAMPARRAY in which each row holds the values of one color component,
2407dd7cddfSDavid du Colombierthat is, colormap[i][j] is the value of the i'th color component for pixel
2417dd7cddfSDavid du Colombiervalue (map index) j.  Note that since the colormap indexes are stored in
2427dd7cddfSDavid du ColombierJSAMPLEs, the maximum number of colors is limited by the size of JSAMPLE
2437dd7cddfSDavid du Colombier(ie, at most 256 colors for an 8-bit JPEG library).
2447dd7cddfSDavid du Colombier
2457dd7cddfSDavid du Colombier
2467dd7cddfSDavid du ColombierCompression details
2477dd7cddfSDavid du Colombier-------------------
2487dd7cddfSDavid du Colombier
2497dd7cddfSDavid du ColombierHere we revisit the JPEG compression outline given in the overview.
2507dd7cddfSDavid du Colombier
2517dd7cddfSDavid du Colombier1. Allocate and initialize a JPEG compression object.
2527dd7cddfSDavid du Colombier
2537dd7cddfSDavid du ColombierA JPEG compression object is a "struct jpeg_compress_struct".  (It also has
2547dd7cddfSDavid du Colombiera bunch of subsidiary structures which are allocated via malloc(), but the
2557dd7cddfSDavid du Colombierapplication doesn't control those directly.)  This struct can be just a local
2567dd7cddfSDavid du Colombiervariable in the calling routine, if a single routine is going to execute the
2577dd7cddfSDavid du Colombierwhole JPEG compression sequence.  Otherwise it can be static or allocated
2587dd7cddfSDavid du Colombierfrom malloc().
2597dd7cddfSDavid du Colombier
2607dd7cddfSDavid du ColombierYou will also need a structure representing a JPEG error handler.  The part
2617dd7cddfSDavid du Colombierof this that the library cares about is a "struct jpeg_error_mgr".  If you
2627dd7cddfSDavid du Colombierare providing your own error handler, you'll typically want to embed the
2637dd7cddfSDavid du Colombierjpeg_error_mgr struct in a larger structure; this is discussed later under
2647dd7cddfSDavid du Colombier"Error handling".  For now we'll assume you are just using the default error
2657dd7cddfSDavid du Colombierhandler.  The default error handler will print JPEG error/warning messages
2667dd7cddfSDavid du Colombieron stderr, and it will call exit() if a fatal error occurs.
2677dd7cddfSDavid du Colombier
2687dd7cddfSDavid du ColombierYou must initialize the error handler structure, store a pointer to it into
2697dd7cddfSDavid du Colombierthe JPEG object's "err" field, and then call jpeg_create_compress() to
2707dd7cddfSDavid du Colombierinitialize the rest of the JPEG object.
2717dd7cddfSDavid du Colombier
2727dd7cddfSDavid du ColombierTypical code for this step, if you are using the default error handler, is
2737dd7cddfSDavid du Colombier
2747dd7cddfSDavid du Colombier	struct jpeg_compress_struct cinfo;
2757dd7cddfSDavid du Colombier	struct jpeg_error_mgr jerr;
2767dd7cddfSDavid du Colombier	...
2777dd7cddfSDavid du Colombier	cinfo.err = jpeg_std_error(&jerr);
2787dd7cddfSDavid du Colombier	jpeg_create_compress(&cinfo);
2797dd7cddfSDavid du Colombier
2807dd7cddfSDavid du Colombierjpeg_create_compress allocates a small amount of memory, so it could fail
2817dd7cddfSDavid du Colombierif you are out of memory.  In that case it will exit via the error handler;
2827dd7cddfSDavid du Colombierthat's why the error handler must be initialized first.
2837dd7cddfSDavid du Colombier
2847dd7cddfSDavid du Colombier
2857dd7cddfSDavid du Colombier2. Specify the destination for the compressed data (eg, a file).
2867dd7cddfSDavid du Colombier
2877dd7cddfSDavid du ColombierAs previously mentioned, the JPEG library delivers compressed data to a
2887dd7cddfSDavid du Colombier"data destination" module.  The library includes one data destination
2897dd7cddfSDavid du Colombiermodule which knows how to write to a stdio stream.  You can use your own
2907dd7cddfSDavid du Colombierdestination module if you want to do something else, as discussed later.
2917dd7cddfSDavid du Colombier
2927dd7cddfSDavid du ColombierIf you use the standard destination module, you must open the target stdio
2937dd7cddfSDavid du Colombierstream beforehand.  Typical code for this step looks like:
2947dd7cddfSDavid du Colombier
2957dd7cddfSDavid du Colombier	FILE * outfile;
2967dd7cddfSDavid du Colombier	...
2977dd7cddfSDavid du Colombier	if ((outfile = fopen(filename, "wb")) == NULL) {
2987dd7cddfSDavid du Colombier	    fprintf(stderr, "can't open %s\n", filename);
2997dd7cddfSDavid du Colombier	    exit(1);
3007dd7cddfSDavid du Colombier	}
3017dd7cddfSDavid du Colombier	jpeg_stdio_dest(&cinfo, outfile);
3027dd7cddfSDavid du Colombier
3037dd7cddfSDavid du Colombierwhere the last line invokes the standard destination module.
3047dd7cddfSDavid du Colombier
3057dd7cddfSDavid du ColombierWARNING: it is critical that the binary compressed data be delivered to the
3067dd7cddfSDavid du Colombieroutput file unchanged.  On non-Unix systems the stdio library may perform
3077dd7cddfSDavid du Colombiernewline translation or otherwise corrupt binary data.  To suppress this
3087dd7cddfSDavid du Colombierbehavior, you may need to use a "b" option to fopen (as shown above), or use
3097dd7cddfSDavid du Colombiersetmode() or another routine to put the stdio stream in binary mode.  See
3107dd7cddfSDavid du Colombiercjpeg.c and djpeg.c for code that has been found to work on many systems.
3117dd7cddfSDavid du Colombier
3127dd7cddfSDavid du ColombierYou can select the data destination after setting other parameters (step 3),
3137dd7cddfSDavid du Colombierif that's more convenient.  You may not change the destination between
3147dd7cddfSDavid du Colombiercalling jpeg_start_compress() and jpeg_finish_compress().
3157dd7cddfSDavid du Colombier
3167dd7cddfSDavid du Colombier
3177dd7cddfSDavid du Colombier3. Set parameters for compression, including image size & colorspace.
3187dd7cddfSDavid du Colombier
3197dd7cddfSDavid du ColombierYou must supply information about the source image by setting the following
3207dd7cddfSDavid du Colombierfields in the JPEG object (cinfo structure):
3217dd7cddfSDavid du Colombier
3227dd7cddfSDavid du Colombier	image_width		Width of image, in pixels
3237dd7cddfSDavid du Colombier	image_height		Height of image, in pixels
3247dd7cddfSDavid du Colombier	input_components	Number of color channels (samples per pixel)
3257dd7cddfSDavid du Colombier	in_color_space		Color space of source image
3267dd7cddfSDavid du Colombier
3277dd7cddfSDavid du ColombierThe image dimensions are, hopefully, obvious.  JPEG supports image dimensions
3287dd7cddfSDavid du Colombierof 1 to 64K pixels in either direction.  The input color space is typically
3297dd7cddfSDavid du ColombierRGB or grayscale, and input_components is 3 or 1 accordingly.  (See "Special
3307dd7cddfSDavid du Colombiercolor spaces", later, for more info.)  The in_color_space field must be
3317dd7cddfSDavid du Colombierassigned one of the J_COLOR_SPACE enum constants, typically JCS_RGB or
3327dd7cddfSDavid du ColombierJCS_GRAYSCALE.
3337dd7cddfSDavid du Colombier
3347dd7cddfSDavid du ColombierJPEG has a large number of compression parameters that determine how the
3357dd7cddfSDavid du Colombierimage is encoded.  Most applications don't need or want to know about all
3367dd7cddfSDavid du Colombierthese parameters.  You can set all the parameters to reasonable defaults by
3377dd7cddfSDavid du Colombiercalling jpeg_set_defaults(); then, if there are particular values you want
3387dd7cddfSDavid du Colombierto change, you can do so after that.  The "Compression parameter selection"
3397dd7cddfSDavid du Colombiersection tells about all the parameters.
3407dd7cddfSDavid du Colombier
3417dd7cddfSDavid du ColombierYou must set in_color_space correctly before calling jpeg_set_defaults(),
3427dd7cddfSDavid du Colombierbecause the defaults depend on the source image colorspace.  However the
3437dd7cddfSDavid du Colombierother three source image parameters need not be valid until you call
3447dd7cddfSDavid du Colombierjpeg_start_compress().  There's no harm in calling jpeg_set_defaults() more
3457dd7cddfSDavid du Colombierthan once, if that happens to be convenient.
3467dd7cddfSDavid du Colombier
3477dd7cddfSDavid du ColombierTypical code for a 24-bit RGB source image is
3487dd7cddfSDavid du Colombier
3497dd7cddfSDavid du Colombier	cinfo.image_width = Width; 	/* image width and height, in pixels */
3507dd7cddfSDavid du Colombier	cinfo.image_height = Height;
3517dd7cddfSDavid du Colombier	cinfo.input_components = 3;	/* # of color components per pixel */
3527dd7cddfSDavid du Colombier	cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
3537dd7cddfSDavid du Colombier
3547dd7cddfSDavid du Colombier	jpeg_set_defaults(&cinfo);
3557dd7cddfSDavid du Colombier	/* Make optional parameter settings here */
3567dd7cddfSDavid du Colombier
3577dd7cddfSDavid du Colombier
3587dd7cddfSDavid du Colombier4. jpeg_start_compress(...);
3597dd7cddfSDavid du Colombier
3607dd7cddfSDavid du ColombierAfter you have established the data destination and set all the necessary
3617dd7cddfSDavid du Colombiersource image info and other parameters, call jpeg_start_compress() to begin
3627dd7cddfSDavid du Colombiera compression cycle.  This will initialize internal state, allocate working
3637dd7cddfSDavid du Colombierstorage, and emit the first few bytes of the JPEG datastream header.
3647dd7cddfSDavid du Colombier
3657dd7cddfSDavid du ColombierTypical code:
3667dd7cddfSDavid du Colombier
3677dd7cddfSDavid du Colombier	jpeg_start_compress(&cinfo, TRUE);
3687dd7cddfSDavid du Colombier
3697dd7cddfSDavid du ColombierThe "TRUE" parameter ensures that a complete JPEG interchange datastream
3707dd7cddfSDavid du Colombierwill be written.  This is appropriate in most cases.  If you think you might
3717dd7cddfSDavid du Colombierwant to use an abbreviated datastream, read the section on abbreviated
3727dd7cddfSDavid du Colombierdatastreams, below.
3737dd7cddfSDavid du Colombier
3747dd7cddfSDavid du ColombierOnce you have called jpeg_start_compress(), you may not alter any JPEG
3757dd7cddfSDavid du Colombierparameters or other fields of the JPEG object until you have completed
3767dd7cddfSDavid du Colombierthe compression cycle.
3777dd7cddfSDavid du Colombier
3787dd7cddfSDavid du Colombier
3797dd7cddfSDavid du Colombier5. while (scan lines remain to be written)
3807dd7cddfSDavid du Colombier	jpeg_write_scanlines(...);
3817dd7cddfSDavid du Colombier
3827dd7cddfSDavid du ColombierNow write all the required image data by calling jpeg_write_scanlines()
3837dd7cddfSDavid du Colombierone or more times.  You can pass one or more scanlines in each call, up
3847dd7cddfSDavid du Colombierto the total image height.  In most applications it is convenient to pass
3857dd7cddfSDavid du Colombierjust one or a few scanlines at a time.  The expected format for the passed
3867dd7cddfSDavid du Colombierdata is discussed under "Data formats", above.
3877dd7cddfSDavid du Colombier
3887dd7cddfSDavid du ColombierImage data should be written in top-to-bottom scanline order.  The JPEG spec
3897dd7cddfSDavid du Colombiercontains some weasel wording about how top and bottom are application-defined
3907dd7cddfSDavid du Colombierterms (a curious interpretation of the English language...) but if you want
3917dd7cddfSDavid du Colombieryour files to be compatible with everyone else's, you WILL use top-to-bottom
3927dd7cddfSDavid du Colombierorder.  If the source data must be read in bottom-to-top order, you can use
3937dd7cddfSDavid du Colombierthe JPEG library's virtual array mechanism to invert the data efficiently.
3947dd7cddfSDavid du ColombierExamples of this can be found in the sample application cjpeg.
3957dd7cddfSDavid du Colombier
3967dd7cddfSDavid du ColombierThe library maintains a count of the number of scanlines written so far
3977dd7cddfSDavid du Colombierin the next_scanline field of the JPEG object.  Usually you can just use
3987dd7cddfSDavid du Colombierthis variable as the loop counter, so that the loop test looks like
3997dd7cddfSDavid du Colombier"while (cinfo.next_scanline < cinfo.image_height)".
4007dd7cddfSDavid du Colombier
4017dd7cddfSDavid du ColombierCode for this step depends heavily on the way that you store the source data.
4027dd7cddfSDavid du Colombierexample.c shows the following code for the case of a full-size 2-D source
4037dd7cddfSDavid du Colombierarray containing 3-byte RGB pixels:
4047dd7cddfSDavid du Colombier
4057dd7cddfSDavid du Colombier	JSAMPROW row_pointer[1];	/* pointer to a single row */
4067dd7cddfSDavid du Colombier	int row_stride;			/* physical row width in buffer */
4077dd7cddfSDavid du Colombier
4087dd7cddfSDavid du Colombier	row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */
4097dd7cddfSDavid du Colombier
4107dd7cddfSDavid du Colombier	while (cinfo.next_scanline < cinfo.image_height) {
4117dd7cddfSDavid du Colombier	    row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
4127dd7cddfSDavid du Colombier	    jpeg_write_scanlines(&cinfo, row_pointer, 1);
4137dd7cddfSDavid du Colombier	}
4147dd7cddfSDavid du Colombier
4157dd7cddfSDavid du Colombierjpeg_write_scanlines() returns the number of scanlines actually written.
4167dd7cddfSDavid du ColombierThis will normally be equal to the number passed in, so you can usually
4177dd7cddfSDavid du Colombierignore the return value.  It is different in just two cases:
4187dd7cddfSDavid du Colombier  * If you try to write more scanlines than the declared image height,
4197dd7cddfSDavid du Colombier    the additional scanlines are ignored.
4207dd7cddfSDavid du Colombier  * If you use a suspending data destination manager, output buffer overrun
4217dd7cddfSDavid du Colombier    will cause the compressor to return before accepting all the passed lines.
4227dd7cddfSDavid du Colombier    This feature is discussed under "I/O suspension", below.  The normal
4237dd7cddfSDavid du Colombier    stdio destination manager will NOT cause this to happen.
4247dd7cddfSDavid du ColombierIn any case, the return value is the same as the change in the value of
4257dd7cddfSDavid du Colombiernext_scanline.
4267dd7cddfSDavid du Colombier
4277dd7cddfSDavid du Colombier
4287dd7cddfSDavid du Colombier6. jpeg_finish_compress(...);
4297dd7cddfSDavid du Colombier
4307dd7cddfSDavid du ColombierAfter all the image data has been written, call jpeg_finish_compress() to
4317dd7cddfSDavid du Colombiercomplete the compression cycle.  This step is ESSENTIAL to ensure that the
4327dd7cddfSDavid du Colombierlast bufferload of data is written to the data destination.
4337dd7cddfSDavid du Colombierjpeg_finish_compress() also releases working memory associated with the JPEG
4347dd7cddfSDavid du Colombierobject.
4357dd7cddfSDavid du Colombier
4367dd7cddfSDavid du ColombierTypical code:
4377dd7cddfSDavid du Colombier
4387dd7cddfSDavid du Colombier	jpeg_finish_compress(&cinfo);
4397dd7cddfSDavid du Colombier
4407dd7cddfSDavid du ColombierIf using the stdio destination manager, don't forget to close the output
441*593dc095SDavid du Colombierstdio stream (if necessary) afterwards.
4427dd7cddfSDavid du Colombier
4437dd7cddfSDavid du ColombierIf you have requested a multi-pass operating mode, such as Huffman code
4447dd7cddfSDavid du Colombieroptimization, jpeg_finish_compress() will perform the additional passes using
4457dd7cddfSDavid du Colombierdata buffered by the first pass.  In this case jpeg_finish_compress() may take
4467dd7cddfSDavid du Colombierquite a while to complete.  With the default compression parameters, this will
4477dd7cddfSDavid du Colombiernot happen.
4487dd7cddfSDavid du Colombier
4497dd7cddfSDavid du ColombierIt is an error to call jpeg_finish_compress() before writing the necessary
4507dd7cddfSDavid du Colombiertotal number of scanlines.  If you wish to abort compression, call
4517dd7cddfSDavid du Colombierjpeg_abort() as discussed below.
4527dd7cddfSDavid du Colombier
4537dd7cddfSDavid du ColombierAfter completing a compression cycle, you may dispose of the JPEG object
4547dd7cddfSDavid du Colombieras discussed next, or you may use it to compress another image.  In that case
4557dd7cddfSDavid du Colombierreturn to step 2, 3, or 4 as appropriate.  If you do not change the
4567dd7cddfSDavid du Colombierdestination manager, the new datastream will be written to the same target.
4577dd7cddfSDavid du ColombierIf you do not change any JPEG parameters, the new datastream will be written
4587dd7cddfSDavid du Colombierwith the same parameters as before.  Note that you can change the input image
4597dd7cddfSDavid du Colombierdimensions freely between cycles, but if you change the input colorspace, you
4607dd7cddfSDavid du Colombiershould call jpeg_set_defaults() to adjust for the new colorspace; and then
4617dd7cddfSDavid du Colombieryou'll need to repeat all of step 3.
4627dd7cddfSDavid du Colombier
4637dd7cddfSDavid du Colombier
4647dd7cddfSDavid du Colombier7. Release the JPEG compression object.
4657dd7cddfSDavid du Colombier
4667dd7cddfSDavid du ColombierWhen you are done with a JPEG compression object, destroy it by calling
467*593dc095SDavid du Colombierjpeg_destroy_compress().  This will free all subsidiary memory (regardless of
468*593dc095SDavid du Colombierthe previous state of the object).  Or you can call jpeg_destroy(), which
469*593dc095SDavid du Colombierworks for either compression or decompression objects --- this may be more
470*593dc095SDavid du Colombierconvenient if you are sharing code between compression and decompression
471*593dc095SDavid du Colombiercases.  (Actually, these routines are equivalent except for the declared type
472*593dc095SDavid du Colombierof the passed pointer.  To avoid gripes from ANSI C compilers, jpeg_destroy()
473*593dc095SDavid du Colombiershould be passed a j_common_ptr.)
4747dd7cddfSDavid du Colombier
4757dd7cddfSDavid du ColombierIf you allocated the jpeg_compress_struct structure from malloc(), freeing
4767dd7cddfSDavid du Colombierit is your responsibility --- jpeg_destroy() won't.  Ditto for the error
4777dd7cddfSDavid du Colombierhandler structure.
4787dd7cddfSDavid du Colombier
4797dd7cddfSDavid du ColombierTypical code:
4807dd7cddfSDavid du Colombier
4817dd7cddfSDavid du Colombier	jpeg_destroy_compress(&cinfo);
4827dd7cddfSDavid du Colombier
4837dd7cddfSDavid du Colombier
4847dd7cddfSDavid du Colombier8. Aborting.
4857dd7cddfSDavid du Colombier
4867dd7cddfSDavid du ColombierIf you decide to abort a compression cycle before finishing, you can clean up
4877dd7cddfSDavid du Colombierin either of two ways:
4887dd7cddfSDavid du Colombier
4897dd7cddfSDavid du Colombier* If you don't need the JPEG object any more, just call
4907dd7cddfSDavid du Colombier  jpeg_destroy_compress() or jpeg_destroy() to release memory.  This is
4917dd7cddfSDavid du Colombier  legitimate at any point after calling jpeg_create_compress() --- in fact,
4927dd7cddfSDavid du Colombier  it's safe even if jpeg_create_compress() fails.
4937dd7cddfSDavid du Colombier
494*593dc095SDavid du Colombier* If you want to re-use the JPEG object, call jpeg_abort_compress(), or call
4957dd7cddfSDavid du Colombier  jpeg_abort() which works on both compression and decompression objects.
4967dd7cddfSDavid du Colombier  This will return the object to an idle state, releasing any working memory.
4977dd7cddfSDavid du Colombier  jpeg_abort() is allowed at any time after successful object creation.
4987dd7cddfSDavid du Colombier
4997dd7cddfSDavid du ColombierNote that cleaning up the data destination, if required, is your
500*593dc095SDavid du Colombierresponsibility; neither of these routines will call term_destination().
501*593dc095SDavid du Colombier(See "Compressed data handling", below, for more about that.)
502*593dc095SDavid du Colombier
503*593dc095SDavid du Colombierjpeg_destroy() and jpeg_abort() are the only safe calls to make on a JPEG
504*593dc095SDavid du Colombierobject that has reported an error by calling error_exit (see "Error handling"
505*593dc095SDavid du Colombierfor more info).  The internal state of such an object is likely to be out of
506*593dc095SDavid du Colombierwhack.  Either of these two routines will return the object to a known state.
5077dd7cddfSDavid du Colombier
5087dd7cddfSDavid du Colombier
5097dd7cddfSDavid du ColombierDecompression details
5107dd7cddfSDavid du Colombier---------------------
5117dd7cddfSDavid du Colombier
5127dd7cddfSDavid du ColombierHere we revisit the JPEG decompression outline given in the overview.
5137dd7cddfSDavid du Colombier
5147dd7cddfSDavid du Colombier1. Allocate and initialize a JPEG decompression object.
5157dd7cddfSDavid du Colombier
5167dd7cddfSDavid du ColombierThis is just like initialization for compression, as discussed above,
5177dd7cddfSDavid du Colombierexcept that the object is a "struct jpeg_decompress_struct" and you
5187dd7cddfSDavid du Colombiercall jpeg_create_decompress().  Error handling is exactly the same.
5197dd7cddfSDavid du Colombier
5207dd7cddfSDavid du ColombierTypical code:
5217dd7cddfSDavid du Colombier
5227dd7cddfSDavid du Colombier	struct jpeg_decompress_struct cinfo;
5237dd7cddfSDavid du Colombier	struct jpeg_error_mgr jerr;
5247dd7cddfSDavid du Colombier	...
5257dd7cddfSDavid du Colombier	cinfo.err = jpeg_std_error(&jerr);
5267dd7cddfSDavid du Colombier	jpeg_create_decompress(&cinfo);
5277dd7cddfSDavid du Colombier
5287dd7cddfSDavid du Colombier(Both here and in the IJG code, we usually use variable name "cinfo" for
5297dd7cddfSDavid du Colombierboth compression and decompression objects.)
5307dd7cddfSDavid du Colombier
5317dd7cddfSDavid du Colombier
5327dd7cddfSDavid du Colombier2. Specify the source of the compressed data (eg, a file).
5337dd7cddfSDavid du Colombier
5347dd7cddfSDavid du ColombierAs previously mentioned, the JPEG library reads compressed data from a "data
5357dd7cddfSDavid du Colombiersource" module.  The library includes one data source module which knows how
5367dd7cddfSDavid du Colombierto read from a stdio stream.  You can use your own source module if you want
5377dd7cddfSDavid du Colombierto do something else, as discussed later.
5387dd7cddfSDavid du Colombier
5397dd7cddfSDavid du ColombierIf you use the standard source module, you must open the source stdio stream
5407dd7cddfSDavid du Colombierbeforehand.  Typical code for this step looks like:
5417dd7cddfSDavid du Colombier
5427dd7cddfSDavid du Colombier	FILE * infile;
5437dd7cddfSDavid du Colombier	...
5447dd7cddfSDavid du Colombier	if ((infile = fopen(filename, "rb")) == NULL) {
5457dd7cddfSDavid du Colombier	    fprintf(stderr, "can't open %s\n", filename);
5467dd7cddfSDavid du Colombier	    exit(1);
5477dd7cddfSDavid du Colombier	}
5487dd7cddfSDavid du Colombier	jpeg_stdio_src(&cinfo, infile);
5497dd7cddfSDavid du Colombier
5507dd7cddfSDavid du Colombierwhere the last line invokes the standard source module.
5517dd7cddfSDavid du Colombier
5527dd7cddfSDavid du ColombierWARNING: it is critical that the binary compressed data be read unchanged.
5537dd7cddfSDavid du ColombierOn non-Unix systems the stdio library may perform newline translation or
5547dd7cddfSDavid du Colombierotherwise corrupt binary data.  To suppress this behavior, you may need to use
5557dd7cddfSDavid du Colombiera "b" option to fopen (as shown above), or use setmode() or another routine to
5567dd7cddfSDavid du Colombierput the stdio stream in binary mode.  See cjpeg.c and djpeg.c for code that
5577dd7cddfSDavid du Colombierhas been found to work on many systems.
5587dd7cddfSDavid du Colombier
5597dd7cddfSDavid du ColombierYou may not change the data source between calling jpeg_read_header() and
5607dd7cddfSDavid du Colombierjpeg_finish_decompress().  If you wish to read a series of JPEG images from
5617dd7cddfSDavid du Colombiera single source file, you should repeat the jpeg_read_header() to
5627dd7cddfSDavid du Colombierjpeg_finish_decompress() sequence without reinitializing either the JPEG
5637dd7cddfSDavid du Colombierobject or the data source module; this prevents buffered input data from
5647dd7cddfSDavid du Colombierbeing discarded.
5657dd7cddfSDavid du Colombier
5667dd7cddfSDavid du Colombier
5677dd7cddfSDavid du Colombier3. Call jpeg_read_header() to obtain image info.
5687dd7cddfSDavid du Colombier
5697dd7cddfSDavid du ColombierTypical code for this step is just
5707dd7cddfSDavid du Colombier
5717dd7cddfSDavid du Colombier	jpeg_read_header(&cinfo, TRUE);
5727dd7cddfSDavid du Colombier
5737dd7cddfSDavid du ColombierThis will read the source datastream header markers, up to the beginning
5747dd7cddfSDavid du Colombierof the compressed data proper.  On return, the image dimensions and other
5757dd7cddfSDavid du Colombierinfo have been stored in the JPEG object.  The application may wish to
5767dd7cddfSDavid du Colombierconsult this information before selecting decompression parameters.
5777dd7cddfSDavid du Colombier
5787dd7cddfSDavid du ColombierMore complex code is necessary if
5797dd7cddfSDavid du Colombier  * A suspending data source is used --- in that case jpeg_read_header()
5807dd7cddfSDavid du Colombier    may return before it has read all the header data.  See "I/O suspension",
5817dd7cddfSDavid du Colombier    below.  The normal stdio source manager will NOT cause this to happen.
5827dd7cddfSDavid du Colombier  * Abbreviated JPEG files are to be processed --- see the section on
5837dd7cddfSDavid du Colombier    abbreviated datastreams.  Standard applications that deal only in
5847dd7cddfSDavid du Colombier    interchange JPEG files need not be concerned with this case either.
5857dd7cddfSDavid du Colombier
5867dd7cddfSDavid du ColombierIt is permissible to stop at this point if you just wanted to find out the
5877dd7cddfSDavid du Colombierimage dimensions and other header info for a JPEG file.  In that case,
5887dd7cddfSDavid du Colombiercall jpeg_destroy() when you are done with the JPEG object, or call
5897dd7cddfSDavid du Colombierjpeg_abort() to return it to an idle state before selecting a new data
5907dd7cddfSDavid du Colombiersource and reading another header.
5917dd7cddfSDavid du Colombier
5927dd7cddfSDavid du Colombier
5937dd7cddfSDavid du Colombier4. Set parameters for decompression.
5947dd7cddfSDavid du Colombier
5957dd7cddfSDavid du Colombierjpeg_read_header() sets appropriate default decompression parameters based on
5967dd7cddfSDavid du Colombierthe properties of the image (in particular, its colorspace).  However, you
5977dd7cddfSDavid du Colombiermay well want to alter these defaults before beginning the decompression.
5987dd7cddfSDavid du ColombierFor example, the default is to produce full color output from a color file.
5997dd7cddfSDavid du ColombierIf you want colormapped output you must ask for it.  Other options allow the
6007dd7cddfSDavid du Colombierreturned image to be scaled and allow various speed/quality tradeoffs to be
6017dd7cddfSDavid du Colombierselected.  "Decompression parameter selection", below, gives details.
6027dd7cddfSDavid du Colombier
6037dd7cddfSDavid du ColombierIf the defaults are appropriate, nothing need be done at this step.
6047dd7cddfSDavid du Colombier
6057dd7cddfSDavid du ColombierNote that all default values are set by each call to jpeg_read_header().
6067dd7cddfSDavid du ColombierIf you reuse a decompression object, you cannot expect your parameter
6077dd7cddfSDavid du Colombiersettings to be preserved across cycles, as you can for compression.
6087dd7cddfSDavid du ColombierYou must set desired parameter values each time.
6097dd7cddfSDavid du Colombier
6107dd7cddfSDavid du Colombier
6117dd7cddfSDavid du Colombier5. jpeg_start_decompress(...);
6127dd7cddfSDavid du Colombier
6137dd7cddfSDavid du ColombierOnce the parameter values are satisfactory, call jpeg_start_decompress() to
6147dd7cddfSDavid du Colombierbegin decompression.  This will initialize internal state, allocate working
6157dd7cddfSDavid du Colombiermemory, and prepare for returning data.
6167dd7cddfSDavid du Colombier
6177dd7cddfSDavid du ColombierTypical code is just
6187dd7cddfSDavid du Colombier
6197dd7cddfSDavid du Colombier	jpeg_start_decompress(&cinfo);
6207dd7cddfSDavid du Colombier
6217dd7cddfSDavid du ColombierIf you have requested a multi-pass operating mode, such as 2-pass color
6227dd7cddfSDavid du Colombierquantization, jpeg_start_decompress() will do everything needed before data
6237dd7cddfSDavid du Colombieroutput can begin.  In this case jpeg_start_decompress() may take quite a while
6247dd7cddfSDavid du Colombierto complete.  With a single-scan (non progressive) JPEG file and default
6257dd7cddfSDavid du Colombierdecompression parameters, this will not happen; jpeg_start_decompress() will
6267dd7cddfSDavid du Colombierreturn quickly.
6277dd7cddfSDavid du Colombier
6287dd7cddfSDavid du ColombierAfter this call, the final output image dimensions, including any requested
6297dd7cddfSDavid du Colombierscaling, are available in the JPEG object; so is the selected colormap, if
6307dd7cddfSDavid du Colombiercolormapped output has been requested.  Useful fields include
6317dd7cddfSDavid du Colombier
6327dd7cddfSDavid du Colombier	output_width		image width and height, as scaled
6337dd7cddfSDavid du Colombier	output_height
6347dd7cddfSDavid du Colombier	out_color_components	# of color components in out_color_space
6357dd7cddfSDavid du Colombier	output_components	# of color components returned per pixel
6367dd7cddfSDavid du Colombier	colormap		the selected colormap, if any
6377dd7cddfSDavid du Colombier	actual_number_of_colors		number of entries in colormap
6387dd7cddfSDavid du Colombier
6397dd7cddfSDavid du Colombieroutput_components is 1 (a colormap index) when quantizing colors; otherwise it
6407dd7cddfSDavid du Colombierequals out_color_components.  It is the number of JSAMPLE values that will be
6417dd7cddfSDavid du Colombieremitted per pixel in the output arrays.
6427dd7cddfSDavid du Colombier
6437dd7cddfSDavid du ColombierTypically you will need to allocate data buffers to hold the incoming image.
6447dd7cddfSDavid du ColombierYou will need output_width * output_components JSAMPLEs per scanline in your
6457dd7cddfSDavid du Colombieroutput buffer, and a total of output_height scanlines will be returned.
6467dd7cddfSDavid du Colombier
6477dd7cddfSDavid du ColombierNote: if you are using the JPEG library's internal memory manager to allocate
6487dd7cddfSDavid du Colombierdata buffers (as djpeg does), then the manager's protocol requires that you
6497dd7cddfSDavid du Colombierrequest large buffers *before* calling jpeg_start_decompress().  This is a
6507dd7cddfSDavid du Colombierlittle tricky since the output_XXX fields are not normally valid then.  You
6517dd7cddfSDavid du Colombiercan make them valid by calling jpeg_calc_output_dimensions() after setting the
6527dd7cddfSDavid du Colombierrelevant parameters (scaling, output color space, and quantization flag).
6537dd7cddfSDavid du Colombier
6547dd7cddfSDavid du Colombier
6557dd7cddfSDavid du Colombier6. while (scan lines remain to be read)
6567dd7cddfSDavid du Colombier	jpeg_read_scanlines(...);
6577dd7cddfSDavid du Colombier
6587dd7cddfSDavid du ColombierNow you can read the decompressed image data by calling jpeg_read_scanlines()
6597dd7cddfSDavid du Colombierone or more times.  At each call, you pass in the maximum number of scanlines
6607dd7cddfSDavid du Colombierto be read (ie, the height of your working buffer); jpeg_read_scanlines()
6617dd7cddfSDavid du Colombierwill return up to that many lines.  The return value is the number of lines
6627dd7cddfSDavid du Colombieractually read.  The format of the returned data is discussed under "Data
6637dd7cddfSDavid du Colombierformats", above.  Don't forget that grayscale and color JPEGs will return
6647dd7cddfSDavid du Colombierdifferent data formats!
6657dd7cddfSDavid du Colombier
6667dd7cddfSDavid du ColombierImage data is returned in top-to-bottom scanline order.  If you must write
6677dd7cddfSDavid du Colombierout the image in bottom-to-top order, you can use the JPEG library's virtual
6687dd7cddfSDavid du Colombierarray mechanism to invert the data efficiently.  Examples of this can be
6697dd7cddfSDavid du Colombierfound in the sample application djpeg.
6707dd7cddfSDavid du Colombier
6717dd7cddfSDavid du ColombierThe library maintains a count of the number of scanlines returned so far
6727dd7cddfSDavid du Colombierin the output_scanline field of the JPEG object.  Usually you can just use
6737dd7cddfSDavid du Colombierthis variable as the loop counter, so that the loop test looks like
6747dd7cddfSDavid du Colombier"while (cinfo.output_scanline < cinfo.output_height)".  (Note that the test
6757dd7cddfSDavid du Colombiershould NOT be against image_height, unless you never use scaling.  The
6767dd7cddfSDavid du Colombierimage_height field is the height of the original unscaled image.)
6777dd7cddfSDavid du ColombierThe return value always equals the change in the value of output_scanline.
6787dd7cddfSDavid du Colombier
6797dd7cddfSDavid du ColombierIf you don't use a suspending data source, it is safe to assume that
6807dd7cddfSDavid du Colombierjpeg_read_scanlines() reads at least one scanline per call, until the
6817dd7cddfSDavid du Colombierbottom of the image has been reached.
6827dd7cddfSDavid du Colombier
6837dd7cddfSDavid du ColombierIf you use a buffer larger than one scanline, it is NOT safe to assume that
684*593dc095SDavid du Colombierjpeg_read_scanlines() fills it.  (The current implementation returns only a
685*593dc095SDavid du Colombierfew scanlines per call, no matter how large a buffer you pass.)  So you must
686*593dc095SDavid du Colombieralways provide a loop that calls jpeg_read_scanlines() repeatedly until the
687*593dc095SDavid du Colombierwhole image has been read.
6887dd7cddfSDavid du Colombier
6897dd7cddfSDavid du Colombier
6907dd7cddfSDavid du Colombier7. jpeg_finish_decompress(...);
6917dd7cddfSDavid du Colombier
6927dd7cddfSDavid du ColombierAfter all the image data has been read, call jpeg_finish_decompress() to
6937dd7cddfSDavid du Colombiercomplete the decompression cycle.  This causes working memory associated
6947dd7cddfSDavid du Colombierwith the JPEG object to be released.
6957dd7cddfSDavid du Colombier
6967dd7cddfSDavid du ColombierTypical code:
6977dd7cddfSDavid du Colombier
6987dd7cddfSDavid du Colombier	jpeg_finish_decompress(&cinfo);
6997dd7cddfSDavid du Colombier
7007dd7cddfSDavid du ColombierIf using the stdio source manager, don't forget to close the source stdio
7017dd7cddfSDavid du Colombierstream if necessary.
7027dd7cddfSDavid du Colombier
7037dd7cddfSDavid du ColombierIt is an error to call jpeg_finish_decompress() before reading the correct
704*593dc095SDavid du Colombiertotal number of scanlines.  If you wish to abort decompression, call
7057dd7cddfSDavid du Colombierjpeg_abort() as discussed below.
7067dd7cddfSDavid du Colombier
7077dd7cddfSDavid du ColombierAfter completing a decompression cycle, you may dispose of the JPEG object as
7087dd7cddfSDavid du Colombierdiscussed next, or you may use it to decompress another image.  In that case
7097dd7cddfSDavid du Colombierreturn to step 2 or 3 as appropriate.  If you do not change the source
7107dd7cddfSDavid du Colombiermanager, the next image will be read from the same source.
7117dd7cddfSDavid du Colombier
7127dd7cddfSDavid du Colombier
7137dd7cddfSDavid du Colombier8. Release the JPEG decompression object.
7147dd7cddfSDavid du Colombier
7157dd7cddfSDavid du ColombierWhen you are done with a JPEG decompression object, destroy it by calling
7167dd7cddfSDavid du Colombierjpeg_destroy_decompress() or jpeg_destroy().  The previous discussion of
7177dd7cddfSDavid du Colombierdestroying compression objects applies here too.
7187dd7cddfSDavid du Colombier
7197dd7cddfSDavid du ColombierTypical code:
7207dd7cddfSDavid du Colombier
7217dd7cddfSDavid du Colombier	jpeg_destroy_decompress(&cinfo);
7227dd7cddfSDavid du Colombier
7237dd7cddfSDavid du Colombier
7247dd7cddfSDavid du Colombier9. Aborting.
7257dd7cddfSDavid du Colombier
7267dd7cddfSDavid du ColombierYou can abort a decompression cycle by calling jpeg_destroy_decompress() or
7277dd7cddfSDavid du Colombierjpeg_destroy() if you don't need the JPEG object any more, or
7287dd7cddfSDavid du Colombierjpeg_abort_decompress() or jpeg_abort() if you want to reuse the object.
7297dd7cddfSDavid du ColombierThe previous discussion of aborting compression cycles applies here too.
7307dd7cddfSDavid du Colombier
7317dd7cddfSDavid du Colombier
7327dd7cddfSDavid du ColombierMechanics of usage: include files, linking, etc
7337dd7cddfSDavid du Colombier-----------------------------------------------
7347dd7cddfSDavid du Colombier
7357dd7cddfSDavid du ColombierApplications using the JPEG library should include the header file jpeglib.h
7367dd7cddfSDavid du Colombierto obtain declarations of data types and routines.  Before including
7377dd7cddfSDavid du Colombierjpeglib.h, include system headers that define at least the typedefs FILE and
7387dd7cddfSDavid du Colombiersize_t.  On ANSI-conforming systems, including <stdio.h> is sufficient; on
7397dd7cddfSDavid du Colombierolder Unix systems, you may need <sys/types.h> to define size_t.
7407dd7cddfSDavid du Colombier
7417dd7cddfSDavid du ColombierIf the application needs to refer to individual JPEG library error codes, also
7427dd7cddfSDavid du Colombierinclude jerror.h to define those symbols.
7437dd7cddfSDavid du Colombier
7447dd7cddfSDavid du Colombierjpeglib.h indirectly includes the files jconfig.h and jmorecfg.h.  If you are
7457dd7cddfSDavid du Colombierinstalling the JPEG header files in a system directory, you will want to
7467dd7cddfSDavid du Colombierinstall all four files: jpeglib.h, jerror.h, jconfig.h, jmorecfg.h.
7477dd7cddfSDavid du Colombier
7487dd7cddfSDavid du ColombierThe most convenient way to include the JPEG code into your executable program
7497dd7cddfSDavid du Colombieris to prepare a library file ("libjpeg.a", or a corresponding name on non-Unix
7507dd7cddfSDavid du Colombiermachines) and reference it at your link step.  If you use only half of the
7517dd7cddfSDavid du Colombierlibrary (only compression or only decompression), only that much code will be
7527dd7cddfSDavid du Colombierincluded from the library, unless your linker is hopelessly brain-damaged.
7537dd7cddfSDavid du ColombierThe supplied makefiles build libjpeg.a automatically (see install.doc).
7547dd7cddfSDavid du Colombier
755*593dc095SDavid du ColombierWhile you can build the JPEG library as a shared library if the whim strikes
756*593dc095SDavid du Colombieryou, we don't really recommend it.  The trouble with shared libraries is that
757*593dc095SDavid du Colombierat some point you'll probably try to substitute a new version of the library
758*593dc095SDavid du Colombierwithout recompiling the calling applications.  That generally doesn't work
759*593dc095SDavid du Colombierbecause the parameter struct declarations usually change with each new
760*593dc095SDavid du Colombierversion.  In other words, the library's API is *not* guaranteed binary
761*593dc095SDavid du Colombiercompatible across versions; we only try to ensure source-code compatibility.
762*593dc095SDavid du Colombier(In hindsight, it might have been smarter to hide the parameter structs from
763*593dc095SDavid du Colombierapplications and introduce a ton of access functions instead.  Too late now,
764*593dc095SDavid du Colombierhowever.)
765*593dc095SDavid du Colombier
7667dd7cddfSDavid du ColombierOn some systems your application may need to set up a signal handler to ensure
7677dd7cddfSDavid du Colombierthat temporary files are deleted if the program is interrupted.  This is most
7687dd7cddfSDavid du Colombiercritical if you are on MS-DOS and use the jmemdos.c memory manager back end;
7697dd7cddfSDavid du Colombierit will try to grab extended memory for temp files, and that space will NOT be
7707dd7cddfSDavid du Colombierfreed automatically.  See cjpeg.c or djpeg.c for an example signal handler.
7717dd7cddfSDavid du Colombier
7727dd7cddfSDavid du ColombierIt may be worth pointing out that the core JPEG library does not actually
7737dd7cddfSDavid du Colombierrequire the stdio library: only the default source/destination managers and
7747dd7cddfSDavid du Colombiererror handler need it.  You can use the library in a stdio-less environment
7757dd7cddfSDavid du Colombierif you replace those modules and use jmemnobs.c (or another memory manager of
7767dd7cddfSDavid du Colombieryour own devising).  More info about the minimum system library requirements
7777dd7cddfSDavid du Colombiermay be found in jinclude.h.
7787dd7cddfSDavid du Colombier
7797dd7cddfSDavid du Colombier
7807dd7cddfSDavid du ColombierADVANCED FEATURES
7817dd7cddfSDavid du Colombier=================
7827dd7cddfSDavid du Colombier
7837dd7cddfSDavid du ColombierCompression parameter selection
7847dd7cddfSDavid du Colombier-------------------------------
7857dd7cddfSDavid du Colombier
7867dd7cddfSDavid du ColombierThis section describes all the optional parameters you can set for JPEG
7877dd7cddfSDavid du Colombiercompression, as well as the "helper" routines provided to assist in this
7887dd7cddfSDavid du Colombiertask.  Proper setting of some parameters requires detailed understanding
7897dd7cddfSDavid du Colombierof the JPEG standard; if you don't know what a parameter is for, it's best
7907dd7cddfSDavid du Colombiernot to mess with it!  See REFERENCES in the README file for pointers to
7917dd7cddfSDavid du Colombiermore info about JPEG.
7927dd7cddfSDavid du Colombier
7937dd7cddfSDavid du ColombierIt's a good idea to call jpeg_set_defaults() first, even if you plan to set
7947dd7cddfSDavid du Colombierall the parameters; that way your code is more likely to work with future JPEG
7957dd7cddfSDavid du Colombierlibraries that have additional parameters.  For the same reason, we recommend
7967dd7cddfSDavid du Colombieryou use a helper routine where one is provided, in preference to twiddling
7977dd7cddfSDavid du Colombiercinfo fields directly.
7987dd7cddfSDavid du Colombier
7997dd7cddfSDavid du ColombierThe helper routines are:
8007dd7cddfSDavid du Colombier
8017dd7cddfSDavid du Colombierjpeg_set_defaults (j_compress_ptr cinfo)
8027dd7cddfSDavid du Colombier	This routine sets all JPEG parameters to reasonable defaults, using
8037dd7cddfSDavid du Colombier	only the input image's color space (field in_color_space, which must
8047dd7cddfSDavid du Colombier	already be set in cinfo).  Many applications will only need to use
8057dd7cddfSDavid du Colombier	this routine and perhaps jpeg_set_quality().
8067dd7cddfSDavid du Colombier
8077dd7cddfSDavid du Colombierjpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
8087dd7cddfSDavid du Colombier	Sets the JPEG file's colorspace (field jpeg_color_space) as specified,
8097dd7cddfSDavid du Colombier	and sets other color-space-dependent parameters appropriately.  See
8107dd7cddfSDavid du Colombier	"Special color spaces", below, before using this.  A large number of
8117dd7cddfSDavid du Colombier	parameters, including all per-component parameters, are set by this
8127dd7cddfSDavid du Colombier	routine; if you want to twiddle individual parameters you should call
8137dd7cddfSDavid du Colombier	jpeg_set_colorspace() before rather than after.
8147dd7cddfSDavid du Colombier
8157dd7cddfSDavid du Colombierjpeg_default_colorspace (j_compress_ptr cinfo)
8167dd7cddfSDavid du Colombier	Selects an appropriate JPEG colorspace based on cinfo->in_color_space,
8177dd7cddfSDavid du Colombier	and calls jpeg_set_colorspace().  This is actually a subroutine of
8187dd7cddfSDavid du Colombier	jpeg_set_defaults().  It's broken out in case you want to change
8197dd7cddfSDavid du Colombier	just the colorspace-dependent JPEG parameters.
8207dd7cddfSDavid du Colombier
8217dd7cddfSDavid du Colombierjpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
8227dd7cddfSDavid du Colombier	Constructs JPEG quantization tables appropriate for the indicated
8237dd7cddfSDavid du Colombier	quality setting.  The quality value is expressed on the 0..100 scale
8247dd7cddfSDavid du Colombier	recommended by IJG (cjpeg's "-quality" switch uses this routine).
8257dd7cddfSDavid du Colombier	Note that the exact mapping from quality values to tables may change
8267dd7cddfSDavid du Colombier	in future IJG releases as more is learned about DCT quantization.
8277dd7cddfSDavid du Colombier	If the force_baseline parameter is TRUE, then the quantization table
8287dd7cddfSDavid du Colombier	entries are constrained to the range 1..255 for full JPEG baseline
8297dd7cddfSDavid du Colombier	compatibility.  In the current implementation, this only makes a
8307dd7cddfSDavid du Colombier	difference for quality settings below 25, and it effectively prevents
8317dd7cddfSDavid du Colombier	very small/low quality files from being generated.  The IJG decoder
8327dd7cddfSDavid du Colombier	is capable of reading the non-baseline files generated at low quality
8337dd7cddfSDavid du Colombier	settings when force_baseline is FALSE, but other decoders may not be.
8347dd7cddfSDavid du Colombier
8357dd7cddfSDavid du Colombierjpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
8367dd7cddfSDavid du Colombier			 boolean force_baseline)
8377dd7cddfSDavid du Colombier	Same as jpeg_set_quality() except that the generated tables are the
8387dd7cddfSDavid du Colombier	sample tables given in the JPEC spec section K.1, multiplied by the
8397dd7cddfSDavid du Colombier	specified scale factor (which is expressed as a percentage; thus
8407dd7cddfSDavid du Colombier	scale_factor = 100 reproduces the spec's tables).  Note that larger
8417dd7cddfSDavid du Colombier	scale factors give lower quality.  This entry point is useful for
8427dd7cddfSDavid du Colombier	conforming to the Adobe PostScript DCT conventions, but we do not
8437dd7cddfSDavid du Colombier	recommend linear scaling as a user-visible quality scale otherwise.
8447dd7cddfSDavid du Colombier	force_baseline again constrains the computed table entries to 1..255.
8457dd7cddfSDavid du Colombier
8467dd7cddfSDavid du Colombierint jpeg_quality_scaling (int quality)
8477dd7cddfSDavid du Colombier	Converts a value on the IJG-recommended quality scale to a linear
8487dd7cddfSDavid du Colombier	scaling percentage.  Note that this routine may change or go away
8497dd7cddfSDavid du Colombier	in future releases --- IJG may choose to adopt a scaling method that
8507dd7cddfSDavid du Colombier	can't be expressed as a simple scalar multiplier, in which case the
8517dd7cddfSDavid du Colombier	premise of this routine collapses.  Caveat user.
8527dd7cddfSDavid du Colombier
8537dd7cddfSDavid du Colombierjpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
8547dd7cddfSDavid du Colombier		      const unsigned int *basic_table,
8557dd7cddfSDavid du Colombier		      int scale_factor, boolean force_baseline)
8567dd7cddfSDavid du Colombier	Allows an arbitrary quantization table to be created.  which_tbl
8577dd7cddfSDavid du Colombier	indicates which table slot to fill.  basic_table points to an array
8587dd7cddfSDavid du Colombier	of 64 unsigned ints given in normal array order.  These values are
8597dd7cddfSDavid du Colombier	multiplied by scale_factor/100 and then clamped to the range 1..65535
8607dd7cddfSDavid du Colombier	(or to 1..255 if force_baseline is TRUE).
8617dd7cddfSDavid du Colombier	CAUTION: prior to library version 6a, jpeg_add_quant_table expected
8627dd7cddfSDavid du Colombier	the basic table to be given in JPEG zigzag order.  If you need to
8637dd7cddfSDavid du Colombier	write code that works with either older or newer versions of this
8647dd7cddfSDavid du Colombier	routine, you must check the library version number.  Something like
8657dd7cddfSDavid du Colombier	"#if JPEG_LIB_VERSION >= 61" is the right test.
8667dd7cddfSDavid du Colombier
8677dd7cddfSDavid du Colombierjpeg_simple_progression (j_compress_ptr cinfo)
8687dd7cddfSDavid du Colombier	Generates a default scan script for writing a progressive-JPEG file.
8697dd7cddfSDavid du Colombier	This is the recommended method of creating a progressive file,
8707dd7cddfSDavid du Colombier	unless you want to make a custom scan sequence.  You must ensure that
8717dd7cddfSDavid du Colombier	the JPEG color space is set correctly before calling this routine.
8727dd7cddfSDavid du Colombier
8737dd7cddfSDavid du Colombier
8747dd7cddfSDavid du ColombierCompression parameters (cinfo fields) include:
8757dd7cddfSDavid du Colombier
8767dd7cddfSDavid du ColombierJ_DCT_METHOD dct_method
8777dd7cddfSDavid du Colombier	Selects the algorithm used for the DCT step.  Choices are:
8787dd7cddfSDavid du Colombier		JDCT_ISLOW: slow but accurate integer algorithm
8797dd7cddfSDavid du Colombier		JDCT_IFAST: faster, less accurate integer method
8807dd7cddfSDavid du Colombier		JDCT_FLOAT: floating-point method
8817dd7cddfSDavid du Colombier		JDCT_DEFAULT: default method (normally JDCT_ISLOW)
8827dd7cddfSDavid du Colombier		JDCT_FASTEST: fastest method (normally JDCT_IFAST)
8837dd7cddfSDavid du Colombier	The FLOAT method is very slightly more accurate than the ISLOW method,
8847dd7cddfSDavid du Colombier	but may give different results on different machines due to varying
8857dd7cddfSDavid du Colombier	roundoff behavior.  The integer methods should give the same results
8867dd7cddfSDavid du Colombier	on all machines.  On machines with sufficiently fast FP hardware, the
8877dd7cddfSDavid du Colombier	floating-point method may also be the fastest.  The IFAST method is
8887dd7cddfSDavid du Colombier	considerably less accurate than the other two; its use is not
8897dd7cddfSDavid du Colombier	recommended if high quality is a concern.  JDCT_DEFAULT and
8907dd7cddfSDavid du Colombier	JDCT_FASTEST are macros configurable by each installation.
8917dd7cddfSDavid du Colombier
8927dd7cddfSDavid du ColombierJ_COLOR_SPACE jpeg_color_space
8937dd7cddfSDavid du Colombierint num_components
8947dd7cddfSDavid du Colombier	The JPEG color space and corresponding number of components; see
8957dd7cddfSDavid du Colombier	"Special color spaces", below, for more info.  We recommend using
8967dd7cddfSDavid du Colombier	jpeg_set_color_space() if you want to change these.
8977dd7cddfSDavid du Colombier
8987dd7cddfSDavid du Colombierboolean optimize_coding
8997dd7cddfSDavid du Colombier	TRUE causes the compressor to compute optimal Huffman coding tables
9007dd7cddfSDavid du Colombier	for the image.  This requires an extra pass over the data and
9017dd7cddfSDavid du Colombier	therefore costs a good deal of space and time.  The default is
9027dd7cddfSDavid du Colombier	FALSE, which tells the compressor to use the supplied or default
9037dd7cddfSDavid du Colombier	Huffman tables.  In most cases optimal tables save only a few percent
9047dd7cddfSDavid du Colombier	of file size compared to the default tables.  Note that when this is
9057dd7cddfSDavid du Colombier	TRUE, you need not supply Huffman tables at all, and any you do
9067dd7cddfSDavid du Colombier	supply will be overwritten.
9077dd7cddfSDavid du Colombier
9087dd7cddfSDavid du Colombierunsigned int restart_interval
9097dd7cddfSDavid du Colombierint restart_in_rows
9107dd7cddfSDavid du Colombier	To emit restart markers in the JPEG file, set one of these nonzero.
9117dd7cddfSDavid du Colombier	Set restart_interval to specify the exact interval in MCU blocks.
9127dd7cddfSDavid du Colombier	Set restart_in_rows to specify the interval in MCU rows.  (If
9137dd7cddfSDavid du Colombier	restart_in_rows is not 0, then restart_interval is set after the
9147dd7cddfSDavid du Colombier	image width in MCUs is computed.)  Defaults are zero (no restarts).
915*593dc095SDavid du Colombier	One restart marker per MCU row is often a good choice.
916*593dc095SDavid du Colombier	NOTE: the overhead of restart markers is higher in grayscale JPEG
917*593dc095SDavid du Colombier	files than in color files, and MUCH higher in progressive JPEGs.
918*593dc095SDavid du Colombier	If you use restarts, you may want to use larger intervals in those
919*593dc095SDavid du Colombier	cases.
9207dd7cddfSDavid du Colombier
9217dd7cddfSDavid du Colombierconst jpeg_scan_info * scan_info
9227dd7cddfSDavid du Colombierint num_scans
9237dd7cddfSDavid du Colombier	By default, scan_info is NULL; this causes the compressor to write a
9247dd7cddfSDavid du Colombier	single-scan sequential JPEG file.  If not NULL, scan_info points to
9257dd7cddfSDavid du Colombier	an array of scan definition records of length num_scans.  The
9267dd7cddfSDavid du Colombier	compressor will then write a JPEG file having one scan for each scan
9277dd7cddfSDavid du Colombier	definition record.  This is used to generate noninterleaved or
9287dd7cddfSDavid du Colombier	progressive JPEG files.  The library checks that the scan array
9297dd7cddfSDavid du Colombier	defines a valid JPEG scan sequence.  (jpeg_simple_progression creates
9307dd7cddfSDavid du Colombier	a suitable scan definition array for progressive JPEG.)  This is
9317dd7cddfSDavid du Colombier	discussed further under "Progressive JPEG support".
9327dd7cddfSDavid du Colombier
9337dd7cddfSDavid du Colombierint smoothing_factor
9347dd7cddfSDavid du Colombier	If non-zero, the input image is smoothed; the value should be 1 for
9357dd7cddfSDavid du Colombier	minimal smoothing to 100 for maximum smoothing.  Consult jcsample.c
9367dd7cddfSDavid du Colombier	for details of the smoothing algorithm.  The default is zero.
9377dd7cddfSDavid du Colombier
9387dd7cddfSDavid du Colombierboolean write_JFIF_header
9397dd7cddfSDavid du Colombier	If TRUE, a JFIF APP0 marker is emitted.  jpeg_set_defaults() and
9407dd7cddfSDavid du Colombier	jpeg_set_colorspace() set this TRUE if a JFIF-legal JPEG color space
9417dd7cddfSDavid du Colombier	(ie, YCbCr or grayscale) is selected, otherwise FALSE.
9427dd7cddfSDavid du Colombier
943*593dc095SDavid du ColombierUINT8 JFIF_major_version
944*593dc095SDavid du ColombierUINT8 JFIF_minor_version
945*593dc095SDavid du Colombier	The version number to be written into the JFIF marker.
946*593dc095SDavid du Colombier	jpeg_set_defaults() initializes the version to 1.01 (major=minor=1).
947*593dc095SDavid du Colombier	You should set it to 1.02 (major=1, minor=2) if you plan to write
948*593dc095SDavid du Colombier	any JFIF 1.02 extension markers.
949*593dc095SDavid du Colombier
9507dd7cddfSDavid du ColombierUINT8 density_unit
9517dd7cddfSDavid du ColombierUINT16 X_density
9527dd7cddfSDavid du ColombierUINT16 Y_density
9537dd7cddfSDavid du Colombier	The resolution information to be written into the JFIF marker;
9547dd7cddfSDavid du Colombier	not used otherwise.  density_unit may be 0 for unknown,
9557dd7cddfSDavid du Colombier	1 for dots/inch, or 2 for dots/cm.  The default values are 0,1,1
9567dd7cddfSDavid du Colombier	indicating square pixels of unknown size.
9577dd7cddfSDavid du Colombier
9587dd7cddfSDavid du Colombierboolean write_Adobe_marker
9597dd7cddfSDavid du Colombier	If TRUE, an Adobe APP14 marker is emitted.  jpeg_set_defaults() and
9607dd7cddfSDavid du Colombier	jpeg_set_colorspace() set this TRUE if JPEG color space RGB, CMYK,
9617dd7cddfSDavid du Colombier	or YCCK is selected, otherwise FALSE.  It is generally a bad idea
9627dd7cddfSDavid du Colombier	to set both write_JFIF_header and write_Adobe_marker.  In fact,
9637dd7cddfSDavid du Colombier	you probably shouldn't change the default settings at all --- the
9647dd7cddfSDavid du Colombier	default behavior ensures that the JPEG file's color space can be
9657dd7cddfSDavid du Colombier	recognized by the decoder.
9667dd7cddfSDavid du Colombier
9677dd7cddfSDavid du ColombierJQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]
9687dd7cddfSDavid du Colombier	Pointers to coefficient quantization tables, one per table slot,
9697dd7cddfSDavid du Colombier	or NULL if no table is defined for a slot.  Usually these should
9707dd7cddfSDavid du Colombier	be set via one of the above helper routines; jpeg_add_quant_table()
9717dd7cddfSDavid du Colombier	is general enough to define any quantization table.  The other
9727dd7cddfSDavid du Colombier	routines will set up table slot 0 for luminance quality and table
9737dd7cddfSDavid du Colombier	slot 1 for chrominance.
9747dd7cddfSDavid du Colombier
9757dd7cddfSDavid du ColombierJHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]
9767dd7cddfSDavid du ColombierJHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]
9777dd7cddfSDavid du Colombier	Pointers to Huffman coding tables, one per table slot, or NULL if
9787dd7cddfSDavid du Colombier	no table is defined for a slot.  Slots 0 and 1 are filled with the
9797dd7cddfSDavid du Colombier	JPEG sample tables by jpeg_set_defaults().  If you need to allocate
9807dd7cddfSDavid du Colombier	more table structures, jpeg_alloc_huff_table() may be used.
9817dd7cddfSDavid du Colombier	Note that optimal Huffman tables can be computed for an image
9827dd7cddfSDavid du Colombier	by setting optimize_coding, as discussed above; there's seldom
9837dd7cddfSDavid du Colombier	any need to mess with providing your own Huffman tables.
9847dd7cddfSDavid du Colombier
9857dd7cddfSDavid du ColombierThere are some additional cinfo fields which are not documented here
9867dd7cddfSDavid du Colombierbecause you currently can't change them; for example, you can't set
9877dd7cddfSDavid du Colombierarith_code TRUE because arithmetic coding is unsupported.
9887dd7cddfSDavid du Colombier
9897dd7cddfSDavid du Colombier
9907dd7cddfSDavid du ColombierPer-component parameters are stored in the struct cinfo.comp_info[i] for
9917dd7cddfSDavid du Colombiercomponent number i.  Note that components here refer to components of the
9927dd7cddfSDavid du ColombierJPEG color space, *not* the source image color space.  A suitably large
9937dd7cddfSDavid du Colombiercomp_info[] array is allocated by jpeg_set_defaults(); if you choose not
9947dd7cddfSDavid du Colombierto use that routine, it's up to you to allocate the array.
9957dd7cddfSDavid du Colombier
9967dd7cddfSDavid du Colombierint component_id
9977dd7cddfSDavid du Colombier	The one-byte identifier code to be recorded in the JPEG file for
9987dd7cddfSDavid du Colombier	this component.  For the standard color spaces, we recommend you
9997dd7cddfSDavid du Colombier	leave the default values alone.
10007dd7cddfSDavid du Colombier
10017dd7cddfSDavid du Colombierint h_samp_factor
10027dd7cddfSDavid du Colombierint v_samp_factor
10037dd7cddfSDavid du Colombier	Horizontal and vertical sampling factors for the component; must
10047dd7cddfSDavid du Colombier	be 1..4 according to the JPEG standard.  Note that larger sampling
10057dd7cddfSDavid du Colombier	factors indicate a higher-resolution component; many people find
10067dd7cddfSDavid du Colombier	this behavior quite unintuitive.  The default values are 2,2 for
10077dd7cddfSDavid du Colombier	luminance components and 1,1 for chrominance components, except
10087dd7cddfSDavid du Colombier	for grayscale where 1,1 is used.
10097dd7cddfSDavid du Colombier
10107dd7cddfSDavid du Colombierint quant_tbl_no
10117dd7cddfSDavid du Colombier	Quantization table number for component.  The default value is
10127dd7cddfSDavid du Colombier	0 for luminance components and 1 for chrominance components.
10137dd7cddfSDavid du Colombier
10147dd7cddfSDavid du Colombierint dc_tbl_no
10157dd7cddfSDavid du Colombierint ac_tbl_no
10167dd7cddfSDavid du Colombier	DC and AC entropy coding table numbers.  The default values are
10177dd7cddfSDavid du Colombier	0 for luminance components and 1 for chrominance components.
10187dd7cddfSDavid du Colombier
10197dd7cddfSDavid du Colombierint component_index
10207dd7cddfSDavid du Colombier	Must equal the component's index in comp_info[].  (Beginning in
10217dd7cddfSDavid du Colombier	release v6, the compressor library will fill this in automatically;
10227dd7cddfSDavid du Colombier	you don't have to.)
10237dd7cddfSDavid du Colombier
10247dd7cddfSDavid du Colombier
10257dd7cddfSDavid du ColombierDecompression parameter selection
10267dd7cddfSDavid du Colombier---------------------------------
10277dd7cddfSDavid du Colombier
10287dd7cddfSDavid du ColombierDecompression parameter selection is somewhat simpler than compression
10297dd7cddfSDavid du Colombierparameter selection, since all of the JPEG internal parameters are
10307dd7cddfSDavid du Colombierrecorded in the source file and need not be supplied by the application.
10317dd7cddfSDavid du Colombier(Unless you are working with abbreviated files, in which case see
10327dd7cddfSDavid du Colombier"Abbreviated datastreams", below.)  Decompression parameters control
10337dd7cddfSDavid du Colombierthe postprocessing done on the image to deliver it in a format suitable
10347dd7cddfSDavid du Colombierfor the application's use.  Many of the parameters control speed/quality
10357dd7cddfSDavid du Colombiertradeoffs, in which faster decompression may be obtained at the price of
10367dd7cddfSDavid du Colombiera poorer-quality image.  The defaults select the highest quality (slowest)
10377dd7cddfSDavid du Colombierprocessing.
10387dd7cddfSDavid du Colombier
10397dd7cddfSDavid du ColombierThe following fields in the JPEG object are set by jpeg_read_header() and
10407dd7cddfSDavid du Colombiermay be useful to the application in choosing decompression parameters:
10417dd7cddfSDavid du Colombier
10427dd7cddfSDavid du ColombierJDIMENSION image_width			Width and height of image
10437dd7cddfSDavid du ColombierJDIMENSION image_height
10447dd7cddfSDavid du Colombierint num_components			Number of color components
10457dd7cddfSDavid du ColombierJ_COLOR_SPACE jpeg_color_space		Colorspace of image
10467dd7cddfSDavid du Colombierboolean saw_JFIF_marker			TRUE if a JFIF APP0 marker was seen
1047*593dc095SDavid du Colombier  UINT8 JFIF_major_version		Version information from JFIF marker
1048*593dc095SDavid du Colombier  UINT8 JFIF_minor_version
10497dd7cddfSDavid du Colombier  UINT8 density_unit			Resolution data from JFIF marker
10507dd7cddfSDavid du Colombier  UINT16 X_density
10517dd7cddfSDavid du Colombier  UINT16 Y_density
10527dd7cddfSDavid du Colombierboolean saw_Adobe_marker		TRUE if an Adobe APP14 marker was seen
10537dd7cddfSDavid du Colombier  UINT8 Adobe_transform			Color transform code from Adobe marker
10547dd7cddfSDavid du Colombier
10557dd7cddfSDavid du ColombierThe JPEG color space, unfortunately, is something of a guess since the JPEG
10567dd7cddfSDavid du Colombierstandard proper does not provide a way to record it.  In practice most files
10577dd7cddfSDavid du Colombieradhere to the JFIF or Adobe conventions, and the decoder will recognize these
10587dd7cddfSDavid du Colombiercorrectly.  See "Special color spaces", below, for more info.
10597dd7cddfSDavid du Colombier
10607dd7cddfSDavid du Colombier
10617dd7cddfSDavid du ColombierThe decompression parameters that determine the basic properties of the
10627dd7cddfSDavid du Colombierreturned image are:
10637dd7cddfSDavid du Colombier
10647dd7cddfSDavid du ColombierJ_COLOR_SPACE out_color_space
10657dd7cddfSDavid du Colombier	Output color space.  jpeg_read_header() sets an appropriate default
10667dd7cddfSDavid du Colombier	based on jpeg_color_space; typically it will be RGB or grayscale.
10677dd7cddfSDavid du Colombier	The application can change this field to request output in a different
10687dd7cddfSDavid du Colombier	colorspace.  For example, set it to JCS_GRAYSCALE to get grayscale
10697dd7cddfSDavid du Colombier	output from a color file.  (This is useful for previewing: grayscale
10707dd7cddfSDavid du Colombier	output is faster than full color since the color components need not
10717dd7cddfSDavid du Colombier	be processed.)  Note that not all possible color space transforms are
10727dd7cddfSDavid du Colombier	currently implemented; you may need to extend jdcolor.c if you want an
10737dd7cddfSDavid du Colombier	unusual conversion.
10747dd7cddfSDavid du Colombier
10757dd7cddfSDavid du Colombierunsigned int scale_num, scale_denom
10767dd7cddfSDavid du Colombier	Scale the image by the fraction scale_num/scale_denom.  Default is
10777dd7cddfSDavid du Colombier	1/1, or no scaling.  Currently, the only supported scaling ratios
10787dd7cddfSDavid du Colombier	are 1/1, 1/2, 1/4, and 1/8.  (The library design allows for arbitrary
10797dd7cddfSDavid du Colombier	scaling ratios but this is not likely to be implemented any time soon.)
10807dd7cddfSDavid du Colombier	Smaller scaling ratios permit significantly faster decoding since
10817dd7cddfSDavid du Colombier	fewer pixels need be processed and a simpler IDCT method can be used.
10827dd7cddfSDavid du Colombier
10837dd7cddfSDavid du Colombierboolean quantize_colors
10847dd7cddfSDavid du Colombier	If set TRUE, colormapped output will be delivered.  Default is FALSE,
10857dd7cddfSDavid du Colombier	meaning that full-color output will be delivered.
10867dd7cddfSDavid du Colombier
10877dd7cddfSDavid du ColombierThe next three parameters are relevant only if quantize_colors is TRUE.
10887dd7cddfSDavid du Colombier
10897dd7cddfSDavid du Colombierint desired_number_of_colors
10907dd7cddfSDavid du Colombier	Maximum number of colors to use in generating a library-supplied color
10917dd7cddfSDavid du Colombier	map (the actual number of colors is returned in a different field).
10927dd7cddfSDavid du Colombier	Default 256.  Ignored when the application supplies its own color map.
10937dd7cddfSDavid du Colombier
10947dd7cddfSDavid du Colombierboolean two_pass_quantize
10957dd7cddfSDavid du Colombier	If TRUE, an extra pass over the image is made to select a custom color
10967dd7cddfSDavid du Colombier	map for the image.  This usually looks a lot better than the one-size-
10977dd7cddfSDavid du Colombier	fits-all colormap that is used otherwise.  Default is TRUE.  Ignored
10987dd7cddfSDavid du Colombier	when the application supplies its own color map.
10997dd7cddfSDavid du Colombier
11007dd7cddfSDavid du ColombierJ_DITHER_MODE dither_mode
11017dd7cddfSDavid du Colombier	Selects color dithering method.  Supported values are:
11027dd7cddfSDavid du Colombier		JDITHER_NONE	no dithering: fast, very low quality
11037dd7cddfSDavid du Colombier		JDITHER_ORDERED	ordered dither: moderate speed and quality
11047dd7cddfSDavid du Colombier		JDITHER_FS	Floyd-Steinberg dither: slow, high quality
11057dd7cddfSDavid du Colombier	Default is JDITHER_FS.  (At present, ordered dither is implemented
11067dd7cddfSDavid du Colombier	only in the single-pass, standard-colormap case.  If you ask for
11077dd7cddfSDavid du Colombier	ordered dither when two_pass_quantize is TRUE or when you supply
11087dd7cddfSDavid du Colombier	an external color map, you'll get F-S dithering.)
11097dd7cddfSDavid du Colombier
11107dd7cddfSDavid du ColombierWhen quantize_colors is TRUE, the target color map is described by the next
11117dd7cddfSDavid du Colombiertwo fields.  colormap is set to NULL by jpeg_read_header().  The application
11127dd7cddfSDavid du Colombiercan supply a color map by setting colormap non-NULL and setting
11137dd7cddfSDavid du Colombieractual_number_of_colors to the map size.  Otherwise, jpeg_start_decompress()
11147dd7cddfSDavid du Colombierselects a suitable color map and sets these two fields itself.
11157dd7cddfSDavid du Colombier[Implementation restriction: at present, an externally supplied colormap is
11167dd7cddfSDavid du Colombieronly accepted for 3-component output color spaces.]
11177dd7cddfSDavid du Colombier
11187dd7cddfSDavid du ColombierJSAMPARRAY colormap
11197dd7cddfSDavid du Colombier	The color map, represented as a 2-D pixel array of out_color_components
11207dd7cddfSDavid du Colombier	rows and actual_number_of_colors columns.  Ignored if not quantizing.
11217dd7cddfSDavid du Colombier	CAUTION: if the JPEG library creates its own colormap, the storage
11227dd7cddfSDavid du Colombier	pointed to by this field is released by jpeg_finish_decompress().
11237dd7cddfSDavid du Colombier	Copy the colormap somewhere else first, if you want to save it.
11247dd7cddfSDavid du Colombier
11257dd7cddfSDavid du Colombierint actual_number_of_colors
11267dd7cddfSDavid du Colombier	The number of colors in the color map.
11277dd7cddfSDavid du Colombier
11287dd7cddfSDavid du ColombierAdditional decompression parameters that the application may set include:
11297dd7cddfSDavid du Colombier
11307dd7cddfSDavid du ColombierJ_DCT_METHOD dct_method
11317dd7cddfSDavid du Colombier	Selects the algorithm used for the DCT step.  Choices are the same
11327dd7cddfSDavid du Colombier	as described above for compression.
11337dd7cddfSDavid du Colombier
11347dd7cddfSDavid du Colombierboolean do_fancy_upsampling
11357dd7cddfSDavid du Colombier	If TRUE, do careful upsampling of chroma components.  If FALSE,
11367dd7cddfSDavid du Colombier	a faster but sloppier method is used.  Default is TRUE.  The visual
11377dd7cddfSDavid du Colombier	impact of the sloppier method is often very small.
11387dd7cddfSDavid du Colombier
11397dd7cddfSDavid du Colombierboolean do_block_smoothing
11407dd7cddfSDavid du Colombier	If TRUE, interblock smoothing is applied in early stages of decoding
11417dd7cddfSDavid du Colombier	progressive JPEG files; if FALSE, not.  Default is TRUE.  Early
11427dd7cddfSDavid du Colombier	progression stages look "fuzzy" with smoothing, "blocky" without.
11437dd7cddfSDavid du Colombier	In any case, block smoothing ceases to be applied after the first few
11447dd7cddfSDavid du Colombier	AC coefficients are known to full accuracy, so it is relevant only
11457dd7cddfSDavid du Colombier	when using buffered-image mode for progressive images.
11467dd7cddfSDavid du Colombier
11477dd7cddfSDavid du Colombierboolean enable_1pass_quant
11487dd7cddfSDavid du Colombierboolean enable_external_quant
11497dd7cddfSDavid du Colombierboolean enable_2pass_quant
11507dd7cddfSDavid du Colombier	These are significant only in buffered-image mode, which is
11517dd7cddfSDavid du Colombier	described in its own section below.
11527dd7cddfSDavid du Colombier
11537dd7cddfSDavid du Colombier
11547dd7cddfSDavid du ColombierThe output image dimensions are given by the following fields.  These are
11557dd7cddfSDavid du Colombiercomputed from the source image dimensions and the decompression parameters
11567dd7cddfSDavid du Colombierby jpeg_start_decompress().  You can also call jpeg_calc_output_dimensions()
11577dd7cddfSDavid du Colombierto obtain the values that will result from the current parameter settings.
11587dd7cddfSDavid du ColombierThis can be useful if you are trying to pick a scaling ratio that will get
11597dd7cddfSDavid du Colombierclose to a desired target size.  It's also important if you are using the
11607dd7cddfSDavid du ColombierJPEG library's memory manager to allocate output buffer space, because you
11617dd7cddfSDavid du Colombierare supposed to request such buffers *before* jpeg_start_decompress().
11627dd7cddfSDavid du Colombier
11637dd7cddfSDavid du ColombierJDIMENSION output_width		Actual dimensions of output image.
11647dd7cddfSDavid du ColombierJDIMENSION output_height
11657dd7cddfSDavid du Colombierint out_color_components	Number of color components in out_color_space.
11667dd7cddfSDavid du Colombierint output_components		Number of color components returned.
11677dd7cddfSDavid du Colombierint rec_outbuf_height		Recommended height of scanline buffer.
11687dd7cddfSDavid du Colombier
11697dd7cddfSDavid du ColombierWhen quantizing colors, output_components is 1, indicating a single color map
11707dd7cddfSDavid du Colombierindex per pixel.  Otherwise it equals out_color_components.  The output arrays
11717dd7cddfSDavid du Colombierare required to be output_width * output_components JSAMPLEs wide.
11727dd7cddfSDavid du Colombier
11737dd7cddfSDavid du Colombierrec_outbuf_height is the recommended minimum height (in scanlines) of the
11747dd7cddfSDavid du Colombierbuffer passed to jpeg_read_scanlines().  If the buffer is smaller, the
11757dd7cddfSDavid du Colombierlibrary will still work, but time will be wasted due to unnecessary data
11767dd7cddfSDavid du Colombiercopying.  In high-quality modes, rec_outbuf_height is always 1, but some
11777dd7cddfSDavid du Colombierfaster, lower-quality modes set it to larger values (typically 2 to 4).
11787dd7cddfSDavid du ColombierIf you are going to ask for a high-speed processing mode, you may as well
11797dd7cddfSDavid du Colombiergo to the trouble of honoring rec_outbuf_height so as to avoid data copying.
1180*593dc095SDavid du Colombier(An output buffer larger than rec_outbuf_height lines is OK, but won't
1181*593dc095SDavid du Colombierprovide any material speed improvement over that height.)
11827dd7cddfSDavid du Colombier
11837dd7cddfSDavid du Colombier
11847dd7cddfSDavid du ColombierSpecial color spaces
11857dd7cddfSDavid du Colombier--------------------
11867dd7cddfSDavid du Colombier
11877dd7cddfSDavid du ColombierThe JPEG standard itself is "color blind" and doesn't specify any particular
11887dd7cddfSDavid du Colombiercolor space.  It is customary to convert color data to a luminance/chrominance
11897dd7cddfSDavid du Colombiercolor space before compressing, since this permits greater compression.  The
11907dd7cddfSDavid du Colombierexisting de-facto JPEG file format standards specify YCbCr or grayscale data
11917dd7cddfSDavid du Colombier(JFIF), or grayscale, RGB, YCbCr, CMYK, or YCCK (Adobe).  For special
11927dd7cddfSDavid du Colombierapplications such as multispectral images, other color spaces can be used,
11937dd7cddfSDavid du Colombierbut it must be understood that such files will be unportable.
11947dd7cddfSDavid du Colombier
11957dd7cddfSDavid du ColombierThe JPEG library can handle the most common colorspace conversions (namely
11967dd7cddfSDavid du ColombierRGB <=> YCbCr and CMYK <=> YCCK).  It can also deal with data of an unknown
11977dd7cddfSDavid du Colombiercolor space, passing it through without conversion.  If you deal extensively
11987dd7cddfSDavid du Colombierwith an unusual color space, you can easily extend the library to understand
11997dd7cddfSDavid du Colombieradditional color spaces and perform appropriate conversions.
12007dd7cddfSDavid du Colombier
12017dd7cddfSDavid du ColombierFor compression, the source data's color space is specified by field
12027dd7cddfSDavid du Colombierin_color_space.  This is transformed to the JPEG file's color space given
12037dd7cddfSDavid du Colombierby jpeg_color_space.  jpeg_set_defaults() chooses a reasonable JPEG color
12047dd7cddfSDavid du Colombierspace depending on in_color_space, but you can override this by calling
12057dd7cddfSDavid du Colombierjpeg_set_colorspace().  Of course you must select a supported transformation.
12067dd7cddfSDavid du Colombierjccolor.c currently supports the following transformations:
12077dd7cddfSDavid du Colombier	RGB => YCbCr
12087dd7cddfSDavid du Colombier	RGB => GRAYSCALE
12097dd7cddfSDavid du Colombier	YCbCr => GRAYSCALE
12107dd7cddfSDavid du Colombier	CMYK => YCCK
12117dd7cddfSDavid du Colombierplus the null transforms: GRAYSCALE => GRAYSCALE, RGB => RGB,
12127dd7cddfSDavid du ColombierYCbCr => YCbCr, CMYK => CMYK, YCCK => YCCK, and UNKNOWN => UNKNOWN.
12137dd7cddfSDavid du Colombier
12147dd7cddfSDavid du ColombierThe de-facto file format standards (JFIF and Adobe) specify APPn markers that
12157dd7cddfSDavid du Colombierindicate the color space of the JPEG file.  It is important to ensure that
12167dd7cddfSDavid du Colombierthese are written correctly, or omitted if the JPEG file's color space is not
12177dd7cddfSDavid du Colombierone of the ones supported by the de-facto standards.  jpeg_set_colorspace()
12187dd7cddfSDavid du Colombierwill set the compression parameters to include or omit the APPn markers
12197dd7cddfSDavid du Colombierproperly, so long as it is told the truth about the JPEG color space.
12207dd7cddfSDavid du ColombierFor example, if you are writing some random 3-component color space without
12217dd7cddfSDavid du Colombierconversion, don't try to fake out the library by setting in_color_space and
12227dd7cddfSDavid du Colombierjpeg_color_space to JCS_YCbCr; use JCS_UNKNOWN.  You may want to write an
12237dd7cddfSDavid du ColombierAPPn marker of your own devising to identify the colorspace --- see "Special
12247dd7cddfSDavid du Colombiermarkers", below.
12257dd7cddfSDavid du Colombier
12267dd7cddfSDavid du ColombierWhen told that the color space is UNKNOWN, the library will default to using
12277dd7cddfSDavid du Colombierluminance-quality compression parameters for all color components.  You may
12287dd7cddfSDavid du Colombierwell want to change these parameters.  See the source code for
12297dd7cddfSDavid du Colombierjpeg_set_colorspace(), in jcparam.c, for details.
12307dd7cddfSDavid du Colombier
12317dd7cddfSDavid du ColombierFor decompression, the JPEG file's color space is given in jpeg_color_space,
12327dd7cddfSDavid du Colombierand this is transformed to the output color space out_color_space.
12337dd7cddfSDavid du Colombierjpeg_read_header's setting of jpeg_color_space can be relied on if the file
12347dd7cddfSDavid du Colombierconforms to JFIF or Adobe conventions, but otherwise it is no better than a
12357dd7cddfSDavid du Colombierguess.  If you know the JPEG file's color space for certain, you can override
12367dd7cddfSDavid du Colombierjpeg_read_header's guess by setting jpeg_color_space.  jpeg_read_header also
12377dd7cddfSDavid du Colombierselects a default output color space based on (its guess of) jpeg_color_space;
12387dd7cddfSDavid du Colombierset out_color_space to override this.  Again, you must select a supported
12397dd7cddfSDavid du Colombiertransformation.  jdcolor.c currently supports
12407dd7cddfSDavid du Colombier	YCbCr => GRAYSCALE
12417dd7cddfSDavid du Colombier	YCbCr => RGB
1242*593dc095SDavid du Colombier	GRAYSCALE => RGB
12437dd7cddfSDavid du Colombier	YCCK => CMYK
1244*593dc095SDavid du Colombieras well as the null transforms.  (Since GRAYSCALE=>RGB is provided, an
1245*593dc095SDavid du Colombierapplication can force grayscale JPEGs to look like color JPEGs if it only
1246*593dc095SDavid du Colombierwants to handle one case.)
12477dd7cddfSDavid du Colombier
12487dd7cddfSDavid du ColombierThe two-pass color quantizer, jquant2.c, is specialized to handle RGB data
12497dd7cddfSDavid du Colombier(it weights distances appropriately for RGB colors).  You'll need to modify
12507dd7cddfSDavid du Colombierthe code if you want to use it for non-RGB output color spaces.  Note that
12517dd7cddfSDavid du Colombierjquant2.c is used to map to an application-supplied colormap as well as for
12527dd7cddfSDavid du Colombierthe normal two-pass colormap selection process.
12537dd7cddfSDavid du Colombier
12547dd7cddfSDavid du ColombierCAUTION: it appears that Adobe Photoshop writes inverted data in CMYK JPEG
12557dd7cddfSDavid du Colombierfiles: 0 represents 100% ink coverage, rather than 0% ink as you'd expect.
12567dd7cddfSDavid du ColombierThis is arguably a bug in Photoshop, but if you need to work with Photoshop
12577dd7cddfSDavid du ColombierCMYK files, you will have to deal with it in your application.  We cannot
12587dd7cddfSDavid du Colombier"fix" this in the library by inverting the data during the CMYK<=>YCCK
12597dd7cddfSDavid du Colombiertransform, because that would break other applications, notably Ghostscript.
12607dd7cddfSDavid du ColombierPhotoshop versions prior to 3.0 write EPS files containing JPEG-encoded CMYK
12617dd7cddfSDavid du Colombierdata in the same inverted-YCCK representation used in bare JPEG files, but
12627dd7cddfSDavid du Colombierthe surrounding PostScript code performs an inversion using the PS image
12637dd7cddfSDavid du Colombieroperator.  I am told that Photoshop 3.0 will write uninverted YCCK in
12647dd7cddfSDavid du ColombierEPS/JPEG files, and will omit the PS-level inversion.  (But the data
12657dd7cddfSDavid du Colombierpolarity used in bare JPEG files will not change in 3.0.)  In either case,
12667dd7cddfSDavid du Colombierthe JPEG library must not invert the data itself, or else Ghostscript would
12677dd7cddfSDavid du Colombierread these EPS files incorrectly.
12687dd7cddfSDavid du Colombier
12697dd7cddfSDavid du Colombier
12707dd7cddfSDavid du ColombierError handling
12717dd7cddfSDavid du Colombier--------------
12727dd7cddfSDavid du Colombier
12737dd7cddfSDavid du ColombierWhen the default error handler is used, any error detected inside the JPEG
12747dd7cddfSDavid du Colombierroutines will cause a message to be printed on stderr, followed by exit().
12757dd7cddfSDavid du ColombierYou can supply your own error handling routines to override this behavior
12767dd7cddfSDavid du Colombierand to control the treatment of nonfatal warnings and trace/debug messages.
12777dd7cddfSDavid du ColombierThe file example.c illustrates the most common case, which is to have the
12787dd7cddfSDavid du Colombierapplication regain control after an error rather than exiting.
12797dd7cddfSDavid du Colombier
12807dd7cddfSDavid du ColombierThe JPEG library never writes any message directly; it always goes through
12817dd7cddfSDavid du Colombierthe error handling routines.  Three classes of messages are recognized:
12827dd7cddfSDavid du Colombier  * Fatal errors: the library cannot continue.
12837dd7cddfSDavid du Colombier  * Warnings: the library can continue, but the data is corrupt, and a
12847dd7cddfSDavid du Colombier    damaged output image is likely to result.
12857dd7cddfSDavid du Colombier  * Trace/informational messages.  These come with a trace level indicating
12867dd7cddfSDavid du Colombier    the importance of the message; you can control the verbosity of the
12877dd7cddfSDavid du Colombier    program by adjusting the maximum trace level that will be displayed.
12887dd7cddfSDavid du Colombier
12897dd7cddfSDavid du ColombierYou may, if you wish, simply replace the entire JPEG error handling module
12907dd7cddfSDavid du Colombier(jerror.c) with your own code.  However, you can avoid code duplication by
12917dd7cddfSDavid du Colombieronly replacing some of the routines depending on the behavior you need.
12927dd7cddfSDavid du ColombierThis is accomplished by calling jpeg_std_error() as usual, but then overriding
12937dd7cddfSDavid du Colombiersome of the method pointers in the jpeg_error_mgr struct, as illustrated by
12947dd7cddfSDavid du Colombierexample.c.
12957dd7cddfSDavid du Colombier
12967dd7cddfSDavid du ColombierAll of the error handling routines will receive a pointer to the JPEG object
12977dd7cddfSDavid du Colombier(a j_common_ptr which points to either a jpeg_compress_struct or a
12987dd7cddfSDavid du Colombierjpeg_decompress_struct; if you need to tell which, test the is_decompressor
12997dd7cddfSDavid du Colombierfield).  This struct includes a pointer to the error manager struct in its
13007dd7cddfSDavid du Colombier"err" field.  Frequently, custom error handler routines will need to access
13017dd7cddfSDavid du Colombieradditional data which is not known to the JPEG library or the standard error
13027dd7cddfSDavid du Colombierhandler.  The most convenient way to do this is to embed either the JPEG
13037dd7cddfSDavid du Colombierobject or the jpeg_error_mgr struct in a larger structure that contains
13047dd7cddfSDavid du Colombieradditional fields; then casting the passed pointer provides access to the
1305*593dc095SDavid du Colombieradditional fields.  Again, see example.c for one way to do it.  (Beginning
1306*593dc095SDavid du Colombierwith IJG version 6b, there is also a void pointer "client_data" in each
1307*593dc095SDavid du ColombierJPEG object, which the application can also use to find related data.
1308*593dc095SDavid du ColombierThe library does not touch client_data at all.)
13097dd7cddfSDavid du Colombier
13107dd7cddfSDavid du ColombierThe individual methods that you might wish to override are:
13117dd7cddfSDavid du Colombier
13127dd7cddfSDavid du Colombiererror_exit (j_common_ptr cinfo)
13137dd7cddfSDavid du Colombier	Receives control for a fatal error.  Information sufficient to
13147dd7cddfSDavid du Colombier	generate the error message has been stored in cinfo->err; call
13157dd7cddfSDavid du Colombier	output_message to display it.  Control must NOT return to the caller;
13167dd7cddfSDavid du Colombier	generally this routine will exit() or longjmp() somewhere.
13177dd7cddfSDavid du Colombier	Typically you would override this routine to get rid of the exit()
13187dd7cddfSDavid du Colombier	default behavior.  Note that if you continue processing, you should
13197dd7cddfSDavid du Colombier	clean up the JPEG object with jpeg_abort() or jpeg_destroy().
13207dd7cddfSDavid du Colombier
13217dd7cddfSDavid du Colombieroutput_message (j_common_ptr cinfo)
13227dd7cddfSDavid du Colombier	Actual output of any JPEG message.  Override this to send messages
13237dd7cddfSDavid du Colombier	somewhere other than stderr.  Note that this method does not know
13247dd7cddfSDavid du Colombier	how to generate a message, only where to send it.
13257dd7cddfSDavid du Colombier
13267dd7cddfSDavid du Colombierformat_message (j_common_ptr cinfo, char * buffer)
13277dd7cddfSDavid du Colombier	Constructs a readable error message string based on the error info
13287dd7cddfSDavid du Colombier	stored in cinfo->err.  This method is called by output_message.  Few
13297dd7cddfSDavid du Colombier	applications should need to override this method.  One possible
13307dd7cddfSDavid du Colombier	reason for doing so is to implement dynamic switching of error message
13317dd7cddfSDavid du Colombier	language.
13327dd7cddfSDavid du Colombier
13337dd7cddfSDavid du Colombieremit_message (j_common_ptr cinfo, int msg_level)
13347dd7cddfSDavid du Colombier	Decide whether or not to emit a warning or trace message; if so,
13357dd7cddfSDavid du Colombier	calls output_message.  The main reason for overriding this method
13367dd7cddfSDavid du Colombier	would be to abort on warnings.  msg_level is -1 for warnings,
13377dd7cddfSDavid du Colombier	0 and up for trace messages.
13387dd7cddfSDavid du Colombier
13397dd7cddfSDavid du ColombierOnly error_exit() and emit_message() are called from the rest of the JPEG
13407dd7cddfSDavid du Colombierlibrary; the other two are internal to the error handler.
13417dd7cddfSDavid du Colombier
13427dd7cddfSDavid du ColombierThe actual message texts are stored in an array of strings which is pointed to
13437dd7cddfSDavid du Colombierby the field err->jpeg_message_table.  The messages are numbered from 0 to
13447dd7cddfSDavid du Colombiererr->last_jpeg_message, and it is these code numbers that are used in the
13457dd7cddfSDavid du ColombierJPEG library code.  You could replace the message texts (for instance, with
13467dd7cddfSDavid du Colombiermessages in French or German) by changing the message table pointer.  See
13477dd7cddfSDavid du Colombierjerror.h for the default texts.  CAUTION: this table will almost certainly
13487dd7cddfSDavid du Colombierchange or grow from one library version to the next.
13497dd7cddfSDavid du Colombier
13507dd7cddfSDavid du ColombierIt may be useful for an application to add its own message texts that are
13517dd7cddfSDavid du Colombierhandled by the same mechanism.  The error handler supports a second "add-on"
13527dd7cddfSDavid du Colombiermessage table for this purpose.  To define an addon table, set the pointer
13537dd7cddfSDavid du Colombiererr->addon_message_table and the message numbers err->first_addon_message and
13547dd7cddfSDavid du Colombiererr->last_addon_message.  If you number the addon messages beginning at 1000
13557dd7cddfSDavid du Colombieror so, you won't have to worry about conflicts with the library's built-in
13567dd7cddfSDavid du Colombiermessages.  See the sample applications cjpeg/djpeg for an example of using
13577dd7cddfSDavid du Colombieraddon messages (the addon messages are defined in cderror.h).
13587dd7cddfSDavid du Colombier
13597dd7cddfSDavid du ColombierActual invocation of the error handler is done via macros defined in jerror.h:
13607dd7cddfSDavid du Colombier	ERREXITn(...)	for fatal errors
13617dd7cddfSDavid du Colombier	WARNMSn(...)	for corrupt-data warnings
13627dd7cddfSDavid du Colombier	TRACEMSn(...)	for trace and informational messages.
13637dd7cddfSDavid du ColombierThese macros store the message code and any additional parameters into the
13647dd7cddfSDavid du Colombiererror handler struct, then invoke the error_exit() or emit_message() method.
13657dd7cddfSDavid du ColombierThe variants of each macro are for varying numbers of additional parameters.
13667dd7cddfSDavid du ColombierThe additional parameters are inserted into the generated message using
13677dd7cddfSDavid du Colombierstandard printf() format codes.
13687dd7cddfSDavid du Colombier
13697dd7cddfSDavid du ColombierSee jerror.h and jerror.c for further details.
13707dd7cddfSDavid du Colombier
13717dd7cddfSDavid du Colombier
13727dd7cddfSDavid du ColombierCompressed data handling (source and destination managers)
13737dd7cddfSDavid du Colombier----------------------------------------------------------
13747dd7cddfSDavid du Colombier
13757dd7cddfSDavid du ColombierThe JPEG compression library sends its compressed data to a "destination
13767dd7cddfSDavid du Colombiermanager" module.  The default destination manager just writes the data to a
13777dd7cddfSDavid du Colombierstdio stream, but you can provide your own manager to do something else.
13787dd7cddfSDavid du ColombierSimilarly, the decompression library calls a "source manager" to obtain the
13797dd7cddfSDavid du Colombiercompressed data; you can provide your own source manager if you want the data
13807dd7cddfSDavid du Colombierto come from somewhere other than a stdio stream.
13817dd7cddfSDavid du Colombier
13827dd7cddfSDavid du ColombierIn both cases, compressed data is processed a bufferload at a time: the
13837dd7cddfSDavid du Colombierdestination or source manager provides a work buffer, and the library invokes
13847dd7cddfSDavid du Colombierthe manager only when the buffer is filled or emptied.  (You could define a
13857dd7cddfSDavid du Colombierone-character buffer to force the manager to be invoked for each byte, but
13867dd7cddfSDavid du Colombierthat would be rather inefficient.)  The buffer's size and location are
13877dd7cddfSDavid du Colombiercontrolled by the manager, not by the library.  For example, if you desired to
13887dd7cddfSDavid du Colombierdecompress a JPEG datastream that was all in memory, you could just make the
13897dd7cddfSDavid du Colombierbuffer pointer and length point to the original data in memory.  Then the
13907dd7cddfSDavid du Colombierbuffer-reload procedure would be invoked only if the decompressor ran off the
13917dd7cddfSDavid du Colombierend of the datastream, which would indicate an erroneous datastream.
13927dd7cddfSDavid du Colombier
13937dd7cddfSDavid du ColombierThe work buffer is defined as an array of datatype JOCTET, which is generally
13947dd7cddfSDavid du Colombier"char" or "unsigned char".  On a machine where char is not exactly 8 bits
13957dd7cddfSDavid du Colombierwide, you must define JOCTET as a wider data type and then modify the data
13967dd7cddfSDavid du Colombiersource and destination modules to transcribe the work arrays into 8-bit units
13977dd7cddfSDavid du Colombieron external storage.
13987dd7cddfSDavid du Colombier
13997dd7cddfSDavid du ColombierA data destination manager struct contains a pointer and count defining the
14007dd7cddfSDavid du Colombiernext byte to write in the work buffer and the remaining free space:
14017dd7cddfSDavid du Colombier
14027dd7cddfSDavid du Colombier	JOCTET * next_output_byte;  /* => next byte to write in buffer */
14037dd7cddfSDavid du Colombier	size_t free_in_buffer;      /* # of byte spaces remaining in buffer */
14047dd7cddfSDavid du Colombier
14057dd7cddfSDavid du ColombierThe library increments the pointer and decrements the count until the buffer
14067dd7cddfSDavid du Colombieris filled.  The manager's empty_output_buffer method must reset the pointer
14077dd7cddfSDavid du Colombierand count.  The manager is expected to remember the buffer's starting address
14087dd7cddfSDavid du Colombierand total size in private fields not visible to the library.
14097dd7cddfSDavid du Colombier
14107dd7cddfSDavid du ColombierA data destination manager provides three methods:
14117dd7cddfSDavid du Colombier
14127dd7cddfSDavid du Colombierinit_destination (j_compress_ptr cinfo)
14137dd7cddfSDavid du Colombier	Initialize destination.  This is called by jpeg_start_compress()
14147dd7cddfSDavid du Colombier	before any data is actually written.  It must initialize
14157dd7cddfSDavid du Colombier	next_output_byte and free_in_buffer.  free_in_buffer must be
14167dd7cddfSDavid du Colombier	initialized to a positive value.
14177dd7cddfSDavid du Colombier
14187dd7cddfSDavid du Colombierempty_output_buffer (j_compress_ptr cinfo)
14197dd7cddfSDavid du Colombier	This is called whenever the buffer has filled (free_in_buffer
14207dd7cddfSDavid du Colombier	reaches zero).  In typical applications, it should write out the
14217dd7cddfSDavid du Colombier	*entire* buffer (use the saved start address and buffer length;
14227dd7cddfSDavid du Colombier	ignore the current state of next_output_byte and free_in_buffer).
14237dd7cddfSDavid du Colombier	Then reset the pointer & count to the start of the buffer, and
14247dd7cddfSDavid du Colombier	return TRUE indicating that the buffer has been dumped.
14257dd7cddfSDavid du Colombier	free_in_buffer must be set to a positive value when TRUE is
14267dd7cddfSDavid du Colombier	returned.  A FALSE return should only be used when I/O suspension is
14277dd7cddfSDavid du Colombier	desired (this operating mode is discussed in the next section).
14287dd7cddfSDavid du Colombier
14297dd7cddfSDavid du Colombierterm_destination (j_compress_ptr cinfo)
14307dd7cddfSDavid du Colombier	Terminate destination --- called by jpeg_finish_compress() after all
14317dd7cddfSDavid du Colombier	data has been written.  In most applications, this must flush any
14327dd7cddfSDavid du Colombier	data remaining in the buffer.  Use either next_output_byte or
14337dd7cddfSDavid du Colombier	free_in_buffer to determine how much data is in the buffer.
14347dd7cddfSDavid du Colombier
14357dd7cddfSDavid du Colombierterm_destination() is NOT called by jpeg_abort() or jpeg_destroy().  If you
14367dd7cddfSDavid du Colombierwant the destination manager to be cleaned up during an abort, you must do it
14377dd7cddfSDavid du Colombieryourself.
14387dd7cddfSDavid du Colombier
14397dd7cddfSDavid du ColombierYou will also need code to create a jpeg_destination_mgr struct, fill in its
14407dd7cddfSDavid du Colombiermethod pointers, and insert a pointer to the struct into the "dest" field of
14417dd7cddfSDavid du Colombierthe JPEG compression object.  This can be done in-line in your setup code if
14427dd7cddfSDavid du Colombieryou like, but it's probably cleaner to provide a separate routine similar to
14437dd7cddfSDavid du Colombierthe jpeg_stdio_dest() routine of the supplied destination manager.
14447dd7cddfSDavid du Colombier
14457dd7cddfSDavid du ColombierDecompression source managers follow a parallel design, but with some
14467dd7cddfSDavid du Colombieradditional frammishes.  The source manager struct contains a pointer and count
14477dd7cddfSDavid du Colombierdefining the next byte to read from the work buffer and the number of bytes
14487dd7cddfSDavid du Colombierremaining:
14497dd7cddfSDavid du Colombier
14507dd7cddfSDavid du Colombier	const JOCTET * next_input_byte; /* => next byte to read from buffer */
14517dd7cddfSDavid du Colombier	size_t bytes_in_buffer;         /* # of bytes remaining in buffer */
14527dd7cddfSDavid du Colombier
14537dd7cddfSDavid du ColombierThe library increments the pointer and decrements the count until the buffer
14547dd7cddfSDavid du Colombieris emptied.  The manager's fill_input_buffer method must reset the pointer and
14557dd7cddfSDavid du Colombiercount.  In most applications, the manager must remember the buffer's starting
14567dd7cddfSDavid du Colombieraddress and total size in private fields not visible to the library.
14577dd7cddfSDavid du Colombier
14587dd7cddfSDavid du ColombierA data source manager provides five methods:
14597dd7cddfSDavid du Colombier
14607dd7cddfSDavid du Colombierinit_source (j_decompress_ptr cinfo)
14617dd7cddfSDavid du Colombier	Initialize source.  This is called by jpeg_read_header() before any
14627dd7cddfSDavid du Colombier	data is actually read.  Unlike init_destination(), it may leave
14637dd7cddfSDavid du Colombier	bytes_in_buffer set to 0 (in which case a fill_input_buffer() call
14647dd7cddfSDavid du Colombier	will occur immediately).
14657dd7cddfSDavid du Colombier
14667dd7cddfSDavid du Colombierfill_input_buffer (j_decompress_ptr cinfo)
14677dd7cddfSDavid du Colombier	This is called whenever bytes_in_buffer has reached zero and more
14687dd7cddfSDavid du Colombier	data is wanted.  In typical applications, it should read fresh data
14697dd7cddfSDavid du Colombier	into the buffer (ignoring the current state of next_input_byte and
14707dd7cddfSDavid du Colombier	bytes_in_buffer), reset the pointer & count to the start of the
14717dd7cddfSDavid du Colombier	buffer, and return TRUE indicating that the buffer has been reloaded.
14727dd7cddfSDavid du Colombier	It is not necessary to fill the buffer entirely, only to obtain at
14737dd7cddfSDavid du Colombier	least one more byte.  bytes_in_buffer MUST be set to a positive value
14747dd7cddfSDavid du Colombier	if TRUE is returned.  A FALSE return should only be used when I/O
14757dd7cddfSDavid du Colombier	suspension is desired (this mode is discussed in the next section).
14767dd7cddfSDavid du Colombier
14777dd7cddfSDavid du Colombierskip_input_data (j_decompress_ptr cinfo, long num_bytes)
14787dd7cddfSDavid du Colombier	Skip num_bytes worth of data.  The buffer pointer and count should
14797dd7cddfSDavid du Colombier	be advanced over num_bytes input bytes, refilling the buffer as
14807dd7cddfSDavid du Colombier	needed.  This is used to skip over a potentially large amount of
14817dd7cddfSDavid du Colombier	uninteresting data (such as an APPn marker).  In some applications
14827dd7cddfSDavid du Colombier	it may be possible to optimize away the reading of the skipped data,
14837dd7cddfSDavid du Colombier	but it's not clear that being smart is worth much trouble; large
14847dd7cddfSDavid du Colombier	skips are uncommon.  bytes_in_buffer may be zero on return.
14857dd7cddfSDavid du Colombier	A zero or negative skip count should be treated as a no-op.
14867dd7cddfSDavid du Colombier
14877dd7cddfSDavid du Colombierresync_to_restart (j_decompress_ptr cinfo, int desired)
14887dd7cddfSDavid du Colombier	This routine is called only when the decompressor has failed to find
14897dd7cddfSDavid du Colombier	a restart (RSTn) marker where one is expected.  Its mission is to
14907dd7cddfSDavid du Colombier	find a suitable point for resuming decompression.  For most
14917dd7cddfSDavid du Colombier	applications, we recommend that you just use the default resync
14927dd7cddfSDavid du Colombier	procedure, jpeg_resync_to_restart().  However, if you are able to back
14937dd7cddfSDavid du Colombier	up in the input data stream, or if you have a-priori knowledge about
14947dd7cddfSDavid du Colombier	the likely location of restart markers, you may be able to do better.
14957dd7cddfSDavid du Colombier	Read the read_restart_marker() and jpeg_resync_to_restart() routines
14967dd7cddfSDavid du Colombier	in jdmarker.c if you think you'd like to implement your own resync
14977dd7cddfSDavid du Colombier	procedure.
14987dd7cddfSDavid du Colombier
14997dd7cddfSDavid du Colombierterm_source (j_decompress_ptr cinfo)
15007dd7cddfSDavid du Colombier	Terminate source --- called by jpeg_finish_decompress() after all
15017dd7cddfSDavid du Colombier	data has been read.  Often a no-op.
15027dd7cddfSDavid du Colombier
15037dd7cddfSDavid du ColombierFor both fill_input_buffer() and skip_input_data(), there is no such thing
15047dd7cddfSDavid du Colombieras an EOF return.  If the end of the file has been reached, the routine has
15057dd7cddfSDavid du Colombiera choice of exiting via ERREXIT() or inserting fake data into the buffer.
15067dd7cddfSDavid du ColombierIn most cases, generating a warning message and inserting a fake EOI marker
15077dd7cddfSDavid du Colombieris the best course of action --- this will allow the decompressor to output
15087dd7cddfSDavid du Colombierhowever much of the image is there.  In pathological cases, the decompressor
15097dd7cddfSDavid du Colombiermay swallow the EOI and again demand data ... just keep feeding it fake EOIs.
15107dd7cddfSDavid du Colombierjdatasrc.c illustrates the recommended error recovery behavior.
15117dd7cddfSDavid du Colombier
15127dd7cddfSDavid du Colombierterm_source() is NOT called by jpeg_abort() or jpeg_destroy().  If you want
15137dd7cddfSDavid du Colombierthe source manager to be cleaned up during an abort, you must do it yourself.
15147dd7cddfSDavid du Colombier
15157dd7cddfSDavid du ColombierYou will also need code to create a jpeg_source_mgr struct, fill in its method
15167dd7cddfSDavid du Colombierpointers, and insert a pointer to the struct into the "src" field of the JPEG
15177dd7cddfSDavid du Colombierdecompression object.  This can be done in-line in your setup code if you
15187dd7cddfSDavid du Colombierlike, but it's probably cleaner to provide a separate routine similar to the
15197dd7cddfSDavid du Colombierjpeg_stdio_src() routine of the supplied source manager.
15207dd7cddfSDavid du Colombier
15217dd7cddfSDavid du ColombierFor more information, consult the stdio source and destination managers
15227dd7cddfSDavid du Colombierin jdatasrc.c and jdatadst.c.
15237dd7cddfSDavid du Colombier
15247dd7cddfSDavid du Colombier
15257dd7cddfSDavid du ColombierI/O suspension
15267dd7cddfSDavid du Colombier--------------
15277dd7cddfSDavid du Colombier
15287dd7cddfSDavid du ColombierSome applications need to use the JPEG library as an incremental memory-to-
15297dd7cddfSDavid du Colombiermemory filter: when the compressed data buffer is filled or emptied, they want
15307dd7cddfSDavid du Colombiercontrol to return to the outer loop, rather than expecting that the buffer can
15317dd7cddfSDavid du Colombierbe emptied or reloaded within the data source/destination manager subroutine.
15327dd7cddfSDavid du ColombierThe library supports this need by providing an "I/O suspension" mode, which we
15337dd7cddfSDavid du Colombierdescribe in this section.
15347dd7cddfSDavid du Colombier
15357dd7cddfSDavid du ColombierThe I/O suspension mode is not a panacea: nothing is guaranteed about the
15367dd7cddfSDavid du Colombiermaximum amount of time spent in any one call to the library, so it will not
15377dd7cddfSDavid du Colombiereliminate response-time problems in single-threaded applications.  If you
15387dd7cddfSDavid du Colombierneed guaranteed response time, we suggest you "bite the bullet" and implement
15397dd7cddfSDavid du Colombiera real multi-tasking capability.
15407dd7cddfSDavid du Colombier
15417dd7cddfSDavid du ColombierTo use I/O suspension, cooperation is needed between the calling application
15427dd7cddfSDavid du Colombierand the data source or destination manager; you will always need a custom
15437dd7cddfSDavid du Colombiersource/destination manager.  (Please read the previous section if you haven't
15447dd7cddfSDavid du Colombieralready.)  The basic idea is that the empty_output_buffer() or
15457dd7cddfSDavid du Colombierfill_input_buffer() routine is a no-op, merely returning FALSE to indicate
15467dd7cddfSDavid du Colombierthat it has done nothing.  Upon seeing this, the JPEG library suspends
15477dd7cddfSDavid du Colombieroperation and returns to its caller.  The surrounding application is
15487dd7cddfSDavid du Colombierresponsible for emptying or refilling the work buffer before calling the
15497dd7cddfSDavid du ColombierJPEG library again.
15507dd7cddfSDavid du Colombier
15517dd7cddfSDavid du ColombierCompression suspension:
15527dd7cddfSDavid du Colombier
15537dd7cddfSDavid du ColombierFor compression suspension, use an empty_output_buffer() routine that returns
15547dd7cddfSDavid du ColombierFALSE; typically it will not do anything else.  This will cause the
15557dd7cddfSDavid du Colombiercompressor to return to the caller of jpeg_write_scanlines(), with the return
15567dd7cddfSDavid du Colombiervalue indicating that not all the supplied scanlines have been accepted.
15577dd7cddfSDavid du ColombierThe application must make more room in the output buffer, adjust the output
15587dd7cddfSDavid du Colombierbuffer pointer/count appropriately, and then call jpeg_write_scanlines()
15597dd7cddfSDavid du Colombieragain, pointing to the first unconsumed scanline.
15607dd7cddfSDavid du Colombier
15617dd7cddfSDavid du ColombierWhen forced to suspend, the compressor will backtrack to a convenient stopping
15627dd7cddfSDavid du Colombierpoint (usually the start of the current MCU); it will regenerate some output
15637dd7cddfSDavid du Colombierdata when restarted.  Therefore, although empty_output_buffer() is only
15647dd7cddfSDavid du Colombiercalled when the buffer is filled, you should NOT write out the entire buffer
15657dd7cddfSDavid du Colombierafter a suspension.  Write only the data up to the current position of
15667dd7cddfSDavid du Colombiernext_output_byte/free_in_buffer.  The data beyond that point will be
15677dd7cddfSDavid du Colombierregenerated after resumption.
15687dd7cddfSDavid du Colombier
15697dd7cddfSDavid du ColombierBecause of the backtracking behavior, a good-size output buffer is essential
15707dd7cddfSDavid du Colombierfor efficiency; you don't want the compressor to suspend often.  (In fact, an
15717dd7cddfSDavid du Colombieroverly small buffer could lead to infinite looping, if a single MCU required
15727dd7cddfSDavid du Colombiermore data than would fit in the buffer.)  We recommend a buffer of at least
15737dd7cddfSDavid du Colombierseveral Kbytes.  You may want to insert explicit code to ensure that you don't
15747dd7cddfSDavid du Colombiercall jpeg_write_scanlines() unless there is a reasonable amount of space in
15757dd7cddfSDavid du Colombierthe output buffer; in other words, flush the buffer before trying to compress
15767dd7cddfSDavid du Colombiermore data.
15777dd7cddfSDavid du Colombier
15787dd7cddfSDavid du ColombierThe compressor does not allow suspension while it is trying to write JPEG
15797dd7cddfSDavid du Colombiermarkers at the beginning and end of the file.  This means that:
15807dd7cddfSDavid du Colombier  * At the beginning of a compression operation, there must be enough free
15817dd7cddfSDavid du Colombier    space in the output buffer to hold the header markers (typically 600 or
15827dd7cddfSDavid du Colombier    so bytes).  The recommended buffer size is bigger than this anyway, so
15837dd7cddfSDavid du Colombier    this is not a problem as long as you start with an empty buffer.  However,
15847dd7cddfSDavid du Colombier    this restriction might catch you if you insert large special markers, such
15857dd7cddfSDavid du Colombier    as a JFIF thumbnail image, without flushing the buffer afterwards.
15867dd7cddfSDavid du Colombier  * When you call jpeg_finish_compress(), there must be enough space in the
15877dd7cddfSDavid du Colombier    output buffer to emit any buffered data and the final EOI marker.  In the
15887dd7cddfSDavid du Colombier    current implementation, half a dozen bytes should suffice for this, but
15897dd7cddfSDavid du Colombier    for safety's sake we recommend ensuring that at least 100 bytes are free
15907dd7cddfSDavid du Colombier    before calling jpeg_finish_compress().
15917dd7cddfSDavid du Colombier
15927dd7cddfSDavid du ColombierA more significant restriction is that jpeg_finish_compress() cannot suspend.
15937dd7cddfSDavid du ColombierThis means you cannot use suspension with multi-pass operating modes, namely
15947dd7cddfSDavid du ColombierHuffman code optimization and multiple-scan output.  Those modes write the
15957dd7cddfSDavid du Colombierwhole file during jpeg_finish_compress(), which will certainly result in
15967dd7cddfSDavid du Colombierbuffer overrun.  (Note that this restriction applies only to compression,
15977dd7cddfSDavid du Colombiernot decompression.  The decompressor supports input suspension in all of its
15987dd7cddfSDavid du Colombieroperating modes.)
15997dd7cddfSDavid du Colombier
16007dd7cddfSDavid du ColombierDecompression suspension:
16017dd7cddfSDavid du Colombier
16027dd7cddfSDavid du ColombierFor decompression suspension, use a fill_input_buffer() routine that simply
16037dd7cddfSDavid du Colombierreturns FALSE (except perhaps during error recovery, as discussed below).
16047dd7cddfSDavid du ColombierThis will cause the decompressor to return to its caller with an indication
16057dd7cddfSDavid du Colombierthat suspension has occurred.  This can happen at four places:
16067dd7cddfSDavid du Colombier  * jpeg_read_header(): will return JPEG_SUSPENDED.
16077dd7cddfSDavid du Colombier  * jpeg_start_decompress(): will return FALSE, rather than its usual TRUE.
16087dd7cddfSDavid du Colombier  * jpeg_read_scanlines(): will return the number of scanlines already
16097dd7cddfSDavid du Colombier	completed (possibly 0).
16107dd7cddfSDavid du Colombier  * jpeg_finish_decompress(): will return FALSE, rather than its usual TRUE.
16117dd7cddfSDavid du ColombierThe surrounding application must recognize these cases, load more data into
16127dd7cddfSDavid du Colombierthe input buffer, and repeat the call.  In the case of jpeg_read_scanlines(),
16137dd7cddfSDavid du Colombierincrement the passed pointers past any scanlines successfully read.
16147dd7cddfSDavid du Colombier
16157dd7cddfSDavid du ColombierJust as with compression, the decompressor will typically backtrack to a
16167dd7cddfSDavid du Colombierconvenient restart point before suspending.  When fill_input_buffer() is
16177dd7cddfSDavid du Colombiercalled, next_input_byte/bytes_in_buffer point to the current restart point,
16187dd7cddfSDavid du Colombierwhich is where the decompressor will backtrack to if FALSE is returned.
16197dd7cddfSDavid du ColombierThe data beyond that position must NOT be discarded if you suspend; it needs
16207dd7cddfSDavid du Colombierto be re-read upon resumption.  In most implementations, you'll need to shift
16217dd7cddfSDavid du Colombierthis data down to the start of your work buffer and then load more data after
16227dd7cddfSDavid du Colombierit.  Again, this behavior means that a several-Kbyte work buffer is essential
16237dd7cddfSDavid du Colombierfor decent performance; furthermore, you should load a reasonable amount of
16247dd7cddfSDavid du Colombiernew data before resuming decompression.  (If you loaded, say, only one new
16257dd7cddfSDavid du Colombierbyte each time around, you could waste a LOT of cycles.)
16267dd7cddfSDavid du Colombier
16277dd7cddfSDavid du ColombierThe skip_input_data() source manager routine requires special care in a
16287dd7cddfSDavid du Colombiersuspension scenario.  This routine is NOT granted the ability to suspend the
16297dd7cddfSDavid du Colombierdecompressor; it can decrement bytes_in_buffer to zero, but no more.  If the
16307dd7cddfSDavid du Colombierrequested skip distance exceeds the amount of data currently in the input
16317dd7cddfSDavid du Colombierbuffer, then skip_input_data() must set bytes_in_buffer to zero and record the
16327dd7cddfSDavid du Colombieradditional skip distance somewhere else.  The decompressor will immediately
16337dd7cddfSDavid du Colombiercall fill_input_buffer(), which should return FALSE, which will cause a
16347dd7cddfSDavid du Colombiersuspension return.  The surrounding application must then arrange to discard
16357dd7cddfSDavid du Colombierthe recorded number of bytes before it resumes loading the input buffer.
16367dd7cddfSDavid du Colombier(Yes, this design is rather baroque, but it avoids complexity in the far more
16377dd7cddfSDavid du Colombiercommon case where a non-suspending source manager is used.)
16387dd7cddfSDavid du Colombier
16397dd7cddfSDavid du ColombierIf the input data has been exhausted, we recommend that you emit a warning
16407dd7cddfSDavid du Colombierand insert dummy EOI markers just as a non-suspending data source manager
16417dd7cddfSDavid du Colombierwould do.  This can be handled either in the surrounding application logic or
16427dd7cddfSDavid du Colombierwithin fill_input_buffer(); the latter is probably more efficient.  If
16437dd7cddfSDavid du Colombierfill_input_buffer() knows that no more data is available, it can set the
16447dd7cddfSDavid du Colombierpointer/count to point to a dummy EOI marker and then return TRUE just as
16457dd7cddfSDavid du Colombierthough it had read more data in a non-suspending situation.
16467dd7cddfSDavid du Colombier
1647*593dc095SDavid du ColombierThe decompressor does not attempt to suspend within standard JPEG markers;
1648*593dc095SDavid du Colombierinstead it will backtrack to the start of the marker and reprocess the whole
1649*593dc095SDavid du Colombiermarker next time.  Hence the input buffer must be large enough to hold the
1650*593dc095SDavid du Colombierlongest standard marker in the file.  Standard JPEG markers should normally
1651*593dc095SDavid du Colombiernot exceed a few hundred bytes each (DHT tables are typically the longest).
1652*593dc095SDavid du ColombierWe recommend at least a 2K buffer for performance reasons, which is much
1653*593dc095SDavid du Colombierlarger than any correct marker is likely to be.  For robustness against
1654*593dc095SDavid du Colombierdamaged marker length counts, you may wish to insert a test in your
1655*593dc095SDavid du Colombierapplication for the case that the input buffer is completely full and yet
1656*593dc095SDavid du Colombierthe decoder has suspended without consuming any data --- otherwise, if this
1657*593dc095SDavid du Colombiersituation did occur, it would lead to an endless loop.  (The library can't
1658*593dc095SDavid du Colombierprovide this test since it has no idea whether "the buffer is full", or
1659*593dc095SDavid du Colombiereven whether there is a fixed-size input buffer.)
1660*593dc095SDavid du Colombier
1661*593dc095SDavid du ColombierThe input buffer would need to be 64K to allow for arbitrary COM or APPn
1662*593dc095SDavid du Colombiermarkers, but these are handled specially: they are either saved into allocated
1663*593dc095SDavid du Colombiermemory, or skipped over by calling skip_input_data().  In the former case,
1664*593dc095SDavid du Colombiersuspension is handled correctly, and in the latter case, the problem of
1665*593dc095SDavid du Colombierbuffer overrun is placed on skip_input_data's shoulders, as explained above.
1666*593dc095SDavid du ColombierNote that if you provide your own marker handling routine for large markers,
1667*593dc095SDavid du Colombieryou should consider how to deal with buffer overflow.
16687dd7cddfSDavid du Colombier
16697dd7cddfSDavid du ColombierMultiple-buffer management:
16707dd7cddfSDavid du Colombier
16717dd7cddfSDavid du ColombierIn some applications it is desirable to store the compressed data in a linked
16727dd7cddfSDavid du Colombierlist of buffer areas, so as to avoid data copying.  This can be handled by
16737dd7cddfSDavid du Colombierhaving empty_output_buffer() or fill_input_buffer() set the pointer and count
16747dd7cddfSDavid du Colombierto reference the next available buffer; FALSE is returned only if no more
16757dd7cddfSDavid du Colombierbuffers are available.  Although seemingly straightforward, there is a
16767dd7cddfSDavid du Colombierpitfall in this approach: the backtrack that occurs when FALSE is returned
16777dd7cddfSDavid du Colombiercould back up into an earlier buffer.  For example, when fill_input_buffer()
16787dd7cddfSDavid du Colombieris called, the current pointer & count indicate the backtrack restart point.
16797dd7cddfSDavid du ColombierSince fill_input_buffer() will set the pointer and count to refer to a new
16807dd7cddfSDavid du Colombierbuffer, the restart position must be saved somewhere else.  Suppose a second
16817dd7cddfSDavid du Colombiercall to fill_input_buffer() occurs in the same library call, and no
16827dd7cddfSDavid du Colombieradditional input data is available, so fill_input_buffer must return FALSE.
16837dd7cddfSDavid du ColombierIf the JPEG library has not moved the pointer/count forward in the current
16847dd7cddfSDavid du Colombierbuffer, then *the correct restart point is the saved position in the prior
16857dd7cddfSDavid du Colombierbuffer*.  Prior buffers may be discarded only after the library establishes
16867dd7cddfSDavid du Colombiera restart point within a later buffer.  Similar remarks apply for output into
16877dd7cddfSDavid du Colombiera chain of buffers.
16887dd7cddfSDavid du Colombier
16897dd7cddfSDavid du ColombierThe library will never attempt to backtrack over a skip_input_data() call,
16907dd7cddfSDavid du Colombierso any skipped data can be permanently discarded.  You still have to deal
16917dd7cddfSDavid du Colombierwith the case of skipping not-yet-received data, however.
16927dd7cddfSDavid du Colombier
16937dd7cddfSDavid du ColombierIt's much simpler to use only a single buffer; when fill_input_buffer() is
16947dd7cddfSDavid du Colombiercalled, move any unconsumed data (beyond the current pointer/count) down to
16957dd7cddfSDavid du Colombierthe beginning of this buffer and then load new data into the remaining buffer
16967dd7cddfSDavid du Colombierspace.  This approach requires a little more data copying but is far easier
16977dd7cddfSDavid du Colombierto get right.
16987dd7cddfSDavid du Colombier
16997dd7cddfSDavid du Colombier
17007dd7cddfSDavid du ColombierProgressive JPEG support
17017dd7cddfSDavid du Colombier------------------------
17027dd7cddfSDavid du Colombier
17037dd7cddfSDavid du ColombierProgressive JPEG rearranges the stored data into a series of scans of
17047dd7cddfSDavid du Colombierincreasing quality.  In situations where a JPEG file is transmitted across a
17057dd7cddfSDavid du Colombierslow communications link, a decoder can generate a low-quality image very
17067dd7cddfSDavid du Colombierquickly from the first scan, then gradually improve the displayed quality as
17077dd7cddfSDavid du Colombiermore scans are received.  The final image after all scans are complete is
17087dd7cddfSDavid du Colombieridentical to that of a regular (sequential) JPEG file of the same quality
17097dd7cddfSDavid du Colombiersetting.  Progressive JPEG files are often slightly smaller than equivalent
17107dd7cddfSDavid du Colombiersequential JPEG files, but the possibility of incremental display is the main
17117dd7cddfSDavid du Colombierreason for using progressive JPEG.
17127dd7cddfSDavid du Colombier
17137dd7cddfSDavid du ColombierThe IJG encoder library generates progressive JPEG files when given a
17147dd7cddfSDavid du Colombiersuitable "scan script" defining how to divide the data into scans.
17157dd7cddfSDavid du ColombierCreation of progressive JPEG files is otherwise transparent to the encoder.
17167dd7cddfSDavid du ColombierProgressive JPEG files can also be read transparently by the decoder library.
17177dd7cddfSDavid du ColombierIf the decoding application simply uses the library as defined above, it
17187dd7cddfSDavid du Colombierwill receive a final decoded image without any indication that the file was
17197dd7cddfSDavid du Colombierprogressive.  Of course, this approach does not allow incremental display.
17207dd7cddfSDavid du ColombierTo perform incremental display, an application needs to use the decoder
17217dd7cddfSDavid du Colombierlibrary's "buffered-image" mode, in which it receives a decoded image
17227dd7cddfSDavid du Colombiermultiple times.
17237dd7cddfSDavid du Colombier
17247dd7cddfSDavid du ColombierEach displayed scan requires about as much work to decode as a full JPEG
17257dd7cddfSDavid du Colombierimage of the same size, so the decoder must be fairly fast in relation to the
17267dd7cddfSDavid du Colombierdata transmission rate in order to make incremental display useful.  However,
17277dd7cddfSDavid du Colombierit is possible to skip displaying the image and simply add the incoming bits
17287dd7cddfSDavid du Colombierto the decoder's coefficient buffer.  This is fast because only Huffman
17297dd7cddfSDavid du Colombierdecoding need be done, not IDCT, upsampling, colorspace conversion, etc.
17307dd7cddfSDavid du ColombierThe IJG decoder library allows the application to switch dynamically between
17317dd7cddfSDavid du Colombierdisplaying the image and simply absorbing the incoming bits.  A properly
17327dd7cddfSDavid du Colombiercoded application can automatically adapt the number of display passes to
17337dd7cddfSDavid du Colombiersuit the time available as the image is received.  Also, a final
17347dd7cddfSDavid du Colombierhigher-quality display cycle can be performed from the buffered data after
17357dd7cddfSDavid du Colombierthe end of the file is reached.
17367dd7cddfSDavid du Colombier
17377dd7cddfSDavid du ColombierProgressive compression:
17387dd7cddfSDavid du Colombier
17397dd7cddfSDavid du ColombierTo create a progressive JPEG file (or a multiple-scan sequential JPEG file),
17407dd7cddfSDavid du Colombierset the scan_info cinfo field to point to an array of scan descriptors, and
17417dd7cddfSDavid du Colombierperform compression as usual.  Instead of constructing your own scan list,
17427dd7cddfSDavid du Colombieryou can call the jpeg_simple_progression() helper routine to create a
17437dd7cddfSDavid du Colombierrecommended progression sequence; this method should be used by all
17447dd7cddfSDavid du Colombierapplications that don't want to get involved in the nitty-gritty of
17457dd7cddfSDavid du Colombierprogressive scan sequence design.  (If you want to provide user control of
17467dd7cddfSDavid du Colombierscan sequences, you may wish to borrow the scan script reading code found
17477dd7cddfSDavid du Colombierin rdswitch.c, so that you can read scan script files just like cjpeg's.)
17487dd7cddfSDavid du ColombierWhen scan_info is not NULL, the compression library will store DCT'd data
17497dd7cddfSDavid du Colombierinto a buffer array as jpeg_write_scanlines() is called, and will emit all
17507dd7cddfSDavid du Colombierthe requested scans during jpeg_finish_compress().  This implies that
17517dd7cddfSDavid du Colombiermultiple-scan output cannot be created with a suspending data destination
17527dd7cddfSDavid du Colombiermanager, since jpeg_finish_compress() does not support suspension.  We
17537dd7cddfSDavid du Colombiershould also note that the compressor currently forces Huffman optimization
17547dd7cddfSDavid du Colombiermode when creating a progressive JPEG file, because the default Huffman
17557dd7cddfSDavid du Colombiertables are unsuitable for progressive files.
17567dd7cddfSDavid du Colombier
17577dd7cddfSDavid du ColombierProgressive decompression:
17587dd7cddfSDavid du Colombier
17597dd7cddfSDavid du ColombierWhen buffered-image mode is not used, the decoder library will read all of
17607dd7cddfSDavid du Colombiera multi-scan file during jpeg_start_decompress(), so that it can provide a
17617dd7cddfSDavid du Colombierfinal decoded image.  (Here "multi-scan" means either progressive or
17627dd7cddfSDavid du Colombiermulti-scan sequential.)  This makes multi-scan files transparent to the
17637dd7cddfSDavid du Colombierdecoding application.  However, existing applications that used suspending
17647dd7cddfSDavid du Colombierinput with version 5 of the IJG library will need to be modified to check
17657dd7cddfSDavid du Colombierfor a suspension return from jpeg_start_decompress().
17667dd7cddfSDavid du Colombier
17677dd7cddfSDavid du ColombierTo perform incremental display, an application must use the library's
17687dd7cddfSDavid du Colombierbuffered-image mode.  This is described in the next section.
17697dd7cddfSDavid du Colombier
17707dd7cddfSDavid du Colombier
17717dd7cddfSDavid du ColombierBuffered-image mode
17727dd7cddfSDavid du Colombier-------------------
17737dd7cddfSDavid du Colombier
17747dd7cddfSDavid du ColombierIn buffered-image mode, the library stores the partially decoded image in a
17757dd7cddfSDavid du Colombiercoefficient buffer, from which it can be read out as many times as desired.
17767dd7cddfSDavid du ColombierThis mode is typically used for incremental display of progressive JPEG files,
17777dd7cddfSDavid du Colombierbut it can be used with any JPEG file.  Each scan of a progressive JPEG file
17787dd7cddfSDavid du Colombieradds more data (more detail) to the buffered image.  The application can
17797dd7cddfSDavid du Colombierdisplay in lockstep with the source file (one display pass per input scan),
17807dd7cddfSDavid du Colombieror it can allow input processing to outrun display processing.  By making
17817dd7cddfSDavid du Colombierinput and display processing run independently, it is possible for the
17827dd7cddfSDavid du Colombierapplication to adapt progressive display to a wide range of data transmission
17837dd7cddfSDavid du Colombierrates.
17847dd7cddfSDavid du Colombier
17857dd7cddfSDavid du ColombierThe basic control flow for buffered-image decoding is
17867dd7cddfSDavid du Colombier
17877dd7cddfSDavid du Colombier	jpeg_create_decompress()
17887dd7cddfSDavid du Colombier	set data source
17897dd7cddfSDavid du Colombier	jpeg_read_header()
17907dd7cddfSDavid du Colombier	set overall decompression parameters
17917dd7cddfSDavid du Colombier	cinfo.buffered_image = TRUE;	/* select buffered-image mode */
17927dd7cddfSDavid du Colombier	jpeg_start_decompress()
17937dd7cddfSDavid du Colombier	for (each output pass) {
17947dd7cddfSDavid du Colombier	    adjust output decompression parameters if required
17957dd7cddfSDavid du Colombier	    jpeg_start_output()		/* start a new output pass */
17967dd7cddfSDavid du Colombier	    for (all scanlines in image) {
17977dd7cddfSDavid du Colombier	        jpeg_read_scanlines()
17987dd7cddfSDavid du Colombier	        display scanlines
17997dd7cddfSDavid du Colombier	    }
18007dd7cddfSDavid du Colombier	    jpeg_finish_output()	/* terminate output pass */
18017dd7cddfSDavid du Colombier	}
18027dd7cddfSDavid du Colombier	jpeg_finish_decompress()
18037dd7cddfSDavid du Colombier	jpeg_destroy_decompress()
18047dd7cddfSDavid du Colombier
18057dd7cddfSDavid du ColombierThis differs from ordinary unbuffered decoding in that there is an additional
18067dd7cddfSDavid du Colombierlevel of looping.  The application can choose how many output passes to make
18077dd7cddfSDavid du Colombierand how to display each pass.
18087dd7cddfSDavid du Colombier
18097dd7cddfSDavid du ColombierThe simplest approach to displaying progressive images is to do one display
18107dd7cddfSDavid du Colombierpass for each scan appearing in the input file.  In this case the outer loop
18117dd7cddfSDavid du Colombiercondition is typically
18127dd7cddfSDavid du Colombier	while (! jpeg_input_complete(&cinfo))
18137dd7cddfSDavid du Colombierand the start-output call should read
18147dd7cddfSDavid du Colombier	jpeg_start_output(&cinfo, cinfo.input_scan_number);
18157dd7cddfSDavid du ColombierThe second parameter to jpeg_start_output() indicates which scan of the input
18167dd7cddfSDavid du Colombierfile is to be displayed; the scans are numbered starting at 1 for this
18177dd7cddfSDavid du Colombierpurpose.  (You can use a loop counter starting at 1 if you like, but using
18187dd7cddfSDavid du Colombierthe library's input scan counter is easier.)  The library automatically reads
18197dd7cddfSDavid du Colombierdata as necessary to complete each requested scan, and jpeg_finish_output()
18207dd7cddfSDavid du Colombieradvances to the next scan or end-of-image marker (hence input_scan_number
18217dd7cddfSDavid du Colombierwill be incremented by the time control arrives back at jpeg_start_output()).
18227dd7cddfSDavid du ColombierWith this technique, data is read from the input file only as needed, and
18237dd7cddfSDavid du Colombierinput and output processing run in lockstep.
18247dd7cddfSDavid du Colombier
18257dd7cddfSDavid du ColombierAfter reading the final scan and reaching the end of the input file, the
18267dd7cddfSDavid du Colombierbuffered image remains available; it can be read additional times by
18277dd7cddfSDavid du Colombierrepeating the jpeg_start_output()/jpeg_read_scanlines()/jpeg_finish_output()
18287dd7cddfSDavid du Colombiersequence.  For example, a useful technique is to use fast one-pass color
18297dd7cddfSDavid du Colombierquantization for display passes made while the image is arriving, followed by
18307dd7cddfSDavid du Colombiera final display pass using two-pass quantization for highest quality.  This
18317dd7cddfSDavid du Colombieris done by changing the library parameters before the final output pass.
18327dd7cddfSDavid du ColombierChanging parameters between passes is discussed in detail below.
18337dd7cddfSDavid du Colombier
18347dd7cddfSDavid du ColombierIn general the last scan of a progressive file cannot be recognized as such
18357dd7cddfSDavid du Colombieruntil after it is read, so a post-input display pass is the best approach if
18367dd7cddfSDavid du Colombieryou want special processing in the final pass.
18377dd7cddfSDavid du Colombier
18387dd7cddfSDavid du ColombierWhen done with the image, be sure to call jpeg_finish_decompress() to release
18397dd7cddfSDavid du Colombierthe buffered image (or just use jpeg_destroy_decompress()).
18407dd7cddfSDavid du Colombier
18417dd7cddfSDavid du ColombierIf input data arrives faster than it can be displayed, the application can
18427dd7cddfSDavid du Colombiercause the library to decode input data in advance of what's needed to produce
18437dd7cddfSDavid du Colombieroutput.  This is done by calling the routine jpeg_consume_input().
18447dd7cddfSDavid du ColombierThe return value is one of the following:
18457dd7cddfSDavid du Colombier	JPEG_REACHED_SOS:    reached an SOS marker (the start of a new scan)
18467dd7cddfSDavid du Colombier	JPEG_REACHED_EOI:    reached the EOI marker (end of image)
18477dd7cddfSDavid du Colombier	JPEG_ROW_COMPLETED:  completed reading one MCU row of compressed data
18487dd7cddfSDavid du Colombier	JPEG_SCAN_COMPLETED: completed reading last MCU row of current scan
18497dd7cddfSDavid du Colombier	JPEG_SUSPENDED:      suspended before completing any of the above
18507dd7cddfSDavid du Colombier(JPEG_SUSPENDED can occur only if a suspending data source is used.)  This
18517dd7cddfSDavid du Colombierroutine can be called at any time after initializing the JPEG object.  It
18527dd7cddfSDavid du Colombierreads some additional data and returns when one of the indicated significant
18537dd7cddfSDavid du Colombierevents occurs.  (If called after the EOI marker is reached, it will
18547dd7cddfSDavid du Colombierimmediately return JPEG_REACHED_EOI without attempting to read more data.)
18557dd7cddfSDavid du Colombier
18567dd7cddfSDavid du ColombierThe library's output processing will automatically call jpeg_consume_input()
18577dd7cddfSDavid du Colombierwhenever the output processing overtakes the input; thus, simple lockstep
18587dd7cddfSDavid du Colombierdisplay requires no direct calls to jpeg_consume_input().  But by adding
18597dd7cddfSDavid du Colombiercalls to jpeg_consume_input(), you can absorb data in advance of what is
18607dd7cddfSDavid du Colombierbeing displayed.  This has two benefits:
18617dd7cddfSDavid du Colombier  * You can limit buildup of unprocessed data in your input buffer.
18627dd7cddfSDavid du Colombier  * You can eliminate extra display passes by paying attention to the
18637dd7cddfSDavid du Colombier    state of the library's input processing.
18647dd7cddfSDavid du Colombier
18657dd7cddfSDavid du ColombierThe first of these benefits only requires interspersing calls to
18667dd7cddfSDavid du Colombierjpeg_consume_input() with your display operations and any other processing
18677dd7cddfSDavid du Colombieryou may be doing.  To avoid wasting cycles due to backtracking, it's best to
18687dd7cddfSDavid du Colombiercall jpeg_consume_input() only after a hundred or so new bytes have arrived.
18697dd7cddfSDavid du ColombierThis is discussed further under "I/O suspension", above.  (Note: the JPEG
18707dd7cddfSDavid du Colombierlibrary currently is not thread-safe.  You must not call jpeg_consume_input()
18717dd7cddfSDavid du Colombierfrom one thread of control if a different library routine is working on the
18727dd7cddfSDavid du Colombiersame JPEG object in another thread.)
18737dd7cddfSDavid du Colombier
18747dd7cddfSDavid du ColombierWhen input arrives fast enough that more than one new scan is available
18757dd7cddfSDavid du Colombierbefore you start a new output pass, you may as well skip the output pass
18767dd7cddfSDavid du Colombiercorresponding to the completed scan.  This occurs for free if you pass
18777dd7cddfSDavid du Colombiercinfo.input_scan_number as the target scan number to jpeg_start_output().
18787dd7cddfSDavid du ColombierThe input_scan_number field is simply the index of the scan currently being
18797dd7cddfSDavid du Colombierconsumed by the input processor.  You can ensure that this is up-to-date by
18807dd7cddfSDavid du Colombieremptying the input buffer just before calling jpeg_start_output(): call
18817dd7cddfSDavid du Colombierjpeg_consume_input() repeatedly until it returns JPEG_SUSPENDED or
18827dd7cddfSDavid du ColombierJPEG_REACHED_EOI.
18837dd7cddfSDavid du Colombier
18847dd7cddfSDavid du ColombierThe target scan number passed to jpeg_start_output() is saved in the
18857dd7cddfSDavid du Colombiercinfo.output_scan_number field.  The library's output processing calls
18867dd7cddfSDavid du Colombierjpeg_consume_input() whenever the current input scan number and row within
18877dd7cddfSDavid du Colombierthat scan is less than or equal to the current output scan number and row.
18887dd7cddfSDavid du ColombierThus, input processing can "get ahead" of the output processing but is not
18897dd7cddfSDavid du Colombierallowed to "fall behind".  You can achieve several different effects by
18907dd7cddfSDavid du Colombiermanipulating this interlock rule.  For example, if you pass a target scan
18917dd7cddfSDavid du Colombiernumber greater than the current input scan number, the output processor will
18927dd7cddfSDavid du Colombierwait until that scan starts to arrive before producing any output.  (To avoid
18937dd7cddfSDavid du Colombieran infinite loop, the target scan number is automatically reset to the last
18947dd7cddfSDavid du Colombierscan number when the end of image is reached.  Thus, if you specify a large
18957dd7cddfSDavid du Colombiertarget scan number, the library will just absorb the entire input file and
18967dd7cddfSDavid du Colombierthen perform an output pass.  This is effectively the same as what
18977dd7cddfSDavid du Colombierjpeg_start_decompress() does when you don't select buffered-image mode.)
18987dd7cddfSDavid du ColombierWhen you pass a target scan number equal to the current input scan number,
18997dd7cddfSDavid du Colombierthe image is displayed no faster than the current input scan arrives.  The
19007dd7cddfSDavid du Colombierfinal possibility is to pass a target scan number less than the current input
19017dd7cddfSDavid du Colombierscan number; this disables the input/output interlock and causes the output
19027dd7cddfSDavid du Colombierprocessor to simply display whatever it finds in the image buffer, without
19037dd7cddfSDavid du Colombierwaiting for input.  (However, the library will not accept a target scan
19047dd7cddfSDavid du Colombiernumber less than one, so you can't avoid waiting for the first scan.)
19057dd7cddfSDavid du Colombier
19067dd7cddfSDavid du ColombierWhen data is arriving faster than the output display processing can advance
19077dd7cddfSDavid du Colombierthrough the image, jpeg_consume_input() will store data into the buffered
19087dd7cddfSDavid du Colombierimage beyond the point at which the output processing is reading data out
19097dd7cddfSDavid du Colombieragain.  If the input arrives fast enough, it may "wrap around" the buffer to
19107dd7cddfSDavid du Colombierthe point where the input is more than one whole scan ahead of the output.
19117dd7cddfSDavid du ColombierIf the output processing simply proceeds through its display pass without
19127dd7cddfSDavid du Colombierpaying attention to the input, the effect seen on-screen is that the lower
19137dd7cddfSDavid du Colombierpart of the image is one or more scans better in quality than the upper part.
19147dd7cddfSDavid du ColombierThen, when the next output scan is started, you have a choice of what target
19157dd7cddfSDavid du Colombierscan number to use.  The recommended choice is to use the current input scan
19167dd7cddfSDavid du Colombiernumber at that time, which implies that you've skipped the output scans
19177dd7cddfSDavid du Colombiercorresponding to the input scans that were completed while you processed the
19187dd7cddfSDavid du Colombierprevious output scan.  In this way, the decoder automatically adapts its
19197dd7cddfSDavid du Colombierspeed to the arriving data, by skipping output scans as necessary to keep up
19207dd7cddfSDavid du Colombierwith the arriving data.
19217dd7cddfSDavid du Colombier
19227dd7cddfSDavid du ColombierWhen using this strategy, you'll want to be sure that you perform a final
19237dd7cddfSDavid du Colombieroutput pass after receiving all the data; otherwise your last display may not
19247dd7cddfSDavid du Colombierbe full quality across the whole screen.  So the right outer loop logic is
19257dd7cddfSDavid du Colombiersomething like this:
19267dd7cddfSDavid du Colombier	do {
19277dd7cddfSDavid du Colombier	    absorb any waiting input by calling jpeg_consume_input()
19287dd7cddfSDavid du Colombier	    final_pass = jpeg_input_complete(&cinfo);
19297dd7cddfSDavid du Colombier	    adjust output decompression parameters if required
19307dd7cddfSDavid du Colombier	    jpeg_start_output(&cinfo, cinfo.input_scan_number);
19317dd7cddfSDavid du Colombier	    ...
19327dd7cddfSDavid du Colombier	    jpeg_finish_output()
19337dd7cddfSDavid du Colombier	} while (! final_pass);
19347dd7cddfSDavid du Colombierrather than quitting as soon as jpeg_input_complete() returns TRUE.  This
19357dd7cddfSDavid du Colombierarrangement makes it simple to use higher-quality decoding parameters
19367dd7cddfSDavid du Colombierfor the final pass.  But if you don't want to use special parameters for
19377dd7cddfSDavid du Colombierthe final pass, the right loop logic is like this:
19387dd7cddfSDavid du Colombier	for (;;) {
19397dd7cddfSDavid du Colombier	    absorb any waiting input by calling jpeg_consume_input()
19407dd7cddfSDavid du Colombier	    jpeg_start_output(&cinfo, cinfo.input_scan_number);
19417dd7cddfSDavid du Colombier	    ...
19427dd7cddfSDavid du Colombier	    jpeg_finish_output()
19437dd7cddfSDavid du Colombier	    if (jpeg_input_complete(&cinfo) &&
19447dd7cddfSDavid du Colombier	        cinfo.input_scan_number == cinfo.output_scan_number)
19457dd7cddfSDavid du Colombier	      break;
19467dd7cddfSDavid du Colombier	}
19477dd7cddfSDavid du ColombierIn this case you don't need to know in advance whether an output pass is to
19487dd7cddfSDavid du Colombierbe the last one, so it's not necessary to have reached EOF before starting
19497dd7cddfSDavid du Colombierthe final output pass; rather, what you want to test is whether the output
19507dd7cddfSDavid du Colombierpass was performed in sync with the final input scan.  This form of the loop
19517dd7cddfSDavid du Colombierwill avoid an extra output pass whenever the decoder is able (or nearly able)
19527dd7cddfSDavid du Colombierto keep up with the incoming data.
19537dd7cddfSDavid du Colombier
19547dd7cddfSDavid du ColombierWhen the data transmission speed is high, you might begin a display pass,
19557dd7cddfSDavid du Colombierthen find that much or all of the file has arrived before you can complete
19567dd7cddfSDavid du Colombierthe pass.  (You can detect this by noting the JPEG_REACHED_EOI return code
19577dd7cddfSDavid du Colombierfrom jpeg_consume_input(), or equivalently by testing jpeg_input_complete().)
19587dd7cddfSDavid du ColombierIn this situation you may wish to abort the current display pass and start a
19597dd7cddfSDavid du Colombiernew one using the newly arrived information.  To do so, just call
19607dd7cddfSDavid du Colombierjpeg_finish_output() and then start a new pass with jpeg_start_output().
19617dd7cddfSDavid du Colombier
19627dd7cddfSDavid du ColombierA variant strategy is to abort and restart display if more than one complete
19637dd7cddfSDavid du Colombierscan arrives during an output pass; this can be detected by noting
19647dd7cddfSDavid du ColombierJPEG_REACHED_SOS returns and/or examining cinfo.input_scan_number.  This
19657dd7cddfSDavid du Colombieridea should be employed with caution, however, since the display process
19667dd7cddfSDavid du Colombiermight never get to the bottom of the image before being aborted, resulting
19677dd7cddfSDavid du Colombierin the lower part of the screen being several passes worse than the upper.
19687dd7cddfSDavid du ColombierIn most cases it's probably best to abort an output pass only if the whole
19697dd7cddfSDavid du Colombierfile has arrived and you want to begin the final output pass immediately.
19707dd7cddfSDavid du Colombier
19717dd7cddfSDavid du ColombierWhen receiving data across a communication link, we recommend always using
19727dd7cddfSDavid du Colombierthe current input scan number for the output target scan number; if a
19737dd7cddfSDavid du Colombierhigher-quality final pass is to be done, it should be started (aborting any
19747dd7cddfSDavid du Colombierincomplete output pass) as soon as the end of file is received.  However,
19757dd7cddfSDavid du Colombiermany other strategies are possible.  For example, the application can examine
19767dd7cddfSDavid du Colombierthe parameters of the current input scan and decide whether to display it or
19777dd7cddfSDavid du Colombiernot.  If the scan contains only chroma data, one might choose not to use it
19787dd7cddfSDavid du Colombieras the target scan, expecting that the scan will be small and will arrive
19797dd7cddfSDavid du Colombierquickly.  To skip to the next scan, call jpeg_consume_input() until it
19807dd7cddfSDavid du Colombierreturns JPEG_REACHED_SOS or JPEG_REACHED_EOI.  Or just use the next higher
19817dd7cddfSDavid du Colombiernumber as the target scan for jpeg_start_output(); but that method doesn't
19827dd7cddfSDavid du Colombierlet you inspect the next scan's parameters before deciding to display it.
19837dd7cddfSDavid du Colombier
19847dd7cddfSDavid du Colombier
19857dd7cddfSDavid du ColombierIn buffered-image mode, jpeg_start_decompress() never performs input and
19867dd7cddfSDavid du Colombierthus never suspends.  An application that uses input suspension with
19877dd7cddfSDavid du Colombierbuffered-image mode must be prepared for suspension returns from these
19887dd7cddfSDavid du Colombierroutines:
19897dd7cddfSDavid du Colombier* jpeg_start_output() performs input only if you request 2-pass quantization
19907dd7cddfSDavid du Colombier  and the target scan isn't fully read yet.  (This is discussed below.)
19917dd7cddfSDavid du Colombier* jpeg_read_scanlines(), as always, returns the number of scanlines that it
19927dd7cddfSDavid du Colombier  was able to produce before suspending.
19937dd7cddfSDavid du Colombier* jpeg_finish_output() will read any markers following the target scan,
19947dd7cddfSDavid du Colombier  up to the end of the file or the SOS marker that begins another scan.
19957dd7cddfSDavid du Colombier  (But it reads no input if jpeg_consume_input() has already reached the
19967dd7cddfSDavid du Colombier  end of the file or a SOS marker beyond the target output scan.)
19977dd7cddfSDavid du Colombier* jpeg_finish_decompress() will read until the end of file, and thus can
19987dd7cddfSDavid du Colombier  suspend if the end hasn't already been reached (as can be tested by
19997dd7cddfSDavid du Colombier  calling jpeg_input_complete()).
20007dd7cddfSDavid du Colombierjpeg_start_output(), jpeg_finish_output(), and jpeg_finish_decompress()
20017dd7cddfSDavid du Colombierall return TRUE if they completed their tasks, FALSE if they had to suspend.
20027dd7cddfSDavid du ColombierIn the event of a FALSE return, the application must load more input data
20037dd7cddfSDavid du Colombierand repeat the call.  Applications that use non-suspending data sources need
20047dd7cddfSDavid du Colombiernot check the return values of these three routines.
20057dd7cddfSDavid du Colombier
20067dd7cddfSDavid du Colombier
20077dd7cddfSDavid du ColombierIt is possible to change decoding parameters between output passes in the
20087dd7cddfSDavid du Colombierbuffered-image mode.  The decoder library currently supports only very
20097dd7cddfSDavid du Colombierlimited changes of parameters.  ONLY THE FOLLOWING parameter changes are
20107dd7cddfSDavid du Colombierallowed after jpeg_start_decompress() is called:
20117dd7cddfSDavid du Colombier* dct_method can be changed before each call to jpeg_start_output().
20127dd7cddfSDavid du Colombier  For example, one could use a fast DCT method for early scans, changing
20137dd7cddfSDavid du Colombier  to a higher quality method for the final scan.
20147dd7cddfSDavid du Colombier* dither_mode can be changed before each call to jpeg_start_output();
20157dd7cddfSDavid du Colombier  of course this has no impact if not using color quantization.  Typically
20167dd7cddfSDavid du Colombier  one would use ordered dither for initial passes, then switch to
20177dd7cddfSDavid du Colombier  Floyd-Steinberg dither for the final pass.  Caution: changing dither mode
20187dd7cddfSDavid du Colombier  can cause more memory to be allocated by the library.  Although the amount
20197dd7cddfSDavid du Colombier  of memory involved is not large (a scanline or so), it may cause the
20207dd7cddfSDavid du Colombier  initial max_memory_to_use specification to be exceeded, which in the worst
20217dd7cddfSDavid du Colombier  case would result in an out-of-memory failure.
20227dd7cddfSDavid du Colombier* do_block_smoothing can be changed before each call to jpeg_start_output().
20237dd7cddfSDavid du Colombier  This setting is relevant only when decoding a progressive JPEG image.
20247dd7cddfSDavid du Colombier  During the first DC-only scan, block smoothing provides a very "fuzzy" look
20257dd7cddfSDavid du Colombier  instead of the very "blocky" look seen without it; which is better seems a
20267dd7cddfSDavid du Colombier  matter of personal taste.  But block smoothing is nearly always a win
20277dd7cddfSDavid du Colombier  during later stages, especially when decoding a successive-approximation
20287dd7cddfSDavid du Colombier  image: smoothing helps to hide the slight blockiness that otherwise shows
20297dd7cddfSDavid du Colombier  up on smooth gradients until the lowest coefficient bits are sent.
20307dd7cddfSDavid du Colombier* Color quantization mode can be changed under the rules described below.
20317dd7cddfSDavid du Colombier  You *cannot* change between full-color and quantized output (because that
20327dd7cddfSDavid du Colombier  would alter the required I/O buffer sizes), but you can change which
20337dd7cddfSDavid du Colombier  quantization method is used.
20347dd7cddfSDavid du Colombier
20357dd7cddfSDavid du ColombierWhen generating color-quantized output, changing quantization method is a
20367dd7cddfSDavid du Colombiervery useful way of switching between high-speed and high-quality display.
20377dd7cddfSDavid du ColombierThe library allows you to change among its three quantization methods:
20387dd7cddfSDavid du Colombier1. Single-pass quantization to a fixed color cube.
20397dd7cddfSDavid du Colombier   Selected by cinfo.two_pass_quantize = FALSE and cinfo.colormap = NULL.
20407dd7cddfSDavid du Colombier2. Single-pass quantization to an application-supplied colormap.
20417dd7cddfSDavid du Colombier   Selected by setting cinfo.colormap to point to the colormap (the value of
20427dd7cddfSDavid du Colombier   two_pass_quantize is ignored); also set cinfo.actual_number_of_colors.
20437dd7cddfSDavid du Colombier3. Two-pass quantization to a colormap chosen specifically for the image.
20447dd7cddfSDavid du Colombier   Selected by cinfo.two_pass_quantize = TRUE and cinfo.colormap = NULL.
20457dd7cddfSDavid du Colombier   (This is the default setting selected by jpeg_read_header, but it is
20467dd7cddfSDavid du Colombier   probably NOT what you want for the first pass of progressive display!)
20477dd7cddfSDavid du ColombierThese methods offer successively better quality and lesser speed.  However,
20487dd7cddfSDavid du Colombieronly the first method is available for quantizing in non-RGB color spaces.
20497dd7cddfSDavid du Colombier
20507dd7cddfSDavid du ColombierIMPORTANT: because the different quantizer methods have very different
20517dd7cddfSDavid du Colombierworking-storage requirements, the library requires you to indicate which
20527dd7cddfSDavid du Colombierone(s) you intend to use before you call jpeg_start_decompress().  (If we did
20537dd7cddfSDavid du Colombiernot require this, the max_memory_to_use setting would be a complete fiction.)
20547dd7cddfSDavid du ColombierYou do this by setting one or more of these three cinfo fields to TRUE:
20557dd7cddfSDavid du Colombier	enable_1pass_quant		Fixed color cube colormap
20567dd7cddfSDavid du Colombier	enable_external_quant		Externally-supplied colormap
20577dd7cddfSDavid du Colombier	enable_2pass_quant		Two-pass custom colormap
20587dd7cddfSDavid du ColombierAll three are initialized FALSE by jpeg_read_header().  But
20597dd7cddfSDavid du Colombierjpeg_start_decompress() automatically sets TRUE the one selected by the
20607dd7cddfSDavid du Colombiercurrent two_pass_quantize and colormap settings, so you only need to set the
20617dd7cddfSDavid du Colombierenable flags for any other quantization methods you plan to change to later.
20627dd7cddfSDavid du Colombier
20637dd7cddfSDavid du ColombierAfter setting the enable flags correctly at jpeg_start_decompress() time, you
20647dd7cddfSDavid du Colombiercan change to any enabled quantization method by setting two_pass_quantize
20657dd7cddfSDavid du Colombierand colormap properly just before calling jpeg_start_output().  The following
20667dd7cddfSDavid du Colombierspecial rules apply:
20677dd7cddfSDavid du Colombier1. You must explicitly set cinfo.colormap to NULL when switching to 1-pass
20687dd7cddfSDavid du Colombier   or 2-pass mode from a different mode, or when you want the 2-pass
20697dd7cddfSDavid du Colombier   quantizer to be re-run to generate a new colormap.
20707dd7cddfSDavid du Colombier2. To switch to an external colormap, or to change to a different external
20717dd7cddfSDavid du Colombier   colormap than was used on the prior pass, you must call
20727dd7cddfSDavid du Colombier   jpeg_new_colormap() after setting cinfo.colormap.
20737dd7cddfSDavid du ColombierNOTE: if you want to use the same colormap as was used in the prior pass,
20747dd7cddfSDavid du Colombieryou should not do either of these things.  This will save some nontrivial
20757dd7cddfSDavid du Colombierswitchover costs.
20767dd7cddfSDavid du Colombier(These requirements exist because cinfo.colormap will always be non-NULL
20777dd7cddfSDavid du Colombierafter completing a prior output pass, since both the 1-pass and 2-pass
20787dd7cddfSDavid du Colombierquantizers set it to point to their output colormaps.  Thus you have to
20797dd7cddfSDavid du Colombierdo one of these two things to notify the library that something has changed.
20807dd7cddfSDavid du ColombierYup, it's a bit klugy, but it's necessary to do it this way for backwards
20817dd7cddfSDavid du Colombiercompatibility.)
20827dd7cddfSDavid du Colombier
20837dd7cddfSDavid du ColombierNote that in buffered-image mode, the library generates any requested colormap
20847dd7cddfSDavid du Colombierduring jpeg_start_output(), not during jpeg_start_decompress().
20857dd7cddfSDavid du Colombier
20867dd7cddfSDavid du ColombierWhen using two-pass quantization, jpeg_start_output() makes a pass over the
20877dd7cddfSDavid du Colombierbuffered image to determine the optimum color map; it therefore may take a
20887dd7cddfSDavid du Colombiersignificant amount of time, whereas ordinarily it does little work.  The
20897dd7cddfSDavid du Colombierprogress monitor hook is called during this pass, if defined.  It is also
20907dd7cddfSDavid du Colombierimportant to realize that if the specified target scan number is greater than
20917dd7cddfSDavid du Colombieror equal to the current input scan number, jpeg_start_output() will attempt
20927dd7cddfSDavid du Colombierto consume input as it makes this pass.  If you use a suspending data source,
20937dd7cddfSDavid du Colombieryou need to check for a FALSE return from jpeg_start_output() under these
20947dd7cddfSDavid du Colombierconditions.  The combination of 2-pass quantization and a not-yet-fully-read
20957dd7cddfSDavid du Colombiertarget scan is the only case in which jpeg_start_output() will consume input.
20967dd7cddfSDavid du Colombier
20977dd7cddfSDavid du Colombier
20987dd7cddfSDavid du ColombierApplication authors who support buffered-image mode may be tempted to use it
20997dd7cddfSDavid du Colombierfor all JPEG images, even single-scan ones.  This will work, but it is
21007dd7cddfSDavid du Colombierinefficient: there is no need to create an image-sized coefficient buffer for
21017dd7cddfSDavid du Colombiersingle-scan images.  Requesting buffered-image mode for such an image wastes
21027dd7cddfSDavid du Colombiermemory.  Worse, it can cost time on large images, since the buffered data has
21037dd7cddfSDavid du Colombierto be swapped out or written to a temporary file.  If you are concerned about
21047dd7cddfSDavid du Colombiermaximum performance on baseline JPEG files, you should use buffered-image
21057dd7cddfSDavid du Colombiermode only when the incoming file actually has multiple scans.  This can be
21067dd7cddfSDavid du Colombiertested by calling jpeg_has_multiple_scans(), which will return a correct
21077dd7cddfSDavid du Colombierresult at any time after jpeg_read_header() completes.
21087dd7cddfSDavid du Colombier
21097dd7cddfSDavid du ColombierIt is also worth noting that when you use jpeg_consume_input() to let input
21107dd7cddfSDavid du Colombierprocessing get ahead of output processing, the resulting pattern of access to
21117dd7cddfSDavid du Colombierthe coefficient buffer is quite nonsequential.  It's best to use the memory
21127dd7cddfSDavid du Colombiermanager jmemnobs.c if you can (ie, if you have enough real or virtual main
21137dd7cddfSDavid du Colombiermemory).  If not, at least make sure that max_memory_to_use is set as high as
21147dd7cddfSDavid du Colombierpossible.  If the JPEG memory manager has to use a temporary file, you will
21157dd7cddfSDavid du Colombierprobably see a lot of disk traffic and poor performance.  (This could be
21167dd7cddfSDavid du Colombierimproved with additional work on the memory manager, but we haven't gotten
21177dd7cddfSDavid du Colombieraround to it yet.)
21187dd7cddfSDavid du Colombier
21197dd7cddfSDavid du ColombierIn some applications it may be convenient to use jpeg_consume_input() for all
21207dd7cddfSDavid du Colombierinput processing, including reading the initial markers; that is, you may
21217dd7cddfSDavid du Colombierwish to call jpeg_consume_input() instead of jpeg_read_header() during
21227dd7cddfSDavid du Colombierstartup.  This works, but note that you must check for JPEG_REACHED_SOS and
21237dd7cddfSDavid du ColombierJPEG_REACHED_EOI return codes as the equivalent of jpeg_read_header's codes.
21247dd7cddfSDavid du ColombierOnce the first SOS marker has been reached, you must call
21257dd7cddfSDavid du Colombierjpeg_start_decompress() before jpeg_consume_input() will consume more input;
21267dd7cddfSDavid du Colombierit'll just keep returning JPEG_REACHED_SOS until you do.  If you read a
21277dd7cddfSDavid du Colombiertables-only file this way, jpeg_consume_input() will return JPEG_REACHED_EOI
21287dd7cddfSDavid du Colombierwithout ever returning JPEG_REACHED_SOS; be sure to check for this case.
21297dd7cddfSDavid du ColombierIf this happens, the decompressor will not read any more input until you call
21307dd7cddfSDavid du Colombierjpeg_abort() to reset it.  It is OK to call jpeg_consume_input() even when not
21317dd7cddfSDavid du Colombierusing buffered-image mode, but in that case it's basically a no-op after the
21327dd7cddfSDavid du Colombierinitial markers have been read: it will just return JPEG_SUSPENDED.
21337dd7cddfSDavid du Colombier
21347dd7cddfSDavid du Colombier
21357dd7cddfSDavid du ColombierAbbreviated datastreams and multiple images
21367dd7cddfSDavid du Colombier-------------------------------------------
21377dd7cddfSDavid du Colombier
21387dd7cddfSDavid du ColombierA JPEG compression or decompression object can be reused to process multiple
21397dd7cddfSDavid du Colombierimages.  This saves a small amount of time per image by eliminating the
21407dd7cddfSDavid du Colombier"create" and "destroy" operations, but that isn't the real purpose of the
21417dd7cddfSDavid du Colombierfeature.  Rather, reuse of an object provides support for abbreviated JPEG
21427dd7cddfSDavid du Colombierdatastreams.  Object reuse can also simplify processing a series of images in
21437dd7cddfSDavid du Colombiera single input or output file.  This section explains these features.
21447dd7cddfSDavid du Colombier
21457dd7cddfSDavid du ColombierA JPEG file normally contains several hundred bytes worth of quantization
21467dd7cddfSDavid du Colombierand Huffman tables.  In a situation where many images will be stored or
21477dd7cddfSDavid du Colombiertransmitted with identical tables, this may represent an annoying overhead.
21487dd7cddfSDavid du ColombierThe JPEG standard therefore permits tables to be omitted.  The standard
21497dd7cddfSDavid du Colombierdefines three classes of JPEG datastreams:
21507dd7cddfSDavid du Colombier  * "Interchange" datastreams contain an image and all tables needed to decode
21517dd7cddfSDavid du Colombier     the image.  These are the usual kind of JPEG file.
21527dd7cddfSDavid du Colombier  * "Abbreviated image" datastreams contain an image, but are missing some or
21537dd7cddfSDavid du Colombier    all of the tables needed to decode that image.
21547dd7cddfSDavid du Colombier  * "Abbreviated table specification" (henceforth "tables-only") datastreams
21557dd7cddfSDavid du Colombier    contain only table specifications.
21567dd7cddfSDavid du ColombierTo decode an abbreviated image, it is necessary to load the missing table(s)
21577dd7cddfSDavid du Colombierinto the decoder beforehand.  This can be accomplished by reading a separate
21587dd7cddfSDavid du Colombiertables-only file.  A variant scheme uses a series of images in which the first
21597dd7cddfSDavid du Colombierimage is an interchange (complete) datastream, while subsequent ones are
21607dd7cddfSDavid du Colombierabbreviated and rely on the tables loaded by the first image.  It is assumed
21617dd7cddfSDavid du Colombierthat once the decoder has read a table, it will remember that table until a
21627dd7cddfSDavid du Colombiernew definition for the same table number is encountered.
21637dd7cddfSDavid du Colombier
21647dd7cddfSDavid du ColombierIt is the application designer's responsibility to figure out how to associate
21657dd7cddfSDavid du Colombierthe correct tables with an abbreviated image.  While abbreviated datastreams
21667dd7cddfSDavid du Colombiercan be useful in a closed environment, their use is strongly discouraged in
21677dd7cddfSDavid du Colombierany situation where data exchange with other applications might be needed.
21687dd7cddfSDavid du ColombierCaveat designer.
21697dd7cddfSDavid du Colombier
21707dd7cddfSDavid du ColombierThe JPEG library provides support for reading and writing any combination of
21717dd7cddfSDavid du Colombiertables-only datastreams and abbreviated images.  In both compression and
21727dd7cddfSDavid du Colombierdecompression objects, a quantization or Huffman table will be retained for
21737dd7cddfSDavid du Colombierthe lifetime of the object, unless it is overwritten by a new table definition.
21747dd7cddfSDavid du Colombier
21757dd7cddfSDavid du Colombier
21767dd7cddfSDavid du ColombierTo create abbreviated image datastreams, it is only necessary to tell the
21777dd7cddfSDavid du Colombiercompressor not to emit some or all of the tables it is using.  Each
21787dd7cddfSDavid du Colombierquantization and Huffman table struct contains a boolean field "sent_table",
21797dd7cddfSDavid du Colombierwhich normally is initialized to FALSE.  For each table used by the image, the
21807dd7cddfSDavid du Colombierheader-writing process emits the table and sets sent_table = TRUE unless it is
21817dd7cddfSDavid du Colombieralready TRUE.  (In normal usage, this prevents outputting the same table
21827dd7cddfSDavid du Colombierdefinition multiple times, as would otherwise occur because the chroma
21837dd7cddfSDavid du Colombiercomponents typically share tables.)  Thus, setting this field to TRUE before
21847dd7cddfSDavid du Colombiercalling jpeg_start_compress() will prevent the table from being written at
21857dd7cddfSDavid du Colombierall.
21867dd7cddfSDavid du Colombier
21877dd7cddfSDavid du ColombierIf you want to create a "pure" abbreviated image file containing no tables,
21887dd7cddfSDavid du Colombierjust call "jpeg_suppress_tables(&cinfo, TRUE)" after constructing all the
21897dd7cddfSDavid du Colombiertables.  If you want to emit some but not all tables, you'll need to set the
21907dd7cddfSDavid du Colombierindividual sent_table fields directly.
21917dd7cddfSDavid du Colombier
21927dd7cddfSDavid du ColombierTo create an abbreviated image, you must also call jpeg_start_compress()
21937dd7cddfSDavid du Colombierwith a second parameter of FALSE, not TRUE.  Otherwise jpeg_start_compress()
21947dd7cddfSDavid du Colombierwill force all the sent_table fields to FALSE.  (This is a safety feature to
21957dd7cddfSDavid du Colombierprevent abbreviated images from being created accidentally.)
21967dd7cddfSDavid du Colombier
21977dd7cddfSDavid du ColombierTo create a tables-only file, perform the same parameter setup that you
21987dd7cddfSDavid du Colombiernormally would, but instead of calling jpeg_start_compress() and so on, call
21997dd7cddfSDavid du Colombierjpeg_write_tables(&cinfo).  This will write an abbreviated datastream
22007dd7cddfSDavid du Colombiercontaining only SOI, DQT and/or DHT markers, and EOI.  All the quantization
22017dd7cddfSDavid du Colombierand Huffman tables that are currently defined in the compression object will
22027dd7cddfSDavid du Colombierbe emitted unless their sent_tables flag is already TRUE, and then all the
22037dd7cddfSDavid du Colombiersent_tables flags will be set TRUE.
22047dd7cddfSDavid du Colombier
22057dd7cddfSDavid du ColombierA sure-fire way to create matching tables-only and abbreviated image files
22067dd7cddfSDavid du Colombieris to proceed as follows:
22077dd7cddfSDavid du Colombier
22087dd7cddfSDavid du Colombier	create JPEG compression object
22097dd7cddfSDavid du Colombier	set JPEG parameters
22107dd7cddfSDavid du Colombier	set destination to tables-only file
22117dd7cddfSDavid du Colombier	jpeg_write_tables(&cinfo);
22127dd7cddfSDavid du Colombier	set destination to image file
22137dd7cddfSDavid du Colombier	jpeg_start_compress(&cinfo, FALSE);
22147dd7cddfSDavid du Colombier	write data...
22157dd7cddfSDavid du Colombier	jpeg_finish_compress(&cinfo);
22167dd7cddfSDavid du Colombier
22177dd7cddfSDavid du ColombierSince the JPEG parameters are not altered between writing the table file and
22187dd7cddfSDavid du Colombierthe abbreviated image file, the same tables are sure to be used.  Of course,
22197dd7cddfSDavid du Colombieryou can repeat the jpeg_start_compress() ... jpeg_finish_compress() sequence
22207dd7cddfSDavid du Colombiermany times to produce many abbreviated image files matching the table file.
22217dd7cddfSDavid du Colombier
22227dd7cddfSDavid du ColombierYou cannot suppress output of the computed Huffman tables when Huffman
22237dd7cddfSDavid du Colombieroptimization is selected.  (If you could, there'd be no way to decode the
22247dd7cddfSDavid du Colombierimage...)  Generally, you don't want to set optimize_coding = TRUE when
22257dd7cddfSDavid du Colombieryou are trying to produce abbreviated files.
22267dd7cddfSDavid du Colombier
22277dd7cddfSDavid du ColombierIn some cases you might want to compress an image using tables which are
22287dd7cddfSDavid du Colombiernot stored in the application, but are defined in an interchange or
22297dd7cddfSDavid du Colombiertables-only file readable by the application.  This can be done by setting up
22307dd7cddfSDavid du Colombiera JPEG decompression object to read the specification file, then copying the
22317dd7cddfSDavid du Colombiertables into your compression object.  See jpeg_copy_critical_parameters()
22327dd7cddfSDavid du Colombierfor an example of copying quantization tables.
22337dd7cddfSDavid du Colombier
22347dd7cddfSDavid du Colombier
22357dd7cddfSDavid du ColombierTo read abbreviated image files, you simply need to load the proper tables
22367dd7cddfSDavid du Colombierinto the decompression object before trying to read the abbreviated image.
22377dd7cddfSDavid du ColombierIf the proper tables are stored in the application program, you can just
2238*593dc095SDavid du Colombierallocate the table structs and fill in their contents directly.  For example,
2239*593dc095SDavid du Colombierto load a fixed quantization table into table slot "n":
2240*593dc095SDavid du Colombier
2241*593dc095SDavid du Colombier    if (cinfo.quant_tbl_ptrs[n] == NULL)
2242*593dc095SDavid du Colombier      cinfo.quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) &cinfo);
2243*593dc095SDavid du Colombier    quant_ptr = cinfo.quant_tbl_ptrs[n];	/* quant_ptr is JQUANT_TBL* */
2244*593dc095SDavid du Colombier    for (i = 0; i < 64; i++) {
2245*593dc095SDavid du Colombier      /* Qtable[] is desired quantization table, in natural array order */
2246*593dc095SDavid du Colombier      quant_ptr->quantval[i] = Qtable[i];
2247*593dc095SDavid du Colombier    }
2248*593dc095SDavid du Colombier
2249*593dc095SDavid du ColombierCode to load a fixed Huffman table is typically (for AC table "n"):
2250*593dc095SDavid du Colombier
2251*593dc095SDavid du Colombier    if (cinfo.ac_huff_tbl_ptrs[n] == NULL)
2252*593dc095SDavid du Colombier      cinfo.ac_huff_tbl_ptrs[n] = jpeg_alloc_huff_table((j_common_ptr) &cinfo);
2253*593dc095SDavid du Colombier    huff_ptr = cinfo.ac_huff_tbl_ptrs[n];	/* huff_ptr is JHUFF_TBL* */
2254*593dc095SDavid du Colombier    for (i = 1; i <= 16; i++) {
2255*593dc095SDavid du Colombier      /* counts[i] is number of Huffman codes of length i bits, i=1..16 */
2256*593dc095SDavid du Colombier      huff_ptr->bits[i] = counts[i];
2257*593dc095SDavid du Colombier    }
2258*593dc095SDavid du Colombier    for (i = 0; i < 256; i++) {
2259*593dc095SDavid du Colombier      /* symbols[] is the list of Huffman symbols, in code-length order */
2260*593dc095SDavid du Colombier      huff_ptr->huffval[i] = symbols[i];
2261*593dc095SDavid du Colombier    }
2262*593dc095SDavid du Colombier
2263*593dc095SDavid du Colombier(Note that trying to set cinfo.quant_tbl_ptrs[n] to point directly at a
2264*593dc095SDavid du Colombierconstant JQUANT_TBL object is not safe.  If the incoming file happened to
2265*593dc095SDavid du Colombiercontain a quantization table definition, your master table would get
2266*593dc095SDavid du Colombieroverwritten!  Instead allocate a working table copy and copy the master table
2267*593dc095SDavid du Colombierinto it, as illustrated above.  Ditto for Huffman tables, of course.)
2268*593dc095SDavid du Colombier
2269*593dc095SDavid du ColombierYou might want to read the tables from a tables-only file, rather than
2270*593dc095SDavid du Colombierhard-wiring them into your application.  The jpeg_read_header() call is
2271*593dc095SDavid du Colombiersufficient to read a tables-only file.  You must pass a second parameter of
2272*593dc095SDavid du ColombierFALSE to indicate that you do not require an image to be present.  Thus, the
2273*593dc095SDavid du Colombiertypical scenario is
22747dd7cddfSDavid du Colombier
22757dd7cddfSDavid du Colombier	create JPEG decompression object
22767dd7cddfSDavid du Colombier	set source to tables-only file
22777dd7cddfSDavid du Colombier	jpeg_read_header(&cinfo, FALSE);
22787dd7cddfSDavid du Colombier	set source to abbreviated image file
22797dd7cddfSDavid du Colombier	jpeg_read_header(&cinfo, TRUE);
22807dd7cddfSDavid du Colombier	set decompression parameters
22817dd7cddfSDavid du Colombier	jpeg_start_decompress(&cinfo);
22827dd7cddfSDavid du Colombier	read data...
22837dd7cddfSDavid du Colombier	jpeg_finish_decompress(&cinfo);
22847dd7cddfSDavid du Colombier
22857dd7cddfSDavid du ColombierIn some cases, you may want to read a file without knowing whether it contains
22867dd7cddfSDavid du Colombieran image or just tables.  In that case, pass FALSE and check the return value
22877dd7cddfSDavid du Colombierfrom jpeg_read_header(): it will be JPEG_HEADER_OK if an image was found,
22887dd7cddfSDavid du ColombierJPEG_HEADER_TABLES_ONLY if only tables were found.  (A third return value,
22897dd7cddfSDavid du ColombierJPEG_SUSPENDED, is possible when using a suspending data source manager.)
22907dd7cddfSDavid du ColombierNote that jpeg_read_header() will not complain if you read an abbreviated
22917dd7cddfSDavid du Colombierimage for which you haven't loaded the missing tables; the missing-table check
22927dd7cddfSDavid du Colombieroccurs later, in jpeg_start_decompress().
22937dd7cddfSDavid du Colombier
22947dd7cddfSDavid du Colombier
22957dd7cddfSDavid du ColombierIt is possible to read a series of images from a single source file by
22967dd7cddfSDavid du Colombierrepeating the jpeg_read_header() ... jpeg_finish_decompress() sequence,
22977dd7cddfSDavid du Colombierwithout releasing/recreating the JPEG object or the data source module.
22987dd7cddfSDavid du Colombier(If you did reinitialize, any partial bufferload left in the data source
22997dd7cddfSDavid du Colombierbuffer at the end of one image would be discarded, causing you to lose the
23007dd7cddfSDavid du Colombierstart of the next image.)  When you use this method, stored tables are
23017dd7cddfSDavid du Colombierautomatically carried forward, so some of the images can be abbreviated images
23027dd7cddfSDavid du Colombierthat depend on tables from earlier images.
23037dd7cddfSDavid du Colombier
23047dd7cddfSDavid du ColombierIf you intend to write a series of images into a single destination file,
23057dd7cddfSDavid du Colombieryou might want to make a specialized data destination module that doesn't
23067dd7cddfSDavid du Colombierflush the output buffer at term_destination() time.  This would speed things
23077dd7cddfSDavid du Colombierup by some trifling amount.  Of course, you'd need to remember to flush the
23087dd7cddfSDavid du Colombierbuffer after the last image.  You can make the later images be abbreviated
23097dd7cddfSDavid du Colombierones by passing FALSE to jpeg_start_compress().
23107dd7cddfSDavid du Colombier
23117dd7cddfSDavid du Colombier
23127dd7cddfSDavid du ColombierSpecial markers
23137dd7cddfSDavid du Colombier---------------
23147dd7cddfSDavid du Colombier
23157dd7cddfSDavid du ColombierSome applications may need to insert or extract special data in the JPEG
23167dd7cddfSDavid du Colombierdatastream.  The JPEG standard provides marker types "COM" (comment) and
23177dd7cddfSDavid du Colombier"APP0" through "APP15" (application) to hold application-specific data.
23187dd7cddfSDavid du ColombierUnfortunately, the use of these markers is not specified by the standard.
23197dd7cddfSDavid du ColombierCOM markers are fairly widely used to hold user-supplied text.  The JFIF file
23207dd7cddfSDavid du Colombierformat spec uses APP0 markers with specified initial strings to hold certain
23217dd7cddfSDavid du Colombierdata.  Adobe applications use APP14 markers beginning with the string "Adobe"
23227dd7cddfSDavid du Colombierfor miscellaneous data.  Other APPn markers are rarely seen, but might
23237dd7cddfSDavid du Colombiercontain almost anything.
23247dd7cddfSDavid du Colombier
23257dd7cddfSDavid du ColombierIf you wish to store user-supplied text, we recommend you use COM markers
23267dd7cddfSDavid du Colombierand place readable 7-bit ASCII text in them.  Newline conventions are not
23277dd7cddfSDavid du Colombierstandardized --- expect to find LF (Unix style), CR/LF (DOS style), or CR
23287dd7cddfSDavid du Colombier(Mac style).  A robust COM reader should be able to cope with random binary
23297dd7cddfSDavid du Colombiergarbage, including nulls, since some applications generate COM markers
23307dd7cddfSDavid du Colombiercontaining non-ASCII junk.  (But yours should not be one of them.)
23317dd7cddfSDavid du Colombier
23327dd7cddfSDavid du ColombierFor program-supplied data, use an APPn marker, and be sure to begin it with an
23337dd7cddfSDavid du Colombieridentifying string so that you can tell whether the marker is actually yours.
23347dd7cddfSDavid du ColombierIt's probably best to avoid using APP0 or APP14 for any private markers.
23357dd7cddfSDavid du Colombier(NOTE: the upcoming SPIFF standard will use APP8 markers; we recommend you
23367dd7cddfSDavid du Colombiernot use APP8 markers for any private purposes, either.)
23377dd7cddfSDavid du Colombier
23387dd7cddfSDavid du ColombierKeep in mind that at most 65533 bytes can be put into one marker, but you
23397dd7cddfSDavid du Colombiercan have as many markers as you like.
23407dd7cddfSDavid du Colombier
23417dd7cddfSDavid du ColombierBy default, the IJG compression library will write a JFIF APP0 marker if the
23427dd7cddfSDavid du Colombierselected JPEG colorspace is grayscale or YCbCr, or an Adobe APP14 marker if
23437dd7cddfSDavid du Colombierthe selected colorspace is RGB, CMYK, or YCCK.  You can disable this, but
23447dd7cddfSDavid du Colombierwe don't recommend it.  The decompression library will recognize JFIF and
23457dd7cddfSDavid du ColombierAdobe markers and will set the JPEG colorspace properly when one is found.
23467dd7cddfSDavid du Colombier
2347*593dc095SDavid du Colombier
23487dd7cddfSDavid du ColombierYou can write special markers immediately following the datastream header by
23497dd7cddfSDavid du Colombiercalling jpeg_write_marker() after jpeg_start_compress() and before the first
23507dd7cddfSDavid du Colombiercall to jpeg_write_scanlines().  When you do this, the markers appear after
23517dd7cddfSDavid du Colombierthe SOI and the JFIF APP0 and Adobe APP14 markers (if written), but before
23527dd7cddfSDavid du Colombierall else.  Specify the marker type parameter as "JPEG_COM" for COM or
23537dd7cddfSDavid du Colombier"JPEG_APP0 + n" for APPn.  (Actually, jpeg_write_marker will let you write
23547dd7cddfSDavid du Colombierany marker type, but we don't recommend writing any other kinds of marker.)
23557dd7cddfSDavid du ColombierFor example, to write a user comment string pointed to by comment_text:
23567dd7cddfSDavid du Colombier	jpeg_write_marker(cinfo, JPEG_COM, comment_text, strlen(comment_text));
23577dd7cddfSDavid du Colombier
2358*593dc095SDavid du ColombierIf it's not convenient to store all the marker data in memory at once,
2359*593dc095SDavid du Colombieryou can instead call jpeg_write_m_header() followed by multiple calls to
2360*593dc095SDavid du Colombierjpeg_write_m_byte().  If you do it this way, it's your responsibility to
2361*593dc095SDavid du Colombiercall jpeg_write_m_byte() exactly the number of times given in the length
2362*593dc095SDavid du Colombierparameter to jpeg_write_m_header().  (This method lets you empty the
2363*593dc095SDavid du Colombieroutput buffer partway through a marker, which might be important when
2364*593dc095SDavid du Colombierusing a suspending data destination module.  In any case, if you are using
2365*593dc095SDavid du Colombiera suspending destination, you should flush its buffer after inserting
2366*593dc095SDavid du Colombierany special markers.  See "I/O suspension".)
23677dd7cddfSDavid du Colombier
2368*593dc095SDavid du ColombierOr, if you prefer to synthesize the marker byte sequence yourself,
2369*593dc095SDavid du Colombieryou can just cram it straight into the data destination module.
2370*593dc095SDavid du Colombier
2371*593dc095SDavid du ColombierIf you are writing JFIF 1.02 extension markers (thumbnail images), don't
2372*593dc095SDavid du Colombierforget to set cinfo.JFIF_minor_version = 2 so that the encoder will write the
2373*593dc095SDavid du Colombiercorrect JFIF version number in the JFIF header marker.  The library's default
2374*593dc095SDavid du Colombieris to write version 1.01, but that's wrong if you insert any 1.02 extension
2375*593dc095SDavid du Colombiermarkers.  (We could probably get away with just defaulting to 1.02, but there
2376*593dc095SDavid du Colombierused to be broken decoders that would complain about unknown minor version
2377*593dc095SDavid du Colombiernumbers.  To reduce compatibility risks it's safest not to write 1.02 unless
2378*593dc095SDavid du Colombieryou are actually using 1.02 extensions.)
2379*593dc095SDavid du Colombier
2380*593dc095SDavid du Colombier
2381*593dc095SDavid du ColombierWhen reading, two methods of handling special markers are available:
2382*593dc095SDavid du Colombier1. You can ask the library to save the contents of COM and/or APPn markers
2383*593dc095SDavid du Colombierinto memory, and then examine them at your leisure afterwards.
2384*593dc095SDavid du Colombier2. You can supply your own routine to process COM and/or APPn markers
2385*593dc095SDavid du Colombieron-the-fly as they are read.
2386*593dc095SDavid du ColombierThe first method is simpler to use, especially if you are using a suspending
2387*593dc095SDavid du Colombierdata source; writing a marker processor that copes with input suspension is
2388*593dc095SDavid du Colombiernot easy (consider what happens if the marker is longer than your available
2389*593dc095SDavid du Colombierinput buffer).  However, the second method conserves memory since the marker
2390*593dc095SDavid du Colombierdata need not be kept around after it's been processed.
2391*593dc095SDavid du Colombier
2392*593dc095SDavid du ColombierFor either method, you'd normally set up marker handling after creating a
2393*593dc095SDavid du Colombierdecompression object and before calling jpeg_read_header(), because the
2394*593dc095SDavid du Colombiermarkers of interest will typically be near the head of the file and so will
2395*593dc095SDavid du Colombierbe scanned by jpeg_read_header.  Once you've established a marker handling
2396*593dc095SDavid du Colombiermethod, it will be used for the life of that decompression object
2397*593dc095SDavid du Colombier(potentially many datastreams), unless you change it.  Marker handling is
2398*593dc095SDavid du Colombierdetermined separately for COM markers and for each APPn marker code.
2399*593dc095SDavid du Colombier
2400*593dc095SDavid du Colombier
2401*593dc095SDavid du ColombierTo save the contents of special markers in memory, call
2402*593dc095SDavid du Colombier	jpeg_save_markers(cinfo, marker_code, length_limit)
2403*593dc095SDavid du Colombierwhere marker_code is the marker type to save, JPEG_COM or JPEG_APP0+n.
2404*593dc095SDavid du Colombier(To arrange to save all the special marker types, you need to call this
2405*593dc095SDavid du Colombierroutine 17 times, for COM and APP0-APP15.)  If the incoming marker is longer
2406*593dc095SDavid du Colombierthan length_limit data bytes, only length_limit bytes will be saved; this
2407*593dc095SDavid du Colombierparameter allows you to avoid chewing up memory when you only need to see the
2408*593dc095SDavid du Colombierfirst few bytes of a potentially large marker.  If you want to save all the
2409*593dc095SDavid du Colombierdata, set length_limit to 0xFFFF; that is enough since marker lengths are only
2410*593dc095SDavid du Colombier16 bits.  As a special case, setting length_limit to 0 prevents that marker
2411*593dc095SDavid du Colombiertype from being saved at all.  (That is the default behavior, in fact.)
2412*593dc095SDavid du Colombier
2413*593dc095SDavid du ColombierAfter jpeg_read_header() completes, you can examine the special markers by
2414*593dc095SDavid du Colombierfollowing the cinfo->marker_list pointer chain.  All the special markers in
2415*593dc095SDavid du Colombierthe file appear in this list, in order of their occurrence in the file (but
2416*593dc095SDavid du Colombieromitting any markers of types you didn't ask for).  Both the original data
2417*593dc095SDavid du Colombierlength and the saved data length are recorded for each list entry; the latter
2418*593dc095SDavid du Colombierwill not exceed length_limit for the particular marker type.  Note that these
2419*593dc095SDavid du Colombierlengths exclude the marker length word, whereas the stored representation
2420*593dc095SDavid du Colombierwithin the JPEG file includes it.  (Hence the maximum data length is really
2421*593dc095SDavid du Colombieronly 65533.)
2422*593dc095SDavid du Colombier
2423*593dc095SDavid du ColombierIt is possible that additional special markers appear in the file beyond the
2424*593dc095SDavid du ColombierSOS marker at which jpeg_read_header stops; if so, the marker list will be
2425*593dc095SDavid du Colombierextended during reading of the rest of the file.  This is not expected to be
2426*593dc095SDavid du Colombiercommon, however.  If you are short on memory you may want to reset the length
2427*593dc095SDavid du Colombierlimit to zero for all marker types after finishing jpeg_read_header, to
2428*593dc095SDavid du Colombierensure that the max_memory_to_use setting cannot be exceeded due to addition
2429*593dc095SDavid du Colombierof later markers.
2430*593dc095SDavid du Colombier
2431*593dc095SDavid du ColombierThe marker list remains stored until you call jpeg_finish_decompress or
2432*593dc095SDavid du Colombierjpeg_abort, at which point the memory is freed and the list is set to empty.
2433*593dc095SDavid du Colombier(jpeg_destroy also releases the storage, of course.)
2434*593dc095SDavid du Colombier
2435*593dc095SDavid du ColombierNote that the library is internally interested in APP0 and APP14 markers;
2436*593dc095SDavid du Colombierif you try to set a small nonzero length limit on these types, the library
2437*593dc095SDavid du Colombierwill silently force the length up to the minimum it wants.  (But you can set
2438*593dc095SDavid du Colombiera zero length limit to prevent them from being saved at all.)  Also, in a
2439*593dc095SDavid du Colombier16-bit environment, the maximum length limit may be constrained to less than
2440*593dc095SDavid du Colombier65533 by malloc() limitations.  It is therefore best not to assume that the
2441*593dc095SDavid du Colombiereffective length limit is exactly what you set it to be.
2442*593dc095SDavid du Colombier
2443*593dc095SDavid du Colombier
2444*593dc095SDavid du ColombierIf you want to supply your own marker-reading routine, you do it by calling
2445*593dc095SDavid du Colombierjpeg_set_marker_processor().  A marker processor routine must have the
2446*593dc095SDavid du Colombiersignature
24477dd7cddfSDavid du Colombier	boolean jpeg_marker_parser_method (j_decompress_ptr cinfo)
24487dd7cddfSDavid du ColombierAlthough the marker code is not explicitly passed, the routine can find it
24497dd7cddfSDavid du Colombierin cinfo->unread_marker.  At the time of call, the marker proper has been
24507dd7cddfSDavid du Colombierread from the data source module.  The processor routine is responsible for
24517dd7cddfSDavid du Colombierreading the marker length word and the remaining parameter bytes, if any.
24527dd7cddfSDavid du ColombierReturn TRUE to indicate success.  (FALSE should be returned only if you are
24537dd7cddfSDavid du Colombierusing a suspending data source and it tells you to suspend.  See the standard
24547dd7cddfSDavid du Colombiermarker processors in jdmarker.c for appropriate coding methods if you need to
24557dd7cddfSDavid du Colombieruse a suspending data source.)
24567dd7cddfSDavid du Colombier
24577dd7cddfSDavid du ColombierIf you override the default APP0 or APP14 processors, it is up to you to
24587dd7cddfSDavid du Colombierrecognize JFIF and Adobe markers if you want colorspace recognition to occur
24597dd7cddfSDavid du Colombierproperly.  We recommend copying and extending the default processors if you
2460*593dc095SDavid du Colombierwant to do that.  (A better idea is to save these marker types for later
2461*593dc095SDavid du Colombierexamination by calling jpeg_save_markers(); that method doesn't interfere
2462*593dc095SDavid du Colombierwith the library's own processing of these markers.)
2463*593dc095SDavid du Colombier
2464*593dc095SDavid du Colombierjpeg_set_marker_processor() and jpeg_save_markers() are mutually exclusive
2465*593dc095SDavid du Colombier--- if you call one it overrides any previous call to the other, for the
2466*593dc095SDavid du Colombierparticular marker type specified.
24677dd7cddfSDavid du Colombier
24687dd7cddfSDavid du ColombierA simple example of an external COM processor can be found in djpeg.c.
2469*593dc095SDavid du ColombierAlso, see jpegtran.c for an example of using jpeg_save_markers.
24707dd7cddfSDavid du Colombier
24717dd7cddfSDavid du Colombier
24727dd7cddfSDavid du ColombierRaw (downsampled) image data
24737dd7cddfSDavid du Colombier----------------------------
24747dd7cddfSDavid du Colombier
24757dd7cddfSDavid du ColombierSome applications need to supply already-downsampled image data to the JPEG
24767dd7cddfSDavid du Colombiercompressor, or to receive raw downsampled data from the decompressor.  The
24777dd7cddfSDavid du Colombierlibrary supports this requirement by allowing the application to write or
24787dd7cddfSDavid du Colombierread raw data, bypassing the normal preprocessing or postprocessing steps.
24797dd7cddfSDavid du ColombierThe interface is different from the standard one and is somewhat harder to
24807dd7cddfSDavid du Colombieruse.  If your interest is merely in bypassing color conversion, we recommend
24817dd7cddfSDavid du Colombierthat you use the standard interface and simply set jpeg_color_space =
24827dd7cddfSDavid du Colombierin_color_space (or jpeg_color_space = out_color_space for decompression).
24837dd7cddfSDavid du ColombierThe mechanism described in this section is necessary only to supply or
24847dd7cddfSDavid du Colombierreceive downsampled image data, in which not all components have the same
24857dd7cddfSDavid du Colombierdimensions.
24867dd7cddfSDavid du Colombier
24877dd7cddfSDavid du Colombier
24887dd7cddfSDavid du ColombierTo compress raw data, you must supply the data in the colorspace to be used
24897dd7cddfSDavid du Colombierin the JPEG file (please read the earlier section on Special color spaces)
24907dd7cddfSDavid du Colombierand downsampled to the sampling factors specified in the JPEG parameters.
24917dd7cddfSDavid du ColombierYou must supply the data in the format used internally by the JPEG library,
24927dd7cddfSDavid du Colombiernamely a JSAMPIMAGE array.  This is an array of pointers to two-dimensional
24937dd7cddfSDavid du Colombierarrays, each of type JSAMPARRAY.  Each 2-D array holds the values for one
24947dd7cddfSDavid du Colombiercolor component.  This structure is necessary since the components are of
24957dd7cddfSDavid du Colombierdifferent sizes.  If the image dimensions are not a multiple of the MCU size,
24967dd7cddfSDavid du Colombieryou must also pad the data correctly (usually, this is done by replicating
24977dd7cddfSDavid du Colombierthe last column and/or row).  The data must be padded to a multiple of a DCT
24987dd7cddfSDavid du Colombierblock in each component: that is, each downsampled row must contain a
24997dd7cddfSDavid du Colombiermultiple of 8 valid samples, and there must be a multiple of 8 sample rows
25007dd7cddfSDavid du Colombierfor each component.  (For applications such as conversion of digital TV
25017dd7cddfSDavid du Colombierimages, the standard image size is usually a multiple of the DCT block size,
25027dd7cddfSDavid du Colombierso that no padding need actually be done.)
25037dd7cddfSDavid du Colombier
25047dd7cddfSDavid du ColombierThe procedure for compression of raw data is basically the same as normal
25057dd7cddfSDavid du Colombiercompression, except that you call jpeg_write_raw_data() in place of
25067dd7cddfSDavid du Colombierjpeg_write_scanlines().  Before calling jpeg_start_compress(), you must do
25077dd7cddfSDavid du Colombierthe following:
25087dd7cddfSDavid du Colombier  * Set cinfo->raw_data_in to TRUE.  (It is set FALSE by jpeg_set_defaults().)
25097dd7cddfSDavid du Colombier    This notifies the library that you will be supplying raw data.
25107dd7cddfSDavid du Colombier  * Ensure jpeg_color_space is correct --- an explicit jpeg_set_colorspace()
25117dd7cddfSDavid du Colombier    call is a good idea.  Note that since color conversion is bypassed,
25127dd7cddfSDavid du Colombier    in_color_space is ignored, except that jpeg_set_defaults() uses it to
25137dd7cddfSDavid du Colombier    choose the default jpeg_color_space setting.
25147dd7cddfSDavid du Colombier  * Ensure the sampling factors, cinfo->comp_info[i].h_samp_factor and
25157dd7cddfSDavid du Colombier    cinfo->comp_info[i].v_samp_factor, are correct.  Since these indicate the
25167dd7cddfSDavid du Colombier    dimensions of the data you are supplying, it's wise to set them
25177dd7cddfSDavid du Colombier    explicitly, rather than assuming the library's defaults are what you want.
25187dd7cddfSDavid du Colombier
25197dd7cddfSDavid du ColombierTo pass raw data to the library, call jpeg_write_raw_data() in place of
25207dd7cddfSDavid du Colombierjpeg_write_scanlines().  The two routines work similarly except that
25217dd7cddfSDavid du Colombierjpeg_write_raw_data takes a JSAMPIMAGE data array rather than JSAMPARRAY.
25227dd7cddfSDavid du ColombierThe scanlines count passed to and returned from jpeg_write_raw_data is
25237dd7cddfSDavid du Colombiermeasured in terms of the component with the largest v_samp_factor.
25247dd7cddfSDavid du Colombier
25257dd7cddfSDavid du Colombierjpeg_write_raw_data() processes one MCU row per call, which is to say
25267dd7cddfSDavid du Colombierv_samp_factor*DCTSIZE sample rows of each component.  The passed num_lines
25277dd7cddfSDavid du Colombiervalue must be at least max_v_samp_factor*DCTSIZE, and the return value will
25287dd7cddfSDavid du Colombierbe exactly that amount (or possibly some multiple of that amount, in future
25297dd7cddfSDavid du Colombierlibrary versions).  This is true even on the last call at the bottom of the
25307dd7cddfSDavid du Colombierimage; don't forget to pad your data as necessary.
25317dd7cddfSDavid du Colombier
25327dd7cddfSDavid du ColombierThe required dimensions of the supplied data can be computed for each
25337dd7cddfSDavid du Colombiercomponent as
25347dd7cddfSDavid du Colombier	cinfo->comp_info[i].width_in_blocks*DCTSIZE  samples per row
25357dd7cddfSDavid du Colombier	cinfo->comp_info[i].height_in_blocks*DCTSIZE rows in image
25367dd7cddfSDavid du Colombierafter jpeg_start_compress() has initialized those fields.  If the valid data
25377dd7cddfSDavid du Colombieris smaller than this, it must be padded appropriately.  For some sampling
25387dd7cddfSDavid du Colombierfactors and image sizes, additional dummy DCT blocks are inserted to make
25397dd7cddfSDavid du Colombierthe image a multiple of the MCU dimensions.  The library creates such dummy
25407dd7cddfSDavid du Colombierblocks itself; it does not read them from your supplied data.  Therefore you
25417dd7cddfSDavid du Colombierneed never pad by more than DCTSIZE samples.  An example may help here.
25427dd7cddfSDavid du ColombierAssume 2h2v downsampling of YCbCr data, that is
25437dd7cddfSDavid du Colombier	cinfo->comp_info[0].h_samp_factor = 2		for Y
25447dd7cddfSDavid du Colombier	cinfo->comp_info[0].v_samp_factor = 2
25457dd7cddfSDavid du Colombier	cinfo->comp_info[1].h_samp_factor = 1		for Cb
25467dd7cddfSDavid du Colombier	cinfo->comp_info[1].v_samp_factor = 1
25477dd7cddfSDavid du Colombier	cinfo->comp_info[2].h_samp_factor = 1		for Cr
25487dd7cddfSDavid du Colombier	cinfo->comp_info[2].v_samp_factor = 1
25497dd7cddfSDavid du Colombierand suppose that the nominal image dimensions (cinfo->image_width and
25507dd7cddfSDavid du Colombiercinfo->image_height) are 101x101 pixels.  Then jpeg_start_compress() will
25517dd7cddfSDavid du Colombiercompute downsampled_width = 101 and width_in_blocks = 13 for Y,
25527dd7cddfSDavid du Colombierdownsampled_width = 51 and width_in_blocks = 7 for Cb and Cr (and the same
25537dd7cddfSDavid du Colombierfor the height fields).  You must pad the Y data to at least 13*8 = 104
25547dd7cddfSDavid du Colombiercolumns and rows, the Cb/Cr data to at least 7*8 = 56 columns and rows.  The
25557dd7cddfSDavid du ColombierMCU height is max_v_samp_factor = 2 DCT rows so you must pass at least 16
25567dd7cddfSDavid du Colombierscanlines on each call to jpeg_write_raw_data(), which is to say 16 actual
25577dd7cddfSDavid du Colombiersample rows of Y and 8 each of Cb and Cr.  A total of 7 MCU rows are needed,
25587dd7cddfSDavid du Colombierso you must pass a total of 7*16 = 112 "scanlines".  The last DCT block row
25597dd7cddfSDavid du Colombierof Y data is dummy, so it doesn't matter what you pass for it in the data
25607dd7cddfSDavid du Colombierarrays, but the scanlines count must total up to 112 so that all of the Cb
25617dd7cddfSDavid du Colombierand Cr data gets passed.
25627dd7cddfSDavid du Colombier
25637dd7cddfSDavid du ColombierOutput suspension is supported with raw-data compression: if the data
25647dd7cddfSDavid du Colombierdestination module suspends, jpeg_write_raw_data() will return 0.
25657dd7cddfSDavid du ColombierIn this case the same data rows must be passed again on the next call.
25667dd7cddfSDavid du Colombier
25677dd7cddfSDavid du Colombier
25687dd7cddfSDavid du ColombierDecompression with raw data output implies bypassing all postprocessing:
25697dd7cddfSDavid du Colombieryou cannot ask for rescaling or color quantization, for instance.  More
25707dd7cddfSDavid du Colombierseriously, you must deal with the color space and sampling factors present in
25717dd7cddfSDavid du Colombierthe incoming file.  If your application only handles, say, 2h1v YCbCr data,
25727dd7cddfSDavid du Colombieryou must check for and fail on other color spaces or other sampling factors.
25737dd7cddfSDavid du ColombierThe library will not convert to a different color space for you.
25747dd7cddfSDavid du Colombier
25757dd7cddfSDavid du ColombierTo obtain raw data output, set cinfo->raw_data_out = TRUE before
25767dd7cddfSDavid du Colombierjpeg_start_decompress() (it is set FALSE by jpeg_read_header()).  Be sure to
25777dd7cddfSDavid du Colombierverify that the color space and sampling factors are ones you can handle.
25787dd7cddfSDavid du ColombierThen call jpeg_read_raw_data() in place of jpeg_read_scanlines().  The
25797dd7cddfSDavid du Colombierdecompression process is otherwise the same as usual.
25807dd7cddfSDavid du Colombier
25817dd7cddfSDavid du Colombierjpeg_read_raw_data() returns one MCU row per call, and thus you must pass a
25827dd7cddfSDavid du Colombierbuffer of at least max_v_samp_factor*DCTSIZE scanlines (scanline counting is
25837dd7cddfSDavid du Colombierthe same as for raw-data compression).  The buffer you pass must be large
25847dd7cddfSDavid du Colombierenough to hold the actual data plus padding to DCT-block boundaries.  As with
25857dd7cddfSDavid du Colombiercompression, any entirely dummy DCT blocks are not processed so you need not
25867dd7cddfSDavid du Colombierallocate space for them, but the total scanline count includes them.  The
25877dd7cddfSDavid du Colombierabove example of computing buffer dimensions for raw-data compression is
25887dd7cddfSDavid du Colombierequally valid for decompression.
25897dd7cddfSDavid du Colombier
25907dd7cddfSDavid du ColombierInput suspension is supported with raw-data decompression: if the data source
25917dd7cddfSDavid du Colombiermodule suspends, jpeg_read_raw_data() will return 0.  You can also use
25927dd7cddfSDavid du Colombierbuffered-image mode to read raw data in multiple passes.
25937dd7cddfSDavid du Colombier
25947dd7cddfSDavid du Colombier
25957dd7cddfSDavid du ColombierReally raw data: DCT coefficients
25967dd7cddfSDavid du Colombier---------------------------------
25977dd7cddfSDavid du Colombier
25987dd7cddfSDavid du ColombierIt is possible to read or write the contents of a JPEG file as raw DCT
25997dd7cddfSDavid du Colombiercoefficients.  This facility is mainly intended for use in lossless
26007dd7cddfSDavid du Colombiertranscoding between different JPEG file formats.  Other possible applications
26017dd7cddfSDavid du Colombierinclude lossless cropping of a JPEG image, lossless reassembly of a
26027dd7cddfSDavid du Colombiermulti-strip or multi-tile TIFF/JPEG file into a single JPEG datastream, etc.
26037dd7cddfSDavid du Colombier
26047dd7cddfSDavid du ColombierTo read the contents of a JPEG file as DCT coefficients, open the file and do
26057dd7cddfSDavid du Colombierjpeg_read_header() as usual.  But instead of calling jpeg_start_decompress()
26067dd7cddfSDavid du Colombierand jpeg_read_scanlines(), call jpeg_read_coefficients().  This will read the
26077dd7cddfSDavid du Colombierentire image into a set of virtual coefficient-block arrays, one array per
26087dd7cddfSDavid du Colombiercomponent.  The return value is a pointer to an array of virtual-array
26097dd7cddfSDavid du Colombierdescriptors.  Each virtual array can be accessed directly using the JPEG
26107dd7cddfSDavid du Colombiermemory manager's access_virt_barray method (see Memory management, below,
26117dd7cddfSDavid du Colombierand also read structure.doc's discussion of virtual array handling).  Or,
26127dd7cddfSDavid du Colombierfor simple transcoding to a different JPEG file format, the array list can
26137dd7cddfSDavid du Colombierjust be handed directly to jpeg_write_coefficients().
26147dd7cddfSDavid du Colombier
2615*593dc095SDavid du ColombierEach block in the block arrays contains quantized coefficient values in
2616*593dc095SDavid du Colombiernormal array order (not JPEG zigzag order).  The block arrays contain only
2617*593dc095SDavid du ColombierDCT blocks containing real data; any entirely-dummy blocks added to fill out
2618*593dc095SDavid du Colombierinterleaved MCUs at the right or bottom edges of the image are discarded
2619*593dc095SDavid du Colombierduring reading and are not stored in the block arrays.  (The size of each
2620*593dc095SDavid du Colombierblock array can be determined from the width_in_blocks and height_in_blocks
2621*593dc095SDavid du Colombierfields of the component's comp_info entry.)  This is also the data format
2622*593dc095SDavid du Colombierexpected by jpeg_write_coefficients().
2623*593dc095SDavid du Colombier
26247dd7cddfSDavid du ColombierWhen you are done using the virtual arrays, call jpeg_finish_decompress()
26257dd7cddfSDavid du Colombierto release the array storage and return the decompression object to an idle
26267dd7cddfSDavid du Colombierstate; or just call jpeg_destroy() if you don't need to reuse the object.
26277dd7cddfSDavid du Colombier
26287dd7cddfSDavid du ColombierIf you use a suspending data source, jpeg_read_coefficients() will return
26297dd7cddfSDavid du ColombierNULL if it is forced to suspend; a non-NULL return value indicates successful
26307dd7cddfSDavid du Colombiercompletion.  You need not test for a NULL return value when using a
26317dd7cddfSDavid du Colombiernon-suspending data source.
26327dd7cddfSDavid du Colombier
2633*593dc095SDavid du ColombierIt is also possible to call jpeg_read_coefficients() to obtain access to the
2634*593dc095SDavid du Colombierdecoder's coefficient arrays during a normal decode cycle in buffered-image
2635*593dc095SDavid du Colombiermode.  This frammish might be useful for progressively displaying an incoming
2636*593dc095SDavid du Colombierimage and then re-encoding it without loss.  To do this, decode in buffered-
2637*593dc095SDavid du Colombierimage mode as discussed previously, then call jpeg_read_coefficients() after
2638*593dc095SDavid du Colombierthe last jpeg_finish_output() call.  The arrays will be available for your use
2639*593dc095SDavid du Colombieruntil you call jpeg_finish_decompress().
2640*593dc095SDavid du Colombier
26417dd7cddfSDavid du Colombier
26427dd7cddfSDavid du ColombierTo write the contents of a JPEG file as DCT coefficients, you must provide
26437dd7cddfSDavid du Colombierthe DCT coefficients stored in virtual block arrays.  You can either pass
26447dd7cddfSDavid du Colombierblock arrays read from an input JPEG file by jpeg_read_coefficients(), or
26457dd7cddfSDavid du Colombierallocate virtual arrays from the JPEG compression object and fill them
26467dd7cddfSDavid du Colombieryourself.  In either case, jpeg_write_coefficients() is substituted for
26477dd7cddfSDavid du Colombierjpeg_start_compress() and jpeg_write_scanlines().  Thus the sequence is
26487dd7cddfSDavid du Colombier  * Create compression object
26497dd7cddfSDavid du Colombier  * Set all compression parameters as necessary
26507dd7cddfSDavid du Colombier  * Request virtual arrays if needed
26517dd7cddfSDavid du Colombier  * jpeg_write_coefficients()
26527dd7cddfSDavid du Colombier  * jpeg_finish_compress()
26537dd7cddfSDavid du Colombier  * Destroy or re-use compression object
26547dd7cddfSDavid du Colombierjpeg_write_coefficients() is passed a pointer to an array of virtual block
26557dd7cddfSDavid du Colombierarray descriptors; the number of arrays is equal to cinfo.num_components.
26567dd7cddfSDavid du Colombier
26577dd7cddfSDavid du ColombierThe virtual arrays need only have been requested, not realized, before
26587dd7cddfSDavid du Colombierjpeg_write_coefficients() is called.  A side-effect of
26597dd7cddfSDavid du Colombierjpeg_write_coefficients() is to realize any virtual arrays that have been
26607dd7cddfSDavid du Colombierrequested from the compression object's memory manager.  Thus, when obtaining
26617dd7cddfSDavid du Colombierthe virtual arrays from the compression object, you should fill the arrays
26627dd7cddfSDavid du Colombierafter calling jpeg_write_coefficients().  The data is actually written out
26637dd7cddfSDavid du Colombierwhen you call jpeg_finish_compress(); jpeg_write_coefficients() only writes
26647dd7cddfSDavid du Colombierthe file header.
26657dd7cddfSDavid du Colombier
26667dd7cddfSDavid du ColombierWhen writing raw DCT coefficients, it is crucial that the JPEG quantization
26677dd7cddfSDavid du Colombiertables and sampling factors match the way the data was encoded, or the
26687dd7cddfSDavid du Colombierresulting file will be invalid.  For transcoding from an existing JPEG file,
26697dd7cddfSDavid du Colombierwe recommend using jpeg_copy_critical_parameters().  This routine initializes
26707dd7cddfSDavid du Colombierall the compression parameters to default values (like jpeg_set_defaults()),
26717dd7cddfSDavid du Colombierthen copies the critical information from a source decompression object.
26727dd7cddfSDavid du ColombierThe decompression object should have just been used to read the entire
26737dd7cddfSDavid du ColombierJPEG input file --- that is, it should be awaiting jpeg_finish_decompress().
26747dd7cddfSDavid du Colombier
26757dd7cddfSDavid du Colombierjpeg_write_coefficients() marks all tables stored in the compression object
26767dd7cddfSDavid du Colombieras needing to be written to the output file (thus, it acts like
26777dd7cddfSDavid du Colombierjpeg_start_compress(cinfo, TRUE)).  This is for safety's sake, to avoid
26787dd7cddfSDavid du Colombieremitting abbreviated JPEG files by accident.  If you really want to emit an
26797dd7cddfSDavid du Colombierabbreviated JPEG file, call jpeg_suppress_tables(), or set the tables'
26807dd7cddfSDavid du Colombierindividual sent_table flags, between calling jpeg_write_coefficients() and
26817dd7cddfSDavid du Colombierjpeg_finish_compress().
26827dd7cddfSDavid du Colombier
26837dd7cddfSDavid du Colombier
26847dd7cddfSDavid du ColombierProgress monitoring
26857dd7cddfSDavid du Colombier-------------------
26867dd7cddfSDavid du Colombier
26877dd7cddfSDavid du ColombierSome applications may need to regain control from the JPEG library every so
26887dd7cddfSDavid du Colombieroften.  The typical use of this feature is to produce a percent-done bar or
26897dd7cddfSDavid du Colombierother progress display.  (For a simple example, see cjpeg.c or djpeg.c.)
26907dd7cddfSDavid du ColombierAlthough you do get control back frequently during the data-transferring pass
26917dd7cddfSDavid du Colombier(the jpeg_read_scanlines or jpeg_write_scanlines loop), any additional passes
26927dd7cddfSDavid du Colombierwill occur inside jpeg_finish_compress or jpeg_start_decompress; those
26937dd7cddfSDavid du Colombierroutines may take a long time to execute, and you don't get control back
26947dd7cddfSDavid du Colombieruntil they are done.
26957dd7cddfSDavid du Colombier
26967dd7cddfSDavid du ColombierYou can define a progress-monitor routine which will be called periodically
26977dd7cddfSDavid du Colombierby the library.  No guarantees are made about how often this call will occur,
26987dd7cddfSDavid du Colombierso we don't recommend you use it for mouse tracking or anything like that.
26997dd7cddfSDavid du ColombierAt present, a call will occur once per MCU row, scanline, or sample row
27007dd7cddfSDavid du Colombiergroup, whichever unit is convenient for the current processing mode; so the
27017dd7cddfSDavid du Colombierwider the image, the longer the time between calls.  During the data
27027dd7cddfSDavid du Colombiertransferring pass, only one call occurs per call of jpeg_read_scanlines or
27037dd7cddfSDavid du Colombierjpeg_write_scanlines, so don't pass a large number of scanlines at once if
27047dd7cddfSDavid du Colombieryou want fine resolution in the progress count.  (If you really need to use
27057dd7cddfSDavid du Colombierthe callback mechanism for time-critical tasks like mouse tracking, you could
27067dd7cddfSDavid du Colombierinsert additional calls inside some of the library's inner loops.)
27077dd7cddfSDavid du Colombier
27087dd7cddfSDavid du ColombierTo establish a progress-monitor callback, create a struct jpeg_progress_mgr,
27097dd7cddfSDavid du Colombierfill in its progress_monitor field with a pointer to your callback routine,
27107dd7cddfSDavid du Colombierand set cinfo->progress to point to the struct.  The callback will be called
27117dd7cddfSDavid du Colombierwhenever cinfo->progress is non-NULL.  (This pointer is set to NULL by
27127dd7cddfSDavid du Colombierjpeg_create_compress or jpeg_create_decompress; the library will not change
27137dd7cddfSDavid du Colombierit thereafter.  So if you allocate dynamic storage for the progress struct,
27147dd7cddfSDavid du Colombiermake sure it will live as long as the JPEG object does.  Allocating from the
27157dd7cddfSDavid du ColombierJPEG memory manager with lifetime JPOOL_PERMANENT will work nicely.)  You
27167dd7cddfSDavid du Colombiercan use the same callback routine for both compression and decompression.
27177dd7cddfSDavid du Colombier
27187dd7cddfSDavid du ColombierThe jpeg_progress_mgr struct contains four fields which are set by the library:
27197dd7cddfSDavid du Colombier	long pass_counter;	/* work units completed in this pass */
27207dd7cddfSDavid du Colombier	long pass_limit;	/* total number of work units in this pass */
27217dd7cddfSDavid du Colombier	int completed_passes;	/* passes completed so far */
27227dd7cddfSDavid du Colombier	int total_passes;	/* total number of passes expected */
27237dd7cddfSDavid du ColombierDuring any one pass, pass_counter increases from 0 up to (not including)
27247dd7cddfSDavid du Colombierpass_limit; the step size is usually but not necessarily 1.  The pass_limit
27257dd7cddfSDavid du Colombiervalue may change from one pass to another.  The expected total number of
27267dd7cddfSDavid du Colombierpasses is in total_passes, and the number of passes already completed is in
27277dd7cddfSDavid du Colombiercompleted_passes.  Thus the fraction of work completed may be estimated as
27287dd7cddfSDavid du Colombier		completed_passes + (pass_counter/pass_limit)
27297dd7cddfSDavid du Colombier		--------------------------------------------
27307dd7cddfSDavid du Colombier				total_passes
27317dd7cddfSDavid du Colombierignoring the fact that the passes may not be equal amounts of work.
27327dd7cddfSDavid du Colombier
27337dd7cddfSDavid du ColombierWhen decompressing, pass_limit can even change within a pass, because it
27347dd7cddfSDavid du Colombierdepends on the number of scans in the JPEG file, which isn't always known in
27357dd7cddfSDavid du Colombieradvance.  The computed fraction-of-work-done may jump suddenly (if the library
27367dd7cddfSDavid du Colombierdiscovers it has overestimated the number of scans) or even decrease (in the
27377dd7cddfSDavid du Colombieropposite case).  It is not wise to put great faith in the work estimate.
27387dd7cddfSDavid du Colombier
27397dd7cddfSDavid du ColombierWhen using the decompressor's buffered-image mode, the progress monitor work
27407dd7cddfSDavid du Colombierestimate is likely to be completely unhelpful, because the library has no way
27417dd7cddfSDavid du Colombierto know how many output passes will be demanded of it.  Currently, the library
27427dd7cddfSDavid du Colombiersets total_passes based on the assumption that there will be one more output
27437dd7cddfSDavid du Colombierpass if the input file end hasn't yet been read (jpeg_input_complete() isn't
27447dd7cddfSDavid du ColombierTRUE), but no more output passes if the file end has been reached when the
27457dd7cddfSDavid du Colombieroutput pass is started.  This means that total_passes will rise as additional
27467dd7cddfSDavid du Colombieroutput passes are requested.  If you have a way of determining the input file
27477dd7cddfSDavid du Colombiersize, estimating progress based on the fraction of the file that's been read
27487dd7cddfSDavid du Colombierwill probably be more useful than using the library's value.
27497dd7cddfSDavid du Colombier
27507dd7cddfSDavid du Colombier
27517dd7cddfSDavid du ColombierMemory management
27527dd7cddfSDavid du Colombier-----------------
27537dd7cddfSDavid du Colombier
27547dd7cddfSDavid du ColombierThis section covers some key facts about the JPEG library's built-in memory
27557dd7cddfSDavid du Colombiermanager.  For more info, please read structure.doc's section about the memory
27567dd7cddfSDavid du Colombiermanager, and consult the source code if necessary.
27577dd7cddfSDavid du Colombier
27587dd7cddfSDavid du ColombierAll memory and temporary file allocation within the library is done via the
27597dd7cddfSDavid du Colombiermemory manager.  If necessary, you can replace the "back end" of the memory
27607dd7cddfSDavid du Colombiermanager to control allocation yourself (for example, if you don't want the
27617dd7cddfSDavid du Colombierlibrary to use malloc() and free() for some reason).
27627dd7cddfSDavid du Colombier
27637dd7cddfSDavid du ColombierSome data is allocated "permanently" and will not be freed until the JPEG
27647dd7cddfSDavid du Colombierobject is destroyed.  Most data is allocated "per image" and is freed by
27657dd7cddfSDavid du Colombierjpeg_finish_compress, jpeg_finish_decompress, or jpeg_abort.  You can call the
27667dd7cddfSDavid du Colombiermemory manager yourself to allocate structures that will automatically be
27677dd7cddfSDavid du Colombierfreed at these times.  Typical code for this is
27687dd7cddfSDavid du Colombier  ptr = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, size);
27697dd7cddfSDavid du ColombierUse JPOOL_PERMANENT to get storage that lasts as long as the JPEG object.
27707dd7cddfSDavid du ColombierUse alloc_large instead of alloc_small for anything bigger than a few Kbytes.
27717dd7cddfSDavid du ColombierThere are also alloc_sarray and alloc_barray routines that automatically
27727dd7cddfSDavid du Colombierbuild 2-D sample or block arrays.
27737dd7cddfSDavid du Colombier
27747dd7cddfSDavid du ColombierThe library's minimum space requirements to process an image depend on the
27757dd7cddfSDavid du Colombierimage's width, but not on its height, because the library ordinarily works
27767dd7cddfSDavid du Colombierwith "strip" buffers that are as wide as the image but just a few rows high.
27777dd7cddfSDavid du ColombierSome operating modes (eg, two-pass color quantization) require full-image
27787dd7cddfSDavid du Colombierbuffers.  Such buffers are treated as "virtual arrays": only the current strip
27797dd7cddfSDavid du Colombierneed be in memory, and the rest can be swapped out to a temporary file.
27807dd7cddfSDavid du Colombier
27817dd7cddfSDavid du ColombierIf you use the simplest memory manager back end (jmemnobs.c), then no
27827dd7cddfSDavid du Colombiertemporary files are used; virtual arrays are simply malloc()'d.  Images bigger
27837dd7cddfSDavid du Colombierthan memory can be processed only if your system supports virtual memory.
27847dd7cddfSDavid du ColombierThe other memory manager back ends support temporary files of various flavors
27857dd7cddfSDavid du Colombierand thus work in machines without virtual memory.  They may also be useful on
27867dd7cddfSDavid du ColombierUnix machines if you need to process images that exceed available swap space.
27877dd7cddfSDavid du Colombier
27887dd7cddfSDavid du ColombierWhen using temporary files, the library will make the in-memory buffers for
27897dd7cddfSDavid du Colombierits virtual arrays just big enough to stay within a "maximum memory" setting.
27907dd7cddfSDavid du ColombierYour application can set this limit by setting cinfo->mem->max_memory_to_use
27917dd7cddfSDavid du Colombierafter creating the JPEG object.  (Of course, there is still a minimum size for
27927dd7cddfSDavid du Colombierthe buffers, so the max-memory setting is effective only if it is bigger than
27937dd7cddfSDavid du Colombierthe minimum space needed.)  If you allocate any large structures yourself, you
27947dd7cddfSDavid du Colombiermust allocate them before jpeg_start_compress() or jpeg_start_decompress() in
27957dd7cddfSDavid du Colombierorder to have them counted against the max memory limit.  Also keep in mind
27967dd7cddfSDavid du Colombierthat space allocated with alloc_small() is ignored, on the assumption that
27977dd7cddfSDavid du Colombierit's too small to be worth worrying about; so a reasonable safety margin
27987dd7cddfSDavid du Colombiershould be left when setting max_memory_to_use.
27997dd7cddfSDavid du Colombier
28007dd7cddfSDavid du ColombierIf you use the jmemname.c or jmemdos.c memory manager back end, it is
28017dd7cddfSDavid du Colombierimportant to clean up the JPEG object properly to ensure that the temporary
28027dd7cddfSDavid du Colombierfiles get deleted.  (This is especially crucial with jmemdos.c, where the
28037dd7cddfSDavid du Colombier"temporary files" may be extended-memory segments; if they are not freed,
28047dd7cddfSDavid du ColombierDOS will require a reboot to recover the memory.)  Thus, with these memory
28057dd7cddfSDavid du Colombiermanagers, it's a good idea to provide a signal handler that will trap any
28067dd7cddfSDavid du Colombierearly exit from your program.  The handler should call either jpeg_abort()
28077dd7cddfSDavid du Colombieror jpeg_destroy() for any active JPEG objects.  A handler is not needed with
28087dd7cddfSDavid du Colombierjmemnobs.c, and shouldn't be necessary with jmemansi.c or jmemmac.c either,
28097dd7cddfSDavid du Colombiersince the C library is supposed to take care of deleting files made with
28107dd7cddfSDavid du Colombiertmpfile().
28117dd7cddfSDavid du Colombier
28127dd7cddfSDavid du Colombier
2813*593dc095SDavid du ColombierMemory usage
2814*593dc095SDavid du Colombier------------
2815*593dc095SDavid du Colombier
2816*593dc095SDavid du ColombierWorking memory requirements while performing compression or decompression
2817*593dc095SDavid du Colombierdepend on image dimensions, image characteristics (such as colorspace and
2818*593dc095SDavid du ColombierJPEG process), and operating mode (application-selected options).
2819*593dc095SDavid du Colombier
2820*593dc095SDavid du ColombierAs of v6b, the decompressor requires:
2821*593dc095SDavid du Colombier 1. About 24K in more-or-less-fixed-size data.  This varies a bit depending
2822*593dc095SDavid du Colombier    on operating mode and image characteristics (particularly color vs.
2823*593dc095SDavid du Colombier    grayscale), but it doesn't depend on image dimensions.
2824*593dc095SDavid du Colombier 2. Strip buffers (of size proportional to the image width) for IDCT and
2825*593dc095SDavid du Colombier    upsampling results.  The worst case for commonly used sampling factors
2826*593dc095SDavid du Colombier    is about 34 bytes * width in pixels for a color image.  A grayscale image
2827*593dc095SDavid du Colombier    only needs about 8 bytes per pixel column.
2828*593dc095SDavid du Colombier 3. A full-image DCT coefficient buffer is needed to decode a multi-scan JPEG
2829*593dc095SDavid du Colombier    file (including progressive JPEGs), or whenever you select buffered-image
2830*593dc095SDavid du Colombier    mode.  This takes 2 bytes/coefficient.  At typical 2x2 sampling, that's
2831*593dc095SDavid du Colombier    3 bytes per pixel for a color image.  Worst case (1x1 sampling) requires
2832*593dc095SDavid du Colombier    6 bytes/pixel.  For grayscale, figure 2 bytes/pixel.
2833*593dc095SDavid du Colombier 4. To perform 2-pass color quantization, the decompressor also needs a
2834*593dc095SDavid du Colombier    128K color lookup table and a full-image pixel buffer (3 bytes/pixel).
2835*593dc095SDavid du ColombierThis does not count any memory allocated by the application, such as a
2836*593dc095SDavid du Colombierbuffer to hold the final output image.
2837*593dc095SDavid du Colombier
2838*593dc095SDavid du ColombierThe above figures are valid for 8-bit JPEG data precision and a machine with
2839*593dc095SDavid du Colombier32-bit ints.  For 12-bit JPEG data, double the size of the strip buffers and
2840*593dc095SDavid du Colombierquantization pixel buffer.  The "fixed-size" data will be somewhat smaller
2841*593dc095SDavid du Colombierwith 16-bit ints, larger with 64-bit ints.  Also, CMYK or other unusual
2842*593dc095SDavid du Colombiercolor spaces will require different amounts of space.
2843*593dc095SDavid du Colombier
2844*593dc095SDavid du ColombierThe full-image coefficient and pixel buffers, if needed at all, do not
2845*593dc095SDavid du Colombierhave to be fully RAM resident; you can have the library use temporary
2846*593dc095SDavid du Colombierfiles instead when the total memory usage would exceed a limit you set.
2847*593dc095SDavid du Colombier(But if your OS supports virtual memory, it's probably better to just use
2848*593dc095SDavid du Colombierjmemnobs and let the OS do the swapping.)
2849*593dc095SDavid du Colombier
2850*593dc095SDavid du ColombierThe compressor's memory requirements are similar, except that it has no need
2851*593dc095SDavid du Colombierfor color quantization.  Also, it needs a full-image DCT coefficient buffer
2852*593dc095SDavid du Colombierif Huffman-table optimization is asked for, even if progressive mode is not
2853*593dc095SDavid du Colombierrequested.
2854*593dc095SDavid du Colombier
2855*593dc095SDavid du ColombierIf you need more detailed information about memory usage in a particular
2856*593dc095SDavid du Colombiersituation, you can enable the MEM_STATS code in jmemmgr.c.
2857*593dc095SDavid du Colombier
2858*593dc095SDavid du Colombier
28597dd7cddfSDavid du ColombierLibrary compile-time options
28607dd7cddfSDavid du Colombier----------------------------
28617dd7cddfSDavid du Colombier
28627dd7cddfSDavid du ColombierA number of compile-time options are available by modifying jmorecfg.h.
28637dd7cddfSDavid du Colombier
28647dd7cddfSDavid du ColombierThe JPEG standard provides for both the baseline 8-bit DCT process and
2865*593dc095SDavid du Colombiera 12-bit DCT process.  The IJG code supports 12-bit lossy JPEG if you define
28667dd7cddfSDavid du ColombierBITS_IN_JSAMPLE as 12 rather than 8.  Note that this causes JSAMPLE to be
28677dd7cddfSDavid du Colombierlarger than a char, so it affects the surrounding application's image data.
28687dd7cddfSDavid du ColombierThe sample applications cjpeg and djpeg can support 12-bit mode only for PPM
28697dd7cddfSDavid du Colombierand GIF file formats; you must disable the other file formats to compile a
28707dd7cddfSDavid du Colombier12-bit cjpeg or djpeg.  (install.doc has more information about that.)
28717dd7cddfSDavid du ColombierAt present, a 12-bit library can handle *only* 12-bit images, not both
28727dd7cddfSDavid du Colombierprecisions.  (If you need to include both 8- and 12-bit libraries in a single
28737dd7cddfSDavid du Colombierapplication, you could probably do it by defining NEED_SHORT_EXTERNAL_NAMES
28747dd7cddfSDavid du Colombierfor just one of the copies.  You'd have to access the 8-bit and 12-bit copies
28757dd7cddfSDavid du Colombierfrom separate application source files.  This is untested ... if you try it,
28767dd7cddfSDavid du Colombierwe'd like to hear whether it works!)
28777dd7cddfSDavid du Colombier
28787dd7cddfSDavid du ColombierNote that a 12-bit library always compresses in Huffman optimization mode,
28797dd7cddfSDavid du Colombierin order to generate valid Huffman tables.  This is necessary because our
28807dd7cddfSDavid du Colombierdefault Huffman tables only cover 8-bit data.  If you need to output 12-bit
28817dd7cddfSDavid du Colombierfiles in one pass, you'll have to supply suitable default Huffman tables.
2882*593dc095SDavid du ColombierYou may also want to supply your own DCT quantization tables; the existing
2883*593dc095SDavid du Colombierquality-scaling code has been developed for 8-bit use, and probably doesn't
2884*593dc095SDavid du Colombiergenerate especially good tables for 12-bit.
28857dd7cddfSDavid du Colombier
28867dd7cddfSDavid du ColombierThe maximum number of components (color channels) in the image is determined
28877dd7cddfSDavid du Colombierby MAX_COMPONENTS.  The JPEG standard allows up to 255 components, but we
28887dd7cddfSDavid du Colombierexpect that few applications will need more than four or so.
28897dd7cddfSDavid du Colombier
28907dd7cddfSDavid du ColombierOn machines with unusual data type sizes, you may be able to improve
28917dd7cddfSDavid du Colombierperformance or reduce memory space by tweaking the various typedefs in
28927dd7cddfSDavid du Colombierjmorecfg.h.  In particular, on some RISC CPUs, access to arrays of "short"s
28937dd7cddfSDavid du Colombieris quite slow; consider trading memory for speed by making JCOEF, INT16, and
28947dd7cddfSDavid du ColombierUINT16 be "int" or "unsigned int".  UINT8 is also a candidate to become int.
28957dd7cddfSDavid du ColombierYou probably don't want to make JSAMPLE be int unless you have lots of memory
28967dd7cddfSDavid du Colombierto burn.
28977dd7cddfSDavid du Colombier
28987dd7cddfSDavid du ColombierYou can reduce the size of the library by compiling out various optional
28997dd7cddfSDavid du Colombierfunctions.  To do this, undefine xxx_SUPPORTED symbols as necessary.
29007dd7cddfSDavid du Colombier
2901*593dc095SDavid du ColombierYou can also save a few K by not having text error messages in the library;
2902*593dc095SDavid du Colombierthe standard error message table occupies about 5Kb.  This is particularly
2903*593dc095SDavid du Colombierreasonable for embedded applications where there's no good way to display
2904*593dc095SDavid du Colombiera message anyway.  To do this, remove the creation of the message table
2905*593dc095SDavid du Colombier(jpeg_std_message_table[]) from jerror.c, and alter format_message to do
2906*593dc095SDavid du Colombiersomething reasonable without it.  You could output the numeric value of the
2907*593dc095SDavid du Colombiermessage code number, for example.  If you do this, you can also save a couple
2908*593dc095SDavid du Colombiermore K by modifying the TRACEMSn() macros in jerror.h to expand to nothing;
2909*593dc095SDavid du Colombieryou don't need trace capability anyway, right?
2910*593dc095SDavid du Colombier
29117dd7cddfSDavid du Colombier
29127dd7cddfSDavid du ColombierPortability considerations
29137dd7cddfSDavid du Colombier--------------------------
29147dd7cddfSDavid du Colombier
29157dd7cddfSDavid du ColombierThe JPEG library has been written to be extremely portable; the sample
29167dd7cddfSDavid du Colombierapplications cjpeg and djpeg are slightly less so.  This section summarizes
29177dd7cddfSDavid du Colombierthe design goals in this area.  (If you encounter any bugs that cause the
29187dd7cddfSDavid du Colombierlibrary to be less portable than is claimed here, we'd appreciate hearing
29197dd7cddfSDavid du Colombierabout them.)
29207dd7cddfSDavid du Colombier
2921*593dc095SDavid du ColombierThe code works fine on ANSI C, C++, and pre-ANSI C compilers, using any of
2922*593dc095SDavid du Colombierthe popular system include file setups, and some not-so-popular ones too.
2923*593dc095SDavid du ColombierSee install.doc for configuration procedures.
29247dd7cddfSDavid du Colombier
29257dd7cddfSDavid du ColombierThe code is not dependent on the exact sizes of the C data types.  As
29267dd7cddfSDavid du Colombierdistributed, we make the assumptions that
29277dd7cddfSDavid du Colombier	char	is at least 8 bits wide
29287dd7cddfSDavid du Colombier	short	is at least 16 bits wide
29297dd7cddfSDavid du Colombier	int	is at least 16 bits wide
29307dd7cddfSDavid du Colombier	long	is at least 32 bits wide
29317dd7cddfSDavid du Colombier(These are the minimum requirements of the ANSI C standard.)  Wider types will
29327dd7cddfSDavid du Colombierwork fine, although memory may be used inefficiently if char is much larger
29337dd7cddfSDavid du Colombierthan 8 bits or short is much bigger than 16 bits.  The code should work
29347dd7cddfSDavid du Colombierequally well with 16- or 32-bit ints.
29357dd7cddfSDavid du Colombier
29367dd7cddfSDavid du ColombierIn a system where these assumptions are not met, you may be able to make the
29377dd7cddfSDavid du Colombiercode work by modifying the typedefs in jmorecfg.h.  However, you will probably
29387dd7cddfSDavid du Colombierhave difficulty if int is less than 16 bits wide, since references to plain
29397dd7cddfSDavid du Colombierint abound in the code.
29407dd7cddfSDavid du Colombier
29417dd7cddfSDavid du Colombierchar can be either signed or unsigned, although the code runs faster if an
29427dd7cddfSDavid du Colombierunsigned char type is available.  If char is wider than 8 bits, you will need
29437dd7cddfSDavid du Colombierto redefine JOCTET and/or provide custom data source/destination managers so
29447dd7cddfSDavid du Colombierthat JOCTET represents exactly 8 bits of data on external storage.
29457dd7cddfSDavid du Colombier
29467dd7cddfSDavid du ColombierThe JPEG library proper does not assume ASCII representation of characters.
29477dd7cddfSDavid du ColombierBut some of the image file I/O modules in cjpeg/djpeg do have ASCII
29487dd7cddfSDavid du Colombierdependencies in file-header manipulation; so does cjpeg's select_file_type()
29497dd7cddfSDavid du Colombierroutine.
29507dd7cddfSDavid du Colombier
29517dd7cddfSDavid du ColombierThe JPEG library does not rely heavily on the C library.  In particular, C
29527dd7cddfSDavid du Colombierstdio is used only by the data source/destination modules and the error
29537dd7cddfSDavid du Colombierhandler, all of which are application-replaceable.  (cjpeg/djpeg are more
29547dd7cddfSDavid du Colombierheavily dependent on stdio.)  malloc and free are called only from the memory
29557dd7cddfSDavid du Colombiermanager "back end" module, so you can use a different memory allocator by
29567dd7cddfSDavid du Colombierreplacing that one file.
29577dd7cddfSDavid du Colombier
29587dd7cddfSDavid du ColombierThe code generally assumes that C names must be unique in the first 15
29597dd7cddfSDavid du Colombiercharacters.  However, global function names can be made unique in the
29607dd7cddfSDavid du Colombierfirst 6 characters by defining NEED_SHORT_EXTERNAL_NAMES.
29617dd7cddfSDavid du Colombier
29627dd7cddfSDavid du ColombierMore info about porting the code may be gleaned by reading jconfig.doc,
29637dd7cddfSDavid du Colombierjmorecfg.h, and jinclude.h.
29647dd7cddfSDavid du Colombier
29657dd7cddfSDavid du Colombier
29667dd7cddfSDavid du ColombierNotes for MS-DOS implementors
29677dd7cddfSDavid du Colombier-----------------------------
29687dd7cddfSDavid du Colombier
29697dd7cddfSDavid du ColombierThe IJG code is designed to work efficiently in 80x86 "small" or "medium"
29707dd7cddfSDavid du Colombiermemory models (i.e., data pointers are 16 bits unless explicitly declared
29717dd7cddfSDavid du Colombier"far"; code pointers can be either size).  You may be able to use small
29727dd7cddfSDavid du Colombiermodel to compile cjpeg or djpeg by itself, but you will probably have to use
29737dd7cddfSDavid du Colombiermedium model for any larger application.  This won't make much difference in
29747dd7cddfSDavid du Colombierperformance.  You *will* take a noticeable performance hit if you use a
29757dd7cddfSDavid du Colombierlarge-data memory model (perhaps 10%-25%), and you should avoid "huge" model
29767dd7cddfSDavid du Colombierif at all possible.
29777dd7cddfSDavid du Colombier
29787dd7cddfSDavid du ColombierThe JPEG library typically needs 2Kb-3Kb of stack space.  It will also
29797dd7cddfSDavid du Colombiermalloc about 20K-30K of near heap space while executing (and lots of far
29807dd7cddfSDavid du Colombierheap, but that doesn't count in this calculation).  This figure will vary
29817dd7cddfSDavid du Colombierdepending on selected operating mode, and to a lesser extent on image size.
29827dd7cddfSDavid du ColombierThere is also about 5Kb-6Kb of constant data which will be allocated in the
29837dd7cddfSDavid du Colombiernear data segment (about 4Kb of this is the error message table).
29847dd7cddfSDavid du ColombierThus you have perhaps 20K available for other modules' static data and near
29857dd7cddfSDavid du Colombierheap space before you need to go to a larger memory model.  The C library's
29867dd7cddfSDavid du Colombierstatic data will account for several K of this, but that still leaves a good
29877dd7cddfSDavid du Colombierdeal for your needs.  (If you are tight on space, you could reduce the sizes
29887dd7cddfSDavid du Colombierof the I/O buffers allocated by jdatasrc.c and jdatadst.c, say from 4K to
29897dd7cddfSDavid du Colombier1K.  Another possibility is to move the error message table to far memory;
29907dd7cddfSDavid du Colombierthis should be doable with only localized hacking on jerror.c.)
29917dd7cddfSDavid du Colombier
29927dd7cddfSDavid du ColombierAbout 2K of the near heap space is "permanent" memory that will not be
29937dd7cddfSDavid du Colombierreleased until you destroy the JPEG object.  This is only an issue if you
29947dd7cddfSDavid du Colombiersave a JPEG object between compression or decompression operations.
29957dd7cddfSDavid du Colombier
29967dd7cddfSDavid du ColombierFar data space may also be a tight resource when you are dealing with large
29977dd7cddfSDavid du Colombierimages.  The most memory-intensive case is decompression with two-pass color
29987dd7cddfSDavid du Colombierquantization, or single-pass quantization to an externally supplied color
29997dd7cddfSDavid du Colombiermap.  This requires a 128Kb color lookup table plus strip buffers amounting
3000*593dc095SDavid du Colombierto about 40 bytes per column for typical sampling ratios (eg, about 25600
30017dd7cddfSDavid du Colombierbytes for a 640-pixel-wide image).  You may not be able to process wide
30027dd7cddfSDavid du Colombierimages if you have large data structures of your own.
30037dd7cddfSDavid du Colombier
30047dd7cddfSDavid du ColombierOf course, all of these concerns vanish if you use a 32-bit flat-memory-model
30057dd7cddfSDavid du Colombiercompiler, such as DJGPP or Watcom C.  We highly recommend flat model if you
30067dd7cddfSDavid du Colombiercan use it; the JPEG library is significantly faster in flat model.
3007