tif_jpeg.c 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301
  1. /* $Id: tif_jpeg.c,v 1.108 2012-06-05 03:24:30 fwarmerdam 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* tif, uint32 strip);
  43. int TIFFFillTile(TIFF* tif, uint32 tile);
  44. int TIFFReInitJPEG_12( TIFF *tif, int scheme, int is_encode );
  45. /* We undefine FAR to avoid conflict with JPEG definition */
  46. #ifdef FAR
  47. #undef FAR
  48. #endif
  49. /*
  50. Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
  51. not defined. Unfortunately, the MinGW and Borland compilers include
  52. a typedef for INT32, which causes a conflict. MSVC does not include
  53. a conficting typedef given the headers which are included.
  54. */
  55. #if defined(__BORLANDC__) || defined(__MINGW32__)
  56. # define XMD_H 1
  57. #endif
  58. /*
  59. The windows RPCNDR.H file defines boolean, but defines it with the
  60. unsigned char size. You should compile JPEG library using appropriate
  61. definitions in jconfig.h header, but many users compile library in wrong
  62. way. That causes errors of the following type:
  63. "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
  64. caller expects 464"
  65. For such users we wil fix the problem here. See install.doc file from
  66. the JPEG library distribution for details.
  67. */
  68. /* Define "boolean" as unsigned char, not int, per Windows custom. */
  69. #if defined(__WIN32__) && !defined(__MINGW32__)
  70. # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  71. typedef unsigned char boolean;
  72. # endif
  73. # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  74. #endif
  75. #include "jpeglib.h"
  76. #include "jerror.h"
  77. /*
  78. * Do we want to do special processing suitable for when JSAMPLE is a
  79. * 16bit value?
  80. */
  81. #if defined(JPEG_LIB_MK1)
  82. # define JPEG_LIB_MK1_OR_12BIT 1
  83. #elif BITS_IN_JSAMPLE == 12
  84. # define JPEG_LIB_MK1_OR_12BIT 1
  85. #endif
  86. /*
  87. * We are using width_in_blocks which is supposed to be private to
  88. * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
  89. * renamed this member to width_in_data_units. Since the header has
  90. * also renamed a define, use that unique define name in order to
  91. * detect the problem header and adjust to suit.
  92. */
  93. #if defined(D_MAX_DATA_UNITS_IN_MCU)
  94. #define width_in_blocks width_in_data_units
  95. #endif
  96. /*
  97. * On some machines it may be worthwhile to use _setjmp or sigsetjmp
  98. * in place of plain setjmp. These macros will make it easier.
  99. */
  100. #define SETJMP(jbuf) setjmp(jbuf)
  101. #define LONGJMP(jbuf,code) longjmp(jbuf,code)
  102. #define JMP_BUF jmp_buf
  103. typedef struct jpeg_destination_mgr jpeg_destination_mgr;
  104. typedef struct jpeg_source_mgr jpeg_source_mgr;
  105. typedef struct jpeg_error_mgr jpeg_error_mgr;
  106. /*
  107. * State block for each open TIFF file using
  108. * libjpeg to do JPEG compression/decompression.
  109. *
  110. * libjpeg's visible state is either a jpeg_compress_struct
  111. * or jpeg_decompress_struct depending on which way we
  112. * are going. comm can be used to refer to the fields
  113. * which are common to both.
  114. *
  115. * NB: cinfo is required to be the first member of JPEGState,
  116. * so we can safely cast JPEGState* -> jpeg_xxx_struct*
  117. * and vice versa!
  118. */
  119. typedef struct {
  120. union {
  121. struct jpeg_compress_struct c;
  122. struct jpeg_decompress_struct d;
  123. struct jpeg_common_struct comm;
  124. } cinfo; /* NB: must be first */
  125. int cinfo_initialized;
  126. jpeg_error_mgr err; /* libjpeg error manager */
  127. JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
  128. /*
  129. * The following two members could be a union, but
  130. * they're small enough that it's not worth the effort.
  131. */
  132. jpeg_destination_mgr dest; /* data dest for compression */
  133. jpeg_source_mgr src; /* data source for decompression */
  134. /* private state */
  135. TIFF* tif; /* back link needed by some code */
  136. uint16 photometric; /* copy of PhotometricInterpretation */
  137. uint16 h_sampling; /* luminance sampling factors */
  138. uint16 v_sampling;
  139. tmsize_t bytesperline; /* decompressed bytes per scanline */
  140. /* pointers to intermediate buffers when processing downsampled data */
  141. JSAMPARRAY ds_buffer[MAX_COMPONENTS];
  142. int scancount; /* number of "scanlines" accumulated */
  143. int samplesperclump;
  144. TIFFVGetMethod vgetparent; /* super-class method */
  145. TIFFVSetMethod vsetparent; /* super-class method */
  146. TIFFPrintMethod printdir; /* super-class method */
  147. TIFFStripMethod defsparent; /* super-class method */
  148. TIFFTileMethod deftparent; /* super-class method */
  149. /* pseudo-tag fields */
  150. void* jpegtables; /* JPEGTables tag value, or NULL */
  151. uint32 jpegtables_length; /* number of bytes in same */
  152. int jpegquality; /* Compression quality level */
  153. int jpegcolormode; /* Auto RGB<=>YCbCr convert? */
  154. int jpegtablesmode; /* What to put in JPEGTables */
  155. int ycbcrsampling_fetched;
  156. } JPEGState;
  157. #define JState(tif) ((JPEGState*)(tif)->tif_data)
  158. static int JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
  159. static int JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
  160. static int JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
  161. static int JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
  162. static int JPEGInitializeLibJPEG(TIFF * tif, int decode );
  163. static int DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
  164. #define FIELD_JPEGTABLES (FIELD_CODEC+0)
  165. static const TIFFField jpegFields[] = {
  166. { TIFFTAG_JPEGTABLES, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_C32_UINT8, FIELD_JPEGTABLES, FALSE, TRUE, "JPEGTables", NULL },
  167. { TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "", NULL },
  168. { TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL },
  169. { TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL }
  170. };
  171. /*
  172. * libjpeg interface layer.
  173. *
  174. * We use setjmp/longjmp to return control to libtiff
  175. * when a fatal error is encountered within the JPEG
  176. * library. We also direct libjpeg error and warning
  177. * messages through the appropriate libtiff handlers.
  178. */
  179. /*
  180. * Error handling routines (these replace corresponding
  181. * IJG routines from jerror.c). These are used for both
  182. * compression and decompression.
  183. */
  184. static void
  185. TIFFjpeg_error_exit(j_common_ptr cinfo)
  186. {
  187. JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */
  188. char buffer[JMSG_LENGTH_MAX];
  189. (*cinfo->err->format_message) (cinfo, buffer);
  190. TIFFErrorExt(sp->tif->tif_clientdata, "JPEGLib", "%s", buffer); /* display the error message */
  191. jpeg_abort(cinfo); /* clean up libjpeg state */
  192. LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
  193. }
  194. /*
  195. * This routine is invoked only for warning messages,
  196. * since error_exit does its own thing and trace_level
  197. * is never set > 0.
  198. */
  199. static void
  200. TIFFjpeg_output_message(j_common_ptr cinfo)
  201. {
  202. char buffer[JMSG_LENGTH_MAX];
  203. (*cinfo->err->format_message) (cinfo, buffer);
  204. TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", "%s", buffer);
  205. }
  206. /*
  207. * Interface routines. This layer of routines exists
  208. * primarily to limit side-effects from using setjmp.
  209. * Also, normal/error returns are converted into return
  210. * values per libtiff practice.
  211. */
  212. #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
  213. #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
  214. static int
  215. TIFFjpeg_create_compress(JPEGState* sp)
  216. {
  217. /* initialize JPEG error handling */
  218. sp->cinfo.c.err = jpeg_std_error(&sp->err);
  219. sp->err.error_exit = TIFFjpeg_error_exit;
  220. sp->err.output_message = TIFFjpeg_output_message;
  221. return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
  222. }
  223. static int
  224. TIFFjpeg_create_decompress(JPEGState* sp)
  225. {
  226. /* initialize JPEG error handling */
  227. sp->cinfo.d.err = jpeg_std_error(&sp->err);
  228. sp->err.error_exit = TIFFjpeg_error_exit;
  229. sp->err.output_message = TIFFjpeg_output_message;
  230. return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
  231. }
  232. static int
  233. TIFFjpeg_set_defaults(JPEGState* sp)
  234. {
  235. return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
  236. }
  237. static int
  238. TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
  239. {
  240. return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
  241. }
  242. static int
  243. TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
  244. {
  245. return CALLVJPEG(sp,
  246. jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
  247. }
  248. static int
  249. TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
  250. {
  251. return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
  252. }
  253. static int
  254. TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
  255. {
  256. return CALLVJPEG(sp,
  257. jpeg_start_compress(&sp->cinfo.c, write_all_tables));
  258. }
  259. static int
  260. TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
  261. {
  262. return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
  263. scanlines, (JDIMENSION) num_lines));
  264. }
  265. static int
  266. TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
  267. {
  268. return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
  269. data, (JDIMENSION) num_lines));
  270. }
  271. static int
  272. TIFFjpeg_finish_compress(JPEGState* sp)
  273. {
  274. return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
  275. }
  276. static int
  277. TIFFjpeg_write_tables(JPEGState* sp)
  278. {
  279. return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
  280. }
  281. static int
  282. TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
  283. {
  284. return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
  285. }
  286. static int
  287. TIFFjpeg_start_decompress(JPEGState* sp)
  288. {
  289. return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
  290. }
  291. static int
  292. TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
  293. {
  294. return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
  295. scanlines, (JDIMENSION) max_lines));
  296. }
  297. static int
  298. TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
  299. {
  300. return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
  301. data, (JDIMENSION) max_lines));
  302. }
  303. static int
  304. TIFFjpeg_finish_decompress(JPEGState* sp)
  305. {
  306. return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
  307. }
  308. static int
  309. TIFFjpeg_abort(JPEGState* sp)
  310. {
  311. return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
  312. }
  313. static int
  314. TIFFjpeg_destroy(JPEGState* sp)
  315. {
  316. return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
  317. }
  318. static JSAMPARRAY
  319. TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
  320. JDIMENSION samplesperrow, JDIMENSION numrows)
  321. {
  322. return CALLJPEG(sp, (JSAMPARRAY) NULL,
  323. (*sp->cinfo.comm.mem->alloc_sarray)
  324. (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
  325. }
  326. /*
  327. * JPEG library destination data manager.
  328. * These routines direct compressed data from libjpeg into the
  329. * libtiff output buffer.
  330. */
  331. static void
  332. std_init_destination(j_compress_ptr cinfo)
  333. {
  334. JPEGState* sp = (JPEGState*) cinfo;
  335. TIFF* tif = sp->tif;
  336. sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
  337. sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
  338. }
  339. static boolean
  340. std_empty_output_buffer(j_compress_ptr cinfo)
  341. {
  342. JPEGState* sp = (JPEGState*) cinfo;
  343. TIFF* tif = sp->tif;
  344. /* the entire buffer has been filled */
  345. tif->tif_rawcc = tif->tif_rawdatasize;
  346. #ifdef IPPJ_HUFF
  347. /*
  348. * The Intel IPP performance library does not necessarily fill up
  349. * the whole output buffer on each pass, so only dump out the parts
  350. * that have been filled.
  351. * http://trac.osgeo.org/gdal/wiki/JpegIPP
  352. */
  353. if ( sp->dest.free_in_buffer >= 0 ) {
  354. tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
  355. }
  356. #endif
  357. TIFFFlushData1(tif);
  358. sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
  359. sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
  360. return (TRUE);
  361. }
  362. static void
  363. std_term_destination(j_compress_ptr cinfo)
  364. {
  365. JPEGState* sp = (JPEGState*) cinfo;
  366. TIFF* tif = sp->tif;
  367. tif->tif_rawcp = (uint8*) sp->dest.next_output_byte;
  368. tif->tif_rawcc =
  369. tif->tif_rawdatasize - (tmsize_t) sp->dest.free_in_buffer;
  370. /* NB: libtiff does the final buffer flush */
  371. }
  372. static void
  373. TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
  374. {
  375. (void) tif;
  376. sp->cinfo.c.dest = &sp->dest;
  377. sp->dest.init_destination = std_init_destination;
  378. sp->dest.empty_output_buffer = std_empty_output_buffer;
  379. sp->dest.term_destination = std_term_destination;
  380. }
  381. /*
  382. * Alternate destination manager for outputting to JPEGTables field.
  383. */
  384. static void
  385. tables_init_destination(j_compress_ptr cinfo)
  386. {
  387. JPEGState* sp = (JPEGState*) cinfo;
  388. /* while building, jpegtables_length is allocated buffer size */
  389. sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
  390. sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
  391. }
  392. static boolean
  393. tables_empty_output_buffer(j_compress_ptr cinfo)
  394. {
  395. JPEGState* sp = (JPEGState*) cinfo;
  396. void* newbuf;
  397. /* the entire buffer has been filled; enlarge it by 1000 bytes */
  398. newbuf = _TIFFrealloc((void*) sp->jpegtables,
  399. (tmsize_t) (sp->jpegtables_length + 1000));
  400. if (newbuf == NULL)
  401. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
  402. sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
  403. sp->dest.free_in_buffer = (size_t) 1000;
  404. sp->jpegtables = newbuf;
  405. sp->jpegtables_length += 1000;
  406. return (TRUE);
  407. }
  408. static void
  409. tables_term_destination(j_compress_ptr cinfo)
  410. {
  411. JPEGState* sp = (JPEGState*) cinfo;
  412. /* set tables length to number of bytes actually emitted */
  413. sp->jpegtables_length -= (uint32) sp->dest.free_in_buffer;
  414. }
  415. static int
  416. TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
  417. {
  418. (void) tif;
  419. /*
  420. * Allocate a working buffer for building tables.
  421. * Initial size is 1000 bytes, which is usually adequate.
  422. */
  423. if (sp->jpegtables)
  424. _TIFFfree(sp->jpegtables);
  425. sp->jpegtables_length = 1000;
  426. sp->jpegtables = (void*) _TIFFmalloc((tmsize_t) sp->jpegtables_length);
  427. if (sp->jpegtables == NULL) {
  428. sp->jpegtables_length = 0;
  429. TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
  430. return (0);
  431. }
  432. sp->cinfo.c.dest = &sp->dest;
  433. sp->dest.init_destination = tables_init_destination;
  434. sp->dest.empty_output_buffer = tables_empty_output_buffer;
  435. sp->dest.term_destination = tables_term_destination;
  436. return (1);
  437. }
  438. /*
  439. * JPEG library source data manager.
  440. * These routines supply compressed data to libjpeg.
  441. */
  442. static void
  443. std_init_source(j_decompress_ptr cinfo)
  444. {
  445. JPEGState* sp = (JPEGState*) cinfo;
  446. TIFF* tif = sp->tif;
  447. sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
  448. sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
  449. }
  450. static boolean
  451. std_fill_input_buffer(j_decompress_ptr cinfo)
  452. {
  453. JPEGState* sp = (JPEGState* ) cinfo;
  454. static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
  455. #ifdef IPPJ_HUFF
  456. /*
  457. * The Intel IPP performance library does not necessarily read the whole
  458. * input buffer in one pass, so it is possible to get here with data
  459. * yet to read.
  460. *
  461. * We just return without doing anything, until the entire buffer has
  462. * been read.
  463. * http://trac.osgeo.org/gdal/wiki/JpegIPP
  464. */
  465. if( sp->src.bytes_in_buffer > 0 ) {
  466. return (TRUE);
  467. }
  468. #endif
  469. /*
  470. * Normally the whole strip/tile is read and so we don't need to do
  471. * a fill. In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
  472. * all the data, but the rawdata is refreshed between scanlines and
  473. * we push this into the io machinery in JPEGDecode().
  474. * http://trac.osgeo.org/gdal/ticket/3894
  475. */
  476. WARNMS(cinfo, JWRN_JPEG_EOF);
  477. /* insert a fake EOI marker */
  478. sp->src.next_input_byte = dummy_EOI;
  479. sp->src.bytes_in_buffer = 2;
  480. return (TRUE);
  481. }
  482. static void
  483. std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
  484. {
  485. JPEGState* sp = (JPEGState*) cinfo;
  486. if (num_bytes > 0) {
  487. if ((size_t)num_bytes > sp->src.bytes_in_buffer) {
  488. /* oops, buffer overrun */
  489. (void) std_fill_input_buffer(cinfo);
  490. } else {
  491. sp->src.next_input_byte += (size_t) num_bytes;
  492. sp->src.bytes_in_buffer -= (size_t) num_bytes;
  493. }
  494. }
  495. }
  496. static void
  497. std_term_source(j_decompress_ptr cinfo)
  498. {
  499. /* No work necessary here */
  500. (void) cinfo;
  501. }
  502. static void
  503. TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
  504. {
  505. (void) tif;
  506. sp->cinfo.d.src = &sp->src;
  507. sp->src.init_source = std_init_source;
  508. sp->src.fill_input_buffer = std_fill_input_buffer;
  509. sp->src.skip_input_data = std_skip_input_data;
  510. sp->src.resync_to_restart = jpeg_resync_to_restart;
  511. sp->src.term_source = std_term_source;
  512. sp->src.bytes_in_buffer = 0; /* for safety */
  513. sp->src.next_input_byte = NULL;
  514. }
  515. /*
  516. * Alternate source manager for reading from JPEGTables.
  517. * We can share all the code except for the init routine.
  518. */
  519. static void
  520. tables_init_source(j_decompress_ptr cinfo)
  521. {
  522. JPEGState* sp = (JPEGState*) cinfo;
  523. sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
  524. sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
  525. }
  526. static void
  527. TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
  528. {
  529. TIFFjpeg_data_src(sp, tif);
  530. sp->src.init_source = tables_init_source;
  531. }
  532. /*
  533. * Allocate downsampled-data buffers needed for downsampled I/O.
  534. * We use values computed in jpeg_start_compress or jpeg_start_decompress.
  535. * We use libjpeg's allocator so that buffers will be released automatically
  536. * when done with strip/tile.
  537. * This is also a handy place to compute samplesperclump, bytesperline.
  538. */
  539. static int
  540. alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
  541. int num_components)
  542. {
  543. JPEGState* sp = JState(tif);
  544. int ci;
  545. jpeg_component_info* compptr;
  546. JSAMPARRAY buf;
  547. int samples_per_clump = 0;
  548. for (ci = 0, compptr = comp_info; ci < num_components;
  549. ci++, compptr++) {
  550. samples_per_clump += compptr->h_samp_factor *
  551. compptr->v_samp_factor;
  552. buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
  553. compptr->width_in_blocks * DCTSIZE,
  554. (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
  555. if (buf == NULL)
  556. return (0);
  557. sp->ds_buffer[ci] = buf;
  558. }
  559. sp->samplesperclump = samples_per_clump;
  560. return (1);
  561. }
  562. /*
  563. * JPEG Decoding.
  564. */
  565. #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
  566. #define JPEG_MARKER_SOF0 0xC0
  567. #define JPEG_MARKER_SOF1 0xC1
  568. #define JPEG_MARKER_SOF3 0xC3
  569. #define JPEG_MARKER_DHT 0xC4
  570. #define JPEG_MARKER_SOI 0xD8
  571. #define JPEG_MARKER_SOS 0xDA
  572. #define JPEG_MARKER_DQT 0xDB
  573. #define JPEG_MARKER_DRI 0xDD
  574. #define JPEG_MARKER_APP0 0xE0
  575. #define JPEG_MARKER_COM 0xFE
  576. struct JPEGFixupTagsSubsamplingData
  577. {
  578. TIFF* tif;
  579. void* buffer;
  580. uint32 buffersize;
  581. uint8* buffercurrentbyte;
  582. uint32 bufferbytesleft;
  583. uint64 fileoffset;
  584. uint64 filebytesleft;
  585. uint8 filepositioned;
  586. };
  587. static void JPEGFixupTagsSubsampling(TIFF* tif);
  588. static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data);
  589. static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result);
  590. static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result);
  591. static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength);
  592. #endif
  593. static int
  594. JPEGFixupTags(TIFF* tif)
  595. {
  596. #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
  597. if ((tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)&&
  598. (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
  599. (tif->tif_dir.td_samplesperpixel==3))
  600. JPEGFixupTagsSubsampling(tif);
  601. #endif
  602. return(1);
  603. }
  604. #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
  605. static void
  606. JPEGFixupTagsSubsampling(TIFF* tif)
  607. {
  608. /*
  609. * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
  610. * the TIFF tags, but still use non-default (2,2) values within the jpeg
  611. * data stream itself. In order for TIFF applications to work properly
  612. * - for instance to get the strip buffer size right - it is imperative
  613. * that the subsampling be available before we start reading the image
  614. * data normally. This function will attempt to analyze the first strip in
  615. * order to get the sampling values from the jpeg data stream.
  616. *
  617. * Note that JPEGPreDeocode() will produce a fairly loud warning when the
  618. * discovered sampling does not match the default sampling (2,2) or whatever
  619. * was actually in the tiff tags.
  620. *
  621. * See the bug in bugzilla for details:
  622. *
  623. * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
  624. *
  625. * Frank Warmerdam, July 2002
  626. * Joris Van Damme, May 2007
  627. */
  628. static const char module[] = "JPEGFixupTagsSubsampling";
  629. struct JPEGFixupTagsSubsamplingData m;
  630. _TIFFFillStriles( tif );
  631. if( tif->tif_dir.td_stripbytecount == NULL
  632. || tif->tif_dir.td_stripbytecount[0] == 0 )
  633. {
  634. /* Do not even try to check if the first strip/tile does not
  635. yet exist, as occurs when GDAL has created a new NULL file
  636. for instance. */
  637. return;
  638. }
  639. m.tif=tif;
  640. m.buffersize=2048;
  641. m.buffer=_TIFFmalloc(m.buffersize);
  642. if (m.buffer==NULL)
  643. {
  644. TIFFWarningExt(tif->tif_clientdata,module,
  645. "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
  646. return;
  647. }
  648. m.buffercurrentbyte=NULL;
  649. m.bufferbytesleft=0;
  650. m.fileoffset=tif->tif_dir.td_stripoffset[0];
  651. m.filepositioned=0;
  652. m.filebytesleft=tif->tif_dir.td_stripbytecount[0];
  653. if (!JPEGFixupTagsSubsamplingSec(&m))
  654. TIFFWarningExt(tif->tif_clientdata,module,
  655. "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
  656. _TIFFfree(m.buffer);
  657. }
  658. static int
  659. JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
  660. {
  661. static const char module[] = "JPEGFixupTagsSubsamplingSec";
  662. uint8 m;
  663. while (1)
  664. {
  665. while (1)
  666. {
  667. if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
  668. return(0);
  669. if (m==255)
  670. break;
  671. }
  672. while (1)
  673. {
  674. if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
  675. return(0);
  676. if (m!=255)
  677. break;
  678. }
  679. switch (m)
  680. {
  681. case JPEG_MARKER_SOI:
  682. /* this type of marker has no data and should be skipped */
  683. break;
  684. case JPEG_MARKER_COM:
  685. case JPEG_MARKER_APP0:
  686. case JPEG_MARKER_APP0+1:
  687. case JPEG_MARKER_APP0+2:
  688. case JPEG_MARKER_APP0+3:
  689. case JPEG_MARKER_APP0+4:
  690. case JPEG_MARKER_APP0+5:
  691. case JPEG_MARKER_APP0+6:
  692. case JPEG_MARKER_APP0+7:
  693. case JPEG_MARKER_APP0+8:
  694. case JPEG_MARKER_APP0+9:
  695. case JPEG_MARKER_APP0+10:
  696. case JPEG_MARKER_APP0+11:
  697. case JPEG_MARKER_APP0+12:
  698. case JPEG_MARKER_APP0+13:
  699. case JPEG_MARKER_APP0+14:
  700. case JPEG_MARKER_APP0+15:
  701. case JPEG_MARKER_DQT:
  702. case JPEG_MARKER_SOS:
  703. case JPEG_MARKER_DHT:
  704. case JPEG_MARKER_DRI:
  705. /* this type of marker has data, but it has no use to us and should be skipped */
  706. {
  707. uint16 n;
  708. if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
  709. return(0);
  710. if (n<2)
  711. return(0);
  712. n-=2;
  713. if (n>0)
  714. JPEGFixupTagsSubsamplingSkip(data,n);
  715. }
  716. break;
  717. case JPEG_MARKER_SOF0:
  718. case JPEG_MARKER_SOF1:
  719. /* this marker contains the subsampling factors we're scanning for */
  720. {
  721. uint16 n;
  722. uint16 o;
  723. uint8 p;
  724. uint8 ph,pv;
  725. if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
  726. return(0);
  727. if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
  728. return(0);
  729. JPEGFixupTagsSubsamplingSkip(data,7);
  730. if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
  731. return(0);
  732. ph=(p>>4);
  733. pv=(p&15);
  734. JPEGFixupTagsSubsamplingSkip(data,1);
  735. for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
  736. {
  737. JPEGFixupTagsSubsamplingSkip(data,1);
  738. if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
  739. return(0);
  740. if (p!=0x11)
  741. {
  742. TIFFWarningExt(data->tif->tif_clientdata,module,
  743. "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
  744. return(1);
  745. }
  746. JPEGFixupTagsSubsamplingSkip(data,1);
  747. }
  748. if (((ph!=1)&&(ph!=2)&&(ph!=4))||((pv!=1)&&(pv!=2)&&(pv!=4)))
  749. {
  750. TIFFWarningExt(data->tif->tif_clientdata,module,
  751. "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
  752. return(1);
  753. }
  754. if ((ph!=data->tif->tif_dir.td_ycbcrsubsampling[0])||(pv!=data->tif->tif_dir.td_ycbcrsubsampling[1]))
  755. {
  756. TIFFWarningExt(data->tif->tif_clientdata,module,
  757. "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
  758. (int)data->tif->tif_dir.td_ycbcrsubsampling[0],
  759. (int)data->tif->tif_dir.td_ycbcrsubsampling[1],
  760. (int)ph,(int)pv);
  761. data->tif->tif_dir.td_ycbcrsubsampling[0]=ph;
  762. data->tif->tif_dir.td_ycbcrsubsampling[1]=pv;
  763. }
  764. }
  765. return(1);
  766. default:
  767. return(0);
  768. }
  769. }
  770. }
  771. static int
  772. JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
  773. {
  774. if (data->bufferbytesleft==0)
  775. {
  776. uint32 m;
  777. if (data->filebytesleft==0)
  778. return(0);
  779. if (!data->filepositioned)
  780. {
  781. TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET);
  782. data->filepositioned=1;
  783. }
  784. m=data->buffersize;
  785. if ((uint64)m>data->filebytesleft)
  786. m=(uint32)data->filebytesleft;
  787. assert(m<0x80000000UL);
  788. if (TIFFReadFile(data->tif,data->buffer,(tmsize_t)m)!=(tmsize_t)m)
  789. return(0);
  790. data->buffercurrentbyte=data->buffer;
  791. data->bufferbytesleft=m;
  792. data->fileoffset+=m;
  793. data->filebytesleft-=m;
  794. }
  795. *result=*data->buffercurrentbyte;
  796. data->buffercurrentbyte++;
  797. data->bufferbytesleft--;
  798. return(1);
  799. }
  800. static int
  801. JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
  802. {
  803. uint8 ma;
  804. uint8 mb;
  805. if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
  806. return(0);
  807. if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
  808. return(0);
  809. *result=(ma<<8)|mb;
  810. return(1);
  811. }
  812. static void
  813. JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
  814. {
  815. if ((uint32)skiplength<=data->bufferbytesleft)
  816. {
  817. data->buffercurrentbyte+=skiplength;
  818. data->bufferbytesleft-=skiplength;
  819. }
  820. else
  821. {
  822. uint16 m;
  823. m=skiplength-data->bufferbytesleft;
  824. if (m<=data->filebytesleft)
  825. {
  826. data->bufferbytesleft=0;
  827. data->fileoffset+=m;
  828. data->filebytesleft-=m;
  829. data->filepositioned=0;
  830. }
  831. else
  832. {
  833. data->bufferbytesleft=0;
  834. data->filebytesleft=0;
  835. }
  836. }
  837. }
  838. #endif
  839. static int
  840. JPEGSetupDecode(TIFF* tif)
  841. {
  842. JPEGState* sp = JState(tif);
  843. TIFFDirectory *td = &tif->tif_dir;
  844. #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
  845. if( tif->tif_dir.td_bitspersample == 12 )
  846. return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 0 );
  847. #endif
  848. JPEGInitializeLibJPEG( tif, TRUE );
  849. assert(sp != NULL);
  850. assert(sp->cinfo.comm.is_decompressor);
  851. /* Read JPEGTables if it is present */
  852. if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
  853. TIFFjpeg_tables_src(sp, tif);
  854. if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
  855. TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
  856. return (0);
  857. }
  858. }
  859. /* Grab parameters that are same for all strips/tiles */
  860. sp->photometric = td->td_photometric;
  861. switch (sp->photometric) {
  862. case PHOTOMETRIC_YCBCR:
  863. sp->h_sampling = td->td_ycbcrsubsampling[0];
  864. sp->v_sampling = td->td_ycbcrsubsampling[1];
  865. break;
  866. default:
  867. /* TIFF 6.0 forbids subsampling of all other color spaces */
  868. sp->h_sampling = 1;
  869. sp->v_sampling = 1;
  870. break;
  871. }
  872. /* Set up for reading normal data */
  873. TIFFjpeg_data_src(sp, tif);
  874. tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
  875. return (1);
  876. }
  877. /*
  878. * Set up for decoding a strip or tile.
  879. */
  880. static int
  881. JPEGPreDecode(TIFF* tif, uint16 s)
  882. {
  883. JPEGState *sp = JState(tif);
  884. TIFFDirectory *td = &tif->tif_dir;
  885. static const char module[] = "JPEGPreDecode";
  886. uint32 segment_width, segment_height;
  887. int downsampled_output;
  888. int ci;
  889. assert(sp != NULL);
  890. if (sp->cinfo.comm.is_decompressor == 0)
  891. {
  892. tif->tif_setupdecode( tif );
  893. }
  894. assert(sp->cinfo.comm.is_decompressor);
  895. /*
  896. * Reset decoder state from any previous strip/tile,
  897. * in case application didn't read the whole strip.
  898. */
  899. if (!TIFFjpeg_abort(sp))
  900. return (0);
  901. /*
  902. * Read the header for this strip/tile.
  903. */
  904. if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
  905. return (0);
  906. tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
  907. tif->tif_rawcc = sp->src.bytes_in_buffer;
  908. /*
  909. * Check image parameters and set decompression parameters.
  910. */
  911. segment_width = td->td_imagewidth;
  912. segment_height = td->td_imagelength - tif->tif_row;
  913. if (isTiled(tif)) {
  914. segment_width = td->td_tilewidth;
  915. segment_height = td->td_tilelength;
  916. sp->bytesperline = TIFFTileRowSize(tif);
  917. } else {
  918. if (segment_height > td->td_rowsperstrip)
  919. segment_height = td->td_rowsperstrip;
  920. sp->bytesperline = TIFFScanlineSize(tif);
  921. }
  922. if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
  923. /*
  924. * For PC 2, scale down the expected strip/tile size
  925. * to match a downsampled component
  926. */
  927. segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
  928. segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
  929. }
  930. if (sp->cinfo.d.image_width < segment_width ||
  931. sp->cinfo.d.image_height < segment_height) {
  932. TIFFWarningExt(tif->tif_clientdata, module,
  933. "Improper JPEG strip/tile size, "
  934. "expected %dx%d, got %dx%d",
  935. segment_width, segment_height,
  936. sp->cinfo.d.image_width,
  937. sp->cinfo.d.image_height);
  938. }
  939. if (sp->cinfo.d.image_width > segment_width ||
  940. sp->cinfo.d.image_height > segment_height) {
  941. /*
  942. * This case could be dangerous, if the strip or tile size has
  943. * been reported as less than the amount of data jpeg will
  944. * return, some potential security issues arise. Catch this
  945. * case and error out.
  946. */
  947. TIFFErrorExt(tif->tif_clientdata, module,
  948. "JPEG strip/tile size exceeds expected dimensions,"
  949. " expected %dx%d, got %dx%d",
  950. segment_width, segment_height,
  951. sp->cinfo.d.image_width, sp->cinfo.d.image_height);
  952. return (0);
  953. }
  954. if (sp->cinfo.d.num_components !=
  955. (td->td_planarconfig == PLANARCONFIG_CONTIG ?
  956. td->td_samplesperpixel : 1)) {
  957. TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
  958. return (0);
  959. }
  960. #ifdef JPEG_LIB_MK1
  961. if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
  962. TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
  963. return (0);
  964. }
  965. sp->cinfo.d.data_precision = td->td_bitspersample;
  966. sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
  967. #else
  968. if (sp->cinfo.d.data_precision != td->td_bitspersample) {
  969. TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
  970. return (0);
  971. }
  972. #endif
  973. if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
  974. /* Component 0 should have expected sampling factors */
  975. if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
  976. sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
  977. TIFFErrorExt(tif->tif_clientdata, module,
  978. "Improper JPEG sampling factors %d,%d\n"
  979. "Apparently should be %d,%d.",
  980. sp->cinfo.d.comp_info[0].h_samp_factor,
  981. sp->cinfo.d.comp_info[0].v_samp_factor,
  982. sp->h_sampling, sp->v_sampling);
  983. return (0);
  984. }
  985. /* Rest should have sampling factors 1,1 */
  986. for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
  987. if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
  988. sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
  989. TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
  990. return (0);
  991. }
  992. }
  993. } else {
  994. /* PC 2's single component should have sampling factors 1,1 */
  995. if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
  996. sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
  997. TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
  998. return (0);
  999. }
  1000. }
  1001. downsampled_output = FALSE;
  1002. if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
  1003. sp->photometric == PHOTOMETRIC_YCBCR &&
  1004. sp->jpegcolormode == JPEGCOLORMODE_RGB) {
  1005. /* Convert YCbCr to RGB */
  1006. sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
  1007. sp->cinfo.d.out_color_space = JCS_RGB;
  1008. } else {
  1009. /* Suppress colorspace handling */
  1010. sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
  1011. sp->cinfo.d.out_color_space = JCS_UNKNOWN;
  1012. if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
  1013. (sp->h_sampling != 1 || sp->v_sampling != 1))
  1014. downsampled_output = TRUE;
  1015. /* XXX what about up-sampling? */
  1016. }
  1017. if (downsampled_output) {
  1018. /* Need to use raw-data interface to libjpeg */
  1019. sp->cinfo.d.raw_data_out = TRUE;
  1020. tif->tif_decoderow = DecodeRowError;
  1021. tif->tif_decodestrip = JPEGDecodeRaw;
  1022. tif->tif_decodetile = JPEGDecodeRaw;
  1023. } else {
  1024. /* Use normal interface to libjpeg */
  1025. sp->cinfo.d.raw_data_out = FALSE;
  1026. tif->tif_decoderow = JPEGDecode;
  1027. tif->tif_decodestrip = JPEGDecode;
  1028. tif->tif_decodetile = JPEGDecode;
  1029. }
  1030. /* Start JPEG decompressor */
  1031. if (!TIFFjpeg_start_decompress(sp))
  1032. return (0);
  1033. /* Allocate downsampled-data buffers if needed */
  1034. if (downsampled_output) {
  1035. if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
  1036. sp->cinfo.d.num_components))
  1037. return (0);
  1038. sp->scancount = DCTSIZE; /* mark buffer empty */
  1039. }
  1040. return (1);
  1041. }
  1042. /*
  1043. * Decode a chunk of pixels.
  1044. * "Standard" case: returned data is not downsampled.
  1045. */
  1046. /*ARGSUSED*/ static int
  1047. JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
  1048. {
  1049. JPEGState *sp = JState(tif);
  1050. tmsize_t nrows;
  1051. (void) s;
  1052. /*
  1053. ** Update available information, buffer may have been refilled
  1054. ** between decode requests
  1055. */
  1056. sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
  1057. sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
  1058. if( sp->bytesperline == 0 )
  1059. return 0;
  1060. nrows = cc / sp->bytesperline;
  1061. if (cc % sp->bytesperline)
  1062. TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
  1063. if( nrows > (tmsize_t) sp->cinfo.d.image_height )
  1064. nrows = sp->cinfo.d.image_height;
  1065. /* data is expected to be read in multiples of a scanline */
  1066. if (nrows)
  1067. {
  1068. JSAMPROW line_work_buf = NULL;
  1069. /*
  1070. * For 6B, only use temporary buffer for 12 bit imagery.
  1071. * For Mk1 always use it.
  1072. */
  1073. #if !defined(JPEG_LIB_MK1)
  1074. if( sp->cinfo.d.data_precision == 12 )
  1075. #endif
  1076. {
  1077. line_work_buf = (JSAMPROW)
  1078. _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
  1079. * sp->cinfo.d.num_components );
  1080. }
  1081. do {
  1082. if( line_work_buf != NULL )
  1083. {
  1084. /*
  1085. * In the MK1 case, we aways read into a 16bit buffer, and then
  1086. * pack down to 12bit or 8bit. In 6B case we only read into 16
  1087. * bit buffer for 12bit data, which we need to repack.
  1088. */
  1089. if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
  1090. return (0);
  1091. if( sp->cinfo.d.data_precision == 12 )
  1092. {
  1093. int value_pairs = (sp->cinfo.d.output_width
  1094. * sp->cinfo.d.num_components) / 2;
  1095. int iPair;
  1096. for( iPair = 0; iPair < value_pairs; iPair++ )
  1097. {
  1098. unsigned char *out_ptr =
  1099. ((unsigned char *) buf) + iPair * 3;
  1100. JSAMPLE *in_ptr = line_work_buf + iPair * 2;
  1101. out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
  1102. out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
  1103. | ((in_ptr[1] & 0xf00) >> 8);
  1104. out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
  1105. }
  1106. }
  1107. else if( sp->cinfo.d.data_precision == 8 )
  1108. {
  1109. int value_count = (sp->cinfo.d.output_width
  1110. * sp->cinfo.d.num_components);
  1111. int iValue;
  1112. for( iValue = 0; iValue < value_count; iValue++ )
  1113. {
  1114. ((unsigned char *) buf)[iValue] =
  1115. line_work_buf[iValue] & 0xff;
  1116. }
  1117. }
  1118. }
  1119. else
  1120. {
  1121. /*
  1122. * In the libjpeg6b 8bit case. We read directly into the
  1123. * TIFF buffer.
  1124. */
  1125. JSAMPROW bufptr = (JSAMPROW)buf;
  1126. if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
  1127. return (0);
  1128. }
  1129. ++tif->tif_row;
  1130. buf += sp->bytesperline;
  1131. cc -= sp->bytesperline;
  1132. } while (--nrows > 0);
  1133. if( line_work_buf != NULL )
  1134. _TIFFfree( line_work_buf );
  1135. }
  1136. /* Update information on consumed data */
  1137. tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
  1138. tif->tif_rawcc = sp->src.bytes_in_buffer;
  1139. /* Close down the decompressor if we've finished the strip or tile. */
  1140. return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
  1141. || TIFFjpeg_finish_decompress(sp);
  1142. }
  1143. /*ARGSUSED*/ static int
  1144. DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
  1145. {
  1146. (void) buf;
  1147. (void) cc;
  1148. (void) s;
  1149. TIFFErrorExt(tif->tif_clientdata, "TIFFReadScanline",
  1150. "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
  1151. return 0;
  1152. }
  1153. /*
  1154. * Decode a chunk of pixels.
  1155. * Returned data is downsampled per sampling factors.
  1156. */
  1157. /*ARGSUSED*/ static int
  1158. JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
  1159. {
  1160. JPEGState *sp = JState(tif);
  1161. tmsize_t nrows;
  1162. (void) s;
  1163. /* data is expected to be read in multiples of a scanline */
  1164. if ( (nrows = sp->cinfo.d.image_height) ) {
  1165. /* Cb,Cr both have sampling factors 1, so this is correct */
  1166. JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
  1167. int samples_per_clump = sp->samplesperclump;
  1168. #if defined(JPEG_LIB_MK1_OR_12BIT)
  1169. unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
  1170. sp->cinfo.d.output_width *
  1171. sp->cinfo.d.num_components);
  1172. if(tmpbuf==NULL) {
  1173. TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
  1174. "Out of memory");
  1175. return 0;
  1176. }
  1177. #endif
  1178. do {
  1179. jpeg_component_info *compptr;
  1180. int ci, clumpoffset;
  1181. if( cc < sp->bytesperline ) {
  1182. TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
  1183. "application buffer not large enough for all data.");
  1184. return 0;
  1185. }
  1186. /* Reload downsampled-data buffer if needed */
  1187. if (sp->scancount >= DCTSIZE) {
  1188. int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
  1189. if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
  1190. return (0);
  1191. sp->scancount = 0;
  1192. }
  1193. /*
  1194. * Fastest way to unseparate data is to make one pass
  1195. * over the scanline for each row of each component.
  1196. */
  1197. clumpoffset = 0; /* first sample in clump */
  1198. for (ci = 0, compptr = sp->cinfo.d.comp_info;
  1199. ci < sp->cinfo.d.num_components;
  1200. ci++, compptr++) {
  1201. int hsamp = compptr->h_samp_factor;
  1202. int vsamp = compptr->v_samp_factor;
  1203. int ypos;
  1204. for (ypos = 0; ypos < vsamp; ypos++) {
  1205. JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
  1206. JDIMENSION nclump;
  1207. #if defined(JPEG_LIB_MK1_OR_12BIT)
  1208. JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
  1209. #else
  1210. JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
  1211. if (cc < clumpoffset + samples_per_clump*(clumps_per_line-1) + hsamp) {
  1212. TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
  1213. "application buffer not large enough for all data, possible subsampling issue");
  1214. return 0;
  1215. }
  1216. #endif
  1217. if (hsamp == 1) {
  1218. /* fast path for at least Cb and Cr */
  1219. for (nclump = clumps_per_line; nclump-- > 0; ) {
  1220. outptr[0] = *inptr++;
  1221. outptr += samples_per_clump;
  1222. }
  1223. } else {
  1224. int xpos;
  1225. /* general case */
  1226. for (nclump = clumps_per_line; nclump-- > 0; ) {
  1227. for (xpos = 0; xpos < hsamp; xpos++)
  1228. outptr[xpos] = *inptr++;
  1229. outptr += samples_per_clump;
  1230. }
  1231. }
  1232. clumpoffset += hsamp;
  1233. }
  1234. }
  1235. #if defined(JPEG_LIB_MK1_OR_12BIT)
  1236. {
  1237. if (sp->cinfo.d.data_precision == 8)
  1238. {
  1239. int i=0;
  1240. int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
  1241. for (i=0; i<len; i++)
  1242. {
  1243. ((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
  1244. }
  1245. }
  1246. else
  1247. { /* 12-bit */
  1248. int value_pairs = (sp->cinfo.d.output_width
  1249. * sp->cinfo.d.num_components) / 2;
  1250. int iPair;
  1251. for( iPair = 0; iPair < value_pairs; iPair++ )
  1252. {
  1253. unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
  1254. JSAMPLE *in_ptr = (JSAMPLE *) (tmpbuf + iPair * 2);
  1255. out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
  1256. out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
  1257. | ((in_ptr[1] & 0xf00) >> 8);
  1258. out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
  1259. }
  1260. }
  1261. }
  1262. #endif
  1263. sp->scancount ++;
  1264. tif->tif_row += sp->v_sampling;
  1265. buf += sp->bytesperline;
  1266. cc -= sp->bytesperline;
  1267. nrows -= sp->v_sampling;
  1268. } while (nrows > 0);
  1269. #if defined(JPEG_LIB_MK1_OR_12BIT)
  1270. _TIFFfree(tmpbuf);
  1271. #endif
  1272. }
  1273. /* Close down the decompressor if done. */
  1274. return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
  1275. || TIFFjpeg_finish_decompress(sp);
  1276. }
  1277. /*
  1278. * JPEG Encoding.
  1279. */
  1280. static void
  1281. unsuppress_quant_table (JPEGState* sp, int tblno)
  1282. {
  1283. JQUANT_TBL* qtbl;
  1284. if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
  1285. qtbl->sent_table = FALSE;
  1286. }
  1287. static void
  1288. unsuppress_huff_table (JPEGState* sp, int tblno)
  1289. {
  1290. JHUFF_TBL* htbl;
  1291. if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
  1292. htbl->sent_table = FALSE;
  1293. if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
  1294. htbl->sent_table = FALSE;
  1295. }
  1296. static int
  1297. prepare_JPEGTables(TIFF* tif)
  1298. {
  1299. JPEGState* sp = JState(tif);
  1300. /* Initialize quant tables for current quality setting */
  1301. if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
  1302. return (0);
  1303. /* Mark only the tables we want for output */
  1304. /* NB: chrominance tables are currently used only with YCbCr */
  1305. if (!TIFFjpeg_suppress_tables(sp, TRUE))
  1306. return (0);
  1307. if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
  1308. unsuppress_quant_table(sp, 0);
  1309. if (sp->photometric == PHOTOMETRIC_YCBCR)
  1310. unsuppress_quant_table(sp, 1);
  1311. }
  1312. if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
  1313. unsuppress_huff_table(sp, 0);
  1314. if (sp->photometric == PHOTOMETRIC_YCBCR)
  1315. unsuppress_huff_table(sp, 1);
  1316. }
  1317. /* Direct libjpeg output into jpegtables */
  1318. if (!TIFFjpeg_tables_dest(sp, tif))
  1319. return (0);
  1320. /* Emit tables-only datastream */
  1321. if (!TIFFjpeg_write_tables(sp))
  1322. return (0);
  1323. return (1);
  1324. }
  1325. static int
  1326. JPEGSetupEncode(TIFF* tif)
  1327. {
  1328. JPEGState* sp = JState(tif);
  1329. TIFFDirectory *td = &tif->tif_dir;
  1330. static const char module[] = "JPEGSetupEncode";
  1331. #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
  1332. if( tif->tif_dir.td_bitspersample == 12 )
  1333. return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 1 );
  1334. #endif
  1335. JPEGInitializeLibJPEG( tif, FALSE );
  1336. assert(sp != NULL);
  1337. assert(!sp->cinfo.comm.is_decompressor);
  1338. /*
  1339. * Initialize all JPEG parameters to default values.
  1340. * Note that jpeg_set_defaults needs legal values for
  1341. * in_color_space and input_components.
  1342. */
  1343. sp->cinfo.c.in_color_space = JCS_UNKNOWN;
  1344. sp->cinfo.c.input_components = 1;
  1345. if (!TIFFjpeg_set_defaults(sp))
  1346. return (0);
  1347. /* Set per-file parameters */
  1348. sp->photometric = td->td_photometric;
  1349. switch (sp->photometric) {
  1350. case PHOTOMETRIC_YCBCR:
  1351. sp->h_sampling = td->td_ycbcrsubsampling[0];
  1352. sp->v_sampling = td->td_ycbcrsubsampling[1];
  1353. /*
  1354. * A ReferenceBlackWhite field *must* be present since the
  1355. * default value is inappropriate for YCbCr. Fill in the
  1356. * proper value if application didn't set it.
  1357. */
  1358. {
  1359. float *ref;
  1360. if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
  1361. &ref)) {
  1362. float refbw[6];
  1363. long top = 1L << td->td_bitspersample;
  1364. refbw[0] = 0;
  1365. refbw[1] = (float)(top-1L);
  1366. refbw[2] = (float)(top>>1);
  1367. refbw[3] = refbw[1];
  1368. refbw[4] = refbw[2];
  1369. refbw[5] = refbw[1];
  1370. TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
  1371. refbw);
  1372. }
  1373. }
  1374. break;
  1375. case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
  1376. case PHOTOMETRIC_MASK:
  1377. TIFFErrorExt(tif->tif_clientdata, module,
  1378. "PhotometricInterpretation %d not allowed for JPEG",
  1379. (int) sp->photometric);
  1380. return (0);
  1381. default:
  1382. /* TIFF 6.0 forbids subsampling of all other color spaces */
  1383. sp->h_sampling = 1;
  1384. sp->v_sampling = 1;
  1385. break;
  1386. }
  1387. /* Verify miscellaneous parameters */
  1388. /*
  1389. * This would need work if libtiff ever supports different
  1390. * depths for different components, or if libjpeg ever supports
  1391. * run-time selection of depth. Neither is imminent.
  1392. */
  1393. #ifdef JPEG_LIB_MK1
  1394. /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
  1395. if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
  1396. #else
  1397. if (td->td_bitspersample != BITS_IN_JSAMPLE )
  1398. #endif
  1399. {
  1400. TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
  1401. (int) td->td_bitspersample);
  1402. return (0);
  1403. }
  1404. sp->cinfo.c.data_precision = td->td_bitspersample;
  1405. #ifdef JPEG_LIB_MK1
  1406. sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
  1407. #endif
  1408. if (isTiled(tif)) {
  1409. if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
  1410. TIFFErrorExt(tif->tif_clientdata, module,
  1411. "JPEG tile height must be multiple of %d",
  1412. sp->v_sampling * DCTSIZE);
  1413. return (0);
  1414. }
  1415. if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
  1416. TIFFErrorExt(tif->tif_clientdata, module,
  1417. "JPEG tile width must be multiple of %d",
  1418. sp->h_sampling * DCTSIZE);
  1419. return (0);
  1420. }
  1421. } else {
  1422. if (td->td_rowsperstrip < td->td_imagelength &&
  1423. (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
  1424. TIFFErrorExt(tif->tif_clientdata, module,
  1425. "RowsPerStrip must be multiple of %d for JPEG",
  1426. sp->v_sampling * DCTSIZE);
  1427. return (0);
  1428. }
  1429. }
  1430. /* Create a JPEGTables field if appropriate */
  1431. if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
  1432. if( sp->jpegtables == NULL
  1433. || memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
  1434. {
  1435. if (!prepare_JPEGTables(tif))
  1436. return (0);
  1437. /* Mark the field present */
  1438. /* Can't use TIFFSetField since BEENWRITING is already set! */
  1439. tif->tif_flags |= TIFF_DIRTYDIRECT;
  1440. TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
  1441. }
  1442. } else {
  1443. /* We do not support application-supplied JPEGTables, */
  1444. /* so mark the field not present */
  1445. TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
  1446. }
  1447. /* Direct libjpeg output to libtiff's output buffer */
  1448. TIFFjpeg_data_dest(sp, tif);
  1449. return (1);
  1450. }
  1451. /*
  1452. * Set encoding state at the start of a strip or tile.
  1453. */
  1454. static int
  1455. JPEGPreEncode(TIFF* tif, uint16 s)
  1456. {
  1457. JPEGState *sp = JState(tif);
  1458. TIFFDirectory *td = &tif->tif_dir;
  1459. static const char module[] = "JPEGPreEncode";
  1460. uint32 segment_width, segment_height;
  1461. int downsampled_input;
  1462. assert(sp != NULL);
  1463. if (sp->cinfo.comm.is_decompressor == 1)
  1464. {
  1465. tif->tif_setupencode( tif );
  1466. }
  1467. assert(!sp->cinfo.comm.is_decompressor);
  1468. /*
  1469. * Set encoding parameters for this strip/tile.
  1470. */
  1471. if (isTiled(tif)) {
  1472. segment_width = td->td_tilewidth;
  1473. segment_height = td->td_tilelength;
  1474. sp->bytesperline = TIFFTileRowSize(tif);
  1475. } else {
  1476. segment_width = td->td_imagewidth;
  1477. segment_height = td->td_imagelength - tif->tif_row;
  1478. if (segment_height > td->td_rowsperstrip)
  1479. segment_height = td->td_rowsperstrip;
  1480. sp->bytesperline = TIFFScanlineSize(tif);
  1481. }
  1482. if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
  1483. /* for PC 2, scale down the strip/tile size
  1484. * to match a downsampled component
  1485. */
  1486. segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
  1487. segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
  1488. }
  1489. if (segment_width > 65535 || segment_height > 65535) {
  1490. TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
  1491. return (0);
  1492. }
  1493. sp->cinfo.c.image_width = segment_width;
  1494. sp->cinfo.c.image_height = segment_height;
  1495. downsampled_input = FALSE;
  1496. if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
  1497. sp->cinfo.c.input_components = td->td_samplesperpixel;
  1498. if (sp->photometric == PHOTOMETRIC_YCBCR) {
  1499. if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
  1500. sp->cinfo.c.in_color_space = JCS_RGB;
  1501. } else {
  1502. sp->cinfo.c.in_color_space = JCS_YCbCr;
  1503. if (sp->h_sampling != 1 || sp->v_sampling != 1)
  1504. downsampled_input = TRUE;
  1505. }
  1506. if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
  1507. return (0);
  1508. /*
  1509. * Set Y sampling factors;
  1510. * we assume jpeg_set_colorspace() set the rest to 1
  1511. */
  1512. sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
  1513. sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
  1514. } else {
  1515. if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
  1516. sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
  1517. else if (td->td_photometric == PHOTOMETRIC_RGB)
  1518. sp->cinfo.c.in_color_space = JCS_RGB;
  1519. else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
  1520. sp->cinfo.c.in_color_space = JCS_CMYK;
  1521. else
  1522. sp->cinfo.c.in_color_space = JCS_UNKNOWN;
  1523. if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
  1524. return (0);
  1525. /* jpeg_set_colorspace set all sampling factors to 1 */
  1526. }
  1527. } else {
  1528. sp->cinfo.c.input_components = 1;
  1529. sp->cinfo.c.in_color_space = JCS_UNKNOWN;
  1530. if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
  1531. return (0);
  1532. sp->cinfo.c.comp_info[0].component_id = s;
  1533. /* jpeg_set_colorspace() set sampling factors to 1 */
  1534. if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
  1535. sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
  1536. sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
  1537. sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
  1538. }
  1539. }
  1540. /* ensure libjpeg won't write any extraneous markers */
  1541. sp->cinfo.c.write_JFIF_header = FALSE;
  1542. sp->cinfo.c.write_Adobe_marker = FALSE;
  1543. /* set up table handling correctly */
  1544. if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
  1545. return (0);
  1546. if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
  1547. unsuppress_quant_table(sp, 0);
  1548. unsuppress_quant_table(sp, 1);
  1549. }
  1550. if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
  1551. sp->cinfo.c.optimize_coding = FALSE;
  1552. else
  1553. sp->cinfo.c.optimize_coding = TRUE;
  1554. if (downsampled_input) {
  1555. /* Need to use raw-data interface to libjpeg */
  1556. sp->cinfo.c.raw_data_in = TRUE;
  1557. tif->tif_encoderow = JPEGEncodeRaw;
  1558. tif->tif_encodestrip = JPEGEncodeRaw;
  1559. tif->tif_encodetile = JPEGEncodeRaw;
  1560. } else {
  1561. /* Use normal interface to libjpeg */
  1562. sp->cinfo.c.raw_data_in = FALSE;
  1563. tif->tif_encoderow = JPEGEncode;
  1564. tif->tif_encodestrip = JPEGEncode;
  1565. tif->tif_encodetile = JPEGEncode;
  1566. }
  1567. /* Start JPEG compressor */
  1568. if (!TIFFjpeg_start_compress(sp, FALSE))
  1569. return (0);
  1570. /* Allocate downsampled-data buffers if needed */
  1571. if (downsampled_input) {
  1572. if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
  1573. sp->cinfo.c.num_components))
  1574. return (0);
  1575. }
  1576. sp->scancount = 0;
  1577. return (1);
  1578. }
  1579. /*
  1580. * Encode a chunk of pixels.
  1581. * "Standard" case: incoming data is not downsampled.
  1582. */
  1583. static int
  1584. JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
  1585. {
  1586. JPEGState *sp = JState(tif);
  1587. tmsize_t nrows;
  1588. JSAMPROW bufptr[1];
  1589. short *line16 = NULL;
  1590. int line16_count = 0;
  1591. (void) s;
  1592. assert(sp != NULL);
  1593. /* data is expected to be supplied in multiples of a scanline */
  1594. nrows = cc / sp->bytesperline;
  1595. if (cc % sp->bytesperline)
  1596. TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
  1597. "fractional scanline discarded");
  1598. /* The last strip will be limited to image size */
  1599. if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
  1600. nrows = tif->tif_dir.td_imagelength - tif->tif_row;
  1601. if( sp->cinfo.c.data_precision == 12 )
  1602. {
  1603. line16_count = (sp->bytesperline * 2) / 3;
  1604. line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
  1605. // FIXME: undiagnosed malloc failure
  1606. }
  1607. while (nrows-- > 0) {
  1608. if( sp->cinfo.c.data_precision == 12 )
  1609. {
  1610. int value_pairs = line16_count / 2;
  1611. int iPair;
  1612. bufptr[0] = (JSAMPROW) line16;
  1613. for( iPair = 0; iPair < value_pairs; iPair++ )
  1614. {
  1615. unsigned char *in_ptr =
  1616. ((unsigned char *) buf) + iPair * 3;
  1617. JSAMPLE *out_ptr = (JSAMPLE *) (line16 + iPair * 2);
  1618. out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
  1619. out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
  1620. }
  1621. }
  1622. else
  1623. {
  1624. bufptr[0] = (JSAMPROW) buf;
  1625. }
  1626. if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
  1627. return (0);
  1628. if (nrows > 0)
  1629. tif->tif_row++;
  1630. buf += sp->bytesperline;
  1631. }
  1632. if( sp->cinfo.c.data_precision == 12 )
  1633. {
  1634. _TIFFfree( line16 );
  1635. }
  1636. return (1);
  1637. }
  1638. /*
  1639. * Encode a chunk of pixels.
  1640. * Incoming data is expected to be downsampled per sampling factors.
  1641. */
  1642. static int
  1643. JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
  1644. {
  1645. JPEGState *sp = JState(tif);
  1646. JSAMPLE* inptr;
  1647. JSAMPLE* outptr;
  1648. tmsize_t nrows;
  1649. JDIMENSION clumps_per_line, nclump;
  1650. int clumpoffset, ci, xpos, ypos;
  1651. jpeg_component_info* compptr;
  1652. int samples_per_clump = sp->samplesperclump;
  1653. tmsize_t bytesperclumpline;
  1654. (void) s;
  1655. assert(sp != NULL);
  1656. /* data is expected to be supplied in multiples of a clumpline */
  1657. /* a clumpline is equivalent to v_sampling desubsampled scanlines */
  1658. /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
  1659. bytesperclumpline = (((sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
  1660. *(sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
  1661. /8;
  1662. nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
  1663. if (cc % bytesperclumpline)
  1664. TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
  1665. /* Cb,Cr both have sampling factors 1, so this is correct */
  1666. clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
  1667. while (nrows > 0) {
  1668. /*
  1669. * Fastest way to separate the data is to make one pass
  1670. * over the scanline for each row of each component.
  1671. */
  1672. clumpoffset = 0; /* first sample in clump */
  1673. for (ci = 0, compptr = sp->cinfo.c.comp_info;
  1674. ci < sp->cinfo.c.num_components;
  1675. ci++, compptr++) {
  1676. int hsamp = compptr->h_samp_factor;
  1677. int vsamp = compptr->v_samp_factor;
  1678. int padding = (int) (compptr->width_in_blocks * DCTSIZE -
  1679. clumps_per_line * hsamp);
  1680. for (ypos = 0; ypos < vsamp; ypos++) {
  1681. inptr = ((JSAMPLE*) buf) + clumpoffset;
  1682. outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
  1683. if (hsamp == 1) {
  1684. /* fast path for at least Cb and Cr */
  1685. for (nclump = clumps_per_line; nclump-- > 0; ) {
  1686. *outptr++ = inptr[0];
  1687. inptr += samples_per_clump;
  1688. }
  1689. } else {
  1690. /* general case */
  1691. for (nclump = clumps_per_line; nclump-- > 0; ) {
  1692. for (xpos = 0; xpos < hsamp; xpos++)
  1693. *outptr++ = inptr[xpos];
  1694. inptr += samples_per_clump;
  1695. }
  1696. }
  1697. /* pad each scanline as needed */
  1698. for (xpos = 0; xpos < padding; xpos++) {
  1699. *outptr = outptr[-1];
  1700. outptr++;
  1701. }
  1702. clumpoffset += hsamp;
  1703. }
  1704. }
  1705. sp->scancount++;
  1706. if (sp->scancount >= DCTSIZE) {
  1707. int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
  1708. if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
  1709. return (0);
  1710. sp->scancount = 0;
  1711. }
  1712. tif->tif_row += sp->v_sampling;
  1713. buf += bytesperclumpline;
  1714. nrows -= sp->v_sampling;
  1715. }
  1716. return (1);
  1717. }
  1718. /*
  1719. * Finish up at the end of a strip or tile.
  1720. */
  1721. static int
  1722. JPEGPostEncode(TIFF* tif)
  1723. {
  1724. JPEGState *sp = JState(tif);
  1725. if (sp->scancount > 0) {
  1726. /*
  1727. * Need to emit a partial bufferload of downsampled data.
  1728. * Pad the data vertically.
  1729. */
  1730. int ci, ypos, n;
  1731. jpeg_component_info* compptr;
  1732. for (ci = 0, compptr = sp->cinfo.c.comp_info;
  1733. ci < sp->cinfo.c.num_components;
  1734. ci++, compptr++) {
  1735. int vsamp = compptr->v_samp_factor;
  1736. tmsize_t row_width = compptr->width_in_blocks * DCTSIZE
  1737. * sizeof(JSAMPLE);
  1738. for (ypos = sp->scancount * vsamp;
  1739. ypos < DCTSIZE * vsamp; ypos++) {
  1740. _TIFFmemcpy((void*)sp->ds_buffer[ci][ypos],
  1741. (void*)sp->ds_buffer[ci][ypos-1],
  1742. row_width);
  1743. }
  1744. }
  1745. n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
  1746. if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
  1747. return (0);
  1748. }
  1749. return (TIFFjpeg_finish_compress(JState(tif)));
  1750. }
  1751. static void
  1752. JPEGCleanup(TIFF* tif)
  1753. {
  1754. JPEGState *sp = JState(tif);
  1755. assert(sp != 0);
  1756. tif->tif_tagmethods.vgetfield = sp->vgetparent;
  1757. tif->tif_tagmethods.vsetfield = sp->vsetparent;
  1758. tif->tif_tagmethods.printdir = sp->printdir;
  1759. if( sp != NULL ) {
  1760. if( sp->cinfo_initialized )
  1761. TIFFjpeg_destroy(sp); /* release libjpeg resources */
  1762. if (sp->jpegtables) /* tag value */
  1763. _TIFFfree(sp->jpegtables);
  1764. }
  1765. _TIFFfree(tif->tif_data); /* release local state */
  1766. tif->tif_data = NULL;
  1767. _TIFFSetDefaultCompressionState(tif);
  1768. }
  1769. static void
  1770. JPEGResetUpsampled( TIFF* tif )
  1771. {
  1772. JPEGState* sp = JState(tif);
  1773. TIFFDirectory* td = &tif->tif_dir;
  1774. /*
  1775. * Mark whether returned data is up-sampled or not so TIFFStripSize
  1776. * and TIFFTileSize return values that reflect the true amount of
  1777. * data.
  1778. */
  1779. tif->tif_flags &= ~TIFF_UPSAMPLED;
  1780. if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
  1781. if (td->td_photometric == PHOTOMETRIC_YCBCR &&
  1782. sp->jpegcolormode == JPEGCOLORMODE_RGB) {
  1783. tif->tif_flags |= TIFF_UPSAMPLED;
  1784. } else {
  1785. #ifdef notdef
  1786. if (td->td_ycbcrsubsampling[0] != 1 ||
  1787. td->td_ycbcrsubsampling[1] != 1)
  1788. ; /* XXX what about up-sampling? */
  1789. #endif
  1790. }
  1791. }
  1792. /*
  1793. * Must recalculate cached tile size in case sampling state changed.
  1794. * Should we really be doing this now if image size isn't set?
  1795. */
  1796. if( tif->tif_tilesize > 0 )
  1797. tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
  1798. if( tif->tif_scanlinesize > 0 )
  1799. tif->tif_scanlinesize = TIFFScanlineSize(tif);
  1800. }
  1801. static int
  1802. JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
  1803. {
  1804. JPEGState* sp = JState(tif);
  1805. const TIFFField* fip;
  1806. uint32 v32;
  1807. assert(sp != NULL);
  1808. switch (tag) {
  1809. case TIFFTAG_JPEGTABLES:
  1810. v32 = (uint32) va_arg(ap, uint32);
  1811. if (v32 == 0) {
  1812. /* XXX */
  1813. return (0);
  1814. }
  1815. _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
  1816. (long) v32);
  1817. sp->jpegtables_length = v32;
  1818. TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
  1819. break;
  1820. case TIFFTAG_JPEGQUALITY:
  1821. sp->jpegquality = (int) va_arg(ap, int);
  1822. return (1); /* pseudo tag */
  1823. case TIFFTAG_JPEGCOLORMODE:
  1824. sp->jpegcolormode = (int) va_arg(ap, int);
  1825. JPEGResetUpsampled( tif );
  1826. return (1); /* pseudo tag */
  1827. case TIFFTAG_PHOTOMETRIC:
  1828. {
  1829. int ret_value = (*sp->vsetparent)(tif, tag, ap);
  1830. JPEGResetUpsampled( tif );
  1831. return ret_value;
  1832. }
  1833. case TIFFTAG_JPEGTABLESMODE:
  1834. sp->jpegtablesmode = (int) va_arg(ap, int);
  1835. return (1); /* pseudo tag */
  1836. case TIFFTAG_YCBCRSUBSAMPLING:
  1837. /* mark the fact that we have a real ycbcrsubsampling! */
  1838. sp->ycbcrsampling_fetched = 1;
  1839. /* should we be recomputing upsampling info here? */
  1840. return (*sp->vsetparent)(tif, tag, ap);
  1841. default:
  1842. return (*sp->vsetparent)(tif, tag, ap);
  1843. }
  1844. if ((fip = TIFFFieldWithTag(tif, tag))) {
  1845. TIFFSetFieldBit(tif, fip->field_bit);
  1846. } else {
  1847. return (0);
  1848. }
  1849. tif->tif_flags |= TIFF_DIRTYDIRECT;
  1850. return (1);
  1851. }
  1852. static int
  1853. JPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
  1854. {
  1855. JPEGState* sp = JState(tif);
  1856. assert(sp != NULL);
  1857. switch (tag) {
  1858. case TIFFTAG_JPEGTABLES:
  1859. *va_arg(ap, uint32*) = sp->jpegtables_length;
  1860. *va_arg(ap, void**) = sp->jpegtables;
  1861. break;
  1862. case TIFFTAG_JPEGQUALITY:
  1863. *va_arg(ap, int*) = sp->jpegquality;
  1864. break;
  1865. case TIFFTAG_JPEGCOLORMODE:
  1866. *va_arg(ap, int*) = sp->jpegcolormode;
  1867. break;
  1868. case TIFFTAG_JPEGTABLESMODE:
  1869. *va_arg(ap, int*) = sp->jpegtablesmode;
  1870. break;
  1871. default:
  1872. return (*sp->vgetparent)(tif, tag, ap);
  1873. }
  1874. return (1);
  1875. }
  1876. static void
  1877. JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
  1878. {
  1879. JPEGState* sp = JState(tif);
  1880. assert(sp != NULL);
  1881. (void) flags;
  1882. if( sp != NULL ) {
  1883. if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
  1884. fprintf(fd, " JPEG Tables: (%lu bytes)\n",
  1885. (unsigned long) sp->jpegtables_length);
  1886. if (sp->printdir)
  1887. (*sp->printdir)(tif, fd, flags);
  1888. }
  1889. }
  1890. static uint32
  1891. JPEGDefaultStripSize(TIFF* tif, uint32 s)
  1892. {
  1893. JPEGState* sp = JState(tif);
  1894. TIFFDirectory *td = &tif->tif_dir;
  1895. s = (*sp->defsparent)(tif, s);
  1896. if (s < td->td_imagelength)
  1897. s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
  1898. return (s);
  1899. }
  1900. static void
  1901. JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
  1902. {
  1903. JPEGState* sp = JState(tif);
  1904. TIFFDirectory *td = &tif->tif_dir;
  1905. (*sp->deftparent)(tif, tw, th);
  1906. *tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
  1907. *th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
  1908. }
  1909. /*
  1910. * The JPEG library initialized used to be done in TIFFInitJPEG(), but
  1911. * now that we allow a TIFF file to be opened in update mode it is necessary
  1912. * to have some way of deciding whether compression or decompression is
  1913. * desired other than looking at tif->tif_mode. We accomplish this by
  1914. * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
  1915. * If so, we assume decompression is desired.
  1916. *
  1917. * This is tricky, because TIFFInitJPEG() is called while the directory is
  1918. * being read, and generally speaking the BYTECOUNTS tag won't have been read
  1919. * at that point. So we try to defer jpeg library initialization till we
  1920. * do have that tag ... basically any access that might require the compressor
  1921. * or decompressor that occurs after the reading of the directory.
  1922. *
  1923. * In an ideal world compressors or decompressors would be setup
  1924. * at the point where a single tile or strip was accessed (for read or write)
  1925. * so that stuff like update of missing tiles, or replacement of tiles could
  1926. * be done. However, we aren't trying to crack that nut just yet ...
  1927. *
  1928. * NFW, Feb 3rd, 2003.
  1929. */
  1930. static int JPEGInitializeLibJPEG( TIFF * tif, int decompress )
  1931. {
  1932. JPEGState* sp = JState(tif);
  1933. if(sp->cinfo_initialized)
  1934. {
  1935. if( !decompress && sp->cinfo.comm.is_decompressor )
  1936. TIFFjpeg_destroy( sp );
  1937. else if( decompress && !sp->cinfo.comm.is_decompressor )
  1938. TIFFjpeg_destroy( sp );
  1939. else
  1940. return 1;
  1941. sp->cinfo_initialized = 0;
  1942. }
  1943. /*
  1944. * Initialize libjpeg.
  1945. */
  1946. if ( decompress ) {
  1947. if (!TIFFjpeg_create_decompress(sp))
  1948. return (0);
  1949. } else {
  1950. if (!TIFFjpeg_create_compress(sp))
  1951. return (0);
  1952. }
  1953. sp->cinfo_initialized = TRUE;
  1954. return 1;
  1955. }
  1956. int
  1957. TIFFInitJPEG(TIFF* tif, int scheme)
  1958. {
  1959. JPEGState* sp;
  1960. assert(scheme == COMPRESSION_JPEG);
  1961. /*
  1962. * Merge codec-specific tag information.
  1963. */
  1964. if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields))) {
  1965. TIFFErrorExt(tif->tif_clientdata,
  1966. "TIFFInitJPEG",
  1967. "Merging JPEG codec-specific tags failed");
  1968. return 0;
  1969. }
  1970. /*
  1971. * Allocate state block so tag methods have storage to record values.
  1972. */
  1973. tif->tif_data = (uint8*) _TIFFmalloc(sizeof (JPEGState));
  1974. if (tif->tif_data == NULL) {
  1975. TIFFErrorExt(tif->tif_clientdata,
  1976. "TIFFInitJPEG", "No space for JPEG state block");
  1977. return 0;
  1978. }
  1979. _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
  1980. sp = JState(tif);
  1981. sp->tif = tif; /* back link */
  1982. /*
  1983. * Override parent get/set field methods.
  1984. */
  1985. sp->vgetparent = tif->tif_tagmethods.vgetfield;
  1986. tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
  1987. sp->vsetparent = tif->tif_tagmethods.vsetfield;
  1988. tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
  1989. sp->printdir = tif->tif_tagmethods.printdir;
  1990. tif->tif_tagmethods.printdir = JPEGPrintDir; /* hook for codec tags */
  1991. /* Default values for codec-specific fields */
  1992. sp->jpegtables = NULL;
  1993. sp->jpegtables_length = 0;
  1994. sp->jpegquality = 75; /* Default IJG quality */
  1995. sp->jpegcolormode = JPEGCOLORMODE_RAW;
  1996. sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
  1997. sp->ycbcrsampling_fetched = 0;
  1998. /*
  1999. * Install codec methods.
  2000. */
  2001. tif->tif_fixuptags = JPEGFixupTags;
  2002. tif->tif_setupdecode = JPEGSetupDecode;
  2003. tif->tif_predecode = JPEGPreDecode;
  2004. tif->tif_decoderow = JPEGDecode;
  2005. tif->tif_decodestrip = JPEGDecode;
  2006. tif->tif_decodetile = JPEGDecode;
  2007. tif->tif_setupencode = JPEGSetupEncode;
  2008. tif->tif_preencode = JPEGPreEncode;
  2009. tif->tif_postencode = JPEGPostEncode;
  2010. tif->tif_encoderow = JPEGEncode;
  2011. tif->tif_encodestrip = JPEGEncode;
  2012. tif->tif_encodetile = JPEGEncode;
  2013. tif->tif_cleanup = JPEGCleanup;
  2014. sp->defsparent = tif->tif_defstripsize;
  2015. tif->tif_defstripsize = JPEGDefaultStripSize;
  2016. sp->deftparent = tif->tif_deftilesize;
  2017. tif->tif_deftilesize = JPEGDefaultTileSize;
  2018. tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
  2019. sp->cinfo_initialized = FALSE;
  2020. /*
  2021. ** Create a JPEGTables field if no directory has yet been created.
  2022. ** We do this just to ensure that sufficient space is reserved for
  2023. ** the JPEGTables field. It will be properly created the right
  2024. ** size later.
  2025. */
  2026. if( tif->tif_diroff == 0 )
  2027. {
  2028. #define SIZE_OF_JPEGTABLES 2000
  2029. /*
  2030. The following line assumes incorrectly that all JPEG-in-TIFF files will have
  2031. a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
  2032. when the JPEG data is placed with TIFFWriteRawStrip. The field bit should be
  2033. set, anyway, later when actual JPEGTABLES header is generated, so removing it
  2034. here hopefully is harmless.
  2035. TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
  2036. */
  2037. sp->jpegtables_length = SIZE_OF_JPEGTABLES;
  2038. sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
  2039. // FIXME: NULL-deref after malloc failure
  2040. _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
  2041. #undef SIZE_OF_JPEGTABLES
  2042. }
  2043. return 1;
  2044. }
  2045. #endif /* JPEG_SUPPORT */
  2046. /* vim: set ts=8 sts=8 sw=8 noet: */
  2047. /*
  2048. * Local Variables:
  2049. * mode: c
  2050. * c-basic-offset: 8
  2051. * fill-column: 78
  2052. * End:
  2053. */