kusano 7d535a
USING THE IJG JPEG LIBRARY
kusano 7d535a
kusano 7d535a
Copyright (C) 1994-2013, Thomas G. Lane, Guido Vollbeding.
kusano 7d535a
This file is part of the Independent JPEG Group's software.
kusano 7d535a
For conditions of distribution and use, see the accompanying README file.
kusano 7d535a
kusano 7d535a
kusano 7d535a
This file describes how to use the IJG JPEG library within an application
kusano 7d535a
program.  Read it if you want to write a program that uses the library.
kusano 7d535a
kusano 7d535a
The file example.c provides heavily commented skeleton code for calling the
kusano 7d535a
JPEG library.  Also see jpeglib.h (the include file to be used by application
kusano 7d535a
programs) for full details about data structures and function parameter lists.
kusano 7d535a
The library source code, of course, is the ultimate reference.
kusano 7d535a
kusano 7d535a
Note that there have been *major* changes from the application interface
kusano 7d535a
presented by IJG version 4 and earlier versions.  The old design had several
kusano 7d535a
inherent limitations, and it had accumulated a lot of cruft as we added
kusano 7d535a
features while trying to minimize application-interface changes.  We have
kusano 7d535a
sacrificed backward compatibility in the version 5 rewrite, but we think the
kusano 7d535a
improvements justify this.
kusano 7d535a
kusano 7d535a
kusano 7d535a
TABLE OF CONTENTS
kusano 7d535a
-----------------
kusano 7d535a
kusano 7d535a
Overview:
kusano 7d535a
	Functions provided by the library
kusano 7d535a
	Outline of typical usage
kusano 7d535a
Basic library usage:
kusano 7d535a
	Data formats
kusano 7d535a
	Compression details
kusano 7d535a
	Decompression details
kusano 7d535a
	Mechanics of usage: include files, linking, etc
kusano 7d535a
Advanced features:
kusano 7d535a
	Compression parameter selection
kusano 7d535a
	Decompression parameter selection
kusano 7d535a
	Special color spaces
kusano 7d535a
	Error handling
kusano 7d535a
	Compressed data handling (source and destination managers)
kusano 7d535a
	I/O suspension
kusano 7d535a
	Progressive JPEG support
kusano 7d535a
	Buffered-image mode
kusano 7d535a
	Abbreviated datastreams and multiple images
kusano 7d535a
	Special markers
kusano 7d535a
	Raw (downsampled) image data
kusano 7d535a
	Really raw data: DCT coefficients
kusano 7d535a
	Progress monitoring
kusano 7d535a
	Memory management
kusano 7d535a
	Memory usage
kusano 7d535a
	Library compile-time options
kusano 7d535a
	Portability considerations
kusano 7d535a
	Notes for MS-DOS implementors
kusano 7d535a
kusano 7d535a
You should read at least the overview and basic usage sections before trying
kusano 7d535a
to program with the library.  The sections on advanced features can be read
kusano 7d535a
if and when you need them.
kusano 7d535a
kusano 7d535a
kusano 7d535a
OVERVIEW
kusano 7d535a
========
kusano 7d535a
kusano 7d535a
Functions provided by the library
kusano 7d535a
---------------------------------
kusano 7d535a
kusano 7d535a
The IJG JPEG library provides C code to read and write JPEG-compressed image
kusano 7d535a
files.  The surrounding application program receives or supplies image data a
kusano 7d535a
scanline at a time, using a straightforward uncompressed image format.  All
kusano 7d535a
details of color conversion and other preprocessing/postprocessing can be
kusano 7d535a
handled by the library.
kusano 7d535a
kusano 7d535a
The library includes a substantial amount of code that is not covered by the
kusano 7d535a
JPEG standard but is necessary for typical applications of JPEG.  These
kusano 7d535a
functions preprocess the image before JPEG compression or postprocess it after
kusano 7d535a
decompression.  They include colorspace conversion, downsampling/upsampling,
kusano 7d535a
and color quantization.  The application indirectly selects use of this code
kusano 7d535a
by specifying the format in which it wishes to supply or receive image data.
kusano 7d535a
For example, if colormapped output is requested, then the decompression
kusano 7d535a
library automatically invokes color quantization.
kusano 7d535a
kusano 7d535a
A wide range of quality vs. speed tradeoffs are possible in JPEG processing,
kusano 7d535a
and even more so in decompression postprocessing.  The decompression library
kusano 7d535a
provides multiple implementations that cover most of the useful tradeoffs,
kusano 7d535a
ranging from very-high-quality down to fast-preview operation.  On the
kusano 7d535a
compression side we have generally not provided low-quality choices, since
kusano 7d535a
compression is normally less time-critical.  It should be understood that the
kusano 7d535a
low-quality modes may not meet the JPEG standard's accuracy requirements;
kusano 7d535a
nonetheless, they are useful for viewers.
kusano 7d535a
kusano 7d535a
A word about functions *not* provided by the library.  We handle a subset of
kusano 7d535a
the ISO JPEG standard; most baseline, extended-sequential, and progressive
kusano 7d535a
JPEG processes are supported.  (Our subset includes all features now in common
kusano 7d535a
use.)  Unsupported ISO options include:
kusano 7d535a
	* Hierarchical storage
kusano 7d535a
	* Lossless JPEG
kusano 7d535a
	* DNL marker
kusano 7d535a
	* Nonintegral subsampling ratios
kusano 7d535a
We support both 8- and 12-bit data precision, but this is a compile-time
kusano 7d535a
choice rather than a run-time choice; hence it is difficult to use both
kusano 7d535a
precisions in a single application.
kusano 7d535a
kusano 7d535a
By itself, the library handles only interchange JPEG datastreams --- in
kusano 7d535a
particular the widely used JFIF file format.  The library can be used by
kusano 7d535a
surrounding code to process interchange or abbreviated JPEG datastreams that
kusano 7d535a
are embedded in more complex file formats.  (For example, this library is
kusano 7d535a
used by the free LIBTIFF library to support JPEG compression in TIFF.)
kusano 7d535a
kusano 7d535a
kusano 7d535a
Outline of typical usage
kusano 7d535a
------------------------
kusano 7d535a
kusano 7d535a
The rough outline of a JPEG compression operation is:
kusano 7d535a
kusano 7d535a
	Allocate and initialize a JPEG compression object
kusano 7d535a
	Specify the destination for the compressed data (eg, a file)
kusano 7d535a
	Set parameters for compression, including image size & colorspace
kusano 7d535a
	jpeg_start_compress(...);
kusano 7d535a
	while (scan lines remain to be written)
kusano 7d535a
		jpeg_write_scanlines(...);
kusano 7d535a
	jpeg_finish_compress(...);
kusano 7d535a
	Release the JPEG compression object
kusano 7d535a
kusano 7d535a
A JPEG compression object holds parameters and working state for the JPEG
kusano 7d535a
library.  We make creation/destruction of the object separate from starting
kusano 7d535a
or finishing compression of an image; the same object can be re-used for a
kusano 7d535a
series of image compression operations.  This makes it easy to re-use the
kusano 7d535a
same parameter settings for a sequence of images.  Re-use of a JPEG object
kusano 7d535a
also has important implications for processing abbreviated JPEG datastreams,
kusano 7d535a
as discussed later.
kusano 7d535a
kusano 7d535a
The image data to be compressed is supplied to jpeg_write_scanlines() from
kusano 7d535a
in-memory buffers.  If the application is doing file-to-file compression,
kusano 7d535a
reading image data from the source file is the application's responsibility.
kusano 7d535a
The library emits compressed data by calling a "data destination manager",
kusano 7d535a
which typically will write the data into a file; but the application can
kusano 7d535a
provide its own destination manager to do something else.
kusano 7d535a
kusano 7d535a
Similarly, the rough outline of a JPEG decompression operation is:
kusano 7d535a
kusano 7d535a
	Allocate and initialize a JPEG decompression object
kusano 7d535a
	Specify the source of the compressed data (eg, a file)
kusano 7d535a
	Call jpeg_read_header() to obtain image info
kusano 7d535a
	Set parameters for decompression
kusano 7d535a
	jpeg_start_decompress(...);
kusano 7d535a
	while (scan lines remain to be read)
kusano 7d535a
		jpeg_read_scanlines(...);
kusano 7d535a
	jpeg_finish_decompress(...);
kusano 7d535a
	Release the JPEG decompression object
