Coverage Report

Created: 2025-07-01 06:27

/src/libjpeg-turbo.main/src/jcphuff.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * jcphuff.c
3
 *
4
 * This file was part of the Independent JPEG Group's software:
5
 * Copyright (C) 1995-1997, Thomas G. Lane.
6
 * Lossless JPEG Modifications:
7
 * Copyright (C) 1999, Ken Murchison.
8
 * libjpeg-turbo Modifications:
9
 * Copyright (C) 2011, 2015, 2018, 2021-2022, 2024, D. R. Commander.
10
 * Copyright (C) 2016, 2018, 2022, Matthieu Darbois.
11
 * Copyright (C) 2020, Arm Limited.
12
 * Copyright (C) 2021, Alex Richardson.
13
 * For conditions of distribution and use, see the accompanying README.ijg
14
 * file.
15
 *
16
 * This file contains Huffman entropy encoding routines for progressive JPEG.
17
 *
18
 * We do not support output suspension in this module, since the library
19
 * currently does not allow multiple-scan files to be written with output
20
 * suspension.
21
 */
22
23
#define JPEG_INTERNALS
24
#include "jinclude.h"
25
#include "jpeglib.h"
26
#ifdef WITH_SIMD
27
#include "jsimd.h"
28
#else
29
#include "jchuff.h"             /* Declarations shared with jc*huff.c */
30
#endif
31
#include <limits.h>
32
33
#ifdef HAVE_INTRIN_H
34
#include <intrin.h>
35
#ifdef _MSC_VER
36
#ifdef HAVE_BITSCANFORWARD64
37
#pragma intrinsic(_BitScanForward64)
38
#endif
39
#ifdef HAVE_BITSCANFORWARD
40
#pragma intrinsic(_BitScanForward)
41
#endif
42
#endif
43
#endif
44
45
#ifdef C_PROGRESSIVE_SUPPORTED
46
47
#include "jpeg_nbits.h"
48
49
50
/* Expanded entropy encoder object for progressive Huffman encoding. */
51
52
typedef struct {
53
  struct jpeg_entropy_encoder pub; /* public fields */
54
55
  /* Pointer to routine to prepare data for encode_mcu_AC_first() */
56
  void (*AC_first_prepare) (const JCOEF *block,
57
                            const int *jpeg_natural_order_start, int Sl,
58
                            int Al, UJCOEF *values, size_t *zerobits);
59
  /* Pointer to routine to prepare data for encode_mcu_AC_refine() */
60
  int (*AC_refine_prepare) (const JCOEF *block,
61
                            const int *jpeg_natural_order_start, int Sl,
62
                            int Al, UJCOEF *absvalues, size_t *bits);
63
64
  /* Mode flag: TRUE for optimization, FALSE for actual data output */
65
  boolean gather_statistics;
66
67
  /* Bit-level coding status.
68
   * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
69
   */
70
  JOCTET *next_output_byte;     /* => next byte to write in buffer */
71
  size_t free_in_buffer;        /* # of byte spaces remaining in buffer */
72
  size_t put_buffer;            /* current bit-accumulation buffer */
73
  int put_bits;                 /* # of bits now in it */
74
  j_compress_ptr cinfo;         /* link to cinfo (needed for dump_buffer) */
75
76
  /* Coding status for DC components */
77
  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
78
79
  /* Coding status for AC components */
80
  int ac_tbl_no;                /* the table number of the single component */
81
  unsigned int EOBRUN;          /* run length of EOBs */
82
  unsigned int BE;              /* # of buffered correction bits before MCU */
83
  char *bit_buffer;             /* buffer for correction bits (1 per char) */
84
  /* packing correction bits tightly would save some space but cost time... */
85
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
   * Since any one scan codes only DC or only AC, we only need one set
91
   * of tables, not one for DC and one for AC.
92
   */
93
  c_derived_tbl *derived_tbls[NUM_HUFF_TBLS];
94
95
  /* Statistics tables for optimization; again, one set is enough */
96
  long *count_ptrs[NUM_HUFF_TBLS];
97
} phuff_entropy_encoder;
98
99
typedef phuff_entropy_encoder *phuff_entropy_ptr;
100
101
/* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
102
 * buffer can hold.  Larger sizes may slightly improve compression, but
103
 * 1000 is already well into the realm of overkill.
104
 * The minimum safe size is 64 bits.
105
 */
106
107
279M
#define MAX_CORR_BITS  1000     /* Max # of correction bits I can buffer */
108
109
/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than JLONG.
110
 * We assume that int right shift is unsigned if JLONG right shift is,
111
 * which should be safe.
112
 */
113
114
#ifdef RIGHT_SHIFT_IS_UNSIGNED
115
#define ISHIFT_TEMPS    int ishift_temp;
116
#define IRIGHT_SHIFT(x, shft) \
117
  ((ishift_temp = (x)) < 0 ? \
118
   (ishift_temp >> (shft)) | ((~0) << (16 - (shft))) : \
119
   (ishift_temp >> (shft)))
120
#else
121
#define ISHIFT_TEMPS
122
189M
#define IRIGHT_SHIFT(x, shft)   ((x) >> (shft))
123
#endif
124
125
566M
#define PAD(v, p)  ((v + (p) - 1) & (~((p) - 1)))
126
127
/* Forward declarations */
128
METHODDEF(boolean) encode_mcu_DC_first(j_compress_ptr cinfo,
129
                                       JBLOCKROW *MCU_data);
130
METHODDEF(void) encode_mcu_AC_first_prepare
131
  (const JCOEF *block, const int *jpeg_natural_order_start, int Sl, int Al,
132
   UJCOEF *values, size_t *zerobits);
133
METHODDEF(boolean) encode_mcu_AC_first(j_compress_ptr cinfo,
134
                                       JBLOCKROW *MCU_data);
