USING THE IJG JPEG LIBRARY
This file was part of the Independent JPEG Group's software:
-Copyright (C) 1994-2011, Thomas G. Lane, Guido Vollbeding.
+Copyright (C) 1994-2013, Thomas G. Lane, Guido Vollbeding.
libjpeg-turbo Modifications:
-Copyright (C) 2010, 2014, D. R. Commander.
-For conditions of distribution and use, see the accompanying README file.
+Copyright (C) 2010, 2014-2018, 2020, 2022, D. R. Commander.
+Copyright (C) 2015, Google, Inc.
+For conditions of distribution and use, see the accompanying README.ijg file.
This file describes how to use the IJG JPEG library within an application
program. Read it if you want to write a program that uses the library.
-The file example.c provides heavily commented skeleton code for calling the
+The file example.txt provides heavily commented skeleton code for calling the
JPEG library. Also see jpeglib.h (the include file to be used by application
programs) for full details about data structures and function parameter lists.
The library source code, of course, is the ultimate reference.
Data formats
Compression details
Decompression details
+ Partial image decompression
Mechanics of usage: include files, linking, etc
Advanced features:
Compression parameter selection
Buffered-image mode
Abbreviated datastreams and multiple images
Special markers
+ ICC profiles
Raw (downsampled) image data
Really raw data: DCT coefficients
Progress monitoring
feed in a colormapped image by expanding it to full-color format. However
JPEG often doesn't work very well with source data that has been colormapped,
because of dithering noise. This is discussed in more detail in the JPEG FAQ
-and the other references mentioned in the README file.
+and the other references mentioned in the README.ijg file.
Pixels are stored by scanlines, with each scanline running from left to
right. The component values for each pixel are adjacent in the row; for
If you use the standard destination module, you must open the target stdio
stream beforehand. Typical code for this step looks like:
- FILE * outfile;
+ FILE *outfile;
...
if ((outfile = fopen(filename, "wb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
just one or a few scanlines at a time. The expected format for the passed
data is discussed under "Data formats", above.
-Image data should be written in top-to-bottom scanline order. The JPEG spec
-contains some weasel wording about how top and bottom are application-defined
-terms (a curious interpretation of the English language...) but if you want
-your files to be compatible with everyone else's, you WILL use top-to-bottom
-order. If the source data must be read in bottom-to-top order, you can use
-the JPEG library's virtual array mechanism to invert the data efficiently.
-Examples of this can be found in the sample application cjpeg.
+Image data should be written in top-to-bottom scanline order.
+Rec. ITU-T T.81 | ISO/IEC 10918-1 says, "Applications determine which edges of
+a source image are defined as top, bottom, left, and right." However, if you
+want your files to be compatible with everyone else's, then top-to-bottom order
+must be used. If the source data must be read in bottom-to-top order, then you
+can use the JPEG library's virtual array mechanism to invert the data
+efficiently. Examples of this can be found in the sample application cjpeg.
The library maintains a count of the number of scanlines written so far
in the next_scanline field of the JPEG object. Usually you can just use
"while (cinfo.next_scanline < cinfo.image_height)".
Code for this step depends heavily on the way that you store the source data.
-example.c shows the following code for the case of a full-size 2-D source
+example.txt shows the following code for the case of a full-size 2-D source
array containing 3-byte RGB pixels:
JSAMPROW row_pointer[1]; /* pointer to a single row */
row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */
while (cinfo.next_scanline < cinfo.image_height) {
- row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
+ row_pointer[0] = &image_buffer[cinfo.next_scanline * row_stride];
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
If you use the standard source module, you must open the source stdio stream
beforehand. Typical code for this step looks like:
- FILE * infile;
+ FILE *infile;
...
if ((infile = fopen(filename, "rb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
The previous discussion of aborting compression cycles applies here too.
+Partial image decompression
+---------------------------
+
+Partial image decompression is convenient for performance-critical applications
+that wish to view only a portion of a large JPEG image without decompressing
+the whole thing. It it also useful in memory-constrained environments (such as
+on mobile devices.) This library provides the following functions to support
+partial image decompression:
+
+1. Skipping rows when decompressing
+
+ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines);
+
+This function provides application programmers with the ability to skip over
+multiple rows in the JPEG image.
+
+Suspending data sources are not supported by this function. Calling
+jpeg_skip_scanlines() with a suspending data source will result in undefined
+behavior. Two-pass color quantization is also not supported by this function.
+Calling jpeg_skip_scanlines() with two-pass color quantization enabled will
+result in an error.
+
+jpeg_skip_scanlines() will not allow skipping past the bottom of the image. If
+the value of num_lines is large enough to skip past the bottom of the image,
+then the function will skip to the end of the image instead.
+
+If the value of num_lines is valid, then jpeg_skip_scanlines() will always
+skip all of the input rows requested. There is no need to inspect the return
+value of the function in that case.
+
+Best results will be achieved by calling jpeg_skip_scanlines() for large chunks
+of rows. The function should be viewed as a way to quickly jump to a
+particular vertical offset in the JPEG image in order to decode a subset of the
+image. Used in this manner, it will provide significant performance
+improvements.
+
+Calling jpeg_skip_scanlines() for small values of num_lines has several
+potential drawbacks:
+ 1) JPEG decompression occurs in blocks, so if jpeg_skip_scanlines() is
+ called from the middle of a decompression block, then it is likely that
+ much of the decompression work has already been done for the first
+ couple of rows that need to be skipped.
+ 2) When this function returns, it must leave the decompressor in a state
+ such that it is ready to read the next line. This may involve
+ decompressing a block that must be partially skipped.
+These issues are especially tricky for cases in which upsampling requires
+context rows. In the worst case, jpeg_skip_scanlines() will perform similarly
+to jpeg_read_scanlines() (since it will actually call jpeg_read_scanlines().)
+
+2. Decompressing partial scanlines
+
+ jpeg_crop_scanline (j_decompress_ptr cinfo, JDIMENSION *xoffset,
+ JDIMENSION *width)
+
+This function provides application programmers with the ability to decompress
+only a portion of each row in the JPEG image. It must be called after
+jpeg_start_decompress() and before any calls to jpeg_read_scanlines() or
+jpeg_skip_scanlines().
+
+If xoffset and width do not form a valid subset of the image row, then this
+function will generate an error. Note that if the output image is scaled, then
+xoffset and width are relative to the scaled image dimensions.
+
+xoffset and width are passed by reference because xoffset must fall on an iMCU
+boundary. If it doesn't, then it will be moved left to the nearest iMCU
+boundary, and width will be increased accordingly. If the calling program does
+not like the adjusted values of xoffset and width, then it can call
+jpeg_crop_scanline() again with new values (for instance, if it wants to move
+xoffset to the nearest iMCU boundary to the right instead of to the left.)
+
+After calling this function, cinfo->output_width will be set to the adjusted
+width. This value should be used when allocating an output buffer to pass to
+jpeg_read_scanlines().
+
+The output image from a partial-width decompression will be identical to the
+corresponding image region from a full decode, with one exception: The "fancy"
+(smooth) h2v2 (4:2:0) and h2v1 (4:2:2) upsampling algorithms fill in the
+missing chroma components by averaging the chroma components from neighboring
+pixels, except on the right and left edges of the image (where there are no
+neighboring pixels.) When performing a partial-width decompression, these
+"fancy" upsampling algorithms may treat the left and right edges of the partial
+image region as if they are the left and right edges of the image, meaning that
+the upsampling algorithm may be simplified. The result is that the pixels on
+the left or right edge of the partial image may not be exactly identical to the
+corresponding pixels in the original image.
+
+
Mechanics of usage: include files, linking, etc
-----------------------------------------------
machines) and reference it at your link step. If you use only half of the
library (only compression or only decompression), only that much code will be
included from the library, unless your linker is hopelessly brain-damaged.
-The supplied makefiles build libjpeg.a automatically (see install.txt).
-
-While you can build the JPEG library as a shared library if the whim strikes
-you, we don't really recommend it. The trouble with shared libraries is that
-at some point you'll probably try to substitute a new version of the library
-without recompiling the calling applications. That generally doesn't work
-because the parameter struct declarations usually change with each new
-version. In other words, the library's API is *not* guaranteed binary
-compatible across versions; we only try to ensure source-code compatibility.
-(In hindsight, it might have been smarter to hide the parameter structs from
-applications and introduce a ton of access functions instead. Too late now,
-however.)
+The supplied build system builds libjpeg.a automatically.
It may be worth pointing out that the core JPEG library does not actually
require the stdio library: only the default source/destination managers and
compression, as well as the "helper" routines provided to assist in this
task. Proper setting of some parameters requires detailed understanding
of the JPEG standard; if you don't know what a parameter is for, it's best
-not to mess with it! See REFERENCES in the README file for pointers to
+not to mess with it! See REFERENCES in the README.ijg file for pointers to
more info about JPEG.
It's a good idea to call jpeg_set_defaults() first, even if you plan to set
jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
boolean force_baseline)
Same as jpeg_set_quality() except that the generated tables are the
- sample tables given in the JPEC spec section K.1, multiplied by the
+ sample tables given in Annex K (Clause K.1) of
+ Rec. ITU-T T.81 (1992) | ISO/IEC 10918-1:1994, multiplied by the
specified scale factor (which is expressed as a percentage; thus
scale_factor = 100 reproduces the spec's tables). Note that larger
scale factors give lower quality. This entry point is useful for
Compression parameters (cinfo fields) include:
+boolean arith_code
+ If TRUE, use arithmetic coding.
+ If FALSE, use Huffman coding.
+
J_DCT_METHOD dct_method
Selects the algorithm used for the DCT step. Choices are:
- JDCT_ISLOW: slow but accurate integer algorithm
- JDCT_IFAST: faster, less accurate integer method
- JDCT_FLOAT: floating-point method
+ JDCT_ISLOW: accurate integer method
+ JDCT_IFAST: less accurate integer method [legacy feature]
+ JDCT_FLOAT: floating-point method [legacy feature]
JDCT_DEFAULT: default method (normally JDCT_ISLOW)
JDCT_FASTEST: fastest method (normally JDCT_IFAST)
- In libjpeg-turbo, JDCT_IFAST is generally about 5-15% faster than
- JDCT_ISLOW when using the x86/x86-64 SIMD extensions (results may vary
- with other SIMD implementations, or when using libjpeg-turbo without
- SIMD extensions.) For quality levels of 90 and below, there should be
- little or no perceptible difference between the two algorithms. For
- quality levels above 90, however, the difference between JDCT_IFAST and
+ When the Independent JPEG Group's software was first released in 1991,
+ the compression time for a 1-megapixel JPEG image on a mainstream PC
+ was measured in minutes. Thus, JDCT_IFAST provided noticeable
+ performance benefits. On modern CPUs running libjpeg-turbo, however,
+ the compression time for a 1-megapixel JPEG image is measured in
+ milliseconds, and thus the performance benefits of JDCT_IFAST are much
+ less noticeable. On modern x86/x86-64 CPUs that support AVX2
+ instructions, JDCT_IFAST and JDCT_ISLOW have similar performance. On
+ other types of CPUs, JDCT_IFAST is generally about 5-15% faster than
+ JDCT_ISLOW.
+
+ For quality levels of 90 and below, there should be little or no
+ perceptible quality difference between the two algorithms. For quality
+ levels above 90, however, the difference between JDCT_IFAST and
JDCT_ISLOW becomes more pronounced. With quality=97, for instance,
- JDCT_IFAST incurs generally about a 1-3 dB loss (in PSNR) relative to
+ JDCT_IFAST incurs generally about a 1-3 dB loss in PSNR relative to
JDCT_ISLOW, but this can be larger for some images. Do not use
JDCT_IFAST with quality levels above 97. The algorithm often
degenerates at quality=98 and above and can actually produce a more
lossy image than if lower quality levels had been used. Also, in
libjpeg-turbo, JDCT_IFAST is not fully accelerated for quality levels
- above 97, so it will be slower than JDCT_ISLOW. JDCT_FLOAT is mainly a
- legacy feature. It does not produce significantly more accurate
- results than the ISLOW method, and it is much slower. The FLOAT method
- may also give different results on different machines due to varying
- roundoff behavior, whereas the integer methods should give the same
- results on all machines.
+ above 97, so it will be slower than JDCT_ISLOW.
+
+ JDCT_FLOAT does not produce significantly more accurate results than
+ JDCT_ISLOW, and it is much slower. JDCT_FLOAT may also give different
+ results on different machines due to varying roundoff behavior, whereas
+ the integer methods should give the same results on all machines.
J_COLOR_SPACE jpeg_color_space
int num_components
If you use restarts, you may want to use larger intervals in those
cases.
-const jpeg_scan_info * scan_info
+const jpeg_scan_info *scan_info
int num_scans
By default, scan_info is NULL; this causes the compressor to write a
single-scan sequential JPEG file. If not NULL, scan_info points to
default behavior ensures that the JPEG file's color space can be
recognized by the decoder.
-JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]
+JQUANT_TBL *quant_tbl_ptrs[NUM_QUANT_TBLS]
Pointers to coefficient quantization tables, one per table slot,
or NULL if no table is defined for a slot. Usually these should
be set via one of the above helper routines; jpeg_add_quant_table()
cinfo->comp_info[0].v_samp_factor = 1;
cinfo->comp_info[0].h_samp_factor = 1;
-JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]
-JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]
+JHUFF_TBL *dc_huff_tbl_ptrs[NUM_HUFF_TBLS]
+JHUFF_TBL *ac_huff_tbl_ptrs[NUM_HUFF_TBLS]
Pointers to Huffman coding tables, one per table slot, or NULL if
no table is defined for a slot. Slots 0 and 1 are filled with the
JPEG sample tables by jpeg_set_defaults(). If you need to allocate
J_DCT_METHOD dct_method
Selects the algorithm used for the DCT step. Choices are:
- JDCT_ISLOW: slow but accurate integer algorithm
- JDCT_IFAST: faster, less accurate integer method
- JDCT_FLOAT: floating-point method
+ JDCT_ISLOW: accurate integer method
+ JDCT_IFAST: less accurate integer method [legacy feature]
+ JDCT_FLOAT: floating-point method [legacy feature]
JDCT_DEFAULT: default method (normally JDCT_ISLOW)
JDCT_FASTEST: fastest method (normally JDCT_IFAST)
- In libjpeg-turbo, JDCT_IFAST is generally about 5-15% faster than
- JDCT_ISLOW when using the x86/x86-64 SIMD extensions (results may vary
- with other SIMD implementations, or when using libjpeg-turbo without
- SIMD extensions.) If the JPEG image was compressed using a quality
- level of 85 or below, then there should be little or no perceptible
- difference between the two algorithms. When decompressing images that
- were compressed using quality levels above 85, however, the difference
+ When the Independent JPEG Group's software was first released in 1991,
+ the decompression time for a 1-megapixel JPEG image on a mainstream PC
+ was measured in minutes. Thus, JDCT_IFAST provided noticeable
+ performance benefits. On modern CPUs running libjpeg-turbo, however,
+ the decompression time for a 1-megapixel JPEG image is measured in
+ milliseconds, and thus the performance benefits of JDCT_IFAST are much
+ less noticeable. On modern x86/x86-64 CPUs that support AVX2
+ instructions, JDCT_IFAST and JDCT_ISLOW have similar performance. On
+ other types of CPUs, JDCT_IFAST is generally about 5-15% faster than
+ JDCT_ISLOW.
+
+ If the JPEG image was compressed using a quality level of 85 or below,
+ then there should be little or no perceptible quality difference
+ between the two algorithms. When decompressing images that were
+ compressed using quality levels above 85, however, the difference
between JDCT_IFAST and JDCT_ISLOW becomes more pronounced. With images
compressed using quality=97, for instance, JDCT_IFAST incurs generally
- about a 4-6 dB loss (in PSNR) relative to JDCT_ISLOW, but this can be
+ about a 4-6 dB loss in PSNR relative to JDCT_ISLOW, but this can be
larger for some images. If you can avoid it, do not use JDCT_IFAST
when decompressing images that were compressed using quality levels
above 97. The algorithm often degenerates for such images and can
actually produce a more lossy output image than if the JPEG image had
- been compressed using lower quality levels. JDCT_FLOAT is mainly a
- legacy feature. It does not produce significantly more accurate
- results than the ISLOW method, and it is much slower. The FLOAT method
- may also give different results on different machines due to varying
- roundoff behavior, whereas the integer methods should give the same
- results on all machines.
+ been compressed using lower quality levels.
+
+ JDCT_FLOAT does not produce significantly more accurate results than
+ JDCT_ISLOW, and it is much slower. JDCT_FLOAT may also give different
+ results on different machines due to varying roundoff behavior, whereas
+ the integer methods should give the same results on all machines.
boolean do_fancy_upsampling
If TRUE, do careful upsampling of chroma components. If FALSE,
routines will cause a message to be printed on stderr, followed by exit().
You can supply your own error handling routines to override this behavior
and to control the treatment of nonfatal warnings and trace/debug messages.
-The file example.c illustrates the most common case, which is to have the
+The file example.txt illustrates the most common case, which is to have the
application regain control after an error rather than exiting.
The JPEG library never writes any message directly; it always goes through
only replacing some of the routines depending on the behavior you need.
This is accomplished by calling jpeg_std_error() as usual, but then overriding
some of the method pointers in the jpeg_error_mgr struct, as illustrated by
-example.c.
+example.txt.
All of the error handling routines will receive a pointer to the JPEG object
(a j_common_ptr which points to either a jpeg_compress_struct or a
handler. The most convenient way to do this is to embed either the JPEG
object or the jpeg_error_mgr struct in a larger structure that contains
additional fields; then casting the passed pointer provides access to the
-additional fields. Again, see example.c for one way to do it. (Beginning
+additional fields. Again, see example.txt for one way to do it. (Beginning
with IJG version 6b, there is also a void pointer "client_data" in each
JPEG object, which the application can also use to find related data.
The library does not touch client_data at all.)
somewhere other than stderr. Note that this method does not know
how to generate a message, only where to send it.
-format_message (j_common_ptr cinfo, char * buffer)
+format_message (j_common_ptr cinfo, char *buffer)
Constructs a readable error message string based on the error info
stored in cinfo->err. This method is called by output_message. Few
applications should need to override this method. One possible
A data destination manager struct contains a pointer and count defining the
next byte to write in the work buffer and the remaining free space:
- JOCTET * next_output_byte; /* => next byte to write in buffer */
+ JOCTET *next_output_byte; /* => next byte to write in buffer */
size_t free_in_buffer; /* # of byte spaces remaining in buffer */
The library increments the pointer and decrements the count until the buffer
defining the next byte to read from the work buffer and the number of bytes
remaining:
- const JOCTET * next_input_byte; /* => next byte to read from buffer */
+ const JOCTET *next_input_byte; /* => next byte to read from buffer */
size_t bytes_in_buffer; /* # of bytes remaining in buffer */
The library increments the pointer and decrements the count until the buffer
The simplest approach to displaying progressive images is to do one display
pass for each scan appearing in the input file. In this case the outer loop
condition is typically
- while (! jpeg_input_complete(&cinfo))
+ while (!jpeg_input_complete(&cinfo))
and the start-output call should read
jpeg_start_output(&cinfo, cinfo.input_scan_number);
The second parameter to jpeg_start_output() indicates which scan of the input
jpeg_start_output(&cinfo, cinfo.input_scan_number);
...
jpeg_finish_output()
- } while (! final_pass);
+ } while (!final_pass);
rather than quitting as soon as jpeg_input_complete() returns TRUE. This
arrangement makes it simple to use higher-quality decoding parameters
for the final pass. But if you don't want to use special parameters for
Also, see jpegtran.c for an example of using jpeg_save_markers.
+ICC profiles
+------------
+
+Two functions are provided for writing and reading International Color
+Consortium (ICC) device profiles embedded in JFIF JPEG image files:
+
+ void jpeg_write_icc_profile (j_compress_ptr cinfo,
+ const JOCTET *icc_data_ptr,
+ unsigned int icc_data_len);
+ boolean jpeg_read_icc_profile (j_decompress_ptr cinfo,
+ JOCTET **icc_data_ptr,
+ unsigned int *icc_data_len);
+
+The ICC has defined a standard for including such data in JPEG "APP2" markers.
+The aforementioned functions do not know anything about the internal structure
+of the ICC profile data; they just know how to embed the profile data into a
+JPEG file while writing it, or to extract the profile data from a JPEG file
+while reading it.
+
+jpeg_write_icc_profile() must be called after calling jpeg_start_compress() and
+before the first call to jpeg_write_scanlines() or jpeg_write_raw_data(). This
+ordering ensures that the APP2 marker(s) will appear after the SOI and JFIF or
+Adobe markers, but before all other data.
+
+jpeg_read_icc_profile() returns TRUE if an ICC profile was found and FALSE
+otherwise. If an ICC profile was found, then the function will allocate a
+memory region containing the profile and will return a pointer to that memory
+region in *icc_data_ptr, as well as the length of the region in *icc_data_len.
+This memory region is allocated by the library using malloc() and must be freed
+by the caller using free() when the memory region is no longer needed. Callers
+wishing to use jpeg_read_icc_profile() must call
+
+ jpeg_save_markers(cinfo, JPEG_APP0 + 2, 0xFFFF);
+
+prior to calling jpeg_read_header(). jpeg_read_icc_profile() can be called at
+any point between jpeg_read_header() and jpeg_finish_decompress().
+
+
Raw (downsampled) image data
----------------------------
jpeg_finish_compress, jpeg_finish_decompress, or jpeg_abort. You can call the
memory manager yourself to allocate structures that will automatically be
freed at these times. Typical code for this is
- ptr = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, size);
+ ptr = (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, size);
Use JPOOL_PERMANENT to get storage that lasts as long as the JPEG object.
Use alloc_large instead of alloc_small for anything bigger than a few Kbytes.
There are also alloc_sarray and alloc_barray routines that automatically
buffers. Such buffers are treated as "virtual arrays": only the current strip
need be in memory, and the rest can be swapped out to a temporary file.
-If you use the simplest memory manager back end (jmemnobs.c), then no
-temporary files are used; virtual arrays are simply malloc()'d. Images bigger
-than memory can be processed only if your system supports virtual memory.
-The other memory manager back ends support temporary files of various flavors
-and thus work in machines without virtual memory. They may also be useful on
-Unix machines if you need to process images that exceed available swap space.
-
When using temporary files, the library will make the in-memory buffers for
its virtual arrays just big enough to stay within a "maximum memory" setting.
Your application can set this limit by setting cinfo->mem->max_memory_to_use
it's too small to be worth worrying about; so a reasonable safety margin
should be left when setting max_memory_to_use.
+NOTE: Unless you develop your own memory manager back end, then temporary files
+will never be used. The back end provided in libjpeg-turbo (jmemnobs.c) simply
+malloc()s and free()s virtual arrays, and an error occurs if the required
+memory exceeds the limit specified in cinfo->mem->max_memory_to_use.
+
Memory usage
------------
larger than a char, so it affects the surrounding application's image data.
The sample applications cjpeg and djpeg can support 12-bit mode only for PPM
and GIF file formats; you must disable the other file formats to compile a
-12-bit cjpeg or djpeg. (install.txt has more information about that.)
-At present, a 12-bit library can handle *only* 12-bit images, not both
-precisions.
+12-bit cjpeg or djpeg. At present, a 12-bit library can handle *only* 12-bit
+images, not both precisions.
Note that a 12-bit library always compresses in Huffman optimization mode,
in order to generate valid Huffman tables. This is necessary because our