Coverage Report

Created: 2025-06-10 06:49

/src/ghostpdl/obj/jchuff.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * jchuff.c
3
 *
4
 * Copyright (C) 1991-1997, Thomas G. Lane.
5
 * Modified 2006-2023 by Guido Vollbeding.
6
 * This file is part of the Independent JPEG Group's software.
7
 * For conditions of distribution and use, see the accompanying README file.
8
 *
9
 * This file contains Huffman entropy encoding routines.
10
 * Both sequential and progressive modes are supported in this single module.
11
 *
12
 * Much of the complexity here has to do with supporting output suspension.
13
 * If the data destination module demands suspension, we want to be able to
14
 * back up to the start of the current MCU.  To do this, we copy state
15
 * variables into local working storage, and update them back to the
16
 * permanent JPEG objects only upon successful completion of an MCU.
17
 *
18
 * We do not support output suspension for the progressive JPEG mode, since
19
 * the library currently does not allow multiple-scan files to be written
20
 * with output suspension.
21
 */
22
23
#define JPEG_INTERNALS
24
#include "jinclude.h"
25
#include "jpeglib.h"
26
27
28
/* The legal range of a DCT coefficient is
29
 *  -1024 .. +1023  for 8-bit sample data precision;
30
 * -16384 .. +16383 for 12-bit sample data precision.
31
 * Hence the magnitude should always fit in sample data precision + 2 bits.
32
 */
33
34
/* Derived data constructed for each Huffman table */
35
36
typedef struct {
37
  unsigned int ehufco[256]; /* code for each symbol */
38
  char ehufsi[256];   /* length of code for each symbol */
39
  /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
40
} c_derived_tbl;
41
42
43
/* Expanded entropy encoder object for Huffman encoding.
44
 *
45
 * The savable_state subrecord contains fields that change within an MCU,
46
 * but must not be updated permanently until we complete the MCU.
47
 */
48
49
typedef struct {
50
  INT32 put_buffer;   /* current bit-accumulation buffer */
51
  int put_bits;     /* # of bits now in it */
52
  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
53
} savable_state;
54
55
/* This macro is to work around compilers with missing or broken
56
 * structure assignment.  You'll need to fix this code if you have
57
 * such a compiler and you change MAX_COMPS_IN_SCAN.
58
 */
59
60
#ifndef NO_STRUCT_ASSIGN
61
0
#define ASSIGN_STATE(dest,src)  ((dest) = (src))
62
#else
63
#if MAX_COMPS_IN_SCAN == 4
64
#define ASSIGN_STATE(dest,src)  \
65
  ((dest).put_buffer = (src).put_buffer, \
66
   (dest).put_bits = (src).put_bits, \
67
   (dest).last_dc_val[0] = (src).last_dc_val[0], \
68
   (dest).last_dc_val[1] = (src).last_dc_val[1], \
69
   (dest).last_dc_val[2] = (src).last_dc_val[2], \
70
   (dest).last_dc_val[3] = (src).last_dc_val[3])
71
#endif
72
#endif
73
74
75
typedef struct {
76
  struct jpeg_entropy_encoder pub; /* public fields */
77
78
  savable_state saved;    /* Bit buffer & DC state at start of MCU */
79
80
  /* These fields are NOT loaded into local working state. */
81
  unsigned int restarts_to_go;  /* MCUs left in this restart interval */
82
  int next_restart_num;   /* next restart number to write (0-7) */
83
84
  /* Pointers to derived tables (these workspaces have image lifespan) */
85
  c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
86
  c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
87
88
  /* Statistics tables for optimization */
89
  long * dc_count_ptrs[NUM_HUFF_TBLS];
90
  long * ac_count_ptrs[NUM_HUFF_TBLS];
91
92
  /* Following fields used only in progressive mode */
93
94
  /* Mode flag: TRUE for optimization, FALSE for actual data output */
95
  boolean gather_statistics;
96
97
  /* next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
98
   */
99
  JOCTET * next_output_byte;  /* => next byte to write in buffer */
100
  size_t free_in_buffer;  /* # of byte spaces remaining in buffer */
101
  j_compress_ptr cinfo;   /* link to cinfo (needed for dump_buffer) */
102
103
  /* Coding status for AC components */
104
  int ac_tbl_no;    /* the table number of the single component */
105
  unsigned int EOBRUN;    /* run length of EOBs */
106
  unsigned int BE;    /* # of buffered correction bits before MCU */
107
  char * bit_buffer;    /* buffer for correction bits (1 per char) */
108
  /* packing correction bits tightly would save some space but cost time... */
109
} huff_entropy_encoder;
110
111
typedef huff_entropy_encoder * huff_entropy_ptr;
112
113
/* Working state while writing an MCU (sequential mode).
114
 * This struct contains all the fields that are needed by subroutines.
115
 */
116
117
typedef struct {
118
  JOCTET * next_output_byte;  /* => next byte to write in buffer */
119
  size_t free_in_buffer;  /* # of byte spaces remaining in buffer */
120
  savable_state cur;    /* Current bit buffer & DC state */
121
  j_compress_ptr cinfo;   /* dump_buffer needs access to this */
122
} working_state;
123
124
/* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
125
 * buffer can hold.  Larger sizes may slightly improve compression, but
126
 * 1000 is already well into the realm of overkill.
127
 * The minimum safe size is 64 bits.
128
 */
129
130
0
#define MAX_CORR_BITS  1000  /* Max # of correction bits I can buffer */
131
132
/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
133
 * We assume that int right shift is unsigned if INT32 right shift is,
134
 * which should be safe.
135
 */
136
137
#ifdef RIGHT_SHIFT_IS_UNSIGNED
138
#define ISHIFT_TEMPS  int ishift_temp;
139
#define IRIGHT_SHIFT(x,shft)  \
140
  ((ishift_temp = (x)) < 0 ? \
141
   (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
142
   (ishift_temp >> (shft)))
143
#else
144
#define ISHIFT_TEMPS
145
0
#define IRIGHT_SHIFT(x,shft)  ((x) >> (shft))
146
#endif
147
148
149
/*
150
 * Compute the derived values for a Huffman table.
151
 * This routine also performs some validation checks on the table.
152
 */
153
154
LOCAL(void)
155
jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
156
       c_derived_tbl ** pdtbl)
157
0
{
158
0
  JHUFF_TBL *htbl;
159
0
  c_derived_tbl *dtbl;
160
0
  int p, i, l, lastp, si, maxsymbol;
161
0
  char huffsize[257];
162
0
  unsigned int huffcode[257];
163
0
  unsigned int code;
164
165
  /* Note that huffsize[] and huffcode[] are filled in code-length order,
166
   * paralleling the order of the symbols themselves in htbl->huffval[].
167
   */
168
169
  /* Find the input Huffman table */
170
0
  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
171
0
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
172
0
  htbl =
173
0
    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
174
0
  if (htbl == NULL)
175
0
    htbl = jpeg_std_huff_table((j_common_ptr) cinfo, isDC, tblno);
176
177
  /* Allocate a workspace if we haven't already done so. */
178
0
  if (*pdtbl == NULL)
179
0
    *pdtbl = (c_derived_tbl *) (*cinfo->mem->alloc_small)
180
0
      ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(c_derived_tbl));
181
0
  dtbl = *pdtbl;
182
  
183
  /* Figure C.1: make table of Huffman code length for each symbol */
184
185
0
  p = 0;
186
0
  for (l = 1; l <= 16; l++) {
187
0
    i = (int) htbl->bits[l];
188
0
    if (i < 0 || p + i > 256) /* protect against table overrun */
189
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
190
0
    while (i--)
191
0
      huffsize[p++] = (char) l;
192
0
  }
193
0
  huffsize[p] = 0;
194
0
  lastp = p;
195
  
196
  /* Figure C.2: generate the codes themselves */
197
  /* We also validate that the counts represent a legal Huffman code tree. */
198
199
0
  code = 0;
200
0
  si = huffsize[0];
201
0
  p = 0;
