/src/FreeImage/Source/LibTIFF/tif_jpeg.c

https://bitbucket.org/cabalistic/ogredeps/ · C · 2078 lines · 1412 code · 219 blank · 447 comment · 300 complexity · 6eeffb4f0ce8ba5b5d9c37b7014cbbc4 MD5 · raw file

Large files are truncated click here to view the full file

  1. /* $Id: tif_jpeg.c,v 1.37 2011/04/10 17:14:09 drolon Exp $ */
  2. /*
  3. * Copyright (c) 1994-1997 Sam Leffler
  4. * Copyright (c) 1994-1997 Silicon Graphics, Inc.
  5. *
  6. * Permission to use, copy, modify, distribute, and sell this software and
  7. * its documentation for any purpose is hereby granted without fee, provided
  8. * that (i) the above copyright notices and this permission notice appear in
  9. * all copies of the software and related documentation, and (ii) the names of
  10. * Sam Leffler and Silicon Graphics may not be used in any advertising or
  11. * publicity relating to the software without the specific, prior written
  12. * permission of Sam Leffler and Silicon Graphics.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
  15. * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
  16. * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
  17. *
  18. * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
  19. * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
  20. * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  21. * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
  22. * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  23. * OF THIS SOFTWARE.
  24. */
  25. #define WIN32_LEAN_AND_MEAN
  26. #define VC_EXTRALEAN
  27. #include "tiffiop.h"
  28. #ifdef JPEG_SUPPORT
  29. /*
  30. * TIFF Library
  31. *
  32. * JPEG Compression support per TIFF Technical Note #2
  33. * (*not* per the original TIFF 6.0 spec).
  34. *
  35. * This file is simply an interface to the libjpeg library written by
  36. * the Independent JPEG Group. You need release 5 or later of the IJG
  37. * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
  38. *
  39. * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
  40. */
  41. #include <setjmp.h>
  42. int TIFFFillStrip(TIFF*, tstrip_t);
  43. int TIFFFillTile(TIFF*, ttile_t);
  44. /* We undefine FAR to avoid conflict with JPEG definition */
  45. #ifdef FAR
  46. #undef FAR
  47. #endif
  48. /*
  49. Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
  50. not defined. Unfortunately, the MinGW and Borland compilers include
  51. a typedef for INT32, which causes a conflict. MSVC does not include
  52. a conficting typedef given the headers which are included.
  53. */
  54. #if defined(__BORLANDC__) || defined(__MINGW32__)
  55. # define XMD_H 1
  56. #endif
  57. /*
  58. The windows RPCNDR.H file defines boolean, but defines it with the
  59. unsigned char size. You should compile JPEG library using appropriate
  60. definitions in jconfig.h header, but many users compile library in wrong
  61. way. That causes errors of the following type:
  62. "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
  63. caller expects 464"
  64. For such users we wil fix the problem here. See install.doc file from
  65. the JPEG library distribution for details.
  66. */
  67. /* Define "boolean" as unsigned char, not int, per Windows custom. */
  68. #if defined(WIN32) && !defined(__MINGW32__)
  69. # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  70. typedef unsigned char boolean;
  71. # endif
  72. # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  73. #endif
  74. #include "../LibJPEG/jpeglib.h"
  75. #include "../LibJPEG/jerror.h"
  76. /*
  77. * We are using width_in_blocks which is supposed to be private to
  78. * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
  79. * renamed this member to width_in_data_units. Since the header has
  80. * also renamed a define, use that unique define name in order to
  81. * detect the problem header and adjust to suit.
  82. */
  83. #if defined(D_MAX_DATA_UNITS_IN_MCU)
  84. #define width_in_blocks width_in_data_units
  85. #endif
  86. /*
  87. * On some machines it may be worthwhile to use _setjmp or sigsetjmp
  88. * in place of plain setjmp. These macros will make it easier.
  89. */
  90. #define SETJMP(jbuf) setjmp(jbuf)
  91. #define LONGJMP(jbuf,code) longjmp(jbuf,code)
  92. #define JMP_BUF jmp_buf
  93. typedef struct jpeg_destination_mgr jpeg_destination_mgr;
  94. typedef struct jpeg_source_mgr jpeg_source_mgr;
  95. typedef struct jpeg_error_mgr jpeg_error_mgr;
  96. /*
  97. * State block for each open TIFF file using
  98. * libjpeg to do JPEG compression/decompression.
  99. *
  100. * libjpeg's visible state is either a jpeg_compress_struct
  101. * or jpeg_decompress_struct depending on which way we
  102. * are going. comm can be used to refer to the fields
  103. * which are common to both.
  104. *
  105. * NB: cinfo is required to be the first member of JPEGState,
  106. * so we can safely cast JPEGState* -> jpeg_xxx_struct*
  107. * and vice versa!
  108. */
  109. typedef struct {
  110. union {
  111. struct jpeg_compress_struct c;
  112. struct jpeg_decompress_struct d;
  113. struct jpeg_common_struct comm;
  114. } cinfo; /* NB: must be first */
  115. int cinfo_initialized;
  116. jpeg_error_mgr err; /* libjpeg error manager */
  117. JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
  118. /*
  119. * The following two members could be a union, but
  120. * they're small enough that it's not worth the effort.
  121. */
  122. jpeg_destination_mgr dest; /* data dest for compression */
  123. jpeg_source_mgr src; /* data source for decompression */
  124. /* private state */
  125. TIFF* tif; /* back link needed by some code */
  126. uint16 photometric; /* copy of PhotometricInterpretation */
  127. uint16 h_sampling; /* luminance sampling factors */
  128. uint16 v_sampling;
  129. tsize_t bytesperline; /* decompressed bytes per scanline */
  130. /* pointers to intermediate buffers when processing downsampled data */
  131. JSAMPARRAY ds_buffer[MAX_COMPONENTS];
  132. int scancount; /* number of "scanlines" accumulated */
  133. int samplesperclump;
  134. TIFFVGetMethod vgetparent; /* super-class method */
  135. TIFFVSetMethod vsetparent; /* super-class method */
  136. TIFFPrintMethod printdir; /* super-class method */
  137. TIFFStripMethod defsparent; /* super-class method */
  138. TIFFTileMethod deftparent; /* super-class method */
  139. /* pseudo-tag fields */
  140. void* jpegtables; /* JPEGTables tag value, or NULL */
  141. uint32 jpegtables_length; /* number of bytes in same */
  142. int jpegquality; /* Compression quality level */
  143. int jpegcolormode; /* Auto RGB<=>YCbCr convert? */
  144. int jpegtablesmode; /* What to put in JPEGTables */
  145. int ycbcrsampling_fetched;
  146. uint32 recvparams; /* encoded Class 2 session params */
  147. char* subaddress; /* subaddress string */
  148. uint32 recvtime; /* time spent receiving (secs) */
  149. char* faxdcs; /* encoded fax parameters (DCS, Table 2/T.30) */
  150. } JPEGState;
  151. #define JState(tif) ((JPEGState*)(tif)->tif_data)
  152. static int JPEGDecode(TIFF*, tidata_t, tsize_t, tsample_t);
  153. static int JPEGDecodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
  154. static int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t);
  155. static int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
  156. static int JPEGInitializeLibJPEG( TIFF * tif,
  157. int force_encode, int force_decode );
  158. #define FIELD_JPEGTABLES (FIELD_CODEC+0)
  159. #define FIELD_RECVPARAMS (FIELD_CODEC+1)
  160. #define FIELD_SUBADDRESS (FIELD_CODEC+2)
  161. #define FIELD_RECVTIME (FIELD_CODEC+3)
  162. #define FIELD_FAXDCS (FIELD_CODEC+4)
  163. static const TIFFFieldInfo jpegFieldInfo[] = {
  164. { TIFFTAG_JPEGTABLES, -3,-3, TIFF_UNDEFINED, FIELD_JPEGTABLES,
  165. FALSE, TRUE, "JPEGTables" },
  166. { TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, FIELD_PSEUDO,
  167. TRUE, FALSE, "" },
  168. { TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
  169. FALSE, FALSE, "" },
  170. { TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
  171. FALSE, FALSE, "" },
  172. /* Specific for JPEG in faxes */
  173. { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, FIELD_RECVPARAMS,
  174. TRUE, FALSE, "FaxRecvParams" },
  175. { TIFFTAG_FAXSUBADDRESS, -1,-1, TIFF_ASCII, FIELD_SUBADDRESS,
  176. TRUE, FALSE, "FaxSubAddress" },
  177. { TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, FIELD_RECVTIME,
  178. TRUE, FALSE, "FaxRecvTime" },
  179. { TIFFTAG_FAXDCS, -1, -1, TIFF_ASCII, FIELD_FAXDCS,
  180. TRUE, FALSE, "FaxDcs" },
  181. };
  182. #define N(a) (sizeof (a) / sizeof (a[0]))
  183. /*
  184. * libjpeg interface layer.
  185. *
  186. * We use setjmp/longjmp to return control to libtiff
  187. * when a fatal error is encountered within the JPEG
  188. * library. We also direct libjpeg error and warning
  189. * messages through the appropriate libtiff handlers.
  190. */
  191. /*
  192. * Error handling routines (these replace corresponding
  193. * IJG routines from jerror.c). These are used for both
  194. * compression and decompression.
  195. */
  196. static void
  197. TIFFjpeg_error_exit(j_common_ptr cinfo)
  198. {
  199. JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */
  200. char buffer[JMSG_LENGTH_MAX];
  201. (*cinfo->err->format_message) (cinfo, buffer);
  202. TIFFErrorExt(sp->tif->tif_clientdata, "JPEGLib", "%s", buffer); /* display the error message */
  203. jpeg_abort(cinfo); /* clean up libjpeg state */
  204. LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
  205. }
  206. /*
  207. * This routine is invoked only for warning messages,
  208. * since error_exit does its own thing and trace_level
  209. * is never set > 0.
  210. */
  211. static void
  212. TIFFjpeg_output_message(j_common_ptr cinfo)
  213. {
  214. char buffer[JMSG_LENGTH_MAX];
  215. (*cinfo->err->format_message) (cinfo, buffer);
  216. TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", "%s", buffer);
  217. }
  218. /*
  219. * Interface routines. This layer of routines exists
  220. * primarily to limit side-effects from using setjmp.
  221. * Also, normal/error returns are converted into return
  222. * values per libtiff practice.
  223. */
  224. #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
  225. #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
  226. static int
  227. TIFFjpeg_create_compress(JPEGState* sp)
  228. {
  229. /* initialize JPEG error handling */
  230. sp->cinfo.c.err = jpeg_std_error(&sp->err);
  231. sp->err.error_exit = TIFFjpeg_error_exit;
  232. sp->err.output_message = TIFFjpeg_output_message;
  233. return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
  234. }
  235. static int
  236. TIFFjpeg_create_decompress(JPEGState* sp)
  237. {
  238. /* initialize JPEG error handling */
  239. sp->cinfo.d.err = jpeg_std_error(&sp->err);
  240. sp->err.error_exit = TIFFjpeg_error_exit;
  241. sp->err.output_message = TIFFjpeg_output_message;
  242. return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
  243. }
  244. static int
  245. TIFFjpeg_set_defaults(JPEGState* sp)
  246. {
  247. return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
  248. }
  249. static int
  250. TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
  251. {
  252. return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
  253. }
  254. static int
  255. TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
  256. {
  257. return CALLVJPEG(sp,
  258. jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
  259. }
  260. static int
  261. TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
  262. {
  263. return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
  264. }
  265. static int
  266. TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
  267. {
  268. return CALLVJPEG(sp,
  269. jpeg_start_compress(&sp->cinfo.c, write_all_tables));
  270. }
  271. static int
  272. TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
  273. {
  274. return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
  275. scanlines, (JDIMENSION) num_lines));
  276. }
  277. static int
  278. TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
  279. {
  280. return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
  281. data, (JDIMENSION) num_lines));
  282. }
  283. static int
  284. TIFFjpeg_finish_compress(JPEGState* sp)
  285. {
  286. return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
  287. }
  288. static int
  289. TIFFjpeg_write_tables(JPEGState* sp)
  290. {
  291. return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
  292. }
  293. static int
  294. TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
  295. {
  296. return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
  297. }
  298. static int
  299. TIFFjpeg_start_decompress(JPEGState* sp)
  300. {
  301. return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
  302. }
  303. static int
  304. TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
  305. {
  306. return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
  307. scanlines, (JDIMENSION) max_lines));
  308. }
  309. static int
  310. TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
  311. {
  312. return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
  313. data, (JDIMENSION) max_lines));
  314. }
  315. static int
  316. TIFFjpeg_finish_decompress(JPEGState* sp)
  317. {
  318. return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
  319. }
  320. static int
  321. TIFFjpeg_abort(JPEGState* sp)
  322. {
  323. return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
  324. }
  325. static int
  326. TIFFjpeg_destroy(JPEGState* sp)
  327. {
  328. return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
  329. }
  330. static JSAMPARRAY
  331. TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
  332. JDIMENSION samplesperrow, JDIMENSION numrows)
  333. {
  334. return CALLJPEG(sp, (JSAMPARRAY) NULL,
  335. (*sp->cinfo.comm.mem->alloc_sarray)
  336. (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
  337. }
  338. /*
  339. * JPEG library destination data manager.
  340. * These routines direct compressed data from libjpeg into the
  341. * libtiff output buffer.
  342. */
  343. static void
  344. std_init_destination(j_compress_ptr cinfo)
  345. {
  346. JPEGState* sp = (JPEGState*) cinfo;
  347. TIFF* tif = sp->tif;
  348. sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
  349. sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
  350. }
  351. static boolean
  352. std_empty_output_buffer(j_compress_ptr cinfo)
  353. {
  354. JPEGState* sp = (JPEGState*) cinfo;
  355. TIFF* tif = sp->tif;
  356. /* the entire buffer has been filled */
  357. tif->tif_rawcc = tif->tif_rawdatasize;
  358. TIFFFlushData1(tif);
  359. sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
  360. sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
  361. return (TRUE);
  362. }
  363. static void
  364. std_term_destination(j_compress_ptr cinfo)
  365. {
  366. JPEGState* sp = (JPEGState*) cinfo;
  367. TIFF* tif = sp->tif;
  368. tif->tif_rawcp = (tidata_t) sp->dest.next_output_byte;
  369. tif->tif_rawcc =
  370. tif->tif_rawdatasize - (tsize_t) sp->dest.free_in_buffer;
  371. /* NB: libtiff does the final buffer flush */
  372. }
  373. static void
  374. TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
  375. {
  376. (void) tif;
  377. sp->cinfo.c.dest = &sp->dest;
  378. sp->dest.init_destination = std_init_destination;
  379. sp->dest.empty_output_buffer = std_empty_output_buffer;
  380. sp->dest.term_destination = std_term_destination;
  381. }
  382. /*
  383. * Alternate destination manager for outputting to JPEGTables field.
  384. */
  385. static void
  386. tables_init_destination(j_compress_ptr cinfo)
  387. {
  388. JPEGState* sp = (JPEGState*) cinfo;
  389. /* while building, jpegtables_length is allocated buffer size */
  390. sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
  391. sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
  392. }
  393. static boolean
  394. tables_empty_output_buffer(j_compress_ptr cinfo)
  395. {
  396. JPEGState* sp = (JPEGState*) cinfo;
  397. void* newbuf;
  398. /* the entire buffer has been filled; enlarge it by 1000 bytes */
  399. newbuf = _TIFFrealloc((tdata_t) sp->jpegtables,
  400. (tsize_t) (sp->jpegtables_length + 1000));
  401. if (newbuf == NULL)
  402. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
  403. sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
  404. sp->dest.free_in_buffer = (size_t) 1000;
  405. sp->jpegtables = newbuf;
  406. sp->jpegtables_length += 1000;
  407. return (TRUE);
  408. }
  409. static void
  410. tables_term_destination(j_compress_ptr cinfo)
  411. {
  412. JPEGState* sp = (JPEGState*) cinfo;
  413. /* set tables length to number of bytes actually emitted */
  414. sp->jpegtables_length -= sp->dest.free_in_buffer;
  415. }
  416. static int
  417. TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
  418. {
  419. (void) tif;
  420. /*
  421. * Allocate a working buffer for building tables.
  422. * Initial size is 1000 bytes, which is usually adequate.
  423. */
  424. if (sp->jpegtables)
  425. _TIFFfree(sp->jpegtables);
  426. sp->jpegtables_length = 1000;
  427. sp->jpegtables = (void*) _TIFFmalloc((tsize_t) sp->jpegtables_length);
  428. if (sp->jpegtables == NULL) {
  429. sp->jpegtables_length = 0;
  430. TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
  431. return (0);
  432. }
  433. sp->cinfo.c.dest = &sp->dest;
  434. sp->dest.init_destination = tables_init_destination;
  435. sp->dest.empty_output_buffer = tables_empty_output_buffer;
  436. sp->dest.term_destination = tables_term_destination;
  437. return (1);
  438. }
  439. /*
  440. * JPEG library source data manager.
  441. * These routines supply compressed data to libjpeg.
  442. */
  443. static void
  444. std_init_source(j_decompress_ptr cinfo)
  445. {
  446. JPEGState* sp = (JPEGState*) cinfo;
  447. TIFF* tif = sp->tif;
  448. sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
  449. sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
  450. }
  451. static boolean
  452. std_fill_input_buffer(j_decompress_ptr cinfo)
  453. {
  454. JPEGState* sp = (JPEGState* ) cinfo;
  455. static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
  456. /*
  457. * Should never get here since entire strip/tile is
  458. * read into memory before the decompressor is called,
  459. * and thus was supplied by init_source.
  460. */
  461. WARNMS(cinfo, JWRN_JPEG_EOF);
  462. /* insert a fake EOI marker */
  463. sp->src.next_input_byte = dummy_EOI;
  464. sp->src.bytes_in_buffer = 2;
  465. return (TRUE);
  466. }
  467. static void
  468. std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
  469. {
  470. JPEGState* sp = (JPEGState*) cinfo;
  471. if (num_bytes > 0) {
  472. if (num_bytes > (long) sp->src.bytes_in_buffer) {
  473. /* oops, buffer overrun */
  474. (void) std_fill_input_buffer(cinfo);
  475. } else {
  476. sp->src.next_input_byte += (size_t) num_bytes;
  477. sp->src.bytes_in_buffer -= (size_t) num_bytes;
  478. }
  479. }
  480. }
  481. static void
  482. std_term_source(j_decompress_ptr cinfo)
  483. {
  484. /* No work necessary here */
  485. /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
  486. /* (if so, need empty tables_term_source!) */
  487. (void) cinfo;
  488. }
  489. static void
  490. TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
  491. {
  492. (void) tif;
  493. sp->cinfo.d.src = &sp->src;
  494. sp->src.init_source = std_init_source;
  495. sp->src.fill_input_buffer = std_fill_input_buffer;
  496. sp->src.skip_input_data = std_skip_input_data;
  497. sp->src.resync_to_restart = jpeg_resync_to_restart;
  498. sp->src.term_source = std_term_source;
  499. sp->src.bytes_in_buffer = 0; /* for safety */
  500. sp->src.next_input_byte = NULL;
  501. }
  502. /*
  503. * Alternate source manager for reading from JPEGTables.
  504. * We can share all the code except for the init routine.
  505. */
  506. static void
  507. tables_init_source(j_decompress_ptr cinfo)
  508. {
  509. JPEGState* sp = (JPEGState*) cinfo;
  510. sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
  511. sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
  512. }
  513. static void
  514. TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
  515. {
  516. TIFFjpeg_data_src(sp, tif);
  517. sp->src.init_source = tables_init_source;
  518. }
  519. /*
  520. * Allocate downsampled-data buffers needed for downsampled I/O.
  521. * We use values computed in jpeg_start_compress or jpeg_start_decompress.
  522. * We use libjpeg's allocator so that buffers will be released automatically
  523. * when done with strip/tile.
  524. * This is also a handy place to compute samplesperclump, bytesperline.
  525. */
  526. static int
  527. alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
  528. int num_components)
  529. {
  530. JPEGState* sp = JState(tif);
  531. int ci;
  532. jpeg_component_info* compptr;
  533. JSAMPARRAY buf;
  534. int samples_per_clump = 0;
  535. for (ci = 0, compptr = comp_info; ci < num_components;
  536. ci++, compptr++) {
  537. samples_per_clump += compptr->h_samp_factor *
  538. compptr->v_samp_factor;
  539. buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
  540. compptr->width_in_blocks * DCTSIZE,
  541. (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
  542. if (buf == NULL)
  543. return (0);
  544. sp->ds_buffer[ci] = buf;
  545. }
  546. sp->samplesperclump = samples_per_clump;
  547. return (1);
  548. }
  549. /*
  550. * JPEG Decoding.
  551. */
  552. static int
  553. JPEGSetupDecode(TIFF* tif)
  554. {
  555. JPEGState* sp = JState(tif);
  556. TIFFDirectory *td = &tif->tif_dir;
  557. JPEGInitializeLibJPEG( tif, 0, 1 );
  558. assert(sp != NULL);
  559. assert(sp->cinfo.comm.is_decompressor);
  560. /* Read JPEGTables if it is present */
  561. if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
  562. TIFFjpeg_tables_src(sp, tif);
  563. if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
  564. TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
  565. return (0);
  566. }
  567. }
  568. /* Grab parameters that are same for all strips/tiles */
  569. sp->photometric = td->td_photometric;
  570. switch (sp->photometric) {
  571. case PHOTOMETRIC_YCBCR:
  572. sp->h_sampling = td->td_ycbcrsubsampling[0];
  573. sp->v_sampling = td->td_ycbcrsubsampling[1];
  574. break;
  575. default:
  576. /* TIFF 6.0 forbids subsampling of all other color spaces */
  577. sp->h_sampling = 1;
  578. sp->v_sampling = 1;
  579. break;
  580. }
  581. /* Set up for reading normal data */
  582. TIFFjpeg_data_src(sp, tif);
  583. tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
  584. return (1);
  585. }
  586. /*
  587. * Set up for decoding a strip or tile.
  588. */
  589. static int
  590. JPEGPreDecode(TIFF* tif, tsample_t s)
  591. {
  592. JPEGState *sp = JState(tif);
  593. TIFFDirectory *td = &tif->tif_dir;
  594. static const char module[] = "JPEGPreDecode";
  595. uint32 segment_width, segment_height;
  596. int downsampled_output;
  597. int ci;
  598. assert(sp != NULL);
  599. assert(sp->cinfo.comm.is_decompressor);
  600. /*
  601. * Reset decoder state from any previous strip/tile,
  602. * in case application didn't read the whole strip.
  603. */
  604. if (!TIFFjpeg_abort(sp))
  605. return (0);
  606. /*
  607. * Read the header for this strip/tile.
  608. */
  609. if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
  610. return (0);
  611. /*
  612. * Check image parameters and set decompression parameters.
  613. */
  614. segment_width = td->td_imagewidth;
  615. segment_height = td->td_imagelength - tif->tif_row;
  616. if (isTiled(tif)) {
  617. segment_width = td->td_tilewidth;
  618. segment_height = td->td_tilelength;
  619. sp->bytesperline = TIFFTileRowSize(tif);
  620. } else {
  621. if (segment_height > td->td_rowsperstrip)
  622. segment_height = td->td_rowsperstrip;
  623. sp->bytesperline = TIFFOldScanlineSize(tif);
  624. }
  625. if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
  626. /*
  627. * For PC 2, scale down the expected strip/tile size
  628. * to match a downsampled component
  629. */
  630. segment_width = TIFFhowmany(segment_width, sp->h_sampling);
  631. segment_height = TIFFhowmany(segment_height, sp->v_sampling);
  632. }
  633. if (sp->cinfo.d.image_width < segment_width ||
  634. sp->cinfo.d.image_height < segment_height) {
  635. TIFFWarningExt(tif->tif_clientdata, module,
  636. "Improper JPEG strip/tile size, "
  637. "expected %dx%d, got %dx%d",
  638. segment_width, segment_height,
  639. sp->cinfo.d.image_width,
  640. sp->cinfo.d.image_height);
  641. }
  642. if (sp->cinfo.d.image_width > segment_width ||
  643. sp->cinfo.d.image_height > segment_height) {
  644. /*
  645. * This case could be dangerous, if the strip or tile size has
  646. * been reported as less than the amount of data jpeg will
  647. * return, some potential security issues arise. Catch this
  648. * case and error out.
  649. */
  650. TIFFErrorExt(tif->tif_clientdata, module,
  651. "JPEG strip/tile size exceeds expected dimensions,"
  652. " expected %dx%d, got %dx%d",
  653. segment_width, segment_height,
  654. sp->cinfo.d.image_width, sp->cinfo.d.image_height);
  655. return (0);
  656. }
  657. if (sp->cinfo.d.num_components !=
  658. (td->td_planarconfig == PLANARCONFIG_CONTIG ?
  659. td->td_samplesperpixel : 1)) {
  660. TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
  661. return (0);
  662. }
  663. #ifdef JPEG_LIB_MK1
  664. if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
  665. TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
  666. return (0);
  667. }
  668. sp->cinfo.d.data_precision = td->td_bitspersample;
  669. sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
  670. #else
  671. if (sp->cinfo.d.data_precision != td->td_bitspersample) {
  672. TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
  673. return (0);
  674. }
  675. #endif
  676. if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
  677. /* Component 0 should have expected sampling factors */
  678. if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
  679. sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
  680. TIFFWarningExt(tif->tif_clientdata, module,
  681. "Improper JPEG sampling factors %d,%d\n"
  682. "Apparently should be %d,%d.",
  683. sp->cinfo.d.comp_info[0].h_samp_factor,
  684. sp->cinfo.d.comp_info[0].v_samp_factor,
  685. sp->h_sampling, sp->v_sampling);
  686. /*
  687. * There are potential security issues here
  688. * for decoders that have already allocated
  689. * buffers based on the expected sampling
  690. * factors. Lets check the sampling factors
  691. * dont exceed what we were expecting.
  692. */
  693. if (sp->cinfo.d.comp_info[0].h_samp_factor
  694. > sp->h_sampling
  695. || sp->cinfo.d.comp_info[0].v_samp_factor
  696. > sp->v_sampling) {
  697. TIFFErrorExt(tif->tif_clientdata,
  698. module,
  699. "Cannot honour JPEG sampling factors"
  700. " that exceed those specified.");
  701. return (0);
  702. }
  703. /*
  704. * XXX: Files written by the Intergraph software
  705. * has different sampling factors stored in the
  706. * TIFF tags and in the JPEG structures. We will
  707. * try to deduce Intergraph files by the presense
  708. * of the tag 33918.
  709. */
  710. if (!_TIFFFindFieldInfo(tif, 33918, TIFF_ANY)) {
  711. TIFFWarningExt(tif->tif_clientdata, module,
  712. "Decompressor will try reading with "
  713. "sampling %d,%d.",
  714. sp->cinfo.d.comp_info[0].h_samp_factor,
  715. sp->cinfo.d.comp_info[0].v_samp_factor);
  716. sp->h_sampling = (uint16)
  717. sp->cinfo.d.comp_info[0].h_samp_factor;
  718. sp->v_sampling = (uint16)
  719. sp->cinfo.d.comp_info[0].v_samp_factor;
  720. }
  721. }
  722. /* Rest should have sampling factors 1,1 */
  723. for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
  724. if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
  725. sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
  726. TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
  727. return (0);
  728. }
  729. }
  730. } else {
  731. /* PC 2's single component should have sampling factors 1,1 */
  732. if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
  733. sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
  734. TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
  735. return (0);
  736. }
  737. }
  738. downsampled_output = FALSE;
  739. if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
  740. sp->photometric == PHOTOMETRIC_YCBCR &&
  741. sp->jpegcolormode == JPEGCOLORMODE_RGB) {
  742. /* Convert YCbCr to RGB */
  743. sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
  744. sp->cinfo.d.out_color_space = JCS_RGB;
  745. } else {
  746. /* Suppress colorspace handling */
  747. sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
  748. sp->cinfo.d.out_color_space = JCS_UNKNOWN;
  749. if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
  750. (sp->h_sampling != 1 || sp->v_sampling != 1))
  751. downsampled_output = TRUE;
  752. /* XXX what about up-sampling? */
  753. }
  754. if (downsampled_output) {
  755. /* Need to use raw-data interface to libjpeg */
  756. sp->cinfo.d.raw_data_out = TRUE;
  757. tif->tif_decoderow = JPEGDecodeRaw;
  758. tif->tif_decodestrip = JPEGDecodeRaw;
  759. tif->tif_decodetile = JPEGDecodeRaw;
  760. } else {
  761. /* Use normal interface to libjpeg */
  762. sp->cinfo.d.raw_data_out = FALSE;
  763. tif->tif_decoderow = JPEGDecode;
  764. tif->tif_decodestrip = JPEGDecode;
  765. tif->tif_decodetile = JPEGDecode;
  766. }
  767. /* Start JPEG decompressor */
  768. if (!TIFFjpeg_start_decompress(sp))
  769. return (0);
  770. /* Allocate downsampled-data buffers if needed */
  771. if (downsampled_output) {
  772. if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
  773. sp->cinfo.d.num_components))
  774. return (0);
  775. sp->scancount = DCTSIZE; /* mark buffer empty */
  776. }
  777. return (1);
  778. }
  779. /*
  780. * Decode a chunk of pixels.
  781. * "Standard" case: returned data is not downsampled.
  782. */
  783. /*ARGSUSED*/ static int
  784. JPEGDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
  785. {
  786. JPEGState *sp = JState(tif);
  787. tsize_t nrows;
  788. (void) s;
  789. nrows = cc / sp->bytesperline;
  790. if (cc % sp->bytesperline)
  791. TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
  792. if( nrows > (int) sp->cinfo.d.image_height )
  793. nrows = sp->cinfo.d.image_height;
  794. /* data is expected to be read in multiples of a scanline */
  795. if (nrows)
  796. {
  797. JSAMPROW line_work_buf = NULL;
  798. /*
  799. ** For 6B, only use temporary buffer for 12 bit imagery.
  800. ** For Mk1 always use it.
  801. */
  802. #if !defined(JPEG_LIB_MK1)
  803. if( sp->cinfo.d.data_precision == 12 )
  804. #endif
  805. {
  806. line_work_buf = (JSAMPROW)
  807. _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
  808. * sp->cinfo.d.num_components );
  809. }
  810. do {
  811. if( line_work_buf != NULL )
  812. {
  813. /*
  814. ** In the MK1 case, we aways read into a 16bit buffer, and then
  815. ** pack down to 12bit or 8bit. In 6B case we only read into 16
  816. ** bit buffer for 12bit data, which we need to repack.
  817. */
  818. if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
  819. return (0);
  820. if( sp->cinfo.d.data_precision == 12 )
  821. {
  822. int value_pairs = (sp->cinfo.d.output_width
  823. * sp->cinfo.d.num_components) / 2;
  824. int iPair;
  825. for( iPair = 0; iPair < value_pairs; iPair++ )
  826. {
  827. unsigned char *out_ptr =
  828. ((unsigned char *) buf) + iPair * 3;
  829. JSAMPLE *in_ptr = line_work_buf + iPair * 2;
  830. out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
  831. out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
  832. | ((in_ptr[1] & 0xf00) >> 8);
  833. out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
  834. }
  835. }
  836. else if( sp->cinfo.d.data_precision == 8 )
  837. {
  838. int value_count = (sp->cinfo.d.output_width
  839. * sp->cinfo.d.num_components);
  840. int iValue;
  841. for( iValue = 0; iValue < value_count; iValue++ )
  842. {
  843. ((unsigned char *) buf)[iValue] =
  844. line_work_buf[iValue] & 0xff;
  845. }
  846. }
  847. }
  848. else
  849. {
  850. /*
  851. ** In the libjpeg6b 8bit case. We read directly into the
  852. ** TIFF buffer.
  853. */
  854. JSAMPROW bufptr = (JSAMPROW)buf;
  855. if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
  856. return (0);
  857. }
  858. ++tif->tif_row;
  859. buf += sp->bytesperline;
  860. cc -= sp->bytesperline;
  861. } while (--nrows > 0);
  862. if( line_work_buf != NULL )
  863. _TIFFfree( line_work_buf );
  864. }
  865. /* Close down the decompressor if we've finished the strip or tile. */
  866. return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
  867. || TIFFjpeg_finish_decompress(sp);
  868. }
  869. /*
  870. * Decode a chunk of pixels.
  871. * Returned data is downsampled per sampling factors.
  872. */
  873. /*ARGSUSED*/ static int
  874. JPEGDecodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
  875. {
  876. JPEGState *sp = JState(tif);
  877. tsize_t nrows;
  878. (void) s;
  879. nrows = cc / sp->bytesperline;
  880. if (cc % sp->bytesperline)
  881. TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
  882. if( nrows > (int) sp->cinfo.d.image_height )
  883. nrows = sp->cinfo.d.image_height;
  884. /* data is expected to be read in multiples of a scanline */
  885. if (nrows) {
  886. /* Cb,Cr both have sampling factors 1, so this is correct */
  887. JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
  888. int samples_per_clump = sp->samplesperclump;
  889. #ifdef JPEG_LIB_MK1
  890. unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
  891. sp->cinfo.d.output_width *
  892. sp->cinfo.d.num_components);
  893. #endif
  894. do {
  895. jpeg_component_info *compptr;
  896. int ci, clumpoffset;
  897. /* Reload downsampled-data buffer if needed */
  898. if (sp->scancount >= DCTSIZE) {
  899. int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
  900. if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
  901. return (0);
  902. sp->scancount = 0;
  903. }
  904. /*
  905. * Fastest way to unseparate data is to make one pass
  906. * over the scanline for each row of each component.
  907. */
  908. clumpoffset = 0; /* first sample in clump */
  909. for (ci = 0, compptr = sp->cinfo.d.comp_info;
  910. ci < sp->cinfo.d.num_components;
  911. ci++, compptr++) {
  912. int hsamp = compptr->h_samp_factor;
  913. int vsamp = compptr->v_samp_factor;
  914. int ypos;
  915. for (ypos = 0; ypos < vsamp; ypos++) {
  916. JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
  917. #ifdef JPEG_LIB_MK1
  918. JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
  919. #else
  920. JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
  921. #endif
  922. JDIMENSION nclump;
  923. if (hsamp == 1) {
  924. /* fast path for at least Cb and Cr */
  925. for (nclump = clumps_per_line; nclump-- > 0; ) {
  926. outptr[0] = *inptr++;
  927. outptr += samples_per_clump;
  928. }
  929. } else {
  930. int xpos;
  931. /* general case */
  932. for (nclump = clumps_per_line; nclump-- > 0; ) {
  933. for (xpos = 0; xpos < hsamp; xpos++)
  934. outptr[xpos] = *inptr++;
  935. outptr += samples_per_clump;
  936. }
  937. }
  938. clumpoffset += hsamp;
  939. }
  940. }
  941. #ifdef JPEG_LIB_MK1
  942. {
  943. if (sp->cinfo.d.data_precision == 8)
  944. {
  945. int i=0;
  946. int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
  947. for (i=0; i<len; i++)
  948. {
  949. ((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
  950. }
  951. }
  952. else
  953. { /* 12-bit */
  954. int value_pairs = (sp->cinfo.d.output_width
  955. * sp->cinfo.d.num_components) / 2;
  956. int iPair;
  957. for( iPair = 0; iPair < value_pairs; iPair++ )
  958. {
  959. unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
  960. JSAMPLE *in_ptr = tmpbuf + iPair * 2;
  961. out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
  962. out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
  963. | ((in_ptr[1] & 0xf00) >> 8);
  964. out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
  965. }
  966. }
  967. }
  968. #endif
  969. sp->scancount ++;
  970. tif->tif_row += sp->v_sampling;
  971. /* increment/decrement of buf and cc is still incorrect, but should not matter
  972. * TODO: resolve this */
  973. buf += sp->bytesperline;
  974. cc -= sp->bytesperline;
  975. } while (--nrows > 0);
  976. #ifdef JPEG_LIB_MK1
  977. _TIFFfree(tmpbuf);
  978. #endif
  979. }
  980. /* Close down the decompressor if done. */
  981. return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
  982. || TIFFjpeg_finish_decompress(sp);
  983. }
  984. /*
  985. * JPEG Encoding.
  986. */
  987. static void
  988. unsuppress_quant_table (JPEGState* sp, int tblno)
  989. {
  990. JQUANT_TBL* qtbl;
  991. if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
  992. qtbl->sent_table = FALSE;
  993. }
  994. static void
  995. unsuppress_huff_table (JPEGState* sp, int tblno)
  996. {
  997. JHUFF_TBL* htbl;
  998. if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
  999. htbl->sent_table = FALSE;
  1000. if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
  1001. htbl->sent_table = FALSE;
  1002. }
  1003. static int
  1004. prepare_JPEGTables(TIFF* tif)
  1005. {
  1006. JPEGState* sp = JState(tif);
  1007. JPEGInitializeLibJPEG( tif, 0, 0 );
  1008. /* Initialize quant tables for current quality setting */
  1009. if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
  1010. return (0);
  1011. /* Mark only the tables we want for output */
  1012. /* NB: chrominance tables are currently used only with YCbCr */
  1013. if (!TIFFjpeg_suppress_tables(sp, TRUE))
  1014. return (0);
  1015. if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
  1016. unsuppress_quant_table(sp, 0);
  1017. if (sp->photometric == PHOTOMETRIC_YCBCR)
  1018. unsuppress_quant_table(sp, 1);
  1019. }
  1020. if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
  1021. unsuppress_huff_table(sp, 0);
  1022. if (sp->photometric == PHOTOMETRIC_YCBCR)
  1023. unsuppress_huff_table(sp, 1);
  1024. }
  1025. /* Direct libjpeg output into jpegtables */
  1026. if (!TIFFjpeg_tables_dest(sp, tif))
  1027. return (0);
  1028. /* Emit tables-only datastream */
  1029. if (!TIFFjpeg_write_tables(sp))
  1030. return (0);
  1031. return (1);
  1032. }
  1033. static int
  1034. JPEGSetupEncode(TIFF* tif)
  1035. {
  1036. JPEGState* sp = JState(tif);
  1037. TIFFDirectory *td = &tif->tif_dir;
  1038. static const char module[] = "JPEGSetupEncode";
  1039. JPEGInitializeLibJPEG( tif, 1, 0 );
  1040. assert(sp != NULL);
  1041. assert(!sp->cinfo.comm.is_decompressor);
  1042. /*
  1043. * Initialize all JPEG parameters to default values.
  1044. * Note that jpeg_set_defaults needs legal values for
  1045. * in_color_space and input_components.
  1046. */
  1047. sp->cinfo.c.in_color_space = JCS_UNKNOWN;
  1048. sp->cinfo.c.input_components = 1;
  1049. if (!TIFFjpeg_set_defaults(sp))
  1050. return (0);
  1051. /* Set per-file parameters */
  1052. sp->photometric = td->td_photometric;
  1053. switch (sp->photometric) {
  1054. case PHOTOMETRIC_YCBCR:
  1055. sp->h_sampling = td->td_ycbcrsubsampling[0];
  1056. sp->v_sampling = td->td_ycbcrsubsampling[1];
  1057. /*
  1058. * A ReferenceBlackWhite field *must* be present since the
  1059. * default value is inappropriate for YCbCr. Fill in the
  1060. * proper value if application didn't set it.
  1061. */
  1062. {
  1063. float *ref;
  1064. if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
  1065. &ref)) {
  1066. float refbw[6];
  1067. long top = 1L << td->td_bitspersample;
  1068. refbw[0] = 0;
  1069. refbw[1] = (float)(top-1L);
  1070. refbw[2] = (float)(top>>1);
  1071. refbw[3] = refbw[1];
  1072. refbw[4] = refbw[2];
  1073. refbw[5] = refbw[1];
  1074. TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
  1075. refbw);
  1076. }
  1077. }
  1078. break;
  1079. case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
  1080. case PHOTOMETRIC_MASK:
  1081. TIFFErrorExt(tif->tif_clientdata, module,
  1082. "PhotometricInterpretation %d not allowed for JPEG",
  1083. (int) sp->photometric);
  1084. return (0);
  1085. default:
  1086. /* TIFF 6.0 forbids subsampling of all other color spaces */
  1087. sp->h_sampling = 1;
  1088. sp->v_sampling = 1;
  1089. break;
  1090. }
  1091. /* Verify miscellaneous parameters */
  1092. /*
  1093. * This would need work if libtiff ever supports different
  1094. * depths for different components, or if libjpeg ever supports
  1095. * run-time selection of depth. Neither is imminent.
  1096. */
  1097. #ifdef JPEG_LIB_MK1
  1098. /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
  1099. if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
  1100. #else
  1101. if (td->td_bitspersample != BITS_IN_JSAMPLE )
  1102. #endif
  1103. {
  1104. TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
  1105. (int) td->td_bitspersample);
  1106. return (0);
  1107. }
  1108. sp->cinfo.c.data_precision = td->td_bitspersample;
  1109. #ifdef JPEG_LIB_MK1
  1110. sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
  1111. #endif
  1112. if (isTiled(tif)) {
  1113. if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
  1114. TIFFErrorExt(tif->tif_clientdata, module,
  1115. "JPEG tile height must be multiple of %d",
  1116. sp->v_sampling * DCTSIZE);
  1117. return (0);
  1118. }
  1119. if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
  1120. TIFFErrorExt(tif->tif_clientdata, module,
  1121. "JPEG tile width must be multiple of %d",
  1122. sp->h_sampling * DCTSIZE);
  1123. return (0);
  1124. }
  1125. } else {
  1126. if (td->td_rowsperstrip < td->td_imagelength &&
  1127. (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
  1128. TIFFErrorExt(tif->tif_clientdata, module,
  1129. "RowsPerStrip must be multiple of %d for JPEG",
  1130. sp->v_sampling * DCTSIZE);
  1131. return (0);
  1132. }
  1133. }
  1134. /* Create a JPEGTables field if appropriate */
  1135. if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
  1136. if( sp->jpegtables == NULL
  1137. || memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
  1138. {
  1139. if (!prepare_JPEGTables(tif))
  1140. return (0);
  1141. /* Mark the field present */
  1142. /* Can't use TIFFSetField since BEENWRITING is already set! */
  1143. tif->tif_flags |= TIFF_DIRTYDIRECT;
  1144. TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
  1145. }
  1146. } else {
  1147. /* We do not support application-supplied JPEGTables, */
  1148. /* so mark the field not present */
  1149. TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
  1150. }
  1151. /* Direct libjpeg output to libtiff's output buffer */
  1152. TIFFjpeg_data_dest(sp, tif);
  1153. return (1);
  1154. }
  1155. /*
  1156. * Set encoding state at the start of a strip or tile.
  1157. */
  1158. static int
  1159. JPEGPreEncode(TIFF* tif, tsample_t s)
  1160. {
  1161. JPEGState *sp = JState(tif);
  1162. TIFFDirectory *td = &tif->tif_dir;
  1163. static const char module[] = "JPEGPreEncode";
  1164. uint32 segment_width, segment_height;
  1165. int downsampled_input;
  1166. assert(sp != NULL);
  1167. assert(!sp->cinfo.comm.is_decompressor);
  1168. /*
  1169. * Set encoding parameters for this strip/tile.
  1170. */
  1171. if (isTiled(tif)) {
  1172. segment_width = td->td_tilewidth;
  1173. segment_height = td->td_tilelength;
  1174. sp->bytesperline = TIFFTileRowSize(tif);
  1175. } else {
  1176. segment_width = td->td_imagewidth;
  1177. segment_height = td->td_imagelength - tif->tif_row;
  1178. if (segment_height > td->td_rowsperstrip)
  1179. segment_height = td->td_rowsperstrip;
  1180. sp->bytesperline = TIFFOldScanlineSize(tif);
  1181. }
  1182. if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
  1183. /* for PC 2, scale down the strip/tile size
  1184. * to match a downsampled component
  1185. */
  1186. segment_width = TIFFhowmany(segment_width, sp->h_sampling);
  1187. segment_height = TIFFhowmany(segment_height, sp->v_sampling);
  1188. }
  1189. if (segment_width > 65535 || segment_height > 65535) {
  1190. TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
  1191. return (0);
  1192. }
  1193. sp->cinfo.c.image_width = segment_width;
  1194. sp->cinfo.c.image_height = segment_height;
  1195. downsampled_input = FALSE;
  1196. if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
  1197. sp->cinfo.c.input_components = td->td_samplesperpixel;
  1198. if (sp->photometric == PHOTOMETRIC_YCBCR) {
  1199. if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
  1200. sp->cinfo.c.in_color_space = JCS_RGB;
  1201. } else {
  1202. sp->cinfo.c.in_color_space = JCS_YCbCr;
  1203. if (sp->h_sampling != 1 || sp->v_sampling != 1)
  1204. downsampled_input = TRUE;
  1205. }
  1206. if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
  1207. return (0);
  1208. /*
  1209. * Set Y sampling factors;
  1210. * we assume jpeg_set_colorspace() set the rest to 1
  1211. */
  1212. sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
  1213. sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
  1214. } else {
  1215. if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
  1216. sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
  1217. else if (td->td_photometric == PHOTOMETRIC_RGB)
  1218. sp->cinfo.c.in_color_space = JCS_RGB;
  1219. else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
  1220. sp->cinfo.c.in_color_space = JCS_CMYK;
  1221. else
  1222. sp->cinfo.c.in_color_space = JCS_UNKNOWN;
  1223. if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
  1224. return (0);
  1225. /* jpeg_set_colorspace set all sampling factors to 1 */
  1226. }
  1227. } else {
  1228. sp->cinfo.c.input_components = 1;
  1229. sp->cinfo.c.in_color_space = JCS_UNKNOWN;
  1230. if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
  1231. return (0);
  1232. sp->cinfo.c.comp_info[0].component_id = s;
  1233. /* jpeg_set_colorspace() set sampling factors to 1 */
  1234. if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
  1235. sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
  1236. sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
  1237. sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
  1238. }
  1239. }
  1240. /* ensure libjpeg won't write any extraneous markers */
  1241. sp->cinfo.c.write_JFIF_header = FALSE;
  1242. sp->cinfo.c.write_Adobe_marker = FALSE;
  1243. /* set up table handling correctly */
  1244. if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
  1245. return (0);
  1246. if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
  1247. unsuppress_quant_table(sp, 0);
  1248. unsuppress_quant_table(sp, 1);
  1249. }
  1250. if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
  1251. sp->cinfo.c.optimize_coding = FALSE;
  1252. else
  1253. sp->cinfo.c.optimize_coding = TRUE;
  1254. if (downsampled_input) {
  1255. /* Need to use raw-data interface to libjpeg */
  1256. sp->cinfo.c.raw_data_in = TRUE;
  1257. tif->tif_encoderow = JPEGEncodeRaw;
  1258. tif->tif_encodestrip = JPEGEncodeRaw;
  1259. tif->tif_encodetile = JPEGEncodeRaw;
  1260. } else {
  1261. /* Use normal interface to libjpeg */
  1262. sp->cinfo.c.raw_data_in = FALSE;
  1263. tif->tif_encoderow = JPEGEncode;
  1264. tif->tif_encodestrip = JPEGEncode;
  1265. tif->tif_encodetile = JPEGEncode;
  1266. }
  1267. /* Start JPEG compressor */
  1268. if (!TIFFjpeg_start_compress(sp, FALSE))
  1269. return (0);
  1270. /* Allocate downsampled-data buffers if needed */
  1271. if (downsampled_input) {
  1272. if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
  1273. sp->cinfo.c.num_components))
  1274. return (0);
  1275. }
  1276. sp->scancount = 0;
  1277. return (1);
  1278. }
  1279. /*
  1280. * Encode a chunk of pixels.
  1281. * "Standard" case: incoming data is not downsampled.
  1282. */
  1283. static int
  1284. JPEGEncode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
  1285. {
  1286. JPEGState *sp = JState(tif);
  1287. tsize_t nrows;
  1288. JSAMPROW bufptr[1];
  1289. (void) s;
  1290. assert(sp != NULL);
  1291. /* data is expected to be supplied in multiples of a scanline */
  1292. nrows = cc / sp->bytesperline;
  1293. if (cc % sp->bytesperline)
  1294. TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
  1295. /* The last strip will be limited to image size */
  1296. if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
  1297. nrows = tif->tif_dir.td_imagelength - tif->tif_row;
  1298. while (nrows-- > 0) {
  1299. bufptr[0] = (JSAMPROW) buf;
  1300. if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
  1301. return (0);
  1302. if (nrows > 0)
  1303. tif->tif_row++;
  1304. buf += sp->bytesperline;
  1305. }
  1306. return (1);
  1307. }
  1308. /*
  1309. * Encode a chunk of pixels.
  1310. * Incoming data is expected to be downsampled per sampling factors.
  1311. */
  1312. static int
  1313. JPEGEncodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
  1314. {
  1315. JPEGState *sp = JState(tif);
  1316. JSAMPLE* inptr;
  1317. JSAMPLE* outptr;
  1318. tsize_t nrows;
  1319. JDIMENSION clumps_per_line, nclump;
  1320. int clumpoffset, ci, xpos, ypos;
  1321. jpeg_component_info* compptr;
  1322. int samples_per_clump = sp->samplesperclump;
  1323. tsize_t bytesperclumpline;
  1324. (void) s;
  1325. assert(sp != NULL);
  1326. /* data is expected to be supplied in multiples of a clumpline */
  1327. /* a clumpline is equivalent to v_sampling desubsampled scanlines */
  1328. /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
  1329. bytesperclumpline = (((sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
  1330. *(sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
  1331. /8;
  1332. nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
  1333. if (cc % bytesperclumpline)
  1334. TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
  1335. /* Cb,Cr both have sampling factors 1, so this is correct */
  1336. clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
  1337. while (nrows > 0) {
  1338. /*
  1339. * Fastest way to separate the data is to make one pass
  1340. * over the scanline for each row of each component.
  1341. */
  1342. clumpoffset = 0; /* first sample in clump */
  1343. for (ci = 0, compptr = sp->cinfo.c.comp_info;
  1344. ci < sp->cinfo.c.num_components;
  1345. ci++, compptr++) {
  1346. int hsamp = compptr->h_samp_factor;
  1347. int vsamp = compptr->v_samp_factor;
  1348. int padding = (int) (compptr->width_in_blocks * DCTSIZE -
  1349. clumps_per_line * hsamp);
  1350. for (ypos = 0; ypos < vsamp; ypos++) {
  1351. inptr = ((JSAMPLE*) buf) + clumpoffset;
  1352. outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
  1353. if (hsamp == 1) {
  1354. /* fast path for at least Cb and Cr */
  1355. for (nclump = clumps_per_line; nclump-- > 0; ) {
  1356. *outptr++ = inptr[0];
  1357. inptr += samples_per_clump;
  1358. }
  1359. } else {
  1360. /* general case */
  1361. for (nclump = clumps_per_line; nclump-- > 0; ) {
  1362. for (xpos = 0; xpos < hsamp; xpos++)
  1363. *outptr++ = inptr[xpos];
  1364. inptr += samples_per_clump;
  1365. }
  1366. }
  1367. /* pad each scanline as needed */
  1368. for (xpos = 0; xpos < padding; xpos++) {
  1369. *outptr = outptr[-1];
  1370. outptr++;
  1371. }
  1372. clumpoffset += hsamp;
  1373. }
  1374. }
  1375. sp->scancount++;
  1376. if (sp->scancount >= DCTSIZE) {
  1377. int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
  1378. if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
  1379. return (0);
  1380. sp->scancount = 0;
  1381. }
  1382. tif->tif_row += sp->v_sampling;
  1383. buf += bytesperclumpline;
  1384. nrows -= sp->v_sampling;
  1385. }
  1386. return (1);
  1387. }
  1388. /*
  1389. * Finish up at the end of a strip or tile.
  1390. */
  1391. static int
  1392. JPEGPostEncode(TIFF* tif)
  1393. {
  1394. JPEGState *sp = JState(tif);
  1395. if (sp->scancount > 0) {
  1396. /*
  1397. * Need to emit a partial bufferload of downsampled data.
  1398. * Pad the data vertically.
  1399. */
  1400. int ci, ypos, n;
  1401. jpeg_component_info* compptr;
  1402. for (ci = 0, compptr = sp->cinfo.c.comp_info;
  1403. ci < sp->cinfo.c.num_components;
  1404. ci++, compptr++) {
  1405. int vsamp = compptr->v_samp_factor;
  1406. tsize_t row_width = compptr->width_in_blocks * DCTSIZE
  1407. * sizeof(JSAMPLE);
  1408. for (ypos = sp->scancount * vsamp;
  1409. ypos < DCTSIZE * vsamp; ypos++) {
  1410. _TIFFmemcpy((tdata_t)sp->ds_buffer[ci][ypos],
  1411. (tdata_t)sp->ds_buffer[ci][ypos-1],
  1412. row_width);
  1413. }
  1414. }
  1415. n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
  1416. if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
  1417. return (0);
  1418. }
  1419. return (TIFFjpeg_finish_compress(JState(tif)));
  1420. }
  1421. static void
  1422. JPEGCleanup(TIFF* tif)
  1423. {
  1424. JPEGState *sp = JState(tif);
  1425. assert(sp != 0);
  1426. tif->tif_tagmethods.vgetfield = sp->vgetparent;
  1427. tif->tif_tagmethods.vsetfield = sp->vsetparent;
  1428. tif->tif_tagmethods.printdir = sp->printdir;
  1429. if( sp->cinfo_initialized )
  1430. TIFFjpeg_destroy(sp); /* release libjpeg resources */
  1431. if (sp->jpegtables) /* tag value */
  1432. _TIFFfree(sp->jpegtables);
  1433. _TIFFfree(tif->tif_data); /* release local state */
  1434. tif->tif_data = NULL;
  1435. _TIFFSetDefaultCompressionState(tif);
  1436. }
  1437. static void
  1438. JPEGResetUpsampled( TIFF* tif )
  1439. {
  1440. JPEGState* sp = JState(tif);
  1441. TIFFDirectory* td = &tif->tif_dir;
  1442. /*
  1443. * Mark whether returned data is up-sampled or not so TIFFStripSize
  1444. * and TIFFTileSize return values that reflect the true amount of
  1445. * data.
  1446. */
  1447. tif->tif_flags &= ~TIFF_UPSAMPLED;
  1448. if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
  1449. if (td->td_photometric == PHOTOMETRIC_YCBCR &&
  1450. sp->jpegcolormode == JPEGCOLORMODE_RGB) {
  1451. tif->tif_flags |= TIFF_UPSAMPLED;
  1452. } else {
  1453. #ifdef notdef
  1454. if (td->td_ycbcrsubsampling[0] != 1 ||
  1455. td->td_ycbcrsubsampling[1] != 1)
  1456. ; /* XXX what about up-sampling? */
  1457. #endif
  1458. }
  1459. }
  1460. /*
  1461. * Must recalculate cached tile size in case sampling state changed.
  1462. * Should we really be doing this now if image size isn't set?
  1463. */
  1464. if( tif->tif_tilesize > 0 )
  1465. tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
  1466. if(tif->tif_scanlinesize > 0 )
  1467. tif->tif_scanlinesize = TIFFScanlineSize(tif);
  1468. }
  1469. static int
  1470. JPEGVSetField(TIFF* tif, ttag_t tag, va_list ap)
  1471. {
  1472. JPEGState* sp = JState(tif);
  1473. const TIFFFieldInfo* fip;
  1474. uint32 v32;
  1475. assert(sp != NULL);
  1476. switch (tag) {
  1477. case TIFFTAG_JPEGTABLES:
  1478. v32 = va_arg(ap, uint32);
  1479. if