135
METHODDEF(boolean) encode_mcu_DC_refine(j_compress_ptr cinfo,
136
                                        JBLOCKROW *MCU_data);
137
METHODDEF(int) encode_mcu_AC_refine_prepare
138
  (const JCOEF *block, const int *jpeg_natural_order_start, int Sl, int Al,
139
   UJCOEF *absvalues, size_t *bits);
140
METHODDEF(boolean) encode_mcu_AC_refine(j_compress_ptr cinfo,
141
                                        JBLOCKROW *MCU_data);
142
METHODDEF(void) finish_pass_phuff(j_compress_ptr cinfo);
143
METHODDEF(void) finish_pass_gather_phuff(j_compress_ptr cinfo);
144
145
146
/* Count bit loop zeroes */
147
INLINE
148
METHODDEF(int)
149
count_zeroes(size_t *x)
150
1.04G
{
151
1.04G
#if defined(HAVE_BUILTIN_CTZL)
152
1.04G
  int result;
153
1.04G
  result = __builtin_ctzl(*x);
154
1.04G
  *x >>= result;
155
#elif defined(HAVE_BITSCANFORWARD64)
156
  unsigned long result;
157
  _BitScanForward64(&result, *x);
158
  *x >>= result;
159
#elif defined(HAVE_BITSCANFORWARD)
160
  unsigned long result;
161
  _BitScanForward(&result, *x);
162
  *x >>= result;
163
#else
164
  int result = 0;
165
  while ((*x & 1) == 0) {
166
    ++result;
167
    *x >>= 1;
168
  }
169
#endif
170
1.04G
  return (int)result;
171
1.04G
}
172
173
174
/*
175
 * Initialize for a Huffman-compressed scan using progressive JPEG.
176
 */
177
178
METHODDEF(void)
179
start_pass_phuff(j_compress_ptr cinfo, boolean gather_statistics)
180
397k
{
181
397k
  phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
182
397k
  boolean is_DC_band;
183
397k
  int ci, tbl;
184
397k
  jpeg_component_info *compptr;
185
186
397k
  entropy->cinfo = cinfo;
187
397k
  entropy->gather_statistics = gather_statistics;
188
189
397k
  is_DC_band = (cinfo->Ss == 0);
190
191
  /* We assume jcmaster.c already validated the scan parameters. */
192
193
  /* Select execution routines */
194
397k
  if (cinfo->Ah == 0) {
195
212k
    if (is_DC_band)
196
48.2k
      entropy->pub.encode_mcu = encode_mcu_DC_first;
197
163k
    else
198
163k
      entropy->pub.encode_mcu = encode_mcu_AC_first;
199
212k
#ifdef WITH_SIMD
200
212k
    if (jsimd_can_encode_mcu_AC_first_prepare())
201
212k
      entropy->AC_first_prepare = jsimd_encode_mcu_AC_first_prepare;
202
0
    else
203
0
#endif
204
0
      entropy->AC_first_prepare = encode_mcu_AC_first_prepare;
205
212k
  } else {
206
185k
    if (is_DC_band)
207
23.0k
      entropy->pub.encode_mcu = encode_mcu_DC_refine;
208
162k
    else {
209
162k
      entropy->pub.encode_mcu = encode_mcu_AC_refine;
210
162k
#ifdef WITH_SIMD
211
162k
      if (jsimd_can_encode_mcu_AC_refine_prepare())
212
162k
        entropy->AC_refine_prepare = jsimd_encode_mcu_AC_refine_prepare;
213
0
      else
214
0
#endif
215
0
        entropy->AC_refine_prepare = encode_mcu_AC_refine_prepare;
216
      /* AC refinement needs a correction bit buffer */
217
162k
      if (entropy->bit_buffer == NULL)
218
23.0k
        entropy->bit_buffer = (char *)
219
23.0k
          (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
220
23.0k
                                      MAX_CORR_BITS * sizeof(char));
221
162k
    }
222
185k
  }
223
397k
  if (gather_statistics)
224
188k
    entropy->pub.finish_pass = finish_pass_gather_phuff;
225
209k
  else
226
209k
    entropy->pub.finish_pass = finish_pass_phuff;
227
228
  /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
229
   * for AC coefficients.
230
   */
231
897k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
232
500k
    compptr = cinfo->cur_comp_info[ci];
233
    /* Initialize DC predictions to 0 */
234
500k
    entropy->last_dc_val[ci] = 0;
235
    /* Get table index */
236
500k
    if (is_DC_band) {
237
173k
      if (cinfo->Ah != 0)       /* DC refinement needs no table */
238
56.9k
        continue;
239
116k
      tbl = compptr->dc_tbl_no;
240
326k
    } else {
241
326k
      entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
242
326k
    }
243
443k
    if (gather_statistics) {
244
      /* Check for invalid table index */
245
      /* (make_c_derived_tbl does this in the other path) */
246
222k
      if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
247
0
        ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
248
      /* Allocate and zero the statistics tables */
249
      /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
250
222k
      if (entropy->count_ptrs[tbl] == NULL)
251
41.1k
        entropy->count_ptrs[tbl] = (long *)
252
41.1k
          (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
253
41.1k
                                      257 * sizeof(long));
254
222k
      memset(entropy->count_ptrs[tbl], 0, 257 * sizeof(long));
255
222k
    } else {
256
      /* Compute derived values for Huffman table */
257
      /* We may do this more than once for a table, but it's not expensive */
258
220k
      jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
259
220k
                              &entropy->derived_tbls[tbl]);
260
220k
    }
261
443k
  }
262
263
  /* Initialize AC stuff */
264
397k
  entropy->EOBRUN = 0;
265
397k
  entropy->BE = 0;
266
267
  /* Initialize bit buffer to empty */
268
397k
  entropy->put_buffer = 0;
