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



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: ae4571287 Thu Nov 23 00:06:53 2017 +0100 at dom oct 27 23:51:55 CET 2019