kusano 7d535a
IJG JPEG LIBRARY:  SYSTEM ARCHITECTURE
kusano 7d535a
kusano 7d535a
Copyright (C) 1991-2012, 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 provides an overview of the architecture of the IJG JPEG software;
kusano 7d535a
that is, the functions of the various modules in the system and the interfaces
kusano 7d535a
between modules.  For more precise details about any data structure or calling
kusano 7d535a
convention, see the include files and comments in the source code.
kusano 7d535a
kusano 7d535a
We assume that the reader is already somewhat familiar with the JPEG standard.
kusano 7d535a
The README file includes references for learning about JPEG.  The file
kusano 7d535a
libjpeg.txt describes the library from the viewpoint of an application
kusano 7d535a
programmer using the library; it's best to read that file before this one.
kusano 7d535a
Also, the file coderules.txt describes the coding style conventions we use.
kusano 7d535a
kusano 7d535a
In this document, JPEG-specific terminology follows the JPEG standard:
kusano 7d535a
  A "component" means a color channel, e.g., Red or Luminance.
kusano 7d535a
  A "sample" is a single component value (i.e., one number in the image data).
kusano 7d535a
  A "coefficient" is a frequency coefficient (a DCT transform output number).
kusano 7d535a
  A "block" is an array of samples or coefficients.
kusano 7d535a
  An "MCU" (minimum coded unit) is an interleaved set of blocks of size
kusano 7d535a
	determined by the sampling factors, or a single block in a
kusano 7d535a
	noninterleaved scan.
kusano 7d535a
We do not use the terms "pixel" and "sample" interchangeably.  When we say
kusano 7d535a
pixel, we mean an element of the full-size image, while a sample is an element
kusano 7d535a
of the downsampled image.  Thus the number of samples may vary across
kusano 7d535a
components while the number of pixels does not.  (This terminology is not used
kusano 7d535a
rigorously throughout the code, but it is used in places where confusion would
kusano 7d535a
otherwise result.)
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** System features ***
kusano 7d535a
kusano 7d535a
The IJG distribution contains two parts:
kusano 7d535a
  * A subroutine library for JPEG compression and decompression.
kusano 7d535a
  * cjpeg/djpeg, two sample applications that use the library to transform
kusano 7d535a
    JFIF JPEG files to and from several other image formats.
kusano 7d535a
cjpeg/djpeg are of no great intellectual complexity: they merely add a simple
kusano 7d535a
command-line user interface and I/O routines for several uncompressed image
kusano 7d535a
formats.  This document concentrates on the library itself.
kusano 7d535a
kusano 7d535a
We desire the library to be capable of supporting all JPEG baseline, extended
kusano 7d535a
sequential, and progressive DCT processes.  The library does not support the
kusano 7d535a
hierarchical or lossless processes defined in the standard.
kusano 7d535a
kusano 7d535a
Within these limits, any set of compression parameters allowed by the JPEG
kusano 7d535a
spec should be readable for decompression.  (We can be more restrictive about
kusano 7d535a
what formats we can generate.)  Although the system design allows for all
kusano 7d535a
parameter values, some uncommon settings are not yet implemented and may
kusano 7d535a
never be; nonintegral sampling ratios are the prime example.  Furthermore,
kusano 7d535a
we treat 8-bit vs. 12-bit data precision as a compile-time switch, not a
kusano 7d535a
run-time option, because most machines can store 8-bit pixels much more
kusano 7d535a
compactly than 12-bit.
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, libtiff uses this
kusano 7d535a
library to implement JPEG compression within the TIFF file format.)
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.  This code can be omitted if not needed.
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
kusano 7d535a
*** Portability issues ***
kusano 7d535a
kusano 7d535a
Portability is an essential requirement for the library.  The key portability
kusano 7d535a
issues that show up at the level of system architecture are:
kusano 7d535a
kusano 7d535a
1.  Memory usage.  We want the code to be able to run on PC-class machines
kusano 7d535a
with limited memory.  Images should therefore be processed sequentially (in
kusano 7d535a
strips), to avoid holding the whole image in memory at once.  Where a
kusano 7d535a
full-image buffer is necessary, we should be able to use either virtual memory
kusano 7d535a
or temporary files.
kusano 7d535a
kusano 7d535a
2.  Near/far pointer distinction.  To run efficiently on 80x86 machines, the
kusano 7d535a
code should distinguish "small" objects (kept in near data space) from
kusano 7d535a
"large" ones (kept in far data space).  This is an annoying restriction, but
kusano 7d535a
fortunately it does not impact code quality for less brain-damaged machines,
kusano 7d535a
and the source code clutter turns out to be minimal with sufficient use of
kusano 7d535a
pointer typedefs.
kusano 7d535a
kusano 7d535a
3. Data precision.  We assume that "char" is at least 8 bits, "short" and
kusano 7d535a
"int" at least 16, "long" at least 32.  The code will work fine with larger
kusano 7d535a
data sizes, although memory may be used inefficiently in some cases.  However,
kusano 7d535a
the JPEG compressed datastream must ultimately appear on external storage as a
kusano 7d535a
sequence of 8-bit bytes if it is to conform to the standard.  This may pose a
kusano 7d535a
problem on machines where char is wider than 8 bits.  The library represents
kusano 7d535a
compressed data as an array of values of typedef JOCTET.  If no data type
kusano 7d535a
exactly 8 bits wide is available, custom data source and data destination
kusano 7d535a
modules must be written to unpack and pack the chosen JOCTET datatype into
kusano 7d535a
8-bit external representation.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** System overview ***
kusano 7d535a
kusano 7d535a
The compressor and decompressor are each divided into two main sections:
kusano 7d535a
the JPEG compressor or decompressor proper, and the preprocessing or
kusano 7d535a
postprocessing functions.  The interface between these two sections is the
kusano 7d535a
image data that the official JPEG spec regards as its input or output: this
kusano 7d535a
data is in the colorspace to be used for compression, and it is downsampled
kusano 7d535a
to the sampling factors to be used.  The preprocessing and postprocessing
kusano 7d535a
steps are responsible for converting a normal image representation to or from
kusano 7d535a
this form.  (Those few applications that want to deal with YCbCr downsampled
kusano 7d535a
data can skip the preprocessing or postprocessing step.)
kusano 7d535a
kusano 7d535a
Looking more closely, the compressor library contains the following main
kusano 7d535a
elements:
kusano 7d535a
kusano 7d535a
  Preprocessing:
kusano 7d535a
    * Color space conversion (e.g., RGB to YCbCr).
kusano 7d535a
    * Edge expansion and downsampling.  Optionally, this step can do simple
kusano 7d535a
      smoothing --- this is often helpful for low-quality source data.
kusano 7d535a
  JPEG proper:
kusano 7d535a
    * MCU assembly, DCT, quantization.
kusano 7d535a
    * Entropy coding (sequential or progressive, Huffman or arithmetic).
kusano 7d535a
kusano 7d535a
In addition to these modules we need overall control, marker generation,
kusano 7d535a
and support code (memory management & error handling).  There is also a
kusano 7d535a
module responsible for physically writing the output data --- typically
kusano 7d535a
this is just an interface to fwrite(), but some applications may need to
kusano 7d535a
do something else with the data.
kusano 7d535a
kusano 7d535a
The decompressor library contains the following main elements:
kusano 7d535a
kusano 7d535a
  JPEG proper:
kusano 7d535a
    * Entropy decoding (sequential or progressive, Huffman or arithmetic).
