jchuff.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. /*
  2. * jchuff.c
  3. *
  4. * Copyright (C) 1991-1997, Thomas G. Lane.
  5. * Modified 2006-2009 by Guido Vollbeding.
  6. * This file is part of the Independent JPEG Group's software.
  7. * For conditions of distribution and use, see the accompanying README file.
  8. *
  9. * This file contains Huffman entropy encoding routines.
  10. * Both sequential and progressive modes are supported in this single module.
  11. *
  12. * Much of the complexity here has to do with supporting output suspension.
  13. * If the data destination module demands suspension, we want to be able to
  14. * back up to the start of the current MCU. To do this, we copy state
  15. * variables into local working storage, and update them back to the
  16. * permanent JPEG objects only upon successful completion of an MCU.
  17. *
  18. * We do not support output suspension for the progressive JPEG mode, since
  19. * the library currently does not allow multiple-scan files to be written
  20. * with output suspension.
  21. */
  22. #define JPEG_INTERNALS
  23. #include "jinclude.h"
  24. #include "jpeglib.h"
  25. /* The legal range of a DCT coefficient is
  26. * -1024 .. +1023 for 8-bit data;
  27. * -16384 .. +16383 for 12-bit data.
  28. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  29. */
  30. #if BITS_IN_JSAMPLE == 8
  31. #define MAX_COEF_BITS 10
  32. #else
  33. #define MAX_COEF_BITS 14
  34. #endif
  35. /* Derived data constructed for each Huffman table */
  36. typedef struct {
  37. unsigned int ehufco[256]; /* code for each symbol */
  38. char ehufsi[256]; /* length of code for each symbol */
  39. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  40. } c_derived_tbl;
  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. typedef struct {
  47. INT32 put_buffer; /* current bit-accumulation buffer */
  48. int put_bits; /* # of bits now in it */
  49. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  50. } savable_state;
  51. /* This macro is to work around compilers with missing or broken
  52. * structure assignment. You'll need to fix this code if you have
  53. * such a compiler and you change MAX_COMPS_IN_SCAN.
  54. */
  55. #ifndef NO_STRUCT_ASSIGN
  56. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  57. #else
  58. #if MAX_COMPS_IN_SCAN == 4
  59. #define ASSIGN_STATE(dest,src) \
  60. ((dest).put_buffer = (src).put_buffer, \
  61. (dest).put_bits = (src).put_bits, \
  62. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  63. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  64. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  65. (dest).last_dc_val[3] = (src).last_dc_val[3])
  66. #endif
  67. #endif
  68. typedef struct {
  69. struct jpeg_entropy_encoder pub; /* public fields */
  70. savable_state saved; /* Bit buffer & DC state at start of MCU */
  71. /* These fields are NOT loaded into local working state. */
  72. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  73. int next_restart_num; /* next restart number to write (0-7) */
  74. /* Following four fields used only in sequential mode */
  75. /* Pointers to derived tables (these workspaces have image lifespan) */
  76. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  77. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  78. /* Statistics tables for optimization */
  79. long * dc_count_ptrs[NUM_HUFF_TBLS];
  80. long * ac_count_ptrs[NUM_HUFF_TBLS];
  81. /* Following fields used only in progressive mode */
  82. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  83. boolean gather_statistics;
  84. /* next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  85. */
  86. JOCTET * next_output_byte; /* => next byte to write in buffer */
  87. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  88. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  89. /* Coding status for AC components */
  90. int ac_tbl_no; /* the table number of the single component */
  91. unsigned int EOBRUN; /* run length of EOBs */
  92. unsigned int BE; /* # of buffered correction bits before MCU */
  93. char * bit_buffer; /* buffer for correction bits (1 per char) */
  94. /* packing correction bits tightly would save some space but cost time... */
  95. /* Pointers to derived tables (these workspaces have image lifespan).
  96. * Since any one scan in progressive mode codes only DC or only AC,
  97. * we only need one set of tables, not one for DC and one for AC.
  98. */
  99. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  100. /* Statistics tables for optimization; again, one set is enough */
  101. long * count_ptrs[NUM_HUFF_TBLS];
  102. } huff_entropy_encoder;
  103. typedef huff_entropy_encoder * huff_entropy_ptr;
  104. /* Working state while writing an MCU (sequential mode).
  105. * This struct contains all the fields that are needed by subroutines.
  106. */
  107. typedef struct {
  108. JOCTET * next_output_byte; /* => next byte to write in buffer */
  109. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  110. savable_state cur; /* Current bit buffer & DC state */
  111. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  112. } working_state;
  113. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  114. * buffer can hold. Larger sizes may slightly improve compression, but
  115. * 1000 is already well into the realm of overkill.
  116. * The minimum safe size is 64 bits.
  117. */
  118. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  119. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  120. * We assume that int right shift is unsigned if INT32 right shift is,
  121. * which should be safe.
  122. */
  123. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  124. #define ISHIFT_TEMPS int ishift_temp;
  125. #define IRIGHT_SHIFT(x,shft) \
  126. ((ishift_temp = (x)) < 0 ? \
  127. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  128. (ishift_temp >> (shft)))
  129. #else
  130. #define ISHIFT_TEMPS
  131. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  132. #endif
  133. /*
  134. * Compute the derived values for a Huffman table.
  135. * This routine also performs some validation checks on the table.
  136. */
  137. LOCAL(void)
  138. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  139. c_derived_tbl ** pdtbl)
  140. {
  141. JHUFF_TBL *htbl;
  142. c_derived_tbl *dtbl;
  143. int p, i, l, lastp, si, maxsymbol;
  144. char huffsize[257];
  145. unsigned int huffcode[257];
  146. unsigned int code;
  147. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  148. * paralleling the order of the symbols themselves in htbl->huffval[].
  149. */
  150. /* Find the input Huffman table */
  151. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  152. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  153. htbl =
  154. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  155. if (htbl == NULL)
  156. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  157. /* Allocate a workspace if we haven't already done so. */
  158. if (*pdtbl == NULL)
  159. *pdtbl = (c_derived_tbl *)
  160. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161. SIZEOF(c_derived_tbl));
  162. dtbl = *pdtbl;
  163. /* Figure C.1: make table of Huffman code length for each symbol */
  164. p = 0;
  165. for (l = 1; l <= 16; l++) {
  166. i = (int) htbl->bits[l];
  167. if (i < 0 || p + i > 256) /* protect against table overrun */
  168. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169. while (i--)
  170. huffsize[p++] = (char) l;
  171. }
  172. huffsize[p] = 0;
  173. lastp = p;
  174. /* Figure C.2: generate the codes themselves */
  175. /* We also validate that the counts represent a legal Huffman code tree. */
  176. code = 0;
  177. si = huffsize[0];
  178. p = 0;
  179. while (huffsize[p]) {
  180. while (((int) huffsize[p]) == si) {
  181. huffcode[p++] = code;
  182. code++;
  183. }
  184. /* code is now 1 more than the last code used for codelength si; but
  185. * it must still fit in si bits, since no code is allowed to be all ones.
  186. */
  187. if (((INT32) code) >= (((INT32) 1) << si))
  188. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  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 all codeless symbols to have code length 0;
  195. * this lets us detect duplicate VAL entries here, and later
  196. * allows emit_bits to detect any attempt to emit such symbols.
  197. */
  198. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  199. /* This is also a convenient place to check for out-of-range
  200. * and duplicated VAL entries. We allow 0..255 for AC symbols
  201. * but only 0..15 for DC. (We could constrain them further
  202. * based on data depth and mode, but this seems enough.)
  203. */
  204. maxsymbol = isDC ? 15 : 255;
  205. for (p = 0; p < lastp; p++) {
  206. i = htbl->huffval[p];
  207. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  208. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  209. dtbl->ehufco[i] = huffcode[p];
  210. dtbl->ehufsi[i] = huffsize[p];
  211. }
  212. }
  213. /* Outputting bytes to the file.
  214. * NB: these must be called only when actually outputting,
  215. * that is, entropy->gather_statistics == FALSE.
  216. */
  217. /* Emit a byte, taking 'action' if must suspend. */
  218. #define emit_byte_s(state,val,action) \
  219. { *(state)->next_output_byte++ = (JOCTET) (val); \
  220. if (--(state)->free_in_buffer == 0) \
  221. if (! dump_buffer_s(state)) \
  222. { action; } }
  223. /* Emit a byte */
  224. #define emit_byte_e(entropy,val) \
  225. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  226. if (--(entropy)->free_in_buffer == 0) \
  227. dump_buffer_e(entropy); }
  228. LOCAL(boolean)
  229. dump_buffer_s (working_state * state)
  230. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  231. {
  232. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  233. if (! (*dest->empty_output_buffer) (state->cinfo))
  234. return FALSE;
  235. /* After a successful buffer dump, must reset buffer pointers */
  236. state->next_output_byte = dest->next_output_byte;
  237. state->free_in_buffer = dest->free_in_buffer;
  238. return TRUE;
  239. }
  240. LOCAL(void)
  241. dump_buffer_e (huff_entropy_ptr entropy)
  242. /* Empty the output buffer; we do not support suspension in this case. */
  243. {
  244. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  245. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  246. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  247. /* After a successful buffer dump, must reset buffer pointers */
  248. entropy->next_output_byte = dest->next_output_byte;
  249. entropy->free_in_buffer = dest->free_in_buffer;
  250. }
  251. /* Outputting bits to the file */
  252. /* Only the right 24 bits of put_buffer are used; the valid bits are
  253. * left-justified in this part. At most 16 bits can be passed to emit_bits
  254. * in one call, and we never retain more than 7 bits in put_buffer
  255. * between calls, so 24 bits are sufficient.
  256. */
  257. INLINE
  258. LOCAL(boolean)
  259. emit_bits_s (working_state * state, unsigned int code, int size)
  260. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  261. {
  262. /* This routine is heavily used, so it's worth coding tightly. */
  263. register INT32 put_buffer = (INT32) code;
  264. register int put_bits = state->cur.put_bits;
  265. /* if size is 0, caller used an invalid Huffman table entry */
  266. if (size == 0)
  267. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  268. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  269. put_bits += size; /* new number of bits in buffer */
  270. put_buffer <<= 24 - put_bits; /* align incoming bits */
  271. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  272. while (put_bits >= 8) {
  273. int c = (int) ((put_buffer >> 16) & 0xFF);
  274. emit_byte_s(state, c, return FALSE);
  275. if (c == 0xFF) { /* need to stuff a zero byte? */
  276. emit_byte_s(state, 0, return FALSE);
  277. }
  278. put_buffer <<= 8;
  279. put_bits -= 8;
  280. }
  281. state->cur.put_buffer = put_buffer; /* update state variables */
  282. state->cur.put_bits = put_bits;
  283. return TRUE;
  284. }
  285. INLINE
  286. LOCAL(void)
  287. emit_bits_e (huff_entropy_ptr entropy, unsigned int code, int size)
  288. /* Emit some bits, unless we are in gather mode */
  289. {
  290. /* This routine is heavily used, so it's worth coding tightly. */
  291. register INT32 put_buffer = (INT32) code;
  292. register int put_bits = entropy->saved.put_bits;
  293. /* if size is 0, caller used an invalid Huffman table entry */
  294. if (size == 0)
  295. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  296. if (entropy->gather_statistics)
  297. return; /* do nothing if we're only getting stats */
  298. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  299. put_bits += size; /* new number of bits in buffer */
  300. put_buffer <<= 24 - put_bits; /* align incoming bits */
  301. /* and merge with old buffer contents */
  302. put_buffer |= entropy->saved.put_buffer;
  303. while (put_bits >= 8) {
  304. int c = (int) ((put_buffer >> 16) & 0xFF);
  305. emit_byte_e(entropy, c);
  306. if (c == 0xFF) { /* need to stuff a zero byte? */
  307. emit_byte_e(entropy, 0);
  308. }
  309. put_buffer <<= 8;
  310. put_bits -= 8;
  311. }
  312. entropy->saved.put_buffer = put_buffer; /* update variables */
  313. entropy->saved.put_bits = put_bits;
  314. }
  315. LOCAL(boolean)
  316. flush_bits_s (working_state * state)
  317. {
  318. if (! emit_bits_s(state, 0x7F, 7)) /* fill any partial byte with ones */
  319. return FALSE;
  320. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  321. state->cur.put_bits = 0;
  322. return TRUE;
  323. }
  324. LOCAL(void)
  325. flush_bits_e (huff_entropy_ptr entropy)
  326. {
  327. emit_bits_e(entropy, 0x7F, 7); /* fill any partial byte with ones */
  328. entropy->saved.put_buffer = 0; /* and reset bit-buffer to empty */
  329. entropy->saved.put_bits = 0;
  330. }
  331. /*
  332. * Emit (or just count) a Huffman symbol.
  333. */
  334. INLINE
  335. LOCAL(void)
  336. emit_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
  337. {
  338. if (entropy->gather_statistics)
  339. entropy->count_ptrs[tbl_no][symbol]++;
  340. else {
  341. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  342. emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  343. }
  344. }
  345. /*
  346. * Emit bits from a correction bit buffer.
  347. */
  348. LOCAL(void)
  349. emit_buffered_bits (huff_entropy_ptr entropy, char * bufstart,
  350. unsigned int nbits)
  351. {
  352. if (entropy->gather_statistics)
  353. return; /* no real work */
  354. while (nbits > 0) {
  355. emit_bits_e(entropy, (unsigned int) (*bufstart), 1);
  356. bufstart++;
  357. nbits--;
  358. }
  359. }
  360. /*
  361. * Emit any pending EOBRUN symbol.
  362. */
  363. LOCAL(void)
  364. emit_eobrun (huff_entropy_ptr entropy)
  365. {
  366. register int temp, nbits;
  367. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  368. temp = entropy->EOBRUN;
  369. nbits = 0;
  370. while ((temp >>= 1))
  371. nbits++;
  372. /* safety check: shouldn't happen given limited correction-bit buffer */
  373. if (nbits > 14)
  374. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  375. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  376. if (nbits)
  377. emit_bits_e(entropy, entropy->EOBRUN, nbits);
  378. entropy->EOBRUN = 0;
  379. /* Emit any buffered correction bits */
  380. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  381. entropy->BE = 0;
  382. }
  383. }
  384. /*
  385. * Emit a restart marker & resynchronize predictions.
  386. */
  387. LOCAL(boolean)
  388. emit_restart_s (working_state * state, int restart_num)
  389. {
  390. int ci;
  391. if (! flush_bits_s(state))
  392. return FALSE;
  393. emit_byte_s(state, 0xFF, return FALSE);
  394. emit_byte_s(state, JPEG_RST0 + restart_num, return FALSE);
  395. /* Re-initialize DC predictions to 0 */
  396. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  397. state->cur.last_dc_val[ci] = 0;
  398. /* The restart counter is not updated until we successfully write the MCU. */
  399. return TRUE;
  400. }
  401. LOCAL(void)
  402. emit_restart_e (huff_entropy_ptr entropy, int restart_num)
  403. {
  404. int ci;
  405. emit_eobrun(entropy);
  406. if (! entropy->gather_statistics) {
  407. flush_bits_e(entropy);
  408. emit_byte_e(entropy, 0xFF);
  409. emit_byte_e(entropy, JPEG_RST0 + restart_num);
  410. }
  411. if (entropy->cinfo->Ss == 0) {
  412. /* Re-initialize DC predictions to 0 */
  413. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  414. entropy->saved.last_dc_val[ci] = 0;
  415. } else {
  416. /* Re-initialize all AC-related fields to 0 */
  417. entropy->EOBRUN = 0;
  418. entropy->BE = 0;
  419. }
  420. }
  421. /*
  422. * MCU encoding for DC initial scan (either spectral selection,
  423. * or first pass of successive approximation).
  424. */
  425. METHODDEF(boolean)
  426. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  427. {
  428. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  429. register int temp, temp2;
  430. register int nbits;
  431. int blkn, ci;
  432. int Al = cinfo->Al;
  433. JBLOCKROW block;
  434. jpeg_component_info * compptr;
  435. ISHIFT_TEMPS
  436. entropy->next_output_byte = cinfo->dest->next_output_byte;
  437. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  438. /* Emit restart marker if needed */
  439. if (cinfo->restart_interval)
  440. if (entropy->restarts_to_go == 0)
  441. emit_restart_e(entropy, entropy->next_restart_num);
  442. /* Encode the MCU data blocks */
  443. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  444. block = MCU_data[blkn];
  445. ci = cinfo->MCU_membership[blkn];
  446. compptr = cinfo->cur_comp_info[ci];
  447. /* Compute the DC value after the required point transform by Al.
  448. * This is simply an arithmetic right shift.
  449. */
  450. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  451. /* DC differences are figured on the point-transformed values. */
  452. temp = temp2 - entropy->saved.last_dc_val[ci];
  453. entropy->saved.last_dc_val[ci] = temp2;
  454. /* Encode the DC coefficient difference per section G.1.2.1 */
  455. temp2 = temp;
  456. if (temp < 0) {
  457. temp = -temp; /* temp is abs value of input */
  458. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  459. /* This code assumes we are on a two's complement machine */
  460. temp2--;
  461. }
  462. /* Find the number of bits needed for the magnitude of the coefficient */
  463. nbits = 0;
  464. while (temp) {
  465. nbits++;
  466. temp >>= 1;
  467. }
  468. /* Check for out-of-range coefficient values.
  469. * Since we're encoding a difference, the range limit is twice as much.
  470. */
  471. if (nbits > MAX_COEF_BITS+1)
  472. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  473. /* Count/emit the Huffman-coded symbol for the number of bits */
  474. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  475. /* Emit that number of bits of the value, if positive, */
  476. /* or the complement of its magnitude, if negative. */
  477. if (nbits) /* emit_bits rejects calls with size 0 */
  478. emit_bits_e(entropy, (unsigned int) temp2, nbits);
  479. }
  480. cinfo->dest->next_output_byte = entropy->next_output_byte;
  481. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  482. /* Update restart-interval state too */
  483. if (cinfo->restart_interval) {
  484. if (entropy->restarts_to_go == 0) {
  485. entropy->restarts_to_go = cinfo->restart_interval;
  486. entropy->next_restart_num++;
  487. entropy->next_restart_num &= 7;
  488. }
  489. entropy->restarts_to_go--;
  490. }
  491. return TRUE;
  492. }
  493. /*
  494. * MCU encoding for AC initial scan (either spectral selection,
  495. * or first pass of successive approximation).
  496. */
  497. METHODDEF(boolean)
  498. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  499. {
  500. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  501. register int temp, temp2;
  502. register int nbits;
  503. register int r, k;
  504. int Se = cinfo->Se;
  505. int Al = cinfo->Al;
  506. JBLOCKROW block;
  507. entropy->next_output_byte = cinfo->dest->next_output_byte;
  508. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  509. /* Emit restart marker if needed */
  510. if (cinfo->restart_interval)
  511. if (entropy->restarts_to_go == 0)
  512. emit_restart_e(entropy, entropy->next_restart_num);
  513. /* Encode the MCU data block */
  514. block = MCU_data[0];
  515. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  516. r = 0; /* r = run length of zeros */
  517. for (k = cinfo->Ss; k <= Se; k++) {
  518. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  519. r++;
  520. continue;
  521. }
  522. /* We must apply the point transform by Al. For AC coefficients this
  523. * is an integer division with rounding towards 0. To do this portably
  524. * in C, we shift after obtaining the absolute value; so the code is
  525. * interwoven with finding the abs value (temp) and output bits (temp2).
  526. */
  527. if (temp < 0) {
  528. temp = -temp; /* temp is abs value of input */
  529. temp >>= Al; /* apply the point transform */
  530. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  531. temp2 = ~temp;
  532. } else {
  533. temp >>= Al; /* apply the point transform */
  534. temp2 = temp;
  535. }
  536. /* Watch out for case that nonzero coef is zero after point transform */
  537. if (temp == 0) {
  538. r++;
  539. continue;
  540. }
  541. /* Emit any pending EOBRUN */
  542. if (entropy->EOBRUN > 0)
  543. emit_eobrun(entropy);
  544. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  545. while (r > 15) {
  546. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  547. r -= 16;
  548. }
  549. /* Find the number of bits needed for the magnitude of the coefficient */
  550. nbits = 1; /* there must be at least one 1 bit */
  551. while ((temp >>= 1))
  552. nbits++;
  553. /* Check for out-of-range coefficient values */
  554. if (nbits > MAX_COEF_BITS)
  555. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  556. /* Count/emit Huffman symbol for run length / number of bits */
  557. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  558. /* Emit that number of bits of the value, if positive, */
  559. /* or the complement of its magnitude, if negative. */
  560. emit_bits_e(entropy, (unsigned int) temp2, nbits);
  561. r = 0; /* reset zero run length */
  562. }
  563. if (r > 0) { /* If there are trailing zeroes, */
  564. entropy->EOBRUN++; /* count an EOB */
  565. if (entropy->EOBRUN == 0x7FFF)
  566. emit_eobrun(entropy); /* force it out to avoid overflow */
  567. }
  568. cinfo->dest->next_output_byte = entropy->next_output_byte;
  569. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  570. /* Update restart-interval state too */
  571. if (cinfo->restart_interval) {
  572. if (entropy->restarts_to_go == 0) {
  573. entropy->restarts_to_go = cinfo->restart_interval;
  574. entropy->next_restart_num++;
  575. entropy->next_restart_num &= 7;
  576. }
  577. entropy->restarts_to_go--;
  578. }
  579. return TRUE;
  580. }
  581. /*
  582. * MCU encoding for DC successive approximation refinement scan.
  583. * Note: we assume such scans can be multi-component, although the spec
  584. * is not very clear on the point.
  585. */
  586. METHODDEF(boolean)
  587. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  588. {
  589. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  590. register int temp;
  591. int blkn;
  592. int Al = cinfo->Al;
  593. JBLOCKROW block;
  594. entropy->next_output_byte = cinfo->dest->next_output_byte;
  595. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  596. /* Emit restart marker if needed */
  597. if (cinfo->restart_interval)
  598. if (entropy->restarts_to_go == 0)
  599. emit_restart_e(entropy, entropy->next_restart_num);
  600. /* Encode the MCU data blocks */
  601. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  602. block = MCU_data[blkn];
  603. /* We simply emit the Al'th bit of the DC coefficient value. */
  604. temp = (*block)[0];
  605. emit_bits_e(entropy, (unsigned int) (temp >> Al), 1);
  606. }
  607. cinfo->dest->next_output_byte = entropy->next_output_byte;
  608. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  609. /* Update restart-interval state too */
  610. if (cinfo->restart_interval) {
  611. if (entropy->restarts_to_go == 0) {
  612. entropy->restarts_to_go = cinfo->restart_interval;
  613. entropy->next_restart_num++;
  614. entropy->next_restart_num &= 7;
  615. }
  616. entropy->restarts_to_go--;
  617. }
  618. return TRUE;
  619. }
  620. /*
  621. * MCU encoding for AC successive approximation refinement scan.
  622. */
  623. METHODDEF(boolean)
  624. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  625. {
  626. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  627. register int temp;
  628. register int r, k;
  629. int EOB;
  630. char *BR_buffer;
  631. unsigned int BR;
  632. int Se = cinfo->Se;
  633. int Al = cinfo->Al;
  634. JBLOCKROW block;
  635. int absvalues[DCTSIZE2];
  636. entropy->next_output_byte = cinfo->dest->next_output_byte;
  637. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  638. /* Emit restart marker if needed */
  639. if (cinfo->restart_interval)
  640. if (entropy->restarts_to_go == 0)
  641. emit_restart_e(entropy, entropy->next_restart_num);
  642. /* Encode the MCU data block */
  643. block = MCU_data[0];
  644. /* It is convenient to make a pre-pass to determine the transformed
  645. * coefficients' absolute values and the EOB position.
  646. */
  647. EOB = 0;
  648. for (k = cinfo->Ss; k <= Se; k++) {
  649. temp = (*block)[jpeg_natural_order[k]];
  650. /* We must apply the point transform by Al. For AC coefficients this
  651. * is an integer division with rounding towards 0. To do this portably
  652. * in C, we shift after obtaining the absolute value.
  653. */
  654. if (temp < 0)
  655. temp = -temp; /* temp is abs value of input */
  656. temp >>= Al; /* apply the point transform */
  657. absvalues[k] = temp; /* save abs value for main pass */
  658. if (temp == 1)
  659. EOB = k; /* EOB = index of last newly-nonzero coef */
  660. }
  661. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  662. r = 0; /* r = run length of zeros */
  663. BR = 0; /* BR = count of buffered bits added now */
  664. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  665. for (k = cinfo->Ss; k <= Se; k++) {
  666. if ((temp = absvalues[k]) == 0) {
  667. r++;
  668. continue;
  669. }
  670. /* Emit any required ZRLs, but not if they can be folded into EOB */
  671. while (r > 15 && k <= EOB) {
  672. /* emit any pending EOBRUN and the BE correction bits */
  673. emit_eobrun(entropy);
  674. /* Emit ZRL */
  675. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  676. r -= 16;
  677. /* Emit buffered correction bits that must be associated with ZRL */
  678. emit_buffered_bits(entropy, BR_buffer, BR);
  679. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  680. BR = 0;
  681. }
  682. /* If the coef was previously nonzero, it only needs a correction bit.
  683. * NOTE: a straight translation of the spec's figure G.7 would suggest
  684. * that we also need to test r > 15. But if r > 15, we can only get here
  685. * if k > EOB, which implies that this coefficient is not 1.
  686. */
  687. if (temp > 1) {
  688. /* The correction bit is the next bit of the absolute value. */
  689. BR_buffer[BR++] = (char) (temp & 1);
  690. continue;
  691. }
  692. /* Emit any pending EOBRUN and the BE correction bits */
  693. emit_eobrun(entropy);
  694. /* Count/emit Huffman symbol for run length / number of bits */
  695. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  696. /* Emit output bit for newly-nonzero coef */
  697. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  698. emit_bits_e(entropy, (unsigned int) temp, 1);
  699. /* Emit buffered correction bits that must be associated with this code */
  700. emit_buffered_bits(entropy, BR_buffer, BR);
  701. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  702. BR = 0;
  703. r = 0; /* reset zero run length */
  704. }
  705. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  706. entropy->EOBRUN++; /* count an EOB */
  707. entropy->BE += BR; /* concat my correction bits to older ones */
  708. /* We force out the EOB if we risk either:
  709. * 1. overflow of the EOB counter;
  710. * 2. overflow of the correction bit buffer during the next MCU.
  711. */
  712. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  713. emit_eobrun(entropy);
  714. }
  715. cinfo->dest->next_output_byte = entropy->next_output_byte;
  716. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  717. /* Update restart-interval state too */
  718. if (cinfo->restart_interval) {
  719. if (entropy->restarts_to_go == 0) {
  720. entropy->restarts_to_go = cinfo->restart_interval;
  721. entropy->next_restart_num++;
  722. entropy->next_restart_num &= 7;
  723. }
  724. entropy->restarts_to_go--;
  725. }
  726. return TRUE;
  727. }
  728. /* Encode a single block's worth of coefficients */
  729. LOCAL(boolean)
  730. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  731. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  732. {
  733. register int temp, temp2;
  734. register int nbits;
  735. register int k, r, i;
  736. /* Encode the DC coefficient difference per section F.1.2.1 */
  737. temp = temp2 = block[0] - last_dc_val;
  738. if (temp < 0) {
  739. temp = -temp; /* temp is abs value of input */
  740. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  741. /* This code assumes we are on a two's complement machine */
  742. temp2--;
  743. }
  744. /* Find the number of bits needed for the magnitude of the coefficient */
  745. nbits = 0;
  746. while (temp) {
  747. nbits++;
  748. temp >>= 1;
  749. }
  750. /* Check for out-of-range coefficient values.
  751. * Since we're encoding a difference, the range limit is twice as much.
  752. */
  753. if (nbits > MAX_COEF_BITS+1)
  754. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  755. /* Emit the Huffman-coded symbol for the number of bits */
  756. if (! emit_bits_s(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  757. return FALSE;
  758. /* Emit that number of bits of the value, if positive, */
  759. /* or the complement of its magnitude, if negative. */
  760. if (nbits) /* emit_bits rejects calls with size 0 */
  761. if (! emit_bits_s(state, (unsigned int) temp2, nbits))
  762. return FALSE;
  763. /* Encode the AC coefficients per section F.1.2.2 */
  764. r = 0; /* r = run length of zeros */
  765. for (k = 1; k < DCTSIZE2; k++) {
  766. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  767. r++;
  768. } else {
  769. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  770. while (r > 15) {
  771. if (! emit_bits_s(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  772. return FALSE;
  773. r -= 16;
  774. }
  775. temp2 = temp;
  776. if (temp < 0) {
  777. temp = -temp; /* temp is abs value of input */
  778. /* This code assumes we are on a two's complement machine */
  779. temp2--;
  780. }
  781. /* Find the number of bits needed for the magnitude of the coefficient */
  782. nbits = 1; /* there must be at least one 1 bit */
  783. while ((temp >>= 1))
  784. nbits++;
  785. /* Check for out-of-range coefficient values */
  786. if (nbits > MAX_COEF_BITS)
  787. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  788. /* Emit Huffman symbol for run length / number of bits */
  789. i = (r << 4) + nbits;
  790. if (! emit_bits_s(state, actbl->ehufco[i], actbl->ehufsi[i]))
  791. return FALSE;
  792. /* Emit that number of bits of the value, if positive, */
  793. /* or the complement of its magnitude, if negative. */
  794. if (! emit_bits_s(state, (unsigned int) temp2, nbits))
  795. return FALSE;
  796. r = 0;
  797. }
  798. }
  799. /* If the last coef(s) were zero, emit an end-of-block code */
  800. if (r > 0)
  801. if (! emit_bits_s(state, actbl->ehufco[0], actbl->ehufsi[0]))
  802. return FALSE;
  803. return TRUE;
  804. }
  805. /*
  806. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  807. */
  808. METHODDEF(boolean)
  809. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  810. {
  811. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  812. working_state state;
  813. int blkn, ci;
  814. jpeg_component_info * compptr;
  815. /* Load up working state */
  816. state.next_output_byte = cinfo->dest->next_output_byte;
  817. state.free_in_buffer = cinfo->dest->free_in_buffer;
  818. ASSIGN_STATE(state.cur, entropy->saved);
  819. state.cinfo = cinfo;
  820. /* Emit restart marker if needed */
  821. if (cinfo->restart_interval) {
  822. if (entropy->restarts_to_go == 0)
  823. if (! emit_restart_s(&state, entropy->next_restart_num))
  824. return FALSE;
  825. }
  826. /* Encode the MCU data blocks */
  827. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  828. ci = cinfo->MCU_membership[blkn];
  829. compptr = cinfo->cur_comp_info[ci];
  830. if (! encode_one_block(&state,
  831. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  832. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  833. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  834. return FALSE;
  835. /* Update last_dc_val */
  836. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  837. }
  838. /* Completed MCU, so update state */
  839. cinfo->dest->next_output_byte = state.next_output_byte;
  840. cinfo->dest->free_in_buffer = state.free_in_buffer;
  841. ASSIGN_STATE(entropy->saved, state.cur);
  842. /* Update restart-interval state too */
  843. if (cinfo->restart_interval) {
  844. if (entropy->restarts_to_go == 0) {
  845. entropy->restarts_to_go = cinfo->restart_interval;
  846. entropy->next_restart_num++;
  847. entropy->next_restart_num &= 7;
  848. }
  849. entropy->restarts_to_go--;
  850. }
  851. return TRUE;
  852. }
  853. /*
  854. * Finish up at the end of a Huffman-compressed scan.
  855. */
  856. METHODDEF(void)
  857. finish_pass_huff (j_compress_ptr cinfo)
  858. {
  859. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  860. working_state state;
  861. if (cinfo->progressive_mode) {
  862. entropy->next_output_byte = cinfo->dest->next_output_byte;
  863. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  864. /* Flush out any buffered data */
  865. emit_eobrun(entropy);
  866. flush_bits_e(entropy);
  867. cinfo->dest->next_output_byte = entropy->next_output_byte;
  868. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  869. } else {
  870. /* Load up working state ... flush_bits needs it */
  871. state.next_output_byte = cinfo->dest->next_output_byte;
  872. state.free_in_buffer = cinfo->dest->free_in_buffer;
  873. ASSIGN_STATE(state.cur, entropy->saved);
  874. state.cinfo = cinfo;
  875. /* Flush out the last data */
  876. if (! flush_bits_s(&state))
  877. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  878. /* Update state */
  879. cinfo->dest->next_output_byte = state.next_output_byte;
  880. cinfo->dest->free_in_buffer = state.free_in_buffer;
  881. ASSIGN_STATE(entropy->saved, state.cur);
  882. }
  883. }
  884. /*
  885. * Huffman coding optimization.
  886. *
  887. * We first scan the supplied data and count the number of uses of each symbol
  888. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  889. * Then we build a Huffman coding tree for the observed counts.
  890. * Symbols which are not needed at all for the particular image are not
  891. * assigned any code, which saves space in the DHT marker as well as in
  892. * the compressed data.
  893. */
  894. /* Process a single block's worth of coefficients */
  895. LOCAL(void)
  896. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  897. long dc_counts[], long ac_counts[])
  898. {
  899. register int temp;
  900. register int nbits;
  901. register int k, r;
  902. /* Encode the DC coefficient difference per section F.1.2.1 */
  903. temp = block[0] - last_dc_val;
  904. if (temp < 0)
  905. temp = -temp;
  906. /* Find the number of bits needed for the magnitude of the coefficient */
  907. nbits = 0;
  908. while (temp) {
  909. nbits++;
  910. temp >>= 1;
  911. }
  912. /* Check for out-of-range coefficient values.
  913. * Since we're encoding a difference, the range limit is twice as much.
  914. */
  915. if (nbits > MAX_COEF_BITS+1)
  916. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  917. /* Count the Huffman symbol for the number of bits */
  918. dc_counts[nbits]++;
  919. /* Encode the AC coefficients per section F.1.2.2 */
  920. r = 0; /* r = run length of zeros */
  921. for (k = 1; k < DCTSIZE2; k++) {
  922. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  923. r++;
  924. } else {
  925. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  926. while (r > 15) {
  927. ac_counts[0xF0]++;
  928. r -= 16;
  929. }
  930. /* Find the number of bits needed for the magnitude of the coefficient */
  931. if (temp < 0)
  932. temp = -temp;
  933. /* Find the number of bits needed for the magnitude of the coefficient */
  934. nbits = 1; /* there must be at least one 1 bit */
  935. while ((temp >>= 1))
  936. nbits++;
  937. /* Check for out-of-range coefficient values */
  938. if (nbits > MAX_COEF_BITS)
  939. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  940. /* Count Huffman symbol for run length / number of bits */
  941. ac_counts[(r << 4) + nbits]++;
  942. r = 0;
  943. }
  944. }
  945. /* If the last coef(s) were zero, emit an end-of-block code */
  946. if (r > 0)
  947. ac_counts[0]++;
  948. }
  949. /*
  950. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  951. * No data is actually output, so no suspension return is possible.
  952. */
  953. METHODDEF(boolean)
  954. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  955. {
  956. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  957. int blkn, ci;
  958. jpeg_component_info * compptr;
  959. /* Take care of restart intervals if needed */
  960. if (cinfo->restart_interval) {
  961. if (entropy->restarts_to_go == 0) {
  962. /* Re-initialize DC predictions to 0 */
  963. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  964. entropy->saved.last_dc_val[ci] = 0;
  965. /* Update restart state */
  966. entropy->restarts_to_go = cinfo->restart_interval;
  967. }
  968. entropy->restarts_to_go--;
  969. }
  970. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  971. ci = cinfo->MCU_membership[blkn];
  972. compptr = cinfo->cur_comp_info[ci];
  973. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  974. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  975. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  976. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  977. }
  978. return TRUE;
  979. }
  980. /*
  981. * Generate the best Huffman code table for the given counts, fill htbl.
  982. *
  983. * The JPEG standard requires that no symbol be assigned a codeword of all
  984. * one bits (so that padding bits added at the end of a compressed segment
  985. * can't look like a valid code). Because of the canonical ordering of
  986. * codewords, this just means that there must be an unused slot in the
  987. * longest codeword length category. Section K.2 of the JPEG spec suggests
  988. * reserving such a slot by pretending that symbol 256 is a valid symbol
  989. * with count 1. In theory that's not optimal; giving it count zero but
  990. * including it in the symbol set anyway should give a better Huffman code.
  991. * But the theoretically better code actually seems to come out worse in
  992. * practice, because it produces more all-ones bytes (which incur stuffed
  993. * zero bytes in the final file). In any case the difference is tiny.
  994. *
  995. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  996. * If some symbols have a very small but nonzero probability, the Huffman tree
  997. * must be adjusted to meet the code length restriction. We currently use
  998. * the adjustment method suggested in JPEG section K.2. This method is *not*
  999. * optimal; it may not choose the best possible limited-length code. But
  1000. * typically only very-low-frequency symbols will be given less-than-optimal
  1001. * lengths, so the code is almost optimal. Experimental comparisons against
  1002. * an optimal limited-length-code algorithm indicate that the difference is
  1003. * microscopic --- usually less than a hundredth of a percent of total size.
  1004. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  1005. */
  1006. LOCAL(void)
  1007. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  1008. {
  1009. #define MAX_CLEN 32 /* assumed maximum initial code length */
  1010. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  1011. int codesize[257]; /* codesize[k] = code length of symbol k */
  1012. int others[257]; /* next symbol in current branch of tree */
  1013. int c1, c2;
  1014. int p, i, j;
  1015. long v;
  1016. /* This algorithm is explained in section K.2 of the JPEG standard */
  1017. MEMZERO(bits, SIZEOF(bits));
  1018. MEMZERO(codesize, SIZEOF(codesize));
  1019. for (i = 0; i < 257; i++)
  1020. others[i] = -1; /* init links to empty */
  1021. freq[256] = 1; /* make sure 256 has a nonzero count */
  1022. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  1023. * that no real symbol is given code-value of all ones, because 256
  1024. * will be placed last in the largest codeword category.
  1025. */
  1026. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  1027. for (;;) {
  1028. /* Find the smallest nonzero frequency, set c1 = its symbol */
  1029. /* In case of ties, take the larger symbol number */
  1030. c1 = -1;
  1031. v = 1000000000L;
  1032. for (i = 0; i <= 256; i++) {
  1033. if (freq[i] && freq[i] <= v) {
  1034. v = freq[i];
  1035. c1 = i;
  1036. }
  1037. }
  1038. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  1039. /* In case of ties, take the larger symbol number */
  1040. c2 = -1;
  1041. v = 1000000000L;
  1042. for (i = 0; i <= 256; i++) {
  1043. if (freq[i] && freq[i] <= v && i != c1) {
  1044. v = freq[i];
  1045. c2 = i;
  1046. }
  1047. }
  1048. /* Done if we've merged everything into one frequency */
  1049. if (c2 < 0)
  1050. break;
  1051. /* Else merge the two counts/trees */
  1052. freq[c1] += freq[c2];
  1053. freq[c2] = 0;
  1054. /* Increment the codesize of everything in c1's tree branch */
  1055. codesize[c1]++;
  1056. while (others[c1] >= 0) {
  1057. c1 = others[c1];
  1058. codesize[c1]++;
  1059. }
  1060. others[c1] = c2; /* chain c2 onto c1's tree branch */
  1061. /* Increment the codesize of everything in c2's tree branch */
  1062. codesize[c2]++;
  1063. while (others[c2] >= 0) {
  1064. c2 = others[c2];
  1065. codesize[c2]++;
  1066. }
  1067. }
  1068. /* Now count the number of symbols of each code length */
  1069. for (i = 0; i <= 256; i++) {
  1070. if (codesize[i]) {
  1071. /* The JPEG standard seems to think that this can't happen, */
  1072. /* but I'm paranoid... */
  1073. if (codesize[i] > MAX_CLEN)
  1074. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  1075. bits[codesize[i]]++;
  1076. }
  1077. }
  1078. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  1079. * Huffman procedure assigned any such lengths, we must adjust the coding.
  1080. * Here is what the JPEG spec says about how this next bit works:
  1081. * Since symbols are paired for the longest Huffman code, the symbols are
  1082. * removed from this length category two at a time. The prefix for the pair
  1083. * (which is one bit shorter) is allocated to one of the pair; then,
  1084. * skipping the BITS entry for that prefix length, a code word from the next
  1085. * shortest nonzero BITS entry is converted into a prefix for two code words
  1086. * one bit longer.
  1087. */
  1088. for (i = MAX_CLEN; i > 16; i--) {
  1089. while (bits[i] > 0) {
  1090. j = i - 2; /* find length of new prefix to be used */
  1091. while (bits[j] == 0)
  1092. j--;
  1093. bits[i] -= 2; /* remove two symbols */
  1094. bits[i-1]++; /* one goes in this length */
  1095. bits[j+1] += 2; /* two new symbols in this length */
  1096. bits[j]--; /* symbol of this length is now a prefix */
  1097. }
  1098. }
  1099. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  1100. while (bits[i] == 0) /* find largest codelength still in use */
  1101. i--;
  1102. bits[i]--;
  1103. /* Return final symbol counts (only for lengths 0..16) */
  1104. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  1105. /* Return a list of the symbols sorted by code length */
  1106. /* It's not real clear to me why we don't need to consider the codelength
  1107. * changes made above, but the JPEG spec seems to think this works.
  1108. */
  1109. p = 0;
  1110. for (i = 1; i <= MAX_CLEN; i++) {
  1111. for (j = 0; j <= 255; j++) {
  1112. if (codesize[j] == i) {
  1113. htbl->huffval[p] = (UINT8) j;
  1114. p++;
  1115. }
  1116. }
  1117. }
  1118. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  1119. htbl->sent_table = FALSE;
  1120. }
  1121. /*
  1122. * Finish up a statistics-gathering pass and create the new Huffman tables.
  1123. */
  1124. METHODDEF(void)
  1125. finish_pass_gather (j_compress_ptr cinfo)
  1126. {
  1127. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1128. int ci, dctbl, actbl, tbl;
  1129. jpeg_component_info * compptr;
  1130. JHUFF_TBL **htblptr;
  1131. boolean did_dc[NUM_HUFF_TBLS];
  1132. boolean did_ac[NUM_HUFF_TBLS];
  1133. boolean did[NUM_HUFF_TBLS];
  1134. /* It's important not to apply jpeg_gen_optimal_table more than once
  1135. * per table, because it clobbers the input frequency counts!
  1136. */
  1137. if (cinfo->progressive_mode) {
  1138. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  1139. emit_eobrun(entropy);
  1140. MEMZERO(did, SIZEOF(did));
  1141. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1142. compptr = cinfo->cur_comp_info[ci];
  1143. if (cinfo->Ss == 0) {
  1144. if (cinfo->Ah != 0) /* DC refinement needs no table */
  1145. continue;
  1146. tbl = compptr->dc_tbl_no;
  1147. } else {
  1148. tbl = compptr->ac_tbl_no;
  1149. }
  1150. if (! did[tbl]) {
  1151. if (cinfo->Ss == 0)
  1152. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  1153. else
  1154. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  1155. if (*htblptr == NULL)
  1156. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  1157. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  1158. did[tbl] = TRUE;
  1159. }
  1160. }
  1161. } else {
  1162. MEMZERO(did_dc, SIZEOF(did_dc));
  1163. MEMZERO(did_ac, SIZEOF(did_ac));
  1164. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1165. compptr = cinfo->cur_comp_info[ci];
  1166. dctbl = compptr->dc_tbl_no;
  1167. actbl = compptr->ac_tbl_no;
  1168. if (! did_dc[dctbl]) {
  1169. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  1170. if (*htblptr == NULL)
  1171. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  1172. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  1173. did_dc[dctbl] = TRUE;
  1174. }
  1175. if (! did_ac[actbl]) {
  1176. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  1177. if (*htblptr == NULL)
  1178. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  1179. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  1180. did_ac[actbl] = TRUE;
  1181. }
  1182. }
  1183. }
  1184. }
  1185. /*
  1186. * Initialize for a Huffman-compressed scan.
  1187. * If gather_statistics is TRUE, we do not output anything during the scan,
  1188. * just count the Huffman symbols used and generate Huffman code tables.
  1189. */
  1190. METHODDEF(void)
  1191. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  1192. {
  1193. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1194. int ci, dctbl, actbl, tbl;
  1195. jpeg_component_info * compptr;
  1196. if (gather_statistics)
  1197. entropy->pub.finish_pass = finish_pass_gather;
  1198. else
  1199. entropy->pub.finish_pass = finish_pass_huff;
  1200. if (cinfo->progressive_mode) {
  1201. entropy->cinfo = cinfo;
  1202. entropy->gather_statistics = gather_statistics;
  1203. /* We assume jcmaster.c already validated the scan parameters. */
  1204. /* Select execution routine */
  1205. if (cinfo->Ah == 0) {
  1206. if (cinfo->Ss == 0)
  1207. entropy->pub.encode_mcu = encode_mcu_DC_first;
  1208. else
  1209. entropy->pub.encode_mcu = encode_mcu_AC_first;
  1210. } else {
  1211. if (cinfo->Ss == 0)
  1212. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  1213. else {
  1214. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  1215. /* AC refinement needs a correction bit buffer */
  1216. if (entropy->bit_buffer == NULL)
  1217. entropy->bit_buffer = (char *)
  1218. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1219. MAX_CORR_BITS * SIZEOF(char));
  1220. }
  1221. }
  1222. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  1223. * for AC coefficients.
  1224. */
  1225. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1226. compptr = cinfo->cur_comp_info[ci];
  1227. /* Initialize DC predictions to 0 */
  1228. entropy->saved.last_dc_val[ci] = 0;
  1229. /* Get table index */
  1230. if (cinfo->Ss == 0) {
  1231. if (cinfo->Ah != 0) /* DC refinement needs no table */
  1232. continue;
  1233. tbl = compptr->dc_tbl_no;
  1234. } else {
  1235. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  1236. }
  1237. if (gather_statistics) {
  1238. /* Check for invalid table index */
  1239. /* (make_c_derived_tbl does this in the other path) */
  1240. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  1241. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  1242. /* Allocate and zero the statistics tables */
  1243. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  1244. if (entropy->count_ptrs[tbl] == NULL)
  1245. entropy->count_ptrs[tbl] = (long *)
  1246. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1247. 257 * SIZEOF(long));
  1248. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  1249. } else {
  1250. /* Compute derived values for Huffman table */
  1251. /* We may do this more than once for a table, but it's not expensive */
  1252. jpeg_make_c_derived_tbl(cinfo, cinfo->Ss == 0, tbl,
  1253. & entropy->derived_tbls[tbl]);
  1254. }
  1255. }
  1256. /* Initialize AC stuff */
  1257. entropy->EOBRUN = 0;
  1258. entropy->BE = 0;
  1259. } else {
  1260. if (gather_statistics)
  1261. entropy->pub.encode_mcu = encode_mcu_gather;
  1262. else
  1263. entropy->pub.encode_mcu = encode_mcu_huff;
  1264. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1265. compptr = cinfo->cur_comp_info[ci];
  1266. dctbl = compptr->dc_tbl_no;
  1267. actbl = compptr->ac_tbl_no;
  1268. if (gather_statistics) {
  1269. /* Check for invalid table indexes */
  1270. /* (make_c_derived_tbl does this in the other path) */
  1271. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  1272. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  1273. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  1274. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  1275. /* Allocate and zero the statistics tables */
  1276. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  1277. if (entropy->dc_count_ptrs[dctbl] == NULL)
  1278. entropy->dc_count_ptrs[dctbl] = (long *)
  1279. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1280. 257 * SIZEOF(long));
  1281. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  1282. if (entropy->ac_count_ptrs[actbl] == NULL)
  1283. entropy->ac_count_ptrs[actbl] = (long *)
  1284. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1285. 257 * SIZEOF(long));
  1286. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  1287. } else {
  1288. /* Compute derived values for Huffman tables */
  1289. /* We may do this more than once for a table, but it's not expensive */
  1290. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  1291. & entropy->dc_derived_tbls[dctbl]);
  1292. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  1293. & entropy->ac_derived_tbls[actbl]);
  1294. }
  1295. /* Initialize DC predictions to 0 */
  1296. entropy->saved.last_dc_val[ci] = 0;
  1297. }
  1298. }
  1299. /* Initialize bit buffer to empty */
  1300. entropy->saved.put_buffer = 0;
  1301. entropy->saved.put_bits = 0;
  1302. /* Initialize restart stuff */
  1303. entropy->restarts_to_go = cinfo->restart_interval;
  1304. entropy->next_restart_num = 0;
  1305. }
  1306. /*
  1307. * Module initialization routine for Huffman entropy encoding.
  1308. */
  1309. GLOBAL(void)
  1310. jinit_huff_encoder (j_compress_ptr cinfo)
  1311. {
  1312. huff_entropy_ptr entropy;
  1313. int i;
  1314. entropy = (huff_entropy_ptr)
  1315. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1316. SIZEOF(huff_entropy_encoder));
  1317. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  1318. entropy->pub.start_pass = start_pass_huff;
  1319. if (cinfo->progressive_mode) {
  1320. /* Mark tables unallocated */
  1321. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1322. entropy->derived_tbls[i] = NULL;
  1323. entropy->count_ptrs[i] = NULL;
  1324. }
  1325. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  1326. } else {
  1327. /* Mark tables unallocated */
  1328. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1329. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  1330. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  1331. }
  1332. }
  1333. }