blob: a5c0a1fda33612b12daa78904e9409287549f8f8 [file] [log] [blame]
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001/*
2 * jchuff.c
3 *
DRCa73e8702012-12-31 02:52:30 +00004 * This file was part of the Independent JPEG Group's software:
Thomas G. Lane5ead57a1998-03-27 00:00:00 +00005 * Copyright (C) 1991-1997, Thomas G. Lane.
DRCa6ef2822013-09-28 03:23:49 +00006 * libjpeg-turbo Modifications:
DRC29823fa2014-08-21 01:55:22 +00007 * Copyright (C) 2009-2011, 2014 D. R. Commander.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00008 * For conditions of distribution and use, see the accompanying README file.
9 *
10 * This file contains Huffman entropy encoding routines.
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000011 *
12 * Much of the complexity here has to do with supporting output suspension.
13 * If the data destination module demands suspension, we want to be able to
14 * back up to the start of the current MCU. To do this, we copy state
15 * variables into local working storage, and update them back to the
16 * permanent JPEG objects only upon successful completion of an MCU.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000017 */
18
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000019#define JPEG_INTERNALS
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000020#include "jinclude.h"
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000021#include "jpeglib.h"
DRCe5eaf372014-05-09 18:00:32 +000022#include "jchuff.h" /* Declarations shared with jcphuff.c */
DRC8443e522009-07-30 08:35:06 +000023#include <limits.h>
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000024
DRC0cfc4c12014-03-28 18:33:25 +000025/*
26 * NOTE: If USE_CLZ_INTRINSIC is defined, then clz/bsr instructions will be
27 * used for bit counting rather than the lookup table. This will reduce the
28 * memory footprint by 64k, which is important for some mobile applications
29 * that create many isolated instances of libjpeg-turbo (web browsers, for
30 * instance.) This may improve performance on some mobile platforms as well.
31 * This feature is enabled by default only on ARM processors, because some x86
32 * chips have a slow implementation of bsr, and the use of clz/bsr cannot be
33 * shown to have a significant performance impact even on the x86 chips that
34 * have a fast implementation of it. When building for ARMv6, you can
35 * explicitly disable the use of clz/bsr by adding -mthumb to the compiler
36 * flags (this defines __thumb__).
37 */
38
39/* NOTE: Both GCC and Clang define __GNUC__ */
DRC803b5d22014-11-18 15:56:43 +000040#if defined __GNUC__ && (defined __arm__ || defined __aarch64__)
DRC0cfc4c12014-03-28 18:33:25 +000041#if !defined __thumb__ || defined __thumb2__
42#define USE_CLZ_INTRINSIC
43#endif
44#endif
45
46#ifdef USE_CLZ_INTRINSIC
47#define JPEG_NBITS_NONZERO(x) (32 - __builtin_clz(x))
48#define JPEG_NBITS(x) (x ? JPEG_NBITS_NONZERO(x) : 0)
49#else
DRCef9a4e02014-03-28 18:50:30 +000050#include "jpeg_nbits_table.h"
DRC0cfc4c12014-03-28 18:33:25 +000051#define JPEG_NBITS(x) (jpeg_nbits_table[x])
52#define JPEG_NBITS_NONZERO(x) JPEG_NBITS(x)
53#endif
DRC99313382009-03-12 17:24:27 +000054
DRC3cba8db2009-03-16 23:58:30 +000055#ifndef min
56 #define min(a,b) ((a)<(b)?(a):(b))
57#endif
58
DRC6bb57b72011-04-26 22:08:31 +000059
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000060/* Expanded entropy encoder object for Huffman encoding.
61 *
62 * The savable_state subrecord contains fields that change within an MCU,
63 * but must not be updated permanently until we complete the MCU.
64 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000065
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000066typedef struct {
DRCe5eaf372014-05-09 18:00:32 +000067 size_t put_buffer; /* current bit-accumulation buffer */
68 int put_bits; /* # of bits now in it */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000069 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
70} savable_state;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000071
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000072/* This macro is to work around compilers with missing or broken
73 * structure assignment. You'll need to fix this code if you have
74 * such a compiler and you change MAX_COMPS_IN_SCAN.
75 */
76
77#ifndef NO_STRUCT_ASSIGN
78#define ASSIGN_STATE(dest,src) ((dest) = (src))
79#else
80#if MAX_COMPS_IN_SCAN == 4
81#define ASSIGN_STATE(dest,src) \
DRCe5eaf372014-05-09 18:00:32 +000082 ((dest).put_buffer = (src).put_buffer, \
83 (dest).put_bits = (src).put_bits, \
84 (dest).last_dc_val[0] = (src).last_dc_val[0], \
85 (dest).last_dc_val[1] = (src).last_dc_val[1], \
86 (dest).last_dc_val[2] = (src).last_dc_val[2], \
87 (dest).last_dc_val[3] = (src).last_dc_val[3])
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000088#endif
89#endif
90
91
92typedef struct {
93 struct jpeg_entropy_encoder pub; /* public fields */
94
DRCe5eaf372014-05-09 18:00:32 +000095 savable_state saved; /* Bit buffer & DC state at start of MCU */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000096
97 /* These fields are NOT loaded into local working state. */
DRCe5eaf372014-05-09 18:00:32 +000098 unsigned int restarts_to_go; /* MCUs left in this restart interval */
99 int next_restart_num; /* next restart number to write (0-7) */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000100
101 /* Pointers to derived tables (these workspaces have image lifespan) */
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000102 c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
103 c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000104
DRCe5eaf372014-05-09 18:00:32 +0000105#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000106 long * dc_count_ptrs[NUM_HUFF_TBLS];
107 long * ac_count_ptrs[NUM_HUFF_TBLS];
108#endif
109} huff_entropy_encoder;
110
111typedef huff_entropy_encoder * huff_entropy_ptr;
112
113/* Working state while writing an MCU.
114 * This struct contains all the fields that are needed by subroutines.
115 */
116
117typedef struct {
DRCe5eaf372014-05-09 18:00:32 +0000118 JOCTET * next_output_byte; /* => next byte to write in buffer */
119 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
120 savable_state cur; /* Current bit buffer & DC state */
121 j_compress_ptr cinfo; /* dump_buffer needs access to this */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000122} working_state;
123
124
125/* Forward declarations */
DRCbc56b752014-05-16 10:43:44 +0000126METHODDEF(boolean) encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data);
127METHODDEF(void) finish_pass_huff (j_compress_ptr cinfo);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000128#ifdef ENTROPY_OPT_SUPPORTED
DRCbc56b752014-05-16 10:43:44 +0000129METHODDEF(boolean) encode_mcu_gather (j_compress_ptr cinfo,
130 JBLOCKROW *MCU_data);
131METHODDEF(void) finish_pass_gather (j_compress_ptr cinfo);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000132#endif
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000133
134
135/*
136 * Initialize for a Huffman-compressed scan.
137 * If gather_statistics is TRUE, we do not output anything during the scan,
138 * just count the Huffman symbols used and generate Huffman code tables.
139 */
140
Thomas G. Lane489583f1996-02-07 00:00:00 +0000141METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000142start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
143{
144 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
145 int ci, dctbl, actbl;
146 jpeg_component_info * compptr;
147
148 if (gather_statistics) {
149#ifdef ENTROPY_OPT_SUPPORTED
150 entropy->pub.encode_mcu = encode_mcu_gather;
151 entropy->pub.finish_pass = finish_pass_gather;
152#else
153 ERREXIT(cinfo, JERR_NOT_COMPILED);
154#endif
155 } else {
156 entropy->pub.encode_mcu = encode_mcu_huff;
157 entropy->pub.finish_pass = finish_pass_huff;
158 }
159
160 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
161 compptr = cinfo->cur_comp_info[ci];
162 dctbl = compptr->dc_tbl_no;
163 actbl = compptr->ac_tbl_no;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000164 if (gather_statistics) {
165#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000166 /* Check for invalid table indexes */
167 /* (make_c_derived_tbl does this in the other path) */
168 if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
DRCe5eaf372014-05-09 18:00:32 +0000169 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000170 if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
DRCe5eaf372014-05-09 18:00:32 +0000171 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000172 /* Allocate and zero the statistics tables */
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000173 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000174 if (entropy->dc_count_ptrs[dctbl] == NULL)
DRCe5eaf372014-05-09 18:00:32 +0000175 entropy->dc_count_ptrs[dctbl] = (long *)
176 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
DRC5de454b2014-05-18 19:04:03 +0000177 257 * sizeof(long));
178 MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * sizeof(long));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000179 if (entropy->ac_count_ptrs[actbl] == NULL)
DRCe5eaf372014-05-09 18:00:32 +0000180 entropy->ac_count_ptrs[actbl] = (long *)
181 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
DRC5de454b2014-05-18 19:04:03 +0000182 257 * sizeof(long));
183 MEMZERO(entropy->ac_count_ptrs[actbl], 257 * sizeof(long));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000184#endif
185 } else {
186 /* Compute derived values for Huffman tables */
187 /* We may do this more than once for a table, but it's not expensive */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000188 jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
DRCe5eaf372014-05-09 18:00:32 +0000189 & entropy->dc_derived_tbls[dctbl]);
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000190 jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
DRCe5eaf372014-05-09 18:00:32 +0000191 & entropy->ac_derived_tbls[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000192 }
193 /* Initialize DC predictions to 0 */
194 entropy->saved.last_dc_val[ci] = 0;
195 }
196
197 /* Initialize bit buffer to empty */
198 entropy->saved.put_buffer = 0;
199 entropy->saved.put_bits = 0;
200
201 /* Initialize restart stuff */
202 entropy->restarts_to_go = cinfo->restart_interval;
203 entropy->next_restart_num = 0;
204}
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000205
206
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000207/*
208 * Compute the derived values for a Huffman table.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000209 * This routine also performs some validation checks on the table.
210 *
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000211 * Note this is also used by jcphuff.c.
212 */
213
Thomas G. Lane489583f1996-02-07 00:00:00 +0000214GLOBAL(void)
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000215jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
DRCe5eaf372014-05-09 18:00:32 +0000216 c_derived_tbl ** pdtbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000217{
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000218 JHUFF_TBL *htbl;
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000219 c_derived_tbl *dtbl;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000220 int p, i, l, lastp, si, maxsymbol;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000221 char huffsize[257];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000222 unsigned int huffcode[257];
223 unsigned int code;
224
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000225 /* Note that huffsize[] and huffcode[] are filled in code-length order,
226 * paralleling the order of the symbols themselves in htbl->huffval[].
227 */
228
229 /* Find the input Huffman table */
230 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
231 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
232 htbl =
233 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
234 if (htbl == NULL)
235 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
236
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000237 /* Allocate a workspace if we haven't already done so. */
238 if (*pdtbl == NULL)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000239 *pdtbl = (c_derived_tbl *)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000240 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
DRC5de454b2014-05-18 19:04:03 +0000241 sizeof(c_derived_tbl));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000242 dtbl = *pdtbl;
DRCe5eaf372014-05-09 18:00:32 +0000243
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000244 /* Figure C.1: make table of Huffman code length for each symbol */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000245
246 p = 0;
247 for (l = 1; l <= 16; l++) {
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000248 i = (int) htbl->bits[l];
DRCe5eaf372014-05-09 18:00:32 +0000249 if (i < 0 || p + i > 256) /* protect against table overrun */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000250 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
251 while (i--)
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000252 huffsize[p++] = (char) l;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000253 }
254 huffsize[p] = 0;
255 lastp = p;
DRCe5eaf372014-05-09 18:00:32 +0000256
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000257 /* Figure C.2: generate the codes themselves */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000258 /* We also validate that the counts represent a legal Huffman code tree. */
259
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000260 code = 0;
261 si = huffsize[0];
262 p = 0;
263 while (huffsize[p]) {
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000264 while (((int) huffsize[p]) == si) {
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000265 huffcode[p++] = code;
266 code++;
267 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000268 /* code is now 1 more than the last code used for codelength si; but
269 * it must still fit in si bits, since no code is allowed to be all ones.
270 */
271 if (((INT32) code) >= (((INT32) 1) << si))
272 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000273 code <<= 1;
274 si++;
275 }
DRCe5eaf372014-05-09 18:00:32 +0000276
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000277 /* Figure C.3: generate encoding tables */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000278 /* These are code and size indexed by symbol value */
279
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000280 /* Set all codeless symbols to have code length 0;
281 * this lets us detect duplicate VAL entries here, and later
282 * allows emit_bits to detect any attempt to emit such symbols.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000283 */
DRC5de454b2014-05-18 19:04:03 +0000284 MEMZERO(dtbl->ehufsi, sizeof(dtbl->ehufsi));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000285
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000286 /* This is also a convenient place to check for out-of-range
287 * and duplicated VAL entries. We allow 0..255 for AC symbols
288 * but only 0..15 for DC. (We could constrain them further
289 * based on data depth and mode, but this seems enough.)
290 */
291 maxsymbol = isDC ? 15 : 255;
292
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000293 for (p = 0; p < lastp; p++) {
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000294 i = htbl->huffval[p];
295 if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
296 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
297 dtbl->ehufco[i] = huffcode[p];
298 dtbl->ehufsi[i] = huffsize[p];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000299 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000300}
301
302
303/* Outputting bytes to the file */
304
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000305/* Emit a byte, taking 'action' if must suspend. */
306#define emit_byte(state,val,action) \
DRCe5eaf372014-05-09 18:00:32 +0000307 { *(state)->next_output_byte++ = (JOCTET) (val); \
308 if (--(state)->free_in_buffer == 0) \
309 if (! dump_buffer(state)) \
310 { action; } }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000311
312
Thomas G. Lane489583f1996-02-07 00:00:00 +0000313LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000314dump_buffer (working_state * state)
315/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000316{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000317 struct jpeg_destination_mgr * dest = state->cinfo->dest;
318
319 if (! (*dest->empty_output_buffer) (state->cinfo))
320 return FALSE;
321 /* After a successful buffer dump, must reset buffer pointers */
322 state->next_output_byte = dest->next_output_byte;
323 state->free_in_buffer = dest->free_in_buffer;
324 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000325}
326
327
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000328/* Outputting bits to the file */
329
DRC6bb57b72011-04-26 22:08:31 +0000330/* These macros perform the same task as the emit_bits() function in the
331 * original libjpeg code. In addition to reducing overhead by explicitly
332 * inlining the code, additional performance is achieved by taking into
333 * account the size of the bit buffer and waiting until it is almost full
334 * before emptying it. This mostly benefits 64-bit platforms, since 6
335 * bytes can be stored in a 64-bit bit buffer before it has to be emptied.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000336 */
337
DRC6bb57b72011-04-26 22:08:31 +0000338#define EMIT_BYTE() { \
339 JOCTET c; \
340 put_bits -= 8; \
341 c = (JOCTET)GETJOCTET(put_buffer >> put_bits); \
342 *buffer++ = c; \
343 if (c == 0xFF) /* need to stuff a zero byte? */ \
344 *buffer++ = 0; \
DRC8443e522009-07-30 08:35:06 +0000345 }
346
DRC6bb57b72011-04-26 22:08:31 +0000347#define PUT_BITS(code, size) { \
348 put_bits += size; \
349 put_buffer = (put_buffer << size) | code; \
DRC8443e522009-07-30 08:35:06 +0000350}
351
DRC6bb57b72011-04-26 22:08:31 +0000352#define CHECKBUF15() { \
353 if (put_bits > 15) { \
354 EMIT_BYTE() \
355 EMIT_BYTE() \
356 } \
DRC8443e522009-07-30 08:35:06 +0000357}
358
DRC6bb57b72011-04-26 22:08:31 +0000359#define CHECKBUF31() { \
360 if (put_bits > 31) { \
361 EMIT_BYTE() \
362 EMIT_BYTE() \
363 EMIT_BYTE() \
364 EMIT_BYTE() \
365 } \
DRC8443e522009-07-30 08:35:06 +0000366}
367
DRC6bb57b72011-04-26 22:08:31 +0000368#define CHECKBUF47() { \
369 if (put_bits > 47) { \
370 EMIT_BYTE() \
371 EMIT_BYTE() \
372 EMIT_BYTE() \
373 EMIT_BYTE() \
374 EMIT_BYTE() \
375 EMIT_BYTE() \
376 } \
377}
DRC8443e522009-07-30 08:35:06 +0000378
DRC830d5fc2010-04-20 21:13:26 +0000379#if __WORDSIZE==64 || defined(_WIN64)
DRC8443e522009-07-30 08:35:06 +0000380
DRC6bb57b72011-04-26 22:08:31 +0000381#define EMIT_BITS(code, size) { \
382 CHECKBUF47() \
383 PUT_BITS(code, size) \
384}
385
386#define EMIT_CODE(code, size) { \
387 temp2 &= (((INT32) 1)<<nbits) - 1; \
388 CHECKBUF31() \
389 PUT_BITS(code, size) \
390 PUT_BITS(temp2, nbits) \
DRC8443e522009-07-30 08:35:06 +0000391 }
392
393#else
394
DRC6bb57b72011-04-26 22:08:31 +0000395#define EMIT_BITS(code, size) { \
396 PUT_BITS(code, size) \
397 CHECKBUF15() \
398}
399
400#define EMIT_CODE(code, size) { \
401 temp2 &= (((INT32) 1)<<nbits) - 1; \
402 PUT_BITS(code, size) \
403 CHECKBUF15() \
404 PUT_BITS(temp2, nbits) \
405 CHECKBUF15() \
DRC99313382009-03-12 17:24:27 +0000406 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000407
DRC8443e522009-07-30 08:35:06 +0000408#endif
409
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000410
DRC402a7152014-11-22 22:09:30 +0000411/* Although it is exceedingly rare, it is possible for a Huffman-encoded
412 * coefficient block to be larger than the 128-byte unencoded block. For each
413 * of the 64 coefficients, PUT_BITS is invoked twice, and each invocation can
414 * theoretically store 16 bits (for a maximum of 2048 bits or 256 bytes per
415 * encoded block.) If, for instance, one artificially sets the AC
416 * coefficients to alternating values of 32767 and -32768 (using the JPEG
417 * scanning order-- 1, 8, 16, etc.), then this will produce an encoded block
418 * larger than 200 bytes.
419 */
420#define BUFSIZE (DCTSIZE2 * 4)
DRC3cba8db2009-03-16 23:58:30 +0000421
DRC6bb57b72011-04-26 22:08:31 +0000422#define LOAD_BUFFER() { \
423 if (state->free_in_buffer < BUFSIZE) { \
424 localbuf = 1; \
425 buffer = _buffer; \
426 } \
427 else buffer = state->next_output_byte; \
DRC3cba8db2009-03-16 23:58:30 +0000428 }
429
DRC6bb57b72011-04-26 22:08:31 +0000430#define STORE_BUFFER() { \
431 if (localbuf) { \
432 bytes = buffer - _buffer; \
433 buffer = _buffer; \
434 while (bytes > 0) { \
435 bytestocopy = min(bytes, state->free_in_buffer); \
436 MEMCOPY(state->next_output_byte, buffer, bytestocopy); \
437 state->next_output_byte += bytestocopy; \
438 buffer += bytestocopy; \
439 state->free_in_buffer -= bytestocopy; \
440 if (state->free_in_buffer == 0) \
441 if (! dump_buffer(state)) return FALSE; \
442 bytes -= bytestocopy; \
443 } \
444 } \
445 else { \
446 state->free_in_buffer -= (buffer - state->next_output_byte); \
447 state->next_output_byte = buffer; \
448 } \
DRC3cba8db2009-03-16 23:58:30 +0000449 }
450
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000451
Thomas G. Lane489583f1996-02-07 00:00:00 +0000452LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000453flush_bits (working_state * state)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000454{
DRCeddc3552014-08-21 03:38:14 +0000455 JOCTET _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000456 size_t put_buffer; int put_bits;
457 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000458
DRC99313382009-03-12 17:24:27 +0000459 put_buffer = state->cur.put_buffer;
460 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000461 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000462
DRC6bb57b72011-04-26 22:08:31 +0000463 /* fill any partial byte with ones */
464 PUT_BITS(0x7F, 7)
465 while (put_bits >= 8) EMIT_BYTE()
DRC99313382009-03-12 17:24:27 +0000466
DRCe5eaf372014-05-09 18:00:32 +0000467 state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000468 state->cur.put_bits = 0;
DRC3cba8db2009-03-16 23:58:30 +0000469 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000470
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000471 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000472}
473
DRC6bb57b72011-04-26 22:08:31 +0000474
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000475/* Encode a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000476
Thomas G. Lane489583f1996-02-07 00:00:00 +0000477LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000478encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
DRCe5eaf372014-05-09 18:00:32 +0000479 c_derived_tbl *dctbl, c_derived_tbl *actbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000480{
DRC6bb57b72011-04-26 22:08:31 +0000481 int temp, temp2, temp3;
DRC99313382009-03-12 17:24:27 +0000482 int nbits;
DRC6bb57b72011-04-26 22:08:31 +0000483 int r, code, size;
DRCeddc3552014-08-21 03:38:14 +0000484 JOCTET _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000485 size_t put_buffer; int put_bits;
DRC99313382009-03-12 17:24:27 +0000486 int code_0xf0 = actbl->ehufco[0xf0], size_0xf0 = actbl->ehufsi[0xf0];
DRC04899092010-02-26 23:01:19 +0000487 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000488
DRC99313382009-03-12 17:24:27 +0000489 put_buffer = state->cur.put_buffer;
490 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000491 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000492
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000493 /* Encode the DC coefficient difference per section F.1.2.1 */
DRCe5eaf372014-05-09 18:00:32 +0000494
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000495 temp = temp2 = block[0] - last_dc_val;
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000496
DRC6bb57b72011-04-26 22:08:31 +0000497 /* This is a well-known technique for obtaining the absolute value without a
498 * branch. It is derived from an assembly language technique presented in
499 * "How to Optimize for the Pentium Processors", Copyright (c) 1996, 1997 by
500 * Agner Fog.
501 */
502 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1);
503 temp ^= temp3;
504 temp -= temp3;
505
506 /* For a negative input, want temp2 = bitwise complement of abs(input) */
507 /* This code assumes we are on a two's complement machine */
508 temp2 += temp3;
509
510 /* Find the number of bits needed for the magnitude of the coefficient */
DRC0cfc4c12014-03-28 18:33:25 +0000511 nbits = JPEG_NBITS(temp);
DRC6bb57b72011-04-26 22:08:31 +0000512
513 /* Emit the Huffman-coded symbol for the number of bits */
514 code = dctbl->ehufco[nbits];
515 size = dctbl->ehufsi[nbits];
516 PUT_BITS(code, size)
517 CHECKBUF15()
518
519 /* Mask off any extra bits in code */
520 temp2 &= (((INT32) 1)<<nbits) - 1;
521
522 /* Emit that number of bits of the value, if positive, */
523 /* or the complement of its magnitude, if negative. */
524 PUT_BITS(temp2, nbits)
525 CHECKBUF15()
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000526
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000527 /* Encode the AC coefficients per section F.1.2.2 */
DRCe5eaf372014-05-09 18:00:32 +0000528
529 r = 0; /* r = run length of zeros */
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000530
DRC6bb57b72011-04-26 22:08:31 +0000531/* Manually unroll the k loop to eliminate the counter variable. This
532 * improves performance greatly on systems with a limited number of
533 * registers (such as x86.)
534 */
535#define kloop(jpeg_natural_order_of_k) { \
536 if ((temp = block[jpeg_natural_order_of_k]) == 0) { \
537 r++; \
538 } else { \
539 temp2 = temp; \
540 /* Branch-less absolute value, bitwise complement, etc., same as above */ \
541 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1); \
542 temp ^= temp3; \
543 temp -= temp3; \
544 temp2 += temp3; \
DRC0cfc4c12014-03-28 18:33:25 +0000545 nbits = JPEG_NBITS_NONZERO(temp); \
DRC6bb57b72011-04-26 22:08:31 +0000546 /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \
547 while (r > 15) { \
548 EMIT_BITS(code_0xf0, size_0xf0) \
549 r -= 16; \
550 } \
551 /* Emit Huffman symbol for run length / number of bits */ \
552 temp3 = (r << 4) + nbits; \
553 code = actbl->ehufco[temp3]; \
554 size = actbl->ehufsi[temp3]; \
555 EMIT_CODE(code, size) \
DRC99313382009-03-12 17:24:27 +0000556 r = 0; \
DRC6bb57b72011-04-26 22:08:31 +0000557 } \
558}
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000559
DRC6bb57b72011-04-26 22:08:31 +0000560 /* One iteration for each value in jpeg_natural_order[] */
561 kloop(1); kloop(8); kloop(16); kloop(9); kloop(2); kloop(3);
562 kloop(10); kloop(17); kloop(24); kloop(32); kloop(25); kloop(18);
563 kloop(11); kloop(4); kloop(5); kloop(12); kloop(19); kloop(26);
564 kloop(33); kloop(40); kloop(48); kloop(41); kloop(34); kloop(27);
565 kloop(20); kloop(13); kloop(6); kloop(7); kloop(14); kloop(21);
566 kloop(28); kloop(35); kloop(42); kloop(49); kloop(56); kloop(57);
567 kloop(50); kloop(43); kloop(36); kloop(29); kloop(22); kloop(15);
568 kloop(23); kloop(30); kloop(37); kloop(44); kloop(51); kloop(58);
569 kloop(59); kloop(52); kloop(45); kloop(38); kloop(31); kloop(39);
570 kloop(46); kloop(53); kloop(60); kloop(61); kloop(54); kloop(47);
571 kloop(55); kloop(62); kloop(63);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000572
573 /* If the last coef(s) were zero, emit an end-of-block code */
DRC6bb57b72011-04-26 22:08:31 +0000574 if (r > 0) {
575 code = actbl->ehufco[0];
576 size = actbl->ehufsi[0];
577 EMIT_BITS(code, size)
578 }
DRC99313382009-03-12 17:24:27 +0000579
580 state->cur.put_buffer = put_buffer;
581 state->cur.put_bits = put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000582 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000583
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000584 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000585}
586
587
588/*
589 * Emit a restart marker & resynchronize predictions.
590 */
591
Thomas G. Lane489583f1996-02-07 00:00:00 +0000592LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000593emit_restart (working_state * state, int restart_num)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000594{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000595 int ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000596
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000597 if (! flush_bits(state))
598 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000599
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000600 emit_byte(state, 0xFF, return FALSE);
601 emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000602
603 /* Re-initialize DC predictions to 0 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000604 for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
605 state->cur.last_dc_val[ci] = 0;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000606
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000607 /* The restart counter is not updated until we successfully write the MCU. */
608
609 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000610}
611
612
613/*
614 * Encode and output one MCU's worth of Huffman-compressed coefficients.
615 */
616
Thomas G. Lane489583f1996-02-07 00:00:00 +0000617METHODDEF(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000618encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000619{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000620 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
621 working_state state;
622 int blkn, ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000623 jpeg_component_info * compptr;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000624
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000625 /* Load up working state */
626 state.next_output_byte = cinfo->dest->next_output_byte;
627 state.free_in_buffer = cinfo->dest->free_in_buffer;
628 ASSIGN_STATE(state.cur, entropy->saved);
629 state.cinfo = cinfo;
630
631 /* Emit restart marker if needed */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000632 if (cinfo->restart_interval) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000633 if (entropy->restarts_to_go == 0)
634 if (! emit_restart(&state, entropy->next_restart_num))
DRCe5eaf372014-05-09 18:00:32 +0000635 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000636 }
637
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000638 /* Encode the MCU data blocks */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000639 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
640 ci = cinfo->MCU_membership[blkn];
641 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000642 if (! encode_one_block(&state,
DRCe5eaf372014-05-09 18:00:32 +0000643 MCU_data[blkn][0], state.cur.last_dc_val[ci],
644 entropy->dc_derived_tbls[compptr->dc_tbl_no],
645 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000646 return FALSE;
647 /* Update last_dc_val */
648 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000649 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000650
651 /* Completed MCU, so update state */
652 cinfo->dest->next_output_byte = state.next_output_byte;
653 cinfo->dest->free_in_buffer = state.free_in_buffer;
654 ASSIGN_STATE(entropy->saved, state.cur);
655
656 /* Update restart-interval state too */
657 if (cinfo->restart_interval) {
658 if (entropy->restarts_to_go == 0) {
659 entropy->restarts_to_go = cinfo->restart_interval;
660 entropy->next_restart_num++;
661 entropy->next_restart_num &= 7;
662 }
663 entropy->restarts_to_go--;
664 }
665
666 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000667}
668
669
670/*
671 * Finish up at the end of a Huffman-compressed scan.
672 */
673
Thomas G. Lane489583f1996-02-07 00:00:00 +0000674METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000675finish_pass_huff (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000676{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000677 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
678 working_state state;
679
680 /* Load up working state ... flush_bits needs it */
681 state.next_output_byte = cinfo->dest->next_output_byte;
682 state.free_in_buffer = cinfo->dest->free_in_buffer;
683 ASSIGN_STATE(state.cur, entropy->saved);
684 state.cinfo = cinfo;
685
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000686 /* Flush out the last data */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000687 if (! flush_bits(&state))
688 ERREXIT(cinfo, JERR_CANT_SUSPEND);
689
690 /* Update state */
691 cinfo->dest->next_output_byte = state.next_output_byte;
692 cinfo->dest->free_in_buffer = state.free_in_buffer;
693 ASSIGN_STATE(entropy->saved, state.cur);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000694}
695
696
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000697/*
698 * Huffman coding optimization.
699 *
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000700 * We first scan the supplied data and count the number of uses of each symbol
701 * that is to be Huffman-coded. (This process MUST agree with the code above.)
702 * Then we build a Huffman coding tree for the observed counts.
703 * Symbols which are not needed at all for the particular image are not
704 * assigned any code, which saves space in the DHT marker as well as in
705 * the compressed data.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000706 */
707
708#ifdef ENTROPY_OPT_SUPPORTED
709
710
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000711/* Process a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000712
Thomas G. Lane489583f1996-02-07 00:00:00 +0000713LOCAL(void)
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000714htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
DRCe5eaf372014-05-09 18:00:32 +0000715 long dc_counts[], long ac_counts[])
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000716{
717 register int temp;
718 register int nbits;
719 register int k, r;
DRCe5eaf372014-05-09 18:00:32 +0000720
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000721 /* Encode the DC coefficient difference per section F.1.2.1 */
DRCe5eaf372014-05-09 18:00:32 +0000722
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000723 temp = block[0] - last_dc_val;
724 if (temp < 0)
725 temp = -temp;
DRCe5eaf372014-05-09 18:00:32 +0000726
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000727 /* Find the number of bits needed for the magnitude of the coefficient */
728 nbits = 0;
729 while (temp) {
730 nbits++;
731 temp >>= 1;
732 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000733 /* Check for out-of-range coefficient values.
734 * Since we're encoding a difference, the range limit is twice as much.
735 */
736 if (nbits > MAX_COEF_BITS+1)
737 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000738
739 /* Count the Huffman symbol for the number of bits */
740 dc_counts[nbits]++;
DRCe5eaf372014-05-09 18:00:32 +0000741
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000742 /* Encode the AC coefficients per section F.1.2.2 */
DRCe5eaf372014-05-09 18:00:32 +0000743
744 r = 0; /* r = run length of zeros */
745
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000746 for (k = 1; k < DCTSIZE2; k++) {
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000747 if ((temp = block[jpeg_natural_order[k]]) == 0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000748 r++;
749 } else {
750 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
751 while (r > 15) {
DRCe5eaf372014-05-09 18:00:32 +0000752 ac_counts[0xF0]++;
753 r -= 16;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000754 }
DRCe5eaf372014-05-09 18:00:32 +0000755
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000756 /* Find the number of bits needed for the magnitude of the coefficient */
757 if (temp < 0)
DRCe5eaf372014-05-09 18:00:32 +0000758 temp = -temp;
759
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000760 /* Find the number of bits needed for the magnitude of the coefficient */
DRCe5eaf372014-05-09 18:00:32 +0000761 nbits = 1; /* there must be at least one 1 bit */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000762 while ((temp >>= 1))
DRCe5eaf372014-05-09 18:00:32 +0000763 nbits++;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000764 /* Check for out-of-range coefficient values */
765 if (nbits > MAX_COEF_BITS)
DRCe5eaf372014-05-09 18:00:32 +0000766 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
767
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000768 /* Count Huffman symbol for run length / number of bits */
769 ac_counts[(r << 4) + nbits]++;
DRCe5eaf372014-05-09 18:00:32 +0000770
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000771 r = 0;
772 }
773 }
774
775 /* If the last coef(s) were zero, emit an end-of-block code */
776 if (r > 0)
777 ac_counts[0]++;
778}
779
780
781/*
782 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
783 * No data is actually output, so no suspension return is possible.
784 */
785
Thomas G. Lane489583f1996-02-07 00:00:00 +0000786METHODDEF(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000787encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
788{
789 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
790 int blkn, ci;
791 jpeg_component_info * compptr;
792
793 /* Take care of restart intervals if needed */
794 if (cinfo->restart_interval) {
795 if (entropy->restarts_to_go == 0) {
796 /* Re-initialize DC predictions to 0 */
797 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
DRCe5eaf372014-05-09 18:00:32 +0000798 entropy->saved.last_dc_val[ci] = 0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000799 /* Update restart state */
800 entropy->restarts_to_go = cinfo->restart_interval;
801 }
802 entropy->restarts_to_go--;
803 }
804
805 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
806 ci = cinfo->MCU_membership[blkn];
807 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000808 htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
DRCe5eaf372014-05-09 18:00:32 +0000809 entropy->dc_count_ptrs[compptr->dc_tbl_no],
810 entropy->ac_count_ptrs[compptr->ac_tbl_no]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000811 entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
812 }
813
814 return TRUE;
815}
816
817
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000818/*
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000819 * Generate the best Huffman code table for the given counts, fill htbl.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000820 * Note this is also used by jcphuff.c.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000821 *
822 * The JPEG standard requires that no symbol be assigned a codeword of all
823 * one bits (so that padding bits added at the end of a compressed segment
824 * can't look like a valid code). Because of the canonical ordering of
825 * codewords, this just means that there must be an unused slot in the
826 * longest codeword length category. Section K.2 of the JPEG spec suggests
827 * reserving such a slot by pretending that symbol 256 is a valid symbol
828 * with count 1. In theory that's not optimal; giving it count zero but
829 * including it in the symbol set anyway should give a better Huffman code.
830 * But the theoretically better code actually seems to come out worse in
831 * practice, because it produces more all-ones bytes (which incur stuffed
832 * zero bytes in the final file). In any case the difference is tiny.
833 *
834 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
835 * If some symbols have a very small but nonzero probability, the Huffman tree
836 * must be adjusted to meet the code length restriction. We currently use
837 * the adjustment method suggested in JPEG section K.2. This method is *not*
838 * optimal; it may not choose the best possible limited-length code. But
839 * typically only very-low-frequency symbols will be given less-than-optimal
840 * lengths, so the code is almost optimal. Experimental comparisons against
841 * an optimal limited-length-code algorithm indicate that the difference is
842 * microscopic --- usually less than a hundredth of a percent of total size.
843 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000844 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000845
Thomas G. Lane489583f1996-02-07 00:00:00 +0000846GLOBAL(void)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000847jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000848{
DRCe5eaf372014-05-09 18:00:32 +0000849#define MAX_CLEN 32 /* assumed maximum initial code length */
850 UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
851 int codesize[257]; /* codesize[k] = code length of symbol k */
852 int others[257]; /* next symbol in current branch of tree */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000853 int c1, c2;
854 int p, i, j;
855 long v;
856
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000857 /* This algorithm is explained in section K.2 of the JPEG standard */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000858
DRC5de454b2014-05-18 19:04:03 +0000859 MEMZERO(bits, sizeof(bits));
860 MEMZERO(codesize, sizeof(codesize));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000861 for (i = 0; i < 257; i++)
DRCe5eaf372014-05-09 18:00:32 +0000862 others[i] = -1; /* init links to empty */
863
864 freq[256] = 1; /* make sure 256 has a nonzero count */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000865 /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000866 * that no real symbol is given code-value of all ones, because 256
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000867 * will be placed last in the largest codeword category.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000868 */
869
870 /* Huffman's basic algorithm to assign optimal code lengths to symbols */
871
872 for (;;) {
873 /* Find the smallest nonzero frequency, set c1 = its symbol */
874 /* In case of ties, take the larger symbol number */
875 c1 = -1;
876 v = 1000000000L;
877 for (i = 0; i <= 256; i++) {
878 if (freq[i] && freq[i] <= v) {
DRCe5eaf372014-05-09 18:00:32 +0000879 v = freq[i];
880 c1 = i;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000881 }
882 }
883
884 /* Find the next smallest nonzero frequency, set c2 = its symbol */
885 /* In case of ties, take the larger symbol number */
886 c2 = -1;
887 v = 1000000000L;
888 for (i = 0; i <= 256; i++) {
889 if (freq[i] && freq[i] <= v && i != c1) {
DRCe5eaf372014-05-09 18:00:32 +0000890 v = freq[i];
891 c2 = i;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000892 }
893 }
894
895 /* Done if we've merged everything into one frequency */
896 if (c2 < 0)
897 break;
DRCe5eaf372014-05-09 18:00:32 +0000898
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000899 /* Else merge the two counts/trees */
900 freq[c1] += freq[c2];
901 freq[c2] = 0;
902
903 /* Increment the codesize of everything in c1's tree branch */
904 codesize[c1]++;
905 while (others[c1] >= 0) {
906 c1 = others[c1];
907 codesize[c1]++;
908 }
DRCe5eaf372014-05-09 18:00:32 +0000909
910 others[c1] = c2; /* chain c2 onto c1's tree branch */
911
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000912 /* Increment the codesize of everything in c2's tree branch */
913 codesize[c2]++;
914 while (others[c2] >= 0) {
915 c2 = others[c2];
916 codesize[c2]++;
917 }
918 }
919
920 /* Now count the number of symbols of each code length */
921 for (i = 0; i <= 256; i++) {
922 if (codesize[i]) {
923 /* The JPEG standard seems to think that this can't happen, */
924 /* but I'm paranoid... */
925 if (codesize[i] > MAX_CLEN)
DRCe5eaf372014-05-09 18:00:32 +0000926 ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000927
928 bits[codesize[i]]++;
929 }
930 }
931
932 /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
933 * Huffman procedure assigned any such lengths, we must adjust the coding.
934 * Here is what the JPEG spec says about how this next bit works:
935 * Since symbols are paired for the longest Huffman code, the symbols are
936 * removed from this length category two at a time. The prefix for the pair
937 * (which is one bit shorter) is allocated to one of the pair; then,
938 * skipping the BITS entry for that prefix length, a code word from the next
939 * shortest nonzero BITS entry is converted into a prefix for two code words
940 * one bit longer.
941 */
DRCe5eaf372014-05-09 18:00:32 +0000942
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000943 for (i = MAX_CLEN; i > 16; i--) {
944 while (bits[i] > 0) {
DRCe5eaf372014-05-09 18:00:32 +0000945 j = i - 2; /* find length of new prefix to be used */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000946 while (bits[j] == 0)
DRCe5eaf372014-05-09 18:00:32 +0000947 j--;
948
949 bits[i] -= 2; /* remove two symbols */
950 bits[i-1]++; /* one goes in this length */
951 bits[j+1] += 2; /* two new symbols in this length */
952 bits[j]--; /* symbol of this length is now a prefix */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000953 }
954 }
955
956 /* Remove the count for the pseudo-symbol 256 from the largest codelength */
DRCe5eaf372014-05-09 18:00:32 +0000957 while (bits[i] == 0) /* find largest codelength still in use */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000958 i--;
959 bits[i]--;
DRCe5eaf372014-05-09 18:00:32 +0000960
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000961 /* Return final symbol counts (only for lengths 0..16) */
DRC5de454b2014-05-18 19:04:03 +0000962 MEMCOPY(htbl->bits, bits, sizeof(htbl->bits));
DRCe5eaf372014-05-09 18:00:32 +0000963
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000964 /* Return a list of the symbols sorted by code length */
965 /* It's not real clear to me why we don't need to consider the codelength
966 * changes made above, but the JPEG spec seems to think this works.
967 */
968 p = 0;
969 for (i = 1; i <= MAX_CLEN; i++) {
970 for (j = 0; j <= 255; j++) {
971 if (codesize[j] == i) {
DRCe5eaf372014-05-09 18:00:32 +0000972 htbl->huffval[p] = (UINT8) j;
973 p++;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000974 }
975 }
976 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000977
978 /* Set sent_table FALSE so updated table will be written to JPEG file. */
979 htbl->sent_table = FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000980}
981
982
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000983/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000984 * Finish up a statistics-gathering pass and create the new Huffman tables.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000985 */
986
Thomas G. Lane489583f1996-02-07 00:00:00 +0000987METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000988finish_pass_gather (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000989{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000990 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
991 int ci, dctbl, actbl;
992 jpeg_component_info * compptr;
993 JHUFF_TBL **htblptr;
994 boolean did_dc[NUM_HUFF_TBLS];
995 boolean did_ac[NUM_HUFF_TBLS];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000996
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000997 /* It's important not to apply jpeg_gen_optimal_table more than once
998 * per table, because it clobbers the input frequency counts!
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000999 */
DRC5de454b2014-05-18 19:04:03 +00001000 MEMZERO(did_dc, sizeof(did_dc));
1001 MEMZERO(did_ac, sizeof(did_ac));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001002
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001003 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1004 compptr = cinfo->cur_comp_info[ci];
1005 dctbl = compptr->dc_tbl_no;
1006 actbl = compptr->ac_tbl_no;
1007 if (! did_dc[dctbl]) {
1008 htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001009 if (*htblptr == NULL)
DRCe5eaf372014-05-09 18:00:32 +00001010 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001011 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001012 did_dc[dctbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001013 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001014 if (! did_ac[actbl]) {
1015 htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001016 if (*htblptr == NULL)
DRCe5eaf372014-05-09 18:00:32 +00001017 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001018 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001019 did_ac[actbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001020 }
1021 }
1022}
1023
1024
1025#endif /* ENTROPY_OPT_SUPPORTED */
1026
1027
1028/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001029 * Module initialization routine for Huffman entropy encoding.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001030 */
1031
Thomas G. Lane489583f1996-02-07 00:00:00 +00001032GLOBAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001033jinit_huff_encoder (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001034{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001035 huff_entropy_ptr entropy;
1036 int i;
1037
1038 entropy = (huff_entropy_ptr)
1039 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
DRC5de454b2014-05-18 19:04:03 +00001040 sizeof(huff_entropy_encoder));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001041 cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
1042 entropy->pub.start_pass = start_pass_huff;
1043
1044 /* Mark tables unallocated */
1045 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1046 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001047#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001048 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001049#endif
1050 }
1051}