kusano 7d535a
    * Dequantization, inverse DCT, MCU disassembly.
kusano 7d535a
  Postprocessing:
kusano 7d535a
    * Upsampling.  Optionally, this step may be able to do more general
kusano 7d535a
      rescaling of the image.
kusano 7d535a
    * Color space conversion (e.g., YCbCr to RGB).  This step may also
kusano 7d535a
      provide gamma adjustment [ currently it does not ].
kusano 7d535a
    * Optional color quantization (e.g., reduction to 256 colors).
kusano 7d535a
    * Optional color precision reduction (e.g., 24-bit to 15-bit color).
kusano 7d535a
      [This feature is not currently implemented.]
kusano 7d535a
kusano 7d535a
We also need overall control, marker parsing, and a data source module.
kusano 7d535a
The support code (memory management & error handling) can be shared with
kusano 7d535a
the compression half of the library.
kusano 7d535a
kusano 7d535a
There may be several implementations of each of these elements, particularly
kusano 7d535a
in the decompressor, where a wide range of speed/quality tradeoffs is very
kusano 7d535a
useful.  It must be understood that some of the best speedups involve
kusano 7d535a
merging adjacent steps in the pipeline.  For example, upsampling, color space
kusano 7d535a
conversion, and color quantization might all be done at once when using a
kusano 7d535a
low-quality ordered-dither technique.  The system architecture is designed to
kusano 7d535a
allow such merging where appropriate.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Note: it is convenient to regard edge expansion (padding to block boundaries)
kusano 7d535a
as a preprocessing/postprocessing function, even though the JPEG spec includes
kusano 7d535a
it in compression/decompression.  We do this because downsampling/upsampling
kusano 7d535a
can be simplified a little if they work on padded data: it's not necessary to
kusano 7d535a
have special cases at the right and bottom edges.  Therefore the interface
kusano 7d535a
buffer is always an integral number of blocks wide and high, and we expect
kusano 7d535a
compression preprocessing to pad the source data properly.  Padding will occur
kusano 7d535a
only to the next block (N-sample) boundary.  In an interleaved-scan situation,
kusano 7d535a
additional dummy blocks may be used to fill out MCUs, but the MCU assembly and
kusano 7d535a
disassembly logic will create or discard these blocks internally.  (This is
kusano 7d535a
advantageous for speed reasons, since we avoid DCTing the dummy blocks.
kusano 7d535a
It also permits a small reduction in file size, because the compressor can
kusano 7d535a
choose dummy block contents so as to minimize their size in compressed form.
kusano 7d535a
Finally, it makes the interface buffer specification independent of whether
kusano 7d535a
the file is actually interleaved or not.)  Applications that wish to deal
kusano 7d535a
directly with the downsampled data must provide similar buffering and padding
kusano 7d535a
for odd-sized images.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** Poor man's object-oriented programming ***
kusano 7d535a
kusano 7d535a
It should be clear by now that we have a lot of quasi-independent processing
kusano 7d535a
steps, many of which have several possible behaviors.  To avoid cluttering the
kusano 7d535a
code with lots of switch statements, we use a simple form of object-style
kusano 7d535a
programming to separate out the different possibilities.
kusano 7d535a
kusano 7d535a
For example, two different color quantization algorithms could be implemented
kusano 7d535a
as two separate modules that present the same external interface; at runtime,
kusano 7d535a
the calling code will access the proper module indirectly through an "object".
kusano 7d535a
kusano 7d535a
We can get the limited features we need while staying within portable C.
kusano 7d535a
The basic tool is a function pointer.  An "object" is just a struct
kusano 7d535a
containing one or more function pointer fields, each of which corresponds to
kusano 7d535a
a method name in real object-oriented languages.  During initialization we
kusano 7d535a
fill in the function pointers with references to whichever module we have
kusano 7d535a
determined we need to use in this run.  Then invocation of the module is done
kusano 7d535a
by indirecting through a function pointer; on most machines this is no more
kusano 7d535a
expensive than a switch statement, which would be the only other way of
kusano 7d535a
making the required run-time choice.  The really significant benefit, of
kusano 7d535a
course, is keeping the source code clean and well structured.
kusano 7d535a
kusano 7d535a
We can also arrange to have private storage that varies between different
kusano 7d535a
implementations of the same kind of object.  We do this by making all the
kusano 7d535a
module-specific object structs be separately allocated entities, which will
kusano 7d535a
be accessed via pointers in the master compression or decompression struct.
kusano 7d535a
The "public" fields or methods for a given kind of object are specified by
kusano 7d535a
a commonly known struct.  But a module's initialization code can allocate
kusano 7d535a
a larger struct that contains the common struct as its first member, plus
kusano 7d535a
additional private fields.  With appropriate pointer casting, the module's
kusano 7d535a
internal functions can access these private fields.  (For a simple example,
kusano 7d535a
see jdatadst.c, which implements the external interface specified by struct
kusano 7d535a
jpeg_destination_mgr, but adds extra fields.)
kusano 7d535a
kusano 7d535a
(Of course this would all be a lot easier if we were using C++, but we are
kusano 7d535a
not yet prepared to assume that everyone has a C++ compiler.)
kusano 7d535a
kusano 7d535a
An important benefit of this scheme is that it is easy to provide multiple
kusano 7d535a
versions of any method, each tuned to a particular case.  While a lot of
kusano 7d535a
precalculation might be done to select an optimal implementation of a method,
kusano 7d535a
the cost per invocation is constant.  For example, the upsampling step might
kusano 7d535a
have a "generic" method, plus one or more "hardwired" methods for the most
kusano 7d535a
popular sampling factors; the hardwired methods would be faster because they'd
kusano 7d535a
use straight-line code instead of for-loops.  The cost to determine which
kusano 7d535a
method to use is paid only once, at startup, and the selection criteria are
kusano 7d535a
hidden from the callers of the method.
kusano 7d535a
kusano 7d535a
This plan differs a little bit from usual object-oriented structures, in that
kusano 7d535a
only one instance of each object class will exist during execution.  The
kusano 7d535a
reason for having the class structure is that on different runs we may create
kusano 7d535a
different instances (choose to execute different modules).  You can think of
kusano 7d535a
the term "method" as denoting the common interface presented by a particular
kusano 7d535a
set of interchangeable functions, and "object" as denoting a group of related
kusano 7d535a
methods, or the total shared interface behavior of a group of modules.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** Overall control structure ***
kusano 7d535a
kusano 7d535a
We previously mentioned the need for overall control logic in the compression
kusano 7d535a
and decompression libraries.  In IJG implementations prior to v5, overall
kusano 7d535a
control was mostly provided by "pipeline control" modules, which proved to be
kusano 7d535a
large, unwieldy, and hard to understand.  To improve the situation, the
kusano 7d535a
control logic has been subdivided into multiple modules.  The control modules
kusano 7d535a
consist of:
kusano 7d535a
kusano 7d535a
1. Master control for module selection and initialization.  This has two
kusano 7d535a
responsibilities:
kusano 7d535a
kusano 7d535a
   1A.  Startup initialization at the beginning of image processing.
kusano 7d535a
        The individual processing modules to be used in this run are selected
kusano 7d535a
        and given initialization calls.
kusano 7d535a
kusano 7d535a
   1B.  Per-pass control.  This determines how many passes will be performed
kusano 7d535a
        and calls each active processing module to configure itself
