jcarith.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. /*
  2. * jcarith.c
  3. *
  4. * Developed 1997-2009 by Guido Vollbeding.
  5. * This file is part of the Independent JPEG Group's software.
  6. * For conditions of distribution and use, see the accompanying README file.
  7. *
  8. * This file contains portable arithmetic entropy encoding routines for JPEG
  9. * (implementing the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81).
  10. *
  11. * Both sequential and progressive modes are supported in this single module.
  12. *
  13. * Suspension is not currently supported in this module.
  14. */
  15. #define JPEG_INTERNALS
  16. #include "jinclude.h"
  17. #include "jpeglib.h"
  18. /* Expanded entropy encoder object for arithmetic encoding. */
  19. typedef struct {
  20. struct jpeg_entropy_encoder pub; /* public fields */
  21. INT32 c; /* C register, base of coding interval, layout as in sec. D.1.3 */
  22. INT32 a; /* A register, normalized size of coding interval */
  23. INT32 sc; /* counter for stacked 0xFF values which might overflow */
  24. INT32 zc; /* counter for pending 0x00 output values which might *
  25. * be discarded at the end ("Pacman" termination) */
  26. int ct; /* bit shift counter, determines when next byte will be written */
  27. int buffer; /* buffer for most recent output byte != 0xFF */
  28. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  29. int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */
  30. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  31. int next_restart_num; /* next restart number to write (0-7) */
  32. /* Pointers to statistics areas (these workspaces have image lifespan) */
  33. unsigned char * dc_stats[NUM_ARITH_TBLS];
  34. unsigned char * ac_stats[NUM_ARITH_TBLS];
  35. /* Statistics bin for coding with fixed probability 0.5 */
  36. unsigned char fixed_bin[4];
  37. } arith_entropy_encoder;
  38. typedef arith_entropy_encoder * arith_entropy_ptr;
  39. /* The following two definitions specify the allocation chunk size
  40. * for the statistics area.
  41. * According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least
  42. * 49 statistics bins for DC, and 245 statistics bins for AC coding.
  43. *
  44. * We use a compact representation with 1 byte per statistics bin,
  45. * thus the numbers directly represent byte sizes.
  46. * This 1 byte per statistics bin contains the meaning of the MPS
  47. * (more probable symbol) in the highest bit (mask 0x80), and the
  48. * index into the probability estimation state machine table
  49. * in the lower bits (mask 0x7F).
  50. */
  51. #define DC_STAT_BINS 64
  52. #define AC_STAT_BINS 256
  53. /* NOTE: Uncomment the following #define if you want to use the
  54. * given formula for calculating the AC conditioning parameter Kx
  55. * for spectral selection progressive coding in section G.1.3.2
  56. * of the spec (Kx = Kmin + SRL (8 + Se - Kmin) 4).
  57. * Although the spec and P&M authors claim that this "has proven
  58. * to give good results for 8 bit precision samples", I'm not
  59. * convinced yet that this is really beneficial.
  60. * Early tests gave only very marginal compression enhancements
  61. * (a few - around 5 or so - bytes even for very large files),
  62. * which would turn out rather negative if we'd suppress the
  63. * DAC (Define Arithmetic Conditioning) marker segments for
  64. * the default parameters in the future.
  65. * Note that currently the marker writing module emits 12-byte
  66. * DAC segments for a full-component scan in a color image.
  67. * This is not worth worrying about IMHO. However, since the
  68. * spec defines the default values to be used if the tables
  69. * are omitted (unlike Huffman tables, which are required
  70. * anyway), one might optimize this behaviour in the future,
  71. * and then it would be disadvantageous to use custom tables if
  72. * they don't provide sufficient gain to exceed the DAC size.
  73. *
  74. * On the other hand, I'd consider it as a reasonable result
  75. * that the conditioning has no significant influence on the
  76. * compression performance. This means that the basic
  77. * statistical model is already rather stable.
  78. *
  79. * Thus, at the moment, we use the default conditioning values
  80. * anyway, and do not use the custom formula.
  81. *
  82. #define CALCULATE_SPECTRAL_CONDITIONING
  83. */
  84. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  85. * We assume that int right shift is unsigned if INT32 right shift is,
  86. * which should be safe.
  87. */
  88. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  89. #define ISHIFT_TEMPS int ishift_temp;
  90. #define IRIGHT_SHIFT(x,shft) \
  91. ((ishift_temp = (x)) < 0 ? \
  92. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  93. (ishift_temp >> (shft)))
  94. #else
  95. #define ISHIFT_TEMPS
  96. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  97. #endif
  98. LOCAL(void)
  99. emit_byte (int val, j_compress_ptr cinfo)
  100. /* Write next output byte; we do not support suspension in this module. */
  101. {
  102. struct jpeg_destination_mgr * dest = cinfo->dest;
  103. *dest->next_output_byte++ = (JOCTET) val;
  104. if (--dest->free_in_buffer == 0)
  105. if (! (*dest->empty_output_buffer) (cinfo))
  106. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  107. }
  108. /*
  109. * Finish up at the end of an arithmetic-compressed scan.
  110. */
  111. METHODDEF(void)
  112. finish_pass (j_compress_ptr cinfo)
  113. {
  114. arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
  115. INT32 temp;
  116. /* Section D.1.8: Termination of encoding */
  117. /* Find the e->c in the coding interval with the largest
  118. * number of trailing zero bits */
  119. if ((temp = (e->a - 1 + e->c) & 0xFFFF0000L) < e->c)
  120. e->c = temp + 0x8000L;
  121. else
  122. e->c = temp;
  123. /* Send remaining bytes to output */
  124. e->c <<= e->ct;
  125. if (e->c & 0xF8000000L) {
  126. /* One final overflow has to be handled */
  127. if (e->buffer >= 0) {
  128. if (e->zc)
  129. do emit_byte(0x00, cinfo);
  130. while (--e->zc);
  131. emit_byte(e->buffer + 1, cinfo);
  132. if (e->buffer + 1 == 0xFF)
  133. emit_byte(0x00, cinfo);
  134. }
  135. e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */
  136. e->sc = 0;
  137. } else {
  138. if (e->buffer == 0)
  139. ++e->zc;
  140. else if (e->buffer >= 0) {
  141. if (e->zc)
  142. do emit_byte(0x00, cinfo);
  143. while (--e->zc);
  144. emit_byte(e->buffer, cinfo);
  145. }
  146. if (e->sc) {
  147. if (e->zc)
  148. do emit_byte(0x00, cinfo);
  149. while (--e->zc);
  150. do {
  151. emit_byte(0xFF, cinfo);
  152. emit_byte(0x00, cinfo);
  153. } while (--e->sc);
  154. }
  155. }
  156. /* Output final bytes only if they are not 0x00 */
  157. if (e->c & 0x7FFF800L) {
  158. if (e->zc) /* output final pending zero bytes */
  159. do emit_byte(0x00, cinfo);
  160. while (--e->zc);
  161. emit_byte((e->c >> 19) & 0xFF, cinfo);
  162. if (((e->c >> 19) & 0xFF) == 0xFF)
  163. emit_byte(0x00, cinfo);
  164. if (e->c & 0x7F800L) {
  165. emit_byte((e->c >> 11) & 0xFF, cinfo);
  166. if (((e->c >> 11) & 0xFF) == 0xFF)
  167. emit_byte(0x00, cinfo);
  168. }
  169. }
  170. }
  171. /*
  172. * The core arithmetic encoding routine (common in JPEG and JBIG).
  173. * This needs to go as fast as possible.
  174. * Machine-dependent optimization facilities
  175. * are not utilized in this portable implementation.
  176. * However, this code should be fairly efficient and
  177. * may be a good base for further optimizations anyway.
  178. *
  179. * Parameter 'val' to be encoded may be 0 or 1 (binary decision).
  180. *
  181. * Note: I've added full "Pacman" termination support to the
  182. * byte output routines, which is equivalent to the optional
  183. * Discard_final_zeros procedure (Figure D.15) in the spec.
  184. * Thus, we always produce the shortest possible output
  185. * stream compliant to the spec (no trailing zero bytes,
  186. * except for FF stuffing).
  187. *
  188. * I've also introduced a new scheme for accessing
  189. * the probability estimation state machine table,
  190. * derived from Markus Kuhn's JBIG implementation.
  191. */
  192. LOCAL(void)
  193. arith_encode (j_compress_ptr cinfo, unsigned char *st, int val)
  194. {
  195. register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
  196. register unsigned char nl, nm;
  197. register INT32 qe, temp;
  198. register int sv;
  199. /* Fetch values from our compact representation of Table D.2:
  200. * Qe values and probability estimation state machine
  201. */
  202. sv = *st;
  203. qe = jpeg_aritab[sv & 0x7F]; /* => Qe_Value */
  204. nl = qe & 0xFF; qe >>= 8; /* Next_Index_LPS + Switch_MPS */
  205. nm = qe & 0xFF; qe >>= 8; /* Next_Index_MPS */
  206. /* Encode & estimation procedures per sections D.1.4 & D.1.5 */
  207. e->a -= qe;
  208. if (val != (sv >> 7)) {
  209. /* Encode the less probable symbol */
  210. if (e->a >= qe) {
  211. /* If the interval size (qe) for the less probable symbol (LPS)
  212. * is larger than the interval size for the MPS, then exchange
  213. * the two symbols for coding efficiency, otherwise code the LPS
  214. * as usual: */
  215. e->c += e->a;
  216. e->a = qe;
  217. }
  218. *st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */
  219. } else {
  220. /* Encode the more probable symbol */
  221. if (e->a >= 0x8000L)
  222. return; /* A >= 0x8000 -> ready, no renormalization required */
  223. if (e->a < qe) {
  224. /* If the interval size (qe) for the less probable symbol (LPS)
  225. * is larger than the interval size for the MPS, then exchange
  226. * the two symbols for coding efficiency: */
  227. e->c += e->a;
  228. e->a = qe;
  229. }
  230. *st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */
  231. }
  232. /* Renormalization & data output per section D.1.6 */
  233. do {
  234. e->a <<= 1;
  235. e->c <<= 1;
  236. if (--e->ct == 0) {
  237. /* Another byte is ready for output */
  238. temp = e->c >> 19;
  239. if (temp > 0xFF) {
  240. /* Handle overflow over all stacked 0xFF bytes */
  241. if (e->buffer >= 0) {
  242. if (e->zc)
  243. do emit_byte(0x00, cinfo);
  244. while (--e->zc);
  245. emit_byte(e->buffer + 1, cinfo);
  246. if (e->buffer + 1 == 0xFF)
  247. emit_byte(0x00, cinfo);
  248. }
  249. e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */
  250. e->sc = 0;
  251. /* Note: The 3 spacer bits in the C register guarantee
  252. * that the new buffer byte can't be 0xFF here
  253. * (see page 160 in the P&M JPEG book). */
  254. e->buffer = temp & 0xFF; /* new output byte, might overflow later */
  255. } else if (temp == 0xFF) {
  256. ++e->sc; /* stack 0xFF byte (which might overflow later) */
  257. } else {
  258. /* Output all stacked 0xFF bytes, they will not overflow any more */
  259. if (e->buffer == 0)
  260. ++e->zc;
  261. else if (e->buffer >= 0) {
  262. if (e->zc)
  263. do emit_byte(0x00, cinfo);
  264. while (--e->zc);
  265. emit_byte(e->buffer, cinfo);
  266. }
  267. if (e->sc) {
  268. if (e->zc)
  269. do emit_byte(0x00, cinfo);
  270. while (--e->zc);
  271. do {
  272. emit_byte(0xFF, cinfo);
  273. emit_byte(0x00, cinfo);
  274. } while (--e->sc);
  275. }
  276. e->buffer = temp & 0xFF; /* new output byte (can still overflow) */
  277. }
  278. e->c &= 0x7FFFFL;
  279. e->ct += 8;
  280. }
  281. } while (e->a < 0x8000L);
  282. }
  283. /*
  284. * Emit a restart marker & resynchronize predictions.
  285. */
  286. LOCAL(void)
  287. emit_restart (j_compress_ptr cinfo, int restart_num)
  288. {
  289. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  290. int ci;
  291. jpeg_component_info * compptr;
  292. finish_pass(cinfo);
  293. emit_byte(0xFF, cinfo);
  294. emit_byte(JPEG_RST0 + restart_num, cinfo);
  295. /* Re-initialize statistics areas */
  296. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  297. compptr = cinfo->cur_comp_info[ci];
  298. /* DC needs no table for refinement scan */
  299. if (cinfo->progressive_mode == 0 || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
  300. MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS);
  301. /* Reset DC predictions to 0 */
  302. entropy->last_dc_val[ci] = 0;
  303. entropy->dc_context[ci] = 0;
  304. }
  305. /* AC needs no table when not present */
  306. if (cinfo->progressive_mode == 0 || cinfo->Se) {
  307. MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS);
  308. }
  309. }
  310. /* Reset arithmetic encoding variables */
  311. entropy->c = 0;
  312. entropy->a = 0x10000L;
  313. entropy->sc = 0;
  314. entropy->zc = 0;
  315. entropy->ct = 11;
  316. entropy->buffer = -1; /* empty */
  317. }
  318. /*
  319. * MCU encoding for DC initial scan (either spectral selection,
  320. * or first pass of successive approximation).
  321. */
  322. METHODDEF(boolean)
  323. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  324. {
  325. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  326. JBLOCKROW block;
  327. unsigned char *st;
  328. int blkn, ci, tbl;
  329. int v, v2, m;
  330. ISHIFT_TEMPS
  331. /* Emit restart marker if needed */
  332. if (cinfo->restart_interval) {
  333. if (entropy->restarts_to_go == 0) {
  334. emit_restart(cinfo, entropy->next_restart_num);
  335. entropy->restarts_to_go = cinfo->restart_interval;
  336. entropy->next_restart_num++;
  337. entropy->next_restart_num &= 7;
  338. }
  339. entropy->restarts_to_go--;
  340. }
  341. /* Encode the MCU data blocks */
  342. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  343. block = MCU_data[blkn];
  344. ci = cinfo->MCU_membership[blkn];
  345. tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
  346. /* Compute the DC value after the required point transform by Al.
  347. * This is simply an arithmetic right shift.
  348. */
  349. m = IRIGHT_SHIFT((int) ((*block)[0]), cinfo->Al);
  350. /* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */
  351. /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
  352. st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
  353. /* Figure F.4: Encode_DC_DIFF */
  354. if ((v = m - entropy->last_dc_val[ci]) == 0) {
  355. arith_encode(cinfo, st, 0);
  356. entropy->dc_context[ci] = 0; /* zero diff category */
  357. } else {
  358. entropy->last_dc_val[ci] = m;
  359. arith_encode(cinfo, st, 1);
  360. /* Figure F.6: Encoding nonzero value v */
  361. /* Figure F.7: Encoding the sign of v */
  362. if (v > 0) {
  363. arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
  364. st += 2; /* Table F.4: SP = S0 + 2 */
  365. entropy->dc_context[ci] = 4; /* small positive diff category */
  366. } else {
  367. v = -v;
  368. arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
  369. st += 3; /* Table F.4: SN = S0 + 3 */
  370. entropy->dc_context[ci] = 8; /* small negative diff category */
  371. }
  372. /* Figure F.8: Encoding the magnitude category of v */
  373. m = 0;
  374. if (v -= 1) {
  375. arith_encode(cinfo, st, 1);
  376. m = 1;
  377. v2 = v;
  378. st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
  379. while (v2 >>= 1) {
  380. arith_encode(cinfo, st, 1);
  381. m <<= 1;
  382. st += 1;
  383. }
  384. }
  385. arith_encode(cinfo, st, 0);
  386. /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
  387. if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
  388. entropy->dc_context[ci] = 0; /* zero diff category */
  389. else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
  390. entropy->dc_context[ci] += 8; /* large diff category */
  391. /* Figure F.9: Encoding the magnitude bit pattern of v */
  392. st += 14;
  393. while (m >>= 1)
  394. arith_encode(cinfo, st, (m & v) ? 1 : 0);
  395. }
  396. }
  397. return TRUE;
  398. }
  399. /*
  400. * MCU encoding for AC initial scan (either spectral selection,
  401. * or first pass of successive approximation).
  402. */
  403. METHODDEF(boolean)
  404. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  405. {
  406. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  407. JBLOCKROW block;
  408. unsigned char *st;
  409. int tbl, k, ke;
  410. int v, v2, m;
  411. /* Emit restart marker if needed */
  412. if (cinfo->restart_interval) {
  413. if (entropy->restarts_to_go == 0) {
  414. emit_restart(cinfo, entropy->next_restart_num);
  415. entropy->restarts_to_go = cinfo->restart_interval;
  416. entropy->next_restart_num++;
  417. entropy->next_restart_num &= 7;
  418. }
  419. entropy->restarts_to_go--;
  420. }
  421. /* Encode the MCU data block */
  422. block = MCU_data[0];
  423. tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
  424. /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
  425. /* Establish EOB (end-of-block) index */
  426. for (ke = cinfo->Se; ke > 0; ke--)
  427. /* We must apply the point transform by Al. For AC coefficients this
  428. * is an integer division with rounding towards 0. To do this portably
  429. * in C, we shift after obtaining the absolute value.
  430. */
  431. if ((v = (*block)[jpeg_natural_order[ke]]) >= 0) {
  432. if (v >>= cinfo->Al) break;
  433. } else {
  434. v = -v;
  435. if (v >>= cinfo->Al) break;
  436. }
  437. /* Figure F.5: Encode_AC_Coefficients */
  438. for (k = cinfo->Ss; k <= ke; k++) {
  439. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  440. arith_encode(cinfo, st, 0); /* EOB decision */
  441. for (;;) {
  442. if ((v = (*block)[jpeg_natural_order[k]]) >= 0) {
  443. if (v >>= cinfo->Al) {
  444. arith_encode(cinfo, st + 1, 1);
  445. arith_encode(cinfo, entropy->fixed_bin, 0);
  446. break;
  447. }
  448. } else {
  449. v = -v;
  450. if (v >>= cinfo->Al) {
  451. arith_encode(cinfo, st + 1, 1);
  452. arith_encode(cinfo, entropy->fixed_bin, 1);
  453. break;
  454. }
  455. }
  456. arith_encode(cinfo, st + 1, 0); st += 3; k++;
  457. }
  458. st += 2;
  459. /* Figure F.8: Encoding the magnitude category of v */
  460. m = 0;
  461. if (v -= 1) {
  462. arith_encode(cinfo, st, 1);
  463. m = 1;
  464. v2 = v;
  465. if (v2 >>= 1) {
  466. arith_encode(cinfo, st, 1);
  467. m <<= 1;
  468. st = entropy->ac_stats[tbl] +
  469. (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
  470. while (v2 >>= 1) {
  471. arith_encode(cinfo, st, 1);
  472. m <<= 1;
  473. st += 1;
  474. }
  475. }
  476. }
  477. arith_encode(cinfo, st, 0);
  478. /* Figure F.9: Encoding the magnitude bit pattern of v */
  479. st += 14;
  480. while (m >>= 1)
  481. arith_encode(cinfo, st, (m & v) ? 1 : 0);
  482. }
  483. /* Encode EOB decision only if k <= cinfo->Se */
  484. if (k <= cinfo->Se) {
  485. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  486. arith_encode(cinfo, st, 1);
  487. }
  488. return TRUE;
  489. }
  490. /*
  491. * MCU encoding for DC successive approximation refinement scan.
  492. */
  493. METHODDEF(boolean)
  494. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  495. {
  496. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  497. unsigned char *st;
  498. int Al, blkn;
  499. /* Emit restart marker if needed */
  500. if (cinfo->restart_interval) {
  501. if (entropy->restarts_to_go == 0) {
  502. emit_restart(cinfo, entropy->next_restart_num);
  503. entropy->restarts_to_go = cinfo->restart_interval;
  504. entropy->next_restart_num++;
  505. entropy->next_restart_num &= 7;
  506. }
  507. entropy->restarts_to_go--;
  508. }
  509. st = entropy->fixed_bin; /* use fixed probability estimation */
  510. Al = cinfo->Al;
  511. /* Encode the MCU data blocks */
  512. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  513. /* We simply emit the Al'th bit of the DC coefficient value. */
  514. arith_encode(cinfo, st, (MCU_data[blkn][0][0] >> Al) & 1);
  515. }
  516. return TRUE;
  517. }
  518. /*
  519. * MCU encoding for AC successive approximation refinement scan.
  520. */
  521. METHODDEF(boolean)
  522. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  523. {
  524. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  525. JBLOCKROW block;
  526. unsigned char *st;
  527. int tbl, k, ke, kex;
  528. int v;
  529. /* Emit restart marker if needed */
  530. if (cinfo->restart_interval) {
  531. if (entropy->restarts_to_go == 0) {
  532. emit_restart(cinfo, entropy->next_restart_num);
  533. entropy->restarts_to_go = cinfo->restart_interval;
  534. entropy->next_restart_num++;
  535. entropy->next_restart_num &= 7;
  536. }
  537. entropy->restarts_to_go--;
  538. }
  539. /* Encode the MCU data block */
  540. block = MCU_data[0];
  541. tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
  542. /* Section G.1.3.3: Encoding of AC coefficients */
  543. /* Establish EOB (end-of-block) index */
  544. for (ke = cinfo->Se; ke > 0; ke--)
  545. /* We must apply the point transform by Al. For AC coefficients this
  546. * is an integer division with rounding towards 0. To do this portably
  547. * in C, we shift after obtaining the absolute value.
  548. */
  549. if ((v = (*block)[jpeg_natural_order[ke]]) >= 0) {
  550. if (v >>= cinfo->Al) break;
  551. } else {
  552. v = -v;
  553. if (v >>= cinfo->Al) break;
  554. }
  555. /* Establish EOBx (previous stage end-of-block) index */
  556. for (kex = ke; kex > 0; kex--)
  557. if ((v = (*block)[jpeg_natural_order[kex]]) >= 0) {
  558. if (v >>= cinfo->Ah) break;
  559. } else {
  560. v = -v;
  561. if (v >>= cinfo->Ah) break;
  562. }
  563. /* Figure G.10: Encode_AC_Coefficients_SA */
  564. for (k = cinfo->Ss; k <= ke; k++) {
  565. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  566. if (k > kex)
  567. arith_encode(cinfo, st, 0); /* EOB decision */
  568. for (;;) {
  569. if ((v = (*block)[jpeg_natural_order[k]]) >= 0) {
  570. if (v >>= cinfo->Al) {
  571. if (v >> 1) /* previously nonzero coef */
  572. arith_encode(cinfo, st + 2, (v & 1));
  573. else { /* newly nonzero coef */
  574. arith_encode(cinfo, st + 1, 1);
  575. arith_encode(cinfo, entropy->fixed_bin, 0);
  576. }
  577. break;
  578. }
  579. } else {
  580. v = -v;
  581. if (v >>= cinfo->Al) {
  582. if (v >> 1) /* previously nonzero coef */
  583. arith_encode(cinfo, st + 2, (v & 1));
  584. else { /* newly nonzero coef */
  585. arith_encode(cinfo, st + 1, 1);
  586. arith_encode(cinfo, entropy->fixed_bin, 1);
  587. }
  588. break;
  589. }
  590. }
  591. arith_encode(cinfo, st + 1, 0); st += 3; k++;
  592. }
  593. }
  594. /* Encode EOB decision only if k <= cinfo->Se */
  595. if (k <= cinfo->Se) {
  596. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  597. arith_encode(cinfo, st, 1);
  598. }
  599. return TRUE;
  600. }
  601. /*
  602. * Encode and output one MCU's worth of arithmetic-compressed coefficients.
  603. */
  604. METHODDEF(boolean)
  605. encode_mcu (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  606. {
  607. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  608. jpeg_component_info * compptr;
  609. JBLOCKROW block;
  610. unsigned char *st;
  611. int blkn, ci, tbl, k, ke;
  612. int v, v2, m;
  613. /* Emit restart marker if needed */
  614. if (cinfo->restart_interval) {
  615. if (entropy->restarts_to_go == 0) {
  616. emit_restart(cinfo, entropy->next_restart_num);
  617. entropy->restarts_to_go = cinfo->restart_interval;
  618. entropy->next_restart_num++;
  619. entropy->next_restart_num &= 7;
  620. }
  621. entropy->restarts_to_go--;
  622. }
  623. /* Encode the MCU data blocks */
  624. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  625. block = MCU_data[blkn];
  626. ci = cinfo->MCU_membership[blkn];
  627. compptr = cinfo->cur_comp_info[ci];
  628. /* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */
  629. tbl = compptr->dc_tbl_no;
  630. /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
  631. st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
  632. /* Figure F.4: Encode_DC_DIFF */
  633. if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) {
  634. arith_encode(cinfo, st, 0);
  635. entropy->dc_context[ci] = 0; /* zero diff category */
  636. } else {
  637. entropy->last_dc_val[ci] = (*block)[0];
  638. arith_encode(cinfo, st, 1);
  639. /* Figure F.6: Encoding nonzero value v */
  640. /* Figure F.7: Encoding the sign of v */
  641. if (v > 0) {
  642. arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
  643. st += 2; /* Table F.4: SP = S0 + 2 */
  644. entropy->dc_context[ci] = 4; /* small positive diff category */
  645. } else {
  646. v = -v;
  647. arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
  648. st += 3; /* Table F.4: SN = S0 + 3 */
  649. entropy->dc_context[ci] = 8; /* small negative diff category */
  650. }
  651. /* Figure F.8: Encoding the magnitude category of v */
  652. m = 0;
  653. if (v -= 1) {
  654. arith_encode(cinfo, st, 1);
  655. m = 1;
  656. v2 = v;
  657. st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
  658. while (v2 >>= 1) {
  659. arith_encode(cinfo, st, 1);
  660. m <<= 1;
  661. st += 1;
  662. }
  663. }
  664. arith_encode(cinfo, st, 0);
  665. /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
  666. if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
  667. entropy->dc_context[ci] = 0; /* zero diff category */
  668. else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
  669. entropy->dc_context[ci] += 8; /* large diff category */
  670. /* Figure F.9: Encoding the magnitude bit pattern of v */
  671. st += 14;
  672. while (m >>= 1)
  673. arith_encode(cinfo, st, (m & v) ? 1 : 0);
  674. }
  675. /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
  676. tbl = compptr->ac_tbl_no;
  677. /* Establish EOB (end-of-block) index */
  678. for (ke = DCTSIZE2 - 1; ke > 0; ke--)
  679. if ((*block)[jpeg_natural_order[ke]]) break;
  680. /* Figure F.5: Encode_AC_Coefficients */
  681. for (k = 1; k <= ke; k++) {
  682. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  683. arith_encode(cinfo, st, 0); /* EOB decision */
  684. while ((v = (*block)[jpeg_natural_order[k]]) == 0) {
  685. arith_encode(cinfo, st + 1, 0); st += 3; k++;
  686. }
  687. arith_encode(cinfo, st + 1, 1);
  688. /* Figure F.6: Encoding nonzero value v */
  689. /* Figure F.7: Encoding the sign of v */
  690. if (v > 0) {
  691. arith_encode(cinfo, entropy->fixed_bin, 0);
  692. } else {
  693. v = -v;
  694. arith_encode(cinfo, entropy->fixed_bin, 1);
  695. }
  696. st += 2;
  697. /* Figure F.8: Encoding the magnitude category of v */
  698. m = 0;
  699. if (v -= 1) {
  700. arith_encode(cinfo, st, 1);
  701. m = 1;
  702. v2 = v;
  703. if (v2 >>= 1) {
  704. arith_encode(cinfo, st, 1);
  705. m <<= 1;
  706. st = entropy->ac_stats[tbl] +
  707. (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
  708. while (v2 >>= 1) {
  709. arith_encode(cinfo, st, 1);
  710. m <<= 1;
  711. st += 1;
  712. }
  713. }
  714. }
  715. arith_encode(cinfo, st, 0);
  716. /* Figure F.9: Encoding the magnitude bit pattern of v */
  717. st += 14;
  718. while (m >>= 1)
  719. arith_encode(cinfo, st, (m & v) ? 1 : 0);
  720. }
  721. /* Encode EOB decision only if k <= DCTSIZE2 - 1 */
  722. if (k <= DCTSIZE2 - 1) {
  723. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  724. arith_encode(cinfo, st, 1);
  725. }
  726. }
  727. return TRUE;
  728. }
  729. /*
  730. * Initialize for an arithmetic-compressed scan.
  731. */
  732. METHODDEF(void)
  733. start_pass (j_compress_ptr cinfo, boolean gather_statistics)
  734. {
  735. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  736. int ci, tbl;
  737. jpeg_component_info * compptr;
  738. if (gather_statistics)
  739. /* Make sure to avoid that in the master control logic!
  740. * We are fully adaptive here and need no extra
  741. * statistics gathering pass!
  742. */
  743. ERREXIT(cinfo, JERR_NOT_COMPILED);
  744. /* We assume jcmaster.c already validated the progressive scan parameters. */
  745. /* Select execution routines */
  746. if (cinfo->progressive_mode) {
  747. if (cinfo->Ah == 0) {
  748. if (cinfo->Ss == 0)
  749. entropy->pub.encode_mcu = encode_mcu_DC_first;
  750. else
  751. entropy->pub.encode_mcu = encode_mcu_AC_first;
  752. } else {
  753. if (cinfo->Ss == 0)
  754. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  755. else
  756. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  757. }
  758. } else
  759. entropy->pub.encode_mcu = encode_mcu;
  760. /* Allocate & initialize requested statistics areas */
  761. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  762. compptr = cinfo->cur_comp_info[ci];
  763. /* DC needs no table for refinement scan */
  764. if (cinfo->progressive_mode == 0 || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
  765. tbl = compptr->dc_tbl_no;
  766. if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
  767. ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
  768. if (entropy->dc_stats[tbl] == NULL)
  769. entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
  770. ((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);
  771. MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);
  772. /* Initialize DC predictions to 0 */
  773. entropy->last_dc_val[ci] = 0;
  774. entropy->dc_context[ci] = 0;
  775. }
  776. /* AC needs no table when not present */
  777. if (cinfo->progressive_mode == 0 || cinfo->Se) {
  778. tbl = compptr->ac_tbl_no;
  779. if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
  780. ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
  781. if (entropy->ac_stats[tbl] == NULL)
  782. entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
  783. ((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);
  784. MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);
  785. #ifdef CALCULATE_SPECTRAL_CONDITIONING
  786. if (cinfo->progressive_mode)
  787. /* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */
  788. cinfo->arith_ac_K[tbl] = cinfo->Ss + ((8 + cinfo->Se - cinfo->Ss) >> 4);
  789. #endif
  790. }
  791. }
  792. /* Initialize arithmetic encoding variables */
  793. entropy->c = 0;
  794. entropy->a = 0x10000L;
  795. entropy->sc = 0;
  796. entropy->zc = 0;
  797. entropy->ct = 11;
  798. entropy->buffer = -1; /* empty */
  799. /* Initialize restart stuff */
  800. entropy->restarts_to_go = cinfo->restart_interval;
  801. entropy->next_restart_num = 0;
  802. }
  803. /*
  804. * Module initialization routine for arithmetic entropy encoding.
  805. */
  806. GLOBAL(void)
  807. jinit_arith_encoder (j_compress_ptr cinfo)
  808. {
  809. arith_entropy_ptr entropy;
  810. int i;
  811. entropy = (arith_entropy_ptr)
  812. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  813. SIZEOF(arith_entropy_encoder));
  814. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  815. entropy->pub.start_pass = start_pass;
  816. entropy->pub.finish_pass = finish_pass;
  817. /* Mark tables unallocated */
  818. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  819. entropy->dc_stats[i] = NULL;
  820. entropy->ac_stats[i] = NULL;
  821. }
  822. /* Initialize index for fixed probability estimation */
  823. entropy->fixed_bin[0] = 113;
  824. }