Alien-FreeImage

 view release on metacpan or  search on metacpan

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

Advanced features:
	Compression parameter selection
	Decompression parameter selection
	Special color spaces
	Error handling
	Compressed data handling (source and destination managers)
	I/O suspension
	Progressive JPEG support
	Buffered-image mode
	Abbreviated datastreams and multiple images
	Special markers
	Raw (downsampled) image data
	Really raw data: DCT coefficients
	Progress monitoring
	Memory management
	Memory usage
	Library compile-time options
	Portability considerations
	Notes for MS-DOS implementors

You should read at least the overview and basic usage sections before trying
to program with the library.  The sections on advanced features can be read
if and when you need them.


OVERVIEW
========

Functions provided by the library
---------------------------------

The IJG JPEG library provides C code to read and write JPEG-compressed image
files.  The surrounding application program receives or supplies image data a
scanline at a time, using a straightforward uncompressed image format.  All
details of color conversion and other preprocessing/postprocessing can be
handled by the library.

The library includes a substantial amount of code that is not covered by the
JPEG standard but is necessary for typical applications of JPEG.  These
functions preprocess the image before JPEG compression or postprocess it after
decompression.  They include colorspace conversion, downsampling/upsampling,
and color quantization.  The application indirectly selects use of this code
by specifying the format in which it wishes to supply or receive image data.
For example, if colormapped output is requested, then the decompression
library automatically invokes color quantization.

A wide range of quality vs. speed tradeoffs are possible in JPEG processing,
and even more so in decompression postprocessing.  The decompression library
provides multiple implementations that cover most of the useful tradeoffs,
ranging from very-high-quality down to fast-preview operation.  On the
compression side we have generally not provided low-quality choices, since
compression is normally less time-critical.  It should be understood that the
low-quality modes may not meet the JPEG standard's accuracy requirements;
nonetheless, they are useful for viewers.

A word about functions *not* provided by the library.  We handle a subset of
the ISO JPEG standard; most baseline, extended-sequential, and progressive
JPEG processes are supported.  (Our subset includes all features now in common
use.)  Unsupported ISO options include:
	* Hierarchical storage
	* Lossless JPEG
	* DNL marker
	* Nonintegral subsampling ratios
We support 8-bit to 12-bit data precision, but this is a compile-time choice
rather than a run-time choice; hence it is difficult to use different
precisions in a single application.

By itself, the library handles only interchange JPEG datastreams --- in
particular the widely used JFIF file format.  The library can be used by
surrounding code to process interchange or abbreviated JPEG datastreams that
are embedded in more complex file formats.  (For example, this library is
used by the free LIBTIFF library to support JPEG compression in TIFF.)


Outline of typical usage
------------------------

The rough outline of a JPEG compression operation is:

	Allocate and initialize a JPEG compression object
	Specify the destination for the compressed data (eg, a file)
	Set parameters for compression, including image size & colorspace
	jpeg_start_compress(...);
	while (scan lines remain to be written)
		jpeg_write_scanlines(...);
	jpeg_finish_compress(...);
	Release the JPEG compression object

A JPEG compression object holds parameters and working state for the JPEG
library.  We make creation/destruction of the object separate from starting
or finishing compression of an image; the same object can be re-used for a
series of image compression operations.  This makes it easy to re-use the
same parameter settings for a sequence of images.  Re-use of a JPEG object
also has important implications for processing abbreviated JPEG datastreams,
as discussed later.

The image data to be compressed is supplied to jpeg_write_scanlines() from
in-memory buffers.  If the application is doing file-to-file compression,
reading image data from the source file is the application's responsibility.
The library emits compressed data by calling a "data destination manager",
which typically will write the data into a file; but the application can
provide its own destination manager to do something else.

Similarly, the rough outline of a JPEG decompression operation is:

	Allocate and initialize a JPEG decompression object
	Specify the source of the compressed data (eg, a file)
	Call jpeg_read_header() to obtain image info
	Set parameters for decompression
	jpeg_start_decompress(...);
	while (scan lines remain to be read)
		jpeg_read_scanlines(...);
	jpeg_finish_decompress(...);
	Release the JPEG decompression object

This is comparable to the compression outline except that reading the
datastream header is a separate step.  This is helpful because information
about the image's size, colorspace, etc is available when the application
selects decompression parameters.  For example, the application can choose an
output scaling ratio that will fit the image into the available screen size.

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

After all the image data has been read, call jpeg_finish_decompress() to
complete the decompression cycle.  This causes working memory associated
with the JPEG object to be released.

Typical code:

	jpeg_finish_decompress(&cinfo);

If using the stdio source manager, don't forget to close the source stdio
stream if necessary.