kusano 7d535a
kusano 7d535a
This is comparable to the compression outline except that reading the
kusano 7d535a
datastream header is a separate step.  This is helpful because information
kusano 7d535a
about the image's size, colorspace, etc is available when the application
kusano 7d535a
selects decompression parameters.  For example, the application can choose an
kusano 7d535a
output scaling ratio that will fit the image into the available screen size.
kusano 7d535a
kusano 7d535a
The decompression library obtains compressed data by calling a data source
kusano 7d535a
manager, which typically will read the data from a file; but other behaviors
kusano 7d535a
can be obtained with a custom source manager.  Decompressed data is delivered
kusano 7d535a
into in-memory buffers passed to jpeg_read_scanlines().
kusano 7d535a
kusano 7d535a
It is possible to abort an incomplete compression or decompression operation
kusano 7d535a
by calling jpeg_abort(); or, if you do not need to retain the JPEG object,
kusano 7d535a
simply release it by calling jpeg_destroy().
kusano 7d535a
kusano 7d535a
JPEG compression and decompression objects are two separate struct types.
kusano 7d535a
However, they share some common fields, and certain routines such as
kusano 7d535a
jpeg_destroy() can work on either type of object.
kusano 7d535a
kusano 7d535a
The JPEG library has no static variables: all state is in the compression
kusano 7d535a
or decompression object.  Therefore it is possible to process multiple
kusano 7d535a
compression and decompression operations concurrently, using multiple JPEG
kusano 7d535a
objects.
kusano 7d535a
kusano 7d535a
Both compression and decompression can be done in an incremental memory-to-
kusano 7d535a
memory fashion, if suitable source/destination managers are used.  See the
kusano 7d535a
section on "I/O suspension" for more details.
kusano 7d535a
kusano 7d535a
kusano 7d535a
BASIC LIBRARY USAGE
kusano 7d535a
===================
kusano 7d535a
kusano 7d535a
Data formats
kusano 7d535a
------------
kusano 7d535a
kusano 7d535a
Before diving into procedural details, it is helpful to understand the
kusano 7d535a
image data format that the JPEG library expects or returns.
kusano 7d535a
kusano 7d535a
The standard input image format is a rectangular array of pixels, with each
kusano 7d535a
pixel having the same number of "component" or "sample" values (color
kusano 7d535a
channels).  You must specify how many components there are and the colorspace
kusano 7d535a
interpretation of the components.  Most applications will use RGB data
kusano 7d535a
(three components per pixel) or grayscale data (one component per pixel).
kusano 7d535a
PLEASE NOTE THAT RGB DATA IS THREE SAMPLES PER PIXEL, GRAYSCALE ONLY ONE.
kusano 7d535a
A remarkable number of people manage to miss this, only to find that their
kusano 7d535a
programs don't work with grayscale JPEG files.
kusano 7d535a
kusano 7d535a
There is no provision for colormapped input.  JPEG files are always full-color
kusano 7d535a
or full grayscale (or sometimes another colorspace such as CMYK).  You can
kusano 7d535a
feed in a colormapped image by expanding it to full-color format.  However
kusano 7d535a
JPEG often doesn't work very well with source data that has been colormapped,
kusano 7d535a
because of dithering noise.  This is discussed in more detail in the JPEG FAQ
kusano 7d535a
and the other references mentioned in the README file.
kusano 7d535a
kusano 7d535a
Pixels are stored by scanlines, with each scanline running from left to
kusano 7d535a
right.  The component values for each pixel are adjacent in the row; for
kusano 7d535a
example, R,G,B,R,G,B,R,G,B,... for 24-bit RGB color.  Each scanline is an
kusano 7d535a
array of data type JSAMPLE --- which is typically "unsigned char", unless
kusano 7d535a
you've changed jmorecfg.h.  (You can also change the RGB pixel layout, say
kusano 7d535a
to B,G,R order, by modifying jmorecfg.h.  But see the restrictions listed in
kusano 7d535a
that file before doing so.)
kusano 7d535a
kusano 7d535a
A 2-D array of pixels is formed by making a list of pointers to the starts of
kusano 7d535a
scanlines; so the scanlines need not be physically adjacent in memory.  Even
kusano 7d535a
if you process just one scanline at a time, you must make a one-element
kusano 7d535a
pointer array to conform to this structure.  Pointers to JSAMPLE rows are of
kusano 7d535a
type JSAMPROW, and the pointer to the pointer array is of type JSAMPARRAY.
kusano 7d535a
kusano 7d535a
The library accepts or supplies one or more complete scanlines per call.
kusano 7d535a
It is not possible to process part of a row at a time.  Scanlines are always
kusano 7d535a
processed top-to-bottom.  You can process an entire image in one call if you
kusano 7d535a
have it all in memory, but usually it's simplest to process one scanline at
kusano 7d535a
a time.
kusano 7d535a
kusano 7d535a
For best results, source data values should have the precision specified by
kusano 7d535a
BITS_IN_JSAMPLE (normally 8 bits).  For instance, if you choose to compress
kusano 7d535a
data that's only 6 bits/channel, you should left-justify each value in a
kusano 7d535a
byte before passing it to the compressor.  If you need to compress data
kusano 7d535a
that has more than 8 bits/channel, compile with BITS_IN_JSAMPLE = 12.
kusano 7d535a
(See "Library compile-time options", later.)
kusano 7d535a
kusano 7d535a
kusano 7d535a
The data format returned by the decompressor is the same in all details,
kusano 7d535a
except that colormapped output is supported.  (Again, a JPEG file is never
kusano 7d535a
colormapped.  But you can ask the decompressor to perform on-the-fly color
kusano 7d535a
quantization to deliver colormapped output.)  If you request colormapped
kusano 7d535a
output then the returned data array contains a single JSAMPLE per pixel;
kusano 7d535a
its value is an index into a color map.  The color map is represented as
kusano 7d535a
a 2-D JSAMPARRAY in which each row holds the values of one color component,
kusano 7d535a
that is, colormap[i][j] is the value of the i'th color component for pixel
kusano 7d535a
value (map index) j.  Note that since the colormap indexes are stored in
kusano 7d535a
JSAMPLEs, the maximum number of colors is limited by the size of JSAMPLE
kusano 7d535a
(ie, at most 256 colors for an 8-bit JPEG library).
kusano 7d535a
kusano 7d535a
kusano 7d535a
Compression details
kusano 7d535a
-------------------
kusano 7d535a
kusano 7d535a
Here we revisit the JPEG compression outline given in the overview.
kusano 7d535a
kusano 7d535a
1. Allocate and initialize a JPEG compression object.
kusano 7d535a
kusano 7d535a
A JPEG compression object is a "struct jpeg_compress_struct".  (It also has
kusano 7d535a
a bunch of subsidiary structures which are allocated via malloc(), but the
kusano 7d535a
application doesn't control those directly.)  This struct can be just a local
kusano 7d535a
variable in the calling routine, if a single routine is going to execute the
kusano 7d535a
whole JPEG compression sequence.  Otherwise it can be static or allocated
kusano 7d535a
from malloc().
kusano 7d535a
kusano 7d535a
You will also need a structure representing a JPEG error handler.  The part
kusano 7d535a
of this that the library cares about is a "struct jpeg_error_mgr".  If you
kusano 7d535a
are providing your own error handler, you'll typically want to embed the
kusano 7d535a
jpeg_error_mgr struct in a larger structure; this is discussed later under
kusano 7d535a
"Error handling".  For now we'll assume you are just using the default error
kusano 7d535a
handler.  The default error handler will print JPEG error/warning messages
kusano 7d535a
on stderr, and it will call exit() if a fatal error occurs.
kusano 7d535a
kusano 7d535a
You must initialize the error handler structure, store a pointer to it into
kusano 7d535a
the JPEG object's "err" field, and then call jpeg_create_compress() to
kusano 7d535a
initialize the rest of the JPEG object.
kusano 7d535a
kusano 7d535a
Typical code for this step, if you are using the default error handler, is
kusano 7d535a
kusano 7d535a
	struct jpeg_compress_struct cinfo;
kusano 7d535a
	struct jpeg_error_mgr jerr;
kusano 7d535a
	...
kusano 7d535a
	cinfo.err = jpeg_std_error(&jerr);
kusano 7d535a
	jpeg_create_compress(&cinfo);
kusano 7d535a
kusano 7d535a
jpeg_create_compress allocates a small amount of memory, so it could fail
kusano 7d535a
if you are out of memory.  In that case it will exit via the error handler;
kusano 7d535a
that's why the error handler must be initialized first.
kusano 7d535a
kusano 7d535a
kusano 7d535a
2. Specify the destination for the compressed data (eg, a file).
kusano 7d535a
kusano 7d535a
As previously mentioned, the JPEG library delivers compressed data to a
kusano 7d535a
"data destination" module.  The library includes one data destination
kusano 7d535a
module which knows how to write to a stdio stream.  You can use your own
kusano 7d535a
destination module if you want to do something else, as discussed later.
kusano 7d535a
kusano 7d535a
If you use the standard destination module, you must open the target stdio
kusano 7d535a
stream beforehand.  Typical code for this step looks like:
kusano 7d535a
kusano 7d535a
	FILE * outfile;
kusano 7d535a
	...
kusano 7d535a
	if ((outfile = fopen(filename, "wb")) == NULL) {
kusano 7d535a
	    fprintf(stderr, "can't open %s\n", filename);
kusano 7d535a
	    exit(1);
kusano 7d535a
	}
kusano 7d535a
	jpeg_stdio_dest(&cinfo, outfile);
kusano 7d535a
kusano 7d535a
where the last line invokes the standard destination module.
kusano 7d535a
kusano 7d535a
WARNING: it is critical that the binary compressed data be delivered to the
kusano 7d535a
output file unchanged.  On non-Unix systems the stdio library may perform
kusano 7d535a
newline translation or otherwise corrupt binary data.  To suppress this
kusano 7d535a
behavior, you may need to use a "b" option to fopen (as shown above), or use
kusano 7d535a
setmode() or another routine to put the stdio stream in binary mode.  See
kusano 7d535a
cjpeg.c and djpeg.c for code that has been found to work on many systems.
kusano 7d535a
kusano 7d535a
You can select the data destination after setting other parameters (step 3),
kusano 7d535a
if that's more convenient.  You may not change the destination between
kusano 7d535a
calling jpeg_start_compress() and jpeg_finish_compress().
kusano 7d535a
kusano 7d535a
kusano 7d535a
3. Set parameters for compression, including image size & colorspace.
kusano 7d535a
kusano 7d535a
You must supply information about the source image by setting the following
kusano 7d535a
fields in the JPEG object (cinfo structure):
kusano 7d535a
kusano 7d535a
	image_width		Width of image, in pixels
kusano 7d535a
	image_height		Height of image, in pixels
kusano 7d535a
	input_components	Number of color channels (samples per pixel)
kusano 7d535a
	in_color_space		Color space of source image
kusano 7d535a
kusano 7d535a
The image dimensions are, hopefully, obvious.  JPEG supports image dimensions
kusano 7d535a
of 1 to 64K pixels in either direction.  The input color space is typically
kusano 7d535a
RGB or grayscale, and input_components is 3 or 1 accordingly.  (See "Special
kusano 7d535a
color spaces", later, for more info.)  The in_color_space field must be
kusano 7d535a
assigned one of the J_COLOR_SPACE enum constants, typically JCS_RGB or
kusano 7d535a
JCS_GRAYSCALE.
kusano 7d535a
kusano 7d535a
JPEG has a large number of compression parameters that determine how the
kusano 7d535a
image is encoded.  Most applications don't need or want to know about all
kusano 7d535a
these parameters.  You can set all the parameters to reasonable defaults by
kusano 7d535a
calling jpeg_set_defaults(); then, if there are particular values you want
kusano 7d535a
to change, you can do so after that.  The "Compression parameter selection"
kusano 7d535a
section tells about all the parameters.
kusano 7d535a
kusano 7d535a
You must set in_color_space correctly before calling jpeg_set_defaults(),
kusano 7d535a
because the defaults depend on the source image colorspace.  However the
kusano 7d535a
other three source image parameters need not be valid until you call
kusano 7d535a
jpeg_start_compress().  There's no harm in calling jpeg_set_defaults() more
kusano 7d535a
than once, if that happens to be convenient.
kusano 7d535a
kusano 7d535a
Typical code for a 24-bit RGB source image is
kusano 7d535a
kusano 7d535a
	cinfo.image_width = Width; 	/* image width and height, in pixels */
kusano 7d535a
	cinfo.image_height = Height;
kusano 7d535a
	cinfo.input_components = 3;	/* # of color components per pixel */
kusano 7d535a
	cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
kusano 7d535a
kusano 7d535a
	jpeg_set_defaults(&cinfo);
kusano 7d535a
	/* Make optional parameter settings here */
kusano 7d535a
kusano 7d535a
kusano 7d535a
4. jpeg_start_compress(...);
kusano 7d535a
kusano 7d535a
After you have established the data destination and set all the necessary
kusano 7d535a
source image info and other parameters, call jpeg_start_compress() to begin
kusano 7d535a
a compression cycle.  This will initialize internal state, allocate working
kusano 7d535a
storage, and emit the first few bytes of the JPEG datastream header.
kusano 7d535a
kusano 7d535a
Typical code:
kusano 7d535a
kusano 7d535a
	jpeg_start_compress(&cinfo, TRUE);
kusano 7d535a
kusano 7d535a
The "TRUE" parameter ensures that a complete JPEG interchange datastream
kusano 7d535a
will be written.  This is appropriate in most cases.  If you think you might
kusano 7d535a
want to use an abbreviated datastream, read the section on abbreviated
kusano 7d535a
datastreams, below.
kusano 7d535a
kusano 7d535a
Once you have called jpeg_start_compress(), you may not alter any JPEG
kusano 7d535a
parameters or other fields of the JPEG object until you have completed
kusano 7d535a
the compression cycle.
kusano 7d535a
kusano 7d535a
kusano 7d535a
5. while (scan lines remain to be written)
kusano 7d535a
	jpeg_write_scanlines(...);
kusano 7d535a
kusano 7d535a
Now write all the required image data by calling jpeg_write_scanlines()
kusano 7d535a
one or more times.  You can pass one or more scanlines in each call, up
kusano 7d535a
to the total image height.  In most applications it is convenient to pass
kusano 7d535a
just one or a few scanlines at a time.  The expected format for the passed
kusano 7d535a
data is discussed under "Data formats", above.
kusano 7d535a
kusano 7d535a
Image data should be written in top-to-bottom scanline order.  The JPEG spec
kusano 7d535a
contains some weasel wording about how top and bottom are application-defined
kusano 7d535a
terms (a curious interpretation of the English language...) but if you want
kusano 7d535a
your files to be compatible with everyone else's, you WILL use top-to-bottom
kusano 7d535a
order.  If the source data must be read in bottom-to-top order, you can use
kusano 7d535a
the JPEG library's virtual array mechanism to invert the data efficiently.
kusano 7d535a
Examples of this can be found in the sample application cjpeg.
kusano 7d535a
kusano 7d535a
The library maintains a count of the number of scanlines written so far
kusano 7d535a
in the next_scanline field of the JPEG object.  Usually you can just use
kusano 7d535a
this variable as the loop counter, so that the loop test looks like
kusano 7d535a
"while (cinfo.next_scanline < cinfo.image_height)".
kusano 7d535a
kusano 7d535a
Code for this step depends heavily on the way that you store the source data.
kusano 7d535a
example.c shows the following code for the case of a full-size 2-D source
kusano 7d535a
array containing 3-byte RGB pixels:
kusano 7d535a
kusano 7d535a
	JSAMPROW row_pointer[1];	/* pointer to a single row */
kusano 7d535a
	int row_stride;			/* physical row width in buffer */
kusano 7d535a
kusano 7d535a
	row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */
kusano 7d535a
kusano 7d535a
	while (cinfo.next_scanline < cinfo.image_height) {
kusano 7d535a
	    row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
kusano 7d535a
	    jpeg_write_scanlines(&cinfo, row_pointer, 1);
kusano 7d535a
	}
kusano 7d535a
kusano 7d535a
jpeg_write_scanlines() returns the number of scanlines actually written.
kusano 7d535a
This will normally be equal to the number passed in, so you can usually
kusano 7d535a
ignore the return value.  It is different in just two cases:
kusano 7d535a
  * If you try to write more scanlines than the declared image height,
kusano 7d535a
    the additional scanlines are ignored.
kusano 7d535a
  * If you use a suspending data destination manager, output buffer overrun
kusano 7d535a
    will cause the compressor to return before accepting all the passed lines.
kusano 7d535a
    This feature is discussed under "I/O suspension", below.  The normal
kusano 7d535a
    stdio destination manager will NOT cause this to happen.
kusano 7d535a
In any case, the return value is the same as the change in the value of
kusano 7d535a
next_scanline.
kusano 7d535a
kusano 7d535a
kusano 7d535a
6. jpeg_finish_compress(...);
kusano 7d535a
kusano 7d535a
After all the image data has been written, call jpeg_finish_compress() to
kusano 7d535a
complete the compression cycle.  This step is ESSENTIAL to ensure that the
kusano 7d535a
last bufferload of data is written to the data destination.
kusano 7d535a
jpeg_finish_compress() also releases working memory associated with the JPEG
kusano 7d535a
object.
kusano 7d535a
kusano 7d535a
Typical code:
kusano 7d535a
kusano 7d535a
	jpeg_finish_compress(&cinfo);
kusano 7d535a
kusano 7d535a
If using the stdio destination manager, don't forget to close the output
kusano 7d535a
stdio stream (if necessary) afterwards.
kusano 7d535a
kusano 7d535a
If you have requested a multi-pass operating mode, such as Huffman code
kusano 7d535a
optimization, jpeg_finish_compress() will perform the additional passes using
kusano 7d535a
data buffered by the first pass.  In this case jpeg_finish_compress() may take
kusano 7d535a
quite a while to complete.  With the default compression parameters, this will
kusano 7d535a
not happen.
kusano 7d535a
kusano 7d535a
It is an error to call jpeg_finish_compress() before writing the necessary
kusano 7d535a
total number of scanlines.  If you wish to abort compression, call
kusano 7d535a
jpeg_abort() as discussed below.
kusano 7d535a
kusano 7d535a
After completing a compression cycle, you may dispose of the JPEG object
kusano 7d535a
as discussed next, or you may use it to compress another image.  In that case
kusano 7d535a
return to step 2, 3, or 4 as appropriate.  If you do not change the
kusano 7d535a
destination manager, the new datastream will be written to the same target.
kusano 7d535a
If you do not change any JPEG parameters, the new datastream will be written
kusano 7d535a
with the same parameters as before.  Note that you can change the input image
kusano 7d535a
dimensions freely between cycles, but if you change the input colorspace, you
kusano 7d535a
should call jpeg_set_defaults() to adjust for the new colorspace; and then
kusano 7d535a
you'll need to repeat all of step 3.
kusano 7d535a
kusano 7d535a
kusano 7d535a
7. Release the JPEG compression object.
kusano 7d535a
kusano 7d535a
When you are done with a JPEG compression object, destroy it by calling
kusano 7d535a
jpeg_destroy_compress().  This will free all subsidiary memory (regardless of
kusano 7d535a
the previous state of the object).  Or you can call jpeg_destroy(), which
kusano 7d535a
works for either compression or decompression objects --- this may be more
kusano 7d535a
convenient if you are sharing code between compression and decompression
kusano 7d535a
cases.  (Actually, these routines are equivalent except for the declared type
kusano 7d535a
of the passed pointer.  To avoid gripes from ANSI C compilers, jpeg_destroy()
kusano 7d535a
should be passed a j_common_ptr.)
kusano 7d535a
kusano 7d535a
If you allocated the jpeg_compress_struct structure from malloc(), freeing
kusano 7d535a
it is your responsibility --- jpeg_destroy() won't.  Ditto for the error
kusano 7d535a
handler structure.
kusano 7d535a
kusano 7d535a
Typical code:
kusano 7d535a
kusano 7d535a
	jpeg_destroy_compress(&cinfo);
kusano 7d535a
kusano 7d535a
kusano 7d535a
8. Aborting.
kusano 7d535a
kusano 7d535a
If you decide to abort a compression cycle before finishing, you can clean up
kusano 7d535a
in either of two ways:
kusano 7d535a
kusano 7d535a
* If you don't need the JPEG object any more, just call
kusano 7d535a
  jpeg_destroy_compress() or jpeg_destroy() to release memory.  This is
kusano 7d535a
  legitimate at any point after calling jpeg_create_compress() --- in fact,
kusano 7d535a
  it's safe even if jpeg_create_compress() fails.
kusano 7d535a
kusano 7d535a
* If you want to re-use the JPEG object, call jpeg_abort_compress(), or call
kusano 7d535a
  jpeg_abort() which works on both compression and decompression objects.
kusano 7d535a
  This will return the object to an idle state, releasing any working memory.
kusano 7d535a
  jpeg_abort() is allowed at any time after successful object creation.
kusano 7d535a
kusano 7d535a
Note that cleaning up the data destination, if required, is your
kusano 7d535a
responsibility; neither of these routines will call term_destination().
kusano 7d535a
(See "Compressed data handling", below, for more about that.)
kusano 7d535a
kusano 7d535a
jpeg_destroy() and jpeg_abort() are the only safe calls to make on a JPEG
kusano 7d535a
object that has reported an error by calling error_exit (see "Error handling"
kusano 7d535a
for more info).  The internal state of such an object is likely to be out of
kusano 7d535a
whack.  Either of these two routines will return the object to a known state.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Decompression details
kusano 7d535a
---------------------
kusano 7d535a
kusano 7d535a
Here we revisit the JPEG decompression outline given in the overview.
kusano 7d535a
kusano 7d535a
1. Allocate and initialize a JPEG decompression object.
kusano 7d535a
kusano 7d535a
This is just like initialization for compression, as discussed above,
kusano 7d535a
except that the object is a "struct jpeg_decompress_struct" and you
kusano 7d535a
call jpeg_create_decompress().  Error handling is exactly the same.
kusano 7d535a
kusano 7d535a
Typical code:
kusano 7d535a
kusano 7d535a
	struct jpeg_decompress_struct cinfo;
kusano 7d535a
	struct jpeg_error_mgr jerr;
kusano 7d535a
	...
kusano 7d535a
	cinfo.err = jpeg_std_error(&jerr);
kusano 7d535a
	jpeg_create_decompress(&cinfo);
kusano 7d535a
kusano 7d535a
(Both here and in the IJG code, we usually use variable name "cinfo" for
kusano 7d535a
both compression and decompression objects.)
kusano 7d535a
kusano 7d535a
kusano 7d535a
2. Specify the source of the compressed data (eg, a file).
kusano 7d535a
kusano 7d535a
As previously mentioned, the JPEG library reads compressed data from a "data
kusano 7d535a
source" module.  The library includes one data source module which knows how
kusano 7d535a
to read from a stdio stream.  You can use your own source module if you want
kusano 7d535a
to do something else, as discussed later.
kusano 7d535a
kusano 7d535a
If you use the standard source module, you must open the source stdio stream
kusano 7d535a
beforehand.  Typical code for this step looks like:
kusano 7d535a
kusano 7d535a
	FILE * infile;
kusano 7d535a
	...
kusano 7d535a
	if ((infile = fopen(filename, "rb")) == NULL) {
kusano 7d535a
	    fprintf(stderr, "can't open %s\n", filename);
kusano 7d535a
	    exit(1);
kusano 7d535a
	}
kusano 7d535a
	jpeg_stdio_src(&cinfo, infile);
kusano 7d535a
kusano 7d535a
where the last line invokes the standard source module.
kusano 7d535a
kusano 7d535a
WARNING: it is critical that the binary compressed data be read unchanged.
kusano 7d535a
On non-Unix systems the stdio library may perform newline translation or
kusano 7d535a
otherwise corrupt binary data.  To suppress this behavior, you may need to use
kusano 7d535a
a "b" option to fopen (as shown above), or use setmode() or another routine to
kusano 7d535a
put the stdio stream in binary mode.  See cjpeg.c and djpeg.c for code that
kusano 7d535a
has been found to work on many systems.
kusano 7d535a
kusano 7d535a
You may not change the data source between calling jpeg_read_header() and
kusano 7d535a
jpeg_finish_decompress().  If you wish to read a series of JPEG images from
kusano 7d535a
a single source file, you should repeat the jpeg_read_header() to
kusano 7d535a
jpeg_finish_decompress() sequence without reinitializing either the JPEG
kusano 7d535a
object or the data source module; this prevents buffered input data from
kusano 7d535a
being discarded.
kusano 7d535a
kusano 7d535a
kusano 7d535a
3. Call jpeg_read_header() to obtain image info.
kusano 7d535a
kusano 7d535a
Typical code for this step is just
kusano 7d535a
kusano 7d535a
	jpeg_read_header(&cinfo, TRUE);
kusano 7d535a
kusano 7d535a
This will read the source datastream header markers, up to the beginning
kusano 7d535a
of the compressed data proper.  On return, the image dimensions and other
kusano 7d535a
info have been stored in the JPEG object.  The application may wish to
kusano 7d535a
consult this information before selecting decompression parameters.
kusano 7d535a
kusano 7d535a
More complex code is necessary if
kusano 7d535a
  * A suspending data source is used --- in that case jpeg_read_header()
kusano 7d535a
    may return before it has read all the header data.  See "I/O suspension",
kusano 7d535a
    below.  The normal stdio source manager will NOT cause this to happen.
kusano 7d535a
  * Abbreviated JPEG files are to be processed --- see the section on
kusano 7d535a
    abbreviated datastreams.  Standard applications that deal only in
kusano 7d535a
    interchange JPEG files need not be concerned with this case either.
kusano 7d535a
kusano 7d535a
It is permissible to stop at this point if you just wanted to find out the
kusano 7d535a
image dimensions and other header info for a JPEG file.  In that case,
kusano 7d535a
call jpeg_destroy() when you are done with the JPEG object, or call
kusano 7d535a
jpeg_abort() to return it to an idle state before selecting a new data
kusano 7d535a
source and reading another header.
kusano 7d535a
kusano 7d535a
kusano 7d535a
4. Set parameters for decompression.
kusano 7d535a
kusano 7d535a
jpeg_read_header() sets appropriate default decompression parameters based on
kusano 7d535a
the properties of the image (in particular, its colorspace).  However, you
kusano 7d535a
may well want to alter these defaults before beginning the decompression.
kusano 7d535a
For example, the default is to produce full color output from a color file.
kusano 7d535a
If you want colormapped output you must ask for it.  Other options allow the
kusano 7d535a
returned image to be scaled and allow various speed/quality tradeoffs to be
kusano 7d535a
selected.  "Decompression parameter selection", below, gives details.
kusano 7d535a
kusano 7d535a
If the defaults are appropriate, nothing need be done at this step.
kusano 7d535a
kusano 7d535a
Note that all default values are set by each call to jpeg_read_header().
kusano 7d535a
If you reuse a decompression object, you cannot expect your parameter
kusano 7d535a
settings to be preserved across cycles, as you can for compression.
kusano 7d535a
You must set desired parameter values each time.
kusano 7d535a
kusano 7d535a
kusano 7d535a
5. jpeg_start_decompress(...);
kusano 7d535a
kusano 7d535a
Once the parameter values are satisfactory, call jpeg_start_decompress() to
kusano 7d535a
begin decompression.  This will initialize internal state, allocate working
kusano 7d535a
memory, and prepare for returning data.
kusano 7d535a
kusano 7d535a
Typical code is just
kusano 7d535a
kusano 7d535a
	jpeg_start_decompress(&cinfo);
kusano 7d535a
kusano 7d535a
If you have requested a multi-pass operating mode, such as 2-pass color
kusano 7d535a
quantization, jpeg_start_decompress() will do everything needed before data
kusano 7d535a
output can begin.  In this case jpeg_start_decompress() may take quite a while
kusano 7d535a
to complete.  With a single-scan (non progressive) JPEG file and default
kusano 7d535a
decompression parameters, this will not happen; jpeg_start_decompress() will
kusano 7d535a
return quickly.
kusano 7d535a
kusano 7d535a
After this call, the final output image dimensions, including any requested
kusano 7d535a
scaling, are available in the JPEG object; so is the selected colormap, if
kusano 7d535a
colormapped output has been requested.  Useful fields include
kusano 7d535a
kusano 7d535a
	output_width		image width and height, as scaled
kusano 7d535a
	output_height
kusano 7d535a
	out_color_components	# of color components in out_color_space
kusano 7d535a
	output_components	# of color components returned per pixel
kusano 7d535a
	colormap		the selected colormap, if any
kusano 7d535a
	actual_number_of_colors		number of entries in colormap
kusano 7d535a
kusano 7d535a
output_components is 1 (a colormap index) when quantizing colors; otherwise it
kusano 7d535a
equals out_color_components.  It is the number of JSAMPLE values that will be
kusano 7d535a
emitted per pixel in the output arrays.
kusano 7d535a
kusano 7d535a
Typically you will need to allocate data buffers to hold the incoming image.
kusano 7d535a
You will need output_width * output_components JSAMPLEs per scanline in your
kusano 7d535a
output buffer, and a total of output_height scanlines will be returned.
kusano 7d535a
kusano 7d535a
Note: if you are using the JPEG library's internal memory manager to allocate
kusano 7d535a
data buffers (as djpeg does), then the manager's protocol requires that you
kusano 7d535a
request large buffers *before* calling jpeg_start_decompress().  This is a
kusano 7d535a
little tricky since the output_XXX fields are not normally valid then.  You
kusano 7d535a
can make them valid by calling jpeg_calc_output_dimensions() after setting the
kusano 7d535a
relevant parameters (scaling, output color space, and quantization flag).
kusano 7d535a
kusano 7d535a
kusano 7d535a
6. while (scan lines remain to be read)
kusano 7d535a
	jpeg_read_scanlines(...);
kusano 7d535a
kusano 7d535a
Now you can read the decompressed image data by calling jpeg_read_scanlines()
kusano 7d535a
one or more times.  At each call, you pass in the maximum number of scanlines
kusano 7d535a
to be read (ie, the height of your working buffer); jpeg_read_scanlines()
kusano 7d535a
will return up to that many lines.  The return value is the number of lines
kusano 7d535a
actually read.  The format of the returned data is discussed under "Data
kusano 7d535a
formats", above.  Don't forget that grayscale and color JPEGs will return
kusano 7d535a
different data formats!
kusano 7d535a
kusano 7d535a
Image data is returned in top-to-bottom scanline order.  If you must write
kusano 7d535a
out the image in bottom-to-top order, you can use the JPEG library's virtual
kusano 7d535a
array mechanism to invert the data efficiently.  Examples of this can be
kusano 7d535a
found in the sample application djpeg.
kusano 7d535a
kusano 7d535a
The library maintains a count of the number of scanlines returned so far
kusano 7d535a
in the output_scanline field of the JPEG object.  Usually you can just use
kusano 7d535a
this variable as the loop counter, so that the loop test looks like
kusano 7d535a
"while (cinfo.output_scanline < cinfo.output_height)".  (Note that the test
kusano 7d535a
should NOT be against image_height, unless you never use scaling.  The
kusano 7d535a
image_height field is the height of the original unscaled image.)
kusano 7d535a
The return value always equals the change in the value of output_scanline.
kusano 7d535a
kusano 7d535a
If you don't use a suspending data source, it is safe to assume that
kusano 7d535a
jpeg_read_scanlines() reads at least one scanline per call, until the
kusano 7d535a
bottom of the image has been reached.
kusano 7d535a
kusano 7d535a
If you use a buffer larger than one scanline, it is NOT safe to assume that
kusano 7d535a
jpeg_read_scanlines() fills it.  (The current implementation returns only a
kusano 7d535a
few scanlines per call, no matter how large a buffer you pass.)  So you must
kusano 7d535a
always provide a loop that calls jpeg_read_scanlines() repeatedly until the
kusano 7d535a
whole image has been read.
kusano 7d535a
kusano 7d535a
kusano 7d535a
7. jpeg_finish_decompress(...);
kusano 7d535a
kusano 7d535a
After all the image data has been read, call jpeg_finish_decompress() to
kusano 7d535a
complete the decompression cycle.  This causes working memory associated
kusano 7d535a
with the JPEG object to be released.
kusano 7d535a
kusano 7d535a
Typical code:
kusano 7d535a
kusano 7d535a
	jpeg_finish_decompress(&cinfo);
kusano 7d535a
kusano 7d535a
If using the stdio source manager, don't forget to close the source stdio
kusano 7d535a
stream if necessary.
kusano 7d535a
kusano 7d535a
It is an error to call jpeg_finish_decompress() before reading the correct
kusano 7d535a
total number of scanlines.  If you wish to abort decompression, call
kusano 7d535a
jpeg_abort() as discussed below.
kusano 7d535a
kusano 7d535a
After completing a decompression cycle, you may dispose of the JPEG object as
kusano 7d535a
discussed next, or you may use it to decompress another image.  In that case
kusano 7d535a
return to step 2 or 3 as appropriate.  If you do not change the source
kusano 7d535a
manager, the next image will be read from the same source.
kusano 7d535a
kusano 7d535a
kusano 7d535a
8. Release the JPEG decompression object.
kusano 7d535a
kusano 7d535a
When you are done with a JPEG decompression object, destroy it by calling
kusano 7d535a
jpeg_destroy_decompress() or jpeg_destroy().  The previous discussion of
kusano 7d535a
destroying compression objects applies here too.
kusano 7d535a
kusano 7d535a
Typical code:
kusano 7d535a
kusano 7d535a
	jpeg_destroy_decompress(&cinfo);
kusano 7d535a
kusano 7d535a
kusano 7d535a
9. Aborting.
kusano 7d535a
kusano 7d535a
You can abort a decompression cycle by calling jpeg_destroy_decompress() or
kusano 7d535a
jpeg_destroy() if you don't need the JPEG object any more, or
kusano 7d535a
jpeg_abort_decompress() or jpeg_abort() if you want to reuse the object.
kusano 7d535a
The previous discussion of aborting compression cycles applies here too.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Mechanics of usage: include files, linking, etc
kusano 7d535a
-----------------------------------------------
kusano 7d535a
kusano 7d535a
Applications using the JPEG library should include the header file jpeglib.h
kusano 7d535a
to obtain declarations of data types and routines.  Before including
kusano 7d535a
jpeglib.h, include system headers that define at least the typedefs FILE and
kusano 7d535a
size_t.  On ANSI-conforming systems, including <stdio.h> is sufficient; on
kusano 7d535a
older Unix systems, you may need <sys/types.h> to define size_t.
kusano 7d535a
kusano 7d535a
If the application needs to refer to individual JPEG library error codes, also
kusano 7d535a
include jerror.h to define those symbols.
kusano 7d535a
kusano 7d535a
jpeglib.h indirectly includes the files jconfig.h and jmorecfg.h.  If you are
kusano 7d535a
installing the JPEG header files in a system directory, you will want to
kusano 7d535a
install all four files: jpeglib.h, jerror.h, jconfig.h, jmorecfg.h.
kusano 7d535a
kusano 7d535a
The most convenient way to include the JPEG code into your executable program
kusano 7d535a
is to prepare a library file ("libjpeg.a", or a corresponding name on non-Unix
kusano 7d535a
machines) and reference it at your link step.  If you use only half of the
kusano 7d535a
library (only compression or only decompression), only that much code will be
kusano 7d535a
included from the library, unless your linker is hopelessly brain-damaged.
kusano 7d535a
The supplied makefiles build libjpeg.a automatically (see install.txt).
kusano 7d535a
kusano 7d535a
While you can build the JPEG library as a shared library if the whim strikes
kusano 7d535a
you, we don't really recommend it.  The trouble with shared libraries is that
kusano 7d535a
at some point you'll probably try to substitute a new version of the library
kusano 7d535a
without recompiling the calling applications.  That generally doesn't work
kusano 7d535a
because the parameter struct declarations usually change with each new
kusano 7d535a
version.  In other words, the library's API is *not* guaranteed binary
kusano 7d535a
compatible across versions; we only try to ensure source-code compatibility.
kusano 7d535a
(In hindsight, it might have been smarter to hide the parameter structs from
kusano 7d535a
applications and introduce a ton of access functions instead.  Too late now,
kusano 7d535a
however.)
kusano 7d535a
kusano 7d535a
On some systems your application may need to set up a signal handler to ensure
kusano 7d535a
that temporary files are deleted if the program is interrupted.  This is most
kusano 7d535a
critical if you are on MS-DOS and use the jmemdos.c memory manager back end;
kusano 7d535a
it will try to grab extended memory for temp files, and that space will NOT be
kusano 7d535a
freed automatically.  See cjpeg.c or djpeg.c for an example signal handler.
kusano 7d535a
kusano 7d535a
It may be worth pointing out that the core JPEG library does not actually
kusano 7d535a
require the stdio library: only the default source/destination managers and
kusano 7d535a
error handler need it.  You can use the library in a stdio-less environment
kusano 7d535a
if you replace those modules and use jmemnobs.c (or another memory manager of
kusano 7d535a
your own devising).  More info about the minimum system library requirements
kusano 7d535a
may be found in jinclude.h.
kusano 7d535a
kusano 7d535a
kusano 7d535a
ADVANCED FEATURES
kusano 7d535a
=================
kusano 7d535a
kusano 7d535a
Compression parameter selection
kusano 7d535a
-------------------------------
kusano 7d535a
kusano 7d535a
This section describes all the optional parameters you can set for JPEG
kusano 7d535a
compression, as well as the "helper" routines provided to assist in this
kusano 7d535a
task.  Proper setting of some parameters requires detailed understanding
kusano 7d535a
of the JPEG standard; if you don't know what a parameter is for, it's best
kusano 7d535a
not to mess with it!  See REFERENCES in the README file for pointers to
kusano 7d535a
more info about JPEG.
kusano 7d535a
kusano 7d535a
It's a good idea to call jpeg_set_defaults() first, even if you plan to set
kusano 7d535a
all the parameters; that way your code is more likely to work with future JPEG
kusano 7d535a
libraries that have additional parameters.  For the same reason, we recommend
kusano 7d535a
you use a helper routine where one is provided, in preference to twiddling
kusano 7d535a
cinfo fields directly.
kusano 7d535a
kusano 7d535a
The helper routines are:
kusano 7d535a
kusano 7d535a
jpeg_set_defaults (j_compress_ptr cinfo)
kusano 7d535a
	This routine sets all JPEG parameters to reasonable defaults, using
kusano 7d535a
	only the input image's color space (field in_color_space, which must
kusano 7d535a
	already be set in cinfo).  Many applications will only need to use
kusano 7d535a
	this routine and perhaps jpeg_set_quality().
kusano 7d535a
kusano 7d535a
jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
kusano 7d535a
	Sets the JPEG file's colorspace (field jpeg_color_space) as specified,
kusano 7d535a
	and sets other color-space-dependent parameters appropriately.  See
kusano 7d535a
	"Special color spaces", below, before using this.  A large number of
kusano 7d535a
	parameters, including all per-component parameters, are set by this
kusano 7d535a
	routine; if you want to twiddle individual parameters you should call
kusano 7d535a
	jpeg_set_colorspace() before rather than after.
kusano 7d535a
kusano 7d535a
jpeg_default_colorspace (j_compress_ptr cinfo)
kusano 7d535a
	Selects an appropriate JPEG colorspace based on cinfo->in_color_space,
kusano 7d535a
	and calls jpeg_set_colorspace().  This is actually a subroutine of
kusano 7d535a
	jpeg_set_defaults().  It's broken out in case you want to change
kusano 7d535a
	just the colorspace-dependent JPEG parameters.
kusano 7d535a
kusano 7d535a
jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
kusano 7d535a
	Constructs JPEG quantization tables appropriate for the indicated
kusano 7d535a
	quality setting.  The quality value is expressed on the 0..100 scale
kusano 7d535a
	recommended by IJG (cjpeg's "-quality" switch uses this routine).
kusano 7d535a
	Note that the exact mapping from quality values to tables may change
kusano 7d535a
	in future IJG releases as more is learned about DCT quantization.
kusano 7d535a
	If the force_baseline parameter is TRUE, then the quantization table
kusano 7d535a
	entries are constrained to the range 1..255 for full JPEG baseline
kusano 7d535a
	compatibility.  In the current implementation, this only makes a
kusano 7d535a
	difference for quality settings below 25, and it effectively prevents
kusano 7d535a
	very small/low quality files from being generated.  The IJG decoder
kusano 7d535a
	is capable of reading the non-baseline files generated at low quality
kusano 7d535a
	settings when force_baseline is FALSE, but other decoders may not be.
kusano 7d535a
kusano 7d535a
jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
kusano 7d535a
			 boolean force_baseline)
kusano 7d535a
	Same as jpeg_set_quality() except that the generated tables are the
kusano 7d535a
	sample tables given in the JPEC spec section K.1, multiplied by the
kusano 7d535a
	specified scale factor (which is expressed as a percentage; thus
kusano 7d535a
	scale_factor = 100 reproduces the spec's tables).  Note that larger
kusano 7d535a
	scale factors give lower quality.  This entry point is useful for
kusano 7d535a
	conforming to the Adobe PostScript DCT conventions, but we do not
kusano 7d535a
	recommend linear scaling as a user-visible quality scale otherwise.
kusano 7d535a
	force_baseline again constrains the computed table entries to 1..255.
kusano 7d535a
kusano 7d535a
int jpeg_quality_scaling (int quality)
kusano 7d535a
	Converts a value on the IJG-recommended quality scale to a linear
kusano 7d535a
	scaling percentage.  Note that this routine may change or go away
kusano 7d535a
	in future releases --- IJG may choose to adopt a scaling method that
kusano 7d535a
	can't be expressed as a simple scalar multiplier, in which case the
kusano 7d535a
	premise of this routine collapses.  Caveat user.
kusano 7d535a
kusano 7d535a
jpeg_default_qtables (j_compress_ptr cinfo, boolean force_baseline)
kusano 7d535a
	Set default quantization tables with linear q_scale_factor[] values
kusano 7d535a
	(see below).
kusano 7d535a
kusano 7d535a
jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
kusano 7d535a
		      const unsigned int *basic_table,
kusano 7d535a
		      int scale_factor, boolean force_baseline)
kusano 7d535a
	Allows an arbitrary quantization table to be created.  which_tbl
kusano 7d535a
	indicates which table slot to fill.  basic_table points to an array
kusano 7d535a
	of 64 unsigned ints given in normal array order.  These values are
kusano 7d535a
	multiplied by scale_factor/100 and then clamped to the range 1..65535
kusano 7d535a
	(or to 1..255 if force_baseline is TRUE).
kusano 7d535a
	CAUTION: prior to library version 6a, jpeg_add_quant_table expected
kusano 7d535a
	the basic table to be given in JPEG zigzag order.  If you need to
kusano 7d535a
	write code that works with either older or newer versions of this
kusano 7d535a
	routine, you must check the library version number.  Something like
kusano 7d535a
	"#if JPEG_LIB_VERSION >= 61" is the right test.
kusano 7d535a
kusano 7d535a
jpeg_simple_progression (j_compress_ptr cinfo)
kusano 7d535a
	Generates a default scan script for writing a progressive-JPEG file.
kusano 7d535a
	This is the recommended method of creating a progressive file,
kusano 7d535a
	unless you want to make a custom scan sequence.  You must ensure that
kusano 7d535a
	the JPEG color space is set correctly before calling this routine.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Compression parameters (cinfo fields) include:
kusano 7d535a
kusano 7d535a
boolean arith_code
kusano 7d535a
	If TRUE, use arithmetic coding.
kusano 7d535a
	If FALSE, use Huffman coding.
kusano 7d535a
kusano 7d535a
int block_size
kusano 7d535a
	Set DCT block size.  All N from 1 to 16 are possible.
kusano 7d535a
	Default is 8 (baseline format).
kusano 7d535a
	Larger values produce higher compression,
kusano 7d535a
	smaller values produce higher quality.
kusano 7d535a
	An exact DCT stage is possible with 1 or 2.
kusano 7d535a
	With the default quality of 75 and default Luminance qtable
kusano 7d535a
	the DCT+Quantization stage is lossless for value 1.
kusano 7d535a
	Note that values other than 8 require a SmartScale capable decoder,
kusano 7d535a
	introduced with IJG JPEG 8.  Setting the block_size parameter for
kusano 7d535a
	compression works with version 8c and later.
kusano 7d535a
kusano 7d535a
J_DCT_METHOD dct_method
kusano 7d535a
	Selects the algorithm used for the DCT step.  Choices are:
kusano 7d535a
		JDCT_ISLOW: slow but accurate integer algorithm
kusano 7d535a
		JDCT_IFAST: faster, less accurate integer method
kusano 7d535a
		JDCT_FLOAT: floating-point method
kusano 7d535a
		JDCT_DEFAULT: default method (normally JDCT_ISLOW)
kusano 7d535a
		JDCT_FASTEST: fastest method (normally JDCT_IFAST)
kusano 7d535a
	The FLOAT method is very slightly more accurate than the ISLOW method,
kusano 7d535a
	but may give different results on different machines due to varying
kusano 7d535a
	roundoff behavior.  The integer methods should give the same results
kusano 7d535a
	on all machines.  On machines with sufficiently fast FP hardware, the
kusano 7d535a
	floating-point method may also be the fastest.  The IFAST method is
kusano 7d535a
	considerably less accurate than the other two; its use is not
kusano 7d535a
	recommended if high quality is a concern.  JDCT_DEFAULT and
kusano 7d535a
	JDCT_FASTEST are macros configurable by each installation.
kusano 7d535a
kusano 7d535a
unsigned int scale_num, scale_denom
kusano 7d535a
	Scale the image by the fraction scale_num/scale_denom.  Default is
kusano 7d535a
	1/1, or no scaling.  Currently, the supported scaling ratios are
kusano 7d535a
	M/N with all N from 1 to 16, where M is the destination DCT size,
kusano 7d535a
	which is 8 by default (see block_size parameter above).
kusano 7d535a
	(The library design allows for arbitrary scaling ratios but this
kusano 7d535a
	is not likely to be implemented any time soon.)
kusano 7d535a
kusano 7d535a
J_COLOR_SPACE jpeg_color_space
kusano 7d535a
int num_components
kusano 7d535a
	The JPEG color space and corresponding number of components; see
kusano 7d535a
	"Special color spaces", below, for more info.  We recommend using
kusano 7d535a
	jpeg_set_colorspace() if you want to change these.
kusano 7d535a
kusano 7d535a
J_COLOR_TRANSFORM color_transform
kusano 7d535a
	Internal color transform identifier, writes LSE marker if nonzero
kusano 7d535a
	(requires decoder with inverse color transform support, introduced
kusano 7d535a
	with IJG JPEG 9).
kusano 7d535a
	Two values are currently possible: JCT_NONE and JCT_SUBTRACT_GREEN.
kusano 7d535a
	Set this value for lossless RGB application *before* calling
kusano 7d535a
	jpeg_set_colorspace(), because entropy table assignment in
kusano 7d535a
	jpeg_set_colorspace() depends on color_transform.
kusano 7d535a
kusano 7d535a
boolean optimize_coding
kusano 7d535a
	TRUE causes the compressor to compute optimal Huffman coding tables
kusano 7d535a
	for the image.  This requires an extra pass over the data and
kusano 7d535a
	therefore costs a good deal of space and time.  The default is
kusano 7d535a
	FALSE, which tells the compressor to use the supplied or default
kusano 7d535a
	Huffman tables.  In most cases optimal tables save only a few percent
kusano 7d535a
	of file size compared to the default tables.  Note that when this is
kusano 7d535a
	TRUE, you need not supply Huffman tables at all, and any you do
kusano 7d535a
	supply will be overwritten.
kusano 7d535a
kusano 7d535a
unsigned int restart_interval
kusano 7d535a
int restart_in_rows
kusano 7d535a
	To emit restart markers in the JPEG file, set one of these nonzero.
kusano 7d535a
	Set restart_interval to specify the exact interval in MCU blocks.
kusano 7d535a
	Set restart_in_rows to specify the interval in MCU rows.  (If
kusano 7d535a
	restart_in_rows is not 0, then restart_interval is set after the
kusano 7d535a
	image width in MCUs is computed.)  Defaults are zero (no restarts).
kusano 7d535a
	One restart marker per MCU row is often a good choice.
kusano 7d535a
	NOTE: the overhead of restart markers is higher in grayscale JPEG
kusano 7d535a
	files than in color files, and MUCH higher in progressive JPEGs.
kusano 7d535a
	If you use restarts, you may want to use larger intervals in those
kusano 7d535a
	cases.
kusano 7d535a
kusano 7d535a
const jpeg_scan_info * scan_info
kusano 7d535a
int num_scans
kusano 7d535a
	By default, scan_info is NULL; this causes the compressor to write a
kusano 7d535a
	single-scan sequential JPEG file.  If not NULL, scan_info points to
kusano 7d535a
	an array of scan definition records of length num_scans.  The
kusano 7d535a
	compressor will then write a JPEG file having one scan for each scan
kusano 7d535a
	definition record.  This is used to generate noninterleaved or
kusano 7d535a
	progressive JPEG files.  The library checks that the scan array
kusano 7d535a
	defines a valid JPEG scan sequence.  (jpeg_simple_progression creates
kusano 7d535a
	a suitable scan definition array for progressive JPEG.)  This is
kusano 7d535a
	discussed further under "Progressive JPEG support".
kusano 7d535a
kusano 7d535a
boolean do_fancy_downsampling
kusano 7d535a
	If TRUE, use direct DCT scaling with DCT size > 8 for downsampling
kusano 7d535a
	of chroma components.
kusano 7d535a
	If FALSE, use only DCT size <= 8 and simple separate downsampling.
kusano 7d535a
	Default is TRUE.
kusano 7d535a
	For better image stability in multiple generation compression cycles
kusano 7d535a
	it is preferable that this value matches the corresponding
kusano 7d535a
	do_fancy_upsampling value in decompression.
kusano 7d535a
kusano 7d535a
int smoothing_factor
kusano 7d535a
	If non-zero, the input image is smoothed; the value should be 1 for
kusano 7d535a
	minimal smoothing to 100 for maximum smoothing.  Consult jcsample.c
kusano 7d535a
	for details of the smoothing algorithm.  The default is zero.
kusano 7d535a
kusano 7d535a
boolean write_JFIF_header
kusano 7d535a
	If TRUE, a JFIF APP0 marker is emitted.  jpeg_set_defaults() and
kusano 7d535a
	jpeg_set_colorspace() set this TRUE if a JFIF-legal JPEG color space
kusano 7d535a
	(ie, YCbCr or grayscale) is selected, otherwise FALSE.
kusano 7d535a
kusano 7d535a
UINT8 JFIF_major_version
kusano 7d535a
UINT8 JFIF_minor_version
kusano 7d535a
	The version number to be written into the JFIF marker.
kusano 7d535a
	jpeg_set_defaults() initializes the version to 1.01 (major=minor=1).
kusano 7d535a
	You should set it to 1.02 (major=1, minor=2) if you plan to write
kusano 7d535a
	any JFIF 1.02 extension markers.
kusano 7d535a
kusano 7d535a
UINT8 density_unit
kusano 7d535a
UINT16 X_density
kusano 7d535a
UINT16 Y_density
kusano 7d535a
	The resolution information to be written into the JFIF marker;
kusano 7d535a
	not used otherwise.  density_unit may be 0 for unknown,
kusano 7d535a
	1 for dots/inch, or 2 for dots/cm.  The default values are 0,1,1
kusano 7d535a
	indicating square pixels of unknown size.
kusano 7d535a
kusano 7d535a
boolean write_Adobe_marker
kusano 7d535a
	If TRUE, an Adobe APP14 marker is emitted.  jpeg_set_defaults() and
kusano 7d535a
	jpeg_set_colorspace() set this TRUE if JPEG color space RGB, CMYK,
kusano 7d535a
	or YCCK is selected, otherwise FALSE.  It is generally a bad idea
kusano 7d535a
	to set both write_JFIF_header and write_Adobe_marker.  In fact,
kusano 7d535a
	you probably shouldn't change the default settings at all --- the
kusano 7d535a
	default behavior ensures that the JPEG file's color space can be
kusano 7d535a
	recognized by the decoder.
kusano 7d535a
kusano 7d535a
JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]
kusano 7d535a
	Pointers to coefficient quantization tables, one per table slot,