202
0
  while (huffsize[p]) {
203
0
    while (((int) huffsize[p]) == si) {
204
0
      huffcode[p++] = code;
205
0
      code++;
206
0
    }
207
    /* code is now 1 more than the last code used for codelength si; but
208
     * it must still fit in si bits, since no code is allowed to be all ones.
209
     */
210
0
    if (((INT32) code) >= (((INT32) 1) << si))
211
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
212
0
    code <<= 1;
213
0
    si++;
214
0
  }
215
  
216
  /* Figure C.3: generate encoding tables */
217
  /* These are code and size indexed by symbol value */
218
219
  /* Set all codeless symbols to have code length 0;
220
   * this lets us detect duplicate VAL entries here, and later
221
   * allows emit_bits to detect any attempt to emit such symbols.
222
   */
223
0
  MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
224
225
  /* This is also a convenient place to check for out-of-range
226
   * and duplicated VAL entries.  We allow 0..255 for AC symbols
227
   * but only 0..15 for DC.  (We could constrain them further
228
   * based on data depth and mode, but this seems enough.)
229
   */
230
0
  maxsymbol = isDC ? 15 : 255;
231
232
0
  for (p = 0; p < lastp; p++) {
233
0
    i = htbl->huffval[p];
234
0
    if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
235
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
236
0
    dtbl->ehufco[i] = huffcode[p];
237
0
    dtbl->ehufsi[i] = huffsize[p];
238
0
  }
239
0
}
240
241
242
/* Outputting bytes to the file.
243
 * NB: these must be called only when actually outputting,
244
 * that is, entropy->gather_statistics == FALSE.
245
 */
246
247
/* Emit a byte, taking 'action' if must suspend. */
248
#define emit_byte_s(state,val,action)  \
249
0
  { *(state)->next_output_byte++ = (JOCTET) (val);  \
250
0
    if (--(state)->free_in_buffer == 0)  \
251
0
      if (! dump_buffer_s(state))  \
252
0
        { action; } }
253
254
/* Emit a byte */
255
#define emit_byte_e(entropy,val)  \
256
0
  { *(entropy)->next_output_byte++ = (JOCTET) (val);  \
257
0
    if (--(entropy)->free_in_buffer == 0)  \
258
0
      dump_buffer_e(entropy); }
259
260
261
LOCAL(boolean)
262
dump_buffer_s (working_state * state)
263
/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
264
0
{
265
0
  struct jpeg_destination_mgr * dest = state->cinfo->dest;
266
267
0
  if (! (*dest->empty_output_buffer) (state->cinfo))
268
0
    return FALSE;
269
  /* After a successful buffer dump, must reset buffer pointers */
270
0
  state->next_output_byte = dest->next_output_byte;
271
0
  state->free_in_buffer = dest->free_in_buffer;
272
0
  return TRUE;
273
0
}
274
275
276
LOCAL(void)
277
dump_buffer_e (huff_entropy_ptr entropy)
278
/* Empty the output buffer; we do not support suspension in this case. */
279
0
{
280
0
  struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
281
282
0
  if (! (*dest->empty_output_buffer) (entropy->cinfo))
283
0
    ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
284
  /* After a successful buffer dump, must reset buffer pointers */
285
0
  entropy->next_output_byte = dest->next_output_byte;
286
0
  entropy->free_in_buffer = dest->free_in_buffer;
287
0
}
288
289
290
/* Outputting bits to the file */
291
292
/* Only the right 24 bits of put_buffer are used; the valid bits are
293
 * left-justified in this part.  At most 16 bits can be passed to emit_bits
294
 * in one call, and we never retain more than 7 bits in put_buffer
295
 * between calls, so 24 bits are sufficient.
296
 */
297
298
INLINE
299
LOCAL(boolean)
300
emit_bits_s (working_state * state, unsigned int code, int size)
301
/* Emit some bits; return TRUE if successful, FALSE if must suspend */
302
0
{
303
  /* This routine is heavily used, so it's worth coding tightly. */
304
0
  register INT32 put_buffer;
305
0
  register int put_bits;
306
307
  /* if size is 0, caller used an invalid Huffman table entry */
308
0
  if (size == 0)
309
0
    ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
310
311
  /* mask off any extra bits in code */
312
0
  put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1);
313
314
  /* new number of bits in buffer */
315
0
  put_bits = size + state->cur.put_bits;
316
317
0
  put_buffer <<= 24 - put_bits; /* align incoming bits */
318
319
  /* and merge with old buffer contents */
320
0
  put_buffer |= state->cur.put_buffer;
321
322
0
  while (put_bits >= 8) {
323
0
    int c = (int) ((put_buffer >> 16) & 0xFF);
324
325
0
    emit_byte_s(state, c, return FALSE);
326
0
    if (c == 0xFF) {   /* need to stuff a zero byte? */
327
0
      emit_byte_s(state, 0, return FALSE);
328
0
    }
329
0
    put_buffer <<= 8;
330
0
    put_bits -= 8;
331
0
  }
332
333
0
  state->cur.put_buffer = put_buffer; /* update state variables */
334
0
  state->cur.put_bits = put_bits;
335
336
0
  return TRUE;
337
0
}
338
339
340
INLINE
341
LOCAL(void)
342
emit_bits_e (huff_entropy_ptr entropy, unsigned int code, int size)
343
/* Emit some bits, unless we are in gather mode */
344
0
{
345
  /* This routine is heavily used, so it's worth coding tightly. */
346
0
  register INT32 put_buffer;
347
0
  register int put_bits;
348
349
  /* if size is 0, caller used an invalid Huffman table entry */
350
0
  if (size == 0)
351
0
    ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
352
353
0
  if (entropy->gather_statistics)
354
0
    return;     /* do nothing if we're only getting stats */
355
356
  /* mask off any extra bits in code */
357
0
  put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1);
358
359
  /* new number of bits in buffer */
360
0
  put_bits = size + entropy->saved.put_bits;
361
362
0
  put_buffer <<= 24 - put_bits; /* align incoming bits */
363
364
  /* and merge with old buffer contents */
365
0
  put_buffer |= entropy->saved.put_buffer;
366
367
0
  while (put_bits >= 8) {
368
0
    int c = (int) ((put_buffer >> 16) & 0xFF);
369
370
0
    emit_byte_e(entropy, c);
371
0
    if (c == 0xFF) {   /* need to stuff a zero byte? */
372
0
      emit_byte_e(entropy, 0);
373
0
    }
374
0
    put_buffer <<= 8;
375
0
    put_bits -= 8;
376
0
  }
377
378
0
  entropy->saved.put_buffer = put_buffer; /* update variables */
379
0
  entropy->saved.put_bits = put_bits;
380
0
}
381
382
383
LOCAL(boolean)
384
flush_bits_s (working_state * state)
385
0
{
386
0
  if (! emit_bits_s(state, 0x7F, 7)) /* fill any partial byte with ones */
387
0
    return FALSE;
388
0
  state->cur.put_buffer = 0;       /* and reset bit-buffer to empty */
389
0
  state->cur.put_bits = 0;
390
0
  return TRUE;
391
0
}
392
393
394
LOCAL(void)
395
flush_bits_e (huff_entropy_ptr entropy)
396
0
{
397
0
  emit_bits_e(entropy, 0x7F, 7); /* fill any partial byte with ones */
398
0
  entropy->saved.put_buffer = 0; /* and reset bit-buffer to empty */
399
0
  entropy->saved.put_bits = 0;
400
0
}
401
402
403
/*
404
 * Emit (or just count) a Huffman symbol.
405
 */
406
407
INLINE
408
LOCAL(void)
409
emit_dc_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
410
0
{
411
0
  if (entropy->gather_statistics)
412
0
    entropy->dc_count_ptrs[tbl_no][symbol]++;
413
0
  else {
414
0
    c_derived_tbl * tbl = entropy->dc_derived_tbls[tbl_no];
415
0
    emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
416
0
  }
417
0
}
418
419
420
INLINE
421
LOCAL(void)
422
emit_ac_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
423
0
{
424
0
  if (entropy->gather_statistics)
425
0
    entropy->ac_count_ptrs[tbl_no][symbol]++;
426
0
  else {
427
0
    c_derived_tbl * tbl = entropy->ac_derived_tbls[tbl_no];
428
0
    emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
429
0
  }
430
0
}
431
432
433
/*
434
 * Emit bits from a correction bit buffer.
435
 */