269
397k
  entropy->put_bits = 0;
270
271
  /* Initialize restart stuff */
272
397k
  entropy->restarts_to_go = cinfo->restart_interval;
273
397k
  entropy->next_restart_num = 0;
274
397k
}
275
276
277
/* Outputting bytes to the file.
278
 * NB: these must be called only when actually outputting,
279
 * that is, entropy->gather_statistics == FALSE.
280
 */
281
282
/* Emit a byte */
283
299M
#define emit_byte(entropy, val) { \
284
299M
  *(entropy)->next_output_byte++ = (JOCTET)(val); \
285
299M
  if (--(entropy)->free_in_buffer == 0) \
286
299M
    dump_buffer(entropy); \
287
299M
}
288
289
290
LOCAL(void)
291
dump_buffer(phuff_entropy_ptr entropy)
292
/* Empty the output buffer; we do not support suspension in this module. */
293
1.95k
{
294
1.95k
  struct jpeg_destination_mgr *dest = entropy->cinfo->dest;
295
296
1.95k
  if (!(*dest->empty_output_buffer) (entropy->cinfo))
297
0
    ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
298
  /* After a successful buffer dump, must reset buffer pointers */
299
1.95k
  entropy->next_output_byte = dest->next_output_byte;
300
1.95k
  entropy->free_in_buffer = dest->free_in_buffer;
301
1.95k
}
302
303
304
/* Outputting bits to the file */
305
306
/* Only the right 24 bits of put_buffer are used; the valid bits are
307
 * left-justified in this part.  At most 16 bits can be passed to emit_bits
308
 * in one call, and we never retain more than 7 bits in put_buffer
309
 * between calls, so 24 bits are sufficient.
310
 */
311
312
LOCAL(void)
313
emit_bits(phuff_entropy_ptr entropy, unsigned int code, int size)
314
/* Emit some bits, unless we are in gather mode */
315
1.26G
{
316
  /* This routine is heavily used, so it's worth coding tightly. */
317
1.26G
  register size_t put_buffer = (size_t)code;
318
1.26G
  register int put_bits = entropy->put_bits;
319
320
  /* if size is 0, caller used an invalid Huffman table entry */
321
1.26G
  if (size == 0)
322
0
    ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
323
324
1.26G
  if (entropy->gather_statistics)
325
247M
    return;                     /* do nothing if we're only getting stats */
326
327
1.02G
  put_buffer &= (((size_t)1) << size) - 1; /* mask off any extra bits in code */
328
329
1.02G
  put_bits += size;             /* new number of bits in buffer */
330
331
1.02G
  put_buffer <<= 24 - put_bits; /* align incoming bits */
332
333
1.02G
  put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
334
335
1.26G
  while (put_bits >= 8) {
336
247M
    int c = (int)((put_buffer >> 16) & 0xFF);
337
338
247M
    emit_byte(entropy, c);
339
247M
    if (c == 0xFF) {            /* need to stuff a zero byte? */
340
1.33M
      emit_byte(entropy, 0);
341
1.33M
    }
342
247M
    put_buffer <<= 8;
343
247M
    put_bits -= 8;
344
247M
  }
345
346
1.02G
  entropy->put_buffer = put_buffer; /* update variables */
347
1.02G
  entropy->put_bits = put_bits;
348
1.02G
}
349
350
351
LOCAL(void)
352
flush_bits(phuff_entropy_ptr entropy)
353
25.5M
{
354
25.5M
  emit_bits(entropy, 0x7F, 7); /* fill any partial byte with ones */
355
25.5M
  entropy->put_buffer = 0;     /* and reset bit-buffer to empty */
356
25.5M
  entropy->put_bits = 0;
357
25.5M
}
358
359
360
/*
361
 * Emit (or just count) a Huffman symbol.
362
 */
