Coverage Report

Created: 2026-04-12 06:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjpeg-turbo.main/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-2026, 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
46.0k
#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
23.0k
{
139
23.0k
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
140
23.0k
  int ci, dctbl, actbl;
141
23.0k
  jpeg_component_info *compptr;
142
143
23.0k
  if (gather_statistics) {
144
11.5k
#ifdef ENTROPY_OPT_SUPPORTED
145
11.5k
    entropy->pub.encode_mcu = encode_mcu_gather;
146
11.5k
    entropy->pub.finish_pass = finish_pass_gather;
147
#else
148
    ERREXIT(cinfo, JERR_NOT_COMPILED);
149
#endif
150
11.5k
  } else {
151
11.5k
    entropy->pub.encode_mcu = encode_mcu_huff;
152
11.5k
    entropy->pub.finish_pass = finish_pass_huff;
153
11.5k
  }
154
155
23.0k
#ifdef WITH_SIMD
156
23.0k
  entropy->simd = jsimd_set_huff_encode_one_block(cinfo);
157
23.0k
#endif
158
159
80.8k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
160
57.8k
    compptr = cinfo->cur_comp_info[ci];
161
57.8k
    dctbl = compptr->dc_tbl_no;
162
57.8k
    actbl = compptr->ac_tbl_no;
163
57.8k
    if (gather_statistics) {
164
28.9k
#ifdef ENTROPY_OPT_SUPPORTED
165
      /* Check for invalid table indexes */
166
      /* (make_c_derived_tbl does this in the other path) */
167
28.9k
      if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
168
0
        ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
169
28.9k
      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
28.9k
      if (entropy->dc_count_ptrs[dctbl] == NULL)
174
20.2k
        entropy->dc_count_ptrs[dctbl] = (long *)
175
20.2k
          (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
176
20.2k
                                      257 * sizeof(long));
177
28.9k
      memset(entropy->dc_count_ptrs[dctbl], 0, 257 * sizeof(long));
178
28.9k
      if (entropy->ac_count_ptrs[actbl] == NULL)
179
20.2k
        entropy->ac_count_ptrs[actbl] = (long *)
180
20.2k
          (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
181
20.2k
                                      257 * sizeof(long));
182
28.9k
      memset(entropy->ac_count_ptrs[actbl], 0, 257 * sizeof(long));
183
28.9k
#endif
184
28.9k
    } 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
28.9k
      jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
188
28.9k
                              &entropy->dc_derived_tbls[dctbl]);
189
28.9k
      jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
190
28.9k
                              &entropy->ac_derived_tbls[actbl]);
191
28.9k
    }
192
    /* Initialize DC predictions to 0 */
193
57.8k
    entropy->saved.last_dc_val[ci] = 0;
194
57.8k
  }
195
196
  /* Initialize bit buffer to empty */
197
23.0k
#ifdef WITH_SIMD
198
23.0k
  if (entropy->simd) {
199
23.0k
    entropy->saved.put_buffer.simd = 0;
200
23.0k
    entropy->saved.free_bits = SIMD_BIT_BUF_SIZE;
201
23.0k
  } 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
23.0k
  entropy->restarts_to_go = cinfo->restart_interval;
210
23.0k
  entropy->next_restart_num = 0;
211
23.0k
}
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
73.8k
{
225
73.8k
  JHUFF_TBL *htbl;
226
73.8k
  c_derived_tbl *dtbl;
227
73.8k
  int p, i, l, lastp, si, maxsymbol;
228
73.8k
  char huffsize[257];
229
73.8k
  unsigned int huffcode[257];
230
73.8k
  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
73.8k
  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
238
0
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
239
73.8k
  htbl =
240
73.8k
    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
241
73.8k
  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
73.8k
  if (*pdtbl == NULL)
246
43.6k
    *pdtbl = (c_derived_tbl *)
247
43.6k
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
248
43.6k
                                  sizeof(c_derived_tbl));
249
73.8k
  dtbl = *pdtbl;
250
251
  /* Figure C.1: make table of Huffman code length for each symbol */
252
253
73.8k
  p = 0;
254
1.25M
  for (l = 1; l <= 16; l++) {
255
1.18M
    i = (int)htbl->bits[l];
256
1.18M
    if (i < 0 || p + i > 256)   /* protect against table overrun */
257
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
258
1.83M
    while (i--)
259
655k
      huffsize[p++] = (char)l;
260
1.18M
  }
261
73.8k
  huffsize[p] = 0;
262
73.8k
  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
