tif_jpeg.c 96 KB

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