Coverage Report

Created: 2025-10-10 07:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjpeg-turbo.dev/src/jchuff.c
Line
Count
Source
1
/*
2
 * jchuff.c
3
 *
4
 * This file was part of the Independent JPEG Group's software:
5
 * Copyright (C) 1991-1997, Thomas G. Lane.
6
 * Lossless JPEG Modifications:
7
 * Copyright (C) 1999, Ken Murchison.
8
 * libjpeg-turbo Modifications:
9
 * Copyright (C) 2009-2011, 2014-2016, 2018-2025, D. R. Commander.
10
 * Copyright (C) 2015, Matthieu Darbois.
11
 * Copyright (C) 2018, Matthias Räncker.
12
 * Copyright (C) 2020, Arm Limited.
13
 * Copyright (C) 2022, Felix Hanau.
14
 * For conditions of distribution and use, see the accompanying README.ijg
15
 * file.
16
 *
17
 * This file contains Huffman entropy encoding routines.
18
 *
19
 * Much of the complexity here has to do with supporting output suspension.
20
 * If the data destination module demands suspension, we want to be able to
21
 * back up to the start of the current MCU.  To do this, we copy state
22
 * variables into local working storage, and update them back to the
23
 * permanent JPEG objects only upon successful completion of an MCU.
24
 *
25
 * NOTE: All referenced figures are from
26
 * Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.
27
 */
28
29
#define JPEG_INTERNALS
30
#include "jinclude.h"
31
#include "jpeglib.h"
32
#ifdef WITH_SIMD
33
#include "../simd/jsimd.h"
34
#endif
35
#include "jchuff.h"             /* Declarations shared with jc*huff.c */
36
#include <limits.h>
37
#include "jpeg_nbits.h"
38
39
40
/* Expanded entropy encoder object for Huffman encoding.
41
 *
42
 * The savable_state subrecord contains fields that change within an MCU,
43
 * but must not be updated permanently until we complete the MCU.
44
 */
45
46
#if defined(__x86_64__) && defined(__ILP32__)
47
typedef unsigned long long bit_buf_type;
48
#else
49
typedef size_t bit_buf_type;
50
#endif
51
52
#if defined(WITH_SIMD) && \
53
    SIMD_ARCHITECTURE != ARM64 && SIMD_ARCHITECTURE != ARM
54
typedef unsigned long long simd_bit_buf_type;
55
#else
56
typedef bit_buf_type simd_bit_buf_type;
57
#endif
58
59
#if (defined(SIZEOF_SIZE_T) && SIZEOF_SIZE_T == 8) || defined(_WIN64) || \
60
    (defined(__x86_64__) && defined(__ILP32__))
61
0
#define BIT_BUF_SIZE  64
62
#elif (defined(SIZEOF_SIZE_T) && SIZEOF_SIZE_T == 4) || defined(_WIN32)
63
#define BIT_BUF_SIZE  32
64
#else
65
#error Cannot determine word size
66
#endif
67
5.67k
#define SIMD_BIT_BUF_SIZE  (sizeof(simd_bit_buf_type) * 8)
68
69
typedef struct {
70
  union {
71
    bit_buf_type c;
72
#ifdef WITH_SIMD
73
    simd_bit_buf_type simd;
74
#endif
75
  } put_buffer;                         /* current bit accumulation buffer */
76
  int free_bits;                        /* # of bits available in it */
77
  int last_dc_val[MAX_COMPS_IN_SCAN];   /* last DC coef for each component */
78
} savable_state;
79
80
typedef struct {
81
  struct jpeg_entropy_encoder pub; /* public fields */
82
83
  savable_state saved;          /* Bit buffer & DC state at start of MCU */
84
85
  /* These fields are NOT loaded into local working state. */
86
  unsigned int restarts_to_go;  /* MCUs left in this restart interval */
87
  int next_restart_num;         /* next restart number to write (0-7) */
88
89
  /* Pointers to derived tables (these workspaces have image lifespan) */
90
  c_derived_tbl *dc_derived_tbls[NUM_HUFF_TBLS];
91
  c_derived_tbl *ac_derived_tbls[NUM_HUFF_TBLS];
92
93
#ifdef ENTROPY_OPT_SUPPORTED    /* Statistics tables for optimization */
94
  long *dc_count_ptrs[NUM_HUFF_TBLS];
95
  long *ac_count_ptrs[NUM_HUFF_TBLS];
96
#endif
97
98
#ifdef WITH_SIMD
99
  unsigned int simd;
100
#endif
101
} huff_entropy_encoder;
102
103
typedef huff_entropy_encoder *huff_entropy_ptr;
104
105
/* Working state while writing an MCU.
106
 * This struct contains all the fields that are needed by subroutines.
107
 */
108
109
typedef struct {
110
  JOCTET *next_output_byte;     /* => next byte to write in buffer */
111
  size_t free_in_buffer;        /* # of byte spaces remaining in buffer */
112
  savable_state cur;            /* Current bit buffer & DC state */
113
  j_compress_ptr cinfo;         /* dump_buffer needs access to this */
114
#ifdef WITH_SIMD
115
  unsigned int simd;
116
#endif
117
} working_state;
118
119
120
/* Forward declarations */
121
METHODDEF(boolean) encode_mcu_huff(j_compress_ptr cinfo, JBLOCKROW *MCU_data);
122
METHODDEF(void) finish_pass_huff(j_compress_ptr cinfo);
123
#ifdef ENTROPY_OPT_SUPPORTED
124
METHODDEF(boolean) encode_mcu_gather(j_compress_ptr cinfo,
125
                                     JBLOCKROW *MCU_data);
126
METHODDEF(void) finish_pass_gather(j_compress_ptr cinfo);
127
#endif
128
129
130
/*
131
 * Initialize for a Huffman-compressed scan.
132
 * If gather_statistics is TRUE, we do not output anything during the scan,
133
 * just count the Huffman symbols used and generate Huffman code tables.
134
 */
