PageRenderTime 62ms CodeModel.GetById 16ms 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
  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, 4 };
  1533. int trans3[12] = { 1, 0, 3, 2, 11, 10, 9, 8, 7, 6, 5, 4 };
  1534. #define FILL_TABLE2(offset, len, trans) \
  1535. for (i = 0; i < len; i++) { \
  1536. k = 0; \
  1537. for (j = 0; j < 8; j++) \
  1538. k |= ((i >> j) & 1) << trans[j]; \
  1539. internal[k + offset] = \
  1540. (dptable[(i + offset) >> 2] >> ((3 - (i & 3)) << 1)) & 3; \
  1541. }
  1542. FILL_TABLE2( 0, 256, trans0);
  1543. FILL_TABLE2( 256, 512, trans1);
  1544. FILL_TABLE2( 768, 2048, trans2);
  1545. FILL_TABLE2(2816, 4096, trans3);
  1546. return;
  1547. }
  1548. /*
  1549. * Encode one full BIE and pass the generated data to the specified
  1550. * call-back function
  1551. */
  1552. void jbg_enc_out(struct jbg_enc_state *s)
  1553. {
  1554. unsigned long bpl;
  1555. unsigned char buf[20];
  1556. unsigned long xd, yd, y;
  1557. long ii[3], is[3], ie[3]; /* generic variables for the 3 nested loops */
  1558. unsigned long stripe;
  1559. int layer, plane;
  1560. int order;
  1561. unsigned char dpbuf[1728];
  1562. extern char jbg_dptable[];
  1563. /* some sanity checks */
  1564. s->order &= JBG_HITOLO | JBG_SEQ | JBG_ILEAVE | JBG_SMID;
  1565. order = s->order & (JBG_SEQ | JBG_ILEAVE | JBG_SMID);
  1566. if (iindex[order][0] < 0)
  1567. s->order = order = JBG_SMID | JBG_ILEAVE;
  1568. if (s->options & JBG_DPON && s->dppriv != jbg_dptable)
  1569. s->options |= JBG_DPPRIV;
  1570. if (s->mx > MX_MAX)
  1571. s->mx = MX_MAX;
  1572. s->my = 0;
  1573. if (s->mx && s->mx < ((s->options & JBG_LRLTWO) ? 5U : 3U))
  1574. s->mx = 0;
  1575. if (s->d > 255 || s->d < 0 || s->dh > s->d || s->dh < 0 ||
  1576. s->dl < 0 || s->dl > s->dh || s->planes < 0 || s->planes > 255)
  1577. return;
  1578. /* prevent uint32 overflow: s->l0 * 2 ^ s->d < 2 ^ 32 */
  1579. if (s->d > 31 || (s->d != 0 && s->l0 >= (1UL << (32 - s->d))))
  1580. return;
  1581. if (s->yd1 < s->yd)
  1582. s->yd1 = s->yd;
  1583. if (s->yd1 > s->yd)
  1584. s->options |= JBG_VLENGTH;
  1585. /* ensure correct zero padding of bitmap at the final byte of each line */
  1586. if (s->xd & 7) {
  1587. bpl = jbg_ceil_half(s->xd, 3); /* bytes per line */
  1588. for (plane = 0; plane < s->planes; plane++)
  1589. for (y = 0; y < s->yd; y++)
  1590. s->lhp[0][plane][y * bpl + bpl - 1] &= ~((1 << (8 - (s->xd & 7))) - 1);
  1591. }
  1592. /* prepare BIH */
  1593. buf[0] = s->dl;
  1594. buf[1] = s->dh;
  1595. buf[2] = s->planes;
  1596. buf[3] = 0;
  1597. xd = jbg_ceil_half(s->xd, s->d - s->dh);
  1598. yd = jbg_ceil_half(s->yd1, s->d - s->dh);
  1599. buf[4] = (unsigned char)(xd >> 24);
  1600. buf[5] = (unsigned char)((xd >> 16) & 0xff);
  1601. buf[6] = (unsigned char)((xd >> 8) & 0xff);
  1602. buf[7] = (unsigned char)(xd & 0xff);
  1603. buf[8] = (unsigned char)(yd >> 24);
  1604. buf[9] = (unsigned char)((yd >> 16) & 0xff);
  1605. buf[10] = (unsigned char)((yd >> 8) & 0xff);
  1606. buf[11] = (unsigned char)(yd & 0xff);
  1607. buf[12] = (unsigned char)(s->l0 >> 24);
  1608. buf[13] = (unsigned char)((s->l0 >> 16) & 0xff);
  1609. buf[14] = (unsigned char)((s->l0 >> 8) & 0xff);
  1610. buf[15] = (unsigned char)(s->l0 & 0xff);
  1611. buf[16] = (unsigned char)(s->mx);
  1612. buf[17] = (unsigned char)(s->my);
  1613. buf[18] = (unsigned char)(s->order);
  1614. buf[19] = (unsigned char)(s->options & 0x7f);
  1615. #if 0
  1616. /* sanitize L0 (if it was set to 0xffffffff for T.85-style NEWLEN tests) */
  1617. if (s->l0 > (s->yd >> s->d))
  1618. s->l0 = s->yd >> s->d;
  1619. #endif
  1620. /* calculate number of stripes that will be required */
  1621. s->stripes = jbg_stripes(s->l0, s->yd, s->d);
  1622. /* allocate buffers for SDE pointers */
  1623. if (s->sde == NULL) {
  1624. s->sde = (struct jbg_buf ****)
  1625. checked_malloc(s->stripes, sizeof(struct jbg_buf ***));
  1626. for (stripe = 0; stripe < s->stripes; stripe++) {
  1627. s->sde[stripe] = (struct jbg_buf ***)
  1628. checked_malloc(s->d + 1, sizeof(struct jbg_buf **));
  1629. for (layer = 0; layer < s->d + 1; layer++) {
  1630. s->sde[stripe][layer] = (struct jbg_buf **)
  1631. checked_malloc(s->planes, sizeof(struct jbg_buf *));
  1632. for (plane = 0; plane < s->planes; plane++)
  1633. s->sde[stripe][layer][plane] = SDE_TODO;
  1634. }
  1635. }
  1636. }
  1637. /* output BIH */
  1638. s->data_out(buf, 20, s->file);
  1639. if ((s->options & (JBG_DPON | JBG_DPPRIV | JBG_DPLAST)) ==
  1640. (JBG_DPON | JBG_DPPRIV)) {
  1641. /* write private table */
  1642. jbg_int2dppriv(dpbuf, s->dppriv);
  1643. s->data_out(dpbuf, 1728, s->file);
  1644. }
  1645. #if 0
  1646. /*
  1647. * Encode everything first. This is a simple-minded alternative to
  1648. * all the tricky on-demand encoding logic in output_sde() for
  1649. * debugging purposes.
  1650. */
  1651. for (layer = s->dh; layer >= s->dl; layer--) {
  1652. for (plane = 0; plane < s->planes; plane++) {
  1653. if (layer > 0)
  1654. resolution_reduction(s, plane, layer);
  1655. for (stripe = 0; stripe < s->stripes; stripe++)
  1656. encode_sde(s, stripe, layer, plane);
  1657. s->highres[plane] ^= 1;
  1658. }
  1659. }
  1660. #endif
  1661. /*
  1662. * Generic loops over all SDEs. Which loop represents layer, plane and
  1663. * stripe depends on the option flags.
  1664. */
  1665. /* start and end value vor each loop */
  1666. is[iindex[order][STRIPE]] = 0;
  1667. ie[iindex[order][STRIPE]] = s->stripes - 1;
  1668. is[iindex[order][LAYER]] = s->dl;
  1669. ie[iindex[order][LAYER]] = s->dh;
  1670. is[iindex[order][PLANE]] = 0;
  1671. ie[iindex[order][PLANE]] = s->planes - 1;
  1672. for (ii[0] = is[0]; ii[0] <= ie[0]; ii[0]++)
  1673. for (ii[1] = is[1]; ii[1] <= ie[1]; ii[1]++)
  1674. for (ii[2] = is[2]; ii[2] <= ie[2]; ii[2]++) {
  1675. stripe = ii[iindex[order][STRIPE]];
  1676. if (s->order & JBG_HITOLO)
  1677. layer = s->dh - (ii[iindex[order][LAYER]] - s->dl);
  1678. else
  1679. layer = ii[iindex[order][LAYER]];
  1680. plane = ii[iindex[order][PLANE]];
  1681. output_sde(s, stripe, layer, plane);
  1682. /*
  1683. * When we generate a NEWLEN test case (s->yd1 > s->yd), output
  1684. * NEWLEN after last stripe if we have only a single
  1685. * resolution layer or plane (see ITU-T T.85 profile), otherwise
  1686. * output NEWLEN before last stripe.
  1687. */
  1688. if (s->yd1 > s->yd &&
  1689. (stripe == s->stripes - 1 ||
  1690. (stripe == s->stripes - 2 &&
  1691. (s->dl != s->dh || s->planes > 1)))) {
  1692. s->yd1 = s->yd;
  1693. yd = jbg_ceil_half(s->yd, s->d - s->dh);
  1694. buf[0] = MARKER_ESC;
  1695. buf[1] = MARKER_NEWLEN;
  1696. buf[2] = (unsigned char)(yd >> 24);
  1697. buf[3] = (unsigned char)((yd >> 16) & 0xff);
  1698. buf[4] = (unsigned char)((yd >> 8) & 0xff);
  1699. buf[5] = (unsigned char)(yd & 0xff);
  1700. s->data_out(buf, 6, s->file);
  1701. #ifdef DEBUG
  1702. fprintf(stderr, "NEWLEN: yd=%lu\n", yd);
  1703. #endif
  1704. if (stripe == s->stripes - 1) {
  1705. buf[1] = MARKER_SDNORM;
  1706. s->data_out(buf, 2, s->file);
  1707. }
  1708. }
  1709. }
  1710. return;
  1711. }
  1712. void jbg_enc_free(struct jbg_enc_state *s)
  1713. {
  1714. unsigned long stripe;
  1715. int layer, plane;
  1716. #ifdef DEBUG
  1717. fprintf(stderr, "jbg_enc_free(%p)\n", (void *) s);
  1718. #endif
  1719. /* clear buffers for SDEs */
  1720. if (s->sde) {
  1721. for (stripe = 0; stripe < s->stripes; stripe++) {
  1722. for (layer = 0; layer < s->d + 1; layer++) {
  1723. for (plane = 0; plane < s->planes; plane++)
  1724. if (s->sde[stripe][layer][plane] != SDE_DONE &&
  1725. s->sde[stripe][layer][plane] != SDE_TODO)
  1726. jbg_buf_free(&s->sde[stripe][layer][plane]);
  1727. checked_free(s->sde[stripe][layer]);
  1728. }
  1729. checked_free(s->sde[stripe]);
  1730. }
  1731. checked_free(s->sde);
  1732. }
  1733. /* clear free_list */
  1734. jbg_buf_free(&s->free_list);
  1735. /* clear memory for arithmetic encoder states */
  1736. checked_free(s->s);
  1737. /* clear memory for differential-layer typical prediction buffer */
  1738. checked_free(s->tp);
  1739. /* clear memory for adaptive template pixel offsets */
  1740. checked_free(s->tx);
  1741. /* clear lowres image buffers */
  1742. if (s->lhp[1]) {
  1743. for (plane = 0; plane < s->planes; plane++)
  1744. checked_free(s->lhp[1][plane]);
  1745. checked_free(s->lhp[1]);
  1746. }
  1747. /* clear buffer for index of highres image in lhp */
  1748. checked_free(s->highres);
  1749. return;
  1750. }
  1751. /*
  1752. * Convert the error codes used by jbg_dec_in() into a string
  1753. * written in the selected language and character set.
  1754. */
  1755. const char *jbg_strerror(int errnum, int language)
  1756. {
  1757. if (errnum < 0 || errnum >= NEMSG)
  1758. return "Unknown error code passed to jbg_strerror()";
  1759. if (language < 0 || language >= NEMSG_LANG)
  1760. return "Unknown language code passed to jbg_strerror()";
  1761. return errmsg[language][errnum];
  1762. }
  1763. /*
  1764. * The constructor for a decoder
  1765. */
  1766. void jbg_dec_init(struct jbg_dec_state *s)
  1767. {
  1768. s->order = 0;
  1769. s->d = -1;
  1770. s->bie_len = 0;
  1771. s->buf_len = 0;
  1772. s->dppriv = NULL;
  1773. s->xmax = 4294967295UL;
  1774. s->ymax = 4294967295UL;
  1775. s->dmax = 256;
  1776. s->s = NULL;
  1777. return;
  1778. }
  1779. /*
  1780. * Specify a maximum image size for the decoder. If the JBIG file has
  1781. * the order bit ILEAVE, but not the bit SEQ set, then the decoder
  1782. * will abort to decode after the image has reached the maximal
  1783. * resolution layer which is still not wider than xmax or higher than
  1784. * ymax.
  1785. */
  1786. void jbg_dec_maxsize(struct jbg_dec_state *s, unsigned long xmax,
  1787. unsigned long ymax)
  1788. {
  1789. if (xmax > 0) s->xmax = xmax;
  1790. if (ymax > 0) s->ymax = ymax;
  1791. return;
  1792. }
  1793. /*
  1794. * Decode the new len PSDC bytes to which data points and add them to
  1795. * the current stripe. Return the number of bytes which have actually
  1796. * been read (this will be less than len if a marker segment was
  1797. * part of the data or if the final byte was 0xff were this code
  1798. * can not determine, whether we have a marker segment.
  1799. */
  1800. static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
  1801. size_t len)
  1802. {
  1803. unsigned long stripe;
  1804. unsigned int layer, plane;
  1805. unsigned long hl, ll, y, hx, hy, lx, ly, hbpl, lbpl;
  1806. unsigned char *hp, *lp1, *lp2, *p1, *q1;
  1807. register unsigned long line_h1, line_h2, line_h3;
  1808. register unsigned long line_l1, line_l2, line_l3;
  1809. struct jbg_ardec_state *se;
  1810. unsigned long x;
  1811. long o;
  1812. unsigned a;
  1813. int n;
  1814. int pix, cx = 0, slntp, tx;
  1815. /* SDE loop variables */
  1816. stripe = s->ii[iindex[s->order & 7][STRIPE]];
  1817. layer = s->ii[iindex[s->order & 7][LAYER]];
  1818. plane = s->ii[iindex[s->order & 7][PLANE]];
  1819. /* forward data to arithmetic decoder */
  1820. se = s->s[plane] + layer - s->dl;
  1821. se->pscd_ptr = data;
  1822. se->pscd_end = data + len;
  1823. /* number of lines per stripe in highres image */
  1824. hl = s->l0 << layer;
  1825. /* number of lines per stripe in lowres image */
  1826. ll = hl >> 1;
  1827. /* current line number in highres image */
  1828. y = stripe * hl + s->i;
  1829. /* number of pixels in highres image */
  1830. hx = jbg_ceil_half(s->xd, s->d - layer);
  1831. hy = jbg_ceil_half(s->yd, s->d - layer);
  1832. /* number of pixels in lowres image */
  1833. lx = jbg_ceil_half(hx, 1);
  1834. ly = jbg_ceil_half(hy, 1);
  1835. /* bytes per line in highres and lowres image */
  1836. hbpl = jbg_ceil_half(hx, 3);
  1837. lbpl = jbg_ceil_half(lx, 3);
  1838. /* pointer to highres and lowres image bytes */
  1839. hp = s->lhp[ layer & 1][plane] + (stripe * hl + s->i) * hbpl +
  1840. (s->x >> 3);
  1841. lp2 = s->lhp[(layer-1) & 1][plane] + (stripe * ll + (s->i >> 1)) * lbpl +
  1842. (s->x >> 4);
  1843. lp1 = lp2 + lbpl;
  1844. /* restore a few local variables */
  1845. line_h1 = s->line_h1;
  1846. line_h2 = s->line_h2;
  1847. line_h3 = s->line_h3;
  1848. line_l1 = s->line_l1;
  1849. line_l2 = s->line_l2;
  1850. line_l3 = s->line_l3;
  1851. x = s->x;
  1852. if (s->x == 0 && s->i == 0 &&
  1853. (stripe == 0 || s->reset[plane][layer - s->dl])) {
  1854. s->tx[plane][layer - s->dl] = s->ty[plane][layer - s->dl] = 0;
  1855. if (s->pseudo)
  1856. s->lntp[plane][layer - s->dl] = 1;
  1857. }
  1858. #ifdef DEBUG
  1859. if (s->x == 0 && s->i == 0 && s->pseudo)
  1860. fprintf(stderr, "decode_pscd(%p, %p, %ld): s/d/p = %2lu/%2u/%2u\n",
  1861. (void *) s, (void *) data, (long) len, stripe, layer, plane);
  1862. #endif
  1863. if (layer == 0) {
  1864. /*
  1865. * Decode lowest resolution layer
  1866. */
  1867. for (; s->i < hl && y < hy; s->i++, y++) {
  1868. /* adaptive template changes */
  1869. if (x == 0)
  1870. for (n = 0; n < s->at_moves; n++)
  1871. if (s->at_line[n] == s->i) {
  1872. s->tx[plane][layer - s->dl] = s->at_tx[n];
  1873. s->ty[plane][layer - s->dl] = s->at_ty[n];
  1874. #ifdef DEBUG
  1875. fprintf(stderr, "ATMOVE: line=%lu, tx=%d, ty=%d.\n", s->i,
  1876. s->tx[plane][layer - s->dl], s->ty[plane][layer - s->dl]);
  1877. #endif
  1878. }
  1879. tx = s->tx[plane][layer - s->dl];
  1880. assert(tx >= 0); /* i.e., tx can safely be cast to unsigned */
  1881. /* typical prediction */
  1882. if (s->options & JBG_TPBON && s->pseudo) {
  1883. slntp = arith_decode(se, (s->options & JBG_LRLTWO) ? TPB2CX : TPB3CX);
  1884. if (se->result == JBG_MORE || se->result == JBG_MARKER)
  1885. goto leave;
  1886. s->lntp[plane][layer - s->dl] =
  1887. !(slntp ^ s->lntp[plane][layer - s->dl]);
  1888. if (s->lntp[plane][layer - s->dl]) {
  1889. /* this line is 'not typical' and has to be coded completely */
  1890. s->pseudo = 0;
  1891. } else {
  1892. /* this line is 'typical' (i.e. identical to the previous one) */
  1893. p1 = hp;
  1894. if (s->i == 0 && (stripe == 0 || s->reset[plane][layer - s->dl]))
  1895. while (p1 < hp + hbpl) *p1++ = 0;
  1896. else {
  1897. q1 = hp - hbpl;
  1898. while (q1 < hp) *p1++ = *q1++;
  1899. }
  1900. hp += hbpl;
  1901. continue;
  1902. }
  1903. }
  1904. /*
  1905. * Layout of the variables line_h1, line_h2, line_h3, which contain
  1906. * as bits the neighbour pixels of the currently decoded pixel X:
  1907. *
  1908. * 76543210 76543210 76543210 76543210 line_h3
  1909. * 76543210 76543210 76543210 76543210 line_h2
  1910. * 76543210 76543210 76543210 76543210 X line_h1
  1911. */
  1912. if (x == 0) {
  1913. line_h1 = line_h2 = line_h3 = 0;
  1914. if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl]))
  1915. line_h2 = (long)*(hp - hbpl) << 8;
  1916. if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
  1917. line_h3 = (long)*(hp - hbpl - hbpl) << 8;
  1918. }
  1919. /*
  1920. * Another tiny JBIG standard bug:
  1921. *
  1922. * While implementing the line_h3 handling here, I discovered
  1923. * another problem with the ITU-T T.82(1993 E) specification.
  1924. * This might be a somewhat pathological case, however. The
  1925. * standard is unclear about how a decoder should behave in the
  1926. * following situation:
  1927. *
  1928. * Assume we are in layer 0 and all stripes are single lines
  1929. * (L0=1 allowed by table 9). We are now decoding the first (and
  1930. * only) line of the third stripe. Assume, the first stripe was
  1931. * terminated by SDRST and the second stripe was terminated by
  1932. * SDNORM. While decoding the only line of the third stripe with
  1933. * the three-line template, we need access to pixels from the
  1934. * previous two stripes. We know that the previous stripe
  1935. * terminated with SDNROM, so we access the pixel from the
  1936. * second stripe. But do we have to replace the pixels from the
  1937. * first stripe by background pixels, because this stripe ended
  1938. * with SDRST? The standard, especially clause 6.2.5 does never
  1939. * mention this case, so the behaviour is undefined here. My
  1940. * current implementation remembers only the marker used to
  1941. * terminate the previous stripe. In the above example, the
  1942. * pixels of the first stripe are accessed despite the fact that
  1943. * this stripe ended with SDRST. An alternative (only slightly
  1944. * more complicated) implementation would be to remember the end
  1945. * marker (SDNORM or SDRST) of the previous two stripes in a
  1946. * plane/layer and to act accordingly when accessing the two
  1947. * previous lines. What am I supposed to do here?
  1948. *
  1949. * As the standard is unclear about the correct behaviour in the
  1950. * situation of the above example, I strongly suggest to avoid
  1951. * the following situation while encoding data with JBIG:
  1952. *
  1953. * LRLTWO = 0, L0=1 and both SDNORM and SDRST appear in layer 0.
  1954. *
  1955. * I guess that only a very few if any encoders will switch
  1956. * between SDNORM and SDRST, so let us hope that this ambiguity
  1957. * in the standard will never cause any interoperability
  1958. * problems.
  1959. *
  1960. * Markus Kuhn -- 1995-04-30
  1961. */
  1962. /* decode line */
  1963. while (x < hx) {
  1964. if ((x & 7) == 0) {
  1965. if (x < hbpl * 8 - 8 &&
  1966. (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl]))) {
  1967. line_h2 |= *(hp - hbpl + 1);
  1968. if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
  1969. line_h3 |= *(hp - hbpl - hbpl + 1);
  1970. }
  1971. }
  1972. if (s->options & JBG_LRLTWO) {
  1973. /* two line template */
  1974. do {
  1975. if (tx) {
  1976. if ((unsigned) tx > x)
  1977. a = 0;
  1978. else if (tx < 8)
  1979. a = ((line_h1 >> (tx - 5)) & 0x010);
  1980. else {
  1981. o = (x - tx) - (x & ~7L);
  1982. a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
  1983. a <<= 4;
  1984. }
  1985. assert(tx > 31 ||
  1986. a == ((line_h1 >> (tx - 5)) & 0x010));
  1987. pix = arith_decode(se, (((line_h2 >> 9) & 0x3e0) | a |
  1988. (line_h1 & 0x00f)));
  1989. } else
  1990. pix = arith_decode(se, (((line_h2 >> 9) & 0x3f0) |
  1991. (line_h1 & 0x00f)));
  1992. if (se->result == JBG_MORE || se->result == JBG_MARKER)
  1993. goto leave;
  1994. line_h1 = (line_h1 << 1) | pix;
  1995. line_h2 <<= 1;
  1996. } while ((++x & 7) && x < hx);
  1997. } else {
  1998. /* three line template */
  1999. do {
  2000. if (tx) {
  2001. if ((unsigned) tx > x)
  2002. a = 0;
  2003. else if (tx < 8)
  2004. a = ((line_h1 >> (tx - 3)) & 0x004);
  2005. else {
  2006. o = (x - tx) - (x & ~7L);
  2007. a = (hp[o >> 3] >> (7 - (o & 7))) & 1;
  2008. a <<= 2;
  2009. }
  2010. assert(tx > 31 ||
  2011. a == ((line_h1 >> (tx - 3)) & 0x004));
  2012. pix = arith_decode(se, (((line_h3 >> 7) & 0x380) |
  2013. ((line_h2 >> 11) & 0x078) | a |
  2014. (line_h1 & 0x003)));
  2015. } else
  2016. pix = arith_decode(se, (((line_h3 >> 7) & 0x380) |
  2017. ((line_h2 >> 11) & 0x07c) |
  2018. (line_h1 & 0x003)));
  2019. if (se->result == JBG_MORE || se->result == JBG_MARKER)
  2020. goto leave;
  2021. line_h1 = (line_h1 << 1) | pix;
  2022. line_h2 <<= 1;
  2023. line_h3 <<= 1;
  2024. } while ((++x & 7) && x < hx);
  2025. } /* if (s->options & JBG_LRLTWO) */
  2026. *hp++ = (unsigned char)(line_h1);
  2027. } /* while */
  2028. *(hp - 1) <<= hbpl * 8 - hx;
  2029. x = 0;
  2030. s->pseudo = 1;
  2031. } /* for (i = ...) */
  2032. } else {
  2033. /*
  2034. * Decode differential layer
  2035. */
  2036. for (; s->i < hl && y < hy; s->i++, y++) {
  2037. /* adaptive template changes */
  2038. if (x == 0)
  2039. for (n = 0; n < s->at_moves; n++)
  2040. if (s->at_line[n] == s->i) {
  2041. s->tx[plane][layer - s->dl] = s->at_tx[n];
  2042. s->ty[plane][layer - s->dl] = s->at_ty[n];
  2043. #ifdef DEBUG
  2044. fprintf(stderr, "ATMOVE: line=%lu, tx=%d, ty=%d.\n", s->i,
  2045. s->tx[plane][layer - s->dl], s->ty[plane][layer - s->dl]);
  2046. #endif
  2047. }
  2048. tx = s->tx[plane][layer - s->dl];
  2049. /* handle lower border of low-resolution image */
  2050. if ((s->i >> 1) >= ll - 1 || (y >> 1) >= ly - 1)
  2051. lp1 = lp2;
  2052. /* typical prediction */
  2053. if (s->options & JBG_TPDON && s->pseudo) {
  2054. s->lntp[plane][layer - s->dl] = arith_decode(se, TPDCX);
  2055. if (se->result == JBG_MORE || se->result == JBG_MARKER)
  2056. goto leave;
  2057. s->pseudo = 0;
  2058. }
  2059. /*
  2060. * Layout of the variables line_h1, line_h2, line_h3, which contain
  2061. * as bits the high resolution neighbour pixels of the currently
  2062. * decoded highres pixel X:
  2063. *
  2064. * 76543210 76543210 76543210 76543210 line_h3
  2065. * 76543210 76543210 76543210 76543210 line_h2
  2066. * 76543210 76543210 76543210 76543210 X line_h1
  2067. *
  2068. * Layout of the variables line_l1, line_l2, line_l3, which contain
  2069. * the low resolution pixels near the currently decoded pixel as bits.
  2070. * The lowres pixel in which the currently coded highres pixel is
  2071. * located is marked as Y:
  2072. *
  2073. * 76543210 76543210 76543210 76543210 line_l3
  2074. * 76543210 76543210 Y6543210 76543210 line_l2
  2075. * 76543210 76543210 76543210 76543210 line_l1
  2076. */
  2077. if (x == 0) {
  2078. line_h1 = line_h2 = line_h3 = line_l1 = line_l2 = line_l3 = 0;
  2079. if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl])) {
  2080. line_h2 = (long)*(hp - hbpl) << 8;
  2081. if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
  2082. line_h3 = (long)*(hp - hbpl - hbpl) << 8;
  2083. }
  2084. if (s->i > 1 || (y > 1 && !s->reset[plane][layer-s->dl]))
  2085. line_l3 = (long)*(lp2 - lbpl) << 8;
  2086. line_l2 = (long)*lp2 << 8;
  2087. line_l1 = (long)*lp1 << 8;
  2088. }
  2089. /* decode line */
  2090. while (x < hx) {
  2091. if ((x & 15) == 0)
  2092. if ((x >> 1) < lbpl * 8 - 8) {
  2093. line_l1 |= *(lp1 + 1);
  2094. line_l2 |= *(lp2 + 1);
  2095. if (s->i > 1 ||
  2096. (y > 1 && !s->reset[plane][layer - s->dl]))
  2097. line_l3 |= *(lp2 - lbpl + 1);
  2098. }
  2099. do {
  2100. assert(hp - (s->lhp[ layer &1][plane] + (stripe * hl + s->i)
  2101. * hbpl) == (ptrdiff_t) x >> 3);
  2102. assert(lp2 - (s->lhp[(layer-1) &1][plane] + (stripe * ll + (s->i>>1))
  2103. * lbpl) == (ptrdiff_t) x >> 4);
  2104. if ((x & 7) == 0)
  2105. if (x < hbpl * 8 - 8) {
  2106. if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl])) {
  2107. line_h2 |= *(hp + 1 - hbpl);
  2108. if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
  2109. line_h3 |= *(hp + 1 - hbpl - hbpl);
  2110. }
  2111. }
  2112. do {
  2113. if (!s->lntp[plane][layer - s->dl])
  2114. cx = (((line_l3 >> 14) & 0x007) |
  2115. ((line_l2 >> 11) & 0x038) |
  2116. ((line_l1 >> 8) & 0x1c0));
  2117. if (!s->lntp[plane][layer - s->dl] &&
  2118. (cx == 0x000 || cx == 0x1ff)) {
  2119. /* pixels are typical and have not to be decoded */
  2120. do {
  2121. line_h1 = (line_h1 << 1) | (cx & 1);
  2122. } while ((++x & 1) && x < hx);
  2123. line_h2 <<= 2; line_h3 <<= 2;
  2124. } else
  2125. do {
  2126. /* deterministic prediction */
  2127. if (s->options & JBG_DPON)
  2128. if ((y & 1) == 0)
  2129. if ((x & 1) == 0)
  2130. /* phase 0 */
  2131. pix = s->dppriv[((line_l3 >> 15) & 0x003) |
  2132. ((line_l2 >> 13) & 0x00c) |
  2133. ((line_h1 << 4) & 0x010) |
  2134. ((line_h2 >> 9) & 0x0e0)];
  2135. else
  2136. /* phase 1 */
  2137. pix = s->dppriv[(((line_l3 >> 15) & 0x003) |
  2138. ((line_l2 >> 13) & 0x00c) |
  2139. ((line_h1 << 4) & 0x030) |
  2140. ((line_h2 >> 9) & 0x1c0)) + 256];
  2141. else
  2142. if ((x & 1) == 0)
  2143. /* phase 2 */
  2144. pix = s->dppriv[(((line_l3 >> 15) & 0x003) |
  2145. ((line_l2 >> 13) & 0x00c) |
  2146. ((line_h1 << 4) & 0x010) |
  2147. ((line_h2 >> 9) & 0x0e0) |
  2148. ((line_h3 >> 6) & 0x700)) + 768];
  2149. else
  2150. /* phase 3 */
  2151. pix = s->dppriv[(((line_l3 >> 15) & 0x003) |
  2152. ((line_l2 >> 13) & 0x00c) |
  2153. ((line_h1 << 4) & 0x030) |
  2154. ((line_h2 >> 9) & 0x1c0) |
  2155. ((line_h3 >> 6) & 0xe00)) + 2816];
  2156. else
  2157. pix = 2;
  2158. if (pix & 2) {
  2159. if (tx)
  2160. cx = ((line_h1 & 0x003) |
  2161. (((line_h1 << 2) >> (tx - 3)) & 0x010) |
  2162. ((line_h2 >> 12) & 0x00c) |
  2163. ((line_h3 >> 10) & 0x020));
  2164. else
  2165. cx = ((line_h1 & 0x003) |
  2166. ((line_h2 >> 12) & 0x01c) |
  2167. ((line_h3 >> 10) & 0x020));
  2168. if (x & 1)
  2169. cx |= (((line_l2 >> 8) & 0x0c0) |
  2170. ((line_l1 >> 6) & 0x300)) | (1UL << 10);
  2171. else
  2172. cx |= (((line_l2 >> 9) & 0x0c0) |
  2173. ((line_l1 >> 7) & 0x300));
  2174. cx |= (y & 1) << 11;
  2175. pix = arith_decode(se, cx);
  2176. if (se->result == JBG_MORE || se->result == JBG_MARKER)
  2177. goto leave;
  2178. }
  2179. line_h1 = (line_h1 << 1) | pix;
  2180. line_h2 <<= 1;
  2181. line_h3 <<= 1;
  2182. } while ((++x & 1) && x < hx);
  2183. line_l1 <<= 1; line_l2 <<= 1; line_l3 <<= 1;
  2184. } while ((x & 7) && x < hx);
  2185. *hp++ = (unsigned char)(line_h1);
  2186. } while ((x & 15) && x < hx);
  2187. ++lp1;
  2188. ++lp2;
  2189. } /* while */
  2190. x = 0;
  2191. *(hp - 1) <<= hbpl * 8 - hx;
  2192. if ((s->i & 1) == 0) {
  2193. /* low resolution pixels are used twice */
  2194. lp1 -= lbpl;
  2195. lp2 -= lbpl;
  2196. } else
  2197. s->pseudo = 1;
  2198. } /* for (i = ...) */
  2199. }
  2200. leave:
  2201. /* save a few local variables */
  2202. s->line_h1 = line_h1;
  2203. s->line_h2 = line_h2;
  2204. s->line_h3 = line_h3;
  2205. s->line_l1 = line_l1;
  2206. s->line_l2 = line_l2;
  2207. s->line_l3 = line_l3;
  2208. s->x = x;
  2209. return se->pscd_ptr - data;
  2210. }
  2211. /*
  2212. * Provide a new BIE fragment to the decoder.
  2213. *
  2214. * If cnt is not NULL, then *cnt will contain after the call the
  2215. * number of actually read bytes. If the data was not complete, then
  2216. * the return value will be JBG_EAGAIN and *cnt == len. In case this
  2217. * function has returned with JBG_EOK, then it has reached the end of
  2218. * a BIE but it can be called again with data from the next BIE if
  2219. * there exists one in order to get to a higher resolution layer. In
  2220. * case the return value was JBG_EOK_INTR then this function can be
  2221. * called again with the rest of the BIE, because parsing the BIE has
  2222. * been interrupted by a jbg_dec_maxsize() specification. In both
  2223. * cases the remaining len - *cnt bytes of the previous block will
  2224. * have to passed to this function again (if len > *cnt). In case of
  2225. * any other return value than JBG_EOK, JBG_EOK_INTR or JBG_EAGAIN, a
  2226. * serious problem has occured and the only function you should call
  2227. * is jbg_dec_free() in order to remove the mess (and probably
  2228. * jbg_strerror() in order to find out what to tell the user).
  2229. */
  2230. int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
  2231. size_t *cnt)
  2232. {
  2233. int i, j, required_length;
  2234. unsigned long x, y;
  2235. unsigned long is[3], ie[3];
  2236. extern char jbg_dptable[];
  2237. size_t dummy_cnt;
  2238. if (!cnt) cnt = &dummy_cnt;
  2239. *cnt = 0;
  2240. if (len < 1) return JBG_EAGAIN;
  2241. /* read in 20-byte BIH */
  2242. if (s->bie_len < 20) {
  2243. while (s->bie_len < 20 && *cnt < len)
  2244. s->buffer[s->bie_len++] = data[(*cnt)++];
  2245. if (s->bie_len < 20)
  2246. return JBG_EAGAIN;
  2247. if (s->buffer[1] < s->buffer[0])
  2248. return JBG_EINVAL;
  2249. /* test whether this looks like a valid JBIG header at all */
  2250. if (s->buffer[3] != 0 || (s->buffer[18] & 0xf0) != 0 ||
  2251. (s->buffer[19] & 0x80) != 0)
  2252. return JBG_EINVAL;
  2253. if (s->buffer[0] != s->d + 1)
  2254. return JBG_ENOCONT;
  2255. s->dl = s->buffer[0];
  2256. s->d = s->buffer[1];
  2257. if (s->dl == 0)
  2258. s->planes = s->buffer[2];
  2259. else
  2260. if (s->planes != s->buffer[2])
  2261. return JBG_ENOCONT;
  2262. x = (((long) s->buffer[ 4] << 24) | ((long) s->buffer[ 5] << 16) |
  2263. ((long) s->buffer[ 6] << 8) | (long) s->buffer[ 7]);
  2264. y = (((long) s->buffer[ 8] << 24) | ((long) s->buffer[ 9] << 16) |
  2265. ((long) s->buffer[10] << 8) | (long) s->buffer[11]);
  2266. if (s->dl != 0 && ((s->xd << (s->d - s->dl + 1)) != x &&
  2267. (s->yd << (s->d - s->dl + 1)) != y))
  2268. return JBG_ENOCONT;
  2269. s->xd = x;
  2270. s->yd = y;
  2271. s->l0 = (((long) s->buffer[12] << 24) | ((long) s->buffer[13] << 16) |
  2272. ((long) s->buffer[14] << 8) | (long) s->buffer[15]);
  2273. /* ITU-T T.85 trick not directly supported by decoder; for full
  2274. * T.85 compatibility with respect to all NEWLEN marker scenarios,
  2275. * preprocess BIE with jbg_newlen() before passing it to the decoder. */
  2276. if (s->yd == 0xffffffff)
  2277. return JBG_EIMPL;
  2278. if (!s->planes || !s->xd || !s->yd || !s->l0)
  2279. return JBG_EINVAL;
  2280. /* prevent uint32 overflow: s->l0 * 2 ^ s->d < 2 ^ 32 */
  2281. if (s->d > 31 || (s->d != 0 && s->l0 >= (1UL << (32 - s->d))))
  2282. return JBG_EIMPL;
  2283. s->mx = s->buffer[16];
  2284. if (s->mx > 127)
  2285. return JBG_EINVAL;
  2286. s->my = s->buffer[17];
  2287. #if 0
  2288. if (s->my > 0)
  2289. return JBG_EIMPL;
  2290. #endif
  2291. s->order = s->buffer[18];
  2292. if (iindex[s->order & 7][0] < 0)
  2293. return JBG_EINVAL;
  2294. /* HITOLO and SEQ currently not yet implemented */
  2295. if (s->dl != s->d && (s->order & JBG_HITOLO || s->order & JBG_SEQ))
  2296. return JBG_EIMPL;
  2297. s->options = s->buffer[19];
  2298. /* calculate number of stripes that will be required */
  2299. s->stripes = jbg_stripes(s->l0, s->yd, s->d);
  2300. /* some initialization */
  2301. s->ii[iindex[s->order & 7][STRIPE]] = 0;
  2302. s->ii[iindex[s->order & 7][LAYER]] = s->dl;
  2303. s->ii[iindex[s->order & 7][PLANE]] = 0;
  2304. if (s->dl == 0) {
  2305. s->s = (struct jbg_ardec_state **)
  2306. checked_malloc(s->planes, sizeof(struct jbg_ardec_state *));
  2307. s->tx = (int **) checked_malloc(s->planes, sizeof(int *));
  2308. s->ty = (int **) checked_malloc(s->planes, sizeof(int *));
  2309. s->reset = (int **) checked_malloc(s->planes, sizeof(int *));
  2310. s->lntp = (int **) checked_malloc(s->planes, sizeof(int *));
  2311. s->lhp[0] = (unsigned char **)
  2312. checked_malloc(s->planes, sizeof(unsigned char *));
  2313. s->lhp[1] = (unsigned char **)
  2314. checked_malloc(s->planes, sizeof(unsigned char *));
  2315. for (i = 0; i < s->planes; i++) {
  2316. s->s[i] = (struct jbg_ardec_state *)
  2317. checked_malloc(s->d - s->dl + 1, sizeof(struct jbg_ardec_state));
  2318. s->tx[i] = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
  2319. s->ty[i] = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
  2320. s->reset[i] = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
  2321. s->lntp[i] = (int *) checked_malloc(s->d - s->dl + 1, sizeof(int));
  2322. s->lhp[ s->d & 1][i] = (unsigned char *)
  2323. checked_malloc(s->yd, jbg_ceil_half(s->xd, 3));
  2324. s->lhp[(s->d-1) & 1][i] = (unsigned char *)
  2325. checked_malloc(jbg_ceil_half(s->yd, 1), jbg_ceil_half(s->xd, 1+3));
  2326. }
  2327. } else {
  2328. for (i = 0; i < s->planes; i++) {
  2329. s->s[i] = (struct jbg_ardec_state *)
  2330. checked_realloc(s->s[i], s->d - s->dl + 1,
  2331. sizeof(struct jbg_ardec_state));
  2332. s->tx[i] = (int *) checked_realloc(s->tx[i],
  2333. s->d - s->dl + 1, sizeof(int));
  2334. s->ty[i] = (int *) checked_realloc(s->ty[i],
  2335. s->d - s->dl + 1, sizeof(int));
  2336. s->reset[i] = (int *) checked_realloc(s->reset[i],
  2337. s->d - s->dl + 1, sizeof(int));
  2338. s->lntp[i] = (int *) checked_realloc(s->lntp[i],
  2339. s->d - s->dl + 1, sizeof(int));
  2340. s->lhp[ s->d & 1][i] = (unsigned char *)
  2341. checked_realloc(s->lhp[ s->d & 1][i],
  2342. s->yd, jbg_ceil_half(s->xd, 3));
  2343. s->lhp[(s->d-1) & 1][i] = (unsigned char *)
  2344. checked_realloc(s->lhp[(s->d-1) & 1][i],
  2345. jbg_ceil_half(s->yd, 1), jbg_ceil_half(s->xd, 1+3));
  2346. }
  2347. }
  2348. for (i = 0; i < s->planes; i++)
  2349. for (j = 0; j <= s->d - s->dl; j++)
  2350. arith_decode_init(s->s[i] + j, 0);
  2351. if (s->dl == 0 || (s->options & JBG_DPON && !(s->options & JBG_DPPRIV)))
  2352. s->dppriv = jbg_dptable;
  2353. s->comment_skip = 0;
  2354. s->buf_len = 0;
  2355. s->x = 0;
  2356. s->i = 0;
  2357. s->pseudo = 1;
  2358. s->at_moves = 0;
  2359. }
  2360. /* read in DPTABLE */
  2361. if (s->bie_len < 20 + 1728 &&
  2362. (s->options & (JBG_DPON | JBG_DPPRIV | JBG_DPLAST)) ==
  2363. (JBG_DPON | JBG_DPPRIV)) {
  2364. assert(s->bie_len >= 20);
  2365. while (s->bie_len < 20 + 1728 && *cnt < len)
  2366. s->buffer[s->bie_len++ - 20] = data[(*cnt)++];
  2367. if (s->bie_len < 20 + 1728)
  2368. return JBG_EAGAIN;
  2369. if (!s->dppriv || s->dppriv == jbg_dptable)
  2370. s->dppriv = (char *) checked_malloc(1728, sizeof(char));
  2371. jbg_dppriv2int(s->dppriv, s->buffer);
  2372. }
  2373. /*
  2374. * BID processing loop
  2375. */
  2376. while (*cnt < len) {
  2377. /* process floating marker segments */
  2378. /* skip COMMENT contents */
  2379. if (s->comment_skip) {
  2380. if (s->comment_skip <= len - *cnt) {
  2381. *cnt += s->comment_skip;
  2382. s->comment_skip = 0;
  2383. } else {
  2384. s->comment_skip -= len - *cnt;
  2385. *cnt = len;
  2386. }
  2387. continue;
  2388. }
  2389. /* load complete marker segments into s->buffer for processing */
  2390. if (s->buf_len > 0) {
  2391. assert(s->buffer[0] == MARKER_ESC);
  2392. while (s->buf_len < 2 && *cnt < len)
  2393. s->buffer[s->buf_len++] = data[(*cnt)++];
  2394. if (s->buf_len < 2) continue;
  2395. switch (s->buffer[1]) {
  2396. case MARKER_COMMENT: required_length = 6; break;
  2397. case MARKER_ATMOVE: required_length = 8; break;
  2398. case MARKER_NEWLEN: required_length = 6; break;
  2399. case MARKER_ABORT:
  2400. case MARKER_SDNORM:
  2401. case MARKER_SDRST: required_length = 2; break;
  2402. case MARKER_STUFF:
  2403. /* forward stuffed 0xff to arithmetic decoder */
  2404. s->buf_len = 0;
  2405. decode_pscd(s, s->buffer, 2);
  2406. continue;
  2407. default:
  2408. return JBG_EMARKER;
  2409. }
  2410. while (s->buf_len < required_length && *cnt < len)
  2411. s->buffer[s->buf_len++] = data[(*cnt)++];
  2412. if (s->buf_len < required_length) continue;
  2413. /* now the buffer is filled with exactly one marker segment */
  2414. switch (s->buffer[1]) {
  2415. case MARKER_COMMENT:
  2416. s->comment_skip =
  2417. (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) |
  2418. ((long) s->buffer[4] << 8) | (long) s->buffer[5]);
  2419. break;
  2420. case MARKER_ATMOVE:
  2421. if (s->at_moves < JBG_ATMOVES_MAX) {
  2422. s->at_line[s->at_moves] =
  2423. (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) |
  2424. ((long) s->buffer[4] << 8) | (long) s->buffer[5]);
  2425. s->at_tx[s->at_moves] = (signed char) s->buffer[6];
  2426. s->at_ty[s->at_moves] = s->buffer[7];
  2427. if (s->at_tx[s->at_moves] < - (int) s->mx ||
  2428. s->at_tx[s->at_moves] > (int) s->mx ||
  2429. s->at_ty[s->at_moves] > (int) s->my ||
  2430. (s->at_ty[s->at_moves] == 0 && s->at_tx[s->at_moves] < 0))
  2431. return JBG_EINVAL;
  2432. if (s->at_ty[s->at_moves] != 0)
  2433. return JBG_EIMPL;
  2434. s->at_moves++;
  2435. } else
  2436. return JBG_EIMPL;
  2437. break;
  2438. case MARKER_NEWLEN:
  2439. y = (((long) s->buffer[2] << 24) | ((long) s->buffer[3] << 16) |
  2440. ((long) s->buffer[4] << 8) | (long) s->buffer[5]);
  2441. if (y > s->yd || !(s->options & JBG_VLENGTH))
  2442. return JBG_EINVAL;
  2443. s->yd = y;
  2444. /* calculate again number of stripes that will be required */
  2445. s->stripes = jbg_stripes(s->l0, s->yd, s->d);
  2446. break;
  2447. case MARKER_ABORT:
  2448. return JBG_EABORT;
  2449. case MARKER_SDNORM:
  2450. case MARKER_SDRST:
  2451. /* decode final pixels based on trailing zero bytes */
  2452. decode_pscd(s, s->buffer, 2);
  2453. arith_decode_init(s->s[s->ii[iindex[s->order & 7][PLANE]]] +
  2454. s->ii[iindex[s->order & 7][LAYER]] - s->dl,
  2455. s->ii[iindex[s->order & 7][STRIPE]] != s->stripes - 1
  2456. && s->buffer[1] != MARKER_SDRST);
  2457. s->reset[s->ii[iindex[s->order & 7][PLANE]]]
  2458. [s->ii[iindex[s->order & 7][LAYER]] - s->dl] =
  2459. (s->buffer[1] == MARKER_SDRST);
  2460. /* prepare for next SDE */
  2461. s->x = 0;
  2462. s->i = 0;
  2463. s->pseudo = 1;
  2464. s->at_moves = 0;
  2465. /* increment layer/stripe/plane loop variables */
  2466. /* start and end value for each loop: */
  2467. is[iindex[s->order & 7][STRIPE]] = 0;
  2468. ie[iindex[s->order & 7][STRIPE]] = s->stripes - 1;
  2469. is[iindex[s->order & 7][LAYER]] = s->dl;
  2470. ie[iindex[s->order & 7][LAYER]] = s->d;
  2471. is[iindex[s->order & 7][PLANE]] = 0;
  2472. ie[iindex[s->order & 7][PLANE]] = s->planes - 1;
  2473. i = 2; /* index to innermost loop */
  2474. do {
  2475. j = 0; /* carry flag */
  2476. if (++s->ii[i] > ie[i]) {
  2477. /* handling overflow of loop variable */
  2478. j = 1;
  2479. if (i > 0)
  2480. s->ii[i] = is[i];
  2481. }
  2482. } while (--i >= 0 && j);
  2483. s->buf_len = 0;
  2484. /* check whether this have been all SDEs */
  2485. if (j) {
  2486. #ifdef DEBUG
  2487. fprintf(stderr, "This was the final SDE in this BIE, "
  2488. "%d bytes left.\n", len - *cnt);
  2489. #endif
  2490. s->bie_len = 0;
  2491. return JBG_EOK;
  2492. }
  2493. /* check whether we have to abort because of xmax/ymax */
  2494. if (iindex[s->order & 7][LAYER] == 0 && i < 0) {
  2495. /* LAYER is the outermost loop and we have just gone to next layer */
  2496. if (jbg_ceil_half(s->xd, s->d - s->ii[0]) > s->xmax ||
  2497. jbg_ceil_half(s->yd, s->d - s->ii[0]) > s->ymax) {
  2498. s->xmax = 4294967295UL;
  2499. s->ymax = 4294967295UL;
  2500. return JBG_EOK_INTR;
  2501. }
  2502. if (s->ii[0] > (unsigned long) s->dmax) {
  2503. s->dmax = 256;
  2504. return JBG_EOK_INTR;
  2505. }
  2506. }
  2507. break;
  2508. }
  2509. s->buf_len = 0;
  2510. } else if (data[*cnt] == MARKER_ESC)
  2511. s->buffer[s->buf_len++] = data[(*cnt)++];
  2512. else {
  2513. /* we have found PSCD bytes */
  2514. *cnt += decode_pscd(s, data + *cnt, len - *cnt);
  2515. if (*cnt < len && data[*cnt] != 0xff) {
  2516. #ifdef DEBUG
  2517. fprintf(stderr, "PSCD was longer than expected, unread bytes "
  2518. "%02x %02x %02x %02x ...\n", data[*cnt], data[*cnt+1],
  2519. data[*cnt+2], data[*cnt+3]);
  2520. #endif
  2521. return JBG_EINVAL;
  2522. }
  2523. }
  2524. } /* of BID processing loop 'while (*cnt < len) ...' */
  2525. return JBG_EAGAIN;
  2526. }
  2527. /*
  2528. * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call this
  2529. * function in order to find out the width of the image.
  2530. */
  2531. long jbg_dec_getwidth(const struct jbg_dec_state *s)
  2532. {
  2533. if (s->d < 0)
  2534. return -1;
  2535. if (iindex[s->order & 7][LAYER] == 0) {
  2536. if (s->ii[0] < 1)
  2537. return -1;
  2538. else
  2539. return jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1));
  2540. }
  2541. return s->xd;
  2542. }
  2543. /*
  2544. * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call this
  2545. * function in order to find out the height of the image.
  2546. */
  2547. long jbg_dec_getheight(const struct jbg_dec_state *s)
  2548. {
  2549. if (s->d < 0)
  2550. return -1;
  2551. if (iindex[s->order & 7][LAYER] == 0) {
  2552. if (s->ii[0] < 1)
  2553. return -1;
  2554. else
  2555. return jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1));
  2556. }
  2557. return s->yd;
  2558. }
  2559. /*
  2560. * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call this
  2561. * function in order to get a pointer to the image.
  2562. */
  2563. unsigned char *jbg_dec_getimage(const struct jbg_dec_state *s, int plane)
  2564. {
  2565. if (s->d < 0)
  2566. return NULL;
  2567. if (iindex[s->order & 7][LAYER] == 0) {
  2568. if (s->ii[0] < 1)
  2569. return NULL;
  2570. else
  2571. return s->lhp[(s->ii[0] - 1) & 1][plane];
  2572. }
  2573. return s->lhp[s->d & 1][plane];
  2574. }
  2575. /*
  2576. * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call
  2577. * this function in order to find out the size in bytes of one
  2578. * bitplane of the image.
  2579. */
  2580. long jbg_dec_getsize(const struct jbg_dec_state *s)
  2581. {
  2582. if (s->d < 0)
  2583. return -1;
  2584. if (iindex[s->order & 7][LAYER] == 0) {
  2585. if (s->ii[0] < 1)
  2586. return -1;
  2587. else
  2588. return
  2589. jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1) + 3) *
  2590. jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1));
  2591. }
  2592. return jbg_ceil_half(s->xd, 3) * s->yd;
  2593. }
  2594. /*
  2595. * After jbg_dec_in() returned JBG_EOK or JBG_EOK_INTR, you can call
  2596. * this function in order to find out the size of the image that you
  2597. * can retrieve with jbg_merge_planes().
  2598. */
  2599. long jbg_dec_getsize_merged(const struct jbg_dec_state *s)
  2600. {
  2601. if (s->d < 0)
  2602. return -1;
  2603. if (iindex[s->order & 7][LAYER] == 0) {
  2604. if (s->ii[0] < 1)
  2605. return -1;
  2606. else
  2607. return
  2608. jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1)) *
  2609. jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1)) *
  2610. ((s->planes + 7) / 8);
  2611. }
  2612. return s->xd * s->yd * ((s->planes + 7) / 8);
  2613. }
  2614. /*
  2615. * The destructor function which releases any resources obtained by the
  2616. * other decoder functions.
  2617. */
  2618. void jbg_dec_free(struct jbg_dec_state *s)
  2619. {
  2620. int i;
  2621. extern char jbg_dptable[];
  2622. if (s->d < 0 || s->s == NULL)
  2623. return;
  2624. s->d = -2;
  2625. for (i = 0; i < s->planes; i++) {
  2626. checked_free(s->s[i]);
  2627. checked_free(s->tx[i]);
  2628. checked_free(s->ty[i]);
  2629. checked_free(s->reset[i]);
  2630. checked_free(s->lntp[i]);
  2631. checked_free(s->lhp[0][i]);
  2632. checked_free(s->lhp[1][i]);
  2633. }
  2634. checked_free(s->s);
  2635. checked_free(s->tx);
  2636. checked_free(s->ty);
  2637. checked_free(s->reset);
  2638. checked_free(s->lntp);
  2639. checked_free(s->lhp[0]);
  2640. checked_free(s->lhp[1]);
  2641. if (s->dppriv && s->dppriv != jbg_dptable)
  2642. checked_free(s->dppriv);
  2643. s->s = NULL;
  2644. return;
  2645. }
  2646. /*
  2647. * Split bigendian integer pixel field into separate bit planes. In the
  2648. * src array, every pixel is represented by a ((has_planes + 7) / 8) byte
  2649. * long word, most significant byte first. While has_planes describes
  2650. * the number of used bits per pixel in the source image, encode_plane
  2651. * is the number of most significant bits among those that we
  2652. * actually transfer to dest.
  2653. */
  2654. void jbg_split_planes(unsigned long x, unsigned long y, int has_planes,
  2655. int encode_planes,
  2656. const unsigned char *src, unsigned char **dest,
  2657. int use_graycode)
  2658. {
  2659. unsigned long bpl = jbg_ceil_half(x, 3); /* bytes per line in dest plane */
  2660. unsigned long line, i;
  2661. unsigned k = 8;
  2662. int p;
  2663. unsigned prev; /* previous *src byte shifted by 8 bit to the left */
  2664. register int bits, msb = has_planes - 1;
  2665. int bitno;
  2666. /* sanity checks */
  2667. if (encode_planes > has_planes)
  2668. encode_planes = has_planes;
  2669. use_graycode = use_graycode != 0 && encode_planes > 1;
  2670. for (p = 0; p < encode_planes; p++)
  2671. memset(dest[p], 0, bpl * y);
  2672. for (line = 0; line < y; line++) { /* lines loop */
  2673. for (i = 0; i * 8 < x; i++) { /* dest bytes loop */
  2674. for (k = 0; k < 8 && i * 8 + k < x; k++) { /* pixel loop */
  2675. prev = 0;
  2676. for (p = 0; p < encode_planes; p++) { /* bit planes loop */
  2677. /* calculate which bit in *src do we want */
  2678. bitno = (msb - p) & 7;
  2679. /* put this bit with its left neighbor right adjusted into bits */
  2680. bits = (prev | *src) >> bitno;
  2681. /* go to next *src byte, but keep old */
  2682. if (bitno == 0)
  2683. prev = *src++ << 8;
  2684. /* make space for inserting new bit */
  2685. dest[p][bpl * line + i] <<= 1;
  2686. /* insert bit, if requested apply Gray encoding */
  2687. dest[p][bpl * line + i] |= (bits ^ (use_graycode & (bits>>1))) & 1;
  2688. /*
  2689. * Theorem: Let b(n),...,b(1),b(0) be the digits of a
  2690. * binary word and let g(n),...,g(1),g(0) be the digits of the
  2691. * corresponding Gray code word, then g(i) = b(i) xor b(i+1).
  2692. */
  2693. }
  2694. /* skip unused *src bytes */
  2695. for (;p < has_planes; p++)
  2696. if (((msb - p) & 7) == 0)
  2697. src++;
  2698. }
  2699. }
  2700. for (p = 0; p < encode_planes; p++) /* right padding loop */
  2701. dest[p][bpl * (line + 1) - 1] <<= 8 - k;
  2702. }
  2703. return;
  2704. }
  2705. /*
  2706. * Merge the separate bit planes decoded by the JBIG decoder into an
  2707. * integer pixel field. This is essentially the counterpart to
  2708. * jbg_split_planes().
  2709. */
  2710. void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode,
  2711. void (*data_out)(unsigned char *start, size_t len,
  2712. void *file), void *file)
  2713. {
  2714. #define BUFLEN 4096
  2715. int bpp;
  2716. unsigned long bpl, line, i;
  2717. unsigned k = 8;
  2718. int p;
  2719. unsigned char buf[BUFLEN];
  2720. unsigned char *bp = buf;
  2721. unsigned char **src;
  2722. unsigned long x, y;
  2723. unsigned v;
  2724. /* sanity check */
  2725. use_graycode = use_graycode != 0;
  2726. x = jbg_dec_getwidth(s);
  2727. y = jbg_dec_getheight(s);
  2728. if (x <= 0 || y <= 0)
  2729. return;
  2730. bpp = (s->planes + 7) / 8; /* bytes per pixel in dest image */
  2731. bpl = jbg_ceil_half(x, 3); /* bytes per line in src plane */
  2732. if (iindex[s->order & 7][LAYER] == 0)
  2733. if (s->ii[0] < 1)
  2734. return;
  2735. else
  2736. src = s->lhp[(s->ii[0] - 1) & 1];
  2737. else
  2738. src = s->lhp[s->d & 1];
  2739. for (line = 0; line < y; line++) { /* lines loop */
  2740. for (i = 0; i * 8 < x; i++) { /* src bytes loop */
  2741. for (k = 0; k < 8 && i * 8 + k < x; k++) { /* pixel loop */
  2742. v = 0;
  2743. for (p = 0; p < s->planes;) { /* dest bytes loop */
  2744. do {
  2745. v = (v << 1) |
  2746. (((src[p][bpl * line + i] >> (7 - k)) & 1) ^
  2747. (use_graycode & v));
  2748. } while ((s->planes - ++p) & 7);
  2749. *bp++ = v;
  2750. if (bp - buf == BUFLEN) {
  2751. data_out(buf, BUFLEN, file);
  2752. bp = buf;
  2753. }
  2754. }
  2755. }
  2756. }
  2757. }
  2758. if (bp - buf > 0)
  2759. data_out(buf, bp - buf, file);
  2760. return;
  2761. }
  2762. /*
  2763. * Given a pointer p to the first byte of either a marker segment or a
  2764. * PSCD, as well as the length len of the remaining data, return
  2765. * either the pointer to the first byte of the next marker segment or
  2766. * PSCD, or p+len if this was the last one, or NULL if some error was
  2767. * encountered.
  2768. */
  2769. unsigned char *jbg_next_pscdms(unsigned char *p, size_t len)
  2770. {
  2771. unsigned char *pp;
  2772. unsigned long l;
  2773. if (len < 2)
  2774. return NULL;
  2775. if (p[0] != MARKER_ESC || p[1] == MARKER_STUFF) {
  2776. do {
  2777. while (p[0] == MARKER_ESC && p[1] == MARKER_STUFF) {
  2778. p += 2;
  2779. len -= 2;
  2780. if (len < 2) return NULL;
  2781. }
  2782. pp = (unsigned char *) memchr(p, MARKER_ESC, len - 1);
  2783. if (!pp) return NULL;
  2784. l = pp - p;
  2785. assert(l < len);
  2786. p += l;
  2787. len -= l;
  2788. } while (p[1] == MARKER_STUFF);
  2789. } else {
  2790. switch (p[1]) {
  2791. case MARKER_SDNORM:
  2792. case MARKER_SDRST:
  2793. case MARKER_ABORT:
  2794. return p + 2;
  2795. case MARKER_NEWLEN:
  2796. if (len < 6) return NULL;
  2797. return p + 6;
  2798. case MARKER_ATMOVE:
  2799. if (len < 8) return NULL;
  2800. return p + 8;
  2801. case MARKER_COMMENT:
  2802. if (len < 6) return NULL;
  2803. l = (((long) p[2] << 24) | ((long) p[3] << 16) |
  2804. ((long) p[4] << 8) | (long) p[5]);
  2805. if (len - 6 < l) return NULL;
  2806. return p + 6 + l;
  2807. default:
  2808. return NULL;
  2809. }
  2810. }
  2811. return p;
  2812. }
  2813. /*
  2814. * Scan a complete BIE for a NEWLEN marker segment, then read the new
  2815. * YD value found in it and use it to overwrite the one in the BIE
  2816. * header. Use this procedure if a BIE initially declares an
  2817. * unreasonably high provisional YD value (e.g., 0xffffffff) or
  2818. * depends on the fact that section 6.2.6.2 of ITU-T T.82 says that a
  2819. * NEWLEN marker segment "could refer to a line in the immediately
  2820. * preceding stripe due to an unexpected termination of the image or
  2821. * the use of only such stripe". ITU-T.85 explicitely suggests the
  2822. * use of this for fax machines that start transmission before having
  2823. * encountered the end of the page. None of this is necessary for
  2824. * BIEs produced by JBIG-KIT, which normally does not use NEWLEN.
  2825. */
  2826. int jbg_newlen(unsigned char *bie, size_t len)
  2827. {
  2828. unsigned char *p = bie + 20;
  2829. int i;
  2830. if (len < 20)
  2831. return JBG_EAGAIN;
  2832. if ((bie[19] & (JBG_DPON | JBG_DPPRIV | JBG_DPLAST))
  2833. == (JBG_DPON | JBG_DPPRIV))
  2834. p += 1728; /* skip DPTABLE */
  2835. if (p >= bie + len)
  2836. return JBG_EAGAIN;
  2837. while ((p = jbg_next_pscdms(p, len - (p - bie)))) {
  2838. if (p == bie + len)
  2839. return JBG_EOK;
  2840. else if (p[0] == MARKER_ESC)
  2841. switch (p[1]) {
  2842. case MARKER_NEWLEN:
  2843. /* overwrite YD in BIH with YD from NEWLEN */
  2844. for (i = 0; i < 4; i++) {
  2845. bie[8+i] = p[2+i];
  2846. }
  2847. return JBG_EOK;
  2848. case MARKER_ABORT:
  2849. return JBG_EABORT;
  2850. }
  2851. }
  2852. return JBG_EINVAL;
  2853. }