home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1994 March / Source_Code_CD-ROM_Walnut_Creek_March_1994.iso / compsrcs / misc / volume34 / jpeg / part03 < prev    next >
Encoding:
Text File  |  1992-12-16  |  58.1 KB  |  1,180 lines

  1. Newsgroups: comp.sources.misc
  2. From: jpeg-info@uunet.uu.net (Independent JPEG Group)
  3. Subject:  v34i057:  jpeg - JPEG image compression, Part03/18
  4. Message-ID: <1992Dec17.041609.23233@sparky.imd.sterling.com>
  5. X-Md4-Signature: 9f8d2e17bad75b14d03d15ad50ee9f88
  6. Date: Thu, 17 Dec 1992 04:16:09 GMT
  7. Approved: kent@sparky.imd.sterling.com
  8.  
  9. Submitted-by: jpeg-info@uunet.uu.net (Independent JPEG Group)
  10. Posting-number: Volume 34, Issue 57
  11. Archive-name: jpeg/part03
  12. Environment: UNIX, VMS, MS-DOS, Mac, Amiga, Atari, Cray
  13. Supersedes: jpeg: Volume 29, Issue 1-18
  14.  
  15. #! /bin/sh
  16. # This is a shell archive.  Remove anything before this line, then feed it
  17. # into a shell via "sh file" or similar.  To overwrite existing files,
  18. # type "sh file -c".
  19. # Contents:  architecture.B jcdeflts.c jversion.h
  20. # Wrapped by kent@sparky on Wed Dec 16 20:52:25 1992
  21. PATH=/bin:/usr/bin:/usr/ucb:/usr/local/bin:/usr/lbin ; export PATH
  22. echo If this archive is complete, you will see the following message:
  23. echo '          "shar: End of archive 3 (of 18)."'
  24. if test -f 'architecture.B' -a "${1}" != "-c" ; then 
  25.   echo shar: Will not clobber existing file \"'architecture.B'\"
  26. else
  27.   echo shar: Extracting \"'architecture.B'\" \(40461 characters\)
  28.   sed "s/^X//" >'architecture.B' <<'END_OF_FILE'
  29. X
  30. XFor similar reasons, one MCU is also the best chunk size for the frequency
  31. Xcoefficient quantization and dequantization steps.
  32. X
  33. XFor downsampling and upsampling, the best chunk size is to have each call
  34. Xtransform Vk sample rows from or to Vmax sample rows (Vk = this component's
  35. Xvertical sampling factor, Vmax = largest vertical sampling factor).  There are
  36. Xeight such chunks in each MCU row.  Using a whole MCU row as the chunk size
  37. Xwould reduce function call overhead a fraction, but would imply more buffering
  38. Xto provide context for cross-pixel smoothing.
  39. X
  40. X
  41. X*** Compression object structure ***
  42. X
  43. XI propose the following set of objects for the compressor.  Here an "object"
  44. Xis the common interface for one or more modules having comparable functions.
  45. X
  46. XMost of these objects can be justified as information-hiding modules.
  47. XI've indicated what information is private to each object/module.
  48. X
  49. XNote that in all cases, the caller of a method is expected to have allocated
  50. Xany storage needed for it to return its result.  (Typically this storage can
  51. Xbe re-used in successive calls, so malloc'ing and free'ing once per call is
  52. Xnot reasonable.)  Also, much of the context required (compression parameters,
  53. Ximage size, etc) will be passed around in large common data structures, which
  54. Xaren't described here; see the header files.  Notice that any object that
  55. Xmight need to allocate working storage receives an "init" and a "term" call;
  56. X"term" should be careful to free all allocated storage so that the JPEG system
  57. Xcan be used multiple times during a program run.  (For the same reason,
  58. Xdepending on static initialization of variables is a no-no.  The only
  59. Xexception to the free-all-allocated-storage rule is that storage allocated for
  60. Xthe entire processing of an image need not be explicitly freed, since the
  61. Xmemory manager's free_all cleanup will free it.)
  62. X
  63. X1. Input file conversion to standardized form.  This provides these methods:
  64. X    input_init: read the file header, report image size & component count.
  65. X    get_input_row: read one pixel row, return it in our standard format.
  66. X    input_term: finish up at the end.
  67. X   In implementations that support multiple input formats, input_init could
  68. X   set up an appropriate get_input_row method depending on the format it
  69. X   finds.  Note that in most applications, the selection and opening of the
  70. X   input file will be under the control of the user interface module; and
  71. X   indeed the user interface may have already read the input header, so that
  72. X   all that input_init may have to do is return previously saved values.  The
  73. X   behind-the-scenes interaction between this object and the user interface is
  74. X   not specified by this architecture.
  75. X   (Hides format of input image and mechanism used to read it.  This code is
  76. X   likely to vary considerably from one implementation to another.  Note that
  77. X   the color space and number of color components of the source are not hidden;
  78. X   but they are used only by the next object.)
  79. X
  80. X2. Gamma and color space conversion.  This provides three methods:
  81. X    colorin_init: initialization.
  82. X    get_sample_rows: read, convert, and return a specified number of pixel
  83. X             rows (not more than remain in the picture).
  84. X    colorin_term: finish up at the end.
  85. X   The most efficient approach seems to be for this object to call
  86. X   get_input_row directly, rather than being passed the input data; that way,
  87. X   any intermediate storage required can be local to this object.
  88. X   (get_sample_rows might tell get_input_row to read directly into its own
  89. X   output area and then convert in place; or it may do something different.
  90. X   For example, conversion in place wouldn't work if it is changing the number
  91. X   of color components.)  The output of this step is in the standardized
  92. X   sample array format shown previously.
  93. X   (Hides all knowledge of color space semantics and conversion.  Remaining
  94. X   modules only need to know the number of JPEG components.)
  95. X
  96. X3. Edge expansion: needs only a single method.
  97. X    edge_expand: Given an NxM sample array, expand to a desired size (a
  98. X             multiple of the MCU dimensions) by duplicating the last
  99. X             row or column.  Repeat for each component.
  100. X   Expansion will occur in place, so the caller must have pre-allocated enough
  101. X   storage.  (I'm assuming that it is easier and faster to do this expansion
  102. X   than it is to worry about boundary conditions in the next two steps.
  103. X   Notice that vertical expansion will occur only once, at the bottom of the
  104. X   picture, so only horizontal expansion by a few pixels is speed-critical.)
  105. X   (This doesn't really hide any information, so maybe it could be a simple
  106. X   subroutine instead of a method.  Depends on whether we want to be able to
  107. X   use alternative, optimized methods.)
  108. X
  109. X4. Downsampling: this will be applied to one component at a time.
  110. X    downsample_init: initialize (precalculate convolution factors, for
  111. X             example).  This will be called once per scan.
  112. X    downsample: Given a sample array, reduce it to a smaller number of
  113. X            samples using specified sampling factors.
  114. X    downsample_term: clean up at the end of a scan.
  115. X   If the current component has vertical sampling factor Vk and the largest
  116. X   sampling factor is Vmax, then the input is always Vmax sample rows (whose
  117. X   width is a multiple of Hmax) and the output is always Vk sample rows.
  118. X   Vmax additional rows above and below the nominal input rows are also passed
  119. X   for use by partial-pixel-averaging sampling methods.  (Is this necessary?)
  120. X   At the top and bottom of the image, these extra rows are copies of the
  121. X   first or last actual input row.
  122. X   (This hides whether and how cross-pixel averaging occurs.)
  123. X
  124. X5. MCU extraction (creation of a single sequence of 8x8 sample blocks).
  125. X    extract_init: initialize as needed.  This will be called once per scan.
  126. X    extract_MCUs: convert a sample array to a sequence of MCUs.
  127. X    extract_term: clean up at the end of a scan.
  128. X   Given one or more MCU rows worth of image data, extract sample blocks in the
  129. X   appropriate order; pass these off to subsequent steps one MCU at a time.
  130. X   The input must be a multiple of the MCU dimensions.  It will probably be
  131. X   most convenient for the DCT transform, frequency quantization, and zigzag
  132. X   reordering of each block to be done as simple subroutines of this step.
  133. X   Once a transformed MCU has been completed, it'll be passed off to a
  134. X   method call, which will be passed as a parameter to extract_MCUs.
  135. X   That routine might either encode and output the MCU immediately, or buffer
  136. X   it up for later output if we want to do global optimization of the entropy
  137. X   encoding coefficients.  Note: when outputting a noninterleaved file this
  138. X   object will be called separately for each component.  Direct output could
  139. X   be done for the first component, but the others would have to be buffered.
  140. X   (Again, an object mainly on the grounds that multiple instantiations might
  141. X   be useful.)
  142. X
  143. X6. DCT transformation of each 8x8 block.  This probably doesn't have to be a
  144. X   full-fledged method, but just a plain subroutine that will be called by MCU
  145. X   extraction.  One 8x8 block will be processed per call.
  146. X
  147. X7. Quantization scaling and zigzag reordering of the elements in each 8x8
  148. X   block.  (This can probably be a plain subroutine called once per block by
  149. X   MCU extraction; hard to see a need for multiple instantiations here.)
  150. X
  151. X8. Entropy encoding (Huffman or arithmetic).
  152. X    entropy_encode_init: prepare for one scan.
  153. X    entropy_encode: accepts an MCU's worth of quantized coefficients,
  154. X            encodes and outputs them.
  155. X    entropy_encode_term: finish up at end of a scan (dump any buffered
  156. X                 bytes, for example).
  157. X   The data output by this module will be sent to the entropy_output method
  158. X   provided by the pipeline controller.  (It will probably be worth using
  159. X   buffering to pass multiple bytes per call of the output method.)  The
  160. X   output method could be just write_jpeg_data, but might also be a dummy
  161. X   routine that counts output bytes (for use during cut-and-try coefficient
  162. X   optimization).
  163. X   (This hides which entropy encoding method is in use.)
  164. X
  165. X9. JPEG file header construction.  This will provide these methods:
  166. X    write_file_header: output the initial header.
  167. X    write_scan_header: output scan header (called once per component
  168. X               if noninterleaved mode).
  169. X    write_jpeg_data: the actual data output method for the preceding step.
  170. X    write_scan_trailer: finish up after one scan.
  171. X    write_file_trailer: finish up at end of file.
  172. X   Note that compressed data is passed to the write_jpeg_data method, in case
  173. X   a simple fwrite isn't appropriate for some reason.
  174. X   (This hides which variant JPEG file format is being written.  Also, the
  175. X   actual mechanism for writing the file is private to this object and the
  176. X   user interface.)
  177. X
  178. X10. Pipeline control.  This object will provide the "main loop" that invokes
  179. X    all the pipeline objects.  Note that we will need several different main
  180. X    loops depending on the situation (interleaved output or not, global
  181. X    optimization of encoding parameters or not, etc).  This object will do
  182. X    most of the memory allocation, since it will provide the working buffers
  183. X    that are the inputs and outputs of the pipeline steps.
  184. X    (An object mostly to support multiple instantiations; however, overall
  185. X    memory management and sequencing of operations are known only here.)
  186. X
  187. X11. Overall control.  This module will provide at least two routines:
  188. X    jpeg_compress: the main entry point to the compressor.
  189. X    per_scan_method_selection: called by pipeline controllers for
  190. X                   secondary method selection passes.
  191. X    jpeg_compress is invoked from the user interface after the UI has selected
  192. X    the input and output files and obtained values for all compression
  193. X    parameters that aren't dynamically determined.  jpeg_compress performs
  194. X    basic initialization (e.g., calculating the size of MCUs), does the
  195. X    "global" method selection pass, and finally calls the selected pipeline
  196. X    control object.  (Per-scan method selections will be invoked by the
  197. X    pipeline controller.)
  198. X    Note that jpeg_compress can't be a method since it is invoked prior to
  199. X    method selection.
  200. X
  201. X12. User interface; this is the architecture's term for "the rest of the
  202. X    application program", i.e., that which invokes the JPEG compressor.  In a
  203. X    standalone JPEG compression program the UI need be little more than a C
  204. X    main() routine and argument parsing code; but we can expect that the JPEG
  205. X    compressor may be incorporated into complex graphics applications, wherein
  206. X    the UI is much more complex.  Much of the UI will need to be written
  207. X    afresh for each non-Unix-like platform the compressor is ported to.
  208. X    The UI is expected to supply input and output files and values for all
  209. X    non-automatically-chosen compression parameters.  (Hence defaults are
  210. X    determined by the UI; we should provide helpful routines to fill in
  211. X    the recommended defaults.)  The UI must also supply error handling
  212. X    routines and some mechanism for trace messages.
  213. X    (This module hides the user interface provided --- command line,
  214. X    interactive, etc.  Except for error/message handling, the UI calls the
  215. X    portable JPEG code, not the other way around.)
  216. X
  217. X13. (Optional) Compression parameter selection control.
  218. X    entropy_optimize: given an array of MCUs ready to be fed to entropy
  219. X              encoding, find optimal encoding parameters.
  220. X    The actual optimization algorithm ought to be separated out as an object,
  221. X    even though a special pipeline control method will be needed.  (The
  222. X    pipeline controller only has to understand that the output of extract_MCUs
  223. X    must be built up as a virtual array rather than fed directly to entropy
  224. X    encoding and output.  This pipeline behavior may also be useful for future
  225. X    implementation of hierarchical modes, etc.)
  226. X    To minimize the amount of control logic in the optimization module, the
  227. X    pipeline control doesn't actually hand over big-array pointers, but rather
  228. X    an "iterator": a function which knows how to scan the stored image.
  229. X    (This hides the details of the parameter optimization algorithm.)
  230. X
  231. X    The present design doesn't allow for multiple passes at earlier points
  232. X    in the pipeline, but allowing that would only require providing some
  233. X    new pipeline control methods; nothing else need change.
  234. X
  235. X14. A memory management object.  This will provide methods to allocate "small"
  236. X    things and "big" things.  Small things have to fit in memory and you get
  237. X    back direct pointers (this could be handled by direct calls to malloc, but
  238. X    it's cleaner not to assume malloc is the right routine).  "Big" things
  239. X    mean buffered images for multiple passes, noninterleaved output, etc.
  240. X    In this case the memory management object will give you room for a few MCU
  241. X    rows and you have to ask for access to the next few; dumping and reloading
  242. X    in a temporary file will go on behind the scenes.  (All big objects are
  243. X    image arrays containing either samples or coefficients, and will be
  244. X    scanned top-to-bottom some number of times, so we can apply this access
  245. X    model easily.)  On a platform with virtual memory, the memory manager can
  246. X    treat small and big things alike: just malloc up enough virtual memory for
  247. X    the whole image, and let the operating system worry about swapping the
  248. X    image to disk.
  249. X
  250. X    Most of the actual calls on the memory manager will be made from pipeline
  251. X    control objects; changing any data item from "small" to "big" status would
  252. X    require a new pipeline control object, since it will contain the logic to
  253. X    ask for a new chunk of a big thing.  Thus, one way in which pipeline
  254. X    controllers will vary is in which structures they treat as big.
  255. X
  256. X    The memory manager will need to be told roughly how much space is going to
  257. X    be requested overall, so that it can figure out how big a buffer is safe
  258. X    to allocate for a "big" object.  (If it happens that you are dealing with
  259. X    a small image, you'd like to decide to keep it all in memory!)  The most
  260. X    flexible way of doing this is to divide allocation of "big" objects into
  261. X    two steps.  First, there will be one or more "request" calls that indicate
  262. X    the desired object sizes; then an "instantiate" call causes the memory
  263. X    manager to actually construct the objects.  The instantiation must occur
  264. X    before the contents of any big object can be accessed.
  265. X
  266. X    For 80x86 CPUs, we would like the code to be compilable under small or
  267. X    medium model, meaning that pointers are 16 bits unless explicitly declared
  268. X    FAR.  Hence space allocated by the "small" allocator must fit into the
  269. X    64Kb default data segment, along with stack space and global/static data.
  270. X    For normal JPEG operations we seem to need only about 32Kb of such space,
  271. X    so we are within the target (and have a reasonable slop for the needs of
  272. X    a surrounding application program).  However, some color quantization
  273. X    algorithms need 64Kb or more of all-in-memory space in order to create
  274. X    color histograms.  For this purpose, we will also support "medium" size
  275. X    things.  These are semantically the same as "small" things but are
  276. X    referenced through FAR pointers.
  277. X
  278. X    The following methods will be needed:
  279. X    alloc_small:    allocate an object of given size; use for any random
  280. X            data that's not an image array.
  281. X    free_small:    release same.
  282. X    alloc_medium:    like alloc_small, but returns a FAR pointer.  Use for
  283. X            any object bigger than a couple kilobytes.
  284. X    free_medium:    release same.
  285. X    alloc_small_sarray: construct an all-in-memory image sample array.
  286. X    free_small_sarray:  release same.
  287. X    alloc_small_barray,
  288. X    free_small_barray:  ditto for block (coefficient) arrays.
  289. X    request_big_sarray:  request a virtual image sample array.  The size
  290. X                 of the in-memory buffer will be determined by the
  291. X                 memory manager, but it will always be a multiple
  292. X                 of the passed-in MCU height.
  293. X    request_big_barray:  ditto for block (coefficient) arrays.
  294. X    alloc_big_arrays:  instantiate all the big arrays previously requested.
  295. X               This call will also pass some info about future
  296. X               memory demands, so that the memory manager can
  297. X               figure out how much space to leave unallocated.
  298. X    access_big_sarray: obtain access to a specified portion of a virtual
  299. X               image sample array.
  300. X    free_big_sarray:   release a virtual sample array.
  301. X    access_big_barray,
  302. X    free_big_barray:   ditto for block (coefficient) arrays.
  303. X    free_all:       release any remaining storage.  This is called
  304. X               before normal or error termination; the main reason
  305. X               why it must exist is to ensure that any temporary
  306. X               files will be deleted upon error termination.
  307. X
  308. X    alloc_big_arrays will be called by the pipeline controller, which does
  309. X    most of the memory allocation anyway.  The only reason for having separate
  310. X    request calls is to allow some of the other modules to get big arrays.
  311. X    The pipeline controller is required to give an upper bound on total future
  312. X    small-array requests, so that this space can be discounted.  (A fairly
  313. X    conservative estimate will be adequate.)  Future small-object requests
  314. X    aren't counted; the memory manager has to use a slop factor for those.
  315. X    10K or so seems to be sufficient.  (In an 80x86, small objects aren't an
  316. X    issue anyway, since they don't compete for far-heap space.  "Medium"-size
  317. X    objects will have to be counted separately.)
  318. X
  319. X    The distinction between sample and coefficient array routines is annoying,
  320. X    but it has to be maintained for machines in which "char *" is represented
  321. X    differently from "int *".  On byte-addressable machines some of these
  322. X    methods could perhaps point to the same code.
  323. X
  324. X    The array routines will operate on only 2-D arrays (one component at a
  325. X    time), since different components may require different-size arrays.
  326. X
  327. X    (This object hides the knowledge of whether virtual memory is available,
  328. X    as well as the actual interface to OS and library support routines.)
  329. X
  330. XNote that any given implementation will presumably contain only one
  331. Xinstantiation of input file header reading, overall control, user interface,
  332. Xand memory management.  Thus these could be called as simple subroutines,
  333. Xwithout bothering with an object indirection.  This is essential for overall
  334. Xcontrol (which has to initialize the object structure); for consistency we
  335. Xwill impose objectness on the other three.
  336. X
  337. X
  338. X*** Decompression object structure ***
  339. X
  340. XI propose the following set of objects for decompression.  The general
  341. Xcomments at the top of the compression object section also apply here.
  342. X
  343. X1. JPEG file scanning.  This will provide these methods:
  344. X    read_file_header: read the file header, determine which variant
  345. X              JPEG format is in use, read everything through SOF.
  346. X    read_scan_header: read scan header (up through SOS).  This is called
  347. X              after read_file_header and again after each scan;
  348. X              it returns TRUE if it finds SOS, FALSE if EOI.
  349. X    read_jpeg_data: fetch data for entropy decoder.
  350. X    resync_to_restart: try to recover from bogus data (see below).
  351. X    read_scan_trailer: finish up after one scan, prepare for another call
  352. X               of read_scan_header (may be a no-op).
  353. X    read_file_trailer: finish up at end of file (probably a no-op).
  354. X   The entropy decoder must deal with restart markers, but all other JPEG
  355. X   marker types will be handled in this object; useful data from the markers
  356. X   will be extracted into data structures available to subsequent routines.
  357. X   Note that on exit from read_file_header, only the SOF-marker data should be
  358. X   assumed valid (image size, component IDs, sampling factors); other data
  359. X   such as Huffman tables may not appear until after the SOF.  The overall
  360. X   image size and colorspace can be determined after read_file_header, but not
  361. X   whether or how the data is interleaved.  (This hides which variant JPEG
  362. X   file format is being read.  In particular, for JPEG-in-TIFF the read_header
  363. X   routines might not be scanning standard JPEG markers at all; they could
  364. X   extract the data from TIFF tags.  The user interface will already have
  365. X   opened the input file and possibly read part of the header before
  366. X   read_file_header is called.)
  367. X
  368. X   When reading a file with a nonzero restart interval, the entropy decoder
  369. X   expects to see a correct sequence of restart markers.  In some cases, these
  370. X   markers may be synthesized by the file-format module (a TIFF reader might
  371. X   do so, for example, using tile boundary pointers to determine where the
  372. X   restart intervals fall).  If the incoming data is corrupted, the entropy
  373. X   decoder will read as far as the next JPEG marker, which may or may not be
  374. X   the expected next restart marker.  If it isn't, resync_to_restart is called
  375. X   to try to locate a good place to resume reading.  We make this heuristic a
  376. X   file-format-dependent operation since some file formats may have special
  377. X   info that's not available to the entropy decoder (again, TIFF is an
  378. X   example).  Note that resync_to_restart is NOT called at the end of a scan;
  379. X   it is read_scan_trailer's responsibility to resync there.
  380. X
  381. X   NOTE: for JFIF/raw-JPEG file format, the read_jpeg_data routine is actually
  382. X   supplied by the user interface; the jrdjfif module uses read_jpeg_data
  383. X   internally to scan the input stream.  This makes it possible for the user
  384. X   interface module to single-handedly implement special applications like
  385. X   reading from a non-stdio source.  For JPEG-in-TIFF format, the need for
  386. X   random access will make it impossible for this to work; hence the TIFF
  387. X   header module will override the UI-supplied read_jpeg_data routine.
  388. X   Non-stdio input from a TIFF file will require extensive surgery to the TIFF
  389. X   header module, if indeed it is practical at all.
  390. X
  391. X2. Entropy (Huffman or arithmetic) decoding of the coefficient sequence.
  392. X    entropy_decode_init: prepare for one scan.
  393. X    entropy_decode: decodes and returns an MCU's worth of quantized
  394. X            coefficients per call.
  395. X    entropy_decode_term: finish up after a scan (may be a no-op).
  396. X   This will read raw data by calling the read_jpeg_data method (I don't see
  397. X   any reason to provide a further level of indirection).
  398. X   (This hides which entropy encoding method is in use.)
  399. X
  400. X3. Quantization descaling and zigzag reordering of the elements in each 8x8
  401. X   block.  This will be folded into entropy_decode for efficiency reasons:
  402. X   many of the coefficients are zeroes, and this can be exploited most easily
  403. X   within entropy_decode since the encoding explicitly skips zeroes.
  404. X
  405. X4. MCU disassembly (conversion of a possibly interleaved sequence of 8x8
  406. X   blocks back to separate components in pixel map order).
  407. X    disassemble_init: initialize.  This will be called once per scan.
  408. X    disassemble_MCU:  Given an MCU's worth of dequantized blocks,
  409. X              distribute them into the proper locations in a
  410. X              coefficient image array.
  411. X    disassemble_term: clean up at the end of a scan.
  412. X   Probably this should be called once per MCU row and should call the
  413. X   entropy decoder repeatedly to obtain the row's data.  The output is
  414. X   always a multiple of an MCU's dimensions.
  415. X   (An object on the grounds that multiple instantiations might be useful.)
  416. X
  417. X5. Cross-block smoothing per JPEG section K.8 or a similar algorithm.
  418. X    smooth_coefficients: Given three block rows' worth of a single
  419. X                 component, emit a smoothed equivalent of the
  420. X                 middle row.  The "above" and "below" pointers
  421. X                 may be NULL if at top/bottom of image.
  422. X   The pipeline controller will do the necessary buffering to provide the
  423. X   above/below context.  Smoothing will be optional since a good deal of
  424. X   extra memory is needed to buffer the additional block rows.
  425. X   (This object hides the details of the smoothing algorithm.)
  426. X
  427. X6. Inverse DCT transformation of each 8x8 block.
  428. X    reverse_DCT: given an MCU row's worth of blocks, perform inverse
  429. X             DCT on each block and output the results into an array
  430. X             of samples.
  431. X   We put this method into the jdmcu module for symmetry with the division of
  432. X   labor in compression.  Note that the actual IDCT code is a separate source
  433. X   file.
  434. X
  435. X7. Upsampling and smoothing: this will be applied to one component at a
  436. X   time.  Note that cross-pixel smoothing, which was a separate step in the
  437. X   prototype code, will now be performed simultaneously with expansion.
  438. X    upsample_init: initialize (precalculate convolution factors, for
  439. X               example).  This will be called once per scan.
  440. X    upsample: Given a sample array, enlarge it by specified sampling
  441. X          factors.
  442. X    upsample_term: clean up at the end of a scan.
  443. X   If the current component has vertical sampling factor Vk and the largest
  444. X   sampling factor is Vmax, then the input is always Vk sample rows (whose
  445. X   width is a multiple of Hk) and the output is always Vmax sample rows.
  446. X   Vk additional rows above and below the nominal input rows are also passed
  447. X   for use in cross-pixel smoothing.  At the top and bottom of the image,
  448. X   these extra rows are copies of the first or last actual input row.
  449. X   (This hides whether and how cross-pixel smoothing occurs.)
  450. X
  451. X8. Cropping to the original pixel dimensions (throwing away duplicated
  452. X   pixels at the edges).  This won't be a separate object, just an
  453. X   adjustment of the nominal image size in the pipeline controller.
  454. X
  455. X9. Color space reconversion and gamma adjustment.
  456. X    colorout_init: initialization.  This will be passed the component
  457. X               data from read_file_header, and will determine the
  458. X               number of output components.
  459. X    color_convert: convert a specified number of pixel rows.  Input and
  460. X               output are image arrays of same size but possibly
  461. X               different numbers of components.
  462. X    colorout_term: cleanup (probably a no-op except for memory dealloc).
  463. X   In practice will usually be given an MCU row's worth of pixel rows, except
  464. X   at the bottom where a smaller number of rows may be left over.  Note that
  465. X   this object works on all the components at once.
  466. X   When quantizing colors, color_convert may be applied to the colormap
  467. X   instead of actual pixel data.  color_convert is called by the color
  468. X   quantizer in this case; the pipeline controller calls color_convert
  469. X   directly only when not quantizing.
  470. X   (Hides all knowledge of color space semantics and conversion.  Remaining
  471. X   modules only need to know the number of JPEG and output components.)
  472. X
  473. X10. Color quantization (used only if a colormapped output format is requested).
  474. X    We use two different strategies depending on whether one-pass (on-the-fly)
  475. X    or two-pass quantization is requested.  Note that the two-pass interface
  476. X    is actually designed to let the quantizer make any number of passes.
  477. X    color_quant_init: initialization, allocate working memory.  In 1-pass
  478. X              quantization, should call put_color_map.
  479. X    color_quantize: convert a specified number of pixel rows.  Input
  480. X            and output are image arrays of same size, but input
  481. X            is N coefficients and output is only one.  (Used only
  482. X            in 1-pass quantization.)
  483. X    color_quant_prescan: prescan a specified number of pixel rows in
  484. X                 2-pass quantization.
  485. X    color_quant_doit: perform multi-pass color quantization.  Input is a
  486. X              "big" sample image, output is via put_color_map and
  487. X              put_pixel_rows.  (Used only in 2-pass quantization.)
  488. X    color_quant_term: cleanup (probably a no-op except for memory dealloc).
  489. X    The input to the color quantizer is always in the unconverted colorspace;
  490. X    its output colormap must be in the converted colorspace.  The quantizer
  491. X    has the choice of which space to work in internally.  It must call
  492. X    color_convert either on its input data or on the colormap it sends to the
  493. X    output module.
  494. X    For one-pass quantization the image is simply processed by color_quantize,
  495. X    a few rows at a time.  For two-pass quantization, the pipeline controller
  496. X    accumulates the output of steps 1-8 into a "big" sample image.  The
  497. X    color_quant_prescan method is invoked during this process so that the
  498. X    quantizer can accumulate statistics.  (If the input file has multiple
  499. X    scans, the prescan may be done during the final scan or as a separate
  500. X    pass.)  At the end of the image, color_quant_doit is called; it must
  501. X    create and output a colormap, then rescan the "big" image and pass mapped
  502. X    data to the output module.  Additional scans of the image could be made
  503. X    before the output pass is done (in fact, prescan could be a no-op).
  504. X    As with entropy parameter optimization, the pipeline controller actually
  505. X    passes an iterator function rather than direct access to the big image.
  506. X    (Hides color quantization algorithm.)
  507. X
  508. X11. Writing of the desired image format.
  509. X    output_init: produce the file header given data from read_file_header.
  510. X    put_color_map: output colormap, if any (called by color quantizer).
  511. X               If used, must be called before any pixel data is output.
  512. X    put_pixel_rows: output image data in desired format.
  513. X    output_term: finish up at the end.
  514. X    The actual timing of I/O may differ from that suggested by the routine
  515. X    names; for instance, writing of the file header may be delayed until
  516. X    put_color_map time if the actual number of colors is needed in the header.
  517. X    Also, the colormap is available to put_pixel_rows and output_term as well
  518. X    as put_color_map.
  519. X    Note that whether colormapping is needed will be determined by the user
  520. X    interface object prior to method selection.  In implementations that
  521. X    support multiple output formats, the actual output format will also be
  522. X    determined by the user interface.
  523. X    (Hides format of output image and mechanism used to write it.  Note that
  524. X    several other objects know the color model used by the output format.
  525. X    The actual mechanism for writing the file is private to this object and
  526. X    the user interface.)
  527. X
  528. X12. Pipeline control.  This object will provide the "main loop" that invokes
  529. X    all the pipeline objects.  Note that we will need several different main
  530. X    loops depending on the situation (interleaved input or not, whether to
  531. X    apply cross-block smoothing or not, etc).  We may want to divvy up the
  532. X    pipeline controllers into two levels, one that retains control over the
  533. X    whole file and one that is invoked per scan.
  534. X    This object will do most of the memory allocation, since it will provide
  535. X    the working buffers that are the inputs and outputs of the pipeline steps.
  536. X    (An object mostly to support multiple instantiations; however, overall
  537. X    memory management and sequencing of operations are known only here.)
  538. X
  539. X13. Overall control.  This module will provide at least two routines:
  540. X    jpeg_decompress: the main entry point to the decompressor.
  541. X    per_scan_method_selection: called by pipeline controllers for
  542. X                   secondary method selection passes.
  543. X    jpeg_decompress is invoked from the user interface after the UI has
  544. X    selected the input and output files and obtained values for all
  545. X    user-specified options (e.g., output file format, whether to do block
  546. X    smoothing).  jpeg_decompress calls read_file_header, performs basic
  547. X    initialization (e.g., calculating the size of MCUs), does the "global"
  548. X    method selection pass, and finally calls the selected pipeline control
  549. X    object.  (Per-scan method selections will be invoked by the pipeline
  550. X    controller.)
  551. X    Note that jpeg_decompress can't be a method since it is invoked prior to
  552. X    method selection.
  553. X
  554. X14. User interface; this is the architecture's term for "the rest of the
  555. X    application program", i.e., that which invokes the JPEG decompressor.
  556. X    The UI is expected to supply input and output files and values for all
  557. X    operational parameters.  The UI must also supply error handling routines.
  558. X    (This module hides the user interface provided --- command line,
  559. X    interactive, etc.  Except for error handling, the UI calls the portable
  560. X    JPEG code, not the other way around.)
  561. X
  562. X15. A memory management object.  This will be identical to the memory
  563. X    management for compression (and will be the same code, in combined
  564. X    programs).  See above for details.
  565. X
  566. X
  567. X*** Initial method selection ***
  568. X
  569. XThe main ugliness in this design is the portion of startup that will select
  570. Xwhich of several instantiations should be used for each of the objects.  (For
  571. Xexample, Huffman or arithmetic for entropy encoding; one of several pipeline
  572. Xcontrollers depending on interleaving, the size of the image, etc.)  It's not
  573. Xreally desirable to have a single chunk of code that knows the names of all
  574. Xthe possible instantiations and the conditions under which to select each one.
  575. X
  576. XThe best approach seems to be to provide a selector function for each object
  577. X(group of related method calls).  This function knows about each possible
  578. Xinstantiation of its object and how to choose the right one; but it doesn't
  579. Xknow about any other objects.
  580. X
  581. XNote that there will be several rounds of method selection: at initial startup,
  582. Xafter overall compression parameters are determined (after the file header is
  583. Xread, if decompressing), and one in preparation for each scan (this occurs
  584. Xmore than once if the file is noninterleaved).  Each object method will need
  585. Xto be clearly identified as to which round sets it up.
  586. X
  587. X
  588. X*** Implications of DNL marker ***
  589. X
  590. XSome JPEG files may use a DNL marker to postpone definition of the image
  591. Xheight (this would be useful for a fax-like scanner's output, for instance).
  592. XIn these files the SOF marker claims the image height is 0, and you only
  593. Xfind out the true image height at the end of the first scan.
  594. X
  595. XWe could handle these files as follows:
  596. X1. Upon seeing zero image height, replace it by 65535 (the maximum allowed).
  597. X2. When the DNL is found, update the image height in the global image
  598. X   descriptor.
  599. XThis implies that pipeline control objects must avoid making copies of the
  600. Ximage height, and must re-test for termination after each MCU row.  This is
  601. Xno big deal.
  602. X
  603. XIn situations where image-size data structures are allocated, this approach
  604. Xwill result in very inefficient use of virtual memory or
  605. Xmuch-larger-than-necessary temporary files.  This seems acceptable for
  606. Xsomething that probably won't be a mainstream usage.  People might have to
  607. Xforgo use of memory-hogging options (such as two-pass color quantization or
  608. Xnoninterleaved JPEG files) if they want efficient conversion of such files.
  609. X(One could improve efficiency by demanding a user-supplied upper bound for the
  610. Xheight, less than 65536; in most cases it could be much less.)
  611. X
  612. XAlternately, we could insist that DNL-using files be preprocessed by a
  613. Xseparate program that reads ahead to the DNL, then goes back and fixes the SOF
  614. Xmarker.  This is a much simpler solution and is probably far more efficient.
  615. XEven if one wants piped input, buffering the first scan of the JPEG file
  616. Xneeds a lot smaller temp file than is implied by the maximum-height method.
  617. XFor this approach we'd simply treat DNL as a no-op in the decompressor (at
  618. Xmost, check that it matches the SOF image height).
  619. X
  620. XWe will not worry about making the compressor capable of outputting DNL.
  621. XSomething similar to the first scheme above could be applied if anyone ever
  622. Xwants to make that work.
  623. X
  624. X
  625. X*** Memory manager internal structure ***
  626. X
  627. XThe memory manager contains the most potential for system dependencies.
  628. XTo isolate system dependencies as much as possible, we have broken the
  629. Xmemory manager into two parts.  There is a reasonably system-independent
  630. X"front end" (jmemmgr.c) and a "back end" that contains only the code
  631. Xlikely to change across systems.  All of the memory management methods
  632. Xoutlined above are implemented by the front end.  The back end provides
  633. Xthe following routines for use by the front end (none of these routines
  634. Xare known to the rest of the JPEG code):
  635. X
  636. Xjmem_init, jmem_term    system-dependent initialization/shutdown
  637. X
  638. Xjget_small, jfree_small    interface to malloc and free library routines
  639. X
  640. Xjget_large, jfree_large    interface to FAR malloc/free in MS-DOS machines;
  641. X            otherwise same as jget_small/jfree_small
  642. X
  643. Xjmem_available        estimate available memory
  644. X
  645. Xjopen_backing_store    create a backing-store object
  646. X
  647. Xread_backing_store,    manipulate a backing store object
  648. Xwrite_backing_store,
  649. Xclose_backing_store
  650. X
  651. XOn some systems there will be more than one type of backing-store object
  652. X(specifically, in MS-DOS a backing store file might be an area of extended
  653. Xmemory as well as a disk file).  jopen_backing_store is responsible for
  654. Xchoosing how to implement a given object.  The read/write/close routines
  655. Xare method pointers in the structure that describes a given object; this
  656. Xlets them be different for different object types.
  657. X
  658. XIt may be necessary to ensure that backing store objects are explicitly
  659. Xreleased upon abnormal program termination.  (For example, MS-DOS won't free
  660. Xextended memory by itself.)  To support this, we will expect the main program
  661. Xor surrounding application to arrange to call the free_all method upon
  662. Xabnormal termination; this may require a SIGINT signal handler, for instance.
  663. X(We don't want to have the system-dependent module install its own signal
  664. Xhandler, because that would pre-empt the surrounding application's ability
  665. Xto control signal handling.)
  666. X
  667. X
  668. X*** Notes for MS-DOS implementors ***
  669. X
  670. XThe standalone cjpeg and djpeg applications can be compiled in "small" memory
  671. Xmodel, at least at the moment; as the code grows we may be forced to switch to
  672. X"medium" model.  (Small = both code and data pointers are near by default;
  673. Xmedium = far code pointers, near data pointers.)  Medium model will slow down
  674. Xcalls through method pointers, but I don't think this will amount to any
  675. Xsignificant speed penalty.
  676. X
  677. XWhen integrating the JPEG code into a larger application, it's a good idea to
  678. Xstay with a small-data-space model if possible.  An 8K stack is much more than
  679. Xsufficient for the JPEG code, and its static data requirements are less than
  680. X1K.  When executed, it will typically malloc about 10K-20K worth of near heap
  681. Xspace (and lots of far heap, but that doesn't count in this calculation).
  682. XThis figure will vary depending on image size and other factors, but figuring
  683. X30K should be more than sufficient.  Thus you have about 25K available for
  684. Xother modules' static data and near heap requirements before you need to go to
  685. Xa larger memory model.  The C library's static data will account for several K
  686. Xof this, but that still leaves a good deal for your needs.  (If you are tight
  687. Xon space, you could reduce JPEG_BUF_SIZE from 4K to 1K to save 3K of near heap
  688. Xspace.)
  689. X
  690. XAs the code is improved, we will endeavor to hold the near data requirements
  691. Xto the range given above.  This does imply that certain data structures will
  692. Xbe allocated as FAR although they would fit in near space if we assumed the
  693. XJPEG code is stand-alone.  (The LZW tables in jrdgif/jwrgif are examples.)
  694. XTo make an optimal implementation, you might want to move these structures
  695. Xback to near heap if you know there is sufficient space.
  696. X
  697. XFAR data space may also be a tight resource when you are dealing with large
  698. Ximages.  The most memory-intensive case is decompression with two-pass color
  699. Xquantization.  This requires a 128Kb color histogram plus strip buffers
  700. Xamounting to about 150 bytes per column for typical sampling ratios (eg, about
  701. X96000 bytes for a 640-pixel-wide image).  You may not be able to process wide
  702. Ximages if you have large data structures of your own.
  703. X
  704. X
  705. X*** Potential optimizations ***
  706. X
  707. XFor colormapped input formats it might be worthwhile to merge the input file
  708. Xreading and the colorspace conversion steps; in other words, do the colorspace
  709. Xconversion by hacking up the colormap before inputting the image body, rather
  710. Xthan doing the conversion on each pixel independently.  Not clear if this is
  711. Xworth the uglification involved.  In the above design for the compressor, only
  712. Xthe colorspace conversion step ever sees the output of get_input_row, so this
  713. Xsort of thing could be done via private agreement between those two modules.
  714. X
  715. XLevel shift from 0..255 to -128..127 may be done either during colorspace
  716. Xconversion, or at the moment of converting an 8x8 sample block into the format
  717. Xused by the DCT step (which will be signed short or long int).  This could be
  718. Xselectable by a compile-time flag, so that the intermediate steps can work on
  719. Xeither signed or unsigned chars as samples, whichever is most easily handled
  720. Xby the platform.  However, making sure that rounding is done right will be a
  721. Xlot easier if we can assume positive values.  At the moment I think that
  722. Xbenefit is worth the overhead of "& 0xFF" when reading out sample values on
  723. Xsigned-char-only machines.
  724. END_OF_FILE
  725.   if test 40461 -ne `wc -c <'architecture.B'`; then
  726.     echo shar: \"'architecture.B'\" unpacked with wrong size!
  727.   elif test -f 'architecture.A'; then
  728.     echo shar: Combining  \"'architecture'\" \(66550 characters\)
  729.     cat 'architecture.A' 'architecture.B' > 'architecture'
  730.     if test 66550 -ne `wc -c <'architecture'`; then
  731.       echo shar: \"'architecture'\" combined with wrong size!
  732.     else
  733.       rm architecture.A architecture.B
  734.     fi
  735.   fi
  736.   # end of 'architecture.B'
  737. fi
  738. if test -f 'jcdeflts.c' -a "${1}" != "-c" ; then 
  739.   echo shar: Will not clobber existing file \"'jcdeflts.c'\"
  740. else
  741.   echo shar: Extracting \"'jcdeflts.c'\" \(14662 characters\)
  742.   sed "s/^X//" >'jcdeflts.c' <<'END_OF_FILE'
  743. X/*
  744. X * jcdeflts.c
  745. X *
  746. X * Copyright (C) 1991, 1992, Thomas G. Lane.
  747. X * This file is part of the Independent JPEG Group's software.
  748. X * For conditions of distribution and use, see the accompanying README file.
  749. X *
  750. X * This file contains optional default-setting code for the JPEG compressor.
  751. X * User interfaces do not have to use this file, but those that don't use it
  752. X * must know a lot more about the innards of the JPEG code.
  753. X */
  754. X
  755. X#include "jinclude.h"
  756. X
  757. X
  758. X/* Default do-nothing progress monitoring routine.
  759. X * This can be overridden by a user interface that wishes to
  760. X * provide progress monitoring; just set methods->progress_monitor
  761. X * after j_c_defaults is done.  The routine will be called periodically
  762. X * during the compression process.
  763. X *
  764. X * During any one pass, loopcounter increases from 0 up to (not including)
  765. X * looplimit; the step size is not necessarily 1.  Both the step size and
  766. X * the limit may differ between passes.  The expected total number of passes
  767. X * is in cinfo->total_passes, and the number of passes already completed is
  768. X * in cinfo->completed_passes.  Thus the fraction of work completed may be
  769. X * estimated as
  770. X *        completed_passes + (loopcounter/looplimit)
  771. X *        ------------------------------------------
  772. X *                total_passes
  773. X * ignoring the fact that the passes may not be equal amounts of work.
  774. X */
  775. X
  776. XMETHODDEF void
  777. Xprogress_monitor (compress_info_ptr cinfo, long loopcounter, long looplimit)
  778. X{
  779. X  /* do nothing */
  780. X}
  781. X
  782. X
  783. X/*
  784. X * Huffman table setup routines
  785. X */
  786. X
  787. XLOCAL void
  788. Xadd_huff_table (compress_info_ptr cinfo,
  789. X        HUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  790. X/* Define a Huffman table */
  791. X{
  792. X  if (*htblptr == NULL)
  793. X    *htblptr = (HUFF_TBL *) (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
  794. X  
  795. X  MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  796. X  MEMCOPY((*htblptr)->huffval, val, SIZEOF((*htblptr)->huffval));
  797. X
  798. X  /* Initialize sent_table FALSE so table will be written to JPEG file.
  799. X   * In an application where we are writing non-interchange JPEG files,
  800. X   * it might be desirable to save space by leaving default Huffman tables
  801. X   * out of the file.  To do that, just initialize sent_table = TRUE...
  802. X   */
  803. X
  804. X  (*htblptr)->sent_table = FALSE;
  805. X}
  806. X
  807. X
  808. XLOCAL void
  809. Xstd_huff_tables (compress_info_ptr cinfo)
  810. X/* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  811. X/* IMPORTANT: these are only valid for 8-bit data precision! */
  812. X{
  813. X  static const UINT8 dc_luminance_bits[17] =
  814. X    { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  815. X  static const UINT8 dc_luminance_val[] =
  816. X    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  817. X  
  818. X  static const UINT8 dc_chrominance_bits[17] =
  819. X    { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  820. X  static const UINT8 dc_chrominance_val[] =
  821. X    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  822. X  
  823. X  static const UINT8 ac_luminance_bits[17] =
  824. X    { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  825. X  static const UINT8 ac_luminance_val[] =
  826. X    { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  827. X      0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  828. X      0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  829. X      0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  830. X      0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  831. X      0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  832. X      0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  833. X      0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  834. X      0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  835. X      0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  836. X      0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  837. X      0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  838. X      0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  839. X      0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  840. X      0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  841. X      0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  842. X      0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  843. X      0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  844. X      0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  845. X      0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  846. X      0xf9, 0xfa };
  847. X  
  848. X  static const UINT8 ac_chrominance_bits[17] =
  849. X    { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  850. X  static const UINT8 ac_chrominance_val[] =
  851. X    { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  852. X      0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  853. X      0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  854. X      0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  855. X      0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  856. X      0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  857. X      0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  858. X      0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  859. X      0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  860. X      0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  861. X      0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  862. X      0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  863. X      0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  864. X      0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  865. X      0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  866. X      0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  867. X      0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  868. X      0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  869. X      0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  870. X      0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  871. X      0xf9, 0xfa };
  872. X  
  873. X  add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  874. X         dc_luminance_bits, dc_luminance_val);
  875. X  add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  876. X         ac_luminance_bits, ac_luminance_val);
  877. X  add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  878. X         dc_chrominance_bits, dc_chrominance_val);
  879. X  add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  880. X         ac_chrominance_bits, ac_chrominance_val);
  881. X}
  882. X
  883. X
  884. X/*
  885. X * Quantization table setup routines
  886. X */
  887. X
  888. XGLOBAL void
  889. Xj_add_quant_table (compress_info_ptr cinfo, int which_tbl,
  890. X           const QUANT_VAL *basic_table, int scale_factor,
  891. X           boolean force_baseline)
  892. X/* Define a quantization table equal to the basic_table times
  893. X * a scale factor (given as a percentage).
  894. X * If force_baseline is TRUE, the computed quantization table entries
  895. X * are limited to 1..255 for JPEG baseline compatibility.
  896. X */
  897. X{
  898. X  QUANT_TBL_PTR * qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  899. X  int i;
  900. X  long temp;
  901. X
  902. X  if (*qtblptr == NULL)
  903. X    *qtblptr = (QUANT_TBL_PTR) (*cinfo->emethods->alloc_small) (SIZEOF(QUANT_TBL));
  904. X
  905. X  for (i = 0; i < DCTSIZE2; i++) {
  906. X    temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  907. X    /* limit the values to the valid range */
  908. X    if (temp <= 0L) temp = 1L;
  909. X#ifdef EIGHT_BIT_SAMPLES
  910. X    if (temp > 32767L) temp = 32767L; /* QUANT_VALs are 'short' */
  911. X#else
  912. X    if (temp > 65535L) temp = 65535L; /* QUANT_VALs are 'UINT16' */
  913. X#endif
  914. X    if (force_baseline && temp > 255L)
  915. X      temp = 255L;        /* limit to baseline range if requested */
  916. X    (*qtblptr)[i] = (QUANT_VAL) temp;
  917. X  }
  918. X}
  919. X
  920. X
  921. XGLOBAL int
  922. Xj_quality_scaling (int quality)
  923. X/* Convert a user-specified quality rating to a percentage scaling factor
  924. X * for an underlying quantization table, using our recommended scaling curve.
  925. X * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  926. X */
  927. X{
  928. X  /* Safety limit on quality factor.  Convert 0 to 1 to avoid zero divide. */
  929. X  if (quality <= 0) quality = 1;
  930. X  if (quality > 100) quality = 100;
  931. X
  932. X  /* The basic table is used as-is (scaling 100) for a quality of 50.
  933. X   * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  934. X   * note that at Q=100 the scaling is 0, which will cause j_add_quant_table
  935. X   * to make all the table entries 1 (hence, no quantization loss).
  936. X   * Qualities 1..50 are converted to scaling percentage 5000/Q.
  937. X   */
  938. X  if (quality < 50)
  939. X    quality = 5000 / quality;
  940. X  else
  941. X    quality = 200 - quality*2;
  942. X
  943. X  return quality;
  944. X}
  945. X
  946. X
  947. XGLOBAL void
  948. Xj_set_quality (compress_info_ptr cinfo, int quality, boolean force_baseline)
  949. X/* Set or change the 'quality' (quantization) setting, using default tables.
  950. X * This is the standard quality-adjusting entry point for typical user
  951. X * interfaces; only those who want detailed control over quantization tables
  952. X * would use the preceding two routines directly.
  953. X */
  954. X{
  955. X  /* This is the sample quantization table given in the JPEG spec section K.1,
  956. X   * but expressed in zigzag order (as are all of our quant. tables).
  957. X   * The spec says that the values given produce "good" quality, and
  958. X   * when divided by 2, "very good" quality.  (These two settings are
  959. X   * selected by quality=50 and quality=75 respectively.)
  960. X   */
  961. X  static const QUANT_VAL std_luminance_quant_tbl[DCTSIZE2] = {
  962. X    16,  11,  12,  14,  12,  10,  16,  14,
  963. X    13,  14,  18,  17,  16,  19,  24,  40,
  964. X    26,  24,  22,  22,  24,  49,  35,  37,
  965. X    29,  40,  58,  51,  61,  60,  57,  51,
  966. X    56,  55,  64,  72,  92,  78,  64,  68,
  967. X    87,  69,  55,  56,  80, 109,  81,  87,
  968. X    95,  98, 103, 104, 103,  62,  77, 113,
  969. X    121, 112, 100, 120,  92, 101, 103,  99
  970. X    };
  971. X  static const QUANT_VAL std_chrominance_quant_tbl[DCTSIZE2] = {
  972. X    17,  18,  18,  24,  21,  24,  47,  26,
  973. X    26,  47,  99,  66,  56,  66,  99,  99,
  974. X    99,  99,  99,  99,  99,  99,  99,  99,
  975. X    99,  99,  99,  99,  99,  99,  99,  99,
  976. X    99,  99,  99,  99,  99,  99,  99,  99,
  977. X    99,  99,  99,  99,  99,  99,  99,  99,
  978. X    99,  99,  99,  99,  99,  99,  99,  99,
  979. X    99,  99,  99,  99,  99,  99,  99,  99
  980. X    };
  981. X
  982. X  /* Convert user 0-100 rating to percentage scaling */
  983. X  quality = j_quality_scaling(quality);
  984. X
  985. X  /* Set up two quantization tables using the specified quality scaling */
  986. X  j_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  987. X            quality, force_baseline);
  988. X  j_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  989. X            quality, force_baseline);
  990. X}
  991. X
  992. X
  993. X
  994. X/* Default parameter setup for compression.
  995. X *
  996. X * User interfaces that don't choose to use this routine must do their
  997. X * own setup of all these parameters.  Alternately, you can call this
  998. X * to establish defaults and then alter parameters selectively.  This
  999. X * is the recommended approach since, if we add any new parameters,
  1000. X * your code will still work (they'll be set to reasonable defaults).
  1001. X *
  1002. X * See above for the meaning of the 'quality' and 'force_baseline' parameters.
  1003. X * Typically, the application's default quality setting will be passed to this
  1004. X * routine.  A later call on j_set_quality() can be used to change to a
  1005. X * user-specified quality setting.
  1006. X *
  1007. X * This routine sets up for a color image; to output a grayscale image,
  1008. X * do this first and call j_monochrome_default() afterwards.
  1009. X * (The latter can be called within c_ui_method_selection, so the
  1010. X * choice can depend on the input file header.)
  1011. X * Note that if you want a JPEG colorspace other than GRAYSCALE or YCbCr,
  1012. X * you should also change the component ID codes, and you should NOT emit
  1013. X * a JFIF header (set write_JFIF_header = FALSE).
  1014. X *
  1015. X * CAUTION: if you want to compress multiple images per run, it's necessary
  1016. X * to call j_c_defaults before *each* call to jpeg_compress, since subsidiary
  1017. X * structures like the Huffman tables are automatically freed during cleanup.
  1018. X */
  1019. X
  1020. XGLOBAL void
  1021. Xj_c_defaults (compress_info_ptr cinfo, int quality, boolean force_baseline)
  1022. X/* NB: the external methods must already be set up. */
  1023. X{
  1024. X  short i;
  1025. X  jpeg_component_info * compptr;
  1026. X
  1027. X  /* Initialize pointers as needed to mark stuff unallocated. */
  1028. X  cinfo->comp_info = NULL;
  1029. X  for (i = 0; i < NUM_QUANT_TBLS; i++)
  1030. X    cinfo->quant_tbl_ptrs[i] = NULL;
  1031. X  for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1032. X    cinfo->dc_huff_tbl_ptrs[i] = NULL;
  1033. X    cinfo->ac_huff_tbl_ptrs[i] = NULL;
  1034. X  }
  1035. X
  1036. X  cinfo->data_precision = BITS_IN_JSAMPLE; /* default; can be overridden by input_init */
  1037. X  cinfo->density_unit = 0;    /* Pixel size is unknown by default */
  1038. X  cinfo->X_density = 1;        /* Pixel aspect ratio is square by default */
  1039. X  cinfo->Y_density = 1;
  1040. X
  1041. X  cinfo->input_gamma = 1.0;    /* no gamma correction by default */
  1042. X
  1043. X  /* Prepare three color components; first is luminance which is also usable */
  1044. X  /* for grayscale.  The others are assumed to be UV or similar chrominance. */
  1045. X  cinfo->write_JFIF_header = TRUE;
  1046. X  cinfo->jpeg_color_space = CS_YCbCr;
  1047. X  cinfo->num_components = 3;
  1048. X  cinfo->comp_info = (jpeg_component_info *)
  1049. X    (*cinfo->emethods->alloc_small) (4 * SIZEOF(jpeg_component_info));
  1050. X  /* Note: we allocate a 4-entry comp_info array so that user interface can
  1051. X   * easily change over to CMYK color space if desired.
  1052. X   */
  1053. X
  1054. X  compptr = &cinfo->comp_info[0];
  1055. X  compptr->component_index = 0;
  1056. X  compptr->component_id = 1;    /* JFIF specifies IDs 1,2,3 */
  1057. X  compptr->h_samp_factor = 2;    /* default to 2x2 subsamples of chrominance */
  1058. X  compptr->v_samp_factor = 2;
  1059. X  compptr->quant_tbl_no = 0;    /* use tables 0 for luminance */
  1060. X  compptr->dc_tbl_no = 0;
  1061. X  compptr->ac_tbl_no = 0;
  1062. X
  1063. X  compptr = &cinfo->comp_info[1];
  1064. X  compptr->component_index = 1;
  1065. X  compptr->component_id = 2;
  1066. X  compptr->h_samp_factor = 1;
  1067. X  compptr->v_samp_factor = 1;
  1068. X  compptr->quant_tbl_no = 1;    /* use tables 1 for chrominance */
  1069. X  compptr->dc_tbl_no = 1;
  1070. X  compptr->ac_tbl_no = 1;
  1071. X
  1072. X  compptr = &cinfo->comp_info[2];
  1073. X  compptr->component_index = 2;
  1074. X  compptr->component_id = 3;
  1075. X  compptr->h_samp_factor = 1;
  1076. X  compptr->v_samp_factor = 1;
  1077. X  compptr->quant_tbl_no = 1;    /* use tables 1 for chrominance */
  1078. X  compptr->dc_tbl_no = 1;
  1079. X  compptr->ac_tbl_no = 1;
  1080. X
  1081. X  /* Set up two quantization tables using the specified quality scaling */
  1082. X  j_set_quality(cinfo, quality, force_baseline);
  1083. X
  1084. X  /* Set up two Huffman tables in case user interface wants Huffman coding */
  1085. X  std_huff_tables(cinfo);
  1086. X
  1087. X  /* Initialize default arithmetic coding conditioning */
  1088. X  for (i = 0; i < NUM_ARITH_TBLS; i++) {
  1089. X    cinfo->arith_dc_L[i] = 0;
  1090. X    cinfo->arith_dc_U[i] = 1;
  1091. X    cinfo->arith_ac_K[i] = 5;
  1092. X  }
  1093. X
  1094. X  /* Use Huffman coding, not arithmetic coding, by default */
  1095. X  cinfo->arith_code = FALSE;
  1096. X
  1097. X  /* Color images are interleaved by default */
  1098. X  cinfo->interleave = TRUE;
  1099. X
  1100. X  /* By default, don't do extra passes to optimize entropy coding */
  1101. X  cinfo->optimize_coding = FALSE;
  1102. X
  1103. X  /* By default, use the simpler non-cosited sampling alignment */
  1104. X  cinfo->CCIR601_sampling = FALSE;
  1105. X
  1106. X  /* No input smoothing */
  1107. X  cinfo->smoothing_factor = 0;
  1108. X
  1109. X  /* No restart markers */
  1110. X  cinfo->restart_interval = 0;
  1111. X  cinfo->restart_in_rows = 0;
  1112. X
  1113. X  /* Install default do-nothing progress monitoring method. */
  1114. X  cinfo->methods->progress_monitor = progress_monitor;
  1115. X}
  1116. X
  1117. X
  1118. X
  1119. XGLOBAL void
  1120. Xj_monochrome_default (compress_info_ptr cinfo)
  1121. X/* Change the j_c_defaults() values to emit a monochrome JPEG file. */
  1122. X{
  1123. X  jpeg_component_info * compptr;
  1124. X
  1125. X  cinfo->jpeg_color_space = CS_GRAYSCALE;
  1126. X  cinfo->num_components = 1;
  1127. X  /* Set single component to 1x1 subsampling */
  1128. X  compptr = &cinfo->comp_info[0];
  1129. X  compptr->h_samp_factor = 1;
  1130. X  compptr->v_samp_factor = 1;
  1131. X}
  1132. END_OF_FILE
  1133.   if test 14662 -ne `wc -c <'jcdeflts.c'`; then
  1134.     echo shar: \"'jcdeflts.c'\" unpacked with wrong size!
  1135.   fi
  1136.   # end of 'jcdeflts.c'
  1137. fi
  1138. if test -f 'jversion.h' -a "${1}" != "-c" ; then 
  1139.   echo shar: Will not clobber existing file \"'jversion.h'\"
  1140. else
  1141.   echo shar: Extracting \"'jversion.h'\" \(357 characters\)
  1142.   sed "s/^X//" >'jversion.h' <<'END_OF_FILE'
  1143. X/*
  1144. X * jversion.h
  1145. X *
  1146. X * Copyright (C) 1991, 1992, Thomas G. Lane.
  1147. X * This file is part of the Independent JPEG Group's software.
  1148. X * For conditions of distribution and use, see the accompanying README file.
  1149. X *
  1150. X * This file contains software version identification.
  1151. X */
  1152. X
  1153. X
  1154. X#define JVERSION    "4 10-Dec-92"
  1155. X
  1156. X#define JCOPYRIGHT    "Copyright (C) 1992, Thomas G. Lane"
  1157. END_OF_FILE
  1158.   if test 357 -ne `wc -c <'jversion.h'`; then
  1159.     echo shar: \"'jversion.h'\" unpacked with wrong size!
  1160.   fi
  1161.   # end of 'jversion.h'
  1162. fi
  1163. echo shar: End of archive 3 \(of 18\).
  1164. cp /dev/null ark3isdone
  1165. MISSING=""
  1166. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ; do
  1167.     if test ! -f ark${I}isdone ; then
  1168.     MISSING="${MISSING} ${I}"
  1169.     fi
  1170. done
  1171. if test "${MISSING}" = "" ; then
  1172.     echo You have unpacked all 18 archives.
  1173.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1174. else
  1175.     echo You still must unpack the following archives:
  1176.     echo "        " ${MISSING}
  1177. fi
  1178. exit 0
  1179. exit 0 # Just in case...
  1180.