tif_jpeg.c 79 KB

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