tif_jpeg.c 72 KB

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