73.8k
  code = 0;
268
73.8k
  si = huffsize[0];
269
73.8k
  p = 0;
270
364k
  while (huffsize[p]) {
271
946k
    while (((int)huffsize[p]) == si) {
272
655k
      huffcode[p++] = code;
273
655k
      code++;
274
655k
    }
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
290k
    if (((JLONG)code) >= (((JLONG)1) << si))
279
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
280
290k
    code <<= 1;
281
290k
    si++;
282
290k
  }
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
73.8k
  memset(dtbl->ehufco, 0, sizeof(dtbl->ehufco));
292
73.8k
  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
73.8k
  maxsymbol = isDC ? (cinfo->master->lossless ? 16 : 15) : 255;
300
301
729k
  for (p = 0; p < lastp; p++) {
302
655k
    i = htbl->huffval[p];
303
655k
    if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
304
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
305
655k
    dtbl->ehufco[i] = huffcode[p];
306
655k
    dtbl->ehufsi[i] = huffsize[p];
307
655k
  }
308
73.8k
}
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
3.75k
{
326
3.75k
  struct jpeg_destination_mgr *dest = state->cinfo->dest;
327
328
3.75k
  if (!(*dest->empty_output_buffer) (state->cinfo))
329
0
    return FALSE;
330
  /* After a successful buffer dump, must reset buffer pointers */
331
3.75k
  state->next_output_byte = dest->next_output_byte;
332
3.75k
  state->free_in_buffer = dest->free_in_buffer;
333
3.75k
  return TRUE;
334
3.75k
}
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
49.4k
#define EMIT_BYTE(b) { \
345
49.4k
  buffer[0] = (JOCTET)(b); \
346
49.4k
  buffer[1] = 0; \
347
49.4k
  buffer -= -2 + ((JOCTET)(b) < 0xFF); \
348
49.4k
}
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
14.3M
#define BUFSIZE  (DCTSIZE2 * 8)
438
439
14.3M
#define LOAD_BUFFER() { \
440
14.3M
  if (state->free_in_buffer < BUFSIZE) { \
441
427k
    localbuf = 1; \
442
427k
    buffer = _buffer; \
443
427k
  } else \
444
14.3M
    buffer = state->next_output_byte; \
445
14.3M
}
446
447
14.3M
#define STORE_BUFFER() { \
448
14.3M
  if (localbuf) { \
449
427k
    size_t bytes, bytestocopy; \
450
427k
    bytes = buffer - _buffer; \
451
427k
    buffer = _buffer; \
452
506k
    while (bytes > 0) { \
453
78.7k
      bytestocopy = MIN(bytes, state->free_in_buffer); \
454
78.7k
      memcpy(state->next_output_byte, buffer, bytestocopy); \
455
78.7k
      state->next_output_byte += bytestocopy; \
456
78.7k
      buffer += bytestocopy; \
457
78.7k
      state->free_in_buffer -= bytestocopy; \
458
78.7k
      if (state->free_in_buffer == 0) \
459
78.7k
        if (!dump_buffer(state)) return FALSE; \
460
78.7k
      bytes -= bytestocopy; \
461
78.7k
    } \
462
13.9M
  } else { \
463
13.9M
    state->free_in_buffer -= (buffer - state->next_output_byte); \
464
13.9M
    state->next_output_byte = buffer; \
465
13.9M
  } \
