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