kusano 7d535a
	or NULL if no table is defined for a slot.  Usually these should
kusano 7d535a
	be set via one of the above helper routines; jpeg_add_quant_table()
kusano 7d535a
	is general enough to define any quantization table.  The other
kusano 7d535a
	routines will set up table slot 0 for luminance quality and table
kusano 7d535a
	slot 1 for chrominance.
kusano 7d535a
kusano 7d535a
int q_scale_factor[NUM_QUANT_TBLS]
kusano 7d535a
	Linear quantization scaling factors (percentage, initialized 100)
kusano 7d535a
	for use with jpeg_default_qtables().
kusano 7d535a
	See rdswitch.c and cjpeg.c for an example of usage.
kusano 7d535a
	Note that the q_scale_factor[] fields are the "linear" scales, so you
kusano 7d535a
	have to convert from user-defined ratings via jpeg_quality_scaling().
kusano 7d535a
	Here is an example code which corresponds to cjpeg -quality 90,70:
kusano 7d535a
kusano 7d535a
		jpeg_set_defaults(cinfo);
kusano 7d535a
kusano 7d535a
		/* Set luminance quality 90. */
kusano 7d535a
		cinfo->q_scale_factor[0] = jpeg_quality_scaling(90);
kusano 7d535a
		/* Set chrominance quality 70. */
kusano 7d535a
		cinfo->q_scale_factor[1] = jpeg_quality_scaling(70);
kusano 7d535a
kusano 7d535a
		jpeg_default_qtables(cinfo, force_baseline);
kusano 7d535a
kusano 7d535a
	CAUTION: You must also set 1x1 subsampling for efficient separate
kusano 7d535a
	color quality selection, since the default value used by library
kusano 7d535a
	is 2x2:
kusano 7d535a
kusano 7d535a
		cinfo->comp_info[0].v_samp_factor = 1;
kusano 7d535a
		cinfo->comp_info[0].h_samp_factor = 1;
kusano 7d535a
kusano 7d535a
JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]
kusano 7d535a
JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]
kusano 7d535a
	Pointers to Huffman coding tables, one per table slot, or NULL if
kusano 7d535a
	no table is defined for a slot.  Slots 0 and 1 are filled with the
kusano 7d535a
	JPEG sample tables by jpeg_set_defaults().  If you need to allocate
kusano 7d535a
	more table structures, jpeg_alloc_huff_table() may be used.
kusano 7d535a
	Note that optimal Huffman tables can be computed for an image
kusano 7d535a
	by setting optimize_coding, as discussed above; there's seldom
kusano 7d535a
	any need to mess with providing your own Huffman tables.
kusano 7d535a
kusano 7d535a
kusano 7d535a
The actual dimensions of the JPEG image that will be written to the file are
kusano 7d535a
given by the following fields.  These are computed from the input image
kusano 7d535a
dimensions and the compression parameters by jpeg_start_compress().  You can
kusano 7d535a
also call jpeg_calc_jpeg_dimensions() to obtain the values that will result
kusano 7d535a
from the current parameter settings.  This can be useful if you are trying
kusano 7d535a
to pick a scaling ratio that will get close to a desired target size.
kusano 7d535a
kusano 7d535a
JDIMENSION jpeg_width		Actual dimensions of output image.
kusano 7d535a
JDIMENSION jpeg_height
kusano 7d535a
kusano 7d535a
kusano 7d535a
Per-component parameters are stored in the struct cinfo.comp_info[i] for
kusano 7d535a
component number i.  Note that components here refer to components of the
kusano 7d535a
JPEG color space, *not* the source image color space.  A suitably large
kusano 7d535a
comp_info[] array is allocated by jpeg_set_defaults(); if you choose not
kusano 7d535a
to use that routine, it's up to you to allocate the array.
kusano 7d535a
kusano 7d535a
int component_id
kusano 7d535a
	The one-byte identifier code to be recorded in the JPEG file for
kusano 7d535a
	this component.  For the standard color spaces, we recommend you
kusano 7d535a
	leave the default values alone.
kusano 7d535a
kusano 7d535a
int h_samp_factor
kusano 7d535a
int v_samp_factor
kusano 7d535a
	Horizontal and vertical sampling factors for the component; must
kusano 7d535a
	be 1..4 according to the JPEG standard.  Note that larger sampling
kusano 7d535a
	factors indicate a higher-resolution component; many people find
kusano 7d535a
	this behavior quite unintuitive.  The default values are 2,2 for
kusano 7d535a
	luminance components and 1,1 for chrominance components, except
kusano 7d535a
	for grayscale where 1,1 is used.
kusano 7d535a
kusano 7d535a
int quant_tbl_no
kusano 7d535a
	Quantization table number for component.  The default value is
kusano 7d535a
	0 for luminance components and 1 for chrominance components.
kusano 7d535a
kusano 7d535a
int dc_tbl_no
kusano 7d535a
int ac_tbl_no
kusano 7d535a
	DC and AC entropy coding table numbers.  The default values are
kusano 7d535a
	0 for luminance components and 1 for chrominance components.
kusano 7d535a
kusano 7d535a
int component_index
kusano 7d535a
	Must equal the component's index in comp_info[].  (Beginning in
kusano 7d535a
	release v6, the compressor library will fill this in automatically;
kusano 7d535a
	you don't have to.)
kusano 7d535a
kusano 7d535a
kusano 7d535a
Decompression parameter selection
kusano 7d535a
---------------------------------
kusano 7d535a
kusano 7d535a
Decompression parameter selection is somewhat simpler than compression
kusano 7d535a
parameter selection, since all of the JPEG internal parameters are
kusano 7d535a
recorded in the source file and need not be supplied by the application.
kusano 7d535a
(Unless you are working with abbreviated files, in which case see
kusano 7d535a
"Abbreviated datastreams", below.)  Decompression parameters control
kusano 7d535a
the postprocessing done on the image to deliver it in a format suitable
kusano 7d535a
for the application's use.  Many of the parameters control speed/quality
kusano 7d535a
tradeoffs, in which faster decompression may be obtained at the price of
kusano 7d535a
a poorer-quality image.  The defaults select the highest quality (slowest)
kusano 7d535a
processing.
kusano 7d535a
kusano 7d535a
The following fields in the JPEG object are set by jpeg_read_header() and
kusano 7d535a
may be useful to the application in choosing decompression parameters:
kusano 7d535a
kusano 7d535a
JDIMENSION image_width			Width and height of image
kusano 7d535a
JDIMENSION image_height
kusano 7d535a
int num_components			Number of color components
kusano 7d535a
J_COLOR_SPACE jpeg_color_space		Colorspace of image
kusano 7d535a
boolean saw_JFIF_marker			TRUE if a JFIF APP0 marker was seen
kusano 7d535a
  UINT8 JFIF_major_version		Version information from JFIF marker
kusano 7d535a
  UINT8 JFIF_minor_version
kusano 7d535a
  UINT8 density_unit			Resolution data from JFIF marker
kusano 7d535a
  UINT16 X_density
kusano 7d535a
  UINT16 Y_density
kusano 7d535a
boolean saw_Adobe_marker		TRUE if an Adobe APP14 marker was seen
kusano 7d535a
  UINT8 Adobe_transform			Color transform code from Adobe marker
kusano 7d535a
kusano 7d535a
The JPEG color space, unfortunately, is something of a guess since the JPEG
kusano 7d535a
standard proper does not provide a way to record it.  In practice most files
kusano 7d535a
adhere to the JFIF or Adobe conventions, and the decoder will recognize these
kusano 7d535a
correctly.  See "Special color spaces", below, for more info.
kusano 7d535a
kusano 7d535a
kusano 7d535a
The decompression parameters that determine the basic properties of the
kusano 7d535a
returned image are:
kusano 7d535a
kusano 7d535a
J_COLOR_SPACE out_color_space
kusano 7d535a
	Output color space.  jpeg_read_header() sets an appropriate default
kusano 7d535a
	based on jpeg_color_space; typically it will be RGB or grayscale.
kusano 7d535a
	The application can change this field to request output in a different
kusano 7d535a
	colorspace.  For example, set it to JCS_GRAYSCALE to get grayscale
kusano 7d535a
	output from a color file.  (This is useful for previewing: grayscale
kusano 7d535a
	output is faster than full color since the color components need not
kusano 7d535a
	be processed.)  Note that not all possible color space transforms are
kusano 7d535a
	currently implemented; you may need to extend jdcolor.c if you want an
kusano 7d535a
	unusual conversion.
kusano 7d535a
kusano 7d535a
unsigned int scale_num, scale_denom
kusano 7d535a
	Scale the image by the fraction scale_num/scale_denom.  Currently,
kusano 7d535a
	the supported scaling ratios are M/N with all M from 1 to 16, where
kusano 7d535a
	N is the source DCT size, which is 8 for baseline JPEG.  (The library
kusano 7d535a
	design allows for arbitrary scaling ratios but this is not likely
kusano 7d535a
	to be implemented any time soon.)  The values are initialized by
kusano 7d535a
	jpeg_read_header() with the source DCT size.  For baseline JPEG
kusano 7d535a
	this is 8/8.  If you change only the scale_num value while leaving
kusano 7d535a
	the other unchanged, then this specifies the DCT scaled size to be
kusano 7d535a
	applied on the given input.  For baseline JPEG this is equivalent
kusano 7d535a
	to M/8 scaling, since the source DCT size for baseline JPEG is 8.
kusano 7d535a
	Smaller scaling ratios permit significantly faster decoding since
kusano 7d535a
	fewer pixels need be processed and a simpler IDCT method can be used.
kusano 7d535a
kusano 7d535a
boolean quantize_colors
kusano 7d535a
	If set TRUE, colormapped output will be delivered.  Default is FALSE,
kusano 7d535a
	meaning that full-color output will be delivered.
kusano 7d535a
kusano 7d535a
The next three parameters are relevant only if quantize_colors is TRUE.
kusano 7d535a
kusano 7d535a
int desired_number_of_colors
kusano 7d535a
	Maximum number of colors to use in generating a library-supplied color
kusano 7d535a
	map (the actual number of colors is returned in a different field).
kusano 7d535a
	Default 256.  Ignored when the application supplies its own color map.
kusano 7d535a
kusano 7d535a
boolean two_pass_quantize
kusano 7d535a
	If TRUE, an extra pass over the image is made to select a custom color
kusano 7d535a
	map for the image.  This usually looks a lot better than the one-size-
kusano 7d535a
	fits-all colormap that is used otherwise.  Default is TRUE.  Ignored
kusano 7d535a
	when the application supplies its own color map.
kusano 7d535a
kusano 7d535a
J_DITHER_MODE dither_mode
kusano 7d535a
	Selects color dithering method.  Supported values are:
kusano 7d535a
		JDITHER_NONE	no dithering: fast, very low quality
kusano 7d535a
		JDITHER_ORDERED	ordered dither: moderate speed and quality
kusano 7d535a
		JDITHER_FS	Floyd-Steinberg dither: slow, high quality
