home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume34 / jpeg / part03 / architecture.B next >
Encoding:
Text File  |  1992-12-17  |  39.5 KB  |  696 lines

  1.  
  2. For similar reasons, one MCU is also the best chunk size for the frequency
  3. coefficient quantization and dequantization steps.
  4.  
  5. For downsampling and upsampling, the best chunk size is to have each call
  6. transform Vk sample rows from or to Vmax sample rows (Vk = this component's
  7. vertical sampling factor, Vmax = largest vertical sampling factor).  There are
  8. eight such chunks in each MCU row.  Using a whole MCU row as the chunk size
  9. would reduce function call overhead a fraction, but would imply more buffering
  10. to provide context for cross-pixel smoothing.
  11.  
  12.  
  13. *** Compression object structure ***
  14.  
  15. I propose the following set of objects for the compressor.  Here an "object"
  16. is the common interface for one or more modules having comparable functions.
  17.  
  18. Most of these objects can be justified as information-hiding modules.
  19. I've indicated what information is private to each object/module.
  20.  
  21. Note that in all cases, the caller of a method is expected to have allocated
  22. any storage needed for it to return its result.  (Typically this storage can
  23. be re-used in successive calls, so malloc'ing and free'ing once per call is
  24. not reasonable.)  Also, much of the context required (compression parameters,
  25. image size, etc) will be passed around in large common data structures, which
  26. aren't described here; see the header files.  Notice that any object that
  27. might need to allocate working storage receives an "init" and a "term" call;
  28. "term" should be careful to free all allocated storage so that the JPEG system
  29. can be used multiple times during a program run.  (For the same reason,
  30. depending on static initialization of variables is a no-no.  The only
  31. exception to the free-all-allocated-storage rule is that storage allocated for
  32. the entire processing of an image need not be explicitly freed, since the
  33. memory manager's free_all cleanup will free it.)
  34.  
  35. 1. Input file conversion to standardized form.  This provides these methods:
  36.     input_init: read the file header, report image size & component count.
  37.     get_input_row: read one pixel row, return it in our standard format.
  38.     input_term: finish up at the end.
  39.    In implementations that support multiple input formats, input_init could
  40.    set up an appropriate get_input_row method depending on the format it
  41.    finds.  Note that in most applications, the selection and opening of the
  42.    input file will be under the control of the user interface module; and
  43.    indeed the user interface may have already read the input header, so that
  44.    all that input_init may have to do is return previously saved values.  The
  45.    behind-the-scenes interaction between this object and the user interface is
  46.    not specified by this architecture.
  47.    (Hides format of input image and mechanism used to read it.  This code is
  48.    likely to vary considerably from one implementation to another.  Note that
  49.    the color space and number of color components of the source are not hidden;
  50.    but they are used only by the next object.)
  51.  
  52. 2. Gamma and color space conversion.  This provides three methods:
  53.     colorin_init: initialization.
  54.     get_sample_rows: read, convert, and return a specified number of pixel
  55.              rows (not more than remain in the picture).
  56.     colorin_term: finish up at the end.
  57.    The most efficient approach seems to be for this object to call
  58.    get_input_row directly, rather than being passed the input data; that way,
  59.    any intermediate storage required can be local to this object.
  60.    (get_sample_rows might tell get_input_row to read directly into its own
  61.    output area and then convert in place; or it may do something different.
  62.    For example, conversion in place wouldn't work if it is changing the number
  63.    of color components.)  The output of this step is in the standardized
  64.    sample array format shown previously.
  65.    (Hides all knowledge of color space semantics and conversion.  Remaining
  66.    modules only need to know the number of JPEG components.)
  67.  
  68. 3. Edge expansion: needs only a single method.
  69.     edge_expand: Given an NxM sample array, expand to a desired size (a
  70.              multiple of the MCU dimensions) by duplicating the last
  71.              row or column.  Repeat for each component.
  72.    Expansion will occur in place, so the caller must have pre-allocated enough
  73.    storage.  (I'm assuming that it is easier and faster to do this expansion
  74.    than it is to worry about boundary conditions in the next two steps.
  75.    Notice that vertical expansion will occur only once, at the bottom of the
  76.    picture, so only horizontal expansion by a few pixels is speed-critical.)
  77.    (This doesn't really hide any information, so maybe it could be a simple
  78.    subroutine instead of a method.  Depends on whether we want to be able to
  79.    use alternative, optimized methods.)
  80.  
  81. 4. Downsampling: this will be applied to one component at a time.
  82.     downsample_init: initialize (precalculate convolution factors, for
  83.              example).  This will be called once per scan.
  84.     downsample: Given a sample array, reduce it to a smaller number of
  85.             samples using specified sampling factors.
  86.     downsample_term: clean up at the end of a scan.
  87.    If the current component has vertical sampling factor Vk and the largest
  88.    sampling factor is Vmax, then the input is always Vmax sample rows (whose
  89.    width is a multiple of Hmax) and the output is always Vk sample rows.
  90.    Vmax additional rows above and below the nominal input rows are also passed
  91.    for use by partial-pixel-averaging sampling methods.  (Is this necessary?)
  92.    At the top and bottom of the image, these extra rows are copies of the
  93.    first or last actual input row.
  94.    (This hides whether and how cross-pixel averaging occurs.)
  95.  
  96. 5. MCU extraction (creation of a single sequence of 8x8 sample blocks).
  97.     extract_init: initialize as needed.  This will be called once per scan.
  98.     extract_MCUs: convert a sample array to a sequence of MCUs.
  99.     extract_term: clean up at the end of a scan.
  100.    Given one or more MCU rows worth of image data, extract sample blocks in the
  101.    appropriate order; pass these off to subsequent steps one MCU at a time.
  102.    The input must be a multiple of the MCU dimensions.  It will probably be
  103.    most convenient for the DCT transform, frequency quantization, and zigzag
  104.    reordering of each block to be done as simple subroutines of this step.
  105.    Once a transformed MCU has been completed, it'll be passed off to a
  106.    method call, which will be passed as a parameter to extract_MCUs.
  107.    That routine might either encode and output the MCU immediately, or buffer
  108.    it up for later output if we want to do global optimization of the entropy
  109.    encoding coefficients.  Note: when outputting a noninterleaved file this
  110.    object will be called separately for each component.  Direct output could
  111.    be done for the first component, but the others would have to be buffered.
  112.    (Again, an object mainly on the grounds that multiple instantiations might
  113.    be useful.)
  114.  
  115. 6. DCT transformation of each 8x8 block.  This probably doesn't have to be a
  116.    full-fledged method, but just a plain subroutine that will be called by MCU
  117.    extraction.  One 8x8 block will be processed per call.
  118.  
  119. 7. Quantization scaling and zigzag reordering of the elements in each 8x8
  120.    block.  (This can probably be a plain subroutine called once per block by
  121.    MCU extraction; hard to see a need for multiple instantiations here.)
  122.  
  123. 8. Entropy encoding (Huffman or arithmetic).
  124.     entropy_encode_init: prepare for one scan.
  125.     entropy_encode: accepts an MCU's worth of quantized coefficients,
  126.             encodes and outputs them.
  127.     entropy_encode_term: finish up at end of a scan (dump any buffered
  128.                  bytes, for example).
  129.    The data output by this module will be sent to the entropy_output method
  130.    provided by the pipeline controller.  (It will probably be worth using
  131.    buffering to pass multiple bytes per call of the output method.)  The
  132.    output method could be just write_jpeg_data, but might also be a dummy
  133.    routine that counts output bytes (for use during cut-and-try coefficient
  134.    optimization).
  135.    (This hides which entropy encoding method is in use.)
  136.  
  137. 9. JPEG file header construction.  This will provide these methods:
  138.     write_file_header: output the initial header.
  139.     write_scan_header: output scan header (called once per component
  140.                if noninterleaved mode).
  141.     write_jpeg_data: the actual data output method for the preceding step.
  142.     write_scan_trailer: finish up after one scan.
  143.     write_file_trailer: finish up at end of file.
  144.    Note that compressed data is passed to the write_jpeg_data method, in case
  145.    a simple fwrite isn't appropriate for some reason.
  146.    (This hides which variant JPEG file format is being written.  Also, the
  147.    actual mechanism for writing the file is private to this object and the
  148.    user interface.)
  149.  
  150. 10. Pipeline control.  This object will provide the "main loop" that invokes
  151.     all the pipeline objects.  Note that we will need several different main
  152.     loops depending on the situation (interleaved output or not, global
  153.     optimization of encoding parameters or not, etc).  This object will do
  154.     most of the memory allocation, since it will provide the working buffers
  155.     that are the inputs and outputs of the pipeline steps.
  156.     (An object mostly to support multiple instantiations; however, overall
  157.     memory management and sequencing of operations are known only here.)
  158.  
  159. 11. Overall control.  This module will provide at least two routines:
  160.     jpeg_compress: the main entry point to the compressor.
  161.     per_scan_method_selection: called by pipeline controllers for
  162.                    secondary method selection passes.
  163.     jpeg_compress is invoked from the user interface after the UI has selected
  164.     the input and output files and obtained values for all compression
  165.     parameters that aren't dynamically determined.  jpeg_compress performs
  166.     basic initialization (e.g., calculating the size of MCUs), does the
  167.     "global" method selection pass, and finally calls the selected pipeline
  168.     control object.  (Per-scan method selections will be invoked by the
  169.     pipeline controller.)
  170.     Note that jpeg_compress can't be a method since it is invoked prior to
  171.     method selection.
  172.  
  173. 12. User interface; this is the architecture's term for "the rest of the
  174.     application program", i.e., that which invokes the JPEG compressor.  In a
  175.     standalone JPEG compression program the UI need be little more than a C
  176.     main() routine and argument parsing code; but we can expect that the JPEG
  177.     compressor may be incorporated into complex graphics applications, wherein
  178.     the UI is much more complex.  Much of the UI will need to be written
  179.     afresh for each non-Unix-like platform the compressor is ported to.
  180.     The UI is expected to supply input and output files and values for all
  181.     non-automatically-chosen compression parameters.  (Hence defaults are
  182.     determined by the UI; we should provide helpful routines to fill in
  183.     the recommended defaults.)  The UI must also supply error handling
  184.     routines and some mechanism for trace messages.
  185.     (This module hides the user interface provided --- command line,
  186.     interactive, etc.  Except for error/message handling, the UI calls the
  187.     portable JPEG code, not the other way around.)
  188.  
  189. 13. (Optional) Compression parameter selection control.
  190.     entropy_optimize: given an array of MCUs ready to be fed to entropy
  191.               encoding, find optimal encoding parameters.
  192.     The actual optimization algorithm ought to be separated out as an object,
  193.     even though a special pipeline control method will be needed.  (The
  194.     pipeline controller only has to understand that the output of extract_MCUs
  195.     must be built up as a virtual array rather than fed directly to entropy
  196.     encoding and output.  This pipeline behavior may also be useful for future
  197.     implementation of hierarchical modes, etc.)
  198.     To minimize the amount of control logic in the optimization module, the
  199.     pipeline control doesn't actually hand over big-array pointers, but rather
  200.     an "iterator": a function which knows how to scan the stored image.
  201.     (This hides the details of the parameter optimization algorithm.)
  202.  
  203.     The present design doesn't allow for multiple passes at earlier points
  204.     in the pipeline, but allowing that would only require providing some
  205.     new pipeline control methods; nothing else need change.
  206.  
  207. 14. A memory management object.  This will provide methods to allocate "small"
  208.     things and "big" things.  Small things have to fit in memory and you get
  209.     back direct pointers (this could be handled by direct calls to malloc, but
  210.     it's cleaner not to assume malloc is the right routine).  "Big" things
  211.     mean buffered images for multiple passes, noninterleaved output, etc.
  212.     In this case the memory management object will give you room for a few MCU
  213.     rows and you have to ask for access to the next few; dumping and reloading
  214.     in a temporary file will go on behind the scenes.  (All big objects are
  215.     image arrays containing either samples or coefficients, and will be
  216.     scanned top-to-bottom some number of times, so we can apply this access
  217.     model easily.)  On a platform with virtual memory, the memory manager can
  218.     treat small and big things alike: just malloc up enough virtual memory for
  219.     the whole image, and let the operating system worry about swapping the
  220.     image to disk.
  221.  
  222.     Most of the actual calls on the memory manager will be made from pipeline
  223.     control objects; changing any data item from "small" to "big" status would
  224.     require a new pipeline control object, since it will contain the logic to
  225.     ask for a new chunk of a big thing.  Thus, one way in which pipeline
  226.     controllers will vary is in which structures they treat as big.
  227.  
  228.     The memory manager will need to be told roughly how much space is going to
  229.     be requested overall, so that it can figure out how big a buffer is safe
  230.     to allocate for a "big" object.  (If it happens that you are dealing with
  231.     a small image, you'd like to decide to keep it all in memory!)  The most
  232.     flexible way of doing this is to divide allocation of "big" objects into
  233.     two steps.  First, there will be one or more "request" calls that indicate
  234.     the desired object sizes; then an "instantiate" call causes the memory
  235.     manager to actually construct the objects.  The instantiation must occur
  236.     before the contents of any big object can be accessed.
  237.  
  238.     For 80x86 CPUs, we would like the code to be compilable under small or
  239.     medium model, meaning that pointers are 16 bits unless explicitly declared
  240.     FAR.  Hence space allocated by the "small" allocator must fit into the
  241.     64Kb default data segment, along with stack space and global/static data.
  242.     For normal JPEG operations we seem to need only about 32Kb of such space,
  243.     so we are within the target (and have a reasonable slop for the needs of
  244.     a surrounding application program).  However, some color quantization
  245.     algorithms need 64Kb or more of all-in-memory space in order to create
  246.     color histograms.  For this purpose, we will also support "medium" size
  247.     things.  These are semantically the same as "small" things but are
  248.     referenced through FAR pointers.
  249.  
  250.     The following methods will be needed:
  251.     alloc_small:    allocate an object of given size; use for any random
  252.             data that's not an image array.
  253.     free_small:    release same.
  254.     alloc_medium:    like alloc_small, but returns a FAR pointer.  Use for
  255.             any object bigger than a couple kilobytes.
  256.     free_medium:    release same.
  257.     alloc_small_sarray: construct an all-in-memory image sample array.
  258.     free_small_sarray:  release same.
  259.     alloc_small_barray,
  260.     free_small_barray:  ditto for block (coefficient) arrays.
  261.     request_big_sarray:  request a virtual image sample array.  The size
  262.                  of the in-memory buffer will be determined by the
  263.                  memory manager, but it will always be a multiple
  264.                  of the passed-in MCU height.
  265.     request_big_barray:  ditto for block (coefficient) arrays.
  266.     alloc_big_arrays:  instantiate all the big arrays previously requested.
  267.                This call will also pass some info about future
  268.                memory demands, so that the memory manager can
  269.                figure out how much space to leave unallocated.
  270.     access_big_sarray: obtain access to a specified portion of a virtual
  271.                image sample array.
  272.     free_big_sarray:   release a virtual sample array.
  273.     access_big_barray,
  274.     free_big_barray:   ditto for block (coefficient) arrays.
  275.     free_all:       release any remaining storage.  This is called
  276.                before normal or error termination; the main reason
  277.                why it must exist is to ensure that any temporary
  278.                files will be deleted upon error termination.
  279.  
  280.     alloc_big_arrays will be called by the pipeline controller, which does
  281.     most of the memory allocation anyway.  The only reason for having separate
  282.     request calls is to allow some of the other modules to get big arrays.
  283.     The pipeline controller is required to give an upper bound on total future
  284.     small-array requests, so that this space can be discounted.  (A fairly
  285.     conservative estimate will be adequate.)  Future small-object requests
  286.     aren't counted; the memory manager has to use a slop factor for those.
  287.     10K or so seems to be sufficient.  (In an 80x86, small objects aren't an
  288.     issue anyway, since they don't compete for far-heap space.  "Medium"-size
  289.     objects will have to be counted separately.)
  290.  
  291.     The distinction between sample and coefficient array routines is annoying,
  292.     but it has to be maintained for machines in which "char *" is represented
  293.     differently from "int *".  On byte-addressable machines some of these
  294.     methods could perhaps point to the same code.
  295.  
  296.     The array routines will operate on only 2-D arrays (one component at a
  297.     time), since different components may require different-size arrays.
  298.  
  299.     (This object hides the knowledge of whether virtual memory is available,
  300.     as well as the actual interface to OS and library support routines.)
  301.  
  302. Note that any given implementation will presumably contain only one
  303. instantiation of input file header reading, overall control, user interface,
  304. and memory management.  Thus these could be called as simple subroutines,
  305. without bothering with an object indirection.  This is essential for overall
  306. control (which has to initialize the object structure); for consistency we
  307. will impose objectness on the other three.
  308.  
  309.  
  310. *** Decompression object structure ***
  311.  
  312. I propose the following set of objects for decompression.  The general
  313. comments at the top of the compression object section also apply here.
  314.  
  315. 1. JPEG file scanning.  This will provide these methods:
  316.     read_file_header: read the file header, determine which variant
  317.               JPEG format is in use, read everything through SOF.
  318.     read_scan_header: read scan header (up through SOS).  This is called
  319.               after read_file_header and again after each scan;
  320.               it returns TRUE if it finds SOS, FALSE if EOI.
  321.     read_jpeg_data: fetch data for entropy decoder.
  322.     resync_to_restart: try to recover from bogus data (see below).
  323.     read_scan_trailer: finish up after one scan, prepare for another call
  324.                of read_scan_header (may be a no-op).
  325.     read_file_trailer: finish up at end of file (probably a no-op).
  326.    The entropy decoder must deal with restart markers, but all other JPEG
  327.    marker types will be handled in this object; useful data from the markers
  328.    will be extracted into data structures available to subsequent routines.
  329.    Note that on exit from read_file_header, only the SOF-marker data should be
  330.    assumed valid (image size, component IDs, sampling factors); other data
  331.    such as Huffman tables may not appear until after the SOF.  The overall
  332.    image size and colorspace can be determined after read_file_header, but not
  333.    whether or how the data is interleaved.  (This hides which variant JPEG
  334.    file format is being read.  In particular, for JPEG-in-TIFF the read_header
  335.    routines might not be scanning standard JPEG markers at all; they could
  336.    extract the data from TIFF tags.  The user interface will already have
  337.    opened the input file and possibly read part of the header before
  338.    read_file_header is called.)
  339.  
  340.    When reading a file with a nonzero restart interval, the entropy decoder
  341.    expects to see a correct sequence of restart markers.  In some cases, these
  342.    markers may be synthesized by the file-format module (a TIFF reader might
  343.    do so, for example, using tile boundary pointers to determine where the
  344.    restart intervals fall).  If the incoming data is corrupted, the entropy
  345.    decoder will read as far as the next JPEG marker, which may or may not be
  346.    the expected next restart marker.  If it isn't, resync_to_restart is called
  347.    to try to locate a good place to resume reading.  We make this heuristic a
  348.    file-format-dependent operation since some file formats may have special
  349.    info that's not available to the entropy decoder (again, TIFF is an
  350.    example).  Note that resync_to_restart is NOT called at the end of a scan;
  351.    it is read_scan_trailer's responsibility to resync there.
  352.  
  353.    NOTE: for JFIF/raw-JPEG file format, the read_jpeg_data routine is actually
  354.    supplied by the user interface; the jrdjfif module uses read_jpeg_data
  355.    internally to scan the input stream.  This makes it possible for the user
  356.    interface module to single-handedly implement special applications like
  357.    reading from a non-stdio source.  For JPEG-in-TIFF format, the need for
  358.    random access will make it impossible for this to work; hence the TIFF
  359.    header module will override the UI-supplied read_jpeg_data routine.
  360.    Non-stdio input from a TIFF file will require extensive surgery to the TIFF
  361.    header module, if indeed it is practical at all.
  362.  
  363. 2. Entropy (Huffman or arithmetic) decoding of the coefficient sequence.
  364.     entropy_decode_init: prepare for one scan.
  365.     entropy_decode: decodes and returns an MCU's worth of quantized
  366.             coefficients per call.
  367.     entropy_decode_term: finish up after a scan (may be a no-op).
  368.    This will read raw data by calling the read_jpeg_data method (I don't see
  369.    any reason to provide a further level of indirection).
  370.    (This hides which entropy encoding method is in use.)
  371.  
  372. 3. Quantization descaling and zigzag reordering of the elements in each 8x8
  373.    block.  This will be folded into entropy_decode for efficiency reasons:
  374.    many of the coefficients are zeroes, and this can be exploited most easily
  375.    within entropy_decode since the encoding explicitly skips zeroes.
  376.  
  377. 4. MCU disassembly (conversion of a possibly interleaved sequence of 8x8
  378.    blocks back to separate components in pixel map order).
  379.     disassemble_init: initialize.  This will be called once per scan.
  380.     disassemble_MCU:  Given an MCU's worth of dequantized blocks,
  381.               distribute them into the proper locations in a
  382.               coefficient image array.
  383.     disassemble_term: clean up at the end of a scan.
  384.    Probably this should be called once per MCU row and should call the
  385.    entropy decoder repeatedly to obtain the row's data.  The output is
  386.    always a multiple of an MCU's dimensions.
  387.    (An object on the grounds that multiple instantiations might be useful.)
  388.  
  389. 5. Cross-block smoothing per JPEG section K.8 or a similar algorithm.
  390.     smooth_coefficients: Given three block rows' worth of a single
  391.                  component, emit a smoothed equivalent of the
  392.                  middle row.  The "above" and "below" pointers
  393.                  may be NULL if at top/bottom of image.
  394.    The pipeline controller will do the necessary buffering to provide the
  395.    above/below context.  Smoothing will be optional since a good deal of
  396.    extra memory is needed to buffer the additional block rows.
  397.    (This object hides the details of the smoothing algorithm.)
  398.  
  399. 6. Inverse DCT transformation of each 8x8 block.
  400.     reverse_DCT: given an MCU row's worth of blocks, perform inverse
  401.              DCT on each block and output the results into an array
  402.              of samples.
  403.    We put this method into the jdmcu module for symmetry with the division of
  404.    labor in compression.  Note that the actual IDCT code is a separate source
  405.    file.
  406.  
  407. 7. Upsampling and smoothing: this will be applied to one component at a
  408.    time.  Note that cross-pixel smoothing, which was a separate step in the
  409.    prototype code, will now be performed simultaneously with expansion.
  410.     upsample_init: initialize (precalculate convolution factors, for
  411.                example).  This will be called once per scan.
  412.     upsample: Given a sample array, enlarge it by specified sampling
  413.           factors.
  414.     upsample_term: clean up at the end of a scan.
  415.    If the current component has vertical sampling factor Vk and the largest
  416.    sampling factor is Vmax, then the input is always Vk sample rows (whose
  417.    width is a multiple of Hk) and the output is always Vmax sample rows.
  418.    Vk additional rows above and below the nominal input rows are also passed
  419.    for use in cross-pixel smoothing.  At the top and bottom of the image,
  420.    these extra rows are copies of the first or last actual input row.
  421.    (This hides whether and how cross-pixel smoothing occurs.)
  422.  
  423. 8. Cropping to the original pixel dimensions (throwing away duplicated
  424.    pixels at the edges).  This won't be a separate object, just an
  425.    adjustment of the nominal image size in the pipeline controller.
  426.  
  427. 9. Color space reconversion and gamma adjustment.
  428.     colorout_init: initialization.  This will be passed the component
  429.                data from read_file_header, and will determine the
  430.                number of output components.
  431.     color_convert: convert a specified number of pixel rows.  Input and
  432.                output are image arrays of same size but possibly
  433.                different numbers of components.
  434.     colorout_term: cleanup (probably a no-op except for memory dealloc).
  435.    In practice will usually be given an MCU row's worth of pixel rows, except
  436.    at the bottom where a smaller number of rows may be left over.  Note that
  437.    this object works on all the components at once.
  438.    When quantizing colors, color_convert may be applied to the colormap
  439.    instead of actual pixel data.  color_convert is called by the color
  440.    quantizer in this case; the pipeline controller calls color_convert
  441.    directly only when not quantizing.
  442.    (Hides all knowledge of color space semantics and conversion.  Remaining
  443.    modules only need to know the number of JPEG and output components.)
  444.  
  445. 10. Color quantization (used only if a colormapped output format is requested).
  446.     We use two different strategies depending on whether one-pass (on-the-fly)
  447.     or two-pass quantization is requested.  Note that the two-pass interface
  448.     is actually designed to let the quantizer make any number of passes.
  449.     color_quant_init: initialization, allocate working memory.  In 1-pass
  450.               quantization, should call put_color_map.
  451.     color_quantize: convert a specified number of pixel rows.  Input
  452.             and output are image arrays of same size, but input
  453.             is N coefficients and output is only one.  (Used only
  454.             in 1-pass quantization.)
  455.     color_quant_prescan: prescan a specified number of pixel rows in
  456.                  2-pass quantization.
  457.     color_quant_doit: perform multi-pass color quantization.  Input is a
  458.               "big" sample image, output is via put_color_map and
  459.               put_pixel_rows.  (Used only in 2-pass quantization.)
  460.     color_quant_term: cleanup (probably a no-op except for memory dealloc).
  461.     The input to the color quantizer is always in the unconverted colorspace;
  462.     its output colormap must be in the converted colorspace.  The quantizer
  463.     has the choice of which space to work in internally.  It must call
  464.     color_convert either on its input data or on the colormap it sends to the
  465.     output module.
  466.     For one-pass quantization the image is simply processed by color_quantize,
  467.     a few rows at a time.  For two-pass quantization, the pipeline controller
  468.     accumulates the output of steps 1-8 into a "big" sample image.  The
  469.     color_quant_prescan method is invoked during this process so that the
  470.     quantizer can accumulate statistics.  (If the input file has multiple
  471.     scans, the prescan may be done during the final scan or as a separate
  472.     pass.)  At the end of the image, color_quant_doit is called; it must
  473.     create and output a colormap, then rescan the "big" image and pass mapped
  474.     data to the output module.  Additional scans of the image could be made
  475.     before the output pass is done (in fact, prescan could be a no-op).
  476.     As with entropy parameter optimization, the pipeline controller actually
  477.     passes an iterator function rather than direct access to the big image.
  478.     (Hides color quantization algorithm.)
  479.  
  480. 11. Writing of the desired image format.
  481.     output_init: produce the file header given data from read_file_header.
  482.     put_color_map: output colormap, if any (called by color quantizer).
  483.                If used, must be called before any pixel data is output.
  484.     put_pixel_rows: output image data in desired format.
  485.     output_term: finish up at the end.
  486.     The actual timing of I/O may differ from that suggested by the routine
  487.     names; for instance, writing of the file header may be delayed until
  488.     put_color_map time if the actual number of colors is needed in the header.
  489.     Also, the colormap is available to put_pixel_rows and output_term as well
  490.     as put_color_map.
  491.     Note that whether colormapping is needed will be determined by the user
  492.     interface object prior to method selection.  In implementations that
  493.     support multiple output formats, the actual output format will also be
  494.     determined by the user interface.
  495.     (Hides format of output image and mechanism used to write it.  Note that
  496.     several other objects know the color model used by the output format.
  497.     The actual mechanism for writing the file is private to this object and
  498.     the user interface.)
  499.  
  500. 12. Pipeline control.  This object will provide the "main loop" that invokes
  501.     all the pipeline objects.  Note that we will need several different main
  502.     loops depending on the situation (interleaved input or not, whether to
  503.     apply cross-block smoothing or not, etc).  We may want to divvy up the
  504.     pipeline controllers into two levels, one that retains control over the
  505.     whole file and one that is invoked per scan.
  506.     This object will do most of the memory allocation, since it will provide
  507.     the working buffers that are the inputs and outputs of the pipeline steps.
  508.     (An object mostly to support multiple instantiations; however, overall
  509.     memory management and sequencing of operations are known only here.)
  510.  
  511. 13. Overall control.  This module will provide at least two routines:
  512.     jpeg_decompress: the main entry point to the decompressor.
  513.     per_scan_method_selection: called by pipeline controllers for
  514.                    secondary method selection passes.
  515.     jpeg_decompress is invoked from the user interface after the UI has
  516.     selected the input and output files and obtained values for all
  517.     user-specified options (e.g., output file format, whether to do block
  518.     smoothing).  jpeg_decompress calls read_file_header, performs basic
  519.     initialization (e.g., calculating the size of MCUs), does the "global"
  520.     method selection pass, and finally calls the selected pipeline control
  521.     object.  (Per-scan method selections will be invoked by the pipeline
  522.     controller.)
  523.     Note that jpeg_decompress can't be a method since it is invoked prior to
  524.     method selection.
  525.  
  526. 14. User interface; this is the architecture's term for "the rest of the
  527.     application program", i.e., that which invokes the JPEG decompressor.
  528.     The UI is expected to supply input and output files and values for all
  529.     operational parameters.  The UI must also supply error handling routines.
  530.     (This module hides the user interface provided --- command line,
  531.     interactive, etc.  Except for error handling, the UI calls the portable
  532.     JPEG code, not the other way around.)
  533.  
  534. 15. A memory management object.  This will be identical to the memory
  535.     management for compression (and will be the same code, in combined
  536.     programs).  See above for details.
  537.  
  538.  
  539. *** Initial method selection ***
  540.  
  541. The main ugliness in this design is the portion of startup that will select
  542. which of several instantiations should be used for each of the objects.  (For
  543. example, Huffman or arithmetic for entropy encoding; one of several pipeline
  544. controllers depending on interleaving, the size of the image, etc.)  It's not
  545. really desirable to have a single chunk of code that knows the names of all
  546. the possible instantiations and the conditions under which to select each one.
  547.  
  548. The best approach seems to be to provide a selector function for each object
  549. (group of related method calls).  This function knows about each possible
  550. instantiation of its object and how to choose the right one; but it doesn't
  551. know about any other objects.
  552.  
  553. Note that there will be several rounds of method selection: at initial startup,
  554. after overall compression parameters are determined (after the file header is
  555. read, if decompressing), and one in preparation for each scan (this occurs
  556. more than once if the file is noninterleaved).  Each object method will need
  557. to be clearly identified as to which round sets it up.
  558.  
  559.  
  560. *** Implications of DNL marker ***
  561.  
  562. Some JPEG files may use a DNL marker to postpone definition of the image
  563. height (this would be useful for a fax-like scanner's output, for instance).
  564. In these files the SOF marker claims the image height is 0, and you only
  565. find out the true image height at the end of the first scan.
  566.  
  567. We could handle these files as follows:
  568. 1. Upon seeing zero image height, replace it by 65535 (the maximum allowed).
  569. 2. When the DNL is found, update the image height in the global image
  570.    descriptor.
  571. This implies that pipeline control objects must avoid making copies of the
  572. image height, and must re-test for termination after each MCU row.  This is
  573. no big deal.
  574.  
  575. In situations where image-size data structures are allocated, this approach
  576. will result in very inefficient use of virtual memory or
  577. much-larger-than-necessary temporary files.  This seems acceptable for
  578. something that probably won't be a mainstream usage.  People might have to
  579. forgo use of memory-hogging options (such as two-pass color quantization or
  580. noninterleaved JPEG files) if they want efficient conversion of such files.
  581. (One could improve efficiency by demanding a user-supplied upper bound for the
  582. height, less than 65536; in most cases it could be much less.)
  583.  
  584. Alternately, we could insist that DNL-using files be preprocessed by a
  585. separate program that reads ahead to the DNL, then goes back and fixes the SOF
  586. marker.  This is a much simpler solution and is probably far more efficient.
  587. Even if one wants piped input, buffering the first scan of the JPEG file
  588. needs a lot smaller temp file than is implied by the maximum-height method.
  589. For this approach we'd simply treat DNL as a no-op in the decompressor (at
  590. most, check that it matches the SOF image height).
  591.  
  592. We will not worry about making the compressor capable of outputting DNL.
  593. Something similar to the first scheme above could be applied if anyone ever
  594. wants to make that work.
  595.  
  596.  
  597. *** Memory manager internal structure ***
  598.  
  599. The memory manager contains the most potential for system dependencies.
  600. To isolate system dependencies as much as possible, we have broken the
  601. memory manager into two parts.  There is a reasonably system-independent
  602. "front end" (jmemmgr.c) and a "back end" that contains only the code
  603. likely to change across systems.  All of the memory management methods
  604. outlined above are implemented by the front end.  The back end provides
  605. the following routines for use by the front end (none of these routines
  606. are known to the rest of the JPEG code):
  607.  
  608. jmem_init, jmem_term    system-dependent initialization/shutdown
  609.  
  610. jget_small, jfree_small    interface to malloc and free library routines
  611.  
  612. jget_large, jfree_large    interface to FAR malloc/free in MS-DOS machines;
  613.             otherwise same as jget_small/jfree_small
  614.  
  615. jmem_available        estimate available memory
  616.  
  617. jopen_backing_store    create a backing-store object
  618.  
  619. read_backing_store,    manipulate a backing store object
  620. write_backing_store,
  621. close_backing_store
  622.  
  623. On some systems there will be more than one type of backing-store object
  624. (specifically, in MS-DOS a backing store file might be an area of extended
  625. memory as well as a disk file).  jopen_backing_store is responsible for
  626. choosing how to implement a given object.  The read/write/close routines
  627. are method pointers in the structure that describes a given object; this
  628. lets them be different for different object types.
  629.  
  630. It may be necessary to ensure that backing store objects are explicitly
  631. released upon abnormal program termination.  (For example, MS-DOS won't free
  632. extended memory by itself.)  To support this, we will expect the main program
  633. or surrounding application to arrange to call the free_all method upon
  634. abnormal termination; this may require a SIGINT signal handler, for instance.
  635. (We don't want to have the system-dependent module install its own signal
  636. handler, because that would pre-empt the surrounding application's ability
  637. to control signal handling.)
  638.  
  639.  
  640. *** Notes for MS-DOS implementors ***
  641.  
  642. The standalone cjpeg and djpeg applications can be compiled in "small" memory
  643. model, at least at the moment; as the code grows we may be forced to switch to
  644. "medium" model.  (Small = both code and data pointers are near by default;
  645. medium = far code pointers, near data pointers.)  Medium model will slow down
  646. calls through method pointers, but I don't think this will amount to any
  647. significant speed penalty.
  648.  
  649. When integrating the JPEG code into a larger application, it's a good idea to
  650. stay with a small-data-space model if possible.  An 8K stack is much more than
  651. sufficient for the JPEG code, and its static data requirements are less than
  652. 1K.  When executed, it will typically malloc about 10K-20K worth of near heap
  653. space (and lots of far heap, but that doesn't count in this calculation).
  654. This figure will vary depending on image size and other factors, but figuring
  655. 30K should be more than sufficient.  Thus you have about 25K available for
  656. other modules' static data and near heap requirements before you need to go to
  657. a larger memory model.  The C library's static data will account for several K
  658. of this, but that still leaves a good deal for your needs.  (If you are tight
  659. on space, you could reduce JPEG_BUF_SIZE from 4K to 1K to save 3K of near heap
  660. space.)
  661.  
  662. As the code is improved, we will endeavor to hold the near data requirements
  663. to the range given above.  This does imply that certain data structures will
  664. be allocated as FAR although they would fit in near space if we assumed the
  665. JPEG code is stand-alone.  (The LZW tables in jrdgif/jwrgif are examples.)
  666. To make an optimal implementation, you might want to move these structures
  667. back to near heap if you know there is sufficient space.
  668.  
  669. FAR data space may also be a tight resource when you are dealing with large
  670. images.  The most memory-intensive case is decompression with two-pass color
  671. quantization.  This requires a 128Kb color histogram plus strip buffers
  672. amounting to about 150 bytes per column for typical sampling ratios (eg, about
  673. 96000 bytes for a 640-pixel-wide image).  You may not be able to process wide
  674. images if you have large data structures of your own.
  675.  
  676.  
  677. *** Potential optimizations ***
  678.  
  679. For colormapped input formats it might be worthwhile to merge the input file
  680. reading and the colorspace conversion steps; in other words, do the colorspace
  681. conversion by hacking up the colormap before inputting the image body, rather
  682. than doing the conversion on each pixel independently.  Not clear if this is
  683. worth the uglification involved.  In the above design for the compressor, only
  684. the colorspace conversion step ever sees the output of get_input_row, so this
  685. sort of thing could be done via private agreement between those two modules.
  686.  
  687. Level shift from 0..255 to -128..127 may be done either during colorspace
  688. conversion, or at the moment of converting an 8x8 sample block into the format
  689. used by the DCT step (which will be signed short or long int).  This could be
  690. selectable by a compile-time flag, so that the intermediate steps can work on
  691. either signed or unsigned chars as samples, whichever is most easily handled
  692. by the platform.  However, making sure that rounding is done right will be a
  693. lot easier if we can assume positive values.  At the moment I think that
  694. benefit is worth the overhead of "& 0xFF" when reading out sample values on
  695. signed-char-only machines.
  696.