source: golgotha/src/i4/loaders/jpg/jcphuff.cc @ 608

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