blob: 8ea48b80e3fbdb2962d93bba87e3351faa077438 [file] [log] [blame]
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001/*
2 * jchuff.c
3 *
noel@chromium.org3395bcc2014-04-14 06:56:00 +00004 * This file was part of the Independent JPEG Group's software:
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00005 * Copyright (C) 1991-1997, Thomas G. Lane.
noel@chromium.org3395bcc2014-04-14 06:56:00 +00006 * libjpeg-turbo Modifications:
Jonathan Wrightbbb82822020-11-25 13:36:43 +00007 * Copyright (C) 2009-2011, 2014-2016, 2018-2020, D. R. Commander.
Chris Blumecca8c4d2019-03-01 01:09:50 -08008 * Copyright (C) 2015, Matthieu Darbois.
Jonathan Wrightbbb82822020-11-25 13:36:43 +00009 * Copyright (C) 2018, Matthias Räncker.
10 * Copyright (C) 2020, Arm Limited.
Tom Hudson0d47d2d2016-05-04 13:22:56 -040011 * For conditions of distribution and use, see the accompanying README.ijg
12 * file.
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +000013 *
14 * This file contains Huffman entropy encoding routines.
15 *
16 * Much of the complexity here has to do with supporting output suspension.
17 * If the data destination module demands suspension, we want to be able to
18 * back up to the start of the current MCU. To do this, we copy state
19 * variables into local working storage, and update them back to the
20 * permanent JPEG objects only upon successful completion of an MCU.
Chris Blumecca8c4d2019-03-01 01:09:50 -080021 *
22 * NOTE: All referenced figures are from
23 * Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +000024 */
25
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +000026#define JPEG_INTERNALS
27#include "jinclude.h"
28#include "jpeglib.h"
Tom Hudson0d47d2d2016-05-04 13:22:56 -040029#include "jsimd.h"
30#include "jconfigint.h"
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +000031#include <limits.h>
32
noel@chromium.org841fff82014-05-23 23:38:59 +000033/*
34 * NOTE: If USE_CLZ_INTRINSIC is defined, then clz/bsr instructions will be
35 * used for bit counting rather than the lookup table. This will reduce the
36 * memory footprint by 64k, which is important for some mobile applications
37 * that create many isolated instances of libjpeg-turbo (web browsers, for
38 * instance.) This may improve performance on some mobile platforms as well.
Jonathan Wrightbbb82822020-11-25 13:36:43 +000039 * This feature is enabled by default only on Arm processors, because some x86
noel@chromium.org841fff82014-05-23 23:38:59 +000040 * chips have a slow implementation of bsr, and the use of clz/bsr cannot be
41 * shown to have a significant performance impact even on the x86 chips that
Jonathan Wrightbbb82822020-11-25 13:36:43 +000042 * have a fast implementation of it. When building for Armv6, you can
noel@chromium.org841fff82014-05-23 23:38:59 +000043 * explicitly disable the use of clz/bsr by adding -mthumb to the compiler
44 * flags (this defines __thumb__).
45 */
46
47/* NOTE: Both GCC and Clang define __GNUC__ */
Jonathan Wrightdb870df2020-08-05 11:42:22 +010048#if defined(__GNUC__) && (defined(__arm__) || defined(__aarch64__))
49#if !defined(__thumb__) || defined(__thumb2__)
noel@chromium.org841fff82014-05-23 23:38:59 +000050#define USE_CLZ_INTRINSIC
51#endif
52#endif
53
54#ifdef USE_CLZ_INTRINSIC
Chris Blumecca8c4d2019-03-01 01:09:50 -080055#define JPEG_NBITS_NONZERO(x) (32 - __builtin_clz(x))
56#define JPEG_NBITS(x) (x ? JPEG_NBITS_NONZERO(x) : 0)
noel@chromium.org841fff82014-05-23 23:38:59 +000057#else
Tom Hudson0d47d2d2016-05-04 13:22:56 -040058#include "jpeg_nbits_table.h"
Chris Blumecca8c4d2019-03-01 01:09:50 -080059#define JPEG_NBITS(x) (jpeg_nbits_table[x])
60#define JPEG_NBITS_NONZERO(x) JPEG_NBITS(x)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +000061#endif
62
hbono@chromium.org98626972011-08-03 03:13:08 +000063
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +000064/* Expanded entropy encoder object for Huffman encoding.
65 *
66 * The savable_state subrecord contains fields that change within an MCU,
67 * but must not be updated permanently until we complete the MCU.
68 */
69
Jonathan Wrightbbb82822020-11-25 13:36:43 +000070#if defined(__x86_64__) && defined(__ILP32__)
71typedef unsigned long long bit_buf_type;
72#else
73typedef size_t bit_buf_type;
74#endif
75
76/* NOTE: The more optimal Huffman encoding algorithm is only used by the
77 * intrinsics implementation of the Arm Neon SIMD extensions, which is why we
78 * retain the old Huffman encoder behavior when using the GAS implementation.
79 */
80#if defined(WITH_SIMD) && !(defined(__arm__) || defined(__aarch64__) || \
81 defined(_M_ARM) || defined(_M_ARM64))
82typedef unsigned long long simd_bit_buf_type;
83#else
84typedef bit_buf_type simd_bit_buf_type;
85#endif
86
87#if (defined(SIZEOF_SIZE_T) && SIZEOF_SIZE_T == 8) || defined(_WIN64) || \
88 (defined(__x86_64__) && defined(__ILP32__))
89#define BIT_BUF_SIZE 64
90#elif (defined(SIZEOF_SIZE_T) && SIZEOF_SIZE_T == 4) || defined(_WIN32)
91#define BIT_BUF_SIZE 32
92#else
93#error Cannot determine word size
94#endif
95#define SIMD_BIT_BUF_SIZE (sizeof(simd_bit_buf_type) * 8)
96
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +000097typedef struct {
Jonathan Wrightbbb82822020-11-25 13:36:43 +000098 union {
99 bit_buf_type c;
100 simd_bit_buf_type simd;
101 } put_buffer; /* current bit accumulation buffer */
102 int free_bits; /* # of bits available in it */
103 /* (Neon GAS: # of bits now in it) */
Chris Blumecca8c4d2019-03-01 01:09:50 -0800104 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000105} savable_state;
106
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000107typedef struct {
108 struct jpeg_entropy_encoder pub; /* public fields */
109
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400110 savable_state saved; /* Bit buffer & DC state at start of MCU */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000111
112 /* These fields are NOT loaded into local working state. */
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400113 unsigned int restarts_to_go; /* MCUs left in this restart interval */
114 int next_restart_num; /* next restart number to write (0-7) */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000115
116 /* Pointers to derived tables (these workspaces have image lifespan) */
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400117 c_derived_tbl *dc_derived_tbls[NUM_HUFF_TBLS];
118 c_derived_tbl *ac_derived_tbls[NUM_HUFF_TBLS];
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000119
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400120#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
121 long *dc_count_ptrs[NUM_HUFF_TBLS];
122 long *ac_count_ptrs[NUM_HUFF_TBLS];
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000123#endif
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400124
125 int simd;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000126} huff_entropy_encoder;
127
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400128typedef huff_entropy_encoder *huff_entropy_ptr;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000129
130/* Working state while writing an MCU.
131 * This struct contains all the fields that are needed by subroutines.
132 */
133
134typedef struct {
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400135 JOCTET *next_output_byte; /* => next byte to write in buffer */
136 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
137 savable_state cur; /* Current bit buffer & DC state */
138 j_compress_ptr cinfo; /* dump_buffer needs access to this */
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000139 int simd;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000140} working_state;
141
142
143/* Forward declarations */
Chris Blumecca8c4d2019-03-01 01:09:50 -0800144METHODDEF(boolean) encode_mcu_huff(j_compress_ptr cinfo, JBLOCKROW *MCU_data);
145METHODDEF(void) finish_pass_huff(j_compress_ptr cinfo);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000146#ifdef ENTROPY_OPT_SUPPORTED
Chris Blumecca8c4d2019-03-01 01:09:50 -0800147METHODDEF(boolean) encode_mcu_gather(j_compress_ptr cinfo,
148 JBLOCKROW *MCU_data);
149METHODDEF(void) finish_pass_gather(j_compress_ptr cinfo);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000150#endif
151
152
153/*
154 * Initialize for a Huffman-compressed scan.
155 * If gather_statistics is TRUE, we do not output anything during the scan,
156 * just count the Huffman symbols used and generate Huffman code tables.
157 */
158
159METHODDEF(void)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800160start_pass_huff(j_compress_ptr cinfo, boolean gather_statistics)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000161{
Chris Blumecca8c4d2019-03-01 01:09:50 -0800162 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000163 int ci, dctbl, actbl;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400164 jpeg_component_info *compptr;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000165
166 if (gather_statistics) {
167#ifdef ENTROPY_OPT_SUPPORTED
168 entropy->pub.encode_mcu = encode_mcu_gather;
169 entropy->pub.finish_pass = finish_pass_gather;
170#else
171 ERREXIT(cinfo, JERR_NOT_COMPILED);
172#endif
173 } else {
174 entropy->pub.encode_mcu = encode_mcu_huff;
175 entropy->pub.finish_pass = finish_pass_huff;
176 }
177
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400178 entropy->simd = jsimd_can_huff_encode_one_block();
179
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000180 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
181 compptr = cinfo->cur_comp_info[ci];
182 dctbl = compptr->dc_tbl_no;
183 actbl = compptr->ac_tbl_no;
184 if (gather_statistics) {
185#ifdef ENTROPY_OPT_SUPPORTED
186 /* Check for invalid table indexes */
187 /* (make_c_derived_tbl does this in the other path) */
188 if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400189 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000190 if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400191 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000192 /* Allocate and zero the statistics tables */
193 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
194 if (entropy->dc_count_ptrs[dctbl] == NULL)
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400195 entropy->dc_count_ptrs[dctbl] = (long *)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800196 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400197 257 * sizeof(long));
198 MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * sizeof(long));
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000199 if (entropy->ac_count_ptrs[actbl] == NULL)
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400200 entropy->ac_count_ptrs[actbl] = (long *)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800201 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400202 257 * sizeof(long));
203 MEMZERO(entropy->ac_count_ptrs[actbl], 257 * sizeof(long));
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000204#endif
205 } else {
206 /* Compute derived values for Huffman tables */
207 /* We may do this more than once for a table, but it's not expensive */
208 jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
Chris Blumecca8c4d2019-03-01 01:09:50 -0800209 &entropy->dc_derived_tbls[dctbl]);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000210 jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
Chris Blumecca8c4d2019-03-01 01:09:50 -0800211 &entropy->ac_derived_tbls[actbl]);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000212 }
213 /* Initialize DC predictions to 0 */
214 entropy->saved.last_dc_val[ci] = 0;
215 }
216
217 /* Initialize bit buffer to empty */
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000218 if (entropy->simd) {
219 entropy->saved.put_buffer.simd = 0;
220#if defined(__aarch64__) && !defined(NEON_INTRINSICS)
221 entropy->saved.free_bits = 0;
222#else
223 entropy->saved.free_bits = SIMD_BIT_BUF_SIZE;
224#endif
225 } else {
226 entropy->saved.put_buffer.c = 0;
227 entropy->saved.free_bits = BIT_BUF_SIZE;
228 }
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000229
230 /* Initialize restart stuff */
231 entropy->restarts_to_go = cinfo->restart_interval;
232 entropy->next_restart_num = 0;
233}
234
235
236/*
237 * Compute the derived values for a Huffman table.
238 * This routine also performs some validation checks on the table.
239 *
240 * Note this is also used by jcphuff.c.
241 */
242
243GLOBAL(void)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800244jpeg_make_c_derived_tbl(j_compress_ptr cinfo, boolean isDC, int tblno,
245 c_derived_tbl **pdtbl)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000246{
247 JHUFF_TBL *htbl;
248 c_derived_tbl *dtbl;
249 int p, i, l, lastp, si, maxsymbol;
250 char huffsize[257];
251 unsigned int huffcode[257];
252 unsigned int code;
253
254 /* Note that huffsize[] and huffcode[] are filled in code-length order,
255 * paralleling the order of the symbols themselves in htbl->huffval[].
256 */
257
258 /* Find the input Huffman table */
259 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
260 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
261 htbl =
262 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
263 if (htbl == NULL)
264 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
265
266 /* Allocate a workspace if we haven't already done so. */
267 if (*pdtbl == NULL)
268 *pdtbl = (c_derived_tbl *)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800269 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400270 sizeof(c_derived_tbl));
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000271 dtbl = *pdtbl;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400272
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000273 /* Figure C.1: make table of Huffman code length for each symbol */
274
275 p = 0;
276 for (l = 1; l <= 16; l++) {
Chris Blumecca8c4d2019-03-01 01:09:50 -0800277 i = (int)htbl->bits[l];
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400278 if (i < 0 || p + i > 256) /* protect against table overrun */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000279 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
280 while (i--)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800281 huffsize[p++] = (char)l;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000282 }
283 huffsize[p] = 0;
284 lastp = p;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400285
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000286 /* Figure C.2: generate the codes themselves */
287 /* We also validate that the counts represent a legal Huffman code tree. */
288
289 code = 0;
290 si = huffsize[0];
291 p = 0;
292 while (huffsize[p]) {
Chris Blumecca8c4d2019-03-01 01:09:50 -0800293 while (((int)huffsize[p]) == si) {
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000294 huffcode[p++] = code;
295 code++;
296 }
297 /* code is now 1 more than the last code used for codelength si; but
298 * it must still fit in si bits, since no code is allowed to be all ones.
299 */
Chris Blumecca8c4d2019-03-01 01:09:50 -0800300 if (((JLONG)code) >= (((JLONG)1) << si))
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000301 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
302 code <<= 1;
303 si++;
304 }
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400305
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000306 /* Figure C.3: generate encoding tables */
307 /* These are code and size indexed by symbol value */
308
309 /* Set all codeless symbols to have code length 0;
310 * this lets us detect duplicate VAL entries here, and later
311 * allows emit_bits to detect any attempt to emit such symbols.
312 */
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400313 MEMZERO(dtbl->ehufsi, sizeof(dtbl->ehufsi));
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000314
315 /* This is also a convenient place to check for out-of-range
316 * and duplicated VAL entries. We allow 0..255 for AC symbols
317 * but only 0..15 for DC. (We could constrain them further
318 * based on data depth and mode, but this seems enough.)
319 */
320 maxsymbol = isDC ? 15 : 255;
321
322 for (p = 0; p < lastp; p++) {
323 i = htbl->huffval[p];
324 if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
325 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
326 dtbl->ehufco[i] = huffcode[p];
327 dtbl->ehufsi[i] = huffsize[p];
328 }
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000329}
330
331
332/* Outputting bytes to the file */
333
334/* Emit a byte, taking 'action' if must suspend. */
Chris Blumecca8c4d2019-03-01 01:09:50 -0800335#define emit_byte(state, val, action) { \
336 *(state)->next_output_byte++ = (JOCTET)(val); \
337 if (--(state)->free_in_buffer == 0) \
338 if (!dump_buffer(state)) \
339 { action; } \
340}
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000341
342
343LOCAL(boolean)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800344dump_buffer(working_state *state)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000345/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
346{
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400347 struct jpeg_destination_mgr *dest = state->cinfo->dest;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000348
Chris Blumecca8c4d2019-03-01 01:09:50 -0800349 if (!(*dest->empty_output_buffer) (state->cinfo))
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000350 return FALSE;
351 /* After a successful buffer dump, must reset buffer pointers */
352 state->next_output_byte = dest->next_output_byte;
353 state->free_in_buffer = dest->free_in_buffer;
354 return TRUE;
355}
356
357
358/* Outputting bits to the file */
359
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000360/* Output byte b and, speculatively, an additional 0 byte. 0xFF must be
361 * encoded as 0xFF 0x00, so the output buffer pointer is advanced by 2 if the
362 * byte is 0xFF. Otherwise, the output buffer pointer is advanced by 1, and
363 * the speculative 0 byte will be overwritten by the next byte.
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000364 */
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000365#define EMIT_BYTE(b) { \
366 buffer[0] = (JOCTET)(b); \
367 buffer[1] = 0; \
368 buffer -= -2 + ((JOCTET)(b) < 0xFF); \
Chris Blumecca8c4d2019-03-01 01:09:50 -0800369}
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000370
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000371/* Output the entire bit buffer. If there are no 0xFF bytes in it, then write
372 * directly to the output buffer. Otherwise, use the EMIT_BYTE() macro to
373 * encode 0xFF as 0xFF 0x00.
374 */
375#if BIT_BUF_SIZE == 64
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000376
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000377#define FLUSH() { \
378 if (put_buffer & 0x8080808080808080 & ~(put_buffer + 0x0101010101010101)) { \
379 EMIT_BYTE(put_buffer >> 56) \
380 EMIT_BYTE(put_buffer >> 48) \
381 EMIT_BYTE(put_buffer >> 40) \
382 EMIT_BYTE(put_buffer >> 32) \
383 EMIT_BYTE(put_buffer >> 24) \
384 EMIT_BYTE(put_buffer >> 16) \
385 EMIT_BYTE(put_buffer >> 8) \
386 EMIT_BYTE(put_buffer ) \
387 } else { \
388 buffer[0] = (JOCTET)(put_buffer >> 56); \
389 buffer[1] = (JOCTET)(put_buffer >> 48); \
390 buffer[2] = (JOCTET)(put_buffer >> 40); \
391 buffer[3] = (JOCTET)(put_buffer >> 32); \
392 buffer[4] = (JOCTET)(put_buffer >> 24); \
393 buffer[5] = (JOCTET)(put_buffer >> 16); \
394 buffer[6] = (JOCTET)(put_buffer >> 8); \
395 buffer[7] = (JOCTET)(put_buffer); \
396 buffer += 8; \
hbono@chromium.org98626972011-08-03 03:13:08 +0000397 } \
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000398}
399
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000400#else
401
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000402#define FLUSH() { \
403 if (put_buffer & 0x80808080 & ~(put_buffer + 0x01010101)) { \
404 EMIT_BYTE(put_buffer >> 24) \
405 EMIT_BYTE(put_buffer >> 16) \
406 EMIT_BYTE(put_buffer >> 8) \
407 EMIT_BYTE(put_buffer ) \
408 } else { \
409 buffer[0] = (JOCTET)(put_buffer >> 24); \
410 buffer[1] = (JOCTET)(put_buffer >> 16); \
411 buffer[2] = (JOCTET)(put_buffer >> 8); \
412 buffer[3] = (JOCTET)(put_buffer); \
413 buffer += 4; \
414 } \
Chris Blumecca8c4d2019-03-01 01:09:50 -0800415}
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000416
417#endif
418
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000419/* Fill the bit buffer to capacity with the leading bits from code, then output
420 * the bit buffer and put the remaining bits from code into the bit buffer.
421 */
422#define PUT_AND_FLUSH(code, size) { \
423 put_buffer = (put_buffer << (size + free_bits)) | (code >> -free_bits); \
424 FLUSH() \
425 free_bits += BIT_BUF_SIZE; \
426 put_buffer = code; \
427}
428
429/* Insert code into the bit buffer and output the bit buffer if needed.
430 * NOTE: We can't flush with free_bits == 0, since the left shift in
431 * PUT_AND_FLUSH() would have undefined behavior.
432 */
433#define PUT_BITS(code, size) { \
434 free_bits -= size; \
435 if (free_bits < 0) \
436 PUT_AND_FLUSH(code, size) \
437 else \
438 put_buffer = (put_buffer << size) | code; \
439}
440
441#define PUT_CODE(code, size) { \
442 temp &= (((JLONG)1) << nbits) - 1; \
443 temp |= code << nbits; \
444 nbits += size; \
445 PUT_BITS(temp, nbits) \
446}
447
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000448
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400449/* Although it is exceedingly rare, it is possible for a Huffman-encoded
450 * coefficient block to be larger than the 128-byte unencoded block. For each
451 * of the 64 coefficients, PUT_BITS is invoked twice, and each invocation can
452 * theoretically store 16 bits (for a maximum of 2048 bits or 256 bytes per
453 * encoded block.) If, for instance, one artificially sets the AC
454 * coefficients to alternating values of 32767 and -32768 (using the JPEG
455 * scanning order-- 1, 8, 16, etc.), then this will produce an encoded block
456 * larger than 200 bytes.
457 */
Jonathan Wrightdb870df2020-08-05 11:42:22 +0100458#define BUFSIZE (DCTSIZE2 * 8)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000459
hbono@chromium.org98626972011-08-03 03:13:08 +0000460#define LOAD_BUFFER() { \
461 if (state->free_in_buffer < BUFSIZE) { \
462 localbuf = 1; \
463 buffer = _buffer; \
Chris Blumecca8c4d2019-03-01 01:09:50 -0800464 } else \
465 buffer = state->next_output_byte; \
466}
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000467
hbono@chromium.org98626972011-08-03 03:13:08 +0000468#define STORE_BUFFER() { \
469 if (localbuf) { \
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000470 size_t bytes, bytestocopy; \
hbono@chromium.org98626972011-08-03 03:13:08 +0000471 bytes = buffer - _buffer; \
472 buffer = _buffer; \
473 while (bytes > 0) { \
Chris Blumecca8c4d2019-03-01 01:09:50 -0800474 bytestocopy = MIN(bytes, state->free_in_buffer); \
hbono@chromium.org98626972011-08-03 03:13:08 +0000475 MEMCOPY(state->next_output_byte, buffer, bytestocopy); \
476 state->next_output_byte += bytestocopy; \
477 buffer += bytestocopy; \
478 state->free_in_buffer -= bytestocopy; \
479 if (state->free_in_buffer == 0) \
Chris Blumecca8c4d2019-03-01 01:09:50 -0800480 if (!dump_buffer(state)) return FALSE; \
hbono@chromium.org98626972011-08-03 03:13:08 +0000481 bytes -= bytestocopy; \
482 } \
Chris Blumecca8c4d2019-03-01 01:09:50 -0800483 } else { \
hbono@chromium.org98626972011-08-03 03:13:08 +0000484 state->free_in_buffer -= (buffer - state->next_output_byte); \
485 state->next_output_byte = buffer; \
486 } \
Chris Blumecca8c4d2019-03-01 01:09:50 -0800487}
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000488
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000489
490LOCAL(boolean)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800491flush_bits(working_state *state)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000492{
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000493 JOCTET _buffer[BUFSIZE], *buffer, temp;
494 simd_bit_buf_type put_buffer; int put_bits;
495 int localbuf = 0;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000496
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000497 if (state->simd) {
498#if defined(__aarch64__) && !defined(NEON_INTRINSICS)
499 put_bits = state->cur.free_bits;
500#else
501 put_bits = SIMD_BIT_BUF_SIZE - state->cur.free_bits;
502#endif
503 put_buffer = state->cur.put_buffer.simd;
504 } else {
505 put_bits = BIT_BUF_SIZE - state->cur.free_bits;
506 put_buffer = state->cur.put_buffer.c;
507 }
508
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000509 LOAD_BUFFER()
510
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000511 while (put_bits >= 8) {
512 put_bits -= 8;
513 temp = (JOCTET)(put_buffer >> put_bits);
514 EMIT_BYTE(temp)
515 }
516 if (put_bits) {
517 /* fill partial byte with ones */
518 temp = (JOCTET)((put_buffer << (8 - put_bits)) | (0xFF >> put_bits));
519 EMIT_BYTE(temp)
520 }
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000521
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000522 if (state->simd) { /* and reset bit buffer to empty */
523 state->cur.put_buffer.simd = 0;
524#if defined(__aarch64__) && !defined(NEON_INTRINSICS)
525 state->cur.free_bits = 0;
526#else
527 state->cur.free_bits = SIMD_BIT_BUF_SIZE;
528#endif
529 } else {
530 state->cur.put_buffer.c = 0;
531 state->cur.free_bits = BIT_BUF_SIZE;
532 }
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000533 STORE_BUFFER()
534
535 return TRUE;
536}
537
hbono@chromium.org98626972011-08-03 03:13:08 +0000538
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000539/* Encode a single block's worth of coefficients */
540
541LOCAL(boolean)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800542encode_one_block_simd(working_state *state, JCOEFPTR block, int last_dc_val,
543 c_derived_tbl *dctbl, c_derived_tbl *actbl)
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400544{
545 JOCTET _buffer[BUFSIZE], *buffer;
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000546 int localbuf = 0;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400547
548 LOAD_BUFFER()
549
550 buffer = jsimd_huff_encode_one_block(state, buffer, block, last_dc_val,
551 dctbl, actbl);
552
553 STORE_BUFFER()
554
555 return TRUE;
556}
557
558LOCAL(boolean)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800559encode_one_block(working_state *state, JCOEFPTR block, int last_dc_val,
560 c_derived_tbl *dctbl, c_derived_tbl *actbl)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000561{
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000562 int temp, nbits, free_bits;
563 bit_buf_type put_buffer;
hbono@chromium.org98626972011-08-03 03:13:08 +0000564 JOCTET _buffer[BUFSIZE], *buffer;
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000565 int localbuf = 0;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000566
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000567 free_bits = state->cur.free_bits;
568 put_buffer = state->cur.put_buffer.c;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000569 LOAD_BUFFER()
570
571 /* Encode the DC coefficient difference per section F.1.2.1 */
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400572
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000573 temp = block[0] - last_dc_val;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000574
Chris Blumecca8c4d2019-03-01 01:09:50 -0800575 /* This is a well-known technique for obtaining the absolute value without a
576 * branch. It is derived from an assembly language technique presented in
577 * "How to Optimize for the Pentium Processors", Copyright (c) 1996, 1997 by
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000578 * Agner Fog. This code assumes we are on a two's complement machine.
Chris Blumecca8c4d2019-03-01 01:09:50 -0800579 */
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000580 nbits = temp >> (CHAR_BIT * sizeof(int) - 1);
581 temp += nbits;
582 nbits ^= temp;
hbono@chromium.org98626972011-08-03 03:13:08 +0000583
584 /* Find the number of bits needed for the magnitude of the coefficient */
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000585 nbits = JPEG_NBITS(nbits);
hbono@chromium.org98626972011-08-03 03:13:08 +0000586
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000587 /* Emit the Huffman-coded symbol for the number of bits.
588 * Emit that number of bits of the value, if positive,
589 * or the complement of its magnitude, if negative.
590 */
591 PUT_CODE(dctbl->ehufco[nbits], dctbl->ehufsi[nbits])
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000592
593 /* Encode the AC coefficients per section F.1.2.2 */
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400594
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000595 {
596 int r = 0; /* r = run length of zeros */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000597
hbono@chromium.org98626972011-08-03 03:13:08 +0000598/* Manually unroll the k loop to eliminate the counter variable. This
599 * improves performance greatly on systems with a limited number of
600 * registers (such as x86.)
601 */
Chris Blumecca8c4d2019-03-01 01:09:50 -0800602#define kloop(jpeg_natural_order_of_k) { \
hbono@chromium.org98626972011-08-03 03:13:08 +0000603 if ((temp = block[jpeg_natural_order_of_k]) == 0) { \
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000604 r += 16; \
hbono@chromium.org98626972011-08-03 03:13:08 +0000605 } else { \
hbono@chromium.org98626972011-08-03 03:13:08 +0000606 /* Branch-less absolute value, bitwise complement, etc., same as above */ \
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000607 nbits = temp >> (CHAR_BIT * sizeof(int) - 1); \
608 temp += nbits; \
609 nbits ^= temp; \
610 nbits = JPEG_NBITS_NONZERO(nbits); \
hbono@chromium.org98626972011-08-03 03:13:08 +0000611 /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000612 while (r >= 16 * 16) { \
613 r -= 16 * 16; \
614 PUT_BITS(actbl->ehufco[0xf0], actbl->ehufsi[0xf0]) \
hbono@chromium.org98626972011-08-03 03:13:08 +0000615 } \
616 /* Emit Huffman symbol for run length / number of bits */ \
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000617 r += nbits; \
618 PUT_CODE(actbl->ehufco[r], actbl->ehufsi[r]) \
Chris Blumecca8c4d2019-03-01 01:09:50 -0800619 r = 0; \
hbono@chromium.org98626972011-08-03 03:13:08 +0000620 } \
621}
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000622
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000623 /* One iteration for each value in jpeg_natural_order[] */
624 kloop(1); kloop(8); kloop(16); kloop(9); kloop(2); kloop(3);
625 kloop(10); kloop(17); kloop(24); kloop(32); kloop(25); kloop(18);
626 kloop(11); kloop(4); kloop(5); kloop(12); kloop(19); kloop(26);
627 kloop(33); kloop(40); kloop(48); kloop(41); kloop(34); kloop(27);
628 kloop(20); kloop(13); kloop(6); kloop(7); kloop(14); kloop(21);
629 kloop(28); kloop(35); kloop(42); kloop(49); kloop(56); kloop(57);
630 kloop(50); kloop(43); kloop(36); kloop(29); kloop(22); kloop(15);
631 kloop(23); kloop(30); kloop(37); kloop(44); kloop(51); kloop(58);
632 kloop(59); kloop(52); kloop(45); kloop(38); kloop(31); kloop(39);
633 kloop(46); kloop(53); kloop(60); kloop(61); kloop(54); kloop(47);
634 kloop(55); kloop(62); kloop(63);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000635
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000636 /* If the last coef(s) were zero, emit an end-of-block code */
637 if (r > 0) {
638 PUT_BITS(actbl->ehufco[0], actbl->ehufsi[0])
639 }
hbono@chromium.org98626972011-08-03 03:13:08 +0000640 }
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000641
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000642 state->cur.put_buffer.c = put_buffer;
643 state->cur.free_bits = free_bits;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000644 STORE_BUFFER()
645
646 return TRUE;
647}
648
649
650/*
651 * Emit a restart marker & resynchronize predictions.
652 */
653
654LOCAL(boolean)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800655emit_restart(working_state *state, int restart_num)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000656{
657 int ci;
658
Chris Blumecca8c4d2019-03-01 01:09:50 -0800659 if (!flush_bits(state))
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000660 return FALSE;
661
662 emit_byte(state, 0xFF, return FALSE);
663 emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
664
665 /* Re-initialize DC predictions to 0 */
666 for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
667 state->cur.last_dc_val[ci] = 0;
668
669 /* The restart counter is not updated until we successfully write the MCU. */
670
671 return TRUE;
672}
673
674
675/*
676 * Encode and output one MCU's worth of Huffman-compressed coefficients.
677 */
678
679METHODDEF(boolean)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800680encode_mcu_huff(j_compress_ptr cinfo, JBLOCKROW *MCU_data)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000681{
Chris Blumecca8c4d2019-03-01 01:09:50 -0800682 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000683 working_state state;
684 int blkn, ci;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400685 jpeg_component_info *compptr;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000686
687 /* Load up working state */
688 state.next_output_byte = cinfo->dest->next_output_byte;
689 state.free_in_buffer = cinfo->dest->free_in_buffer;
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000690 state.cur = entropy->saved;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000691 state.cinfo = cinfo;
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000692 state.simd = entropy->simd;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000693
694 /* Emit restart marker if needed */
695 if (cinfo->restart_interval) {
696 if (entropy->restarts_to_go == 0)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800697 if (!emit_restart(&state, entropy->next_restart_num))
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400698 return FALSE;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000699 }
700
701 /* Encode the MCU data blocks */
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400702 if (entropy->simd) {
703 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
704 ci = cinfo->MCU_membership[blkn];
705 compptr = cinfo->cur_comp_info[ci];
Chris Blumecca8c4d2019-03-01 01:09:50 -0800706 if (!encode_one_block_simd(&state,
707 MCU_data[blkn][0], state.cur.last_dc_val[ci],
708 entropy->dc_derived_tbls[compptr->dc_tbl_no],
709 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400710 return FALSE;
711 /* Update last_dc_val */
712 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
713 }
714 } else {
715 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
716 ci = cinfo->MCU_membership[blkn];
717 compptr = cinfo->cur_comp_info[ci];
Chris Blumecca8c4d2019-03-01 01:09:50 -0800718 if (!encode_one_block(&state,
719 MCU_data[blkn][0], state.cur.last_dc_val[ci],
720 entropy->dc_derived_tbls[compptr->dc_tbl_no],
721 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400722 return FALSE;
723 /* Update last_dc_val */
724 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
725 }
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000726 }
727
728 /* Completed MCU, so update state */
729 cinfo->dest->next_output_byte = state.next_output_byte;
730 cinfo->dest->free_in_buffer = state.free_in_buffer;
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000731 entropy->saved = state.cur;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000732
733 /* Update restart-interval state too */
734 if (cinfo->restart_interval) {
735 if (entropy->restarts_to_go == 0) {
736 entropy->restarts_to_go = cinfo->restart_interval;
737 entropy->next_restart_num++;
738 entropy->next_restart_num &= 7;
739 }
740 entropy->restarts_to_go--;
741 }
742
743 return TRUE;
744}
745
746
747/*
748 * Finish up at the end of a Huffman-compressed scan.
749 */
750
751METHODDEF(void)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800752finish_pass_huff(j_compress_ptr cinfo)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000753{
Chris Blumecca8c4d2019-03-01 01:09:50 -0800754 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000755 working_state state;
756
757 /* Load up working state ... flush_bits needs it */
758 state.next_output_byte = cinfo->dest->next_output_byte;
759 state.free_in_buffer = cinfo->dest->free_in_buffer;
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000760 state.cur = entropy->saved;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000761 state.cinfo = cinfo;
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000762 state.simd = entropy->simd;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000763
764 /* Flush out the last data */
Chris Blumecca8c4d2019-03-01 01:09:50 -0800765 if (!flush_bits(&state))
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000766 ERREXIT(cinfo, JERR_CANT_SUSPEND);
767
768 /* Update state */
769 cinfo->dest->next_output_byte = state.next_output_byte;
770 cinfo->dest->free_in_buffer = state.free_in_buffer;
Jonathan Wrightbbb82822020-11-25 13:36:43 +0000771 entropy->saved = state.cur;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000772}
773
774
775/*
776 * Huffman coding optimization.
777 *
778 * We first scan the supplied data and count the number of uses of each symbol
779 * that is to be Huffman-coded. (This process MUST agree with the code above.)
780 * Then we build a Huffman coding tree for the observed counts.
781 * Symbols which are not needed at all for the particular image are not
782 * assigned any code, which saves space in the DHT marker as well as in
783 * the compressed data.
784 */
785
786#ifdef ENTROPY_OPT_SUPPORTED
787
788
789/* Process a single block's worth of coefficients */
790
791LOCAL(void)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800792htest_one_block(j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
793 long dc_counts[], long ac_counts[])
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000794{
795 register int temp;
796 register int nbits;
797 register int k, r;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400798
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000799 /* Encode the DC coefficient difference per section F.1.2.1 */
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400800
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000801 temp = block[0] - last_dc_val;
802 if (temp < 0)
803 temp = -temp;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400804
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000805 /* Find the number of bits needed for the magnitude of the coefficient */
806 nbits = 0;
807 while (temp) {
808 nbits++;
809 temp >>= 1;
810 }
811 /* Check for out-of-range coefficient values.
812 * Since we're encoding a difference, the range limit is twice as much.
813 */
Chris Blumecca8c4d2019-03-01 01:09:50 -0800814 if (nbits > MAX_COEF_BITS + 1)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000815 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
816
817 /* Count the Huffman symbol for the number of bits */
818 dc_counts[nbits]++;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400819
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000820 /* Encode the AC coefficients per section F.1.2.2 */
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400821
822 r = 0; /* r = run length of zeros */
823
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000824 for (k = 1; k < DCTSIZE2; k++) {
825 if ((temp = block[jpeg_natural_order[k]]) == 0) {
826 r++;
827 } else {
828 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
829 while (r > 15) {
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400830 ac_counts[0xF0]++;
831 r -= 16;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000832 }
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400833
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000834 /* Find the number of bits needed for the magnitude of the coefficient */
835 if (temp < 0)
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400836 temp = -temp;
837
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000838 /* Find the number of bits needed for the magnitude of the coefficient */
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400839 nbits = 1; /* there must be at least one 1 bit */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000840 while ((temp >>= 1))
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400841 nbits++;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000842 /* Check for out-of-range coefficient values */
843 if (nbits > MAX_COEF_BITS)
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400844 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
845
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000846 /* Count Huffman symbol for run length / number of bits */
847 ac_counts[(r << 4) + nbits]++;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400848
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000849 r = 0;
850 }
851 }
852
853 /* If the last coef(s) were zero, emit an end-of-block code */
854 if (r > 0)
855 ac_counts[0]++;
856}
857
858
859/*
860 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
861 * No data is actually output, so no suspension return is possible.
862 */
863
864METHODDEF(boolean)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800865encode_mcu_gather(j_compress_ptr cinfo, JBLOCKROW *MCU_data)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000866{
Chris Blumecca8c4d2019-03-01 01:09:50 -0800867 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000868 int blkn, ci;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400869 jpeg_component_info *compptr;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000870
871 /* Take care of restart intervals if needed */
872 if (cinfo->restart_interval) {
873 if (entropy->restarts_to_go == 0) {
874 /* Re-initialize DC predictions to 0 */
875 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400876 entropy->saved.last_dc_val[ci] = 0;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000877 /* Update restart state */
878 entropy->restarts_to_go = cinfo->restart_interval;
879 }
880 entropy->restarts_to_go--;
881 }
882
883 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
884 ci = cinfo->MCU_membership[blkn];
885 compptr = cinfo->cur_comp_info[ci];
886 htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400887 entropy->dc_count_ptrs[compptr->dc_tbl_no],
888 entropy->ac_count_ptrs[compptr->ac_tbl_no]);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000889 entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
890 }
891
892 return TRUE;
893}
894
895
896/*
897 * Generate the best Huffman code table for the given counts, fill htbl.
898 * Note this is also used by jcphuff.c.
899 *
900 * The JPEG standard requires that no symbol be assigned a codeword of all
901 * one bits (so that padding bits added at the end of a compressed segment
902 * can't look like a valid code). Because of the canonical ordering of
903 * codewords, this just means that there must be an unused slot in the
Chris Blumecca8c4d2019-03-01 01:09:50 -0800904 * longest codeword length category. Annex K (Clause K.2) of
905 * Rec. ITU-T T.81 (1992) | ISO/IEC 10918-1:1994 suggests reserving such a slot
906 * by pretending that symbol 256 is a valid symbol with count 1. In theory
907 * that's not optimal; giving it count zero but including it in the symbol set
908 * anyway should give a better Huffman code. But the theoretically better code
909 * actually seems to come out worse in practice, because it produces more
910 * all-ones bytes (which incur stuffed zero bytes in the final file). In any
911 * case the difference is tiny.
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000912 *
913 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
914 * If some symbols have a very small but nonzero probability, the Huffman tree
915 * must be adjusted to meet the code length restriction. We currently use
916 * the adjustment method suggested in JPEG section K.2. This method is *not*
917 * optimal; it may not choose the best possible limited-length code. But
918 * typically only very-low-frequency symbols will be given less-than-optimal
919 * lengths, so the code is almost optimal. Experimental comparisons against
920 * an optimal limited-length-code algorithm indicate that the difference is
921 * microscopic --- usually less than a hundredth of a percent of total size.
922 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
923 */
924
925GLOBAL(void)
Chris Blumecca8c4d2019-03-01 01:09:50 -0800926jpeg_gen_optimal_table(j_compress_ptr cinfo, JHUFF_TBL *htbl, long freq[])
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000927{
Chris Blumecca8c4d2019-03-01 01:09:50 -0800928#define MAX_CLEN 32 /* assumed maximum initial code length */
929 UINT8 bits[MAX_CLEN + 1]; /* bits[k] = # of symbols with code length k */
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400930 int codesize[257]; /* codesize[k] = code length of symbol k */
931 int others[257]; /* next symbol in current branch of tree */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000932 int c1, c2;
933 int p, i, j;
934 long v;
935
936 /* This algorithm is explained in section K.2 of the JPEG standard */
937
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400938 MEMZERO(bits, sizeof(bits));
939 MEMZERO(codesize, sizeof(codesize));
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000940 for (i = 0; i < 257; i++)
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400941 others[i] = -1; /* init links to empty */
942
943 freq[256] = 1; /* make sure 256 has a nonzero count */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000944 /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
945 * that no real symbol is given code-value of all ones, because 256
946 * will be placed last in the largest codeword category.
947 */
948
949 /* Huffman's basic algorithm to assign optimal code lengths to symbols */
950
951 for (;;) {
952 /* Find the smallest nonzero frequency, set c1 = its symbol */
953 /* In case of ties, take the larger symbol number */
954 c1 = -1;
955 v = 1000000000L;
956 for (i = 0; i <= 256; i++) {
957 if (freq[i] && freq[i] <= v) {
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400958 v = freq[i];
959 c1 = i;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000960 }
961 }
962
963 /* Find the next smallest nonzero frequency, set c2 = its symbol */
964 /* In case of ties, take the larger symbol number */
965 c2 = -1;
966 v = 1000000000L;
967 for (i = 0; i <= 256; i++) {
968 if (freq[i] && freq[i] <= v && i != c1) {
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400969 v = freq[i];
970 c2 = i;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000971 }
972 }
973
974 /* Done if we've merged everything into one frequency */
975 if (c2 < 0)
976 break;
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400977
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000978 /* Else merge the two counts/trees */
979 freq[c1] += freq[c2];
980 freq[c2] = 0;
981
982 /* Increment the codesize of everything in c1's tree branch */
983 codesize[c1]++;
984 while (others[c1] >= 0) {
985 c1 = others[c1];
986 codesize[c1]++;
987 }
Tom Hudson0d47d2d2016-05-04 13:22:56 -0400988
989 others[c1] = c2; /* chain c2 onto c1's tree branch */
990
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +0000991 /* Increment the codesize of everything in c2's tree branch */
992 codesize[c2]++;
993 while (others[c2] >= 0) {
994 c2 = others[c2];
995 codesize[c2]++;
996 }
997 }
998
999 /* Now count the number of symbols of each code length */
1000 for (i = 0; i <= 256; i++) {
1001 if (codesize[i]) {
1002 /* The JPEG standard seems to think that this can't happen, */
1003 /* but I'm paranoid... */
1004 if (codesize[i] > MAX_CLEN)
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001005 ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001006
1007 bits[codesize[i]]++;
1008 }
1009 }
1010
1011 /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
1012 * Huffman procedure assigned any such lengths, we must adjust the coding.
Chris Blumecca8c4d2019-03-01 01:09:50 -08001013 * Here is what Rec. ITU-T T.81 | ISO/IEC 10918-1 says about how this next
1014 * bit works: Since symbols are paired for the longest Huffman code, the
1015 * symbols are removed from this length category two at a time. The prefix
1016 * for the pair (which is one bit shorter) is allocated to one of the pair;
1017 * then, skipping the BITS entry for that prefix length, a code word from the
1018 * next shortest nonzero BITS entry is converted into a prefix for two code
1019 * words one bit longer.
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001020 */
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001021
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001022 for (i = MAX_CLEN; i > 16; i--) {
1023 while (bits[i] > 0) {
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001024 j = i - 2; /* find length of new prefix to be used */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001025 while (bits[j] == 0)
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001026 j--;
1027
1028 bits[i] -= 2; /* remove two symbols */
Chris Blumecca8c4d2019-03-01 01:09:50 -08001029 bits[i - 1]++; /* one goes in this length */
1030 bits[j + 1] += 2; /* two new symbols in this length */
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001031 bits[j]--; /* symbol of this length is now a prefix */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001032 }
1033 }
1034
1035 /* Remove the count for the pseudo-symbol 256 from the largest codelength */
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001036 while (bits[i] == 0) /* find largest codelength still in use */
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001037 i--;
1038 bits[i]--;
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001039
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001040 /* Return final symbol counts (only for lengths 0..16) */
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001041 MEMCOPY(htbl->bits, bits, sizeof(htbl->bits));
1042
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001043 /* Return a list of the symbols sorted by code length */
1044 /* It's not real clear to me why we don't need to consider the codelength
Chris Blumecca8c4d2019-03-01 01:09:50 -08001045 * changes made above, but Rec. ITU-T T.81 | ISO/IEC 10918-1 seems to think
1046 * this works.
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001047 */
1048 p = 0;
1049 for (i = 1; i <= MAX_CLEN; i++) {
1050 for (j = 0; j <= 255; j++) {
1051 if (codesize[j] == i) {
Chris Blumecca8c4d2019-03-01 01:09:50 -08001052 htbl->huffval[p] = (UINT8)j;
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001053 p++;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001054 }
1055 }
1056 }
1057
1058 /* Set sent_table FALSE so updated table will be written to JPEG file. */
1059 htbl->sent_table = FALSE;
1060}
1061
1062
1063/*
1064 * Finish up a statistics-gathering pass and create the new Huffman tables.
1065 */
1066
1067METHODDEF(void)
Chris Blumecca8c4d2019-03-01 01:09:50 -08001068finish_pass_gather(j_compress_ptr cinfo)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001069{
Chris Blumecca8c4d2019-03-01 01:09:50 -08001070 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001071 int ci, dctbl, actbl;
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001072 jpeg_component_info *compptr;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001073 JHUFF_TBL **htblptr;
1074 boolean did_dc[NUM_HUFF_TBLS];
1075 boolean did_ac[NUM_HUFF_TBLS];
1076
1077 /* It's important not to apply jpeg_gen_optimal_table more than once
1078 * per table, because it clobbers the input frequency counts!
1079 */
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001080 MEMZERO(did_dc, sizeof(did_dc));
1081 MEMZERO(did_ac, sizeof(did_ac));
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001082
1083 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1084 compptr = cinfo->cur_comp_info[ci];
1085 dctbl = compptr->dc_tbl_no;
1086 actbl = compptr->ac_tbl_no;
Chris Blumecca8c4d2019-03-01 01:09:50 -08001087 if (!did_dc[dctbl]) {
1088 htblptr = &cinfo->dc_huff_tbl_ptrs[dctbl];
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001089 if (*htblptr == NULL)
Chris Blumecca8c4d2019-03-01 01:09:50 -08001090 *htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001091 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
1092 did_dc[dctbl] = TRUE;
1093 }
Chris Blumecca8c4d2019-03-01 01:09:50 -08001094 if (!did_ac[actbl]) {
1095 htblptr = &cinfo->ac_huff_tbl_ptrs[actbl];
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001096 if (*htblptr == NULL)
Chris Blumecca8c4d2019-03-01 01:09:50 -08001097 *htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001098 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
1099 did_ac[actbl] = TRUE;
1100 }
1101 }
1102}
1103
1104
1105#endif /* ENTROPY_OPT_SUPPORTED */
1106
1107
1108/*
1109 * Module initialization routine for Huffman entropy encoding.
1110 */
1111
1112GLOBAL(void)
Chris Blumecca8c4d2019-03-01 01:09:50 -08001113jinit_huff_encoder(j_compress_ptr cinfo)
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001114{
1115 huff_entropy_ptr entropy;
1116 int i;
1117
1118 entropy = (huff_entropy_ptr)
Chris Blumecca8c4d2019-03-01 01:09:50 -08001119 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
Tom Hudson0d47d2d2016-05-04 13:22:56 -04001120 sizeof(huff_entropy_encoder));
Chris Blumecca8c4d2019-03-01 01:09:50 -08001121 cinfo->entropy = (struct jpeg_entropy_encoder *)entropy;
hbono@chromium.orgf0c4f332010-11-01 05:14:55 +00001122 entropy->pub.start_pass = start_pass_huff;
1123
1124 /* Mark tables unallocated */
1125 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1126 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
1127#ifdef ENTROPY_OPT_SUPPORTED
1128 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
1129#endif
1130 }
1131}