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