kusano 7d535a
	Default is JDITHER_FS.  (At present, ordered dither is implemented
kusano 7d535a
	only in the single-pass, standard-colormap case.  If you ask for
kusano 7d535a
	ordered dither when two_pass_quantize is TRUE or when you supply
kusano 7d535a
	an external color map, you'll get F-S dithering.)
kusano 7d535a
kusano 7d535a
When quantize_colors is TRUE, the target color map is described by the next
kusano 7d535a
two fields.  colormap is set to NULL by jpeg_read_header().  The application
kusano 7d535a
can supply a color map by setting colormap non-NULL and setting
kusano 7d535a
actual_number_of_colors to the map size.  Otherwise, jpeg_start_decompress()
kusano 7d535a
selects a suitable color map and sets these two fields itself.
kusano 7d535a
[Implementation restriction: at present, an externally supplied colormap is
kusano 7d535a
only accepted for 3-component output color spaces.]
kusano 7d535a
kusano 7d535a
JSAMPARRAY colormap
kusano 7d535a
	The color map, represented as a 2-D pixel array of out_color_components
kusano 7d535a
	rows and actual_number_of_colors columns.  Ignored if not quantizing.
kusano 7d535a
	CAUTION: if the JPEG library creates its own colormap, the storage
kusano 7d535a
	pointed to by this field is released by jpeg_finish_decompress().
kusano 7d535a
	Copy the colormap somewhere else first, if you want to save it.
kusano 7d535a
kusano 7d535a
int actual_number_of_colors
kusano 7d535a
	The number of colors in the color map.
kusano 7d535a
kusano 7d535a
Additional decompression parameters that the application may set include:
kusano 7d535a
kusano 7d535a
J_DCT_METHOD dct_method
kusano 7d535a
	Selects the algorithm used for the DCT step.  Choices are the same
kusano 7d535a
	as described above for compression.
kusano 7d535a
kusano 7d535a
boolean do_fancy_upsampling
kusano 7d535a
	If TRUE, use direct DCT scaling with DCT size > 8 for upsampling
kusano 7d535a
	of chroma components.
kusano 7d535a
	If FALSE, use only DCT size <= 8 and simple separate upsampling.
kusano 7d535a
	Default is TRUE.
kusano 7d535a
	For better image stability in multiple generation compression cycles
kusano 7d535a
	it is preferable that this value matches the corresponding
kusano 7d535a
	do_fancy_downsampling value in compression.
kusano 7d535a
kusano 7d535a
boolean do_block_smoothing
kusano 7d535a
	If TRUE, interblock smoothing is applied in early stages of decoding
kusano 7d535a
	progressive JPEG files; if FALSE, not.  Default is TRUE.  Early
kusano 7d535a
	progression stages look "fuzzy" with smoothing, "blocky" without.
kusano 7d535a
	In any case, block smoothing ceases to be applied after the first few
kusano 7d535a
	AC coefficients are known to full accuracy, so it is relevant only
kusano 7d535a
	when using buffered-image mode for progressive images.
kusano 7d535a
kusano 7d535a
boolean enable_1pass_quant
kusano 7d535a
boolean enable_external_quant
kusano 7d535a
boolean enable_2pass_quant
kusano 7d535a
	These are significant only in buffered-image mode, which is
kusano 7d535a
	described in its own section below.
kusano 7d535a
kusano 7d535a
kusano 7d535a
The output image dimensions are given by the following fields.  These are
kusano 7d535a
computed from the source image dimensions and the decompression parameters
kusano 7d535a
by jpeg_start_decompress().  You can also call jpeg_calc_output_dimensions()
kusano 7d535a
to obtain the values that will result from the current parameter settings.
kusano 7d535a
This can be useful if you are trying to pick a scaling ratio that will get
kusano 7d535a
close to a desired target size.  It's also important if you are using the
kusano 7d535a
JPEG library's memory manager to allocate output buffer space, because you
kusano 7d535a
are supposed to request such buffers *before* jpeg_start_decompress().
kusano 7d535a
kusano 7d535a
JDIMENSION output_width		Actual dimensions of output image.
kusano 7d535a
JDIMENSION output_height
kusano 7d535a
int out_color_components	Number of color components in out_color_space.
kusano 7d535a
int output_components		Number of color components returned.
kusano 7d535a
int rec_outbuf_height		Recommended height of scanline buffer.
kusano 7d535a
kusano 7d535a
When quantizing colors, output_components is 1, indicating a single color map
kusano 7d535a
index per pixel.  Otherwise it equals out_color_components.  The output arrays
kusano 7d535a
are required to be output_width * output_components JSAMPLEs wide.
kusano 7d535a
kusano 7d535a
rec_outbuf_height is the recommended minimum height (in scanlines) of the
kusano 7d535a
buffer passed to jpeg_read_scanlines().  If the buffer is smaller, the
kusano 7d535a
library will still work, but time will be wasted due to unnecessary data
kusano 7d535a
copying.  In high-quality modes, rec_outbuf_height is always 1, but some
kusano 7d535a
faster, lower-quality modes set it to larger values (typically 2 to 4).
kusano 7d535a
If you are going to ask for a high-speed processing mode, you may as well
kusano 7d535a
go to the trouble of honoring rec_outbuf_height so as to avoid data copying.
kusano 7d535a
(An output buffer larger than rec_outbuf_height lines is OK, but won't
kusano 7d535a
provide any material speed improvement over that height.)
kusano 7d535a
kusano 7d535a
kusano 7d535a
Special color spaces
kusano 7d535a
--------------------
kusano 7d535a
kusano 7d535a
The JPEG standard itself is "color blind" and doesn't specify any particular
kusano 7d535a
color space.  It is customary to convert color data to a luminance/chrominance
kusano 7d535a
color space before compressing, since this permits greater compression.  The
kusano 7d535a
existing de-facto JPEG file format standards specify YCbCr or grayscale data
kusano 7d535a
(JFIF), or grayscale, RGB, YCbCr, CMYK, or YCCK (Adobe).  For special
kusano 7d535a
applications such as multispectral images, other color spaces can be used,
kusano 7d535a
but it must be understood that such files will be unportable.
kusano 7d535a
kusano 7d535a
The JPEG library can handle the most common colorspace conversions (namely
kusano 7d535a
RGB <=> YCbCr and CMYK <=> YCCK).  It can also deal with data of an unknown
kusano 7d535a
color space, passing it through without conversion.  If you deal extensively
kusano 7d535a
with an unusual color space, you can easily extend the library to understand
kusano 7d535a
additional color spaces and perform appropriate conversions.
kusano 7d535a
kusano 7d535a
For compression, the source data's color space is specified by field
kusano 7d535a
in_color_space.  This is transformed to the JPEG file's color space given
kusano 7d535a
by jpeg_color_space.  jpeg_set_defaults() chooses a reasonable JPEG color
kusano 7d535a
space depending on in_color_space, but you can override this by calling
kusano 7d535a
jpeg_set_colorspace().  Of course you must select a supported transformation.
kusano 7d535a
jccolor.c currently supports the following transformations:
kusano 7d535a
	RGB => YCbCr
kusano 7d535a
	RGB => GRAYSCALE
kusano 7d535a
	YCbCr => GRAYSCALE
kusano 7d535a
	CMYK => YCCK
kusano 7d535a
plus the null transforms: GRAYSCALE => GRAYSCALE, RGB => RGB,
kusano 7d535a
YCbCr => YCbCr, CMYK => CMYK, YCCK => YCCK, and UNKNOWN => UNKNOWN.
kusano 7d535a
kusano 7d535a
The de-facto file format standards (JFIF and Adobe) specify APPn markers that
kusano 7d535a
indicate the color space of the JPEG file.  It is important to ensure that
kusano 7d535a
these are written correctly, or omitted if the JPEG file's color space is not
kusano 7d535a
one of the ones supported by the de-facto standards.  jpeg_set_colorspace()
kusano 7d535a
will set the compression parameters to include or omit the APPn markers
kusano 7d535a
properly, so long as it is told the truth about the JPEG color space.
kusano 7d535a
For example, if you are writing some random 3-component color space without
kusano 7d535a
conversion, don't try to fake out the library by setting in_color_space and
kusano 7d535a
jpeg_color_space to JCS_YCbCr; use JCS_UNKNOWN.  You may want to write an
kusano 7d535a
APPn marker of your own devising to identify the colorspace --- see "Special
kusano 7d535a
markers", below.
kusano 7d535a
kusano 7d535a
When told that the color space is UNKNOWN, the library will default to using
kusano 7d535a
luminance-quality compression parameters for all color components.  You may
kusano 7d535a
well want to change these parameters.  See the source code for
kusano 7d535a
jpeg_set_colorspace(), in jcparam.c, for details.
kusano 7d535a
kusano 7d535a
For decompression, the JPEG file's color space is given in jpeg_color_space,
kusano 7d535a
and this is transformed to the output color space out_color_space.
kusano 7d535a
jpeg_read_header's setting of jpeg_color_space can be relied on if the file
kusano 7d535a
conforms to JFIF or Adobe conventions, but otherwise it is no better than a
kusano 7d535a
guess.  If you know the JPEG file's color space for certain, you can override
kusano 7d535a
jpeg_read_header's guess by setting jpeg_color_space.  jpeg_read_header also
kusano 7d535a
selects a default output color space based on (its guess of) jpeg_color_space;
kusano 7d535a
set out_color_space to override this.  Again, you must select a supported
kusano 7d535a
transformation.  jdcolor.c currently supports
kusano 7d535a
	YCbCr => RGB
kusano 7d535a
	YCbCr => GRAYSCALE
kusano 7d535a
	RGB => GRAYSCALE
kusano 7d535a
	GRAYSCALE => RGB
kusano 7d535a
	YCCK => CMYK
kusano 7d535a
as well as the null transforms.  (Since GRAYSCALE=>RGB is provided, an
kusano 7d535a
application can force grayscale JPEGs to look like color JPEGs if it only
kusano 7d535a
wants to handle one case.)
kusano 7d535a
kusano 7d535a
The two-pass color quantizer, jquant2.c, is specialized to handle RGB data
kusano 7d535a
(it weights distances appropriately for RGB colors).  You'll need to modify
kusano 7d535a
the code if you want to use it for non-RGB output color spaces.  Note that
kusano 7d535a
jquant2.c is used to map to an application-supplied colormap as well as for
kusano 7d535a
the normal two-pass colormap selection process.
kusano 7d535a
kusano 7d535a
CAUTION: it appears that Adobe Photoshop writes inverted data in CMYK JPEG
kusano 7d535a
files: 0 represents 100% ink coverage, rather than 0% ink as you'd expect.
kusano 7d535a
This is arguably a bug in Photoshop, but if you need to work with Photoshop
kusano 7d535a
CMYK files, you will have to deal with it in your application.  We cannot
kusano 7d535a
"fix" this in the library by inverting the data during the CMYK<=>YCCK
kusano 7d535a
transform, because that would break other applications, notably Ghostscript.
kusano 7d535a
Photoshop versions prior to 3.0 write EPS files containing JPEG-encoded CMYK
kusano 7d535a
data in the same inverted-YCCK representation used in bare JPEG files, but
kusano 7d535a
the surrounding PostScript code performs an inversion using the PS image
kusano 7d535a
operator.  I am told that Photoshop 3.0 will write uninverted YCCK in
kusano 7d535a
EPS/JPEG files, and will omit the PS-level inversion.  (But the data
kusano 7d535a
polarity used in bare JPEG files will not change in 3.0.)  In either case,
kusano 7d535a
the JPEG library must not invert the data itself, or else Ghostscript would
kusano 7d535a
read these EPS files incorrectly.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Error handling
kusano 7d535a
--------------
kusano 7d535a
kusano 7d535a
When the default error handler is used, any error detected inside the JPEG
kusano 7d535a
routines will cause a message to be printed on stderr, followed by exit().
kusano 7d535a
You can supply your own error handling routines to override this behavior
kusano 7d535a
and to control the treatment of nonfatal warnings and trace/debug messages.
kusano 7d535a
The file example.c illustrates the most common case, which is to have the
kusano 7d535a
application regain control after an error rather than exiting.
kusano 7d535a
kusano 7d535a
The JPEG library never writes any message directly; it always goes through
kusano 7d535a
the error handling routines.  Three classes of messages are recognized:
kusano 7d535a
  * Fatal errors: the library cannot continue.
kusano 7d535a
  * Warnings: the library can continue, but the data is corrupt, and a
kusano 7d535a
    damaged output image is likely to result.
kusano 7d535a
  * Trace/informational messages.  These come with a trace level indicating
kusano 7d535a
    the importance of the message; you can control the verbosity of the
kusano 7d535a
    program by adjusting the maximum trace level that will be displayed.
kusano 7d535a
kusano 7d535a
You may, if you wish, simply replace the entire JPEG error handling module
kusano 7d535a
(jerror.c) with your own code.  However, you can avoid code duplication by
kusano 7d535a
only replacing some of the routines depending on the behavior you need.
kusano 7d535a
This is accomplished by calling jpeg_std_error() as usual, but then overriding
kusano 7d535a
some of the method pointers in the jpeg_error_mgr struct, as illustrated by
kusano 7d535a
example.c.
kusano 7d535a
kusano 7d535a
All of the error handling routines will receive a pointer to the JPEG object
kusano 7d535a
(a j_common_ptr which points to either a jpeg_compress_struct or a
kusano 7d535a
jpeg_decompress_struct; if you need to tell which, test the is_decompressor
kusano 7d535a
field).  This struct includes a pointer to the error manager struct in its
kusano 7d535a
"err" field.  Frequently, custom error handler routines will need to access
kusano 7d535a
additional data which is not known to the JPEG library or the standard error
kusano 7d535a
handler.  The most convenient way to do this is to embed either the JPEG
kusano 7d535a
object or the jpeg_error_mgr struct in a larger structure that contains
kusano 7d535a
additional fields; then casting the passed pointer provides access to the
kusano 7d535a
additional fields.  Again, see example.c for one way to do it.  (Beginning
kusano 7d535a
with IJG version 6b, there is also a void pointer "client_data" in each
kusano 7d535a
JPEG object, which the application can also use to find related data.
kusano 7d535a
The library does not touch client_data at all.)
kusano 7d535a
kusano 7d535a
The individual methods that you might wish to override are:
kusano 7d535a
kusano 7d535a
error_exit (j_common_ptr cinfo)
kusano 7d535a
	Receives control for a fatal error.  Information sufficient to
kusano 7d535a
	generate the error message has been stored in cinfo->err; call
kusano 7d535a
	output_message to display it.  Control must NOT return to the caller;
kusano 7d535a
	generally this routine will exit() or longjmp() somewhere.
kusano 7d535a
	Typically you would override this routine to get rid of the exit()
kusano 7d535a
	default behavior.  Note that if you continue processing, you should
kusano 7d535a
	clean up the JPEG object with jpeg_abort() or jpeg_destroy().
kusano 7d535a
kusano 7d535a
output_message (j_common_ptr cinfo)
kusano 7d535a
	Actual output of any JPEG message.  Override this to send messages
kusano 7d535a
	somewhere other than stderr.  Note that this method does not know
kusano 7d535a
	how to generate a message, only where to send it.
kusano 7d535a
kusano 7d535a
format_message (j_common_ptr cinfo, char * buffer)
kusano 7d535a
	Constructs a readable error message string based on the error info
kusano 7d535a
	stored in cinfo->err.  This method is called by output_message.  Few
kusano 7d535a
	applications should need to override this method.  One possible
kusano 7d535a
	reason for doing so is to implement dynamic switching of error message
kusano 7d535a
	language.
kusano 7d535a
kusano 7d535a
emit_message (j_common_ptr cinfo, int msg_level)
kusano 7d535a
	Decide whether or not to emit a warning or trace message; if so,
kusano 7d535a
	calls output_message.  The main reason for overriding this method
kusano 7d535a
	would be to abort on warnings.  msg_level is -1 for warnings,
kusano 7d535a
	0 and up for trace messages.
kusano 7d535a
kusano 7d535a
Only error_exit() and emit_message() are called from the rest of the JPEG
kusano 7d535a
library; the other two are internal to the error handler.
kusano 7d535a
kusano 7d535a
The actual message texts are stored in an array of strings which is pointed to
kusano 7d535a
by the field err->jpeg_message_table.  The messages are numbered from 0 to
kusano 7d535a
err->last_jpeg_message, and it is these code numbers that are used in the
kusano 7d535a
JPEG library code.  You could replace the message texts (for instance, with
kusano 7d535a
messages in French or German) by changing the message table pointer.  See
kusano 7d535a
jerror.h for the default texts.  CAUTION: this table will almost certainly
kusano 7d535a
change or grow from one library version to the next.
kusano 7d535a
kusano 7d535a
It may be useful for an application to add its own message texts that are
kusano 7d535a
handled by the same mechanism.  The error handler supports a second "add-on"
kusano 7d535a
message table for this purpose.  To define an addon table, set the pointer
kusano 7d535a
err->addon_message_table and the message numbers err->first_addon_message and
kusano 7d535a
err->last_addon_message.  If you number the addon messages beginning at 1000
kusano 7d535a
or so, you won't have to worry about conflicts with the library's built-in
kusano 7d535a
messages.  See the sample applications cjpeg/djpeg for an example of using
kusano 7d535a
addon messages (the addon messages are defined in cderror.h).
kusano 7d535a
kusano 7d535a
Actual invocation of the error handler is done via macros defined in jerror.h:
kusano 7d535a
	ERREXITn(...)	for fatal errors
kusano 7d535a
	WARNMSn(...)	for corrupt-data warnings
kusano 7d535a
	TRACEMSn(...)	for trace and informational messages.
kusano 7d535a
These macros store the message code and any additional parameters into the
kusano 7d535a
error handler struct, then invoke the error_exit() or emit_message() method.
kusano 7d535a
The variants of each macro are for varying numbers of additional parameters.
kusano 7d535a
The additional parameters are inserted into the generated message using
kusano 7d535a
standard printf() format codes.
kusano 7d535a
kusano 7d535a
See jerror.h and jerror.c for further details.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Compressed data handling (source and destination managers)
kusano 7d535a
----------------------------------------------------------
kusano 7d535a
kusano 7d535a
The JPEG compression library sends its compressed data to a "destination
kusano 7d535a
manager" module.  The default destination manager just writes the data to a
kusano 7d535a
memory buffer or to a stdio stream, but you can provide your own manager to
kusano 7d535a
do something else.  Similarly, the decompression library calls a "source
kusano 7d535a
manager" to obtain the compressed data; you can provide your own source
kusano 7d535a
manager if you want the data to come from somewhere other than a memory
kusano 7d535a
buffer or a stdio stream.
kusano 7d535a
kusano 7d535a
In both cases, compressed data is processed a bufferload at a time: the
kusano 7d535a
destination or source manager provides a work buffer, and the library invokes
kusano 7d535a
the manager only when the buffer is filled or emptied.  (You could define a
kusano 7d535a
one-character buffer to force the manager to be invoked for each byte, but
kusano 7d535a
that would be rather inefficient.)  The buffer's size and location are
kusano 7d535a
controlled by the manager, not by the library.  For example, the memory
kusano 7d535a
source manager just makes the buffer pointer and length point to the original
kusano 7d535a
data in memory.  In this case the buffer-reload procedure will be invoked
kusano 7d535a
only if the decompressor ran off the end of the datastream, which would
kusano 7d535a
indicate an erroneous datastream.
kusano 7d535a
kusano 7d535a
The work buffer is defined as an array of datatype JOCTET, which is generally
kusano 7d535a
"char" or "unsigned char".  On a machine where char is not exactly 8 bits
kusano 7d535a
wide, you must define JOCTET as a wider data type and then modify the data
kusano 7d535a
source and destination modules to transcribe the work arrays into 8-bit units
kusano 7d535a
on external storage.
kusano 7d535a
kusano 7d535a
A data destination manager struct contains a pointer and count defining the
kusano 7d535a
next byte to write in the work buffer and the remaining free space:
kusano 7d535a
kusano 7d535a
	JOCTET * next_output_byte;  /* => next byte to write in buffer */
kusano 7d535a
	size_t free_in_buffer;      /* # of byte spaces remaining in buffer */
kusano 7d535a
kusano 7d535a
The library increments the pointer and decrements the count until the buffer
kusano 7d535a
is filled.  The manager's empty_output_buffer method must reset the pointer
kusano 7d535a
and count.  The manager is expected to remember the buffer's starting address
kusano 7d535a
and total size in private fields not visible to the library.
kusano 7d535a
kusano 7d535a
A data destination manager provides three methods:
kusano 7d535a
kusano 7d535a
init_destination (j_compress_ptr cinfo)
kusano 7d535a
	Initialize destination.  This is called by jpeg_start_compress()
kusano 7d535a
	before any data is actually written.  It must initialize
kusano 7d535a
	next_output_byte and free_in_buffer.  free_in_buffer must be
kusano 7d535a
	initialized to a positive value.
kusano 7d535a
kusano 7d535a
empty_output_buffer (j_compress_ptr cinfo)
kusano 7d535a
	This is called whenever the buffer has filled (free_in_buffer
kusano 7d535a
	reaches zero).  In typical applications, it should write out the
kusano 7d535a
	*entire* buffer (use the saved start address and buffer length;
kusano 7d535a
	ignore the current state of next_output_byte and free_in_buffer).
kusano 7d535a
	Then reset the pointer & count to the start of the buffer, and
kusano 7d535a
	return TRUE indicating that the buffer has been dumped.
kusano 7d535a
	free_in_buffer must be set to a positive value when TRUE is
kusano 7d535a
	returned.  A FALSE return should only be used when I/O suspension is
kusano 7d535a
	desired (this operating mode is discussed in the next section).
kusano 7d535a
kusano 7d535a
term_destination (j_compress_ptr cinfo)
kusano 7d535a
	Terminate destination --- called by jpeg_finish_compress() after all
kusano 7d535a
	data has been written.  In most applications, this must flush any
kusano 7d535a
	data remaining in the buffer.  Use either next_output_byte or
kusano 7d535a
	free_in_buffer to determine how much data is in the buffer.
kusano 7d535a
kusano 7d535a
term_destination() is NOT called by jpeg_abort() or jpeg_destroy().  If you
kusano 7d535a
want the destination manager to be cleaned up during an abort, you must do it
kusano 7d535a
yourself.
kusano 7d535a
kusano 7d535a
You will also need code to create a jpeg_destination_mgr struct, fill in its
kusano 7d535a
method pointers, and insert a pointer to the struct into the "dest" field of
kusano 7d535a
the JPEG compression object.  This can be done in-line in your setup code if
kusano 7d535a
you like, but it's probably cleaner to provide a separate routine similar to
kusano 7d535a
the jpeg_stdio_dest() or jpeg_mem_dest() routines of the supplied destination
kusano 7d535a
managers.
kusano 7d535a
kusano 7d535a
Decompression source managers follow a parallel design, but with some
kusano 7d535a
additional frammishes.  The source manager struct contains a pointer and count
kusano 7d535a
defining the next byte to read from the work buffer and the number of bytes
kusano 7d535a
remaining:
kusano 7d535a
kusano 7d535a
	const JOCTET * next_input_byte; /* => next byte to read from buffer */
kusano 7d535a
	size_t bytes_in_buffer;         /* # of bytes remaining in buffer */
kusano 7d535a
kusano 7d535a
The library increments the pointer and decrements the count until the buffer
kusano 7d535a
is emptied.  The manager's fill_input_buffer method must reset the pointer and
kusano 7d535a
count.  In most applications, the manager must remember the buffer's starting
kusano 7d535a
address and total size in private fields not visible to the library.
kusano 7d535a
kusano 7d535a
A data source manager provides five methods:
kusano 7d535a
kusano 7d535a
init_source (j_decompress_ptr cinfo)
kusano 7d535a
	Initialize source.  This is called by jpeg_read_header() before any
kusano 7d535a
	data is actually read.  Unlike init_destination(), it may leave
kusano 7d535a
	bytes_in_buffer set to 0 (in which case a fill_input_buffer() call
kusano 7d535a
	will occur immediately).
kusano 7d535a
kusano 7d535a
fill_input_buffer (j_decompress_ptr cinfo)
kusano 7d535a
	This is called whenever bytes_in_buffer has reached zero and more
kusano 7d535a
	data is wanted.  In typical applications, it should read fresh data
kusano 7d535a
	into the buffer (ignoring the current state of next_input_byte and
kusano 7d535a
	bytes_in_buffer), reset the pointer & count to the start of the
kusano 7d535a
	buffer, and return TRUE indicating that the buffer has been reloaded.
kusano 7d535a
	It is not necessary to fill the buffer entirely, only to obtain at
kusano 7d535a
	least one more byte.  bytes_in_buffer MUST be set to a positive value
kusano 7d535a
	if TRUE is returned.  A FALSE return should only be used when I/O
kusano 7d535a
	suspension is desired (this mode is discussed in the next section).
kusano 7d535a
kusano 7d535a
skip_input_data (j_decompress_ptr cinfo, long num_bytes)
kusano 7d535a
	Skip num_bytes worth of data.  The buffer pointer and count should
kusano 7d535a
	be advanced over num_bytes input bytes, refilling the buffer as
kusano 7d535a
	needed.  This is used to skip over a potentially large amount of
kusano 7d535a
	uninteresting data (such as an APPn marker).  In some applications
kusano 7d535a
	it may be possible to optimize away the reading of the skipped data,
kusano 7d535a
	but it's not clear that being smart is worth much trouble; large
kusano 7d535a
	skips are uncommon.  bytes_in_buffer may be zero on return.
kusano 7d535a
	A zero or negative skip count should be treated as a no-op.
kusano 7d535a
kusano 7d535a
resync_to_restart (j_decompress_ptr cinfo, int desired)
kusano 7d535a
	This routine is called only when the decompressor has failed to find
kusano 7d535a
	a restart (RSTn) marker where one is expected.  Its mission is to
kusano 7d535a
	find a suitable point for resuming decompression.  For most
kusano 7d535a
	applications, we recommend that you just use the default resync
kusano 7d535a
	procedure, jpeg_resync_to_restart().  However, if you are able to back
kusano 7d535a
	up in the input data stream, or if you have a-priori knowledge about
kusano 7d535a
	the likely location of restart markers, you may be able to do better.
kusano 7d535a
	Read the read_restart_marker() and jpeg_resync_to_restart() routines
kusano 7d535a
	in jdmarker.c if you think you'd like to implement your own resync
kusano 7d535a
	procedure.
kusano 7d535a
kusano 7d535a
term_source (j_decompress_ptr cinfo)
kusano 7d535a
	Terminate source --- called by jpeg_finish_decompress() after all
kusano 7d535a
	data has been read.  Often a no-op.
kusano 7d535a
kusano 7d535a
For both fill_input_buffer() and skip_input_data(), there is no such thing
kusano 7d535a
as an EOF return.  If the end of the file has been reached, the routine has
kusano 7d535a
a choice of exiting via ERREXIT() or inserting fake data into the buffer.
kusano 7d535a
In most cases, generating a warning message and inserting a fake EOI marker
kusano 7d535a
is the best course of action --- this will allow the decompressor to output
kusano 7d535a
however much of the image is there.  In pathological cases, the decompressor
kusano 7d535a
may swallow the EOI and again demand data ... just keep feeding it fake EOIs.
kusano 7d535a
jdatasrc.c illustrates the recommended error recovery behavior.
kusano 7d535a
kusano 7d535a
term_source() is NOT called by jpeg_abort() or jpeg_destroy().  If you want
kusano 7d535a
the source manager to be cleaned up during an abort, you must do it yourself.
kusano 7d535a
kusano 7d535a
You will also need code to create a jpeg_source_mgr struct, fill in its method
kusano 7d535a
pointers, and insert a pointer to the struct into the "src" field of the JPEG
kusano 7d535a
decompression object.  This can be done in-line in your setup code if you
kusano 7d535a
like, but it's probably cleaner to provide a separate routine similar to the
kusano 7d535a
jpeg_stdio_src() or jpeg_mem_src() routines of the supplied source managers.
kusano 7d535a
kusano 7d535a
For more information, consult the memory and stdio source and destination
kusano 7d535a
managers in jdatasrc.c and jdatadst.c.
kusano 7d535a
kusano 7d535a
kusano 7d535a
I/O suspension
kusano 7d535a
--------------
kusano 7d535a
kusano 7d535a
Some applications need to use the JPEG library as an incremental memory-to-
kusano 7d535a
memory filter: when the compressed data buffer is filled or emptied, they want
kusano 7d535a
control to return to the outer loop, rather than expecting that the buffer can
kusano 7d535a
be emptied or reloaded within the data source/destination manager subroutine.
kusano 7d535a
The library supports this need by providing an "I/O suspension" mode, which we
kusano 7d535a
describe in this section.
kusano 7d535a
kusano 7d535a
The I/O suspension mode is not a panacea: nothing is guaranteed about the
kusano 7d535a
maximum amount of time spent in any one call to the library, so it will not
kusano 7d535a
eliminate response-time problems in single-threaded applications.  If you
kusano 7d535a
need guaranteed response time, we suggest you "bite the bullet" and implement
kusano 7d535a
a real multi-tasking capability.
kusano 7d535a
kusano 7d535a
To use I/O suspension, cooperation is needed between the calling application
kusano 7d535a
and the data source or destination manager; you will always need a custom
kusano 7d535a
source/destination manager.  (Please read the previous section if you haven't
kusano 7d535a
already.)  The basic idea is that the empty_output_buffer() or
kusano 7d535a
fill_input_buffer() routine is a no-op, merely returning FALSE to indicate
kusano 7d535a
that it has done nothing.  Upon seeing this, the JPEG library suspends
kusano 7d535a
operation and returns to its caller.  The surrounding application is
kusano 7d535a
responsible for emptying or refilling the work buffer before calling the
kusano 7d535a
JPEG library again.
kusano 7d535a
kusano 7d535a
Compression suspension:
kusano 7d535a
kusano 7d535a
For compression suspension, use an empty_output_buffer() routine that returns
kusano 7d535a
FALSE; typically it will not do anything else.  This will cause the
kusano 7d535a
compressor to return to the caller of jpeg_write_scanlines(), with the return
kusano 7d535a
value indicating that not all the supplied scanlines have been accepted.
kusano 7d535a
The application must make more room in the output buffer, adjust the output
kusano 7d535a
buffer pointer/count appropriately, and then call jpeg_write_scanlines()
kusano 7d535a
again, pointing to the first unconsumed scanline.
kusano 7d535a
kusano 7d535a
When forced to suspend, the compressor will backtrack to a convenient stopping
kusano 7d535a
point (usually the start of the current MCU); it will regenerate some output
kusano 7d535a
data when restarted.  Therefore, although empty_output_buffer() is only
kusano 7d535a
called when the buffer is filled, you should NOT write out the entire buffer
kusano 7d535a
after a suspension.  Write only the data up to the current position of
kusano 7d535a
next_output_byte/free_in_buffer.  The data beyond that point will be
kusano 7d535a
regenerated after resumption.
kusano 7d535a
kusano 7d535a
Because of the backtracking behavior, a good-size output buffer is essential
kusano 7d535a
for efficiency; you don't want the compressor to suspend often.  (In fact, an
kusano 7d535a
overly small buffer could lead to infinite looping, if a single MCU required
kusano 7d535a
more data than would fit in the buffer.)  We recommend a buffer of at least
kusano 7d535a
several Kbytes.  You may want to insert explicit code to ensure that you don't
kusano 7d535a
call jpeg_write_scanlines() unless there is a reasonable amount of space in
kusano 7d535a
the output buffer; in other words, flush the buffer before trying to compress
kusano 7d535a
more data.
kusano 7d535a
kusano 7d535a
The compressor does not allow suspension while it is trying to write JPEG
kusano 7d535a
markers at the beginning and end of the file.  This means that:
kusano 7d535a
  * At the beginning of a compression operation, there must be enough free
