jcarith.c 28 KB

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