436
437
LOCAL(void)
438
emit_buffered_bits (huff_entropy_ptr entropy, char * bufstart,
439
        unsigned int nbits)
440
0
{
441
0
  if (entropy->gather_statistics)
442
0
    return;     /* no real work */
443
444
0
  while (nbits > 0) {
445
0
    emit_bits_e(entropy, (unsigned int) (*bufstart), 1);
446
0
    bufstart++;
447
0
    nbits--;
448
0
  }
449
0
}
450
451
452
/*
453
 * Emit any pending EOBRUN symbol.
454
 */
455
456
LOCAL(void)
457
emit_eobrun (huff_entropy_ptr entropy)
458
0
{
459
0
  register int temp, nbits;
460
461
0
  if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
462
0
    temp = entropy->EOBRUN;
463
0
    nbits = 0;
464
0
    while ((temp >>= 1))
465
0
      nbits++;
466
    /* safety check: shouldn't happen given limited correction-bit buffer */
467
0
    if (nbits > 14)
468
0
      ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
469
470
0
    emit_ac_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
471
0
    if (nbits)
472
0
      emit_bits_e(entropy, entropy->EOBRUN, nbits);
473
474
0
    entropy->EOBRUN = 0;
475
476
    /* Emit any buffered correction bits */
477
0
    emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
478
0
    entropy->BE = 0;
479
0
  }
480
0
}
481
482
483
/*
484
 * Emit a restart marker & resynchronize predictions.
485
 */
486
487
LOCAL(boolean)
488
emit_restart_s (working_state * state, int restart_num)
489
0
{
490
0
  int ci;
491
492
0
  if (! flush_bits_s(state))
493
0
    return FALSE;
494
495
0
  emit_byte_s(state, 0xFF, return FALSE);
496
0
  emit_byte_s(state, JPEG_RST0 + restart_num, return FALSE);
497
498
  /* Re-initialize DC predictions to 0 */
499
0
  for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
500
0
    state->cur.last_dc_val[ci] = 0;
501
502
  /* The restart counter is not updated until we successfully write the MCU. */
503
504
0
  return TRUE;
505
0
}
506
507
508
LOCAL(void)
509
emit_restart_e (huff_entropy_ptr entropy, int restart_num)
510
0
{
511
0
  int ci;
512
513
0
  emit_eobrun(entropy);
514
515
0
  if (! entropy->gather_statistics) {
516
0
    flush_bits_e(entropy);
517
0
    emit_byte_e(entropy, 0xFF);
518
0
    emit_byte_e(entropy, JPEG_RST0 + restart_num);
519
0
  }
520
521
0
  if (entropy->cinfo->Ss == 0) {
522
    /* Re-initialize DC predictions to 0 */
523
0
    for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
524
0
      entropy->saved.last_dc_val[ci] = 0;
525
0
  } else {
526
    /* Re-initialize all AC-related fields to 0 */
527
0
    entropy->EOBRUN = 0;
528
0
    entropy->BE = 0;
529
0
  }
530
0
}
531
532
533
/*
534
 * MCU encoding for DC initial scan (either spectral selection,
535
 * or first pass of successive approximation).
536
 */
537
538
METHODDEF(boolean)
539
encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)
540
0
{
541
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
542
0
  register int temp, temp2;
543
0
  register int nbits;
544
0
  int max_coef_bits;
545
0
  int blkn, ci, tbl;
546
0
  ISHIFT_TEMPS
547
548
0
  entropy->next_output_byte = cinfo->dest->next_output_byte;
549
0
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
550
551
  /* Emit restart marker if needed */
552
0
  if (cinfo->restart_interval)
553
0
    if (entropy->restarts_to_go == 0)
554
0
      emit_restart_e(entropy, entropy->next_restart_num);
555
556
  /* Since we're encoding a difference, the range limit is twice as much. */
557
0
  max_coef_bits = cinfo->data_precision + 3;
558
559
  /* Encode the MCU data blocks */
560
0
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
561
0
    ci = cinfo->MCU_membership[blkn];
562
0
    tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
563
564
    /* Compute the DC value after the required point transform by Al.
565
     * This is simply an arithmetic right shift.
566
     */
567
0
    temp = IRIGHT_SHIFT((int) (MCU_data[blkn][0][0]), cinfo->Al);
568
569
    /* DC differences are figured on the point-transformed values. */
570
0
    if ((temp2 = temp - entropy->saved.last_dc_val[ci]) == 0) {
571
      /* Count/emit the Huffman-coded symbol for the number of bits */
572
0
      emit_dc_symbol(entropy, tbl, 0);
573
574
0
      continue;
575
0
    }
576
577
0
    entropy->saved.last_dc_val[ci] = temp;
578
579
    /* Encode the DC coefficient difference per section G.1.2.1 */
580
0
    if ((temp = temp2) < 0) {
581
0
      temp = -temp;   /* temp is abs value of input */
582
      /* For a negative input, want temp2 = bitwise complement of abs(input) */
583
      /* This code assumes we are on a two's complement machine */
584
0
      temp2--;
585
0
    }
586
587
    /* Find the number of bits needed for the magnitude of the coefficient */
588
0
    nbits = 0;
589
0
    do nbits++;     /* there must be at least one 1 bit */
590
0
    while ((temp >>= 1));
591
    /* Check for out-of-range coefficient values */
592
0
    if (nbits > max_coef_bits)
593
0
      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
594
595
    /* Count/emit the Huffman-coded symbol for the number of bits */
596
0
    emit_dc_symbol(entropy, tbl, nbits);
597
598
    /* Emit that number of bits of the value, if positive, */
599
    /* or the complement of its magnitude, if negative. */
600
0
    emit_bits_e(entropy, (unsigned int) temp2, nbits);
601
0
  }
602
603
0
  cinfo->dest->next_output_byte = entropy->next_output_byte;
604
0
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
605
606
  /* Update restart-interval state too */
607
0
  if (cinfo->restart_interval) {
608
0
    if (entropy->restarts_to_go == 0) {
609
0
      entropy->restarts_to_go = cinfo->restart_interval;
610
0
      entropy->next_restart_num++;
611
0
      entropy->next_restart_num &= 7;
612
0
    }
613
0
    entropy->restarts_to_go--;
614
0
  }
615
616
0
  return TRUE;
617
0
}
618
619
620
/*
621
 * MCU encoding for AC initial scan (either spectral selection,
622
 * or first pass of successive approximation).
623
 */