kusano 7d535a
        appropriately at the beginning of each pass.  End-of-pass processing,
kusano 7d535a
	where necessary, is also invoked from the master control module.
kusano 7d535a
kusano 7d535a
   Method selection is partially distributed, in that a particular processing
kusano 7d535a
   module may contain several possible implementations of a particular method,
kusano 7d535a
   which it will select among when given its initialization call.  The master
kusano 7d535a
   control code need only be concerned with decisions that affect more than
kusano 7d535a
   one module.
kusano 7d535a
 
kusano 7d535a
2. Data buffering control.  A separate control module exists for each
kusano 7d535a
   inter-processing-step data buffer.  This module is responsible for
kusano 7d535a
   invoking the processing steps that write or read that data buffer.
kusano 7d535a
kusano 7d535a
Each buffer controller sees the world as follows:
kusano 7d535a
kusano 7d535a
input data => processing step A => buffer => processing step B => output data
kusano 7d535a
                      |              |               |
kusano 7d535a
              ------------------ controller ------------------
kusano 7d535a
kusano 7d535a
The controller knows the dataflow requirements of steps A and B: how much data
kusano 7d535a
they want to accept in one chunk and how much they output in one chunk.  Its
kusano 7d535a
function is to manage its buffer and call A and B at the proper times.
kusano 7d535a
kusano 7d535a
A data buffer control module may itself be viewed as a processing step by a
kusano 7d535a
higher-level control module; thus the control modules form a binary tree with
kusano 7d535a
elementary processing steps at the leaves of the tree.
kusano 7d535a
kusano 7d535a
The control modules are objects.  A considerable amount of flexibility can
kusano 7d535a
be had by replacing implementations of a control module.  For example:
kusano 7d535a
* Merging of adjacent steps in the pipeline is done by replacing a control
kusano 7d535a
  module and its pair of processing-step modules with a single processing-
kusano 7d535a
  step module.  (Hence the possible merges are determined by the tree of
kusano 7d535a
  control modules.)
kusano 7d535a
* In some processing modes, a given interstep buffer need only be a "strip"
kusano 7d535a
  buffer large enough to accommodate the desired data chunk sizes.  In other
kusano 7d535a
  modes, a full-image buffer is needed and several passes are required.
kusano 7d535a
  The control module determines which kind of buffer is used and manipulates
kusano 7d535a
  virtual array buffers as needed.  One or both processing steps may be
kusano 7d535a
  unaware of the multi-pass behavior.
kusano 7d535a
kusano 7d535a
In theory, we might be able to make all of the data buffer controllers
kusano 7d535a
interchangeable and provide just one set of implementations for all.  In
kusano 7d535a
practice, each one contains considerable special-case processing for its
kusano 7d535a
particular job.  The buffer controller concept should be regarded as an
kusano 7d535a
overall system structuring principle, not as a complete description of the
kusano 7d535a
task performed by any one controller.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** Compression object structure ***
kusano 7d535a
kusano 7d535a
Here is a sketch of the logical structure of the JPEG compression library:
kusano 7d535a
kusano 7d535a
                                                 |-- Colorspace conversion
kusano 7d535a
                  |-- Preprocessing controller --|
kusano 7d535a
                  |                              |-- Downsampling
kusano 7d535a
Main controller --|
kusano 7d535a
                  |                            |-- Forward DCT, quantize
kusano 7d535a
                  |-- Coefficient controller --|
kusano 7d535a
                                               |-- Entropy encoding
kusano 7d535a
kusano 7d535a
This sketch also describes the flow of control (subroutine calls) during
kusano 7d535a
typical image data processing.  Each of the components shown in the diagram is
kusano 7d535a
an "object" which may have several different implementations available.  One
kusano 7d535a
or more source code files contain the actual implementation(s) of each object.
kusano 7d535a
kusano 7d535a
The objects shown above are:
kusano 7d535a
kusano 7d535a
* Main controller: buffer controller for the subsampled-data buffer, which
kusano 7d535a
  holds the preprocessed input data.  This controller invokes preprocessing to
kusano 7d535a
  fill the subsampled-data buffer, and JPEG compression to empty it.  There is
kusano 7d535a
  usually no need for a full-image buffer here; a strip buffer is adequate.
kusano 7d535a
kusano 7d535a
* Preprocessing controller: buffer controller for the downsampling input data
kusano 7d535a
  buffer, which lies between colorspace conversion and downsampling.  Note
kusano 7d535a
  that a unified conversion/downsampling module would probably replace this
kusano 7d535a
  controller entirely.
kusano 7d535a
kusano 7d535a
* Colorspace conversion: converts application image data into the desired
kusano 7d535a
  JPEG color space; also changes the data from pixel-interleaved layout to
kusano 7d535a
  separate component planes.  Processes one pixel row at a time.
kusano 7d535a
kusano 7d535a
* Downsampling: performs reduction of chroma components as required.
kusano 7d535a
  Optionally may perform pixel-level smoothing as well.  Processes a "row
kusano 7d535a
  group" at a time, where a row group is defined as Vmax pixel rows of each
kusano 7d535a
  component before downsampling, and Vk sample rows afterwards (remember Vk
kusano 7d535a
  differs across components).  Some downsampling or smoothing algorithms may
kusano 7d535a
  require context rows above and below the current row group; the
kusano 7d535a
  preprocessing controller is responsible for supplying these rows via proper
kusano 7d535a
  buffering.  The downsampler is responsible for edge expansion at the right
kusano 7d535a
  edge (i.e., extending each sample row to a multiple of N samples); but the
kusano 7d535a
  preprocessing controller is responsible for vertical edge expansion (i.e.,
kusano 7d535a
  duplicating the bottom sample row as needed to make a multiple of N rows).
kusano 7d535a
kusano 7d535a
* Coefficient controller: buffer controller for the DCT-coefficient data.
kusano 7d535a
  This controller handles MCU assembly, including insertion of dummy DCT
kusano 7d535a
  blocks when needed at the right or bottom edge.  When performing
kusano 7d535a
  Huffman-code optimization or emitting a multiscan JPEG file, this
kusano 7d535a
  controller is responsible for buffering the full image.  The equivalent of
kusano 7d535a
  one fully interleaved MCU row of subsampled data is processed per call,
kusano 7d535a
  even when the JPEG file is noninterleaved.
kusano 7d535a
kusano 7d535a
* Forward DCT and quantization: Perform DCT, quantize, and emit coefficients.
kusano 7d535a
  Works on one or more DCT blocks at a time.  (Note: the coefficients are now
kusano 7d535a
  emitted in normal array order, which the entropy encoder is expected to
kusano 7d535a
  convert to zigzag order as necessary.  Prior versions of the IJG code did
kusano 7d535a
  the conversion to zigzag order within the quantization step.)
kusano 7d535a
kusano 7d535a
* Entropy encoding: Perform Huffman or arithmetic entropy coding and emit the
kusano 7d535a
  coded data to the data destination module.  Works on one MCU per call.
kusano 7d535a
  For progressive JPEG, the same DCT blocks are fed to the entropy coder
kusano 7d535a
  during each pass, and the coder must emit the appropriate subset of
kusano 7d535a
  coefficients.
kusano 7d535a
kusano 7d535a
In addition to the above objects, the compression library includes these
kusano 7d535a
objects:
kusano 7d535a
kusano 7d535a
* Master control: determines the number of passes required, controls overall
kusano 7d535a
  and per-pass initialization of the other modules.
