jcarith.c 29 KB

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