135
136
METHODDEF(void)
137
start_pass_huff(j_compress_ptr cinfo, boolean gather_statistics)
138
3.07k
{
139
3.07k
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
140
3.07k
  int ci, dctbl, actbl;
141
3.07k
  jpeg_component_info *compptr;
142
143
3.07k
  if (gather_statistics) {
144
1.76k
#ifdef ENTROPY_OPT_SUPPORTED
145
1.76k
    entropy->pub.encode_mcu = encode_mcu_gather;
146
1.76k
    entropy->pub.finish_pass = finish_pass_gather;
147
#else
148
    ERREXIT(cinfo, JERR_NOT_COMPILED);
149
#endif
150
1.76k
  } else {
151
1.30k
    entropy->pub.encode_mcu = encode_mcu_huff;
152
1.30k
    entropy->pub.finish_pass = finish_pass_huff;
153
1.30k
  }
154
155
3.07k
#ifdef WITH_SIMD
156
3.07k
  entropy->simd = jsimd_set_huff_encode_one_block(cinfo);
157
3.07k
#endif
158
159
6.14k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
160
3.07k
    compptr = cinfo->cur_comp_info[ci];
161
3.07k
    dctbl = compptr->dc_tbl_no;
162
3.07k
    actbl = compptr->ac_tbl_no;
163
3.07k
    if (gather_statistics) {
164
1.76k
#ifdef ENTROPY_OPT_SUPPORTED
165
      /* Check for invalid table indexes */
166
      /* (make_c_derived_tbl does this in the other path) */
167
1.76k
      if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
168
0
        ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
169
1.76k
      if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
170
0
        ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
171
      /* Allocate and zero the statistics tables */
172
      /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
173
1.76k
      if (entropy->dc_count_ptrs[dctbl] == NULL)
174
1.76k
        entropy->dc_count_ptrs[dctbl] = (long *)
175
1.76k
          (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
176
1.76k
                                      257 * sizeof(long));
177
1.76k
      memset(entropy->dc_count_ptrs[dctbl], 0, 257 * sizeof(long));
178
1.76k
      if (entropy->ac_count_ptrs[actbl] == NULL)
179
1.76k
        entropy->ac_count_ptrs[actbl] = (long *)
180
1.76k
          (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
181
1.76k
                                      257 * sizeof(long));
182
1.76k
      memset(entropy->ac_count_ptrs[actbl], 0, 257 * sizeof(long));
183
1.76k
#endif
184
1.76k
    } else {
185
      /* Compute derived values for Huffman tables */
186
      /* We may do this more than once for a table, but it's not expensive */
187
1.30k
      jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
188
1.30k
                              &entropy->dc_derived_tbls[dctbl]);
189
1.30k
      jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
190
1.30k
                              &entropy->ac_derived_tbls[actbl]);
191
1.30k
    }
192
    /* Initialize DC predictions to 0 */
193
3.07k
    entropy->saved.last_dc_val[ci] = 0;
194
3.07k
  }
195
196
  /* Initialize bit buffer to empty */
197
3.07k
#ifdef WITH_SIMD
198
3.07k
  if (entropy->simd) {
199
3.07k
    entropy->saved.put_buffer.simd = 0;
200
3.07k
    entropy->saved.free_bits = SIMD_BIT_BUF_SIZE;
201
3.07k
  } else
202
0
#endif
203
0
  {
204
0
    entropy->saved.put_buffer.c = 0;
205
0
    entropy->saved.free_bits = BIT_BUF_SIZE;
206
0
  }
207
208
  /* Initialize restart stuff */
209
3.07k
  entropy->restarts_to_go = cinfo->restart_interval;
210
3.07k
  entropy->next_restart_num = 0;
211
3.07k
}
212
213
214
/*
215
 * Compute the derived values for a Huffman table.
216
 * This routine also performs some validation checks on the table.
217
 *
218
 * Note this is also used by jcphuff.c and jclhuff.c.
219
 */
220
221
GLOBAL(void)
222
jpeg_make_c_derived_tbl(j_compress_ptr cinfo, boolean isDC, int tblno,
223
                        c_derived_tbl **pdtbl)
224
26.9k
{
225
26.9k
  JHUFF_TBL *htbl;
226
26.9k
  c_derived_tbl *dtbl;
227
26.9k
  int p, i, l, lastp, si, maxsymbol;
228
26.9k
  char huffsize[257];
229
26.9k
  unsigned int huffcode[257];
230
26.9k
  unsigned int code;
231
232
  /* Note that huffsize[] and huffcode[] are filled in code-length order,
233
   * paralleling the order of the symbols themselves in htbl->huffval[].
234
   */
235
236
  /* Find the input Huffman table */
237
26.9k
  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
238
0
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
239
26.9k
  htbl =
240
26.9k
    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
241
26.9k
  if (htbl == NULL)
242
0
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
243
244
  /* Allocate a workspace if we haven't already done so. */
245
26.9k
  if (*pdtbl == NULL)
246
6.74k
    *pdtbl = (c_derived_tbl *)
247
6.74k
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
248
6.74k
                                  sizeof(c_derived_tbl));
249
26.9k
  dtbl = *pdtbl;
250
251
  /* Figure C.1: make table of Huffman code length for each symbol */
252
253
26.9k
  p = 0;
254
458k
  for (l = 1; l <= 16; l++) {
255
431k
    i = (int)htbl->bits[l];
256
431k
    if (i < 0 || p + i > 256)   /* protect against table overrun */
257
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
258
531k
    while (i--)
259
100k
      huffsize[p++] = (char)l;
260
431k
  }
261
26.9k
  huffsize[p] = 0;
262
26.9k
  lastp = p;
263
264
  /* Figure C.2: generate the codes themselves */
265
  /* We also validate that the counts represent a legal Huffman code tree. */
266
267
26.9k
  code = 0;
268
26.9k
  si = huffsize[0];
269
26.9k
  p = 0;
270
89.3k
  while (huffsize[p]) {
271
162k
    while (((int)huffsize[p]) == si) {
272
100k
      huffcode[p++] = code;
273
100k
      code++;
274
100k
    }
275
    /* code is now 1 more than the last code used for codelength si; but
276
     * it must still fit in si bits, since no code is allowed to be all ones.
277
     */
278
62.4k
    if (((JLONG)code) >= (((JLONG)1) << si))
279
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
280
62.4k
    code <<= 1;
281
62.4k
    si++;
282
62.4k
  }
283
284
  /* Figure C.3: generate encoding tables */
285
  /* These are code and size indexed by symbol value */
286
287
  /* Set all codeless symbols to have code length 0;
288
   * this lets us detect duplicate VAL entries here, and later
289
   * allows emit_bits to detect any attempt to emit such symbols.
290
   */
291
26.9k
  memset(dtbl->ehufco, 0, sizeof(dtbl->ehufco));
