1 /*
2 * jchuff.c
3 *
4 * Copyright (C) 1991-1997, Thomas G. Lane.
5 * Modified 2006-2009 by Guido Vollbeding.
6 * This file is part of the Independent JPEG Group's software.
7 * For conditions of distribution and use, see the accompanying README file.
8 *
9 * This file contains Huffman entropy encoding routines.
10 * Both sequential and progressive modes are supported in this single module.
11 *
12 * Much of the complexity here has to do with supporting output suspension.
13 * If the data destination module demands suspension, we want to be able to
14 * back up to the start of the current MCU. To do this, we copy state
15 * variables into local working storage, and update them back to the
16 * permanent JPEG objects only upon successful completion of an MCU.
17 *
18 * We do not support output suspension for the progressive JPEG mode, since
19 * the library currently does not allow multiple-scan files to be written
20 * with output suspension.
21 */
22
23 #define JPEG_INTERNALS
24 #include "jinclude.h"
25 #include "jpeglib.h"
70 #define ASSIGN_STATE(dest,src) \
71 ((dest).put_buffer = (src).put_buffer, \
72 (dest).put_bits = (src).put_bits, \
73 (dest).last_dc_val[0] = (src).last_dc_val[0], \
74 (dest).last_dc_val[1] = (src).last_dc_val[1], \
75 (dest).last_dc_val[2] = (src).last_dc_val[2], \
76 (dest).last_dc_val[3] = (src).last_dc_val[3])
77 #endif
78 #endif
79
80
81 typedef struct {
82 struct jpeg_entropy_encoder pub; /* public fields */
83
84 savable_state saved; /* Bit buffer & DC state at start of MCU */
85
86 /* These fields are NOT loaded into local working state. */
87 unsigned int restarts_to_go; /* MCUs left in this restart interval */
88 int next_restart_num; /* next restart number to write (0-7) */
89
90 /* Following four fields used only in sequential mode */
91
92 /* Pointers to derived tables (these workspaces have image lifespan) */
93 c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
94 c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
95
96 /* Statistics tables for optimization */
97 long * dc_count_ptrs[NUM_HUFF_TBLS];
98 long * ac_count_ptrs[NUM_HUFF_TBLS];
99
100 /* Following fields used only in progressive mode */
101
102 /* Mode flag: TRUE for optimization, FALSE for actual data output */
103 boolean gather_statistics;
104
105 /* next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
106 */
107 JOCTET * next_output_byte; /* => next byte to write in buffer */
108 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
109 j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
110
111 /* Coding status for AC components */
112 int ac_tbl_no; /* the table number of the single component */
113 unsigned int EOBRUN; /* run length of EOBs */
114 unsigned int BE; /* # of buffered correction bits before MCU */
115 char * bit_buffer; /* buffer for correction bits (1 per char) */
116 /* packing correction bits tightly would save some space but cost time... */
117
118 /* Pointers to derived tables (these workspaces have image lifespan).
119 * Since any one scan in progressive mode codes only DC or only AC,
120 * we only need one set of tables, not one for DC and one for AC.
121 */
122 c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
123
124 /* Statistics tables for optimization; again, one set is enough */
125 long * count_ptrs[NUM_HUFF_TBLS];
126 } huff_entropy_encoder;
127
128 typedef huff_entropy_encoder * huff_entropy_ptr;
129
130 /* Working state while writing an MCU (sequential mode).
131 * This struct contains all the fields that are needed by subroutines.
132 */
133
134 typedef struct {
135 JOCTET * next_output_byte; /* => next byte to write in buffer */
136 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
137 savable_state cur; /* Current bit buffer & DC state */
138 j_compress_ptr cinfo; /* dump_buffer needs access to this */
139 } working_state;
140
141 /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
142 * buffer can hold. Larger sizes may slightly improve compression, but
143 * 1000 is already well into the realm of overkill.
144 * The minimum safe size is 64 bits.
145 */
162 #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
163 #endif
164
165
166 /*
167 * Compute the derived values for a Huffman table.
168 * This routine also performs some validation checks on the table.
169 */
170
171 LOCAL(void)
172 jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
173 c_derived_tbl ** pdtbl)
174 {
175 JHUFF_TBL *htbl;
176 c_derived_tbl *dtbl;
177 int p, i, l, lastp, si, maxsymbol;
178 char huffsize[257];
179 unsigned int huffcode[257];
180 unsigned int code;
181
182 MEMZERO(huffsize, SIZEOF(huffsize));
183 MEMZERO(huffcode, SIZEOF(huffcode));
184
185 /* Note that huffsize[] and huffcode[] are filled in code-length order,
186 * paralleling the order of the symbols themselves in htbl->huffval[].
187 */
188
189 /* Find the input Huffman table */
190 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
191 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
192 htbl =
193 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
194 if (htbl == NULL)
195 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
196
197 /* Allocate a workspace if we haven't already done so. */
198 if (*pdtbl == NULL)
199 *pdtbl = (c_derived_tbl *)
200 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
201 SIZEOF(c_derived_tbl));
202 dtbl = *pdtbl;
203
204 /* Figure C.1: make table of Huffman code length for each symbol */
305 /* After a successful buffer dump, must reset buffer pointers */
306 entropy->next_output_byte = dest->next_output_byte;
307 entropy->free_in_buffer = dest->free_in_buffer;
308 }
309
310
311 /* Outputting bits to the file */
312
313 /* Only the right 24 bits of put_buffer are used; the valid bits are
314 * left-justified in this part. At most 16 bits can be passed to emit_bits
315 * in one call, and we never retain more than 7 bits in put_buffer
316 * between calls, so 24 bits are sufficient.
317 */
318
319 INLINE
320 LOCAL(boolean)
321 emit_bits_s (working_state * state, unsigned int code, int size)
322 /* Emit some bits; return TRUE if successful, FALSE if must suspend */
323 {
324 /* This routine is heavily used, so it's worth coding tightly. */
325 register INT32 put_buffer = (INT32) code;
326 register int put_bits = state->cur.put_bits;
327
328 /* if size is 0, caller used an invalid Huffman table entry */
329 if (size == 0)
330 ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
331
332 put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
333
334 put_bits += size; /* new number of bits in buffer */
335
336 put_buffer <<= 24 - put_bits; /* align incoming bits */
337
338 put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
339
340 while (put_bits >= 8) {
341 int c = (int) ((put_buffer >> 16) & 0xFF);
342
343 emit_byte_s(state, c, return FALSE);
344 if (c == 0xFF) { /* need to stuff a zero byte? */
345 emit_byte_s(state, 0, return FALSE);
346 }
347 put_buffer <<= 8;
348 put_bits -= 8;
349 }
350
351 state->cur.put_buffer = put_buffer; /* update state variables */
352 state->cur.put_bits = put_bits;
353
354 return TRUE;
355 }
356
357
358 INLINE
359 LOCAL(void)
360 emit_bits_e (huff_entropy_ptr entropy, unsigned int code, int size)
361 /* Emit some bits, unless we are in gather mode */
362 {
363 /* This routine is heavily used, so it's worth coding tightly. */
364 register INT32 put_buffer = (INT32) code;
365 register int put_bits = entropy->saved.put_bits;
366
367 /* if size is 0, caller used an invalid Huffman table entry */
368 if (size == 0)
369 ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
370
371 if (entropy->gather_statistics)
372 return; /* do nothing if we're only getting stats */
373
374 put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
375
376 put_bits += size; /* new number of bits in buffer */
377
378 put_buffer <<= 24 - put_bits; /* align incoming bits */
379
380 /* and merge with old buffer contents */
381 put_buffer |= entropy->saved.put_buffer;
382
383 while (put_bits >= 8) {
384 int c = (int) ((put_buffer >> 16) & 0xFF);
385
386 emit_byte_e(entropy, c);
387 if (c == 0xFF) { /* need to stuff a zero byte? */
388 emit_byte_e(entropy, 0);
389 }
390 put_buffer <<= 8;
391 put_bits -= 8;
392 }
393
394 entropy->saved.put_buffer = put_buffer; /* update variables */
395 entropy->saved.put_bits = put_bits;
396 }
405 state->cur.put_bits = 0;
406 return TRUE;
407 }
408
409
410 LOCAL(void)
411 flush_bits_e (huff_entropy_ptr entropy)
412 {
413 emit_bits_e(entropy, 0x7F, 7); /* fill any partial byte with ones */
414 entropy->saved.put_buffer = 0; /* and reset bit-buffer to empty */
415 entropy->saved.put_bits = 0;
416 }
417
418
419 /*
420 * Emit (or just count) a Huffman symbol.
421 */
422
423 INLINE
424 LOCAL(void)
425 emit_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
426 {
427 if (entropy->gather_statistics)
428 entropy->count_ptrs[tbl_no][symbol]++;
429 else {
430 c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
431 emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
432 }
433 }
434
435
436 /*
437 * Emit bits from a correction bit buffer.
438 */
439
440 LOCAL(void)
441 emit_buffered_bits (huff_entropy_ptr entropy, char * bufstart,
442 unsigned int nbits)
443 {
444 if (entropy->gather_statistics)
445 return; /* no real work */
446
447 while (nbits > 0) {
448 emit_bits_e(entropy, (unsigned int) (*bufstart), 1);
449 bufstart++;
450 nbits--;
453
454
455 /*
456 * Emit any pending EOBRUN symbol.
457 */
458
459 LOCAL(void)
460 emit_eobrun (huff_entropy_ptr entropy)
461 {
462 register int temp, nbits;
463
464 if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
465 temp = entropy->EOBRUN;
466 nbits = 0;
467 while ((temp >>= 1))
468 nbits++;
469 /* safety check: shouldn't happen given limited correction-bit buffer */
470 if (nbits > 14)
471 ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
472
473 emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
474 if (nbits)
475 emit_bits_e(entropy, entropy->EOBRUN, nbits);
476
477 entropy->EOBRUN = 0;
478
479 /* Emit any buffered correction bits */
480 emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
481 entropy->BE = 0;
482 }
483 }
484
485
486 /*
487 * Emit a restart marker & resynchronize predictions.
488 */
489
490 LOCAL(boolean)
491 emit_restart_s (working_state * state, int restart_num)
492 {
493 int ci;
527 entropy->saved.last_dc_val[ci] = 0;
528 } else {
529 /* Re-initialize all AC-related fields to 0 */
530 entropy->EOBRUN = 0;
531 entropy->BE = 0;
532 }
533 }
534
535
536 /*
537 * MCU encoding for DC initial scan (either spectral selection,
538 * or first pass of successive approximation).
539 */
540
541 METHODDEF(boolean)
542 encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
543 {
544 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
545 register int temp, temp2;
546 register int nbits;
547 int blkn, ci;
548 int Al = cinfo->Al;
549 JBLOCKROW block;
550 jpeg_component_info * compptr;
551 ISHIFT_TEMPS
552
553 entropy->next_output_byte = cinfo->dest->next_output_byte;
554 entropy->free_in_buffer = cinfo->dest->free_in_buffer;
555
556 /* Emit restart marker if needed */
557 if (cinfo->restart_interval)
558 if (entropy->restarts_to_go == 0)
559 emit_restart_e(entropy, entropy->next_restart_num);
560
561 /* Encode the MCU data blocks */
562 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
563 block = MCU_data[blkn];
564 ci = cinfo->MCU_membership[blkn];
565 compptr = cinfo->cur_comp_info[ci];
566
567 /* Compute the DC value after the required point transform by Al.
568 * This is simply an arithmetic right shift.
569 */
570 temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
571
572 /* DC differences are figured on the point-transformed values. */
573 temp = temp2 - entropy->saved.last_dc_val[ci];
574 entropy->saved.last_dc_val[ci] = temp2;
575
576 /* Encode the DC coefficient difference per section G.1.2.1 */
577 temp2 = temp;
578 if (temp < 0) {
579 temp = -temp; /* temp is abs value of input */
580 /* For a negative input, want temp2 = bitwise complement of abs(input) */
581 /* This code assumes we are on a two's complement machine */
582 temp2--;
583 }
584
585 /* Find the number of bits needed for the magnitude of the coefficient */
586 nbits = 0;
587 while (temp) {
588 nbits++;
589 temp >>= 1;
590 }
591 /* Check for out-of-range coefficient values.
592 * Since we're encoding a difference, the range limit is twice as much.
593 */
594 if (nbits > MAX_COEF_BITS+1)
595 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
596
597 /* Count/emit the Huffman-coded symbol for the number of bits */
598 emit_symbol(entropy, compptr->dc_tbl_no, nbits);
599
600 /* Emit that number of bits of the value, if positive, */
601 /* or the complement of its magnitude, if negative. */
602 if (nbits) /* emit_bits rejects calls with size 0 */
603 emit_bits_e(entropy, (unsigned int) temp2, nbits);
604 }
605
606 cinfo->dest->next_output_byte = entropy->next_output_byte;
607 cinfo->dest->free_in_buffer = entropy->free_in_buffer;
608
609 /* Update restart-interval state too */
610 if (cinfo->restart_interval) {
611 if (entropy->restarts_to_go == 0) {
612 entropy->restarts_to_go = cinfo->restart_interval;
613 entropy->next_restart_num++;
614 entropy->next_restart_num &= 7;
615 }
616 entropy->restarts_to_go--;
617 }
618
619 return TRUE;
620 }
621
622
623 /*
624 * MCU encoding for AC initial scan (either spectral selection,
625 * or first pass of successive approximation).
626 */
627
628 METHODDEF(boolean)
629 encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
630 {
631 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
632 register int temp, temp2;
633 register int nbits;
634 register int r, k;
635 int Se = cinfo->Se;
636 int Al = cinfo->Al;
637 JBLOCKROW block;
638
639 entropy->next_output_byte = cinfo->dest->next_output_byte;
640 entropy->free_in_buffer = cinfo->dest->free_in_buffer;
641
642 /* Emit restart marker if needed */
643 if (cinfo->restart_interval)
644 if (entropy->restarts_to_go == 0)
645 emit_restart_e(entropy, entropy->next_restart_num);
646
647 /* Encode the MCU data block */
648 block = MCU_data[0];
649
650 /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
651
652 r = 0; /* r = run length of zeros */
653
654 for (k = cinfo->Ss; k <= Se; k++) {
655 if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
656 r++;
657 continue;
658 }
659 /* We must apply the point transform by Al. For AC coefficients this
660 * is an integer division with rounding towards 0. To do this portably
661 * in C, we shift after obtaining the absolute value; so the code is
662 * interwoven with finding the abs value (temp) and output bits (temp2).
663 */
664 if (temp < 0) {
665 temp = -temp; /* temp is abs value of input */
666 temp >>= Al; /* apply the point transform */
667 /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
668 temp2 = ~temp;
669 } else {
670 temp >>= Al; /* apply the point transform */
671 temp2 = temp;
672 }
673 /* Watch out for case that nonzero coef is zero after point transform */
674 if (temp == 0) {
675 r++;
676 continue;
677 }
678
679 /* Emit any pending EOBRUN */
680 if (entropy->EOBRUN > 0)
681 emit_eobrun(entropy);
682 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
683 while (r > 15) {
684 emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
685 r -= 16;
686 }
687
688 /* Find the number of bits needed for the magnitude of the coefficient */
689 nbits = 1; /* there must be at least one 1 bit */
690 while ((temp >>= 1))
691 nbits++;
692 /* Check for out-of-range coefficient values */
693 if (nbits > MAX_COEF_BITS)
694 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
695
696 /* Count/emit Huffman symbol for run length / number of bits */
697 emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
698
699 /* Emit that number of bits of the value, if positive, */
700 /* or the complement of its magnitude, if negative. */
701 emit_bits_e(entropy, (unsigned int) temp2, nbits);
702
703 r = 0; /* reset zero run length */
704 }
705
706 if (r > 0) { /* If there are trailing zeroes, */
707 entropy->EOBRUN++; /* count an EOB */
708 if (entropy->EOBRUN == 0x7FFF)
709 emit_eobrun(entropy); /* force it out to avoid overflow */
710 }
711
712 cinfo->dest->next_output_byte = entropy->next_output_byte;
713 cinfo->dest->free_in_buffer = entropy->free_in_buffer;
714
715 /* Update restart-interval state too */
716 if (cinfo->restart_interval) {
717 if (entropy->restarts_to_go == 0) {
718 entropy->restarts_to_go = cinfo->restart_interval;
719 entropy->next_restart_num++;
720 entropy->next_restart_num &= 7;
721 }
722 entropy->restarts_to_go--;
723 }
724
725 return TRUE;
726 }
727
728
729 /*
730 * MCU encoding for DC successive approximation refinement scan.
731 * Note: we assume such scans can be multi-component, although the spec
732 * is not very clear on the point.
733 */
734
735 METHODDEF(boolean)
736 encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
737 {
738 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
739 register int temp;
740 int blkn;
741 int Al = cinfo->Al;
742 JBLOCKROW block;
743
744 entropy->next_output_byte = cinfo->dest->next_output_byte;
745 entropy->free_in_buffer = cinfo->dest->free_in_buffer;
746
747 /* Emit restart marker if needed */
748 if (cinfo->restart_interval)
749 if (entropy->restarts_to_go == 0)
750 emit_restart_e(entropy, entropy->next_restart_num);
751
752 /* Encode the MCU data blocks */
753 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
754 block = MCU_data[blkn];
755
756 /* We simply emit the Al'th bit of the DC coefficient value. */
757 temp = (*block)[0];
758 emit_bits_e(entropy, (unsigned int) (temp >> Al), 1);
759 }
760
761 cinfo->dest->next_output_byte = entropy->next_output_byte;
762 cinfo->dest->free_in_buffer = entropy->free_in_buffer;
763
764 /* Update restart-interval state too */
765 if (cinfo->restart_interval) {
766 if (entropy->restarts_to_go == 0) {
767 entropy->restarts_to_go = cinfo->restart_interval;
768 entropy->next_restart_num++;
769 entropy->next_restart_num &= 7;
770 }
771 entropy->restarts_to_go--;
772 }
773
774 return TRUE;
775 }
776
777
778 /*
779 * MCU encoding for AC successive approximation refinement scan.
780 */
781
782 METHODDEF(boolean)
783 encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
784 {
785 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
786 register int temp;
787 register int r, k;
788 int EOB;
789 char *BR_buffer;
790 unsigned int BR;
791 int Se = cinfo->Se;
792 int Al = cinfo->Al;
793 JBLOCKROW block;
794 int absvalues[DCTSIZE2];
795
796 MEMZERO(absvalues, SIZEOF(absvalues));
797
798 entropy->next_output_byte = cinfo->dest->next_output_byte;
799 entropy->free_in_buffer = cinfo->dest->free_in_buffer;
800
801 /* Emit restart marker if needed */
802 if (cinfo->restart_interval)
803 if (entropy->restarts_to_go == 0)
804 emit_restart_e(entropy, entropy->next_restart_num);
805
806 /* Encode the MCU data block */
807 block = MCU_data[0];
808
809 /* It is convenient to make a pre-pass to determine the transformed
810 * coefficients' absolute values and the EOB position.
811 */
812 EOB = 0;
813 for (k = cinfo->Ss; k <= Se; k++) {
814 temp = (*block)[jpeg_natural_order[k]];
815 /* We must apply the point transform by Al. For AC coefficients this
816 * is an integer division with rounding towards 0. To do this portably
817 * in C, we shift after obtaining the absolute value.
818 */
819 if (temp < 0)
820 temp = -temp; /* temp is abs value of input */
821 temp >>= Al; /* apply the point transform */
822 absvalues[k] = temp; /* save abs value for main pass */
823 if (temp == 1)
824 EOB = k; /* EOB = index of last newly-nonzero coef */
825 }
826
827 /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
828
829 r = 0; /* r = run length of zeros */
830 BR = 0; /* BR = count of buffered bits added now */
831 BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
832
833 for (k = cinfo->Ss; k <= Se; k++) {
834 if ((temp = absvalues[k]) == 0) {
835 r++;
836 continue;
837 }
838
839 /* Emit any required ZRLs, but not if they can be folded into EOB */
840 while (r > 15 && k <= EOB) {
841 /* emit any pending EOBRUN and the BE correction bits */
842 emit_eobrun(entropy);
843 /* Emit ZRL */
844 emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
845 r -= 16;
846 /* Emit buffered correction bits that must be associated with ZRL */
847 emit_buffered_bits(entropy, BR_buffer, BR);
848 BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
849 BR = 0;
850 }
851
852 /* If the coef was previously nonzero, it only needs a correction bit.
853 * NOTE: a straight translation of the spec's figure G.7 would suggest
854 * that we also need to test r > 15. But if r > 15, we can only get here
855 * if k > EOB, which implies that this coefficient is not 1.
856 */
857 if (temp > 1) {
858 /* The correction bit is the next bit of the absolute value. */
859 BR_buffer[BR++] = (char) (temp & 1);
860 continue;
861 }
862
863 /* Emit any pending EOBRUN and the BE correction bits */
864 emit_eobrun(entropy);
865
866 /* Count/emit Huffman symbol for run length / number of bits */
867 emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
868
869 /* Emit output bit for newly-nonzero coef */
870 temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
871 emit_bits_e(entropy, (unsigned int) temp, 1);
872
873 /* Emit buffered correction bits that must be associated with this code */
874 emit_buffered_bits(entropy, BR_buffer, BR);
875 BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
876 BR = 0;
877 r = 0; /* reset zero run length */
878 }
879
880 if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
881 entropy->EOBRUN++; /* count an EOB */
882 entropy->BE += BR; /* concat my correction bits to older ones */
883 /* We force out the EOB if we risk either:
884 * 1. overflow of the EOB counter;
885 * 2. overflow of the correction bit buffer during the next MCU.
886 */
887 if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
888 emit_eobrun(entropy);
889 }
890
896 if (entropy->restarts_to_go == 0) {
897 entropy->restarts_to_go = cinfo->restart_interval;
898 entropy->next_restart_num++;
899 entropy->next_restart_num &= 7;
900 }
901 entropy->restarts_to_go--;
902 }
903
904 return TRUE;
905 }
906
907
908 /* Encode a single block's worth of coefficients */
909
910 LOCAL(boolean)
911 encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
912 c_derived_tbl *dctbl, c_derived_tbl *actbl)
913 {
914 register int temp, temp2;
915 register int nbits;
916 register int k, r, i;
917
918 /* Encode the DC coefficient difference per section F.1.2.1 */
919
920 temp = temp2 = block[0] - last_dc_val;
921
922 if (temp < 0) {
923 temp = -temp; /* temp is abs value of input */
924 /* For a negative input, want temp2 = bitwise complement of abs(input) */
925 /* This code assumes we are on a two's complement machine */
926 temp2--;
927 }
928
929 /* Find the number of bits needed for the magnitude of the coefficient */
930 nbits = 0;
931 while (temp) {
932 nbits++;
933 temp >>= 1;
934 }
935 /* Check for out-of-range coefficient values.
936 * Since we're encoding a difference, the range limit is twice as much.
937 */
938 if (nbits > MAX_COEF_BITS+1)
939 ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
940
941 /* Emit the Huffman-coded symbol for the number of bits */
942 if (! emit_bits_s(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
943 return FALSE;
944
945 /* Emit that number of bits of the value, if positive, */
946 /* or the complement of its magnitude, if negative. */
947 if (nbits) /* emit_bits rejects calls with size 0 */
948 if (! emit_bits_s(state, (unsigned int) temp2, nbits))
949 return FALSE;
950
951 /* Encode the AC coefficients per section F.1.2.2 */
952
953 r = 0; /* r = run length of zeros */
954
955 for (k = 1; k < DCTSIZE2; k++) {
956 if ((temp = block[jpeg_natural_order[k]]) == 0) {
957 r++;
958 } else {
959 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
960 while (r > 15) {
961 if (! emit_bits_s(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
962 return FALSE;
963 r -= 16;
964 }
965
966 temp2 = temp;
967 if (temp < 0) {
968 temp = -temp; /* temp is abs value of input */
969 /* This code assumes we are on a two's complement machine */
970 temp2--;
971 }
972
973 /* Find the number of bits needed for the magnitude of the coefficient */
974 nbits = 1; /* there must be at least one 1 bit */
975 while ((temp >>= 1))
976 nbits++;
977 /* Check for out-of-range coefficient values */
978 if (nbits > MAX_COEF_BITS)
979 ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
980
981 /* Emit Huffman symbol for run length / number of bits */
982 i = (r << 4) + nbits;
983 if (! emit_bits_s(state, actbl->ehufco[i], actbl->ehufsi[i]))
984 return FALSE;
985
986 /* Emit that number of bits of the value, if positive, */
987 /* or the complement of its magnitude, if negative. */
988 if (! emit_bits_s(state, (unsigned int) temp2, nbits))
989 return FALSE;
990
991 r = 0;
992 }
993 }
994
995 /* If the last coef(s) were zero, emit an end-of-block code */
996 if (r > 0)
997 if (! emit_bits_s(state, actbl->ehufco[0], actbl->ehufsi[0]))
998 return FALSE;
999
1000 return TRUE;
1001 }
1002
1003
1100 /*
1101 * Huffman coding optimization.
1102 *
1103 * We first scan the supplied data and count the number of uses of each symbol
1104 * that is to be Huffman-coded. (This process MUST agree with the code above.)
1105 * Then we build a Huffman coding tree for the observed counts.
1106 * Symbols which are not needed at all for the particular image are not
1107 * assigned any code, which saves space in the DHT marker as well as in
1108 * the compressed data.
1109 */
1110
1111
1112 /* Process a single block's worth of coefficients */
1113
1114 LOCAL(void)
1115 htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
1116 long dc_counts[], long ac_counts[])
1117 {
1118 register int temp;
1119 register int nbits;
1120 register int k, r;
1121
1122 /* Encode the DC coefficient difference per section F.1.2.1 */
1123
1124 temp = block[0] - last_dc_val;
1125 if (temp < 0)
1126 temp = -temp;
1127
1128 /* Find the number of bits needed for the magnitude of the coefficient */
1129 nbits = 0;
1130 while (temp) {
1131 nbits++;
1132 temp >>= 1;
1133 }
1134 /* Check for out-of-range coefficient values.
1135 * Since we're encoding a difference, the range limit is twice as much.
1136 */
1137 if (nbits > MAX_COEF_BITS+1)
1138 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
1139
1140 /* Count the Huffman symbol for the number of bits */
1141 dc_counts[nbits]++;
1142
1143 /* Encode the AC coefficients per section F.1.2.2 */
1144
1145 r = 0; /* r = run length of zeros */
1146
1147 for (k = 1; k < DCTSIZE2; k++) {
1148 if ((temp = block[jpeg_natural_order[k]]) == 0) {
1149 r++;
1150 } else {
1151 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
1152 while (r > 15) {
1153 ac_counts[0xF0]++;
1154 r -= 16;
1155 }
1156
1157 /* Find the number of bits needed for the magnitude of the coefficient */
1158 if (temp < 0)
1159 temp = -temp;
1160
1161 /* Find the number of bits needed for the magnitude of the coefficient */
1162 nbits = 1; /* there must be at least one 1 bit */
1163 while ((temp >>= 1))
1164 nbits++;
1165 /* Check for out-of-range coefficient values */
1166 if (nbits > MAX_COEF_BITS)
1167 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
1168
1371 if (codesize[j] == i) {
1372 htbl->huffval[p] = (UINT8) j;
1373 p++;
1374 }
1375 }
1376 }
1377
1378 /* Set sent_table FALSE so updated table will be written to JPEG file. */
1379 htbl->sent_table = FALSE;
1380 }
1381
1382
1383 /*
1384 * Finish up a statistics-gathering pass and create the new Huffman tables.
1385 */
1386
1387 METHODDEF(void)
1388 finish_pass_gather (j_compress_ptr cinfo)
1389 {
1390 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1391 int ci, dctbl, actbl, tbl;
1392 jpeg_component_info * compptr;
1393 JHUFF_TBL **htblptr;
1394 boolean did_dc[NUM_HUFF_TBLS];
1395 boolean did_ac[NUM_HUFF_TBLS];
1396 boolean did[NUM_HUFF_TBLS];
1397
1398 /* It's important not to apply jpeg_gen_optimal_table more than once
1399 * per table, because it clobbers the input frequency counts!
1400 */
1401 if (cinfo->progressive_mode) {
1402 /* Flush out buffered data (all we care about is counting the EOB symbol) */
1403 emit_eobrun(entropy);
1404
1405 MEMZERO(did, SIZEOF(did));
1406
1407 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1408 compptr = cinfo->cur_comp_info[ci];
1409 if (cinfo->Ss == 0) {
1410 if (cinfo->Ah != 0) /* DC refinement needs no table */
1411 continue;
1412 tbl = compptr->dc_tbl_no;
1413 } else {
1414 tbl = compptr->ac_tbl_no;
1415 }
1416 if (! did[tbl]) {
1417 if (cinfo->Ss == 0)
1418 htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
1419 else
1420 htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
1421 if (*htblptr == NULL)
1422 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
1423 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
1424 did[tbl] = TRUE;
1425 }
1426 }
1427 } else {
1428 MEMZERO(did_dc, SIZEOF(did_dc));
1429 MEMZERO(did_ac, SIZEOF(did_ac));
1430
1431 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1432 compptr = cinfo->cur_comp_info[ci];
1433 dctbl = compptr->dc_tbl_no;
1434 actbl = compptr->ac_tbl_no;
1435 if (! did_dc[dctbl]) {
1436 htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
1437 if (*htblptr == NULL)
1438 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
1439 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
1440 did_dc[dctbl] = TRUE;
1441 }
1442 if (! did_ac[actbl]) {
1443 htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
1444 if (*htblptr == NULL)
1445 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
1446 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
1447 did_ac[actbl] = TRUE;
1448 }
1449 }
1450 }
1451 }
1452
1453
1454 /*
1455 * Initialize for a Huffman-compressed scan.
1456 * If gather_statistics is TRUE, we do not output anything during the scan,
1457 * just count the Huffman symbols used and generate Huffman code tables.
1458 */
1459
1460 METHODDEF(void)
1461 start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
1462 {
1463 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1464 int ci, dctbl, actbl, tbl;
1465 jpeg_component_info * compptr;
1466
1467 if (gather_statistics)
1468 entropy->pub.finish_pass = finish_pass_gather;
1469 else
1470 entropy->pub.finish_pass = finish_pass_huff;
1471
1472 if (cinfo->progressive_mode) {
1473 entropy->cinfo = cinfo;
1474 entropy->gather_statistics = gather_statistics;
1475
1476 /* We assume jcmaster.c already validated the scan parameters. */
1477
1478 /* Select execution routine */
1479 if (cinfo->Ah == 0) {
1480 if (cinfo->Ss == 0)
1481 entropy->pub.encode_mcu = encode_mcu_DC_first;
1482 else
1483 entropy->pub.encode_mcu = encode_mcu_AC_first;
1484 } else {
1485 if (cinfo->Ss == 0)
1486 entropy->pub.encode_mcu = encode_mcu_DC_refine;
1487 else {
1488 entropy->pub.encode_mcu = encode_mcu_AC_refine;
1489 /* AC refinement needs a correction bit buffer */
1490 if (entropy->bit_buffer == NULL)
1491 entropy->bit_buffer = (char *)
1492 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1493 MAX_CORR_BITS * SIZEOF(char));
1494 }
1495 }
1496
1497 /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
1498 * for AC coefficients.
1499 */
1500 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1501 compptr = cinfo->cur_comp_info[ci];
1502 /* Initialize DC predictions to 0 */
1503 entropy->saved.last_dc_val[ci] = 0;
1504 /* Get table index */
1505 if (cinfo->Ss == 0) {
1506 if (cinfo->Ah != 0) /* DC refinement needs no table */
1507 continue;
1508 tbl = compptr->dc_tbl_no;
1509 } else {
1510 entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
1511 }
1512 if (gather_statistics) {
1513 /* Check for invalid table index */
1514 /* (make_c_derived_tbl does this in the other path) */
1515 if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
1516 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
1517 /* Allocate and zero the statistics tables */
1518 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
1519 if (entropy->count_ptrs[tbl] == NULL)
1520 entropy->count_ptrs[tbl] = (long *)
1521 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1522 257 * SIZEOF(long));
1523 MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
1524 } else {
1525 /* Compute derived values for Huffman table */
1526 /* We may do this more than once for a table, but it's not expensive */
1527 jpeg_make_c_derived_tbl(cinfo, cinfo->Ss == 0, tbl,
1528 & entropy->derived_tbls[tbl]);
1529 }
1530 }
1531
1532 /* Initialize AC stuff */
1533 entropy->EOBRUN = 0;
1534 entropy->BE = 0;
1535 } else {
1536 if (gather_statistics)
1537 entropy->pub.encode_mcu = encode_mcu_gather;
1538 else
1539 entropy->pub.encode_mcu = encode_mcu_huff;
1540
1541 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1542 compptr = cinfo->cur_comp_info[ci];
1543 dctbl = compptr->dc_tbl_no;
1544 actbl = compptr->ac_tbl_no;
1545 if (gather_statistics) {
1546 /* Check for invalid table indexes */
1547 /* (make_c_derived_tbl does this in the other path) */
1548 if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
1549 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
1550 if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
1551 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
1552 /* Allocate and zero the statistics tables */
1553 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
1554 if (entropy->dc_count_ptrs[dctbl] == NULL)
1555 entropy->dc_count_ptrs[dctbl] = (long *)
1556 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1557 257 * SIZEOF(long));
1558 MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
1559 if (entropy->ac_count_ptrs[actbl] == NULL)
1560 entropy->ac_count_ptrs[actbl] = (long *)
1561 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1562 257 * SIZEOF(long));
1563 MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
1564 } else {
1565 /* Compute derived values for Huffman tables */
1566 /* We may do this more than once for a table, but it's not expensive */
1567 jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
1568 & entropy->dc_derived_tbls[dctbl]);
1569 jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
1570 & entropy->ac_derived_tbls[actbl]);
1571 }
1572 /* Initialize DC predictions to 0 */
1573 entropy->saved.last_dc_val[ci] = 0;
1574 }
1575 }
1576
1577 /* Initialize bit buffer to empty */
1578 entropy->saved.put_buffer = 0;
1579 entropy->saved.put_bits = 0;
1580
1581 /* Initialize restart stuff */
1582 entropy->restarts_to_go = cinfo->restart_interval;
1583 entropy->next_restart_num = 0;
1584 }
1585
1586
1587 /*
1588 * Module initialization routine for Huffman entropy encoding.
1589 */
1590
1591 GLOBAL(void)
1592 jinit_huff_encoder (j_compress_ptr cinfo)
1593 {
1594 huff_entropy_ptr entropy;
1595 int i;
1596
1597 entropy = (huff_entropy_ptr)
1598 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1599 SIZEOF(huff_entropy_encoder));
1600 cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
1601 entropy->pub.start_pass = start_pass_huff;
1602
1603 if (cinfo->progressive_mode) {
1604 /* Mark tables unallocated */
1605 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1606 entropy->derived_tbls[i] = NULL;
1607 entropy->count_ptrs[i] = NULL;
1608 }
1609 entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
1610 } else {
1611 /* Mark tables unallocated */
1612 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1613 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
1614 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
1615 }
1616 }
1617 }
|
1 /*
2 * jchuff.c
3 *
4 * Copyright (C) 1991-1997, Thomas G. Lane.
5 * Modified 2006-2013 by Guido Vollbeding.
6 * This file is part of the Independent JPEG Group's software.
7 * For conditions of distribution and use, see the accompanying README file.
8 *
9 * This file contains Huffman entropy encoding routines.
10 * Both sequential and progressive modes are supported in this single module.
11 *
12 * Much of the complexity here has to do with supporting output suspension.
13 * If the data destination module demands suspension, we want to be able to
14 * back up to the start of the current MCU. To do this, we copy state
15 * variables into local working storage, and update them back to the
16 * permanent JPEG objects only upon successful completion of an MCU.
17 *
18 * We do not support output suspension for the progressive JPEG mode, since
19 * the library currently does not allow multiple-scan files to be written
20 * with output suspension.
21 */
22
23 #define JPEG_INTERNALS
24 #include "jinclude.h"
25 #include "jpeglib.h"
70 #define ASSIGN_STATE(dest,src) \
71 ((dest).put_buffer = (src).put_buffer, \
72 (dest).put_bits = (src).put_bits, \
73 (dest).last_dc_val[0] = (src).last_dc_val[0], \
74 (dest).last_dc_val[1] = (src).last_dc_val[1], \
75 (dest).last_dc_val[2] = (src).last_dc_val[2], \
76 (dest).last_dc_val[3] = (src).last_dc_val[3])
77 #endif
78 #endif
79
80
81 typedef struct {
82 struct jpeg_entropy_encoder pub; /* public fields */
83
84 savable_state saved; /* Bit buffer & DC state at start of MCU */
85
86 /* These fields are NOT loaded into local working state. */
87 unsigned int restarts_to_go; /* MCUs left in this restart interval */
88 int next_restart_num; /* next restart number to write (0-7) */
89
90 /* Pointers to derived tables (these workspaces have image lifespan) */
91 c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
92 c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
93
94 /* Statistics tables for optimization */
95 long * dc_count_ptrs[NUM_HUFF_TBLS];
96 long * ac_count_ptrs[NUM_HUFF_TBLS];
97
98 /* Following fields used only in progressive mode */
99
100 /* Mode flag: TRUE for optimization, FALSE for actual data output */
101 boolean gather_statistics;
102
103 /* next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
104 */
105 JOCTET * next_output_byte; /* => next byte to write in buffer */
106 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
107 j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
108
109 /* Coding status for AC components */
110 int ac_tbl_no; /* the table number of the single component */
111 unsigned int EOBRUN; /* run length of EOBs */
112 unsigned int BE; /* # of buffered correction bits before MCU */
113 char * bit_buffer; /* buffer for correction bits (1 per char) */
114 /* packing correction bits tightly would save some space but cost time... */
115 } huff_entropy_encoder;
116
117 typedef huff_entropy_encoder * huff_entropy_ptr;
118
119 /* Working state while writing an MCU (sequential mode).
120 * This struct contains all the fields that are needed by subroutines.
121 */
122
123 typedef struct {
124 JOCTET * next_output_byte; /* => next byte to write in buffer */
125 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
126 savable_state cur; /* Current bit buffer & DC state */
127 j_compress_ptr cinfo; /* dump_buffer needs access to this */
128 } working_state;
129
130 /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
131 * buffer can hold. Larger sizes may slightly improve compression, but
132 * 1000 is already well into the realm of overkill.
133 * The minimum safe size is 64 bits.
134 */
151 #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
152 #endif
153
154
155 /*
156 * Compute the derived values for a Huffman table.
157 * This routine also performs some validation checks on the table.
158 */
159
160 LOCAL(void)
161 jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
162 c_derived_tbl ** pdtbl)
163 {
164 JHUFF_TBL *htbl;
165 c_derived_tbl *dtbl;
166 int p, i, l, lastp, si, maxsymbol;
167 char huffsize[257];
168 unsigned int huffcode[257];
169 unsigned int code;
170
171 /* Note that huffsize[] and huffcode[] are filled in code-length order,
172 * paralleling the order of the symbols themselves in htbl->huffval[].
173 */
174
175 /* Find the input Huffman table */
176 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
177 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
178 htbl =
179 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
180 if (htbl == NULL)
181 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
182
183 /* Allocate a workspace if we haven't already done so. */
184 if (*pdtbl == NULL)
185 *pdtbl = (c_derived_tbl *)
186 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
187 SIZEOF(c_derived_tbl));
188 dtbl = *pdtbl;
189
190 /* Figure C.1: make table of Huffman code length for each symbol */
291 /* After a successful buffer dump, must reset buffer pointers */
292 entropy->next_output_byte = dest->next_output_byte;
293 entropy->free_in_buffer = dest->free_in_buffer;
294 }
295
296
297 /* Outputting bits to the file */
298
299 /* Only the right 24 bits of put_buffer are used; the valid bits are
300 * left-justified in this part. At most 16 bits can be passed to emit_bits
301 * in one call, and we never retain more than 7 bits in put_buffer
302 * between calls, so 24 bits are sufficient.
303 */
304
305 INLINE
306 LOCAL(boolean)
307 emit_bits_s (working_state * state, unsigned int code, int size)
308 /* Emit some bits; return TRUE if successful, FALSE if must suspend */
309 {
310 /* This routine is heavily used, so it's worth coding tightly. */
311 register INT32 put_buffer;
312 register int put_bits;
313
314 /* if size is 0, caller used an invalid Huffman table entry */
315 if (size == 0)
316 ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
317
318 /* mask off any extra bits in code */
319 put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1);
320
321 /* new number of bits in buffer */
322 put_bits = size + state->cur.put_bits;
323
324 put_buffer <<= 24 - put_bits; /* align incoming bits */
325
326 /* and merge with old buffer contents */
327 put_buffer |= state->cur.put_buffer;
328
329 while (put_bits >= 8) {
330 int c = (int) ((put_buffer >> 16) & 0xFF);
331
332 emit_byte_s(state, c, return FALSE);
333 if (c == 0xFF) { /* need to stuff a zero byte? */
334 emit_byte_s(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 INLINE
348 LOCAL(void)
349 emit_bits_e (huff_entropy_ptr entropy, unsigned int code, int size)
350 /* Emit some bits, unless we are in gather mode */
351 {
352 /* This routine is heavily used, so it's worth coding tightly. */
353 register INT32 put_buffer;
354 register int put_bits;
355
356 /* if size is 0, caller used an invalid Huffman table entry */
357 if (size == 0)
358 ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
359
360 if (entropy->gather_statistics)
361 return; /* do nothing if we're only getting stats */
362
363 /* mask off any extra bits in code */
364 put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1);
365
366 /* new number of bits in buffer */
367 put_bits = size + entropy->saved.put_bits;
368
369 put_buffer <<= 24 - put_bits; /* align incoming bits */
370
371 /* and merge with old buffer contents */
372 put_buffer |= entropy->saved.put_buffer;
373
374 while (put_bits >= 8) {
375 int c = (int) ((put_buffer >> 16) & 0xFF);
376
377 emit_byte_e(entropy, c);
378 if (c == 0xFF) { /* need to stuff a zero byte? */
379 emit_byte_e(entropy, 0);
380 }
381 put_buffer <<= 8;
382 put_bits -= 8;
383 }
384
385 entropy->saved.put_buffer = put_buffer; /* update variables */
386 entropy->saved.put_bits = put_bits;
387 }
396 state->cur.put_bits = 0;
397 return TRUE;
398 }
399
400
401 LOCAL(void)
402 flush_bits_e (huff_entropy_ptr entropy)
403 {
404 emit_bits_e(entropy, 0x7F, 7); /* fill any partial byte with ones */
405 entropy->saved.put_buffer = 0; /* and reset bit-buffer to empty */
406 entropy->saved.put_bits = 0;
407 }
408
409
410 /*
411 * Emit (or just count) a Huffman symbol.
412 */
413
414 INLINE
415 LOCAL(void)
416 emit_dc_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
417 {
418 if (entropy->gather_statistics)
419 entropy->dc_count_ptrs[tbl_no][symbol]++;
420 else {
421 c_derived_tbl * tbl = entropy->dc_derived_tbls[tbl_no];
422 emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
423 }
424 }
425
426
427 INLINE
428 LOCAL(void)
429 emit_ac_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
430 {
431 if (entropy->gather_statistics)
432 entropy->ac_count_ptrs[tbl_no][symbol]++;
433 else {
434 c_derived_tbl * tbl = entropy->ac_derived_tbls[tbl_no];
435 emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
436 }
437 }
438
439
440 /*
441 * Emit bits from a correction bit buffer.
442 */
443
444 LOCAL(void)
445 emit_buffered_bits (huff_entropy_ptr entropy, char * bufstart,
446 unsigned int nbits)
447 {
448 if (entropy->gather_statistics)
449 return; /* no real work */
450
451 while (nbits > 0) {
452 emit_bits_e(entropy, (unsigned int) (*bufstart), 1);
453 bufstart++;
454 nbits--;
457
458
459 /*
460 * Emit any pending EOBRUN symbol.
461 */
462
463 LOCAL(void)
464 emit_eobrun (huff_entropy_ptr entropy)
465 {
466 register int temp, nbits;
467
468 if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
469 temp = entropy->EOBRUN;
470 nbits = 0;
471 while ((temp >>= 1))
472 nbits++;
473 /* safety check: shouldn't happen given limited correction-bit buffer */
474 if (nbits > 14)
475 ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
476
477 emit_ac_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
478 if (nbits)
479 emit_bits_e(entropy, entropy->EOBRUN, nbits);
480
481 entropy->EOBRUN = 0;
482
483 /* Emit any buffered correction bits */
484 emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
485 entropy->BE = 0;
486 }
487 }
488
489
490 /*
491 * Emit a restart marker & resynchronize predictions.
492 */
493
494 LOCAL(boolean)
495 emit_restart_s (working_state * state, int restart_num)
496 {
497 int ci;
531 entropy->saved.last_dc_val[ci] = 0;
532 } else {
533 /* Re-initialize all AC-related fields to 0 */
534 entropy->EOBRUN = 0;
535 entropy->BE = 0;
536 }
537 }
538
539
540 /*
541 * MCU encoding for DC initial scan (either spectral selection,
542 * or first pass of successive approximation).
543 */
544
545 METHODDEF(boolean)
546 encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
547 {
548 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
549 register int temp, temp2;
550 register int nbits;
551 int blkn, ci, tbl;
552 ISHIFT_TEMPS
553
554 entropy->next_output_byte = cinfo->dest->next_output_byte;
555 entropy->free_in_buffer = cinfo->dest->free_in_buffer;
556
557 /* Emit restart marker if needed */
558 if (cinfo->restart_interval)
559 if (entropy->restarts_to_go == 0)
560 emit_restart_e(entropy, entropy->next_restart_num);
561
562 /* Encode the MCU data blocks */
563 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
564 ci = cinfo->MCU_membership[blkn];
565 tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
566
567 /* Compute the DC value after the required point transform by Al.
568 * This is simply an arithmetic right shift.
569 */
570 temp = IRIGHT_SHIFT((int) (MCU_data[blkn][0][0]), cinfo->Al);
571
572 /* DC differences are figured on the point-transformed values. */
573 temp2 = temp - entropy->saved.last_dc_val[ci];
574 entropy->saved.last_dc_val[ci] = temp;
575
576 /* Encode the DC coefficient difference per section G.1.2.1 */
577 temp = temp2;
578 if (temp < 0) {
579 temp = -temp; /* temp is abs value of input */
580 /* For a negative input, want temp2 = bitwise complement of abs(input) */
581 /* This code assumes we are on a two's complement machine */
582 temp2--;
583 }
584
585 /* Find the number of bits needed for the magnitude of the coefficient */
586 nbits = 0;
587 while (temp) {
588 nbits++;
589 temp >>= 1;
590 }
591 /* Check for out-of-range coefficient values.
592 * Since we're encoding a difference, the range limit is twice as much.
593 */
594 if (nbits > MAX_COEF_BITS+1)
595 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
596
597 /* Count/emit the Huffman-coded symbol for the number of bits */
598 emit_dc_symbol(entropy, tbl, nbits);
599
600 /* Emit that number of bits of the value, if positive, */
601 /* or the complement of its magnitude, if negative. */
602 if (nbits) /* emit_bits rejects calls with size 0 */
603 emit_bits_e(entropy, (unsigned int) temp2, nbits);
604 }
605
606 cinfo->dest->next_output_byte = entropy->next_output_byte;
607 cinfo->dest->free_in_buffer = entropy->free_in_buffer;
608
609 /* Update restart-interval state too */
610 if (cinfo->restart_interval) {
611 if (entropy->restarts_to_go == 0) {
612 entropy->restarts_to_go = cinfo->restart_interval;
613 entropy->next_restart_num++;
614 entropy->next_restart_num &= 7;
615 }
616 entropy->restarts_to_go--;
617 }
618
619 return TRUE;
620 }
621
622
623 /*
624 * MCU encoding for AC initial scan (either spectral selection,
625 * or first pass of successive approximation).
626 */
627
628 METHODDEF(boolean)
629 encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
630 {
631 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
632 const int * natural_order;
633 JBLOCKROW block;
634 register int temp, temp2;
635 register int nbits;
636 register int r, k;
637 int Se, Al;
638
639 entropy->next_output_byte = cinfo->dest->next_output_byte;
640 entropy->free_in_buffer = cinfo->dest->free_in_buffer;
641
642 /* Emit restart marker if needed */
643 if (cinfo->restart_interval)
644 if (entropy->restarts_to_go == 0)
645 emit_restart_e(entropy, entropy->next_restart_num);
646
647 Se = cinfo->Se;
648 Al = cinfo->Al;
649 natural_order = cinfo->natural_order;
650
651 /* Encode the MCU data block */
652 block = MCU_data[0];
653
654 /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
655
656 r = 0; /* r = run length of zeros */
657
658 for (k = cinfo->Ss; k <= Se; k++) {
659 if ((temp = (*block)[natural_order[k]]) == 0) {
660 r++;
661 continue;
662 }
663 /* We must apply the point transform by Al. For AC coefficients this
664 * is an integer division with rounding towards 0. To do this portably
665 * in C, we shift after obtaining the absolute value; so the code is
666 * interwoven with finding the abs value (temp) and output bits (temp2).
667 */
668 if (temp < 0) {
669 temp = -temp; /* temp is abs value of input */
670 temp >>= Al; /* apply the point transform */
671 /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
672 temp2 = ~temp;
673 } else {
674 temp >>= Al; /* apply the point transform */
675 temp2 = temp;
676 }
677 /* Watch out for case that nonzero coef is zero after point transform */
678 if (temp == 0) {
679 r++;
680 continue;
681 }
682
683 /* Emit any pending EOBRUN */
684 if (entropy->EOBRUN > 0)
685 emit_eobrun(entropy);
686 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
687 while (r > 15) {
688 emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);
689 r -= 16;
690 }
691
692 /* Find the number of bits needed for the magnitude of the coefficient */
693 nbits = 1; /* there must be at least one 1 bit */
694 while ((temp >>= 1))
695 nbits++;
696 /* Check for out-of-range coefficient values */
697 if (nbits > MAX_COEF_BITS)
698 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
699
700 /* Count/emit Huffman symbol for run length / number of bits */
701 emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
702
703 /* Emit that number of bits of the value, if positive, */
704 /* or the complement of its magnitude, if negative. */
705 emit_bits_e(entropy, (unsigned int) temp2, nbits);
706
707 r = 0; /* reset zero run length */
708 }
709
710 if (r > 0) { /* If there are trailing zeroes, */
711 entropy->EOBRUN++; /* count an EOB */
712 if (entropy->EOBRUN == 0x7FFF)
713 emit_eobrun(entropy); /* force it out to avoid overflow */
714 }
715
716 cinfo->dest->next_output_byte = entropy->next_output_byte;
717 cinfo->dest->free_in_buffer = entropy->free_in_buffer;
718
719 /* Update restart-interval state too */
720 if (cinfo->restart_interval) {
721 if (entropy->restarts_to_go == 0) {
722 entropy->restarts_to_go = cinfo->restart_interval;
723 entropy->next_restart_num++;
724 entropy->next_restart_num &= 7;
725 }
726 entropy->restarts_to_go--;
727 }
728
729 return TRUE;
730 }
731
732
733 /*
734 * MCU encoding for DC successive approximation refinement scan.
735 * Note: we assume such scans can be multi-component,
736 * although the spec is not very clear on the point.
737 */
738
739 METHODDEF(boolean)
740 encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
741 {
742 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
743 int Al, blkn;
744
745 entropy->next_output_byte = cinfo->dest->next_output_byte;
746 entropy->free_in_buffer = cinfo->dest->free_in_buffer;
747
748 /* Emit restart marker if needed */
749 if (cinfo->restart_interval)
750 if (entropy->restarts_to_go == 0)
751 emit_restart_e(entropy, entropy->next_restart_num);
752
753 Al = cinfo->Al;
754
755 /* Encode the MCU data blocks */
756 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
757 /* We simply emit the Al'th bit of the DC coefficient value. */
758 emit_bits_e(entropy, (unsigned int) (MCU_data[blkn][0][0] >> Al), 1);
759 }
760
761 cinfo->dest->next_output_byte = entropy->next_output_byte;
762 cinfo->dest->free_in_buffer = entropy->free_in_buffer;
763
764 /* Update restart-interval state too */
765 if (cinfo->restart_interval) {
766 if (entropy->restarts_to_go == 0) {
767 entropy->restarts_to_go = cinfo->restart_interval;
768 entropy->next_restart_num++;
769 entropy->next_restart_num &= 7;
770 }
771 entropy->restarts_to_go--;
772 }
773
774 return TRUE;
775 }
776
777
778 /*
779 * MCU encoding for AC successive approximation refinement scan.
780 */
781
782 METHODDEF(boolean)
783 encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
784 {
785 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
786 const int * natural_order;
787 JBLOCKROW block;
788 register int temp;
789 register int r, k;
790 int Se, Al;
791 int EOB;
792 char *BR_buffer;
793 unsigned int BR;
794 int absvalues[DCTSIZE2];
795
796 entropy->next_output_byte = cinfo->dest->next_output_byte;
797 entropy->free_in_buffer = cinfo->dest->free_in_buffer;
798
799 /* Emit restart marker if needed */
800 if (cinfo->restart_interval)
801 if (entropy->restarts_to_go == 0)
802 emit_restart_e(entropy, entropy->next_restart_num);
803
804 Se = cinfo->Se;
805 Al = cinfo->Al;
806 natural_order = cinfo->natural_order;
807
808 /* Encode the MCU data block */
809 block = MCU_data[0];
810
811 /* It is convenient to make a pre-pass to determine the transformed
812 * coefficients' absolute values and the EOB position.
813 */
814 EOB = 0;
815 for (k = cinfo->Ss; k <= Se; k++) {
816 temp = (*block)[natural_order[k]];
817 /* We must apply the point transform by Al. For AC coefficients this
818 * is an integer division with rounding towards 0. To do this portably
819 * in C, we shift after obtaining the absolute value.
820 */
821 if (temp < 0)
822 temp = -temp; /* temp is abs value of input */
823 temp >>= Al; /* apply the point transform */
824 absvalues[k] = temp; /* save abs value for main pass */
825 if (temp == 1)
826 EOB = k; /* EOB = index of last newly-nonzero coef */
827 }
828
829 /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
830
831 r = 0; /* r = run length of zeros */
832 BR = 0; /* BR = count of buffered bits added now */
833 BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
834
835 for (k = cinfo->Ss; k <= Se; k++) {
836 if ((temp = absvalues[k]) == 0) {
837 r++;
838 continue;
839 }
840
841 /* Emit any required ZRLs, but not if they can be folded into EOB */
842 while (r > 15 && k <= EOB) {
843 /* emit any pending EOBRUN and the BE correction bits */
844 emit_eobrun(entropy);
845 /* Emit ZRL */
846 emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);
847 r -= 16;
848 /* Emit buffered correction bits that must be associated with ZRL */
849 emit_buffered_bits(entropy, BR_buffer, BR);
850 BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
851 BR = 0;
852 }
853
854 /* If the coef was previously nonzero, it only needs a correction bit.
855 * NOTE: a straight translation of the spec's figure G.7 would suggest
856 * that we also need to test r > 15. But if r > 15, we can only get here
857 * if k > EOB, which implies that this coefficient is not 1.
858 */
859 if (temp > 1) {
860 /* The correction bit is the next bit of the absolute value. */
861 BR_buffer[BR++] = (char) (temp & 1);
862 continue;
863 }
864
865 /* Emit any pending EOBRUN and the BE correction bits */
866 emit_eobrun(entropy);
867
868 /* Count/emit Huffman symbol for run length / number of bits */
869 emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
870
871 /* Emit output bit for newly-nonzero coef */
872 temp = ((*block)[natural_order[k]] < 0) ? 0 : 1;
873 emit_bits_e(entropy, (unsigned int) temp, 1);
874
875 /* Emit buffered correction bits that must be associated with this code */
876 emit_buffered_bits(entropy, BR_buffer, BR);
877 BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
878 BR = 0;
879 r = 0; /* reset zero run length */
880 }
881
882 if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
883 entropy->EOBRUN++; /* count an EOB */
884 entropy->BE += BR; /* concat my correction bits to older ones */
885 /* We force out the EOB if we risk either:
886 * 1. overflow of the EOB counter;
887 * 2. overflow of the correction bit buffer during the next MCU.
888 */
889 if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
890 emit_eobrun(entropy);
891 }
892
898 if (entropy->restarts_to_go == 0) {
899 entropy->restarts_to_go = cinfo->restart_interval;
900 entropy->next_restart_num++;
901 entropy->next_restart_num &= 7;
902 }
903 entropy->restarts_to_go--;
904 }
905
906 return TRUE;
907 }
908
909
910 /* Encode a single block's worth of coefficients */
911
912 LOCAL(boolean)
913 encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
914 c_derived_tbl *dctbl, c_derived_tbl *actbl)
915 {
916 register int temp, temp2;
917 register int nbits;
918 register int r, k;
919 int Se = state->cinfo->lim_Se;
920 const int * natural_order = state->cinfo->natural_order;
921
922 /* Encode the DC coefficient difference per section F.1.2.1 */
923
924 temp = temp2 = block[0] - last_dc_val;
925
926 if (temp < 0) {
927 temp = -temp; /* temp is abs value of input */
928 /* For a negative input, want temp2 = bitwise complement of abs(input) */
929 /* This code assumes we are on a two's complement machine */
930 temp2--;
931 }
932
933 /* Find the number of bits needed for the magnitude of the coefficient */
934 nbits = 0;
935 while (temp) {
936 nbits++;
937 temp >>= 1;
938 }
939 /* Check for out-of-range coefficient values.
940 * Since we're encoding a difference, the range limit is twice as much.
941 */
942 if (nbits > MAX_COEF_BITS+1)
943 ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
944
945 /* Emit the Huffman-coded symbol for the number of bits */
946 if (! emit_bits_s(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
947 return FALSE;
948
949 /* Emit that number of bits of the value, if positive, */
950 /* or the complement of its magnitude, if negative. */
951 if (nbits) /* emit_bits rejects calls with size 0 */
952 if (! emit_bits_s(state, (unsigned int) temp2, nbits))
953 return FALSE;
954
955 /* Encode the AC coefficients per section F.1.2.2 */
956
957 r = 0; /* r = run length of zeros */
958
959 for (k = 1; k <= Se; k++) {
960 if ((temp2 = block[natural_order[k]]) == 0) {
961 r++;
962 } else {
963 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
964 while (r > 15) {
965 if (! emit_bits_s(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
966 return FALSE;
967 r -= 16;
968 }
969
970 temp = temp2;
971 if (temp < 0) {
972 temp = -temp; /* temp is abs value of input */
973 /* This code assumes we are on a two's complement machine */
974 temp2--;
975 }
976
977 /* Find the number of bits needed for the magnitude of the coefficient */
978 nbits = 1; /* there must be at least one 1 bit */
979 while ((temp >>= 1))
980 nbits++;
981 /* Check for out-of-range coefficient values */
982 if (nbits > MAX_COEF_BITS)
983 ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
984
985 /* Emit Huffman symbol for run length / number of bits */
986 temp = (r << 4) + nbits;
987 if (! emit_bits_s(state, actbl->ehufco[temp], actbl->ehufsi[temp]))
988 return FALSE;
989
990 /* Emit that number of bits of the value, if positive, */
991 /* or the complement of its magnitude, if negative. */
992 if (! emit_bits_s(state, (unsigned int) temp2, nbits))
993 return FALSE;
994
995 r = 0;
996 }
997 }
998
999 /* If the last coef(s) were zero, emit an end-of-block code */
1000 if (r > 0)
1001 if (! emit_bits_s(state, actbl->ehufco[0], actbl->ehufsi[0]))
1002 return FALSE;
1003
1004 return TRUE;
1005 }
1006
1007
1104 /*
1105 * Huffman coding optimization.
1106 *
1107 * We first scan the supplied data and count the number of uses of each symbol
1108 * that is to be Huffman-coded. (This process MUST agree with the code above.)
1109 * Then we build a Huffman coding tree for the observed counts.
1110 * Symbols which are not needed at all for the particular image are not
1111 * assigned any code, which saves space in the DHT marker as well as in
1112 * the compressed data.
1113 */
1114
1115
1116 /* Process a single block's worth of coefficients */
1117
1118 LOCAL(void)
1119 htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
1120 long dc_counts[], long ac_counts[])
1121 {
1122 register int temp;
1123 register int nbits;
1124 register int r, k;
1125 int Se = cinfo->lim_Se;
1126 const int * natural_order = cinfo->natural_order;
1127
1128 /* Encode the DC coefficient difference per section F.1.2.1 */
1129
1130 temp = block[0] - last_dc_val;
1131 if (temp < 0)
1132 temp = -temp;
1133
1134 /* Find the number of bits needed for the magnitude of the coefficient */
1135 nbits = 0;
1136 while (temp) {
1137 nbits++;
1138 temp >>= 1;
1139 }
1140 /* Check for out-of-range coefficient values.
1141 * Since we're encoding a difference, the range limit is twice as much.
1142 */
1143 if (nbits > MAX_COEF_BITS+1)
1144 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
1145
1146 /* Count the Huffman symbol for the number of bits */
1147 dc_counts[nbits]++;
1148
1149 /* Encode the AC coefficients per section F.1.2.2 */
1150
1151 r = 0; /* r = run length of zeros */
1152
1153 for (k = 1; k <= Se; k++) {
1154 if ((temp = block[natural_order[k]]) == 0) {
1155 r++;
1156 } else {
1157 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
1158 while (r > 15) {
1159 ac_counts[0xF0]++;
1160 r -= 16;
1161 }
1162
1163 /* Find the number of bits needed for the magnitude of the coefficient */
1164 if (temp < 0)
1165 temp = -temp;
1166
1167 /* Find the number of bits needed for the magnitude of the coefficient */
1168 nbits = 1; /* there must be at least one 1 bit */
1169 while ((temp >>= 1))
1170 nbits++;
1171 /* Check for out-of-range coefficient values */
1172 if (nbits > MAX_COEF_BITS)
1173 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
1174
1377 if (codesize[j] == i) {
1378 htbl->huffval[p] = (UINT8) j;
1379 p++;
1380 }
1381 }
1382 }
1383
1384 /* Set sent_table FALSE so updated table will be written to JPEG file. */
1385 htbl->sent_table = FALSE;
1386 }
1387
1388
1389 /*
1390 * Finish up a statistics-gathering pass and create the new Huffman tables.
1391 */
1392
1393 METHODDEF(void)
1394 finish_pass_gather (j_compress_ptr cinfo)
1395 {
1396 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1397 int ci, tbl;
1398 jpeg_component_info * compptr;
1399 JHUFF_TBL **htblptr;
1400 boolean did_dc[NUM_HUFF_TBLS];
1401 boolean did_ac[NUM_HUFF_TBLS];
1402
1403 /* It's important not to apply jpeg_gen_optimal_table more than once
1404 * per table, because it clobbers the input frequency counts!
1405 */
1406 if (cinfo->progressive_mode)
1407 /* Flush out buffered data (all we care about is counting the EOB symbol) */
1408 emit_eobrun(entropy);
1409
1410 MEMZERO(did_dc, SIZEOF(did_dc));
1411 MEMZERO(did_ac, SIZEOF(did_ac));
1412
1413 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1414 compptr = cinfo->cur_comp_info[ci];
1415 /* DC needs no table for refinement scan */
1416 if (cinfo->Ss == 0 && cinfo->Ah == 0) {
1417 tbl = compptr->dc_tbl_no;
1418 if (! did_dc[tbl]) {
1419 htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
1420 if (*htblptr == NULL)
1421 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
1422 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[tbl]);
1423 did_dc[tbl] = TRUE;
1424 }
1425 }
1426 /* AC needs no table when not present */
1427 if (cinfo->Se) {
1428 tbl = compptr->ac_tbl_no;
1429 if (! did_ac[tbl]) {
1430 htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
1431 if (*htblptr == NULL)
1432 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
1433 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[tbl]);
1434 did_ac[tbl] = TRUE;
1435 }
1436 }
1437 }
1438 }
1439
1440
1441 /*
1442 * Initialize for a Huffman-compressed scan.
1443 * If gather_statistics is TRUE, we do not output anything during the scan,
1444 * just count the Huffman symbols used and generate Huffman code tables.
1445 */
1446
1447 METHODDEF(void)
1448 start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
1449 {
1450 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1451 int ci, tbl;
1452 jpeg_component_info * compptr;
1453
1454 if (gather_statistics)
1455 entropy->pub.finish_pass = finish_pass_gather;
1456 else
1457 entropy->pub.finish_pass = finish_pass_huff;
1458
1459 if (cinfo->progressive_mode) {
1460 entropy->cinfo = cinfo;
1461 entropy->gather_statistics = gather_statistics;
1462
1463 /* We assume jcmaster.c already validated the scan parameters. */
1464
1465 /* Select execution routine */
1466 if (cinfo->Ah == 0) {
1467 if (cinfo->Ss == 0)
1468 entropy->pub.encode_mcu = encode_mcu_DC_first;
1469 else
1470 entropy->pub.encode_mcu = encode_mcu_AC_first;
1471 } else {
1472 if (cinfo->Ss == 0)
1473 entropy->pub.encode_mcu = encode_mcu_DC_refine;
1474 else {
1475 entropy->pub.encode_mcu = encode_mcu_AC_refine;
1476 /* AC refinement needs a correction bit buffer */
1477 if (entropy->bit_buffer == NULL)
1478 entropy->bit_buffer = (char *)
1479 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1480 MAX_CORR_BITS * SIZEOF(char));
1481 }
1482 }
1483
1484 /* Initialize AC stuff */
1485 entropy->ac_tbl_no = cinfo->cur_comp_info[0]->ac_tbl_no;
1486 entropy->EOBRUN = 0;
1487 entropy->BE = 0;
1488 } else {
1489 if (gather_statistics)
1490 entropy->pub.encode_mcu = encode_mcu_gather;
1491 else
1492 entropy->pub.encode_mcu = encode_mcu_huff;
1493 }
1494
1495 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1496 compptr = cinfo->cur_comp_info[ci];
1497 /* DC needs no table for refinement scan */
1498 if (cinfo->Ss == 0 && cinfo->Ah == 0) {
1499 tbl = compptr->dc_tbl_no;
1500 if (gather_statistics) {
1501 /* Check for invalid table index */
1502 /* (make_c_derived_tbl does this in the other path) */
1503 if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
1504 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
1505 /* Allocate and zero the statistics tables */
1506 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
1507 if (entropy->dc_count_ptrs[tbl] == NULL)
1508 entropy->dc_count_ptrs[tbl] = (long *)
1509 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1510 257 * SIZEOF(long));
1511 MEMZERO(entropy->dc_count_ptrs[tbl], 257 * SIZEOF(long));
1512 } else {
1513 /* Compute derived values for Huffman tables */
1514 /* We may do this more than once for a table, but it's not expensive */
1515 jpeg_make_c_derived_tbl(cinfo, TRUE, tbl,
1516 & entropy->dc_derived_tbls[tbl]);
1517 }
1518 /* Initialize DC predictions to 0 */
1519 entropy->saved.last_dc_val[ci] = 0;
1520 }
1521 /* AC needs no table when not present */
1522 if (cinfo->Se) {
1523 tbl = compptr->ac_tbl_no;
1524 if (gather_statistics) {
1525 if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
1526 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
1527 if (entropy->ac_count_ptrs[tbl] == NULL)
1528 entropy->ac_count_ptrs[tbl] = (long *)
1529 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1530 257 * SIZEOF(long));
1531 MEMZERO(entropy->ac_count_ptrs[tbl], 257 * SIZEOF(long));
1532 } else {
1533 jpeg_make_c_derived_tbl(cinfo, FALSE, tbl,
1534 & entropy->ac_derived_tbls[tbl]);
1535 }
1536 }
1537 }
1538
1539 /* Initialize bit buffer to empty */
1540 entropy->saved.put_buffer = 0;
1541 entropy->saved.put_bits = 0;
1542
1543 /* Initialize restart stuff */
1544 entropy->restarts_to_go = cinfo->restart_interval;
1545 entropy->next_restart_num = 0;
1546 }
1547
1548
1549 /*
1550 * Module initialization routine for Huffman entropy encoding.
1551 */
1552
1553 GLOBAL(void)
1554 jinit_huff_encoder (j_compress_ptr cinfo)
1555 {
1556 huff_entropy_ptr entropy;
1557 int i;
1558
1559 entropy = (huff_entropy_ptr)
1560 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1561 SIZEOF(huff_entropy_encoder));
1562 cinfo->entropy = &entropy->pub;
1563 entropy->pub.start_pass = start_pass_huff;
1564
1565 /* Mark tables unallocated */
1566 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1567 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
1568 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
1569 }
1570
1571 if (cinfo->progressive_mode)
1572 entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
1573 }
|