Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

934 lines
28 KiB

  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. arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
  196. unsigned char nl, nm;
  197. INT32 qe, temp;
  198. 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->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->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. const int * natural_order;
  412. /* Emit restart marker if needed */
  413. if (cinfo->restart_interval) {
  414. if (entropy->restarts_to_go == 0) {
  415. emit_restart(cinfo, entropy->next_restart_num);
  416. entropy->restarts_to_go = cinfo->restart_interval;
  417. entropy->next_restart_num++;
  418. entropy->next_restart_num &= 7;
  419. }
  420. entropy->restarts_to_go--;
  421. }
  422. natural_order = cinfo->natural_order;
  423. /* Encode the MCU data block */
  424. block = MCU_data[0];
  425. tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
  426. /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
  427. /* Establish EOB (end-of-block) index */
  428. for (ke = cinfo->Se; ke > 0; ke--)
  429. /* We must apply the point transform by Al. For AC coefficients this
  430. * is an integer division with rounding towards 0. To do this portably
  431. * in C, we shift after obtaining the absolute value.
  432. */
  433. if ((v = (*block)[natural_order[ke]]) >= 0) {
  434. if (v >>= cinfo->Al) break;
  435. } else {
  436. v = -v;
  437. if (v >>= cinfo->Al) break;
  438. }
  439. /* Figure F.5: Encode_AC_Coefficients */
  440. for (k = cinfo->Ss; k <= ke; k++) {
  441. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  442. arith_encode(cinfo, st, 0); /* EOB decision */
  443. for (;;) {
  444. if ((v = (*block)[natural_order[k]]) >= 0) {
  445. if (v >>= cinfo->Al) {
  446. arith_encode(cinfo, st + 1, 1);
  447. arith_encode(cinfo, entropy->fixed_bin, 0);
  448. break;
  449. }
  450. } else {
  451. v = -v;
  452. if (v >>= cinfo->Al) {
  453. arith_encode(cinfo, st + 1, 1);
  454. arith_encode(cinfo, entropy->fixed_bin, 1);
  455. break;
  456. }
  457. }
  458. arith_encode(cinfo, st + 1, 0); st += 3; k++;
  459. }
  460. st += 2;
  461. /* Figure F.8: Encoding the magnitude category of v */
  462. m = 0;
  463. if (v -= 1) {
  464. arith_encode(cinfo, st, 1);
  465. m = 1;
  466. v2 = v;
  467. if (v2 >>= 1) {
  468. arith_encode(cinfo, st, 1);
  469. m <<= 1;
  470. st = entropy->ac_stats[tbl] +
  471. (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
  472. while (v2 >>= 1) {
  473. arith_encode(cinfo, st, 1);
  474. m <<= 1;
  475. st += 1;
  476. }
  477. }
  478. }
  479. arith_encode(cinfo, st, 0);
  480. /* Figure F.9: Encoding the magnitude bit pattern of v */
  481. st += 14;
  482. while (m >>= 1)
  483. arith_encode(cinfo, st, (m & v) ? 1 : 0);
  484. }
  485. /* Encode EOB decision only if k <= cinfo->Se */
  486. if (k <= cinfo->Se) {
  487. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  488. arith_encode(cinfo, st, 1);
  489. }
  490. return TRUE;
  491. }
  492. /*
  493. * MCU encoding for DC successive approximation refinement scan.
  494. */
  495. METHODDEF(boolean)
  496. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  497. {
  498. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  499. unsigned char *st;
  500. int Al, blkn;
  501. /* Emit restart marker if needed */
  502. if (cinfo->restart_interval) {
  503. if (entropy->restarts_to_go == 0) {
  504. emit_restart(cinfo, entropy->next_restart_num);
  505. entropy->restarts_to_go = cinfo->restart_interval;
  506. entropy->next_restart_num++;
  507. entropy->next_restart_num &= 7;
  508. }
  509. entropy->restarts_to_go--;
  510. }
  511. st = entropy->fixed_bin; /* use fixed probability estimation */
  512. Al = cinfo->Al;
  513. /* Encode the MCU data blocks */
  514. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  515. /* We simply emit the Al'th bit of the DC coefficient value. */
  516. arith_encode(cinfo, st, (MCU_data[blkn][0][0] >> Al) & 1);
  517. }
  518. return TRUE;
  519. }
  520. /*
  521. * MCU encoding for AC successive approximation refinement scan.
  522. */
  523. METHODDEF(boolean)
  524. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  525. {
  526. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  527. JBLOCKROW block;
  528. unsigned char *st;
  529. int tbl, k, ke, kex;
  530. int v;
  531. const int * natural_order;
  532. /* Emit restart marker if needed */
  533. if (cinfo->restart_interval) {
  534. if (entropy->restarts_to_go == 0) {
  535. emit_restart(cinfo, entropy->next_restart_num);
  536. entropy->restarts_to_go = cinfo->restart_interval;
  537. entropy->next_restart_num++;
  538. entropy->next_restart_num &= 7;
  539. }
  540. entropy->restarts_to_go--;
  541. }
  542. natural_order = cinfo->natural_order;
  543. /* Encode the MCU data block */
  544. block = MCU_data[0];
  545. tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
  546. /* Section G.1.3.3: Encoding of AC coefficients */
  547. /* Establish EOB (end-of-block) index */
  548. for (ke = cinfo->Se; ke > 0; ke--)
  549. /* We must apply the point transform by Al. For AC coefficients this
  550. * is an integer division with rounding towards 0. To do this portably
  551. * in C, we shift after obtaining the absolute value.
  552. */
  553. if ((v = (*block)[natural_order[ke]]) >= 0) {
  554. if (v >>= cinfo->Al) break;
  555. } else {
  556. v = -v;
  557. if (v >>= cinfo->Al) break;
  558. }
  559. /* Establish EOBx (previous stage end-of-block) index */
  560. for (kex = ke; kex > 0; kex--)
  561. if ((v = (*block)[natural_order[kex]]) >= 0) {
  562. if (v >>= cinfo->Ah) break;
  563. } else {
  564. v = -v;
  565. if (v >>= cinfo->Ah) break;
  566. }
  567. /* Figure G.10: Encode_AC_Coefficients_SA */
  568. for (k = cinfo->Ss; k <= ke; k++) {
  569. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  570. if (k > kex)
  571. arith_encode(cinfo, st, 0); /* EOB decision */
  572. for (;;) {
  573. if ((v = (*block)[natural_order[k]]) >= 0) {
  574. if (v >>= cinfo->Al) {
  575. if (v >> 1) /* previously nonzero coef */
  576. arith_encode(cinfo, st + 2, (v & 1));
  577. else { /* newly nonzero coef */
  578. arith_encode(cinfo, st + 1, 1);
  579. arith_encode(cinfo, entropy->fixed_bin, 0);
  580. }
  581. break;
  582. }
  583. } else {
  584. v = -v;
  585. if (v >>= cinfo->Al) {
  586. if (v >> 1) /* previously nonzero coef */
  587. arith_encode(cinfo, st + 2, (v & 1));
  588. else { /* newly nonzero coef */
  589. arith_encode(cinfo, st + 1, 1);
  590. arith_encode(cinfo, entropy->fixed_bin, 1);
  591. }
  592. break;
  593. }
  594. }
  595. arith_encode(cinfo, st + 1, 0); st += 3; k++;
  596. }
  597. }
  598. /* Encode EOB decision only if k <= cinfo->Se */
  599. if (k <= cinfo->Se) {
  600. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  601. arith_encode(cinfo, st, 1);
  602. }
  603. return TRUE;
  604. }
  605. /*
  606. * Encode and output one MCU's worth of arithmetic-compressed coefficients.
  607. */
  608. METHODDEF(boolean)
  609. encode_mcu (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  610. {
  611. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  612. jpeg_component_info * compptr;
  613. JBLOCKROW block;
  614. unsigned char *st;
  615. int blkn, ci, tbl, k, ke;
  616. int v, v2, m;
  617. const int * natural_order;
  618. /* Emit restart marker if needed */
  619. if (cinfo->restart_interval) {
  620. if (entropy->restarts_to_go == 0) {
  621. emit_restart(cinfo, entropy->next_restart_num);
  622. entropy->restarts_to_go = cinfo->restart_interval;
  623. entropy->next_restart_num++;
  624. entropy->next_restart_num &= 7;
  625. }
  626. entropy->restarts_to_go--;
  627. }
  628. natural_order = cinfo->natural_order;
  629. /* Encode the MCU data blocks */
  630. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  631. block = MCU_data[blkn];
  632. ci = cinfo->MCU_membership[blkn];
  633. compptr = cinfo->cur_comp_info[ci];
  634. /* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */
  635. tbl = compptr->dc_tbl_no;
  636. /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
  637. st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
  638. /* Figure F.4: Encode_DC_DIFF */
  639. if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) {
  640. arith_encode(cinfo, st, 0);
  641. entropy->dc_context[ci] = 0; /* zero diff category */
  642. } else {
  643. entropy->last_dc_val[ci] = (*block)[0];
  644. arith_encode(cinfo, st, 1);
  645. /* Figure F.6: Encoding nonzero value v */
  646. /* Figure F.7: Encoding the sign of v */
  647. if (v > 0) {
  648. arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
  649. st += 2; /* Table F.4: SP = S0 + 2 */
  650. entropy->dc_context[ci] = 4; /* small positive diff category */
  651. } else {
  652. v = -v;
  653. arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
  654. st += 3; /* Table F.4: SN = S0 + 3 */
  655. entropy->dc_context[ci] = 8; /* small negative diff category */
  656. }
  657. /* Figure F.8: Encoding the magnitude category of v */
  658. m = 0;
  659. if (v -= 1) {
  660. arith_encode(cinfo, st, 1);
  661. m = 1;
  662. v2 = v;
  663. st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
  664. while (v2 >>= 1) {
  665. arith_encode(cinfo, st, 1);
  666. m <<= 1;
  667. st += 1;
  668. }
  669. }
  670. arith_encode(cinfo, st, 0);
  671. /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
  672. if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
  673. entropy->dc_context[ci] = 0; /* zero diff category */
  674. else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
  675. entropy->dc_context[ci] += 8; /* large diff category */
  676. /* Figure F.9: Encoding the magnitude bit pattern of v */
  677. st += 14;
  678. while (m >>= 1)
  679. arith_encode(cinfo, st, (m & v) ? 1 : 0);
  680. }
  681. /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
  682. tbl = compptr->ac_tbl_no;
  683. /* Establish EOB (end-of-block) index */
  684. for (ke = cinfo->lim_Se; ke > 0; ke--)
  685. if ((*block)[natural_order[ke]]) break;
  686. /* Figure F.5: Encode_AC_Coefficients */
  687. for (k = 1; k <= ke; k++) {
  688. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  689. arith_encode(cinfo, st, 0); /* EOB decision */
  690. while ((v = (*block)[natural_order[k]]) == 0) {
  691. arith_encode(cinfo, st + 1, 0); st += 3; k++;
  692. }
  693. arith_encode(cinfo, st + 1, 1);
  694. /* Figure F.6: Encoding nonzero value v */
  695. /* Figure F.7: Encoding the sign of v */
  696. if (v > 0) {
  697. arith_encode(cinfo, entropy->fixed_bin, 0);
  698. } else {
  699. v = -v;
  700. arith_encode(cinfo, entropy->fixed_bin, 1);
  701. }
  702. st += 2;
  703. /* Figure F.8: Encoding the magnitude category of v */
  704. m = 0;
  705. if (v -= 1) {
  706. arith_encode(cinfo, st, 1);
  707. m = 1;
  708. v2 = v;
  709. if (v2 >>= 1) {
  710. arith_encode(cinfo, st, 1);
  711. m <<= 1;
  712. st = entropy->ac_stats[tbl] +
  713. (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
  714. while (v2 >>= 1) {
  715. arith_encode(cinfo, st, 1);
  716. m <<= 1;
  717. st += 1;
  718. }
  719. }
  720. }
  721. arith_encode(cinfo, st, 0);
  722. /* Figure F.9: Encoding the magnitude bit pattern of v */
  723. st += 14;
  724. while (m >>= 1)
  725. arith_encode(cinfo, st, (m & v) ? 1 : 0);
  726. }
  727. /* Encode EOB decision only if k <= cinfo->lim_Se */
  728. if (k <= cinfo->lim_Se) {
  729. st = entropy->ac_stats[tbl] + 3 * (k - 1);
  730. arith_encode(cinfo, st, 1);
  731. }
  732. }
  733. return TRUE;
  734. }
  735. /*
  736. * Initialize for an arithmetic-compressed scan.
  737. */
  738. METHODDEF(void)
  739. start_pass (j_compress_ptr cinfo, boolean gather_statistics)
  740. {
  741. arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
  742. int ci, tbl;
  743. jpeg_component_info * compptr;
  744. if (gather_statistics)
  745. /* Make sure to avoid that in the master control logic!
  746. * We are fully adaptive here and need no extra
  747. * statistics gathering pass!
  748. */
  749. ERREXIT(cinfo, JERR_NOT_COMPILED);
  750. /* We assume jcmaster.c already validated the progressive scan parameters. */
  751. /* Select execution routines */
  752. if (cinfo->progressive_mode) {
  753. if (cinfo->Ah == 0) {
  754. if (cinfo->Ss == 0)
  755. entropy->pub.encode_mcu = encode_mcu_DC_first;
  756. else
  757. entropy->pub.encode_mcu = encode_mcu_AC_first;
  758. } else {
  759. if (cinfo->Ss == 0)
  760. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  761. else
  762. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  763. }
  764. } else
  765. entropy->pub.encode_mcu = encode_mcu;
  766. /* Allocate & initialize requested statistics areas */
  767. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  768. compptr = cinfo->cur_comp_info[ci];
  769. /* DC needs no table for refinement scan */
  770. if (cinfo->Ss == 0 && cinfo->Ah == 0) {
  771. tbl = compptr->dc_tbl_no;
  772. if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
  773. ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
  774. if (entropy->dc_stats[tbl] == NULL)
  775. entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
  776. ((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);
  777. MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);
  778. /* Initialize DC predictions to 0 */
  779. entropy->last_dc_val[ci] = 0;
  780. entropy->dc_context[ci] = 0;
  781. }
  782. /* AC needs no table when not present */
  783. if (cinfo->Se) {
  784. tbl = compptr->ac_tbl_no;
  785. if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
  786. ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
  787. if (entropy->ac_stats[tbl] == NULL)
  788. entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
  789. ((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);
  790. MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);
  791. #ifdef CALCULATE_SPECTRAL_CONDITIONING
  792. if (cinfo->progressive_mode)
  793. /* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */
  794. cinfo->arith_ac_K[tbl] = cinfo->Ss + ((8 + cinfo->Se - cinfo->Ss) >> 4);
  795. #endif
  796. }
  797. }
  798. /* Initialize arithmetic encoding variables */
  799. entropy->c = 0;
  800. entropy->a = 0x10000L;
  801. entropy->sc = 0;
  802. entropy->zc = 0;
  803. entropy->ct = 11;
  804. entropy->buffer = -1; /* empty */
  805. /* Initialize restart stuff */
  806. entropy->restarts_to_go = cinfo->restart_interval;
  807. entropy->next_restart_num = 0;
  808. }
  809. /*
  810. * Module initialization routine for arithmetic entropy encoding.
  811. */
  812. GLOBAL(void)
  813. jinit_arith_encoder (j_compress_ptr cinfo)
  814. {
  815. arith_entropy_ptr entropy;
  816. int i;
  817. entropy = (arith_entropy_ptr)
  818. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  819. SIZEOF(arith_entropy_encoder));
  820. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  821. entropy->pub.start_pass = start_pass;
  822. entropy->pub.finish_pass = finish_pass;
  823. /* Mark tables unallocated */
  824. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  825. entropy->dc_stats[i] = NULL;
  826. entropy->ac_stats[i] = NULL;
  827. }
  828. /* Initialize index for fixed probability estimation */
  829. entropy->fixed_bin[0] = 113;
  830. }