292
26.9k
  memset(dtbl->ehufsi, 0, sizeof(dtbl->ehufsi));
293
294
  /* This is also a convenient place to check for out-of-range and duplicated
295
   * VAL entries.  We allow 0..255 for AC symbols but only 0..15 for DC in
296
   * lossy mode and 0..16 for DC in lossless mode.  (We could constrain them
297
   * further based on data depth and mode, but this seems enough.)
298
   */
299
26.9k
  maxsymbol = isDC ? (cinfo->master->lossless ? 16 : 15) : 255;
300
301
127k
  for (p = 0; p < lastp; p++) {
302
100k
    i = htbl->huffval[p];
303
100k
    if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
304
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
305
100k
    dtbl->ehufco[i] = huffcode[p];
306
100k
    dtbl->ehufsi[i] = huffsize[p];
307
100k
  }
308
26.9k
}
309
310
311
/* Outputting bytes to the file */
312
313
/* Emit a byte, taking 'action' if must suspend. */
314
0
#define emit_byte(state, val, action) { \
315
0
  *(state)->next_output_byte++ = (JOCTET)(val); \
316
0
  if (--(state)->free_in_buffer == 0) \
317
0
    if (!dump_buffer(state)) \
318
0
      { action; } \
319
0
}
320
321
322
LOCAL(boolean)
323
dump_buffer(working_state *state)
324
/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
325
0
{
326
0
  struct jpeg_destination_mgr *dest = state->cinfo->dest;
327
328
0
  if (!(*dest->empty_output_buffer) (state->cinfo))
329
0
    return FALSE;
330
  /* After a successful buffer dump, must reset buffer pointers */
331
0
  state->next_output_byte = dest->next_output_byte;
332
0
  state->free_in_buffer = dest->free_in_buffer;
333
0
  return TRUE;
334
0
}
335
336
337
/* Outputting bits to the file */
338
339
/* Output byte b and, speculatively, an additional 0 byte.  0xFF must be
340
 * encoded as 0xFF 0x00, so the output buffer pointer is advanced by 2 if the
341
 * byte is 0xFF.  Otherwise, the output buffer pointer is advanced by 1, and
342
 * the speculative 0 byte will be overwritten by the next byte.
343
 */
344
5.10k
#define EMIT_BYTE(b) { \
345
5.10k
  buffer[0] = (JOCTET)(b); \
346
5.10k
  buffer[1] = 0; \
347
5.10k
  buffer -= -2 + ((JOCTET)(b) < 0xFF); \
348
5.10k
}
349
350
/* Output the entire bit buffer.  If there are no 0xFF bytes in it, then write
351
 * directly to the output buffer.  Otherwise, use the EMIT_BYTE() macro to
352
 * encode 0xFF as 0xFF 0x00.
353
 */
354
#if BIT_BUF_SIZE == 64
355
356
0
#define FLUSH() { \
357
0
  if (put_buffer & 0x8080808080808080 & ~(put_buffer + 0x0101010101010101)) { \
358
0
    EMIT_BYTE(put_buffer >> 56) \
359
0
    EMIT_BYTE(put_buffer >> 48) \
360
0
    EMIT_BYTE(put_buffer >> 40) \
361
0
    EMIT_BYTE(put_buffer >> 32) \
362
0
    EMIT_BYTE(put_buffer >> 24) \
363
0
    EMIT_BYTE(put_buffer >> 16) \
364
0
    EMIT_BYTE(put_buffer >>  8) \
365
0
    EMIT_BYTE(put_buffer      ) \
366
0
  } else { \
367
0
    buffer[0] = (JOCTET)(put_buffer >> 56); \
368
0
    buffer[1] = (JOCTET)(put_buffer >> 48); \
369
0
    buffer[2] = (JOCTET)(put_buffer >> 40); \
370
0
    buffer[3] = (JOCTET)(put_buffer >> 32); \
371
0
    buffer[4] = (JOCTET)(put_buffer >> 24); \
372
0
    buffer[5] = (JOCTET)(put_buffer >> 16); \
373
0
    buffer[6] = (JOCTET)(put_buffer >> 8); \
374
0
    buffer[7] = (JOCTET)(put_buffer); \
375
0
    buffer += 8; \
376
0
  } \
377
0
}
378
379
#else
380
381
#define FLUSH() { \
382
  if (put_buffer & 0x80808080 & ~(put_buffer + 0x01010101)) { \
383
    EMIT_BYTE(put_buffer >> 24) \
384
    EMIT_BYTE(put_buffer >> 16) \
385
    EMIT_BYTE(put_buffer >>  8) \
386
    EMIT_BYTE(put_buffer      ) \
387
  } else { \
388
    buffer[0] = (JOCTET)(put_buffer >> 24); \
389
    buffer[1] = (JOCTET)(put_buffer >> 16); \
390
    buffer[2] = (JOCTET)(put_buffer >> 8); \
391
    buffer[3] = (JOCTET)(put_buffer); \
392
    buffer += 4; \
393
  } \
394
}
395
396
#endif
397
398
/* Fill the bit buffer to capacity with the leading bits from code, then output
399
 * the bit buffer and put the remaining bits from code into the bit buffer.
400
 */
401
0
#define PUT_AND_FLUSH(code, size) { \
402
0
  put_buffer = (put_buffer << (size + free_bits)) | (code >> -free_bits); \
403
0
  FLUSH() \
404
0
  free_bits += BIT_BUF_SIZE; \
405
0
  put_buffer = code; \
406
0
}
407
408
/* Insert code into the bit buffer and output the bit buffer if needed.
409
 * NOTE: We can't flush with free_bits == 0, since the left shift in
410
 * PUT_AND_FLUSH() would have undefined behavior.
411
 */
412
0
#define PUT_BITS(code, size) { \
413
0
  free_bits -= size; \
414
0
  if (free_bits < 0) \
415
0
    PUT_AND_FLUSH(code, size) \
416
0
  else \
417
0
    put_buffer = (put_buffer << size) | code; \
418
0
}
419
420
0
#define PUT_CODE(code, size) { \
421
0
  temp &= (((JLONG)1) << nbits) - 1; \
422
0
  temp |= code << nbits; \
423
0
  nbits += size; \
424
0
  PUT_BITS(temp, nbits) \