kusano 7d535a
kusano 7d535a
* Marker writing: generates JPEG markers (except for RSTn, which is emitted
kusano 7d535a
  by the entropy encoder when needed).
kusano 7d535a
kusano 7d535a
* Data destination manager: writes the output JPEG datastream to its final
kusano 7d535a
  destination (e.g., a file).  The destination manager supplied with the
kusano 7d535a
  library knows how to write to a stdio stream or to a memory buffer;
kusano 7d535a
  for other behaviors, the surrounding application may provide its own
kusano 7d535a
  destination manager.
kusano 7d535a
kusano 7d535a
* Memory manager: allocates and releases memory, controls virtual arrays
kusano 7d535a
  (with backing store management, where required).
kusano 7d535a
kusano 7d535a
* Error handler: performs formatting and output of error and trace messages;
kusano 7d535a
  determines handling of nonfatal errors.  The surrounding application may
kusano 7d535a
  override some or all of this object's methods to change error handling.
kusano 7d535a
kusano 7d535a
* Progress monitor: supports output of "percent-done" progress reports.
kusano 7d535a
  This object represents an optional callback to the surrounding application:
kusano 7d535a
  if wanted, it must be supplied by the application.
kusano 7d535a
kusano 7d535a
The error handler, destination manager, and progress monitor objects are
kusano 7d535a
defined as separate objects in order to simplify application-specific
kusano 7d535a
customization of the JPEG library.  A surrounding application may override
kusano 7d535a
individual methods or supply its own all-new implementation of one of these
kusano 7d535a
objects.  The object interfaces for these objects are therefore treated as
kusano 7d535a
part of the application interface of the library, whereas the other objects
kusano 7d535a
are internal to the library.
kusano 7d535a
kusano 7d535a
The error handler and memory manager are shared by JPEG compression and
kusano 7d535a
decompression; the progress monitor, if used, may be shared as well.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** Decompression object structure ***
kusano 7d535a
kusano 7d535a
Here is a sketch of the logical structure of the JPEG decompression library:
kusano 7d535a
kusano 7d535a
                                               |-- Entropy decoding
kusano 7d535a
                  |-- Coefficient controller --|
kusano 7d535a
                  |                            |-- Dequantize, Inverse DCT
kusano 7d535a
Main controller --|
kusano 7d535a
                  |                               |-- Upsampling
kusano 7d535a
                  |-- Postprocessing controller --|   |-- Colorspace conversion
kusano 7d535a
                                                  |-- Color quantization
kusano 7d535a
                                                  |-- Color precision reduction
kusano 7d535a
kusano 7d535a
As before, this diagram also represents typical control flow.  The objects
kusano 7d535a
shown are:
kusano 7d535a
kusano 7d535a
* Main controller: buffer controller for the subsampled-data buffer, which
kusano 7d535a
  holds the output of JPEG decompression proper.  This controller's primary
kusano 7d535a
  task is to feed the postprocessing procedure.  Some upsampling algorithms
kusano 7d535a
  may require context rows above and below the current row group; when this
kusano 7d535a
  is true, the main controller is responsible for managing its buffer so as
kusano 7d535a
  to make context rows available.  In the current design, the main buffer is
kusano 7d535a
  always a strip buffer; a full-image buffer is never required.
kusano 7d535a
kusano 7d535a
* Coefficient controller: buffer controller for the DCT-coefficient data.
kusano 7d535a
  This controller handles MCU disassembly, including deletion of any dummy
kusano 7d535a
  DCT blocks at the right or bottom edge.  When reading a multiscan JPEG
kusano 7d535a
  file, this controller is responsible for buffering the full image.
kusano 7d535a
  (Buffering DCT coefficients, rather than samples, is necessary to support
kusano 7d535a
  progressive JPEG.)  The equivalent of one fully interleaved MCU row of
kusano 7d535a
  subsampled data is processed per call, even when the source JPEG file is
kusano 7d535a
  noninterleaved.
kusano 7d535a
kusano 7d535a
* Entropy decoding: Read coded data from the data source module and perform
kusano 7d535a
  Huffman or arithmetic entropy decoding.  Works on one MCU per call.
kusano 7d535a
  For progressive JPEG decoding, the coefficient controller supplies the prior
kusano 7d535a
  coefficients of each MCU (initially all zeroes), which the entropy decoder
kusano 7d535a
  modifies in each scan.
kusano 7d535a
kusano 7d535a
* Dequantization and inverse DCT: like it says.  Note that the coefficients
kusano 7d535a
  buffered by the coefficient controller have NOT been dequantized; we
kusano 7d535a
  merge dequantization and inverse DCT into a single step for speed reasons.
kusano 7d535a
  When scaled-down output is asked for, simplified DCT algorithms may be used
kusano 7d535a
  that need fewer coefficients and emit fewer samples per DCT block, not the
kusano 7d535a
  full 8x8.  Works on one DCT block at a time.
kusano 7d535a
kusano 7d535a
* Postprocessing controller: buffer controller for the color quantization
kusano 7d535a
  input buffer, when quantization is in use.  (Without quantization, this
kusano 7d535a
  controller just calls the upsampler.)  For two-pass quantization, this
kusano 7d535a
  controller is responsible for buffering the full-image data.
kusano 7d535a
kusano 7d535a
* Upsampling: restores chroma components to full size.  (May support more
kusano 7d535a
  general output rescaling, too.  Note that if undersized DCT outputs have
kusano 7d535a
  been emitted by the DCT module, this module must adjust so that properly
kusano 7d535a
  sized outputs are created.)  Works on one row group at a time.  This module
kusano 7d535a
  also calls the color conversion module, so its top level is effectively a
kusano 7d535a
  buffer controller for the upsampling->color conversion buffer.  However, in
kusano 7d535a
  all but the highest-quality operating modes, upsampling and color
kusano 7d535a
  conversion are likely to be merged into a single step.
kusano 7d535a
kusano 7d535a
* Colorspace conversion: convert from JPEG color space to output color space,
kusano 7d535a
  and change data layout from separate component planes to pixel-interleaved.
kusano 7d535a
  Works on one pixel row at a time.
kusano 7d535a
kusano 7d535a
* Color quantization: reduce the data to colormapped form, using either an
kusano 7d535a
  externally specified colormap or an internally generated one.  This module
kusano 7d535a
  is not used for full-color output.  Works on one pixel row at a time; may
kusano 7d535a
  require two passes to generate a color map.  Note that the output will
kusano 7d535a
  always be a single component representing colormap indexes.  In the current
kusano 7d535a
  design, the output values are JSAMPLEs, so an 8-bit compilation cannot
kusano 7d535a
  quantize to more than 256 colors.  This is unlikely to be a problem in
kusano 7d535a
  practice.
kusano 7d535a
kusano 7d535a
* Color reduction: this module handles color precision reduction, e.g.,
kusano 7d535a
  generating 15-bit color (5 bits/primary) from JPEG's 24-bit output.
kusano 7d535a
  Not quite clear yet how this should be handled... should we merge it with
kusano 7d535a
  colorspace conversion???
kusano 7d535a
kusano 7d535a
Note that some high-speed operating modes might condense the entire
kusano 7d535a
postprocessing sequence to a single module (upsample, color convert, and
kusano 7d535a
quantize in one step).
kusano 7d535a
kusano 7d535a
In addition to the above objects, the decompression library includes these
kusano 7d535a
objects:
kusano 7d535a
kusano 7d535a
* Master control: determines the number of passes required, controls overall
kusano 7d535a
  and per-pass initialization of the other modules.  This is subdivided into