It is an error to call jpeg_finish_decompress() before reading the correct
total number of scanlines.  If you wish to abort decompression, call
jpeg_abort() as discussed below.

After completing a decompression cycle, you may dispose of the JPEG object as
discussed next, or you may use it to decompress another image.  In that case
return to step 2 or 3 as appropriate.  If you do not change the source
manager, the next image will be read from the same source.


8. Release the JPEG decompression object.

When you are done with a JPEG decompression object, destroy it by calling
jpeg_destroy_decompress() or jpeg_destroy().  The previous discussion of
destroying compression objects applies here too.

Typical code:

	jpeg_destroy_decompress(&cinfo);


9. Aborting.

You can abort a decompression cycle by calling jpeg_destroy_decompress() or
jpeg_destroy() if you don't need the JPEG object any more, or
jpeg_abort_decompress() or jpeg_abort() if you want to reuse the object.
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

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

	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
	can't be expressed as a simple scalar multiplier, in which case the
	premise of this routine collapses.  Caveat user.

jpeg_default_qtables (j_compress_ptr cinfo, boolean force_baseline)
	Set default quantization tables with linear q_scale_factor[] values
	(see below).

jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
		      const unsigned int *basic_table,
		      int scale_factor, boolean force_baseline)
	Allows an arbitrary quantization table to be created.  which_tbl
	indicates which table slot to fill.  basic_table points to an array
	of 64 unsigned ints given in normal array order.  These values are
	multiplied by scale_factor/100 and then clamped to the range 1..65535
	(or to 1..255 if force_baseline is TRUE).
	CAUTION: prior to library version 6a, jpeg_add_quant_table expected
	the basic table to be given in JPEG zigzag order.  If you need to
	write code that works with either older or newer versions of this
	routine, you must check the library version number.  Something like
	"#if JPEG_LIB_VERSION >= 61" is the right test.

jpeg_simple_progression (j_compress_ptr cinfo)
	Generates a default scan script for writing a progressive-JPEG file.
	This is the recommended method of creating a progressive file,
	unless you want to make a custom scan sequence.  You must ensure that
	the JPEG color space is set correctly before calling this routine.


Compression parameters (cinfo fields) include:

boolean arith_code
	If TRUE, use arithmetic coding.
	If FALSE, use Huffman coding.

int block_size
	Set DCT block size.  All N from 1 to 16 are possible.
	Default is 8 (baseline format).
	Larger values produce higher compression,
	smaller values produce higher quality.
	An exact DCT stage is possible with 1 or 2.
	With the default quality of 75 and default Luminance qtable
	the DCT+Quantization stage is lossless for value 1.
	Note that values other than 8 require a SmartScale capable decoder,
	introduced with IJG JPEG 8.  Setting the block_size parameter for
	compression works with version 8c and later.

J_DCT_METHOD dct_method
	Selects the algorithm used for the DCT step.  Choices are:
		JDCT_ISLOW: slow but accurate integer algorithm
		JDCT_IFAST: faster, less accurate integer method
		JDCT_FLOAT: floating-point method
		JDCT_DEFAULT: default method (normally JDCT_ISLOW)
		JDCT_FASTEST: fastest method (normally JDCT_IFAST)
	The FLOAT method is very slightly more accurate than the ISLOW method,
	but may give different results on different machines due to varying
	roundoff behavior.  The integer methods should give the same results
	on all machines.  On machines with sufficiently fast FP hardware, the
	floating-point method may also be the fastest.  The IFAST method is
	considerably less accurate than the other two; its use is not
	recommended if high quality is a concern.  JDCT_DEFAULT and
	JDCT_FASTEST are macros configurable by each installation.

unsigned int scale_num, scale_denom
	Scale the image by the fraction scale_num/scale_denom.  Default is
	1/1, or no scaling.  Currently, the supported scaling ratios are
	M/N with all N from 1 to 16, where M is the destination DCT size,
	which is 8 by default (see block_size parameter above).
	(The library design allows for arbitrary scaling ratios but this
	is not likely to be implemented any time soon.)

J_COLOR_SPACE jpeg_color_space
int num_components
	The JPEG color space and corresponding number of components; see
	"Special color spaces", below, for more info.  We recommend using
	jpeg_set_colorspace() if you want to change these.

J_COLOR_TRANSFORM color_transform
	Internal color transform identifier, writes LSE marker if nonzero
	(requires decoder with inverse color transform support, introduced
	with IJG JPEG 9).
	Two values are currently possible: JCT_NONE and JCT_SUBTRACT_GREEN.
	Set this value for lossless RGB application *before* calling
	jpeg_set_colorspace(), because entropy table assignment in
	jpeg_set_colorspace() depends on color_transform.