425
0
}
426
427
428
/* Although it is exceedingly rare, it is possible for a Huffman-encoded
429
 * coefficient block to be larger than the 128-byte unencoded block.  For each
430
 * of the 64 coefficients, PUT_BITS is invoked twice, and each invocation can
431
 * theoretically store 16 bits (for a maximum of 2048 bits or 256 bytes per
432
 * encoded block.)  If, for instance, one artificially sets the AC
433
 * coefficients to alternating values of 32767 and -32768 (using the JPEG
434
 * scanning order-- 1, 8, 16, etc.), then this will produce an encoded block
435
 * larger than 200 bytes.
436
 */
437
2.62M
#define BUFSIZE  (DCTSIZE2 * 8)
438
439
2.62M
#define LOAD_BUFFER() { \
440
2.62M
  if (state->free_in_buffer < BUFSIZE) { \
441
0
    localbuf = 1; \
442
0
    buffer = _buffer; \
443
0
  } else \
444
2.62M
    buffer = state->next_output_byte; \
445
2.62M
}
446
447
2.62M
#define STORE_BUFFER() { \
448
2.62M
  if (localbuf) { \
449
0
    size_t bytes, bytestocopy; \
450
0
    bytes = buffer - _buffer; \
451
0
    buffer = _buffer; \
452
0
    while (bytes > 0) { \
453
0
      bytestocopy = MIN(bytes, state->free_in_buffer); \
454
0
      memcpy(state->next_output_byte, buffer, bytestocopy); \
455
0
      state->next_output_byte += bytestocopy; \
456
0
      buffer += bytestocopy; \
457
0
      state->free_in_buffer -= bytestocopy; \
458
0
      if (state->free_in_buffer == 0) \
459
0
        if (!dump_buffer(state)) return FALSE; \
460
0
      bytes -= bytestocopy; \
461
0
    } \
462
2.62M
  } else { \
463
2.62M
    state->free_in_buffer -= (buffer - state->next_output_byte); \
464
2.62M
    state->next_output_byte = buffer; \
465
2.62M
  } \
466
2.62M
}
467
468
469
LOCAL(boolean)
470
flush_bits(working_state *state)
471
1.30k
{
472
1.30k
  JOCTET _buffer[BUFSIZE], *buffer, temp;
473
1.30k
  simd_bit_buf_type put_buffer;  int put_bits;
474
1.30k
  int localbuf = 0;
475
476
1.30k
#ifdef WITH_SIMD
477
1.30k
  if (state->simd) {
478
1.30k
    put_bits = SIMD_BIT_BUF_SIZE - state->cur.free_bits;
479
1.30k
    put_buffer = state->cur.put_buffer.simd;
480
1.30k
  } else
481
0
#endif
482
0
  {
483
0
    put_bits = BIT_BUF_SIZE - state->cur.free_bits;
484
0
    put_buffer = state->cur.put_buffer.c;
485
0
  }
486
487
1.30k
  LOAD_BUFFER()
488
489
5.33k
  while (put_bits >= 8) {
490
4.02k
    put_bits -= 8;
491
4.02k
    temp = (JOCTET)(put_buffer >> put_bits);
492
4.02k
    EMIT_BYTE(temp)
493
4.02k
  }
494
1.30k
  if (put_bits) {
495
    /* fill partial byte with ones */
496
1.07k
    temp = (JOCTET)((put_buffer << (8 - put_bits)) | (0xFF >> put_bits));
497
1.07k
    EMIT_BYTE(temp)
498
1.07k
  }
499
500
1.30k
#ifdef WITH_SIMD
501
1.30k
  if (state->simd) {                    /* and reset bit buffer to empty */
502
1.30k
    state->cur.put_buffer.simd = 0;
503
1.30k
    state->cur.free_bits = SIMD_BIT_BUF_SIZE;
504
1.30k
  } else
505
0
#endif
506
0
  {
507
0
    state->cur.put_buffer.c = 0;
508
0
    state->cur.free_bits = BIT_BUF_SIZE;
509
0
  }
510
1.30k
  STORE_BUFFER()
511
512
1.30k
  return TRUE;
513
1.30k
}
514
515
516
#ifdef WITH_SIMD
517
518
/* Encode a single block's worth of coefficients */
519
520
LOCAL(boolean)
521
encode_one_block_simd(working_state *state, JCOEFPTR block, int last_dc_val,
522
                      c_derived_tbl *dctbl, c_derived_tbl *actbl)
523
2.62M
{
524
2.62M
  JOCTET _buffer[BUFSIZE], *buffer;
525
2.62M
  int localbuf = 0;
526
527
#ifdef ZERO_BUFFERS
528
  memset(_buffer, 0, sizeof(_buffer));
529
#endif
530
531
2.62M
  LOAD_BUFFER()
532
533
2.62M
  buffer = state->cinfo->entropy->huff_encode_one_block_simd(state, buffer,
534
2.62M
                                                             block,
535
2.62M
                                                             last_dc_val,
536
2.62M
                                                             dctbl, actbl);
537
538
2.62M
  STORE_BUFFER()
539
540
2.62M
  return TRUE;
541
2.62M
}
542
543
#endif
544
545
LOCAL(boolean)
546
encode_one_block(working_state *state, JCOEFPTR block, int last_dc_val,
547
                 c_derived_tbl *dctbl, c_derived_tbl *actbl)