624
625
METHODDEF(boolean)
626
encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)
627
0
{
628
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
629
0
  const int * natural_order;
630
0
  JBLOCKROW block;
631
0
  register int temp, temp2;
632
0
  register int nbits;
633
0
  register int r, k;
634
0
  int Se, Al, max_coef_bits;
635
636
0
  entropy->next_output_byte = cinfo->dest->next_output_byte;
637
0
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
638
639
  /* Emit restart marker if needed */
640
0
  if (cinfo->restart_interval)
641
0
    if (entropy->restarts_to_go == 0)
642
0
      emit_restart_e(entropy, entropy->next_restart_num);
643
644
0
  Se = cinfo->Se;
645
0
  Al = cinfo->Al;
646
0
  natural_order = cinfo->natural_order;
647
0
  max_coef_bits = cinfo->data_precision + 2;
648
649
  /* Encode the MCU data block */
650
0
  block = MCU_data[0];
651
652
  /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
653
  
654
0
  r = 0;      /* r = run length of zeros */
655
   
656
0
  for (k = cinfo->Ss; k <= Se; k++) {
657
0
    if ((temp = (*block)[natural_order[k]]) == 0) {
658
0
      r++;
659
0
      continue;
660
0
    }
661
    /* We must apply the point transform by Al.  For AC coefficients this
662
     * is an integer division with rounding towards 0.  To do this portably
663
     * in C, we shift after obtaining the absolute value; so the code is
664
     * interwoven with finding the abs value (temp) and output bits (temp2).
665
     */
666
0
    if (temp < 0) {
667
0
      temp = -temp;   /* temp is abs value of input */
668
      /* Apply the point transform, and watch out for case */
669
      /* that nonzero coef is zero after point transform. */
670
0
      if ((temp >>= Al) == 0) {
671
0
  r++;
672
0
  continue;
673
0
      }
674
      /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
675
0
      temp2 = ~temp;
676
0
    } else {
677
      /* Apply the point transform, and watch out for case */
678
      /* that nonzero coef is zero after point transform. */
679
0
      if ((temp >>= Al) == 0) {
680
0
  r++;
681
0
  continue;
682
0
      }
683
0
      temp2 = temp;
684
0
    }
685
686
    /* Emit any pending EOBRUN */
687
0
    if (entropy->EOBRUN > 0)
688
0
      emit_eobrun(entropy);
689
    /* if run length > 15, must emit special run-length-16 codes (0xF0) */
690
0
    while (r > 15) {
691
0
      emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);
692
0
      r -= 16;
693
0
    }
694
695
    /* Find the number of bits needed for the magnitude of the coefficient */
696
0
    nbits = 0;
697
0
    do nbits++;     /* there must be at least one 1 bit */
698
0
    while ((temp >>= 1));
699
    /* Check for out-of-range coefficient values */
700
0
    if (nbits > max_coef_bits)
701
0
      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
702
703
    /* Count/emit Huffman symbol for run length / number of bits */
704
0
    emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
705
706
    /* Emit that number of bits of the value, if positive, */
707
    /* or the complement of its magnitude, if negative. */
708
0
    emit_bits_e(entropy, (unsigned int) temp2, nbits);
709
710
0
    r = 0;      /* reset zero run length */
711
0
  }
712
713
0
  if (r > 0) {     /* If there are trailing zeroes, */
714
0
    entropy->EOBRUN++;    /* count an EOB */
715
0
    if (entropy->EOBRUN == 0x7FFF)
716
0
      emit_eobrun(entropy); /* force it out to avoid overflow */
717
0
  }
718
719
0
  cinfo->dest->next_output_byte = entropy->next_output_byte;
720
0
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
721
722
  /* Update restart-interval state too */
723
0
  if (cinfo->restart_interval) {
724
0
    if (entropy->restarts_to_go == 0) {
725
0
      entropy->restarts_to_go = cinfo->restart_interval;
726
0
      entropy->next_restart_num++;
727
0
      entropy->next_restart_num &= 7;
728
0
    }
729
0
    entropy->restarts_to_go--;
730
0
  }
731
732
0
  return TRUE;
733
0
}
734
735
736
/*
737
 * MCU encoding for DC successive approximation refinement scan.
738
 * Note: we assume such scans can be multi-component,
739
 * although the spec is not very clear on the point.
740
 */
741
742
METHODDEF(boolean)
743
encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)
744
0
{
745
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
746
0
  int Al, blkn;
747
748
0
  entropy->next_output_byte = cinfo->dest->next_output_byte;
749
0
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
750
751
  /* Emit restart marker if needed */
752
0
  if (cinfo->restart_interval)
753
0
    if (entropy->restarts_to_go == 0)
754
0
      emit_restart_e(entropy, entropy->next_restart_num);
755
756
0
  Al = cinfo->Al;
757
758
  /* Encode the MCU data blocks */
759
0
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
760
    /* We simply emit the Al'th bit of the DC coefficient value. */
761
0
    emit_bits_e(entropy, (unsigned int) (MCU_data[blkn][0][0] >> Al), 1);
762
0
  }
763
764
0
  cinfo->dest->next_output_byte = entropy->next_output_byte;
765
0
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
766
767
  /* Update restart-interval state too */
768
0
  if (cinfo->restart_interval) {
769
0
    if (entropy->restarts_to_go == 0) {
770
0
      entropy->restarts_to_go = cinfo->restart_interval;
771
0
      entropy->next_restart_num++;
772
0
      entropy->next_restart_num &= 7;
773
0
    }
774
0
    entropy->restarts_to_go--;
775
0
  }
776
777
0
  return TRUE;
778
0
}
779
780
781
/*
782
 * MCU encoding for AC successive approximation refinement scan.
783
 */
784
785
METHODDEF(boolean)
786
encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)
787
0
{
788
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
789
0
  const int * natural_order;
790
0
  JBLOCKROW block;
791
0
  register int temp;
792
0
  register int r, k;
793
0
  int Se, Al;
794
0
  int EOB;
795
0
  char *BR_buffer;
796
0
  unsigned int BR;
797
0
  int absvalues[DCTSIZE2];
798
799
0
  entropy->next_output_byte = cinfo->dest->next_output_byte;
800
0
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
801
802
  /* Emit restart marker if needed */
803
0
  if (cinfo->restart_interval)
804
0
    if (entropy->restarts_to_go == 0)
805
0
      emit_restart_e(entropy, entropy->next_restart_num);
806
807
0
  Se = cinfo->Se;
808
0
  Al = cinfo->Al;
809
0
  natural_order = cinfo->natural_order;
810
811
  /* Encode the MCU data block */
812
0
  block = MCU_data[0];
813
814
  /* It is convenient to make a pre-pass to determine the transformed
815
   * coefficients' absolute values and the EOB position.
816
   */
817
0
  EOB = 0;
818
0
  for (k = cinfo->Ss; k <= Se; k++) {
819
0
    temp = (*block)[natural_order[k]];
820
    /* We must apply the point transform by Al.  For AC coefficients this
821
     * is an integer division with rounding towards 0.  To do this portably
822
     * in C, we shift after obtaining the absolute value.
823
     */
824
0
    if (temp < 0)
825
0
      temp = -temp;   /* temp is abs value of input */
826
0
    temp >>= Al;    /* apply the point transform */
827
0
    absvalues[k] = temp;  /* save abs value for main pass */
828
0
    if (temp == 1)
829
0
      EOB = k;     /* EOB = index of last newly-nonzero coef */
830
0
  }
831
832
  /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
833
  
834
0
  r = 0;      /* r = run length of zeros */
835
0
  BR = 0;     /* BR = count of buffered bits added now */
836
0
  BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
837
838
0
  for (k = cinfo->Ss; k <= Se; k++) {
839
0
    if ((temp = absvalues[k]) == 0) {
840
0
      r++;
841
0
      continue;
842
0
    }
843
844
    /* Emit any required ZRLs, but not if they can be folded into EOB */
845
0
    while (r > 15 && k <= EOB) {
846
      /* emit any pending EOBRUN and the BE correction bits */
847
0
      emit_eobrun(entropy);
848
      /* Emit ZRL */
849
0
      emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);
850
0
      r -= 16;
851
      /* Emit buffered correction bits that must be associated with ZRL */
852
0
      emit_buffered_bits(entropy, BR_buffer, BR);
853
0
      BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
854
0
      BR = 0;
855
0
    }
856
857
    /* If the coef was previously nonzero, it only needs a correction bit.
858
     * NOTE: a straight translation of the spec's figure G.7 would suggest
859
     * that we also need to test r > 15.  But if r > 15, we can only get here
860
     * if k > EOB, which implies that this coefficient is not 1.
861
     */
862
0
    if (temp > 1) {
863
      /* The correction bit is the next bit of the absolute value. */
864
0
      BR_buffer[BR++] = (char) (temp & 1);
865
0
      continue;
866
0
    }
867
868
    /* Emit any pending EOBRUN and the BE correction bits */
869
0
    emit_eobrun(entropy);
870
871
    /* Count/emit Huffman symbol for run length / number of bits */
872
0
    emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
873
874
    /* Emit output bit for newly-nonzero coef */
875
0
    temp = ((*block)[natural_order[k]] < 0) ? 0 : 1;
876
0
    emit_bits_e(entropy, (unsigned int) temp, 1);
877
878
    /* Emit buffered correction bits that must be associated with this code */
879
0
    emit_buffered_bits(entropy, BR_buffer, BR);
880
0
    BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
881
0
    BR = 0;
882
0
    r = 0;      /* reset zero run length */
883
0
  }