boolean optimize_coding
	TRUE causes the compressor to compute optimal Huffman coding tables
	for the image.  This requires an extra pass over the data and
	therefore costs a good deal of space and time.  The default is
	FALSE, which tells the compressor to use the supplied or default
	Huffman tables.  In most cases optimal tables save only a few percent
	of file size compared to the default tables.  Note that when this is
	TRUE, you need not supply Huffman tables at all, and any you do
	supply will be overwritten.

unsigned int restart_interval
int restart_in_rows
	To emit restart markers in the JPEG file, set one of these nonzero.
	Set restart_interval to specify the exact interval in MCU blocks.
	Set restart_in_rows to specify the interval in MCU rows.  (If
	restart_in_rows is not 0, then restart_interval is set after the
	image width in MCUs is computed.)  Defaults are zero (no restarts).
	One restart marker per MCU row is often a good choice.
	NOTE: the overhead of restart markers is higher in grayscale JPEG
	files than in color files, and MUCH higher in progressive JPEGs.
	If you use restarts, you may want to use larger intervals in those
	cases.

const jpeg_scan_info * scan_info
int num_scans
	By default, scan_info is NULL; this causes the compressor to write a
	single-scan sequential JPEG file.  If not NULL, scan_info points to
	an array of scan definition records of length num_scans.  The
	compressor will then write a JPEG file having one scan for each scan
	definition record.  This is used to generate noninterleaved or
	progressive JPEG files.  The library checks that the scan array
	defines a valid JPEG scan sequence.  (jpeg_simple_progression creates
	a suitable scan definition array for progressive JPEG.)  This is
	discussed further under "Progressive JPEG support".

boolean do_fancy_downsampling
	If TRUE, use direct DCT scaling with DCT size > 8 for downsampling
	of chroma components.
	If FALSE, use only DCT size <= 8 and simple separate downsampling.
	Default is TRUE.
	For better image stability in multiple generation compression cycles
	it is preferable that this value matches the corresponding
	do_fancy_upsampling value in decompression.

int smoothing_factor
	If non-zero, the input image is smoothed; the value should be 1 for
	minimal smoothing to 100 for maximum smoothing.  Consult jcsample.c
	for details of the smoothing algorithm.  The default is zero.

boolean write_JFIF_header
	If TRUE, a JFIF APP0 marker is emitted.  jpeg_set_defaults() and
	jpeg_set_colorspace() set this TRUE if a JFIF-legal JPEG color space
	(ie, YCbCr or grayscale) is selected, otherwise FALSE.

UINT8 JFIF_major_version
UINT8 JFIF_minor_version
	The version number to be written into the JFIF marker.

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

blocks itself; it does not read them from your supplied data.  Therefore you
need never pad by more than block_size samples.  An example may help here.
Assume 2h2v downsampling of YCbCr data, that is
	cinfo->comp_info[0].h_samp_factor = 2		for Y
	cinfo->comp_info[0].v_samp_factor = 2
	cinfo->comp_info[1].h_samp_factor = 1		for Cb
	cinfo->comp_info[1].v_samp_factor = 1
	cinfo->comp_info[2].h_samp_factor = 1		for Cr
	cinfo->comp_info[2].v_samp_factor = 1
and suppose that the nominal image dimensions (cinfo->image_width and
cinfo->image_height) are 101x101 pixels.  Then jpeg_start_compress() will
compute downsampled_width = 101 and width_in_blocks = 13 for Y,
downsampled_width = 51 and width_in_blocks = 7 for Cb and Cr (and the same
for the height fields).  You must pad the Y data to at least 13*8 = 104
columns and rows, the Cb/Cr data to at least 7*8 = 56 columns and rows.  The
MCU height is max_v_samp_factor = 2 DCT rows so you must pass at least 16
scanlines on each call to jpeg_write_raw_data(), which is to say 16 actual
sample rows of Y and 8 each of Cb and Cr.  A total of 7 MCU rows are needed,
so you must pass a total of 7*16 = 112 "scanlines".  The last DCT block row
of Y data is dummy, so it doesn't matter what you pass for it in the data
arrays, but the scanlines count must total up to 112 so that all of the Cb
and Cr data gets passed.

Output suspension is supported with raw-data compression: if the data
destination module suspends, jpeg_write_raw_data() will return 0.
In this case the same data rows must be passed again on the next call.


Decompression with raw data output implies bypassing all postprocessing.
You must deal with the color space and sampling factors present in the
incoming file.  If your application only handles, say, 2h1v YCbCr data,
you must check for and fail on other color spaces or other sampling factors.
The library will not convert to a different color space for you.

