Alien-FreeImage

 view release on metacpan or  search on metacpan

src/Source/LibJPEG/libjpeg.txt  view on Meta::CPAN


JPEG compression and decompression objects are two separate struct types.
However, they share some common fields, and certain routines such as
jpeg_destroy() can work on either type of object.

The JPEG library has no static variables: all state is in the compression
or decompression object.  Therefore it is possible to process multiple
compression and decompression operations concurrently, using multiple JPEG
objects.

Both compression and decompression can be done in an incremental memory-to-
memory fashion, if suitable source/destination managers are used.  See the
section on "I/O suspension" for more details.


BASIC LIBRARY USAGE
===================

Data formats
------------

Before diving into procedural details, it is helpful to understand the
image data format that the JPEG library expects or returns.

The standard input image format is a rectangular array of pixels, with each
pixel having the same number of "component" or "sample" values (color
channels).  You must specify how many components there are and the colorspace
interpretation of the components.  Most applications will use RGB data
(three components per pixel) or grayscale data (one component per pixel).
PLEASE NOTE THAT RGB DATA IS THREE SAMPLES PER PIXEL, GRAYSCALE ONLY ONE.
A remarkable number of people manage to miss this, only to find that their
programs don't work with grayscale JPEG files.

There is no provision for colormapped input.  JPEG files are always full-color
or full grayscale (or sometimes another colorspace such as CMYK).  You can
feed in a colormapped image by expanding it to full-color format.  However
JPEG often doesn't work very well with source data that has been colormapped,
because of dithering noise.  This is discussed in more detail in the JPEG FAQ
and the other references mentioned in the README file.

Pixels are stored by scanlines, with each scanline running from left to
right.  The component values for each pixel are adjacent in the row; for
example, R,G,B,R,G,B,R,G,B,... for 24-bit RGB color.  Each scanline is an
array of data type JSAMPLE --- which is typically "unsigned char", unless
you've changed jmorecfg.h.  (You can also change the RGB pixel layout, say
to B,G,R order, by modifying jmorecfg.h.  But see the restrictions listed in
that file before doing so.)

A 2-D array of pixels is formed by making a list of pointers to the starts of
scanlines; so the scanlines need not be physically adjacent in memory.  Even
if you process just one scanline at a time, you must make a one-element
pointer array to conform to this structure.  Pointers to JSAMPLE rows are of
type JSAMPROW, and the pointer to the pointer array is of type JSAMPARRAY.

The library accepts or supplies one or more complete scanlines per call.
It is not possible to process part of a row at a time.  Scanlines are always
processed top-to-bottom.  You can process an entire image in one call if you
have it all in memory, but usually it's simplest to process one scanline at
a time.

For best results, source data values should have the precision specified by
BITS_IN_JSAMPLE (normally 8 bits).  For instance, if you choose to compress
data that's only 6 bits/channel, you should left-justify each value in a
byte before passing it to the compressor.  If you need to compress data
that has more than 8 bits/channel, compile with BITS_IN_JSAMPLE = 9 to 12.
(See "Library compile-time options", later.)


The data format returned by the decompressor is the same in all details,
except that colormapped output is supported.  (Again, a JPEG file is never
colormapped.  But you can ask the decompressor to perform on-the-fly color
quantization to deliver colormapped output.)  If you request colormapped
output then the returned data array contains a single JSAMPLE per pixel;
its value is an index into a color map.  The color map is represented as
a 2-D JSAMPARRAY in which each row holds the values of one color component,
that is, colormap[i][j] is the value of the i'th color component for pixel
value (map index) j.  Note that since the colormap indexes are stored in
JSAMPLEs, the maximum number of colors is limited by the size of JSAMPLE
(ie, at most 256 colors for an 8-bit JPEG library).


Compression details
-------------------

Here we revisit the JPEG compression outline given in the overview.

1. Allocate and initialize a JPEG compression object.

