vrshoot
diff libs/libjpeg/jchuff.c @ 0:b2f14e535253
initial commit
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Sat, 01 Feb 2014 19:58:19 +0200 |
parents | |
children |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/libs/libjpeg/jchuff.c Sat Feb 01 19:58:19 2014 +0200 1.3 @@ -0,0 +1,909 @@ 1.4 +/* 1.5 + * jchuff.c 1.6 + * 1.7 + * Copyright (C) 1991-1997, Thomas G. Lane. 1.8 + * This file is part of the Independent JPEG Group's software. 1.9 + * For conditions of distribution and use, see the accompanying README file. 1.10 + * 1.11 + * This file contains Huffman entropy encoding routines. 1.12 + * 1.13 + * Much of the complexity here has to do with supporting output suspension. 1.14 + * If the data destination module demands suspension, we want to be able to 1.15 + * back up to the start of the current MCU. To do this, we copy state 1.16 + * variables into local working storage, and update them back to the 1.17 + * permanent JPEG objects only upon successful completion of an MCU. 1.18 + */ 1.19 + 1.20 +#define JPEG_INTERNALS 1.21 +#include "jinclude.h" 1.22 +#include "jpeglib.h" 1.23 +#include "jchuff.h" /* Declarations shared with jcphuff.c */ 1.24 + 1.25 + 1.26 +/* Expanded entropy encoder object for Huffman encoding. 1.27 + * 1.28 + * The savable_state subrecord contains fields that change within an MCU, 1.29 + * but must not be updated permanently until we complete the MCU. 1.30 + */ 1.31 + 1.32 +typedef struct { 1.33 + INT32 put_buffer; /* current bit-accumulation buffer */ 1.34 + int put_bits; /* # of bits now in it */ 1.35 + int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ 1.36 +} savable_state; 1.37 + 1.38 +/* This macro is to work around compilers with missing or broken 1.39 + * structure assignment. You'll need to fix this code if you have 1.40 + * such a compiler and you change MAX_COMPS_IN_SCAN. 1.41 + */ 1.42 + 1.43 +#ifndef NO_STRUCT_ASSIGN 1.44 +#define ASSIGN_STATE(dest,src) ((dest) = (src)) 1.45 +#else 1.46 +#if MAX_COMPS_IN_SCAN == 4 1.47 +#define ASSIGN_STATE(dest,src) \ 1.48 + ((dest).put_buffer = (src).put_buffer, \ 1.49 + (dest).put_bits = (src).put_bits, \ 1.50 + (dest).last_dc_val[0] = (src).last_dc_val[0], \ 1.51 + (dest).last_dc_val[1] = (src).last_dc_val[1], \ 1.52 + (dest).last_dc_val[2] = (src).last_dc_val[2], \ 1.53 + (dest).last_dc_val[3] = (src).last_dc_val[3]) 1.54 +#endif 1.55 +#endif 1.56 + 1.57 + 1.58 +typedef struct { 1.59 + struct jpeg_entropy_encoder pub; /* public fields */ 1.60 + 1.61 + savable_state saved; /* Bit buffer & DC state at start of MCU */ 1.62 + 1.63 + /* These fields are NOT loaded into local working state. */ 1.64 + unsigned int restarts_to_go; /* MCUs left in this restart interval */ 1.65 + int next_restart_num; /* next restart number to write (0-7) */ 1.66 + 1.67 + /* Pointers to derived tables (these workspaces have image lifespan) */ 1.68 + c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS]; 1.69 + c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS]; 1.70 + 1.71 +#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */ 1.72 + long * dc_count_ptrs[NUM_HUFF_TBLS]; 1.73 + long * ac_count_ptrs[NUM_HUFF_TBLS]; 1.74 +#endif 1.75 +} huff_entropy_encoder; 1.76 + 1.77 +typedef huff_entropy_encoder * huff_entropy_ptr; 1.78 + 1.79 +/* Working state while writing an MCU. 1.80 + * This struct contains all the fields that are needed by subroutines. 1.81 + */ 1.82 + 1.83 +typedef struct { 1.84 + JOCTET * next_output_byte; /* => next byte to write in buffer */ 1.85 + size_t free_in_buffer; /* # of byte spaces remaining in buffer */ 1.86 + savable_state cur; /* Current bit buffer & DC state */ 1.87 + j_compress_ptr cinfo; /* dump_buffer needs access to this */ 1.88 +} working_state; 1.89 + 1.90 + 1.91 +/* Forward declarations */ 1.92 +METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo, 1.93 + JBLOCKROW *MCU_data)); 1.94 +METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo)); 1.95 +#ifdef ENTROPY_OPT_SUPPORTED 1.96 +METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo, 1.97 + JBLOCKROW *MCU_data)); 1.98 +METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo)); 1.99 +#endif 1.100 + 1.101 + 1.102 +/* 1.103 + * Initialize for a Huffman-compressed scan. 1.104 + * If gather_statistics is TRUE, we do not output anything during the scan, 1.105 + * just count the Huffman symbols used and generate Huffman code tables. 1.106 + */ 1.107 + 1.108 +METHODDEF(void) 1.109 +start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics) 1.110 +{ 1.111 + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; 1.112 + int ci, dctbl, actbl; 1.113 + jpeg_component_info * compptr; 1.114 + 1.115 + if (gather_statistics) { 1.116 +#ifdef ENTROPY_OPT_SUPPORTED 1.117 + entropy->pub.encode_mcu = encode_mcu_gather; 1.118 + entropy->pub.finish_pass = finish_pass_gather; 1.119 +#else 1.120 + ERREXIT(cinfo, JERR_NOT_COMPILED); 1.121 +#endif 1.122 + } else { 1.123 + entropy->pub.encode_mcu = encode_mcu_huff; 1.124 + entropy->pub.finish_pass = finish_pass_huff; 1.125 + } 1.126 + 1.127 + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { 1.128 + compptr = cinfo->cur_comp_info[ci]; 1.129 + dctbl = compptr->dc_tbl_no; 1.130 + actbl = compptr->ac_tbl_no; 1.131 + if (gather_statistics) { 1.132 +#ifdef ENTROPY_OPT_SUPPORTED 1.133 + /* Check for invalid table indexes */ 1.134 + /* (make_c_derived_tbl does this in the other path) */ 1.135 + if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS) 1.136 + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl); 1.137 + if (actbl < 0 || actbl >= NUM_HUFF_TBLS) 1.138 + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl); 1.139 + /* Allocate and zero the statistics tables */ 1.140 + /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */ 1.141 + if (entropy->dc_count_ptrs[dctbl] == NULL) 1.142 + entropy->dc_count_ptrs[dctbl] = (long *) 1.143 + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, 1.144 + 257 * SIZEOF(long)); 1.145 + MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long)); 1.146 + if (entropy->ac_count_ptrs[actbl] == NULL) 1.147 + entropy->ac_count_ptrs[actbl] = (long *) 1.148 + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, 1.149 + 257 * SIZEOF(long)); 1.150 + MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long)); 1.151 +#endif 1.152 + } else { 1.153 + /* Compute derived values for Huffman tables */ 1.154 + /* We may do this more than once for a table, but it's not expensive */ 1.155 + jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl, 1.156 + & entropy->dc_derived_tbls[dctbl]); 1.157 + jpeg_make_c_derived_tbl(cinfo, FALSE, actbl, 1.158 + & entropy->ac_derived_tbls[actbl]); 1.159 + } 1.160 + /* Initialize DC predictions to 0 */ 1.161 + entropy->saved.last_dc_val[ci] = 0; 1.162 + } 1.163 + 1.164 + /* Initialize bit buffer to empty */ 1.165 + entropy->saved.put_buffer = 0; 1.166 + entropy->saved.put_bits = 0; 1.167 + 1.168 + /* Initialize restart stuff */ 1.169 + entropy->restarts_to_go = cinfo->restart_interval; 1.170 + entropy->next_restart_num = 0; 1.171 +} 1.172 + 1.173 + 1.174 +/* 1.175 + * Compute the derived values for a Huffman table. 1.176 + * This routine also performs some validation checks on the table. 1.177 + * 1.178 + * Note this is also used by jcphuff.c. 1.179 + */ 1.180 + 1.181 +GLOBAL(void) 1.182 +jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno, 1.183 + c_derived_tbl ** pdtbl) 1.184 +{ 1.185 + JHUFF_TBL *htbl; 1.186 + c_derived_tbl *dtbl; 1.187 + int p, i, l, lastp, si, maxsymbol; 1.188 + char huffsize[257]; 1.189 + unsigned int huffcode[257]; 1.190 + unsigned int code; 1.191 + 1.192 + /* Note that huffsize[] and huffcode[] are filled in code-length order, 1.193 + * paralleling the order of the symbols themselves in htbl->huffval[]. 1.194 + */ 1.195 + 1.196 + /* Find the input Huffman table */ 1.197 + if (tblno < 0 || tblno >= NUM_HUFF_TBLS) 1.198 + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); 1.199 + htbl = 1.200 + isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno]; 1.201 + if (htbl == NULL) 1.202 + ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); 1.203 + 1.204 + /* Allocate a workspace if we haven't already done so. */ 1.205 + if (*pdtbl == NULL) 1.206 + *pdtbl = (c_derived_tbl *) 1.207 + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, 1.208 + SIZEOF(c_derived_tbl)); 1.209 + dtbl = *pdtbl; 1.210 + 1.211 + /* Figure C.1: make table of Huffman code length for each symbol */ 1.212 + 1.213 + p = 0; 1.214 + for (l = 1; l <= 16; l++) { 1.215 + i = (int) htbl->bits[l]; 1.216 + if (i < 0 || p + i > 256) /* protect against table overrun */ 1.217 + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); 1.218 + while (i--) 1.219 + huffsize[p++] = (char) l; 1.220 + } 1.221 + huffsize[p] = 0; 1.222 + lastp = p; 1.223 + 1.224 + /* Figure C.2: generate the codes themselves */ 1.225 + /* We also validate that the counts represent a legal Huffman code tree. */ 1.226 + 1.227 + code = 0; 1.228 + si = huffsize[0]; 1.229 + p = 0; 1.230 + while (huffsize[p]) { 1.231 + while (((int) huffsize[p]) == si) { 1.232 + huffcode[p++] = code; 1.233 + code++; 1.234 + } 1.235 + /* code is now 1 more than the last code used for codelength si; but 1.236 + * it must still fit in si bits, since no code is allowed to be all ones. 1.237 + */ 1.238 + if (((INT32) code) >= (((INT32) 1) << si)) 1.239 + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); 1.240 + code <<= 1; 1.241 + si++; 1.242 + } 1.243 + 1.244 + /* Figure C.3: generate encoding tables */ 1.245 + /* These are code and size indexed by symbol value */ 1.246 + 1.247 + /* Set all codeless symbols to have code length 0; 1.248 + * this lets us detect duplicate VAL entries here, and later 1.249 + * allows emit_bits to detect any attempt to emit such symbols. 1.250 + */ 1.251 + MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi)); 1.252 + 1.253 + /* This is also a convenient place to check for out-of-range 1.254 + * and duplicated VAL entries. We allow 0..255 for AC symbols 1.255 + * but only 0..15 for DC. (We could constrain them further 1.256 + * based on data depth and mode, but this seems enough.) 1.257 + */ 1.258 + maxsymbol = isDC ? 15 : 255; 1.259 + 1.260 + for (p = 0; p < lastp; p++) { 1.261 + i = htbl->huffval[p]; 1.262 + if (i < 0 || i > maxsymbol || dtbl->ehufsi[i]) 1.263 + ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); 1.264 + dtbl->ehufco[i] = huffcode[p]; 1.265 + dtbl->ehufsi[i] = huffsize[p]; 1.266 + } 1.267 +} 1.268 + 1.269 + 1.270 +/* Outputting bytes to the file */ 1.271 + 1.272 +/* Emit a byte, taking 'action' if must suspend. */ 1.273 +#define emit_byte(state,val,action) \ 1.274 + { *(state)->next_output_byte++ = (JOCTET) (val); \ 1.275 + if (--(state)->free_in_buffer == 0) \ 1.276 + if (! dump_buffer(state)) \ 1.277 + { action; } } 1.278 + 1.279 + 1.280 +LOCAL(boolean) 1.281 +dump_buffer (working_state * state) 1.282 +/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */ 1.283 +{ 1.284 + struct jpeg_destination_mgr * dest = state->cinfo->dest; 1.285 + 1.286 + if (! (*dest->empty_output_buffer) (state->cinfo)) 1.287 + return FALSE; 1.288 + /* After a successful buffer dump, must reset buffer pointers */ 1.289 + state->next_output_byte = dest->next_output_byte; 1.290 + state->free_in_buffer = dest->free_in_buffer; 1.291 + return TRUE; 1.292 +} 1.293 + 1.294 + 1.295 +/* Outputting bits to the file */ 1.296 + 1.297 +/* Only the right 24 bits of put_buffer are used; the valid bits are 1.298 + * left-justified in this part. At most 16 bits can be passed to emit_bits 1.299 + * in one call, and we never retain more than 7 bits in put_buffer 1.300 + * between calls, so 24 bits are sufficient. 1.301 + */ 1.302 + 1.303 +INLINE 1.304 +LOCAL(boolean) 1.305 +emit_bits (working_state * state, unsigned int code, int size) 1.306 +/* Emit some bits; return TRUE if successful, FALSE if must suspend */ 1.307 +{ 1.308 + /* This routine is heavily used, so it's worth coding tightly. */ 1.309 + register INT32 put_buffer = (INT32) code; 1.310 + register int put_bits = state->cur.put_bits; 1.311 + 1.312 + /* if size is 0, caller used an invalid Huffman table entry */ 1.313 + if (size == 0) 1.314 + ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE); 1.315 + 1.316 + put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */ 1.317 + 1.318 + put_bits += size; /* new number of bits in buffer */ 1.319 + 1.320 + put_buffer <<= 24 - put_bits; /* align incoming bits */ 1.321 + 1.322 + put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */ 1.323 + 1.324 + while (put_bits >= 8) { 1.325 + int c = (int) ((put_buffer >> 16) & 0xFF); 1.326 + 1.327 + emit_byte(state, c, return FALSE); 1.328 + if (c == 0xFF) { /* need to stuff a zero byte? */ 1.329 + emit_byte(state, 0, return FALSE); 1.330 + } 1.331 + put_buffer <<= 8; 1.332 + put_bits -= 8; 1.333 + } 1.334 + 1.335 + state->cur.put_buffer = put_buffer; /* update state variables */ 1.336 + state->cur.put_bits = put_bits; 1.337 + 1.338 + return TRUE; 1.339 +} 1.340 + 1.341 + 1.342 +LOCAL(boolean) 1.343 +flush_bits (working_state * state) 1.344 +{ 1.345 + if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */ 1.346 + return FALSE; 1.347 + state->cur.put_buffer = 0; /* and reset bit-buffer to empty */ 1.348 + state->cur.put_bits = 0; 1.349 + return TRUE; 1.350 +} 1.351 + 1.352 + 1.353 +/* Encode a single block's worth of coefficients */ 1.354 + 1.355 +LOCAL(boolean) 1.356 +encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val, 1.357 + c_derived_tbl *dctbl, c_derived_tbl *actbl) 1.358 +{ 1.359 + register int temp, temp2; 1.360 + register int nbits; 1.361 + register int k, r, i; 1.362 + 1.363 + /* Encode the DC coefficient difference per section F.1.2.1 */ 1.364 + 1.365 + temp = temp2 = block[0] - last_dc_val; 1.366 + 1.367 + if (temp < 0) { 1.368 + temp = -temp; /* temp is abs value of input */ 1.369 + /* For a negative input, want temp2 = bitwise complement of abs(input) */ 1.370 + /* This code assumes we are on a two's complement machine */ 1.371 + temp2--; 1.372 + } 1.373 + 1.374 + /* Find the number of bits needed for the magnitude of the coefficient */ 1.375 + nbits = 0; 1.376 + while (temp) { 1.377 + nbits++; 1.378 + temp >>= 1; 1.379 + } 1.380 + /* Check for out-of-range coefficient values. 1.381 + * Since we're encoding a difference, the range limit is twice as much. 1.382 + */ 1.383 + if (nbits > MAX_COEF_BITS+1) 1.384 + ERREXIT(state->cinfo, JERR_BAD_DCT_COEF); 1.385 + 1.386 + /* Emit the Huffman-coded symbol for the number of bits */ 1.387 + if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits])) 1.388 + return FALSE; 1.389 + 1.390 + /* Emit that number of bits of the value, if positive, */ 1.391 + /* or the complement of its magnitude, if negative. */ 1.392 + if (nbits) /* emit_bits rejects calls with size 0 */ 1.393 + if (! emit_bits(state, (unsigned int) temp2, nbits)) 1.394 + return FALSE; 1.395 + 1.396 + /* Encode the AC coefficients per section F.1.2.2 */ 1.397 + 1.398 + r = 0; /* r = run length of zeros */ 1.399 + 1.400 + for (k = 1; k < DCTSIZE2; k++) { 1.401 + if ((temp = block[jpeg_natural_order[k]]) == 0) { 1.402 + r++; 1.403 + } else { 1.404 + /* if run length > 15, must emit special run-length-16 codes (0xF0) */ 1.405 + while (r > 15) { 1.406 + if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0])) 1.407 + return FALSE; 1.408 + r -= 16; 1.409 + } 1.410 + 1.411 + temp2 = temp; 1.412 + if (temp < 0) { 1.413 + temp = -temp; /* temp is abs value of input */ 1.414 + /* This code assumes we are on a two's complement machine */ 1.415 + temp2--; 1.416 + } 1.417 + 1.418 + /* Find the number of bits needed for the magnitude of the coefficient */ 1.419 + nbits = 1; /* there must be at least one 1 bit */ 1.420 + while ((temp >>= 1)) 1.421 + nbits++; 1.422 + /* Check for out-of-range coefficient values */ 1.423 + if (nbits > MAX_COEF_BITS) 1.424 + ERREXIT(state->cinfo, JERR_BAD_DCT_COEF); 1.425 + 1.426 + /* Emit Huffman symbol for run length / number of bits */ 1.427 + i = (r << 4) + nbits; 1.428 + if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i])) 1.429 + return FALSE; 1.430 + 1.431 + /* Emit that number of bits of the value, if positive, */ 1.432 + /* or the complement of its magnitude, if negative. */ 1.433 + if (! emit_bits(state, (unsigned int) temp2, nbits)) 1.434 + return FALSE; 1.435 + 1.436 + r = 0; 1.437 + } 1.438 + } 1.439 + 1.440 + /* If the last coef(s) were zero, emit an end-of-block code */ 1.441 + if (r > 0) 1.442 + if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0])) 1.443 + return FALSE; 1.444 + 1.445 + return TRUE; 1.446 +} 1.447 + 1.448 + 1.449 +/* 1.450 + * Emit a restart marker & resynchronize predictions. 1.451 + */ 1.452 + 1.453 +LOCAL(boolean) 1.454 +emit_restart (working_state * state, int restart_num) 1.455 +{ 1.456 + int ci; 1.457 + 1.458 + if (! flush_bits(state)) 1.459 + return FALSE; 1.460 + 1.461 + emit_byte(state, 0xFF, return FALSE); 1.462 + emit_byte(state, JPEG_RST0 + restart_num, return FALSE); 1.463 + 1.464 + /* Re-initialize DC predictions to 0 */ 1.465 + for (ci = 0; ci < state->cinfo->comps_in_scan; ci++) 1.466 + state->cur.last_dc_val[ci] = 0; 1.467 + 1.468 + /* The restart counter is not updated until we successfully write the MCU. */ 1.469 + 1.470 + return TRUE; 1.471 +} 1.472 + 1.473 + 1.474 +/* 1.475 + * Encode and output one MCU's worth of Huffman-compressed coefficients. 1.476 + */ 1.477 + 1.478 +METHODDEF(boolean) 1.479 +encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data) 1.480 +{ 1.481 + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; 1.482 + working_state state; 1.483 + int blkn, ci; 1.484 + jpeg_component_info * compptr; 1.485 + 1.486 + /* Load up working state */ 1.487 + state.next_output_byte = cinfo->dest->next_output_byte; 1.488 + state.free_in_buffer = cinfo->dest->free_in_buffer; 1.489 + ASSIGN_STATE(state.cur, entropy->saved); 1.490 + state.cinfo = cinfo; 1.491 + 1.492 + /* Emit restart marker if needed */ 1.493 + if (cinfo->restart_interval) { 1.494 + if (entropy->restarts_to_go == 0) 1.495 + if (! emit_restart(&state, entropy->next_restart_num)) 1.496 + return FALSE; 1.497 + } 1.498 + 1.499 + /* Encode the MCU data blocks */ 1.500 + for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { 1.501 + ci = cinfo->MCU_membership[blkn]; 1.502 + compptr = cinfo->cur_comp_info[ci]; 1.503 + if (! encode_one_block(&state, 1.504 + MCU_data[blkn][0], state.cur.last_dc_val[ci], 1.505 + entropy->dc_derived_tbls[compptr->dc_tbl_no], 1.506 + entropy->ac_derived_tbls[compptr->ac_tbl_no])) 1.507 + return FALSE; 1.508 + /* Update last_dc_val */ 1.509 + state.cur.last_dc_val[ci] = MCU_data[blkn][0][0]; 1.510 + } 1.511 + 1.512 + /* Completed MCU, so update state */ 1.513 + cinfo->dest->next_output_byte = state.next_output_byte; 1.514 + cinfo->dest->free_in_buffer = state.free_in_buffer; 1.515 + ASSIGN_STATE(entropy->saved, state.cur); 1.516 + 1.517 + /* Update restart-interval state too */ 1.518 + if (cinfo->restart_interval) { 1.519 + if (entropy->restarts_to_go == 0) { 1.520 + entropy->restarts_to_go = cinfo->restart_interval; 1.521 + entropy->next_restart_num++; 1.522 + entropy->next_restart_num &= 7; 1.523 + } 1.524 + entropy->restarts_to_go--; 1.525 + } 1.526 + 1.527 + return TRUE; 1.528 +} 1.529 + 1.530 + 1.531 +/* 1.532 + * Finish up at the end of a Huffman-compressed scan. 1.533 + */ 1.534 + 1.535 +METHODDEF(void) 1.536 +finish_pass_huff (j_compress_ptr cinfo) 1.537 +{ 1.538 + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; 1.539 + working_state state; 1.540 + 1.541 + /* Load up working state ... flush_bits needs it */ 1.542 + state.next_output_byte = cinfo->dest->next_output_byte; 1.543 + state.free_in_buffer = cinfo->dest->free_in_buffer; 1.544 + ASSIGN_STATE(state.cur, entropy->saved); 1.545 + state.cinfo = cinfo; 1.546 + 1.547 + /* Flush out the last data */ 1.548 + if (! flush_bits(&state)) 1.549 + ERREXIT(cinfo, JERR_CANT_SUSPEND); 1.550 + 1.551 + /* Update state */ 1.552 + cinfo->dest->next_output_byte = state.next_output_byte; 1.553 + cinfo->dest->free_in_buffer = state.free_in_buffer; 1.554 + ASSIGN_STATE(entropy->saved, state.cur); 1.555 +} 1.556 + 1.557 + 1.558 +/* 1.559 + * Huffman coding optimization. 1.560 + * 1.561 + * We first scan the supplied data and count the number of uses of each symbol 1.562 + * that is to be Huffman-coded. (This process MUST agree with the code above.) 1.563 + * Then we build a Huffman coding tree for the observed counts. 1.564 + * Symbols which are not needed at all for the particular image are not 1.565 + * assigned any code, which saves space in the DHT marker as well as in 1.566 + * the compressed data. 1.567 + */ 1.568 + 1.569 +#ifdef ENTROPY_OPT_SUPPORTED 1.570 + 1.571 + 1.572 +/* Process a single block's worth of coefficients */ 1.573 + 1.574 +LOCAL(void) 1.575 +htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val, 1.576 + long dc_counts[], long ac_counts[]) 1.577 +{ 1.578 + register int temp; 1.579 + register int nbits; 1.580 + register int k, r; 1.581 + 1.582 + /* Encode the DC coefficient difference per section F.1.2.1 */ 1.583 + 1.584 + temp = block[0] - last_dc_val; 1.585 + if (temp < 0) 1.586 + temp = -temp; 1.587 + 1.588 + /* Find the number of bits needed for the magnitude of the coefficient */ 1.589 + nbits = 0; 1.590 + while (temp) { 1.591 + nbits++; 1.592 + temp >>= 1; 1.593 + } 1.594 + /* Check for out-of-range coefficient values. 1.595 + * Since we're encoding a difference, the range limit is twice as much. 1.596 + */ 1.597 + if (nbits > MAX_COEF_BITS+1) 1.598 + ERREXIT(cinfo, JERR_BAD_DCT_COEF); 1.599 + 1.600 + /* Count the Huffman symbol for the number of bits */ 1.601 + dc_counts[nbits]++; 1.602 + 1.603 + /* Encode the AC coefficients per section F.1.2.2 */ 1.604 + 1.605 + r = 0; /* r = run length of zeros */ 1.606 + 1.607 + for (k = 1; k < DCTSIZE2; k++) { 1.608 + if ((temp = block[jpeg_natural_order[k]]) == 0) { 1.609 + r++; 1.610 + } else { 1.611 + /* if run length > 15, must emit special run-length-16 codes (0xF0) */ 1.612 + while (r > 15) { 1.613 + ac_counts[0xF0]++; 1.614 + r -= 16; 1.615 + } 1.616 + 1.617 + /* Find the number of bits needed for the magnitude of the coefficient */ 1.618 + if (temp < 0) 1.619 + temp = -temp; 1.620 + 1.621 + /* Find the number of bits needed for the magnitude of the coefficient */ 1.622 + nbits = 1; /* there must be at least one 1 bit */ 1.623 + while ((temp >>= 1)) 1.624 + nbits++; 1.625 + /* Check for out-of-range coefficient values */ 1.626 + if (nbits > MAX_COEF_BITS) 1.627 + ERREXIT(cinfo, JERR_BAD_DCT_COEF); 1.628 + 1.629 + /* Count Huffman symbol for run length / number of bits */ 1.630 + ac_counts[(r << 4) + nbits]++; 1.631 + 1.632 + r = 0; 1.633 + } 1.634 + } 1.635 + 1.636 + /* If the last coef(s) were zero, emit an end-of-block code */ 1.637 + if (r > 0) 1.638 + ac_counts[0]++; 1.639 +} 1.640 + 1.641 + 1.642 +/* 1.643 + * Trial-encode one MCU's worth of Huffman-compressed coefficients. 1.644 + * No data is actually output, so no suspension return is possible. 1.645 + */ 1.646 + 1.647 +METHODDEF(boolean) 1.648 +encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data) 1.649 +{ 1.650 + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; 1.651 + int blkn, ci; 1.652 + jpeg_component_info * compptr; 1.653 + 1.654 + /* Take care of restart intervals if needed */ 1.655 + if (cinfo->restart_interval) { 1.656 + if (entropy->restarts_to_go == 0) { 1.657 + /* Re-initialize DC predictions to 0 */ 1.658 + for (ci = 0; ci < cinfo->comps_in_scan; ci++) 1.659 + entropy->saved.last_dc_val[ci] = 0; 1.660 + /* Update restart state */ 1.661 + entropy->restarts_to_go = cinfo->restart_interval; 1.662 + } 1.663 + entropy->restarts_to_go--; 1.664 + } 1.665 + 1.666 + for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { 1.667 + ci = cinfo->MCU_membership[blkn]; 1.668 + compptr = cinfo->cur_comp_info[ci]; 1.669 + htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci], 1.670 + entropy->dc_count_ptrs[compptr->dc_tbl_no], 1.671 + entropy->ac_count_ptrs[compptr->ac_tbl_no]); 1.672 + entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0]; 1.673 + } 1.674 + 1.675 + return TRUE; 1.676 +} 1.677 + 1.678 + 1.679 +/* 1.680 + * Generate the best Huffman code table for the given counts, fill htbl. 1.681 + * Note this is also used by jcphuff.c. 1.682 + * 1.683 + * The JPEG standard requires that no symbol be assigned a codeword of all 1.684 + * one bits (so that padding bits added at the end of a compressed segment 1.685 + * can't look like a valid code). Because of the canonical ordering of 1.686 + * codewords, this just means that there must be an unused slot in the 1.687 + * longest codeword length category. Section K.2 of the JPEG spec suggests 1.688 + * reserving such a slot by pretending that symbol 256 is a valid symbol 1.689 + * with count 1. In theory that's not optimal; giving it count zero but 1.690 + * including it in the symbol set anyway should give a better Huffman code. 1.691 + * But the theoretically better code actually seems to come out worse in 1.692 + * practice, because it produces more all-ones bytes (which incur stuffed 1.693 + * zero bytes in the final file). In any case the difference is tiny. 1.694 + * 1.695 + * The JPEG standard requires Huffman codes to be no more than 16 bits long. 1.696 + * If some symbols have a very small but nonzero probability, the Huffman tree 1.697 + * must be adjusted to meet the code length restriction. We currently use 1.698 + * the adjustment method suggested in JPEG section K.2. This method is *not* 1.699 + * optimal; it may not choose the best possible limited-length code. But 1.700 + * typically only very-low-frequency symbols will be given less-than-optimal 1.701 + * lengths, so the code is almost optimal. Experimental comparisons against 1.702 + * an optimal limited-length-code algorithm indicate that the difference is 1.703 + * microscopic --- usually less than a hundredth of a percent of total size. 1.704 + * So the extra complexity of an optimal algorithm doesn't seem worthwhile. 1.705 + */ 1.706 + 1.707 +GLOBAL(void) 1.708 +jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]) 1.709 +{ 1.710 +#define MAX_CLEN 32 /* assumed maximum initial code length */ 1.711 + UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */ 1.712 + int codesize[257]; /* codesize[k] = code length of symbol k */ 1.713 + int others[257]; /* next symbol in current branch of tree */ 1.714 + int c1, c2; 1.715 + int p, i, j; 1.716 + long v; 1.717 + 1.718 + /* This algorithm is explained in section K.2 of the JPEG standard */ 1.719 + 1.720 + MEMZERO(bits, SIZEOF(bits)); 1.721 + MEMZERO(codesize, SIZEOF(codesize)); 1.722 + for (i = 0; i < 257; i++) 1.723 + others[i] = -1; /* init links to empty */ 1.724 + 1.725 + freq[256] = 1; /* make sure 256 has a nonzero count */ 1.726 + /* Including the pseudo-symbol 256 in the Huffman procedure guarantees 1.727 + * that no real symbol is given code-value of all ones, because 256 1.728 + * will be placed last in the largest codeword category. 1.729 + */ 1.730 + 1.731 + /* Huffman's basic algorithm to assign optimal code lengths to symbols */ 1.732 + 1.733 + for (;;) { 1.734 + /* Find the smallest nonzero frequency, set c1 = its symbol */ 1.735 + /* In case of ties, take the larger symbol number */ 1.736 + c1 = -1; 1.737 + v = 1000000000L; 1.738 + for (i = 0; i <= 256; i++) { 1.739 + if (freq[i] && freq[i] <= v) { 1.740 + v = freq[i]; 1.741 + c1 = i; 1.742 + } 1.743 + } 1.744 + 1.745 + /* Find the next smallest nonzero frequency, set c2 = its symbol */ 1.746 + /* In case of ties, take the larger symbol number */ 1.747 + c2 = -1; 1.748 + v = 1000000000L; 1.749 + for (i = 0; i <= 256; i++) { 1.750 + if (freq[i] && freq[i] <= v && i != c1) { 1.751 + v = freq[i]; 1.752 + c2 = i; 1.753 + } 1.754 + } 1.755 + 1.756 + /* Done if we've merged everything into one frequency */ 1.757 + if (c2 < 0) 1.758 + break; 1.759 + 1.760 + /* Else merge the two counts/trees */ 1.761 + freq[c1] += freq[c2]; 1.762 + freq[c2] = 0; 1.763 + 1.764 + /* Increment the codesize of everything in c1's tree branch */ 1.765 + codesize[c1]++; 1.766 + while (others[c1] >= 0) { 1.767 + c1 = others[c1]; 1.768 + codesize[c1]++; 1.769 + } 1.770 + 1.771 + others[c1] = c2; /* chain c2 onto c1's tree branch */ 1.772 + 1.773 + /* Increment the codesize of everything in c2's tree branch */ 1.774 + codesize[c2]++; 1.775 + while (others[c2] >= 0) { 1.776 + c2 = others[c2]; 1.777 + codesize[c2]++; 1.778 + } 1.779 + } 1.780 + 1.781 + /* Now count the number of symbols of each code length */ 1.782 + for (i = 0; i <= 256; i++) { 1.783 + if (codesize[i]) { 1.784 + /* The JPEG standard seems to think that this can't happen, */ 1.785 + /* but I'm paranoid... */ 1.786 + if (codesize[i] > MAX_CLEN) 1.787 + ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW); 1.788 + 1.789 + bits[codesize[i]]++; 1.790 + } 1.791 + } 1.792 + 1.793 + /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure 1.794 + * Huffman procedure assigned any such lengths, we must adjust the coding. 1.795 + * Here is what the JPEG spec says about how this next bit works: 1.796 + * Since symbols are paired for the longest Huffman code, the symbols are 1.797 + * removed from this length category two at a time. The prefix for the pair 1.798 + * (which is one bit shorter) is allocated to one of the pair; then, 1.799 + * skipping the BITS entry for that prefix length, a code word from the next 1.800 + * shortest nonzero BITS entry is converted into a prefix for two code words 1.801 + * one bit longer. 1.802 + */ 1.803 + 1.804 + for (i = MAX_CLEN; i > 16; i--) { 1.805 + while (bits[i] > 0) { 1.806 + j = i - 2; /* find length of new prefix to be used */ 1.807 + while (bits[j] == 0) 1.808 + j--; 1.809 + 1.810 + bits[i] -= 2; /* remove two symbols */ 1.811 + bits[i-1]++; /* one goes in this length */ 1.812 + bits[j+1] += 2; /* two new symbols in this length */ 1.813 + bits[j]--; /* symbol of this length is now a prefix */ 1.814 + } 1.815 + } 1.816 + 1.817 + /* Remove the count for the pseudo-symbol 256 from the largest codelength */ 1.818 + while (bits[i] == 0) /* find largest codelength still in use */ 1.819 + i--; 1.820 + bits[i]--; 1.821 + 1.822 + /* Return final symbol counts (only for lengths 0..16) */ 1.823 + MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits)); 1.824 + 1.825 + /* Return a list of the symbols sorted by code length */ 1.826 + /* It's not real clear to me why we don't need to consider the codelength 1.827 + * changes made above, but the JPEG spec seems to think this works. 1.828 + */ 1.829 + p = 0; 1.830 + for (i = 1; i <= MAX_CLEN; i++) { 1.831 + for (j = 0; j <= 255; j++) { 1.832 + if (codesize[j] == i) { 1.833 + htbl->huffval[p] = (UINT8) j; 1.834 + p++; 1.835 + } 1.836 + } 1.837 + } 1.838 + 1.839 + /* Set sent_table FALSE so updated table will be written to JPEG file. */ 1.840 + htbl->sent_table = FALSE; 1.841 +} 1.842 + 1.843 + 1.844 +/* 1.845 + * Finish up a statistics-gathering pass and create the new Huffman tables. 1.846 + */ 1.847 + 1.848 +METHODDEF(void) 1.849 +finish_pass_gather (j_compress_ptr cinfo) 1.850 +{ 1.851 + huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; 1.852 + int ci, dctbl, actbl; 1.853 + jpeg_component_info * compptr; 1.854 + JHUFF_TBL **htblptr; 1.855 + boolean did_dc[NUM_HUFF_TBLS]; 1.856 + boolean did_ac[NUM_HUFF_TBLS]; 1.857 + 1.858 + /* It's important not to apply jpeg_gen_optimal_table more than once 1.859 + * per table, because it clobbers the input frequency counts! 1.860 + */ 1.861 + MEMZERO(did_dc, SIZEOF(did_dc)); 1.862 + MEMZERO(did_ac, SIZEOF(did_ac)); 1.863 + 1.864 + for (ci = 0; ci < cinfo->comps_in_scan; ci++) { 1.865 + compptr = cinfo->cur_comp_info[ci]; 1.866 + dctbl = compptr->dc_tbl_no; 1.867 + actbl = compptr->ac_tbl_no; 1.868 + if (! did_dc[dctbl]) { 1.869 + htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl]; 1.870 + if (*htblptr == NULL) 1.871 + *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); 1.872 + jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]); 1.873 + did_dc[dctbl] = TRUE; 1.874 + } 1.875 + if (! did_ac[actbl]) { 1.876 + htblptr = & cinfo->ac_huff_tbl_ptrs[actbl]; 1.877 + if (*htblptr == NULL) 1.878 + *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); 1.879 + jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]); 1.880 + did_ac[actbl] = TRUE; 1.881 + } 1.882 + } 1.883 +} 1.884 + 1.885 + 1.886 +#endif /* ENTROPY_OPT_SUPPORTED */ 1.887 + 1.888 + 1.889 +/* 1.890 + * Module initialization routine for Huffman entropy encoding. 1.891 + */ 1.892 + 1.893 +GLOBAL(void) 1.894 +jinit_huff_encoder (j_compress_ptr cinfo) 1.895 +{ 1.896 + huff_entropy_ptr entropy; 1.897 + int i; 1.898 + 1.899 + entropy = (huff_entropy_ptr) 1.900 + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, 1.901 + SIZEOF(huff_entropy_encoder)); 1.902 + cinfo->entropy = (struct jpeg_entropy_encoder *) entropy; 1.903 + entropy->pub.start_pass = start_pass_huff; 1.904 + 1.905 + /* Mark tables unallocated */ 1.906 + for (i = 0; i < NUM_HUFF_TBLS; i++) { 1.907 + entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL; 1.908 +#ifdef ENTROPY_OPT_SUPPORTED 1.909 + entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL; 1.910 +#endif 1.911 + } 1.912 +}