466
14.3M
}
467
468
469
LOCAL(boolean)
470
flush_bits(working_state *state)
471
11.5k
{
472
11.5k
  JOCTET _buffer[BUFSIZE], *buffer, temp;
473
11.5k
  simd_bit_buf_type put_buffer;  int put_bits;
474
11.5k
  int localbuf = 0;
475
476
11.5k
#ifdef WITH_SIMD
477
11.5k
  if (state->simd) {
478
11.5k
    put_bits = SIMD_BIT_BUF_SIZE - state->cur.free_bits;
479
11.5k
    put_buffer = state->cur.put_buffer.simd;
480
11.5k
  } 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
11.5k
  LOAD_BUFFER()
488
489
50.8k
  while (put_bits >= 8) {
490
39.3k
    put_bits -= 8;
491
39.3k
    temp = (JOCTET)(put_buffer >> put_bits);
492
39.3k
    EMIT_BYTE(temp)
493
39.3k
  }
494
11.5k
  if (put_bits) {
495
    /* fill partial byte with ones */
496
10.0k
    temp = (JOCTET)((put_buffer << (8 - put_bits)) | (0xFF >> put_bits));
497
10.0k
    EMIT_BYTE(temp)
498
10.0k
  }
499
500
11.5k
#ifdef WITH_SIMD
501
11.5k
  if (state->simd) {                    /* and reset bit buffer to empty */
502
11.5k
    state->cur.put_buffer.simd = 0;
503
11.5k
    state->cur.free_bits = SIMD_BIT_BUF_SIZE;
504
11.5k
  } 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
11.5k
  STORE_BUFFER()
511
512
11.5k
  return TRUE;
513
11.5k
}
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
14.3M
{
524
14.3M
  JOCTET _buffer[BUFSIZE], *buffer;
525
14.3M
  int localbuf = 0;
526
527
#ifdef ZERO_BUFFERS
528
  memset(_buffer, 0, sizeof(_buffer));
529
#endif
530
531
14.3M
  LOAD_BUFFER()
532
533
14.3M
  buffer = state->cinfo->entropy->huff_encode_one_block_simd(state, buffer,
534
14.3M
                                                             block,
535
14.3M
                                                             last_dc_val,
536
14.3M
                                                             dctbl, actbl);
537
538
14.3M
  STORE_BUFFER()
539
540
14.3M
  return TRUE;
541
14.3M
}
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
4.63M
{
678
4.63M
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
679
4.63M
  working_state state;
680
4.63M
  int blkn, ci;
681
4.63M
  jpeg_component_info *compptr;
682
683
  /* Load up working state */
684
4.63M
  state.next_output_byte = cinfo->dest->next_output_byte;
685
4.63M
  state.free_in_buffer = cinfo->dest->free_in_buffer;
686
4.63M
  state.cur = entropy->saved;
687
4.63M
  state.cinfo = cinfo;
688
4.63M
#ifdef WITH_SIMD
689
4.63M
  state.simd = entropy->simd;
690
4.63M
#endif
691
692
  /* Emit restart marker if needed */
693
4.63M
  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
4.63M
#ifdef WITH_SIMD
701
4.63M
  if (entropy->simd) {
702
18.9M
    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
703
14.3M
      ci = cinfo->MCU_membership[blkn];
704
14.3M
      compptr = cinfo->cur_comp_info[ci];
705
14.3M
      if (!encode_one_block_simd(&state,
706
14.3M
                                 MCU_data[blkn][0], state.cur.last_dc_val[ci],
707
14.3M
                                 entropy->dc_derived_tbls[compptr->dc_tbl_no],
708
14.3M
                                 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
709
0
        return FALSE;
710
      /* Update last_dc_val */
711
14.3M
      state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
712
14.3M
    }
713
4.63M
  } 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
4.63M
  cinfo->dest->next_output_byte = state.next_output_byte;
731
4.63M
  cinfo->dest->free_in_buffer = state.free_in_buffer;
732
4.63M
  entropy->saved = state.cur;
733
734
  /* Update restart-interval state too */
735
4.63M
  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
4.63M
  return TRUE;
745
4.63M
}
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
11.5k
{
755
11.5k
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
756
11.5k
  working_state state;
757
758
  /* Load up working state ... flush_bits needs it */
759
11.5k
  state.next_output_byte = cinfo->dest->next_output_byte;
760
11.5k
  state.free_in_buffer = cinfo->dest->free_in_buffer;
761
11.5k
  state.cur = entropy->saved;
762
11.5k
  state.cinfo = cinfo;
763
11.5k
#ifdef WITH_SIMD
764
11.5k
  state.simd = entropy->simd;
765
11.5k
#endif
766
767
  /* Flush out the last data */
768
11.5k
  if (!flush_bits(&state))
769
0
    ERREXIT(cinfo, JERR_CANT_SUSPEND);
770
771
  /* Update state */
772
11.5k
  cinfo->dest->next_output_byte = state.next_output_byte;
773
11.5k
  cinfo->dest->free_in_buffer = state.free_in_buffer;
774
11.5k
  entropy->saved = state.cur;
775
11.5k
}
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
14.3M
{
798
14.3M
  register int temp;
799
14.3M
  register int nbits;
800
14.3M
  register int k, r;
801
14.3M
  int max_coef_bits = cinfo->data_precision + 2;
802
803
  /* Encode the DC coefficient difference per section F.1.2.1 */
804
805
14.3M
  temp = block[0] - last_dc_val;
806
14.3M
  if (temp < 0)
807
2.25M
    temp = -temp;
808
809
  /* Find the number of bits needed for the magnitude of the coefficient */
810
14.3M
  nbits = 0;
811
52.7M
  while (temp) {
812
38.4M
    nbits++;
813
38.4M
    temp >>= 1;
814
38.4M
  }
815
  /* Check for out-of-range coefficient values.
816
   * Since we're encoding a difference, the range limit is twice as much.
817
   */
818
14.3M
  if (nbits > max_coef_bits + 1)
819
0
    ERREXIT(cinfo, JERR_BAD_DCT_COEF);
820
821
  /* Count the Huffman symbol for the number of bits */
822
14.3M
  dc_counts[nbits]++;
823
824
  /* Encode the AC coefficients per section F.1.2.2 */
825
826
14.3M
  r = 0;                        /* r = run length of zeros */
827
828
917M
  for (k = 1; k < DCTSIZE2; k++) {
829
903M
    if ((temp = block[jpeg_natural_order[k]]) == 0) {
830
682M
      r++;
831
682M
    } else {
832
      /* if run length > 15, must emit special run-length-16 codes (0xF0) */
833
220M
      while (r > 15) {
834
1.39k
        ac_counts[0xF0]++;
835
1.39k
        r -= 16;
836
1.39k
      }
837
838
      /* Find the number of bits needed for the magnitude of the coefficient */
839
220M
      if (temp < 0)
840
111M
        temp = -temp;
841
842
      /* Find the number of bits needed for the magnitude of the coefficient */
843
220M
      nbits = 1;                /* there must be at least one 1 bit */
844
1.23G
      while ((temp >>= 1))
845
1.01G
        nbits++;
846
      /* Check for out-of-range coefficient values */
847
220M
      if (nbits > max_coef_bits)
848
0
        ERREXIT(cinfo, JERR_BAD_DCT_COEF);
849
850
      /* Count Huffman symbol for run length / number of bits */
851
220M
      ac_counts[(r << 4) + nbits]++;
852
853
220M
      r = 0;
854
220M
    }
855
903M
  }
856
857
  /* If the last coef(s) were zero, emit an end-of-block code */
858
14.3M
  if (r > 0)
859
11.2M
    ac_counts[0]++;
860
14.3M
}
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
4.63M
{
871
4.63M
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
872
4.63M
  int blkn, ci;
873
4.63M
  jpeg_component_info *compptr;
874
875
  /* Take care of restart intervals if needed */
876
4.63M
  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
18.9M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
888
14.3M
    ci = cinfo->MCU_membership[blkn];
889
14.3M
    compptr = cinfo->cur_comp_info[ci];
890
14.3M
    htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
891
14.3M
                    entropy->dc_count_ptrs[compptr->dc_tbl_no],
892
14.3M
                    entropy->ac_count_ptrs[compptr->ac_tbl_no]);
893
14.3M
    entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
894
14.3M
  }