kusano 7d535a
  input and output control: jdinput.c controls only input-side processing,
kusano 7d535a
  while jdmaster.c handles overall initialization and output-side control.
kusano 7d535a
kusano 7d535a
* Marker reading: decodes JPEG markers (except for RSTn).
kusano 7d535a
kusano 7d535a
* Data source manager: supplies the input JPEG datastream.  The source
kusano 7d535a
  manager supplied with the library knows how to read from a stdio stream
kusano 7d535a
  or from a memory buffer;  for other behaviors, the surrounding application
kusano 7d535a
  may provide its own source manager.
kusano 7d535a
kusano 7d535a
* Memory manager: same as for compression library.
kusano 7d535a
kusano 7d535a
* Error handler: same as for compression library.
kusano 7d535a
kusano 7d535a
* Progress monitor: same as for compression library.
kusano 7d535a
kusano 7d535a
As with compression, the data source manager, error handler, and progress
kusano 7d535a
monitor are candidates for replacement by a surrounding application.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** Decompression input and output separation ***
kusano 7d535a
kusano 7d535a
To support efficient incremental display of progressive JPEG files, the
kusano 7d535a
decompressor is divided into two sections that can run independently:
kusano 7d535a
kusano 7d535a
1. Data input includes marker parsing, entropy decoding, and input into the
kusano 7d535a
   coefficient controller's DCT coefficient buffer.  Note that this
kusano 7d535a
   processing is relatively cheap and fast.
kusano 7d535a
kusano 7d535a
2. Data output reads from the DCT coefficient buffer and performs the IDCT
kusano 7d535a
   and all postprocessing steps.
kusano 7d535a
kusano 7d535a
For a progressive JPEG file, the data input processing is allowed to get
kusano 7d535a
arbitrarily far ahead of the data output processing.  (This occurs only
kusano 7d535a
if the application calls jpeg_consume_input(); otherwise input and output
kusano 7d535a
run in lockstep, since the input section is called only when the output
kusano 7d535a
section needs more data.)  In this way the application can avoid making
kusano 7d535a
extra display passes when data is arriving faster than the display pass
kusano 7d535a
can run.  Furthermore, it is possible to abort an output pass without
kusano 7d535a
losing anything, since the coefficient buffer is read-only as far as the
kusano 7d535a
output section is concerned.  See libjpeg.txt for more detail.
kusano 7d535a
kusano 7d535a
A full-image coefficient array is only created if the JPEG file has multiple
kusano 7d535a
scans (or if the application specifies buffered-image mode anyway).  When
kusano 7d535a
reading a single-scan file, the coefficient controller normally creates only
kusano 7d535a
a one-MCU buffer, so input and output processing must run in lockstep in this
kusano 7d535a
case.  jpeg_consume_input() is effectively a no-op in this situation.
kusano 7d535a
kusano 7d535a
The main impact of dividing the decompressor in this fashion is that we must
kusano 7d535a
be very careful with shared variables in the cinfo data structure.  Each
kusano 7d535a
variable that can change during the course of decompression must be
kusano 7d535a
classified as belonging to data input or data output, and each section must
kusano 7d535a
look only at its own variables.  For example, the data output section may not
kusano 7d535a
depend on any of the variables that describe the current scan in the JPEG
kusano 7d535a
file, because these may change as the data input section advances into a new
kusano 7d535a
scan.
kusano 7d535a
kusano 7d535a
The progress monitor is (somewhat arbitrarily) defined to treat input of the
kusano 7d535a
file as one pass when buffered-image mode is not used, and to ignore data
kusano 7d535a
input work completely when buffered-image mode is used.  Note that the
kusano 7d535a
library has no reliable way to predict the number of passes when dealing
kusano 7d535a
with a progressive JPEG file, nor can it predict the number of output passes
kusano 7d535a
in buffered-image mode.  So the work estimate is inherently bogus anyway.
kusano 7d535a
kusano 7d535a
No comparable division is currently made in the compression library, because
kusano 7d535a
there isn't any real need for it.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** Data formats ***
kusano 7d535a
kusano 7d535a
Arrays of pixel sample values use the following data structure:
kusano 7d535a
kusano 7d535a
    typedef something JSAMPLE;		a pixel component value, 0..MAXJSAMPLE
kusano 7d535a
    typedef JSAMPLE *JSAMPROW;		ptr to a row of samples
kusano 7d535a
    typedef JSAMPROW *JSAMPARRAY;	ptr to a list of rows
kusano 7d535a
    typedef JSAMPARRAY *JSAMPIMAGE;	ptr to a list of color-component arrays
kusano 7d535a
kusano 7d535a
The basic element type JSAMPLE will typically be one of unsigned char,
kusano 7d535a
(signed) char, or short.  Short will be used if samples wider than 8 bits are
kusano 7d535a
to be supported (this is a compile-time option).  Otherwise, unsigned char is
kusano 7d535a
used if possible.  If the compiler only supports signed chars, then it is
kusano 7d535a
necessary to mask off the value when reading.  Thus, all reads of JSAMPLE
kusano 7d535a
values must be coded as "GETJSAMPLE(value)", where the macro will be defined
kusano 7d535a
as "((value) & 0xFF)" on signed-char machines and "((int) (value))" elsewhere.
kusano 7d535a
kusano 7d535a
With these conventions, JSAMPLE values can be assumed to be >= 0.  This helps
kusano 7d535a
simplify correct rounding during downsampling, etc.  The JPEG standard's
kusano 7d535a
specification that sample values run from -128..127 is accommodated by
kusano 7d535a
subtracting 128 from the sample value in the DCT step.  Similarly, during
kusano 7d535a
decompression the output of the IDCT step will be immediately shifted back to
kusano 7d535a
0..255.  (NB: different values are required when 12-bit samples are in use.
kusano 7d535a
The code is written in terms of MAXJSAMPLE and CENTERJSAMPLE, which will be
kusano 7d535a
defined as 255 and 128 respectively in an 8-bit implementation, and as 4095
kusano 7d535a
and 2048 in a 12-bit implementation.)
kusano 7d535a
kusano 7d535a
We use a pointer per row, rather than a two-dimensional JSAMPLE array.  This
kusano 7d535a
choice costs only a small amount of memory and has several benefits:
kusano 7d535a
* Code using the data structure doesn't need to know the allocated width of
kusano 7d535a
  the rows.  This simplifies edge expansion/compression, since we can work
kusano 7d535a
  in an array that's wider than the logical picture width.
kusano 7d535a
* Indexing doesn't require multiplication; this is a performance win on many
kusano 7d535a
  machines.
kusano 7d535a
* Arrays with more than 64K total elements can be supported even on machines
kusano 7d535a
  where malloc() cannot allocate chunks larger than 64K.
kusano 7d535a
* The rows forming a component array may be allocated at different times
kusano 7d535a
  without extra copying.  This trick allows some speedups in smoothing steps
kusano 7d535a
  that need access to the previous and next rows.
kusano 7d535a
kusano 7d535a
Note that each color component is stored in a separate array; we don't use the
kusano 7d535a
traditional layout in which the components of a pixel are stored together.
kusano 7d535a
This simplifies coding of modules that work on each component independently,
kusano 7d535a
because they don't need to know how many components there are.  Furthermore,
kusano 7d535a
we can read or write each component to a temporary file independently, which
kusano 7d535a
is helpful when dealing with noninterleaved JPEG files.
kusano 7d535a
kusano 7d535a
In general, a specific sample value is accessed by code such as
kusano 7d535a
	GETJSAMPLE(image[colorcomponent][row][col])
