home *** CD-ROM | disk | FTP | other *** search
/ Tools / WinSN5.0Ver.iso / NETSCAP.50 / WIN1998.ZIP / ns / jpeg / jchuff.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-04-08  |  25.6 KB  |  848 lines

  1. /*
  2.  * jchuff.c
  3.  *
  4.  * Copyright (C) 1991-1995, 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.  
  17. #define JPEG_INTERNALS
  18. #include "xp_core.h"/*defines of int32 ect*/
  19. #include "jinclude.h"
  20. #include "jpeglib.h"
  21. #include "jchuff.h"        /* Declarations shared with jcphuff.c */
  22.  
  23.  
  24. /* Expanded entropy encoder object for Huffman encoding.
  25.  *
  26.  * The savable_state subrecord contains fields that change within an MCU,
  27.  * but must not be updated permanently until we complete the MCU.
  28.  */
  29.  
  30. typedef struct {
  31.   int32 put_buffer;        /* current bit-accumulation buffer */
  32.   int16 put_bits;            /* # of bits now in it */
  33.   int16 last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  34. } savable_state;
  35.  
  36. /* This macro is to work around compilers with missing or broken
  37.  * structure assignment.  You'll need to fix this code if you have
  38.  * such a compiler and you change MAX_COMPS_IN_SCAN.
  39.  */
  40.  
  41. #ifndef NO_STRUCT_ASSIGN
  42. #define ASSIGN_STATE(dest,src)  ((dest) = (src))
  43. #else
  44. #if MAX_COMPS_IN_SCAN == 4
  45. #define ASSIGN_STATE(dest,src)  \
  46.     ((dest).put_buffer = (src).put_buffer, \
  47.      (dest).put_bits = (src).put_bits, \
  48.      (dest).last_dc_val[0] = (src).last_dc_val[0], \
  49.      (dest).last_dc_val[1] = (src).last_dc_val[1], \
  50.      (dest).last_dc_val[2] = (src).last_dc_val[2], \
  51.      (dest).last_dc_val[3] = (src).last_dc_val[3])
  52. #endif
  53. #endif
  54.  
  55.  
  56. typedef struct {
  57.   struct jpeg_entropy_encoder pub; /* public fields */
  58.  
  59.   savable_state saved;        /* Bit buffer & DC state at start of MCU */
  60.  
  61.   /* These fields are NOT loaded into local working state. */
  62.   uint16 restarts_to_go;    /* MCUs left in this restart interval */
  63.   int16 next_restart_num;        /* next restart number to write (0-7) */
  64.  
  65.   /* Pointers to derived tables (these workspaces have image lifespan) */
  66.   c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  67.   c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  68.  
  69. #ifdef ENTROPY_OPT_SUPPORTED    /* Statistics tables for optimization */
  70.   int32 * dc_count_ptrs[NUM_HUFF_TBLS];
  71.   int32 * ac_count_ptrs[NUM_HUFF_TBLS];
  72. #endif
  73. } huff_entropy_encoder;
  74.  
  75. typedef huff_entropy_encoder * huff_entropy_ptr;
  76.  
  77. /* Working state while writing an MCU.
  78.  * This struct contains all the fields that are needed by subroutines.
  79.  */
  80.  
  81. typedef struct {
  82.   JOCTET * next_output_byte;    /* => next byte to write in buffer */
  83.   size_t free_in_buffer;    /* # of byte spaces remaining in buffer */
  84.   savable_state cur;        /* Current bit buffer & DC state */
  85.   j_compress_ptr cinfo;        /* dump_buffer needs access to this */
  86. } working_state;
  87.  
  88.  
  89. /* Forward declarations */
  90. METHODDEF boolean encode_mcu_huff JPP((j_compress_ptr cinfo,
  91.                        JBLOCKROW *MCU_data));
  92. METHODDEF void finish_pass_huff JPP((j_compress_ptr cinfo));
  93. #ifdef ENTROPY_OPT_SUPPORTED
  94. METHODDEF boolean encode_mcu_gather JPP((j_compress_ptr cinfo,
  95.                      JBLOCKROW *MCU_data));
  96. METHODDEF void finish_pass_gather JPP((j_compress_ptr cinfo));
  97. #endif
  98.  
  99.  
  100. /*
  101.  * Initialize for a Huffman-compressed scan.
  102.  * If gather_statistics is TRUE, we do not output anything during the scan,
  103.  * just count the Huffman symbols used and generate Huffman code tables.
  104.  */
  105.  
  106. METHODDEF void
  107. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  108. {
  109.   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  110.   int16 ci, dctbl, actbl;
  111.   jpeg_component_info * compptr;
  112.  
  113.   if (gather_statistics) {
  114. #ifdef ENTROPY_OPT_SUPPORTED
  115.     entropy->pub.encode_mcu = encode_mcu_gather;
  116.     entropy->pub.finish_pass = finish_pass_gather;
  117. #else
  118.     ERREXIT(cinfo, JERR_NOT_COMPILED);
  119. #endif
  120.   } else {
  121.     entropy->pub.encode_mcu = encode_mcu_huff;
  122.     entropy->pub.finish_pass = finish_pass_huff;
  123.   }
  124.  
  125.   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  126.     compptr = cinfo->cur_comp_info[ci];
  127.     dctbl = compptr->dc_tbl_no;
  128.     actbl = compptr->ac_tbl_no;
  129.     /* Make sure requested tables are present */
  130.     /* (In gather mode, tables need not be allocated yet) */
  131.     if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS ||
  132.     (cinfo->dc_huff_tbl_ptrs[dctbl] == NULL && !gather_statistics))
  133.       ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  134.     if (actbl < 0 || actbl >= NUM_HUFF_TBLS ||
  135.     (cinfo->ac_huff_tbl_ptrs[actbl] == NULL && !gather_statistics))
  136.       ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  137.     if (gather_statistics) {
  138. #ifdef ENTROPY_OPT_SUPPORTED
  139.       /* Allocate and zero the statistics tables */
  140.       /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  141.       if (entropy->dc_count_ptrs[dctbl] == NULL)
  142.     entropy->dc_count_ptrs[dctbl] = (int32 *)
  143.       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  144.                       257 * SIZEOF(int32));
  145.       MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(int32));
  146.       if (entropy->ac_count_ptrs[actbl] == NULL)
  147.     entropy->ac_count_ptrs[actbl] = (int32 *)
  148.       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  149.                       257 * SIZEOF(int32));
  150.       MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(int32));
  151. #endif
  152.     } else {
  153.       /* Compute derived values for Huffman tables */
  154.       /* We may do this more than once for a table, but it's not expensive */
  155.       jpeg_make_c_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[dctbl],
  156.                   & entropy->dc_derived_tbls[dctbl]);
  157.       jpeg_make_c_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[actbl],
  158.                   & entropy->ac_derived_tbls[actbl]);
  159.     }
  160.     /* Initialize DC predictions to 0 */
  161.     entropy->saved.last_dc_val[ci] = 0;
  162.   }
  163.  
  164.   /* Initialize bit buffer to empty */
  165.   entropy->saved.put_buffer = 0;
  166.   entropy->saved.put_bits = 0;
  167.  
  168.   /* Initialize restart stuff */
  169.   entropy->restarts_to_go = cinfo->restart_interval;
  170.   entropy->next_restart_num = 0;
  171. }
  172.  
  173.  
  174. /*
  175.  * Compute the derived values for a Huffman table.
  176.  * Note this is also used by jcphuff.c.
  177.  */
  178.  
  179. GLOBAL void
  180. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, JHUFF_TBL * htbl,
  181.              c_derived_tbl ** pdtbl)
  182. {
  183.   c_derived_tbl *dtbl;
  184.   int16 p, i, l, lastp, si;
  185.   char huffsize[257];
  186.   uint16 huffcode[257];
  187.   uint16 code;
  188.  
  189.   /* Allocate a workspace if we haven't already done so. */
  190.   if (*pdtbl == NULL)
  191.     *pdtbl = (c_derived_tbl *)
  192.       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  193.                   SIZEOF(c_derived_tbl));
  194.   dtbl = *pdtbl;
  195.   
  196.   /* Figure C.1: make table of Huffman code length for each symbol */
  197.   /* Note that this is in code-length order. */
  198.  
  199.   p = 0;
  200.   for (l = 1; l <= 16; l++) {
  201.     for (i = 1; i <= (int16) htbl->bits[l]; i++)
  202.       huffsize[p++] = (char) l;
  203.   }
  204.   huffsize[p] = 0;
  205.   lastp = p;
  206.   
  207.   /* Figure C.2: generate the codes themselves */
  208.   /* Note that this is in code-length order. */
  209.   
  210.   code = 0;
  211.   si = huffsize[0];
  212.   p = 0;
  213.   while (huffsize[p]) {
  214.     while (((int16) huffsize[p]) == si) {
  215.       huffcode[p++] = code;
  216.       code++;
  217.     }
  218.     code <<= 1;
  219.     si++;
  220.   }
  221.   
  222.   /* Figure C.3: generate encoding tables */
  223.   /* These are code and size indexed by symbol value */
  224.  
  225.   /* Set any codeless symbols to have code length 0;
  226.    * this allows emit_bits to detect any attempt to emit such symbols.
  227.    */
  228.   MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  229.  
  230.   for (p = 0; p < lastp; p++) {
  231.     dtbl->ehufco[htbl->huffval[p]] = huffcode[p];
  232.     dtbl->ehufsi[htbl->huffval[p]] = huffsize[p];
  233.   }
  234. }
  235.  
  236.  
  237. /* Outputting bytes to the file */
  238.  
  239. /* Emit a byte, taking 'action' if must suspend. */
  240. #define emit_byte(state,val,action)  \
  241.     { *(state)->next_output_byte++ = (JOCTET) (val);  \
  242.       if (--(state)->free_in_buffer == 0)  \
  243.         if (! dump_buffer(state))  \
  244.           { action; } }
  245.  
  246.  
  247. LOCAL boolean
  248. dump_buffer (working_state * state)
  249. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  250. {
  251.   struct jpeg_destination_mgr * dest = state->cinfo->dest;
  252.  
  253.   if (! (*dest->empty_output_buffer) (state->cinfo))
  254.     return FALSE;
  255.   /* After a successful buffer dump, must reset buffer pointers */
  256.   state->next_output_byte = dest->next_output_byte;
  257.   state->free_in_buffer = dest->free_in_buffer;
  258.   return TRUE;
  259. }
  260.  
  261.  
  262. /* Outputting bits to the file */
  263.  
  264. /* Only the right 24 bits of put_buffer are used; the valid bits are
  265.  * left-justified in this part.  At most 16 bits can be passed to emit_bits
  266.  * in one call, and we never retain more than 7 bits in put_buffer
  267.  * between calls, so 24 bits are sufficient.
  268.  */
  269.  
  270. INLINE
  271. LOCAL boolean
  272. emit_bits (working_state * state, uint16 code, int16 size)
  273. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  274. {
  275.   /* This routine is heavily used, so it's worth coding tightly. */
  276.   register int32 put_buffer = (int32) code;
  277.   register int16 put_bits = state->cur.put_bits;
  278.  
  279.   /* if size is 0, caller used an invalid Huffman table entry */
  280.   if (size == 0)
  281.     ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  282.  
  283.   put_buffer &= (((int32) 1)<<size) - 1; /* mask off any extra bits in code */
  284.   
  285.   put_bits += size;        /* new number of bits in buffer */
  286.   
  287.   put_buffer <<= 24 - put_bits; /* align incoming bits */
  288.  
  289.   put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  290.   
  291.   while (put_bits >= 8) {
  292.     int16 c = (int16) ((put_buffer >> 16) & 0xFF);
  293.     
  294.     emit_byte(state, c, return FALSE);
  295.     if (c == 0xFF) {        /* need to stuff a zero byte? */
  296.       emit_byte(state, 0, return FALSE);
  297.     }
  298.     put_buffer <<= 8;
  299.     put_bits -= 8;
  300.   }
  301.  
  302.   state->cur.put_buffer = put_buffer; /* update state variables */
  303.   state->cur.put_bits = put_bits;
  304.  
  305.   return TRUE;
  306. }
  307.  
  308.  
  309. LOCAL boolean
  310. flush_bits (working_state * state)
  311. {
  312.   if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  313.     return FALSE;
  314.   state->cur.put_buffer = 0;    /* and reset bit-buffer to empty */
  315.   state->cur.put_bits = 0;
  316.   return TRUE;
  317. }
  318.  
  319.  
  320. /* Encode a single block's worth of coefficients */
  321.  
  322. LOCAL boolean
  323. encode_one_block (working_state * state, JCOEFPTR block, int16 last_dc_val,
  324.           c_derived_tbl *dctbl, c_derived_tbl *actbl)
  325. {
  326.   register int16 temp, temp2;
  327.   register int16 nbits;
  328.   register int16 k, r, i;
  329.   
  330.   /* Encode the DC coefficient difference per section F.1.2.1 */
  331.   
  332.   temp = temp2 = block[0] - last_dc_val;
  333.  
  334.   if (temp < 0) {
  335.     temp = -temp;        /* temp is abs value of input */
  336.     /* For a negative input, want temp2 = bitwise complement of abs(input) */
  337.     /* This code assumes we are on a two's complement machine */
  338.     temp2--;
  339.   }
  340.   
  341.   /* Find the number of bits needed for the magnitude of the coefficient */
  342.   nbits = 0;
  343.   while (temp) {
  344.     nbits++;
  345.     temp >>= 1;
  346.   }
  347.   
  348.   /* Emit the Huffman-coded symbol for the number of bits */
  349.   if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  350.     return FALSE;
  351.  
  352.   /* Emit that number of bits of the value, if positive, */
  353.   /* or the complement of its magnitude, if negative. */
  354.   if (nbits)            /* emit_bits rejects calls with size 0 */
  355.     if (! emit_bits(state, (uint16) temp2, nbits))
  356.       return FALSE;
  357.  
  358.   /* Encode the AC coefficients per section F.1.2.2 */
  359.   
  360.   r = 0;            /* r = run length of zeros */
  361.   
  362.   for (k = 1; k < DCTSIZE2; k++) {
  363.     if ((temp = block[jpeg_natural_order[k]]) == 0) {
  364.       r++;
  365.     } else {
  366.       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  367.       while (r > 15) {
  368.     if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  369.       return FALSE;
  370.     r -= 16;
  371.       }
  372.  
  373.       temp2 = temp;
  374.       if (temp < 0) {
  375.     temp = -temp;        /* temp is abs value of input */
  376.     /* This code assumes we are on a two's complement machine */
  377.     temp2--;
  378.       }
  379.       
  380.       /* Find the number of bits needed for the magnitude of the coefficient */
  381.       nbits = 1;        /* there must be at least one 1 bit */
  382.       while ((temp >>= 1))
  383.     nbits++;
  384.       
  385.       /* Emit Huffman symbol for run length / number of bits */
  386.       i = (r << 4) + nbits;
  387.       if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  388.     return FALSE;
  389.  
  390.       /* Emit that number of bits of the value, if positive, */
  391.       /* or the complement of its magnitude, if negative. */
  392.       if (! emit_bits(state, (uint16) temp2, nbits))
  393.     return FALSE;
  394.       
  395.       r = 0;
  396.     }
  397.   }
  398.  
  399.   /* If the last coef(s) were zero, emit an end-of-block code */
  400.   if (r > 0)
  401.     if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  402.       return FALSE;
  403.  
  404.   return TRUE;
  405. }
  406.  
  407.  
  408. /*
  409.  * Emit a restart marker & resynchronize predictions.
  410.  */
  411.  
  412. LOCAL boolean
  413. emit_restart (working_state * state, int16 restart_num)
  414. {
  415.   int16 ci;
  416.  
  417.   if (! flush_bits(state))
  418.     return FALSE;
  419.  
  420.   emit_byte(state, 0xFF, return FALSE);
  421.   emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  422.  
  423.   /* Re-initialize DC predictions to 0 */
  424.   for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  425.     state->cur.last_dc_val[ci] = 0;
  426.  
  427.   /* The restart counter is not updated until we successfully write the MCU. */
  428.  
  429.   return TRUE;
  430. }
  431.  
  432.  
  433. /*
  434.  * Encode and output one MCU's worth of Huffman-compressed coefficients.
  435.  */
  436.  
  437. METHODDEF boolean
  438. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  439. {
  440.   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  441.   working_state state;
  442.   int16 blkn, ci;
  443.   jpeg_component_info * compptr;
  444.  
  445.   /* Load up working state */
  446.   state.next_output_byte = cinfo->dest->next_output_byte;
  447.   state.free_in_buffer = cinfo->dest->free_in_buffer;
  448.   ASSIGN_STATE(state.cur, entropy->saved);
  449.   state.cinfo = cinfo;
  450.  
  451.   /* Emit restart marker if needed */
  452.   if (cinfo->restart_interval) {
  453.     if (entropy->restarts_to_go == 0)
  454.       if (! emit_restart(&state, entropy->next_restart_num))
  455.     return FALSE;
  456.   }
  457.  
  458.   /* Encode the MCU data blocks */
  459.   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  460.     ci = cinfo->MCU_membership[blkn];
  461.     compptr = cinfo->cur_comp_info[ci];
  462.     if (! encode_one_block(&state,
  463.                MCU_data[blkn][0], state.cur.last_dc_val[ci],
  464.                entropy->dc_derived_tbls[compptr->dc_tbl_no],
  465.                entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  466.       return FALSE;
  467.     /* Update last_dc_val */
  468.     state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  469.   }
  470.  
  471.   /* Completed MCU, so update state */
  472.   cinfo->dest->next_output_byte = state.next_output_byte;
  473.   cinfo->dest->free_in_buffer = state.free_in_buffer;
  474.   ASSIGN_STATE(entropy->saved, state.cur);
  475.  
  476.   /* Update restart-interval state too */
  477.   if (cinfo->restart_interval) {
  478.     if (entropy->restarts_to_go == 0) {
  479.       entropy->restarts_to_go = cinfo->restart_interval;
  480.       entropy->next_restart_num++;
  481.       entropy->next_restart_num &= 7;
  482.     }
  483.     entropy->restarts_to_go--;
  484.   }
  485.  
  486.   return TRUE;
  487. }
  488.  
  489.  
  490. /*
  491.  * Finish up at the end of a Huffman-compressed scan.
  492.  */
  493.  
  494. METHODDEF void
  495. finish_pass_huff (j_compress_ptr cinfo)
  496. {
  497.   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  498.   working_state state;
  499.  
  500.   /* Load up working state ... flush_bits needs it */
  501.   state.next_output_byte = cinfo->dest->next_output_byte;
  502.   state.free_in_buffer = cinfo->dest->free_in_buffer;
  503.   ASSIGN_STATE(state.cur, entropy->saved);
  504.   state.cinfo = cinfo;
  505.  
  506.   /* Flush out the last data */
  507.   if (! flush_bits(&state))
  508.     ERREXIT(cinfo, JERR_CANT_SUSPEND);
  509.  
  510.   /* Update state */
  511.   cinfo->dest->next_output_byte = state.next_output_byte;
  512.   cinfo->dest->free_in_buffer = state.free_in_buffer;
  513.   ASSIGN_STATE(entropy->saved, state.cur);
  514. }
  515.  
  516.  
  517. /*
  518.  * Huffman coding optimization.
  519.  *
  520.  * This actually is optimization, in the sense that we find the best possible
  521.  * Huffman table(s) for the given data.  We first scan the supplied data and
  522.  * count the number of uses of each symbol that is to be Huffman-coded.
  523.  * (This process must agree with the code above.)  Then we build an
  524.  * optimal Huffman coding tree for the observed counts.
  525.  *
  526.  * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  527.  * If some symbols have a very small but nonzero probability, the Huffman tree
  528.  * must be adjusted to meet the code length restriction.  We currently use
  529.  * the adjustment method suggested in the JPEG spec.  This method is *not*
  530.  * optimal; it may not choose the best possible limited-length code.  But
  531.  * since the symbols involved are infrequently used, it's not clear that
  532.  * going to extra trouble is worthwhile.
  533.  */
  534.  
  535. #ifdef ENTROPY_OPT_SUPPORTED
  536.  
  537.  
  538. /* Process a single block's worth of coefficients */
  539.  
  540. LOCAL void
  541. htest_one_block (JCOEFPTR block, int16 last_dc_val,
  542.          int32 dc_counts[], int32 ac_counts[])
  543. {
  544.   register int16 temp;
  545.   register int16 nbits;
  546.   register int16 k, r;
  547.   
  548.   /* Encode the DC coefficient difference per section F.1.2.1 */
  549.   
  550.   temp = block[0] - last_dc_val;
  551.   if (temp < 0)
  552.     temp = -temp;
  553.   
  554.   /* Find the number of bits needed for the magnitude of the coefficient */
  555.   nbits = 0;
  556.   while (temp) {
  557.     nbits++;
  558.     temp >>= 1;
  559.   }
  560.  
  561.   /* Count the Huffman symbol for the number of bits */
  562.   dc_counts[nbits]++;
  563.   
  564.   /* Encode the AC coefficients per section F.1.2.2 */
  565.   
  566.   r = 0;            /* r = run length of zeros */
  567.   
  568.   for (k = 1; k < DCTSIZE2; k++) {
  569.     if ((temp = block[jpeg_natural_order[k]]) == 0) {
  570.       r++;
  571.     } else {
  572.       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  573.       while (r > 15) {
  574.     ac_counts[0xF0]++;
  575.     r -= 16;
  576.       }
  577.       
  578.       /* Find the number of bits needed for the magnitude of the coefficient */
  579.       if (temp < 0)
  580.     temp = -temp;
  581.       
  582.       /* Find the number of bits needed for the magnitude of the coefficient */
  583.       nbits = 1;        /* there must be at least one 1 bit */
  584.       while ((temp >>= 1))
  585.     nbits++;
  586.       
  587.       /* Count Huffman symbol for run length / number of bits */
  588.       ac_counts[(r << 4) + nbits]++;
  589.       
  590.       r = 0;
  591.     }
  592.   }
  593.  
  594.   /* If the last coef(s) were zero, emit an end-of-block code */
  595.   if (r > 0)
  596.     ac_counts[0]++;
  597. }
  598.  
  599.  
  600. /*
  601.  * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  602.  * No data is actually output, so no suspension return is possible.
  603.  */
  604.  
  605. METHODDEF boolean
  606. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  607. {
  608.   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  609.   int16 blkn, ci;
  610.   jpeg_component_info * compptr;
  611.  
  612.   /* Take care of restart intervals if needed */
  613.   if (cinfo->restart_interval) {
  614.     if (entropy->restarts_to_go == 0) {
  615.       /* Re-initialize DC predictions to 0 */
  616.       for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  617.     entropy->saved.last_dc_val[ci] = 0;
  618.       /* Update restart state */
  619.       entropy->restarts_to_go = cinfo->restart_interval;
  620.     }
  621.     entropy->restarts_to_go--;
  622.   }
  623.  
  624.   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  625.     ci = cinfo->MCU_membership[blkn];
  626.     compptr = cinfo->cur_comp_info[ci];
  627.     htest_one_block(MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  628.             entropy->dc_count_ptrs[compptr->dc_tbl_no],
  629.             entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  630.     entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  631.   }
  632.  
  633.   return TRUE;
  634. }
  635.  
  636.  
  637. /*
  638.  * Generate the optimal coding for the given counts, fill htbl.
  639.  * Note this is also used by jcphuff.c.
  640.  */
  641.  
  642. GLOBAL void
  643. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, int32 freq[])
  644. {
  645. #define MAX_CLEN 32        /* assumed maximum initial code length */
  646.   UINT8 bits[MAX_CLEN+1];    /* bits[k] = # of symbols with code length k */
  647.   int16 codesize[257];        /* codesize[k] = code length of symbol k */
  648.   int16 others[257];        /* next symbol in current branch of tree */
  649.   int16 c1, c2;
  650.   int16 p, i, j;
  651.   int32 v;
  652.  
  653.   /* This algorithm is explained in section K.2 of the JPEG standard */
  654.  
  655.   MEMZERO(bits, SIZEOF(bits));
  656.   MEMZERO(codesize, SIZEOF(codesize));
  657.   for (i = 0; i < 257; i++)
  658.     others[i] = -1;        /* init links to empty */
  659.   
  660.   freq[256] = 1;        /* make sure there is a nonzero count */
  661.   /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  662.    * that no real symbol is given code-value of all ones, because 256
  663.    * will be placed in the largest codeword category.
  664.    */
  665.  
  666.   /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  667.  
  668.   for (;;) {
  669.     /* Find the smallest nonzero frequency, set c1 = its symbol */
  670.     /* In case of ties, take the larger symbol number */
  671.     c1 = -1;
  672.     v = 1000000000L;
  673.     for (i = 0; i <= 256; i++) {
  674.       if (freq[i] && freq[i] <= v) {
  675.     v = freq[i];
  676.     c1 = i;
  677.       }
  678.     }
  679.  
  680.     /* Find the next smallest nonzero frequency, set c2 = its symbol */
  681.     /* In case of ties, take the larger symbol number */
  682.     c2 = -1;
  683.     v = 1000000000L;
  684.     for (i = 0; i <= 256; i++) {
  685.       if (freq[i] && freq[i] <= v && i != c1) {
  686.     v = freq[i];
  687.     c2 = i;
  688.       }
  689.     }
  690.  
  691.     /* Done if we've merged everything into one frequency */
  692.     if (c2 < 0)
  693.       break;
  694.     
  695.     /* Else merge the two counts/trees */
  696.     freq[c1] += freq[c2];
  697.     freq[c2] = 0;
  698.  
  699.     /* Increment the codesize of everything in c1's tree branch */
  700.     codesize[c1]++;
  701.     while (others[c1] >= 0) {
  702.       c1 = others[c1];
  703.       codesize[c1]++;
  704.     }
  705.     
  706.     others[c1] = c2;        /* chain c2 onto c1's tree branch */
  707.     
  708.     /* Increment the codesize of everything in c2's tree branch */
  709.     codesize[c2]++;
  710.     while (others[c2] >= 0) {
  711.       c2 = others[c2];
  712.       codesize[c2]++;
  713.     }
  714.   }
  715.  
  716.   /* Now count the number of symbols of each code length */
  717.   for (i = 0; i <= 256; i++) {
  718.     if (codesize[i]) {
  719.       /* The JPEG standard seems to think that this can't happen, */
  720.       /* but I'm paranoid... */
  721.       if (codesize[i] > MAX_CLEN)
  722.     ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  723.  
  724.       bits[codesize[i]]++;
  725.     }
  726.   }
  727.  
  728.   /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  729.    * Huffman procedure assigned any such lengths, we must adjust the coding.
  730.    * Here is what the JPEG spec says about how this next bit works:
  731.    * Since symbols are paired for the longest Huffman code, the symbols are
  732.    * removed from this length category two at a time.  The prefix for the pair
  733.    * (which is one bit shorter) is allocated to one of the pair; then,
  734.    * skipping the BITS entry for that prefix length, a code word from the next
  735.    * shortest nonzero BITS entry is converted into a prefix for two code words
  736.    * one bit longer.
  737.    */
  738.   
  739.   for (i = MAX_CLEN; i > 16; i--) {
  740.     while (bits[i] > 0) {
  741.       j = i - 2;        /* find length of new prefix to be used */
  742.       while (bits[j] == 0)
  743.     j--;
  744.       
  745.       bits[i] -= 2;        /* remove two symbols */
  746.       bits[i-1]++;        /* one goes in this length */
  747.       bits[j+1] += 2;        /* two new symbols in this length */
  748.       bits[j]--;        /* symbol of this length is now a prefix */
  749.     }
  750.   }
  751.  
  752.   /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  753.   while (bits[i] == 0)        /* find largest codelength still in use */
  754.     i--;
  755.   bits[i]--;
  756.   
  757.   /* Return final symbol counts (only for lengths 0..16) */
  758.   MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  759.   
  760.   /* Return a list of the symbols sorted by code length */
  761.   /* It's not real clear to me why we don't need to consider the codelength
  762.    * changes made above, but the JPEG spec seems to think this works.
  763.    */
  764.   p = 0;
  765.   for (i = 1; i <= MAX_CLEN; i++) {
  766.     for (j = 0; j <= 255; j++) {
  767.       if (codesize[j] == i) {
  768.     htbl->huffval[p] = (UINT8) j;
  769.     p++;
  770.       }
  771.     }
  772.   }
  773.  
  774.   /* Set sent_table FALSE so updated table will be written to JPEG file. */
  775.   htbl->sent_table = FALSE;
  776. }
  777.  
  778.  
  779. /*
  780.  * Finish up a statistics-gathering pass and create the new Huffman tables.
  781.  */
  782.  
  783. METHODDEF void
  784. finish_pass_gather (j_compress_ptr cinfo)
  785. {
  786.   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  787.   int16 ci, dctbl, actbl;
  788.   jpeg_component_info * compptr;
  789.   JHUFF_TBL **htblptr;
  790.   boolean did_dc[NUM_HUFF_TBLS];
  791.   boolean did_ac[NUM_HUFF_TBLS];
  792.  
  793.   /* It's important not to apply jpeg_gen_optimal_table more than once
  794.    * per table, because it clobbers the input frequency counts!
  795.    */
  796.   MEMZERO(did_dc, SIZEOF(did_dc));
  797.   MEMZERO(did_ac, SIZEOF(did_ac));
  798.  
  799.   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  800.     compptr = cinfo->cur_comp_info[ci];
  801.     dctbl = compptr->dc_tbl_no;
  802.     actbl = compptr->ac_tbl_no;
  803.     if (! did_dc[dctbl]) {
  804.       htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  805.       if (*htblptr == NULL)
  806.     *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  807.       jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  808.       did_dc[dctbl] = TRUE;
  809.     }
  810.     if (! did_ac[actbl]) {
  811.       htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  812.       if (*htblptr == NULL)
  813.     *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  814.       jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  815.       did_ac[actbl] = TRUE;
  816.     }
  817.   }
  818. }
  819.  
  820.  
  821. #endif /* ENTROPY_OPT_SUPPORTED */
  822.  
  823.  
  824. /*
  825.  * Module initialization routine for Huffman entropy encoding.
  826.  */
  827.  
  828. GLOBAL void
  829. jinit_huff_encoder (j_compress_ptr cinfo)
  830. {
  831.   huff_entropy_ptr entropy;
  832.   int16 i;
  833.  
  834.   entropy = (huff_entropy_ptr)
  835.     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  836.                 SIZEOF(huff_entropy_encoder));
  837.   cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  838.   entropy->pub.start_pass = start_pass_huff;
  839.  
  840.   /* Mark tables unallocated */
  841.   for (i = 0; i < NUM_HUFF_TBLS; i++) {
  842.     entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  843. #ifdef ENTROPY_OPT_SUPPORTED
  844.     entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  845. #endif
  846.   }
  847. }
  848.