home *** CD-ROM | disk | FTP | other *** search
/ Windows Graphics Programming / Feng_Yuan_Win32_GDI_DirectX.iso / Samples / include / jlib / jcphuff.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-16  |  25.6 KB  |  821 lines

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