kusano 7d535a
where col is measured from the image left edge, but row is measured from the
kusano 7d535a
first sample row currently in memory.  Either of the first two indexings can
kusano 7d535a
be precomputed by copying the relevant pointer.
kusano 7d535a
kusano 7d535a
kusano 7d535a
Since most image-processing applications prefer to work on images in which
kusano 7d535a
the components of a pixel are stored together, the data passed to or from the
kusano 7d535a
surrounding application uses the traditional convention: a single pixel is
kusano 7d535a
represented by N consecutive JSAMPLE values, and an image row is an array of
kusano 7d535a
(# of color components)*(image width) JSAMPLEs.  One or more rows of data can
kusano 7d535a
be represented by a pointer of type JSAMPARRAY in this scheme.  This scheme is
kusano 7d535a
converted to component-wise storage inside the JPEG library.  (Applications
kusano 7d535a
that want to skip JPEG preprocessing or postprocessing will have to contend
kusano 7d535a
with component-wise storage.)
kusano 7d535a
kusano 7d535a
kusano 7d535a
Arrays of DCT-coefficient values use the following data structure:
kusano 7d535a
kusano 7d535a
    typedef short JCOEF;		a 16-bit signed integer
kusano 7d535a
    typedef JCOEF JBLOCK[DCTSIZE2];	an 8x8 block of coefficients
kusano 7d535a
    typedef JBLOCK *JBLOCKROW;		ptr to one horizontal row of 8x8 blocks
kusano 7d535a
    typedef JBLOCKROW *JBLOCKARRAY;	ptr to a list of such rows
kusano 7d535a
    typedef JBLOCKARRAY *JBLOCKIMAGE;	ptr to a list of color component arrays
kusano 7d535a
kusano 7d535a
The underlying type is at least a 16-bit signed integer; while "short" is big
kusano 7d535a
enough on all machines of interest, on some machines it is preferable to use
kusano 7d535a
"int" for speed reasons, despite the storage cost.  Coefficients are grouped
kusano 7d535a
into 8x8 blocks (but we always use #defines DCTSIZE and DCTSIZE2 rather than
kusano 7d535a
"8" and "64").
kusano 7d535a
kusano 7d535a
The contents of a coefficient block may be in either "natural" or zigzagged
kusano 7d535a
order, and may be true values or divided by the quantization coefficients,
kusano 7d535a
depending on where the block is in the processing pipeline.  In the current
kusano 7d535a
library, coefficient blocks are kept in natural order everywhere; the entropy
kusano 7d535a
codecs zigzag or dezigzag the data as it is written or read.  The blocks
kusano 7d535a
contain quantized coefficients everywhere outside the DCT/IDCT subsystems.
kusano 7d535a
(This latter decision may need to be revisited to support variable
kusano 7d535a
quantization a la JPEG Part 3.)
kusano 7d535a
kusano 7d535a
Notice that the allocation unit is now a row of 8x8 coefficient blocks,
kusano 7d535a
corresponding to N rows of samples.  Otherwise the structure is much the same
kusano 7d535a
as for samples, and for the same reasons.
kusano 7d535a
kusano 7d535a
On machines where malloc() can't handle a request bigger than 64Kb, this data
kusano 7d535a
structure limits us to rows of less than 512 JBLOCKs, or a picture width of
kusano 7d535a
4000+ pixels.  This seems an acceptable restriction.
kusano 7d535a
kusano 7d535a
kusano 7d535a
On 80x86 machines, the bottom-level pointer types (JSAMPROW and JBLOCKROW)
kusano 7d535a
must be declared as "far" pointers, but the upper levels can be "near"
kusano 7d535a
(implying that the pointer lists are allocated in the DS segment).
kusano 7d535a
We use a #define symbol FAR, which expands to the "far" keyword when
kusano 7d535a
compiling on 80x86 machines and to nothing elsewhere.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** Suspendable processing ***
kusano 7d535a
kusano 7d535a
In some applications it is desirable to use the JPEG library as an
kusano 7d535a
incremental, memory-to-memory filter.  In this situation the data source or
kusano 7d535a
destination may be a limited-size buffer, and we can't rely on being able to
kusano 7d535a
empty or refill the buffer at arbitrary times.  Instead the application would
kusano 7d535a
like to have control return from the library at buffer overflow/underrun, and
kusano 7d535a
then resume compression or decompression at a later time.
kusano 7d535a
kusano 7d535a
This scenario is supported for simple cases.  (For anything more complex, we
kusano 7d535a
recommend that the application "bite the bullet" and develop real multitasking
kusano 7d535a
capability.)  The libjpeg.txt file goes into more detail about the usage and
kusano 7d535a
limitations of this capability; here we address the implications for library
kusano 7d535a
structure.
kusano 7d535a
kusano 7d535a
The essence of the problem is that the entropy codec (coder or decoder) must
kusano 7d535a
be prepared to stop at arbitrary times.  In turn, the controllers that call
kusano 7d535a
the entropy codec must be able to stop before having produced or consumed all
kusano 7d535a
the data that they normally would handle in one call.  That part is reasonably
kusano 7d535a
straightforward: we make the controller call interfaces include "progress
kusano 7d535a
counters" which indicate the number of data chunks successfully processed, and
kusano 7d535a
we require callers to test the counter rather than just assume all of the data
kusano 7d535a
was processed.
kusano 7d535a
kusano 7d535a
Rather than trying to restart at an arbitrary point, the current Huffman
kusano 7d535a
codecs are designed to restart at the beginning of the current MCU after a
kusano 7d535a
suspension due to buffer overflow/underrun.  At the start of each call, the
kusano 7d535a
codec's internal state is loaded from permanent storage (in the JPEG object
kusano 7d535a
structures) into local variables.  On successful completion of the MCU, the
kusano 7d535a
permanent state is updated.  (This copying is not very expensive, and may even
kusano 7d535a
lead to *improved* performance if the local variables can be registerized.)
kusano 7d535a
If a suspension occurs, the codec simply returns without updating the state,
kusano 7d535a
thus effectively reverting to the start of the MCU.  Note that this implies
kusano 7d535a
leaving some data unprocessed in the source/destination buffer (ie, the
kusano 7d535a
compressed partial MCU).  The data source/destination module interfaces are
kusano 7d535a
specified so as to make this possible.  This also implies that the data buffer
kusano 7d535a
must be large enough to hold a worst-case compressed MCU; a couple thousand
kusano 7d535a
bytes should be enough.
kusano 7d535a
kusano 7d535a
In a successive-approximation AC refinement scan, the progressive Huffman
kusano 7d535a
decoder has to be able to undo assignments of newly nonzero coefficients if it
kusano 7d535a
suspends before the MCU is complete, since decoding requires distinguishing
kusano 7d535a
previously-zero and previously-nonzero coefficients.  This is a bit tedious
kusano 7d535a
but probably won't have much effect on performance.  Other variants of Huffman
kusano 7d535a
decoding need not worry about this, since they will just store the same values
kusano 7d535a
again if forced to repeat the MCU.
kusano 7d535a
kusano 7d535a
This approach would probably not work for an arithmetic codec, since its
kusano 7d535a
modifiable state is quite large and couldn't be copied cheaply.  Instead it
kusano 7d535a
would have to suspend and resume exactly at the point of the buffer end.
kusano 7d535a
kusano 7d535a
The JPEG marker reader is designed to cope with suspension at an arbitrary
kusano 7d535a
point.  It does so by backing up to the start of the marker parameter segment,
kusano 7d535a
so the data buffer must be big enough to hold the largest marker of interest.
kusano 7d535a
Again, a couple KB should be adequate.  (A special "skip" convention is used
kusano 7d535a
to bypass COM and APPn markers, so these can be larger than the buffer size
kusano 7d535a
without causing problems; otherwise a 64K buffer would be needed in the worst
kusano 7d535a
case.)
kusano 7d535a
kusano 7d535a
The JPEG marker writer currently does *not* cope with suspension.
kusano 7d535a
We feel that this is not necessary; it is much easier simply to require
kusano 7d535a
the application to ensure there is enough buffer space before starting.  (An
kusano 7d535a
empty 2K buffer is more than sufficient for the header markers; and ensuring
kusano 7d535a
there are a dozen or two bytes available before calling jpeg_finish_compress()
kusano 7d535a
will suffice for the trailer.)  This would not work for writing multi-scan
kusano 7d535a
JPEG files, but we simply do not intend to support that capability with
kusano 7d535a
suspension.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** Memory manager services ***
kusano 7d535a
kusano 7d535a
The JPEG library's memory manager controls allocation and deallocation of
kusano 7d535a
memory, and it manages large "virtual" data arrays on machines where the
kusano 7d535a
operating system does not provide virtual memory.  Note that the same
kusano 7d535a
memory manager serves both compression and decompression operations.
kusano 7d535a
kusano 7d535a
In all cases, allocated objects are tied to a particular compression or
kusano 7d535a
decompression master record, and they will be released when that master
kusano 7d535a
record is destroyed.
kusano 7d535a
kusano 7d535a
The memory manager does not provide explicit deallocation of objects.
kusano 7d535a
Instead, objects are created in "pools" of free storage, and a whole pool
kusano 7d535a
can be freed at once.  This approach helps prevent storage-leak bugs, and
kusano 7d535a
it speeds up operations whenever malloc/free are slow (as they often are).
kusano 7d535a
The pools can be regarded as lifetime identifiers for objects.  Two
kusano 7d535a
pools/lifetimes are defined:
kusano 7d535a
  * JPOOL_PERMANENT	lasts until master record is destroyed
