jcarith.c 29 KB

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