To obtain raw data output, set cinfo->raw_data_out = TRUE before
jpeg_start_decompress() (it is set FALSE by jpeg_read_header()).  Be sure to
verify that the color space and sampling factors are ones you can handle.
Furthermore, set cinfo->do_fancy_upsampling = FALSE if you want to get real
downsampled data (it is set TRUE by jpeg_read_header()).
Then call jpeg_read_raw_data() in place of jpeg_read_scanlines().  The
decompression process is otherwise the same as usual.

jpeg_read_raw_data() returns one MCU row per call, and thus you must pass a
buffer of at least max_v_samp_factor*block_size scanlines (scanline counting
is the same as for raw-data compression).  The buffer you pass must be large
enough to hold the actual data plus padding to DCT-block boundaries.  As with
compression, any entirely dummy DCT blocks are not processed so you need not
allocate space for them, but the total scanline count includes them.  The
above example of computing buffer dimensions for raw-data compression is
equally valid for decompression.

Input suspension is supported with raw-data decompression: if the data source
module suspends, jpeg_read_raw_data() will return 0.  You can also use
buffered-image mode to read raw data in multiple passes.


Really raw data: DCT coefficients
---------------------------------

It is possible to read or write the contents of a JPEG file as raw DCT
coefficients.  This facility is mainly intended for use in lossless
transcoding between different JPEG file formats.  Other possible applications
include lossless cropping of a JPEG image, lossless reassembly of a
multi-strip or multi-tile TIFF/JPEG file into a single JPEG datastream, etc.

To read the contents of a JPEG file as DCT coefficients, open the file and do
jpeg_read_header() as usual.  But instead of calling jpeg_start_decompress()
and jpeg_read_scanlines(), call jpeg_read_coefficients().  This will read the
entire image into a set of virtual coefficient-block arrays, one array per
component.  The return value is a pointer to an array of virtual-array
descriptors.  Each virtual array can be accessed directly using the JPEG
memory manager's access_virt_barray method (see Memory management, below,
and also read structure.txt's discussion of virtual array handling).  Or,
for simple transcoding to a different JPEG file format, the array list can
just be handed directly to jpeg_write_coefficients().

Each block in the block arrays contains quantized coefficient values in
normal array order (not JPEG zigzag order).  The block arrays contain only
DCT blocks containing real data; any entirely-dummy blocks added to fill out
interleaved MCUs at the right or bottom edges of the image are discarded
during reading and are not stored in the block arrays.  (The size of each
block array can be determined from the width_in_blocks and height_in_blocks
fields of the component's comp_info entry.)  This is also the data format
expected by jpeg_write_coefficients().

When you are done using the virtual arrays, call jpeg_finish_decompress()
to release the array storage and return the decompression object to an idle
state; or just call jpeg_destroy() if you don't need to reuse the object.

If you use a suspending data source, jpeg_read_coefficients() will return
NULL if it is forced to suspend; a non-NULL return value indicates successful
completion.  You need not test for a NULL return value when using a
non-suspending data source.

It is also possible to call jpeg_read_coefficients() to obtain access to the
decoder's coefficient arrays during a normal decode cycle in buffered-image
mode.  This frammish might be useful for progressively displaying an incoming
image and then re-encoding it without loss.  To do this, decode in buffered-
image mode as discussed previously, then call jpeg_read_coefficients() after
the last jpeg_finish_output() call.  The arrays will be available for your use
until you call jpeg_finish_decompress().


To write the contents of a JPEG file as DCT coefficients, you must provide
the DCT coefficients stored in virtual block arrays.  You can either pass
block arrays read from an input JPEG file by jpeg_read_coefficients(), or
allocate virtual arrays from the JPEG compression object and fill them
yourself.  In either case, jpeg_write_coefficients() is substituted for
jpeg_start_compress() and jpeg_write_scanlines().  Thus the sequence is
  * Create compression object
  * Set all compression parameters as necessary
  * Request virtual arrays if needed
  * jpeg_write_coefficients()
  * jpeg_finish_compress()
  * Destroy or re-use compression object
jpeg_write_coefficients() is passed a pointer to an array of virtual block
array descriptors; the number of arrays is equal to cinfo.num_components.

The virtual arrays need only have been requested, not realized, before
jpeg_write_coefficients() is called.  A side-effect of
jpeg_write_coefficients() is to realize any virtual arrays that have been
requested from the compression object's memory manager.  Thus, when obtaining
the virtual arrays from the compression object, you should fill the arrays



( run in 1.583 second using v1.01-cache-2.11-cpan-acf6aa7dc9e )