Coverage Report

Created: 2025-06-13 06:18

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