548
0
{
549
0
  int temp, nbits, free_bits;
550
0
  bit_buf_type put_buffer;
551
0
  JOCTET _buffer[BUFSIZE], *buffer;
552
0
  int localbuf = 0;
553
0
  int max_coef_bits = state->cinfo->data_precision + 2;
554
555
0
  free_bits = state->cur.free_bits;
556
0
  put_buffer = state->cur.put_buffer.c;
557
0
  LOAD_BUFFER()
558
559
  /* Encode the DC coefficient difference per section F.1.2.1 */
560
561
0
  temp = block[0] - last_dc_val;
562
563
  /* This is a well-known technique for obtaining the absolute value without a
564
   * branch.  It is derived from an assembly language technique presented in
565
   * "How to Optimize for the Pentium Processors", Copyright (c) 1996, 1997 by
566
   * Agner Fog.  This code assumes we are on a two's complement machine.
567
   */
568
0
  nbits = temp >> (CHAR_BIT * sizeof(int) - 1);
569
0
  temp += nbits;
570
0
  nbits ^= temp;
571
572
  /* Find the number of bits needed for the magnitude of the coefficient */
573
0
  nbits = JPEG_NBITS(nbits);
574
  /* Check for out-of-range coefficient values.
575
   * Since we're encoding a difference, the range limit is twice as much.
576
   */
577
0
  if (nbits > max_coef_bits + 1)
578
0
    ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
579
580
  /* Emit the Huffman-coded symbol for the number of bits.
581
   * Emit that number of bits of the value, if positive,
582
   * or the complement of its magnitude, if negative.
583
   */
584
0
  PUT_CODE(dctbl->ehufco[nbits], dctbl->ehufsi[nbits])
585
586
  /* Encode the AC coefficients per section F.1.2.2 */
587
588
0
  {
589
0
    int r = 0;                  /* r = run length of zeros */
590
591
/* Manually unroll the k loop to eliminate the counter variable.  This
592
 * improves performance greatly on systems with a limited number of
593
 * registers (such as x86.)
594
 */
595
0
#define kloop(jpeg_natural_order_of_k) { \
596
0
  if ((temp = block[jpeg_natural_order_of_k]) == 0) { \
597
0
    r += 16; \
598
0
  } else { \
599
    /* Branch-less absolute value, bitwise complement, etc., same as above */ \
600
0
    nbits = temp >> (CHAR_BIT * sizeof(int) - 1); \
601
0
    temp += nbits; \
602
0
    nbits ^= temp; \
603
0
    nbits = JPEG_NBITS_NONZERO(nbits); \
604
    /* Check for out-of-range coefficient values */ \
605
0
    if (nbits > max_coef_bits) \
606
0
      ERREXIT(state->cinfo, JERR_BAD_DCT_COEF); \
607
    /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \
608
0
    while (r >= 16 * 16) { \
609
0
      r -= 16 * 16; \
610
0
      PUT_BITS(actbl->ehufco[0xf0], actbl->ehufsi[0xf0]) \
611
0
    } \
612
    /* Emit Huffman symbol for run length / number of bits */ \
613
0
    r += nbits; \
614
0
    PUT_CODE(actbl->ehufco[r], actbl->ehufsi[r]) \
615
0
    r = 0; \
616
0
  } \
617
0
}
618
619
    /* One iteration for each value in jpeg_natural_order[] */
620
0
    kloop(1);   kloop(8);   kloop(16);  kloop(9);   kloop(2);   kloop(3);
621
0
    kloop(10);  kloop(17);  kloop(24);  kloop(32);  kloop(25);  kloop(18);
622
0
    kloop(11);  kloop(4);   kloop(5);   kloop(12);  kloop(19);  kloop(26);
623
0
    kloop(33);  kloop(40);  kloop(48);  kloop(41);  kloop(34);  kloop(27);
624
0
    kloop(20);  kloop(13);  kloop(6);   kloop(7);   kloop(14);  kloop(21);
625
0
    kloop(28);  kloop(35);  kloop(42);  kloop(49);  kloop(56);  kloop(57);
626
0
    kloop(50);  kloop(43);  kloop(36);  kloop(29);  kloop(22);  kloop(15);
627
0
    kloop(23);  kloop(30);  kloop(37);  kloop(44);  kloop(51);  kloop(58);
628
0
    kloop(59);  kloop(52);  kloop(45);  kloop(38);  kloop(31);  kloop(39);
629
0
    kloop(46);  kloop(53);  kloop(60);  kloop(61);  kloop(54);  kloop(47);
630
0
    kloop(55);  kloop(62);  kloop(63);
631
632
    /* If the last coef(s) were zero, emit an end-of-block code */
633
0
    if (r > 0) {
634
0
      PUT_BITS(actbl->ehufco[0], actbl->ehufsi[0])
635
0
    }
636
0
  }
637
638
0
  state->cur.put_buffer.c = put_buffer;
639
0
  state->cur.free_bits = free_bits;
640
0
  STORE_BUFFER()
641
642
0
  return TRUE;
643
0
}
644
645
646
/*
647
 * Emit a restart marker & resynchronize predictions.
648
 */
649
650
LOCAL(boolean)
651
emit_restart(working_state *state, int restart_num)
652
0
{
653
0
  int ci;
654
655
0
  if (!flush_bits(state))
656
0
    return FALSE;
657
658
0
  emit_byte(state, 0xFF, return FALSE);
659
0
  emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
660
661
  /* Re-initialize DC predictions to 0 */
662
0
  for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
663
0
    state->cur.last_dc_val[ci] = 0;
664
665
  /* The restart counter is not updated until we successfully write the MCU. */
666
667
0
  return TRUE;
668
0
}
669
670
671
/*
672
 * Encode and output one MCU's worth of Huffman-compressed coefficients.
673
 */
674
675
METHODDEF(boolean)
676
encode_mcu_huff(j_compress_ptr cinfo, JBLOCKROW *MCU_data)
677
2.62M
{
678
2.62M
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
679
2.62M
  working_state state;
680
2.62M
  int blkn, ci;
681
2.62M
  jpeg_component_info *compptr;
682
683
  /* Load up working state */
684
2.62M
  state.next_output_byte = cinfo->dest->next_output_byte;
685
2.62M
  state.free_in_buffer = cinfo->dest->free_in_buffer;
686
2.62M
  state.cur = entropy->saved;
687
2.62M
  state.cinfo = cinfo;
688
2.62M
#ifdef WITH_SIMD
689
2.62M
  state.simd = entropy->simd;
690
2.62M
#endif
691
692
  /* Emit restart marker if needed */
693
2.62M
  if (cinfo->restart_interval) {
694
0
    if (entropy->restarts_to_go == 0)
695
0
      if (!emit_restart(&state, entropy->next_restart_num))
696
0
        return FALSE;
697
0
  }
698
699
  /* Encode the MCU data blocks */
700
2.62M
#ifdef WITH_SIMD
701
2.62M
  if (entropy->simd) {
702
5.25M
    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
703
2.62M
      ci = cinfo->MCU_membership[blkn];
704
2.62M
      compptr = cinfo->cur_comp_info[ci];
705
2.62M
      if (!encode_one_block_simd(&state,
706
2.62M
                                 MCU_data[blkn][0], state.cur.last_dc_val[ci],
707
2.62M
                                 entropy->dc_derived_tbls[compptr->dc_tbl_no],
708
2.62M
                                 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
709
0
        return FALSE;
710
      /* Update last_dc_val */
711
2.62M
      state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
712
2.62M
    }
713
2.62M
  } else
714
0
#endif
715
0
  {
716
0
    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
717
0
      ci = cinfo->MCU_membership[blkn];
718
0
      compptr = cinfo->cur_comp_info[ci];
719
0
      if (!encode_one_block(&state,
720
0
                            MCU_data[blkn][0], state.cur.last_dc_val[ci],
721
0
                            entropy->dc_derived_tbls[compptr->dc_tbl_no],
722
0
                            entropy->ac_derived_tbls[compptr->ac_tbl_no]))
723
0
        return FALSE;
724
      /* Update last_dc_val */
725
0
      state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
726
0
    }
727
0
  }
728
729
  /* Completed MCU, so update state */
730
2.62M
  cinfo->dest->next_output_byte = state.next_output_byte;
731
2.62M
  cinfo->dest->free_in_buffer = state.free_in_buffer;
732
2.62M
  entropy->saved = state.cur;
733
734
  /* Update restart-interval state too */
735
2.62M
  if (cinfo->restart_interval) {
736
0
    if (entropy->restarts_to_go == 0) {
737
0
      entropy->restarts_to_go = cinfo->restart_interval;
738
0
      entropy->next_restart_num++;
739
0
      entropy->next_restart_num &= 7;
740
0
    }
741
0
    entropy->restarts_to_go--;
742
0
  }
743
744
2.62M
  return TRUE;
745
2.62M
}
746
747
748
/*
749
 * Finish up at the end of a Huffman-compressed scan.
750
 */