kusano 7d535a
    space in the output buffer to hold the header markers (typically 600 or
kusano 7d535a
    so bytes).  The recommended buffer size is bigger than this anyway, so
kusano 7d535a
    this is not a problem as long as you start with an empty buffer.  However,
kusano 7d535a
    this restriction might catch you if you insert large special markers, such
kusano 7d535a
    as a JFIF thumbnail image, without flushing the buffer afterwards.
kusano 7d535a
  * When you call jpeg_finish_compress(), there must be enough space in the
kusano 7d535a
    output buffer to emit any buffered data and the final EOI marker.  In the
kusano 7d535a
    current implementation, half a dozen bytes should suffice for this, but
kusano 7d535a
    for safety's sake we recommend ensuring that at least 100 bytes are free
kusano 7d535a
    before calling jpeg_finish_compress().
kusano 7d535a
kusano 7d535a
A more significant restriction is that jpeg_finish_compress() cannot suspend.
kusano 7d535a
This means you cannot use suspension with multi-pass operating modes, namely
kusano 7d535a
Huffman code optimization and multiple-scan output.  Those modes write the
kusano 7d535a
whole file during jpeg_finish_compress(), which will certainly result in
kusano 7d535a
buffer overrun.  (Note that this restriction applies only to compression,
kusano 7d535a
not decompression.  The decompressor supports input suspension in all of its
kusano 7d535a
operating modes.)
kusano 7d535a
kusano 7d535a
Decompression suspension:
kusano 7d535a
kusano 7d535a
For decompression suspension, use a fill_input_buffer() routine that simply
kusano 7d535a
returns FALSE (except perhaps during error recovery, as discussed below).
kusano 7d535a
This will cause the decompressor to return to its caller with an indication
kusano 7d535a
that suspension has occurred.  This can happen at four places:
kusano 7d535a
  * jpeg_read_header(): will return JPEG_SUSPENDED.
kusano 7d535a
  * jpeg_start_decompress(): will return FALSE, rather than its usual TRUE.
kusano 7d535a
  * jpeg_read_scanlines(): will return the number of scanlines already
kusano 7d535a
	completed (possibly 0).
kusano 7d535a
  * jpeg_finish_decompress(): will return FALSE, rather than its usual TRUE.
