jchuff.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. /*
  2. * jchuff.c
  3. *
  4. * Copyright (C) 1991-1995, Thomas G. Lane.
  5. * This file is part of the Independent JPEG Group's software.
  6. * For conditions of distribution and use, see the accompanying README file.
  7. *
  8. * This file contains Huffman entropy encoding routines.
  9. *
  10. * Much of the complexity here has to do with supporting output suspension.
  11. * If the data destination module demands suspension, we want to be able to
  12. * back up to the start of the current MCU. To do this, we copy state
  13. * variables into local working storage, and update them back to the
  14. * permanent JPEG objects only upon successful completion of an MCU.
  15. */
  16. #define JPEG_INTERNALS
  17. #include "jinclude.h"
  18. #include "jpeglib.h"
  19. #include "jchuff.h" /* Declarations shared with jcphuff.c */
  20. /* Expanded entropy encoder object for Huffman encoding.
  21. *
  22. * The savable_state subrecord contains fields that change within an MCU,
  23. * but must not be updated permanently until we complete the MCU.
  24. */
  25. typedef struct {
  26. INT32 put_buffer; /* current bit-accumulation buffer */
  27. int put_bits; /* # of bits now in it */
  28. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  29. } savable_state;
  30. /* This macro is to work around compilers with missing or broken
  31. * structure assignment. You'll need to fix this code if you have
  32. * such a compiler and you change MAX_COMPS_IN_SCAN.
  33. */
  34. #ifndef NO_STRUCT_ASSIGN
  35. #define ASSIGN_STATE( dest, src ) ( ( dest ) = ( src ) )
  36. #else
  37. #if MAX_COMPS_IN_SCAN == 4
  38. #define ASSIGN_STATE( dest, src ) \
  39. ( ( dest ).put_buffer = ( src ).put_buffer, \
  40. ( dest ).put_bits = ( src ).put_bits, \
  41. ( dest ).last_dc_val[0] = ( src ).last_dc_val[0], \
  42. ( dest ).last_dc_val[1] = ( src ).last_dc_val[1], \
  43. ( dest ).last_dc_val[2] = ( src ).last_dc_val[2], \
  44. ( dest ).last_dc_val[3] = ( src ).last_dc_val[3] )
  45. #endif
  46. #endif
  47. typedef struct {
  48. struct jpeg_entropy_encoder pub;/* public fields */
  49. savable_state saved; /* Bit buffer & DC state at start of MCU */
  50. /* These fields are NOT loaded into local working state. */
  51. unsigned int restarts_to_go;/* MCUs left in this restart interval */
  52. int next_restart_num; /* next restart number to write (0-7) */
  53. /* Pointers to derived tables (these workspaces have image lifespan) */
  54. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  55. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  56. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  57. long * dc_count_ptrs[NUM_HUFF_TBLS];
  58. long * ac_count_ptrs[NUM_HUFF_TBLS];
  59. #endif
  60. } huff_entropy_encoder;
  61. typedef huff_entropy_encoder * huff_entropy_ptr;
  62. /* Working state while writing an MCU.
  63. * This struct contains all the fields that are needed by subroutines.
  64. */
  65. typedef struct {
  66. JOCTET * next_output_byte; /* => next byte to write in buffer */
  67. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  68. savable_state cur; /* Current bit buffer & DC state */
  69. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  70. } working_state;
  71. /* Forward declarations */
  72. METHODDEF boolean encode_mcu_huff JPP( ( j_compress_ptr cinfo,
  73. JBLOCKROW * MCU_data ) );
  74. METHODDEF void finish_pass_huff JPP( (j_compress_ptr cinfo) );
  75. #ifdef ENTROPY_OPT_SUPPORTED
  76. METHODDEF boolean encode_mcu_gather JPP( ( j_compress_ptr cinfo,
  77. JBLOCKROW * MCU_data ) );
  78. METHODDEF void finish_pass_gather JPP( (j_compress_ptr cinfo) );
  79. #endif
  80. /*
  81. * Initialize for a Huffman-compressed scan.
  82. * If gather_statistics is TRUE, we do not output anything during the scan,
  83. * just count the Huffman symbols used and generate Huffman code tables.
  84. */
  85. METHODDEF void
  86. start_pass_huff( j_compress_ptr cinfo, boolean gather_statistics ) {
  87. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  88. int ci, dctbl, actbl;
  89. jpeg_component_info * compptr;
  90. if ( gather_statistics ) {
  91. #ifdef ENTROPY_OPT_SUPPORTED
  92. entropy->pub.encode_mcu = encode_mcu_gather;
  93. entropy->pub.finish_pass = finish_pass_gather;
  94. #else
  95. ERREXIT( cinfo, JERR_NOT_COMPILED );
  96. #endif
  97. } else {
  98. entropy->pub.encode_mcu = encode_mcu_huff;
  99. entropy->pub.finish_pass = finish_pass_huff;
  100. }
  101. for ( ci = 0; ci < cinfo->comps_in_scan; ci++ ) {
  102. compptr = cinfo->cur_comp_info[ci];
  103. dctbl = compptr->dc_tbl_no;
  104. actbl = compptr->ac_tbl_no;
  105. /* Make sure requested tables are present */
  106. /* (In gather mode, tables need not be allocated yet) */
  107. if ( ( dctbl < 0 ) || ( dctbl >= NUM_HUFF_TBLS ) ||
  108. ( ( cinfo->dc_huff_tbl_ptrs[dctbl] == NULL ) && ( !gather_statistics ) ) ) {
  109. ERREXIT1( cinfo, JERR_NO_HUFF_TABLE, dctbl );
  110. }
  111. if ( ( actbl < 0 ) || ( actbl >= NUM_HUFF_TBLS ) ||
  112. ( ( cinfo->ac_huff_tbl_ptrs[actbl] == NULL ) && ( !gather_statistics ) ) ) {
  113. ERREXIT1( cinfo, JERR_NO_HUFF_TABLE, actbl );
  114. }
  115. if ( gather_statistics ) {
  116. #ifdef ENTROPY_OPT_SUPPORTED
  117. /* Allocate and zero the statistics tables */
  118. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  119. if ( entropy->dc_count_ptrs[dctbl] == NULL ) {
  120. entropy->dc_count_ptrs[dctbl] = (long *)
  121. ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE,
  122. 257 * SIZEOF( long ) );
  123. }
  124. MEMZERO( entropy->dc_count_ptrs[dctbl], 257 * SIZEOF( long ) );
  125. if ( entropy->ac_count_ptrs[actbl] == NULL ) {
  126. entropy->ac_count_ptrs[actbl] = (long *)
  127. ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE,
  128. 257 * SIZEOF( long ) );
  129. }
  130. MEMZERO( entropy->ac_count_ptrs[actbl], 257 * SIZEOF( long ) );
  131. #endif
  132. } else {
  133. /* Compute derived values for Huffman tables */
  134. /* We may do this more than once for a table, but it's not expensive */
  135. jpeg_make_c_derived_tbl( cinfo, cinfo->dc_huff_tbl_ptrs[dctbl],
  136. &entropy->dc_derived_tbls[dctbl] );
  137. jpeg_make_c_derived_tbl( cinfo, cinfo->ac_huff_tbl_ptrs[actbl],
  138. &entropy->ac_derived_tbls[actbl] );
  139. }
  140. /* Initialize DC predictions to 0 */
  141. entropy->saved.last_dc_val[ci] = 0;
  142. }
  143. /* Initialize bit buffer to empty */
  144. entropy->saved.put_buffer = 0;
  145. entropy->saved.put_bits = 0;
  146. /* Initialize restart stuff */
  147. entropy->restarts_to_go = cinfo->restart_interval;
  148. entropy->next_restart_num = 0;
  149. }
  150. /*
  151. * Compute the derived values for a Huffman table.
  152. * Note this is also used by jcphuff.c.
  153. */
  154. GLOBAL void
  155. jpeg_make_c_derived_tbl( j_compress_ptr cinfo, JHUFF_TBL * htbl,
  156. c_derived_tbl ** pdtbl ) {
  157. c_derived_tbl * dtbl;
  158. int p, i, l, lastp, si;
  159. char huffsize[257];
  160. unsigned int huffcode[257];
  161. unsigned int code;
  162. /* Allocate a workspace if we haven't already done so. */
  163. if ( *pdtbl == NULL ) {
  164. *pdtbl = (c_derived_tbl *)
  165. ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE,
  166. SIZEOF( c_derived_tbl ) );
  167. }
  168. dtbl = *pdtbl;
  169. /* Figure C.1: make table of Huffman code length for each symbol */
  170. /* Note that this is in code-length order. */
  171. p = 0;
  172. for ( l = 1; l <= 16; l++ ) {
  173. for ( i = 1; i <= (int) htbl->bits[l]; i++ ) {
  174. huffsize[p++] = (char) l;
  175. }
  176. }
  177. huffsize[p] = 0;
  178. lastp = p;
  179. /* Figure C.2: generate the codes themselves */
  180. /* Note that this is in code-length order. */
  181. code = 0;
  182. si = huffsize[0];
  183. p = 0;
  184. while ( huffsize[p] ) {
  185. while ( ( (int) huffsize[p] ) == si ) {
  186. huffcode[p++] = code;
  187. code++;
  188. }
  189. code <<= 1;
  190. si++;
  191. }
  192. /* Figure C.3: generate encoding tables */
  193. /* These are code and size indexed by symbol value */
  194. /* Set any codeless symbols to have code length 0;
  195. * this allows emit_bits to detect any attempt to emit such symbols.
  196. */
  197. MEMZERO( dtbl->ehufsi, SIZEOF( dtbl->ehufsi ) );
  198. for ( p = 0; p < lastp; p++ ) {
  199. dtbl->ehufco[htbl->huffval[p]] = huffcode[p];
  200. dtbl->ehufsi[htbl->huffval[p]] = huffsize[p];
  201. }
  202. }
  203. /* Outputting bytes to the file */
  204. /* Emit a byte, taking 'action' if must suspend. */
  205. #define emit_byte( state, val, action ) \
  206. { *( state )->next_output_byte++ = (JOCTET) ( val ); \
  207. if ( -- ( state )->free_in_buffer == 0 ) { \
  208. if ( !dump_buffer( state ) ) \
  209. { action; } } }
  210. LOCAL boolean
  211. dump_buffer( working_state * state ) {
  212. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  213. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  214. if ( !( *dest->empty_output_buffer )( state->cinfo ) ) {
  215. return FALSE;
  216. }
  217. /* After a successful buffer dump, must reset buffer pointers */
  218. state->next_output_byte = dest->next_output_byte;
  219. state->free_in_buffer = dest->free_in_buffer;
  220. return TRUE;
  221. }
  222. /* Outputting bits to the file */
  223. /* Only the right 24 bits of put_buffer are used; the valid bits are
  224. * left-justified in this part. At most 16 bits can be passed to emit_bits
  225. * in one call, and we never retain more than 7 bits in put_buffer
  226. * between calls, so 24 bits are sufficient.
  227. */
  228. INLINE
  229. LOCAL boolean
  230. emit_bits( working_state * state, unsigned int code, int size ) {
  231. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  232. /* This routine is heavily used, so it's worth coding tightly. */
  233. register INT32 put_buffer = (INT32) code;
  234. register int put_bits = state->cur.put_bits;
  235. /* if size is 0, caller used an invalid Huffman table entry */
  236. if ( size == 0 ) {
  237. ERREXIT( state->cinfo, JERR_HUFF_MISSING_CODE );
  238. }
  239. put_buffer &= ( ( (INT32) 1 ) << size ) - 1;/* mask off any extra bits in code */
  240. put_bits += size; /* new number of bits in buffer */
  241. put_buffer <<= 24 - put_bits;/* align incoming bits */
  242. put_buffer |= state->cur.put_buffer;/* and merge with old buffer contents */
  243. while ( put_bits >= 8 ) {
  244. int c = (int) ( ( put_buffer >> 16 ) & 0xFF );
  245. emit_byte( state, c, return FALSE );
  246. if ( c == 0xFF ) { /* need to stuff a zero byte? */
  247. emit_byte( state, 0, return FALSE );
  248. }
  249. put_buffer <<= 8;
  250. put_bits -= 8;
  251. }
  252. state->cur.put_buffer = put_buffer;/* update state variables */
  253. state->cur.put_bits = put_bits;
  254. return TRUE;
  255. }
  256. LOCAL boolean
  257. flush_bits( working_state * state ) {
  258. if ( !emit_bits( state, 0x7F, 7 ) ) {/* fill any partial byte with ones */
  259. return FALSE;
  260. }
  261. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  262. state->cur.put_bits = 0;
  263. return TRUE;
  264. }
  265. /* Encode a single block's worth of coefficients */
  266. LOCAL boolean
  267. encode_one_block( working_state * state, JCOEFPTR block, int last_dc_val,
  268. c_derived_tbl * dctbl, c_derived_tbl * actbl ) {
  269. register int temp, temp2;
  270. register int nbits;
  271. register int k, r, i;
  272. /* Encode the DC coefficient difference per section F.1.2.1 */
  273. temp = temp2 = block[0] - last_dc_val;
  274. if ( temp < 0 ) {
  275. temp = -temp; /* temp is abs value of input */
  276. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  277. /* This code assumes we are on a two's complement machine */
  278. temp2--;
  279. }
  280. /* Find the number of bits needed for the magnitude of the coefficient */
  281. nbits = 0;
  282. while ( temp ) {
  283. nbits++;
  284. temp >>= 1;
  285. }
  286. /* Emit the Huffman-coded symbol for the number of bits */
  287. if ( !emit_bits( state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits] ) ) {
  288. return FALSE;
  289. }
  290. /* Emit that number of bits of the value, if positive, */
  291. /* or the complement of its magnitude, if negative. */
  292. if ( nbits ) { /* emit_bits rejects calls with size 0 */
  293. if ( !emit_bits( state, (unsigned int) temp2, nbits ) ) {
  294. return FALSE;
  295. }
  296. }
  297. /* Encode the AC coefficients per section F.1.2.2 */
  298. r = 0; /* r = run length of zeros */
  299. for ( k = 1; k < DCTSIZE2; k++ ) {
  300. if ( ( temp = block[jpeg_natural_order[k]] ) == 0 ) {
  301. r++;
  302. } else {
  303. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  304. while ( r > 15 ) {
  305. if ( !emit_bits( state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0] ) ) {
  306. return FALSE;
  307. }
  308. r -= 16;
  309. }
  310. temp2 = temp;
  311. if ( temp < 0 ) {
  312. temp = -temp;/* temp is abs value of input */
  313. /* This code assumes we are on a two's complement machine */
  314. temp2--;
  315. }
  316. /* Find the number of bits needed for the magnitude of the coefficient */
  317. nbits = 1; /* there must be at least one 1 bit */
  318. while ( ( temp >>= 1 ) ) {
  319. nbits++;
  320. }
  321. /* Emit Huffman symbol for run length / number of bits */
  322. i = ( r << 4 ) + nbits;
  323. if ( !emit_bits( state, actbl->ehufco[i], actbl->ehufsi[i] ) ) {
  324. return FALSE;
  325. }
  326. /* Emit that number of bits of the value, if positive, */
  327. /* or the complement of its magnitude, if negative. */
  328. if ( !emit_bits( state, (unsigned int) temp2, nbits ) ) {
  329. return FALSE;
  330. }
  331. r = 0;
  332. }
  333. }
  334. /* If the last coef(s) were zero, emit an end-of-block code */
  335. if ( r > 0 ) {
  336. if ( !emit_bits( state, actbl->ehufco[0], actbl->ehufsi[0] ) ) {
  337. return FALSE;
  338. }
  339. }
  340. return TRUE;
  341. }
  342. /*
  343. * Emit a restart marker & resynchronize predictions.
  344. */
  345. LOCAL boolean
  346. emit_restart( working_state * state, int restart_num ) {
  347. int ci;
  348. if ( !flush_bits( state ) ) {
  349. return FALSE;
  350. }
  351. emit_byte( state, 0xFF, return FALSE );
  352. emit_byte( state, JPEG_RST0 + restart_num, return FALSE );
  353. /* Re-initialize DC predictions to 0 */
  354. for ( ci = 0; ci < state->cinfo->comps_in_scan; ci++ ) {
  355. state->cur.last_dc_val[ci] = 0;
  356. }
  357. /* The restart counter is not updated until we successfully write the MCU. */
  358. return TRUE;
  359. }
  360. /*
  361. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  362. */
  363. METHODDEF boolean
  364. encode_mcu_huff( j_compress_ptr cinfo, JBLOCKROW * MCU_data ) {
  365. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  366. working_state state;
  367. int blkn, ci;
  368. jpeg_component_info * compptr;
  369. /* Load up working state */
  370. state.next_output_byte = cinfo->dest->next_output_byte;
  371. state.free_in_buffer = cinfo->dest->free_in_buffer;
  372. ASSIGN_STATE( state.cur, entropy->saved );
  373. state.cinfo = cinfo;
  374. /* Emit restart marker if needed */
  375. if ( cinfo->restart_interval ) {
  376. if ( entropy->restarts_to_go == 0 ) {
  377. if ( !emit_restart( &state, entropy->next_restart_num ) ) {
  378. return FALSE;
  379. }
  380. }
  381. }
  382. /* Encode the MCU data blocks */
  383. for ( blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++ ) {
  384. ci = cinfo->MCU_membership[blkn];
  385. compptr = cinfo->cur_comp_info[ci];
  386. if ( !encode_one_block( &state,
  387. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  388. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  389. entropy->ac_derived_tbls[compptr->ac_tbl_no] ) ) {
  390. return FALSE;
  391. }
  392. /* Update last_dc_val */
  393. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  394. }
  395. /* Completed MCU, so update state */
  396. cinfo->dest->next_output_byte = state.next_output_byte;
  397. cinfo->dest->free_in_buffer = state.free_in_buffer;
  398. ASSIGN_STATE( entropy->saved, state.cur );
  399. /* Update restart-interval state too */
  400. if ( cinfo->restart_interval ) {
  401. if ( entropy->restarts_to_go == 0 ) {
  402. entropy->restarts_to_go = cinfo->restart_interval;
  403. entropy->next_restart_num++;
  404. entropy->next_restart_num &= 7;
  405. }
  406. entropy->restarts_to_go--;
  407. }
  408. return TRUE;
  409. }
  410. /*
  411. * Finish up at the end of a Huffman-compressed scan.
  412. */
  413. METHODDEF void
  414. finish_pass_huff( j_compress_ptr cinfo ) {
  415. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  416. working_state state;
  417. /* Load up working state ... flush_bits needs it */
  418. state.next_output_byte = cinfo->dest->next_output_byte;
  419. state.free_in_buffer = cinfo->dest->free_in_buffer;
  420. ASSIGN_STATE( state.cur, entropy->saved );
  421. state.cinfo = cinfo;
  422. /* Flush out the last data */
  423. if ( !flush_bits( &state ) ) {
  424. ERREXIT( cinfo, JERR_CANT_SUSPEND );
  425. }
  426. /* Update state */
  427. cinfo->dest->next_output_byte = state.next_output_byte;
  428. cinfo->dest->free_in_buffer = state.free_in_buffer;
  429. ASSIGN_STATE( entropy->saved, state.cur );
  430. }
  431. /*
  432. * Huffman coding optimization.
  433. *
  434. * This actually is optimization, in the sense that we find the best possible
  435. * Huffman table(s) for the given data. We first scan the supplied data and
  436. * count the number of uses of each symbol that is to be Huffman-coded.
  437. * (This process must agree with the code above.) Then we build an
  438. * optimal Huffman coding tree for the observed counts.
  439. *
  440. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  441. * If some symbols have a very small but nonzero probability, the Huffman tree
  442. * must be adjusted to meet the code length restriction. We currently use
  443. * the adjustment method suggested in the JPEG spec. This method is *not*
  444. * optimal; it may not choose the best possible limited-length code. But
  445. * since the symbols involved are infrequently used, it's not clear that
  446. * going to extra trouble is worthwhile.
  447. */
  448. #ifdef ENTROPY_OPT_SUPPORTED
  449. /* Process a single block's worth of coefficients */
  450. LOCAL void
  451. htest_one_block( JCOEFPTR block, int last_dc_val,
  452. long dc_counts[], long ac_counts[] ) {
  453. register int temp;
  454. register int nbits;
  455. register int k, r;
  456. /* Encode the DC coefficient difference per section F.1.2.1 */
  457. temp = block[0] - last_dc_val;
  458. if ( temp < 0 ) {
  459. temp = -temp;
  460. }
  461. /* Find the number of bits needed for the magnitude of the coefficient */
  462. nbits = 0;
  463. while ( temp ) {
  464. nbits++;
  465. temp >>= 1;
  466. }
  467. /* Count the Huffman symbol for the number of bits */
  468. dc_counts[nbits]++;
  469. /* Encode the AC coefficients per section F.1.2.2 */
  470. r = 0; /* r = run length of zeros */
  471. for ( k = 1; k < DCTSIZE2; k++ ) {
  472. if ( ( temp = block[jpeg_natural_order[k]] ) == 0 ) {
  473. r++;
  474. } else {
  475. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  476. while ( r > 15 ) {
  477. ac_counts[0xF0]++;
  478. r -= 16;
  479. }
  480. /* Find the number of bits needed for the magnitude of the coefficient */
  481. if ( temp < 0 ) {
  482. temp = -temp;
  483. }
  484. /* Find the number of bits needed for the magnitude of the coefficient */
  485. nbits = 1; /* there must be at least one 1 bit */
  486. while ( ( temp >>= 1 ) ) {
  487. nbits++;
  488. }
  489. /* Count Huffman symbol for run length / number of bits */
  490. ac_counts[( r << 4 ) + nbits]++;
  491. r = 0;
  492. }
  493. }
  494. /* If the last coef(s) were zero, emit an end-of-block code */
  495. if ( r > 0 ) {
  496. ac_counts[0]++;
  497. }
  498. }
  499. /*
  500. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  501. * No data is actually output, so no suspension return is possible.
  502. */
  503. METHODDEF boolean
  504. encode_mcu_gather( j_compress_ptr cinfo, JBLOCKROW * MCU_data ) {
  505. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  506. int blkn, ci;
  507. jpeg_component_info * compptr;
  508. /* Take care of restart intervals if needed */
  509. if ( cinfo->restart_interval ) {
  510. if ( entropy->restarts_to_go == 0 ) {
  511. /* Re-initialize DC predictions to 0 */
  512. for ( ci = 0; ci < cinfo->comps_in_scan; ci++ ) {
  513. entropy->saved.last_dc_val[ci] = 0;
  514. }
  515. /* Update restart state */
  516. entropy->restarts_to_go = cinfo->restart_interval;
  517. }
  518. entropy->restarts_to_go--;
  519. }
  520. for ( blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++ ) {
  521. ci = cinfo->MCU_membership[blkn];
  522. compptr = cinfo->cur_comp_info[ci];
  523. htest_one_block( MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  524. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  525. entropy->ac_count_ptrs[compptr->ac_tbl_no] );
  526. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  527. }
  528. return TRUE;
  529. }
  530. /*
  531. * Generate the optimal coding for the given counts, fill htbl.
  532. * Note this is also used by jcphuff.c.
  533. */
  534. GLOBAL void
  535. jpeg_gen_optimal_table( j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[] ) {
  536. #define MAX_CLEN 32 /* assumed maximum initial code length */
  537. UINT8 bits[MAX_CLEN + 1];/* bits[k] = # of symbols with code length k */
  538. int codesize[257]; /* codesize[k] = code length of symbol k */
  539. int others[257]; /* next symbol in current branch of tree */
  540. int c1, c2;
  541. int p, i, j;
  542. long v;
  543. /* This algorithm is explained in section K.2 of the JPEG standard */
  544. MEMZERO( bits, SIZEOF( bits ) );
  545. MEMZERO( codesize, SIZEOF( codesize ) );
  546. for ( i = 0; i < 257; i++ ) {
  547. others[i] = -1;
  548. } /* init links to empty */
  549. freq[256] = 1; /* make sure there is a nonzero count */
  550. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  551. * that no real symbol is given code-value of all ones, because 256
  552. * will be placed in the largest codeword category.
  553. */
  554. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  555. for (;; ) {
  556. /* Find the smallest nonzero frequency, set c1 = its symbol */
  557. /* In case of ties, take the larger symbol number */
  558. c1 = -1;
  559. v = 1000000000L;
  560. for ( i = 0; i <= 256; i++ ) {
  561. if ( ( freq[i] ) && ( freq[i] <= v ) ) {
  562. v = freq[i];
  563. c1 = i;
  564. }
  565. }
  566. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  567. /* In case of ties, take the larger symbol number */
  568. c2 = -1;
  569. v = 1000000000L;
  570. for ( i = 0; i <= 256; i++ ) {
  571. if ( ( freq[i] ) && ( freq[i] <= v ) && ( i != c1 ) ) {
  572. v = freq[i];
  573. c2 = i;
  574. }
  575. }
  576. /* Done if we've merged everything into one frequency */
  577. if ( c2 < 0 ) {
  578. break;
  579. }
  580. /* Else merge the two counts/trees */
  581. freq[c1] += freq[c2];
  582. freq[c2] = 0;
  583. /* Increment the codesize of everything in c1's tree branch */
  584. codesize[c1]++;
  585. while ( others[c1] >= 0 ) {
  586. c1 = others[c1];
  587. codesize[c1]++;
  588. }
  589. others[c1] = c2; /* chain c2 onto c1's tree branch */
  590. /* Increment the codesize of everything in c2's tree branch */
  591. codesize[c2]++;
  592. while ( others[c2] >= 0 ) {
  593. c2 = others[c2];
  594. codesize[c2]++;
  595. }
  596. }
  597. /* Now count the number of symbols of each code length */
  598. for ( i = 0; i <= 256; i++ ) {
  599. if ( codesize[i] ) {
  600. /* The JPEG standard seems to think that this can't happen, */
  601. /* but I'm paranoid... */
  602. if ( codesize[i] > MAX_CLEN ) {
  603. ERREXIT( cinfo, JERR_HUFF_CLEN_OVERFLOW );
  604. }
  605. bits[codesize[i]]++;
  606. }
  607. }
  608. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  609. * Huffman procedure assigned any such lengths, we must adjust the coding.
  610. * Here is what the JPEG spec says about how this next bit works:
  611. * Since symbols are paired for the longest Huffman code, the symbols are
  612. * removed from this length category two at a time. The prefix for the pair
  613. * (which is one bit shorter) is allocated to one of the pair; then,
  614. * skipping the BITS entry for that prefix length, a code word from the next
  615. * shortest nonzero BITS entry is converted into a prefix for two code words
  616. * one bit longer.
  617. */
  618. for ( i = MAX_CLEN; i > 16; i-- ) {
  619. while ( bits[i] > 0 ) {
  620. j = i - 2; /* find length of new prefix to be used */
  621. while ( bits[j] == 0 ) {
  622. j--;
  623. }
  624. bits[i] -= 2;/* remove two symbols */
  625. bits[i - 1]++;/* one goes in this length */
  626. bits[j + 1] += 2;/* two new symbols in this length */
  627. bits[j]--; /* symbol of this length is now a prefix */
  628. }
  629. }
  630. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  631. while ( bits[i] == 0 ) {/* find largest codelength still in use */
  632. i--;
  633. }
  634. bits[i]--;
  635. /* Return final symbol counts (only for lengths 0..16) */
  636. MEMCOPY( htbl->bits, bits, SIZEOF( htbl->bits ) );
  637. /* Return a list of the symbols sorted by code length */
  638. /* It's not real clear to me why we don't need to consider the codelength
  639. * changes made above, but the JPEG spec seems to think this works.
  640. */
  641. p = 0;
  642. for ( i = 1; i <= MAX_CLEN; i++ ) {
  643. for ( j = 0; j <= 255; j++ ) {
  644. if ( codesize[j] == i ) {
  645. htbl->huffval[p] = (UINT8) j;
  646. p++;
  647. }
  648. }
  649. }
  650. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  651. htbl->sent_table = FALSE;
  652. }
  653. /*
  654. * Finish up a statistics-gathering pass and create the new Huffman tables.
  655. */
  656. METHODDEF void
  657. finish_pass_gather( j_compress_ptr cinfo ) {
  658. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  659. int ci, dctbl, actbl;
  660. jpeg_component_info * compptr;
  661. JHUFF_TBL ** htblptr;
  662. boolean did_dc[NUM_HUFF_TBLS];
  663. boolean did_ac[NUM_HUFF_TBLS];
  664. /* It's important not to apply jpeg_gen_optimal_table more than once
  665. * per table, because it clobbers the input frequency counts!
  666. */
  667. MEMZERO( did_dc, SIZEOF( did_dc ) );
  668. MEMZERO( did_ac, SIZEOF( did_ac ) );
  669. for ( ci = 0; ci < cinfo->comps_in_scan; ci++ ) {
  670. compptr = cinfo->cur_comp_info[ci];
  671. dctbl = compptr->dc_tbl_no;
  672. actbl = compptr->ac_tbl_no;
  673. if ( !did_dc[dctbl] ) {
  674. htblptr = &cinfo->dc_huff_tbl_ptrs[dctbl];
  675. if ( *htblptr == NULL ) {
  676. *htblptr = jpeg_alloc_huff_table( (j_common_ptr) cinfo );
  677. }
  678. jpeg_gen_optimal_table( cinfo, *htblptr, entropy->dc_count_ptrs[dctbl] );
  679. did_dc[dctbl] = TRUE;
  680. }
  681. if ( !did_ac[actbl] ) {
  682. htblptr = &cinfo->ac_huff_tbl_ptrs[actbl];
  683. if ( *htblptr == NULL ) {
  684. *htblptr = jpeg_alloc_huff_table( (j_common_ptr) cinfo );
  685. }
  686. jpeg_gen_optimal_table( cinfo, *htblptr, entropy->ac_count_ptrs[actbl] );
  687. did_ac[actbl] = TRUE;
  688. }
  689. }
  690. }
  691. #endif /* ENTROPY_OPT_SUPPORTED */
  692. /*
  693. * Module initialization routine for Huffman entropy encoding.
  694. */
  695. GLOBAL void
  696. jinit_huff_encoder( j_compress_ptr cinfo ) {
  697. huff_entropy_ptr entropy;
  698. int i;
  699. entropy = (huff_entropy_ptr)
  700. ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE,
  701. SIZEOF( huff_entropy_encoder ) );
  702. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  703. entropy->pub.start_pass = start_pass_huff;
  704. /* Mark tables unallocated */
  705. for ( i = 0; i < NUM_HUFF_TBLS; i++ ) {
  706. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  707. #ifdef ENTROPY_OPT_SUPPORTED
  708. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  709. #endif
  710. }
  711. }