jchuff.c 50 KB

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