blob: fd4fa46ca5311f23f3c9ae991eb38abf13f83d4d [file] [log] [blame]
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001/*
2 * jchuff.c
3 *
4 * Copyright (C) 1991-1997, Thomas G. Lane.
hbono@chromium.org98626972011-08-03 03:13:08 +00005 * Copyright (C) 2009-2011, D. R. Commander.
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00006 * This file is part of the Independent JPEG Group's software.
7 * For conditions of distribution and use, see the accompanying README file.
8 *
9 * This file contains Huffman entropy encoding routines.
10 *
11 * Much of the complexity here has to do with supporting output suspension.
12 * If the data destination module demands suspension, we want to be able to
13 * back up to the start of the current MCU. To do this, we copy state
14 * variables into local working storage, and update them back to the
15 * permanent JPEG objects only upon successful completion of an MCU.
16 */
17
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +000018#define JPEG_INTERNALS
19#include "jinclude.h"
20#include "jpeglib.h"
21#include "jchuff.h" /* Declarations shared with jcphuff.c */
22#include <limits.h>
23
hbono@chromium.org98626972011-08-03 03:13:08 +000024static unsigned char jpeg_nbits_table[65536];
25static int jpeg_nbits_table_init = 0;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +000026
27#ifndef min
28 #define min(a,b) ((a)<(b)?(a):(b))
29#endif
30
hbono@chromium.org98626972011-08-03 03:13:08 +000031
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +000032/* Expanded entropy encoder object for Huffman encoding.
33 *
34 * The savable_state subrecord contains fields that change within an MCU,
35 * but must not be updated permanently until we complete the MCU.
36 */
37
38typedef struct {
39 size_t put_buffer; /* current bit-accumulation buffer */
40 int put_bits; /* # of bits now in it */
41 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
42} savable_state;
43
44/* This macro is to work around compilers with missing or broken
45 * structure assignment. You'll need to fix this code if you have
46 * such a compiler and you change MAX_COMPS_IN_SCAN.
47 */
48
49#ifndef NO_STRUCT_ASSIGN
50#define ASSIGN_STATE(dest,src) ((dest) = (src))
51#else
52#if MAX_COMPS_IN_SCAN == 4
53#define ASSIGN_STATE(dest,src) \
54 ((dest).put_buffer = (src).put_buffer, \
55 (dest).put_bits = (src).put_bits, \
56 (dest).last_dc_val[0] = (src).last_dc_val[0], \
57 (dest).last_dc_val[1] = (src).last_dc_val[1], \
58 (dest).last_dc_val[2] = (src).last_dc_val[2], \
59 (dest).last_dc_val[3] = (src).last_dc_val[3])
60#endif
61#endif
62
63
64typedef struct {
65 struct jpeg_entropy_encoder pub; /* public fields */
66
67 savable_state saved; /* Bit buffer & DC state at start of MCU */
68
69 /* These fields are NOT loaded into local working state. */
70 unsigned int restarts_to_go; /* MCUs left in this restart interval */
71 int next_restart_num; /* next restart number to write (0-7) */
72
73 /* Pointers to derived tables (these workspaces have image lifespan) */
74 c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
75 c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
76
77#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
78 long * dc_count_ptrs[NUM_HUFF_TBLS];
79 long * ac_count_ptrs[NUM_HUFF_TBLS];
80#endif
81} huff_entropy_encoder;
82
83typedef huff_entropy_encoder * huff_entropy_ptr;
84
85/* Working state while writing an MCU.
86 * This struct contains all the fields that are needed by subroutines.
87 */
88
89typedef struct {
90 JOCTET * next_output_byte; /* => next byte to write in buffer */
91 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
92 savable_state cur; /* Current bit buffer & DC state */
93 j_compress_ptr cinfo; /* dump_buffer needs access to this */
94} working_state;
95
96
97/* Forward declarations */
98METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
99 JBLOCKROW *MCU_data));
100METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
101#ifdef ENTROPY_OPT_SUPPORTED
102METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
103 JBLOCKROW *MCU_data));
104METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
105#endif
106
107
108/*
109 * Initialize for a Huffman-compressed scan.
110 * If gather_statistics is TRUE, we do not output anything during the scan,
111 * just count the Huffman symbols used and generate Huffman code tables.
112 */
113
114METHODDEF(void)
115start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
116{
117 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
118 int ci, dctbl, actbl;
119 jpeg_component_info * compptr;
120
121 if (gather_statistics) {
122#ifdef ENTROPY_OPT_SUPPORTED
123 entropy->pub.encode_mcu = encode_mcu_gather;
124 entropy->pub.finish_pass = finish_pass_gather;
125#else
126 ERREXIT(cinfo, JERR_NOT_COMPILED);
127#endif
128 } else {
129 entropy->pub.encode_mcu = encode_mcu_huff;
130 entropy->pub.finish_pass = finish_pass_huff;
131 }
132
133 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
134 compptr = cinfo->cur_comp_info[ci];
135 dctbl = compptr->dc_tbl_no;
136 actbl = compptr->ac_tbl_no;
137 if (gather_statistics) {
138#ifdef ENTROPY_OPT_SUPPORTED
139 /* Check for invalid table indexes */
140 /* (make_c_derived_tbl does this in the other path) */
141 if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
142 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
143 if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
144 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
145 /* Allocate and zero the statistics tables */
146 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
147 if (entropy->dc_count_ptrs[dctbl] == NULL)
148 entropy->dc_count_ptrs[dctbl] = (long *)
149 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
150 257 * SIZEOF(long));
151 MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
152 if (entropy->ac_count_ptrs[actbl] == NULL)
153 entropy->ac_count_ptrs[actbl] = (long *)
154 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
155 257 * SIZEOF(long));
156 MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
157#endif
158 } else {
159 /* Compute derived values for Huffman tables */
160 /* We may do this more than once for a table, but it's not expensive */
161 jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
162 & entropy->dc_derived_tbls[dctbl]);
163 jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
164 & entropy->ac_derived_tbls[actbl]);
165 }
166 /* Initialize DC predictions to 0 */
167 entropy->saved.last_dc_val[ci] = 0;
168 }
169
170 /* Initialize bit buffer to empty */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000171 entropy->saved.put_buffer = 0;
172 entropy->saved.put_bits = 0;
173
174 /* Initialize restart stuff */
175 entropy->restarts_to_go = cinfo->restart_interval;
176 entropy->next_restart_num = 0;
177}
178
179
180/*
181 * Compute the derived values for a Huffman table.
182 * This routine also performs some validation checks on the table.
183 *
184 * Note this is also used by jcphuff.c.
185 */
186
187GLOBAL(void)
188jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
189 c_derived_tbl ** pdtbl)
190{
191 JHUFF_TBL *htbl;
192 c_derived_tbl *dtbl;
193 int p, i, l, lastp, si, maxsymbol;
194 char huffsize[257];
195 unsigned int huffcode[257];
196 unsigned int code;
197
198 /* Note that huffsize[] and huffcode[] are filled in code-length order,
199 * paralleling the order of the symbols themselves in htbl->huffval[].
200 */
201
202 /* Find the input Huffman table */
203 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
204 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
205 htbl =
206 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
207 if (htbl == NULL)
208 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
209
210 /* Allocate a workspace if we haven't already done so. */
211 if (*pdtbl == NULL)
212 *pdtbl = (c_derived_tbl *)
213 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
214 SIZEOF(c_derived_tbl));
215 dtbl = *pdtbl;
216
217 /* Figure C.1: make table of Huffman code length for each symbol */
218
219 p = 0;
220 for (l = 1; l <= 16; l++) {
221 i = (int) htbl->bits[l];
222 if (i < 0 || p + i > 256) /* protect against table overrun */
223 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
224 while (i--)
225 huffsize[p++] = (char) l;
226 }
227 huffsize[p] = 0;
228 lastp = p;
229
230 /* Figure C.2: generate the codes themselves */
231 /* We also validate that the counts represent a legal Huffman code tree. */
232
233 code = 0;
234 si = huffsize[0];
235 p = 0;
236 while (huffsize[p]) {
237 while (((int) huffsize[p]) == si) {
238 huffcode[p++] = code;
239 code++;
240 }
241 /* code is now 1 more than the last code used for codelength si; but
242 * it must still fit in si bits, since no code is allowed to be all ones.
243 */
244 if (((INT32) code) >= (((INT32) 1) << si))
245 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
246 code <<= 1;
247 si++;
248 }
249
250 /* Figure C.3: generate encoding tables */
251 /* These are code and size indexed by symbol value */
252
253 /* Set all codeless symbols to have code length 0;
254 * this lets us detect duplicate VAL entries here, and later
255 * allows emit_bits to detect any attempt to emit such symbols.
256 */
257 MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
258
259 /* This is also a convenient place to check for out-of-range
260 * and duplicated VAL entries. We allow 0..255 for AC symbols
261 * but only 0..15 for DC. (We could constrain them further
262 * based on data depth and mode, but this seems enough.)
263 */
264 maxsymbol = isDC ? 15 : 255;
265
266 for (p = 0; p < lastp; p++) {
267 i = htbl->huffval[p];
268 if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
269 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
270 dtbl->ehufco[i] = huffcode[p];
271 dtbl->ehufsi[i] = huffsize[p];
272 }
273
hbono@chromium.org98626972011-08-03 03:13:08 +0000274 if(!jpeg_nbits_table_init) {
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000275 for(i = 0; i < 65536; i++) {
hbono@chromium.org98626972011-08-03 03:13:08 +0000276 int nbits = 0, temp = i;
277 while (temp) {temp >>= 1; nbits++;}
278 jpeg_nbits_table[i] = nbits;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000279 }
hbono@chromium.org98626972011-08-03 03:13:08 +0000280 jpeg_nbits_table_init = 1;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000281 }
282}
283
284
285/* Outputting bytes to the file */
286
287/* Emit a byte, taking 'action' if must suspend. */
288#define emit_byte(state,val,action) \
289 { *(state)->next_output_byte++ = (JOCTET) (val); \
290 if (--(state)->free_in_buffer == 0) \
291 if (! dump_buffer(state)) \
292 { action; } }
293
294
295LOCAL(boolean)
296dump_buffer (working_state * state)
297/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
298{
299 struct jpeg_destination_mgr * dest = state->cinfo->dest;
300
301 dest->free_in_buffer = state->free_in_buffer;
302
303 if (! (*dest->empty_output_buffer) (state->cinfo))
304 return FALSE;
305 /* After a successful buffer dump, must reset buffer pointers */
306 state->next_output_byte = dest->next_output_byte;
307 state->free_in_buffer = dest->free_in_buffer;
308 return TRUE;
309}
310
311
312/* Outputting bits to the file */
313
hbono@chromium.org98626972011-08-03 03:13:08 +0000314/* These macros perform the same task as the emit_bits() function in the
315 * original libjpeg code. In addition to reducing overhead by explicitly
316 * inlining the code, additional performance is achieved by taking into
317 * account the size of the bit buffer and waiting until it is almost full
318 * before emptying it. This mostly benefits 64-bit platforms, since 6
319 * bytes can be stored in a 64-bit bit buffer before it has to be emptied.
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000320 */
321
hbono@chromium.org98626972011-08-03 03:13:08 +0000322#define EMIT_BYTE() { \
323 JOCTET c; \
324 put_bits -= 8; \
325 c = (JOCTET)GETJOCTET(put_buffer >> put_bits); \
326 *buffer++ = c; \
327 if (c == 0xFF) /* need to stuff a zero byte? */ \
328 *buffer++ = 0; \
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000329 }
330
hbono@chromium.org98626972011-08-03 03:13:08 +0000331#define PUT_BITS(code, size) { \
332 put_bits += size; \
333 put_buffer = (put_buffer << size) | code; \
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000334}
335
hbono@chromium.org98626972011-08-03 03:13:08 +0000336#define CHECKBUF15() { \
337 if (put_bits > 15) { \
338 EMIT_BYTE() \
339 EMIT_BYTE() \
340 } \
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000341}
342
hbono@chromium.org98626972011-08-03 03:13:08 +0000343#define CHECKBUF31() { \
344 if (put_bits > 31) { \
345 EMIT_BYTE() \
346 EMIT_BYTE() \
347 EMIT_BYTE() \
348 EMIT_BYTE() \
349 } \
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000350}
351
hbono@chromium.org98626972011-08-03 03:13:08 +0000352#define CHECKBUF47() { \
353 if (put_bits > 47) { \
354 EMIT_BYTE() \
355 EMIT_BYTE() \
356 EMIT_BYTE() \
357 EMIT_BYTE() \
358 EMIT_BYTE() \
359 EMIT_BYTE() \
360 } \
361}
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000362
363#if __WORDSIZE==64 || defined(_WIN64)
364
hbono@chromium.org98626972011-08-03 03:13:08 +0000365#define EMIT_BITS(code, size) { \
366 CHECKBUF47() \
367 PUT_BITS(code, size) \
368}
369
370#define EMIT_CODE(code, size) { \
371 temp2 &= (((INT32) 1)<<nbits) - 1; \
372 CHECKBUF31() \
373 PUT_BITS(code, size) \
374 PUT_BITS(temp2, nbits) \
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000375 }
376
377#else
378
hbono@chromium.org98626972011-08-03 03:13:08 +0000379#define EMIT_BITS(code, size) { \
380 PUT_BITS(code, size) \
381 CHECKBUF15() \
382}
383
384#define EMIT_CODE(code, size) { \
385 temp2 &= (((INT32) 1)<<nbits) - 1; \
386 PUT_BITS(code, size) \
387 CHECKBUF15() \
388 PUT_BITS(temp2, nbits) \
389 CHECKBUF15() \
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000390 }
391
392#endif
393
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000394
395#define BUFSIZE (DCTSIZE2 * 2)
396
hbono@chromium.org98626972011-08-03 03:13:08 +0000397#define LOAD_BUFFER() { \
398 if (state->free_in_buffer < BUFSIZE) { \
399 localbuf = 1; \
400 buffer = _buffer; \
401 } \
402 else buffer = state->next_output_byte; \
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000403 }
404
hbono@chromium.org98626972011-08-03 03:13:08 +0000405#define STORE_BUFFER() { \
406 if (localbuf) { \
407 bytes = buffer - _buffer; \
408 buffer = _buffer; \
409 while (bytes > 0) { \
410 bytestocopy = min(bytes, state->free_in_buffer); \
411 MEMCOPY(state->next_output_byte, buffer, bytestocopy); \
412 state->next_output_byte += bytestocopy; \
413 buffer += bytestocopy; \
414 state->free_in_buffer -= bytestocopy; \
415 if (state->free_in_buffer == 0) \
416 if (! dump_buffer(state)) return FALSE; \
417 bytes -= bytestocopy; \
418 } \
419 } \
420 else { \
421 state->free_in_buffer -= (buffer - state->next_output_byte); \
422 state->next_output_byte = buffer; \
423 } \
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000424 }
425
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000426
427LOCAL(boolean)
428flush_bits (working_state * state)
429{
hbono@chromium.org98626972011-08-03 03:13:08 +0000430 JOCTET _buffer[BUFSIZE], *buffer;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000431 size_t put_buffer; int put_bits;
432 size_t bytes, bytestocopy; int localbuf = 0;
433
434 put_buffer = state->cur.put_buffer;
435 put_bits = state->cur.put_bits;
436 LOAD_BUFFER()
437
hbono@chromium.org98626972011-08-03 03:13:08 +0000438 /* fill any partial byte with ones */
439 PUT_BITS(0x7F, 7)
440 while (put_bits >= 8) EMIT_BYTE()
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000441
442 state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
443 state->cur.put_bits = 0;
444 STORE_BUFFER()
445
446 return TRUE;
447}
448
hbono@chromium.org98626972011-08-03 03:13:08 +0000449
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000450/* Encode a single block's worth of coefficients */
451
452LOCAL(boolean)
453encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
454 c_derived_tbl *dctbl, c_derived_tbl *actbl)
455{
hbono@chromium.org98626972011-08-03 03:13:08 +0000456 int temp, temp2, temp3;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000457 int nbits;
hbono@chromium.org98626972011-08-03 03:13:08 +0000458 int r, code, size;
459 JOCTET _buffer[BUFSIZE], *buffer;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000460 size_t put_buffer; int put_bits;
461 int code_0xf0 = actbl->ehufco[0xf0], size_0xf0 = actbl->ehufsi[0xf0];
462 size_t bytes, bytestocopy; int localbuf = 0;
463
464 put_buffer = state->cur.put_buffer;
465 put_bits = state->cur.put_bits;
466 LOAD_BUFFER()
467
468 /* Encode the DC coefficient difference per section F.1.2.1 */
469
470 temp = temp2 = block[0] - last_dc_val;
471
hbono@chromium.org98626972011-08-03 03:13:08 +0000472 /* This is a well-known technique for obtaining the absolute value without a
473 * branch. It is derived from an assembly language technique presented in
474 * "How to Optimize for the Pentium Processors", Copyright (c) 1996, 1997 by
475 * Agner Fog.
476 */
477 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1);
478 temp ^= temp3;
479 temp -= temp3;
480
481 /* For a negative input, want temp2 = bitwise complement of abs(input) */
482 /* This code assumes we are on a two's complement machine */
483 temp2 += temp3;
484
485 /* Find the number of bits needed for the magnitude of the coefficient */
486 nbits = jpeg_nbits_table[temp];
487
488 /* Emit the Huffman-coded symbol for the number of bits */
489 code = dctbl->ehufco[nbits];
490 size = dctbl->ehufsi[nbits];
491 PUT_BITS(code, size)
492 CHECKBUF15()
493
494 /* Mask off any extra bits in code */
495 temp2 &= (((INT32) 1)<<nbits) - 1;
496
497 /* Emit that number of bits of the value, if positive, */
498 /* or the complement of its magnitude, if negative. */
499 PUT_BITS(temp2, nbits)
500 CHECKBUF15()
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000501
502 /* Encode the AC coefficients per section F.1.2.2 */
503
504 r = 0; /* r = run length of zeros */
505
hbono@chromium.org98626972011-08-03 03:13:08 +0000506/* Manually unroll the k loop to eliminate the counter variable. This
507 * improves performance greatly on systems with a limited number of
508 * registers (such as x86.)
509 */
510#define kloop(jpeg_natural_order_of_k) { \
511 if ((temp = block[jpeg_natural_order_of_k]) == 0) { \
512 r++; \
513 } else { \
514 temp2 = temp; \
515 /* Branch-less absolute value, bitwise complement, etc., same as above */ \
516 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1); \
517 temp ^= temp3; \
518 temp -= temp3; \
519 temp2 += temp3; \
520 nbits = jpeg_nbits_table[temp]; \
521 /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \
522 while (r > 15) { \
523 EMIT_BITS(code_0xf0, size_0xf0) \
524 r -= 16; \
525 } \
526 /* Emit Huffman symbol for run length / number of bits */ \
527 temp3 = (r << 4) + nbits; \
528 code = actbl->ehufco[temp3]; \
529 size = actbl->ehufsi[temp3]; \
530 EMIT_CODE(code, size) \
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000531 r = 0; \
hbono@chromium.org98626972011-08-03 03:13:08 +0000532 } \
533}
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000534
hbono@chromium.org98626972011-08-03 03:13:08 +0000535 /* One iteration for each value in jpeg_natural_order[] */
536 kloop(1); kloop(8); kloop(16); kloop(9); kloop(2); kloop(3);
537 kloop(10); kloop(17); kloop(24); kloop(32); kloop(25); kloop(18);
538 kloop(11); kloop(4); kloop(5); kloop(12); kloop(19); kloop(26);
539 kloop(33); kloop(40); kloop(48); kloop(41); kloop(34); kloop(27);
540 kloop(20); kloop(13); kloop(6); kloop(7); kloop(14); kloop(21);
541 kloop(28); kloop(35); kloop(42); kloop(49); kloop(56); kloop(57);
542 kloop(50); kloop(43); kloop(36); kloop(29); kloop(22); kloop(15);
543 kloop(23); kloop(30); kloop(37); kloop(44); kloop(51); kloop(58);
544 kloop(59); kloop(52); kloop(45); kloop(38); kloop(31); kloop(39);
545 kloop(46); kloop(53); kloop(60); kloop(61); kloop(54); kloop(47);
546 kloop(55); kloop(62); kloop(63);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000547
548 /* If the last coef(s) were zero, emit an end-of-block code */
hbono@chromium.org98626972011-08-03 03:13:08 +0000549 if (r > 0) {
550 code = actbl->ehufco[0];
551 size = actbl->ehufsi[0];
552 EMIT_BITS(code, size)
553 }
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000554
555 state->cur.put_buffer = put_buffer;
556 state->cur.put_bits = put_bits;
557 STORE_BUFFER()
558
559 return TRUE;
560}
561
562
563/*
564 * Emit a restart marker & resynchronize predictions.
565 */
566
567LOCAL(boolean)
568emit_restart (working_state * state, int restart_num)
569{
570 int ci;
571
572 if (! flush_bits(state))
573 return FALSE;
574
575 emit_byte(state, 0xFF, return FALSE);
576 emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
577
578 /* Re-initialize DC predictions to 0 */
579 for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
580 state->cur.last_dc_val[ci] = 0;
581
582 /* The restart counter is not updated until we successfully write the MCU. */
583
584 return TRUE;
585}
586
587
588/*
589 * Encode and output one MCU's worth of Huffman-compressed coefficients.
590 */
591
592METHODDEF(boolean)
593encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
594{
595 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
596 working_state state;
597 int blkn, ci;
598 jpeg_component_info * compptr;
599
600 /* Load up working state */
601 state.next_output_byte = cinfo->dest->next_output_byte;
602 state.free_in_buffer = cinfo->dest->free_in_buffer;
603 ASSIGN_STATE(state.cur, entropy->saved);
604 state.cinfo = cinfo;
605
606 /* Emit restart marker if needed */
607 if (cinfo->restart_interval) {
608 if (entropy->restarts_to_go == 0)
609 if (! emit_restart(&state, entropy->next_restart_num))
610 return FALSE;
611 }
612
613 /* Encode the MCU data blocks */
614 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
615 ci = cinfo->MCU_membership[blkn];
616 compptr = cinfo->cur_comp_info[ci];
617 if (! encode_one_block(&state,
618 MCU_data[blkn][0], state.cur.last_dc_val[ci],
619 entropy->dc_derived_tbls[compptr->dc_tbl_no],
620 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
621 return FALSE;
622 /* Update last_dc_val */
623 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
624 }
625
626 /* Completed MCU, so update state */
627 cinfo->dest->next_output_byte = state.next_output_byte;
628 cinfo->dest->free_in_buffer = state.free_in_buffer;
629 ASSIGN_STATE(entropy->saved, state.cur);
630
631 /* Update restart-interval state too */
632 if (cinfo->restart_interval) {
633 if (entropy->restarts_to_go == 0) {
634 entropy->restarts_to_go = cinfo->restart_interval;
635 entropy->next_restart_num++;
636 entropy->next_restart_num &= 7;
637 }
638 entropy->restarts_to_go--;
639 }
640
641 return TRUE;
642}
643
644
645/*
646 * Finish up at the end of a Huffman-compressed scan.
647 */
648
649METHODDEF(void)
650finish_pass_huff (j_compress_ptr cinfo)
651{
652 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
653 working_state state;
654
655 /* Load up working state ... flush_bits needs it */
656 state.next_output_byte = cinfo->dest->next_output_byte;
657 state.free_in_buffer = cinfo->dest->free_in_buffer;
658 ASSIGN_STATE(state.cur, entropy->saved);
659 state.cinfo = cinfo;
660
661 /* Flush out the last data */
662 if (! flush_bits(&state))
663 ERREXIT(cinfo, JERR_CANT_SUSPEND);
664
665 /* Update state */
666 cinfo->dest->next_output_byte = state.next_output_byte;
667 cinfo->dest->free_in_buffer = state.free_in_buffer;
668 ASSIGN_STATE(entropy->saved, state.cur);
669}
670
671
672/*
673 * Huffman coding optimization.
674 *
675 * We first scan the supplied data and count the number of uses of each symbol
676 * that is to be Huffman-coded. (This process MUST agree with the code above.)
677 * Then we build a Huffman coding tree for the observed counts.
678 * Symbols which are not needed at all for the particular image are not
679 * assigned any code, which saves space in the DHT marker as well as in
680 * the compressed data.
681 */
682
683#ifdef ENTROPY_OPT_SUPPORTED
684
685
686/* Process a single block's worth of coefficients */
687
688LOCAL(void)
689htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
690 long dc_counts[], long ac_counts[])
691{
692 register int temp;
693 register int nbits;
694 register int k, r;
695
696 /* Encode the DC coefficient difference per section F.1.2.1 */
697
698 temp = block[0] - last_dc_val;
699 if (temp < 0)
700 temp = -temp;
701
702 /* Find the number of bits needed for the magnitude of the coefficient */
703 nbits = 0;
704 while (temp) {
705 nbits++;
706 temp >>= 1;
707 }
708 /* Check for out-of-range coefficient values.
709 * Since we're encoding a difference, the range limit is twice as much.
710 */
711 if (nbits > MAX_COEF_BITS+1)
712 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
713
714 /* Count the Huffman symbol for the number of bits */
715 dc_counts[nbits]++;
716
717 /* Encode the AC coefficients per section F.1.2.2 */
718
719 r = 0; /* r = run length of zeros */
720
721 for (k = 1; k < DCTSIZE2; k++) {
722 if ((temp = block[jpeg_natural_order[k]]) == 0) {
723 r++;
724 } else {
725 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
726 while (r > 15) {
727 ac_counts[0xF0]++;
728 r -= 16;
729 }
730
731 /* Find the number of bits needed for the magnitude of the coefficient */
732 if (temp < 0)
733 temp = -temp;
734
735 /* Find the number of bits needed for the magnitude of the coefficient */
736 nbits = 1; /* there must be at least one 1 bit */
737 while ((temp >>= 1))
738 nbits++;
739 /* Check for out-of-range coefficient values */
740 if (nbits > MAX_COEF_BITS)
741 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
742
743 /* Count Huffman symbol for run length / number of bits */
744 ac_counts[(r << 4) + nbits]++;
745
746 r = 0;
747 }
748 }
749
750 /* If the last coef(s) were zero, emit an end-of-block code */
751 if (r > 0)
752 ac_counts[0]++;
753}
754
755
756/*
757 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
758 * No data is actually output, so no suspension return is possible.
759 */
760
761METHODDEF(boolean)
762encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
763{
764 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
765 int blkn, ci;
766 jpeg_component_info * compptr;
767
768 /* Take care of restart intervals if needed */
769 if (cinfo->restart_interval) {
770 if (entropy->restarts_to_go == 0) {
771 /* Re-initialize DC predictions to 0 */
772 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
773 entropy->saved.last_dc_val[ci] = 0;
774 /* Update restart state */
775 entropy->restarts_to_go = cinfo->restart_interval;
776 }
777 entropy->restarts_to_go--;
778 }
779
780 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
781 ci = cinfo->MCU_membership[blkn];
782 compptr = cinfo->cur_comp_info[ci];
783 htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
784 entropy->dc_count_ptrs[compptr->dc_tbl_no],
785 entropy->ac_count_ptrs[compptr->ac_tbl_no]);
786 entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
787 }
788
789 return TRUE;
790}
791
792
793/*
794 * Generate the best Huffman code table for the given counts, fill htbl.
795 * Note this is also used by jcphuff.c.
796 *
797 * The JPEG standard requires that no symbol be assigned a codeword of all
798 * one bits (so that padding bits added at the end of a compressed segment
799 * can't look like a valid code). Because of the canonical ordering of
800 * codewords, this just means that there must be an unused slot in the
801 * longest codeword length category. Section K.2 of the JPEG spec suggests
802 * reserving such a slot by pretending that symbol 256 is a valid symbol
803 * with count 1. In theory that's not optimal; giving it count zero but
804 * including it in the symbol set anyway should give a better Huffman code.
805 * But the theoretically better code actually seems to come out worse in
806 * practice, because it produces more all-ones bytes (which incur stuffed
807 * zero bytes in the final file). In any case the difference is tiny.
808 *
809 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
810 * If some symbols have a very small but nonzero probability, the Huffman tree
811 * must be adjusted to meet the code length restriction. We currently use
812 * the adjustment method suggested in JPEG section K.2. This method is *not*
813 * optimal; it may not choose the best possible limited-length code. But
814 * typically only very-low-frequency symbols will be given less-than-optimal
815 * lengths, so the code is almost optimal. Experimental comparisons against
816 * an optimal limited-length-code algorithm indicate that the difference is
817 * microscopic --- usually less than a hundredth of a percent of total size.
818 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
819 */
820
821GLOBAL(void)
822jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
823{
824#define MAX_CLEN 32 /* assumed maximum initial code length */
825 UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
826 int codesize[257]; /* codesize[k] = code length of symbol k */
827 int others[257]; /* next symbol in current branch of tree */
828 int c1, c2;
829 int p, i, j;
830 long v;
831
832 /* This algorithm is explained in section K.2 of the JPEG standard */
833
834 MEMZERO(bits, SIZEOF(bits));
835 MEMZERO(codesize, SIZEOF(codesize));
836 for (i = 0; i < 257; i++)
837 others[i] = -1; /* init links to empty */
838
839 freq[256] = 1; /* make sure 256 has a nonzero count */
840 /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
841 * that no real symbol is given code-value of all ones, because 256
842 * will be placed last in the largest codeword category.
843 */
844
845 /* Huffman's basic algorithm to assign optimal code lengths to symbols */
846
847 for (;;) {
848 /* Find the smallest nonzero frequency, set c1 = its symbol */
849 /* In case of ties, take the larger symbol number */
850 c1 = -1;
851 v = 1000000000L;
852 for (i = 0; i <= 256; i++) {
853 if (freq[i] && freq[i] <= v) {
854 v = freq[i];
855 c1 = i;
856 }
857 }
858
859 /* Find the next smallest nonzero frequency, set c2 = its symbol */
860 /* In case of ties, take the larger symbol number */
861 c2 = -1;
862 v = 1000000000L;
863 for (i = 0; i <= 256; i++) {
864 if (freq[i] && freq[i] <= v && i != c1) {
865 v = freq[i];
866 c2 = i;
867 }
868 }
869
870 /* Done if we've merged everything into one frequency */
871 if (c2 < 0)
872 break;
873
874 /* Else merge the two counts/trees */
875 freq[c1] += freq[c2];
876 freq[c2] = 0;
877
878 /* Increment the codesize of everything in c1's tree branch */
879 codesize[c1]++;
880 while (others[c1] >= 0) {
881 c1 = others[c1];
882 codesize[c1]++;
883 }
884
885 others[c1] = c2; /* chain c2 onto c1's tree branch */
886
887 /* Increment the codesize of everything in c2's tree branch */
888 codesize[c2]++;
889 while (others[c2] >= 0) {
890 c2 = others[c2];
891 codesize[c2]++;
892 }
893 }
894
895 /* Now count the number of symbols of each code length */
896 for (i = 0; i <= 256; i++) {
897 if (codesize[i]) {
898 /* The JPEG standard seems to think that this can't happen, */
899 /* but I'm paranoid... */
900 if (codesize[i] > MAX_CLEN)
901 ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
902
903 bits[codesize[i]]++;
904 }
905 }
906
907 /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
908 * Huffman procedure assigned any such lengths, we must adjust the coding.
909 * Here is what the JPEG spec says about how this next bit works:
910 * Since symbols are paired for the longest Huffman code, the symbols are
911 * removed from this length category two at a time. The prefix for the pair
912 * (which is one bit shorter) is allocated to one of the pair; then,
913 * skipping the BITS entry for that prefix length, a code word from the next
914 * shortest nonzero BITS entry is converted into a prefix for two code words
915 * one bit longer.
916 */
917
918 for (i = MAX_CLEN; i > 16; i--) {
919 while (bits[i] > 0) {
920 j = i - 2; /* find length of new prefix to be used */
921 while (bits[j] == 0)
922 j--;
923
924 bits[i] -= 2; /* remove two symbols */
925 bits[i-1]++; /* one goes in this length */
926 bits[j+1] += 2; /* two new symbols in this length */
927 bits[j]--; /* symbol of this length is now a prefix */
928 }
929 }
930
931 /* Remove the count for the pseudo-symbol 256 from the largest codelength */
932 while (bits[i] == 0) /* find largest codelength still in use */
933 i--;
934 bits[i]--;
935
936 /* Return final symbol counts (only for lengths 0..16) */
937 MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
938
939 /* Return a list of the symbols sorted by code length */
940 /* It's not real clear to me why we don't need to consider the codelength
941 * changes made above, but the JPEG spec seems to think this works.
942 */
943 p = 0;
944 for (i = 1; i <= MAX_CLEN; i++) {
945 for (j = 0; j <= 255; j++) {
946 if (codesize[j] == i) {
947 htbl->huffval[p] = (UINT8) j;
948 p++;
949 }
950 }
951 }
952
953 /* Set sent_table FALSE so updated table will be written to JPEG file. */
954 htbl->sent_table = FALSE;
955}
956
957
958/*
959 * Finish up a statistics-gathering pass and create the new Huffman tables.
960 */
961
962METHODDEF(void)
963finish_pass_gather (j_compress_ptr cinfo)
964{
965 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
966 int ci, dctbl, actbl;
967 jpeg_component_info * compptr;
968 JHUFF_TBL **htblptr;
969 boolean did_dc[NUM_HUFF_TBLS];
970 boolean did_ac[NUM_HUFF_TBLS];
971
972 /* It's important not to apply jpeg_gen_optimal_table more than once
973 * per table, because it clobbers the input frequency counts!
974 */
975 MEMZERO(did_dc, SIZEOF(did_dc));
976 MEMZERO(did_ac, SIZEOF(did_ac));
977
978 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
979 compptr = cinfo->cur_comp_info[ci];
980 dctbl = compptr->dc_tbl_no;
981 actbl = compptr->ac_tbl_no;
982 if (! did_dc[dctbl]) {
983 htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
984 if (*htblptr == NULL)
985 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
986 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
987 did_dc[dctbl] = TRUE;
988 }
989 if (! did_ac[actbl]) {
990 htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
991 if (*htblptr == NULL)
992 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
993 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
994 did_ac[actbl] = TRUE;
995 }
996 }
997}
998
999
1000#endif /* ENTROPY_OPT_SUPPORTED */
1001
1002
1003/*
1004 * Module initialization routine for Huffman entropy encoding.
1005 */
1006
1007GLOBAL(void)
1008jinit_huff_encoder (j_compress_ptr cinfo)
1009{
1010 huff_entropy_ptr entropy;
1011 int i;
1012
1013 entropy = (huff_entropy_ptr)
1014 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1015 SIZEOF(huff_entropy_encoder));
1016 cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
1017 entropy->pub.start_pass = start_pass_huff;
1018
1019 /* Mark tables unallocated */
1020 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1021 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
1022#ifdef ENTROPY_OPT_SUPPORTED
1023 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
1024#endif
1025 }
1026}