kusano 7d535a
  * JPOOL_IMAGE		lasts until done with image (JPEG datastream)
kusano 7d535a
Permanent lifetime is used for parameters and tables that should be carried
kusano 7d535a
across from one datastream to another; this includes all application-visible
kusano 7d535a
parameters.  Image lifetime is used for everything else.  (A third lifetime,
kusano 7d535a
JPOOL_PASS = one processing pass, was originally planned.  However it was
kusano 7d535a
dropped as not being worthwhile.  The actual usage patterns are such that the
kusano 7d535a
peak memory usage would be about the same anyway; and having per-pass storage
kusano 7d535a
substantially complicates the virtual memory allocation rules --- see below.)
kusano 7d535a
kusano 7d535a
The memory manager deals with three kinds of object:
kusano 7d535a
1. "Small" objects.  Typically these require no more than 10K-20K total.
kusano 7d535a
2. "Large" objects.  These may require tens to hundreds of K depending on
kusano 7d535a
   image size.  Semantically they behave the same as small objects, but we
kusano 7d535a
   distinguish them for two reasons:
kusano 7d535a
     * On MS-DOS machines, large objects are referenced by FAR pointers,
kusano 7d535a
       small objects by NEAR pointers.
kusano 7d535a
     * Pool allocation heuristics may differ for large and small objects.
kusano 7d535a
   Note that individual "large" objects cannot exceed the size allowed by
kusano 7d535a
   type size_t, which may be 64K or less on some machines.
kusano 7d535a
3. "Virtual" objects.  These are large 2-D arrays of JSAMPLEs or JBLOCKs
kusano 7d535a
   (typically large enough for the entire image being processed).  The
kusano 7d535a
   memory manager provides stripwise access to these arrays.  On machines
kusano 7d535a
   without virtual memory, the rest of the array may be swapped out to a
kusano 7d535a
   temporary file.