751
752
METHODDEF(void)
753
finish_pass_huff(j_compress_ptr cinfo)
754
1.30k
{
755
1.30k
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
756
1.30k
  working_state state;
757
758
  /* Load up working state ... flush_bits needs it */
759
1.30k
  state.next_output_byte = cinfo->dest->next_output_byte;
760
1.30k
  state.free_in_buffer = cinfo->dest->free_in_buffer;
761
1.30k
  state.cur = entropy->saved;
762
1.30k
  state.cinfo = cinfo;
763
1.30k
#ifdef WITH_SIMD
764
1.30k
  state.simd = entropy->simd;
765
1.30k
#endif
766
767
  /* Flush out the last data */
768
1.30k
  if (!flush_bits(&state))
769
0
    ERREXIT(cinfo, JERR_CANT_SUSPEND);
770
771
  /* Update state */
772
1.30k
  cinfo->dest->next_output_byte = state.next_output_byte;
773
1.30k
  cinfo->dest->free_in_buffer = state.free_in_buffer;
774
1.30k
  entropy->saved = state.cur;
775
1.30k
}
776
777
778
/*
779
 * Huffman coding optimization.
780
 *
781
 * We first scan the supplied data and count the number of uses of each symbol
782
 * that is to be Huffman-coded. (This process MUST agree with the code above.)
783
 * Then we build a Huffman coding tree for the observed counts.
784
 * Symbols which are not needed at all for the particular image are not
785
 * assigned any code, which saves space in the DHT marker as well as in
786
 * the compressed data.
787
 */
788
789
#ifdef ENTROPY_OPT_SUPPORTED
790
791
792
/* Process a single block's worth of coefficients */
793
794
LOCAL(void)
795
htest_one_block(j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
796
                long dc_counts[], long ac_counts[])
797
2.74M
{
798
2.74M
  register int temp;
799
2.74M
  register int nbits;
800
2.74M
  register int k, r;
801
2.74M
  int max_coef_bits = cinfo->data_precision + 2;
802
803
  /* Encode the DC coefficient difference per section F.1.2.1 */
804
805
2.74M
  temp = block[0] - last_dc_val;
806
2.74M
  if (temp < 0)
807
201k
    temp = -temp;
808
809
  /* Find the number of bits needed for the magnitude of the coefficient */
810
2.74M
  nbits = 0;
811
4.79M
  while (temp) {
812
2.05M
    nbits++;
813
2.05M
    temp >>= 1;
814
2.05M
  }
815
  /* Check for out-of-range coefficient values.
816
   * Since we're encoding a difference, the range limit is twice as much.
817
   */
818
2.74M
  if (nbits > max_coef_bits + 1)
819
300
    ERREXIT(cinfo, JERR_BAD_DCT_COEF);
820
821
  /* Count the Huffman symbol for the number of bits */
822
2.74M
  dc_counts[nbits]++;
823
824
  /* Encode the AC coefficients per section F.1.2.2 */
825
826
2.74M
  r = 0;                        /* r = run length of zeros */
827
828
175M
  for (k = 1; k < DCTSIZE2; k++) {
829
172M
    if ((temp = block[jpeg_natural_order[k]]) == 0) {
830
169M
      r++;
831
169M
    } else {
832
      /* if run length > 15, must emit special run-length-16 codes (0xF0) */
833
3.71M
      while (r > 15) {
834
276k
        ac_counts[0xF0]++;
835
276k
        r -= 16;
836
276k
      }
837
838
      /* Find the number of bits needed for the magnitude of the coefficient */
839
3.44M
      if (temp < 0)
840
2.13M
        temp = -temp;
841
842
      /* Find the number of bits needed for the magnitude of the coefficient */
843
3.44M
      nbits = 1;                /* there must be at least one 1 bit */
844
13.6M
      while ((temp >>= 1))
845
10.2M
        nbits++;
846
      /* Check for out-of-range coefficient values */
847
3.44M
      if (nbits > max_coef_bits)
848
166
        ERREXIT(cinfo, JERR_BAD_DCT_COEF);
849
850
      /* Count Huffman symbol for run length / number of bits */
851
3.44M
      ac_counts[(r << 4) + nbits]++;
852
853
3.44M
      r = 0;
854
3.44M
    }
855
172M
  }
856
857
  /* If the last coef(s) were zero, emit an end-of-block code */
858
2.74M
  if (r > 0)
859
2.72M
    ac_counts[0]++;
860
2.74M
}
861
862
863
/*
864
 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
865
 * No data is actually output, so no suspension return is possible.
866
 */
