blob: 398d2a11fd875d58f978a61f91b670cf334c2cd6 [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:
DRC6bb57b72011-04-26 22:08:31 +00007 * Copyright (C) 2009-2011, 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"
Thomas G. Lanebc79e061995-08-02 00:00:00 +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__ */
40#if defined __GNUC__ && defined __arm__
41#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 {
DRC04899092010-02-26 23:01:19 +000067 size_t put_buffer; /* current bit-accumulation buffer */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000068 int put_bits; /* # of bits now in it */
69 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) \
82 ((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])
88#endif
89#endif
90
91
92typedef struct {
93 struct jpeg_entropy_encoder pub; /* public fields */
94
95 savable_state saved; /* Bit buffer & DC state at start of MCU */
96
97 /* These fields are NOT loaded into local working state. */
98 unsigned int restarts_to_go; /* MCUs left in this restart interval */
99 int next_restart_num; /* next restart number to write (0-7) */
100
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
105#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
106 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 {
118 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 */
122} working_state;
123
124
125/* Forward declarations */
Thomas G. Lane489583f1996-02-07 00:00:00 +0000126METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
127 JBLOCKROW *MCU_data));
128METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000129#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane489583f1996-02-07 00:00:00 +0000130METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
131 JBLOCKROW *MCU_data));
132METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000133#endif
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000134
135
136/*
137 * Initialize for a Huffman-compressed scan.
138 * If gather_statistics is TRUE, we do not output anything during the scan,
139 * just count the Huffman symbols used and generate Huffman code tables.
140 */
141
Thomas G. Lane489583f1996-02-07 00:00:00 +0000142METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000143start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
144{
145 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
146 int ci, dctbl, actbl;
147 jpeg_component_info * compptr;
148
149 if (gather_statistics) {
150#ifdef ENTROPY_OPT_SUPPORTED
151 entropy->pub.encode_mcu = encode_mcu_gather;
152 entropy->pub.finish_pass = finish_pass_gather;
153#else
154 ERREXIT(cinfo, JERR_NOT_COMPILED);
155#endif
156 } else {
157 entropy->pub.encode_mcu = encode_mcu_huff;
158 entropy->pub.finish_pass = finish_pass_huff;
159 }
160
161 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
162 compptr = cinfo->cur_comp_info[ci];
163 dctbl = compptr->dc_tbl_no;
164 actbl = compptr->ac_tbl_no;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000165 if (gather_statistics) {
166#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000167 /* Check for invalid table indexes */
168 /* (make_c_derived_tbl does this in the other path) */
169 if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
170 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
171 if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
172 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000173 /* Allocate and zero the statistics tables */
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000174 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000175 if (entropy->dc_count_ptrs[dctbl] == NULL)
176 entropy->dc_count_ptrs[dctbl] = (long *)
177 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
178 257 * SIZEOF(long));
179 MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
180 if (entropy->ac_count_ptrs[actbl] == NULL)
181 entropy->ac_count_ptrs[actbl] = (long *)
182 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
183 257 * SIZEOF(long));
184 MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
185#endif
186 } else {
187 /* Compute derived values for Huffman tables */
188 /* We may do this more than once for a table, but it's not expensive */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000189 jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000190 & entropy->dc_derived_tbls[dctbl]);
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000191 jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000192 & entropy->ac_derived_tbls[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000193 }
194 /* Initialize DC predictions to 0 */
195 entropy->saved.last_dc_val[ci] = 0;
196 }
197
198 /* Initialize bit buffer to empty */
199 entropy->saved.put_buffer = 0;
200 entropy->saved.put_bits = 0;
201
202 /* Initialize restart stuff */
203 entropy->restarts_to_go = cinfo->restart_interval;
204 entropy->next_restart_num = 0;
205}
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000206
207
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000208/*
209 * Compute the derived values for a Huffman table.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000210 * This routine also performs some validation checks on the table.
211 *
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000212 * Note this is also used by jcphuff.c.
213 */
214
Thomas G. Lane489583f1996-02-07 00:00:00 +0000215GLOBAL(void)
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000216jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000217 c_derived_tbl ** pdtbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000218{
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000219 JHUFF_TBL *htbl;
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000220 c_derived_tbl *dtbl;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000221 int p, i, l, lastp, si, maxsymbol;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000222 char huffsize[257];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000223 unsigned int huffcode[257];
224 unsigned int code;
225
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000226 /* Note that huffsize[] and huffcode[] are filled in code-length order,
227 * paralleling the order of the symbols themselves in htbl->huffval[].
228 */
229
230 /* Find the input Huffman table */
231 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
232 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
233 htbl =
234 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
235 if (htbl == NULL)
236 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
237
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000238 /* Allocate a workspace if we haven't already done so. */
239 if (*pdtbl == NULL)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000240 *pdtbl = (c_derived_tbl *)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000241 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000242 SIZEOF(c_derived_tbl));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000243 dtbl = *pdtbl;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000244
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000245 /* Figure C.1: make table of Huffman code length for each symbol */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000246
247 p = 0;
248 for (l = 1; l <= 16; l++) {
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000249 i = (int) htbl->bits[l];
250 if (i < 0 || p + i > 256) /* protect against table overrun */
251 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
252 while (i--)
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000253 huffsize[p++] = (char) l;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000254 }
255 huffsize[p] = 0;
256 lastp = p;
257
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000258 /* Figure C.2: generate the codes themselves */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000259 /* We also validate that the counts represent a legal Huffman code tree. */
260
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000261 code = 0;
262 si = huffsize[0];
263 p = 0;
264 while (huffsize[p]) {
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000265 while (((int) huffsize[p]) == si) {
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000266 huffcode[p++] = code;
267 code++;
268 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000269 /* code is now 1 more than the last code used for codelength si; but
270 * it must still fit in si bits, since no code is allowed to be all ones.
271 */
272 if (((INT32) code) >= (((INT32) 1) << si))
273 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000274 code <<= 1;
275 si++;
276 }
277
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000278 /* Figure C.3: generate encoding tables */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000279 /* These are code and size indexed by symbol value */
280
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000281 /* Set all codeless symbols to have code length 0;
282 * this lets us detect duplicate VAL entries here, and later
283 * allows emit_bits to detect any attempt to emit such symbols.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000284 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000285 MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000286
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000287 /* This is also a convenient place to check for out-of-range
288 * and duplicated VAL entries. We allow 0..255 for AC symbols
289 * but only 0..15 for DC. (We could constrain them further
290 * based on data depth and mode, but this seems enough.)
291 */
292 maxsymbol = isDC ? 15 : 255;
293
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000294 for (p = 0; p < lastp; p++) {
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000295 i = htbl->huffval[p];
296 if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
297 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
298 dtbl->ehufco[i] = huffcode[p];
299 dtbl->ehufsi[i] = huffsize[p];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000300 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000301}
302
303
304/* Outputting bytes to the file */
305
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000306/* Emit a byte, taking 'action' if must suspend. */
307#define emit_byte(state,val,action) \
308 { *(state)->next_output_byte++ = (JOCTET) (val); \
309 if (--(state)->free_in_buffer == 0) \
310 if (! dump_buffer(state)) \
311 { action; } }
312
313
Thomas G. Lane489583f1996-02-07 00:00:00 +0000314LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000315dump_buffer (working_state * state)
316/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000317{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000318 struct jpeg_destination_mgr * dest = state->cinfo->dest;
319
320 if (! (*dest->empty_output_buffer) (state->cinfo))
321 return FALSE;
322 /* After a successful buffer dump, must reset buffer pointers */
323 state->next_output_byte = dest->next_output_byte;
324 state->free_in_buffer = dest->free_in_buffer;
325 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000326}
327
328
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000329/* Outputting bits to the file */
330
DRC6bb57b72011-04-26 22:08:31 +0000331/* These macros perform the same task as the emit_bits() function in the
332 * original libjpeg code. In addition to reducing overhead by explicitly
333 * inlining the code, additional performance is achieved by taking into
334 * account the size of the bit buffer and waiting until it is almost full
335 * before emptying it. This mostly benefits 64-bit platforms, since 6
336 * bytes can be stored in a 64-bit bit buffer before it has to be emptied.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000337 */
338
DRC6bb57b72011-04-26 22:08:31 +0000339#define EMIT_BYTE() { \
340 JOCTET c; \
341 put_bits -= 8; \
342 c = (JOCTET)GETJOCTET(put_buffer >> put_bits); \
343 *buffer++ = c; \
344 if (c == 0xFF) /* need to stuff a zero byte? */ \
345 *buffer++ = 0; \
DRC8443e522009-07-30 08:35:06 +0000346 }
347
DRC6bb57b72011-04-26 22:08:31 +0000348#define PUT_BITS(code, size) { \
349 put_bits += size; \
350 put_buffer = (put_buffer << size) | code; \
DRC8443e522009-07-30 08:35:06 +0000351}
352
DRC6bb57b72011-04-26 22:08:31 +0000353#define CHECKBUF15() { \
354 if (put_bits > 15) { \
355 EMIT_BYTE() \
356 EMIT_BYTE() \
357 } \
DRC8443e522009-07-30 08:35:06 +0000358}
359
DRC6bb57b72011-04-26 22:08:31 +0000360#define CHECKBUF31() { \
361 if (put_bits > 31) { \
362 EMIT_BYTE() \
363 EMIT_BYTE() \
364 EMIT_BYTE() \
365 EMIT_BYTE() \
366 } \
DRC8443e522009-07-30 08:35:06 +0000367}
368
DRC6bb57b72011-04-26 22:08:31 +0000369#define CHECKBUF47() { \
370 if (put_bits > 47) { \
371 EMIT_BYTE() \
372 EMIT_BYTE() \
373 EMIT_BYTE() \
374 EMIT_BYTE() \
375 EMIT_BYTE() \
376 EMIT_BYTE() \
377 } \
378}
DRC8443e522009-07-30 08:35:06 +0000379
DRC830d5fc2010-04-20 21:13:26 +0000380#if __WORDSIZE==64 || defined(_WIN64)
DRC8443e522009-07-30 08:35:06 +0000381
DRC6bb57b72011-04-26 22:08:31 +0000382#define EMIT_BITS(code, size) { \
383 CHECKBUF47() \
384 PUT_BITS(code, size) \
385}
386
387#define EMIT_CODE(code, size) { \
388 temp2 &= (((INT32) 1)<<nbits) - 1; \
389 CHECKBUF31() \
390 PUT_BITS(code, size) \
391 PUT_BITS(temp2, nbits) \
DRC8443e522009-07-30 08:35:06 +0000392 }
393
394#else
395
DRC6bb57b72011-04-26 22:08:31 +0000396#define EMIT_BITS(code, size) { \
397 PUT_BITS(code, size) \
398 CHECKBUF15() \
399}
400
401#define EMIT_CODE(code, size) { \
402 temp2 &= (((INT32) 1)<<nbits) - 1; \
403 PUT_BITS(code, size) \
404 CHECKBUF15() \
405 PUT_BITS(temp2, nbits) \
406 CHECKBUF15() \
DRC99313382009-03-12 17:24:27 +0000407 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000408
DRC8443e522009-07-30 08:35:06 +0000409#endif
410
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000411
DRC3cba8db2009-03-16 23:58:30 +0000412#define BUFSIZE (DCTSIZE2 * 2)
413
DRC6bb57b72011-04-26 22:08:31 +0000414#define LOAD_BUFFER() { \
415 if (state->free_in_buffer < BUFSIZE) { \
416 localbuf = 1; \
417 buffer = _buffer; \
418 } \
419 else buffer = state->next_output_byte; \
DRC3cba8db2009-03-16 23:58:30 +0000420 }
421
DRC6bb57b72011-04-26 22:08:31 +0000422#define STORE_BUFFER() { \
423 if (localbuf) { \
424 bytes = buffer - _buffer; \
425 buffer = _buffer; \
426 while (bytes > 0) { \
427 bytestocopy = min(bytes, state->free_in_buffer); \
428 MEMCOPY(state->next_output_byte, buffer, bytestocopy); \
429 state->next_output_byte += bytestocopy; \
430 buffer += bytestocopy; \
431 state->free_in_buffer -= bytestocopy; \
432 if (state->free_in_buffer == 0) \
433 if (! dump_buffer(state)) return FALSE; \
434 bytes -= bytestocopy; \
435 } \
436 } \
437 else { \
438 state->free_in_buffer -= (buffer - state->next_output_byte); \
439 state->next_output_byte = buffer; \
440 } \
DRC3cba8db2009-03-16 23:58:30 +0000441 }
442
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000443
Thomas G. Lane489583f1996-02-07 00:00:00 +0000444LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000445flush_bits (working_state * state)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000446{
DRC6bb57b72011-04-26 22:08:31 +0000447 JOCTET _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000448 size_t put_buffer; int put_bits;
449 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000450
DRC99313382009-03-12 17:24:27 +0000451 put_buffer = state->cur.put_buffer;
452 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000453 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000454
DRC6bb57b72011-04-26 22:08:31 +0000455 /* fill any partial byte with ones */
456 PUT_BITS(0x7F, 7)
457 while (put_bits >= 8) EMIT_BYTE()
DRC99313382009-03-12 17:24:27 +0000458
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000459 state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
460 state->cur.put_bits = 0;
DRC3cba8db2009-03-16 23:58:30 +0000461 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000462
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000463 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000464}
465
DRC6bb57b72011-04-26 22:08:31 +0000466
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000467/* Encode a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000468
Thomas G. Lane489583f1996-02-07 00:00:00 +0000469LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000470encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000471 c_derived_tbl *dctbl, c_derived_tbl *actbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000472{
DRC6bb57b72011-04-26 22:08:31 +0000473 int temp, temp2, temp3;
DRC99313382009-03-12 17:24:27 +0000474 int nbits;
DRC6bb57b72011-04-26 22:08:31 +0000475 int r, code, size;
476 JOCTET _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000477 size_t put_buffer; int put_bits;
DRC99313382009-03-12 17:24:27 +0000478 int code_0xf0 = actbl->ehufco[0xf0], size_0xf0 = actbl->ehufsi[0xf0];
DRC04899092010-02-26 23:01:19 +0000479 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000480
DRC99313382009-03-12 17:24:27 +0000481 put_buffer = state->cur.put_buffer;
482 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000483 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000484
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000485 /* Encode the DC coefficient difference per section F.1.2.1 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000486
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000487 temp = temp2 = block[0] - last_dc_val;
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000488
DRC6bb57b72011-04-26 22:08:31 +0000489 /* This is a well-known technique for obtaining the absolute value without a
490 * branch. It is derived from an assembly language technique presented in
491 * "How to Optimize for the Pentium Processors", Copyright (c) 1996, 1997 by
492 * Agner Fog.
493 */
494 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1);
495 temp ^= temp3;
496 temp -= temp3;
497
498 /* For a negative input, want temp2 = bitwise complement of abs(input) */
499 /* This code assumes we are on a two's complement machine */
500 temp2 += temp3;
501
502 /* Find the number of bits needed for the magnitude of the coefficient */
DRC0cfc4c12014-03-28 18:33:25 +0000503 nbits = JPEG_NBITS(temp);
DRC6bb57b72011-04-26 22:08:31 +0000504
505 /* Emit the Huffman-coded symbol for the number of bits */
506 code = dctbl->ehufco[nbits];
507 size = dctbl->ehufsi[nbits];
508 PUT_BITS(code, size)
509 CHECKBUF15()
510
511 /* Mask off any extra bits in code */
512 temp2 &= (((INT32) 1)<<nbits) - 1;
513
514 /* Emit that number of bits of the value, if positive, */
515 /* or the complement of its magnitude, if negative. */
516 PUT_BITS(temp2, nbits)
517 CHECKBUF15()
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000518
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000519 /* Encode the AC coefficients per section F.1.2.2 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000520
521 r = 0; /* r = run length of zeros */
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000522
DRC6bb57b72011-04-26 22:08:31 +0000523/* Manually unroll the k loop to eliminate the counter variable. This
524 * improves performance greatly on systems with a limited number of
525 * registers (such as x86.)
526 */
527#define kloop(jpeg_natural_order_of_k) { \
528 if ((temp = block[jpeg_natural_order_of_k]) == 0) { \
529 r++; \
530 } else { \
531 temp2 = temp; \
532 /* Branch-less absolute value, bitwise complement, etc., same as above */ \
533 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1); \
534 temp ^= temp3; \
535 temp -= temp3; \
536 temp2 += temp3; \
DRC0cfc4c12014-03-28 18:33:25 +0000537 nbits = JPEG_NBITS_NONZERO(temp); \
DRC6bb57b72011-04-26 22:08:31 +0000538 /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \
539 while (r > 15) { \
540 EMIT_BITS(code_0xf0, size_0xf0) \
541 r -= 16; \
542 } \
543 /* Emit Huffman symbol for run length / number of bits */ \
544 temp3 = (r << 4) + nbits; \
545 code = actbl->ehufco[temp3]; \
546 size = actbl->ehufsi[temp3]; \
547 EMIT_CODE(code, size) \
DRC99313382009-03-12 17:24:27 +0000548 r = 0; \
DRC6bb57b72011-04-26 22:08:31 +0000549 } \
550}
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000551
DRC6bb57b72011-04-26 22:08:31 +0000552 /* One iteration for each value in jpeg_natural_order[] */
553 kloop(1); kloop(8); kloop(16); kloop(9); kloop(2); kloop(3);
554 kloop(10); kloop(17); kloop(24); kloop(32); kloop(25); kloop(18);
555 kloop(11); kloop(4); kloop(5); kloop(12); kloop(19); kloop(26);
556 kloop(33); kloop(40); kloop(48); kloop(41); kloop(34); kloop(27);
557 kloop(20); kloop(13); kloop(6); kloop(7); kloop(14); kloop(21);
558 kloop(28); kloop(35); kloop(42); kloop(49); kloop(56); kloop(57);
559 kloop(50); kloop(43); kloop(36); kloop(29); kloop(22); kloop(15);
560 kloop(23); kloop(30); kloop(37); kloop(44); kloop(51); kloop(58);
561 kloop(59); kloop(52); kloop(45); kloop(38); kloop(31); kloop(39);
562 kloop(46); kloop(53); kloop(60); kloop(61); kloop(54); kloop(47);
563 kloop(55); kloop(62); kloop(63);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000564
565 /* If the last coef(s) were zero, emit an end-of-block code */
DRC6bb57b72011-04-26 22:08:31 +0000566 if (r > 0) {
567 code = actbl->ehufco[0];
568 size = actbl->ehufsi[0];
569 EMIT_BITS(code, size)
570 }
DRC99313382009-03-12 17:24:27 +0000571
572 state->cur.put_buffer = put_buffer;
573 state->cur.put_bits = put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000574 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000575
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000576 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000577}
578
579
580/*
581 * Emit a restart marker & resynchronize predictions.
582 */
583
Thomas G. Lane489583f1996-02-07 00:00:00 +0000584LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000585emit_restart (working_state * state, int restart_num)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000586{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000587 int ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000588
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000589 if (! flush_bits(state))
590 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000591
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000592 emit_byte(state, 0xFF, return FALSE);
593 emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000594
595 /* Re-initialize DC predictions to 0 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000596 for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
597 state->cur.last_dc_val[ci] = 0;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000598
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000599 /* The restart counter is not updated until we successfully write the MCU. */
600
601 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000602}
603
604
605/*
606 * Encode and output one MCU's worth of Huffman-compressed coefficients.
607 */
608
Thomas G. Lane489583f1996-02-07 00:00:00 +0000609METHODDEF(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000610encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000611{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000612 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
613 working_state state;
614 int blkn, ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000615 jpeg_component_info * compptr;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000616
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000617 /* Load up working state */
618 state.next_output_byte = cinfo->dest->next_output_byte;
619 state.free_in_buffer = cinfo->dest->free_in_buffer;
620 ASSIGN_STATE(state.cur, entropy->saved);
621 state.cinfo = cinfo;
622
623 /* Emit restart marker if needed */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000624 if (cinfo->restart_interval) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000625 if (entropy->restarts_to_go == 0)
626 if (! emit_restart(&state, entropy->next_restart_num))
627 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000628 }
629
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000630 /* Encode the MCU data blocks */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000631 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
632 ci = cinfo->MCU_membership[blkn];
633 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000634 if (! encode_one_block(&state,
635 MCU_data[blkn][0], state.cur.last_dc_val[ci],
636 entropy->dc_derived_tbls[compptr->dc_tbl_no],
637 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
638 return FALSE;
639 /* Update last_dc_val */
640 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000641 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000642
643 /* Completed MCU, so update state */
644 cinfo->dest->next_output_byte = state.next_output_byte;
645 cinfo->dest->free_in_buffer = state.free_in_buffer;
646 ASSIGN_STATE(entropy->saved, state.cur);
647
648 /* Update restart-interval state too */
649 if (cinfo->restart_interval) {
650 if (entropy->restarts_to_go == 0) {
651 entropy->restarts_to_go = cinfo->restart_interval;
652 entropy->next_restart_num++;
653 entropy->next_restart_num &= 7;
654 }
655 entropy->restarts_to_go--;
656 }
657
658 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000659}
660
661
662/*
663 * Finish up at the end of a Huffman-compressed scan.
664 */
665
Thomas G. Lane489583f1996-02-07 00:00:00 +0000666METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000667finish_pass_huff (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000668{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000669 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
670 working_state state;
671
672 /* Load up working state ... flush_bits needs it */
673 state.next_output_byte = cinfo->dest->next_output_byte;
674 state.free_in_buffer = cinfo->dest->free_in_buffer;
675 ASSIGN_STATE(state.cur, entropy->saved);
676 state.cinfo = cinfo;
677
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000678 /* Flush out the last data */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000679 if (! flush_bits(&state))
680 ERREXIT(cinfo, JERR_CANT_SUSPEND);
681
682 /* Update state */
683 cinfo->dest->next_output_byte = state.next_output_byte;
684 cinfo->dest->free_in_buffer = state.free_in_buffer;
685 ASSIGN_STATE(entropy->saved, state.cur);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000686}
687
688
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000689/*
690 * Huffman coding optimization.
691 *
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000692 * We first scan the supplied data and count the number of uses of each symbol
693 * that is to be Huffman-coded. (This process MUST agree with the code above.)
694 * Then we build a Huffman coding tree for the observed counts.
695 * Symbols which are not needed at all for the particular image are not
696 * assigned any code, which saves space in the DHT marker as well as in
697 * the compressed data.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000698 */
699
700#ifdef ENTROPY_OPT_SUPPORTED
701
702
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000703/* Process a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000704
Thomas G. Lane489583f1996-02-07 00:00:00 +0000705LOCAL(void)
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000706htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000707 long dc_counts[], long ac_counts[])
708{
709 register int temp;
710 register int nbits;
711 register int k, r;
712
713 /* Encode the DC coefficient difference per section F.1.2.1 */
714
715 temp = block[0] - last_dc_val;
716 if (temp < 0)
717 temp = -temp;
718
719 /* Find the number of bits needed for the magnitude of the coefficient */
720 nbits = 0;
721 while (temp) {
722 nbits++;
723 temp >>= 1;
724 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000725 /* Check for out-of-range coefficient values.
726 * Since we're encoding a difference, the range limit is twice as much.
727 */
728 if (nbits > MAX_COEF_BITS+1)
729 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000730
731 /* Count the Huffman symbol for the number of bits */
732 dc_counts[nbits]++;
733
734 /* Encode the AC coefficients per section F.1.2.2 */
735
736 r = 0; /* r = run length of zeros */
737
738 for (k = 1; k < DCTSIZE2; k++) {
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000739 if ((temp = block[jpeg_natural_order[k]]) == 0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000740 r++;
741 } else {
742 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
743 while (r > 15) {
744 ac_counts[0xF0]++;
745 r -= 16;
746 }
747
748 /* Find the number of bits needed for the magnitude of the coefficient */
749 if (temp < 0)
750 temp = -temp;
751
752 /* Find the number of bits needed for the magnitude of the coefficient */
753 nbits = 1; /* there must be at least one 1 bit */
754 while ((temp >>= 1))
755 nbits++;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000756 /* Check for out-of-range coefficient values */
757 if (nbits > MAX_COEF_BITS)
758 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000759
760 /* Count Huffman symbol for run length / number of bits */
761 ac_counts[(r << 4) + nbits]++;
762
763 r = 0;
764 }
765 }
766
767 /* If the last coef(s) were zero, emit an end-of-block code */
768 if (r > 0)
769 ac_counts[0]++;
770}
771
772
773/*
774 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
775 * No data is actually output, so no suspension return is possible.
776 */
777
Thomas G. Lane489583f1996-02-07 00:00:00 +0000778METHODDEF(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000779encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
780{
781 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
782 int blkn, ci;
783 jpeg_component_info * compptr;
784
785 /* Take care of restart intervals if needed */
786 if (cinfo->restart_interval) {
787 if (entropy->restarts_to_go == 0) {
788 /* Re-initialize DC predictions to 0 */
789 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
790 entropy->saved.last_dc_val[ci] = 0;
791 /* Update restart state */
792 entropy->restarts_to_go = cinfo->restart_interval;
793 }
794 entropy->restarts_to_go--;
795 }
796
797 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
798 ci = cinfo->MCU_membership[blkn];
799 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000800 htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000801 entropy->dc_count_ptrs[compptr->dc_tbl_no],
802 entropy->ac_count_ptrs[compptr->ac_tbl_no]);
803 entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
804 }
805
806 return TRUE;
807}
808
809
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000810/*
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000811 * Generate the best Huffman code table for the given counts, fill htbl.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000812 * Note this is also used by jcphuff.c.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000813 *
814 * The JPEG standard requires that no symbol be assigned a codeword of all
815 * one bits (so that padding bits added at the end of a compressed segment
816 * can't look like a valid code). Because of the canonical ordering of
817 * codewords, this just means that there must be an unused slot in the
818 * longest codeword length category. Section K.2 of the JPEG spec suggests
819 * reserving such a slot by pretending that symbol 256 is a valid symbol
820 * with count 1. In theory that's not optimal; giving it count zero but
821 * including it in the symbol set anyway should give a better Huffman code.
822 * But the theoretically better code actually seems to come out worse in
823 * practice, because it produces more all-ones bytes (which incur stuffed
824 * zero bytes in the final file). In any case the difference is tiny.
825 *
826 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
827 * If some symbols have a very small but nonzero probability, the Huffman tree
828 * must be adjusted to meet the code length restriction. We currently use
829 * the adjustment method suggested in JPEG section K.2. This method is *not*
830 * optimal; it may not choose the best possible limited-length code. But
831 * typically only very-low-frequency symbols will be given less-than-optimal
832 * lengths, so the code is almost optimal. Experimental comparisons against
833 * an optimal limited-length-code algorithm indicate that the difference is
834 * microscopic --- usually less than a hundredth of a percent of total size.
835 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000836 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000837
Thomas G. Lane489583f1996-02-07 00:00:00 +0000838GLOBAL(void)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000839jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000840{
841#define MAX_CLEN 32 /* assumed maximum initial code length */
842 UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000843 int codesize[257]; /* codesize[k] = code length of symbol k */
844 int others[257]; /* next symbol in current branch of tree */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000845 int c1, c2;
846 int p, i, j;
847 long v;
848
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000849 /* This algorithm is explained in section K.2 of the JPEG standard */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000850
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000851 MEMZERO(bits, SIZEOF(bits));
852 MEMZERO(codesize, SIZEOF(codesize));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000853 for (i = 0; i < 257; i++)
854 others[i] = -1; /* init links to empty */
855
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000856 freq[256] = 1; /* make sure 256 has a nonzero count */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000857 /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000858 * that no real symbol is given code-value of all ones, because 256
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000859 * will be placed last in the largest codeword category.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000860 */
861
862 /* Huffman's basic algorithm to assign optimal code lengths to symbols */
863
864 for (;;) {
865 /* Find the smallest nonzero frequency, set c1 = its symbol */
866 /* In case of ties, take the larger symbol number */
867 c1 = -1;
868 v = 1000000000L;
869 for (i = 0; i <= 256; i++) {
870 if (freq[i] && freq[i] <= v) {
871 v = freq[i];
872 c1 = i;
873 }
874 }
875
876 /* Find the next smallest nonzero frequency, set c2 = its symbol */
877 /* In case of ties, take the larger symbol number */
878 c2 = -1;
879 v = 1000000000L;
880 for (i = 0; i <= 256; i++) {
881 if (freq[i] && freq[i] <= v && i != c1) {
882 v = freq[i];
883 c2 = i;
884 }
885 }
886
887 /* Done if we've merged everything into one frequency */
888 if (c2 < 0)
889 break;
890
891 /* Else merge the two counts/trees */
892 freq[c1] += freq[c2];
893 freq[c2] = 0;
894
895 /* Increment the codesize of everything in c1's tree branch */
896 codesize[c1]++;
897 while (others[c1] >= 0) {
898 c1 = others[c1];
899 codesize[c1]++;
900 }
901
902 others[c1] = c2; /* chain c2 onto c1's tree branch */
903
904 /* Increment the codesize of everything in c2's tree branch */
905 codesize[c2]++;
906 while (others[c2] >= 0) {
907 c2 = others[c2];
908 codesize[c2]++;
909 }
910 }
911
912 /* Now count the number of symbols of each code length */
913 for (i = 0; i <= 256; i++) {
914 if (codesize[i]) {
915 /* The JPEG standard seems to think that this can't happen, */
916 /* but I'm paranoid... */
917 if (codesize[i] > MAX_CLEN)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000918 ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000919
920 bits[codesize[i]]++;
921 }
922 }
923
924 /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
925 * Huffman procedure assigned any such lengths, we must adjust the coding.
926 * Here is what the JPEG spec says about how this next bit works:
927 * Since symbols are paired for the longest Huffman code, the symbols are
928 * removed from this length category two at a time. The prefix for the pair
929 * (which is one bit shorter) is allocated to one of the pair; then,
930 * skipping the BITS entry for that prefix length, a code word from the next
931 * shortest nonzero BITS entry is converted into a prefix for two code words
932 * one bit longer.
933 */
934
935 for (i = MAX_CLEN; i > 16; i--) {
936 while (bits[i] > 0) {
937 j = i - 2; /* find length of new prefix to be used */
938 while (bits[j] == 0)
939 j--;
940
941 bits[i] -= 2; /* remove two symbols */
942 bits[i-1]++; /* one goes in this length */
943 bits[j+1] += 2; /* two new symbols in this length */
944 bits[j]--; /* symbol of this length is now a prefix */
945 }
946 }
947
948 /* Remove the count for the pseudo-symbol 256 from the largest codelength */
949 while (bits[i] == 0) /* find largest codelength still in use */
950 i--;
951 bits[i]--;
952
953 /* Return final symbol counts (only for lengths 0..16) */
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000954 MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000955
956 /* Return a list of the symbols sorted by code length */
957 /* It's not real clear to me why we don't need to consider the codelength
958 * changes made above, but the JPEG spec seems to think this works.
959 */
960 p = 0;
961 for (i = 1; i <= MAX_CLEN; i++) {
962 for (j = 0; j <= 255; j++) {
963 if (codesize[j] == i) {
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000964 htbl->huffval[p] = (UINT8) j;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000965 p++;
966 }
967 }
968 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000969
970 /* Set sent_table FALSE so updated table will be written to JPEG file. */
971 htbl->sent_table = FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000972}
973
974
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000975/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000976 * Finish up a statistics-gathering pass and create the new Huffman tables.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000977 */
978
Thomas G. Lane489583f1996-02-07 00:00:00 +0000979METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000980finish_pass_gather (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000981{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000982 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
983 int ci, dctbl, actbl;
984 jpeg_component_info * compptr;
985 JHUFF_TBL **htblptr;
986 boolean did_dc[NUM_HUFF_TBLS];
987 boolean did_ac[NUM_HUFF_TBLS];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000988
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000989 /* It's important not to apply jpeg_gen_optimal_table more than once
990 * per table, because it clobbers the input frequency counts!
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000991 */
992 MEMZERO(did_dc, SIZEOF(did_dc));
993 MEMZERO(did_ac, SIZEOF(did_ac));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000994
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000995 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
996 compptr = cinfo->cur_comp_info[ci];
997 dctbl = compptr->dc_tbl_no;
998 actbl = compptr->ac_tbl_no;
999 if (! did_dc[dctbl]) {
1000 htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001001 if (*htblptr == NULL)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001002 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001003 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001004 did_dc[dctbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001005 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001006 if (! did_ac[actbl]) {
1007 htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001008 if (*htblptr == NULL)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001009 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001010 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001011 did_ac[actbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001012 }
1013 }
1014}
1015
1016
1017#endif /* ENTROPY_OPT_SUPPORTED */
1018
1019
1020/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001021 * Module initialization routine for Huffman entropy encoding.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001022 */
1023
Thomas G. Lane489583f1996-02-07 00:00:00 +00001024GLOBAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001025jinit_huff_encoder (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001026{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001027 huff_entropy_ptr entropy;
1028 int i;
1029
1030 entropy = (huff_entropy_ptr)
1031 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1032 SIZEOF(huff_entropy_encoder));
1033 cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
1034 entropy->pub.start_pass = start_pass_huff;
1035
1036 /* Mark tables unallocated */
1037 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1038 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001039#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001040 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001041#endif
1042 }
1043}