kusano 7d535a
kusano 7d535a
(Note: JSAMPARRAY and JBLOCKARRAY data structures are a combination of large
kusano 7d535a
objects for the data proper and small objects for the row pointers.  For
kusano 7d535a
convenience and speed, the memory manager provides single routines to create
kusano 7d535a
these structures.  Similarly, virtual arrays include a small control block
kusano 7d535a
and a JSAMPARRAY or JBLOCKARRAY working buffer, all created with one call.)
kusano 7d535a
kusano 7d535a
In the present implementation, virtual arrays are only permitted to have image
kusano 7d535a
lifespan.  (Permanent lifespan would not be reasonable, and pass lifespan is
kusano 7d535a
not very useful since a virtual array's raison d'etre is to store data for
kusano 7d535a
multiple passes through the image.)  We also expect that only "small" objects
kusano 7d535a
will be given permanent lifespan, though this restriction is not required by
kusano 7d535a
the memory manager.
kusano 7d535a
kusano 7d535a
In a non-virtual-memory machine, some performance benefit can be gained by
kusano 7d535a
making the in-memory buffers for virtual arrays be as large as possible.
kusano 7d535a
(For small images, the buffers might fit entirely in memory, so blind
kusano 7d535a
swapping would be very wasteful.)  The memory manager will adjust the height
kusano 7d535a
of the buffers to fit within a prespecified maximum memory usage.  In order
kusano 7d535a
to do this in a reasonably optimal fashion, the manager needs to allocate all
kusano 7d535a
of the virtual arrays at once.  Therefore, there isn't a one-step allocation
kusano 7d535a
routine for virtual arrays; instead, there is a "request" routine that simply
kusano 7d535a
allocates the control block, and a "realize" routine (called just once) that
kusano 7d535a
determines space allocation and creates all of the actual buffers.  The
kusano 7d535a
realize routine must allow for space occupied by non-virtual large objects.
kusano 7d535a
(We don't bother to factor in the space needed for small objects, on the
kusano 7d535a
grounds that it isn't worth the trouble.)
kusano 7d535a
kusano 7d535a
To support all this, we establish the following protocol for doing business
kusano 7d535a
with the memory manager:
kusano 7d535a
  1. Modules must request virtual arrays (which may have only image lifespan)
kusano 7d535a
     during the initial setup phase, i.e., in their jinit_xxx routines.
kusano 7d535a
  2. All "large" objects (including JSAMPARRAYs and JBLOCKARRAYs) must also be
kusano 7d535a
     allocated during initial setup.
kusano 7d535a
  3. realize_virt_arrays will be called at the completion of initial setup.
kusano 7d535a
     The above conventions ensure that sufficient information is available
kusano 7d535a
     for it to choose a good size for virtual array buffers.
kusano 7d535a
Small objects of any lifespan may be allocated at any time.  We expect that
kusano 7d535a
the total space used for small objects will be small enough to be negligible
kusano 7d535a
in the realize_virt_arrays computation.
kusano 7d535a
kusano 7d535a
In a virtual-memory machine, we simply pretend that the available space is
kusano 7d535a
infinite, thus causing realize_virt_arrays to decide that it can allocate all
kusano 7d535a
the virtual arrays as full-size in-memory buffers.  The overhead of the
kusano 7d535a
virtual-array access protocol is very small when no swapping occurs.
kusano 7d535a
kusano 7d535a
A virtual array can be specified to be "pre-zeroed"; when this flag is set,
kusano 7d535a
never-yet-written sections of the array are set to zero before being made
kusano 7d535a
available to the caller.  If this flag is not set, never-written sections
kusano 7d535a
of the array contain garbage.  (This feature exists primarily because the
kusano 7d535a
equivalent logic would otherwise be needed in jdcoefct.c for progressive
kusano 7d535a
JPEG mode; we may as well make it available for possible other uses.)
kusano 7d535a
kusano 7d535a
The first write pass on a virtual array is required to occur in top-to-bottom
kusano 7d535a
order; read passes, as well as any write passes after the first one, may
kusano 7d535a
access the array in any order.  This restriction exists partly to simplify
kusano 7d535a
the virtual array control logic, and partly because some file systems may not
kusano 7d535a
support seeking beyond the current end-of-file in a temporary file.  The main
kusano 7d535a
implication of this restriction is that rearrangement of rows (such as
kusano 7d535a
converting top-to-bottom data order to bottom-to-top) must be handled while
kusano 7d535a
reading data out of the virtual array, not while putting it in.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** Memory manager internal structure ***
kusano 7d535a
kusano 7d535a
To isolate system dependencies as much as possible, we have broken the
kusano 7d535a
memory manager into two parts.  There is a reasonably system-independent
kusano 7d535a
"front end" (jmemmgr.c) and a "back end" that contains only the code
kusano 7d535a
likely to change across systems.  All of the memory management methods
kusano 7d535a
outlined above are implemented by the front end.  The back end provides
kusano 7d535a
the following routines for use by the front end (none of these routines
kusano 7d535a
are known to the rest of the JPEG code):
kusano 7d535a
kusano 7d535a
jpeg_mem_init, jpeg_mem_term	system-dependent initialization/shutdown
kusano 7d535a
kusano 7d535a
jpeg_get_small, jpeg_free_small	interface to malloc and free library routines
kusano 7d535a
				(or their equivalents)
kusano 7d535a
kusano 7d535a
jpeg_get_large, jpeg_free_large	interface to FAR malloc/free in MSDOS machines;
kusano 7d535a
				else usually the same as
kusano 7d535a
				jpeg_get_small/jpeg_free_small
kusano 7d535a
kusano 7d535a
jpeg_mem_available		estimate available memory
kusano 7d535a
kusano 7d535a
jpeg_open_backing_store		create a backing-store object
kusano 7d535a
kusano 7d535a
read_backing_store,		manipulate a backing-store object
kusano 7d535a
write_backing_store,
kusano 7d535a
close_backing_store
kusano 7d535a
kusano 7d535a
On some systems there will be more than one type of backing-store object
kusano 7d535a
(specifically, in MS-DOS a backing store file might be an area of extended
kusano 7d535a
memory as well as a disk file).  jpeg_open_backing_store is responsible for
kusano 7d535a
choosing how to implement a given object.  The read/write/close routines
kusano 7d535a
are method pointers in the structure that describes a given object; this
kusano 7d535a
lets them be different for different object types.
kusano 7d535a
kusano 7d535a
It may be necessary to ensure that backing store objects are explicitly
kusano 7d535a
released upon abnormal program termination.  For example, MS-DOS won't free
kusano 7d535a
extended memory by itself.  To support this, we will expect the main program
kusano 7d535a
or surrounding application to arrange to call self_destruct (typically via
kusano 7d535a
jpeg_destroy) upon abnormal termination.  This may require a SIGINT signal
kusano 7d535a
handler or equivalent.  We don't want to have the back end module install its
kusano 7d535a
own signal handler, because that would pre-empt the surrounding application's
kusano 7d535a
ability to control signal handling.
kusano 7d535a
kusano 7d535a
The IJG distribution includes several memory manager back end implementations.
kusano 7d535a
Usually the same back end should be suitable for all applications on a given
kusano 7d535a
system, but it is possible for an application to supply its own back end at
kusano 7d535a
need.
kusano 7d535a
kusano 7d535a
kusano 7d535a
*** Implications of DNL marker ***
kusano 7d535a
kusano 7d535a
Some JPEG files may use a DNL marker to postpone definition of the image
kusano 7d535a
height (this would be useful for a fax-like scanner's output, for instance).
kusano 7d535a
In these files the SOF marker claims the image height is 0, and you only
kusano 7d535a
find out the true image height at the end of the first scan.
kusano 7d535a
kusano 7d535a
We could read these files as follows:
kusano 7d535a
1. Upon seeing zero image height, replace it by 65535 (the maximum allowed).
kusano 7d535a
2. When the DNL is found, update the image height in the global image
kusano 7d535a
   descriptor.
kusano 7d535a
This implies that control modules must avoid making copies of the image
kusano 7d535a
height, and must re-test for termination after each MCU row.  This would
kusano 7d535a
be easy enough to do.
kusano 7d535a
kusano 7d535a
In cases where image-size data structures are allocated, this approach will
kusano 7d535a
result in very inefficient use of virtual memory or much-larger-than-necessary
kusano 7d535a
temporary files.  This seems acceptable for something that probably won't be a
kusano 7d535a
mainstream usage.  People might have to forgo use of memory-hogging options
kusano 7d535a
(such as two-pass color quantization or noninterleaved JPEG files) if they
kusano 7d535a
want efficient conversion of such files.  (One could improve efficiency by
kusano 7d535a
demanding a user-supplied upper bound for the height, less than 65536; in most
kusano 7d535a
cases it could be much less.)
kusano 7d535a
kusano 7d535a
The standard also permits the SOF marker to overestimate the image height,
kusano 7d535a
with a DNL to give the true, smaller height at the end of the first scan.
kusano 7d535a
This would solve the space problems if the overestimate wasn't too great.
kusano 7d535a
However, it implies that you don't even know whether DNL will be used.
kusano 7d535a
kusano 7d535a
This leads to a couple of very serious objections:
kusano 7d535a
1. Testing for a DNL marker must occur in the inner loop of the decompressor's
kusano 7d535a
   Huffman decoder; this implies a speed penalty whether the feature is used
kusano 7d535a
   or not.
kusano 7d535a
2. There is no way to hide the last-minute change in image height from an
kusano 7d535a
   application using the decoder.  Thus *every* application using the IJG
kusano 7d535a
   library would suffer a complexity penalty whether it cared about DNL or
kusano 7d535a
   not.
kusano 7d535a
We currently do not support DNL because of these problems.
kusano 7d535a
kusano 7d535a
A different approach is to insist that DNL-using files be preprocessed by a
kusano 7d535a
separate program that reads ahead to the DNL, then goes back and fixes the SOF
kusano 7d535a
marker.  This is a much simpler solution and is probably far more efficient.
kusano 7d535a
Even if one wants piped input, buffering the first scan of the JPEG file needs
kusano 7d535a
a lot smaller temp file than is implied by the maximum-height method.  For
kusano 7d535a
this approach we'd simply treat DNL as a no-op in the decompressor (at most,
kusano 7d535a
check that it matches the SOF image height).
kusano 7d535a
kusano 7d535a
We will not worry about making the compressor capable of outputting DNL.
kusano 7d535a
Something similar to the first scheme above could be applied if anyone ever
kusano 7d535a
wants to make that work.