kusano 7d535a
The surrounding application must recognize these cases, load more data into
kusano 7d535a
the input buffer, and repeat the call.  In the case of jpeg_read_scanlines(),
kusano 7d535a
increment the passed pointers past any scanlines successfully read.
kusano 7d535a
kusano 7d535a
Just as with compression, the decompressor will typically backtrack to a
kusano 7d535a
convenient restart point before suspending.  When fill_input_buffer() is
kusano 7d535a
called, next_input_byte/bytes_in_buffer point to the current restart point,
kusano 7d535a
which is where the decompressor will backtrack to if FALSE is returned.
kusano 7d535a
The data beyond that position must NOT be discarded if you suspend; it needs
kusano 7d535a
to be re-read upon resumption.  In most implementations, you'll need to shift
kusano 7d535a
this data down to the start of your work buffer and then load more data after
kusano 7d535a
it.  Again, this behavior means that a several-Kbyte work buffer is essential
kusano 7d535a
for decent performance; furthermore, you should load a reasonable amount of
kusano 7d535a
new data before resuming decompression.  (If you loaded, say, only one new
kusano 7d535a
byte each time around, you could waste a LOT of cycles.)
kusano 7d535a
kusano 7d535a
The skip_input_data() source manager routine requires special care in a
kusano 7d535a
suspension scenario.  This routine is NOT granted the ability to suspend the
kusano 7d535a
decompressor; it can decrement bytes_in_buffer to zero, but no more.  If the
kusano 7d535a
requested skip distance exceeds the amount of data currently in the input
kusano 7d535a
buffer, then skip_input_data() must set bytes_in_buffer to zero and record the
kusano 7d535a
additional skip distance somewhere else.  The decompressor will immediately
kusano 7d535a
call fill_input_buffer(), which should return FALSE, which will cause a
kusano 7d535a
suspension return.  The surrounding application must then arrange to discard
kusano 7d535a
the recorded number of bytes before it resumes loading the input buffer.
kusano 7d535a
(Yes, this design is rather baroque, but it avoids complexity in the far more
kusano 7d535a
common case where a non-suspending source manager is used.)
kusano 7d535a
kusano 7d535a
If the input data has been exhausted, we recommend that you emit a warning
kusano 7d535a
and insert dummy EOI markers just as a non-suspending data source manager
kusano 7d535a
would do.  This can be handled either in the surrounding application logic or
kusano 7d535a
within fill_input_buffer(); the latter is probably more efficient.  If
kusano 7d535a
fill_input_buffer() knows that no more data is available, it can set the
kusano 7d535a
pointer/count to point to a dummy EOI marker and then return TRUE just as
kusano 7d535a
though it had read more data in a non-suspending situation.
kusano 7d535a
kusano 7d535a
The decompressor does not attempt to suspend within standard JPEG markers;
kusano 7d535a
instead it will backtrack to the start of the marker and reprocess the whole
kusano 7d535a
marker next time.  Hence the input buffer must be large enough to hold the
kusano 7d535a
longest standard marker in the file.  Standard JPEG markers should normally
kusano 7d535a
not exceed a few hundred bytes each (DHT tables are typically the longest).
kusano 7d535a
We recommend at least a 2K buffer for performance reasons, which is much
kusano 7d535a
larger than any correct marker is likely to be.  For robustness against
kusano 7d535a
damaged marker length counts, you may wish to insert a test in your
kusano 7d535a
application for the case that the input buffer is completely full and yet
kusano 7d535a
the decoder has suspended without consuming any data --- otherwise, if this
kusano 7d535a
situation did occur, it would lead to an endless loop.  (The library can't
kusano 7d535a
provide this test since it has no idea whether "the buffer is full", or
kusano 7d535a
even whether there is a fixed-size input buffer.)
kusano 7d535a
kusano 7d535a
The input buffer would need to be 64K to allow for arbitrary COM or APPn
kusano 7d535a
markers, but these are handled specially: they are either saved into allocated
kusano 7d535a
memory, or skipped over by calling skip_input_data().  In the former case,
kusano 7d535a
suspension is handled correctly, and in the latter case, the problem of
kusano 7d535a
buffer overrun is placed on skip_input_data's shoulders, as explained above.
kusano 7d535a
Note that if you provide your own marker handling routine for large markers,
kusano 7d535a
you should consider how to deal with buffer overflow.
kusano 7d535a
kusano 7d535a
Multiple-buffer management:
kusano 7d535a
kusano 7d535a
In some applications it is desirable to store the compressed data in a linked
kusano 7d535a
list of buffer areas, so as to avoid data copying.  This can be handled by
kusano 7d535a
having empty_output_buffer() or fill_input_buffer() set the pointer and count
kusano 7d535a
to reference the next available buffer; FALSE is returned only if no more
kusano 7d535a
buffers are available.  Although seemingly straightforward, there is a
kusano 7d535a
pitfall in this approach: the backtrack that occurs when FALSE is returned
kusano 7d535a
could back up into an earlier buffer.  For example, when fill_input_buffer()
kusano 7d535a
is called, the current pointer & count indicate the backtrack restart point.
kusano 7d535a
Since fill_input_buffer() will set the pointer and count to refer to a new
kusano 7d535a
buffer, the restart position must be saved somewhere else.  Suppose a second
kusano 7d535a
call to fill_input_buffer() occurs in the same library call, and no
kusano 7d535a
additional input data is available, so fill_input_buffer must return FALSE.
kusano 7d535a
If the JPEG library has not moved the pointer/count forward in the current
kusano 7d535a
buffer, then *the correct restart point is the saved position in the prior
kusano 7d535a
buffer*.  Prior buffers may be discarded only after the library establishes
kusano 7d535a
a restart point within a later buffer.  Similar remarks apply for output into
kusano 7d535a
a chain of buffers.
kusano 7d535a
kusano 7d535a
The library will never attempt to backtrack over a skip_input_data() call,
kusano 7d535a
so any skipped data can be permanently discarded.  You still have to deal
kusano 7d535a
with the case of skipping not-yet-received data, however.
kusano 7d535a
kusano 7d535a
It's much simpler to use only a single buffer; when fill_input_buffer() is
kusano 7d535a
called, move any unconsumed data (beyond the current pointer/count) down to
kusano 7d535a
the beginning of this buffer and then load new data into the remaining buffer
kusano 7d535a
space.  This approach requires a little more data copying but is far easier
kusano 7d535a
to get right.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Progressive JPEG support
kusano 7d535a
------------------------
kusano 7d535a
kusano 7d535a
Progressive JPEG rearranges the stored data into a series of scans of
kusano 7d535a
increasing quality.  In situations where a JPEG file is transmitted across a
kusano 7d535a
slow communications link, a decoder can generate a low-quality image very
kusano 7d535a
quickly from the first scan, then gradually improve the displayed quality as
kusano 7d535a
more scans are received.  The final image after all scans are complete is
kusano 7d535a
identical to that of a regular (sequential) JPEG file of the same quality
kusano 7d535a
setting.  Progressive JPEG files are often slightly smaller than equivalent
kusano 7d535a
sequential JPEG files, but the possibility of incremental display is the main
kusano 7d535a
reason for using progressive JPEG.
kusano 7d535a
kusano 7d535a
The IJG encoder library generates progressive JPEG files when given a
kusano 7d535a
suitable "scan script" defining how to divide the data into scans.
kusano 7d535a
Creation of progressive JPEG files is otherwise transparent to the encoder.
kusano 7d535a
Progressive JPEG files can also be read transparently by the decoder library.
kusano 7d535a
If the decoding application simply uses the library as defined above, it
kusano 7d535a
will receive a final decoded image without any indication that the file was
kusano 7d535a
progressive.  Of course, this approach does not allow incremental display.
kusano 7d535a
To perform incremental display, an application needs to use the decoder
kusano 7d535a
library's "buffered-image" mode, in which it receives a decoded image
kusano 7d535a
multiple times.
kusano 7d535a
kusano 7d535a
Each displayed scan requires about as much work to decode as a full JPEG
kusano 7d535a
image of the same size, so the decoder must be fairly fast in relation to the
kusano 7d535a
data transmission rate in order to make incremental display useful.  However,
kusano 7d535a
it is possible to skip displaying the image and simply add the incoming bits
kusano 7d535a
to the decoder's coefficient buffer.  This is fast because only Huffman
kusano 7d535a
decoding need be done, not IDCT, upsampling, colorspace conversion, etc.
kusano 7d535a
The IJG decoder library allows the application to switch dynamically between
kusano 7d535a
displaying the image and simply absorbing the incoming bits.  A properly
kusano 7d535a
coded application can automatically adapt the number of display passes to
kusano 7d535a
suit the time available as the image is received.  Also, a final
kusano 7d535a
higher-quality display cycle can be performed from the buffered data after
kusano 7d535a
the end of the file is reached.
kusano 7d535a
kusano 7d535a
Progressive compression:
kusano 7d535a
kusano 7d535a
To create a progressive JPEG file (or a multiple-scan sequential JPEG file),
kusano 7d535a
set the scan_info cinfo field to point to an array of scan descriptors, and
kusano 7d535a
perform compression as usual.  Instead of constructing your own scan list,
kusano 7d535a
you can call the jpeg_simple_progression() helper routine to create a
kusano 7d535a
recommended progression sequence; this method should be used by all
kusano 7d535a
applications that don't want to get involved in the nitty-gritty of
kusano 7d535a
progressive scan sequence design.  (If you want to provide user control of
kusano 7d535a
scan sequences, you may wish to borrow the scan script reading code found
kusano 7d535a
in rdswitch.c, so that you can read scan script files just like cjpeg's.)
kusano 7d535a
When scan_info is not NULL, the compression library will store DCT'd data
kusano 7d535a
into a buffer array as jpeg_write_scanlines() is called, and will emit all
kusano 7d535a
the requested scans during jpeg_finish_compress().  This implies that
kusano 7d535a
multiple-scan output cannot be created with a suspending data destination
kusano 7d535a
manager, since jpeg_finish_compress() does not support suspension.  We
kusano 7d535a
should also note that the compressor currently forces Huffman optimization
kusano 7d535a
mode when creating a progressive JPEG file, because the default Huffman
kusano 7d535a
tables are unsuitable for progressive files.
kusano 7d535a
kusano 7d535a
Progressive decompression:
kusano 7d535a
kusano 7d535a
When buffered-image mode is not used, the decoder library will read all of
kusano 7d535a
a multi-scan file during jpeg_start_decompress(), so that it can provide a
kusano 7d535a
final decoded image.  (Here "multi-scan" means either progressive or
kusano 7d535a
multi-scan sequential.)  This makes multi-scan files transparent to the
kusano 7d535a
decoding application.  However, existing applications that used suspending
kusano 7d535a
input with version 5 of the IJG library will need to be modified to check
kusano 7d535a
for a suspension return from jpeg_start_decompress().
kusano 7d535a
kusano 7d535a
To perform incremental display, an application must use the library's
kusano 7d535a
buffered-image mode.  This is described in the next section.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Buffered-image mode
kusano 7d535a
-------------------
kusano 7d535a
kusano 7d535a
In buffered-image mode, the library stores the partially decoded image in a
kusano 7d535a
coefficient buffer, from which it can be read out as many times as desired.
kusano 7d535a
This mode is typically used for incremental display of progressive JPEG files,
kusano 7d535a
but it can be used with any JPEG file.  Each scan of a progressive JPEG file
kusano 7d535a
adds more data (more detail) to the buffered image.  The application can
kusano 7d535a
display in lockstep with the source file (one display pass per input scan),
kusano 7d535a
or it can allow input processing to outrun display processing.  By making
kusano 7d535a
input and display processing run independently, it is possible for the
kusano 7d535a
application to adapt progressive display to a wide range of data transmission
kusano 7d535a
rates.
kusano 7d535a
kusano 7d535a
The basic control flow for buffered-image decoding is
kusano 7d535a
kusano 7d535a
	jpeg_create_decompress()
kusano 7d535a
	set data source
kusano 7d535a
	jpeg_read_header()
kusano 7d535a
	set overall decompression parameters
kusano 7d535a
	cinfo.buffered_image = TRUE;	/* select buffered-image mode */
kusano 7d535a
	jpeg_start_decompress()
kusano 7d535a
	for (each output pass) {
kusano 7d535a
	    adjust output decompression parameters if required
kusano 7d535a
	    jpeg_start_output()		/* start a new output pass */
kusano 7d535a
	    for (all scanlines in image) {
kusano 7d535a
	        jpeg_read_scanlines()
kusano 7d535a
	        display scanlines
kusano 7d535a
	    }
kusano 7d535a
	    jpeg_finish_output()	/* terminate output pass */
kusano 7d535a
	}
kusano 7d535a
	jpeg_finish_decompress()
kusano 7d535a
	jpeg_destroy_decompress()
kusano 7d535a
kusano 7d535a
This differs from ordinary unbuffered decoding in that there is an additional
kusano 7d535a
level of looping.  The application can choose how many output passes to make
kusano 7d535a
and how to display each pass.
kusano 7d535a
kusano 7d535a
The simplest approach to displaying progressive images is to do one display
kusano 7d535a
pass for each scan appearing in the input file.  In this case the outer loop
kusano 7d535a
condition is typically
kusano 7d535a
	while (! jpeg_input_complete(&cinfo))
kusano 7d535a
and the start-output call should read
kusano 7d535a
	jpeg_start_output(&cinfo, cinfo.input_scan_number);
kusano 7d535a
The second parameter to jpeg_start_output() indicates which scan of the input
kusano 7d535a
file is to be displayed; the scans are numbered starting at 1 for this
kusano 7d535a
purpose.  (You can use a loop counter starting at 1 if you like, but using
kusano 7d535a
the library's input scan counter is easier.)  The library automatically reads
kusano 7d535a
data as necessary to complete each requested scan, and jpeg_finish_output()
kusano 7d535a
advances to the next scan or end-of-image marker (hence input_scan_number
kusano 7d535a
will be incremented by the time control arrives back at jpeg_start_output()).
kusano 7d535a
With this technique, data is read from the input file only as needed, and
kusano 7d535a
input and output processing run in lockstep.
kusano 7d535a
kusano 7d535a
After reading the final scan and reaching the end of the input file, the
kusano 7d535a
buffered image remains available; it can be read additional times by
kusano 7d535a
repeating the jpeg_start_output()/jpeg_read_scanlines()/jpeg_finish_output()
kusano 7d535a
sequence.  For example, a useful technique is to use fast one-pass color
kusano 7d535a
quantization for display passes made while the image is arriving, followed by
kusano 7d535a
a final display pass using two-pass quantization for highest quality.  This
kusano 7d535a
is done by changing the library parameters before the final output pass.
kusano 7d535a
Changing parameters between passes is discussed in detail below.
kusano 7d535a
kusano 7d535a
In general the last scan of a progressive file cannot be recognized as such
kusano 7d535a
until after it is read, so a post-input display pass is the best approach if
kusano 7d535a
you want special processing in the final pass.
kusano 7d535a
kusano 7d535a
When done with the image, be sure to call jpeg_finish_decompress() to release
kusano 7d535a
the buffered image (or just use jpeg_destroy_decompress()).
kusano 7d535a
kusano 7d535a
If input data arrives faster than it can be displayed, the application can
kusano 7d535a
cause the library to decode input data in advance of what's needed to produce
kusano 7d535a
output.  This is done by calling the routine jpeg_consume_input().
kusano 7d535a
The return value is one of the following:
kusano 7d535a
	JPEG_REACHED_SOS:    reached an SOS marker (the start of a new scan)
kusano 7d535a
	JPEG_REACHED_EOI:    reached the EOI marker (end of image)
kusano 7d535a
	JPEG_ROW_COMPLETED:  completed reading one MCU row of compressed data
kusano 7d535a
	JPEG_SCAN_COMPLETED: completed reading last MCU row of current scan
kusano 7d535a
	JPEG_SUSPENDED:      suspended before completing any of the above
kusano 7d535a
(JPEG_SUSPENDED can occur only if a suspending data source is used.)  This
kusano 7d535a
routine can be called at any time after initializing the JPEG object.  It
kusano 7d535a
reads some additional data and returns when one of the indicated significant
kusano 7d535a
events occurs.  (If called after the EOI marker is reached, it will
kusano 7d535a
immediately return JPEG_REACHED_EOI without attempting to read more data.)
kusano 7d535a
kusano 7d535a
The library's output processing will automatically call jpeg_consume_input()
kusano 7d535a
whenever the output processing overtakes the input; thus, simple lockstep
kusano 7d535a
display requires no direct calls to jpeg_consume_input().  But by adding
kusano 7d535a
calls to jpeg_consume_input(), you can absorb data in advance of what is
kusano 7d535a
being displayed.  This has two benefits:
kusano 7d535a
  * You can limit buildup of unprocessed data in your input buffer.
kusano 7d535a
  * You can eliminate extra display passes by paying attention to the
kusano 7d535a
    state of the library's input processing.
kusano 7d535a
kusano 7d535a
The first of these benefits only requires interspersing calls to
kusano 7d535a
jpeg_consume_input() with your display operations and any other processing
kusano 7d535a
you may be doing.  To avoid wasting cycles due to backtracking, it's best to
kusano 7d535a
call jpeg_consume_input() only after a hundred or so new bytes have arrived.
kusano 7d535a
This is discussed further under "I/O suspension", above.  (Note: the JPEG
kusano 7d535a
library currently is not thread-safe.  You must not call jpeg_consume_input()
kusano 7d535a
from one thread of control if a different library routine is working on the
kusano 7d535a
same JPEG object in another thread.)
kusano 7d535a
kusano 7d535a
When input arrives fast enough that more than one new scan is available
kusano 7d535a
before you start a new output pass, you may as well skip the output pass
kusano 7d535a
corresponding to the completed scan.  This occurs for free if you pass
kusano 7d535a
cinfo.input_scan_number as the target scan number to jpeg_start_output().
kusano 7d535a
The input_scan_number field is simply the index of the scan currently being
kusano 7d535a
consumed by the input processor.  You can ensure that this is up-to-date by
kusano 7d535a
emptying the input buffer just before calling jpeg_start_output(): call
kusano 7d535a
jpeg_consume_input() repeatedly until it returns JPEG_SUSPENDED or
kusano 7d535a
JPEG_REACHED_EOI.
kusano 7d535a
kusano 7d535a
The target scan number passed to jpeg_start_output() is saved in the
kusano 7d535a
cinfo.output_scan_number field.  The library's output processing calls
kusano 7d535a
jpeg_consume_input() whenever the current input scan number and row within
kusano 7d535a
that scan is less than or equal to the current output scan number and row.
kusano 7d535a
Thus, input processing can "get ahead" of the output processing but is not
kusano 7d535a
allowed to "fall behind".  You can achieve several different effects by
kusano 7d535a
manipulating this interlock rule.  For example, if you pass a target scan
kusano 7d535a
number greater than the current input scan number, the output processor will
kusano 7d535a
wait until that scan starts to arrive before producing any output.  (To avoid
kusano 7d535a
an infinite loop, the target scan number is automatically reset to the last
kusano 7d535a
scan number when the end of image is reached.  Thus, if you specify a large
kusano 7d535a
target scan number, the library will just absorb the entire input file and
kusano 7d535a
then perform an output pass.  This is effectively the same as what
kusano 7d535a
jpeg_start_decompress() does when you don't select buffered-image mode.)
kusano 7d535a
When you pass a target scan number equal to the current input scan number,
kusano 7d535a
the image is displayed no faster than the current input scan arrives.  The
kusano 7d535a
final possibility is to pass a target scan number less than the current input
kusano 7d535a
scan number; this disables the input/output interlock and causes the output
kusano 7d535a
processor to simply display whatever it finds in the image buffer, without
kusano 7d535a
waiting for input.  (However, the library will not accept a target scan
kusano 7d535a
number less than one, so you can't avoid waiting for the first scan.)
kusano 7d535a
kusano 7d535a
When data is arriving faster than the output display processing can advance
kusano 7d535a
through the image, jpeg_consume_input() will store data into the buffered
kusano 7d535a
image beyond the point at which the output processing is reading data out
kusano 7d535a
again.  If the input arrives fast enough, it may "wrap around" the buffer to
kusano 7d535a
the point where the input is more than one whole scan ahead of the output.
kusano 7d535a
If the output processing simply proceeds through its display pass without
kusano 7d535a
paying attention to the input, the effect seen on-screen is that the lower
kusano 7d535a
part of the image is one or more scans better in quality than the upper part.
kusano 7d535a
Then, when the next output scan is started, you have a choice of what target
kusano 7d535a
scan number to use.  The recommended choice is to use the current input scan
kusano 7d535a
number at that time, which implies that you've skipped the output scans
kusano 7d535a
corresponding to the input scans that were completed while you processed the
kusano 7d535a
previous output scan.  In this way, the decoder automatically adapts its
kusano 7d535a
speed to the arriving data, by skipping output scans as necessary to keep up
kusano 7d535a
with the arriving data.
kusano 7d535a
kusano 7d535a
When using this strategy, you'll want to be sure that you perform a final
kusano 7d535a
output pass after receiving all the data; otherwise your last display may not
kusano 7d535a
be full quality across the whole screen.  So the right outer loop logic is
kusano 7d535a
something like this:
kusano 7d535a
	do {
kusano 7d535a
	    absorb any waiting input by calling jpeg_consume_input()
kusano 7d535a
	    final_pass = jpeg_input_complete(&cinfo);
kusano 7d535a
	    adjust output decompression parameters if required
kusano 7d535a
	    jpeg_start_output(&cinfo, cinfo.input_scan_number);
kusano 7d535a
	    ...
kusano 7d535a
	    jpeg_finish_output()
kusano 7d535a
	} while (! final_pass);
kusano 7d535a
rather than quitting as soon as jpeg_input_complete() returns TRUE.  This
kusano 7d535a
arrangement makes it simple to use higher-quality decoding parameters
kusano 7d535a
for the final pass.  But if you don't want to use special parameters for
kusano 7d535a
the final pass, the right loop logic is like this:
kusano 7d535a
	for (;;) {
kusano 7d535a
	    absorb any waiting input by calling jpeg_consume_input()
kusano 7d535a
	    jpeg_start_output(&cinfo, cinfo.input_scan_number);
kusano 7d535a
	    ...
kusano 7d535a
	    jpeg_finish_output()
kusano 7d535a
	    if (jpeg_input_complete(&cinfo) &&
kusano 7d535a
	        cinfo.input_scan_number == cinfo.output_scan_number)
kusano 7d535a
	      break;
kusano 7d535a
	}
kusano 7d535a
In this case you don't need to know in advance whether an output pass is to
kusano 7d535a
be the last one, so it's not necessary to have reached EOF before starting
kusano 7d535a
the final output pass; rather, what you want to test is whether the output
kusano 7d535a
pass was performed in sync with the final input scan.  This form of the loop
kusano 7d535a
will avoid an extra output pass whenever the decoder is able (or nearly able)
kusano 7d535a
to keep up with the incoming data.
kusano 7d535a
kusano 7d535a
When the data transmission speed is high, you might begin a display pass,
kusano 7d535a
then find that much or all of the file has arrived before you can complete
kusano 7d535a
the pass.  (You can detect this by noting the JPEG_REACHED_EOI return code
kusano 7d535a
from jpeg_consume_input(), or equivalently by testing jpeg_input_complete().)
kusano 7d535a
In this situation you may wish to abort the current display pass and start a
kusano 7d535a
new one using the newly arrived information.  To do so, just call
kusano 7d535a
jpeg_finish_output() and then start a new pass with jpeg_start_output().
kusano 7d535a
kusano 7d535a
A variant strategy is to abort and restart display if more than one complete
kusano 7d535a
scan arrives during an output pass; this can be detected by noting
kusano 7d535a
JPEG_REACHED_SOS returns and/or examining cinfo.input_scan_number.  This
kusano 7d535a
idea should be employed with caution, however, since the display process
kusano 7d535a
might never get to the bottom of the image before being aborted, resulting
kusano 7d535a
in the lower part of the screen being several passes worse than the upper.
kusano 7d535a
In most cases it's probably best to abort an output pass only if the whole
kusano 7d535a
file has arrived and you want to begin the final output pass immediately.
kusano 7d535a
kusano 7d535a
When receiving data across a communication link, we recommend always using
kusano 7d535a
the current input scan number for the output target scan number; if a
kusano 7d535a
higher-quality final pass is to be done, it should be started (aborting any
kusano 7d535a
incomplete output pass) as soon as the end of file is received.  However,
kusano 7d535a
many other strategies are possible.  For example, the application can examine
kusano 7d535a
the parameters of the current input scan and decide whether to display it or
kusano 7d535a
not.  If the scan contains only chroma data, one might choose not to use it
kusano 7d535a
as the target scan, expecting that the scan will be small and will arrive
kusano 7d535a
quickly.  To skip to the next scan, call jpeg_consume_input() until it
kusano 7d535a
returns JPEG_REACHED_SOS or JPEG_REACHED_EOI.  Or just use the next higher
kusano 7d535a
number as the target scan for jpeg_start_output(); but that method doesn't
kusano 7d535a
let you inspect the next scan's parameters before deciding to display it.
kusano 7d535a
kusano 7d535a
kusano 7d535a
In buffered-image mode, jpeg_start_decompress() never performs input and
kusano 7d535a
thus never suspends.  An application that uses input suspension with
kusano 7d535a
buffered-image mode must be prepared for suspension returns from these
kusano 7d535a
routines:
kusano 7d535a
* jpeg_start_output() performs input only if you request 2-pass quantization
kusano 7d535a
  and the target scan isn't fully read yet.  (This is discussed below.)
kusano 7d535a
* jpeg_read_scanlines(), as always, returns the number of scanlines that it
kusano 7d535a
  was able to produce before suspending.
kusano 7d535a
* jpeg_finish_output() will read any markers following the target scan,
kusano 7d535a
  up to the end of the file or the SOS marker that begins another scan.
kusano 7d535a
  (But it reads no input if jpeg_consume_input() has already reached the
kusano 7d535a
  end of the file or a SOS marker beyond the target output scan.)
kusano 7d535a
* jpeg_finish_decompress() will read until the end of file, and thus can
kusano 7d535a
  suspend if the end hasn't already been reached (as can be tested by
kusano 7d535a
  calling jpeg_input_complete()).
kusano 7d535a
jpeg_start_output(), jpeg_finish_output(), and jpeg_finish_decompress()
kusano 7d535a
all return TRUE if they completed their tasks, FALSE if they had to suspend.
kusano 7d535a
In the event of a FALSE return, the application must load more input data
kusano 7d535a
and repeat the call.  Applications that use non-suspending data sources need
kusano 7d535a
not check the return values of these three routines.
kusano 7d535a
kusano 7d535a
kusano 7d535a
It is possible to change decoding parameters between output passes in the
kusano 7d535a
buffered-image mode.  The decoder library currently supports only very
kusano 7d535a
limited changes of parameters.  ONLY THE FOLLOWING parameter changes are
kusano 7d535a
allowed after jpeg_start_decompress() is called:
kusano 7d535a
* dct_method can be changed before each call to jpeg_start_output().
kusano 7d535a
  For example, one could use a fast DCT method for early scans, changing
kusano 7d535a
  to a higher quality method for the final scan.
kusano 7d535a
* dither_mode can be changed before each call to jpeg_start_output();
kusano 7d535a
  of course this has no impact if not using color quantization.  Typically
kusano 7d535a
  one would use ordered dither for initial passes, then switch to
kusano 7d535a
  Floyd-Steinberg dither for the final pass.  Caution: changing dither mode
kusano 7d535a
  can cause more memory to be allocated by the library.  Although the amount
kusano 7d535a
  of memory involved is not large (a scanline or so), it may cause the
kusano 7d535a
  initial max_memory_to_use specification to be exceeded, which in the worst
kusano 7d535a
  case would result in an out-of-memory failure.
kusano 7d535a
* do_block_smoothing can be changed before each call to jpeg_start_output().
kusano 7d535a
  This setting is relevant only when decoding a progressive JPEG image.
kusano 7d535a
  During the first DC-only scan, block smoothing provides a very "fuzzy" look
kusano 7d535a
  instead of the very "blocky" look seen without it; which is better seems a
kusano 7d535a
  matter of personal taste.  But block smoothing is nearly always a win
kusano 7d535a
  during later stages, especially when decoding a successive-approximation
kusano 7d535a
  image: smoothing helps to hide the slight blockiness that otherwise shows
kusano 7d535a
  up on smooth gradients until the lowest coefficient bits are sent.
kusano 7d535a
* Color quantization mode can be changed under the rules described below.
kusano 7d535a
  You *cannot* change between full-color and quantized output (because that
kusano 7d535a
  would alter the required I/O buffer sizes), but you can change which
kusano 7d535a
  quantization method is used.
kusano 7d535a
kusano 7d535a
When generating color-quantized output, changing quantization method is a
kusano 7d535a
very useful way of switching between high-speed and high-quality display.
kusano 7d535a
The library allows you to change among its three quantization methods:
kusano 7d535a
1. Single-pass quantization to a fixed color cube.
kusano 7d535a
   Selected by cinfo.two_pass_quantize = FALSE and cinfo.colormap = NULL.
kusano 7d535a
2. Single-pass quantization to an application-supplied colormap.
kusano 7d535a
   Selected by setting cinfo.colormap to point to the colormap (the value of
kusano 7d535a
   two_pass_quantize is ignored); also set cinfo.actual_number_of_colors.
kusano 7d535a
3. Two-pass quantization to a colormap chosen specifically for the image.
kusano 7d535a
   Selected by cinfo.two_pass_quantize = TRUE and cinfo.colormap = NULL.
kusano 7d535a
   (This is the default setting selected by jpeg_read_header, but it is
kusano 7d535a
   probably NOT what you want for the first pass of progressive display!)
kusano 7d535a
These methods offer successively better quality and lesser speed.  However,
kusano 7d535a
only the first method is available for quantizing in non-RGB color spaces.
kusano 7d535a
kusano 7d535a
IMPORTANT: because the different quantizer methods have very different
kusano 7d535a
working-storage requirements, the library requires you to indicate which
kusano 7d535a
one(s) you intend to use before you call jpeg_start_decompress().  (If we did
kusano 7d535a
not require this, the max_memory_to_use setting would be a complete fiction.)
kusano 7d535a
You do this by setting one or more of these three cinfo fields to TRUE:
kusano 7d535a
	enable_1pass_quant		Fixed color cube colormap
kusano 7d535a
	enable_external_quant		Externally-supplied colormap
kusano 7d535a
	enable_2pass_quant		Two-pass custom colormap
kusano 7d535a
All three are initialized FALSE by jpeg_read_header().  But
kusano 7d535a
jpeg_start_decompress() automatically sets TRUE the one selected by the
kusano 7d535a
current two_pass_quantize and colormap settings, so you only need to set the
kusano 7d535a
enable flags for any other quantization methods you plan to change to later.
kusano 7d535a
kusano 7d535a
After setting the enable flags correctly at jpeg_start_decompress() time, you
kusano 7d535a
can change to any enabled quantization method by setting two_pass_quantize
kusano 7d535a
and colormap properly just before calling jpeg_start_output().  The following
kusano 7d535a
special rules apply:
kusano 7d535a
1. You must explicitly set cinfo.colormap to NULL when switching to 1-pass
kusano 7d535a
   or 2-pass mode from a different mode, or when you want the 2-pass
kusano 7d535a
   quantizer to be re-run to generate a new colormap.
kusano 7d535a
2. To switch to an external colormap, or to change to a different external
kusano 7d535a
   colormap than was used on the prior pass, you must call
kusano 7d535a
   jpeg_new_colormap() after setting cinfo.colormap.
kusano 7d535a
NOTE: if you want to use the same colormap as was used in the prior pass,
kusano 7d535a
you should not do either of these things.  This will save some nontrivial
kusano 7d535a
switchover costs.
kusano 7d535a
(These requirements exist because cinfo.colormap will always be non-NULL
kusano 7d535a
after completing a prior output pass, since both the 1-pass and 2-pass
kusano 7d535a
quantizers set it to point to their output colormaps.  Thus you have to
kusano 7d535a
do one of these two things to notify the library that something has changed.
kusano 7d535a
Yup, it's a bit klugy, but it's necessary to do it this way for backwards
kusano 7d535a
compatibility.)
kusano 7d535a
kusano 7d535a
Note that in buffered-image mode, the library generates any requested colormap
kusano 7d535a
during jpeg_start_output(), not during jpeg_start_decompress().
kusano 7d535a
kusano 7d535a
When using two-pass quantization, jpeg_start_output() makes a pass over the
kusano 7d535a
buffered image to determine the optimum color map; it therefore may take a
kusano 7d535a
significant amount of time, whereas ordinarily it does little work.  The
kusano 7d535a
progress monitor hook is called during this pass, if defined.  It is also
kusano 7d535a
important to realize that if the specified target scan number is greater than
kusano 7d535a
or equal to the current input scan number, jpeg_start_output() will attempt
kusano 7d535a
to consume input as it makes this pass.  If you use a suspending data source,
kusano 7d535a
you need to check for a FALSE return from jpeg_start_output() under these
kusano 7d535a
conditions.  The combination of 2-pass quantization and a not-yet-fully-read
kusano 7d535a
target scan is the only case in which jpeg_start_output() will consume input.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Application authors who support buffered-image mode may be tempted to use it
kusano 7d535a
for all JPEG images, even single-scan ones.  This will work, but it is
kusano 7d535a
inefficient: there is no need to create an image-sized coefficient buffer for
kusano 7d535a
single-scan images.  Requesting buffered-image mode for such an image wastes
kusano 7d535a
memory.  Worse, it can cost time on large images, since the buffered data has
kusano 7d535a
to be swapped out or written to a temporary file.  If you are concerned about
kusano 7d535a
maximum performance on baseline JPEG files, you should use buffered-image
kusano 7d535a
mode only when the incoming file actually has multiple scans.  This can be
kusano 7d535a
tested by calling jpeg_has_multiple_scans(), which will return a correct
kusano 7d535a
result at any time after jpeg_read_header() completes.
kusano 7d535a
kusano 7d535a
It is also worth noting that when you use jpeg_consume_input() to let input
kusano 7d535a
processing get ahead of output processing, the resulting pattern of access to
kusano 7d535a
the coefficient buffer is quite nonsequential.  It's best to use the memory
kusano 7d535a
manager jmemnobs.c if you can (ie, if you have enough real or virtual main
kusano 7d535a
memory).  If not, at least make sure that max_memory_to_use is set as high as
kusano 7d535a
possible.  If the JPEG memory manager has to use a temporary file, you will
kusano 7d535a
probably see a lot of disk traffic and poor performance.  (This could be
kusano 7d535a
improved with additional work on the memory manager, but we haven't gotten
kusano 7d535a
around to it yet.)
kusano 7d535a
kusano 7d535a
In some applications it may be convenient to use jpeg_consume_input() for all
kusano 7d535a
input processing, including reading the initial markers; that is, you may
kusano 7d535a
wish to call jpeg_consume_input() instead of jpeg_read_header() during
kusano 7d535a
startup.  This works, but note that you must check for JPEG_REACHED_SOS and
kusano 7d535a
JPEG_REACHED_EOI return codes as the equivalent of jpeg_read_header's codes.
kusano 7d535a
Once the first SOS marker has been reached, you must call
kusano 7d535a
jpeg_start_decompress() before jpeg_consume_input() will consume more input;
kusano 7d535a
it'll just keep returning JPEG_REACHED_SOS until you do.  If you read a
kusano 7d535a
tables-only file this way, jpeg_consume_input() will return JPEG_REACHED_EOI
kusano 7d535a
without ever returning JPEG_REACHED_SOS; be sure to check for this case.
kusano 7d535a
If this happens, the decompressor will not read any more input until you call
kusano 7d535a
jpeg_abort() to reset it.  It is OK to call jpeg_consume_input() even when not
kusano 7d535a
using buffered-image mode, but in that case it's basically a no-op after the
kusano 7d535a
initial markers have been read: it will just return JPEG_SUSPENDED.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Abbreviated datastreams and multiple images
kusano 7d535a
-------------------------------------------
kusano 7d535a
kusano 7d535a
A JPEG compression or decompression object can be reused to process multiple
kusano 7d535a
images.  This saves a small amount of time per image by eliminating the
kusano 7d535a
"create" and "destroy" operations, but that isn't the real purpose of the
kusano 7d535a
feature.  Rather, reuse of an object provides support for abbreviated JPEG
kusano 7d535a
datastreams.  Object reuse can also simplify processing a series of images in
kusano 7d535a
a single input or output file.  This section explains these features.
kusano 7d535a
kusano 7d535a
A JPEG file normally contains several hundred bytes worth of quantization
kusano 7d535a
and Huffman tables.  In a situation where many images will be stored or
kusano 7d535a
transmitted with identical tables, this may represent an annoying overhead.
kusano 7d535a
The JPEG standard therefore permits tables to be omitted.  The standard
kusano 7d535a
defines three classes of JPEG datastreams:
kusano 7d535a
  * "Interchange" datastreams contain an image and all tables needed to decode
kusano 7d535a
     the image.  These are the usual kind of JPEG file.
kusano 7d535a
  * "Abbreviated image" datastreams contain an image, but are missing some or
kusano 7d535a
    all of the tables needed to decode that image.
kusano 7d535a
  * "Abbreviated table specification" (henceforth "tables-only") datastreams
kusano 7d535a
    contain only table specifications.
kusano 7d535a
To decode an abbreviated image, it is necessary to load the missing table(s)
kusano 7d535a
into the decoder beforehand.  This can be accomplished by reading a separate
kusano 7d535a
tables-only file.  A variant scheme uses a series of images in which the first
kusano 7d535a
image is an interchange (complete) datastream, while subsequent ones are
kusano 7d535a
abbreviated and rely on the tables loaded by the first image.  It is assumed
kusano 7d535a
that once the decoder has read a table, it will remember that table until a
kusano 7d535a
new definition for the same table number is encountered.
kusano 7d535a
kusano 7d535a
It is the application designer's responsibility to figure out how to associate
kusano 7d535a
the correct tables with an abbreviated image.  While abbreviated datastreams
kusano 7d535a
can be useful in a closed environment, their use is strongly discouraged in
kusano 7d535a
any situation where data exchange with other applications might be needed.
kusano 7d535a
Caveat designer.
kusano 7d535a
kusano 7d535a
The JPEG library provides support for reading and writing any combination of
kusano 7d535a
tables-only datastreams and abbreviated images.  In both compression and
kusano 7d535a
decompression objects, a quantization or Huffman table will be retained for
kusano 7d535a
the lifetime of the object, unless it is overwritten by a new table definition.
kusano 7d535a
kusano 7d535a
kusano 7d535a
To create abbreviated image datastreams, it is only necessary to tell the
kusano 7d535a
compressor not to emit some or all of the tables it is using.  Each
kusano 7d535a
quantization and Huffman table struct contains a boolean field "sent_table",
kusano 7d535a
which normally is initialized to FALSE.  For each table used by the image, the
kusano 7d535a
header-writing process emits the table and sets sent_table = TRUE unless it is
kusano 7d535a
already TRUE.  (In normal usage, this prevents outputting the same table
kusano 7d535a
definition multiple times, as would otherwise occur because the chroma
kusano 7d535a
components typically share tables.)  Thus, setting this field to TRUE before
kusano 7d535a
calling jpeg_start_compress() will prevent the table from being written at
kusano 7d535a
all.
kusano 7d535a
kusano 7d535a
If you want to create a "pure" abbreviated image file containing no tables,
kusano 7d535a
just call "jpeg_suppress_tables(&cinfo, TRUE)" after constructing all the
kusano 7d535a
tables.  If you want to emit some but not all tables, you'll need to set the
kusano 7d535a
individual sent_table fields directly.
kusano 7d535a
kusano 7d535a
To create an abbreviated image, you must also call jpeg_start_compress()
kusano 7d535a
with a second parameter of FALSE, not TRUE.  Otherwise jpeg_start_compress()
kusano 7d535a
will force all the sent_table fields to FALSE.  (This is a safety feature to
kusano 7d535a
prevent abbreviated images from being created accidentally.)
kusano 7d535a
kusano 7d535a
To create a tables-only file, perform the same parameter setup that you
kusano 7d535a
normally would, but instead of calling jpeg_start_compress() and so on, call
kusano 7d535a
jpeg_write_tables(&cinfo).  This will write an abbreviated datastream
kusano 7d535a
containing only SOI, DQT and/or DHT markers, and EOI.  All the quantization
kusano 7d535a
and Huffman tables that are currently defined in the compression object will
kusano 7d535a
be emitted unless their sent_tables flag is already TRUE, and then all the
kusano 7d535a
sent_tables flags will be set TRUE.
kusano 7d535a
kusano 7d535a
A sure-fire way to create matching tables-only and abbreviated image files
kusano 7d535a
is to proceed as follows:
kusano 7d535a
kusano 7d535a
	create JPEG compression object
kusano 7d535a
	set JPEG parameters
kusano 7d535a
	set destination to tables-only file
kusano 7d535a
	jpeg_write_tables(&cinfo);
kusano 7d535a
	set destination to image file
kusano 7d535a
	jpeg_start_compress(&cinfo, FALSE);
kusano 7d535a
	write data...
kusano 7d535a
	jpeg_finish_compress(&cinfo);
kusano 7d535a
kusano 7d535a
Since the JPEG parameters are not altered between writing the table file and
kusano 7d535a
the abbreviated image file, the same tables are sure to be used.  Of course,
kusano 7d535a
you can repeat the jpeg_start_compress() ... jpeg_finish_compress() sequence
kusano 7d535a
many times to produce many abbreviated image files matching the table file.
kusano 7d535a
kusano 7d535a
You cannot suppress output of the computed Huffman tables when Huffman
kusano 7d535a
optimization is selected.  (If you could, there'd be no way to decode the
kusano 7d535a
image...)  Generally, you don't want to set optimize_coding = TRUE when
kusano 7d535a
you are trying to produce abbreviated files.
kusano 7d535a
kusano 7d535a
In some cases you might want to compress an image using tables which are
kusano 7d535a
not stored in the application, but are defined in an interchange or
kusano 7d535a
tables-only file readable by the application.  This can be done by setting up
kusano 7d535a
a JPEG decompression object to read the specification file, then copying the
kusano 7d535a
tables into your compression object.  See jpeg_copy_critical_parameters()
kusano 7d535a
for an example of copying quantization tables.
kusano 7d535a
kusano 7d535a
kusano 7d535a
To read abbreviated image files, you simply need to load the proper tables
kusano 7d535a
into the decompression object before trying to read the abbreviated image.
kusano 7d535a
If the proper tables are stored in the application program, you can just
kusano 7d535a
allocate the table structs and fill in their contents directly.  For example,
kusano 7d535a
to load a fixed quantization table into table slot "n":
kusano 7d535a
kusano 7d535a
    if (cinfo.quant_tbl_ptrs[n] == NULL)
kusano 7d535a
      cinfo.quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) &cinfo);
kusano 7d535a
    quant_ptr = cinfo.quant_tbl_ptrs[n];	/* quant_ptr is JQUANT_TBL* */
kusano 7d535a
    for (i = 0; i < 64; i++) {
kusano 7d535a
      /* Qtable[] is desired quantization table, in natural array order */
kusano 7d535a
      quant_ptr->quantval[i] = Qtable[i];
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
Code to load a fixed Huffman table is typically (for AC table "n"):
kusano 7d535a
kusano 7d535a
    if (cinfo.ac_huff_tbl_ptrs[n] == NULL)
kusano 7d535a
      cinfo.ac_huff_tbl_ptrs[n] = jpeg_alloc_huff_table((j_common_ptr) &cinfo);
kusano 7d535a
    huff_ptr = cinfo.ac_huff_tbl_ptrs[n];	/* huff_ptr is JHUFF_TBL* */
kusano 7d535a
    for (i = 1; i <= 16; i++) {
kusano 7d535a
      /* counts[i] is number of Huffman codes of length i bits, i=1..16 */
kusano 7d535a
      huff_ptr->bits[i] = counts[i];
kusano 7d535a
    }
kusano 7d535a
    for (i = 0; i < 256; i++) {
kusano 7d535a
      /* symbols[] is the list of Huffman symbols, in code-length order */
kusano 7d535a
      huff_ptr->huffval[i] = symbols[i];
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
(Note that trying to set cinfo.quant_tbl_ptrs[n] to point directly at a
kusano 7d535a
constant JQUANT_TBL object is not safe.  If the incoming file happened to
kusano 7d535a
contain a quantization table definition, your master table would get
kusano 7d535a
overwritten!  Instead allocate a working table copy and copy the master table
kusano 7d535a
into it, as illustrated above.  Ditto for Huffman tables, of course.)
kusano 7d535a
kusano 7d535a
You might want to read the tables from a tables-only file, rather than
kusano 7d535a
hard-wiring them into your application.  The jpeg_read_header() call is
kusano 7d535a
sufficient to read a tables-only file.  You must pass a second parameter of
kusano 7d535a
FALSE to indicate that you do not require an image to be present.  Thus, the
kusano 7d535a
typical scenario is
kusano 7d535a
kusano 7d535a
	create JPEG decompression object
kusano 7d535a
	set source to tables-only file
kusano 7d535a
	jpeg_read_header(&cinfo, FALSE);
kusano 7d535a
	set source to abbreviated image file
kusano 7d535a
	jpeg_read_header(&cinfo, TRUE);
kusano 7d535a
	set decompression parameters
kusano 7d535a
	jpeg_start_decompress(&cinfo);
kusano 7d535a
	read data...
kusano 7d535a
	jpeg_finish_decompress(&cinfo);
kusano 7d535a
kusano 7d535a
In some cases, you may want to read a file without knowing whether it contains
kusano 7d535a
an image or just tables.  In that case, pass FALSE and check the return value
kusano 7d535a
from jpeg_read_header(): it will be JPEG_HEADER_OK if an image was found,
kusano 7d535a
JPEG_HEADER_TABLES_ONLY if only tables were found.  (A third return value,
kusano 7d535a
JPEG_SUSPENDED, is possible when using a suspending data source manager.)
kusano 7d535a
Note that jpeg_read_header() will not complain if you read an abbreviated
kusano 7d535a
image for which you haven't loaded the missing tables; the missing-table check
kusano 7d535a
occurs later, in jpeg_start_decompress().
kusano 7d535a
kusano 7d535a
kusano 7d535a
It is possible to read a series of images from a single source file by
kusano 7d535a
repeating the jpeg_read_header() ... jpeg_finish_decompress() sequence,
kusano 7d535a
without releasing/recreating the JPEG object or the data source module.
kusano 7d535a
(If you did reinitialize, any partial bufferload left in the data source
kusano 7d535a
buffer at the end of one image would be discarded, causing you to lose the
kusano 7d535a
start of the next image.)  When you use this method, stored tables are
kusano 7d535a
automatically carried forward, so some of the images can be abbreviated images
kusano 7d535a
that depend on tables from earlier images.
kusano 7d535a
kusano 7d535a
If you intend to write a series of images into a single destination file,
kusano 7d535a
you might want to make a specialized data destination module that doesn't
kusano 7d535a
flush the output buffer at term_destination() time.  This would speed things
kusano 7d535a
up by some trifling amount.  Of course, you'd need to remember to flush the
kusano 7d535a
buffer after the last image.  You can make the later images be abbreviated
kusano 7d535a
ones by passing FALSE to jpeg_start_compress().
kusano 7d535a
kusano 7d535a
kusano 7d535a
Special markers
kusano 7d535a
---------------
kusano 7d535a
kusano 7d535a
Some applications may need to insert or extract special data in the JPEG
kusano 7d535a
datastream.  The JPEG standard provides marker types "COM" (comment) and
kusano 7d535a
"APP0" through "APP15" (application) to hold application-specific data.
kusano 7d535a
Unfortunately, the use of these markers is not specified by the standard.
kusano 7d535a
COM markers are fairly widely used to hold user-supplied text.  The JFIF file
kusano 7d535a
format spec uses APP0 markers with specified initial strings to hold certain
kusano 7d535a
data.  Adobe applications use APP14 markers beginning with the string "Adobe"
kusano 7d535a
for miscellaneous data.  Other APPn markers are rarely seen, but might
kusano 7d535a
contain almost anything.
kusano 7d535a
kusano 7d535a
If you wish to store user-supplied text, we recommend you use COM markers
kusano 7d535a
and place readable 7-bit ASCII text in them.  Newline conventions are not
kusano 7d535a
standardized --- expect to find LF (Unix style), CR/LF (DOS style), or CR
kusano 7d535a
(Mac style).  A robust COM reader should be able to cope with random binary
kusano 7d535a
garbage, including nulls, since some applications generate COM markers
kusano 7d535a
containing non-ASCII junk.  (But yours should not be one of them.)
kusano 7d535a
kusano 7d535a
For program-supplied data, use an APPn marker, and be sure to begin it with an
kusano 7d535a
identifying string so that you can tell whether the marker is actually yours.
kusano 7d535a
It's probably best to avoid using APP0 or APP14 for any private markers.
kusano 7d535a
(NOTE: the upcoming SPIFF standard will use APP8 markers; we recommend you
kusano 7d535a
not use APP8 markers for any private purposes, either.)
kusano 7d535a
kusano 7d535a
Keep in mind that at most 65533 bytes can be put into one marker, but you
kusano 7d535a
can have as many markers as you like.
kusano 7d535a
kusano 7d535a
By default, the IJG compression library will write a JFIF APP0 marker if the
kusano 7d535a
selected JPEG colorspace is grayscale or YCbCr, or an Adobe APP14 marker if
kusano 7d535a
the selected colorspace is RGB, CMYK, or YCCK.  You can disable this, but
kusano 7d535a
we don't recommend it.  The decompression library will recognize JFIF and
kusano 7d535a
Adobe markers and will set the JPEG colorspace properly when one is found.
kusano 7d535a
kusano 7d535a
kusano 7d535a
You can write special markers immediately following the datastream header by
kusano 7d535a
calling jpeg_write_marker() after jpeg_start_compress() and before the first
kusano 7d535a
call to jpeg_write_scanlines().  When you do this, the markers appear after
kusano 7d535a
the SOI and the JFIF APP0 and Adobe APP14 markers (if written), but before
kusano 7d535a
all else.  Specify the marker type parameter as "JPEG_COM" for COM or
kusano 7d535a
"JPEG_APP0 + n" for APPn.  (Actually, jpeg_write_marker will let you write
kusano 7d535a
any marker type, but we don't recommend writing any other kinds of marker.)
kusano 7d535a
For example, to write a user comment string pointed to by comment_text:
kusano 7d535a
	jpeg_write_marker(cinfo, JPEG_COM, comment_text, strlen(comment_text));
kusano 7d535a
kusano 7d535a
If it's not convenient to store all the marker data in memory at once,
kusano 7d535a
you can instead call jpeg_write_m_header() followed by multiple calls to
kusano 7d535a
jpeg_write_m_byte().  If you do it this way, it's your responsibility to
kusano 7d535a
call jpeg_write_m_byte() exactly the number of times given in the length
kusano 7d535a
parameter to jpeg_write_m_header().  (This method lets you empty the
kusano 7d535a
output buffer partway through a marker, which might be important when
kusano 7d535a
using a suspending data destination module.  In any case, if you are using
kusano 7d535a
a suspending destination, you should flush its buffer after inserting
kusano 7d535a
any special markers.  See "I/O suspension".)
kusano 7d535a
kusano 7d535a
Or, if you prefer to synthesize the marker byte sequence yourself,
kusano 7d535a
you can just cram it straight into the data destination module.
kusano 7d535a
kusano 7d535a
If you are writing JFIF 1.02 extension markers (thumbnail images), don't
kusano 7d535a
forget to set cinfo.JFIF_minor_version = 2 so that the encoder will write the
kusano 7d535a
correct JFIF version number in the JFIF header marker.  The library's default
kusano 7d535a
is to write version 1.01, but that's wrong if you insert any 1.02 extension
kusano 7d535a
markers.  (We could probably get away with just defaulting to 1.02, but there
kusano 7d535a
used to be broken decoders that would complain about unknown minor version
kusano 7d535a
numbers.  To reduce compatibility risks it's safest not to write 1.02 unless
kusano 7d535a
you are actually using 1.02 extensions.)
kusano 7d535a
kusano 7d535a
kusano 7d535a
When reading, two methods of handling special markers are available:
kusano 7d535a
1. You can ask the library to save the contents of COM and/or APPn markers
kusano 7d535a
into memory, and then examine them at your leisure afterwards.
kusano 7d535a
2. You can supply your own routine to process COM and/or APPn markers
kusano 7d535a
on-the-fly as they are read.
kusano 7d535a
The first method is simpler to use, especially if you are using a suspending
kusano 7d535a
data source; writing a marker processor that copes with input suspension is
kusano 7d535a
not easy (consider what happens if the marker is longer than your available
kusano 7d535a
input buffer).  However, the second method conserves memory since the marker
kusano 7d535a
data need not be kept around after it's been processed.
kusano 7d535a
kusano 7d535a
For either method, you'd normally set up marker handling after creating a
kusano 7d535a
decompression object and before calling jpeg_read_header(), because the
kusano 7d535a
markers of interest will typically be near the head of the file and so will
kusano 7d535a
be scanned by jpeg_read_header.  Once you've established a marker handling
kusano 7d535a
method, it will be used for the life of that decompression object
kusano 7d535a
(potentially many datastreams), unless you change it.  Marker handling is
kusano 7d535a
determined separately for COM markers and for each APPn marker code.
kusano 7d535a
kusano 7d535a
kusano 7d535a
To save the contents of special markers in memory, call
kusano 7d535a
	jpeg_save_markers(cinfo, marker_code, length_limit)
kusano 7d535a
where marker_code is the marker type to save, JPEG_COM or JPEG_APP0+n.
kusano 7d535a
(To arrange to save all the special marker types, you need to call this
kusano 7d535a
routine 17 times, for COM and APP0-APP15.)  If the incoming marker is longer
kusano 7d535a
than length_limit data bytes, only length_limit bytes will be saved; this
kusano 7d535a
parameter allows you to avoid chewing up memory when you only need to see the
kusano 7d535a
first few bytes of a potentially large marker.  If you want to save all the
kusano 7d535a
data, set length_limit to 0xFFFF; that is enough since marker lengths are only
kusano 7d535a
16 bits.  As a special case, setting length_limit to 0 prevents that marker
kusano 7d535a
type from being saved at all.  (That is the default behavior, in fact.)
kusano 7d535a
kusano 7d535a
After jpeg_read_header() completes, you can examine the special markers by
kusano 7d535a
following the cinfo->marker_list pointer chain.  All the special markers in
kusano 7d535a
the file appear in this list, in order of their occurrence in the file (but
kusano 7d535a
omitting any markers of types you didn't ask for).  Both the original data
kusano 7d535a
length and the saved data length are recorded for each list entry; the latter
kusano 7d535a
will not exceed length_limit for the particular marker type.  Note that these
kusano 7d535a
lengths exclude the marker length word, whereas the stored representation
kusano 7d535a
within the JPEG file includes it.  (Hence the maximum data length is really
kusano 7d535a
only 65533.)
kusano 7d535a
kusano 7d535a
It is possible that additional special markers appear in the file beyond the
kusano 7d535a
SOS marker at which jpeg_read_header stops; if so, the marker list will be
kusano 7d535a
extended during reading of the rest of the file.  This is not expected to be
kusano 7d535a
common, however.  If you are short on memory you may want to reset the length
kusano 7d535a
limit to zero for all marker types after finishing jpeg_read_header, to
kusano 7d535a
ensure that the max_memory_to_use setting cannot be exceeded due to addition
kusano 7d535a
of later markers.
kusano 7d535a
kusano 7d535a
The marker list remains stored until you call jpeg_finish_decompress or
kusano 7d535a
jpeg_abort, at which point the memory is freed and the list is set to empty.
kusano 7d535a
(jpeg_destroy also releases the storage, of course.)
kusano 7d535a
kusano 7d535a
Note that the library is internally interested in APP0 and APP14 markers;
kusano 7d535a
if you try to set a small nonzero length limit on these types, the library
kusano 7d535a
will silently force the length up to the minimum it wants.  (But you can set
kusano 7d535a
a zero length limit to prevent them from being saved at all.)  Also, in a
kusano 7d535a
16-bit environment, the maximum length limit may be constrained to less than
kusano 7d535a
65533 by malloc() limitations.  It is therefore best not to assume that the
kusano 7d535a
effective length limit is exactly what you set it to be.
kusano 7d535a
kusano 7d535a
kusano 7d535a
If you want to supply your own marker-reading routine, you do it by calling
kusano 7d535a
jpeg_set_marker_processor().  A marker processor routine must have the
kusano 7d535a
signature
kusano 7d535a
	boolean jpeg_marker_parser_method (j_decompress_ptr cinfo)
kusano 7d535a
Although the marker code is not explicitly passed, the routine can find it
kusano 7d535a
in cinfo->unread_marker.  At the time of call, the marker proper has been
kusano 7d535a
read from the data source module.  The processor routine is responsible for
kusano 7d535a
reading the marker length word and the remaining parameter bytes, if any.
kusano 7d535a
Return TRUE to indicate success.  (FALSE should be returned only if you are
kusano 7d535a
using a suspending data source and it tells you to suspend.  See the standard
kusano 7d535a
marker processors in jdmarker.c for appropriate coding methods if you need to
kusano 7d535a
use a suspending data source.)
kusano 7d535a
kusano 7d535a
If you override the default APP0 or APP14 processors, it is up to you to
kusano 7d535a
recognize JFIF and Adobe markers if you want colorspace recognition to occur
kusano 7d535a
properly.  We recommend copying and extending the default processors if you
kusano 7d535a
want to do that.  (A better idea is to save these marker types for later
kusano 7d535a
examination by calling jpeg_save_markers(); that method doesn't interfere
kusano 7d535a
with the library's own processing of these markers.)
kusano 7d535a
kusano 7d535a
jpeg_set_marker_processor() and jpeg_save_markers() are mutually exclusive
kusano 7d535a
--- if you call one it overrides any previous call to the other, for the
kusano 7d535a
particular marker type specified.
kusano 7d535a
kusano 7d535a
A simple example of an external COM processor can be found in djpeg.c.
kusano 7d535a
Also, see jpegtran.c for an example of using jpeg_save_markers.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Raw (downsampled) image data
kusano 7d535a
----------------------------
kusano 7d535a
kusano 7d535a
Some applications need to supply already-downsampled image data to the JPEG
kusano 7d535a
compressor, or to receive raw downsampled data from the decompressor.  The
kusano 7d535a
library supports this requirement by allowing the application to write or
kusano 7d535a
read raw data, bypassing the normal preprocessing or postprocessing steps.
kusano 7d535a
The interface is different from the standard one and is somewhat harder to
kusano 7d535a
use.  If your interest is merely in bypassing color conversion, we recommend
kusano 7d535a
that you use the standard interface and simply set jpeg_color_space =
kusano 7d535a
in_color_space (or jpeg_color_space = out_color_space for decompression).
kusano 7d535a
The mechanism described in this section is necessary only to supply or
kusano 7d535a
receive downsampled image data, in which not all components have the same
kusano 7d535a
dimensions.
kusano 7d535a
kusano 7d535a
kusano 7d535a
To compress raw data, you must supply the data in the colorspace to be used
kusano 7d535a
in the JPEG file (please read the earlier section on Special color spaces)
kusano 7d535a
and downsampled to the sampling factors specified in the JPEG parameters.
kusano 7d535a
You must supply the data in the format used internally by the JPEG library,
kusano 7d535a
namely a JSAMPIMAGE array.  This is an array of pointers to two-dimensional
kusano 7d535a
arrays, each of type JSAMPARRAY.  Each 2-D array holds the values for one
kusano 7d535a
color component.  This structure is necessary since the components are of
kusano 7d535a
different sizes.  If the image dimensions are not a multiple of the MCU size,
kusano 7d535a
you must also pad the data correctly (usually, this is done by replicating
kusano 7d535a
the last column and/or row).  The data must be padded to a multiple of a DCT
kusano 7d535a
block in each component: that is, each downsampled row must contain a
kusano 7d535a
multiple of 8 valid samples, and there must be a multiple of 8 sample rows
kusano 7d535a
for each component.  (For applications such as conversion of digital TV
kusano 7d535a
images, the standard image size is usually a multiple of the DCT block size,
kusano 7d535a
so that no padding need actually be done.)
kusano 7d535a
kusano 7d535a
The procedure for compression of raw data is basically the same as normal
kusano 7d535a
compression, except that you call jpeg_write_raw_data() in place of
kusano 7d535a
jpeg_write_scanlines().  Before calling jpeg_start_compress(), you must do
kusano 7d535a
the following:
kusano 7d535a
  * Set cinfo->raw_data_in to TRUE.  (It is set FALSE by jpeg_set_defaults().)
kusano 7d535a
    This notifies the library that you will be supplying raw data.
kusano 7d535a
    Furthermore, set cinfo->do_fancy_downsampling to FALSE if you want to use
kusano 7d535a
    real downsampled data.  (It is set TRUE by jpeg_set_defaults().)
kusano 7d535a
  * Ensure jpeg_color_space is correct --- an explicit jpeg_set_colorspace()
kusano 7d535a
    call is a good idea.  Note that since color conversion is bypassed,
kusano 7d535a
    in_color_space is ignored, except that jpeg_set_defaults() uses it to
kusano 7d535a
    choose the default jpeg_color_space setting.
kusano 7d535a
  * Ensure the sampling factors, cinfo->comp_info[i].h_samp_factor and
kusano 7d535a
    cinfo->comp_info[i].v_samp_factor, are correct.  Since these indicate the
kusano 7d535a
    dimensions of the data you are supplying, it's wise to set them
kusano 7d535a
    explicitly, rather than assuming the library's defaults are what you want.
kusano 7d535a
kusano 7d535a
To pass raw data to the library, call jpeg_write_raw_data() in place of
kusano 7d535a
jpeg_write_scanlines().  The two routines work similarly except that
kusano 7d535a
jpeg_write_raw_data takes a JSAMPIMAGE data array rather than JSAMPARRAY.
kusano 7d535a
The scanlines count passed to and returned from jpeg_write_raw_data is
kusano 7d535a
measured in terms of the component with the largest v_samp_factor.
kusano 7d535a
kusano 7d535a
jpeg_write_raw_data() processes one MCU row per call, which is to say
kusano 7d535a
v_samp_factor*DCTSIZE sample rows of each component.  The passed num_lines
kusano 7d535a
value must be at least max_v_samp_factor*DCTSIZE, and the return value will
kusano 7d535a
be exactly that amount (or possibly some multiple of that amount, in future
kusano 7d535a
library versions).  This is true even on the last call at the bottom of the
kusano 7d535a
image; don't forget to pad your data as necessary.
kusano 7d535a
kusano 7d535a
The required dimensions of the supplied data can be computed for each
kusano 7d535a
component as
kusano 7d535a
	cinfo->comp_info[i].width_in_blocks*DCTSIZE  samples per row
kusano 7d535a
	cinfo->comp_info[i].height_in_blocks*DCTSIZE rows in image
kusano 7d535a
after jpeg_start_compress() has initialized those fields.  If the valid data
kusano 7d535a
is smaller than this, it must be padded appropriately.  For some sampling
kusano 7d535a
factors and image sizes, additional dummy DCT blocks are inserted to make
kusano 7d535a
the image a multiple of the MCU dimensions.  The library creates such dummy
kusano 7d535a
blocks itself; it does not read them from your supplied data.  Therefore you
kusano 7d535a
need never pad by more than DCTSIZE samples.  An example may help here.
kusano 7d535a
Assume 2h2v downsampling of YCbCr data, that is
kusano 7d535a
	cinfo->comp_info[0].h_samp_factor = 2		for Y
kusano 7d535a
	cinfo->comp_info[0].v_samp_factor = 2
kusano 7d535a
	cinfo->comp_info[1].h_samp_factor = 1		for Cb
kusano 7d535a
	cinfo->comp_info[1].v_samp_factor = 1
kusano 7d535a
	cinfo->comp_info[2].h_samp_factor = 1		for Cr
kusano 7d535a
	cinfo->comp_info[2].v_samp_factor = 1
kusano 7d535a
and suppose that the nominal image dimensions (cinfo->image_width and
kusano 7d535a
cinfo->image_height) are 101x101 pixels.  Then jpeg_start_compress() will
kusano 7d535a
compute downsampled_width = 101 and width_in_blocks = 13 for Y,
kusano 7d535a
downsampled_width = 51 and width_in_blocks = 7 for Cb and Cr (and the same
kusano 7d535a
for the height fields).  You must pad the Y data to at least 13*8 = 104
kusano 7d535a
columns and rows, the Cb/Cr data to at least 7*8 = 56 columns and rows.  The
kusano 7d535a
MCU height is max_v_samp_factor = 2 DCT rows so you must pass at least 16
kusano 7d535a
scanlines on each call to jpeg_write_raw_data(), which is to say 16 actual
kusano 7d535a
sample rows of Y and 8 each of Cb and Cr.  A total of 7 MCU rows are needed,
kusano 7d535a
so you must pass a total of 7*16 = 112 "scanlines".  The last DCT block row
kusano 7d535a
of Y data is dummy, so it doesn't matter what you pass for it in the data
kusano 7d535a
arrays, but the scanlines count must total up to 112 so that all of the Cb
kusano 7d535a
and Cr data gets passed.
kusano 7d535a
kusano 7d535a
Output suspension is supported with raw-data compression: if the data
kusano 7d535a
destination module suspends, jpeg_write_raw_data() will return 0.
kusano 7d535a
In this case the same data rows must be passed again on the next call.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Decompression with raw data output implies bypassing all postprocessing.
kusano 7d535a
You must deal with the color space and sampling factors present in the
kusano 7d535a
incoming file.  If your application only handles, say, 2h1v YCbCr data,
kusano 7d535a
you must check for and fail on other color spaces or other sampling factors.
kusano 7d535a
The library will not convert to a different color space for you.
kusano 7d535a
kusano 7d535a
To obtain raw data output, set cinfo->raw_data_out = TRUE before
kusano 7d535a
jpeg_start_decompress() (it is set FALSE by jpeg_read_header()).  Be sure to
kusano 7d535a
verify that the color space and sampling factors are ones you can handle.
kusano 7d535a
Furthermore, set cinfo->do_fancy_upsampling = FALSE if you want to get real
kusano 7d535a
downsampled data (it is set TRUE by jpeg_read_header()).
kusano 7d535a
Then call jpeg_read_raw_data() in place of jpeg_read_scanlines().  The
kusano 7d535a
decompression process is otherwise the same as usual.
kusano 7d535a
kusano 7d535a
jpeg_read_raw_data() returns one MCU row per call, and thus you must pass a
kusano 7d535a
buffer of at least max_v_samp_factor*DCTSIZE scanlines (scanline counting is
kusano 7d535a
the same as for raw-data compression).  The buffer you pass must be large
kusano 7d535a
enough to hold the actual data plus padding to DCT-block boundaries.  As with
kusano 7d535a
compression, any entirely dummy DCT blocks are not processed so you need not
kusano 7d535a
allocate space for them, but the total scanline count includes them.  The
kusano 7d535a
above example of computing buffer dimensions for raw-data compression is
kusano 7d535a
equally valid for decompression.
kusano 7d535a
kusano 7d535a
Input suspension is supported with raw-data decompression: if the data source
kusano 7d535a
module suspends, jpeg_read_raw_data() will return 0.  You can also use
kusano 7d535a
buffered-image mode to read raw data in multiple passes.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Really raw data: DCT coefficients
kusano 7d535a
---------------------------------
kusano 7d535a
kusano 7d535a
It is possible to read or write the contents of a JPEG file as raw DCT
kusano 7d535a
coefficients.  This facility is mainly intended for use in lossless
kusano 7d535a
transcoding between different JPEG file formats.  Other possible applications
kusano 7d535a
include lossless cropping of a JPEG image, lossless reassembly of a
kusano 7d535a
multi-strip or multi-tile TIFF/JPEG file into a single JPEG datastream, etc.
kusano 7d535a
kusano 7d535a
To read the contents of a JPEG file as DCT coefficients, open the file and do
kusano 7d535a
jpeg_read_header() as usual.  But instead of calling jpeg_start_decompress()
kusano 7d535a
and jpeg_read_scanlines(), call jpeg_read_coefficients().  This will read the
kusano 7d535a
entire image into a set of virtual coefficient-block arrays, one array per
kusano 7d535a
component.  The return value is a pointer to an array of virtual-array
kusano 7d535a
descriptors.  Each virtual array can be accessed directly using the JPEG
kusano 7d535a
memory manager's access_virt_barray method (see Memory management, below,
kusano 7d535a
and also read structure.txt's discussion of virtual array handling).  Or,
kusano 7d535a
for simple transcoding to a different JPEG file format, the array list can
kusano 7d535a
just be handed directly to jpeg_write_coefficients().
kusano 7d535a
kusano 7d535a
Each block in the block arrays contains quantized coefficient values in
kusano 7d535a
normal array order (not JPEG zigzag order).  The block arrays contain only
kusano 7d535a
DCT blocks containing real data; any entirely-dummy blocks added to fill out
kusano 7d535a
interleaved MCUs at the right or bottom edges of the image are discarded
kusano 7d535a
during reading and are not stored in the block arrays.  (The size of each
kusano 7d535a
block array can be determined from the width_in_blocks and height_in_blocks
kusano 7d535a
fields of the component's comp_info entry.)  This is also the data format
kusano 7d535a
expected by jpeg_write_coefficients().
kusano 7d535a
kusano 7d535a
When you are done using the virtual arrays, call jpeg_finish_decompress()
kusano 7d535a
to release the array storage and return the decompression object to an idle
kusano 7d535a
state; or just call jpeg_destroy() if you don't need to reuse the object.
kusano 7d535a
kusano 7d535a
If you use a suspending data source, jpeg_read_coefficients() will return
kusano 7d535a
NULL if it is forced to suspend; a non-NULL return value indicates successful
kusano 7d535a
completion.  You need not test for a NULL return value when using a
kusano 7d535a
non-suspending data source.
kusano 7d535a
kusano 7d535a
It is also possible to call jpeg_read_coefficients() to obtain access to the
kusano 7d535a
decoder's coefficient arrays during a normal decode cycle in buffered-image
kusano 7d535a
mode.  This frammish might be useful for progressively displaying an incoming
kusano 7d535a
image and then re-encoding it without loss.  To do this, decode in buffered-
kusano 7d535a
image mode as discussed previously, then call jpeg_read_coefficients() after
kusano 7d535a
the last jpeg_finish_output() call.  The arrays will be available for your use
kusano 7d535a
until you call jpeg_finish_decompress().
kusano 7d535a
kusano 7d535a
kusano 7d535a
To write the contents of a JPEG file as DCT coefficients, you must provide
kusano 7d535a
the DCT coefficients stored in virtual block arrays.  You can either pass
kusano 7d535a
block arrays read from an input JPEG file by jpeg_read_coefficients(), or
kusano 7d535a
allocate virtual arrays from the JPEG compression object and fill them
kusano 7d535a
yourself.  In either case, jpeg_write_coefficients() is substituted for
kusano 7d535a
jpeg_start_compress() and jpeg_write_scanlines().  Thus the sequence is
kusano 7d535a
  * Create compression object
kusano 7d535a
  * Set all compression parameters as necessary
kusano 7d535a
  * Request virtual arrays if needed
kusano 7d535a
  * jpeg_write_coefficients()
kusano 7d535a
  * jpeg_finish_compress()
kusano 7d535a
  * Destroy or re-use compression object
kusano 7d535a
jpeg_write_coefficients() is passed a pointer to an array of virtual block
kusano 7d535a
array descriptors; the number of arrays is equal to cinfo.num_components.
kusano 7d535a
kusano 7d535a
The virtual arrays need only have been requested, not realized, before
kusano 7d535a
jpeg_write_coefficients() is called.  A side-effect of
kusano 7d535a
jpeg_write_coefficients() is to realize any virtual arrays that have been
kusano 7d535a
requested from the compression object's memory manager.  Thus, when obtaining
kusano 7d535a
the virtual arrays from the compression object, you should fill the arrays
kusano 7d535a
after calling jpeg_write_coefficients().  The data is actually written out
kusano 7d535a
when you call jpeg_finish_compress(); jpeg_write_coefficients() only writes
kusano 7d535a
the file header.
kusano 7d535a
kusano 7d535a
When writing raw DCT coefficients, it is crucial that the JPEG quantization
kusano 7d535a
tables and sampling factors match the way the data was encoded, or the
kusano 7d535a
resulting file will be invalid.  For transcoding from an existing JPEG file,
kusano 7d535a
we recommend using jpeg_copy_critical_parameters().  This routine initializes
kusano 7d535a
all the compression parameters to default values (like jpeg_set_defaults()),
kusano 7d535a
then copies the critical information from a source decompression object.
kusano 7d535a
The decompression object should have just been used to read the entire
kusano 7d535a
JPEG input file --- that is, it should be awaiting jpeg_finish_decompress().
kusano 7d535a
kusano 7d535a
jpeg_write_coefficients() marks all tables stored in the compression object
kusano 7d535a
as needing to be written to the output file (thus, it acts like
kusano 7d535a
jpeg_start_compress(cinfo, TRUE)).  This is for safety's sake, to avoid
kusano 7d535a
emitting abbreviated JPEG files by accident.  If you really want to emit an
kusano 7d535a
abbreviated JPEG file, call jpeg_suppress_tables(), or set the tables'
kusano 7d535a
individual sent_table flags, between calling jpeg_write_coefficients() and
kusano 7d535a
jpeg_finish_compress().
kusano 7d535a
kusano 7d535a
kusano 7d535a
Progress monitoring
kusano 7d535a
-------------------
kusano 7d535a
kusano 7d535a
Some applications may need to regain control from the JPEG library every so
kusano 7d535a
often.  The typical use of this feature is to produce a percent-done bar or
kusano 7d535a
other progress display.  (For a simple example, see cjpeg.c or djpeg.c.)
kusano 7d535a
Although you do get control back frequently during the data-transferring pass
kusano 7d535a
(the jpeg_read_scanlines or jpeg_write_scanlines loop), any additional passes
kusano 7d535a
will occur inside jpeg_finish_compress or jpeg_start_decompress; those
kusano 7d535a
routines may take a long time to execute, and you don't get control back
kusano 7d535a
until they are done.
kusano 7d535a
kusano 7d535a
You can define a progress-monitor routine which will be called periodically
kusano 7d535a
by the library.  No guarantees are made about how often this call will occur,
kusano 7d535a
so we don't recommend you use it for mouse tracking or anything like that.
kusano 7d535a
At present, a call will occur once per MCU row, scanline, or sample row
kusano 7d535a
group, whichever unit is convenient for the current processing mode; so the
kusano 7d535a
wider the image, the longer the time between calls.  During the data
kusano 7d535a
transferring pass, only one call occurs per call of jpeg_read_scanlines or
kusano 7d535a
jpeg_write_scanlines, so don't pass a large number of scanlines at once if
kusano 7d535a
you want fine resolution in the progress count.  (If you really need to use
kusano 7d535a
the callback mechanism for time-critical tasks like mouse tracking, you could
kusano 7d535a
insert additional calls inside some of the library's inner loops.)
kusano 7d535a
kusano 7d535a
To establish a progress-monitor callback, create a struct jpeg_progress_mgr,
kusano 7d535a
fill in its progress_monitor field with a pointer to your callback routine,
kusano 7d535a
and set cinfo->progress to point to the struct.  The callback will be called
kusano 7d535a
whenever cinfo->progress is non-NULL.  (This pointer is set to NULL by
kusano 7d535a
jpeg_create_compress or jpeg_create_decompress; the library will not change
kusano 7d535a
it thereafter.  So if you allocate dynamic storage for the progress struct,
kusano 7d535a
make sure it will live as long as the JPEG object does.  Allocating from the
kusano 7d535a
JPEG memory manager with lifetime JPOOL_PERMANENT will work nicely.)  You
kusano 7d535a
can use the same callback routine for both compression and decompression.
kusano 7d535a
kusano 7d535a
The jpeg_progress_mgr struct contains four fields which are set by the library:
kusano 7d535a
	long pass_counter;	/* work units completed in this pass */
kusano 7d535a
	long pass_limit;	/* total number of work units in this pass */
kusano 7d535a
	int completed_passes;	/* passes completed so far */
kusano 7d535a
	int total_passes;	/* total number of passes expected */
kusano 7d535a
During any one pass, pass_counter increases from 0 up to (not including)
kusano 7d535a
pass_limit; the step size is usually but not necessarily 1.  The pass_limit
kusano 7d535a
value may change from one pass to another.  The expected total number of
kusano 7d535a
passes is in total_passes, and the number of passes already completed is in
kusano 7d535a
completed_passes.  Thus the fraction of work completed may be estimated as
kusano 7d535a
		completed_passes + (pass_counter/pass_limit)
kusano 7d535a
		--------------------------------------------
kusano 7d535a
				total_passes
kusano 7d535a
ignoring the fact that the passes may not be equal amounts of work.
kusano 7d535a
kusano 7d535a
When decompressing, pass_limit can even change within a pass, because it
kusano 7d535a
depends on the number of scans in the JPEG file, which isn't always known in
kusano 7d535a
advance.  The computed fraction-of-work-done may jump suddenly (if the library
kusano 7d535a
discovers it has overestimated the number of scans) or even decrease (in the
kusano 7d535a
opposite case).  It is not wise to put great faith in the work estimate.
kusano 7d535a
kusano 7d535a
When using the decompressor's buffered-image mode, the progress monitor work
kusano 7d535a
estimate is likely to be completely unhelpful, because the library has no way
kusano 7d535a
to know how many output passes will be demanded of it.  Currently, the library
kusano 7d535a
sets total_passes based on the assumption that there will be one more output
kusano 7d535a
pass if the input file end hasn't yet been read (jpeg_input_complete() isn't
kusano 7d535a
TRUE), but no more output passes if the file end has been reached when the
kusano 7d535a
output pass is started.  This means that total_passes will rise as additional
kusano 7d535a
output passes are requested.  If you have a way of determining the input file
kusano 7d535a
size, estimating progress based on the fraction of the file that's been read
kusano 7d535a
will probably be more useful than using the library's value.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Memory management
kusano 7d535a
-----------------
kusano 7d535a
kusano 7d535a
This section covers some key facts about the JPEG library's built-in memory
kusano 7d535a
manager.  For more info, please read structure.txt's section about the memory
kusano 7d535a
manager, and consult the source code if necessary.
kusano 7d535a
kusano 7d535a
All memory and temporary file allocation within the library is done via the
kusano 7d535a
memory manager.  If necessary, you can replace the "back end" of the memory
kusano 7d535a
manager to control allocation yourself (for example, if you don't want the
kusano 7d535a
library to use malloc() and free() for some reason).
kusano 7d535a
kusano 7d535a
Some data is allocated "permanently" and will not be freed until the JPEG
kusano 7d535a
object is destroyed.  Most data is allocated "per image" and is freed by
kusano 7d535a
jpeg_finish_compress, jpeg_finish_decompress, or jpeg_abort.  You can call the
kusano 7d535a
memory manager yourself to allocate structures that will automatically be
kusano 7d535a
freed at these times.  Typical code for this is
kusano 7d535a
  ptr = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, size);
kusano 7d535a
Use JPOOL_PERMANENT to get storage that lasts as long as the JPEG object.
kusano 7d535a
Use alloc_large instead of alloc_small for anything bigger than a few Kbytes.
kusano 7d535a
There are also alloc_sarray and alloc_barray routines that automatically
kusano 7d535a
build 2-D sample or block arrays.
kusano 7d535a
kusano 7d535a
The library's minimum space requirements to process an image depend on the
kusano 7d535a
image's width, but not on its height, because the library ordinarily works
kusano 7d535a
with "strip" buffers that are as wide as the image but just a few rows high.
kusano 7d535a
Some operating modes (eg, two-pass color quantization) require full-image
kusano 7d535a
buffers.  Such buffers are treated as "virtual arrays": only the current strip
kusano 7d535a
need be in memory, and the rest can be swapped out to a temporary file.
kusano 7d535a
kusano 7d535a
If you use the simplest memory manager back end (jmemnobs.c), then no
kusano 7d535a
temporary files are used; virtual arrays are simply malloc()'d.  Images bigger
kusano 7d535a
than memory can be processed only if your system supports virtual memory.
kusano 7d535a
The other memory manager back ends support temporary files of various flavors
kusano 7d535a
and thus work in machines without virtual memory.  They may also be useful on
kusano 7d535a
Unix machines if you need to process images that exceed available swap space.
kusano 7d535a
kusano 7d535a
When using temporary files, the library will make the in-memory buffers for
kusano 7d535a
its virtual arrays just big enough to stay within a "maximum memory" setting.
kusano 7d535a
Your application can set this limit by setting cinfo->mem->max_memory_to_use
kusano 7d535a
after creating the JPEG object.  (Of course, there is still a minimum size for
kusano 7d535a
the buffers, so the max-memory setting is effective only if it is bigger than
kusano 7d535a
the minimum space needed.)  If you allocate any large structures yourself, you
kusano 7d535a
must allocate them before jpeg_start_compress() or jpeg_start_decompress() in
kusano 7d535a
order to have them counted against the max memory limit.  Also keep in mind
kusano 7d535a
that space allocated with alloc_small() is ignored, on the assumption that
kusano 7d535a
it's too small to be worth worrying about; so a reasonable safety margin
kusano 7d535a
should be left when setting max_memory_to_use.
kusano 7d535a
kusano 7d535a
If you use the jmemname.c or jmemdos.c memory manager back end, it is
kusano 7d535a
important to clean up the JPEG object properly to ensure that the temporary
kusano 7d535a
files get deleted.  (This is especially crucial with jmemdos.c, where the
kusano 7d535a
"temporary files" may be extended-memory segments; if they are not freed,
kusano 7d535a
DOS will require a reboot to recover the memory.)  Thus, with these memory
kusano 7d535a
managers, it's a good idea to provide a signal handler that will trap any
kusano 7d535a
early exit from your program.  The handler should call either jpeg_abort()
kusano 7d535a
or jpeg_destroy() for any active JPEG objects.  A handler is not needed with
kusano 7d535a
jmemnobs.c, and shouldn't be necessary with jmemansi.c or jmemmac.c either,
kusano 7d535a
since the C library is supposed to take care of deleting files made with
kusano 7d535a
tmpfile().
kusano 7d535a
kusano 7d535a
kusano 7d535a
Memory usage
kusano 7d535a
------------
kusano 7d535a
kusano 7d535a
Working memory requirements while performing compression or decompression
kusano 7d535a
depend on image dimensions, image characteristics (such as colorspace and
kusano 7d535a
JPEG process), and operating mode (application-selected options).
kusano 7d535a
kusano 7d535a
As of v6b, the decompressor requires:
kusano 7d535a
 1. About 24K in more-or-less-fixed-size data.  This varies a bit depending
kusano 7d535a
    on operating mode and image characteristics (particularly color vs.
kusano 7d535a
    grayscale), but it doesn't depend on image dimensions.
kusano 7d535a
 2. Strip buffers (of size proportional to the image width) for IDCT and
kusano 7d535a
    upsampling results.  The worst case for commonly used sampling factors
kusano 7d535a
    is about 34 bytes * width in pixels for a color image.  A grayscale image
kusano 7d535a
    only needs about 8 bytes per pixel column.
kusano 7d535a
 3. A full-image DCT coefficient buffer is needed to decode a multi-scan JPEG
kusano 7d535a
    file (including progressive JPEGs), or whenever you select buffered-image
kusano 7d535a
    mode.  This takes 2 bytes/coefficient.  At typical 2x2 sampling, that's
kusano 7d535a
    3 bytes per pixel for a color image.  Worst case (1x1 sampling) requires
kusano 7d535a
    6 bytes/pixel.  For grayscale, figure 2 bytes/pixel.
kusano 7d535a
 4. To perform 2-pass color quantization, the decompressor also needs a
kusano 7d535a
    128K color lookup table and a full-image pixel buffer (3 bytes/pixel).
kusano 7d535a
This does not count any memory allocated by the application, such as a
kusano 7d535a
buffer to hold the final output image.
kusano 7d535a
kusano 7d535a
The above figures are valid for 8-bit JPEG data precision and a machine with
kusano 7d535a
32-bit ints.  For 12-bit JPEG data, double the size of the strip buffers and
kusano 7d535a
quantization pixel buffer.  The "fixed-size" data will be somewhat smaller
kusano 7d535a
with 16-bit ints, larger with 64-bit ints.  Also, CMYK or other unusual
kusano 7d535a
color spaces will require different amounts of space.
kusano 7d535a
kusano 7d535a
The full-image coefficient and pixel buffers, if needed at all, do not
kusano 7d535a
have to be fully RAM resident; you can have the library use temporary
kusano 7d535a
files instead when the total memory usage would exceed a limit you set.
kusano 7d535a
(But if your OS supports virtual memory, it's probably better to just use
kusano 7d535a
jmemnobs and let the OS do the swapping.)
kusano 7d535a
kusano 7d535a
The compressor's memory requirements are similar, except that it has no need
kusano 7d535a
for color quantization.  Also, it needs a full-image DCT coefficient buffer
kusano 7d535a
if Huffman-table optimization is asked for, even if progressive mode is not
kusano 7d535a
requested.
kusano 7d535a
kusano 7d535a
If you need more detailed information about memory usage in a particular
kusano 7d535a
situation, you can enable the MEM_STATS code in jmemmgr.c.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Library compile-time options
kusano 7d535a
----------------------------
kusano 7d535a
kusano 7d535a
A number of compile-time options are available by modifying jmorecfg.h.
kusano 7d535a
kusano 7d535a
The JPEG standard provides for both the baseline 8-bit DCT process and
kusano 7d535a
a 12-bit DCT process.  The IJG code supports 12-bit JPEG if you define
kusano 7d535a
BITS_IN_JSAMPLE as 12 rather than 8.  Note that this causes JSAMPLE to be
kusano 7d535a
larger than a char, so it affects the surrounding application's image data.
kusano 7d535a
The sample applications cjpeg and djpeg can support 12-bit mode only for PPM
kusano 7d535a
and GIF file formats; you must disable the other file formats to compile a
kusano 7d535a
12-bit cjpeg or djpeg.  (install.txt has more information about that.)
kusano 7d535a
At present, a 12-bit library can handle *only* 12-bit images, not both
kusano 7d535a
precisions.  (If you need to include both 8- and 12-bit libraries in a single
kusano 7d535a
application, you could probably do it by defining NEED_SHORT_EXTERNAL_NAMES
kusano 7d535a
for just one of the copies.  You'd have to access the 8-bit and 12-bit copies
kusano 7d535a
from separate application source files.  This is untested ... if you try it,
kusano 7d535a
we'd like to hear whether it works!)
kusano 7d535a
kusano 7d535a
Note that a 12-bit library always compresses in Huffman optimization mode,
kusano 7d535a
in order to generate valid Huffman tables.  This is necessary because our
kusano 7d535a
default Huffman tables only cover 8-bit data.  If you need to output 12-bit
kusano 7d535a
files in one pass, you'll have to supply suitable default Huffman tables.
kusano 7d535a
You may also want to supply your own DCT quantization tables; the existing
kusano 7d535a
quality-scaling code has been developed for 8-bit use, and probably doesn't
kusano 7d535a
generate especially good tables for 12-bit.
kusano 7d535a
kusano 7d535a
The maximum number of components (color channels) in the image is determined
kusano 7d535a
by MAX_COMPONENTS.  The JPEG standard allows up to 255 components, but we
kusano 7d535a
expect that few applications will need more than four or so.
kusano 7d535a
kusano 7d535a
On machines with unusual data type sizes, you may be able to improve
kusano 7d535a
performance or reduce memory space by tweaking the various typedefs in
kusano 7d535a
jmorecfg.h.  In particular, on some RISC CPUs, access to arrays of "short"s
kusano 7d535a
is quite slow; consider trading memory for speed by making JCOEF, INT16, and
kusano 7d535a
UINT16 be "int" or "unsigned int".  UINT8 is also a candidate to become int.
kusano 7d535a
You probably don't want to make JSAMPLE be int unless you have lots of memory
kusano 7d535a
to burn.
kusano 7d535a
kusano 7d535a
You can reduce the size of the library by compiling out various optional
kusano 7d535a
functions.  To do this, undefine xxx_SUPPORTED symbols as necessary.
kusano 7d535a
kusano 7d535a
You can also save a few K by not having text error messages in the library;
kusano 7d535a
the standard error message table occupies about 5Kb.  This is particularly
kusano 7d535a
reasonable for embedded applications where there's no good way to display 
kusano 7d535a
a message anyway.  To do this, remove the creation of the message table
kusano 7d535a
(jpeg_std_message_table[]) from jerror.c, and alter format_message to do
kusano 7d535a
something reasonable without it.  You could output the numeric value of the
kusano 7d535a
message code number, for example.  If you do this, you can also save a couple
kusano 7d535a
more K by modifying the TRACEMSn() macros in jerror.h to expand to nothing;
kusano 7d535a
you don't need trace capability anyway, right?
kusano 7d535a
kusano 7d535a
kusano 7d535a
Portability considerations
kusano 7d535a
--------------------------
kusano 7d535a
kusano 7d535a
The JPEG library has been written to be extremely portable; the sample
kusano 7d535a
applications cjpeg and djpeg are slightly less so.  This section summarizes
kusano 7d535a
the design goals in this area.  (If you encounter any bugs that cause the
kusano 7d535a
library to be less portable than is claimed here, we'd appreciate hearing
kusano 7d535a
about them.)
kusano 7d535a
kusano 7d535a
The code works fine on ANSI C, C++, and pre-ANSI C compilers, using any of
kusano 7d535a
the popular system include file setups, and some not-so-popular ones too.
kusano 7d535a
See install.txt for configuration procedures.
kusano 7d535a
kusano 7d535a
The code is not dependent on the exact sizes of the C data types.  As
kusano 7d535a
distributed, we make the assumptions that
kusano 7d535a
	char	is at least 8 bits wide
kusano 7d535a
	short	is at least 16 bits wide
kusano 7d535a
	int	is at least 16 bits wide
kusano 7d535a
	long	is at least 32 bits wide
kusano 7d535a
(These are the minimum requirements of the ANSI C standard.)  Wider types will
kusano 7d535a
work fine, although memory may be used inefficiently if char is much larger
kusano 7d535a
than 8 bits or short is much bigger than 16 bits.  The code should work
kusano 7d535a
equally well with 16- or 32-bit ints.
kusano 7d535a
kusano 7d535a
In a system where these assumptions are not met, you may be able to make the
kusano 7d535a
code work by modifying the typedefs in jmorecfg.h.  However, you will probably
kusano 7d535a
have difficulty if int is less than 16 bits wide, since references to plain
kusano 7d535a
int abound in the code.
kusano 7d535a
kusano 7d535a
char can be either signed or unsigned, although the code runs faster if an
kusano 7d535a
unsigned char type is available.  If char is wider than 8 bits, you will need
kusano 7d535a
to redefine JOCTET and/or provide custom data source/destination managers so
kusano 7d535a
that JOCTET represents exactly 8 bits of data on external storage.
kusano 7d535a
kusano 7d535a
The JPEG library proper does not assume ASCII representation of characters.
kusano 7d535a
But some of the image file I/O modules in cjpeg/djpeg do have ASCII
kusano 7d535a
dependencies in file-header manipulation; so does cjpeg's select_file_type()
kusano 7d535a
routine.
kusano 7d535a
kusano 7d535a
The JPEG library does not rely heavily on the C library.  In particular, C
kusano 7d535a
stdio is used only by the data source/destination modules and the error
kusano 7d535a
handler, all of which are application-replaceable.  (cjpeg/djpeg are more
kusano 7d535a
heavily dependent on stdio.)  malloc and free are called only from the memory
kusano 7d535a
manager "back end" module, so you can use a different memory allocator by
kusano 7d535a
replacing that one file.
kusano 7d535a
kusano 7d535a
The code generally assumes that C names must be unique in the first 15
kusano 7d535a
characters.  However, global function names can be made unique in the
kusano 7d535a
first 6 characters by defining NEED_SHORT_EXTERNAL_NAMES.
kusano 7d535a
kusano 7d535a
More info about porting the code may be gleaned by reading jconfig.txt,
kusano 7d535a
jmorecfg.h, and jinclude.h.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Notes for MS-DOS implementors
kusano 7d535a
-----------------------------
kusano 7d535a
kusano 7d535a
The IJG code is designed to work efficiently in 80x86 "small" or "medium"
kusano 7d535a
memory models (i.e., data pointers are 16 bits unless explicitly declared
kusano 7d535a
"far"; code pointers can be either size).  You may be able to use small
kusano 7d535a
model to compile cjpeg or djpeg by itself, but you will probably have to use
kusano 7d535a
medium model for any larger application.  This won't make much difference in
kusano 7d535a
performance.  You *will* take a noticeable performance hit if you use a
kusano 7d535a
large-data memory model (perhaps 10%-25%), and you should avoid "huge" model
kusano 7d535a
if at all possible.
kusano 7d535a
kusano 7d535a
The JPEG library typically needs 2Kb-3Kb of stack space.  It will also
kusano 7d535a
malloc about 20K-30K of near heap space while executing (and lots of far
kusano 7d535a
heap, but that doesn't count in this calculation).  This figure will vary
kusano 7d535a
depending on selected operating mode, and to a lesser extent on image size.
kusano 7d535a
There is also about 5Kb-6Kb of constant data which will be allocated in the
kusano 7d535a
near data segment (about 4Kb of this is the error message table).
kusano 7d535a
Thus you have perhaps 20K available for other modules' static data and near
kusano 7d535a
heap space before you need to go to a larger memory model.  The C library's
kusano 7d535a
static data will account for several K of this, but that still leaves a good
kusano 7d535a
deal for your needs.  (If you are tight on space, you could reduce the sizes
kusano 7d535a
of the I/O buffers allocated by jdatasrc.c and jdatadst.c, say from 4K to
kusano 7d535a
1K.  Another possibility is to move the error message table to far memory;
kusano 7d535a
this should be doable with only localized hacking on jerror.c.)
kusano 7d535a
kusano 7d535a
About 2K of the near heap space is "permanent" memory that will not be
kusano 7d535a
released until you destroy the JPEG object.  This is only an issue if you
kusano 7d535a
save a JPEG object between compression or decompression operations.
kusano 7d535a
kusano 7d535a
Far data space may also be a tight resource when you are dealing with large
kusano 7d535a
images.  The most memory-intensive case is decompression with two-pass color
kusano 7d535a
quantization, or single-pass quantization to an externally supplied color
kusano 7d535a
map.  This requires a 128Kb color lookup table plus strip buffers amounting
kusano 7d535a
to about 40 bytes per column for typical sampling ratios (eg, about 25600
kusano 7d535a
bytes for a 640-pixel-wide image).  You may not be able to process wide
kusano 7d535a
images if you have large data structures of your own.
kusano 7d535a
kusano 7d535a
Of course, all of these concerns vanish if you use a 32-bit flat-memory-model
kusano 7d535a
compiler, such as DJGPP or Watcom C.  We highly recommend flat model if you
kusano 7d535a
can use it; the JPEG library is significantly faster in flat model.