tif_jpeg.c 79 KB

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