A JPEG compression object is a "struct jpeg_compress_struct".  (It also has
a bunch of subsidiary structures which are allocated via malloc(), but the
application doesn't control those directly.)  This struct can be just a local
variable in the calling routine, if a single routine is going to execute the
whole JPEG compression sequence.  Otherwise it can be static or allocated
from malloc().

You will also need a structure representing a JPEG error handler.  The part
of this that the library cares about is a "struct jpeg_error_mgr".  If you
are providing your own error handler, you'll typically want to embed the
jpeg_error_mgr struct in a larger structure; this is discussed later under
"Error handling".  For now we'll assume you are just using the default error
handler.  The default error handler will print JPEG error/warning messages
on stderr, and it will call exit() if a fatal error occurs.

You must initialize the error handler structure, store a pointer to it into
the JPEG object's "err" field, and then call jpeg_create_compress() to
initialize the rest of the JPEG object.

Typical code for this step, if you are using the default error handler, is

	struct jpeg_compress_struct cinfo;
	struct jpeg_error_mgr jerr;
	...
	cinfo.err = jpeg_std_error(&jerr);
	jpeg_create_compress(&cinfo);

jpeg_create_compress allocates a small amount of memory, so it could fail
if you are out of memory.  In that case it will exit via the error handler;
that's why the error handler must be initialized first.


2. Specify the destination for the compressed data (eg, a file).

src/Source/LibJPEG/libjpeg.txt  view on Meta::CPAN

The previous discussion of aborting compression cycles applies here too.


Mechanics of usage: include files, linking, etc
-----------------------------------------------

Applications using the JPEG library should include the header file jpeglib.h
to obtain declarations of data types and routines.  Before including
jpeglib.h, include system headers that define at least the typedefs FILE and
size_t.  On ANSI-conforming systems, including <stdio.h> is sufficient; on
older Unix systems, you may need <sys/types.h> to define size_t.

If the application needs to refer to individual JPEG library error codes, also
include jerror.h to define those symbols.

jpeglib.h indirectly includes the files jconfig.h and jmorecfg.h.  If you are
installing the JPEG header files in a system directory, you will want to
install all four files: jpeglib.h, jerror.h, jconfig.h, jmorecfg.h.

The most convenient way to include the JPEG code into your executable program
is to prepare a library file ("libjpeg.a", or a corresponding name on non-Unix
machines) and reference it at your link step.  If you use only half of the
library (only compression or only decompression), only that much code will be
included from the library, unless your linker is hopelessly brain-damaged.
The supplied makefiles build libjpeg.a automatically (see install.txt).

While you can build the JPEG library as a shared library if the whim strikes
you, we don't really recommend it.  The trouble with shared libraries is that
at some point you'll probably try to substitute a new version of the library
without recompiling the calling applications.  That generally doesn't work
because the parameter struct declarations usually change with each new
version.  In other words, the library's API is *not* guaranteed binary
compatible across versions; we only try to ensure source-code compatibility.
(In hindsight, it might have been smarter to hide the parameter structs from
applications and introduce a ton of access functions instead.  Too late now,
however.)

On some systems your application may need to set up a signal handler to ensure
that temporary files are deleted if the program is interrupted.  This is most
critical if you are on MS-DOS and use the jmemdos.c memory manager back end;
it will try to grab extended memory for temp files, and that space will NOT be
freed automatically.  See cjpeg.c or djpeg.c for an example signal handler.

It may be worth pointing out that the core JPEG library does not actually
require the stdio library: only the default source/destination managers and
error handler need it.  You can use the library in a stdio-less environment
if you replace those modules and use jmemnobs.c (or another memory manager of
your own devising).  More info about the minimum system library requirements
may be found in jinclude.h.


ADVANCED FEATURES
=================

Compression parameter selection
-------------------------------

This section describes all the optional parameters you can set for JPEG
compression, as well as the "helper" routines provided to assist in this
task.  Proper setting of some parameters requires detailed understanding
of the JPEG standard; if you don't know what a parameter is for, it's best
not to mess with it!  See REFERENCES in the README file for pointers to
more info about JPEG.

It's a good idea to call jpeg_set_defaults() first, even if you plan to set
all the parameters; that way your code is more likely to work with future JPEG
libraries that have additional parameters.  For the same reason, we recommend
you use a helper routine where one is provided, in preference to twiddling
cinfo fields directly.

The helper routines are:

jpeg_set_defaults (j_compress_ptr cinfo)
	This routine sets all JPEG parameters to reasonable defaults, using
	only the input image's color space (field in_color_space, which must
	already be set in cinfo).  Many applications will only need to use
	this routine and perhaps jpeg_set_quality().

jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
	Sets the JPEG file's colorspace (field jpeg_color_space) as specified,
	and sets other color-space-dependent parameters appropriately.  See
	"Special color spaces", below, before using this.  A large number of
	parameters, including all per-component parameters, are set by this
	routine; if you want to twiddle individual parameters you should call
	jpeg_set_colorspace() before rather than after.

jpeg_default_colorspace (j_compress_ptr cinfo)
	Selects an appropriate JPEG colorspace based on cinfo->in_color_space,
	and calls jpeg_set_colorspace().  This is actually a subroutine of
	jpeg_set_defaults().  It's broken out in case you want to change
	just the colorspace-dependent JPEG parameters.

jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
	Constructs JPEG quantization tables appropriate for the indicated
	quality setting.  The quality value is expressed on the 0..100 scale
	recommended by IJG (cjpeg's "-quality" switch uses this routine).
	Note that the exact mapping from quality values to tables may change
	in future IJG releases as more is learned about DCT quantization.
	If the force_baseline parameter is TRUE, then the quantization table
	entries are constrained to the range 1..255 for full JPEG baseline
	compatibility.  In the current implementation, this only makes a
	difference for quality settings below 25, and it effectively prevents
	very small/low quality files from being generated.  The IJG decoder
	is capable of reading the non-baseline files generated at low quality
	settings when force_baseline is FALSE, but other decoders may not be.

jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
			 boolean force_baseline)
	Same as jpeg_set_quality() except that the generated tables are the
	sample tables given in the JPEC spec section K.1, multiplied by the
	specified scale factor (which is expressed as a percentage; thus
	scale_factor = 100 reproduces the spec's tables).  Note that larger
	scale factors give lower quality.  This entry point is useful for
	conforming to the Adobe PostScript DCT conventions, but we do not
	recommend linear scaling as a user-visible quality scale otherwise.
	force_baseline again constrains the computed table entries to 1..255.

int jpeg_quality_scaling (int quality)
	Converts a value on the IJG-recommended quality scale to a linear
	scaling percentage.  Note that this routine may change or go away
	in future releases --- IJG may choose to adopt a scaling method that

src/Source/LibJPEG/libjpeg.txt  view on Meta::CPAN

defining the next byte to read from the work buffer and the number of bytes
remaining:

	const JOCTET * next_input_byte; /* => next byte to read from buffer */
	size_t bytes_in_buffer;         /* # of bytes remaining in buffer */

The library increments the pointer and decrements the count until the buffer
is emptied.  The manager's fill_input_buffer method must reset the pointer and
count.  In most applications, the manager must remember the buffer's starting
address and total size in private fields not visible to the library.

A data source manager provides five methods:

init_source (j_decompress_ptr cinfo)
	Initialize source.  This is called by jpeg_read_header() before any
	data is actually read.  Unlike init_destination(), it may leave
	bytes_in_buffer set to 0 (in which case a fill_input_buffer() call
	will occur immediately).

fill_input_buffer (j_decompress_ptr cinfo)
	This is called whenever bytes_in_buffer has reached zero and more
	data is wanted.  In typical applications, it should read fresh data
	into the buffer (ignoring the current state of next_input_byte and
	bytes_in_buffer), reset the pointer & count to the start of the
	buffer, and return TRUE indicating that the buffer has been reloaded.
	It is not necessary to fill the buffer entirely, only to obtain at
	least one more byte.  bytes_in_buffer MUST be set to a positive value
	if TRUE is returned.  A FALSE return should only be used when I/O
	suspension is desired (this mode is discussed in the next section).

skip_input_data (j_decompress_ptr cinfo, long num_bytes)
	Skip num_bytes worth of data.  The buffer pointer and count should
	be advanced over num_bytes input bytes, refilling the buffer as
	needed.  This is used to skip over a potentially large amount of
	uninteresting data (such as an APPn marker).  In some applications
	it may be possible to optimize away the reading of the skipped data,
	but it's not clear that being smart is worth much trouble; large
	skips are uncommon.  bytes_in_buffer may be zero on return.
	A zero or negative skip count should be treated as a no-op.

resync_to_restart (j_decompress_ptr cinfo, int desired)
	This routine is called only when the decompressor has failed to find
	a restart (RSTn) marker where one is expected.  Its mission is to
	find a suitable point for resuming decompression.  For most
	applications, we recommend that you just use the default resync
	procedure, jpeg_resync_to_restart().  However, if you are able to back
	up in the input data stream, or if you have a-priori knowledge about
	the likely location of restart markers, you may be able to do better.
	Read the read_restart_marker() and jpeg_resync_to_restart() routines
	in jdmarker.c if you think you'd like to implement your own resync
	procedure.

term_source (j_decompress_ptr cinfo)
	Terminate source --- called by jpeg_finish_decompress() after all
	data has been read.  Often a no-op.

For both fill_input_buffer() and skip_input_data(), there is no such thing
as an EOF return.  If the end of the file has been reached, the routine has
a choice of exiting via ERREXIT() or inserting fake data into the buffer.
In most cases, generating a warning message and inserting a fake EOI marker
is the best course of action --- this will allow the decompressor to output
however much of the image is there.  In pathological cases, the decompressor
may swallow the EOI and again demand data ... just keep feeding it fake EOIs.
jdatasrc.c illustrates the recommended error recovery behavior.

term_source() is NOT called by jpeg_abort() or jpeg_destroy().  If you want
the source manager to be cleaned up during an abort, you must do it yourself.

You will also need code to create a jpeg_source_mgr struct, fill in its method
pointers, and insert a pointer to the struct into the "src" field of the JPEG
decompression object.  This can be done in-line in your setup code if you
like, but it's probably cleaner to provide a separate routine similar to the
jpeg_stdio_src() or jpeg_mem_src() routines of the supplied source managers.

For more information, consult the memory and stdio source and destination
managers in jdatasrc.c and jdatadst.c.


I/O suspension
--------------

Some applications need to use the JPEG library as an incremental memory-to-
memory filter: when the compressed data buffer is filled or emptied, they want
control to return to the outer loop, rather than expecting that the buffer can
be emptied or reloaded within the data source/destination manager subroutine.
The library supports this need by providing an "I/O suspension" mode, which we
describe in this section.

The I/O suspension mode is not a panacea: nothing is guaranteed about the
maximum amount of time spent in any one call to the library, so it will not
eliminate response-time problems in single-threaded applications.  If you
need guaranteed response time, we suggest you "bite the bullet" and implement
a real multi-tasking capability.

To use I/O suspension, cooperation is needed between the calling application
and the data source or destination manager; you will always need a custom
source/destination manager.  (Please read the previous section if you haven't
already.)  The basic idea is that the empty_output_buffer() or
fill_input_buffer() routine is a no-op, merely returning FALSE to indicate
that it has done nothing.  Upon seeing this, the JPEG library suspends
operation and returns to its caller.  The surrounding application is
responsible for emptying or refilling the work buffer before calling the
JPEG library again.

Compression suspension:

For compression suspension, use an empty_output_buffer() routine that returns
FALSE; typically it will not do anything else.  This will cause the
compressor to return to the caller of jpeg_write_scanlines(), with the return
value indicating that not all the supplied scanlines have been accepted.
The application must make more room in the output buffer, adjust the output
buffer pointer/count appropriately, and then call jpeg_write_scanlines()
again, pointing to the first unconsumed scanline.

When forced to suspend, the compressor will backtrack to a convenient stopping
point (usually the start of the current MCU); it will regenerate some output
data when restarted.  Therefore, although empty_output_buffer() is only
called when the buffer is filled, you should NOT write out the entire buffer
after a suspension.  Write only the data up to the current position of
next_output_byte/free_in_buffer.  The data beyond that point will be
regenerated after resumption.

src/Source/LibJPEG/libjpeg.txt  view on Meta::CPAN

coefficient buffer, from which it can be read out as many times as desired.
This mode is typically used for incremental display of progressive JPEG files,
but it can be used with any JPEG file.  Each scan of a progressive JPEG file
adds more data (more detail) to the buffered image.  The application can
display in lockstep with the source file (one display pass per input scan),
or it can allow input processing to outrun display processing.  By making
input and display processing run independently, it is possible for the
application to adapt progressive display to a wide range of data transmission
rates.

The basic control flow for buffered-image decoding is

	jpeg_create_decompress()
	set data source
	jpeg_read_header()
	set overall decompression parameters
	cinfo.buffered_image = TRUE;	/* select buffered-image mode */
	jpeg_start_decompress()
	for (each output pass) {
	    adjust output decompression parameters if required
	    jpeg_start_output()		/* start a new output pass */
	    for (all scanlines in image) {
	        jpeg_read_scanlines()
	        display scanlines
	    }
	    jpeg_finish_output()	/* terminate output pass */
	}
	jpeg_finish_decompress()
	jpeg_destroy_decompress()

This differs from ordinary unbuffered decoding in that there is an additional
level of looping.  The application can choose how many output passes to make
and how to display each pass.

The simplest approach to displaying progressive images is to do one display
pass for each scan appearing in the input file.  In this case the outer loop
condition is typically
	while (! jpeg_input_complete(&cinfo))
and the start-output call should read
	jpeg_start_output(&cinfo, cinfo.input_scan_number);
The second parameter to jpeg_start_output() indicates which scan of the input
file is to be displayed; the scans are numbered starting at 1 for this
purpose.  (You can use a loop counter starting at 1 if you like, but using
the library's input scan counter is easier.)  The library automatically reads
data as necessary to complete each requested scan, and jpeg_finish_output()
advances to the next scan or end-of-image marker (hence input_scan_number
will be incremented by the time control arrives back at jpeg_start_output()).
With this technique, data is read from the input file only as needed, and
input and output processing run in lockstep.

After reading the final scan and reaching the end of the input file, the
buffered image remains available; it can be read additional times by
repeating the jpeg_start_output()/jpeg_read_scanlines()/jpeg_finish_output()
sequence.  For example, a useful technique is to use fast one-pass color
quantization for display passes made while the image is arriving, followed by
a final display pass using two-pass quantization for highest quality.  This
is done by changing the library parameters before the final output pass.
Changing parameters between passes is discussed in detail below.

In general the last scan of a progressive file cannot be recognized as such
until after it is read, so a post-input display pass is the best approach if
you want special processing in the final pass.

When done with the image, be sure to call jpeg_finish_decompress() to release
the buffered image (or just use jpeg_destroy_decompress()).

If input data arrives faster than it can be displayed, the application can
cause the library to decode input data in advance of what's needed to produce
output.  This is done by calling the routine jpeg_consume_input().
The return value is one of the following:
	JPEG_REACHED_SOS:    reached an SOS marker (the start of a new scan)
	JPEG_REACHED_EOI:    reached the EOI marker (end of image)
	JPEG_ROW_COMPLETED:  completed reading one MCU row of compressed data
	JPEG_SCAN_COMPLETED: completed reading last MCU row of current scan
	JPEG_SUSPENDED:      suspended before completing any of the above
(JPEG_SUSPENDED can occur only if a suspending data source is used.)  This
routine can be called at any time after initializing the JPEG object.  It
reads some additional data and returns when one of the indicated significant
events occurs.  (If called after the EOI marker is reached, it will
immediately return JPEG_REACHED_EOI without attempting to read more data.)

The library's output processing will automatically call jpeg_consume_input()
whenever the output processing overtakes the input; thus, simple lockstep
display requires no direct calls to jpeg_consume_input().  But by adding
calls to jpeg_consume_input(), you can absorb data in advance of what is
being displayed.  This has two benefits:
  * You can limit buildup of unprocessed data in your input buffer.
  * You can eliminate extra display passes by paying attention to the
    state of the library's input processing.

The first of these benefits only requires interspersing calls to
jpeg_consume_input() with your display operations and any other processing
you may be doing.  To avoid wasting cycles due to backtracking, it's best to
call jpeg_consume_input() only after a hundred or so new bytes have arrived.
This is discussed further under "I/O suspension", above.  (Note: the JPEG
library currently is not thread-safe.  You must not call jpeg_consume_input()
from one thread of control if a different library routine is working on the
same JPEG object in another thread.)

When input arrives fast enough that more than one new scan is available
before you start a new output pass, you may as well skip the output pass
corresponding to the completed scan.  This occurs for free if you pass
cinfo.input_scan_number as the target scan number to jpeg_start_output().
The input_scan_number field is simply the index of the scan currently being
consumed by the input processor.  You can ensure that this is up-to-date by
emptying the input buffer just before calling jpeg_start_output(): call
jpeg_consume_input() repeatedly until it returns JPEG_SUSPENDED or
JPEG_REACHED_EOI.

The target scan number passed to jpeg_start_output() is saved in the
cinfo.output_scan_number field.  The library's output processing calls
jpeg_consume_input() whenever the current input scan number and row within
that scan is less than or equal to the current output scan number and row.
Thus, input processing can "get ahead" of the output processing but is not
allowed to "fall behind".  You can achieve several different effects by
manipulating this interlock rule.  For example, if you pass a target scan
number greater than the current input scan number, the output processor will
wait until that scan starts to arrive before producing any output.  (To avoid
an infinite loop, the target scan number is automatically reset to the last
scan number when the end of image is reached.  Thus, if you specify a large
target scan number, the library will just absorb the entire input file and
then perform an output pass.  This is effectively the same as what
jpeg_start_decompress() does when you don't select buffered-image mode.)
When you pass a target scan number equal to the current input scan number,
the image is displayed no faster than the current input scan arrives.  The
final possibility is to pass a target scan number less than the current input
scan number; this disables the input/output interlock and causes the output
processor to simply display whatever it finds in the image buffer, without
waiting for input.  (However, the library will not accept a target scan
number less than one, so you can't avoid waiting for the first scan.)

When data is arriving faster than the output display processing can advance
through the image, jpeg_consume_input() will store data into the buffered
image beyond the point at which the output processing is reading data out
again.  If the input arrives fast enough, it may "wrap around" the buffer to
the point where the input is more than one whole scan ahead of the output.
If the output processing simply proceeds through its display pass without
paying attention to the input, the effect seen on-screen is that the lower
part of the image is one or more scans better in quality than the upper part.
Then, when the next output scan is started, you have a choice of what target
scan number to use.  The recommended choice is to use the current input scan
number at that time, which implies that you've skipped the output scans
corresponding to the input scans that were completed while you processed the
previous output scan.  In this way, the decoder automatically adapts its
speed to the arriving data, by skipping output scans as necessary to keep up
with the arriving data.

When using this strategy, you'll want to be sure that you perform a final
output pass after receiving all the data; otherwise your last display may not
be full quality across the whole screen.  So the right outer loop logic is
something like this:
	do {
	    absorb any waiting input by calling jpeg_consume_input()
	    final_pass = jpeg_input_complete(&cinfo);
	    adjust output decompression parameters if required
	    jpeg_start_output(&cinfo, cinfo.input_scan_number);
	    ...
	    jpeg_finish_output()
	} while (! final_pass);
rather than quitting as soon as jpeg_input_complete() returns TRUE.  This
arrangement makes it simple to use higher-quality decoding parameters
for the final pass.  But if you don't want to use special parameters for
the final pass, the right loop logic is like this:
	for (;;) {
	    absorb any waiting input by calling jpeg_consume_input()
	    jpeg_start_output(&cinfo, cinfo.input_scan_number);
	    ...
	    jpeg_finish_output()
	    if (jpeg_input_complete(&cinfo) &&
	        cinfo.input_scan_number == cinfo.output_scan_number)
	      break;
	}
In this case you don't need to know in advance whether an output pass is to
be the last one, so it's not necessary to have reached EOF before starting
the final output pass; rather, what you want to test is whether the output
pass was performed in sync with the final input scan.  This form of the loop
will avoid an extra output pass whenever the decoder is able (or nearly able)
to keep up with the incoming data.

When the data transmission speed is high, you might begin a display pass,
then find that much or all of the file has arrived before you can complete
the pass.  (You can detect this by noting the JPEG_REACHED_EOI return code
from jpeg_consume_input(), or equivalently by testing jpeg_input_complete().)
In this situation you may wish to abort the current display pass and start a
new one using the newly arrived information.  To do so, just call
jpeg_finish_output() and then start a new pass with jpeg_start_output().

A variant strategy is to abort and restart display if more than one complete
scan arrives during an output pass; this can be detected by noting
JPEG_REACHED_SOS returns and/or examining cinfo.input_scan_number.  This
idea should be employed with caution, however, since the display process
might never get to the bottom of the image before being aborted, resulting
in the lower part of the screen being several passes worse than the upper.
In most cases it's probably best to abort an output pass only if the whole
file has arrived and you want to begin the final output pass immediately.

When receiving data across a communication link, we recommend always using
the current input scan number for the output target scan number; if a
higher-quality final pass is to be done, it should be started (aborting any
incomplete output pass) as soon as the end of file is received.  However,
many other strategies are possible.  For example, the application can examine
the parameters of the current input scan and decide whether to display it or
not.  If the scan contains only chroma data, one might choose not to use it
as the target scan, expecting that the scan will be small and will arrive
quickly.  To skip to the next scan, call jpeg_consume_input() until it
returns JPEG_REACHED_SOS or JPEG_REACHED_EOI.  Or just use the next higher
number as the target scan for jpeg_start_output(); but that method doesn't
let you inspect the next scan's parameters before deciding to display it.


In buffered-image mode, jpeg_start_decompress() never performs input and
thus never suspends.  An application that uses input suspension with
buffered-image mode must be prepared for suspension returns from these
routines:
* jpeg_start_output() performs input only if you request 2-pass quantization
  and the target scan isn't fully read yet.  (This is discussed below.)
* jpeg_read_scanlines(), as always, returns the number of scanlines that it
  was able to produce before suspending.
* jpeg_finish_output() will read any markers following the target scan,
  up to the end of the file or the SOS marker that begins another scan.
  (But it reads no input if jpeg_consume_input() has already reached the
  end of the file or a SOS marker beyond the target output scan.)
* jpeg_finish_decompress() will read until the end of file, and thus can
  suspend if the end hasn't already been reached (as can be tested by
  calling jpeg_input_complete()).
jpeg_start_output(), jpeg_finish_output(), and jpeg_finish_decompress()
all return TRUE if they completed their tasks, FALSE if they had to suspend.
In the event of a FALSE return, the application must load more input data
and repeat the call.  Applications that use non-suspending data sources need
not check the return values of these three routines.


It is possible to change decoding parameters between output passes in the
buffered-image mode.  The decoder library currently supports only very
limited changes of parameters.  ONLY THE FOLLOWING parameter changes are
allowed after jpeg_start_decompress() is called:
* dct_method can be changed before each call to jpeg_start_output().
  For example, one could use a fast DCT method for early scans, changing
  to a higher quality method for the final scan.
* dither_mode can be changed before each call to jpeg_start_output();
  of course this has no impact if not using color quantization.  Typically
  one would use ordered dither for initial passes, then switch to
  Floyd-Steinberg dither for the final pass.  Caution: changing dither mode
  can cause more memory to be allocated by the library.  Although the amount
  of memory involved is not large (a scanline or so), it may cause the
  initial max_memory_to_use specification to be exceeded, which in the worst
  case would result in an out-of-memory failure.
* do_block_smoothing can be changed before each call to jpeg_start_output().
  This setting is relevant only when decoding a progressive JPEG image.
  During the first DC-only scan, block smoothing provides a very "fuzzy" look
  instead of the very "blocky" look seen without it; which is better seems a
  matter of personal taste.  But block smoothing is nearly always a win
  during later stages, especially when decoding a successive-approximation
  image: smoothing helps to hide the slight blockiness that otherwise shows

src/Source/LibJPEG/libjpeg.txt  view on Meta::CPAN

working-storage requirements, the library requires you to indicate which
one(s) you intend to use before you call jpeg_start_decompress().  (If we did
not require this, the max_memory_to_use setting would be a complete fiction.)
You do this by setting one or more of these three cinfo fields to TRUE:
	enable_1pass_quant		Fixed color cube colormap
	enable_external_quant		Externally-supplied colormap
	enable_2pass_quant		Two-pass custom colormap
All three are initialized FALSE by jpeg_read_header().  But
jpeg_start_decompress() automatically sets TRUE the one selected by the
current two_pass_quantize and colormap settings, so you only need to set the
enable flags for any other quantization methods you plan to change to later.

After setting the enable flags correctly at jpeg_start_decompress() time, you
can change to any enabled quantization method by setting two_pass_quantize
and colormap properly just before calling jpeg_start_output().  The following
special rules apply:
1. You must explicitly set cinfo.colormap to NULL when switching to 1-pass
   or 2-pass mode from a different mode, or when you want the 2-pass
   quantizer to be re-run to generate a new colormap.
2. To switch to an external colormap, or to change to a different external
   colormap than was used on the prior pass, you must call
   jpeg_new_colormap() after setting cinfo.colormap.
NOTE: if you want to use the same colormap as was used in the prior pass,
you should not do either of these things.  This will save some nontrivial
switchover costs.
(These requirements exist because cinfo.colormap will always be non-NULL
after completing a prior output pass, since both the 1-pass and 2-pass
quantizers set it to point to their output colormaps.  Thus you have to
do one of these two things to notify the library that something has changed.
Yup, it's a bit klugy, but it's necessary to do it this way for backwards
compatibility.)

Note that in buffered-image mode, the library generates any requested colormap
during jpeg_start_output(), not during jpeg_start_decompress().

When using two-pass quantization, jpeg_start_output() makes a pass over the
buffered image to determine the optimum color map; it therefore may take a
significant amount of time, whereas ordinarily it does little work.  The
progress monitor hook is called during this pass, if defined.  It is also
important to realize that if the specified target scan number is greater than
or equal to the current input scan number, jpeg_start_output() will attempt
to consume input as it makes this pass.  If you use a suspending data source,
you need to check for a FALSE return from jpeg_start_output() under these
conditions.  The combination of 2-pass quantization and a not-yet-fully-read
target scan is the only case in which jpeg_start_output() will consume input.


Application authors who support buffered-image mode may be tempted to use it
for all JPEG images, even single-scan ones.  This will work, but it is
inefficient: there is no need to create an image-sized coefficient buffer for
single-scan images.  Requesting buffered-image mode for such an image wastes
memory.  Worse, it can cost time on large images, since the buffered data has
to be swapped out or written to a temporary file.  If you are concerned about
maximum performance on baseline JPEG files, you should use buffered-image
mode only when the incoming file actually has multiple scans.  This can be
tested by calling jpeg_has_multiple_scans(), which will return a correct
result at any time after jpeg_read_header() completes.

It is also worth noting that when you use jpeg_consume_input() to let input
processing get ahead of output processing, the resulting pattern of access to
the coefficient buffer is quite nonsequential.  It's best to use the memory
manager jmemnobs.c if you can (ie, if you have enough real or virtual main
memory).  If not, at least make sure that max_memory_to_use is set as high as
possible.  If the JPEG memory manager has to use a temporary file, you will
probably see a lot of disk traffic and poor performance.  (This could be
improved with additional work on the memory manager, but we haven't gotten
around to it yet.)

In some applications it may be convenient to use jpeg_consume_input() for all
input processing, including reading the initial markers; that is, you may
wish to call jpeg_consume_input() instead of jpeg_read_header() during
startup.  This works, but note that you must check for JPEG_REACHED_SOS and
JPEG_REACHED_EOI return codes as the equivalent of jpeg_read_header's codes.
Once the first SOS marker has been reached, you must call
jpeg_start_decompress() before jpeg_consume_input() will consume more input;
it'll just keep returning JPEG_REACHED_SOS until you do.  If you read a
tables-only file this way, jpeg_consume_input() will return JPEG_REACHED_EOI
without ever returning JPEG_REACHED_SOS; be sure to check for this case.
If this happens, the decompressor will not read any more input until you call
jpeg_abort() to reset it.  It is OK to call jpeg_consume_input() even when not
using buffered-image mode, but in that case it's basically a no-op after the
initial markers have been read: it will just return JPEG_SUSPENDED.


Abbreviated datastreams and multiple images
-------------------------------------------

A JPEG compression or decompression object can be reused to process multiple
images.  This saves a small amount of time per image by eliminating the
"create" and "destroy" operations, but that isn't the real purpose of the
feature.  Rather, reuse of an object provides support for abbreviated JPEG
datastreams.  Object reuse can also simplify processing a series of images in
a single input or output file.  This section explains these features.

A JPEG file normally contains several hundred bytes worth of quantization
and Huffman tables.  In a situation where many images will be stored or
transmitted with identical tables, this may represent an annoying overhead.
The JPEG standard therefore permits tables to be omitted.  The standard
defines three classes of JPEG datastreams:
  * "Interchange" datastreams contain an image and all tables needed to decode
     the image.  These are the usual kind of JPEG file.
  * "Abbreviated image" datastreams contain an image, but are missing some or
    all of the tables needed to decode that image.
  * "Abbreviated table specification" (henceforth "tables-only") datastreams
    contain only table specifications.
To decode an abbreviated image, it is necessary to load the missing table(s)
into the decoder beforehand.  This can be accomplished by reading a separate
tables-only file.  A variant scheme uses a series of images in which the first
image is an interchange (complete) datastream, while subsequent ones are
abbreviated and rely on the tables loaded by the first image.  It is assumed
that once the decoder has read a table, it will remember that table until a
new definition for the same table number is encountered.

It is the application designer's responsibility to figure out how to associate
the correct tables with an abbreviated image.  While abbreviated datastreams
can be useful in a closed environment, their use is strongly discouraged in
any situation where data exchange with other applications might be needed.
Caveat designer.

The JPEG library provides support for reading and writing any combination of
tables-only datastreams and abbreviated images.  In both compression and

src/Source/LibJPEG/libjpeg.txt  view on Meta::CPAN


	create JPEG decompression object
	set source to tables-only file
	jpeg_read_header(&cinfo, FALSE);
	set source to abbreviated image file
	jpeg_read_header(&cinfo, TRUE);
	set decompression parameters
	jpeg_start_decompress(&cinfo);
	read data...
	jpeg_finish_decompress(&cinfo);

In some cases, you may want to read a file without knowing whether it contains
an image or just tables.  In that case, pass FALSE and check the return value
from jpeg_read_header(): it will be JPEG_HEADER_OK if an image was found,
JPEG_HEADER_TABLES_ONLY if only tables were found.  (A third return value,
JPEG_SUSPENDED, is possible when using a suspending data source manager.)
Note that jpeg_read_header() will not complain if you read an abbreviated
image for which you haven't loaded the missing tables; the missing-table check
occurs later, in jpeg_start_decompress().


It is possible to read a series of images from a single source file by
repeating the jpeg_read_header() ... jpeg_finish_decompress() sequence,
without releasing/recreating the JPEG object or the data source module.
(If you did reinitialize, any partial bufferload left in the data source
buffer at the end of one image would be discarded, causing you to lose the
start of the next image.)  When you use this method, stored tables are
automatically carried forward, so some of the images can be abbreviated images
that depend on tables from earlier images.

If you intend to write a series of images into a single destination file,
you might want to make a specialized data destination module that doesn't
flush the output buffer at term_destination() time.  This would speed things
up by some trifling amount.  Of course, you'd need to remember to flush the
buffer after the last image.  You can make the later images be abbreviated
ones by passing FALSE to jpeg_start_compress().


Special markers
---------------

Some applications may need to insert or extract special data in the JPEG
datastream.  The JPEG standard provides marker types "COM" (comment) and
"APP0" through "APP15" (application) to hold application-specific data.
Unfortunately, the use of these markers is not specified by the standard.
COM markers are fairly widely used to hold user-supplied text.  The JFIF file
format spec uses APP0 markers with specified initial strings to hold certain
data.  Adobe applications use APP14 markers beginning with the string "Adobe"
for miscellaneous data.  Other APPn markers are rarely seen, but might
contain almost anything.

If you wish to store user-supplied text, we recommend you use COM markers
and place readable 7-bit ASCII text in them.  Newline conventions are not
standardized --- expect to find LF (Unix style), CR/LF (DOS style), or CR
(Mac style).  A robust COM reader should be able to cope with random binary
garbage, including nulls, since some applications generate COM markers
containing non-ASCII junk.  (But yours should not be one of them.)

For program-supplied data, use an APPn marker, and be sure to begin it with an
identifying string so that you can tell whether the marker is actually yours.
It's probably best to avoid using APP0 or APP14 for any private markers.
(NOTE: the upcoming SPIFF standard will use APP8 markers; we recommend you
not use APP8 markers for any private purposes, either.)

Keep in mind that at most 65533 bytes can be put into one marker, but you
can have as many markers as you like.

By default, the IJG compression library will write a JFIF APP0 marker if the
selected JPEG colorspace is grayscale or YCbCr, or an Adobe APP14 marker if
the selected colorspace is RGB, CMYK, or YCCK.  You can disable this, but
we don't recommend it.  The decompression library will recognize JFIF and
Adobe markers and will set the JPEG colorspace properly when one is found.


You can write special markers immediately following the datastream header by
calling jpeg_write_marker() after jpeg_start_compress() and before the first
call to jpeg_write_scanlines().  When you do this, the markers appear after
the SOI and the JFIF APP0 and Adobe APP14 markers (if written), but before
all else.  Specify the marker type parameter as "JPEG_COM" for COM or
"JPEG_APP0 + n" for APPn.  (Actually, jpeg_write_marker will let you write
any marker type, but we don't recommend writing any other kinds of marker.)
For example, to write a user comment string pointed to by comment_text:
	jpeg_write_marker(cinfo, JPEG_COM, comment_text, strlen(comment_text));

If it's not convenient to store all the marker data in memory at once,
you can instead call jpeg_write_m_header() followed by multiple calls to
jpeg_write_m_byte().  If you do it this way, it's your responsibility to
call jpeg_write_m_byte() exactly the number of times given in the length
parameter to jpeg_write_m_header().  (This method lets you empty the
output buffer partway through a marker, which might be important when
using a suspending data destination module.  In any case, if you are using
a suspending destination, you should flush its buffer after inserting
any special markers.  See "I/O suspension".)

Or, if you prefer to synthesize the marker byte sequence yourself,
you can just cram it straight into the data destination module.

If you are writing JFIF 1.02 extension markers (thumbnail images), don't
forget to set cinfo.JFIF_minor_version = 2 so that the encoder will write the
correct JFIF version number in the JFIF header marker.  The library's default
is to write version 1.01, but that's wrong if you insert any 1.02 extension
markers.  (We could probably get away with just defaulting to 1.02, but there
used to be broken decoders that would complain about unknown minor version
numbers.  To reduce compatibility risks it's safest not to write 1.02 unless
you are actually using 1.02 extensions.)


When reading, two methods of handling special markers are available:
1. You can ask the library to save the contents of COM and/or APPn markers
into memory, and then examine them at your leisure afterwards.
2. You can supply your own routine to process COM and/or APPn markers
on-the-fly as they are read.
The first method is simpler to use, especially if you are using a suspending
data source; writing a marker processor that copes with input suspension is
not easy (consider what happens if the marker is longer than your available
input buffer).  However, the second method conserves memory since the marker
data need not be kept around after it's been processed.

For either method, you'd normally set up marker handling after creating a
decompression object and before calling jpeg_read_header(), because the
markers of interest will typically be near the head of the file and so will
be scanned by jpeg_read_header.  Once you've established a marker handling
method, it will be used for the life of that decompression object
(potentially many datastreams), unless you change it.  Marker handling is
determined separately for COM markers and for each APPn marker code.


To save the contents of special markers in memory, call
	jpeg_save_markers(cinfo, marker_code, length_limit)
where marker_code is the marker type to save, JPEG_COM or JPEG_APP0+n.
(To arrange to save all the special marker types, you need to call this
routine 17 times, for COM and APP0-APP15.)  If the incoming marker is longer
than length_limit data bytes, only length_limit bytes will be saved; this
parameter allows you to avoid chewing up memory when you only need to see the
first few bytes of a potentially large marker.  If you want to save all the
data, set length_limit to 0xFFFF; that is enough since marker lengths are only
16 bits.  As a special case, setting length_limit to 0 prevents that marker
type from being saved at all.  (That is the default behavior, in fact.)

After jpeg_read_header() completes, you can examine the special markers by
following the cinfo->marker_list pointer chain.  All the special markers in
the file appear in this list, in order of their occurrence in the file (but
omitting any markers of types you didn't ask for).  Both the original data
length and the saved data length are recorded for each list entry; the latter
will not exceed length_limit for the particular marker type.  Note that these
lengths exclude the marker length word, whereas the stored representation
within the JPEG file includes it.  (Hence the maximum data length is really
only 65533.)

It is possible that additional special markers appear in the file beyond the
SOS marker at which jpeg_read_header stops; if so, the marker list will be
extended during reading of the rest of the file.  This is not expected to be
common, however.  If you are short on memory you may want to reset the length
limit to zero for all marker types after finishing jpeg_read_header, to
ensure that the max_memory_to_use setting cannot be exceeded due to addition
of later markers.

The marker list remains stored until you call jpeg_finish_decompress or
jpeg_abort, at which point the memory is freed and the list is set to empty.
(jpeg_destroy also releases the storage, of course.)

Note that the library is internally interested in APP0 and APP14 markers;
if you try to set a small nonzero length limit on these types, the library
will silently force the length up to the minimum it wants.  (But you can set
a zero length limit to prevent them from being saved at all.)  Also, in a
16-bit environment, the maximum length limit may be constrained to less than
65533 by malloc() limitations.  It is therefore best not to assume that the
effective length limit is exactly what you set it to be.


If you want to supply your own marker-reading routine, you do it by calling
jpeg_set_marker_processor().  A marker processor routine must have the
signature
	boolean jpeg_marker_parser_method (j_decompress_ptr cinfo)
Although the marker code is not explicitly passed, the routine can find it
in cinfo->unread_marker.  At the time of call, the marker proper has been
read from the data source module.  The processor routine is responsible for
reading the marker length word and the remaining parameter bytes, if any.
Return TRUE to indicate success.  (FALSE should be returned only if you are
using a suspending data source and it tells you to suspend.  See the standard
marker processors in jdmarker.c for appropriate coding methods if you need to
use a suspending data source.)

If you override the default APP0 or APP14 processors, it is up to you to
recognize JFIF and Adobe markers if you want colorspace recognition to occur
properly.  We recommend copying and extending the default processors if you
want to do that.  (A better idea is to save these marker types for later
examination by calling jpeg_save_markers(); that method doesn't interfere
with the library's own processing of these markers.)

jpeg_set_marker_processor() and jpeg_save_markers() are mutually exclusive
--- if you call one it overrides any previous call to the other, for the
particular marker type specified.

A simple example of an external COM processor can be found in djpeg.c.
Also, see jpegtran.c for an example of using jpeg_save_markers.


Raw (downsampled) image data
----------------------------

Some applications need to supply already-downsampled image data to the JPEG
compressor, or to receive raw downsampled data from the decompressor.  The
library supports this requirement by allowing the application to write or
read raw data, bypassing the normal preprocessing or postprocessing steps.
The interface is different from the standard one and is somewhat harder to
use.  If your interest is merely in bypassing color conversion, we recommend
that you use the standard interface and simply set jpeg_color_space =
in_color_space (or jpeg_color_space = out_color_space for decompression).
The mechanism described in this section is necessary only to supply or
receive downsampled image data, in which not all components have the same
dimensions.


To compress raw data, you must supply the data in the colorspace to be used
in the JPEG file (please read the earlier section on Special color spaces)
and downsampled to the sampling factors specified in the JPEG parameters.
You must supply the data in the format used internally by the JPEG library,
namely a JSAMPIMAGE array.  This is an array of pointers to two-dimensional
arrays, each of type JSAMPARRAY.  Each 2-D array holds the values for one
color component.  This structure is necessary since the components are of
different sizes.  If the image dimensions are not a multiple of the MCU size,
you must also pad the data correctly (usually, this is done by replicating
the last column and/or row).  The data must be padded to a multiple of a DCT
block in each component: that is, each downsampled row must contain a
multiple of block_size valid samples, and there must be a multiple of
block_size sample rows for each component.  (For applications such as



( run in 0.306 second using v1.01-cache-2.11-cpan-2ed5026b665 )