884
885
0
  if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
886
0
    entropy->EOBRUN++;    /* count an EOB */
887
0
    entropy->BE += BR;    /* concat my correction bits to older ones */
888
    /* We force out the EOB if we risk either:
889
     * 1. overflow of the EOB counter;
890
     * 2. overflow of the correction bit buffer during the next MCU.
891
     */
892
0
    if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
893
0
      emit_eobrun(entropy);
894
0
  }
895
896
0
  cinfo->dest->next_output_byte = entropy->next_output_byte;
897
0
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
898
899
  /* Update restart-interval state too */
900
0
  if (cinfo->restart_interval) {
901
0
    if (entropy->restarts_to_go == 0) {
902
0
      entropy->restarts_to_go = cinfo->restart_interval;
903
0
      entropy->next_restart_num++;
904
0
      entropy->next_restart_num &= 7;
905
0
    }
906
0
    entropy->restarts_to_go--;
907
0
  }
908
909
0
  return TRUE;
910
0
}
911
912
913
/* Encode a single block's worth of coefficients */
914
915
LOCAL(boolean)
916
encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
917
      c_derived_tbl *dctbl, c_derived_tbl *actbl)
918
0
{
919
0
  register int temp, temp2;
920
0
  register int nbits;
921
0
  register int r, k;
922
0
  int Se = state->cinfo->lim_Se;
923
0
  int max_coef_bits = state->cinfo->data_precision + 3;
924
0
  const int * natural_order = state->cinfo->natural_order;
925
926
  /* Encode the DC coefficient difference per section F.1.2.1 */
927
928
0
  if ((temp = block[0] - last_dc_val) == 0) {
929
    /* Emit the Huffman-coded symbol for the number of bits */
930
0
    if (! emit_bits_s(state, dctbl->ehufco[0], dctbl->ehufsi[0]))
931
0
      return FALSE;
932
0
  } else {
933
0
    if ((temp2 = temp) < 0) {
934
0
      temp = -temp;   /* temp is abs value of input */
935
      /* For a negative input, want temp2 = bitwise complement of abs(input) */
936
      /* This code assumes we are on a two's complement machine */
937
0
      temp2--;
938
0
    }
939
940
    /* Find the number of bits needed for the magnitude of the coefficient */
941
0
    nbits = 0;
942
0
    do nbits++;     /* there must be at least one 1 bit */
943
0
    while ((temp >>= 1));
944
    /* Check for out-of-range coefficient values.
945
     * Since we're encoding a difference, the range limit is twice as much.
946
     */
947
0
    if (nbits > max_coef_bits)
948
0
      ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
949
950
    /* Emit the Huffman-coded symbol for the number of bits */
951
0
    if (! emit_bits_s(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
952
0
      return FALSE;
953
954
    /* Emit that number of bits of the value, if positive, */
955
    /* or the complement of its magnitude, if negative. */
956
0
    if (! emit_bits_s(state, (unsigned int) temp2, nbits))
957
0
      return FALSE;
958
0
  }
959
960
  /* Encode the AC coefficients per section F.1.2.2 */
961
962
0
  r = 0;      /* r = run length of zeros */
963
964
0
  for (k = 1; k <= Se; k++) {
965
0
    if ((temp = block[natural_order[k]]) == 0) {
966
0
      r++;
967
0
      continue;
968
0
    }
969
970
    /* if run length > 15, must emit special run-length-16 codes (0xF0) */
971
0
    while (r > 15) {
972
0
      if (! emit_bits_s(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
973
0
  return FALSE;
974
0
      r -= 16;
975
0
    }
976
977
0
    if ((temp2 = temp) < 0) {
978
0
      temp = -temp;   /* temp is abs value of input */
979
      /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
980
      /* This code assumes we are on a two's complement machine */
981
0
      temp2--;
982
0
    }
983
984
    /* Find the number of bits needed for the magnitude of the coefficient */
985
0
    nbits = 0;
986
0
    do nbits++;     /* there must be at least one 1 bit */
987
0
    while ((temp >>= 1));
988
    /* Check for out-of-range coefficient values.
989
     * Use ">=" instead of ">" so can use the
990
     * same one larger limit from DC check here.
991
     */
992
0
    if (nbits >= max_coef_bits)
993
0
      ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
994
995
    /* Emit Huffman symbol for run length / number of bits */
996
0
    temp = (r << 4) + nbits;
997
0
    if (! emit_bits_s(state, actbl->ehufco[temp], actbl->ehufsi[temp]))
998
0
      return FALSE;
999
1000
    /* Emit that number of bits of the value, if positive, */
1001
    /* or the complement of its magnitude, if negative. */
1002
0
    if (! emit_bits_s(state, (unsigned int) temp2, nbits))
1003
0
      return FALSE;
1004
1005
0
    r = 0;      /* reset zero run length */
1006
0
  }
1007
1008
  /* If the last coef(s) were zero, emit an end-of-block code */
1009
0
  if (r > 0)
1010
0
    if (! emit_bits_s(state, actbl->ehufco[0], actbl->ehufsi[0]))
1011
0
      return FALSE;
1012
1013
0
  return TRUE;
1014
0
}
1015
1016
1017
/*
1018
 * Encode and output one MCU's worth of Huffman-compressed coefficients.
1019
 */
1020
1021
METHODDEF(boolean)
1022
encode_mcu_huff (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)
1023
0
{
1024
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1025
0
  working_state state;
1026
0
  int blkn, ci;
1027
0
  jpeg_component_info * compptr;
1028
1029
  /* Load up working state */
1030
0
  state.next_output_byte = cinfo->dest->next_output_byte;
1031
0
  state.free_in_buffer = cinfo->dest->free_in_buffer;
1032
0
  ASSIGN_STATE(state.cur, entropy->saved);
1033
0
  state.cinfo = cinfo;
1034
1035
  /* Emit restart marker if needed */
1036
0
  if (cinfo->restart_interval) {
1037
0
    if (entropy->restarts_to_go == 0)
1038
0
      if (! emit_restart_s(&state, entropy->next_restart_num))
1039
0
  return FALSE;
1040
0
  }
1041
1042
  /* Encode the MCU data blocks */
1043
0
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
1044
0
    ci = cinfo->MCU_membership[blkn];
1045
0
    compptr = cinfo->cur_comp_info[ci];
1046
0
    if (! encode_one_block(&state,
1047
0
         MCU_data[blkn][0], state.cur.last_dc_val[ci],
1048
0
         entropy->dc_derived_tbls[compptr->dc_tbl_no],
1049
0
         entropy->ac_derived_tbls[compptr->ac_tbl_no]))
1050
0
      return FALSE;
1051
    /* Update last_dc_val */
1052
0
    state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
1053
0
  }
1054
1055
  /* Completed MCU, so update state */
1056
0
  cinfo->dest->next_output_byte = state.next_output_byte;
1057
0
  cinfo->dest->free_in_buffer = state.free_in_buffer;
1058
0
  ASSIGN_STATE(entropy->saved, state.cur);
1059
1060
  /* Update restart-interval state too */
1061
0
  if (cinfo->restart_interval) {
1062
0
    if (entropy->restarts_to_go == 0) {
1063
0
      entropy->restarts_to_go = cinfo->restart_interval;
1064
0
      entropy->next_restart_num++;
1065
0
      entropy->next_restart_num &= 7;
1066
0
    }
1067
0
    entropy->restarts_to_go--;
1068
0
  }
1069
1070
0
  return TRUE;
1071
0
}
1072
1073
1074
/*
1075
 * Finish up at the end of a Huffman-compressed scan.
1076
 */
1077
1078
METHODDEF(void)
1079
finish_pass_huff (j_compress_ptr cinfo)
1080
0
{
1081
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1082
0
  working_state state;
1083
1084
0
  if (cinfo->progressive_mode) {
1085
0
    entropy->next_output_byte = cinfo->dest->next_output_byte;
1086
0
    entropy->free_in_buffer = cinfo->dest->free_in_buffer;
1087
1088
    /* Flush out any buffered data */
1089
0
    emit_eobrun(entropy);
1090
0
    flush_bits_e(entropy);
1091
1092
0
    cinfo->dest->next_output_byte = entropy->next_output_byte;
1093
0
    cinfo->dest->free_in_buffer = entropy->free_in_buffer;
1094
0
  } else {
1095
    /* Load up working state ... flush_bits needs it */
1096
0
    state.next_output_byte = cinfo->dest->next_output_byte;
1097
0
    state.free_in_buffer = cinfo->dest->free_in_buffer;
1098
0
    ASSIGN_STATE(state.cur, entropy->saved);
1099
0
    state.cinfo = cinfo;
1100
1101
    /* Flush out the last data */
1102
0
    if (! flush_bits_s(&state))
1103
0
      ERREXIT(cinfo, JERR_CANT_SUSPEND);
1104
1105
    /* Update state */
1106
0
    cinfo->dest->next_output_byte = state.next_output_byte;
1107
0
    cinfo->dest->free_in_buffer = state.free_in_buffer;
1108
0
    ASSIGN_STATE(entropy->saved, state.cur);
1109
0
  }
1110
0
}
1111
1112
1113
/*
1114
 * Huffman coding optimization.
1115
 *
1116
 * We first scan the supplied data and count the number of uses of each symbol
1117
 * that is to be Huffman-coded. (This process MUST agree with the code above.)
1118
 * Then we build a Huffman coding tree for the observed counts.
1119
 * Symbols which are not needed at all for the particular image are not
1120
 * assigned any code, which saves space in the DHT marker as well as in
1121
 * the compressed data.
1122
 */
1123
1124
1125
/* Process a single block's worth of coefficients */
1126
1127
LOCAL(void)
1128
htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
1129
     long dc_counts[], long ac_counts[])
1130
0
{
1131
0
  register int temp;
1132
0
  register int nbits;
1133
0
  register int r, k;
1134
0
  int Se = cinfo->lim_Se;
1135
0
  int max_coef_bits = cinfo->data_precision + 3;
1136
0
  const int * natural_order = cinfo->natural_order;
1137
1138
  /* Encode the DC coefficient difference per section F.1.2.1 */
1139
1140
0
  if ((temp = block[0] - last_dc_val) == 0) {
1141
    /* Count the Huffman symbol for the number of bits */
1142
0
    dc_counts[0]++;
1143
0
  } else {
1144
0
    if (temp < 0)
1145
0
      temp = -temp;   /* temp is abs value of input */
1146
1147
    /* Find the number of bits needed for the magnitude of the coefficient */
1148
0
    nbits = 0;
1149
0
    do nbits++;     /* there must be at least one 1 bit */
1150
0
    while ((temp >>= 1));
1151
    /* Check for out-of-range coefficient values.
1152
     * Since we're encoding a difference, the range limit is twice as much.
1153
     */
1154
0
    if (nbits > max_coef_bits)
1155
0
      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
1156
1157
    /* Count the Huffman symbol for the number of bits */
1158
0
    dc_counts[nbits]++;
1159
0
  }
1160
1161
  /* Encode the AC coefficients per section F.1.2.2 */
1162
1163
0
  r = 0;      /* r = run length of zeros */
1164
1165
0
  for (k = 1; k <= Se; k++) {
1166
0
    if ((temp = block[natural_order[k]]) == 0) {
1167
0
      r++;
1168
0
      continue;
1169
0
    }
1170
1171
    /* if run length > 15, must emit special run-length-16 codes (0xF0) */
1172
0
    while (r > 15) {
1173
0
      ac_counts[0xF0]++;
1174
0
      r -= 16;
1175
0
    }
1176
1177
0
    if (temp < 0)
1178
0
      temp = -temp;   /* temp is abs value of input */
1179
1180
    /* Find the number of bits needed for the magnitude of the coefficient */
1181
0
    nbits = 0;
1182
0
    do nbits++;     /* there must be at least one 1 bit */
1183
0
    while ((temp >>= 1));
1184
    /* Check for out-of-range coefficient values.
1185
     * Use ">=" instead of ">" so can use the
1186
     * same one larger limit from DC check here.
1187
     */
1188
0
    if (nbits >= max_coef_bits)
1189
0
      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
1190
1191
    /* Count Huffman symbol for run length / number of bits */
1192
0
    ac_counts[(r << 4) + nbits]++;
1193
1194
0
    r = 0;      /* reset zero run length */
1195
0
  }
1196
1197
  /* If the last coef(s) were zero, emit an end-of-block code */
1198
0
  if (r > 0)
1199
0
    ac_counts[0]++;
1200
0
}
1201
1202
1203
/*
1204
 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
1205
 * No data is actually output, so no suspension return is possible.
1206
 */
1207
1208
METHODDEF(boolean)
1209
encode_mcu_gather (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)
1210
0
{
1211
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1212
0
  int blkn, ci;
1213
0
  jpeg_component_info * compptr;
1214
1215
  /* Take care of restart intervals if needed */
1216
0
  if (cinfo->restart_interval) {
1217
0
    if (entropy->restarts_to_go == 0) {
1218
      /* Re-initialize DC predictions to 0 */
1219
0
      for (ci = 0; ci < cinfo->comps_in_scan; ci++)
1220
0
  entropy->saved.last_dc_val[ci] = 0;
1221
      /* Update restart state */
1222
0
      entropy->restarts_to_go = cinfo->restart_interval;
1223
0
    }
1224
0
    entropy->restarts_to_go--;
1225
0
  }
1226
1227
0
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
1228
0
    ci = cinfo->MCU_membership[blkn];
1229
0
    compptr = cinfo->cur_comp_info[ci];
1230
0
    htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
1231
0
        entropy->dc_count_ptrs[compptr->dc_tbl_no],
1232
0
        entropy->ac_count_ptrs[compptr->ac_tbl_no]);
1233
0
    entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
1234
0
  }
1235
1236
0
  return TRUE;
1237
0
}
1238
1239
1240
/*
1241
 * Generate the best Huffman code table for the given counts, fill htbl.
1242
 *
1243
 * The JPEG standard requires that no symbol be assigned a codeword of all
1244
 * one bits (so that padding bits added at the end of a compressed segment
1245
 * can't look like a valid code).  Because of the canonical ordering of
1246
 * codewords, this just means that there must be an unused slot in the
1247
 * longest codeword length category.  Section K.2 of the JPEG spec suggests
1248
 * reserving such a slot by pretending that symbol 256 is a valid symbol
1249
 * with count 1.  In theory that's not optimal; giving it count zero but
1250
 * including it in the symbol set anyway should give a better Huffman code.
1251
 * But the theoretically better code actually seems to come out worse in
1252
 * practice, because it produces more all-ones bytes (which incur stuffed
1253
 * zero bytes in the final file).  In any case the difference is tiny.
1254
 *
1255
 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
1256
 * If some symbols have a very small but nonzero probability, the Huffman tree
1257
 * must be adjusted to meet the code length restriction.  We currently use
1258
 * the adjustment method suggested in JPEG section K.2.  This method is *not*
1259
 * optimal; it may not choose the best possible limited-length code.  But
1260
 * typically only very-low-frequency symbols will be given less-than-optimal
1261
 * lengths, so the code is almost optimal.  Experimental comparisons against
1262
 * an optimal limited-length-code algorithm indicate that the difference is
1263
 * microscopic --- usually less than a hundredth of a percent of total size.
1264
 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
1265
 */
