home *** CD-ROM | disk | FTP | other *** search
/ Encyclopedia of Graphics File Formats Companion / GFF_CD.ISO / software / unix / jpeg / jpegv4a.tar / jchuff.c < prev    next >
C/C++ Source or Header  |  1993-02-10  |  20KB  |  701 lines

  1. /*
  2.  * jchuff.c
  3.  *
  4.  * Copyright (C) 1991, 1992, 1993, 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.  * These routines are invoked via the methods entropy_encode,
  10.  * entropy_encode_init/term, and entropy_optimize.
  11.  */
  12.  
  13. #include "jinclude.h"
  14.  
  15.  
  16. /* Static variables to avoid passing 'round extra parameters */
  17.  
  18. static compress_info_ptr cinfo;
  19.  
  20. static INT32 huff_put_buffer;    /* current bit-accumulation buffer */
  21. static int huff_put_bits;    /* # of bits now in it */
  22.  
  23. static char * output_buffer;    /* output buffer */
  24. static int bytes_in_buffer;
  25.  
  26.  
  27.  
  28. LOCAL void
  29. fix_huff_tbl (HUFF_TBL * htbl)
  30. /* Compute derived values for a Huffman table */
  31. {
  32.   int p, i, l, lastp, si;
  33.   char huffsize[257];
  34.   UINT16 huffcode[257];
  35.   UINT16 code;
  36.   
  37.   /* Figure C.1: make table of Huffman code length for each symbol */
  38.   /* Note that this is in code-length order. */
  39.  
  40.   p = 0;
  41.   for (l = 1; l <= 16; l++) {
  42.     for (i = 1; i <= (int) htbl->bits[l]; i++)
  43.       huffsize[p++] = (char) l;
  44.   }
  45.   huffsize[p] = 0;
  46.   lastp = p;
  47.   
  48.   /* Figure C.2: generate the codes themselves */
  49.   /* Note that this is in code-length order. */
  50.   
  51.   code = 0;
  52.   si = huffsize[0];
  53.   p = 0;
  54.   while (huffsize[p]) {
  55.     while (((int) huffsize[p]) == si) {
  56.       huffcode[p++] = code;
  57.       code++;
  58.     }
  59.     code <<= 1;
  60.     si++;
  61.   }
  62.   
  63.   /* Figure C.3: generate encoding tables */
  64.   /* These are code and size indexed by symbol value */
  65.  
  66.   /* Set any codeless symbols to have code length 0;
  67.    * this allows emit_bits to detect any attempt to emit such symbols.
  68.    */
  69.   MEMZERO(htbl->priv.enc.ehufsi, SIZEOF(htbl->priv.enc.ehufsi));
  70.  
  71.   for (p = 0; p < lastp; p++) {
  72.     htbl->priv.enc.ehufco[htbl->huffval[p]] = huffcode[p];
  73.     htbl->priv.enc.ehufsi[htbl->huffval[p]] = huffsize[p];
  74.   }
  75. }
  76.  
  77.  
  78. /* Outputting bytes to the file */
  79.  
  80. LOCAL void
  81. flush_bytes (void)
  82. {
  83.   if (bytes_in_buffer)
  84.     (*cinfo->methods->entropy_output) (cinfo, output_buffer, bytes_in_buffer);
  85.   bytes_in_buffer = 0;
  86. }
  87.  
  88.  
  89. #define emit_byte(val)  \
  90.   MAKESTMT( if (bytes_in_buffer >= JPEG_BUF_SIZE) \
  91.           flush_bytes(); \
  92.         output_buffer[bytes_in_buffer++] = (char) (val); )
  93.  
  94.  
  95.  
  96. /* Outputting bits to the file */
  97.  
  98. /* Only the right 24 bits of huff_put_buffer are used; the valid bits are
  99.  * left-justified in this part.  At most 16 bits can be passed to emit_bits
  100.  * in one call, and we never retain more than 7 bits in huff_put_buffer
  101.  * between calls, so 24 bits are sufficient.
  102.  */
  103.  
  104. INLINE
  105. LOCAL void
  106. emit_bits (UINT16 code, int size)
  107. {
  108.   /* This routine is heavily used, so it's worth coding tightly. */
  109.   register INT32 put_buffer = code;
  110.   register int put_bits = huff_put_bits;
  111.  
  112.   /* if size is 0, caller used an invalid Huffman table entry */
  113.   if (size == 0)
  114.     ERREXIT(cinfo->emethods, "Missing Huffman code table entry");
  115.  
  116.   put_buffer &= (((INT32) 1) << size) - 1; /* Mask off any excess bits in code */
  117.   
  118.   put_bits += size;        /* new number of bits in buffer */
  119.   
  120.   put_buffer <<= 24 - put_bits; /* align incoming bits */
  121.  
  122.   put_buffer |= huff_put_buffer; /* and merge with old buffer contents */
  123.   
  124.   while (put_bits >= 8) {
  125.     int c = (int) ((put_buffer >> 16) & 0xFF);
  126.     
  127.     emit_byte(c);
  128.     if (c == 0xFF) {        /* need to stuff a zero byte? */
  129.       emit_byte(0);
  130.     }
  131.     put_buffer <<= 8;
  132.     put_bits -= 8;
  133.   }
  134.  
  135.   huff_put_buffer = put_buffer;    /* Update global variables */
  136.   huff_put_bits = put_bits;
  137. }
  138.  
  139.  
  140. LOCAL void
  141. flush_bits (void)
  142. {
  143.   emit_bits((UINT16) 0x7F, 7);    /* fill any partial byte with ones */
  144.   huff_put_buffer = 0;        /* and reset bit-buffer to empty */
  145.   huff_put_bits = 0;
  146. }
  147.  
  148.  
  149.  
  150. /* Encode a single block's worth of coefficients */
  151. /* Note that the DC coefficient has already been converted to a difference */
  152.  
  153. LOCAL void
  154. encode_one_block (JBLOCK block, HUFF_TBL *dctbl, HUFF_TBL *actbl)
  155. {
  156.   register int temp, temp2;
  157.   register int nbits;
  158.   register int k, r, i;
  159.   
  160.   /* Encode the DC coefficient difference per section F.1.2.1 */
  161.   
  162.   temp = temp2 = block[0];
  163.  
  164.   if (temp < 0) {
  165.     temp = -temp;        /* temp is abs value of input */
  166.     /* For a negative input, want temp2 = bitwise complement of abs(input) */
  167.     /* This code assumes we are on a two's complement machine */
  168.     temp2--;
  169.   }
  170.   
  171.   /* Find the number of bits needed for the magnitude of the coefficient */
  172.   nbits = 0;
  173.   while (temp) {
  174.     nbits++;
  175.     temp >>= 1;
  176.   }
  177.   
  178.   /* Emit the Huffman-coded symbol for the number of bits */
  179.   emit_bits(dctbl->priv.enc.ehufco[nbits], dctbl->priv.enc.ehufsi[nbits]);
  180.  
  181.   /* Emit that number of bits of the value, if positive, */
  182.   /* or the complement of its magnitude, if negative. */
  183.   if (nbits)            /* emit_bits rejects calls with size 0 */
  184.     emit_bits((UINT16) temp2, nbits);
  185.   
  186.   /* Encode the AC coefficients per section F.1.2.2 */
  187.   
  188.   r = 0;            /* r = run length of zeros */
  189.   
  190.   for (k = 1; k < DCTSIZE2; k++) {
  191.     if ((temp = block[k]) == 0) {
  192.       r++;
  193.     } else {
  194.       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  195.       while (r > 15) {
  196.     emit_bits(actbl->priv.enc.ehufco[0xF0], actbl->priv.enc.ehufsi[0xF0]);
  197.     r -= 16;
  198.       }
  199.  
  200.       temp2 = temp;
  201.       if (temp < 0) {
  202.     temp = -temp;        /* temp is abs value of input */
  203.     /* This code assumes we are on a two's complement machine */
  204.     temp2--;
  205.       }
  206.       
  207.       /* Find the number of bits needed for the magnitude of the coefficient */
  208.       nbits = 1;        /* there must be at least one 1 bit */
  209.       while (temp >>= 1)
  210.     nbits++;
  211.       
  212.       /* Emit Huffman symbol for run length / number of bits */
  213.       i = (r << 4) + nbits;
  214.       emit_bits(actbl->priv.enc.ehufco[i], actbl->priv.enc.ehufsi[i]);
  215.       
  216.       /* Emit that number of bits of the value, if positive, */
  217.       /* or the complement of its magnitude, if negative. */
  218.       emit_bits((UINT16) temp2, nbits);
  219.       
  220.       r = 0;
  221.     }
  222.   }
  223.  
  224.   /* If the last coef(s) were zero, emit an end-of-block code */
  225.   if (r > 0)
  226.     emit_bits(actbl->priv.enc.ehufco[0], actbl->priv.enc.ehufsi[0]);
  227. }
  228.  
  229.  
  230.  
  231. /*
  232.  * Initialize for a Huffman-compressed scan.
  233.  * This is invoked after writing the SOS marker.
  234.  * The pipeline controller must establish the entropy_output method pointer
  235.  * before calling this routine.
  236.  */
  237.  
  238. METHODDEF void
  239. huff_init (compress_info_ptr xinfo)
  240. {
  241.   short ci;
  242.   jpeg_component_info * compptr;
  243.  
  244.   /* Initialize static variables */
  245.   cinfo = xinfo;
  246.   huff_put_buffer = 0;
  247.   huff_put_bits = 0;
  248.  
  249.   /* Initialize the output buffer */
  250.   output_buffer = (char *) (*cinfo->emethods->alloc_small)
  251.                 ((size_t) JPEG_BUF_SIZE);
  252.   bytes_in_buffer = 0;
  253.  
  254.   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  255.     compptr = cinfo->cur_comp_info[ci];
  256.     /* Make sure requested tables are present */
  257.     if (cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no] == NULL ||
  258.     cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no] == NULL)
  259.       ERREXIT(cinfo->emethods, "Use of undefined Huffman table");
  260.     /* Compute derived values for Huffman tables */
  261.     /* We may do this more than once for same table, but it's not a big deal */
  262.     fix_huff_tbl(cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no]);
  263.     fix_huff_tbl(cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no]);
  264.     /* Initialize DC predictions to 0 */
  265.     cinfo->last_dc_val[ci] = 0;
  266.   }
  267.  
  268.   /* Initialize restart stuff */
  269.   cinfo->restarts_to_go = cinfo->restart_interval;
  270.   cinfo->next_restart_num = 0;
  271. }
  272.  
  273.  
  274. /*
  275.  * Emit a restart marker & resynchronize predictions.
  276.  */
  277.  
  278. LOCAL void
  279. emit_restart (compress_info_ptr cinfo)
  280. {
  281.   short ci;
  282.  
  283.   flush_bits();
  284.  
  285.   emit_byte(0xFF);
  286.   emit_byte(RST0 + cinfo->next_restart_num);
  287.  
  288.   /* Re-initialize DC predictions to 0 */
  289.   for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  290.     cinfo->last_dc_val[ci] = 0;
  291.  
  292.   /* Update restart state */
  293.   cinfo->restarts_to_go = cinfo->restart_interval;
  294.   cinfo->next_restart_num++;
  295.   cinfo->next_restart_num &= 7;
  296. }
  297.  
  298.  
  299. /*
  300.  * Encode and output one MCU's worth of Huffman-compressed coefficients.
  301.  */
  302.  
  303. METHODDEF void
  304. huff_encode (compress_info_ptr cinfo, JBLOCK *MCU_data)
  305. {
  306.   short blkn, ci;
  307.   jpeg_component_info * compptr;
  308.   JCOEF temp;
  309.  
  310.   /* Account for restart interval, emit restart marker if needed */
  311.   if (cinfo->restart_interval) {
  312.     if (cinfo->restarts_to_go == 0)
  313.       emit_restart(cinfo);
  314.     cinfo->restarts_to_go--;
  315.   }
  316.  
  317.   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  318.     ci = cinfo->MCU_membership[blkn];
  319.     compptr = cinfo->cur_comp_info[ci];
  320.     /* Convert DC value to difference, update last_dc_val */
  321.     temp = MCU_data[blkn][0];
  322.     MCU_data[blkn][0] -= cinfo->last_dc_val[ci];
  323.     cinfo->last_dc_val[ci] = temp;
  324.     encode_one_block(MCU_data[blkn],
  325.              cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no],
  326.              cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no]);
  327.   }
  328. }
  329.  
  330.  
  331. /*
  332.  * Finish up at the end of a Huffman-compressed scan.
  333.  */
  334.  
  335. METHODDEF void
  336. huff_term (compress_info_ptr cinfo)
  337. {
  338.   /* Flush out the last data */
  339.   flush_bits();
  340.   flush_bytes();
  341.   /* Release the I/O buffer */
  342.   (*cinfo->emethods->free_small) ((void *) output_buffer);
  343. }
  344.  
  345.  
  346.  
  347.  
  348. /*
  349.  * Huffman coding optimization.
  350.  *
  351.  * This actually is optimization, in the sense that we find the best possible
  352.  * Huffman table(s) for the given data.  We first scan the supplied data and
  353.  * count the number of uses of each symbol that is to be Huffman-coded.
  354.  * (This process must agree with the code above.)  Then we build an
  355.  * optimal Huffman coding tree for the observed counts.
  356.  */
  357.  
  358. #ifdef ENTROPY_OPT_SUPPORTED
  359.  
  360.  
  361. /* These are static so htest_one_block can find 'em */
  362. static long * dc_count_ptrs[NUM_HUFF_TBLS];
  363. static long * ac_count_ptrs[NUM_HUFF_TBLS];
  364.  
  365.  
  366. LOCAL void
  367. gen_huff_coding (compress_info_ptr cinfo, HUFF_TBL *htbl, long freq[])
  368. /* Generate the optimal coding for the given counts */
  369. {
  370. #define MAX_CLEN 32        /* assumed maximum initial code length */
  371.   UINT8 bits[MAX_CLEN+1];    /* bits[k] = # of symbols with code length k */
  372.   short codesize[257];        /* codesize[k] = code length of symbol k */
  373.   short others[257];        /* next symbol in current branch of tree */
  374.   int c1, c2;
  375.   int p, i, j;
  376.   long v;
  377.  
  378.   /* This algorithm is explained in section K.2 of the JPEG standard */
  379.  
  380.   MEMZERO(bits, SIZEOF(bits));
  381.   MEMZERO(codesize, SIZEOF(codesize));
  382.   for (i = 0; i < 257; i++)
  383.     others[i] = -1;        /* init links to empty */
  384.   
  385.   freq[256] = 1;        /* make sure there is a nonzero count */
  386.   /* including the pseudo-symbol 256 in the Huffman procedure guarantees
  387.    * that no real symbol is given code-value of all ones, because 256
  388.    * will be placed in the largest codeword category.
  389.    */
  390.  
  391.   /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  392.  
  393.   for (;;) {
  394.     /* Find the smallest nonzero frequency, set c1 = its symbol */
  395.     /* In case of ties, take the larger symbol number */
  396.     c1 = -1;
  397.     v = 1000000000L;
  398.     for (i = 0; i <= 256; i++) {
  399.       if (freq[i] && freq[i] <= v) {
  400.     v = freq[i];
  401.     c1 = i;
  402.       }
  403.     }
  404.  
  405.     /* Find the next smallest nonzero frequency, set c2 = its symbol */
  406.     /* In case of ties, take the larger symbol number */
  407.     c2 = -1;
  408.     v = 1000000000L;
  409.     for (i = 0; i <= 256; i++) {
  410.       if (freq[i] && freq[i] <= v && i != c1) {
  411.     v = freq[i];
  412.     c2 = i;
  413.       }
  414.     }
  415.  
  416.     /* Done if we've merged everything into one frequency */
  417.     if (c2 < 0)
  418.       break;
  419.     
  420.     /* Else merge the two counts/trees */
  421.     freq[c1] += freq[c2];
  422.     freq[c2] = 0;
  423.  
  424.     /* Increment the codesize of everything in c1's tree branch */
  425.     codesize[c1]++;
  426.     while (others[c1] >= 0) {
  427.       c1 = others[c1];
  428.       codesize[c1]++;
  429.     }
  430.     
  431.     others[c1] = c2;        /* chain c2 onto c1's tree branch */
  432.     
  433.     /* Increment the codesize of everything in c2's tree branch */
  434.     codesize[c2]++;
  435.     while (others[c2] >= 0) {
  436.       c2 = others[c2];
  437.       codesize[c2]++;
  438.     }
  439.   }
  440.  
  441.   /* Now count the number of symbols of each code length */
  442.   for (i = 0; i <= 256; i++) {
  443.     if (codesize[i]) {
  444.       /* The JPEG standard seems to think that this can't happen, */
  445.       /* but I'm paranoid... */
  446.       if (codesize[i] > MAX_CLEN)
  447.     ERREXIT(cinfo->emethods, "Huffman code size table overflow");
  448.  
  449.       bits[codesize[i]]++;
  450.     }
  451.   }
  452.  
  453.   /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  454.    * Huffman procedure assigned any such lengths, we must adjust the coding.
  455.    * Here is what the JPEG spec says about how this next bit works:
  456.    * Since symbols are paired for the longest Huffman code, the symbols are
  457.    * removed from this length category two at a time.  The prefix for the pair
  458.    * (which is one bit shorter) is allocated to one of the pair; then,
  459.    * skipping the BITS entry for that prefix length, a code word from the next
  460.    * shortest nonzero BITS entry is converted into a prefix for two code words
  461.    * one bit longer.
  462.    */
  463.   
  464.   for (i = MAX_CLEN; i > 16; i--) {
  465.     while (bits[i] > 0) {
  466.       j = i - 2;        /* find length of new prefix to be used */
  467.       while (bits[j] == 0)
  468.     j--;
  469.       
  470.       bits[i] -= 2;        /* remove two symbols */
  471.       bits[i-1]++;        /* one goes in this length */
  472.       bits[j+1] += 2;        /* two new symbols in this length */
  473.       bits[j]--;        /* symbol of this length is now a prefix */
  474.     }
  475.   }
  476.  
  477.   /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  478.   while (bits[i] == 0)        /* find largest codelength still in use */
  479.     i--;
  480.   bits[i]--;
  481.   
  482.   /* Return final symbol counts (only for lengths 0..16) */
  483.   MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  484.   
  485.   /* Return a list of the symbols sorted by code length */
  486.   /* It's not real clear to me why we don't need to consider the codelength
  487.    * changes made above, but the JPEG spec seems to think this works.
  488.    */
  489.   p = 0;
  490.   for (i = 1; i <= MAX_CLEN; i++) {
  491.     for (j = 0; j <= 255; j++) {
  492.       if (codesize[j] == i) {
  493.     htbl->huffval[p] = (UINT8) j;
  494.     p++;
  495.       }
  496.     }
  497.   }
  498. }
  499.  
  500.  
  501. /* Process a single block's worth of coefficients */
  502. /* Note that the DC coefficient has already been converted to a difference */
  503.  
  504. LOCAL void
  505. htest_one_block (JBLOCK block, JCOEF block0,
  506.          long dc_counts[], long ac_counts[])
  507. {
  508.   register INT32 temp;
  509.   register int nbits;
  510.   register int k, r;
  511.   
  512.   /* Encode the DC coefficient difference per section F.1.2.1 */
  513.   
  514.   /* Find the number of bits needed for the magnitude of the coefficient */
  515.   temp = block0;
  516.   if (temp < 0) temp = -temp;
  517.   
  518.   for (nbits = 0; temp; nbits++)
  519.     temp >>= 1;
  520.   
  521.   /* Count the Huffman symbol for the number of bits */
  522.   dc_counts[nbits]++;
  523.   
  524.   /* Encode the AC coefficients per section F.1.2.2 */
  525.   
  526.   r = 0;            /* r = run length of zeros */
  527.   
  528.   for (k = 1; k < DCTSIZE2; k++) {
  529.     if ((temp = block[k]) == 0) {
  530.       r++;
  531.     } else {
  532.       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  533.       while (r > 15) {
  534.     ac_counts[0xF0]++;
  535.     r -= 16;
  536.       }
  537.       
  538.       /* Find the number of bits needed for the magnitude of the coefficient */
  539.       if (temp < 0) temp = -temp;
  540.       
  541.       for (nbits = 0; temp; nbits++)
  542.     temp >>= 1;
  543.       
  544.       /* Count Huffman symbol for run length / number of bits */
  545.       ac_counts[(r << 4) + nbits]++;
  546.       
  547.       r = 0;
  548.     }
  549.   }
  550.  
  551.   /* If the last coef(s) were zero, emit an end-of-block code */
  552.   if (r > 0)
  553.     ac_counts[0]++;
  554. }
  555.  
  556.  
  557.  
  558. /*
  559.  * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  560.  */
  561.  
  562. LOCAL void
  563. htest_encode (compress_info_ptr cinfo, JBLOCK *MCU_data)
  564. {
  565.   short blkn, ci;
  566.   jpeg_component_info * compptr;
  567.  
  568.   /* Take care of restart intervals if needed */
  569.   if (cinfo->restart_interval) {
  570.     if (cinfo->restarts_to_go == 0) {
  571.       /* Re-initialize DC predictions to 0 */
  572.       for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  573.     cinfo->last_dc_val[ci] = 0;
  574.       /* Update restart state */
  575.       cinfo->restarts_to_go = cinfo->restart_interval;
  576.     }
  577.     cinfo->restarts_to_go--;
  578.   }
  579.  
  580.   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  581.     ci = cinfo->MCU_membership[blkn];
  582.     compptr = cinfo->cur_comp_info[ci];
  583.     /* NB: unlike the real entropy encoder, we may not change the input data */
  584.     htest_one_block(MCU_data[blkn],
  585.             (JCOEF) (MCU_data[blkn][0] - cinfo->last_dc_val[ci]),
  586.             dc_count_ptrs[compptr->dc_tbl_no],
  587.             ac_count_ptrs[compptr->ac_tbl_no]);
  588.     cinfo->last_dc_val[ci] = MCU_data[blkn][0];
  589.   }
  590. }
  591.  
  592.  
  593.  
  594. /*
  595.  * Find the best coding parameters for a Huffman-coded scan.
  596.  * When called, the scan data has already been converted to a sequence of
  597.  * MCU groups of quantized coefficients, which are stored in a "big" array.
  598.  * The source_method knows how to iterate through that array.
  599.  * On return, the MCU data is unmodified, but the Huffman tables referenced
  600.  * by the scan components may have been altered.
  601.  */
  602.  
  603. METHODDEF void
  604. huff_optimize (compress_info_ptr cinfo, MCU_output_caller_ptr source_method)
  605. /* Optimize Huffman-coding parameters (Huffman symbol table) */
  606. {
  607.   int i, tbl;
  608.   HUFF_TBL **htblptr;
  609.  
  610.   /* Allocate and zero the count tables */
  611.   /* Note that gen_huff_coding expects 257 entries in each table! */
  612.  
  613.   for (i = 0; i < NUM_HUFF_TBLS; i++) {
  614.     dc_count_ptrs[i] = NULL;
  615.     ac_count_ptrs[i] = NULL;
  616.   }
  617.  
  618.   for (i = 0; i < cinfo->comps_in_scan; i++) {
  619.     /* Create DC table */
  620.     tbl = cinfo->cur_comp_info[i]->dc_tbl_no;
  621.     if (dc_count_ptrs[tbl] == NULL) {
  622.       dc_count_ptrs[tbl] = (long *) (*cinfo->emethods->alloc_small)
  623.                     (257 * SIZEOF(long));
  624.       MEMZERO(dc_count_ptrs[tbl], 257 * SIZEOF(long));
  625.     }
  626.     /* Create AC table */
  627.     tbl = cinfo->cur_comp_info[i]->ac_tbl_no;
  628.     if (ac_count_ptrs[tbl] == NULL) {
  629.       ac_count_ptrs[tbl] = (long *) (*cinfo->emethods->alloc_small)
  630.                     (257 * SIZEOF(long));
  631.       MEMZERO(ac_count_ptrs[tbl], 257 * SIZEOF(long));
  632.     }
  633.   }
  634.  
  635.   /* Initialize DC predictions to 0 */
  636.   for (i = 0; i < cinfo->comps_in_scan; i++) {
  637.     cinfo->last_dc_val[i] = 0;
  638.   }
  639.   /* Initialize restart stuff */
  640.   cinfo->restarts_to_go = cinfo->restart_interval;
  641.  
  642.   /* Scan the MCU data, count symbol uses */
  643.   (*source_method) (cinfo, htest_encode);
  644.  
  645.   /* Now generate optimal Huffman tables */
  646.   for (tbl = 0; tbl < NUM_HUFF_TBLS; tbl++) {
  647.     if (dc_count_ptrs[tbl] != NULL) {
  648.       htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  649.       if (*htblptr == NULL)
  650.     *htblptr = (HUFF_TBL *) (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
  651.       /* Set sent_table FALSE so updated table will be written to JPEG file. */
  652.       (*htblptr)->sent_table = FALSE;
  653.       /* Compute the optimal Huffman encoding */
  654.       gen_huff_coding(cinfo, *htblptr, dc_count_ptrs[tbl]);
  655.       /* Release the count table */
  656.       (*cinfo->emethods->free_small) ((void *) dc_count_ptrs[tbl]);
  657.     }
  658.     if (ac_count_ptrs[tbl] != NULL) {
  659.       htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  660.       if (*htblptr == NULL)
  661.     *htblptr = (HUFF_TBL *) (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
  662.       /* Set sent_table FALSE so updated table will be written to JPEG file. */
  663.       (*htblptr)->sent_table = FALSE;
  664.       /* Compute the optimal Huffman encoding */
  665.       gen_huff_coding(cinfo, *htblptr, ac_count_ptrs[tbl]);
  666.       /* Release the count table */
  667.       (*cinfo->emethods->free_small) ((void *) ac_count_ptrs[tbl]);
  668.     }
  669.   }
  670. }
  671.  
  672.  
  673. #endif /* ENTROPY_OPT_SUPPORTED */
  674.  
  675.  
  676. /*
  677.  * The method selection routine for Huffman entropy encoding.
  678.  */
  679.  
  680. GLOBAL void
  681. jselchuffman (compress_info_ptr cinfo)
  682. {
  683.   if (! cinfo->arith_code) {
  684.     cinfo->methods->entropy_encode_init = huff_init;
  685.     cinfo->methods->entropy_encode = huff_encode;
  686.     cinfo->methods->entropy_encode_term = huff_term;
  687. #ifdef ENTROPY_OPT_SUPPORTED
  688.     cinfo->methods->entropy_optimize = huff_optimize;
  689.     /* The standard Huffman tables are only valid for 8-bit data precision.
  690.      * If the precision is higher, force optimization on so that usable
  691.      * tables will be computed.  This test can be removed if default tables
  692.      * are supplied that are valid for the desired precision.
  693.      */
  694.     if (cinfo->data_precision > 8)
  695.       cinfo->optimize_coding = TRUE;
  696.     if (cinfo->optimize_coding)
  697.       cinfo->total_passes++;    /* one pass needed for entropy optimization */
  698. #endif
  699.   }
  700. }
  701.