tif_jpeg.c 95 KB

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