1266
1267
LOCAL(void)
1268
jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
1269
0
{
1270
0
#define MAX_CLEN 32    /* assumed maximum initial code length */
1271
0
  UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
1272
0
  int codesize[257];    /* codesize[k] = code length of symbol k */
1273
0
  int others[257];    /* next symbol in current branch of tree */
1274
0
  int c1, c2, i, j;
1275
0
  UINT8 *p;
1276
0
  long v;
1277
1278
0
  freq[256] = 1;    /* make sure 256 has a nonzero count */
1279
  /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
1280
   * that no real symbol is given code-value of all ones, because 256
1281
   * will be placed last in the largest codeword category.
1282
   * In the symbol list build procedure this element serves as sentinel
1283
   * for the zero run loop.
1284
   */
1285
1286
0
#ifndef DONT_USE_FANCY_HUFF_OPT
1287
1288
  /* Build list of symbols sorted in order of descending frequency */
1289
  /* This approach has several benefits (thank to John Korejwa for the idea):
1290
   *     1.
1291
   * If a codelength category is split during the length limiting procedure
1292
   * below, the feature that more frequent symbols are assigned shorter
1293
   * codewords remains valid for the adjusted code.
1294
   *     2.
1295
   * To reduce consecutive ones in a Huffman data stream (thus reducing the
1296
   * number of stuff bytes in JPEG) it is preferable to follow 0 branches
1297
   * (and avoid 1 branches) as much as possible.  This is easily done by
1298
   * assigning symbols to leaves of the Huffman tree in order of decreasing
1299
   * frequency, with no secondary sort based on codelengths.
1300
   *     3.
1301
   * The symbol list can be built independently from the assignment of code
1302
   * lengths by the Huffman procedure below.
1303
   * Note: The symbol list build procedure must be performed first, because
1304
   * the Huffman procedure assigning the codelengths clobbers the frequency
1305
   * counts!
1306
   */
1307
1308
  /* Here we use the others array as a linked list of nonzero frequencies
1309
   * to be sorted.  Already sorted elements are removed from the list.
1310
   */
1311
1312
  /* Building list */
1313
1314
  /* This item does not correspond to a valid symbol frequency and is used
1315
   * as starting index.
1316
   */
1317
0
  j = 256;
1318
1319
0
  for (i = 0;; i++) {
1320
0
    if (freq[i] == 0)   /* skip zero frequencies */
1321
0
      continue;
1322
0
    if (i > 255)
1323
0
      break;
1324
0
    others[j] = i;    /* this symbol value */
1325
0
    j = i;      /* previous symbol value */
1326
0
  }
1327
0
  others[j] = -1;   /* mark end of list */
1328
1329
  /* Sorting list */
1330
1331
0
  p = htbl->huffval;
1332
0
  while ((c1 = others[256]) >= 0) {
1333
0
    v = freq[c1];
1334
0
    i = c1;     /* first symbol value */
1335
0
    j = 256;      /* pseudo symbol value for starting index */
1336
0
    while ((c2 = others[c1]) >= 0) {
1337
0
      if (freq[c2] > v) {
1338
0
  v = freq[c2];
1339
0
  i = c2;     /* this symbol value */
1340
0
  j = c1;     /* previous symbol value */
1341
0
      }
1342
0
      c1 = c2;
1343
0
    }
1344
0
    others[j] = others[i];  /* remove this symbol i from list */
1345
0
    *p++ = (UINT8) i;
1346
0
  }
1347
1348
0
#endif /* DONT_USE_FANCY_HUFF_OPT */
1349
1350
  /* This algorithm is explained in section K.2 of the JPEG standard */
1351
1352
0
  MEMZERO(bits, SIZEOF(bits));
1353
0
  MEMZERO(codesize, SIZEOF(codesize));
1354
0
  for (i = 0; i < 257; i++)
1355
0
    others[i] = -1;   /* init links to empty */
1356
1357
  /* Huffman's basic algorithm to assign optimal code lengths to symbols */
1358
1359
0
  for (;;) {
1360
    /* Find the smallest nonzero frequency, set c1 = its symbol */
1361
    /* In case of ties, take the larger symbol number */
1362
0
    c1 = -1;
1363
0
    v = 1000000000L;
1364
0
    for (i = 0; i <= 256; i++) {
1365
0
      if (freq[i] && freq[i] <= v) {
1366
0
  v = freq[i];
1367
0
  c1 = i;
1368
0
      }
1369
0
    }
1370
1371
    /* Find the next smallest nonzero frequency, set c2 = its symbol */
1372
    /* In case of ties, take the larger symbol number */
1373
0
    c2 = -1;
1374
0
    v = 1000000000L;
1375
0
    for (i = 0; i <= 256; i++) {
1376
0
      if (freq[i] && freq[i] <= v && i != c1) {
1377
0
  v = freq[i];
1378
0
  c2 = i;
1379
0
      }
1380
0
    }
1381
1382
    /* Done if we've merged everything into one frequency */
1383
0
    if (c2 < 0)
1384
0
      break;
1385
1386
    /* Else merge the two counts/trees */
1387
0
    freq[c1] += freq[c2];
1388
0
    freq[c2] = 0;
1389
1390
    /* Increment the codesize of everything in c1's tree branch */
1391
0
    codesize[c1]++;
1392
0
    while (others[c1] >= 0) {
1393
0
      c1 = others[c1];
1394
0
      codesize[c1]++;
1395
0
    }
1396
1397
0
    others[c1] = c2;    /* chain c2 onto c1's tree branch */
1398
1399
    /* Increment the codesize of everything in c2's tree branch */
1400
0
    codesize[c2]++;
1401
0
    while (others[c2] >= 0) {
1402
0
      c2 = others[c2];
1403
0
      codesize[c2]++;
1404
0
    }
1405
0
  }
1406
1407
  /* Now count the number of symbols of each code length */
1408
0
  for (i = 0; i <= 256; i++) {
1409
0
    if (codesize[i]) {
1410
      /* The JPEG standard seems to think that this can't happen, */
1411
      /* but I'm paranoid... */
1412
0
      if (codesize[i] > MAX_CLEN)
1413
0
  ERREXIT(cinfo, JERR_HUFF_CLEN_OUTOFBOUNDS);
1414
1415
0
      bits[codesize[i]]++;
1416
0
    }
1417
0
  }
1418
1419
  /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
1420
   * Huffman procedure assigned any such lengths, we must adjust the coding.
1421
   * Here is what the JPEG spec says about how this next bit works:
1422
   * Since symbols are paired for the longest Huffman code, the symbols are
1423
   * removed from this length category two at a time.  The prefix for the pair
1424
   * (which is one bit shorter) is allocated to one of the pair; then,
1425
   * skipping the BITS entry for that prefix length, a code word from the next
1426
   * shortest nonzero BITS entry is converted into a prefix for two code words
1427
   * one bit longer.
1428
   */
1429
1430
0
  for (i = MAX_CLEN; i > 16; i--) {
1431
0
    while (bits[i] > 0) {
1432
0
      j = i - 2;    /* find length of new prefix to be used */
1433
0
      while (bits[j] == 0) {
1434
0
  if (j == 0)
1435
0
    ERREXIT(cinfo, JERR_HUFF_CLEN_OUTOFBOUNDS);
1436
0
  j--;
1437
0
      }
1438
1439
0
      bits[i] -= 2;   /* remove two symbols */
1440
0
      bits[i-1]++;    /* one goes in this length */
1441
0
      bits[j+1] += 2;   /* two new symbols in this length */
1442
0
      bits[j]--;    /* symbol of this length is now a prefix */
1443
0
    }
1444
0
  }
1445
1446
  /* Remove the count for the pseudo-symbol 256 from the largest codelength */
1447
0
  while (bits[i] == 0)   /* find largest codelength still in use */
1448
0
    i--;
1449
0
  bits[i]--;
1450
1451
  /* Return final symbol counts (only for lengths 0..16) */
1452
0
  MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
1453
1454
#ifdef DONT_USE_FANCY_HUFF_OPT
1455
1456
  /* Return a list of the symbols sorted by code length */
1457
  /* Note: Due to the codelength changes made above, it can happen
1458
   * that more frequent symbols are assigned longer codewords.
1459
   */
1460
  p = htbl->huffval;
1461
  for (i = 1; i <= MAX_CLEN; i++) {
1462
    for (j = 0; j <= 255; j++) {
1463
      if (codesize[j] == i) {
1464
  *p++ = (UINT8) j;
1465
      }
1466
    }
1467
  }
1468
1469
#endif /* DONT_USE_FANCY_HUFF_OPT */
1470
1471
  /* Set sent_table FALSE so updated table will be written to JPEG file. */
1472
0
  htbl->sent_table = FALSE;
1473
0
}
1474
1475
1476
/*
1477
 * Finish up a statistics-gathering pass and create the new Huffman tables.
1478
 */