363
364
LOCAL(void)
365
emit_symbol(phuff_entropy_ptr entropy, int tbl_no, int symbol)
366
697M
{
367
697M
  if (entropy->gather_statistics)
368
350M
    entropy->count_ptrs[tbl_no][symbol]++;
369
347M
  else {
370
347M
    c_derived_tbl *tbl = entropy->derived_tbls[tbl_no];
371
347M
    emit_bits(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
372
347M
  }
373
697M
}
374
375
376
/*
377
 * Emit bits from a correction bit buffer.
378
 */
379
380
LOCAL(void)
381
emit_buffered_bits(phuff_entropy_ptr entropy, char *bufstart,
382
                   unsigned int nbits)
383
188M
{
384
188M
  if (entropy->gather_statistics)
385
94.3M
    return;                     /* no real work */
386
387
408M
  while (nbits > 0) {
388
314M
    emit_bits(entropy, (unsigned int)(*bufstart), 1);
389
314M
    bufstart++;
390
314M
    nbits--;
391
314M
  }
392
94.3M
}
393
394
395
/*
396
 * Emit any pending EOBRUN symbol.
397
 */
398
399
LOCAL(void)
400
emit_eobrun(phuff_entropy_ptr entropy)
401
179M
{
402
179M
  register int temp, nbits;
403
404
179M
  if (entropy->EOBRUN > 0) {    /* if there is any pending EOBRUN */
405
81.1M
    temp = entropy->EOBRUN;
406
81.1M
    nbits = JPEG_NBITS_NONZERO(temp) - 1;
407
    /* safety check: shouldn't happen given limited correction-bit buffer */
408
81.1M
    if (nbits > 14)
409
0
      ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
410
411
81.1M
    emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
412
81.1M
    if (nbits)
413
39.5M
      emit_bits(entropy, entropy->EOBRUN, nbits);
414
415
81.1M
    entropy->EOBRUN = 0;
416
417
    /* Emit any buffered correction bits */
418
81.1M
    emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
419
81.1M
    entropy->BE = 0;
420
81.1M
  }
421
179M
}
422
423
424
/*
425
 * Emit a restart marker & resynchronize predictions.
426
 */
427
428
LOCAL(void)
429
emit_restart(phuff_entropy_ptr entropy, int restart_num)
430
48.1M
{
431
48.1M
  int ci;
432
433
48.1M
  emit_eobrun(entropy);
434
435
48.1M
  if (!entropy->gather_statistics) {
436
25.3M
    flush_bits(entropy);
437
25.3M
    emit_byte(entropy, 0xFF);
438
25.3M
    emit_byte(entropy, JPEG_RST0 + restart_num);
439
25.3M
  }
440
441
48.1M
  if (entropy->cinfo->Ss == 0) {
442
    /* Re-initialize DC predictions to 0 */
443
30.3M
    for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
444
22.7M
      entropy->last_dc_val[ci] = 0;
445
40.5M
  } else {
446
    /* Re-initialize all AC-related fields to 0 */
447
40.5M
    entropy->EOBRUN = 0;
448
40.5M
    entropy->BE = 0;
449
40.5M
  }
450
48.1M
}
451
452
453
/*
454
 * MCU encoding for DC initial scan (either spectral selection,
455
 * or first pass of successive approximation).
456
 */
457
458
METHODDEF(boolean)
459
encode_mcu_DC_first(j_compress_ptr cinfo, JBLOCKROW *MCU_data)
460
94.0M
{
461
94.0M
  phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
462
94.0M
  register int temp, temp2, temp3;
463
94.0M
  register int nbits;
464
94.0M
  int blkn, ci;
465
94.0M
  int Al = cinfo->Al;
466
94.0M
  JBLOCKROW block;
467
94.0M
  jpeg_component_info *compptr;
468
94.0M
  ISHIFT_TEMPS
469
94.0M
  int max_coef_bits = cinfo->data_precision + 2;
470
471
94.0M
  entropy->next_output_byte = cinfo->dest->next_output_byte;
472
94.0M
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
473
474
  /* Emit restart marker if needed */
475
94.0M
  if (cinfo->restart_interval)
476
13.0M
    if (entropy->restarts_to_go == 0)
477
5.06M
      emit_restart(entropy, entropy->next_restart_num);
478
479
  /* Encode the MCU data blocks */
480
283M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
481
189M
    block = MCU_data[blkn];
482
189M
    ci = cinfo->MCU_membership[blkn];
483
189M
    compptr = cinfo->cur_comp_info[ci];
484
485
    /* Compute the DC value after the required point transform by Al.
486
     * This is simply an arithmetic right shift.
487
     */
488
189M
    temp2 = IRIGHT_SHIFT((int)((*block)[0]), Al);
489
490
    /* DC differences are figured on the point-transformed values. */
491
189M
    temp = temp2 - entropy->last_dc_val[ci];
492
189M
    entropy->last_dc_val[ci] = temp2;
493
494
    /* Encode the DC coefficient difference per section G.1.2.1 */
495
496
    /* This is a well-known technique for obtaining the absolute value without
497
     * a branch.  It is derived from an assembly language technique presented
498
     * in "How to Optimize for the Pentium Processors", Copyright (c) 1996,
499
     * 1997 by Agner Fog.
500
     */
501
189M
    temp3 = temp >> (CHAR_BIT * sizeof(int) - 1);
502
189M
    temp ^= temp3;
503
189M
    temp -= temp3;              /* temp is abs value of input */
504
    /* For a negative input, want temp2 = bitwise complement of abs(input) */
505
189M
    temp2 = temp ^ temp3;
506
507
    /* Find the number of bits needed for the magnitude of the coefficient */
508
189M
    nbits = JPEG_NBITS(temp);
509
    /* Check for out-of-range coefficient values.
510
     * Since we're encoding a difference, the range limit is twice as much.
511
     */
512
189M
    if (nbits > max_coef_bits + 1)
513
1.06k
      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
514
515
    /* Count/emit the Huffman-coded symbol for the number of bits */
516
189M
    emit_symbol(entropy, compptr->dc_tbl_no, nbits);
517
518
    /* Emit that number of bits of the value, if positive, */
519
    /* or the complement of its magnitude, if negative. */
520
189M
    if (nbits)                  /* emit_bits rejects calls with size 0 */
521
35.8M
      emit_bits(entropy, (unsigned int)temp2, nbits);
522
189M
  }
523
524
94.0M
  cinfo->dest->next_output_byte = entropy->next_output_byte;
525
94.0M
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
526
527
  /* Update restart-interval state too */
528
94.0M
  if (cinfo->restart_interval) {
529
13.0M
    if (entropy->restarts_to_go == 0) {
530
5.06M
      entropy->restarts_to_go = cinfo->restart_interval;
531
5.06M
      entropy->next_restart_num++;
532
5.06M
      entropy->next_restart_num &= 7;
533
5.06M
    }
534
13.0M
    entropy->restarts_to_go--;
535
13.0M
  }
536
537
94.0M
  return TRUE;
538
94.0M
}
539
540
541
/*
542
 * Data preparation for encode_mcu_AC_first().
543
 */
