blob: 526203e3db73b688ed67c900b0f80f59da953bcc [file] [log] [blame]
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001/*
2 * jchuff.c
3 *
DRCa73e8702012-12-31 02:52:30 +00004 * This file was part of the Independent JPEG Group's software:
Thomas G. Lane5ead57a1998-03-27 00:00:00 +00005 * Copyright (C) 1991-1997, Thomas G. Lane.
DRCa6ef2822013-09-28 03:23:49 +00006 * libjpeg-turbo Modifications:
DRC6399d0a2019-04-23 14:10:04 -05007 * Copyright (C) 2009-2011, 2014-2016, 2018-2019, D. R. Commander.
DRC123f7252016-05-24 10:23:56 -05008 * Copyright (C) 2015, Matthieu Darbois.
DRC7e3acc02015-10-10 10:25:46 -05009 * For conditions of distribution and use, see the accompanying README.ijg
10 * file.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000011 *
12 * This file contains Huffman entropy encoding routines.
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000013 *
14 * Much of the complexity here has to do with supporting output suspension.
15 * If the data destination module demands suspension, we want to be able to
16 * back up to the start of the current MCU. To do this, we copy state
17 * variables into local working storage, and update them back to the
18 * permanent JPEG objects only upon successful completion of an MCU.
DRCa6289522018-07-24 18:36:51 -050019 *
20 * NOTE: All referenced figures are from
21 * Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000022 */
23
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000024#define JPEG_INTERNALS
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000025#include "jinclude.h"
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000026#include "jpeglib.h"
DRCf3a86842016-01-07 00:19:43 -060027#include "jsimd.h"
DRC5a3b4fe2016-01-06 19:17:54 -060028#include "jconfigint.h"
DRC8443e522009-07-30 08:35:06 +000029#include <limits.h>
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000030
DRC0cfc4c12014-03-28 18:33:25 +000031/*
32 * NOTE: If USE_CLZ_INTRINSIC is defined, then clz/bsr instructions will be
33 * used for bit counting rather than the lookup table. This will reduce the
34 * memory footprint by 64k, which is important for some mobile applications
35 * that create many isolated instances of libjpeg-turbo (web browsers, for
36 * instance.) This may improve performance on some mobile platforms as well.
37 * This feature is enabled by default only on ARM processors, because some x86
38 * chips have a slow implementation of bsr, and the use of clz/bsr cannot be
39 * shown to have a significant performance impact even on the x86 chips that
40 * have a fast implementation of it. When building for ARMv6, you can
41 * explicitly disable the use of clz/bsr by adding -mthumb to the compiler
42 * flags (this defines __thumb__).
43 */
44
45/* NOTE: Both GCC and Clang define __GNUC__ */
DRC803b5d22014-11-18 15:56:43 +000046#if defined __GNUC__ && (defined __arm__ || defined __aarch64__)
DRC0cfc4c12014-03-28 18:33:25 +000047#if !defined __thumb__ || defined __thumb2__
48#define USE_CLZ_INTRINSIC
49#endif
50#endif
51
52#ifdef USE_CLZ_INTRINSIC
DRC293263c2018-03-17 15:14:35 -050053#define JPEG_NBITS_NONZERO(x) (32 - __builtin_clz(x))
54#define JPEG_NBITS(x) (x ? JPEG_NBITS_NONZERO(x) : 0)
DRC0cfc4c12014-03-28 18:33:25 +000055#else
DRCef9a4e02014-03-28 18:50:30 +000056#include "jpeg_nbits_table.h"
DRC293263c2018-03-17 15:14:35 -050057#define JPEG_NBITS(x) (jpeg_nbits_table[x])
58#define JPEG_NBITS_NONZERO(x) JPEG_NBITS(x)
DRC0cfc4c12014-03-28 18:33:25 +000059#endif
DRC99313382009-03-12 17:24:27 +000060
DRC6bb57b72011-04-26 22:08:31 +000061
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000062/* Expanded entropy encoder object for Huffman encoding.
63 *
64 * The savable_state subrecord contains fields that change within an MCU,
65 * but must not be updated permanently until we complete the MCU.
66 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000067
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000068typedef struct {
DRC19c791c2018-03-08 10:55:20 -060069 size_t put_buffer; /* current bit-accumulation buffer */
70 int put_bits; /* # of bits now in it */
71 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000072} savable_state;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000073
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000074/* This macro is to work around compilers with missing or broken
75 * structure assignment. You'll need to fix this code if you have
76 * such a compiler and you change MAX_COMPS_IN_SCAN.
77 */
78
79#ifndef NO_STRUCT_ASSIGN
DRC19c791c2018-03-08 10:55:20 -060080#define ASSIGN_STATE(dest, src) ((dest) = (src))
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000081#else
82#if MAX_COMPS_IN_SCAN == 4
DRC19c791c2018-03-08 10:55:20 -060083#define ASSIGN_STATE(dest, src) \
84 ((dest).put_buffer = (src).put_buffer, \
85 (dest).put_bits = (src).put_bits, \
86 (dest).last_dc_val[0] = (src).last_dc_val[0], \
87 (dest).last_dc_val[1] = (src).last_dc_val[1], \
88 (dest).last_dc_val[2] = (src).last_dc_val[2], \
89 (dest).last_dc_val[3] = (src).last_dc_val[3])
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000090#endif
91#endif
92
93
94typedef struct {
95 struct jpeg_entropy_encoder pub; /* public fields */
96
DRCe5eaf372014-05-09 18:00:32 +000097 savable_state saved; /* Bit buffer & DC state at start of MCU */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000098
99 /* These fields are NOT loaded into local working state. */
DRCe5eaf372014-05-09 18:00:32 +0000100 unsigned int restarts_to_go; /* MCUs left in this restart interval */
101 int next_restart_num; /* next restart number to write (0-7) */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000102
103 /* Pointers to derived tables (these workspaces have image lifespan) */
DRCbd498032016-02-19 08:53:33 -0600104 c_derived_tbl *dc_derived_tbls[NUM_HUFF_TBLS];
105 c_derived_tbl *ac_derived_tbls[NUM_HUFF_TBLS];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000106
DRCe5eaf372014-05-09 18:00:32 +0000107#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
DRCbd498032016-02-19 08:53:33 -0600108 long *dc_count_ptrs[NUM_HUFF_TBLS];
109 long *ac_count_ptrs[NUM_HUFF_TBLS];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000110#endif
DRCf3a86842016-01-07 00:19:43 -0600111
112 int simd;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000113} huff_entropy_encoder;
114
DRCbd498032016-02-19 08:53:33 -0600115typedef huff_entropy_encoder *huff_entropy_ptr;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000116
117/* Working state while writing an MCU.
118 * This struct contains all the fields that are needed by subroutines.
119 */
120
121typedef struct {
DRCbd498032016-02-19 08:53:33 -0600122 JOCTET *next_output_byte; /* => next byte to write in buffer */
DRCe5eaf372014-05-09 18:00:32 +0000123 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
124 savable_state cur; /* Current bit buffer & DC state */
125 j_compress_ptr cinfo; /* dump_buffer needs access to this */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000126} working_state;
127
128
129/* Forward declarations */
DRC19c791c2018-03-08 10:55:20 -0600130METHODDEF(boolean) encode_mcu_huff(j_compress_ptr cinfo, JBLOCKROW *MCU_data);
131METHODDEF(void) finish_pass_huff(j_compress_ptr cinfo);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000132#ifdef ENTROPY_OPT_SUPPORTED
DRC19c791c2018-03-08 10:55:20 -0600133METHODDEF(boolean) encode_mcu_gather(j_compress_ptr cinfo,
134 JBLOCKROW *MCU_data);
135METHODDEF(void) finish_pass_gather(j_compress_ptr cinfo);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000136#endif
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000137
138
139/*
140 * Initialize for a Huffman-compressed scan.
141 * If gather_statistics is TRUE, we do not output anything during the scan,
142 * just count the Huffman symbols used and generate Huffman code tables.
143 */
144
Thomas G. Lane489583f1996-02-07 00:00:00 +0000145METHODDEF(void)
DRC19c791c2018-03-08 10:55:20 -0600146start_pass_huff(j_compress_ptr cinfo, boolean gather_statistics)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000147{
DRC19c791c2018-03-08 10:55:20 -0600148 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000149 int ci, dctbl, actbl;
DRCbd498032016-02-19 08:53:33 -0600150 jpeg_component_info *compptr;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000151
152 if (gather_statistics) {
153#ifdef ENTROPY_OPT_SUPPORTED
154 entropy->pub.encode_mcu = encode_mcu_gather;
155 entropy->pub.finish_pass = finish_pass_gather;
156#else
157 ERREXIT(cinfo, JERR_NOT_COMPILED);
158#endif
159 } else {
160 entropy->pub.encode_mcu = encode_mcu_huff;
161 entropy->pub.finish_pass = finish_pass_huff;
162 }
163
DRCf3a86842016-01-07 00:19:43 -0600164 entropy->simd = jsimd_can_huff_encode_one_block();
165
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000166 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
167 compptr = cinfo->cur_comp_info[ci];
168 dctbl = compptr->dc_tbl_no;
169 actbl = compptr->ac_tbl_no;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000170 if (gather_statistics) {
171#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000172 /* Check for invalid table indexes */
173 /* (make_c_derived_tbl does this in the other path) */
174 if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
DRCe5eaf372014-05-09 18:00:32 +0000175 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000176 if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
DRCe5eaf372014-05-09 18:00:32 +0000177 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000178 /* Allocate and zero the statistics tables */
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000179 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000180 if (entropy->dc_count_ptrs[dctbl] == NULL)
DRCe5eaf372014-05-09 18:00:32 +0000181 entropy->dc_count_ptrs[dctbl] = (long *)
DRC19c791c2018-03-08 10:55:20 -0600182 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
DRC5de454b2014-05-18 19:04:03 +0000183 257 * sizeof(long));
184 MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * sizeof(long));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000185 if (entropy->ac_count_ptrs[actbl] == NULL)
DRCe5eaf372014-05-09 18:00:32 +0000186 entropy->ac_count_ptrs[actbl] = (long *)
DRC19c791c2018-03-08 10:55:20 -0600187 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
DRC5de454b2014-05-18 19:04:03 +0000188 257 * sizeof(long));
189 MEMZERO(entropy->ac_count_ptrs[actbl], 257 * sizeof(long));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000190#endif
191 } else {
192 /* Compute derived values for Huffman tables */
193 /* We may do this more than once for a table, but it's not expensive */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000194 jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
DRC19c791c2018-03-08 10:55:20 -0600195 &entropy->dc_derived_tbls[dctbl]);
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000196 jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
DRC19c791c2018-03-08 10:55:20 -0600197 &entropy->ac_derived_tbls[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000198 }
199 /* Initialize DC predictions to 0 */
200 entropy->saved.last_dc_val[ci] = 0;
201 }
202
203 /* Initialize bit buffer to empty */
204 entropy->saved.put_buffer = 0;
205 entropy->saved.put_bits = 0;
206
207 /* Initialize restart stuff */
208 entropy->restarts_to_go = cinfo->restart_interval;
209 entropy->next_restart_num = 0;
210}
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000211
212
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000213/*
214 * Compute the derived values for a Huffman table.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000215 * This routine also performs some validation checks on the table.
216 *
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000217 * Note this is also used by jcphuff.c.
218 */
219
Thomas G. Lane489583f1996-02-07 00:00:00 +0000220GLOBAL(void)
DRC19c791c2018-03-08 10:55:20 -0600221jpeg_make_c_derived_tbl(j_compress_ptr cinfo, boolean isDC, int tblno,
222 c_derived_tbl **pdtbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000223{
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000224 JHUFF_TBL *htbl;
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000225 c_derived_tbl *dtbl;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000226 int p, i, l, lastp, si, maxsymbol;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000227 char huffsize[257];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000228 unsigned int huffcode[257];
229 unsigned int code;
230
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000231 /* Note that huffsize[] and huffcode[] are filled in code-length order,
232 * paralleling the order of the symbols themselves in htbl->huffval[].
233 */
234
235 /* Find the input Huffman table */
236 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
237 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
238 htbl =
239 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
240 if (htbl == NULL)
241 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
242
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000243 /* Allocate a workspace if we haven't already done so. */
244 if (*pdtbl == NULL)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000245 *pdtbl = (c_derived_tbl *)
DRC19c791c2018-03-08 10:55:20 -0600246 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
DRC5de454b2014-05-18 19:04:03 +0000247 sizeof(c_derived_tbl));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000248 dtbl = *pdtbl;
DRCe5eaf372014-05-09 18:00:32 +0000249
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000250 /* Figure C.1: make table of Huffman code length for each symbol */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000251
252 p = 0;
253 for (l = 1; l <= 16; l++) {
DRC19c791c2018-03-08 10:55:20 -0600254 i = (int)htbl->bits[l];
DRCe5eaf372014-05-09 18:00:32 +0000255 if (i < 0 || p + i > 256) /* protect against table overrun */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000256 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
257 while (i--)
DRC19c791c2018-03-08 10:55:20 -0600258 huffsize[p++] = (char)l;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000259 }
260 huffsize[p] = 0;
261 lastp = p;
DRCe5eaf372014-05-09 18:00:32 +0000262
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000263 /* Figure C.2: generate the codes themselves */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000264 /* We also validate that the counts represent a legal Huffman code tree. */
265
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000266 code = 0;
267 si = huffsize[0];
268 p = 0;
269 while (huffsize[p]) {
DRC19c791c2018-03-08 10:55:20 -0600270 while (((int)huffsize[p]) == si) {
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000271 huffcode[p++] = code;
272 code++;
273 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000274 /* code is now 1 more than the last code used for codelength si; but
275 * it must still fit in si bits, since no code is allowed to be all ones.
276 */
DRC19c791c2018-03-08 10:55:20 -0600277 if (((JLONG)code) >= (((JLONG)1) << si))
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000278 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000279 code <<= 1;
280 si++;
281 }
DRCe5eaf372014-05-09 18:00:32 +0000282
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000283 /* Figure C.3: generate encoding tables */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000284 /* These are code and size indexed by symbol value */
285
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000286 /* Set all codeless symbols to have code length 0;
287 * this lets us detect duplicate VAL entries here, and later
288 * allows emit_bits to detect any attempt to emit such symbols.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000289 */
DRC5de454b2014-05-18 19:04:03 +0000290 MEMZERO(dtbl->ehufsi, sizeof(dtbl->ehufsi));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000291
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000292 /* This is also a convenient place to check for out-of-range
293 * and duplicated VAL entries. We allow 0..255 for AC symbols
294 * but only 0..15 for DC. (We could constrain them further
295 * based on data depth and mode, but this seems enough.)
296 */
297 maxsymbol = isDC ? 15 : 255;
298
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000299 for (p = 0; p < lastp; p++) {
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000300 i = htbl->huffval[p];
301 if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
302 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
303 dtbl->ehufco[i] = huffcode[p];
304 dtbl->ehufsi[i] = huffsize[p];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000305 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000306}
307
308
309/* Outputting bytes to the file */
310
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000311/* Emit a byte, taking 'action' if must suspend. */
DRC19c791c2018-03-08 10:55:20 -0600312#define emit_byte(state, val, action) { \
313 *(state)->next_output_byte++ = (JOCTET)(val); \
314 if (--(state)->free_in_buffer == 0) \
315 if (!dump_buffer(state)) \
316 { action; } \
317}
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000318
319
Thomas G. Lane489583f1996-02-07 00:00:00 +0000320LOCAL(boolean)
DRC19c791c2018-03-08 10:55:20 -0600321dump_buffer(working_state *state)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000322/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000323{
DRCbd498032016-02-19 08:53:33 -0600324 struct jpeg_destination_mgr *dest = state->cinfo->dest;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000325
DRC19c791c2018-03-08 10:55:20 -0600326 if (!(*dest->empty_output_buffer) (state->cinfo))
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000327 return FALSE;
328 /* After a successful buffer dump, must reset buffer pointers */
329 state->next_output_byte = dest->next_output_byte;
330 state->free_in_buffer = dest->free_in_buffer;
331 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000332}
333
334
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000335/* Outputting bits to the file */
336
DRC6bb57b72011-04-26 22:08:31 +0000337/* These macros perform the same task as the emit_bits() function in the
338 * original libjpeg code. In addition to reducing overhead by explicitly
339 * inlining the code, additional performance is achieved by taking into
340 * account the size of the bit buffer and waiting until it is almost full
341 * before emptying it. This mostly benefits 64-bit platforms, since 6
342 * bytes can be stored in a 64-bit bit buffer before it has to be emptied.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000343 */
344
DRC6bb57b72011-04-26 22:08:31 +0000345#define EMIT_BYTE() { \
346 JOCTET c; \
347 put_bits -= 8; \
348 c = (JOCTET)GETJOCTET(put_buffer >> put_bits); \
349 *buffer++ = c; \
350 if (c == 0xFF) /* need to stuff a zero byte? */ \
351 *buffer++ = 0; \
DRC19c791c2018-03-08 10:55:20 -0600352}
DRC8443e522009-07-30 08:35:06 +0000353
DRC6bb57b72011-04-26 22:08:31 +0000354#define PUT_BITS(code, size) { \
355 put_bits += size; \
356 put_buffer = (put_buffer << size) | code; \
DRC8443e522009-07-30 08:35:06 +0000357}
358
DRC6399d0a2019-04-23 14:10:04 -0500359#if SIZEOF_SIZE_T != 8 && !defined(_WIN64)
360
DRC6bb57b72011-04-26 22:08:31 +0000361#define CHECKBUF15() { \
362 if (put_bits > 15) { \
363 EMIT_BYTE() \
364 EMIT_BYTE() \
365 } \
DRC8443e522009-07-30 08:35:06 +0000366}
367
DRC6399d0a2019-04-23 14:10:04 -0500368#endif
369
DRC6bb57b72011-04-26 22:08:31 +0000370#define CHECKBUF31() { \
371 if (put_bits > 31) { \
372 EMIT_BYTE() \
373 EMIT_BYTE() \
374 EMIT_BYTE() \
375 EMIT_BYTE() \
376 } \
DRC8443e522009-07-30 08:35:06 +0000377}
378
DRC6bb57b72011-04-26 22:08:31 +0000379#define CHECKBUF47() { \
380 if (put_bits > 47) { \
381 EMIT_BYTE() \
382 EMIT_BYTE() \
383 EMIT_BYTE() \
384 EMIT_BYTE() \
385 EMIT_BYTE() \
386 EMIT_BYTE() \
387 } \
388}
DRC8443e522009-07-30 08:35:06 +0000389
DRC3ebcc322015-05-15 19:09:44 +0000390#if !defined(_WIN32) && !defined(SIZEOF_SIZE_T)
391#error Cannot determine word size
DRCf64b36f2015-04-22 08:43:04 +0000392#endif
393
DRC19c791c2018-03-08 10:55:20 -0600394#if SIZEOF_SIZE_T == 8 || defined(_WIN64)
DRC8443e522009-07-30 08:35:06 +0000395
DRC6bb57b72011-04-26 22:08:31 +0000396#define EMIT_BITS(code, size) { \
397 CHECKBUF47() \
398 PUT_BITS(code, size) \
399}
400
401#define EMIT_CODE(code, size) { \
DRC19c791c2018-03-08 10:55:20 -0600402 temp2 &= (((JLONG)1) << nbits) - 1; \
DRC6bb57b72011-04-26 22:08:31 +0000403 CHECKBUF31() \
404 PUT_BITS(code, size) \
405 PUT_BITS(temp2, nbits) \
DRC19c791c2018-03-08 10:55:20 -0600406}
DRC8443e522009-07-30 08:35:06 +0000407
408#else
409
DRC6bb57b72011-04-26 22:08:31 +0000410#define EMIT_BITS(code, size) { \
411 PUT_BITS(code, size) \
412 CHECKBUF15() \
413}
414
415#define EMIT_CODE(code, size) { \
DRC19c791c2018-03-08 10:55:20 -0600416 temp2 &= (((JLONG)1) << nbits) - 1; \
DRC6bb57b72011-04-26 22:08:31 +0000417 PUT_BITS(code, size) \
418 CHECKBUF15() \
419 PUT_BITS(temp2, nbits) \
420 CHECKBUF15() \
DRC19c791c2018-03-08 10:55:20 -0600421}
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000422
DRC8443e522009-07-30 08:35:06 +0000423#endif
424
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000425
DRC402a7152014-11-22 22:09:30 +0000426/* Although it is exceedingly rare, it is possible for a Huffman-encoded
427 * coefficient block to be larger than the 128-byte unencoded block. For each
428 * of the 64 coefficients, PUT_BITS is invoked twice, and each invocation can
429 * theoretically store 16 bits (for a maximum of 2048 bits or 256 bytes per
430 * encoded block.) If, for instance, one artificially sets the AC
431 * coefficients to alternating values of 32767 and -32768 (using the JPEG
432 * scanning order-- 1, 8, 16, etc.), then this will produce an encoded block
433 * larger than 200 bytes.
434 */
DRC293263c2018-03-17 15:14:35 -0500435#define BUFSIZE (DCTSIZE2 * 4)
DRC3cba8db2009-03-16 23:58:30 +0000436
DRC6bb57b72011-04-26 22:08:31 +0000437#define LOAD_BUFFER() { \
438 if (state->free_in_buffer < BUFSIZE) { \
439 localbuf = 1; \
440 buffer = _buffer; \
DRC19c791c2018-03-08 10:55:20 -0600441 } else \
442 buffer = state->next_output_byte; \
443}
DRC3cba8db2009-03-16 23:58:30 +0000444
DRC6bb57b72011-04-26 22:08:31 +0000445#define STORE_BUFFER() { \
446 if (localbuf) { \
447 bytes = buffer - _buffer; \
448 buffer = _buffer; \
449 while (bytes > 0) { \
DRC19c791c2018-03-08 10:55:20 -0600450 bytestocopy = MIN(bytes, state->free_in_buffer); \
DRC6bb57b72011-04-26 22:08:31 +0000451 MEMCOPY(state->next_output_byte, buffer, bytestocopy); \
452 state->next_output_byte += bytestocopy; \
453 buffer += bytestocopy; \
454 state->free_in_buffer -= bytestocopy; \
455 if (state->free_in_buffer == 0) \
DRC19c791c2018-03-08 10:55:20 -0600456 if (!dump_buffer(state)) return FALSE; \
DRC6bb57b72011-04-26 22:08:31 +0000457 bytes -= bytestocopy; \
458 } \
DRC19c791c2018-03-08 10:55:20 -0600459 } else { \
DRC6bb57b72011-04-26 22:08:31 +0000460 state->free_in_buffer -= (buffer - state->next_output_byte); \
461 state->next_output_byte = buffer; \
462 } \
DRC19c791c2018-03-08 10:55:20 -0600463}
DRC3cba8db2009-03-16 23:58:30 +0000464
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000465
Thomas G. Lane489583f1996-02-07 00:00:00 +0000466LOCAL(boolean)
DRC19c791c2018-03-08 10:55:20 -0600467flush_bits(working_state *state)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000468{
DRCeddc3552014-08-21 03:38:14 +0000469 JOCTET _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000470 size_t put_buffer; int put_bits;
471 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000472
DRC99313382009-03-12 17:24:27 +0000473 put_buffer = state->cur.put_buffer;
474 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000475 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000476
DRC6bb57b72011-04-26 22:08:31 +0000477 /* fill any partial byte with ones */
478 PUT_BITS(0x7F, 7)
479 while (put_bits >= 8) EMIT_BYTE()
DRC99313382009-03-12 17:24:27 +0000480
DRCe5eaf372014-05-09 18:00:32 +0000481 state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000482 state->cur.put_bits = 0;
DRC3cba8db2009-03-16 23:58:30 +0000483 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000484
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000485 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000486}
487
DRC6bb57b72011-04-26 22:08:31 +0000488
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000489/* Encode a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000490
Thomas G. Lane489583f1996-02-07 00:00:00 +0000491LOCAL(boolean)
DRC19c791c2018-03-08 10:55:20 -0600492encode_one_block_simd(working_state *state, JCOEFPTR block, int last_dc_val,
493 c_derived_tbl *dctbl, c_derived_tbl *actbl)
DRCf3a86842016-01-07 00:19:43 -0600494{
495 JOCTET _buffer[BUFSIZE], *buffer;
496 size_t bytes, bytestocopy; int localbuf = 0;
497
498 LOAD_BUFFER()
499
500 buffer = jsimd_huff_encode_one_block(state, buffer, block, last_dc_val,
501 dctbl, actbl);
502
503 STORE_BUFFER()
504
505 return TRUE;
506}
507
508LOCAL(boolean)
DRC19c791c2018-03-08 10:55:20 -0600509encode_one_block(working_state *state, JCOEFPTR block, int last_dc_val,
510 c_derived_tbl *dctbl, c_derived_tbl *actbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000511{
DRC6bb57b72011-04-26 22:08:31 +0000512 int temp, temp2, temp3;
DRC99313382009-03-12 17:24:27 +0000513 int nbits;
DRC6bb57b72011-04-26 22:08:31 +0000514 int r, code, size;
DRCeddc3552014-08-21 03:38:14 +0000515 JOCTET _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000516 size_t put_buffer; int put_bits;
DRC99313382009-03-12 17:24:27 +0000517 int code_0xf0 = actbl->ehufco[0xf0], size_0xf0 = actbl->ehufsi[0xf0];
DRC04899092010-02-26 23:01:19 +0000518 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000519
DRC99313382009-03-12 17:24:27 +0000520 put_buffer = state->cur.put_buffer;
521 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000522 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000523
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000524 /* Encode the DC coefficient difference per section F.1.2.1 */
DRCe5eaf372014-05-09 18:00:32 +0000525
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000526 temp = temp2 = block[0] - last_dc_val;
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000527
DRC19c791c2018-03-08 10:55:20 -0600528 /* This is a well-known technique for obtaining the absolute value without a
529 * branch. It is derived from an assembly language technique presented in
530 * "How to Optimize for the Pentium Processors", Copyright (c) 1996, 1997 by
531 * Agner Fog.
532 */
DRC6bb57b72011-04-26 22:08:31 +0000533 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1);
534 temp ^= temp3;
535 temp -= temp3;
536
537 /* For a negative input, want temp2 = bitwise complement of abs(input) */
538 /* This code assumes we are on a two's complement machine */
539 temp2 += temp3;
540
541 /* Find the number of bits needed for the magnitude of the coefficient */
DRC0cfc4c12014-03-28 18:33:25 +0000542 nbits = JPEG_NBITS(temp);
DRC6bb57b72011-04-26 22:08:31 +0000543
544 /* Emit the Huffman-coded symbol for the number of bits */
545 code = dctbl->ehufco[nbits];
546 size = dctbl->ehufsi[nbits];
DRCa8b6ea22015-05-06 22:41:12 +0000547 EMIT_BITS(code, size)
DRC6bb57b72011-04-26 22:08:31 +0000548
549 /* Mask off any extra bits in code */
DRC19c791c2018-03-08 10:55:20 -0600550 temp2 &= (((JLONG)1) << nbits) - 1;
DRC6bb57b72011-04-26 22:08:31 +0000551
552 /* Emit that number of bits of the value, if positive, */
553 /* or the complement of its magnitude, if negative. */
DRCa8b6ea22015-05-06 22:41:12 +0000554 EMIT_BITS(temp2, nbits)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000555
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000556 /* Encode the AC coefficients per section F.1.2.2 */
DRCe5eaf372014-05-09 18:00:32 +0000557
558 r = 0; /* r = run length of zeros */
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000559
DRC6bb57b72011-04-26 22:08:31 +0000560/* Manually unroll the k loop to eliminate the counter variable. This
561 * improves performance greatly on systems with a limited number of
562 * registers (such as x86.)
563 */
DRC19c791c2018-03-08 10:55:20 -0600564#define kloop(jpeg_natural_order_of_k) { \
DRC6bb57b72011-04-26 22:08:31 +0000565 if ((temp = block[jpeg_natural_order_of_k]) == 0) { \
566 r++; \
567 } else { \
568 temp2 = temp; \
569 /* Branch-less absolute value, bitwise complement, etc., same as above */ \
570 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1); \
571 temp ^= temp3; \
572 temp -= temp3; \
573 temp2 += temp3; \
DRC0cfc4c12014-03-28 18:33:25 +0000574 nbits = JPEG_NBITS_NONZERO(temp); \
DRC6bb57b72011-04-26 22:08:31 +0000575 /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \
576 while (r > 15) { \
577 EMIT_BITS(code_0xf0, size_0xf0) \
578 r -= 16; \
579 } \
580 /* Emit Huffman symbol for run length / number of bits */ \
DRC19c791c2018-03-08 10:55:20 -0600581 temp3 = (r << 4) + nbits; \
DRC6bb57b72011-04-26 22:08:31 +0000582 code = actbl->ehufco[temp3]; \
583 size = actbl->ehufsi[temp3]; \
584 EMIT_CODE(code, size) \
DRC19c791c2018-03-08 10:55:20 -0600585 r = 0; \
DRC6bb57b72011-04-26 22:08:31 +0000586 } \
587}
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000588
DRC6bb57b72011-04-26 22:08:31 +0000589 /* One iteration for each value in jpeg_natural_order[] */
590 kloop(1); kloop(8); kloop(16); kloop(9); kloop(2); kloop(3);
591 kloop(10); kloop(17); kloop(24); kloop(32); kloop(25); kloop(18);
592 kloop(11); kloop(4); kloop(5); kloop(12); kloop(19); kloop(26);
593 kloop(33); kloop(40); kloop(48); kloop(41); kloop(34); kloop(27);
594 kloop(20); kloop(13); kloop(6); kloop(7); kloop(14); kloop(21);
595 kloop(28); kloop(35); kloop(42); kloop(49); kloop(56); kloop(57);
596 kloop(50); kloop(43); kloop(36); kloop(29); kloop(22); kloop(15);
597 kloop(23); kloop(30); kloop(37); kloop(44); kloop(51); kloop(58);
598 kloop(59); kloop(52); kloop(45); kloop(38); kloop(31); kloop(39);
599 kloop(46); kloop(53); kloop(60); kloop(61); kloop(54); kloop(47);
600 kloop(55); kloop(62); kloop(63);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000601
602 /* If the last coef(s) were zero, emit an end-of-block code */
DRC6bb57b72011-04-26 22:08:31 +0000603 if (r > 0) {
604 code = actbl->ehufco[0];
605 size = actbl->ehufsi[0];
606 EMIT_BITS(code, size)
607 }
DRC99313382009-03-12 17:24:27 +0000608
609 state->cur.put_buffer = put_buffer;
610 state->cur.put_bits = put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000611 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000612
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000613 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000614}
615
616
617/*
618 * Emit a restart marker & resynchronize predictions.
619 */
620
Thomas G. Lane489583f1996-02-07 00:00:00 +0000621LOCAL(boolean)
DRC19c791c2018-03-08 10:55:20 -0600622emit_restart(working_state *state, int restart_num)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000623{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000624 int ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000625
DRC19c791c2018-03-08 10:55:20 -0600626 if (!flush_bits(state))
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000627 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000628
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000629 emit_byte(state, 0xFF, return FALSE);
630 emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000631
632 /* Re-initialize DC predictions to 0 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000633 for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
634 state->cur.last_dc_val[ci] = 0;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000635
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000636 /* The restart counter is not updated until we successfully write the MCU. */
637
638 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000639}
640
641
642/*
643 * Encode and output one MCU's worth of Huffman-compressed coefficients.
644 */
645
Thomas G. Lane489583f1996-02-07 00:00:00 +0000646METHODDEF(boolean)
DRC19c791c2018-03-08 10:55:20 -0600647encode_mcu_huff(j_compress_ptr cinfo, JBLOCKROW *MCU_data)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000648{
DRC19c791c2018-03-08 10:55:20 -0600649 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000650 working_state state;
651 int blkn, ci;
DRCbd498032016-02-19 08:53:33 -0600652 jpeg_component_info *compptr;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000653
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000654 /* Load up working state */
655 state.next_output_byte = cinfo->dest->next_output_byte;
656 state.free_in_buffer = cinfo->dest->free_in_buffer;
657 ASSIGN_STATE(state.cur, entropy->saved);
658 state.cinfo = cinfo;
659
660 /* Emit restart marker if needed */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000661 if (cinfo->restart_interval) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000662 if (entropy->restarts_to_go == 0)
DRC19c791c2018-03-08 10:55:20 -0600663 if (!emit_restart(&state, entropy->next_restart_num))
DRCe5eaf372014-05-09 18:00:32 +0000664 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000665 }
666
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000667 /* Encode the MCU data blocks */
DRCf3a86842016-01-07 00:19:43 -0600668 if (entropy->simd) {
669 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
670 ci = cinfo->MCU_membership[blkn];
671 compptr = cinfo->cur_comp_info[ci];
DRC19c791c2018-03-08 10:55:20 -0600672 if (!encode_one_block_simd(&state,
673 MCU_data[blkn][0], state.cur.last_dc_val[ci],
674 entropy->dc_derived_tbls[compptr->dc_tbl_no],
675 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
DRCf3a86842016-01-07 00:19:43 -0600676 return FALSE;
677 /* Update last_dc_val */
678 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
679 }
680 } else {
681 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
682 ci = cinfo->MCU_membership[blkn];
683 compptr = cinfo->cur_comp_info[ci];
DRC19c791c2018-03-08 10:55:20 -0600684 if (!encode_one_block(&state,
685 MCU_data[blkn][0], state.cur.last_dc_val[ci],
686 entropy->dc_derived_tbls[compptr->dc_tbl_no],
687 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
DRCf3a86842016-01-07 00:19:43 -0600688 return FALSE;
689 /* Update last_dc_val */
690 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
691 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000692 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000693
694 /* Completed MCU, so update state */
695 cinfo->dest->next_output_byte = state.next_output_byte;
696 cinfo->dest->free_in_buffer = state.free_in_buffer;
697 ASSIGN_STATE(entropy->saved, state.cur);
698
699 /* Update restart-interval state too */
700 if (cinfo->restart_interval) {
701 if (entropy->restarts_to_go == 0) {
702 entropy->restarts_to_go = cinfo->restart_interval;
703 entropy->next_restart_num++;
704 entropy->next_restart_num &= 7;
705 }
706 entropy->restarts_to_go--;
707 }
708
709 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000710}
711
712
713/*
714 * Finish up at the end of a Huffman-compressed scan.
715 */
716
Thomas G. Lane489583f1996-02-07 00:00:00 +0000717METHODDEF(void)
DRC19c791c2018-03-08 10:55:20 -0600718finish_pass_huff(j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000719{
DRC19c791c2018-03-08 10:55:20 -0600720 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000721 working_state state;
722
723 /* Load up working state ... flush_bits needs it */
724 state.next_output_byte = cinfo->dest->next_output_byte;
725 state.free_in_buffer = cinfo->dest->free_in_buffer;
726 ASSIGN_STATE(state.cur, entropy->saved);
727 state.cinfo = cinfo;
728
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000729 /* Flush out the last data */
DRC19c791c2018-03-08 10:55:20 -0600730 if (!flush_bits(&state))
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000731 ERREXIT(cinfo, JERR_CANT_SUSPEND);
732
733 /* Update state */
734 cinfo->dest->next_output_byte = state.next_output_byte;
735 cinfo->dest->free_in_buffer = state.free_in_buffer;
736 ASSIGN_STATE(entropy->saved, state.cur);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000737}
738
739
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000740/*
741 * Huffman coding optimization.
742 *
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000743 * We first scan the supplied data and count the number of uses of each symbol
744 * that is to be Huffman-coded. (This process MUST agree with the code above.)
745 * Then we build a Huffman coding tree for the observed counts.
746 * Symbols which are not needed at all for the particular image are not
747 * assigned any code, which saves space in the DHT marker as well as in
748 * the compressed data.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000749 */
750
751#ifdef ENTROPY_OPT_SUPPORTED
752
753
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000754/* Process a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000755
Thomas G. Lane489583f1996-02-07 00:00:00 +0000756LOCAL(void)
DRC19c791c2018-03-08 10:55:20 -0600757htest_one_block(j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
758 long dc_counts[], long ac_counts[])
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000759{
760 register int temp;
761 register int nbits;
762 register int k, r;
DRCe5eaf372014-05-09 18:00:32 +0000763
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000764 /* Encode the DC coefficient difference per section F.1.2.1 */
DRCe5eaf372014-05-09 18:00:32 +0000765
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000766 temp = block[0] - last_dc_val;
767 if (temp < 0)
768 temp = -temp;
DRCe5eaf372014-05-09 18:00:32 +0000769
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000770 /* Find the number of bits needed for the magnitude of the coefficient */
771 nbits = 0;
772 while (temp) {
773 nbits++;
774 temp >>= 1;
775 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000776 /* Check for out-of-range coefficient values.
777 * Since we're encoding a difference, the range limit is twice as much.
778 */
DRC19c791c2018-03-08 10:55:20 -0600779 if (nbits > MAX_COEF_BITS + 1)
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000780 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000781
782 /* Count the Huffman symbol for the number of bits */
783 dc_counts[nbits]++;
DRCe5eaf372014-05-09 18:00:32 +0000784
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000785 /* Encode the AC coefficients per section F.1.2.2 */
DRCe5eaf372014-05-09 18:00:32 +0000786
787 r = 0; /* r = run length of zeros */
788
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000789 for (k = 1; k < DCTSIZE2; k++) {
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000790 if ((temp = block[jpeg_natural_order[k]]) == 0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000791 r++;
792 } else {
793 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
794 while (r > 15) {
DRCe5eaf372014-05-09 18:00:32 +0000795 ac_counts[0xF0]++;
796 r -= 16;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000797 }
DRCe5eaf372014-05-09 18:00:32 +0000798
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000799 /* Find the number of bits needed for the magnitude of the coefficient */
800 if (temp < 0)
DRCe5eaf372014-05-09 18:00:32 +0000801 temp = -temp;
802
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000803 /* Find the number of bits needed for the magnitude of the coefficient */
DRCe5eaf372014-05-09 18:00:32 +0000804 nbits = 1; /* there must be at least one 1 bit */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000805 while ((temp >>= 1))
DRCe5eaf372014-05-09 18:00:32 +0000806 nbits++;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000807 /* Check for out-of-range coefficient values */
808 if (nbits > MAX_COEF_BITS)
DRCe5eaf372014-05-09 18:00:32 +0000809 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
810
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000811 /* Count Huffman symbol for run length / number of bits */
812 ac_counts[(r << 4) + nbits]++;
DRCe5eaf372014-05-09 18:00:32 +0000813
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000814 r = 0;
815 }
816 }
817
818 /* If the last coef(s) were zero, emit an end-of-block code */
819 if (r > 0)
820 ac_counts[0]++;
821}
822
823
824/*
825 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
826 * No data is actually output, so no suspension return is possible.
827 */
828
Thomas G. Lane489583f1996-02-07 00:00:00 +0000829METHODDEF(boolean)
DRC19c791c2018-03-08 10:55:20 -0600830encode_mcu_gather(j_compress_ptr cinfo, JBLOCKROW *MCU_data)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000831{
DRC19c791c2018-03-08 10:55:20 -0600832 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000833 int blkn, ci;
DRCbd498032016-02-19 08:53:33 -0600834 jpeg_component_info *compptr;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000835
836 /* Take care of restart intervals if needed */
837 if (cinfo->restart_interval) {
838 if (entropy->restarts_to_go == 0) {
839 /* Re-initialize DC predictions to 0 */
840 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
DRCe5eaf372014-05-09 18:00:32 +0000841 entropy->saved.last_dc_val[ci] = 0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000842 /* Update restart state */
843 entropy->restarts_to_go = cinfo->restart_interval;
844 }
845 entropy->restarts_to_go--;
846 }
847
848 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
849 ci = cinfo->MCU_membership[blkn];
850 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000851 htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
DRCe5eaf372014-05-09 18:00:32 +0000852 entropy->dc_count_ptrs[compptr->dc_tbl_no],
853 entropy->ac_count_ptrs[compptr->ac_tbl_no]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000854 entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
855 }
856
857 return TRUE;
858}
859
860
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000861/*
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000862 * Generate the best Huffman code table for the given counts, fill htbl.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000863 * Note this is also used by jcphuff.c.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000864 *
865 * The JPEG standard requires that no symbol be assigned a codeword of all
866 * one bits (so that padding bits added at the end of a compressed segment
867 * can't look like a valid code). Because of the canonical ordering of
868 * codewords, this just means that there must be an unused slot in the
DRCa6289522018-07-24 18:36:51 -0500869 * longest codeword length category. Annex K (Clause K.2) of
870 * Rec. ITU-T T.81 (1992) | ISO/IEC 10918-1:1994 suggests reserving such a slot
871 * by pretending that symbol 256 is a valid symbol with count 1. In theory
872 * that's not optimal; giving it count zero but including it in the symbol set
873 * anyway should give a better Huffman code. But the theoretically better code
874 * actually seems to come out worse in practice, because it produces more
875 * all-ones bytes (which incur stuffed zero bytes in the final file). In any
876 * case the difference is tiny.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000877 *
878 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
879 * If some symbols have a very small but nonzero probability, the Huffman tree
880 * must be adjusted to meet the code length restriction. We currently use
881 * the adjustment method suggested in JPEG section K.2. This method is *not*
882 * optimal; it may not choose the best possible limited-length code. But
883 * typically only very-low-frequency symbols will be given less-than-optimal
884 * lengths, so the code is almost optimal. Experimental comparisons against
885 * an optimal limited-length-code algorithm indicate that the difference is
886 * microscopic --- usually less than a hundredth of a percent of total size.
887 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000888 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000889
Thomas G. Lane489583f1996-02-07 00:00:00 +0000890GLOBAL(void)
DRC19c791c2018-03-08 10:55:20 -0600891jpeg_gen_optimal_table(j_compress_ptr cinfo, JHUFF_TBL *htbl, long freq[])
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000892{
DRC293263c2018-03-17 15:14:35 -0500893#define MAX_CLEN 32 /* assumed maximum initial code length */
DRC19c791c2018-03-08 10:55:20 -0600894 UINT8 bits[MAX_CLEN + 1]; /* bits[k] = # of symbols with code length k */
DRCe5eaf372014-05-09 18:00:32 +0000895 int codesize[257]; /* codesize[k] = code length of symbol k */
896 int others[257]; /* next symbol in current branch of tree */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000897 int c1, c2;
898 int p, i, j;
899 long v;
900
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000901 /* This algorithm is explained in section K.2 of the JPEG standard */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000902
DRC5de454b2014-05-18 19:04:03 +0000903 MEMZERO(bits, sizeof(bits));
904 MEMZERO(codesize, sizeof(codesize));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000905 for (i = 0; i < 257; i++)
DRCe5eaf372014-05-09 18:00:32 +0000906 others[i] = -1; /* init links to empty */
907
908 freq[256] = 1; /* make sure 256 has a nonzero count */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000909 /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000910 * that no real symbol is given code-value of all ones, because 256
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000911 * will be placed last in the largest codeword category.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000912 */
913
914 /* Huffman's basic algorithm to assign optimal code lengths to symbols */
915
916 for (;;) {
917 /* Find the smallest nonzero frequency, set c1 = its symbol */
918 /* In case of ties, take the larger symbol number */
919 c1 = -1;
920 v = 1000000000L;
921 for (i = 0; i <= 256; i++) {
922 if (freq[i] && freq[i] <= v) {
DRCe5eaf372014-05-09 18:00:32 +0000923 v = freq[i];
924 c1 = i;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000925 }
926 }
927
928 /* Find the next smallest nonzero frequency, set c2 = its symbol */
929 /* In case of ties, take the larger symbol number */
930 c2 = -1;
931 v = 1000000000L;
932 for (i = 0; i <= 256; i++) {
933 if (freq[i] && freq[i] <= v && i != c1) {
DRCe5eaf372014-05-09 18:00:32 +0000934 v = freq[i];
935 c2 = i;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000936 }
937 }
938
939 /* Done if we've merged everything into one frequency */
940 if (c2 < 0)
941 break;
DRCe5eaf372014-05-09 18:00:32 +0000942
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000943 /* Else merge the two counts/trees */
944 freq[c1] += freq[c2];
945 freq[c2] = 0;
946
947 /* Increment the codesize of everything in c1's tree branch */
948 codesize[c1]++;
949 while (others[c1] >= 0) {
950 c1 = others[c1];
951 codesize[c1]++;
952 }
DRCe5eaf372014-05-09 18:00:32 +0000953
954 others[c1] = c2; /* chain c2 onto c1's tree branch */
955
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000956 /* Increment the codesize of everything in c2's tree branch */
957 codesize[c2]++;
958 while (others[c2] >= 0) {
959 c2 = others[c2];
960 codesize[c2]++;
961 }
962 }
963
964 /* Now count the number of symbols of each code length */
965 for (i = 0; i <= 256; i++) {
966 if (codesize[i]) {
967 /* The JPEG standard seems to think that this can't happen, */
968 /* but I'm paranoid... */
969 if (codesize[i] > MAX_CLEN)
DRCe5eaf372014-05-09 18:00:32 +0000970 ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000971
972 bits[codesize[i]]++;
973 }
974 }
975
976 /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
977 * Huffman procedure assigned any such lengths, we must adjust the coding.
DRCa6289522018-07-24 18:36:51 -0500978 * Here is what Rec. ITU-T T.81 | ISO/IEC 10918-1 says about how this next
979 * bit works: Since symbols are paired for the longest Huffman code, the
980 * symbols are removed from this length category two at a time. The prefix
981 * for the pair (which is one bit shorter) is allocated to one of the pair;
982 * then, skipping the BITS entry for that prefix length, a code word from the
983 * next shortest nonzero BITS entry is converted into a prefix for two code
984 * words one bit longer.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000985 */
DRCe5eaf372014-05-09 18:00:32 +0000986
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000987 for (i = MAX_CLEN; i > 16; i--) {
988 while (bits[i] > 0) {
DRCe5eaf372014-05-09 18:00:32 +0000989 j = i - 2; /* find length of new prefix to be used */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000990 while (bits[j] == 0)
DRCe5eaf372014-05-09 18:00:32 +0000991 j--;
992
993 bits[i] -= 2; /* remove two symbols */
DRC19c791c2018-03-08 10:55:20 -0600994 bits[i - 1]++; /* one goes in this length */
995 bits[j + 1] += 2; /* two new symbols in this length */
DRCe5eaf372014-05-09 18:00:32 +0000996 bits[j]--; /* symbol of this length is now a prefix */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000997 }
998 }
999
1000 /* Remove the count for the pseudo-symbol 256 from the largest codelength */
DRCe5eaf372014-05-09 18:00:32 +00001001 while (bits[i] == 0) /* find largest codelength still in use */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001002 i--;
1003 bits[i]--;
DRCe5eaf372014-05-09 18:00:32 +00001004
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001005 /* Return final symbol counts (only for lengths 0..16) */
DRC5de454b2014-05-18 19:04:03 +00001006 MEMCOPY(htbl->bits, bits, sizeof(htbl->bits));
DRCe5eaf372014-05-09 18:00:32 +00001007
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001008 /* Return a list of the symbols sorted by code length */
1009 /* It's not real clear to me why we don't need to consider the codelength
DRCa6289522018-07-24 18:36:51 -05001010 * changes made above, but Rec. ITU-T T.81 | ISO/IEC 10918-1 seems to think
1011 * this works.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001012 */
1013 p = 0;
1014 for (i = 1; i <= MAX_CLEN; i++) {
1015 for (j = 0; j <= 255; j++) {
1016 if (codesize[j] == i) {
DRC19c791c2018-03-08 10:55:20 -06001017 htbl->huffval[p] = (UINT8)j;
DRCe5eaf372014-05-09 18:00:32 +00001018 p++;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001019 }
1020 }
1021 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001022
1023 /* Set sent_table FALSE so updated table will be written to JPEG file. */
1024 htbl->sent_table = FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001025}
1026
1027
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001028/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001029 * Finish up a statistics-gathering pass and create the new Huffman tables.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001030 */
1031
Thomas G. Lane489583f1996-02-07 00:00:00 +00001032METHODDEF(void)
DRC19c791c2018-03-08 10:55:20 -06001033finish_pass_gather(j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001034{
DRC19c791c2018-03-08 10:55:20 -06001035 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001036 int ci, dctbl, actbl;
DRCbd498032016-02-19 08:53:33 -06001037 jpeg_component_info *compptr;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001038 JHUFF_TBL **htblptr;
1039 boolean did_dc[NUM_HUFF_TBLS];
1040 boolean did_ac[NUM_HUFF_TBLS];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001041
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001042 /* It's important not to apply jpeg_gen_optimal_table more than once
1043 * per table, because it clobbers the input frequency counts!
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001044 */
DRC5de454b2014-05-18 19:04:03 +00001045 MEMZERO(did_dc, sizeof(did_dc));
1046 MEMZERO(did_ac, sizeof(did_ac));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001047
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001048 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1049 compptr = cinfo->cur_comp_info[ci];
1050 dctbl = compptr->dc_tbl_no;
1051 actbl = compptr->ac_tbl_no;
DRC19c791c2018-03-08 10:55:20 -06001052 if (!did_dc[dctbl]) {
1053 htblptr = &cinfo->dc_huff_tbl_ptrs[dctbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001054 if (*htblptr == NULL)
DRC19c791c2018-03-08 10:55:20 -06001055 *htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001056 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001057 did_dc[dctbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001058 }
DRC19c791c2018-03-08 10:55:20 -06001059 if (!did_ac[actbl]) {
1060 htblptr = &cinfo->ac_huff_tbl_ptrs[actbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001061 if (*htblptr == NULL)
DRC19c791c2018-03-08 10:55:20 -06001062 *htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001063 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001064 did_ac[actbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001065 }
1066 }
1067}
1068
1069
1070#endif /* ENTROPY_OPT_SUPPORTED */
1071
1072
1073/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001074 * Module initialization routine for Huffman entropy encoding.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001075 */
1076
Thomas G. Lane489583f1996-02-07 00:00:00 +00001077GLOBAL(void)
DRC19c791c2018-03-08 10:55:20 -06001078jinit_huff_encoder(j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001079{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001080 huff_entropy_ptr entropy;
1081 int i;
1082
1083 entropy = (huff_entropy_ptr)
DRC19c791c2018-03-08 10:55:20 -06001084 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
DRC5de454b2014-05-18 19:04:03 +00001085 sizeof(huff_entropy_encoder));
DRC19c791c2018-03-08 10:55:20 -06001086 cinfo->entropy = (struct jpeg_entropy_encoder *)entropy;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001087 entropy->pub.start_pass = start_pass_huff;
1088
1089 /* Mark tables unallocated */
1090 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1091 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001092#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001093 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001094#endif
1095 }
1096}