1479
1480
METHODDEF(void)
1481
finish_pass_gather (j_compress_ptr cinfo)
1482
0
{
1483
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1484
0
  int ci, tbl;
1485
0
  jpeg_component_info * compptr;
1486
0
  JHUFF_TBL **htblptr;
1487
0
  boolean did_dc[NUM_HUFF_TBLS];
1488
0
  boolean did_ac[NUM_HUFF_TBLS];
1489
1490
0
  if (cinfo->progressive_mode)
1491
    /* Flush out buffered data (all we care about is counting the EOB symbol) */
1492
0
    emit_eobrun(entropy);
1493
1494
  /* It's important not to apply jpeg_gen_optimal_table more than once
1495
   * per table, because it clobbers the input frequency counts!
1496
   */
1497
0
  MEMZERO(did_dc, SIZEOF(did_dc));
1498
0
  MEMZERO(did_ac, SIZEOF(did_ac));
1499
1500
0
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1501
0
    compptr = cinfo->cur_comp_info[ci];
1502
    /* DC needs no table for refinement scan */
1503
0
    if (cinfo->Ss == 0 && cinfo->Ah == 0) {
1504
0
      tbl = compptr->dc_tbl_no;
1505
0
      if (! did_dc[tbl]) {
1506
0
  htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
1507
0
  if (*htblptr == NULL)
1508
0
    *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
1509
0
  jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[tbl]);
1510
0
  did_dc[tbl] = TRUE;
1511
0
      }
1512
0
    }
