typedefstruct { union {
bit_buf_type c; #ifdef WITH_SIMD
simd_bit_buf_type simd; #endif
} put_buffer; /* current bit accumulation buffer */ int free_bits; /* # of bits available in it */ /* (Neon GAS: # of bits now in it) */ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
} savable_state;
typedefstruct { struct jpeg_entropy_encoder pub; /* public fields */
savable_state saved; /* Bit buffer & DC state at start of MCU */
/* These fields are NOT loaded into local working state. */ unsignedint restarts_to_go; /* MCUs left in this restart interval */ int next_restart_num; /* next restart number to write (0-7) */
/* Pointers to derived tables (these workspaces have image lifespan) */
c_derived_tbl *dc_derived_tbls[NUM_HUFF_TBLS];
c_derived_tbl *ac_derived_tbls[NUM_HUFF_TBLS];
#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */ long *dc_count_ptrs[NUM_HUFF_TBLS]; long *ac_count_ptrs[NUM_HUFF_TBLS]; #endif
#ifdef WITH_SIMD int simd; #endif
} huff_entropy_encoder;
typedef huff_entropy_encoder *huff_entropy_ptr;
/* Working state while writing an MCU. *Thisstructcontainsallthefieldsthatareneededbysubroutines.
*/
typedefstruct {
JOCTET *next_output_byte; /* => next byte to write in buffer */
size_t free_in_buffer; /* # of byte spaces remaining in buffer */
savable_state cur; /* Current bit buffer & DC state */
j_compress_ptr cinfo; /* dump_buffer needs access to this */ #ifdef WITH_SIMD int simd; #endif
} working_state;
/* Allocate a workspace if we haven't already done so. */ if (*pdtbl == NULL)
*pdtbl = (c_derived_tbl *)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, sizeof(c_derived_tbl));
dtbl = *pdtbl;
/* Figure C.1: make table of Huffman code length for each symbol */
p = 0; for (l = 1; l <= 16; l++) {
i = (int)htbl->bits[l]; if (i < 0 || p + i > 256) /* protect against table overrun */
ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); while (i--)
huffsize[p++] = (char)l;
}
huffsize[p] = 0;
lastp = p;
/* Figure C.2: generate the codes themselves */ /* We also validate that the counts represent a legal Huffman code tree. */
code = 0;
si = huffsize[0];
p = 0; while (huffsize[p]) { while (((int)huffsize[p]) == si) {
huffcode[p++] = code;
code++;
} /* code is now 1 more than the last code used for codelength si; but *itmuststillfitinsibits,sincenocodeisallowedtobeallones.
*/ if (((JLONG)code) >= (((JLONG)1) << si))
ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
code <<= 1;
si++;
}
/* Figure C.3: generate encoding tables */ /* These are code and size indexed by symbol value */
/* Set all codeless symbols to have code length 0; *thisletsusdetectduplicateVALentrieshere,andlater *allowsemit_bitstodetectanyattempttoemitsuchsymbols.
*/
memset(dtbl->ehufco, 0, sizeof(dtbl->ehufco));
memset(dtbl->ehufsi, 0, sizeof(dtbl->ehufsi));
/* This is also a convenient place to check for out-of-range and duplicated *VALentries.Weallow0..255forACsymbolsbutonly0..15forDCin *lossymodeand0..16forDCinlosslessmode.(Wecouldconstrainthem *furtherbasedondatadepthandmode,butthisseemsenough.)
*/
maxsymbol = isDC ? (cinfo->master->lossless ? 16 : 15) : 255;
for (p = 0; p < lastp; p++) {
i = htbl->huffval[p]; if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
dtbl->ehufco[i] = huffcode[p];
dtbl->ehufsi[i] = huffsize[p];
}
}
/* Outputting bytes to the file */
/* Emit a byte, taking 'action' if must suspend. */ #define emit_byte(state, val, action) { \
*(state)->next_output_byte++ = (JOCTET)(val); \ if (--(state)->free_in_buffer == 0) \ if (!dump_buffer(state)) \
{ action; } \
}
LOCAL(boolean)
dump_buffer(working_state *state) /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
{ struct jpeg_destination_mgr *dest = state->cinfo->dest;
if (!(*dest->empty_output_buffer) (state->cinfo)) returnFALSE; /* After a successful buffer dump, must reset buffer pointers */
state->next_output_byte = dest->next_output_byte;
state->free_in_buffer = dest->free_in_buffer; return TRUE;
}
/* Outputting bits to the file */
/* Output byte b and, speculatively, an additional 0 byte. 0xFF must be *encodedas0xFF0x00,sotheoutputbufferpointerisadvancedby2ifthe *byteis0xFF.Otherwise,theoutputbufferpointerisadvancedby1,and *thespeculative0bytewillbeoverwrittenbythenextbyte.
*/ #define EMIT_BYTE(b) { \
buffer[0] = (JOCTET)(b); \
buffer[1] = 0; \
buffer -= -2 + ((JOCTET)(b) < 0xFF); \
}
/* Output the entire bit buffer. If there are no 0xFF bytes in it, then write *directlytotheoutputbuffer.Otherwise,usetheEMIT_BYTE()macroto *encode0xFFas0xFF0x00.
*/ #if BIT_BUF_SIZE == 64
/* Fill the bit buffer to capacity with the leading bits from code, then output *thebitbufferandputtheremainingbitsfromcodeintothebitbuffer.
*/ #define PUT_AND_FLUSH(code, size) { \
put_buffer = (put_buffer << (size + free_bits)) | (code >> -free_bits); \
FLUSH() \
free_bits += BIT_BUF_SIZE; \
put_buffer = code; \
}
/* Insert code into the bit buffer and output the bit buffer if needed. *NOTE:Wecan'tflushwithfree_bits==0,sincetheleftshiftin *PUT_AND_FLUSH()wouldhaveundefinedbehavior.
*/ #define PUT_BITS(code, size) { \
free_bits -= size; \ if (free_bits < 0) \
PUT_AND_FLUSH(code, size) \ else \
put_buffer = (put_buffer << size) | code; \
}
/* Although it is exceedingly rare, it is possible for a Huffman-encoded *coefficientblocktobelargerthanthe128-byteunencodedblock.Foreach *ofthe64coefficients,PUT_BITSisinvokedtwice,andeachinvocationcan *theoreticallystore16bits(foramaximumof2048bitsor256bytesper *encodedblock.)If,forinstance,oneartificiallysetstheAC *coefficientstoalternatingvaluesof32767and-32768(usingtheJPEG *scanningorder--1,8,16,etc.),thenthiswillproduceanencodedblock *largerthan200bytes.
*/ #define BUFSIZE (DCTSIZE2 * 8)
/* Encode the DC coefficient difference per section F.1.2.1 */
temp = block[0] - last_dc_val;
/* This is a well-known technique for obtaining the absolute value without a *branch.Itisderivedfromanassemblylanguagetechniquepresentedin *"HowtoOptimizeforthePentiumProcessors",Copyright(c)1996,1997by *AgnerFog.Thiscodeassumesweareonatwo'scomplementmachine.
*/
nbits = temp >> (CHAR_BIT * sizeof(int) - 1);
temp += nbits;
nbits ^= temp;
/* Find the number of bits needed for the magnitude of the coefficient */
nbits = JPEG_NBITS(nbits); /* Check for out-of-range coefficient values. *Sincewe'reencodingadifference,therangelimitistwiceasmuch.
*/ if (nbits > max_coef_bits + 1)
ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
/* Emit the Huffman-coded symbol for the number of bits. *Emitthatnumberofbitsofthevalue,ifpositive, *orthecomplementofitsmagnitude,ifnegative.
*/
PUT_CODE(dctbl->ehufco[nbits], dctbl->ehufsi[nbits])
/* Encode the AC coefficients per section F.1.2.2 */
{ int r = 0; /* r = run length of zeros */
/* Manually unroll the k loop to eliminate the counter variable. This *improvesperformancegreatlyonsystemswithalimitednumberof *registers(suchasx86.)
*/ #define kloop(jpeg_natural_order_of_k) { \ if ((temp = block[jpeg_natural_order_of_k]) == 0) { \
r += 16; \
} else { \ /* Branch-less absolute value, bitwise complement, etc., same as above */ \
nbits = temp >> (CHAR_BIT * sizeof(int) - 1); \
temp += nbits; \
nbits ^= temp; \
nbits = JPEG_NBITS_NONZERO(nbits); \ /* Check for out-of-range coefficient values */ \ if (nbits > max_coef_bits) \
ERREXIT(state->cinfo, JERR_BAD_DCT_COEF); \ /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \ while (r >= 16 * 16) { \
r -= 16 * 16; \
PUT_BITS(actbl->ehufco[0xf0], actbl->ehufsi[0xf0]) \
} \ /* Emit Huffman symbol for run length / number of bits */ \
r += nbits; \
PUT_CODE(actbl->ehufco[r], actbl->ehufsi[r]) \
r = 0; \
} \
}
/* Load up working state */
state.next_output_byte = cinfo->dest->next_output_byte;
state.free_in_buffer = cinfo->dest->free_in_buffer;
state.cur = entropy->saved;
state.cinfo = cinfo; #ifdef WITH_SIMD
state.simd = entropy->simd; #endif
/* Emit restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) if (!emit_restart(&state, entropy->next_restart_num)) returnFALSE;
}
/* Encode the MCU data blocks */ #ifdef WITH_SIMD if (entropy->simd) { for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
ci = cinfo->MCU_membership[blkn];
compptr = cinfo->cur_comp_info[ci]; if (!encode_one_block_simd(&state,
MCU_data[blkn][0], state.cur.last_dc_val[ci],
entropy->dc_derived_tbls[compptr->dc_tbl_no],
entropy->ac_derived_tbls[compptr->ac_tbl_no])) returnFALSE; /* Update last_dc_val */
state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
}
} else #endif
{ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
ci = cinfo->MCU_membership[blkn];
compptr = cinfo->cur_comp_info[ci]; if (!encode_one_block(&state,
MCU_data[blkn][0], state.cur.last_dc_val[ci],
entropy->dc_derived_tbls[compptr->dc_tbl_no],
entropy->ac_derived_tbls[compptr->ac_tbl_no])) returnFALSE; /* Update last_dc_val */
state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
}
}
/* Completed MCU, so update state */
cinfo->dest->next_output_byte = state.next_output_byte;
cinfo->dest->free_in_buffer = state.free_in_buffer;
entropy->saved = state.cur;
/* Update restart-interval state too */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) {
entropy->restarts_to_go = cinfo->restart_interval;
entropy->next_restart_num++;
entropy->next_restart_num &= 7;
}
entropy->restarts_to_go--;
}
/* Find the number of bits needed for the magnitude of the coefficient */
nbits = 0; while (temp) {
nbits++;
temp >>= 1;
} /* Check for out-of-range coefficient values. *Sincewe'reencodingadifference,therangelimitistwiceasmuch.
*/ if (nbits > max_coef_bits + 1)
ERREXIT(cinfo, JERR_BAD_DCT_COEF);
/* Count the Huffman symbol for the number of bits */
dc_counts[nbits]++;
/* Encode the AC coefficients per section F.1.2.2 */
r = 0; /* r = run length of zeros */
for (k = 1; k < DCTSIZE2; k++) { if ((temp = block[jpeg_natural_order[k]]) == 0) {
r++;
} else { /* if run length > 15, must emit special run-length-16 codes (0xF0) */ while (r > 15) {
ac_counts[0xF0]++;
r -= 16;
}
/* Find the number of bits needed for the magnitude of the coefficient */ if (temp < 0)
temp = -temp;
/* Find the number of bits needed for the magnitude of the coefficient */
nbits = 1; /* there must be at least one 1 bit */ while ((temp >>= 1))
nbits++; /* Check for out-of-range coefficient values */ if (nbits > max_coef_bits)
ERREXIT(cinfo, JERR_BAD_DCT_COEF);
/* Count Huffman symbol for run length / number of bits */
ac_counts[(r << 4) + nbits]++;
r = 0;
}
}
/* If the last coef(s) were zero, emit an end-of-block code */ if (r > 0)
ac_counts[0]++;
}
/* Take care of restart intervals if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { /* Re-initialize DC predictions to 0 */ for (ci = 0; ci < cinfo->comps_in_scan; ci++)
entropy->saved.last_dc_val[ci] = 0; /* Update restart state */
entropy->restarts_to_go = cinfo->restart_interval;
}
entropy->restarts_to_go--;
}
GLOBAL(void)
jpeg_gen_optimal_table(j_compress_ptr cinfo, JHUFF_TBL *htbl, long freq[])
{ #define MAX_CLEN 32/* assumed maximum initial code length */ /* The array length is MAX_CLEN + 2 rather than MAX_CLEN + 1 to work around a *-Wstringop-overflowfalsepositivewithGCC12andlater.
*/
UINT8 bits[MAX_CLEN + 2]; /* bits[k] = # of symbols with code length k */ int bit_pos[MAX_CLEN + 1]; /* # of symbols with smaller code length */ int codesize[257]; /* codesize[k] = code length of symbol k */ int nz_index[257]; /* index of nonzero symbol in the original freq
array */ int others[257]; /* next symbol in current branch of tree */ int c1, c2; int p, i, j; int num_nz_symbols; long v, v2;
/* This algorithm is explained in section K.2 of the JPEG standard */
memset(bits, 0, sizeof(bits));
memset(codesize, 0, sizeof(codesize)); for (i = 0; i < 257; i++)
others[i] = -1; /* init links to empty */
freq[256] = 1; /* make sure 256 has a nonzero count */ /* Including the pseudo-symbol 256 in the Huffman procedure guarantees *thatnorealsymbolisgivencode-valueofallones,because256 *willbeplacedlastinthelargestcodewordcategory.
*/
/* Group nonzero frequencies together so we can more easily find the *smallest.
*/
num_nz_symbols = 0; for (i = 0; i < 257; i++) { if (freq[i]) {
nz_index[num_nz_symbols] = i;
freq[num_nz_symbols] = freq[i];
num_nz_symbols++;
}
}
/* Huffman's basic algorithm to assign optimal code lengths to symbols */
for (;;) { /* Find the two smallest nonzero frequencies; set c1, c2 = their symbols */ /* In case of ties, take the larger symbol number. Since we have grouped *thenonzerosymbolstogether,checkingforzerosymbolsisnot *necessary.
*/
c1 = -1;
c2 = -1;
v = 1000000000L;
v2 = 1000000000L; for (i = 0; i < num_nz_symbols; i++) { if (freq[i] <= v2) { if (freq[i] <= v) {
c2 = c1;
v2 = v;
v = freq[i];
c1 = i;
} else {
v2 = freq[i];
c2 = i;
}
}
}
/* Done if we've merged everything into one frequency */ if (c2 < 0) break;
/* Else merge the two counts/trees */
freq[c1] += freq[c2]; /* Set the frequency to a very high value instead of zero, so we don't have *tocheckforzerovalues.
*/
freq[c2] = 1000000001L;
/* Increment the codesize of everything in c1's tree branch */
codesize[c1]++; while (others[c1] >= 0) {
c1 = others[c1];
codesize[c1]++;
}
/* Increment the codesize of everything in c2's tree branch */
codesize[c2]++; while (others[c2] >= 0) {
c2 = others[c2];
codesize[c2]++;
}
}
/* Now count the number of symbols of each code length */ for (i = 0; i < num_nz_symbols; i++) { /* The JPEG standard seems to think that this can't happen, */ /* but I'm paranoid... */ if (codesize[i] > MAX_CLEN)
ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
bits[codesize[i]]++;
}
/* Count the number of symbols with a length smaller than i bits, so we can *constructthesymboltablemoreefficiently.Notethatthisincludesthe *pseudo-symbol256,butsinceitisthelastsymbol,itwillnotaffectthe *table.
*/
p = 0; for (i = 1; i <= MAX_CLEN; i++) {
bit_pos[i] = p;
p += bits[i];
}
/* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure *Huffmanprocedureassignedanysuchlengths,wemustadjustthecoding. *HereiswhatRec.ITU-TT.81|ISO/IEC10918-1saysabouthowthisnext *bitworks:SincesymbolsarepairedforthelongestHuffmancode,the *symbolsareremovedfromthislengthcategorytwoatatime.Theprefix *forthepair(whichisonebitshorter)isallocatedtooneofthepair; *then,skippingtheBITSentryforthatprefixlength,acodewordfromthe *nextshortestnonzeroBITSentryisconvertedintoaprefixfortwocode *wordsonebitlonger.
*/
for (i = MAX_CLEN; i > 16; i--) { while (bits[i] > 0) {
j = i - 2; /* find length of new prefix to be used */ while (bits[j] == 0)
j--;
bits[i] -= 2; /* remove two symbols */
bits[i - 1]++; /* one goes in this length */
bits[j + 1] += 2; /* two new symbols in this length */
bits[j]--; /* symbol of this length is now a prefix */
}
}
/* Remove the count for the pseudo-symbol 256 from the largest codelength */ while (bits[i] == 0) /* find largest codelength still in use */
i--;
bits[i]--;
/* Return final symbol counts (only for lengths 0..16) */
memcpy(htbl->bits, bits, sizeof(htbl->bits));
/* Return a list of the symbols sorted by code length */ /* It's not real clear to me why we don't need to consider the codelength *changesmadeabove,butRec.ITU-TT.81|ISO/IEC10918-1seemstothink *thisworks.
*/ for (i = 0; i < num_nz_symbols - 1; i++) {
htbl->huffval[bit_pos[codesize[i]]] = (UINT8)nz_index[i];
bit_pos[codesize[i]]++;
}
/* Set sent_table FALSE so updated table will be written to JPEG file. */
htbl->sent_table = FALSE;
}
/* It's important not to apply jpeg_gen_optimal_table more than once *pertable,becauseitclobberstheinputfrequencycounts!
*/
memset(did_dc, 0, sizeof(did_dc));
memset(did_ac, 0, sizeof(did_ac));
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
dctbl = compptr->dc_tbl_no;
actbl = compptr->ac_tbl_no; if (!did_dc[dctbl]) {
htblptr = &cinfo->dc_huff_tbl_ptrs[dctbl]; if (*htblptr == NULL)
*htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
did_dc[dctbl] = TRUE;
} if (!did_ac[actbl]) {
htblptr = &cinfo->ac_huff_tbl_ptrs[actbl]; if (*htblptr == NULL)
*htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
did_ac[actbl] = TRUE;
}
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.