544
545
0
#define COMPUTE_ABSVALUES_AC_FIRST(Sl) { \
546
0
  for (k = 0; k < Sl; k++) { \
547
0
    temp = block[jpeg_natural_order_start[k]]; \
548
0
    if (temp == 0) \
549
0
      continue; \
550
0
    /* We must apply the point transform by Al.  For AC coefficients this \
551
0
     * is an integer division with rounding towards 0.  To do this portably \
552
0
     * in C, we shift after obtaining the absolute value; so the code is \
553
0
     * interwoven with finding the abs value (temp) and output bits (temp2). \
554
0
     */ \
555
0
    temp2 = temp >> (CHAR_BIT * sizeof(int) - 1); \
556
0
    temp ^= temp2; \
557
0
    temp -= temp2;              /* temp is abs value of input */ \
558
0
    temp >>= Al;                /* apply the point transform */ \
559
0
    /* Watch out for case that nonzero coef is zero after point transform */ \
560
0
    if (temp == 0) \
561
0
      continue; \
562
0
    /* For a negative coef, want temp2 = bitwise complement of abs(coef) */ \
563
0
    temp2 ^= temp; \
564
0
    values[k] = (UJCOEF)temp; \
565
0
    values[k + DCTSIZE2] = (UJCOEF)temp2; \
566
0
    zerobits |= ((size_t)1U) << k; \
567
0
  } \
568
0
}
569
570
METHODDEF(void)
571
encode_mcu_AC_first_prepare(const JCOEF *block,
572
                            const int *jpeg_natural_order_start, int Sl,
573
                            int Al, UJCOEF *values, size_t *bits)
574
0
{
575
0
  register int k, temp, temp2;
576
0
  size_t zerobits = 0U;
577
0
  int Sl0 = Sl;
578
579
#if SIZEOF_SIZE_T == 4
580
  if (Sl0 > 32)
581
    Sl0 = 32;
582
#endif
583
584
0
  COMPUTE_ABSVALUES_AC_FIRST(Sl0);
585
586
0
  bits[0] = zerobits;
587
#if SIZEOF_SIZE_T == 4
588
  zerobits = 0U;
589
590
  if (Sl > 32) {
591
    Sl -= 32;
592
    jpeg_natural_order_start += 32;
593
    values += 32;
594
595
    COMPUTE_ABSVALUES_AC_FIRST(Sl);
596
  }
597
  bits[1] = zerobits;
598
#endif
599
0
}
600
601
/*
602
 * MCU encoding for AC initial scan (either spectral selection,
603
 * or first pass of successive approximation).
604
 */
605
606
285M
#define ENCODE_COEFS_AC_FIRST(label) { \
607
600M
  while (zerobits) { \
608
315M
    r = count_zeroes(&zerobits); \
609
315M
    cvalue += r; \
610
315M
label \
611
315M
    temp  = cvalue[0]; \
612
315M
    temp2 = cvalue[DCTSIZE2]; \
613
315M
    \
614
315M
    /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \
615
319M
    while (r > 15) { \
616
4.05M
      emit_symbol(entropy, entropy->ac_tbl_no, 0xF0); \
617
4.05M
      r -= 16; \
618
4.05M
    } \
619
315M
    \
620
315M
    /* Find the number of bits needed for the magnitude of the coefficient */ \
621
315M
    nbits = JPEG_NBITS_NONZERO(temp);  /* there must be at least one 1 bit */ \
622
315M
    /* Check for out-of-range coefficient values */ \
623
315M
    if (nbits > max_coef_bits) \
624
315M
      ERREXIT(cinfo, JERR_BAD_DCT_COEF); \
625
315M
    \
626
315M
    /* Count/emit Huffman symbol for run length / number of bits */ \
627
315M
    emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits); \
628
315M
    \
629
315M
    /* Emit that number of bits of the value, if positive, */ \
630
315M
    /* or the complement of its magnitude, if negative. */ \
631
315M
    emit_bits(entropy, (unsigned int)temp2, nbits); \
632
315M
    \
633
315M
    cvalue++; \
634
315M
    zerobits >>= 1; \
635
315M
  } \
636
285M
}
637
638
METHODDEF(boolean)
639
encode_mcu_AC_first(j_compress_ptr cinfo, JBLOCKROW *MCU_data)
640
285M
{
641
285M
  phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
642
285M
  register int temp, temp2;
643
285M
  register int nbits, r;
644
285M
  int Sl = cinfo->Se - cinfo->Ss + 1;
645
285M
  int Al = cinfo->Al;
646
285M
  UJCOEF values_unaligned[2 * DCTSIZE2 + 15];
647
285M
  UJCOEF *values;
648
285M
  const UJCOEF *cvalue;
649
285M
  size_t zerobits;
650
285M
  size_t bits[8 / SIZEOF_SIZE_T];
651
285M
  int max_coef_bits = cinfo->data_precision + 2;
652
653
#ifdef ZERO_BUFFERS
654
  memset(values_unaligned, 0, sizeof(values_unaligned));
655
  memset(bits, 0, sizeof(bits));
656
#endif
657
658
285M
  entropy->next_output_byte = cinfo->dest->next_output_byte;
659
285M
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
660
661
  /* Emit restart marker if needed */
662
285M
  if (cinfo->restart_interval)
663
58.1M
    if (entropy->restarts_to_go == 0)
664
20.2M
      emit_restart(entropy, entropy->next_restart_num);
665
666
285M
#ifdef WITH_SIMD
667
285M
  cvalue = values = (UJCOEF *)PAD((JUINTPTR)values_unaligned, 16);
668
#else
669
  /* Not using SIMD, so alignment is not needed */
670
  cvalue = values = values_unaligned;
671
#endif
672
673
  /* Prepare data */
674
285M
  entropy->AC_first_prepare(MCU_data[0][0], jpeg_natural_order + cinfo->Ss,
675
285M
                            Sl, Al, values, bits);
676
677
285M
  zerobits = bits[0];
678
#if SIZEOF_SIZE_T == 4
679
  zerobits |= bits[1];
680
#endif
681
682
  /* Emit any pending EOBRUN */
683
285M
  if (zerobits && (entropy->EOBRUN > 0))
684
22.9M
    emit_eobrun(entropy);
685
686
#if SIZEOF_SIZE_T == 4
687
  zerobits = bits[0];
688
#endif
689
690
  /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
691
692
285M
  ENCODE_COEFS_AC_FIRST((void)0;);
693
694
#if SIZEOF_SIZE_T == 4
695
  zerobits = bits[1];
696
  if (zerobits) {
697
    int diff = ((values + DCTSIZE2 / 2) - cvalue);
698
    r = count_zeroes(&zerobits);
699
    r += diff;
700
    cvalue += r;
701
    goto first_iter_ac_first;
702
  }
703
704
  ENCODE_COEFS_AC_FIRST(first_iter_ac_first:);
705
#endif
706
707
285M
  if (cvalue < (values + Sl)) { /* If there are trailing zeroes, */
708
276M
    entropy->EOBRUN++;          /* count an EOB */
709
276M
    if (entropy->EOBRUN == 0x7FFF)
710
0
      emit_eobrun(entropy);     /* force it out to avoid overflow */
711
276M
  }
712
713
285M
  cinfo->dest->next_output_byte = entropy->next_output_byte;
714
285M
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
715
716
  /* Update restart-interval state too */
717
285M
  if (cinfo->restart_interval) {
718
58.1M
    if (entropy->restarts_to_go == 0) {
719
20.2M
      entropy->restarts_to_go = cinfo->restart_interval;
720
20.2M
      entropy->next_restart_num++;
721
20.2M
      entropy->next_restart_num &= 7;
722
20.2M
    }
723
58.1M
    entropy->restarts_to_go--;
724
58.1M
  }
725
726
285M
  return TRUE;
727
285M
}
728
729
730
/*
731
 * MCU encoding for DC successive approximation refinement scan.
732
 * Note: we assume such scans can be multi-component, although the spec
733
 * is not very clear on the point.
734
 */