867
868
METHODDEF(boolean)
869
encode_mcu_gather(j_compress_ptr cinfo, JBLOCKROW *MCU_data)
870
2.74M
{
871
2.74M
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
872
2.74M
  int blkn, ci;
873
2.74M
  jpeg_component_info *compptr;
874
875
  /* Take care of restart intervals if needed */
876
2.74M
  if (cinfo->restart_interval) {
877
0
    if (entropy->restarts_to_go == 0) {
878
      /* Re-initialize DC predictions to 0 */
879
0
      for (ci = 0; ci < cinfo->comps_in_scan; ci++)
880
0
        entropy->saved.last_dc_val[ci] = 0;
881
      /* Update restart state */
882
0
      entropy->restarts_to_go = cinfo->restart_interval;
883
0
    }
884
0
    entropy->restarts_to_go--;
885
0
  }
886
887
5.48M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
888
2.74M
    ci = cinfo->MCU_membership[blkn];
889
2.74M
    compptr = cinfo->cur_comp_info[ci];
890
2.74M
    htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
891
2.74M
                    entropy->dc_count_ptrs[compptr->dc_tbl_no],
892
2.74M
                    entropy->ac_count_ptrs[compptr->ac_tbl_no]);
893
2.74M
    entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
894
2.74M
  }
895
896
2.74M
  return TRUE;
897
2.74M
}
898
899
900
/*
901
 * Generate the best Huffman code table for the given counts, fill htbl.
902
 * Note this is also used by jcphuff.c and jclhuff.c.
903
 *
904
 * The JPEG standard requires that no symbol be assigned a codeword of all
905
 * one bits (so that padding bits added at the end of a compressed segment
906
 * can't look like a valid code).  Because of the canonical ordering of
907
 * codewords, this just means that there must be an unused slot in the
908
 * longest codeword length category.  Annex K (Clause K.2) of
909
 * Rec. ITU-T T.81 (1992) | ISO/IEC 10918-1:1994 suggests reserving such a slot
910
 * by pretending that symbol 256 is a valid symbol with count 1.  In theory
911
 * that's not optimal; giving it count zero but including it in the symbol set
912
 * anyway should give a better Huffman code.  But the theoretically better code
913
 * actually seems to come out worse in practice, because it produces more
914
 * all-ones bytes (which incur stuffed zero bytes in the final file).  In any
915
 * case the difference is tiny.
916
 *
917
 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
918
 * If some symbols have a very small but nonzero probability, the Huffman tree
919
 * must be adjusted to meet the code length restriction.  We currently use
920
 * the adjustment method suggested in JPEG section K.2.  This method is *not*
921
 * optimal; it may not choose the best possible limited-length code.  But
922
 * typically only very-low-frequency symbols will be given less-than-optimal
923
 * lengths, so the code is almost optimal.  Experimental comparisons against
924
 * an optimal limited-length-code algorithm indicate that the difference is
925
 * microscopic --- usually less than a hundredth of a percent of total size.
926
 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
927
 */
928
929
GLOBAL(void)
930
jpeg_gen_optimal_table(j_compress_ptr cinfo, JHUFF_TBL *htbl, long freq[])
931
25.5k
{
932
991k
#define MAX_CLEN  32            /* assumed maximum initial code length */
933
25.5k
  UINT8 bits[MAX_CLEN + 1];     /* bits[k] = # of symbols with code length k */
934
25.5k
  int bit_pos[MAX_CLEN + 1];    /* # of symbols with smaller code length */
935
25.5k
  int codesize[257];            /* codesize[k] = code length of symbol k */
936
25.5k
  int nz_index[257];            /* index of nonzero symbol in the original freq
937
                                   array */
938
25.5k
  int others[257];              /* next symbol in current branch of tree */
939
25.5k
  int c1, c2;
940
25.5k
  int p, i, j;
941
25.5k
  int num_nz_symbols;
942
25.5k
  long v, v2;
943
944
  /* This algorithm is explained in section K.2 of the JPEG standard */
945
946
25.5k
  memset(bits, 0, sizeof(bits));
947
25.5k
  memset(codesize, 0, sizeof(codesize));
948
6.59M
  for (i = 0; i < 257; i++)
949
6.57M
    others[i] = -1;             /* init links to empty */
950
951
25.5k
  freq[256] = 1;                /* make sure 256 has a nonzero count */
952
  /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
953
   * that no real symbol is given code-value of all ones, because 256
954
   * will be placed last in the largest codeword category.
955
   */
956
957
  /* Group nonzero frequencies together so we can more easily find the
958
   * smallest.
959
   */
960
25.5k
  num_nz_symbols = 0;
961
6.59M
  for (i = 0; i < 257; i++) {
962
6.57M
    if (freq[i]) {
963
122k
      nz_index[num_nz_symbols] = i;
964
122k
      freq[num_nz_symbols] = freq[i];
965
122k
      num_nz_symbols++;
966
122k
    }
967
6.57M
  }
968
969
  /* Huffman's basic algorithm to assign optimal code lengths to symbols */
970
971
122k
  for (;;) {
972
    /* Find the two smallest nonzero frequencies; set c1, c2 = their symbols */
973
    /* In case of ties, take the larger symbol number.  Since we have grouped
974
     * the nonzero symbols together, checking for zero symbols is not
975
     * necessary.
976
     */
977
122k
    c1 = -1;
978
122k
    c2 = -1;
979
122k
    v = 1000000000L;
980
122k
    v2 = 1000000000L;
981
2.23M
    for (i = 0; i < num_nz_symbols; i++) {
982
2.11M
      if (freq[i] <= v2) {
983
580k
        if (freq[i] <= v) {
984
437k
          c2 = c1;
985
437k
          v2 = v;
986
437k
          v = freq[i];
987
437k
          c1 = i;
988
437k
        } else {
989
142k
          v2 = freq[i];
990
142k
          c2 = i;
991
142k
        }
992
580k
      }
993
2.11M
    }
994
995
    /* Done if we've merged everything into one frequency */
996
122k
    if (c2 < 0)
997
25.5k
      break;
998
999
    /* Else merge the two counts/trees */
1000
96.6k
    freq[c1] += freq[c2];
1001
    /* Set the frequency to a very high value instead of zero, so we don't have
1002
     * to check for zero values.
1003
     */
1004
96.6k
    freq[c2] = 1000000001L;
1005
1006
    /* Increment the codesize of everything in c1's tree branch */
1007
96.6k
    codesize[c1]++;
1008
267k
    while (others[c1] >= 0) {
1009
171k
      c1 = others[c1];
1010
171k
      codesize[c1]++;
1011
171k
    }
1012
1013
96.6k
    others[c1] = c2;            /* chain c2 onto c1's tree branch */
1014
1015
    /* Increment the codesize of everything in c2's tree branch */
1016
96.6k
    codesize[c2]++;
1017
267k
    while (others[c2] >= 0) {
1018
170k
      c2 = others[c2];
1019
170k
      codesize[c2]++;
1020
170k
    }
1021
96.6k
  }
1022
1023
  /* Now count the number of symbols of each code length */
1024
147k
  for (i = 0; i < num_nz_symbols; i++) {
1025
    /* The JPEG standard seems to think that this can't happen, */
1026
    /* but I'm paranoid... */
1027
122k
    if (codesize[i] > MAX_CLEN)
1028
0
      ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
1029
1030
122k
    bits[codesize[i]]++;
1031
122k
  }
1032
1033
  /* Count the number of symbols with a length smaller than i bits, so we can
1034
   * construct the symbol table more efficiently.  Note that this includes the
1035
   * pseudo-symbol 256, but since it is the last symbol, it will not affect the
1036
   * table.
1037
   */
1038
25.5k
  p = 0;
1039
843k
  for (i = 1; i <= MAX_CLEN; i++) {
1040
818k
    bit_pos[i] = p;
1041
818k
    p += bits[i];
1042
818k
  }
1043
1044
  /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
1045
   * Huffman procedure assigned any such lengths, we must adjust the coding.
1046
   * Here is what Rec. ITU-T T.81 | ISO/IEC 10918-1 says about how this next
1047
   * bit works: Since symbols are paired for the longest Huffman code, the
1048
   * symbols are removed from this length category two at a time.  The prefix
1049
   * for the pair (which is one bit shorter) is allocated to one of the pair;
1050
   * then, skipping the BITS entry for that prefix length, a code word from the
1051
   * next shortest nonzero BITS entry is converted into a prefix for two code
1052
   * words one bit longer.
1053
   */
1054
1055
434k
  for (i = MAX_CLEN; i > 16; i--) {
1056
409k
    while (bits[i] > 0) {
1057
630
      j = i - 2;                /* find length of new prefix to be used */
1058
860
      while (bits[j] == 0)
1059
230
        j--;
1060
1061
630
      bits[i] -= 2;             /* remove two symbols */
1062
630
      bits[i - 1]++;            /* one goes in this length */
1063
630
      bits[j + 1] += 2;         /* two new symbols in this length */
1064
630
      bits[j]--;                /* symbol of this length is now a prefix */
1065
630
    }
1066
409k
  }
1067
1068
  /* Remove the count for the pseudo-symbol 256 from the largest codelength */
1069
372k
  while (bits[i] == 0)          /* find largest codelength still in use */
1070
347k
    i--;
1071
25.5k
  bits[i]--;
1072
1073
  /* Return final symbol counts (only for lengths 0..16) */
1074
25.5k
  memcpy(htbl->bits, bits, sizeof(htbl->bits));
1075
1076
  /* Return a list of the symbols sorted by code length */
1077
  /* It's not real clear to me why we don't need to consider the codelength
1078
   * changes made above, but Rec. ITU-T T.81 | ISO/IEC 10918-1 seems to think
1079
   * this works.
1080
   */
1081
122k
  for (i = 0; i < num_nz_symbols - 1; i++) {
1082
96.6k
    htbl->huffval[bit_pos[codesize[i]]] = (UINT8)nz_index[i];
1083
96.6k
    bit_pos[codesize[i]]++;
1084
96.6k
  }
1085
1086
  /* Set sent_table FALSE so updated table will be written to JPEG file. */
1087
25.5k
  htbl->sent_table = FALSE;
1088
25.5k
}
1089
1090
1091
/*
1092
 * Finish up a statistics-gathering pass and create the new Huffman tables.
1093
 */
