TiffDecode.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. /*
  2. * The Python Imaging Library.
  3. * $Id: //modules/pil/libImaging/TiffDecode.c#1 $
  4. *
  5. * LibTiff-based Group3 and Group4 decoder
  6. *
  7. *
  8. * started modding to use non-private tiff functions to port to libtiff 4.x
  9. * eds 3/12/12
  10. *
  11. */
  12. #include "Imaging.h"
  13. #ifdef HAVE_LIBTIFF
  14. #ifdef HAVE_UNISTD_H
  15. #include <unistd.h> /* lseek */
  16. #endif
  17. #ifndef uint
  18. #define uint uint32
  19. #endif
  20. #include "TiffDecode.h"
  21. /* Convert C file descriptor to WinApi HFILE if LibTiff was compiled with tif_win32.c
  22. *
  23. * This cast is safe, as the top 32-bits of HFILE are guaranteed to be zero,
  24. * see
  25. * https://learn.microsoft.com/en-us/windows/win32/winprog64/interprocess-communication
  26. */
  27. #ifndef USE_WIN32_FILEIO
  28. #define fd_to_tiff_fd(fd) (fd)
  29. #else
  30. #define fd_to_tiff_fd(fd) ((int)_get_osfhandle(fd))
  31. #endif
  32. void
  33. dump_state(const TIFFSTATE *state) {
  34. TRACE(
  35. ("State: Location %u size %d eof %d data: %p ifd: %d\n",
  36. (uint)state->loc,
  37. (int)state->size,
  38. (uint)state->eof,
  39. state->data,
  40. state->ifd));
  41. }
  42. /*
  43. procs for TIFFOpenClient
  44. */
  45. tsize_t
  46. _tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) {
  47. TIFFSTATE *state = (TIFFSTATE *)hdata;
  48. tsize_t to_read;
  49. TRACE(("_tiffReadProc: %d \n", (int)size));
  50. dump_state(state);
  51. if (state->loc > state->eof) {
  52. TIFFError("_tiffReadProc", "Invalid Read at loc %" PRIu64 ", eof: %" PRIu64, state->loc, state->eof);
  53. return 0;
  54. }
  55. to_read = min(size, min(state->size, (tsize_t)state->eof) - (tsize_t)state->loc);
  56. TRACE(("to_read: %d\n", (int)to_read));
  57. _TIFFmemcpy(buf, (UINT8 *)state->data + state->loc, to_read);
  58. state->loc += (toff_t)to_read;
  59. TRACE(("location: %u\n", (uint)state->loc));
  60. return to_read;
  61. }
  62. tsize_t
  63. _tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) {
  64. TIFFSTATE *state = (TIFFSTATE *)hdata;
  65. tsize_t to_write;
  66. TRACE(("_tiffWriteProc: %d \n", (int)size));
  67. dump_state(state);
  68. to_write = min(size, state->size - (tsize_t)state->loc);
  69. if (state->flrealloc && size > to_write) {
  70. tdata_t new_data;
  71. tsize_t newsize = state->size;
  72. while (newsize < (size + state->size)) {
  73. if (newsize > INT_MAX - 64 * 1024) {
  74. return 0;
  75. }
  76. newsize += 64 * 1024;
  77. // newsize*=2; // UNDONE, by 64k chunks?
  78. }
  79. TRACE(("Reallocing in write to %d bytes\n", (int)newsize));
  80. /* malloc check ok, overflow checked above */
  81. new_data = realloc(state->data, newsize);
  82. if (!new_data) {
  83. // fail out
  84. return 0;
  85. }
  86. state->data = new_data;
  87. state->size = newsize;
  88. to_write = size;
  89. }
  90. TRACE(("to_write: %d\n", (int)to_write));
  91. _TIFFmemcpy((UINT8 *)state->data + state->loc, buf, to_write);
  92. state->loc += (toff_t)to_write;
  93. state->eof = max(state->loc, state->eof);
  94. dump_state(state);
  95. return to_write;
  96. }
  97. toff_t
  98. _tiffSeekProc(thandle_t hdata, toff_t off, int whence) {
  99. TIFFSTATE *state = (TIFFSTATE *)hdata;
  100. TRACE(("_tiffSeekProc: off: %u whence: %d \n", (uint)off, whence));
  101. dump_state(state);
  102. switch (whence) {
  103. case 0:
  104. state->loc = off;
  105. break;
  106. case 1:
  107. state->loc += off;
  108. break;
  109. case 2:
  110. state->loc = state->eof + off;
  111. break;
  112. }
  113. dump_state(state);
  114. return state->loc;
  115. }
  116. int
  117. _tiffCloseProc(thandle_t hdata) {
  118. TIFFSTATE *state = (TIFFSTATE *)hdata;
  119. TRACE(("_tiffCloseProc \n"));
  120. dump_state(state);
  121. return 0;
  122. }
  123. toff_t
  124. _tiffSizeProc(thandle_t hdata) {
  125. TIFFSTATE *state = (TIFFSTATE *)hdata;
  126. TRACE(("_tiffSizeProc \n"));
  127. dump_state(state);
  128. return (toff_t)state->size;
  129. }
  130. int
  131. _tiffMapProc(thandle_t hdata, tdata_t *pbase, toff_t *psize) {
  132. TIFFSTATE *state = (TIFFSTATE *)hdata;
  133. TRACE(("_tiffMapProc input size: %u, data: %p\n", (uint)*psize, *pbase));
  134. dump_state(state);
  135. *pbase = state->data;
  136. *psize = state->size;
  137. TRACE(("_tiffMapProc returning size: %u, data: %p\n", (uint)*psize, *pbase));
  138. return (1);
  139. }
  140. int
  141. _tiffNullMapProc(thandle_t hdata, tdata_t *pbase, toff_t *psize) {
  142. (void)hdata;
  143. (void)pbase;
  144. (void)psize;
  145. return (0);
  146. }
  147. void
  148. _tiffUnmapProc(thandle_t hdata, tdata_t base, toff_t size) {
  149. TRACE(("_tiffUnMapProc\n"));
  150. (void)hdata;
  151. (void)base;
  152. (void)size;
  153. }
  154. int
  155. ImagingLibTiffInit(ImagingCodecState state, int fp, uint32_t offset) {
  156. TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
  157. TRACE(("initing libtiff\n"));
  158. TRACE(("filepointer: %d \n", fp));
  159. TRACE(
  160. ("State: count %d, state %d, x %d, y %d, ystep %d\n",
  161. state->count,
  162. state->state,
  163. state->x,
  164. state->y,
  165. state->ystep));
  166. TRACE(
  167. ("State: xsize %d, ysize %d, xoff %d, yoff %d \n",
  168. state->xsize,
  169. state->ysize,
  170. state->xoff,
  171. state->yoff));
  172. TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes));
  173. TRACE(("State: context %p \n", state->context));
  174. clientstate->loc = 0;
  175. clientstate->size = 0;
  176. clientstate->data = 0;
  177. clientstate->fp = fp;
  178. clientstate->ifd = offset;
  179. clientstate->eof = 0;
  180. return 1;
  181. }
  182. int
  183. _pickUnpackers(Imaging im, ImagingCodecState state, TIFF *tiff, uint16_t planarconfig, ImagingShuffler *unpackers) {
  184. // if number of bands is 1, there is no difference with contig case
  185. if (planarconfig == PLANARCONFIG_SEPARATE && im->bands > 1) {
  186. uint16_t bits_per_sample = 8;
  187. TIFFGetFieldDefaulted(tiff, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);
  188. if (bits_per_sample != 8 && bits_per_sample != 16) {
  189. TRACE(("Invalid value for bits per sample: %d\n", bits_per_sample));
  190. state->errcode = IMAGING_CODEC_BROKEN;
  191. return -1;
  192. }
  193. // We'll pick appropriate set of unpackers depending on planar_configuration
  194. // It does not matter if data is RGB(A), CMYK or LUV really,
  195. // we just copy it plane by plane
  196. unpackers[0] = ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "R;16N" : "R", NULL);
  197. unpackers[1] = ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "G;16N" : "G", NULL);
  198. unpackers[2] = ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "B;16N" : "B", NULL);
  199. unpackers[3] = ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "A;16N" : "A", NULL);
  200. return im->bands;
  201. } else {
  202. unpackers[0] = state->shuffle;
  203. return 1;
  204. }
  205. }
  206. int
  207. _decodeAsRGBA(Imaging im, ImagingCodecState state, TIFF *tiff) {
  208. // To avoid dealing with YCbCr subsampling and other complications, let libtiff handle it
  209. // Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle
  210. // all of the conversion. Metadata read from the TIFFRGBAImage could
  211. // be different from the metadata that the base tiff returns.
  212. INT32 current_row;
  213. UINT8 *new_data;
  214. UINT32 rows_per_block, row_byte_size, rows_to_read;
  215. int ret;
  216. TIFFRGBAImage img;
  217. char emsg[1024] = "";
  218. // Since using TIFFRGBAImage* functions, we can read whole tiff into rastrr in one call
  219. // Let's select smaller block size. Multiplying image width by (tile length OR rows per strip)
  220. // gives us manageable block size in pixels
  221. if (TIFFIsTiled(tiff)) {
  222. ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_TILELENGTH, &rows_per_block);
  223. }
  224. else {
  225. ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_block);
  226. }
  227. if (ret != 1 || rows_per_block==(UINT32)(-1)) {
  228. rows_per_block = state->ysize;
  229. }
  230. TRACE(("RowsPerBlock: %u \n", rows_per_block));
  231. if (!(TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg))) {
  232. TRACE(("Decode error, msg: %s", emsg));
  233. state->errcode = IMAGING_CODEC_BROKEN;
  234. // nothing to clean up, just return
  235. return -1;
  236. }
  237. img.req_orientation = ORIENTATION_TOPLEFT;
  238. img.col_offset = 0;
  239. /* overflow check for row byte size */
  240. if (INT_MAX / 4 < img.width) {
  241. state->errcode = IMAGING_CODEC_MEMORY;
  242. goto decodergba_err;
  243. }
  244. // TiffRGBAImages are 32bits/pixel.
  245. row_byte_size = img.width * 4;
  246. /* overflow check for realloc */
  247. if (INT_MAX / row_byte_size < rows_per_block) {
  248. state->errcode = IMAGING_CODEC_MEMORY;
  249. goto decodergba_err;
  250. }
  251. state->bytes = rows_per_block * row_byte_size;
  252. TRACE(("BlockSize: %d \n", state->bytes));
  253. /* realloc to fit whole strip */
  254. /* malloc check above */
  255. new_data = realloc(state->buffer, state->bytes);
  256. if (!new_data) {
  257. state->errcode = IMAGING_CODEC_MEMORY;
  258. goto decodergba_err;
  259. }
  260. state->buffer = new_data;
  261. for (; state->y < state->ysize; state->y += rows_per_block) {
  262. img.row_offset = state->y;
  263. rows_to_read = min(rows_per_block, img.height - state->y);
  264. if (!TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read)) {
  265. TRACE(("Decode Error, y: %d\n", state->y));
  266. state->errcode = IMAGING_CODEC_BROKEN;
  267. goto decodergba_err;
  268. }
  269. #if WORDS_BIGENDIAN
  270. TIFFSwabArrayOfLong((UINT32 *)state->buffer, img.width * rows_to_read);
  271. #endif
  272. TRACE(("Decoded strip for row %d \n", state->y));
  273. // iterate over each row in the strip and stuff data into image
  274. for (current_row = 0;
  275. current_row < min((INT32)rows_per_block, state->ysize - state->y);
  276. current_row++) {
  277. TRACE(("Writing data into line %d ; \n", state->y + current_row));
  278. // UINT8 * bbb = state->buffer + current_row * (state->bytes /
  279. // rows_per_block); TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0],
  280. // ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));
  281. state->shuffle(
  282. (UINT8 *)im->image[state->y + state->yoff + current_row] +
  283. state->xoff * im->pixelsize,
  284. state->buffer + current_row * row_byte_size,
  285. state->xsize);
  286. }
  287. }
  288. decodergba_err:
  289. TIFFRGBAImageEnd(&img);
  290. if (state->errcode != 0) {
  291. return -1;
  292. }
  293. return 0;
  294. }
  295. int
  296. _decodeTile(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, ImagingShuffler *unpackers) {
  297. INT32 x, y, tile_y, current_tile_length, current_tile_width;
  298. UINT32 tile_width, tile_length;
  299. tsize_t tile_bytes_size, row_byte_size;
  300. UINT8 *new_data;
  301. tile_bytes_size = TIFFTileSize(tiff);
  302. if (tile_bytes_size == 0) {
  303. TRACE(("Decode Error, Can not calculate TileSize\n"));
  304. state->errcode = IMAGING_CODEC_BROKEN;
  305. return -1;
  306. }
  307. row_byte_size = TIFFTileRowSize(tiff);
  308. if (row_byte_size == 0 || row_byte_size > tile_bytes_size) {
  309. TRACE(("Decode Error, Can not calculate TileRowSize\n"));
  310. state->errcode = IMAGING_CODEC_BROKEN;
  311. return -1;
  312. }
  313. /* overflow check for realloc */
  314. if (tile_bytes_size > INT_MAX - 1) {
  315. state->errcode = IMAGING_CODEC_MEMORY;
  316. return -1;
  317. }
  318. TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width);
  319. TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length);
  320. if (tile_width > INT_MAX || tile_length > INT_MAX) {
  321. // state->x and state->y are ints
  322. state->errcode = IMAGING_CODEC_MEMORY;
  323. return -1;
  324. }
  325. if (tile_bytes_size > ((tile_length * state->bits / planes + 7) / 8) * tile_width) {
  326. // If the tile size as expected by LibTiff isn't what we're expecting, abort.
  327. // man: TIFFTileSize returns the equivalent size for a tile of data as it would be returned in a
  328. // call to TIFFReadTile ...
  329. state->errcode = IMAGING_CODEC_BROKEN;
  330. return -1;
  331. }
  332. state->bytes = tile_bytes_size;
  333. TRACE(("TIFFTileSize: %d\n", state->bytes));
  334. /* realloc to fit whole tile */
  335. /* malloc check above */
  336. new_data = realloc(state->buffer, state->bytes);
  337. if (!new_data) {
  338. state->errcode = IMAGING_CODEC_MEMORY;
  339. return -1;
  340. }
  341. state->buffer = new_data;
  342. for (y = state->yoff; y < state->ysize; y += tile_length) {
  343. int plane;
  344. for (plane = 0; plane < planes; plane++) {
  345. ImagingShuffler shuffler = unpackers[plane];
  346. for (x = state->xoff; x < state->xsize; x += tile_width) {
  347. if (TIFFReadTile(tiff, (tdata_t)state->buffer, x, y, 0, plane) == -1) {
  348. TRACE(("Decode Error, Tile at %dx%d\n", x, y));
  349. state->errcode = IMAGING_CODEC_BROKEN;
  350. return -1;
  351. }
  352. TRACE(("Read tile at %dx%d; \n\n", x, y));
  353. current_tile_width = min((INT32) tile_width, state->xsize - x);
  354. current_tile_length = min((INT32) tile_length, state->ysize - y);
  355. // iterate over each line in the tile and stuff data into image
  356. for (tile_y = 0; tile_y < current_tile_length; tile_y++) {
  357. TRACE(("Writing tile data at %dx%d using tile_width: %d; \n", tile_y + y, x, current_tile_width));
  358. // UINT8 * bbb = state->buffer + tile_y * row_byte_size;
  359. // TRACE(("chars: %x%x%x%x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));
  360. shuffler((UINT8*) im->image[tile_y + y] + x * im->pixelsize,
  361. state->buffer + tile_y * row_byte_size,
  362. current_tile_width
  363. );
  364. }
  365. }
  366. }
  367. }
  368. return 0;
  369. }
  370. int
  371. _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, ImagingShuffler *unpackers) {
  372. INT32 strip_row = 0;
  373. UINT8 *new_data;
  374. UINT32 rows_per_strip;
  375. int ret;
  376. tsize_t strip_size, row_byte_size, unpacker_row_byte_size;
  377. ret = TIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);
  378. if (ret != 1 || rows_per_strip==(UINT32)(-1)) {
  379. rows_per_strip = state->ysize;
  380. }
  381. if (rows_per_strip > INT_MAX) {
  382. state->errcode = IMAGING_CODEC_MEMORY;
  383. return -1;
  384. }
  385. TRACE(("RowsPerStrip: %u\n", rows_per_strip));
  386. strip_size = TIFFStripSize(tiff);
  387. if (strip_size > INT_MAX - 1) {
  388. state->errcode = IMAGING_CODEC_MEMORY;
  389. return -1;
  390. }
  391. unpacker_row_byte_size = (state->xsize * state->bits / planes + 7) / 8;
  392. if (strip_size > (unpacker_row_byte_size * rows_per_strip)) {
  393. // If the strip size as expected by LibTiff isn't what we're expecting, abort.
  394. // man: TIFFStripSize returns the equivalent size for a strip of data as it would be returned in a
  395. // call to TIFFReadEncodedStrip ...
  396. state->errcode = IMAGING_CODEC_BROKEN;
  397. return -1;
  398. }
  399. state->bytes = strip_size;
  400. TRACE(("StripSize: %d \n", state->bytes));
  401. row_byte_size = TIFFScanlineSize(tiff);
  402. // if the unpacker calculated row size is > row byte size, (at least) the last
  403. // row of the strip will have a read buffer overflow.
  404. if (row_byte_size == 0 || unpacker_row_byte_size > row_byte_size) {
  405. state->errcode = IMAGING_CODEC_BROKEN;
  406. return -1;
  407. }
  408. TRACE(("RowsByteSize: %u \n", row_byte_size));
  409. /* realloc to fit whole strip */
  410. /* malloc check above */
  411. new_data = realloc(state->buffer, state->bytes);
  412. if (!new_data) {
  413. state->errcode = IMAGING_CODEC_MEMORY;
  414. return -1;
  415. }
  416. state->buffer = new_data;
  417. for (; state->y < state->ysize; state->y += rows_per_strip) {
  418. int plane;
  419. for (plane = 0; plane < planes; plane++) {
  420. ImagingShuffler shuffler = unpackers[plane];
  421. if (TIFFReadEncodedStrip(tiff, TIFFComputeStrip(tiff, state->y, plane), (tdata_t)state->buffer, strip_size) == -1) {
  422. TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, state->y, 0)));
  423. state->errcode = IMAGING_CODEC_BROKEN;
  424. return -1;
  425. }
  426. TRACE(("Decoded strip for row %d \n", state->y));
  427. // iterate over each row in the strip and stuff data into image
  428. for (strip_row = 0;
  429. strip_row < min((INT32) rows_per_strip, state->ysize - state->y);
  430. strip_row++) {
  431. TRACE(("Writing data into line %d ; \n", state->y + strip_row));
  432. // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip);
  433. // TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));
  434. shuffler(
  435. (UINT8*) im->image[state->y + state->yoff + strip_row] +
  436. state->xoff * im->pixelsize,
  437. state->buffer + strip_row * row_byte_size,
  438. state->xsize);
  439. }
  440. }
  441. }
  442. return 0;
  443. }
  444. int
  445. ImagingLibTiffDecode(
  446. Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes) {
  447. TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
  448. char *filename = "tempfile.tif";
  449. char *mode = "rC";
  450. TIFF *tiff;
  451. uint16_t photometric = 0; // init to not PHOTOMETRIC_YCBCR
  452. uint16_t compression;
  453. int readAsRGBA = 0;
  454. uint16_t planarconfig = 0;
  455. int planes = 1;
  456. ImagingShuffler unpackers[4];
  457. INT32 img_width, img_height;
  458. memset(unpackers, 0, sizeof(ImagingShuffler) * 4);
  459. /* buffer is the encoded file, bytes is the length of the encoded file */
  460. /* it all ends up in state->buffer, which is a uint8* from Imaging.h */
  461. TRACE(("in decoder: bytes %d\n", bytes));
  462. TRACE(
  463. ("State: count %d, state %d, x %d, y %d, ystep %d\n",
  464. state->count,
  465. state->state,
  466. state->x,
  467. state->y,
  468. state->ystep));
  469. TRACE(
  470. ("State: xsize %d, ysize %d, xoff %d, yoff %d \n",
  471. state->xsize,
  472. state->ysize,
  473. state->xoff,
  474. state->yoff));
  475. TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes));
  476. TRACE(
  477. ("Buffer: %p: %c%c%c%c\n",
  478. buffer,
  479. (char)buffer[0],
  480. (char)buffer[1],
  481. (char)buffer[2],
  482. (char)buffer[3]));
  483. TRACE(
  484. ("State->Buffer: %c%c%c%c\n",
  485. (char)state->buffer[0],
  486. (char)state->buffer[1],
  487. (char)state->buffer[2],
  488. (char)state->buffer[3]));
  489. TRACE(
  490. ("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n",
  491. im->mode,
  492. im->type,
  493. im->bands,
  494. im->xsize,
  495. im->ysize));
  496. TRACE(
  497. ("Image: image8 %p, image32 %p, image %p, block %p \n",
  498. im->image8,
  499. im->image32,
  500. im->image,
  501. im->block));
  502. TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize));
  503. dump_state(clientstate);
  504. clientstate->size = bytes;
  505. clientstate->eof = clientstate->size;
  506. clientstate->loc = 0;
  507. clientstate->data = (tdata_t)buffer;
  508. clientstate->flrealloc = 0;
  509. dump_state(clientstate);
  510. TIFFSetWarningHandler(NULL);
  511. TIFFSetWarningHandlerExt(NULL);
  512. if (clientstate->fp) {
  513. TRACE(("Opening using fd: %d\n", clientstate->fp));
  514. lseek(clientstate->fp, 0, SEEK_SET); // Sometimes, I get it set to the end.
  515. tiff = TIFFFdOpen(fd_to_tiff_fd(clientstate->fp), filename, mode);
  516. } else {
  517. TRACE(("Opening from string\n"));
  518. tiff = TIFFClientOpen(
  519. filename,
  520. mode,
  521. (thandle_t)clientstate,
  522. _tiffReadProc,
  523. _tiffWriteProc,
  524. _tiffSeekProc,
  525. _tiffCloseProc,
  526. _tiffSizeProc,
  527. _tiffMapProc,
  528. _tiffUnmapProc);
  529. }
  530. if (!tiff) {
  531. TRACE(("Error, didn't get the tiff\n"));
  532. state->errcode = IMAGING_CODEC_BROKEN;
  533. return -1;
  534. }
  535. if (clientstate->ifd) {
  536. int rv;
  537. uint32_t ifdoffset = clientstate->ifd;
  538. TRACE(("reading tiff ifd %u\n", ifdoffset));
  539. rv = TIFFSetSubDirectory(tiff, ifdoffset);
  540. if (!rv) {
  541. TRACE(("error in TIFFSetSubDirectory"));
  542. goto decode_err;
  543. }
  544. }
  545. TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &img_width);
  546. TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &img_height);
  547. if (state->xsize != img_width || state->ysize != img_height) {
  548. TRACE(
  549. ("Inconsistent Image Error: %d =? %d, %d =? %d",
  550. state->xsize,
  551. img_width,
  552. state->ysize,
  553. img_height));
  554. state->errcode = IMAGING_CODEC_BROKEN;
  555. goto decode_err;
  556. }
  557. TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric);
  558. TIFFGetField(tiff, TIFFTAG_COMPRESSION, &compression);
  559. TIFFGetFieldDefaulted(tiff, TIFFTAG_PLANARCONFIG, &planarconfig);
  560. // Dealing with YCbCr images is complicated in case if subsampling
  561. // Let LibTiff read them as RGBA
  562. readAsRGBA = photometric == PHOTOMETRIC_YCBCR;
  563. if (readAsRGBA && compression == COMPRESSION_JPEG && planarconfig == PLANARCONFIG_CONTIG) {
  564. // If using new JPEG compression, let libjpeg do RGB conversion for performance reasons
  565. TIFFSetField(tiff, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
  566. readAsRGBA = 0;
  567. }
  568. if (readAsRGBA) {
  569. _decodeAsRGBA(im, state, tiff);
  570. }
  571. else {
  572. planes = _pickUnpackers(im, state, tiff, planarconfig, unpackers);
  573. if (planes <= 0) {
  574. goto decode_err;
  575. }
  576. if (TIFFIsTiled(tiff)) {
  577. _decodeTile(im, state, tiff, planes, unpackers);
  578. }
  579. else {
  580. _decodeStrip(im, state, tiff, planes, unpackers);
  581. }
  582. if (!state->errcode) {
  583. // Check if raw mode was RGBa and it was stored on separate planes
  584. // so we have to convert it to RGBA
  585. if (planes > 3 && strcmp(im->mode, "RGBA") == 0) {
  586. uint16_t extrasamples;
  587. uint16_t* sampleinfo;
  588. ImagingShuffler shuffle;
  589. INT32 y;
  590. TIFFGetFieldDefaulted(tiff, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo);
  591. if (extrasamples >= 1 &&
  592. (sampleinfo[0] == EXTRASAMPLE_UNSPECIFIED || sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA)
  593. ) {
  594. shuffle = ImagingFindUnpacker("RGBA", "RGBa", NULL);
  595. for (y = state->yoff; y < state->ysize; y++) {
  596. UINT8* ptr = (UINT8*) im->image[y + state->yoff] +
  597. state->xoff * im->pixelsize;
  598. shuffle(ptr, ptr, state->xsize);
  599. }
  600. }
  601. }
  602. }
  603. }
  604. decode_err:
  605. // TIFFClose in libtiff calls tif_closeproc and TIFFCleanup
  606. if (clientstate->fp) {
  607. // Pillow will manage the closing of the file rather than libtiff
  608. // So only call TIFFCleanup
  609. TIFFCleanup(tiff);
  610. } else {
  611. // When tif_closeproc refers to our custom _tiffCloseProc though,
  612. // that is fine, as it does not close the file
  613. TIFFClose(tiff);
  614. }
  615. TRACE(("Done Decoding, Returning \n"));
  616. // Returning -1 here to force ImageFile.load to break, rather than
  617. // even think about looping back around.
  618. return -1;
  619. }
  620. int
  621. ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) {
  622. // Open the FD or the pointer as a tiff file, for writing.
  623. // We may have to do some monkeying around to make this really work.
  624. // If we have a fp, then we're good.
  625. // If we have a memory string, we're probably going to have to malloc, then
  626. // shuffle bytes into the writescanline process.
  627. // Going to have to deal with the directory as well.
  628. TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
  629. int bufsize = 64 * 1024;
  630. char *mode = "w";
  631. TRACE(("initing libtiff\n"));
  632. TRACE(("Filename %s, filepointer: %d \n", filename, fp));
  633. TRACE(
  634. ("State: count %d, state %d, x %d, y %d, ystep %d\n",
  635. state->count,
  636. state->state,
  637. state->x,
  638. state->y,
  639. state->ystep));
  640. TRACE(
  641. ("State: xsize %d, ysize %d, xoff %d, yoff %d \n",
  642. state->xsize,
  643. state->ysize,
  644. state->xoff,
  645. state->yoff));
  646. TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes));
  647. TRACE(("State: context %p \n", state->context));
  648. clientstate->loc = 0;
  649. clientstate->size = 0;
  650. clientstate->eof = 0;
  651. clientstate->data = 0;
  652. clientstate->flrealloc = 0;
  653. clientstate->fp = fp;
  654. state->state = 0;
  655. if (fp) {
  656. TRACE(("Opening using fd: %d for writing \n", clientstate->fp));
  657. clientstate->tiff = TIFFFdOpen(fd_to_tiff_fd(clientstate->fp), filename, mode);
  658. } else {
  659. // calloc a buffer to write the tif, we're going to need to realloc or something
  660. // if we need bigger.
  661. TRACE(("Opening a buffer for writing \n"));
  662. /* calloc check ok, small constant allocation */
  663. clientstate->data = calloc(bufsize, 1);
  664. clientstate->size = bufsize;
  665. clientstate->flrealloc = 1;
  666. if (!clientstate->data) {
  667. TRACE(("Error, couldn't allocate a buffer of size %d\n", bufsize));
  668. return 0;
  669. }
  670. clientstate->tiff = TIFFClientOpen(
  671. filename,
  672. mode,
  673. (thandle_t)clientstate,
  674. _tiffReadProc,
  675. _tiffWriteProc,
  676. _tiffSeekProc,
  677. _tiffCloseProc,
  678. _tiffSizeProc,
  679. _tiffNullMapProc,
  680. _tiffUnmapProc); /*force no mmap*/
  681. }
  682. if (!clientstate->tiff) {
  683. TRACE(("Error, couldn't open tiff file\n"));
  684. return 0;
  685. }
  686. return 1;
  687. }
  688. int
  689. ImagingLibTiffMergeFieldInfo(
  690. ImagingCodecState state, TIFFDataType field_type, int key, int is_var_length) {
  691. // Refer to libtiff docs (http://www.simplesystems.org/libtiff/addingtags.html)
  692. TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
  693. uint32_t n;
  694. int status = 0;
  695. // custom fields added with ImagingLibTiffMergeFieldInfo are only used for
  696. // decoding, ignore readcount;
  697. int readcount = is_var_length ? TIFF_VARIABLE : 1;
  698. // we support writing a single value, or a variable number of values
  699. int writecount = is_var_length ? TIFF_VARIABLE : 1;
  700. // whether the first value should encode the number of values.
  701. int passcount = (is_var_length && field_type != TIFF_ASCII) ? 1 : 0;
  702. TIFFFieldInfo info[] = {
  703. {key,
  704. readcount,
  705. writecount,
  706. field_type,
  707. FIELD_CUSTOM,
  708. 1,
  709. passcount,
  710. "CustomField"}};
  711. n = sizeof(info) / sizeof(info[0]);
  712. // Test for libtiff 4.0 or later, excluding libtiff 3.9.6 and 3.9.7
  713. #if TIFFLIB_VERSION >= 20111221 && TIFFLIB_VERSION != 20120218 && \
  714. TIFFLIB_VERSION != 20120922
  715. status = TIFFMergeFieldInfo(clientstate->tiff, info, n);
  716. #else
  717. TIFFMergeFieldInfo(clientstate->tiff, info, n);
  718. #endif
  719. return status;
  720. }
  721. int
  722. ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...) {
  723. // after tif_dir.c->TIFFSetField.
  724. TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
  725. va_list ap;
  726. int status;
  727. va_start(ap, tag);
  728. status = TIFFVSetField(clientstate->tiff, tag, ap);
  729. va_end(ap);
  730. return status;
  731. }
  732. int
  733. ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes) {
  734. /* One shot encoder. Encode everything to the tiff in the clientstate.
  735. If we're running off of a FD, then run once, we're good, everything
  736. ends up in the file, we close and we're done.
  737. If we're going to memory, then we need to write the whole file into memory, then
  738. parcel it back out to the pystring buffer bytes at a time.
  739. */
  740. TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
  741. TIFF *tiff = clientstate->tiff;
  742. TRACE(("in encoder: bytes %d\n", bytes));
  743. TRACE(
  744. ("State: count %d, state %d, x %d, y %d, ystep %d\n",
  745. state->count,
  746. state->state,
  747. state->x,
  748. state->y,
  749. state->ystep));
  750. TRACE(
  751. ("State: xsize %d, ysize %d, xoff %d, yoff %d \n",
  752. state->xsize,
  753. state->ysize,
  754. state->xoff,
  755. state->yoff));
  756. TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes));
  757. TRACE(
  758. ("Buffer: %p: %c%c%c%c\n",
  759. buffer,
  760. (char)buffer[0],
  761. (char)buffer[1],
  762. (char)buffer[2],
  763. (char)buffer[3]));
  764. TRACE(
  765. ("State->Buffer: %c%c%c%c\n",
  766. (char)state->buffer[0],
  767. (char)state->buffer[1],
  768. (char)state->buffer[2],
  769. (char)state->buffer[3]));
  770. TRACE(
  771. ("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n",
  772. im->mode,
  773. im->type,
  774. im->bands,
  775. im->xsize,
  776. im->ysize));
  777. TRACE(
  778. ("Image: image8 %p, image32 %p, image %p, block %p \n",
  779. im->image8,
  780. im->image32,
  781. im->image,
  782. im->block));
  783. TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize));
  784. dump_state(clientstate);
  785. if (state->state == 0) {
  786. TRACE(("Encoding line by line"));
  787. while (state->y < state->ysize) {
  788. state->shuffle(
  789. state->buffer,
  790. (UINT8 *)im->image[state->y + state->yoff] +
  791. state->xoff * im->pixelsize,
  792. state->xsize);
  793. if (TIFFWriteScanline(
  794. tiff, (tdata_t)(state->buffer), (uint32_t)state->y, 0) == -1) {
  795. TRACE(("Encode Error, row %d\n", state->y));
  796. state->errcode = IMAGING_CODEC_BROKEN;
  797. TIFFClose(tiff);
  798. if (!clientstate->fp) {
  799. free(clientstate->data);
  800. }
  801. return -1;
  802. }
  803. state->y++;
  804. }
  805. if (state->y == state->ysize) {
  806. state->state = 1;
  807. TRACE(("Flushing \n"));
  808. if (!TIFFFlush(tiff)) {
  809. TRACE(("Error flushing the tiff"));
  810. // likely reason is memory.
  811. state->errcode = IMAGING_CODEC_MEMORY;
  812. TIFFClose(tiff);
  813. if (!clientstate->fp) {
  814. free(clientstate->data);
  815. }
  816. return -1;
  817. }
  818. TRACE(("Closing \n"));
  819. TIFFClose(tiff);
  820. // reset the clientstate metadata to use it to read out the buffer.
  821. clientstate->loc = 0;
  822. clientstate->size = clientstate->eof; // redundant?
  823. }
  824. }
  825. if (state->state == 1 && !clientstate->fp) {
  826. int read = (int)_tiffReadProc(clientstate, (tdata_t)buffer, (tsize_t)bytes);
  827. TRACE(
  828. ("Buffer: %p: %c%c%c%c\n",
  829. buffer,
  830. (char)buffer[0],
  831. (char)buffer[1],
  832. (char)buffer[2],
  833. (char)buffer[3]));
  834. if (clientstate->loc == clientstate->eof) {
  835. TRACE(("Hit EOF, calling an end, freeing data"));
  836. state->errcode = IMAGING_CODEC_END;
  837. free(clientstate->data);
  838. }
  839. return read;
  840. }
  841. state->errcode = IMAGING_CODEC_END;
  842. return 0;
  843. }
  844. const char *
  845. ImagingTiffVersion(void) {
  846. return TIFFGetVersion();
  847. }
  848. #endif