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

  1. /*
  2.  * jcphuff.c
  3.  *
  4.  * Copyright (C) 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 for progressive JPEG.
  9.  *
  10.  * We do not support output suspension in this module, since the library
  11.  * currently does not allow multiple-scan files to be written with output
  12.  * suspension.
  13.  */
  14.  
  15. #define JPEG_INTERNALS
  16. #include "xp_core.h"/*defines of int32 ect*/
  17. #include "jinclude.h"
  18. #include "jpeglib.h"
  19. #include "jchuff.h"        /* Declarations shared with jchuff.c */
  20.  
  21. #ifdef C_PROGRESSIVE_SUPPORTED
  22.  
  23. /* Expanded entropy encoder object for progressive Huffman encoding. */
  24.  
  25. typedef struct {
  26.   struct jpeg_entropy_encoder pub; /* public fields */
  27.  
  28.   /* Mode flag: TRUE for optimization, FALSE for actual data output */
  29.   boolean gather_statistics;
  30.  
  31.   /* Bit-level coding status.
  32.    * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  33.    */
  34.   JOCTET * next_output_byte;    /* => next byte to write in buffer */
  35.   size_t free_in_buffer;    /* # of byte spaces remaining in buffer */
  36.   int32 put_buffer;        /* current bit-accumulation buffer */
  37.   int16 put_bits;            /* # of bits now in it */
  38.   j_compress_ptr cinfo;        /* link to cinfo (needed for dump_buffer) */
  39.  
  40.   /* Coding status for DC components */
  41.   int16 last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  42.  
  43.   /* Coding status for AC components */
  44.   int16 ac_tbl_no;        /* the table number of the single component */
  45.   uint16 EOBRUN;        /* run length of EOBs */
  46.   uint16 BE;        /* # of buffered correction bits before MCU */
  47.   char * bit_buffer;        /* buffer for correction bits (1 per char) */
  48.   /* packing correction bits tightly would save some space but cost time... */
  49.  
  50.   uint16 restarts_to_go;    /* MCUs left in this restart interval */
  51.   int16 next_restart_num;        /* next restart number to write (0-7) */
  52.  
  53.   /* Pointers to derived tables (these workspaces have image lifespan).
  54.    * Since any one scan codes only DC or only AC, we only need one set
  55.    * of tables, not one for DC and one for AC.
  56.    */
  57.   c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  58.  
  59.   /* Statistics tables for optimization; again, one set is enough */
  60.   int32 * count_ptrs[NUM_HUFF_TBLS];
  61. } phuff_entropy_encoder;
  62.  
  63. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  64.  
  65. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  66.  * buffer can hold.  Larger sizes may slightly improve compression, but
  67.  * 1000 is already well into the realm of overkill.
  68.  * The minimum safe size is 64 bits.
  69.  */
  70.  
  71. #define MAX_CORR_BITS  1000    /* Max # of correction bits I can buffer */
  72.  
  73. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int16 rather than int32.
  74.  * We assume that int16 right shift is unsigned if int32 right shift is,
  75.  * which should be safe.
  76.  */
  77.  
  78. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  79. #define ISHIFT_TEMPS    int16 ishift_temp;
  80. #define IRIGHT_SHIFT(x,shft)  \
  81.     ((ishift_temp = (x)) < 0 ? \
  82.      (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  83.      (ishift_temp >> (shft)))
  84. #else
  85. #define ISHIFT_TEMPS
  86. #define IRIGHT_SHIFT(x,shft)    ((x) >> (shft))
  87. #endif
  88.  
  89. /* Forward declarations */
  90. METHODDEF boolean encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  91.                        JBLOCKROW *MCU_data));
  92. METHODDEF boolean encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  93.                        JBLOCKROW *MCU_data));
  94. METHODDEF boolean encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  95.                         JBLOCKROW *MCU_data));
  96. METHODDEF boolean encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  97.                         JBLOCKROW *MCU_data));
  98. METHODDEF void finish_pass_phuff JPP((j_compress_ptr cinfo));
  99. METHODDEF void finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  100.  
  101.  
  102. /*
  103.  * Initialize for a Huffman-compressed scan using progressive JPEG.
  104.  */
  105.  
  106. METHODDEF void
  107. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  108. {  
  109.   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  110.   boolean is_DC_band;
  111.   int16 ci, tbl;
  112.   jpeg_component_info * compptr;
  113.  
  114.   entropy->cinfo = cinfo;
  115.   entropy->gather_statistics = gather_statistics;
  116.  
  117.   is_DC_band = (cinfo->Ss == 0);
  118.  
  119.   /* We assume jcmaster.c already validated the scan parameters. */
  120.  
  121.   /* Select execution routines */
  122.   if (cinfo->Ah == 0) {
  123.     if (is_DC_band)
  124.       entropy->pub.encode_mcu = encode_mcu_DC_first;
  125.     else
  126.       entropy->pub.encode_mcu = encode_mcu_AC_first;
  127.   } else {
  128.     if (is_DC_band)
  129.       entropy->pub.encode_mcu = encode_mcu_DC_refine;
  130.     else {
  131.       entropy->pub.encode_mcu = encode_mcu_AC_refine;
  132.       /* AC refinement needs a correction bit buffer */
  133.       if (entropy->bit_buffer == NULL)
  134.     entropy->bit_buffer = (char *)
  135.       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  136.                       MAX_CORR_BITS * SIZEOF(char));
  137.     }
  138.   }
  139.   if (gather_statistics)
  140.     entropy->pub.finish_pass = finish_pass_gather_phuff;
  141.   else
  142.     entropy->pub.finish_pass = finish_pass_phuff;
  143.  
  144.   /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  145.    * for AC coefficients.
  146.    */
  147.   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  148.     compptr = cinfo->cur_comp_info[ci];
  149.     /* Initialize DC predictions to 0 */
  150.     entropy->last_dc_val[ci] = 0;
  151.     /* Make sure requested tables are present */
  152.     /* (In gather mode, tables need not be allocated yet) */
  153.     if (is_DC_band) {
  154.       if (cinfo->Ah != 0)    /* DC refinement needs no table */
  155.     continue;
  156.       tbl = compptr->dc_tbl_no;
  157.       if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
  158.       (cinfo->dc_huff_tbl_ptrs[tbl] == NULL && !gather_statistics))
  159.     ERREXIT1(cinfo,JERR_NO_HUFF_TABLE, tbl);
  160.     } else {
  161.       entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  162.       if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
  163.           (cinfo->ac_huff_tbl_ptrs[tbl] == NULL && !gather_statistics))
  164.         ERREXIT1(cinfo,JERR_NO_HUFF_TABLE, tbl);
  165.     }
  166.     if (gather_statistics) {
  167.       /* Allocate and zero the statistics tables */
  168.       /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  169.       if (entropy->count_ptrs[tbl] == NULL)
  170.     entropy->count_ptrs[tbl] = (int32 *)
  171.       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172.                       257 * SIZEOF(int32));
  173.       MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(int32));
  174.     } else {
  175.       /* Compute derived values for Huffman tables */
  176.       /* We may do this more than once for a table, but it's not expensive */
  177.       if (is_DC_band)
  178.         jpeg_make_c_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[tbl],
  179.                 & entropy->derived_tbls[tbl]);
  180.       else
  181.         jpeg_make_c_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[tbl],
  182.                 & entropy->derived_tbls[tbl]);
  183.     }
  184.   }
  185.  
  186.   /* Initialize AC stuff */
  187.   entropy->EOBRUN = 0;
  188.   entropy->BE = 0;
  189.  
  190.   /* Initialize bit buffer to empty */
  191.   entropy->put_buffer = 0;
  192.   entropy->put_bits = 0;
  193.  
  194.   /* Initialize restart stuff */
  195.   entropy->restarts_to_go = cinfo->restart_interval;
  196.   entropy->next_restart_num = 0;
  197. }
  198.  
  199.  
  200. /* Outputting bytes to the file.
  201.  * NB: these must be called only when actually outputting,
  202.  * that is, entropy->gather_statistics == FALSE.
  203.  */
  204.  
  205. /* Emit a byte */
  206. #define emit_byte(entropy,val)  \
  207.     { *(entropy)->next_output_byte++ = (JOCTET) (val);  \
  208.       if (--(entropy)->free_in_buffer == 0)  \
  209.         dump_buffer(entropy); }
  210.  
  211.  
  212. LOCAL void
  213. dump_buffer (phuff_entropy_ptr entropy)
  214. /* Empty the output buffer; we do not support suspension in this module. */
  215. {
  216.   struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  217.  
  218.   if (! (*dest->empty_output_buffer) (entropy->cinfo))
  219.     ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  220.   /* After a successful buffer dump, must reset buffer pointers */
  221.   entropy->next_output_byte = dest->next_output_byte;
  222.   entropy->free_in_buffer = dest->free_in_buffer;
  223. }
  224.  
  225.  
  226. /* Outputting bits to the file */
  227.  
  228. /* Only the right 24 bits of put_buffer are used; the valid bits are
  229.  * left-justified in this part.  At most 16 bits can be passed to emit_bits
  230.  * in one call, and we never retain more than 7 bits in put_buffer
  231.  * between calls, so 24 bits are sufficient.
  232.  */
  233.  
  234. INLINE
  235. LOCAL void
  236. emit_bits (phuff_entropy_ptr entropy, uint16 code, int16 size)
  237. /* Emit some bits, unless we are in gather mode */
  238. {
  239.   /* This routine is heavily used, so it's worth coding tightly. */
  240.   register int32 put_buffer = (int32) code;
  241.   register int16 put_bits = entropy->put_bits;
  242.  
  243.   /* if size is 0, caller used an invalid Huffman table entry */
  244.   if (size == 0)
  245.     ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  246.  
  247.   if (entropy->gather_statistics)
  248.     return;            /* do nothing if we're only getting stats */
  249.  
  250.   put_buffer &= (((int32) 1)<<size) - 1; /* mask off any extra bits in code */
  251.   
  252.   put_bits += size;        /* new number of bits in buffer */
  253.   
  254.   put_buffer <<= 24 - put_bits; /* align incoming bits */
  255.  
  256.   put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  257.  
  258.   while (put_bits >= 8) {
  259.     int16 c = (int16) ((put_buffer >> 16) & 0xFF);
  260.     
  261.     emit_byte(entropy, c);
  262.     if (c == 0xFF) {        /* need to stuff a zero byte? */
  263.       emit_byte(entropy, 0);
  264.     }
  265.     put_buffer <<= 8;
  266.     put_bits -= 8;
  267.   }
  268.  
  269.   entropy->put_buffer = put_buffer; /* update variables */
  270.   entropy->put_bits = put_bits;
  271. }
  272.  
  273.  
  274. LOCAL void
  275. flush_bits (phuff_entropy_ptr entropy)
  276. {
  277.   emit_bits(entropy, 0x7F, 7); /* fill any partial byte with ones */
  278.   entropy->put_buffer = 0;     /* and reset bit-buffer to empty */
  279.   entropy->put_bits = 0;
  280. }
  281.  
  282.  
  283. /*
  284.  * Emit (or just count) a Huffman symbol.
  285.  */
  286.  
  287. INLINE
  288. LOCAL void
  289. emit_symbol (phuff_entropy_ptr entropy, int16 tbl_no, int16 symbol)
  290. {
  291.   if (entropy->gather_statistics)
  292.     entropy->count_ptrs[tbl_no][symbol]++;
  293.   else {
  294.     c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  295.     emit_bits(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  296.   }
  297. }
  298.  
  299.  
  300. /*
  301.  * Emit bits from a correction bit buffer.
  302.  */
  303.  
  304. LOCAL void
  305. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  306.             uint16 nbits)
  307. {
  308.   if (entropy->gather_statistics)
  309.     return;            /* no real work */
  310.  
  311.   while (nbits > 0) {
  312.     emit_bits(entropy, (uint16) (*bufstart), 1);
  313.     bufstart++;
  314.     nbits--;
  315.   }
  316. }
  317.  
  318.  
  319. /*
  320.  * Emit any pending EOBRUN symbol.
  321.  */
  322.  
  323. LOCAL void
  324. emit_eobrun (phuff_entropy_ptr entropy)
  325. {
  326.   register int16 temp, nbits;
  327.  
  328.   if (entropy->EOBRUN > 0) {    /* if there is any pending EOBRUN */
  329.     temp = entropy->EOBRUN;
  330.     nbits = 0;
  331.     while ((temp >>= 1))
  332.       nbits++;
  333.  
  334.     emit_symbol(entropy, (int16)entropy->ac_tbl_no, (int16)(nbits << 4));
  335.     if (nbits)
  336.       emit_bits(entropy, entropy->EOBRUN, nbits);
  337.  
  338.     entropy->EOBRUN = 0;
  339.  
  340.     /* Emit any buffered correction bits */
  341.     emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  342.     entropy->BE = 0;
  343.   }
  344. }
  345.  
  346.  
  347. /*
  348.  * Emit a restart marker & resynchronize predictions.
  349.  */
  350.  
  351. LOCAL void
  352. emit_restart (phuff_entropy_ptr entropy, int16 restart_num)
  353. {
  354.   int16 ci;
  355.  
  356.   emit_eobrun(entropy);
  357.  
  358.   if (! entropy->gather_statistics) {
  359.     flush_bits(entropy);
  360.     emit_byte(entropy, 0xFF);
  361.     emit_byte(entropy, JPEG_RST0 + restart_num);
  362.   }
  363.  
  364.   if (entropy->cinfo->Ss == 0) {
  365.     /* Re-initialize DC predictions to 0 */
  366.     for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  367.       entropy->last_dc_val[ci] = 0;
  368.   } else {
  369.     /* Re-initialize all AC-related fields to 0 */
  370.     entropy->EOBRUN = 0;
  371.     entropy->BE = 0;
  372.   }
  373. }
  374.  
  375.  
  376. /*
  377.  * MCU encoding for DC initial scan (either spectral selection,
  378.  * or first pass of successive approximation).
  379.  */
  380.  
  381. METHODDEF boolean
  382. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  383. {
  384.   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  385.   register int16 temp, temp2;
  386.   register int16 nbits;
  387.   int16 blkn, ci;
  388.   int16 Al = cinfo->Al;
  389.   JBLOCKROW block;
  390.   jpeg_component_info * compptr;
  391.   ISHIFT_TEMPS
  392.  
  393.   entropy->next_output_byte = cinfo->dest->next_output_byte;
  394.   entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  395.  
  396.   /* Emit restart marker if needed */
  397.   if (cinfo->restart_interval)
  398.     if (entropy->restarts_to_go == 0)
  399.       emit_restart(entropy, entropy->next_restart_num);
  400.  
  401.   /* Encode the MCU data blocks */
  402.   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  403.     block = MCU_data[blkn];
  404.     ci = cinfo->MCU_membership[blkn];
  405.     compptr = cinfo->cur_comp_info[ci];
  406.  
  407.     /* Compute the DC value after the required point transform by Al.
  408.      * This is simply an arithmetic right shift.
  409.      */
  410.     temp2 = IRIGHT_SHIFT((int16) ((*block)[0]), Al);
  411.  
  412.     /* DC differences are figured on the point-transformed values. */
  413.     temp = temp2 - entropy->last_dc_val[ci];
  414.     entropy->last_dc_val[ci] = temp2;
  415.  
  416.     /* Encode the DC coefficient difference per section G.1.2.1 */
  417.     temp2 = temp;
  418.     if (temp < 0) {
  419.       temp = -temp;        /* temp is abs value of input */
  420.       /* For a negative input, want temp2 = bitwise complement of abs(input) */
  421.       /* This code assumes we are on a two's complement machine */
  422.       temp2--;
  423.     }
  424.     
  425.     /* Find the number of bits needed for the magnitude of the coefficient */
  426.     nbits = 0;
  427.     while (temp) {
  428.       nbits++;
  429.       temp >>= 1;
  430.     }
  431.     
  432.     /* Count/emit the Huffman-coded symbol for the number of bits */
  433.     emit_symbol(entropy, (int16)compptr->dc_tbl_no, (int16)nbits);
  434.     
  435.     /* Emit that number of bits of the value, if positive, */
  436.     /* or the complement of its magnitude, if negative. */
  437.     if (nbits)            /* emit_bits rejects calls with size 0 */
  438.       emit_bits(entropy, (uint16) temp2, nbits);
  439.   }
  440.  
  441.   cinfo->dest->next_output_byte = entropy->next_output_byte;
  442.   cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  443.  
  444.   /* Update restart-interval state too */
  445.   if (cinfo->restart_interval) {
  446.     if (entropy->restarts_to_go == 0) {
  447.       entropy->restarts_to_go = cinfo->restart_interval;
  448.       entropy->next_restart_num++;
  449.       entropy->next_restart_num &= 7;
  450.     }
  451.     entropy->restarts_to_go--;
  452.   }
  453.  
  454.   return TRUE;
  455. }
  456.  
  457.  
  458. /*
  459.  * MCU encoding for AC initial scan (either spectral selection,
  460.  * or first pass of successive approximation).
  461.  */
  462.  
  463. METHODDEF boolean
  464. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  465. {
  466.   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  467.   register int16 temp, temp2;
  468.   register int16 nbits;
  469.   register int16 r, k;
  470.   int16 Se = cinfo->Se;
  471.   int16 Al = cinfo->Al;
  472.   JBLOCKROW block;
  473.  
  474.   entropy->next_output_byte = cinfo->dest->next_output_byte;
  475.   entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  476.  
  477.   /* Emit restart marker if needed */
  478.   if (cinfo->restart_interval)
  479.     if (entropy->restarts_to_go == 0)
  480.       emit_restart(entropy, entropy->next_restart_num);
  481.  
  482.   /* Encode the MCU data block */
  483.   block = MCU_data[0];
  484.  
  485.   /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  486.   
  487.   r = 0;            /* r = run length of zeros */
  488.    
  489.   for (k = cinfo->Ss; k <= Se; k++) {
  490.     if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  491.       r++;
  492.       continue;
  493.     }
  494.     /* We must apply the point transform by Al.  For AC coefficients this
  495.      * is an integer division with rounding towards 0.  To do this portably
  496.      * in C, we shift after obtaining the absolute value; so the code is
  497.      * interwoven with finding the abs value (temp) and output bits (temp2).
  498.      */
  499.     if (temp < 0) {
  500.       temp = -temp;        /* temp is abs value of input */
  501.       temp >>= Al;        /* apply the point transform */
  502.       /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  503.       temp2 = ~temp;
  504.     } else {
  505.       temp >>= Al;        /* apply the point transform */
  506.       temp2 = temp;
  507.     }
  508.     /* Watch out for case that nonzero coef is zero after point transform */
  509.     if (temp == 0) {
  510.       r++;
  511.       continue;
  512.     }
  513.  
  514.     /* Emit any pending EOBRUN */
  515.     if (entropy->EOBRUN > 0)
  516.       emit_eobrun(entropy);
  517.     /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  518.     while (r > 15) {
  519.       emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  520.       r -= 16;
  521.     }
  522.  
  523.     /* Find the number of bits needed for the magnitude of the coefficient */
  524.     nbits = 1;            /* there must be at least one 1 bit */
  525.     while ((temp >>= 1))
  526.       nbits++;
  527.  
  528.     /* Count/emit Huffman symbol for run length / number of bits */
  529.     emit_symbol(entropy, (int16)entropy->ac_tbl_no, (int16)((r << 4) + nbits));
  530.  
  531.     /* Emit that number of bits of the value, if positive, */
  532.     /* or the complement of its magnitude, if negative. */
  533.     emit_bits(entropy, (uint16) temp2, nbits);
  534.  
  535.     r = 0;            /* reset zero run length */
  536.   }
  537.  
  538.   if (r > 0) {            /* If there are trailing zeroes, */
  539.     entropy->EOBRUN++;        /* count an EOB */
  540.     if (entropy->EOBRUN == 0x7FFF)
  541.       emit_eobrun(entropy);    /* force it out to avoid overflow */
  542.   }
  543.  
  544.   cinfo->dest->next_output_byte = entropy->next_output_byte;
  545.   cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  546.  
  547.   /* Update restart-interval state too */
  548.   if (cinfo->restart_interval) {
  549.     if (entropy->restarts_to_go == 0) {
  550.       entropy->restarts_to_go = cinfo->restart_interval;
  551.       entropy->next_restart_num++;
  552.       entropy->next_restart_num &= 7;
  553.     }
  554.     entropy->restarts_to_go--;
  555.   }
  556.  
  557.   return TRUE;
  558. }
  559.  
  560.  
  561. /*
  562.  * MCU encoding for DC successive approximation refinement scan.
  563.  * Note: we assume such scans can be multi-component, although the spec
  564.  * is not very clear on the point.
  565.  */
  566.  
  567. METHODDEF boolean
  568. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  569. {
  570.   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  571.   register int16 temp;
  572.   int16 blkn;
  573.   int16 Al = cinfo->Al;
  574.   JBLOCKROW block;
  575.  
  576.   entropy->next_output_byte = cinfo->dest->next_output_byte;
  577.   entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  578.  
  579.   /* Emit restart marker if needed */
  580.   if (cinfo->restart_interval)
  581.     if (entropy->restarts_to_go == 0)
  582.       emit_restart(entropy, entropy->next_restart_num);
  583.  
  584.   /* Encode the MCU data blocks */
  585.   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  586.     block = MCU_data[blkn];
  587.  
  588.     /* We simply emit the Al'th bit of the DC coefficient value. */
  589.     temp = (*block)[0];
  590.     emit_bits(entropy, (uint16) (temp >> Al), 1);
  591.   }
  592.  
  593.   cinfo->dest->next_output_byte = entropy->next_output_byte;
  594.   cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  595.  
  596.   /* Update restart-interval state too */
  597.   if (cinfo->restart_interval) {
  598.     if (entropy->restarts_to_go == 0) {
  599.       entropy->restarts_to_go = cinfo->restart_interval;
  600.       entropy->next_restart_num++;
  601.       entropy->next_restart_num &= 7;
  602.     }
  603.     entropy->restarts_to_go--;
  604.   }
  605.  
  606.   return TRUE;
  607. }
  608.  
  609.  
  610. /*
  611.  * MCU encoding for AC successive approximation refinement scan.
  612.  */
  613.  
  614. METHODDEF boolean
  615. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  616. {
  617.   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  618.   register int16 temp;
  619.   register int16 r, k;
  620.   int16 EOB;
  621.   char *BR_buffer;
  622.   uint16 BR;
  623.   int16 Se = cinfo->Se;
  624.   int16 Al = cinfo->Al;
  625.   JBLOCKROW block;
  626.   int16 absvalues[DCTSIZE2];
  627.  
  628.   entropy->next_output_byte = cinfo->dest->next_output_byte;
  629.   entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  630.  
  631.   /* Emit restart marker if needed */
  632.   if (cinfo->restart_interval)
  633.     if (entropy->restarts_to_go == 0)
  634.       emit_restart(entropy, entropy->next_restart_num);
  635.  
  636.   /* Encode the MCU data block */
  637.   block = MCU_data[0];
  638.  
  639.   /* It is convenient to make a pre-pass to determine the transformed
  640.    * coefficients' absolute values and the EOB position.
  641.    */
  642.   EOB = 0;
  643.   for (k = cinfo->Ss; k <= Se; k++) {
  644.     temp = (*block)[jpeg_natural_order[k]];
  645.     /* We must apply the point transform by Al.  For AC coefficients this
  646.      * is an integer division with rounding towards 0.  To do this portably
  647.      * in C, we shift after obtaining the absolute value.
  648.      */
  649.     if (temp < 0)
  650.       temp = -temp;        /* temp is abs value of input */
  651.     temp >>= Al;        /* apply the point transform */
  652.     absvalues[k] = temp;    /* save abs value for main pass */
  653.     if (temp == 1)
  654.       EOB = k;            /* EOB = index of last newly-nonzero coef */
  655.   }
  656.  
  657.   /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  658.   
  659.   r = 0;            /* r = run length of zeros */
  660.   BR = 0;            /* BR = count of buffered bits added now */
  661.   BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  662.  
  663.   for (k = cinfo->Ss; k <= Se; k++) {
  664.     if ((temp = absvalues[k]) == 0) {
  665.       r++;
  666.       continue;
  667.     }
  668.  
  669.     /* Emit any required ZRLs, but not if they can be folded into EOB */
  670.     while (r > 15 && k <= EOB) {
  671.       /* emit any pending EOBRUN and the BE correction bits */
  672.       emit_eobrun(entropy);
  673.       /* Emit ZRL */
  674.       emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  675.       r -= 16;
  676.       /* Emit buffered correction bits that must be associated with ZRL */
  677.       emit_buffered_bits(entropy, BR_buffer, BR);
  678.       BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  679.       BR = 0;
  680.     }
  681.  
  682.     /* If the coef was previously nonzero, it only needs a correction bit.
  683.      * NOTE: a straight translation of the spec's figure G.7 would suggest
  684.      * that we also need to test r > 15.  But if r > 15, we can only get here
  685.      * if k > EOB, which implies that this coefficient is not 1.
  686.      */
  687.     if (temp > 1) {
  688.       /* The correction bit is the next bit of the absolute value. */
  689.       BR_buffer[BR++] = (char) (temp & 1);
  690.       continue;
  691.     }
  692.  
  693.     /* Emit any pending EOBRUN and the BE correction bits */
  694.     emit_eobrun(entropy);
  695.  
  696.     /* Count/emit Huffman symbol for run length / number of bits */
  697.     emit_symbol(entropy, (int16)entropy->ac_tbl_no, (int16)((r << 4) + 1));
  698.  
  699.     /* Emit output bit for newly-nonzero coef */
  700.     temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  701.     emit_bits(entropy, (uint16) temp, 1);
  702.  
  703.     /* Emit buffered correction bits that must be associated with this code */
  704.     emit_buffered_bits(entropy, BR_buffer, BR);
  705.     BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  706.     BR = 0;
  707.     r = 0;            /* reset zero run length */
  708.   }
  709.  
  710.   if (r > 0 || BR > 0) {    /* If there are trailing zeroes, */
  711.     entropy->EOBRUN++;        /* count an EOB */
  712.     entropy->BE += BR;        /* concat my correction bits to older ones */
  713.     /* We force out the EOB if we risk either:
  714.      * 1. overflow of the EOB counter;
  715.      * 2. overflow of the correction bit buffer during the next MCU.
  716.      */
  717.     if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  718.       emit_eobrun(entropy);
  719.   }
  720.  
  721.   cinfo->dest->next_output_byte = entropy->next_output_byte;
  722.   cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  723.  
  724.   /* Update restart-interval state too */
  725.   if (cinfo->restart_interval) {
  726.     if (entropy->restarts_to_go == 0) {
  727.       entropy->restarts_to_go = cinfo->restart_interval;
  728.       entropy->next_restart_num++;
  729.       entropy->next_restart_num &= 7;
  730.     }
  731.     entropy->restarts_to_go--;
  732.   }
  733.  
  734.   return TRUE;
  735. }
  736.  
  737.  
  738. /*
  739.  * Finish up at the end of a Huffman-compressed progressive scan.
  740.  */
  741.  
  742. METHODDEF void
  743. finish_pass_phuff (j_compress_ptr cinfo)
  744. {   
  745.   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  746.  
  747.   entropy->next_output_byte = cinfo->dest->next_output_byte;
  748.   entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  749.  
  750.   /* Flush out any buffered data */
  751.   emit_eobrun(entropy);
  752.   flush_bits(entropy);
  753.  
  754.   cinfo->dest->next_output_byte = entropy->next_output_byte;
  755.   cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  756. }
  757.  
  758.  
  759. /*
  760.  * Finish up a statistics-gathering pass and create the new Huffman tables.
  761.  */
  762.  
  763. METHODDEF void
  764. finish_pass_gather_phuff (j_compress_ptr cinfo)
  765. {
  766.   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  767.   boolean is_DC_band;
  768.   int16 ci, tbl;
  769.   jpeg_component_info * compptr;
  770.   JHUFF_TBL **htblptr;
  771.   boolean did[NUM_HUFF_TBLS];
  772.  
  773.   /* Flush out buffered data (all we care about is counting the EOB symbol) */
  774.   emit_eobrun(entropy);
  775.  
  776.   is_DC_band = (cinfo->Ss == 0);
  777.  
  778.   /* It's important not to apply jpeg_gen_optimal_table more than once
  779.    * per table, because it clobbers the input frequency counts!
  780.    */
  781.   MEMZERO(did, SIZEOF(did));
  782.  
  783.   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  784.     compptr = cinfo->cur_comp_info[ci];
  785.     if (is_DC_band) {
  786.       if (cinfo->Ah != 0)    /* DC refinement needs no table */
  787.     continue;
  788.       tbl = compptr->dc_tbl_no;
  789.     } else {
  790.       tbl = compptr->ac_tbl_no;
  791.     }
  792.     if (! did[tbl]) {
  793.       if (is_DC_band)
  794.         htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  795.       else
  796.         htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  797.       if (*htblptr == NULL)
  798.         *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  799.       jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  800.       did[tbl] = TRUE;
  801.     }
  802.   }
  803. }
  804.  
  805.  
  806. /*
  807.  * Module initialization routine for progressive Huffman entropy encoding.
  808.  */
  809.  
  810. GLOBAL void
  811. jinit_phuff_encoder (j_compress_ptr cinfo)
  812. {
  813.   phuff_entropy_ptr entropy;
  814.   int16 i;
  815.  
  816.   entropy = (phuff_entropy_ptr)
  817.     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  818.                 SIZEOF(phuff_entropy_encoder));
  819.   cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  820.   entropy->pub.start_pass = start_pass_phuff;
  821.  
  822.   /* Mark tables unallocated */
  823.   for (i = 0; i < NUM_HUFF_TBLS; i++) {
  824.     entropy->derived_tbls[i] = NULL;
  825.     entropy->count_ptrs[i] = NULL;
  826.   }
  827.   entropy->bit_buffer = NULL;    /* needed only in AC refinement scan */
  828. }
  829.  
  830. #endif /* C_PROGRESSIVE_SUPPORTED */
  831.