1094
1095
METHODDEF(void)
1096
finish_pass_gather(j_compress_ptr cinfo)
1097
1.30k
{
1098
1.30k
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
1099
1.30k
  int ci, dctbl, actbl;
1100
1.30k
  jpeg_component_info *compptr;
1101
1.30k
  JHUFF_TBL **htblptr;
1102
1.30k
  boolean did_dc[NUM_HUFF_TBLS];
1103
1.30k
  boolean did_ac[NUM_HUFF_TBLS];
1104
1105
  /* It's important not to apply jpeg_gen_optimal_table more than once
1106
   * per table, because it clobbers the input frequency counts!
1107
   */
1108
1.30k
  memset(did_dc, 0, sizeof(did_dc));
1109
1.30k
  memset(did_ac, 0, sizeof(did_ac));
1110
1111
2.60k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1112
1.30k
    compptr = cinfo->cur_comp_info[ci];
1113
1.30k
    dctbl = compptr->dc_tbl_no;
1114
1.30k
    actbl = compptr->ac_tbl_no;
1115
1.30k
    if (!did_dc[dctbl]) {
1116
1.30k
      htblptr = &cinfo->dc_huff_tbl_ptrs[dctbl];
1117
1.30k
      if (*htblptr == NULL)
1118
0
        *htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
1119
1.30k
      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
1120
1.30k
      did_dc[dctbl] = TRUE;
1121
1.30k
    }
1122
1.30k
    if (!did_ac[actbl]) {
1123
1.30k
      htblptr = &cinfo->ac_huff_tbl_ptrs[actbl];
1124
1.30k
      if (*htblptr == NULL)
1125
0
        *htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
1126
1.30k
      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
1127
1.30k
      did_ac[actbl] = TRUE;
1128
1.30k
    }
1129
1.30k
  }
1130
1.30k
}
1131
1132
1133
#endif /* ENTROPY_OPT_SUPPORTED */
1134
1135
1136
/*
1137
 * Module initialization routine for Huffman entropy encoding.
1138
 */
1139
1140
GLOBAL(void)
1141
jinit_huff_encoder(j_compress_ptr cinfo)
1142
1.76k
{
1143
1.76k
  huff_entropy_ptr entropy;
1144
1.76k
  int i;
1145
1146
1.76k
  entropy = (huff_entropy_ptr)
1147
1.76k
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
1148
1.76k
                                sizeof(huff_entropy_encoder));
1149
1.76k
  cinfo->entropy = (struct jpeg_entropy_encoder *)entropy;
1150
1.76k
  entropy->pub.start_pass = start_pass_huff;
1151
1152
  /* Mark tables unallocated */
1153
8.84k
  for (i = 0; i < NUM_HUFF_TBLS; i++) {
1154
7.07k
    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
1155
7.07k
#ifdef ENTROPY_OPT_SUPPORTED
1156
    entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
1157
7.07k
#endif
1158
7.07k
  }
1159
1.76k
}