Coverage Report

Created: 2025-08-26 06:41

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