735
736
METHODDEF(boolean)
737
encode_mcu_DC_refine(j_compress_ptr cinfo, JBLOCKROW *MCU_data)
738
43.5M
{
739
43.5M
  phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
740
43.5M
  register int temp;
741
43.5M
  int blkn;
742
43.5M
  int Al = cinfo->Al;
743
43.5M
  JBLOCKROW block;
744
745
43.5M
  entropy->next_output_byte = cinfo->dest->next_output_byte;
746
43.5M
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
747
748
  /* Emit restart marker if needed */
749
43.5M
  if (cinfo->restart_interval)
750
6.52M
    if (entropy->restarts_to_go == 0)
751
2.53M
      emit_restart(entropy, entropy->next_restart_num);
752
753
  /* Encode the MCU data blocks */
754
132M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
755
89.0M
    block = MCU_data[blkn];
756
757
    /* We simply emit the Al'th bit of the DC coefficient value. */
758
89.0M
    temp = (*block)[0];
759
89.0M
    emit_bits(entropy, (unsigned int)(temp >> Al), 1);
760
89.0M
  }
761
762
43.5M
  cinfo->dest->next_output_byte = entropy->next_output_byte;
763
43.5M
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
764
765
  /* Update restart-interval state too */
766
43.5M
  if (cinfo->restart_interval) {
767
6.52M
    if (entropy->restarts_to_go == 0) {
768
2.53M
      entropy->restarts_to_go = cinfo->restart_interval;
769
2.53M
      entropy->next_restart_num++;
770
2.53M
      entropy->next_restart_num &= 7;
771
2.53M
    }
772
6.52M
    entropy->restarts_to_go--;
773
6.52M
  }
774
775
43.5M
  return TRUE;
776
43.5M
}
777
778
779
/*
780
 * Data preparation for encode_mcu_AC_refine().
781
 */
782
783
0
#define COMPUTE_ABSVALUES_AC_REFINE(Sl, koffset) { \
784
0
  /* It is convenient to make a pre-pass to determine the transformed \
785
0
   * coefficients' absolute values and the EOB position. \
786
0
   */ \
787
0
  for (k = 0; k < Sl; k++) { \
788
0
    temp = block[jpeg_natural_order_start[k]]; \
789
0
    /* We must apply the point transform by Al.  For AC coefficients this \
790
0
     * is an integer division with rounding towards 0.  To do this portably \
791
0
     * in C, we shift after obtaining the absolute value. \
792
0
     */ \
793
0
    temp2 = temp >> (CHAR_BIT * sizeof(int) - 1); \
794
0
    temp ^= temp2; \
795
0
    temp -= temp2;              /* temp is abs value of input */ \
796
0
    temp >>= Al;                /* apply the point transform */ \
797
0
    if (temp != 0) { \
798
0
      zerobits |= ((size_t)1U) << k; \
799
0
      signbits |= ((size_t)(temp2 + 1)) << k; \
800
0
    } \
801
0
    absvalues[k] = (UJCOEF)temp; /* save abs value for main pass */ \
802
0
    if (temp == 1) \
803
0
      EOB = k + koffset;        /* EOB = index of last newly-nonzero coef */ \
804
0
  } \
805
0
}
806
807
METHODDEF(int)
808
encode_mcu_AC_refine_prepare(const JCOEF *block,
809
                             const int *jpeg_natural_order_start, int Sl,
810
                             int Al, UJCOEF *absvalues, size_t *bits)
811
0
{
812
0
  register int k, temp, temp2;
813
0
  int EOB = 0;
814
0
  size_t zerobits = 0U, signbits = 0U;
815
0
  int Sl0 = Sl;
816
817
#if SIZEOF_SIZE_T == 4
818
  if (Sl0 > 32)
819
    Sl0 = 32;
820
#endif
821
822
0
  COMPUTE_ABSVALUES_AC_REFINE(Sl0, 0);
823
824
0
  bits[0] = zerobits;
825
0
#if SIZEOF_SIZE_T == 8
826
0
  bits[1] = signbits;
827
#else
828
  bits[2] = signbits;
829
830
  zerobits = 0U;
831
  signbits = 0U;
832
833
  if (Sl > 32) {
834
    Sl -= 32;
835
    jpeg_natural_order_start += 32;
836
    absvalues += 32;
837
838
    COMPUTE_ABSVALUES_AC_REFINE(Sl, 32);
839
  }
840
841
  bits[1] = zerobits;
842
  bits[3] = signbits;
843
#endif
844
845
0
  return EOB;
846
0
}
847
848
849
/*
850
 * MCU encoding for AC successive approximation refinement scan.
851
 */
