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