PageRenderTime 66ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/cximage-6.0/jbig/jbig.c

http://github.com/xbmc/xbmc
C | 3195 lines | 2199 code | 342 blank | 654 comment | 734 complexity | 03e6499b90c85bf79ba05d9f2496ed12 MD5 | raw file
Possible License(s): GPL-3.0, CC-BY-SA-3.0, LGPL-2.0, 0BSD, Unlicense, GPL-2.0, AGPL-1.0, BSD-3-Clause, LGPL-2.1, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * Portable Free JBIG image compression library
  3. *
  4. * Markus Kuhn -- http://www.cl.cam.ac.uk/~mgk25/
  5. *
  6. * $Id: jbig.c,v 1.22 2004-06-11 15:17:06+01 mgk25 Exp $
  7. *
  8. * This module implements a portable standard C encoder and decoder
  9. * using the JBIG lossless bi-level image compression algorithm as
  10. * specified in International Standard ISO 11544:1993 or equivalently
  11. * as specified in ITU-T Recommendation T.82. See the file jbig.doc
  12. * for usage instructions and application examples.
  13. *
  14. * This program is free software; you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation; either version 2 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program; if not, write to the Free Software
  26. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  27. *
  28. * If you want to use this program under different license conditions,
  29. * then contact the author for an arrangement.
  30. *
  31. * It is possible that certain products which can be built using this
  32. * software module might form inventions protected by patent rights in
  33. * some countries (e.g., by patents about arithmetic coding algorithms
  34. * owned by IBM and AT&T in the USA). Provision of this software by the
  35. * author does NOT include any licences for any patents. In those
  36. * countries where a patent licence is required for certain applications
  37. * of this software module, you will have to obtain such a licence
  38. * yourself.
  39. */
  40. #ifdef DEBUG
  41. #include <stdio.h>
  42. #else
  43. #ifndef NDEBUG
  44. #define NDEBUG
  45. #endif
  46. #endif
  47. #include <stdlib.h>
  48. #include <string.h>
  49. #include <assert.h>
  50. #include "jbig.h"
  51. /* optional export of arithmetic coder functions for test purposes */
  52. #ifdef TEST_CODEC
  53. #define ARITH
  54. #define ARITH_INL
  55. #else
  56. #define ARITH static
  57. #ifdef __GNUC__
  58. #define ARITH_INL static __inline__
  59. #else
  60. #define ARITH_INL static
  61. #endif
  62. #endif
  63. #define MX_MAX 127 /* maximal supported mx offset for
  64. * adaptive template in the encoder */
  65. #define TPB2CX 0x195 /* contexts for TP special pixels */
  66. #define TPB3CX 0x0e5
  67. #define TPDCX 0xc3f
  68. /* marker codes */
  69. #define MARKER_STUFF 0x00
  70. #define MARKER_RESERVE 0x01
  71. #define MARKER_SDNORM 0x02
  72. #define MARKER_SDRST 0x03
  73. #define MARKER_ABORT 0x04
  74. #define MARKER_NEWLEN 0x05
  75. #define MARKER_ATMOVE 0x06
  76. #define MARKER_COMMENT 0x07
  77. #define MARKER_ESC 0xff
  78. /* loop array indices */
  79. #define STRIPE 0
  80. #define LAYER 1
  81. #define PLANE 2
  82. /* special jbg_buf pointers (instead of NULL) */
  83. #define SDE_DONE ((struct jbg_buf *) -1)
  84. #define SDE_TODO ((struct jbg_buf *) 0)
  85. /* object code version id */
  86. const char jbg_version[] =
  87. " JBIG-KIT " JBG_VERSION " -- Markus Kuhn -- "
  88. "$Id: jbig.c,v 1.22 2004-06-11 15:17:06+01 mgk25 Exp $ ";
  89. /*
  90. * the following array specifies for each combination of the 3
  91. * ordering bits, which ii[] variable represents which dimension
  92. * of s->sde.
  93. */
  94. static const int iindex[8][3] = {
  95. { 2, 1, 0 }, /* no ordering bit set */
  96. { -1, -1, -1}, /* SMID -> illegal combination */
  97. { 2, 0, 1 }, /* ILEAVE */
  98. { 1, 0, 2 }, /* SMID + ILEAVE */
  99. { 0, 2, 1 }, /* SEQ */
  100. { 1, 2, 0 }, /* SEQ + SMID */
  101. { 0, 1, 2 }, /* SEQ + ILEAVE */
  102. { -1, -1, -1 } /* SEQ + SMID + ILEAVE -> illegal combination */
  103. };
  104. /*
  105. * Array [language][message] with text string error messages that correspond
  106. * to return values from public functions in this library.
  107. */
  108. #define NEMSG 9 /* number of error codes */
  109. #define NEMSG_LANG 3 /* number of supported languages */
  110. static const char *errmsg[NEMSG_LANG][NEMSG] = {
  111. /* English (JBG_EN) */
  112. {
  113. "Everything is ok", /* JBG_EOK */
  114. "Reached specified maximum size", /* JBG_EOK_INTR */
  115. "Unexpected end of data", /* JBG_EAGAIN */
  116. "Not enough memory available", /* JBG_ENOMEM */
  117. "ABORT marker found", /* JBG_EABORT */
  118. "Unknown marker segment encountered", /* JBG_EMARKER */
  119. "Incremental BIE does not fit to previous one", /* JBG_ENOCONT */
  120. "Invalid data encountered", /* JBG_EINVAL */
  121. "Unimplemented features used" /* JBG_EIMPL */
  122. },
  123. /* German (JBG_DE_8859_1) */
  124. {
  125. "Kein Problem aufgetreten", /* JBG_EOK */
  126. "Angegebene maximale Bildgr\366\337e erreicht", /* JBG_EOK_INTR */
  127. "Unerwartetes Ende der Daten", /* JBG_EAGAIN */
  128. "Nicht gen\374gend Speicher vorhanden", /* JBG_ENOMEM */
  129. "Es wurde eine Abbruch-Sequenz gefunden", /* JBG_EABORT */
  130. "Eine unbekannte Markierungssequenz wurde gefunden", /* JBG_EMARKER */
  131. "Neue Daten passen nicht zu vorangegangenen Daten", /* JBG_ENOCONT */
  132. "Es wurden ung\374ltige Daten gefunden", /* JBG_EINVAL */
  133. "Noch nicht implementierte Optionen wurden benutzt" /* JBG_EIMPL */
  134. },
  135. /* German (JBG_DE_UTF_8) */
  136. {
  137. "Kein Problem aufgetreten", /* JBG_EOK */
  138. "Angegebene maximale Bildgr\303\266\303\237e erreicht", /* JBG_EOK_INTR */
  139. "Unerwartetes Ende der Daten", /* JBG_EAGAIN */
  140. "Nicht gen\303\274gend Speicher vorhanden", /* JBG_ENOMEM */
  141. "Es wurde eine Abbruch-Sequenz gefunden", /* JBG_EABORT */
  142. "Eine unbekannte Markierungssequenz wurde gefunden", /* JBG_EMARKER */
  143. "Neue Daten passen nicht zu vorangegangenen Daten", /* JBG_ENOCONT */
  144. "Es wurden ung\303\274ltige Daten gefunden", /* JBG_EINVAL */
  145. "Noch nicht implementierte Optionen wurden benutzt" /* JBG_EIMPL */
  146. }
  147. };
  148. /*
  149. * The following three functions are the only places in this code, were
  150. * C library memory management functions are called. The whole JBIG
  151. * library has been designed in order to allow multi-threaded
  152. * execution. No static or global variables are used, so all fuctions
  153. * are fully reentrant. However if you want to use this multi-thread
  154. * capability and your malloc, realloc and free are not reentrant,
  155. * then simply add the necessary semaphores or mutex primitives below.
  156. * In contrast to C's malloc() and realloc(), but like C's calloc(),
  157. * these functions take two parameters nmemb and size that are multiplied
  158. * before being passed on to the corresponding C function.
  159. * This we can catch all overflows during a size_t multiplication a
  160. * a single place.
  161. */
  162. #ifndef SIZE_MAX
  163. #define SIZE_MAX ((size_t) -1) /* largest value of size_t */
  164. #endif
  165. static void *checked_malloc(size_t nmemb, size_t size)
  166. {
  167. void *p;
  168. /* Full manual exception handling is ugly here for performance
  169. * reasons. If an adequate handling of lack of memory is required,
  170. * then use C++ and throw a C++ exception instead of abort(). */
  171. /* assert that nmemb * size <= SIZE_MAX */
  172. if (size > SIZE_MAX / nmemb)
  173. abort();
  174. p = malloc(nmemb * size);
  175. if (!p)
  176. abort();
  177. #if 0
  178. fprintf(stderr, "%p = malloc(%lu * %lu)\n", p,
  179. (unsigned long) nmemb, (unsigned long) size);
  180. #endif
  181. return p;
  182. }
  183. static void *checked_realloc(void *ptr, size_t nmemb, size_t size)
  184. {
  185. void *p;
  186. /* Full manual exception handling is ugly here for performance
  187. * reasons. If an adequate handling of lack of memory is required,
  188. * then use C++ and throw a C++ exception here instead of abort(). */
  189. /* assert that nmemb * size <= SIZE_MAX */
  190. if (size > SIZE_MAX / nmemb)
  191. abort();
  192. p = realloc(ptr, nmemb * size);
  193. if (!p)
  194. abort();
  195. #if 0
  196. fprintf(stderr, "%p = realloc(%p, %lu * %lu)\n", p, ptr,
  197. (unsigned long) nmemb, (unsigned long) size);
  198. #endif
  199. return p;
  200. }
  201. static void checked_free(void *ptr)
  202. {
  203. free(ptr);
  204. #if 0
  205. fprintf(stderr, "free(%p)\n", ptr);
  206. #endif
  207. }
  208. /*
  209. * The next functions implement the arithmedic encoder and decoder
  210. * required for JBIG. The same algorithm is also used in the arithmetic
  211. * variant of JPEG.
  212. */
  213. #ifdef DEBUG
  214. static long encoded_pixels = 0;
  215. #endif
  216. ARITH void arith_encode_init(struct jbg_arenc_state *s, int reuse_st)
  217. {
  218. int i;
  219. if (!reuse_st)
  220. for (i = 0; i < 4096; s->st[i++] = 0);
  221. s->c = 0;
  222. s->a = 0x10000L;
  223. s->sc = 0;
  224. s->ct = 11;
  225. s->buffer = -1; /* empty */
  226. return;
  227. }
  228. ARITH void arith_encode_flush(struct jbg_arenc_state *s)
  229. {
  230. unsigned long temp;
  231. #ifdef DEBUG
  232. fprintf(stderr, " encoded pixels = %ld, a = %05lx, c = %08lx\n",
  233. encoded_pixels, s->a, s->c);
  234. #endif
  235. /* find the s->c in the coding interval with the largest
  236. * number of trailing zero bits */
  237. if ((temp = (s->a - 1 + s->c) & 0xffff0000L) < s->c)
  238. s->c = temp + 0x8000;
  239. else
  240. s->c = temp;
  241. /* send remaining bytes to output */
  242. s->c <<= s->ct;
  243. if (s->c & 0xf8000000L) {
  244. /* one final overflow has to be handled */
  245. if (s->buffer >= 0) {
  246. s->byte_out(s->buffer + 1, s->file);
  247. if (s->buffer + 1 == MARKER_ESC)
  248. s->byte_out(MARKER_STUFF, s->file);
  249. }
  250. /* output 0x00 bytes only when more non-0x00 will follow */
  251. if (s->c & 0x7fff800L)
  252. for (; s->sc; --s->sc)
  253. s->byte_out(0x00, s->file);
  254. } else {
  255. if (s->buffer >= 0)
  256. s->byte_out(s->buffer, s->file);
  257. /* T.82 figure 30 says buffer+1 for the above line! Typo? */
  258. for (; s->sc; --s->sc) {
  259. s->byte_out(0xff, s->file);
  260. s->byte_out(MARKER_STUFF, s->file);
  261. }
  262. }
  263. /* output final bytes only if they are not 0x00 */
  264. if (s->c & 0x7fff800L) {
  265. s->byte_out((s->c >> 19) & 0xff, s->file);
  266. if (((s->c >> 19) & 0xff) == MARKER_ESC)
  267. s->byte_out(MARKER_STUFF, s->file);
  268. if (s->c & 0x7f800L) {
  269. s->byte_out((s->c >> 11) & 0xff, s->file);
  270. if (((s->c >> 11) & 0xff) == MARKER_ESC)
  271. s->byte_out(MARKER_STUFF, s->file);
  272. }
  273. }
  274. return;
  275. }
  276. ARITH_INL void arith_encode(struct jbg_arenc_state *s, int cx, int pix)
  277. {
  278. extern short jbg_lsz[];
  279. extern unsigned char jbg_nmps[], jbg_nlps[];
  280. register unsigned lsz, ss;
  281. register unsigned char *st;
  282. long temp;
  283. #ifdef DEBUG
  284. ++encoded_pixels;
  285. #endif
  286. assert(cx >= 0 && cx < 4096);
  287. st = s->st + cx;
  288. ss = *st & 0x7f;
  289. assert(ss < 113);
  290. lsz = jbg_lsz[ss];
  291. #if 0
  292. fprintf(stderr, "pix = %d, cx = %d, mps = %d, st = %3d, lsz = 0x%04x, "
  293. "a = 0x%05lx, c = 0x%08lx, ct = %2d, buf = 0x%02x\n",
  294. pix, cx, !!(s->st[cx] & 0x80), ss, lsz, s->a, s->c, s->ct,
  295. s->buffer);
  296. #endif
  297. if (((pix << 7) ^ s->st[cx]) & 0x80) {
  298. /* encode the less probable symbol */
  299. if ((s->a -= lsz) >= lsz) {
  300. /* If the interval size (lsz) for the less probable symbol (LPS)
  301. * is larger than the interval size for the MPS, then exchange
  302. * the two symbols for coding efficiency, otherwise code the LPS
  303. * as usual: */
  304. s->c += s->a;
  305. s->a = lsz;
  306. }
  307. /* Check whether MPS/LPS exchange is necessary
  308. * and chose next probability estimator status */
  309. *st &= 0x80;
  310. *st ^= jbg_nlps[ss];
  311. } else {
  312. /* encode the more probable symbol */
  313. if ((s->a -= lsz) & 0xffff8000L)
  314. return; /* A >= 0x8000 -> ready, no renormalization required */
  315. if (s->a < lsz) {
  316. /* If the interval size (lsz) for the less probable symbol (LPS)
  317. * is larger than the interval size for the MPS, then exchange
  318. * the two symbols for coding efficiency: */
  319. s->c += s->a;
  320. s->a = lsz;
  321. }
  322. /* chose next probability estimator status */
  323. *st &= 0x80;
  324. *st |= jbg_nmps[ss];
  325. }
  326. /* renormalization of coding interval */
  327. do {
  328. s->a <<= 1;
  329. s->c <<= 1;
  330. --s->ct;
  331. if (s->ct == 0) {
  332. /* another byte is ready for output */
  333. temp = s->c >> 19;
  334. if (temp & 0xffffff00L) {
  335. /* handle overflow over all buffered 0xff bytes */
  336. if (s->buffer >= 0) {
  337. ++s->buffer;
  338. s->byte_out(s->buffer, s->file);
  339. if (s->buffer == MARKER_ESC)
  340. s->byte_out(MARKER_STUFF, s->file);
  341. }
  342. for (; s->sc; --s->sc)
  343. s->byte_out(0x00, s->file);
  344. s->buffer = temp & 0xff; /* new output byte, might overflow later */
  345. assert(s->buffer != 0xff);
  346. /* can s->buffer really never become 0xff here? */
  347. } else if (temp == 0xff) {
  348. /* buffer 0xff byte (which might overflow later) */
  349. ++s->sc;
  350. } else {
  351. /* output all buffered 0xff bytes, they will not overflow any more */
  352. if (s->buffer >= 0)
  353. s->byte_out(s->buffer, s->file);
  354. for (; s->sc; --s->sc) {
  355. s->byte_out(0xff, s->file);
  356. s->byte_out(MARKER_STUFF, s->file);
  357. }
  358. s->buffer = temp; /* buffer new output byte (can still overflow) */
  359. }
  360. s->c &= 0x7ffffL;
  361. s->ct = 8;
  362. }
  363. } while (s->a < 0x8000);
  364. return;
  365. }
  366. ARITH void arith_decode_init(struct jbg_ardec_state *s, int reuse_st)
  367. {
  368. int i;
  369. if (!reuse_st)
  370. for (i = 0; i < 4096; s->st[i++] = 0);
  371. s->c = 0;
  372. s->a = 1;
  373. s->ct = 0;
  374. s->result = JBG_OK;
  375. s->startup = 1;
  376. return;
  377. }
  378. ARITH_INL int arith_decode(struct jbg_ardec_state *s, int cx)
  379. {
  380. extern short jbg_lsz[];
  381. extern unsigned char jbg_nmps[], jbg_nlps[];
  382. register unsigned lsz, ss;
  383. register unsigned char *st;
  384. int pix;
  385. /* renormalization */
  386. while (s->a < 0x8000 || s->startup) {
  387. if (s->ct < 1 && s->result != JBG_READY) {
  388. /* first we have to move a new byte into s->c */
  389. if (s->pscd_ptr >= s->pscd_end) {
  390. s->result = JBG_MORE;
  391. return -1;
  392. }
  393. if (*s->pscd_ptr == 0xff)
  394. if (s->pscd_ptr + 1 >= s->pscd_end) {
  395. s->result = JBG_MARKER;
  396. return -1;
  397. } else {
  398. if (*(s->pscd_ptr + 1) == MARKER_STUFF) {
  399. s->c |= 0xffL << (8 - s->ct);
  400. s->ct += 8;
  401. s->pscd_ptr += 2;
  402. s->result = JBG_OK;
  403. } else
  404. s->result = JBG_READY;
  405. }
  406. else {
  407. s->c |= (long)*(s->pscd_ptr++) << (8 - s->ct);
  408. s->ct += 8;
  409. s->result = JBG_OK;
  410. }
  411. }
  412. s->c <<= 1;
  413. s->a <<= 1;
  414. --s->ct;
  415. if (s->a == 0x10000L)
  416. s->startup = 0;
  417. }
  418. st = s->st + cx;
  419. ss = *st & 0x7f;
  420. assert(ss < 113);
  421. lsz = jbg_lsz[ss];
  422. #if 0
  423. fprintf(stderr, "cx = %d, mps = %d, st = %3d, lsz = 0x%04x, a = 0x%05lx, "
  424. "c = 0x%08lx, ct = %2d\n",
  425. cx, !!(s->st[cx] & 0x80), ss, lsz, s->a, s->c, s->ct);
  426. #endif
  427. if ((s->c >> 16) < (s->a -= lsz))
  428. if (s->a & 0xffff8000L)
  429. return *st >> 7;
  430. else {
  431. /* MPS_EXCHANGE */
  432. if (s->a < lsz) {
  433. pix = 1 - (*st >> 7);
  434. /* Check whether MPS/LPS exchange is necessary
  435. * and chose next probability estimator status */
  436. *st &= 0x80;
  437. *st ^= jbg_nlps[ss];
  438. } else {
  439. pix = *st >> 7;
  440. *st &= 0x80;
  441. *st |= jbg_nmps[ss];
  442. }
  443. }
  444. else {
  445. /* LPS_EXCHANGE */
  446. if (s->a < lsz) {
  447. s->c -= s->a << 16;
  448. s->a = lsz;
  449. pix = *st >> 7;
  450. *st &= 0x80;
  451. *st |= jbg_nmps[ss];
  452. } else {
  453. s->c -= s->a << 16;
  454. s->a = lsz;
  455. pix = 1 - (*st >> 7);
  456. /* Check whether MPS/LPS exchange is necessary
  457. * and chose next probability estimator status */
  458. *st &= 0x80;
  459. *st ^= jbg_nlps[ss];
  460. }
  461. }
  462. return pix;
  463. }
  464. /*
  465. * Memory management for buffers which are used for temporarily
  466. * storing SDEs by the encoder.
  467. *
  468. * The following functions manage a set of struct jbg_buf storage
  469. * containers were each can keep JBG_BUFSIZE bytes. The jbg_buf
  470. * containers can be linked to form linear double-chained lists for
  471. * which a number of operations are provided. Blocks which are
  472. * tempoarily not used any more are returned to a freelist which each
  473. * encoder keeps. Only the destructor of the encoder actually returns
  474. * the block via checked_free() to the stdlib memory management.
  475. */
  476. /*
  477. * Allocate a new buffer block and initialize it. Try to get it from
  478. * the free_list, and if it is empty, call checked_malloc().
  479. */
  480. static struct jbg_buf *jbg_buf_init(struct jbg_buf **free_list)
  481. {
  482. struct jbg_buf *new_block;
  483. /* Test whether a block from the free list is available */
  484. if (*free_list) {
  485. new_block = *free_list;
  486. *free_list = new_block->next;
  487. } else {
  488. /* request a new memory block */
  489. new_block = (struct jbg_buf *) checked_malloc(1, sizeof(struct jbg_buf));
  490. }
  491. new_block->len = 0;
  492. new_block->next = NULL;
  493. new_block->previous = NULL;
  494. new_block->last = new_block;
  495. new_block->free_list = free_list;
  496. return new_block;
  497. }
  498. /*
  499. * Return an entire free_list to the memory management of stdlib.
  500. * This is only done by jbg_enc_free().
  501. */
  502. static void jbg_buf_free(struct jbg_buf **free_list)
  503. {
  504. struct jbg_buf *tmp;
  505. while (*free_list) {
  506. tmp = (*free_list)->next;
  507. checked_free(*free_list);
  508. *free_list = tmp;
  509. }
  510. return;
  511. }
  512. /*
  513. * Append a single byte to a single list that starts with the block
  514. * *(struct jbg_buf *) head. The type of *head is void here in order to
  515. * keep the interface of the arithmetic encoder gereric, which uses this
  516. * function as a call-back function in order to deliver single bytes
  517. * for a PSCD.
  518. */
  519. static void jbg_buf_write(int b, void *head)
  520. {
  521. struct jbg_buf *now;
  522. now = ((struct jbg_buf *) head)->last;
  523. if (now->len < JBG_BUFSIZE - 1) {
  524. now->d[now->len++] = b;
  525. return;
  526. }
  527. now->next = jbg_buf_init(((struct jbg_buf *) head)->free_list);
  528. now->next->previous = now;
  529. now->next->d[now->next->len++] = b;
  530. ((struct jbg_buf *) head)->last = now->next;
  531. return;
  532. }
  533. /*
  534. * Remove any trailing zero bytes from the end of a linked jbg_buf list,
  535. * however make sure that no zero byte is removed which directly
  536. * follows a 0xff byte (i.e., keep MARKER_ESC MARKER_STUFF sequences
  537. * intact). This function is used to remove any redundant final zero
  538. * bytes from a PSCD.
  539. */
  540. static void jbg_buf_remove_zeros(struct jbg_buf *head)
  541. {
  542. struct jbg_buf *last;
  543. while (1) {
  544. /* remove trailing 0x00 in last block of list until this block is empty */
  545. last = head->last;
  546. while (last->len && last->d[last->len - 1] == 0)
  547. last->len--;
  548. /* if block became really empty, remove it in case it is not the
  549. * only remaining block and then loop to next block */
  550. if (last->previous && !last->len) {
  551. head->last->next = *head->free_list;
  552. *head->free_list = head->last;
  553. head->last = last->previous;
  554. head->last->next = NULL;
  555. } else
  556. break;
  557. }
  558. /*
  559. * If the final non-zero byte is 0xff (MARKER_ESC), then we just have
  560. * removed a MARKER_STUFF and we will append it again now in order
  561. * to preserve PSCD status of byte stream.
  562. */
  563. if (head->last->len && head->last->d[head->last->len - 1] == MARKER_ESC)
  564. jbg_buf_write(MARKER_STUFF, head);
  565. return;
  566. }
  567. /*
  568. * The jbg_buf list which starts with block *new_prefix is concatenated
  569. * with the list which starts with block **start and *start will then point
  570. * to the first block of the new list.
  571. */
  572. static void jbg_buf_prefix(struct jbg_buf *new_prefix, struct jbg_buf **start)
  573. {
  574. new_prefix->last->next = *start;
  575. new_prefix->last->next->previous = new_prefix->last;
  576. new_prefix->last = new_prefix->last->next->last;
  577. *start = new_prefix;
  578. return;
  579. }
  580. /*
  581. * Send the contents of a jbg_buf list that starts with block **head to
  582. * the call back function data_out and return the blocks of the jbg_buf
  583. * list to the freelist from which these jbg_buf blocks have been taken.
  584. * After the call, *head == NULL.
  585. */
  586. static void jbg_buf_output(struct jbg_buf **head,
  587. void (*data_out)(unsigned char *start,
  588. size_t len, void *file),
  589. void *file)
  590. {
  591. struct jbg_buf *tmp;
  592. while (*head) {
  593. data_out((*head)->d, (*head)->len, file);
  594. tmp = (*head)->next;
  595. (*head)->next = *(*head)->free_list;
  596. *(*head)->free_list = *head;
  597. *head = tmp;
  598. }
  599. return;
  600. }
  601. /*
  602. * Calculate y = ceil(x/2) applied n times, which is equivalent to
  603. * y = ceil(x/(2^n)). This function is used to
  604. * determine the number of pixels per row or column after n resolution
  605. * reductions. E.g. X[d-1] = jbg_ceil_half(X[d], 1) and X[0] =
  606. * jbg_ceil_half(X[d], d) as defined in clause 6.2.3 of T.82.
  607. */
  608. unsigned long jbg_ceil_half(unsigned long x, int n)
  609. {
  610. unsigned long mask;
  611. assert(n >= 0 && n < 32);
  612. mask = (1UL << n) - 1; /* the lowest n bits are 1 here */
  613. return (x >> n) + ((mask & x) != 0);
  614. }
  615. /*
  616. * Set L0 (the number of lines in a stripe at lowest resolution)
  617. * to a default value, such that there are about 35 stripes, as
  618. * suggested in Annex C of ITU-T T.82, without exceeding the
  619. * limit 128/2^D suggested in Annex A.
  620. */
  621. static void jbg_set_default_l0(struct jbg_enc_state *s)
  622. {
  623. s->l0 = jbg_ceil_half(s->yd, s->d) / 35; /* 35 stripes/image */
  624. while ((s->l0 << s->d) > 128) /* but <= 128 lines/stripe */
  625. --s->l0;
  626. if (s->l0 < 2) s->l0 = 2;
  627. }
  628. /*
  629. * Calculate the number of stripes, as defined in clause 6.2.3 of T.82.
  630. */
  631. static unsigned long jbg_stripes(unsigned long l0, unsigned long yd,
  632. unsigned long d)
  633. {
  634. unsigned long y0 = jbg_ceil_half(yd, d);
  635. return y0 / l0 + (y0 % l0 != 0);
  636. }
  637. /*
  638. * Initialize the status struct for the encoder.
  639. */
  640. void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y,
  641. int planes, unsigned char **p,
  642. void (*data_out)(unsigned char *start, size_t len,
  643. void *file),
  644. void *file)
  645. {
  646. unsigned long l, lx;
  647. int i;
  648. extern char jbg_resred[], jbg_dptable[];
  649. s->xd = x;
  650. s->yd = y;
  651. s->yd1 = y; /* This is the hight initially announced in BIH. To provoke
  652. generation of NEWLEN for T.85 compatibility tests,
  653. overwrite with new value s->yd1 > s->yd */
  654. s->planes = planes;
  655. s->data_out = data_out;
  656. s->file = file;
  657. s->d = 0;
  658. s->dl = 0;
  659. s->dh = s->d;
  660. jbg_set_default_l0(s);
  661. s->mx = 8;
  662. s->my = 0;
  663. s->order = JBG_ILEAVE | JBG_SMID;
  664. s->options = JBG_TPBON | JBG_TPDON | JBG_DPON;
  665. s->dppriv = jbg_dptable;
  666. s->res_tab = jbg_resred;
  667. s->highres = (int *) checked_malloc(planes, sizeof(int));
  668. s->lhp[0] = p;
  669. s->lhp[1] = (unsigned char **)
  670. checked_malloc(planes, sizeof(unsigned char *));
  671. for (i = 0; i < planes; i++) {
  672. s->highres[i] = 0;
  673. s->lhp[1][i] = (unsigned char *)
  674. checked_malloc(jbg_ceil_half(y, 1), jbg_ceil_half(x, 1+3));
  675. }
  676. s->free_list = NULL;
  677. s->s = (struct jbg_arenc_state *)
  678. checked_malloc(s->planes, sizeof(struct jbg_arenc_state));
  679. s->tx = (int *) checked_malloc(s->planes, sizeof(int));
  680. lx = jbg_ceil_half(x, 1);
  681. s->tp = (char *) checked_malloc(lx, sizeof(char));
  682. for (l = 0; l < lx; s->tp[l++] = 2);
  683. s->sde = NULL;
  684. return;
  685. }
  686. /*
  687. * This function selects the number of differential layers based on
  688. * the maximum size requested for the lowest resolution layer. If
  689. * possible, a number of differential layers is selected, which will
  690. * keep the size of the lowest resolution layer below or equal to the
  691. * given width x and height y. However not more than 6 differential
  692. * resolution layers will be used. In addition, a reasonable value for
  693. * l0 (height of one stripe in the lowest resolution layer) is
  694. * selected, which obeys the recommended limitations for l0 in annex A
  695. * and C of the JBIG standard. The selected number of resolution layers
  696. * is returned.
  697. */
  698. int jbg_enc_lrlmax(struct jbg_enc_state *s, unsigned long x,
  699. unsigned long y)
  700. {
  701. for (s->d = 0; s->d < 6; s->d++)
  702. if (jbg_ceil_half(s->xd, s->d) <= x && jbg_ceil_half(s->yd, s->d) <= y)
  703. break;
  704. s->dl = 0;
  705. s->dh = s->d;
  706. jbg_set_default_l0(s);
  707. return s->d;
  708. }
  709. /*
  710. * As an alternative to jbg_enc_lrlmax(), the following function allows
  711. * to specify the number of layers directly. The stripe height and layer
  712. * range is also adjusted automatically here.
  713. */
  714. void jbg_enc_layers(struct jbg_enc_state *s, int d)
  715. {
  716. if (d < 0 || d > 31)
  717. return;
  718. s->d = d;
  719. s->dl = 0;
  720. s->dh = s->d;
  721. jbg_set_default_l0(s);
  722. return;
  723. }
  724. /*
  725. * Specify the highest and lowest resolution layers which will be
  726. * written to the output file. Call this function not before
  727. * jbg_enc_layers() or jbg_enc_lrlmax(), because these two functions
  728. * reset the lowest and highest resolution layer to default values.
  729. * Negative values are ignored. The total number of layers is returned.
  730. */
  731. int jbg_enc_lrange(struct jbg_enc_state *s, int dl, int dh)
  732. {
  733. if (dl >= 0 && dl <= s->d) s->dl = dl;
  734. if (dh >= s->dl && dh <= s->d) s->dh = dh;
  735. return s->d;
  736. }
  737. /*
  738. * The following function allows to specify the bits describing the
  739. * options of the format as well as the maximum AT movement window and
  740. * the number of layer 0 lines per stripes.
  741. */
  742. void jbg_enc_options(struct jbg_enc_state *s, int order, int options,
  743. unsigned long l0, int mx, int my)
  744. {
  745. if (order >= 0 && order <= 0x0f) s->order = order;
  746. if (options >= 0) s->options = options;
  747. if (l0 > 0) s->l0 = l0;
  748. if (mx >= 0 && my < 128) s->mx = mx;
  749. if (my >= 0 && my < 256) s->my = my;
  750. return;
  751. }
  752. /*
  753. * This function actually does all the tricky work involved in producing
  754. * a SDE, which is stored in the appropriate s->sde[][][] element
  755. * for later output in the correct order.
  756. */
  757. static void encode_sde(struct jbg_enc_state *s,
  758. long stripe, int layer, int plane)
  759. {
  760. unsigned char *hp, *lp1, *lp2, *p0, *p1, *q1, *q2;
  761. unsigned long hl, ll, hx, hy, lx, ly, hbpl, lbpl;
  762. unsigned long line_h0 = 0, line_h1 = 0;
  763. unsigned long line_h2, line_h3, line_l1, line_l2, line_l3;
  764. struct jbg_arenc_state *se;
  765. unsigned long i, j, y;
  766. long o;
  767. unsigned a, p, t;
  768. int ltp, ltp_old, cx;
  769. unsigned long c_all, c[MX_MAX + 1], cmin, cmax, clmin, clmax;
  770. int tmax, at_determined;
  771. int new_tx;
  772. long new_tx_line = -1;
  773. struct jbg_buf *new_jbg_buf;
  774. #ifdef DEBUG
  775. static long tp_lines, tp_exceptions, tp_pixels, dp_pixels;
  776. static long encoded_pixels;
  777. #endif
  778. /* return immediately if this stripe has already been encoded */
  779. if (s->sde[stripe][layer][plane] != SDE_TODO)
  780. return;
  781. #ifdef DEBUG
  782. if (stripe == 0)
  783. tp_lines = tp_exceptions = tp_pixels = dp_pixels = encoded_pixels = 0;
  784. fprintf(stderr, "encode_sde: s/d/p = %2ld/%2d/%2d\n",
  785. stripe, layer, plane);
  786. #endif
  787. /* number of lines per stripe in highres image */
  788. hl = s->l0 << layer;
  789. /* number of lines per stripe in lowres image */
  790. ll = hl >> 1;
  791. /* current line number in highres image */
  792. y = stripe * hl;
  793. /* number of pixels in highres image */
  794. hx = jbg_ceil_half(s->xd, s->d - layer);
  795. hy = jbg_ceil_half(s->yd, s->d - layer);
  796. /* number of pixels in lowres image */
  797. lx = jbg_ceil_half(hx, 1);
  798. ly = jbg_ceil_half(hy, 1);
  799. /* bytes per line in highres and lowres image */
  800. hbpl = jbg_ceil_half(hx, 3);
  801. lbpl = jbg_ceil_half(lx, 3);
  802. /* pointer to first image byte of highres stripe */
  803. hp = s->lhp[s->highres[plane]][plane] + stripe * hl * hbpl;
  804. lp2 = s->lhp[1 - s->highres[plane]][plane] + stripe * ll * lbpl;
  805. lp1 = lp2 + lbpl;
  806. /* initialize arithmetic encoder */
  807. se = s->s + plane;
  808. arith_encode_init(se, stripe != 0);
  809. s->sde[stripe][layer][plane] = jbg_buf_init(&s->free_list);
  810. se->byte_out = jbg_buf_write;
  811. se->file = s->sde[stripe][layer][plane];
  812. /* initialize adaptive template movement algorithm */
  813. c_all = 0;
  814. for (t = 0; t <= s->mx; t++)
  815. c[t] = 0;
  816. if (stripe == 0)
  817. s->tx[plane] = 0;
  818. new_tx = -1;
  819. at_determined = 0; /* we haven't yet decided the template move */
  820. if (s->mx == 0)
  821. at_determined = 1;
  822. /* initialize typical prediction */
  823. ltp = 0;
  824. if (stripe == 0)
  825. ltp_old = 0;
  826. else {
  827. ltp_old = 1;
  828. p1 = hp - hbpl;
  829. if (y > 1) {
  830. q1 = p1 - hbpl;
  831. while (p1 < hp && (ltp_old = (*p1++ == *q1++)) != 0);
  832. } else
  833. while (p1 < hp && (ltp_old = (*p1++ == 0)) != 0);
  834. }
  835. if (layer == 0) {
  836. /*
  837. * Encode lowest resolution layer
  838. */
  839. for (i = 0; i < hl && y < hy; i++, y++) {
  840. /* check whether it is worth to perform an ATMOVE */
  841. if (!at_determined && c_all > 2048) {
  842. cmin = clmin = 0xffffffffL;
  843. cmax = clmax = 0;
  844. tmax = 0;
  845. for (t = (s->options & JBG_LRLTWO) ? 5 : 3; t <= s->mx; t++) {
  846. if (c[t] > cmax) cmax = c[t];
  847. if (c[t] < cmin) cmin = c[t];
  848. if (c[t] > c[tmax]) tmax = t;
  849. }
  850. clmin = (c[0] < cmin) ? c[0] : cmin;
  851. clmax = (c[0] > cmax) ? c[0] : cmax;
  852. if (c_all - cmax < (c_all >> 3) &&
  853. cmax - c[s->tx[plane]] > c_all - cmax &&
  854. cmax - c[s->tx[plane]] > (c_all >> 4) &&
  855. /* ^ T.82 said < here, fixed in Cor.1/25 */
  856. cmax - (c_all - c[s->tx[plane]]) > c_all - cmax &&
  857. cmax - (c_all - c[s->tx[plane]]) > (c_all >> 4) &&
  858. cmax - cmin > (c_all >> 2) &&
  859. (s->tx[plane] || clmax - clmin > (c_all >> 3))) {
  860. /* we have decided to perform an ATMOVE */
  861. new_tx = tmax;
  862. if (!(s->options & JBG_DELAY_AT)) {
  863. new_tx_line = i;
  864. s->tx[plane] = new_tx;
  865. }
  866. #ifdef DEBUG
  867. fprintf(stderr, "ATMOVE: line=%ld, tx=%d, c_all=%ld\n",
  868. i, new_tx, c_all);
  869. #endif
  870. }
  871. at_determined = 1;
  872. }
  873. assert(s->tx[plane] >= 0); /* i.e., tx can safely be cast to unsigned */
  874. /* typical prediction */
  875. if (s->options & JBG_TPBON) {
  876. ltp = 1;
  877. p1 = hp;
  878. if (y > 0) {
  879. q1 = hp - hbpl;
  880. while (q1 < hp && (ltp = (*p1++ == *q1++)) != 0);
  881. } else
  882. while (p1 < hp + hbpl && (ltp = (*p1++ == 0)) != 0);
  883. arith_encode(se, (s->options & JBG_LRLTWO) ? TPB2CX : TPB3CX,
  884. ltp == ltp_old);
  885. #ifdef DEBUG
  886. tp_lines += ltp;
  887. #endif
  888. ltp_old = ltp;
  889. if (ltp) {
  890. /* skip next line */
  891. hp += hbpl;
  892. continue;
  893. }
  894. }
  895. /*
  896. * Layout of the variables line_h1, line_h2, line_h3, which contain
  897. * as bits the neighbour pixels of the currently coded pixel X:
  898. *
  899. * 76543210765432107654321076543210 line_h3
  900. * 76543210765432107654321076543210 line_h2
  901. * 76543210765432107654321X76543210 line_h1
  902. */
  903. line_h1 = line_h2 = line_h3 = 0;
  904. if (y > 0) line_h2 = (long)*(hp - hbpl) << 8;
  905. if (y > 1) line_h3 = (long)*(hp - hbpl - hbpl) << 8;
  906. /* encode line */
  907. for (j = 0; j < hx; hp++) {
  908. line_h1 |= *hp;
  909. if (j < hbpl * 8 - 8 && y > 0) {
  910. line_h2 |= *(hp - hbpl + 1);
  911. if (y > 1)
  912. line_h3 |= *(hp - hbpl - hbpl + 1);
  913. }
  914. if (s->options & JBG_LRLTWO) {
  915. /* two line template */
  916. do {
  917. line_h1 <<= 1; line_h2 <<= 1; line_h3 <<= 1;
  918. if (s->tx[plane]) {
  919. if ((unsigned) s->tx[plane] > j)
  920. a = 0;
  921. else {
  922. o = (j - s->tx[plane]) - (j & ~7L);
  923. a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
  924. a <<= 4;
  925. }
  926. assert(s->tx[plane] > 23 ||
  927. a == ((line_h1 >> (4 + s->tx[plane])) & 0x010));
  928. arith_encode(se, (((line_h2 >> 10) & 0x3e0) | a |
  929. ((line_h1 >> 9) & 0x00f)),
  930. (line_h1 >> 8) & 1);
  931. }
  932. else
  933. arith_encode(se, (((line_h2 >> 10) & 0x3f0) |
  934. ((line_h1 >> 9) & 0x00f)),
  935. (line_h1 >> 8) & 1);
  936. #ifdef DEBUG
  937. encoded_pixels++;
  938. #endif
  939. /* statistics for adaptive template changes */
  940. if (!at_determined && j >= s->mx && j < hx-2) {
  941. p = (line_h1 & 0x100) != 0; /* current pixel value */
  942. c[0] += ((unsigned int)((line_h2 & 0x4000) != 0)) == p; /* default position */
  943. assert(!(((line_h2 >> 6) ^ line_h1) & 0x100) ==
  944. (((line_h2 & 0x4000) != 0) == p));
  945. for (t = 5; t <= s->mx && t <= j; t++) {
  946. o = (j - t) - (j & ~7L);
  947. a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
  948. assert(t > 23 ||
  949. (a == p) == !(((line_h1 >> t) ^ line_h1) & 0x100));
  950. c[t] += a == p;
  951. }
  952. for (; t <= s->mx; t++) {
  953. c[t] += 0 == p;
  954. }
  955. ++c_all;
  956. }
  957. } while (++j & 7 && j < hx);
  958. } else {
  959. /* three line template */
  960. do {
  961. line_h1 <<= 1; line_h2 <<= 1; line_h3 <<= 1;
  962. if (s->tx[plane]) {
  963. if ((unsigned) s->tx[plane] > j)
  964. a = 0;
  965. else {
  966. o = (j - s->tx[plane]) - (j & ~7L);
  967. a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
  968. a <<= 2;
  969. }
  970. assert(s->tx[plane] > 23 ||
  971. a == ((line_h1 >> (6 + s->tx[plane])) & 0x004));
  972. arith_encode(se, (((line_h3 >> 8) & 0x380) |
  973. ((line_h2 >> 12) & 0x078) | a |
  974. ((line_h1 >> 9) & 0x003)),
  975. (line_h1 >> 8) & 1);
  976. } else
  977. arith_encode(se, (((line_h3 >> 8) & 0x380) |
  978. ((line_h2 >> 12) & 0x07c) |
  979. ((line_h1 >> 9) & 0x003)),
  980. (line_h1 >> 8) & 1);
  981. #ifdef DEBUG
  982. encoded_pixels++;
  983. #endif
  984. /* statistics for adaptive template changes */
  985. if (!at_determined && j >= s->mx && j < hx-2) {
  986. p = (line_h1 & 0x100) != 0; /* current pixel value */
  987. c[0] += ((unsigned int)((line_h2 & 0x4000) != 0)) == p; /* default position */
  988. assert(!(((line_h2 >> 6) ^ line_h1) & 0x100) ==
  989. (((line_h2 & 0x4000) != 0) == p));
  990. for (t = 3; t <= s->mx && t <= j; t++) {
  991. o = (j - t) - (j & ~7L);
  992. a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
  993. assert(t > 23 ||
  994. (a == p) == !(((line_h1 >> t) ^ line_h1) & 0x100));
  995. c[t] += a == p;
  996. }
  997. for (; t <= s->mx; t++) {
  998. c[t] += 0 == p;
  999. }
  1000. ++c_all;
  1001. }
  1002. } while (++j & 7 && j < hx);
  1003. } /* if (s->options & JBG_LRLTWO) */
  1004. } /* for (j = ...) */
  1005. } /* for (i = ...) */
  1006. } else {
  1007. /*
  1008. * Encode differential layer
  1009. */
  1010. for (i = 0; i < hl && y < hy; i++, y++) {
  1011. /* check whether it is worth to perform an ATMOVE */
  1012. if (!at_determined && c_all > 2048) {
  1013. cmin = clmin = 0xffffffffL;
  1014. cmax = clmax = 0;
  1015. tmax = 0;
  1016. for (t = 3; t <= s->mx; t++) {
  1017. if (c[t] > cmax) cmax = c[t];
  1018. if (c[t] < cmin) cmin = c[t];
  1019. if (c[t] > c[tmax]) tmax = t;
  1020. }
  1021. clmin = (c[0] < cmin) ? c[0] : cmin;
  1022. clmax = (c[0] > cmax) ? c[0] : cmax;
  1023. if (c_all - cmax < (c_all >> 3) &&
  1024. cmax - c[s->tx[plane]] > c_all - cmax &&
  1025. cmax - c[s->tx[plane]] > (c_all >> 4) &&
  1026. /* ^ T.82 said < here, fixed in Cor.1/25 */
  1027. cmax - (c_all - c[s->tx[plane]]) > c_all - cmax &&
  1028. cmax - (c_all - c[s->tx[plane]]) > (c_all >> 4) &&
  1029. cmax - cmin > (c_all >> 2) &&
  1030. (s->tx[plane] || clmax - clmin > (c_all >> 3))) {
  1031. /* we have decided to perform an ATMOVE */
  1032. new_tx = tmax;
  1033. if (!(s->options & JBG_DELAY_AT)) {
  1034. new_tx_line = i;
  1035. s->tx[plane] = new_tx;
  1036. }
  1037. #ifdef DEBUG
  1038. fprintf(stderr, "ATMOVE: line=%ld, tx=%d, c_all=%ld\n",
  1039. i, new_tx, c_all);
  1040. #endif
  1041. }
  1042. at_determined = 1;
  1043. }
  1044. if ((i >> 1) >= ll - 1 || (y >> 1) >= ly - 1)
  1045. lp1 = lp2;
  1046. /* typical prediction */
  1047. if (s->options & JBG_TPDON && (i & 1) == 0) {
  1048. q1 = lp1; q2 = lp2;
  1049. p0 = p1 = hp;
  1050. if (i < hl - 1 && y < hy - 1)
  1051. p0 = hp + hbpl;
  1052. if (y > 1)
  1053. line_l3 = (long)*(q2 - lbpl) << 8;
  1054. else
  1055. line_l3 = 0;
  1056. line_l2 = (long)*q2 << 8;
  1057. line_l1 = (long)*q1 << 8;
  1058. ltp = 1;
  1059. for (j = 0; j < lx && ltp; q1++, q2++) {
  1060. if (j < lbpl * 8 - 8) {
  1061. if (y > 1)
  1062. line_l3 |= *(q2 - lbpl + 1);
  1063. line_l2 |= *(q2 + 1);
  1064. line_l1 |= *(q1 + 1);
  1065. }
  1066. do {
  1067. if ((j >> 2) < hbpl) {
  1068. line_h1 = *(p1++);
  1069. line_h0 = *(p0++);
  1070. }
  1071. do {
  1072. line_l3 <<= 1;
  1073. line_l2 <<= 1;
  1074. line_l1 <<= 1;
  1075. line_h1 <<= 2;
  1076. line_h0 <<= 2;
  1077. cx = (((line_l3 >> 15) & 0x007) |
  1078. ((line_l2 >> 12) & 0x038) |
  1079. ((line_l1 >> 9) & 0x1c0));
  1080. if (cx == 0x000)
  1081. if ((line_h1 & 0x300) == 0 && (line_h0 & 0x300) == 0)
  1082. s->tp[j] = 0;
  1083. else {
  1084. ltp = 0;
  1085. #ifdef DEBUG
  1086. tp_exceptions++;
  1087. #endif
  1088. }
  1089. else if (cx == 0x1ff)
  1090. if ((line_h1 & 0x300) == 0x300 && (line_h0 & 0x300) == 0x300)
  1091. s->tp[j] = 1;
  1092. else {
  1093. ltp = 0;
  1094. #ifdef DEBUG
  1095. tp_exceptions++;
  1096. #endif
  1097. }
  1098. else
  1099. s->tp[j] = 2;
  1100. } while (++j & 3 && j < lx);
  1101. } while (j & 7 && j < lx);
  1102. } /* for (j = ...) */
  1103. arith_encode(se, TPDCX, !ltp);
  1104. #ifdef DEBUG
  1105. tp_lines += ltp;
  1106. #endif
  1107. }
  1108. /*
  1109. * Layout of the variables line_h1, line_h2, line_h3, which contain
  1110. * as bits the high resolution neighbour pixels of the currently coded
  1111. * highres pixel X:
  1112. *
  1113. * 76543210 76543210 76543210 76543210 line_h3
  1114. * 76543210 76543210 76543210 76543210 line_h2
  1115. * 76543210 76543210 7654321X 76543210 line_h1
  1116. *
  1117. * Layout of the variables line_l1, line_l2, line_l3, which contain
  1118. * the low resolution pixels near the currently coded pixel as bits.
  1119. * The lowres pixel in which the currently coded highres pixel is
  1120. * located is marked as Y:
  1121. *
  1122. * 76543210 76543210 76543210 76543210 line_l3
  1123. * 76543210 7654321Y 76543210 76543210 line_l2
  1124. * 76543210 76543210 76543210 76543210 line_l1
  1125. */
  1126. line_h1 = line_h2 = line_h3 = line_l1 = line_l2 = line_l3 = 0;
  1127. if (y > 0) line_h2 = (long)*(hp - hbpl) << 8;
  1128. if (y > 1) {
  1129. line_h3 = (long)*(hp - hbpl - hbpl) << 8;
  1130. line_l3 = (long)*(lp2 - lbpl) << 8;
  1131. }
  1132. line_l2 = (long)*lp2 << 8;
  1133. line_l1 = (long)*lp1 << 8;
  1134. /* encode line */
  1135. for (j = 0; j < hx; lp1++, lp2++) {
  1136. if ((j >> 1) < lbpl * 8 - 8) {
  1137. if (y > 1)
  1138. line_l3 |= *(lp2 - lbpl + 1);
  1139. line_l2 |= *(lp2 + 1);
  1140. line_l1 |= *(lp1 + 1);
  1141. }
  1142. do { /* ... while (j & 15 && j < hx) */
  1143. assert(hp - (s->lhp[s->highres[plane]][plane] +
  1144. (stripe * hl + i) * hbpl)
  1145. == (ptrdiff_t) j >> 3);
  1146. assert(lp2 - (s->lhp[1-s->highres[plane]][plane] +
  1147. (stripe * ll + (i>>1)) * lbpl)
  1148. == (ptrdiff_t) j >> 4);
  1149. line_h1 |= *hp;
  1150. if (j < hbpl * 8 - 8) {
  1151. if (y > 0) {
  1152. line_h2 |= *(hp - hbpl + 1);
  1153. if (y > 1)
  1154. line_h3 |= *(hp - hbpl - hbpl + 1);
  1155. }
  1156. }
  1157. do { /* ... while (j & 7 && j < hx) */
  1158. line_l1 <<= 1; line_l2 <<= 1; line_l3 <<= 1;
  1159. if (ltp && s->tp[j >> 1] < 2) {
  1160. /* pixel are typical and have not to be encoded */
  1161. line_h1 <<= 2; line_h2 <<= 2; line_h3 <<= 2;
  1162. #ifdef DEBUG
  1163. do {
  1164. ++tp_pixels;
  1165. } while (++j & 1 && j < hx);
  1166. #else
  1167. j += 2;
  1168. #endif
  1169. } else
  1170. do { /* ... while (++j & 1 && j < hx) */
  1171. line_h1 <<= 1; line_h2 <<= 1; line_h3 <<= 1;
  1172. /* deterministic prediction */
  1173. if (s->options & JBG_DPON) {
  1174. if ((y & 1) == 0) {
  1175. if ((j & 1) == 0) {
  1176. /* phase 0 */
  1177. if (s->dppriv[((line_l3 >> 16) & 0x003) |
  1178. ((line_l2 >> 14) & 0x00c) |
  1179. ((line_h1 >> 5) & 0x010) |
  1180. ((line_h2 >> 10) & 0x0e0)] < 2) {
  1181. #ifdef DEBUG
  1182. ++dp_pixels;
  1183. #endif
  1184. continue;
  1185. }
  1186. } else {
  1187. /* phase 1 */
  1188. if (s->dppriv[(((line_l3 >> 16) & 0x003) |
  1189. ((line_l2 >> 14) & 0x00c) |
  1190. ((line_h1 >> 5) & 0x030) |
  1191. ((line_h2 >> 10) & 0x1c0)) + 256] < 2) {
  1192. #ifdef DEBUG
  1193. ++dp_pixels;
  1194. #endif
  1195. continue;
  1196. }
  1197. }
  1198. } else {
  1199. if ((j & 1) == 0) {
  1200. /* phase 2 */
  1201. if (s->dppriv[(((line_l3 >> 16) & 0x003) |
  1202. ((line_l2 >> 14) & 0x00c) |
  1203. ((line_h1 >> 5) & 0x010) |
  1204. ((line_h2 >> 10) & 0x0e0) |
  1205. ((line_h3 >> 7) & 0x700)) + 768] < 2) {
  1206. #ifdef DEBUG
  1207. ++dp_pixels;
  1208. #endif
  1209. continue;
  1210. }
  1211. } else {
  1212. /* phase 3 */
  1213. if (s->dppriv[(((line_l3 >> 16) & 0x003) |
  1214. ((line_l2 >> 14) & 0x00c) |
  1215. ((line_h1 >> 5) & 0x030) |
  1216. ((line_h2 >> 10) & 0x1c0) |
  1217. ((line_h3 >> 7) & 0xe00)) + 2816] < 2) {
  1218. #ifdef DEBUG
  1219. ++dp_pixels;
  1220. #endif
  1221. continue;
  1222. }
  1223. }
  1224. }
  1225. }
  1226. /* determine context */
  1227. if (s->tx[plane]) {
  1228. if ((unsigned) s->tx[plane] > j)
  1229. a = 0;
  1230. else {
  1231. o = (j - s->tx[plane]) - (j & ~7L);
  1232. a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
  1233. a <<= 4;
  1234. }
  1235. assert(s->tx[plane] > 23 ||
  1236. a == ((line_h1 >> (4 + s->tx[plane])) & 0x010));
  1237. cx = (((line_h1 >> 9) & 0x003) | a |
  1238. ((line_h2 >> 13) & 0x00c) |
  1239. ((line_h3 >> 11) & 0x020));
  1240. } else
  1241. cx = (((line_h1 >> 9) & 0x003) |
  1242. ((line_h2 >> 13) & 0x01c) |
  1243. ((line_h3 >> 11) & 0x020));
  1244. if (j & 1)
  1245. cx |= (((line_l2 >> 9) & 0x0c0) |
  1246. ((line_l1 >> 7) & 0x300)) | (1UL << 10);
  1247. else
  1248. cx |= (((line_l2 >> 10) & 0x0c0) |
  1249. ((line_l1 >> 8) & 0x300));
  1250. cx |= (y & 1) << 11;
  1251. arith_encode(se, cx, (line_h1 >> 8) & 1);
  1252. #ifdef DEBUG
  1253. encoded_pixels++;
  1254. #endif
  1255. /* statistics for adaptive template changes */
  1256. if (!at_determined && j >= s->mx) {
  1257. c[0] += !(((line_h2 >> 6) ^ line_h1) & 0x100);
  1258. for (t = 3; t <= s->mx; t++)
  1259. c[t] += !(((line_h1 >> t) ^ line_h1) & 0x100);
  1260. ++c_all;
  1261. }
  1262. } while (++j & 1 && j < hx);
  1263. } while (j & 7 && j < hx);
  1264. hp++;
  1265. } while (j & 15 && j < hx);
  1266. } /* for (j = ...) */
  1267. /* low resolution pixels are used twice */
  1268. if ((i & 1) == 0) {
  1269. lp1 -= lbpl;
  1270. lp2 -= lbpl;
  1271. }
  1272. } /* for (i = ...) */
  1273. }
  1274. arith_encode_flush(se);
  1275. jbg_buf_remove_zeros(s->sde[stripe][layer][plane]);
  1276. jbg_buf_write(MARKER_ESC, s->sde[stripe][layer][plane]);
  1277. jbg_buf_write(MARKER_SDNORM, s->sde[stripe][layer][plane]);
  1278. /* add ATMOVE */
  1279. if (new_tx != -1) {
  1280. if (s->options & JBG_DELAY_AT) {
  1281. /* ATMOVE will become active at the first line of the next stripe */
  1282. s->tx[plane] = new_tx;
  1283. jbg_buf_write(MARKER_ESC, s->sde[stripe][layer][plane]);
  1284. jbg_buf_write(MARKER_ATMOVE, s->sde[stripe][layer][plane]);
  1285. jbg_buf_write(0, s->sde[stripe][layer][plane]);
  1286. jbg_buf_write(0, s->sde[stripe][layer][plane]);
  1287. jbg_buf_write(0, s->sde[stripe][layer][plane]);
  1288. jbg_buf_write(0, s->sde[stripe][layer][plane]);
  1289. jbg_buf_write(s->tx[plane], s->sde[stripe][layer][plane]);
  1290. jbg_buf_write(0, s->sde[stripe][layer][plane]);
  1291. } else {
  1292. /* ATMOVE has already become active during this stripe
  1293. * => we have to prefix the SDE data with an ATMOVE marker */
  1294. new_jbg_buf = jbg_buf_init(&s->free_list);
  1295. jbg_buf_write(MARKER_ESC, new_jbg_buf);
  1296. jbg_buf_write(MARKER_ATMOVE, new_jbg_buf);
  1297. jbg_buf_write((new_tx_line >> 24) & 0xff, new_jbg_buf);
  1298. jbg_buf_write((new_tx_line >> 16) & 0xff, new_jbg_buf);
  1299. jbg_buf_write((new_tx_line >> 8) & 0xff, new_jbg_buf);
  1300. jbg_buf_write(new_tx_line & 0xff, new_jbg_buf);
  1301. jbg_buf_write(new_tx, new_jbg_buf);
  1302. jbg_buf_write(0, new_jbg_buf);
  1303. jbg_buf_prefix(new_jbg_buf, &s->sde[stripe][layer][plane]);
  1304. }
  1305. }
  1306. #if 0
  1307. if (stripe == s->stripes - 1)
  1308. fprintf(stderr, "tp_lines = %ld, tp_exceptions = %ld, tp_pixels = %ld, "
  1309. "dp_pixels = %ld, encoded_pixels = %ld\n",
  1310. tp_lines, tp_exceptions, tp_pixels, dp_pixels, encoded_pixels);
  1311. #endif
  1312. return;
  1313. }
  1314. /*
  1315. * Create the next lower resolution version of an image
  1316. */
  1317. static void resolution_reduction(struct jbg_enc_state *s, int plane,
  1318. int higher_layer)
  1319. {
  1320. unsigned long hx, hy, lx, ly, hbpl, lbpl;
  1321. unsigned char *hp1, *hp2, *hp3, *lp;
  1322. unsigned long line_h1, line_h2, line_h3, line_l2;
  1323. unsigned long i, j;
  1324. int pix, k, l;
  1325. /* number of pixels in highres image */
  1326. hx = jbg_ceil_half(s->xd, s->d - higher_layer);
  1327. hy = jbg_ceil_half(s->yd, s->d - higher_layer);
  1328. /* number of pixels in lowres image */
  1329. lx = jbg_ceil_half(hx, 1);
  1330. ly = jbg_ceil_half(hy, 1);
  1331. /* bytes per line in highres and lowres image */
  1332. hbpl = jbg_ceil_half(hx, 3);
  1333. lbpl = jbg_ceil_half(lx, 3);
  1334. /* pointers to first image bytes */
  1335. hp2 = s->lhp[s->highres[plane]][plane];
  1336. hp1 = hp2 + hbpl;
  1337. hp3 = hp2 - hbpl;
  1338. lp = s->lhp[1 - s->highres[plane]][plane];
  1339. #ifdef DEBUG
  1340. fprintf(stderr, "resolution_reduction: plane = %d, higher_layer = %d\n",
  1341. plane, higher_layer);
  1342. #endif
  1343. /*
  1344. * Layout of the variables line_h1, line_h2, line_h3, which contain
  1345. * as bits the high resolution neighbour pixels of the currently coded
  1346. * lowres pixel /\:
  1347. * \/
  1348. *
  1349. * 76543210 76543210 76543210 76543210 line_h3
  1350. * 76543210 76543210 765432/\ 76543210 line_h2
  1351. * 76543210 76543210 765432\/ 76543210 line_h1
  1352. *
  1353. * Layout of the variable line_l2, which contains the low resolution
  1354. * pixels near the currently coded pixel as bits. The lowres pixel
  1355. * which is currently coded is marked as X:
  1356. *
  1357. * 76543210 76543210 76543210 76543210 line_l2
  1358. * X
  1359. */
  1360. for (i = 0; i < ly; i++) {
  1361. if (2*i + 1 >= hy)
  1362. hp1 = hp2;
  1363. pix = 0;
  1364. line_h1 = line_h2 = line_h3 = line_l2 = 0;
  1365. for (j = 0; j < lbpl * 8; j += 8) {
  1366. *lp = 0;
  1367. line_l2 |= i ? *(lp-lbpl) : 0;
  1368. for (k = 0; k < 8 && j + k < lx; k += 4) {
  1369. if (((j + k) >> 2) < hbpl) {
  1370. line_h3 |= i ? *hp3 : 0;
  1371. ++hp3;
  1372. line_h2 |= *(hp2++);
  1373. line_h1 |= *(hp1++);
  1374. }
  1375. for (l = 0; l < 4 && j + k + l < lx; l++) {
  1376. line_h3 <<= 2;
  1377. line_h2 <<= 2;
  1378. line_h1 <<= 2;
  1379. line_l2 <<= 1;
  1380. pix = s->res_tab[((line_h1 >> 8) & 0x007) |
  1381. ((line_h2 >> 5) & 0x038) |
  1382. ((line_h3 >> 2) & 0x1c0) |
  1383. (pix << 9) | ((line_l2 << 2) & 0xc00)];
  1384. *lp = (*lp << 1) | pix;
  1385. }
  1386. }
  1387. ++lp;
  1388. }
  1389. *(lp - 1) <<= lbpl * 8 - lx;
  1390. hp1 += hbpl;
  1391. hp2 += hbpl;
  1392. hp3 += hbpl;
  1393. }
  1394. #ifdef DEBUG
  1395. {
  1396. FILE *f;
  1397. char fn[50];
  1398. sprintf(fn, "dbg_d=%02d.pbm", higher_layer - 1);
  1399. f = fopen(fn, "wb");
  1400. fprintf(f, "P4\n%lu %lu\n", lx, ly);
  1401. fwrite(s->lhp[1 - s->highres[plane]][plane], 1, lbpl * ly, f);
  1402. fclose(f);
  1403. }
  1404. #endif
  1405. return;
  1406. }
  1407. /*
  1408. * This function is called inside the three loops of jbg_enc_out() in
  1409. * order to write the next SDE. It has first to generate the required
  1410. * SDE and all SDEs which have to be encoded before this SDE can be
  1411. * created. The problem here is that if we want to output a lower
  1412. * resolution layer, we have to allpy the resolution reduction
  1413. * algorithm in order to get it. As we try to safe as much memory as
  1414. * possible, the resolution reduction will overwrite previous higher
  1415. * resolution bitmaps. Consequently, we have to encode and buffer SDEs
  1416. * which depend on higher resolution layers before we can start the
  1417. * resolution reduction. All this logic about which SDE has to be
  1418. * encoded before resolution reduction is allowed is handled here.
  1419. * This approach might be a little bit more complex than alternative
  1420. * ways to do it, but it allows us to do the encoding with the minimal
  1421. * possible amount of temporary memory.
  1422. */
  1423. static void output_sde(struct jbg_enc_state *s,
  1424. unsigned long stripe, int layer, int plane)
  1425. {
  1426. int lfcl; /* lowest fully coded layer */
  1427. long i;
  1428. unsigned long u;
  1429. assert(s->sde[stripe][layer][plane] != SDE_DONE);
  1430. if (s->sde[stripe][layer][plane] != SDE_TODO) {
  1431. #ifdef DEBUG
  1432. fprintf(stderr, "writing SDE: s/d/p = %2lu/%2d/%2d\n",
  1433. stripe, layer, plane);
  1434. #endif
  1435. jbg_buf_output(&s->sde[stripe][layer][plane], s->data_out, s->file);
  1436. s->sde[stripe][layer][plane] = SDE_DONE;
  1437. return;
  1438. }
  1439. /* Determine the smallest resolution layer in this plane for which
  1440. * not yet all stripes have been encoded into SDEs. This layer will
  1441. * have to be completely coded, before we can apply the next
  1442. * resolution reduction step. */
  1443. lfcl = 0;
  1444. for (i = s->d; i >= 0; i--)
  1445. if (s->sde[s->stripes - 1][i][plane] == SDE_TODO) {
  1446. lfcl = i + 1;
  1447. break;
  1448. }
  1449. if (lfcl > s->d && s->d > 0 && stripe == 0) {
  1450. /* perform the first resolution reduction */
  1451. resolution_reduction(s, plane, s->d);
  1452. }
  1453. /* In case HITOLO is not used, we have to encode and store the higher
  1454. * resolution layers first, although we do not need them right now. */
  1455. while (lfcl - 1 > layer) {
  1456. for (u = 0; u < s->stripes; u++)
  1457. encode_sde(s, u, lfcl - 1, plane);
  1458. --lfcl;
  1459. s->highres[plane] ^= 1;
  1460. if (lfcl > 1)
  1461. resolution_reduction(s, plane, lfcl - 1);
  1462. }
  1463. encode_sde(s, stripe, layer, plane);
  1464. #ifdef DEBUG
  1465. fprintf(stderr, "writing SDE: s/d/p = %2lu/%2d/%2d\n", stripe, layer, plane);
  1466. #endif
  1467. jbg_buf_output(&s->sde[stripe][layer][plane], s->data_out, s->file);
  1468. s->sde[stripe][layer][plane] = SDE_DONE;
  1469. if (stripe == s->stripes - 1 && layer > 0 &&
  1470. s->sde[0][layer-1][plane] == SDE_TODO) {
  1471. s->highres[plane] ^= 1;
  1472. if (layer > 1)
  1473. resolution_reduction(s, plane, layer - 1);
  1474. }
  1475. return;
  1476. }
  1477. /*
  1478. * Convert the table which controls the deterministic prediction
  1479. * process from the internal format into the representation required
  1480. * for the 1728 byte long DPTABLE element of a BIH.
  1481. *
  1482. * The bit order of the DPTABLE format (see also ITU-T T.82 figure 13) is
  1483. *
  1484. * high res: 4 5 6 low res: 0 1
  1485. * 7 8 9 2 3
  1486. * 10 11 12
  1487. *
  1488. * were 4 table entries are packed into one byte, while we here use
  1489. * internally an unpacked 6912 byte long table indexed by the following
  1490. * bit order:
  1491. *
  1492. * high res: 7 6 5 high res: 8 7 6 low res: 1 0
  1493. * (phase 0) 4 . . (phase 1) 5 4 . 3 2
  1494. * . . . . . .
  1495. *
  1496. * high res: 10 9 8 high res: 11 10 9
  1497. * (phase 2) 7 6 5 (phase 3) 8 7 6
  1498. * 4 . . 5 4 .
  1499. */
  1500. void jbg_int2dppriv(unsigned char *dptable, const char *internal)
  1501. {
  1502. int i, j, k;
  1503. int trans0[ 8] = { 1, 0, 3, 2, 7, 6, 5, 4 };
  1504. int trans1[ 9] = { 1, 0, 3, 2, 8, 7, 6, 5, 4 };
  1505. int trans2[11] = { 1, 0, 3, 2, 10, 9, 8, 7, 6, 5, 4 };
  1506. int trans3[12] = { 1, 0, 3, 2, 11, 10, 9, 8, 7, 6, 5, 4 };
  1507. for (i = 0; i < 1728; dptable[i++] = 0);
  1508. #define FILL_TABLE1(offset, len, trans) \
  1509. for (i = 0; i < len; i++) { \
  1510. k = 0; \
  1511. for (j = 0; j < 8; j++) \
  1512. k |= ((i >> j) & 1) << trans[j]; \
  1513. dptable[(i + offset) >> 2] |= \
  1514. (internal[k + offset] & 3) << ((3 - (i&3)) << 1); \
  1515. }
  1516. FILL_TABLE1( 0, 256, trans0);
  1517. FILL_TABLE1( 256, 512, trans1);
  1518. FILL_TABLE1( 768, 2048, trans2);
  1519. FILL_TABLE1(2816, 4096, trans3);
  1520. return;
  1521. }
  1522. /*
  1523. * Convert the table which controls the deterministic prediction
  1524. * process from the 1728 byte long DPTABLE format into the 6912 byte long
  1525. * internal format.
  1526. */
  1527. void jbg_dppriv2int(char *internal, const unsigned char *dptable)
  1528. {
  1529. int i, j, k;
  1530. int trans0[ 8] = { 1, 0, 3, 2, 7, 6, 5, 4 };
  1531. int trans1[ 9] = { 1, 0, 3, 2, 8, 7, 6, 5, 4 };
  1532. int trans2[11] = { 1, 0, 3, 2, 10, 9, 8, 7, 6, 5,

Large files files are truncated, but you can click here to view the full file