jcarith.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. /*
  2. * jcarith.c
  3. *
  4. * Developed 1997 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. } arith_entropy_encoder;
  36. typedef arith_entropy_encoder * arith_entropy_ptr;
  37. /* The following two definitions specify the allocation chunk size
  38. * for the statistics area.
  39. * According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least
  40. * 49 statistics bins for DC, and 245 statistics bins for AC coding.
  41. * Note that we use one additional AC bin for codings with fixed
  42. * probability (0.5), thus the minimum number for AC is 246.
  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. extern const INT32 jaritab[];
  196. register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
  197. register unsigned char nl, nm;
  198. register INT32 qe, temp;
  199. register int sv;
  200. /* Fetch values from our compact representation of Table D.2:
  201. * Qe values and probability estimation state machine
  202. */
  203. sv = *st;
  204. qe = jaritab[sv & 0x7F]; /* => Qe_Value */
  205. nl = qe & 0xFF; qe >>= 8; /* Next_Index_LPS + Switch_MPS */
  206. nm = qe & 0xFF; qe >>= 8; /* Next_Index_MPS */
  207. /* Encode & estimation procedures per sections D.1.4 & D.1.5 */
  208. e->a -= qe;
  209. if (val != (sv >> 7)) {
  210. /* Encode the less probable symbol */
  211. if (e->a >= qe) {
  212. /* If the interval size (qe) for the less probable symbol (LPS)
  213. * is larger than the interval size for the MPS, then exchange
  214. * the two symbols for coding efficiency, otherwise code the LPS
  215. * as usual: */
  216. e->c += e->a;
  217. e->a = qe;
  218. }
  219. *st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */
  220. } else {
  221. /* Encode the more probable symbol */
  222. if (e->a >= 0x8000L)
  223. return; /* A >= 0x8000 -> ready, no renormalization required */
  224. if (e->a < qe) {
  225. /* If the interval size (qe) for the less probable symbol (LPS)
  226. * is larger than the interval size for the MPS, then exchange
  227. * the two symbols for coding efficiency: */
  228. e->c += e->a;
  229. e->a = qe;
  230. }
  231. *st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */
  232. }
  233. /* Renormalization & data output per section D.1.6 */
  234. do {
  235. e->a <<= 1;
  236. e->c <<= 1;
  237. if (--e->ct == 0) {
  238. /* Another byte is ready for output */
  239. temp = e->c >> 19;
  240. if (temp > 0xFF) {
  241. /* Handle overflow over all stacked 0xFF bytes */
  242. if (e->buffer >= 0) {
  243. if (e->zc)
  244. do emit_byte(0x00, cinfo);
  245. while (--e->zc);
  246. emit_byte(e->buffer + 1, cinfo);
  247. if (e->buffer + 1 == 0xFF)
  248. emit_byte(0x00, cinfo);
  249. }
  250. e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */
  251. e->sc = 0;
  252. /* Note: The 3 spacer bits in the C register guarantee
  253. * that the new buffer byte can't be 0xFF here
  254. * (see page 160 in the P&M JPEG book). */
  255. e->buffer = temp & 0xFF; /* new output byte, might overflow later */
  256. } else if (temp == 0xFF) {
  257. ++e->sc; /* stack 0xFF byte (which might overflow later) */
  258. } else {
  259. /* Output all stacked 0xFF bytes, they will not overflow any more */
  260. if (e->buffer == 0)
  261. ++e->zc;
  262. else if (e->buffer >= 0) {
  263. if (e->zc)
  264. do emit_byte(0x00, cinfo);
  265. while (--e->zc);
  266. emit_byte(e->buffer, cinfo);
  267. }
  268. if (e->sc) {
  269. if (e->zc)
  270. do emit_byte(0x00, cinfo);
  271. while (--e->zc);
  272. do {
  273. emit_byte(0xFF, cinfo);
  274. emit_byte(0x00, cinfo);
  275. } while (--e->sc);
  276. }
  277. e->buffer = temp & 0xFF; /* new output byte (can still overflow) */
  278. }
  279. e->c &= 0x7FFFFL;
  280. e->ct += 8;
  281. }
  282. } while (e->a < 0x8000L);
  283. }
  284. /*
  285. * Emit a restart marker & resynchronize predictions.
  286. */
  287. LOCAL(void)
  288. emit_restart (j_compress_ptr cinfo, int restart_num)
  289. {
  290. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  291. int ci;
  292. jpeg_component_info * compptr;
  293. finish_pass(cinfo);
  294. emit_byte(0xFF, cinfo);
  295. emit_byte(JPEG_RST0 + restart_num, cinfo);
  296. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  297. compptr = cinfo->cur_comp_info[ci];
  298. /* Re-initialize statistics areas */
  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. if (cinfo->progressive_mode == 0 || cinfo->Ss) {
  306. MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS);
  307. }
  308. }
  309. /* Reset arithmetic encoding variables */
  310. entropy->c = 0;
  311. entropy->a = 0x10000L;
  312. entropy->sc = 0;
  313. entropy->zc = 0;
  314. entropy->ct = 11;
  315. entropy->buffer = -1; /* empty */
  316. }
  317. /*
  318. * MCU encoding for DC initial scan (either spectral selection,
  319. * or first pass of successive approximation).
  320. */
  321. METHODDEF(boolean)
  322. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  323. {
  324. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  325. JBLOCKROW block;
  326. unsigned char *st;
  327. int blkn, ci, tbl;
  328. int v, v2, m;
  329. ISHIFT_TEMPS
  330. /* Emit restart marker if needed */
  331. if (cinfo->restart_interval) {
  332. if (entropy->restarts_to_go == 0) {
  333. emit_restart(cinfo, entropy->next_restart_num);
  334. entropy->restarts_to_go = cinfo->restart_interval;
  335. entropy->next_restart_num++;
  336. entropy->next_restart_num &= 7;
  337. }
  338. entropy->restarts_to_go--;
  339. }
  340. /* Encode the MCU data blocks */
  341. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  342. block = MCU_data[blkn];
  343. ci = cinfo->MCU_membership[blkn];
  344. tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
  345. /* Compute the DC value after the required point transform by Al.
  346. * This is simply an arithmetic right shift.
  347. */
  348. m = IRIGHT_SHIFT((int) ((*block)[0]), cinfo->Al);
  349. /* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */
  350. /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
  351. st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
  352. /* Figure F.4: Encode_DC_DIFF */
  353. if ((v = m - entropy->last_dc_val[ci]) == 0) {
  354. arith_encode(cinfo, st, 0);
  355. entropy->dc_context[ci] = 0; /* zero diff category */
  356. } else {
  357. entropy->last_dc_val[ci] = m;
  358. arith_encode(cinfo, st, 1);
  359. /* Figure F.6: Encoding nonzero value v */
  360. /* Figure F.7: Encoding the sign of v */
  361. if (v > 0) {
  362. arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
  363. st += 2; /* Table F.4: SP = S0 + 2 */
  364. entropy->dc_context[ci] = 4; /* small positive diff category */
  365. } else {
  366. v = -v;
  367. arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
  368. st += 3; /* Table F.4: SN = S0 + 3 */
  369. entropy->dc_context[ci] = 8; /* small negative diff category */
  370. }
  371. /* Figure F.8: Encoding the magnitude category of v */
  372. m = 0;
  373. if (v -= 1) {
  374. arith_encode(cinfo, st, 1);
  375. m = 1;
  376. v2 = v;
  377. st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
  378. while (v2 >>= 1) {
  379. arith_encode(cinfo, st, 1);
  380. m <<= 1;
  381. st += 1;
  382. }
  383. }
  384. arith_encode(cinfo, st, 0);
  385. /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
  386. if (m < (int) (((INT32) 1 << cinfo->arith_dc_L[tbl]) >> 1))
  387. entropy->dc_context[ci] = 0; /* zero diff category */
  388. else if (m > (int) (((INT32) 1 << cinfo->arith_dc_U[tbl]) >> 1))
  389. entropy->dc_context[ci] += 8; /* large diff category */
  390. /* Figure F.9: Encoding the magnitude bit pattern of v */
  391. st += 14;
  392. while (m >>= 1)
  393. arith_encode(cinfo, st, (m & v) ? 1 : 0);
  394. }
  395. }
  396. return TRUE;
  397. }
  398. /*
  399. * MCU encoding for AC initial scan (either spectral selection,
  400. * or first pass of successive approximation).
  401. */
  402. METHODDEF(boolean)
  403. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  404. {
  405. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  406. JBLOCKROW block;
  407. unsigned char *st;
  408. int tbl, k, ke;
  409. int v, v2, m;
  410. /* Emit restart marker if needed */
  411. if (cinfo->restart_interval) {
  412. if (entropy->restarts_to_go == 0) {
  413. emit_restart(cinfo, entropy->next_restart_num);
  414. entropy->restarts_to_go = cinfo->restart_interval;
  415. entropy->next_restart_num++;
  416. entropy->next_restart_num &= 7;
  417. }
  418. entropy->restarts_to_go--;
  419. }
  420. /* Encode the MCU data block */
  421. block = MCU_data[0];
  422. tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
  423. /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
  424. /* Establish EOB (end-of-block) index */
  425. for (ke = cinfo->Se + 1; ke > 1; ke--)
  426. /* We must apply the point transform by Al. For AC coefficients this
  427. * is an integer division with rounding towards 0. To do this portably
  428. * in C, we shift after obtaining the absolute value.
  429. */
  430. if ((v = (*block)[jpeg_natural_order[ke - 1]]) >= 0) {
  431. if (v >>= cinfo->Al) break;
  432. } else {
  433. v = -v;
  434. if (v >>= cinfo->Al) break;
  435. }
  436. /* Figure F.5: Encode_AC_Coefficients */
  437. for (k = cinfo->Ss; k < ke; k++) {
  438. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  439. arith_encode(cinfo, st, 0); /* EOB decision */
  440. entropy->ac_stats[tbl][245] = 0;
  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->ac_stats[tbl] + 245, 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->ac_stats[tbl] + 245, 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[4];
  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. Al = cinfo->Al;
  510. /* Encode the MCU data blocks */
  511. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  512. st[0] = 0; /* use fixed probability estimation */
  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 + 1; ke > 1; 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 - 1]]) >= 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 > 1; kex--)
  557. if ((v = (*block)[jpeg_natural_order[kex - 1]]) >= 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. entropy->ac_stats[tbl][245] = 0;
  569. for (;;) {
  570. if ((v = (*block)[jpeg_natural_order[k]]) >= 0) {
  571. if (v >>= cinfo->Al) {
  572. if (v >> 1) /* previously nonzero coef */
  573. arith_encode(cinfo, st + 2, (v & 1));
  574. else { /* newly nonzero coef */
  575. arith_encode(cinfo, st + 1, 1);
  576. arith_encode(cinfo, entropy->ac_stats[tbl] + 245, 0);
  577. }
  578. break;
  579. }
  580. } else {
  581. v = -v;
  582. if (v >>= cinfo->Al) {
  583. if (v >> 1) /* previously nonzero coef */
  584. arith_encode(cinfo, st + 2, (v & 1));
  585. else { /* newly nonzero coef */
  586. arith_encode(cinfo, st + 1, 1);
  587. arith_encode(cinfo, entropy->ac_stats[tbl] + 245, 1);
  588. }
  589. break;
  590. }
  591. }
  592. arith_encode(cinfo, st + 1, 0); st += 3; k++;
  593. }
  594. }
  595. /* Encode EOB decision only if k <= cinfo->Se */
  596. if (k <= cinfo->Se) {
  597. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  598. arith_encode(cinfo, st, 1);
  599. }
  600. return TRUE;
  601. }
  602. /*
  603. * Encode and output one MCU's worth of arithmetic-compressed coefficients.
  604. */
  605. METHODDEF(boolean)
  606. encode_mcu (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  607. {
  608. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  609. jpeg_component_info * compptr;
  610. JBLOCKROW block;
  611. unsigned char *st;
  612. int blkn, ci, tbl, k, ke;
  613. int v, v2, m;
  614. /* Emit restart marker if needed */
  615. if (cinfo->restart_interval) {
  616. if (entropy->restarts_to_go == 0) {
  617. emit_restart(cinfo, entropy->next_restart_num);
  618. entropy->restarts_to_go = cinfo->restart_interval;
  619. entropy->next_restart_num++;
  620. entropy->next_restart_num &= 7;
  621. }
  622. entropy->restarts_to_go--;
  623. }
  624. /* Encode the MCU data blocks */
  625. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  626. block = MCU_data[blkn];
  627. ci = cinfo->MCU_membership[blkn];
  628. compptr = cinfo->cur_comp_info[ci];
  629. /* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */
  630. tbl = compptr->dc_tbl_no;
  631. /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
  632. st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
  633. /* Figure F.4: Encode_DC_DIFF */
  634. if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) {
  635. arith_encode(cinfo, st, 0);
  636. entropy->dc_context[ci] = 0; /* zero diff category */
  637. } else {
  638. entropy->last_dc_val[ci] = (*block)[0];
  639. arith_encode(cinfo, st, 1);
  640. /* Figure F.6: Encoding nonzero value v */
  641. /* Figure F.7: Encoding the sign of v */
  642. if (v > 0) {
  643. arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
  644. st += 2; /* Table F.4: SP = S0 + 2 */
  645. entropy->dc_context[ci] = 4; /* small positive diff category */
  646. } else {
  647. v = -v;
  648. arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
  649. st += 3; /* Table F.4: SN = S0 + 3 */
  650. entropy->dc_context[ci] = 8; /* small negative diff category */
  651. }
  652. /* Figure F.8: Encoding the magnitude category of v */
  653. m = 0;
  654. if (v -= 1) {
  655. arith_encode(cinfo, st, 1);
  656. m = 1;
  657. v2 = v;
  658. st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
  659. while (v2 >>= 1) {
  660. arith_encode(cinfo, st, 1);
  661. m <<= 1;
  662. st += 1;
  663. }
  664. }
  665. arith_encode(cinfo, st, 0);
  666. /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
  667. if (m < (int) (((INT32) 1 << cinfo->arith_dc_L[tbl]) >> 1))
  668. entropy->dc_context[ci] = 0; /* zero diff category */
  669. else if (m > (int) (((INT32) 1 << cinfo->arith_dc_U[tbl]) >> 1))
  670. entropy->dc_context[ci] += 8; /* large diff category */
  671. /* Figure F.9: Encoding the magnitude bit pattern of v */
  672. st += 14;
  673. while (m >>= 1)
  674. arith_encode(cinfo, st, (m & v) ? 1 : 0);
  675. }
  676. /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
  677. tbl = compptr->ac_tbl_no;
  678. /* Establish EOB (end-of-block) index */
  679. for (ke = DCTSIZE2; ke > 1; ke--)
  680. if ((*block)[jpeg_natural_order[ke - 1]]) break;
  681. /* Figure F.5: Encode_AC_Coefficients */
  682. for (k = 1; k < ke; k++) {
  683. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  684. arith_encode(cinfo, st, 0); /* EOB decision */
  685. while ((v = (*block)[jpeg_natural_order[k]]) == 0) {
  686. arith_encode(cinfo, st + 1, 0); st += 3; k++;
  687. }
  688. arith_encode(cinfo, st + 1, 1);
  689. /* Figure F.6: Encoding nonzero value v */
  690. /* Figure F.7: Encoding the sign of v */
  691. entropy->ac_stats[tbl][245] = 0;
  692. if (v > 0) {
  693. arith_encode(cinfo, entropy->ac_stats[tbl] + 245, 0);
  694. } else {
  695. v = -v;
  696. arith_encode(cinfo, entropy->ac_stats[tbl] + 245, 1);
  697. }
  698. st += 2;
  699. /* Figure F.8: Encoding the magnitude category of v */
  700. m = 0;
  701. if (v -= 1) {
  702. arith_encode(cinfo, st, 1);
  703. m = 1;
  704. v2 = v;
  705. if (v2 >>= 1) {
  706. arith_encode(cinfo, st, 1);
  707. m <<= 1;
  708. st = entropy->ac_stats[tbl] +
  709. (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
  710. while (v2 >>= 1) {
  711. arith_encode(cinfo, st, 1);
  712. m <<= 1;
  713. st += 1;
  714. }
  715. }
  716. }
  717. arith_encode(cinfo, st, 0);
  718. /* Figure F.9: Encoding the magnitude bit pattern of v */
  719. st += 14;
  720. while (m >>= 1)
  721. arith_encode(cinfo, st, (m & v) ? 1 : 0);
  722. }
  723. /* Encode EOB decision only if k < DCTSIZE2 */
  724. if (k < DCTSIZE2) {
  725. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  726. arith_encode(cinfo, st, 1);
  727. }
  728. }
  729. return TRUE;
  730. }
  731. /*
  732. * Initialize for an arithmetic-compressed scan.
  733. */
  734. METHODDEF(void)
  735. start_pass (j_compress_ptr cinfo, boolean gather_statistics)
  736. {
  737. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  738. int ci, tbl;
  739. jpeg_component_info * compptr;
  740. if (gather_statistics)
  741. /* Make sure to avoid that in the master control logic!
  742. * We are fully adaptive here and need no extra
  743. * statistics gathering pass!
  744. */
  745. ERREXIT(cinfo, JERR_NOT_COMPILED);
  746. /* We assume jcmaster.c already validated the progressive scan parameters. */
  747. /* Select execution routines */
  748. if (cinfo->progressive_mode) {
  749. if (cinfo->Ah == 0) {
  750. if (cinfo->Ss == 0)
  751. entropy->pub.encode_mcu = encode_mcu_DC_first;
  752. else
  753. entropy->pub.encode_mcu = encode_mcu_AC_first;
  754. } else {
  755. if (cinfo->Ss == 0)
  756. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  757. else
  758. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  759. }
  760. } else
  761. entropy->pub.encode_mcu = encode_mcu;
  762. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  763. compptr = cinfo->cur_comp_info[ci];
  764. /* Allocate & initialize requested statistics areas */
  765. if (cinfo->progressive_mode == 0 || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
  766. tbl = compptr->dc_tbl_no;
  767. if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
  768. ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
  769. if (entropy->dc_stats[tbl] == NULL)
  770. entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
  771. ((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);
  772. MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);
  773. /* Initialize DC predictions to 0 */
  774. entropy->last_dc_val[ci] = 0;
  775. entropy->dc_context[ci] = 0;
  776. }
  777. if (cinfo->progressive_mode == 0 || cinfo->Ss) {
  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. }