852
853
281M
#define ENCODE_COEFS_AC_REFINE(label) { \
854
1.01G
  while (zerobits) { \
855
731M
    idx = count_zeroes(&zerobits); \
856
731M
    r += idx; \
857
731M
    cabsvalue += idx; \
858
731M
    signbits >>= idx; \
859
731M
label \
860
731M
    /* Emit any required ZRLs, but not if they can be folded into EOB */ \
861
736M
    while (r > 15 && (cabsvalue <= EOBPTR)) { \
862
5.60M
      /* emit any pending EOBRUN and the BE correction bits */ \
863
5.60M
      emit_eobrun(entropy); \
864
5.60M
      /* Emit ZRL */ \
865
5.60M
      emit_symbol(entropy, entropy->ac_tbl_no, 0xF0); \
866
5.60M
      r -= 16; \
867
5.60M
      /* Emit buffered correction bits that must be associated with ZRL */ \
868
5.60M
      emit_buffered_bits(entropy, BR_buffer, BR); \
869
5.60M
      BR_buffer = entropy->bit_buffer; /* BE bits are gone now */ \
870
5.60M
      BR = 0; \
871
5.60M
    } \
872
731M
    \
873
731M
    temp = *cabsvalue++; \
874
731M
    \
875
731M
    /* If the coef was previously nonzero, it only needs a correction bit. \
876
731M
     * NOTE: a straight translation of the spec's figure G.7 would suggest \
877
731M
     * that we also need to test r > 15.  But if r > 15, we can only get here \
878
731M
     * if k > EOB, which implies that this coefficient is not 1. \
879
731M
     */ \
880
731M
    if (temp > 1) { \
881
629M
      /* The correction bit is the next bit of the absolute value. */ \
882
629M
      BR_buffer[BR++] = (char)(temp & 1); \
883
629M
      signbits >>= 1; \
884
629M
      zerobits >>= 1; \
885
629M
      continue; \
886
629M
    } \
887
731M
    \
888
731M
    /* Emit any pending EOBRUN and the BE correction bits */ \
889
731M
    emit_eobrun(entropy); \
890
101M
    \
891
101M
    /* Count/emit Huffman symbol for run length / number of bits */ \
892
101M
    emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1); \
893
101M
    \
894
101M
    /* Emit output bit for newly-nonzero coef */ \
895
101M
    temp = signbits & 1; /* ((*block)[jpeg_natural_order_start[k]] < 0) ? 0 : 1 */ \
896
101M
    emit_bits(entropy, (unsigned int)temp, 1); \
897
101M
    \
898
101M
    /* Emit buffered correction bits that must be associated with this code */ \
899
101M
    emit_buffered_bits(entropy, BR_buffer, BR); \
900
101M
    BR_buffer = entropy->bit_buffer; /* BE bits are gone now */ \
901
101M
    BR = 0; \
902
101M
    r = 0;                      /* reset zero run length */ \
903
101M
    signbits >>= 1; \
904
101M
    zerobits >>= 1; \
905
101M
  } \
906
281M
}
907
908
METHODDEF(boolean)
909
encode_mcu_AC_refine(j_compress_ptr cinfo, JBLOCKROW *MCU_data)
910
281M
{
911
281M
  phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
912
281M
  register int temp, r, idx;
913
281M
  char *BR_buffer;
914
281M
  unsigned int BR;
915
281M
  int Sl = cinfo->Se - cinfo->Ss + 1;
916
281M
  int Al = cinfo->Al;
917
281M
  UJCOEF absvalues_unaligned[DCTSIZE2 + 15];
918
281M
  UJCOEF *absvalues;
919
281M
  const UJCOEF *cabsvalue, *EOBPTR;
920
281M
  size_t zerobits, signbits;
921
281M
  size_t bits[16 / SIZEOF_SIZE_T];
922
923
#ifdef ZERO_BUFFERS
924
  memset(absvalues_unaligned, 0, sizeof(absvalues_unaligned));
925
  memset(bits, 0, sizeof(bits));
926
#endif
927
928
281M
  entropy->next_output_byte = cinfo->dest->next_output_byte;
929
281M
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
930
931
  /* Emit restart marker if needed */
932
281M
  if (cinfo->restart_interval)
933
58.1M
    if (entropy->restarts_to_go == 0)
934
20.2M
      emit_restart(entropy, entropy->next_restart_num);
935
936
281M
#ifdef WITH_SIMD
937
281M
  cabsvalue = absvalues = (UJCOEF *)PAD((JUINTPTR)absvalues_unaligned, 16);
938
#else
939
  /* Not using SIMD, so alignment is not needed */
940
  cabsvalue = absvalues = absvalues_unaligned;
941
#endif
942
943
  /* Prepare data */
944
281M
  EOBPTR = absvalues +
945
281M
    entropy->AC_refine_prepare(MCU_data[0][0], jpeg_natural_order + cinfo->Ss,
946
281M
                               Sl, Al, absvalues, bits);
947
948
  /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
949
950
281M
  r = 0;                        /* r = run length of zeros */
951
281M
  BR = 0;                       /* BR = count of buffered bits added now */
952
281M
  BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
953
954
281M
  zerobits = bits[0];
955
281M
#if SIZEOF_SIZE_T == 8
956
281M
  signbits = bits[1];
957
#else
958
  signbits = bits[2];
959
#endif
960
281M
  ENCODE_COEFS_AC_REFINE((void)0;);
961
962
#if SIZEOF_SIZE_T == 4
963
  zerobits = bits[1];
964
  signbits = bits[3];
965
966
  if (zerobits) {
967
    int diff = ((absvalues + DCTSIZE2 / 2) - cabsvalue);
968
    idx = count_zeroes(&zerobits);
969
    signbits >>= idx;
970
    idx += diff;
971
    r += idx;
972
    cabsvalue += idx;
973
    goto first_iter_ac_refine;
974
  }
975
976
  ENCODE_COEFS_AC_REFINE(first_iter_ac_refine:);
977
#endif
978
979
281M
  r |= (int)((absvalues + Sl) - cabsvalue);
980
981
281M
  if (r > 0 || BR > 0) {        /* If there are trailing zeroes, */
982
279M
    entropy->EOBRUN++;          /* count an EOB */
983
279M
    entropy->BE += BR;          /* concat my correction bits to older ones */
984
    /* We force out the EOB if we risk either:
985
     * 1. overflow of the EOB counter;
986
     * 2. overflow of the correction bit buffer during the next MCU.
987
     */
988
279M
    if (entropy->EOBRUN == 0x7FFF ||
989
279M
        entropy->BE > (MAX_CORR_BITS - DCTSIZE2 + 1))
990
162k
      emit_eobrun(entropy);
991
279M
  }
992
993
281M
  cinfo->dest->next_output_byte = entropy->next_output_byte;
994
281M
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
995
996
  /* Update restart-interval state too */
997
281M
  if (cinfo->restart_interval) {
998
58.1M
    if (entropy->restarts_to_go == 0) {
999
20.2M
      entropy->restarts_to_go = cinfo->restart_interval;
1000
20.2M
      entropy->next_restart_num++;
1001
20.2M
      entropy->next_restart_num &= 7;
1002
20.2M
    }
1003
58.1M
    entropy->restarts_to_go--;
1004
58.1M
  }
1005
1006
281M
  return TRUE;
1007
281M
}
1008
1009
1010
/*
1011
 * Finish up at the end of a Huffman-compressed progressive scan.
1012
 */
