structure.txt 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. IJG JPEG LIBRARY: SYSTEM ARCHITECTURE
  2. This file was part of the Independent JPEG Group's software:
  3. Copyright (C) 1991-2012, Thomas G. Lane, Guido Vollbeding.
  4. It was modified by The libjpeg-turbo Project to include only information
  5. relevant to libjpeg-turbo.
  6. For conditions of distribution and use, see the accompanying README.ijg file.
  7. This file provides an overview of the architecture of the IJG JPEG software;
  8. that is, the functions of the various modules in the system and the interfaces
  9. between modules. For more precise details about any data structure or calling
  10. convention, see the include files and comments in the source code.
  11. We assume that the reader is already somewhat familiar with the JPEG standard.
  12. The README.ijg file includes references for learning about JPEG. The file
  13. libjpeg.txt describes the library from the viewpoint of an application
  14. programmer using the library; it's best to read that file before this one.
  15. Also, the file coderules.txt describes the coding style conventions we use.
  16. In this document, JPEG-specific terminology follows the JPEG standard:
  17. A "component" means a color channel, e.g., Red or Luminance.
  18. A "sample" is a single component value (i.e., one number in the image data).
  19. A "coefficient" is a frequency coefficient (a DCT transform output number).
  20. A "block" is an 8x8 group of samples or coefficients.
  21. An "MCU" (minimum coded unit) is an interleaved set of blocks of size
  22. determined by the sampling factors, or a single block in a
  23. noninterleaved scan.
  24. We do not use the terms "pixel" and "sample" interchangeably. When we say
  25. pixel, we mean an element of the full-size image, while a sample is an element
  26. of the downsampled image. Thus the number of samples may vary across
  27. components while the number of pixels does not. (This terminology is not used
  28. rigorously throughout the code, but it is used in places where confusion would
  29. otherwise result.)
  30. *** System features ***
  31. The IJG distribution contains two parts:
  32. * A subroutine library for JPEG compression and decompression.
  33. * cjpeg/djpeg, two sample applications that use the library to transform
  34. JFIF JPEG files to and from several other image formats.
  35. cjpeg/djpeg are of no great intellectual complexity: they merely add a simple
  36. command-line user interface and I/O routines for several uncompressed image
  37. formats. This document concentrates on the library itself.
  38. We desire the library to be capable of supporting all JPEG baseline, extended
  39. sequential, and progressive DCT processes. Hierarchical processes are not
  40. supported.
  41. The library does not support the lossless (spatial) JPEG process. Lossless
  42. JPEG shares little or no code with lossy JPEG, and would normally be used
  43. without the extensive pre- and post-processing provided by this library.
  44. We feel that lossless JPEG is better handled by a separate library.
  45. Within these limits, any set of compression parameters allowed by the JPEG
  46. spec should be readable for decompression. (We can be more restrictive about
  47. what formats we can generate.) Although the system design allows for all
  48. parameter values, some uncommon settings are not yet implemented and may
  49. never be; nonintegral sampling ratios are the prime example. Furthermore,
  50. we treat 8-bit vs. 12-bit data precision as a compile-time switch, not a
  51. run-time option, because most machines can store 8-bit pixels much more
  52. compactly than 12-bit.
  53. By itself, the library handles only interchange JPEG datastreams --- in
  54. particular the widely used JFIF file format. The library can be used by
  55. surrounding code to process interchange or abbreviated JPEG datastreams that
  56. are embedded in more complex file formats. (For example, libtiff uses this
  57. library to implement JPEG compression within the TIFF file format.)
  58. The library includes a substantial amount of code that is not covered by the
  59. JPEG standard but is necessary for typical applications of JPEG. These
  60. functions preprocess the image before JPEG compression or postprocess it after
  61. decompression. They include colorspace conversion, downsampling/upsampling,
  62. and color quantization. This code can be omitted if not needed.
  63. A wide range of quality vs. speed tradeoffs are possible in JPEG processing,
  64. and even more so in decompression postprocessing. The decompression library
  65. provides multiple implementations that cover most of the useful tradeoffs,
  66. ranging from very-high-quality down to fast-preview operation. On the
  67. compression side we have generally not provided low-quality choices, since
  68. compression is normally less time-critical. It should be understood that the
  69. low-quality modes may not meet the JPEG standard's accuracy requirements;
  70. nonetheless, they are useful for viewers.
  71. *** System overview ***
  72. The compressor and decompressor are each divided into two main sections:
  73. the JPEG compressor or decompressor proper, and the preprocessing or
  74. postprocessing functions. The interface between these two sections is the
  75. image data that Rec. ITU-T T.81 | ISO/IEC 10918-1 regards as its input or
  76. output: this data is in the colorspace to be used for compression, and it is
  77. downsampled to the sampling factors to be used. The preprocessing and
  78. postprocessing steps are responsible for converting a normal image
  79. representation to or from this form. (Those few applications that want to deal
  80. with YCbCr downsampled data can skip the preprocessing or postprocessing step.)
  81. Looking more closely, the compressor library contains the following main
  82. elements:
  83. Preprocessing:
  84. * Color space conversion (e.g., RGB to YCbCr).
  85. * Edge expansion and downsampling. Optionally, this step can do simple
  86. smoothing --- this is often helpful for low-quality source data.
  87. JPEG proper:
  88. * MCU assembly, DCT, quantization.
  89. * Entropy coding (sequential or progressive, Huffman or arithmetic).
  90. In addition to these modules we need overall control, marker generation,
  91. and support code (memory management & error handling). There is also a
  92. module responsible for physically writing the output data --- typically
  93. this is just an interface to fwrite(), but some applications may need to
  94. do something else with the data.
  95. The decompressor library contains the following main elements:
  96. JPEG proper:
  97. * Entropy decoding (sequential or progressive, Huffman or arithmetic).
  98. * Dequantization, inverse DCT, MCU disassembly.
  99. Postprocessing:
  100. * Upsampling. Optionally, this step may be able to do more general
  101. rescaling of the image.
  102. * Color space conversion (e.g., YCbCr to RGB). This step may also
  103. provide gamma adjustment [ currently it does not ].
  104. * Optional color quantization (e.g., reduction to 256 colors).
  105. * Optional color precision reduction (e.g., 24-bit to 15-bit color).
  106. [This feature is not currently implemented.]
  107. We also need overall control, marker parsing, and a data source module.
  108. The support code (memory management & error handling) can be shared with
  109. the compression half of the library.
  110. There may be several implementations of each of these elements, particularly
  111. in the decompressor, where a wide range of speed/quality tradeoffs is very
  112. useful. It must be understood that some of the best speedups involve
  113. merging adjacent steps in the pipeline. For example, upsampling, color space
  114. conversion, and color quantization might all be done at once when using a
  115. low-quality ordered-dither technique. The system architecture is designed to
  116. allow such merging where appropriate.
  117. Note: it is convenient to regard edge expansion (padding to block boundaries)
  118. as a preprocessing/postprocessing function, even though
  119. Rec. ITU-T T.81 | ISO/IEC 10918-1 includes it in compression/decompression. We
  120. do this because downsampling/upsampling can be simplified a little if they work
  121. on padded data: it's not necessary to have special cases at the right and
  122. bottom edges. Therefore the interface buffer is always an integral number of
  123. blocks wide and high, and we expect compression preprocessing to pad the source
  124. data properly. Padding will occur only to the next block (8-sample) boundary.
  125. In an interleaved-scan situation, additional dummy blocks may be used to fill
  126. out MCUs, but the MCU assembly and disassembly logic will create or discard
  127. these blocks internally. (This is advantageous for speed reasons, since we
  128. avoid DCTing the dummy blocks. It also permits a small reduction in file size,
  129. because the compressor can choose dummy block contents so as to minimize their
  130. size in compressed form. Finally, it makes the interface buffer specification
  131. independent of whether the file is actually interleaved or not.) Applications
  132. that wish to deal directly with the downsampled data must provide similar
  133. buffering and padding for odd-sized images.
  134. *** Poor man's object-oriented programming ***
  135. It should be clear by now that we have a lot of quasi-independent processing
  136. steps, many of which have several possible behaviors. To avoid cluttering the
  137. code with lots of switch statements, we use a simple form of object-style
  138. programming to separate out the different possibilities.
  139. For example, two different color quantization algorithms could be implemented
  140. as two separate modules that present the same external interface; at runtime,
  141. the calling code will access the proper module indirectly through an "object".
  142. We can get the limited features we need while staying within portable C.
  143. The basic tool is a function pointer. An "object" is just a struct
  144. containing one or more function pointer fields, each of which corresponds to
  145. a method name in real object-oriented languages. During initialization we
  146. fill in the function pointers with references to whichever module we have
  147. determined we need to use in this run. Then invocation of the module is done
  148. by indirecting through a function pointer; on most machines this is no more
  149. expensive than a switch statement, which would be the only other way of
  150. making the required run-time choice. The really significant benefit, of
  151. course, is keeping the source code clean and well structured.
  152. We can also arrange to have private storage that varies between different
  153. implementations of the same kind of object. We do this by making all the
  154. module-specific object structs be separately allocated entities, which will
  155. be accessed via pointers in the master compression or decompression struct.
  156. The "public" fields or methods for a given kind of object are specified by
  157. a commonly known struct. But a module's initialization code can allocate
  158. a larger struct that contains the common struct as its first member, plus
  159. additional private fields. With appropriate pointer casting, the module's
  160. internal functions can access these private fields. (For a simple example,
  161. see jdatadst.c, which implements the external interface specified by struct
  162. jpeg_destination_mgr, but adds extra fields.)
  163. (Of course this would all be a lot easier if we were using C++, but we are
  164. not yet prepared to assume that everyone has a C++ compiler.)
  165. An important benefit of this scheme is that it is easy to provide multiple
  166. versions of any method, each tuned to a particular case. While a lot of
  167. precalculation might be done to select an optimal implementation of a method,
  168. the cost per invocation is constant. For example, the upsampling step might
  169. have a "generic" method, plus one or more "hardwired" methods for the most
  170. popular sampling factors; the hardwired methods would be faster because they'd
  171. use straight-line code instead of for-loops. The cost to determine which
  172. method to use is paid only once, at startup, and the selection criteria are
  173. hidden from the callers of the method.
  174. This plan differs a little bit from usual object-oriented structures, in that
  175. only one instance of each object class will exist during execution. The
  176. reason for having the class structure is that on different runs we may create
  177. different instances (choose to execute different modules). You can think of
  178. the term "method" as denoting the common interface presented by a particular
  179. set of interchangeable functions, and "object" as denoting a group of related
  180. methods, or the total shared interface behavior of a group of modules.
  181. *** Overall control structure ***
  182. We previously mentioned the need for overall control logic in the compression
  183. and decompression libraries. In IJG implementations prior to v5, overall
  184. control was mostly provided by "pipeline control" modules, which proved to be
  185. large, unwieldy, and hard to understand. To improve the situation, the
  186. control logic has been subdivided into multiple modules. The control modules
  187. consist of:
  188. 1. Master control for module selection and initialization. This has two
  189. responsibilities:
  190. 1A. Startup initialization at the beginning of image processing.
  191. The individual processing modules to be used in this run are selected
  192. and given initialization calls.
  193. 1B. Per-pass control. This determines how many passes will be performed
  194. and calls each active processing module to configure itself
  195. appropriately at the beginning of each pass. End-of-pass processing,
  196. where necessary, is also invoked from the master control module.
  197. Method selection is partially distributed, in that a particular processing
  198. module may contain several possible implementations of a particular method,
  199. which it will select among when given its initialization call. The master
  200. control code need only be concerned with decisions that affect more than
  201. one module.
  202. 2. Data buffering control. A separate control module exists for each
  203. inter-processing-step data buffer. This module is responsible for
  204. invoking the processing steps that write or read that data buffer.
  205. Each buffer controller sees the world as follows:
  206. input data => processing step A => buffer => processing step B => output data
  207. | | |
  208. ------------------ controller ------------------
  209. The controller knows the dataflow requirements of steps A and B: how much data
  210. they want to accept in one chunk and how much they output in one chunk. Its
  211. function is to manage its buffer and call A and B at the proper times.
  212. A data buffer control module may itself be viewed as a processing step by a
  213. higher-level control module; thus the control modules form a binary tree with
  214. elementary processing steps at the leaves of the tree.
  215. The control modules are objects. A considerable amount of flexibility can
  216. be had by replacing implementations of a control module. For example:
  217. * Merging of adjacent steps in the pipeline is done by replacing a control
  218. module and its pair of processing-step modules with a single processing-
  219. step module. (Hence the possible merges are determined by the tree of
  220. control modules.)
  221. * In some processing modes, a given interstep buffer need only be a "strip"
  222. buffer large enough to accommodate the desired data chunk sizes. In other
  223. modes, a full-image buffer is needed and several passes are required.
  224. The control module determines which kind of buffer is used and manipulates
  225. virtual array buffers as needed. One or both processing steps may be
  226. unaware of the multi-pass behavior.
  227. In theory, we might be able to make all of the data buffer controllers
  228. interchangeable and provide just one set of implementations for all. In
  229. practice, each one contains considerable special-case processing for its
  230. particular job. The buffer controller concept should be regarded as an
  231. overall system structuring principle, not as a complete description of the
  232. task performed by any one controller.
  233. *** Compression object structure ***
  234. Here is a sketch of the logical structure of the JPEG compression library:
  235. |-- Colorspace conversion
  236. |-- Preprocessing controller --|
  237. | |-- Downsampling
  238. Main controller --|
  239. | |-- Forward DCT, quantize
  240. |-- Coefficient controller --|
  241. |-- Entropy encoding
  242. This sketch also describes the flow of control (subroutine calls) during
  243. typical image data processing. Each of the components shown in the diagram is
  244. an "object" which may have several different implementations available. One
  245. or more source code files contain the actual implementation(s) of each object.
  246. The objects shown above are:
  247. * Main controller: buffer controller for the subsampled-data buffer, which
  248. holds the preprocessed input data. This controller invokes preprocessing to
  249. fill the subsampled-data buffer, and JPEG compression to empty it. There is
  250. usually no need for a full-image buffer here; a strip buffer is adequate.
  251. * Preprocessing controller: buffer controller for the downsampling input data
  252. buffer, which lies between colorspace conversion and downsampling. Note
  253. that a unified conversion/downsampling module would probably replace this
  254. controller entirely.
  255. * Colorspace conversion: converts application image data into the desired
  256. JPEG color space; also changes the data from pixel-interleaved layout to
  257. separate component planes. Processes one pixel row at a time.
  258. * Downsampling: performs reduction of chroma components as required.
  259. Optionally may perform pixel-level smoothing as well. Processes a "row
  260. group" at a time, where a row group is defined as Vmax pixel rows of each
  261. component before downsampling, and Vk sample rows afterwards (remember Vk
  262. differs across components). Some downsampling or smoothing algorithms may
  263. require context rows above and below the current row group; the
  264. preprocessing controller is responsible for supplying these rows via proper
  265. buffering. The downsampler is responsible for edge expansion at the right
  266. edge (i.e., extending each sample row to a multiple of 8 samples); but the
  267. preprocessing controller is responsible for vertical edge expansion (i.e.,
  268. duplicating the bottom sample row as needed to make a multiple of 8 rows).
  269. * Coefficient controller: buffer controller for the DCT-coefficient data.
  270. This controller handles MCU assembly, including insertion of dummy DCT
  271. blocks when needed at the right or bottom edge. When performing
  272. Huffman-code optimization or emitting a multiscan JPEG file, this
  273. controller is responsible for buffering the full image. The equivalent of
  274. one fully interleaved MCU row of subsampled data is processed per call,
  275. even when the JPEG file is noninterleaved.
  276. * Forward DCT and quantization: Perform DCT, quantize, and emit coefficients.
  277. Works on one or more DCT blocks at a time. (Note: the coefficients are now
  278. emitted in normal array order, which the entropy encoder is expected to
  279. convert to zigzag order as necessary. Prior versions of the IJG code did
  280. the conversion to zigzag order within the quantization step.)
  281. * Entropy encoding: Perform Huffman or arithmetic entropy coding and emit the
  282. coded data to the data destination module. Works on one MCU per call.
  283. For progressive JPEG, the same DCT blocks are fed to the entropy coder
  284. during each pass, and the coder must emit the appropriate subset of
  285. coefficients.
  286. In addition to the above objects, the compression library includes these
  287. objects:
  288. * Master control: determines the number of passes required, controls overall
  289. and per-pass initialization of the other modules.
  290. * Marker writing: generates JPEG markers (except for RSTn, which is emitted
  291. by the entropy encoder when needed).
  292. * Data destination manager: writes the output JPEG datastream to its final
  293. destination (e.g., a file). The destination manager supplied with the
  294. library knows how to write to a stdio stream or to a memory buffer;
  295. for other behaviors, the surrounding application may provide its own
  296. destination manager.
  297. * Memory manager: allocates and releases memory, controls virtual arrays
  298. (with backing store management, where required).
  299. * Error handler: performs formatting and output of error and trace messages;
  300. determines handling of nonfatal errors. The surrounding application may
  301. override some or all of this object's methods to change error handling.
  302. * Progress monitor: supports output of "percent-done" progress reports.
  303. This object represents an optional callback to the surrounding application:
  304. if wanted, it must be supplied by the application.
  305. The error handler, destination manager, and progress monitor objects are
  306. defined as separate objects in order to simplify application-specific
  307. customization of the JPEG library. A surrounding application may override
  308. individual methods or supply its own all-new implementation of one of these
  309. objects. The object interfaces for these objects are therefore treated as
  310. part of the application interface of the library, whereas the other objects
  311. are internal to the library.
  312. The error handler and memory manager are shared by JPEG compression and
  313. decompression; the progress monitor, if used, may be shared as well.
  314. *** Decompression object structure ***
  315. Here is a sketch of the logical structure of the JPEG decompression library:
  316. |-- Entropy decoding
  317. |-- Coefficient controller --|
  318. | |-- Dequantize, Inverse DCT
  319. Main controller --|
  320. | |-- Upsampling
  321. |-- Postprocessing controller --| |-- Colorspace conversion
  322. |-- Color quantization
  323. |-- Color precision reduction
  324. As before, this diagram also represents typical control flow. The objects
  325. shown are:
  326. * Main controller: buffer controller for the subsampled-data buffer, which
  327. holds the output of JPEG decompression proper. This controller's primary
  328. task is to feed the postprocessing procedure. Some upsampling algorithms
  329. may require context rows above and below the current row group; when this
  330. is true, the main controller is responsible for managing its buffer so as
  331. to make context rows available. In the current design, the main buffer is
  332. always a strip buffer; a full-image buffer is never required.
  333. * Coefficient controller: buffer controller for the DCT-coefficient data.
  334. This controller handles MCU disassembly, including deletion of any dummy
  335. DCT blocks at the right or bottom edge. When reading a multiscan JPEG
  336. file, this controller is responsible for buffering the full image.
  337. (Buffering DCT coefficients, rather than samples, is necessary to support
  338. progressive JPEG.) The equivalent of one fully interleaved MCU row of
  339. subsampled data is processed per call, even when the source JPEG file is
  340. noninterleaved.
  341. * Entropy decoding: Read coded data from the data source module and perform
  342. Huffman or arithmetic entropy decoding. Works on one MCU per call.
  343. For progressive JPEG decoding, the coefficient controller supplies the prior
  344. coefficients of each MCU (initially all zeroes), which the entropy decoder
  345. modifies in each scan.
  346. * Dequantization and inverse DCT: like it says. Note that the coefficients
  347. buffered by the coefficient controller have NOT been dequantized; we
  348. merge dequantization and inverse DCT into a single step for speed reasons.
  349. When scaled-down output is asked for, simplified DCT algorithms may be used
  350. that emit fewer samples per DCT block, not the full 8x8. Works on one DCT
  351. block at a time.
  352. * Postprocessing controller: buffer controller for the color quantization
  353. input buffer, when quantization is in use. (Without quantization, this
  354. controller just calls the upsampler.) For two-pass quantization, this
  355. controller is responsible for buffering the full-image data.
  356. * Upsampling: restores chroma components to full size. (May support more
  357. general output rescaling, too. Note that if undersized DCT outputs have
  358. been emitted by the DCT module, this module must adjust so that properly
  359. sized outputs are created.) Works on one row group at a time. This module
  360. also calls the color conversion module, so its top level is effectively a
  361. buffer controller for the upsampling->color conversion buffer. However, in
  362. all but the highest-quality operating modes, upsampling and color
  363. conversion are likely to be merged into a single step.
  364. * Colorspace conversion: convert from JPEG color space to output color space,
  365. and change data layout from separate component planes to pixel-interleaved.
  366. Works on one pixel row at a time.
  367. * Color quantization: reduce the data to colormapped form, using either an
  368. externally specified colormap or an internally generated one. This module
  369. is not used for full-color output. Works on one pixel row at a time; may
  370. require two passes to generate a color map. Note that the output will
  371. always be a single component representing colormap indexes. In the current
  372. design, the output values are JSAMPLEs, so an 8-bit compilation cannot
  373. quantize to more than 256 colors. This is unlikely to be a problem in
  374. practice.
  375. * Color reduction: this module handles color precision reduction, e.g.,
  376. generating 15-bit color (5 bits/primary) from JPEG's 24-bit output.
  377. Not quite clear yet how this should be handled... should we merge it with
  378. colorspace conversion???
  379. Note that some high-speed operating modes might condense the entire
  380. postprocessing sequence to a single module (upsample, color convert, and
  381. quantize in one step).
  382. In addition to the above objects, the decompression library includes these
  383. objects:
  384. * Master control: determines the number of passes required, controls overall
  385. and per-pass initialization of the other modules. This is subdivided into
  386. input and output control: jdinput.c controls only input-side processing,
  387. while jdmaster.c handles overall initialization and output-side control.
  388. * Marker reading: decodes JPEG markers (except for RSTn).
  389. * Data source manager: supplies the input JPEG datastream. The source
  390. manager supplied with the library knows how to read from a stdio stream
  391. or from a memory buffer; for other behaviors, the surrounding application
  392. may provide its own source manager.
  393. * Memory manager: same as for compression library.
  394. * Error handler: same as for compression library.
  395. * Progress monitor: same as for compression library.
  396. As with compression, the data source manager, error handler, and progress
  397. monitor are candidates for replacement by a surrounding application.
  398. *** Decompression input and output separation ***
  399. To support efficient incremental display of progressive JPEG files, the
  400. decompressor is divided into two sections that can run independently:
  401. 1. Data input includes marker parsing, entropy decoding, and input into the
  402. coefficient controller's DCT coefficient buffer. Note that this
  403. processing is relatively cheap and fast.
  404. 2. Data output reads from the DCT coefficient buffer and performs the IDCT
  405. and all postprocessing steps.
  406. For a progressive JPEG file, the data input processing is allowed to get
  407. arbitrarily far ahead of the data output processing. (This occurs only
  408. if the application calls jpeg_consume_input(); otherwise input and output
  409. run in lockstep, since the input section is called only when the output
  410. section needs more data.) In this way the application can avoid making
  411. extra display passes when data is arriving faster than the display pass
  412. can run. Furthermore, it is possible to abort an output pass without
  413. losing anything, since the coefficient buffer is read-only as far as the
  414. output section is concerned. See libjpeg.txt for more detail.
  415. A full-image coefficient array is only created if the JPEG file has multiple
  416. scans (or if the application specifies buffered-image mode anyway). When
  417. reading a single-scan file, the coefficient controller normally creates only
  418. a one-MCU buffer, so input and output processing must run in lockstep in this
  419. case. jpeg_consume_input() is effectively a no-op in this situation.
  420. The main impact of dividing the decompressor in this fashion is that we must
  421. be very careful with shared variables in the cinfo data structure. Each
  422. variable that can change during the course of decompression must be
  423. classified as belonging to data input or data output, and each section must
  424. look only at its own variables. For example, the data output section may not
  425. depend on any of the variables that describe the current scan in the JPEG
  426. file, because these may change as the data input section advances into a new
  427. scan.
  428. The progress monitor is (somewhat arbitrarily) defined to treat input of the
  429. file as one pass when buffered-image mode is not used, and to ignore data
  430. input work completely when buffered-image mode is used. Note that the
  431. library has no reliable way to predict the number of passes when dealing
  432. with a progressive JPEG file, nor can it predict the number of output passes
  433. in buffered-image mode. So the work estimate is inherently bogus anyway.
  434. No comparable division is currently made in the compression library, because
  435. there isn't any real need for it.
  436. *** Data formats ***
  437. Arrays of pixel sample values use the following data structure:
  438. typedef something JSAMPLE; a pixel component value, 0..MAXJSAMPLE
  439. typedef JSAMPLE *JSAMPROW; ptr to a row of samples
  440. typedef JSAMPROW *JSAMPARRAY; ptr to a list of rows
  441. typedef JSAMPARRAY *JSAMPIMAGE; ptr to a list of color-component arrays
  442. The basic element type JSAMPLE will typically be one of unsigned char,
  443. (signed) char, or short. Short will be used if samples wider than 8 bits are
  444. to be supported (this is a compile-time option). Otherwise, unsigned char is
  445. used if possible. If the compiler only supports signed chars, then it is
  446. necessary to mask off the value when reading. Thus, all reads of JSAMPLE
  447. values must be coded as "GETJSAMPLE(value)", where the macro will be defined
  448. as "((value) & 0xFF)" on signed-char machines and "((int) (value))" elsewhere.
  449. With these conventions, JSAMPLE values can be assumed to be >= 0. This helps
  450. simplify correct rounding during downsampling, etc. The JPEG standard's
  451. specification that sample values run from -128..127 is accommodated by
  452. subtracting 128 from the sample value in the DCT step. Similarly, during
  453. decompression the output of the IDCT step will be immediately shifted back to
  454. 0..255. (NB: different values are required when 12-bit samples are in use.
  455. The code is written in terms of MAXJSAMPLE and CENTERJSAMPLE, which will be
  456. defined as 255 and 128 respectively in an 8-bit implementation, and as 4095
  457. and 2048 in a 12-bit implementation.)
  458. We use a pointer per row, rather than a two-dimensional JSAMPLE array. This
  459. choice costs only a small amount of memory and has several benefits:
  460. * Code using the data structure doesn't need to know the allocated width of
  461. the rows. This simplifies edge expansion/compression, since we can work
  462. in an array that's wider than the logical picture width.
  463. * Indexing doesn't require multiplication; this is a performance win on many
  464. machines.
  465. * Arrays with more than 64K total elements can be supported even on machines
  466. where malloc() cannot allocate chunks larger than 64K.
  467. * The rows forming a component array may be allocated at different times
  468. without extra copying. This trick allows some speedups in smoothing steps
  469. that need access to the previous and next rows.
  470. Note that each color component is stored in a separate array; we don't use the
  471. traditional layout in which the components of a pixel are stored together.
  472. This simplifies coding of modules that work on each component independently,
  473. because they don't need to know how many components there are. Furthermore,
  474. we can read or write each component to a temporary file independently, which
  475. is helpful when dealing with noninterleaved JPEG files.
  476. In general, a specific sample value is accessed by code such as
  477. GETJSAMPLE(image[colorcomponent][row][col])
  478. where col is measured from the image left edge, but row is measured from the
  479. first sample row currently in memory. Either of the first two indexings can
  480. be precomputed by copying the relevant pointer.
  481. Since most image-processing applications prefer to work on images in which
  482. the components of a pixel are stored together, the data passed to or from the
  483. surrounding application uses the traditional convention: a single pixel is
  484. represented by N consecutive JSAMPLE values, and an image row is an array of
  485. (# of color components)*(image width) JSAMPLEs. One or more rows of data can
  486. be represented by a pointer of type JSAMPARRAY in this scheme. This scheme is
  487. converted to component-wise storage inside the JPEG library. (Applications
  488. that want to skip JPEG preprocessing or postprocessing will have to contend
  489. with component-wise storage.)
  490. Arrays of DCT-coefficient values use the following data structure:
  491. typedef short JCOEF; a 16-bit signed integer
  492. typedef JCOEF JBLOCK[DCTSIZE2]; an 8x8 block of coefficients
  493. typedef JBLOCK *JBLOCKROW; ptr to one horizontal row of 8x8 blocks
  494. typedef JBLOCKROW *JBLOCKARRAY; ptr to a list of such rows
  495. typedef JBLOCKARRAY *JBLOCKIMAGE; ptr to a list of color component arrays
  496. The underlying type is at least a 16-bit signed integer; while "short" is big
  497. enough on all machines of interest, on some machines it is preferable to use
  498. "int" for speed reasons, despite the storage cost. Coefficients are grouped
  499. into 8x8 blocks (but we always use #defines DCTSIZE and DCTSIZE2 rather than
  500. "8" and "64").
  501. The contents of a coefficient block may be in either "natural" or zigzagged
  502. order, and may be true values or divided by the quantization coefficients,
  503. depending on where the block is in the processing pipeline. In the current
  504. library, coefficient blocks are kept in natural order everywhere; the entropy
  505. codecs zigzag or dezigzag the data as it is written or read. The blocks
  506. contain quantized coefficients everywhere outside the DCT/IDCT subsystems.
  507. (This latter decision may need to be revisited to support variable
  508. quantization a la JPEG Part 3.)
  509. Notice that the allocation unit is now a row of 8x8 blocks, corresponding to
  510. eight rows of samples. Otherwise the structure is much the same as for
  511. samples, and for the same reasons.
  512. *** Suspendable processing ***
  513. In some applications it is desirable to use the JPEG library as an
  514. incremental, memory-to-memory filter. In this situation the data source or
  515. destination may be a limited-size buffer, and we can't rely on being able to
  516. empty or refill the buffer at arbitrary times. Instead the application would
  517. like to have control return from the library at buffer overflow/underrun, and
  518. then resume compression or decompression at a later time.
  519. This scenario is supported for simple cases. (For anything more complex, we
  520. recommend that the application "bite the bullet" and develop real multitasking
  521. capability.) The libjpeg.txt file goes into more detail about the usage and
  522. limitations of this capability; here we address the implications for library
  523. structure.
  524. The essence of the problem is that the entropy codec (coder or decoder) must
  525. be prepared to stop at arbitrary times. In turn, the controllers that call
  526. the entropy codec must be able to stop before having produced or consumed all
  527. the data that they normally would handle in one call. That part is reasonably
  528. straightforward: we make the controller call interfaces include "progress
  529. counters" which indicate the number of data chunks successfully processed, and
  530. we require callers to test the counter rather than just assume all of the data
  531. was processed.
  532. Rather than trying to restart at an arbitrary point, the current Huffman
  533. codecs are designed to restart at the beginning of the current MCU after a
  534. suspension due to buffer overflow/underrun. At the start of each call, the
  535. codec's internal state is loaded from permanent storage (in the JPEG object
  536. structures) into local variables. On successful completion of the MCU, the
  537. permanent state is updated. (This copying is not very expensive, and may even
  538. lead to *improved* performance if the local variables can be registerized.)
  539. If a suspension occurs, the codec simply returns without updating the state,
  540. thus effectively reverting to the start of the MCU. Note that this implies
  541. leaving some data unprocessed in the source/destination buffer (ie, the
  542. compressed partial MCU). The data source/destination module interfaces are
  543. specified so as to make this possible. This also implies that the data buffer
  544. must be large enough to hold a worst-case compressed MCU; a couple thousand
  545. bytes should be enough.
  546. In a successive-approximation AC refinement scan, the progressive Huffman
  547. decoder has to be able to undo assignments of newly nonzero coefficients if it
  548. suspends before the MCU is complete, since decoding requires distinguishing
  549. previously-zero and previously-nonzero coefficients. This is a bit tedious
  550. but probably won't have much effect on performance. Other variants of Huffman
  551. decoding need not worry about this, since they will just store the same values
  552. again if forced to repeat the MCU.
  553. This approach would probably not work for an arithmetic codec, since its
  554. modifiable state is quite large and couldn't be copied cheaply. Instead it
  555. would have to suspend and resume exactly at the point of the buffer end.
  556. The JPEG marker reader is designed to cope with suspension at an arbitrary
  557. point. It does so by backing up to the start of the marker parameter segment,
  558. so the data buffer must be big enough to hold the largest marker of interest.
  559. Again, a couple KB should be adequate. (A special "skip" convention is used
  560. to bypass COM and APPn markers, so these can be larger than the buffer size
  561. without causing problems; otherwise a 64K buffer would be needed in the worst
  562. case.)
  563. The JPEG marker writer currently does *not* cope with suspension.
  564. We feel that this is not necessary; it is much easier simply to require
  565. the application to ensure there is enough buffer space before starting. (An
  566. empty 2K buffer is more than sufficient for the header markers; and ensuring
  567. there are a dozen or two bytes available before calling jpeg_finish_compress()
  568. will suffice for the trailer.) This would not work for writing multi-scan
  569. JPEG files, but we simply do not intend to support that capability with
  570. suspension.
  571. *** Memory manager services ***
  572. The JPEG library's memory manager controls allocation and deallocation of
  573. memory, and it manages large "virtual" data arrays on machines where the
  574. operating system does not provide virtual memory. Note that the same
  575. memory manager serves both compression and decompression operations.
  576. In all cases, allocated objects are tied to a particular compression or
  577. decompression master record, and they will be released when that master
  578. record is destroyed.
  579. The memory manager does not provide explicit deallocation of objects.
  580. Instead, objects are created in "pools" of free storage, and a whole pool
  581. can be freed at once. This approach helps prevent storage-leak bugs, and
  582. it speeds up operations whenever malloc/free are slow (as they often are).
  583. The pools can be regarded as lifetime identifiers for objects. Two
  584. pools/lifetimes are defined:
  585. * JPOOL_PERMANENT lasts until master record is destroyed
  586. * JPOOL_IMAGE lasts until done with image (JPEG datastream)
  587. Permanent lifetime is used for parameters and tables that should be carried
  588. across from one datastream to another; this includes all application-visible
  589. parameters. Image lifetime is used for everything else. (A third lifetime,
  590. JPOOL_PASS = one processing pass, was originally planned. However it was
  591. dropped as not being worthwhile. The actual usage patterns are such that the
  592. peak memory usage would be about the same anyway; and having per-pass storage
  593. substantially complicates the virtual memory allocation rules --- see below.)
  594. The memory manager deals with three kinds of object:
  595. 1. "Small" objects. Typically these require no more than 10K-20K total.
  596. 2. "Large" objects. These may require tens to hundreds of K depending on
  597. image size. Semantically they behave the same as small objects, but we
  598. distinguish them because pool allocation heuristics may differ for large and
  599. small objects (historically, large objects were also referenced by far
  600. pointers on MS-DOS machines.) Note that individual "large" objects cannot
  601. exceed the size allowed by type size_t, which may be 64K or less on some
  602. machines.
  603. 3. "Virtual" objects. These are large 2-D arrays of JSAMPLEs or JBLOCKs
  604. (typically large enough for the entire image being processed). The
  605. memory manager provides stripwise access to these arrays. On machines
  606. without virtual memory, the rest of the array may be swapped out to a
  607. temporary file.
  608. (Note: JSAMPARRAY and JBLOCKARRAY data structures are a combination of large
  609. objects for the data proper and small objects for the row pointers. For
  610. convenience and speed, the memory manager provides single routines to create
  611. these structures. Similarly, virtual arrays include a small control block
  612. and a JSAMPARRAY or JBLOCKARRAY working buffer, all created with one call.)
  613. In the present implementation, virtual arrays are only permitted to have image
  614. lifespan. (Permanent lifespan would not be reasonable, and pass lifespan is
  615. not very useful since a virtual array's raison d'etre is to store data for
  616. multiple passes through the image.) We also expect that only "small" objects
  617. will be given permanent lifespan, though this restriction is not required by
  618. the memory manager.
  619. In a non-virtual-memory machine, some performance benefit can be gained by
  620. making the in-memory buffers for virtual arrays be as large as possible.
  621. (For small images, the buffers might fit entirely in memory, so blind
  622. swapping would be very wasteful.) The memory manager will adjust the height
  623. of the buffers to fit within a prespecified maximum memory usage. In order
  624. to do this in a reasonably optimal fashion, the manager needs to allocate all
  625. of the virtual arrays at once. Therefore, there isn't a one-step allocation
  626. routine for virtual arrays; instead, there is a "request" routine that simply
  627. allocates the control block, and a "realize" routine (called just once) that
  628. determines space allocation and creates all of the actual buffers. The
  629. realize routine must allow for space occupied by non-virtual large objects.
  630. (We don't bother to factor in the space needed for small objects, on the
  631. grounds that it isn't worth the trouble.)
  632. To support all this, we establish the following protocol for doing business
  633. with the memory manager:
  634. 1. Modules must request virtual arrays (which may have only image lifespan)
  635. during the initial setup phase, i.e., in their jinit_xxx routines.
  636. 2. All "large" objects (including JSAMPARRAYs and JBLOCKARRAYs) must also be
  637. allocated during initial setup.
  638. 3. realize_virt_arrays will be called at the completion of initial setup.
  639. The above conventions ensure that sufficient information is available
  640. for it to choose a good size for virtual array buffers.
  641. Small objects of any lifespan may be allocated at any time. We expect that
  642. the total space used for small objects will be small enough to be negligible
  643. in the realize_virt_arrays computation.
  644. In a virtual-memory machine, we simply pretend that the available space is
  645. infinite, thus causing realize_virt_arrays to decide that it can allocate all
  646. the virtual arrays as full-size in-memory buffers. The overhead of the
  647. virtual-array access protocol is very small when no swapping occurs.
  648. A virtual array can be specified to be "pre-zeroed"; when this flag is set,
  649. never-yet-written sections of the array are set to zero before being made
  650. available to the caller. If this flag is not set, never-written sections
  651. of the array contain garbage. (This feature exists primarily because the
  652. equivalent logic would otherwise be needed in jdcoefct.c for progressive
  653. JPEG mode; we may as well make it available for possible other uses.)
  654. The first write pass on a virtual array is required to occur in top-to-bottom
  655. order; read passes, as well as any write passes after the first one, may
  656. access the array in any order. This restriction exists partly to simplify
  657. the virtual array control logic, and partly because some file systems may not
  658. support seeking beyond the current end-of-file in a temporary file. The main
  659. implication of this restriction is that rearrangement of rows (such as
  660. converting top-to-bottom data order to bottom-to-top) must be handled while
  661. reading data out of the virtual array, not while putting it in.
  662. *** Memory manager internal structure ***
  663. To isolate system dependencies as much as possible, we have broken the
  664. memory manager into two parts. There is a reasonably system-independent
  665. "front end" (jmemmgr.c) and a "back end" that contains only the code
  666. likely to change across systems. All of the memory management methods
  667. outlined above are implemented by the front end. The back end provides
  668. the following routines for use by the front end (none of these routines
  669. are known to the rest of the JPEG code):
  670. jpeg_mem_init, jpeg_mem_term system-dependent initialization/shutdown
  671. jpeg_get_small, jpeg_free_small interface to malloc and free library routines
  672. (or their equivalents)
  673. jpeg_get_large, jpeg_free_large historically was used to interface with
  674. FAR malloc/free on MS-DOS machines; now the
  675. same as jpeg_get_small/jpeg_free_small
  676. jpeg_mem_available estimate available memory
  677. jpeg_open_backing_store create a backing-store object
  678. read_backing_store, manipulate a backing-store object
  679. write_backing_store,
  680. close_backing_store
  681. On some systems there will be more than one type of backing-store object.
  682. jpeg_open_backing_store is responsible for choosing how to implement a given
  683. object. The read/write/close routines are method pointers in the structure
  684. that describes a given object; this lets them be different for different object
  685. types.
  686. It may be necessary to ensure that backing store objects are explicitly
  687. released upon abnormal program termination. To support this, we will expect
  688. the main program or surrounding application to arrange to call self_destruct
  689. (typically via jpeg_destroy) upon abnormal termination. This may require a
  690. SIGINT signal handler or equivalent. We don't want to have the back end module
  691. install its own signal handler, because that would pre-empt the surrounding
  692. application's ability to control signal handling.
  693. The IJG distribution includes several memory manager back end implementations.
  694. Usually the same back end should be suitable for all applications on a given
  695. system, but it is possible for an application to supply its own back end at
  696. need.
  697. *** Implications of DNL marker ***
  698. Some JPEG files may use a DNL marker to postpone definition of the image
  699. height (this would be useful for a fax-like scanner's output, for instance).
  700. In these files the SOF marker claims the image height is 0, and you only
  701. find out the true image height at the end of the first scan.
  702. We could read these files as follows:
  703. 1. Upon seeing zero image height, replace it by 65535 (the maximum allowed).
  704. 2. When the DNL is found, update the image height in the global image
  705. descriptor.
  706. This implies that control modules must avoid making copies of the image
  707. height, and must re-test for termination after each MCU row. This would
  708. be easy enough to do.
  709. In cases where image-size data structures are allocated, this approach will
  710. result in very inefficient use of virtual memory or much-larger-than-necessary
  711. temporary files. This seems acceptable for something that probably won't be a
  712. mainstream usage. People might have to forgo use of memory-hogging options
  713. (such as two-pass color quantization or noninterleaved JPEG files) if they
  714. want efficient conversion of such files. (One could improve efficiency by
  715. demanding a user-supplied upper bound for the height, less than 65536; in most
  716. cases it could be much less.)
  717. The standard also permits the SOF marker to overestimate the image height,
  718. with a DNL to give the true, smaller height at the end of the first scan.
  719. This would solve the space problems if the overestimate wasn't too great.
  720. However, it implies that you don't even know whether DNL will be used.
  721. This leads to a couple of very serious objections:
  722. 1. Testing for a DNL marker must occur in the inner loop of the decompressor's
  723. Huffman decoder; this implies a speed penalty whether the feature is used
  724. or not.
  725. 2. There is no way to hide the last-minute change in image height from an
  726. application using the decoder. Thus *every* application using the IJG
  727. library would suffer a complexity penalty whether it cared about DNL or
  728. not.
  729. We currently do not support DNL because of these problems.
  730. A different approach is to insist that DNL-using files be preprocessed by a
  731. separate program that reads ahead to the DNL, then goes back and fixes the SOF
  732. marker. This is a much simpler solution and is probably far more efficient.
  733. Even if one wants piped input, buffering the first scan of the JPEG file needs
  734. a lot smaller temp file than is implied by the maximum-height method. For
  735. this approach we'd simply treat DNL as a no-op in the decompressor (at most,
  736. check that it matches the SOF image height).
  737. We will not worry about making the compressor capable of outputting DNL.
  738. Something similar to the first scheme above could be applied if anyone ever
  739. wants to make that work.