1513
    /* AC needs no table when not present */
1514
0
    if (cinfo->Se) {
1515
0
      tbl = compptr->ac_tbl_no;
1516
0
      if (! did_ac[tbl]) {
1517
0
  htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
1518
0
  if (*htblptr == NULL)
1519
0
    *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
1520
0
  jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[tbl]);
1521
0
  did_ac[tbl] = TRUE;
1522
0
      }
1523
0
    }
1524
0
  }
1525
0
}
1526
1527
1528
/*
1529
 * Initialize for a Huffman-compressed scan.
1530
 * If gather_statistics is TRUE, we do not output anything during the scan,
1531
 * just count the Huffman symbols used and generate Huffman code tables.
1532
 */
1533
1534
METHODDEF(void)
1535
start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
1536
0
{
1537
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1538
0
  int ci, tbl;
1539
0
  jpeg_component_info * compptr;
1540
1541
0
  if (gather_statistics)
1542
0
    entropy->pub.finish_pass = finish_pass_gather;
1543
0
  else
1544
0
    entropy->pub.finish_pass = finish_pass_huff;
1545
1546
0
  if (cinfo->progressive_mode) {
1547
0
    entropy->cinfo = cinfo;
1548
0
    entropy->gather_statistics = gather_statistics;
1549
1550
    /* We assume jcmaster.c already validated the scan parameters. */
1551
1552
    /* Select execution routine */
1553
0
    if (cinfo->Ah == 0) {
1554
0
      if (cinfo->Ss == 0)
1555
0
  entropy->pub.encode_mcu = encode_mcu_DC_first;
1556
0
      else
1557
0
  entropy->pub.encode_mcu = encode_mcu_AC_first;
1558
0
    } else {
1559
0
      if (cinfo->Ss == 0)
1560
0
  entropy->pub.encode_mcu = encode_mcu_DC_refine;
1561
0
      else {
1562
0
  entropy->pub.encode_mcu = encode_mcu_AC_refine;
1563
  /* AC refinement needs a correction bit buffer */
1564
0
  if (entropy->bit_buffer == NULL)
1565
0
    entropy->bit_buffer = (char *) (*cinfo->mem->alloc_small)
1566
0
      ((j_common_ptr) cinfo, JPOOL_IMAGE, MAX_CORR_BITS * SIZEOF(char));
1567
0
      }
1568
0
    }
1569
1570
    /* Initialize AC stuff */
1571
0
    entropy->ac_tbl_no = cinfo->cur_comp_info[0]->ac_tbl_no;
1572
0
    entropy->EOBRUN = 0;
1573
0
    entropy->BE = 0;
1574
0
  } else {
1575
0
    if (gather_statistics)
1576
0
      entropy->pub.encode_mcu = encode_mcu_gather;
1577
0
    else
1578
0
      entropy->pub.encode_mcu = encode_mcu_huff;
1579
0
  }
1580
1581
0
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1582
0
    compptr = cinfo->cur_comp_info[ci];
1583
    /* DC needs no table for refinement scan */
1584
0
    if (cinfo->Ss == 0 && cinfo->Ah == 0) {
1585
0
      tbl = compptr->dc_tbl_no;
1586
0
      if (gather_statistics) {
1587
  /* Check for invalid table index */
1588
  /* (make_c_derived_tbl does this in the other path) */
1589
0
  if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
1590
0
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
1591
  /* Allocate and zero the statistics tables */
1592
  /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
1593
0
  if (entropy->dc_count_ptrs[tbl] == NULL)
1594
0
    entropy->dc_count_ptrs[tbl] = (long *) (*cinfo->mem->alloc_small)
1595
0
      ((j_common_ptr) cinfo, JPOOL_IMAGE, 257 * SIZEOF(long));
1596
0
  MEMZERO(entropy->dc_count_ptrs[tbl], 257 * SIZEOF(long));
1597
0
      } else {
1598
  /* Compute derived values for Huffman tables */
1599
  /* We may do this more than once for a table, but it's not expensive */
1600
0
  jpeg_make_c_derived_tbl(cinfo, TRUE, tbl,
1601
0
        & entropy->dc_derived_tbls[tbl]);
1602
0
      }
1603
      /* Initialize DC predictions to 0 */
1604
0
      entropy->saved.last_dc_val[ci] = 0;
1605
0
    }
1606
    /* AC needs no table when not present */
1607
0
    if (cinfo->Se) {
1608
0
      tbl = compptr->ac_tbl_no;
1609
0
      if (gather_statistics) {
1610
0
  if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
1611
0
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
1612
0
  if (entropy->ac_count_ptrs[tbl] == NULL)
1613
0
    entropy->ac_count_ptrs[tbl] = (long *) (*cinfo->mem->alloc_small)
1614
0
      ((j_common_ptr) cinfo, JPOOL_IMAGE, 257 * SIZEOF(long));
1615
0
  MEMZERO(entropy->ac_count_ptrs[tbl], 257 * SIZEOF(long));
1616
0
      } else {
1617
0
  jpeg_make_c_derived_tbl(cinfo, FALSE, tbl,
1618
0
        & entropy->ac_derived_tbls[tbl]);
1619
0
      }
1620
0
    }
1621
0
  }
1622
1623
  /* Initialize bit buffer to empty */
1624
0
  entropy->saved.put_buffer = 0;
1625
0
  entropy->saved.put_bits = 0;
1626
1627
  /* Initialize restart stuff */
1628
0
  entropy->restarts_to_go = cinfo->restart_interval;
1629
0
  entropy->next_restart_num = 0;
1630
0
}
1631
1632
1633
/*
1634
 * Module initialization routine for Huffman entropy encoding.
1635
 */
1636
1637
GLOBAL(void)
1638
jinit_huff_encoder (j_compress_ptr cinfo)
1639
0
{
1640
0
  huff_entropy_ptr entropy;
1641
0
  int i;
1642
1643
0
  entropy = (huff_entropy_ptr) (*cinfo->mem->alloc_small)
1644
0
    ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(huff_entropy_encoder));
1645
0
  cinfo->entropy = &entropy->pub;
1646
0
  entropy->pub.start_pass = start_pass_huff;
1647
1648
  /* Mark tables unallocated */
1649
0
  for (i = 0; i < NUM_HUFF_TBLS; i++) {
1650
0
    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
1651
0
    entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
1652
0
  }
1653
1654
0
  if (cinfo->progressive_mode)
1655
0
    entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
1656
0
}