1013
1014
METHODDEF(void)
1015
finish_pass_phuff(j_compress_ptr cinfo)
1016
209k
{
1017
209k
  phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
1018
1019
209k
  entropy->next_output_byte = cinfo->dest->next_output_byte;
1020
209k
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
1021
1022
  /* Flush out any buffered data */
1023
209k
  emit_eobrun(entropy);
1024
209k
  flush_bits(entropy);
1025
1026
209k
  cinfo->dest->next_output_byte = entropy->next_output_byte;
1027
209k
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
1028
209k
}
1029
1030
1031
/*
1032
 * Finish up a statistics-gathering pass and create the new Huffman tables.
1033
 */
1034
1035
METHODDEF(void)
1036
finish_pass_gather_phuff(j_compress_ptr cinfo)
1037
186k
{
1038
186k
  phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
1039
186k
  boolean is_DC_band;
1040
186k
  int ci, tbl;
1041
186k
  jpeg_component_info *compptr;
1042
186k
  JHUFF_TBL **htblptr;
1043
186k
  boolean did[NUM_HUFF_TBLS];
1044
1045
  /* Flush out buffered data (all we care about is counting the EOB symbol) */
1046
186k
  emit_eobrun(entropy);
1047
1048
186k
  is_DC_band = (cinfo->Ss == 0);
1049
1050
  /* It's important not to apply jpeg_gen_optimal_table more than once
1051
   * per table, because it clobbers the input frequency counts!
1052
   */
1053
186k
  memset(did, 0, sizeof(did));
1054
1055
407k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1056
220k
    compptr = cinfo->cur_comp_info[ci];
1057
220k
    if (is_DC_band) {
1058
57.7k
      if (cinfo->Ah != 0)       /* DC refinement needs no table */
1059
0
        continue;
1060
57.7k
      tbl = compptr->dc_tbl_no;
1061
162k
    } else {
1062
162k
      tbl = compptr->ac_tbl_no;
1063
162k
    }
1064
220k
    if (!did[tbl]) {
1065
202k
      if (is_DC_band)
1066
39.9k
        htblptr = &cinfo->dc_huff_tbl_ptrs[tbl];
1067
162k
      else
1068
162k
        htblptr = &cinfo->ac_huff_tbl_ptrs[tbl];
1069
202k
      if (*htblptr == NULL)
1070
0
        *htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
1071
202k
      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
1072
202k
      did[tbl] = TRUE;
1073
202k
    }
1074
220k
  }
1075
186k
}
1076
1077
1078
/*
1079
 * Module initialization routine for progressive Huffman entropy encoding.
1080
 */
1081
1082
GLOBAL(void)
1083
jinit_phuff_encoder(j_compress_ptr cinfo)
1084
24.8k
{
1085
24.8k
  phuff_entropy_ptr entropy;
1086
24.8k
  int i;
1087
1088
24.8k
  entropy = (phuff_entropy_ptr)
1089
24.8k
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
1090
24.8k
                                sizeof(phuff_entropy_encoder));
1091
24.8k
  cinfo->entropy = (struct jpeg_entropy_encoder *)entropy;
1092
24.8k
  entropy->pub.start_pass = start_pass_phuff;
1093
1094
  /* Mark tables unallocated */
1095
124k
  for (i = 0; i < NUM_HUFF_TBLS; i++) {
1096
99.5k
    entropy->derived_tbls[i] = NULL;
1097
99.5k
    entropy->count_ptrs[i] = NULL;
1098
99.5k
  }
1099
24.8k
  entropy->bit_buffer = NULL;   /* needed only in AC refinement scan */
1100
24.8k
}
1101
1102
#endif /* C_PROGRESSIVE_SUPPORTED */