tif_jpeg.c 96 KB

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