895
896
4.63M
  return TRUE;
897
4.63M
}
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
56.4k
{
932
2.52M
#define MAX_CLEN  32            /* assumed maximum initial code length */
933
  /* The array length is MAX_CLEN + 2 rather than MAX_CLEN + 1 to work around a
934
   * -Wstringop-overflow false positive with GCC 12 and later.
935
   */
936
56.4k
  UINT8 bits[MAX_CLEN + 2];     /* bits[k] = # of symbols with code length k */
937
56.4k
  int bit_pos[MAX_CLEN + 1];    /* # of symbols with smaller code length */
938
56.4k
  int codesize[257];            /* codesize[k] = code length of symbol k */
939
56.4k
  int nz_index[257];            /* index of nonzero symbol in the original freq
940
                                   array */
941
56.4k
  int others[257];              /* next symbol in current branch of tree */
942
56.4k
  int c1, c2;
943
56.4k
  int p, i, j;
944
56.4k
  int num_nz_symbols;
945
56.4k
  long v, v2;
946
947
  /* This algorithm is explained in section K.2 of the JPEG standard */
948
949
56.4k
  memset(bits, 0, sizeof(bits));
950
56.4k
  memset(codesize, 0, sizeof(codesize));
951
14.5M
  for (i = 0; i < 257; i++)
952
14.5M
    others[i] = -1;             /* init links to empty */
953
954
56.4k
  freq[256] = 1;                /* make sure 256 has a nonzero count */
955
  /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
956
   * that no real symbol is given code-value of all ones, because 256
957
   * will be placed last in the largest codeword category.
958
   */
959
960
  /* Group nonzero frequencies together so we can more easily find the
961
   * smallest.
962
   */
963
56.4k
  num_nz_symbols = 0;
964
14.5M
  for (i = 0; i < 257; i++) {
965
14.5M
    if (freq[i]) {
966
602k
      nz_index[num_nz_symbols] = i;
967
602k
      freq[num_nz_symbols] = freq[i];
968
602k
      num_nz_symbols++;
969
602k
    }
970
14.5M
  }
971
972
  /* Huffman's basic algorithm to assign optimal code lengths to symbols */
973
974
602k
  for (;;) {
975
    /* Find the two smallest nonzero frequencies; set c1, c2 = their symbols */
976
    /* In case of ties, take the larger symbol number.  Since we have grouped
977
     * the nonzero symbols together, checking for zero symbols is not
978
     * necessary.
979
     */
980
602k
    c1 = -1;
981
602k
    c2 = -1;
982
602k
    v = 1000000000L;
983
602k
    v2 = 1000000000L;
984
14.9M
    for (i = 0; i < num_nz_symbols; i++) {
985
14.3M
      if (freq[i] <= v2) {
986
3.48M
        if (freq[i] <= v) {
987
2.33M
          c2 = c1;
988
2.33M
          v2 = v;
989
2.33M
          v = freq[i];
990
2.33M
          c1 = i;
991
2.33M
        } else {
992
1.14M
          v2 = freq[i];
993
1.14M
          c2 = i;
994
1.14M
        }
995
3.48M
      }
996
14.3M
    }
997
998
    /* Done if we've merged everything into one frequency */
999
602k
    if (c2 < 0)
1000
56.4k
      break;
1001
1002
    /* Else merge the two counts/trees */
1003
545k
    freq[c1] += freq[c2];
1004
    /* Set the frequency to a very high value instead of zero, so we don't have
1005
     * to check for zero values.
1006
     */
1007
545k
    freq[c2] = 1000000001L;
1008
1009
    /* Increment the codesize of everything in c1's tree branch */
1010
545k
    codesize[c1]++;
1011
1.64M
    while (others[c1] >= 0) {
1012
1.10M
      c1 = others[c1];
1013
1.10M
      codesize[c1]++;
1014
1.10M
    }
1015
1016
545k
    others[c1] = c2;            /* chain c2 onto c1's tree branch */
1017
1018
    /* Increment the codesize of everything in c2's tree branch */
1019
545k
    codesize[c2]++;
1020
1.76M
    while (others[c2] >= 0) {
1021
1.22M
      c2 = others[c2];
1022
1.22M
      codesize[c2]++;
1023
1.22M
    }
1024
545k
  }
1025
1026
  /* Now count the number of symbols of each code length */
1027
658k
  for (i = 0; i < num_nz_symbols; i++) {
1028
    /* The JPEG standard seems to think that this can't happen, */
1029
    /* but I'm paranoid... */
1030
602k
    if (codesize[i] > MAX_CLEN)
1031
0
      ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
1032
1033
602k
    bits[codesize[i]]++;
1034
602k
  }
1035
1036
  /* Count the number of symbols with a length smaller than i bits, so we can
1037
   * construct the symbol table more efficiently.  Note that this includes the
1038
   * pseudo-symbol 256, but since it is the last symbol, it will not affect the
1039
   * table.
1040
   */
1041
56.4k
  p = 0;
1042
1.86M
  for (i = 1; i <= MAX_CLEN; i++) {
1043
1.80M
    bit_pos[i] = p;
1044
1.80M
    p += bits[i];
1045
1.80M
  }
1046
1047
  /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
1048
   * Huffman procedure assigned any such lengths, we must adjust the coding.
1049
   * Here is what Rec. ITU-T T.81 | ISO/IEC 10918-1 says about how this next
1050
   * bit works: Since symbols are paired for the longest Huffman code, the
1051
   * symbols are removed from this length category two at a time.  The prefix
1052
   * for the pair (which is one bit shorter) is allocated to one of the pair;
1053
   * then, skipping the BITS entry for that prefix length, a code word from the
1054
   * next shortest nonzero BITS entry is converted into a prefix for two code
1055
   * words one bit longer.
1056
   */
1057
1058
959k
  for (i = MAX_CLEN; i > 16; i--) {
1059
912k
    while (bits[i] > 0) {
1060
8.91k
      j = i - 2;                /* find length of new prefix to be used */
1061
11.3k
      while (bits[j] == 0)
1062
2.43k
        j--;
1063
1064
8.91k
      bits[i] -= 2;             /* remove two symbols */
1065
8.91k
      bits[i - 1]++;            /* one goes in this length */
1066
8.91k
      bits[j + 1] += 2;         /* two new symbols in this length */
1067
8.91k
      bits[j]--;                /* symbol of this length is now a prefix */
1068
8.91k
    }
1069
903k
  }
1070
1071
  /* Remove the count for the pseudo-symbol 256 from the largest codelength */
1072
692k
  while (bits[i] == 0)          /* find largest codelength still in use */
1073
635k
    i--;
1074
56.4k
  bits[i]--;
1075
1076
  /* Return final symbol counts (only for lengths 0..16) */
1077
56.4k
  memcpy(htbl->bits, bits, sizeof(htbl->bits));
1078
1079
  /* Return a list of the symbols sorted by code length */
1080
  /* It's not real clear to me why we don't need to consider the codelength
1081
   * changes made above, but Rec. ITU-T T.81 | ISO/IEC 10918-1 seems to think
1082
   * this works.
1083
   */
1084
602k
  for (i = 0; i < num_nz_symbols - 1; i++) {
1085
545k
    htbl->huffval[bit_pos[codesize[i]]] = (UINT8)nz_index[i];
1086
545k
    bit_pos[codesize[i]]++;
1087
545k
  }
1088
1089
  /* Set sent_table FALSE so updated table will be written to JPEG file. */
1090
56.4k
  htbl->sent_table = FALSE;
1091
56.4k
}
1092
1093
1094
/*
1095
 * Finish up a statistics-gathering pass and create the new Huffman tables.
1096
 */
1097
1098
METHODDEF(void)
1099
finish_pass_gather(j_compress_ptr cinfo)
1100
11.5k
{
1101
11.5k
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
1102
11.5k
  int ci, dctbl, actbl;
1103
11.5k
  jpeg_component_info *compptr;
1104
11.5k
  JHUFF_TBL **htblptr;
1105
11.5k
  boolean did_dc[NUM_HUFF_TBLS];
1106
11.5k
  boolean did_ac[NUM_HUFF_TBLS];
1107
1108
  /* It's important not to apply jpeg_gen_optimal_table more than once
1109
   * per table, because it clobbers the input frequency counts!
1110
   */
1111
11.5k
  memset(did_dc, 0, sizeof(did_dc));
1112
11.5k
  memset(did_ac, 0, sizeof(did_ac));
1113
1114
40.4k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1115
28.9k
    compptr = cinfo->cur_comp_info[ci];
1116
28.9k
    dctbl = compptr->dc_tbl_no;
1117
28.9k
    actbl = compptr->ac_tbl_no;
1118
28.9k
    if (!did_dc[dctbl]) {
1119
20.2k
      htblptr = &cinfo->dc_huff_tbl_ptrs[dctbl];
1120
20.2k
      if (*htblptr == NULL)
1121
0
        *htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
1122
20.2k
      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
1123
20.2k
      did_dc[dctbl] = TRUE;
1124
20.2k
    }
1125
28.9k
    if (!did_ac[actbl]) {
1126
20.2k
      htblptr = &cinfo->ac_huff_tbl_ptrs[actbl];
1127
20.2k
      if (*htblptr == NULL)
1128
0
        *htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
1129
20.2k
      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
1130
20.2k
      did_ac[actbl] = TRUE;
1131
20.2k
    }
1132
28.9k
  }
1133
11.5k
}
1134
1135
1136
#endif /* ENTROPY_OPT_SUPPORTED */
1137
1138
1139
/*
1140
 * Module initialization routine for Huffman entropy encoding.
1141
 */
1142
1143
GLOBAL(void)
1144
jinit_huff_encoder(j_compress_ptr cinfo)
1145
11.5k
{
1146
11.5k
  huff_entropy_ptr entropy;
1147
11.5k
  int i;
1148
1149
11.5k
  entropy = (huff_entropy_ptr)
1150
11.5k
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
1151
11.5k
                                sizeof(huff_entropy_encoder));
1152
11.5k
  cinfo->entropy = (struct jpeg_entropy_encoder *)entropy;
1153
11.5k
  entropy->pub.start_pass = start_pass_huff;
1154
1155
  /* Mark tables unallocated */
1156
57.6k
  for (i = 0; i < NUM_HUFF_TBLS; i++) {
1157
46.0k
    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
1158
46.0k
#ifdef ENTROPY_OPT_SUPPORTED
1159
    entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
1160
46.0k
#endif
1161
46.0k
  }
1162
11.5k
}