Debian Codegraph @

texk/xdvipsk/thirdparty/libtiff/tools/tiffcp.c

raw
1 /*
2 * Copyright (c) 1988-1997 Sam Leffler
3 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4 *
5 * Revised: 2/18/01 BAR -- added syntax for extracting single images from
6 * multi-image TIFF files.
7 *
8 * New syntax is: sourceFileName,image#
9 *
10 * image# ranges from 0..<n-1> where n is the # of images in the file.
11 * There may be no white space between the comma and the filename or
12 * image number.
13 *
14 * Example: tiffcp source.tif,1 destination.tif
15 *
16 * Copies the 2nd image in source.tif to the destination.
17 *
18 *****
19 * Permission to use, copy, modify, distribute, and sell this software and
20 * its documentation for any purpose is hereby granted without fee, provided
21 * that (i) the above copyright notices and this permission notice appear in
22 * all copies of the software and related documentation, and (ii) the names of
23 * Sam Leffler and Silicon Graphics may not be used in any advertising or
24 * publicity relating to the software without the specific, prior written
25 * permission of Sam Leffler and Silicon Graphics.
26 *
27 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
28 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
29 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
30 *
31 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
32 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
33 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
34 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
35 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
36 * OF THIS SOFTWARE.
37 */
38
39 #include "libport.h"
40 #include "tif_config.h"
41
42 #include <limits.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include <ctype.h>
48
49 #ifdef HAVE_UNISTD_H
50 #include <unistd.h>
51 #endif
52
53 #include "tiffio.h"
54
55 #ifndef EXIT_SUCCESS
56 #define EXIT_SUCCESS 0
57 #endif
58 #ifndef EXIT_FAILURE
59 #define EXIT_FAILURE 1
60 #endif
61
62 #define streq(a, b) (strcmp(a, b) == 0)
63 #define strneq(a, b, n) (strncmp(a, b, n) == 0)
64
65 #define TRUE 1
66 #define FALSE 0
67
68 #define DEFAULT_MAX_MALLOC (256 * 1024 * 1024)
69
70 /* malloc size limit (in bytes)
71 * disabled when set to 0 */
72 static tmsize_t maxMalloc = DEFAULT_MAX_MALLOC;
73
74 static int outtiled = -1;
75 static uint32_t tilewidth;
76 static uint32_t tilelength;
77
78 static uint16_t config;
79 static uint16_t compression;
80 static double max_z_error = 0.0;
81 static uint16_t predictor;
82 static int preset;
83 static uint16_t fillorder;
84 static uint16_t orientation;
85 static uint32_t rowsperstrip;
86 static uint32_t g3opts;
87 static int ignore = FALSE; /* if true, ignore read errors */
88 static uint32_t defg3opts = (uint32_t)-1;
89 static int quality = 75; /* JPEG quality */
90 static int jpeg_photometric = PHOTOMETRIC_YCBCR;
91 static uint16_t defcompression = (uint16_t)-1;
92 static uint16_t defpredictor = (uint16_t)-1;
93 static int defpreset = -1;
94 static int subcodec = -1;
95
96 static int tiffcp(TIFF *, TIFF *);
97 static int processCompressOptions(char *);
98 static void usage(int code);
99
100 static char comma = ','; /* (default) comma separator character */
101 static TIFF *bias = NULL;
102 static int pageNum = 0;
103 static int pageInSeq = 0;
104
105 /**
106 * This custom malloc function enforce a maximum allocation size
107 */
108 static void *limitMalloc(tmsize_t s)
109 {
110 if (maxMalloc && (s > maxMalloc))
111 {
112 fprintf(stderr,
113 "MemoryLimitError: allocation of %" TIFF_SSIZE_FORMAT
114 " bytes is forbidden. Limit is %" TIFF_SSIZE_FORMAT ".\n",
115 s, maxMalloc);
116 fprintf(stderr, " use -m option to change limit.\n");
117 return NULL;
118 }
119 return _TIFFmalloc(s);
120 }
121
122 static int nextSrcImage(TIFF *tif, char **imageSpec)
123 /*
124 seek to the next image specified in *imageSpec
125 returns 1 if success, 0 if no more images to process
126 *imageSpec=NULL if subsequent images should be processed in sequence
127 */
128 {
129 if (**imageSpec == comma)
130 { /* if not @comma, we've done all images */
131 char *start = *imageSpec + 1;
132 tdir_t nextImage = (tdir_t)strtol(start, imageSpec, 0);
133 if (start == *imageSpec)
134 nextImage = TIFFCurrentDirectory(tif);
135 if (**imageSpec)
136 {
137 if (**imageSpec == comma)
138 {
139 /* a trailing comma denotes remaining images in sequence */
140 if ((*imageSpec)[1] == '\0')
141 *imageSpec = NULL;
142 }
143 else
144 {
145 fprintf(stderr,
146 "Expected a %c separated image # list after %s\n",
147 comma, TIFFFileName(tif));
148 exit(EXIT_FAILURE); /* syntax error */
149 }
150 }
151 if (TIFFSetDirectory(tif, nextImage))
152 return 1;
153 fprintf(stderr, "%s%c%" PRIu32 " not found!\n", TIFFFileName(tif),
154 comma, nextImage);
155 }
156 return 0;
157 }
158
159 static TIFF *openSrcImage(char **imageSpec)
160 /*
161 imageSpec points to a pointer to a filename followed by optional ,image#'s
162 Open the TIFF file and assign *imageSpec to either NULL if there are
163 no images specified, or a pointer to the next image number text
164 */
165 {
166 /* disable strip shopping when using jbig compression */
167 const char *mode = (defcompression == COMPRESSION_JBIG) ? "rc" : "r";
168 TIFF *tif;
169 char *fn = *imageSpec;
170 *imageSpec = strchr(fn, comma);
171 TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
172 if (opts == NULL)
173 {
174 return NULL;
175 }
176 TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
177 if (*imageSpec)
178 { /* there is at least one image number specifier */
179 **imageSpec = '\0';
180 tif = TIFFOpenExt(fn, mode, opts);
181 /* but, ignore any single trailing comma */
182 if (!(*imageSpec)[1])
183 {
184 *imageSpec = NULL;
185 TIFFOpenOptionsFree(opts);
186 return tif;
187 }
188 if (tif)
189 {
190 **imageSpec = comma; /* replace the comma */
191 if (!nextSrcImage(tif, imageSpec))
192 {
193 TIFFClose(tif);
194 tif = NULL;
195 }
196 }
197 }
198 else
199 tif = TIFFOpenExt(fn, mode, opts);
200 TIFFOpenOptionsFree(opts);
201 return tif;
202 }
203
204 int main(int argc, char *argv[])
205 {
206 uint16_t defconfig = (uint16_t)-1;
207 uint16_t deffillorder = 0;
208 uint32_t deftilewidth = (uint32_t)-1;
209 uint32_t deftilelength = (uint32_t)-1;
210 uint32_t defrowsperstrip = (uint32_t)0;
211 uint64_t diroff = 0;
212 TIFF *in;
213 TIFF *out;
214 char mode[10];
215 char *mp = mode;
216 int c;
217 #if !HAVE_DECL_OPTARG
218 extern int optind;
219 extern char *optarg;
220 #endif
221
222 *mp++ = 'w';
223 *mp = '\0';
224 while ((c = getopt(argc, argv, "m:,:b:c:f:l:o:p:r:w:aistBLMC8xh")) != -1)
225 switch (c)
226 {
227 case 'm':
228 maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
229 break;
230 case ',':
231 if (optarg[0] != '=')
232 usage(EXIT_FAILURE);
233 comma = optarg[1];
234 break;
235 case 'b': /* this file is bias image subtracted from others */
236 if (bias)
237 {
238 fputs("Only 1 bias image may be specified\n", stderr);
239 exit(EXIT_FAILURE);
240 }
241 {
242 uint16_t samples = (uint16_t)-1;
243 char **biasFn = &optarg;
244 bias = openSrcImage(biasFn);
245 if (!bias)
246 exit(EXIT_FAILURE);
247 if (TIFFIsTiled(bias))
248 {
249 fputs("Bias image must be organized in strips\n",
250 stderr);
251 exit(EXIT_FAILURE);
252 }
253 TIFFGetField(bias, TIFFTAG_SAMPLESPERPIXEL, &samples);
254 if (samples != 1)
255 {
256 fputs("Bias image must be monochrome\n", stderr);
257 exit(EXIT_FAILURE);
258 }
259 }
260 break;
261 case 'a': /* append to output */
262 mode[0] = 'a';
263 break;
264 case 'c': /* compression scheme */
265 if (!processCompressOptions(optarg))
266 usage(EXIT_FAILURE);
267 break;
268 case 'f': /* fill order */
269 if (streq(optarg, "lsb2msb"))
270 deffillorder = FILLORDER_LSB2MSB;
271 else if (streq(optarg, "msb2lsb"))
272 deffillorder = FILLORDER_MSB2LSB;
273 else
274 usage(EXIT_FAILURE);
275 break;
276 case 'i': /* ignore errors */
277 ignore = TRUE;
278 break;
279 case 'l': /* tile length */
280 outtiled = TRUE;
281 deftilelength = atoi(optarg);
282 break;
283 case 'o': /* initial directory offset */
284 diroff = strtoul(optarg, NULL, 0);
285 break;
286 case 'p': /* planar configuration */
287 if (streq(optarg, "separate"))
288 defconfig = PLANARCONFIG_SEPARATE;
289 else if (streq(optarg, "contig"))
290 defconfig = PLANARCONFIG_CONTIG;
291 else
292 usage(EXIT_FAILURE);
293 break;
294 case 'r': /* rows/strip */
295 defrowsperstrip = atol(optarg);
296 break;
297 case 's': /* generate stripped output */
298 outtiled = FALSE;
299 break;
300 case 't': /* generate tiled output */
301 outtiled = TRUE;
302 break;
303 case 'w': /* tile width */
304 outtiled = TRUE;
305 deftilewidth = atoi(optarg);
306 break;
307 case 'B':
308 if (strlen(mode) < (sizeof(mode) - 1))
309 {
310 *mp++ = 'b';
311 *mp = '\0';
312 }
313 break;
314 case 'L':
315 if (strlen(mode) < (sizeof(mode) - 1))
316 {
317 *mp++ = 'l';
318 *mp = '\0';
319 }
320 break;
321 case 'M':
322 if (strlen(mode) < (sizeof(mode) - 1))
323 {
324 *mp++ = 'm';
325 *mp = '\0';
326 }
327 break;
328 case 'C':
329 if (strlen(mode) < (sizeof(mode) - 1))
330 {
331 *mp++ = 'c';
332 *mp = '\0';
333 }
334 break;
335 case '8':
336 if (strlen(mode) < (sizeof(mode) - 1))
337 {
338 *mp++ = '8';
339 *mp = '\0';
340 }
341 break;
342 case 'x':
343 pageInSeq = 1;
344 break;
345 case 'h':
346 usage(EXIT_SUCCESS);
347 /*NOTREACHED*/
348 break;
349 case '?':
350 usage(EXIT_FAILURE);
351 /*NOTREACHED*/
352 break;
353 }
354 if (argc - optind < 2)
355 usage(EXIT_FAILURE);
356 TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
357 if (opts == NULL)
358 {
359 return EXIT_FAILURE;
360 }
361 TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
362 out = TIFFOpenExt(argv[argc - 1], mode, opts);
363 TIFFOpenOptionsFree(opts);
364 if (out == NULL)
365 return (EXIT_FAILURE);
366 if ((argc - optind) == 2)
367 pageNum = -1;
368 for (; optind < argc - 1; optind++)
369 {
370 char *imageCursor = argv[optind];
371 in = openSrcImage(&imageCursor);
372 if (in == NULL)
373 {
374 (void)TIFFClose(out);
375 return (EXIT_FAILURE);
376 }
377 if (diroff != 0 && !TIFFSetSubDirectory(in, diroff))
378 {
379 TIFFError(TIFFFileName(in),
380 "Error, setting subdirectory at %" PRIu64, diroff);
381 (void)TIFFClose(in);
382 (void)TIFFClose(out);
383 return (EXIT_FAILURE);
384 }
385 for (;;)
386 {
387 config = defconfig;
388 compression = defcompression;
389 predictor = defpredictor;
390 preset = defpreset;
391 fillorder = deffillorder;
392 rowsperstrip = defrowsperstrip;
393 tilewidth = deftilewidth;
394 tilelength = deftilelength;
395 g3opts = defg3opts;
396 if (!tiffcp(in, out) || !TIFFWriteDirectory(out))
397 {
398 (void)TIFFClose(in);
399 (void)TIFFClose(out);
400 return (EXIT_FAILURE);
401 }
402 if (imageCursor)
403 { /* seek next image directory */
404 if (!nextSrcImage(in, &imageCursor))
405 break;
406 }
407 else if (!TIFFReadDirectory(in))
408 break;
409 }
410 (void)TIFFClose(in);
411 }
412
413 (void)TIFFClose(out);
414 return (EXIT_SUCCESS);
415 }
416
417 static void processZIPOptions(char *cp)
418 {
419 if ((cp = strchr(cp, ':')))
420 {
421 do
422 {
423 cp++;
424 if (isdigit((int)*cp))
425 defpredictor = atoi(cp);
426 else if (*cp == 'p')
427 defpreset = atoi(++cp);
428 else if (*cp == 's')
429 subcodec = atoi(++cp);
430 else
431 usage(EXIT_FAILURE);
432 } while ((cp = strchr(cp, ':')));
433 }
434 }
435
436 static void processLERCOptions(char *cp)
437 {
438 if ((cp = strchr(cp, ':')))
439 {
440 do
441 {
442 cp++;
443 if (isdigit((int)*cp))
444 max_z_error = atof(cp);
445 else if (*cp == 's')
446 subcodec = atoi(++cp);
447 else if (*cp == 'p')
448 defpreset = atoi(++cp);
449 else
450 usage(EXIT_FAILURE);
451 } while ((cp = strchr(cp, ':')));
452 }
453 }
454
455 static void processG3Options(char *cp)
456 {
457 if ((cp = strchr(cp, ':')))
458 {
459 if (defg3opts == (uint32_t)-1)
460 defg3opts = 0;
461 do
462 {
463 cp++;
464 if (strneq(cp, "1d", 2))
465 defg3opts &= ~GROUP3OPT_2DENCODING;
466 else if (strneq(cp, "2d", 2))
467 defg3opts |= GROUP3OPT_2DENCODING;
468 else if (strneq(cp, "fill", 4))
469 defg3opts |= GROUP3OPT_FILLBITS;
470 else
471 usage(EXIT_FAILURE);
472 } while ((cp = strchr(cp, ':')));
473 }
474 }
475
476 static int processCompressOptions(char *opt)
477 {
478 if (streq(opt, "none"))
479 {
480 defcompression = COMPRESSION_NONE;
481 }
482 else if (streq(opt, "packbits"))
483 {
484 defcompression = COMPRESSION_PACKBITS;
485 }
486 else if (strneq(opt, "jpeg", 4))
487 {
488 char *cp = strchr(opt, ':');
489
490 defcompression = COMPRESSION_JPEG;
491 while (cp)
492 {
493 if (isdigit((int)cp[1]))
494 quality = atoi(cp + 1);
495 else if (cp[1] == 'r')
496 jpeg_photometric = PHOTOMETRIC_RGB;
497 else
498 usage(EXIT_FAILURE);
499
500 cp = strchr(cp + 1, ':');
501 }
502 }
503 else if (strneq(opt, "g3", 2))
504 {
505 processG3Options(opt);
506 defcompression = COMPRESSION_CCITTFAX3;
507 }
508 else if (streq(opt, "g4"))
509 {
510 defcompression = COMPRESSION_CCITTFAX4;
511 }
512 else if (strneq(opt, "lzw", 3))
513 {
514 char *cp = strchr(opt, ':');
515 if (cp)
516 defpredictor = atoi(cp + 1);
517 defcompression = COMPRESSION_LZW;
518 }
519 else if (strneq(opt, "zip", 3))
520 {
521 processZIPOptions(opt);
522 defcompression = COMPRESSION_ADOBE_DEFLATE;
523 }
524 else if (strneq(opt, "lerc", 4))
525 {
526 processLERCOptions(opt);
527 defcompression = COMPRESSION_LERC;
528 }
529 else if (strneq(opt, "lzma", 4))
530 {
531 processZIPOptions(opt);
532 defcompression = COMPRESSION_LZMA;
533 }
534 else if (strneq(opt, "zstd", 4))
535 {
536 processZIPOptions(opt);
537 defcompression = COMPRESSION_ZSTD;
538 }
539 else if (strneq(opt, "webp", 4))
540 {
541 processZIPOptions(opt);
542 defcompression = COMPRESSION_WEBP;
543 }
544 else if (strneq(opt, "jbig", 4))
545 {
546 defcompression = COMPRESSION_JBIG;
547 }
548 else if (strneq(opt, "sgilog", 6))
549 {
550 defcompression = COMPRESSION_SGILOG;
551 }
552 else
553 return (0);
554 return (1);
555 }
556
557 static const char usage_info[] =
558 "Copy, convert, or combine TIFF files\n\n"
559 "usage: tiffcp [options] input... output\n"
560 "where options are:\n"
561 " -a append to output instead of overwriting\n"
562 " -o offset set initial directory offset\n"
563 " -p contig pack samples contiguously (e.g. RGBRGB...)\n"
564 " -p separate store samples separately (e.g. RRR...GGG...BBB...)\n"
565 " -s write output in strips\n"
566 " -t write output in tiles\n"
567 " -x force the merged tiff pages in sequence\n"
568 " -8 write BigTIFF instead of default ClassicTIFF\n"
569 " -B write big-endian instead of native byte order\n"
570 " -L write little-endian instead of native byte order\n"
571 " -M disable use of memory-mapped files\n"
572 " -C disable strip chopping\n"
573 " -i ignore read errors\n"
574 " -b file[,#] bias (dark) monochrome image to be subtracted from all "
575 "others\n"
576 " -,=% use % rather than , to separate image #'s (per Note "
577 "below)\n"
578 " -m size set maximum memory allocation size (MiB). 0 to disable "
579 "limit.\n"
580 "\n"
581 " -r # make each strip have no more than # rows\n"
582 " -w # set output tile width (pixels)\n"
583 " -l # set output tile length (pixels)\n"
584 "\n"
585 " -f lsb2msb force lsb-to-msb FillOrder for output\n"
586 " -f msb2lsb force msb-to-lsb FillOrder for output\n"
587 "\n"
588 #ifdef LZW_SUPPORT
589 " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
590 /* " LZW options:" */
591 " # set predictor value\n"
592 " For example, -c lzw:2 for LZW-encoded data with horizontal "
593 "differencing\n"
594 #endif
595 #ifdef ZIP_SUPPORT
596 " -c zip[:opts] compress output with deflate encoding\n"
597 /* " Deflate (ZIP) options:", */
598 " # set predictor value\n"
599 " p# set compression level (preset)\n"
600 " For example, -c zip:3:p9 for maximum compression level and floating\n"
601 " point predictor.\n"
602 #endif
603 #if defined(ZIP_SUPPORT) && defined(LIBDEFLATE_SUPPORT)
604 " s# set subcodec: 0=zlib, 1=libdeflate (default 1)\n"
605 /* " (only for Deflate/ZIP)", */
606 #endif
607 #ifdef LERC_SUPPORT
608 " -c lerc[:opts] compress output with LERC encoding\n"
609 /* " LERC options:", */
610 " # set max_z_error value\n"
611 " p# set compression level (preset)\n"
612 #ifdef ZSTD_SUPPORT
613 " s# set subcodec: 0=none, 1=deflate, 2=zstd (default 0)\n"
614 " For example, -c lerc:0.5:s2:p22 for max_z_error 0.5,\n"
615 " zstd additional compression with maximum compression level.\n"
616 #else
617 " s# set subcodec: 0=none, 1=deflate (default 0)\n"
618 " For example, -c lerc:0.5:s1:p12 for max_z_error 0.5,\n"
619 " deflate additional compression with maximum compression level.\n"
620 #endif
621 #endif
622 #ifdef LZMA_SUPPORT
623 " -c lzma[:opts] compress output with LZMA2 encoding\n"
624 /* " LZMA options:", */
625 " # set predictor value\n"
626 " p# set compression level (preset)\n"
627 #endif
628 #ifdef ZSTD_SUPPORT
629 " -c zstd[:opts] compress output with ZSTD encoding\n"
630 /* " ZSTD options:", */
631 " # set predictor value\n"
632 " p# set compression level (preset)\n"
633 #endif
634 #ifdef WEBP_SUPPORT
635 " -c webp[:opts] compress output with WEBP encoding\n"
636 /* " WEBP options:", */
637 " # set predictor value\n"
638 " p# set compression level (preset)\n"
639 #endif
640 #ifdef JPEG_SUPPORT
641 " -c jpeg[:opts] compress output with JPEG encoding\n"
642 /* " JPEG options:", */
643 " # set compression quality level (0-100, default 75)\n"
644 " r output color image as RGB rather than YCbCr\n"
645 " For example, -c jpeg:r:50 for JPEG-encoded RGB with 50% comp. "
646 "quality\n"
647 #endif
648 #ifdef JBIG_SUPPORT
649 " -c jbig compress output with ISO JBIG encoding\n"
650 #endif
651 #ifdef PACKBITS_SUPPORT
652 " -c packbits compress output with packbits encoding\n"
653 #endif
654 #ifdef CCITT_SUPPORT
655 " -c g3[:opts] compress output with CCITT Group 3 encoding\n"
656 /* " CCITT Group 3 options:", */
657 " 1d use default CCITT Group 3 1D-encoding\n"
658 " 2d use optional CCITT Group 3 2D-encoding\n"
659 " fill byte-align EOL codes\n"
660 " For example, -c g3:2d:fill for G3-2D-encoded data with byte-aligned "
661 "EOLs\n"
662 " -c g4 compress output with CCITT Group 4 encoding\n"
663 #endif
664 #ifdef LOGLUV_SUPPORT
665 " -c sgilog compress output with SGILOG encoding\n"
666 #endif
667 #if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(LZMA_SUPPORT) || \
668 defined(ZSTD_SUPPORT) || defined(WEBP_SUPPORT) || defined(JPEG_SUPPORT) || \
669 defined(JBIG_SUPPORT) || defined(PACKBITS_SUPPORT) || \
670 defined(CCITT_SUPPORT) || defined(LOGLUV_SUPPORT) || defined(LERC_SUPPORT)
671 " -c none use no compression algorithm on output\n"
672 #endif
673 "\n"
674 "Note that input filenames may be of the form filename,x,y,z\n"
675 "where x, y, and z specify image numbers in the filename to copy.\n"
676 "example: tiffcp -b esp.tif,1 esp.tif,0 test.tif\n"
677 " subtract 2nd image in esp.tif from 1st yielding result test.tif\n";
678
679 static void usage(int code)
680 {
681 FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
682
683 fprintf(out, "%s\n\n", TIFFGetVersion());
684 fprintf(out, "%s", usage_info);
685 exit(code);
686 }
687
688 #define CopyField(tag, v) \
689 do \
690 { \
691 if (TIFFGetField(in, tag, &v)) \
692 TIFFSetField(out, tag, v); \
693 } while (0)
694 #define CopyField2(tag, v1, v2) \
695 do \
696 { \
697 if (TIFFGetField(in, tag, &v1, &v2)) \
698 TIFFSetField(out, tag, v1, v2); \
699 } while (0)
700 #define CopyField3(tag, v1, v2, v3) \
701 do \
702 { \
703 if (TIFFGetField(in, tag, &v1, &v2, &v3)) \
704 TIFFSetField(out, tag, v1, v2, v3); \
705 } while (0)
706 #define CopyField4(tag, v1, v2, v3, v4) \
707 do \
708 { \
709 if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) \
710 TIFFSetField(out, tag, v1, v2, v3, v4); \
711 } while (0)
712
713 static void cpTag(TIFF *in, TIFF *out, uint16_t tag, uint16_t count,
714 TIFFDataType type)
715 {
716 switch (type)
717 {
718 case TIFF_SHORT:
719 if (count == 1)
720 {
721 uint16_t shortv;
722 CopyField(tag, shortv);
723 }
724 else if (count == 2)
725 {
726 uint16_t shortv1, shortv2;
727 CopyField2(tag, shortv1, shortv2);
728 }
729 else if (count == 4)
730 {
731 uint16_t *tr, *tg, *tb, *ta;
732 CopyField4(tag, tr, tg, tb, ta);
733 }
734 else if (count == (uint16_t)-1)
735 {
736 uint16_t shortv1;
737 uint16_t *shortav;
738 CopyField2(tag, shortv1, shortav);
739 }
740 break;
741 case TIFF_LONG:
742 {
743 uint32_t longv;
744 CopyField(tag, longv);
745 }
746 break;
747 case TIFF_RATIONAL:
748 if (count == 1)
749 {
750 float floatv;
751 CopyField(tag, floatv);
752 }
753 else if (count == (uint16_t)-1)
754 {
755 float *floatav;
756 CopyField(tag, floatav);
757 }
758 break;
759 case TIFF_ASCII:
760 {
761 char *stringv;
762 CopyField(tag, stringv);
763 }
764 break;
765 case TIFF_DOUBLE:
766 if (count == 1)
767 {
768 double doublev;
769 CopyField(tag, doublev);
770 }
771 else if (count == (uint16_t)-1)
772 {
773 double *doubleav;
774 CopyField(tag, doubleav);
775 }
776 break;
777 default:
778 TIFFError(TIFFFileName(in),
779 "Data type %" PRIu16 " is not supported, tag %d skipped.",
780 tag, type);
781 }
782 }
783
784 static const struct cpTag
785 {
786 uint16_t tag;
787 uint16_t count;
788 TIFFDataType type;
789 } tags[] = {
790 {TIFFTAG_SUBFILETYPE, 1, TIFF_LONG},
791 {TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT},
792 {TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII},
793 {TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII},
794 {TIFFTAG_MAKE, 1, TIFF_ASCII},
795 {TIFFTAG_MODEL, 1, TIFF_ASCII},
796 {TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT},
797 {TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT},
798 {TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL},
799 {TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL},
800 {TIFFTAG_PAGENAME, 1, TIFF_ASCII},
801 {TIFFTAG_XPOSITION, 1, TIFF_RATIONAL},
802 {TIFFTAG_YPOSITION, 1, TIFF_RATIONAL},
803 {TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT},
804 {TIFFTAG_SOFTWARE, 1, TIFF_ASCII},
805 {TIFFTAG_DATETIME, 1, TIFF_ASCII},
806 {TIFFTAG_ARTIST, 1, TIFF_ASCII},
807 {TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII},
808 {TIFFTAG_WHITEPOINT, (uint16_t)-1, TIFF_RATIONAL},
809 {TIFFTAG_PRIMARYCHROMATICITIES, (uint16_t)-1, TIFF_RATIONAL},
810 {TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT},
811 {TIFFTAG_INKSET, 1, TIFF_SHORT},
812 {TIFFTAG_DOTRANGE, 2, TIFF_SHORT},
813 {TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII},
814 {TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT},
815 {TIFFTAG_EXTRASAMPLES, (uint16_t)-1, TIFF_SHORT},
816 {TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE},
817 {TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE},
818 {TIFFTAG_STONITS, 1, TIFF_DOUBLE},
819 };
820 #define NTAGS (sizeof(tags) / sizeof(tags[0]))
821
822 #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type)
823
824 typedef int (*copyFunc)(TIFF *in, TIFF *out, uint32_t l, uint32_t w,
825 uint16_t samplesperpixel);
826 static copyFunc pickCopyFunc(TIFF *, TIFF *, uint16_t, uint16_t);
827
828 /* PODD */
829
830 static int tiffcp(TIFF *in, TIFF *out)
831 {
832 uint16_t bitspersample = 1, samplesperpixel = 1;
833 uint16_t input_compression, input_photometric = PHOTOMETRIC_MINISBLACK;
834 copyFunc cf;
835 uint32_t width, length;
836 const struct cpTag *p;
837
838 CopyField(TIFFTAG_IMAGEWIDTH, width);
839 CopyField(TIFFTAG_IMAGELENGTH, length);
840 CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample);
841 CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
842 if (compression != (uint16_t)-1)
843 TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
844 else
845 CopyField(TIFFTAG_COMPRESSION, compression);
846 if (!TIFFIsCODECConfigured(compression))
847 return FALSE;
848 TIFFGetFieldDefaulted(in, TIFFTAG_COMPRESSION, &input_compression);
849 if (!TIFFIsCODECConfigured(input_compression))
850 return FALSE;
851 TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric);
852 if (input_compression == COMPRESSION_JPEG)
853 {
854 /* Force conversion to RGB */
855 TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
856 }
857 else if (input_photometric == PHOTOMETRIC_YCBCR)
858 {
859 /* Otherwise, can't handle subsampled input */
860 uint16_t subsamplinghor, subsamplingver;
861
862 TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor,
863 &subsamplingver);
864 if (subsamplinghor != 1 || subsamplingver != 1)
865 {
866 fprintf(stderr,
867 "tiffcp: %s: Can't copy/convert subsampled image.\n",
868 TIFFFileName(in));
869 return FALSE;
870 }
871 }
872 if (compression == COMPRESSION_JPEG)
873 {
874 if (input_photometric == PHOTOMETRIC_RGB ||
875 input_photometric == PHOTOMETRIC_YCBCR)
876 {
877 TIFFSetField(out, TIFFTAG_PHOTOMETRIC, jpeg_photometric);
878 if (jpeg_photometric == PHOTOMETRIC_YCBCR)
879 {
880 uint16_t subsamplinghor = 2, subsamplingver = 2;
881 if (input_compression == COMPRESSION_JPEG &&
882 input_photometric == PHOTOMETRIC_YCBCR)
883 {
884 TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
885 &subsamplinghor, &subsamplingver);
886
887 float *refBW = NULL;
888 if (TIFFGetField(in, TIFFTAG_REFERENCEBLACKWHITE, &refBW))
889 {
890 TIFFSetField(out, TIFFTAG_REFERENCEBLACKWHITE, refBW);
891 }
892 }
893 TIFFSetField(out, TIFFTAG_YCBCRSUBSAMPLING, subsamplinghor,
894 subsamplingver);
895 }
896 }
897 else
898 TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
899 }
900 else if (compression == COMPRESSION_SGILOG ||
901 compression == COMPRESSION_SGILOG24)
902 TIFFSetField(out, TIFFTAG_PHOTOMETRIC,
903 samplesperpixel == 1 ? PHOTOMETRIC_LOGL
904 : PHOTOMETRIC_LOGLUV);
905 else
906 {
907 if (input_photometric == PHOTOMETRIC_YCBCR)
908 TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
909 else
910 CopyTag(TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT);
911 }
912 if (fillorder != 0)
913 TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
914 else
915 CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
916 /*
917 * Will copy `Orientation' tag from input image
918 */
919 TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
920 TIFFSetField(out, TIFFTAG_ORIENTATION, orientation);
921 /*
922 * Choose tiles/strip for the output image according to
923 * the command line arguments (-tiles, -strips) and the
924 * structure of the input image.
925 */
926 if (outtiled == -1)
927 outtiled = TIFFIsTiled(in);
928 if (outtiled)
929 {
930 /*
931 * Setup output file's tile width&height. If either
932 * is not specified, use either the value from the
933 * input image or, if nothing is defined, use the
934 * library default.
935 */
936 if (tilewidth == (uint32_t)-1)
937 TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
938 if (tilelength == (uint32_t)-1)
939 TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
940 TIFFDefaultTileSize(out, &tilewidth, &tilelength);
941 TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
942 TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
943 }
944 else
945 {
946 /*
947 * RowsPerStrip is left unspecified: use either the
948 * value from the input image or, if nothing is defined,
949 * use the library default.
950 */
951 if (rowsperstrip == (uint32_t)0)
952 {
953 if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
954 {
955 rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
956 }
957 if (rowsperstrip > length && rowsperstrip != (uint32_t)-1)
958 rowsperstrip = length;
959 }
960 else if (rowsperstrip == (uint32_t)-1)
961 rowsperstrip = length;
962 TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
963 }
964 if (config != (uint16_t)-1)
965 TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
966 else
967 CopyField(TIFFTAG_PLANARCONFIG, config);
968 if (samplesperpixel <= 4)
969 CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
970 CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
971 /* SMinSampleValue & SMaxSampleValue */
972 switch (compression)
973 {
974 case COMPRESSION_JPEG:
975 TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
976 /* For 3 sample images, the input data provided to libtiff is
977 * always RGB, not YCbCr subsampled. */
978 TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
979 break;
980 case COMPRESSION_JBIG:
981 CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
982 CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
983 CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
984 CopyTag(TIFFTAG_FAXDCS, 1, TIFF_ASCII);
985 break;
986 case COMPRESSION_LERC:
987 if (max_z_error > 0)
988 {
989 if (TIFFSetField(out, TIFFTAG_LERC_MAXZERROR, max_z_error) != 1)
990 {
991 return FALSE;
992 }
993 }
994 if (subcodec != -1)
995 {
996 if (TIFFSetField(out, TIFFTAG_LERC_ADD_COMPRESSION, subcodec) !=
997 1)
998 {
999 return FALSE;
1000 }
1001 }
1002 if (preset != -1)
1003 {
1004 switch (subcodec)
1005 {
1006 case LERC_ADD_COMPRESSION_DEFLATE:
1007 if (TIFFSetField(out, TIFFTAG_ZIPQUALITY, preset) != 1)
1008 {
1009 return FALSE;
1010 }
1011 break;
1012 case LERC_ADD_COMPRESSION_ZSTD:
1013 if (TIFFSetField(out, TIFFTAG_ZSTD_LEVEL, preset) != 1)
1014 {
1015 return FALSE;
1016 }
1017 break;
1018 }
1019 }
1020 break;
1021 case COMPRESSION_LZW:
1022 case COMPRESSION_ADOBE_DEFLATE:
1023 case COMPRESSION_DEFLATE:
1024 case COMPRESSION_LZMA:
1025 case COMPRESSION_ZSTD:
1026 if (predictor != (uint16_t)-1)
1027 TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
1028 else if (input_compression == COMPRESSION_LZW ||
1029 input_compression == COMPRESSION_ADOBE_DEFLATE ||
1030 input_compression == COMPRESSION_DEFLATE ||
1031 input_compression == COMPRESSION_LZMA ||
1032 input_compression == COMPRESSION_ZSTD)
1033 {
1034 CopyField(TIFFTAG_PREDICTOR, predictor);
1035 }
1036 if (compression == COMPRESSION_ADOBE_DEFLATE ||
1037 compression == COMPRESSION_DEFLATE)
1038 {
1039 if (subcodec != -1)
1040 {
1041 if (TIFFSetField(out, TIFFTAG_DEFLATE_SUBCODEC, subcodec) !=
1042 1)
1043 {
1044 return FALSE;
1045 }
1046 }
1047 }
1048 /*fallthrough*/
1049 case COMPRESSION_WEBP:
1050 if (preset != -1)
1051 {
1052 if (preset == 100)
1053 {
1054 TIFFSetField(out, TIFFTAG_WEBP_LOSSLESS, TRUE);
1055 }
1056 else
1057 {
1058 TIFFSetField(out, TIFFTAG_WEBP_LEVEL, preset);
1059 }
1060 }
1061 break;
1062 case COMPRESSION_CCITTFAX3:
1063 case COMPRESSION_CCITTFAX4:
1064 if (compression == COMPRESSION_CCITTFAX3)
1065 {
1066 if (g3opts != (uint32_t)-1)
1067 TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
1068 else if (input_compression == COMPRESSION_CCITTFAX3)
1069 CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
1070 }
1071 else if (input_compression == COMPRESSION_CCITTFAX4)
1072 CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
1073 if (input_compression == COMPRESSION_CCITTFAX3 ||
1074 input_compression == COMPRESSION_CCITTFAX4)
1075 {
1076 CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
1077 CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
1078 CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
1079 }
1080 CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
1081 CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
1082 CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
1083 break;
1084 }
1085 {
1086 uint32_t len32;
1087 void **data;
1088 if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
1089 TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
1090 }
1091 {
1092 uint16_t ninks;
1093 const char *inknames;
1094 if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks))
1095 {
1096 TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
1097 if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames))
1098 {
1099 int inknameslen = strlen(inknames) + 1;
1100 const char *cp = inknames;
1101 while (ninks > 1)
1102 {
1103 cp = strchr(cp, '\0');
1104 cp++;
1105 inknameslen += (strlen(cp) + 1);
1106 ninks--;
1107 }
1108 TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
1109 }
1110 }
1111 }
1112 {
1113 unsigned short pg0, pg1;
1114
1115 if (pageInSeq == 1)
1116 {
1117 if (pageNum < 0) /* only one input file */
1118 {
1119 if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1))
1120 TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
1121 }
1122 else
1123 TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
1124 }
1125 else
1126 {
1127 if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1))
1128 {
1129 if (pageNum < 0) /* only one input file */
1130 TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
1131 else
1132 TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
1133 }
1134 }
1135 }
1136
1137 for (p = tags; p < &tags[NTAGS]; p++)
1138 {
1139 CopyTag(p->tag, p->count, p->type);
1140 }
1141
1142 cf = pickCopyFunc(in, out, bitspersample, samplesperpixel);
1143 return (cf ? (*cf)(in, out, length, width, samplesperpixel) : FALSE);
1144 }
1145
1146 /*
1147 * Copy Functions.
1148 */
1149 #define DECLAREcpFunc(x) \
1150 static int x(TIFF *in, TIFF *out, uint32_t imagelength, \
1151 uint32_t imagewidth, tsample_t spp)
1152
1153 #define DECLAREreadFunc(x) \
1154 static int x(TIFF *in, uint8_t *buf, uint32_t imagelength, \
1155 uint32_t imagewidth, tsample_t spp)
1156 typedef int (*readFunc)(TIFF *, uint8_t *, uint32_t, uint32_t, tsample_t);
1157
1158 #define DECLAREwriteFunc(x) \
1159 static int x(TIFF *out, uint8_t *buf, uint32_t imagelength, \
1160 uint32_t imagewidth, tsample_t spp)
1161 typedef int (*writeFunc)(TIFF *, uint8_t *, uint32_t, uint32_t, tsample_t);
1162
1163 /*
1164 * Contig -> contig by scanline for rows/strip change.
1165 */
1166 DECLAREcpFunc(cpContig2ContigByRow)
1167 {
1168 tsize_t scanlinesize = TIFFScanlineSize(in);
1169 tdata_t buf;
1170 uint32_t row;
1171
1172 buf = limitMalloc(scanlinesize);
1173 if (!buf)
1174 return 0;
1175 _TIFFmemset(buf, 0, scanlinesize);
1176 (void)imagewidth;
1177 (void)spp;
1178 for (row = 0; row < imagelength; row++)
1179 {
1180 if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore)
1181 {
1182 TIFFError(TIFFFileName(in), "Error, can't read scanline %" PRIu32,
1183 row);
1184 goto bad;
1185 }
1186 if (TIFFWriteScanline(out, buf, row, 0) < 0)
1187 {
1188 TIFFError(TIFFFileName(out), "Error, can't write scanline %" PRIu32,
1189 row);
1190 goto bad;
1191 }
1192 }
1193 _TIFFfree(buf);
1194 return 1;
1195 bad:
1196 _TIFFfree(buf);
1197 return 0;
1198 }
1199
1200 typedef void biasFn(void *image, void *bias, uint32_t pixels);
1201
1202 #define subtract(bits) \
1203 static void subtract##bits(void *i, void *b, uint32_t pixels) \
1204 { \
1205 uint##bits##_t *image = i; \
1206 uint##bits##_t *biasx = b; \
1207 while (pixels--) \
1208 { \
1209 *image = *image > *biasx ? *image - *biasx : 0; \
1210 image++, biasx++; \
1211 } \
1212 }
1213
1214 subtract(8) subtract(16) subtract(32)
1215
1216 static biasFn *lineSubtractFn(unsigned bits)
1217 {
1218 switch (bits)
1219 {
1220 case 8:
1221 return subtract8;
1222 case 16:
1223 return subtract16;
1224 case 32:
1225 return subtract32;
1226 }
1227 return NULL;
1228 }
1229
1230 /*
1231 * Contig -> contig by scanline while subtracting a bias image.
1232 */
1233 DECLAREcpFunc(cpBiasedContig2Contig)
1234 {
1235 if (spp == 1)
1236 {
1237 tsize_t biasSize = TIFFScanlineSize(bias);
1238 tsize_t bufSize = TIFFScanlineSize(in);
1239 tdata_t buf, biasBuf;
1240 uint32_t biasWidth = 0, biasLength = 0;
1241 TIFFGetField(bias, TIFFTAG_IMAGEWIDTH, &biasWidth);
1242 TIFFGetField(bias, TIFFTAG_IMAGELENGTH, &biasLength);
1243 if (biasSize == bufSize && imagelength == biasLength &&
1244 imagewidth == biasWidth)
1245 {
1246 uint16_t sampleBits = 0;
1247 biasFn *subtractLine;
1248 TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &sampleBits);
1249 subtractLine = lineSubtractFn(sampleBits);
1250 if (subtractLine)
1251 {
1252 uint32_t row;
1253 buf = limitMalloc(bufSize);
1254 biasBuf = limitMalloc(bufSize);
1255 if (!buf || !biasBuf)
1256 goto bad;
1257 for (row = 0; row < imagelength; row++)
1258 {
1259 if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore)
1260 {
1261 TIFFError(TIFFFileName(in),
1262 "Error, can't read scanline %" PRIu32, row);
1263 goto bad;
1264 }
1265 if (TIFFReadScanline(bias, biasBuf, row, 0) < 0 && !ignore)
1266 {
1267 TIFFError(TIFFFileName(in),
1268 "Error, can't read biased scanline %" PRIu32,
1269 row);
1270 goto bad;
1271 }
1272 subtractLine(buf, biasBuf, imagewidth);
1273 if (TIFFWriteScanline(out, buf, row, 0) < 0)
1274 {
1275 TIFFError(TIFFFileName(out),
1276 "Error, can't write scanline %" PRIu32, row);
1277 goto bad;
1278 }
1279 }
1280
1281 _TIFFfree(buf);
1282 _TIFFfree(biasBuf);
1283 TIFFSetDirectory(bias, TIFFCurrentDirectory(bias)); /* rewind */
1284 return 1;
1285 bad:
1286 if (buf)
1287 _TIFFfree(buf);
1288 if (biasBuf)
1289 _TIFFfree(biasBuf);
1290 return 0;
1291 }
1292 else
1293 {
1294 TIFFError(TIFFFileName(in),
1295 "No support for biasing %" PRIu16 " bit pixels\n",
1296 sampleBits);
1297 return 0;
1298 }
1299 }
1300 TIFFError(TIFFFileName(in),
1301 "Bias image %s,%" PRIu32
1302 "\nis not the same size as %s,%" PRIu32 "\n",
1303 TIFFFileName(bias), TIFFCurrentDirectory(bias),
1304 TIFFFileName(in), TIFFCurrentDirectory(in));
1305 return 0;
1306 }
1307 else
1308 {
1309 TIFFError(TIFFFileName(in),
1310 "Can't bias %s,%" PRIu32 " as it has >1 Sample/Pixel\n",
1311 TIFFFileName(in), TIFFCurrentDirectory(in));
1312 return 0;
1313 }
1314 }
1315
1316 /*
1317 * Strip -> strip for change in encoding.
1318 */
1319 DECLAREcpFunc(cpDecodedStrips)
1320 {
1321 tsize_t stripsize = TIFFStripSize(in);
1322 tdata_t buf = limitMalloc(stripsize);
1323
1324 (void)imagewidth;
1325 (void)spp;
1326 if (buf)
1327 {
1328 tstrip_t s, ns = TIFFNumberOfStrips(in);
1329 uint32_t row = 0;
1330 _TIFFmemset(buf, 0, stripsize);
1331 for (s = 0; s < ns && row < imagelength; s++)
1332 {
1333 tsize_t cc = (row + rowsperstrip > imagelength)
1334 ? TIFFVStripSize(in, imagelength - row)
1335 : stripsize;
1336 if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore)
1337 {
1338 TIFFError(TIFFFileName(in), "Error, can't read strip %" PRIu32,
1339 s);
1340 goto bad;
1341 }
1342 if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0)
1343 {
1344 TIFFError(TIFFFileName(out),
1345 "Error, can't write strip %" PRIu32, s);
1346 goto bad;
1347 }
1348 row += rowsperstrip;
1349 }
1350 _TIFFfree(buf);
1351 return 1;
1352 }
1353 else
1354 {
1355 TIFFError(
1356 TIFFFileName(in),
1357 "Error, can't allocate memory buffer of size %" TIFF_SSIZE_FORMAT
1358 " to read strips",
1359 stripsize);
1360 return 0;
1361 }
1362
1363 bad:
1364 _TIFFfree(buf);
1365 return 0;
1366 }
1367
1368 /*
1369 * Separate -> separate by row for rows/strip change.
1370 */
1371 DECLAREcpFunc(cpSeparate2SeparateByRow)
1372 {
1373 tsize_t scanlinesize = TIFFScanlineSize(in);
1374 tdata_t buf;
1375 uint32_t row;
1376 tsample_t s;
1377
1378 (void)imagewidth;
1379 buf = limitMalloc(scanlinesize);
1380 if (!buf)
1381 return 0;
1382 _TIFFmemset(buf, 0, scanlinesize);
1383 for (s = 0; s < spp; s++)
1384 {
1385 for (row = 0; row < imagelength; row++)
1386 {
1387 if (TIFFReadScanline(in, buf, row, s) < 0 && !ignore)
1388 {
1389 TIFFError(TIFFFileName(in),
1390 "Error, can't read scanline %" PRIu32, row);
1391 goto bad;
1392 }
1393 if (TIFFWriteScanline(out, buf, row, s) < 0)
1394 {
1395 TIFFError(TIFFFileName(out),
1396 "Error, can't write scanline %" PRIu32, row);
1397 goto bad;
1398 }
1399 }
1400 }
1401 _TIFFfree(buf);
1402 return 1;
1403 bad:
1404 _TIFFfree(buf);
1405 return 0;
1406 }
1407
1408 /*
1409 * Contig -> separate by row.
1410 */
1411 DECLAREcpFunc(cpContig2SeparateByRow)
1412 {
1413 tsize_t scanlinesizein = TIFFScanlineSize(in);
1414 tsize_t scanlinesizeout = TIFFScanlineSize(out);
1415 tdata_t inbuf;
1416 tdata_t outbuf;
1417 register uint8_t *inp, *outp;
1418 register uint32_t n;
1419 uint32_t row;
1420 tsample_t s;
1421 uint16_t bps = 0;
1422
1423 (void)TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
1424 if (bps != 8)
1425 {
1426 TIFFError(TIFFFileName(in),
1427 "Error, can only handle BitsPerSample=8 in %s",
1428 "cpContig2SeparateByRow");
1429 return 0;
1430 }
1431
1432 inbuf = limitMalloc(scanlinesizein);
1433 outbuf = limitMalloc(scanlinesizeout);
1434 if (!inbuf || !outbuf)
1435 goto bad;
1436 _TIFFmemset(inbuf, 0, scanlinesizein);
1437 _TIFFmemset(outbuf, 0, scanlinesizeout);
1438 /* unpack channels */
1439 for (s = 0; s < spp; s++)
1440 {
1441 for (row = 0; row < imagelength; row++)
1442 {
1443 if (TIFFReadScanline(in, inbuf, row, 0) < 0 && !ignore)
1444 {
1445 TIFFError(TIFFFileName(in),
1446 "Error, can't read scanline %" PRIu32, row);
1447 goto bad;
1448 }
1449 inp = ((uint8_t *)inbuf) + s;
1450 outp = (uint8_t *)outbuf;
1451 for (n = imagewidth; n-- > 0;)
1452 {
1453 *outp++ = *inp;
1454 inp += spp;
1455 }
1456 if (TIFFWriteScanline(out, outbuf, row, s) < 0)
1457 {
1458 TIFFError(TIFFFileName(out),
1459 "Error, can't write scanline %" PRIu32, row);
1460 goto bad;
1461 }
1462 }
1463 }
1464 if (inbuf)
1465 _TIFFfree(inbuf);
1466 if (outbuf)
1467 _TIFFfree(outbuf);
1468 return 1;
1469 bad:
1470 if (inbuf)
1471 _TIFFfree(inbuf);
1472 if (outbuf)
1473 _TIFFfree(outbuf);
1474 return 0;
1475 }
1476
1477 /*
1478 * Separate -> contig by row.
1479 */
1480 DECLAREcpFunc(cpSeparate2ContigByRow)
1481 {
1482 tsize_t scanlinesizein = TIFFScanlineSize(in);
1483 tsize_t scanlinesizeout = TIFFScanlineSize(out);
1484 tdata_t inbuf;
1485 tdata_t outbuf;
1486 register uint8_t *inp, *outp;
1487 register uint32_t n;
1488 uint32_t row;
1489 tsample_t s;
1490 uint16_t bps = 0;
1491
1492 (void)TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
1493 if (bps != 8)
1494 {
1495 TIFFError(TIFFFileName(in),
1496 "Error, can only handle BitsPerSample=8 in %s",
1497 "cpSeparate2ContigByRow");
1498 return 0;
1499 }
1500
1501 inbuf = limitMalloc(scanlinesizein);
1502 outbuf = limitMalloc(scanlinesizeout);
1503 if (!inbuf || !outbuf)
1504 goto bad;
1505 _TIFFmemset(inbuf, 0, scanlinesizein);
1506 _TIFFmemset(outbuf, 0, scanlinesizeout);
1507 for (row = 0; row < imagelength; row++)
1508 {
1509 /* merge channels */
1510 for (s = 0; s < spp; s++)
1511 {
1512 if (TIFFReadScanline(in, inbuf, row, s) < 0 && !ignore)
1513 {
1514 TIFFError(TIFFFileName(in),
1515 "Error, can't read scanline %" PRIu32, row);
1516 goto bad;
1517 }
1518 inp = (uint8_t *)inbuf;
1519 outp = ((uint8_t *)outbuf) + s;
1520 for (n = imagewidth; n-- > 0;)
1521 {
1522 *outp = *inp++;
1523 outp += spp;
1524 }
1525 }
1526 if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
1527 {
1528 TIFFError(TIFFFileName(out), "Error, can't write scanline %" PRIu32,
1529 row);
1530 goto bad;
1531 }
1532 }
1533 if (inbuf)
1534 _TIFFfree(inbuf);
1535 if (outbuf)
1536 _TIFFfree(outbuf);
1537 return 1;
1538 bad:
1539 if (inbuf)
1540 _TIFFfree(inbuf);
1541 if (outbuf)
1542 _TIFFfree(outbuf);
1543 return 0;
1544 }
1545
1546 static void cpStripToTile(uint8_t *out, uint8_t *in, uint32_t rows,
1547 uint32_t cols, int outskew, int64_t inskew)
1548 {
1549 while (rows-- > 0)
1550 {
1551 uint32_t j = cols;
1552 while (j-- > 0)
1553 *out++ = *in++;
1554 out += outskew;
1555 in += inskew;
1556 }
1557 }
1558
1559 static void cpContigBufToSeparateBuf(uint8_t *out, uint8_t *in, uint32_t rows,
1560 uint32_t cols, int outskew, int inskew,
1561 tsample_t spp, int bytes_per_sample)
1562 {
1563 while (rows-- > 0)
1564 {
1565 uint32_t j = cols;
1566 while (j-- > 0)
1567 {
1568 int n = bytes_per_sample;
1569
1570 while (n--)
1571 {
1572 *out++ = *in++;
1573 }
1574 in += (spp - 1) * bytes_per_sample;
1575 }
1576 out += outskew;
1577 in += inskew;
1578 }
1579 }
1580
1581 static void cpSeparateBufToContigBuf(uint8_t *out, uint8_t *in, uint32_t rows,
1582 uint32_t cols, int outskew, int inskew,
1583 tsample_t spp, int bytes_per_sample)
1584 {
1585 while (rows-- > 0)
1586 {
1587 uint32_t j = cols;
1588 while (j-- > 0)
1589 {
1590 int n = bytes_per_sample;
1591
1592 while (n--)
1593 {
1594 *out++ = *in++;
1595 }
1596 out += (spp - 1) * bytes_per_sample;
1597 }
1598 out += outskew;
1599 in += inskew;
1600 }
1601 }
1602
1603 static int cpImage(TIFF *in, TIFF *out, readFunc fin, writeFunc fout,
1604 uint32_t imagelength, uint32_t imagewidth, tsample_t spp)
1605 {
1606 int status = 0;
1607 tdata_t buf = NULL;
1608 tsize_t scanlinesize = TIFFRasterScanlineSize(in);
1609 tsize_t bytes = scanlinesize * (tsize_t)imagelength;
1610 /*
1611 * XXX: Check for integer overflow.
1612 */
1613 if (scanlinesize && imagelength &&
1614 bytes / (tsize_t)imagelength == scanlinesize)
1615 {
1616 buf = limitMalloc(bytes);
1617 if (buf)
1618 {
1619 if ((*fin)(in, (uint8_t *)buf, imagelength, imagewidth, spp))
1620 {
1621 status =
1622 (*fout)(out, (uint8_t *)buf, imagelength, imagewidth, spp);
1623 }
1624 _TIFFfree(buf);
1625 }
1626 else
1627 {
1628 TIFFError(TIFFFileName(in),
1629 "Error, can't allocate space for image buffer");
1630 }
1631 }
1632 else
1633 {
1634 TIFFError(TIFFFileName(in), "Error, no space for image buffer");
1635 }
1636
1637 return status;
1638 }
1639
1640 DECLAREreadFunc(readContigStripsIntoBuffer)
1641 {
1642 tsize_t scanlinesize = TIFFScanlineSize(in);
1643 uint8_t *bufp = buf;
1644 uint32_t row;
1645
1646 (void)imagewidth;
1647 (void)spp;
1648 for (row = 0; row < imagelength; row++)
1649 {
1650 if (TIFFReadScanline(in, (tdata_t)bufp, row, 0) < 0 && !ignore)
1651 {
1652 TIFFError(TIFFFileName(in), "Error, can't read scanline %" PRIu32,
1653 row);
1654 return 0;
1655 }
1656 bufp += scanlinesize;
1657 }
1658
1659 return 1;
1660 }
1661
1662 DECLAREreadFunc(readSeparateStripsIntoBuffer)
1663 {
1664 int status = 1;
1665 tsize_t scanlinesize = TIFFScanlineSize(in);
1666 tdata_t scanline;
1667 if (!scanlinesize)
1668 return 0;
1669
1670 scanline = limitMalloc(scanlinesize);
1671 if (!scanline)
1672 return 0;
1673 _TIFFmemset(scanline, 0, scanlinesize);
1674 (void)imagewidth;
1675 if (scanline)
1676 {
1677 uint8_t *bufp = (uint8_t *)buf;
1678 uint32_t row;
1679 tsample_t s;
1680 for (row = 0; row < imagelength; row++)
1681 {
1682 /* merge channels */
1683 for (s = 0; s < spp; s++)
1684 {
1685 uint8_t *bp = bufp + s;
1686 tsize_t n = scanlinesize;
1687 uint8_t *sbuf = scanline;
1688
1689 if (TIFFReadScanline(in, scanline, row, s) < 0 && !ignore)
1690 {
1691 TIFFError(TIFFFileName(in),
1692 "Error, can't read scanline %" PRIu32, row);
1693 status = 0;
1694 goto done;
1695 }
1696 while (n-- > 0)
1697 *bp = *sbuf++, bp += spp;
1698 }
1699 bufp += scanlinesize * spp;
1700 }
1701 }
1702
1703 done:
1704 _TIFFfree(scanline);
1705 return status;
1706 }
1707
1708 DECLAREreadFunc(readContigTilesIntoBuffer)
1709 {
1710 int status = 1;
1711 tsize_t tilesize = TIFFTileSize(in);
1712 tdata_t tilebuf;
1713 uint32_t imagew = TIFFScanlineSize(in);
1714 uint32_t tilew = TIFFTileRowSize(in);
1715 int64_t iskew = (int64_t)imagew - (int64_t)tilew;
1716 uint8_t *bufp = (uint8_t *)buf;
1717 uint32_t tw, tl;
1718 uint32_t row;
1719
1720 (void)spp;
1721 tilebuf = limitMalloc(tilesize);
1722 if (tilebuf == 0)
1723 return 0;
1724 _TIFFmemset(tilebuf, 0, tilesize);
1725 (void)TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
1726 (void)TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
1727
1728 for (row = 0; row < imagelength; row += tl)
1729 {
1730 uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
1731 uint32_t colb = 0;
1732 uint32_t col;
1733
1734 for (col = 0; col < imagewidth && colb < imagew; col += tw)
1735 {
1736 if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore)
1737 {
1738 TIFFError(TIFFFileName(in),
1739 "Error, can't read tile at %" PRIu32 " %" PRIu32, col,
1740 row);
1741 status = 0;
1742 goto done;
1743 }
1744 if (colb > iskew)
1745 {
1746 uint32_t width = imagew - colb;
1747 uint32_t oskew = tilew - width;
1748 cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew,
1749 oskew);
1750 }
1751 else
1752 cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0);
1753 colb += tilew;
1754 }
1755 bufp += imagew * nrow;
1756 }
1757 done:
1758 _TIFFfree(tilebuf);
1759 return status;
1760 }
1761
1762 DECLAREreadFunc(readSeparateTilesIntoBuffer)
1763 {
1764 int status = 1;
1765 uint32_t imagew = TIFFRasterScanlineSize(in);
1766 uint32_t tilew = TIFFTileRowSize(in);
1767 int iskew;
1768 tsize_t tilesize = TIFFTileSize(in);
1769 tdata_t tilebuf;
1770 uint8_t *bufp = (uint8_t *)buf;
1771 uint32_t tw, tl;
1772 uint32_t row;
1773 uint16_t bps = 0, bytes_per_sample;
1774
1775 if (tilew && spp > (INT_MAX / tilew))
1776 {
1777 TIFFError(TIFFFileName(in),
1778 "Error, cannot handle that much samples per tile row (Tile "
1779 "Width * Samples/Pixel)");
1780 return 0;
1781 }
1782
1783 if ((imagew - tilew * spp) > INT_MAX)
1784 {
1785 TIFFError(TIFFFileName(in),
1786 "Error, image raster scan line size is too large");
1787 return 0;
1788 }
1789
1790 iskew = imagew - tilew * spp;
1791 tilebuf = limitMalloc(tilesize);
1792 if (tilebuf == 0)
1793 return 0;
1794 _TIFFmemset(tilebuf, 0, tilesize);
1795 (void)TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
1796 (void)TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
1797 (void)TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
1798 if (bps == 0)
1799 {
1800 TIFFError(TIFFFileName(in), "Error, cannot read BitsPerSample");
1801 status = 0;
1802 goto done;
1803 }
1804 if ((bps % 8) != 0)
1805 {
1806 TIFFError(
1807 TIFFFileName(in),
1808 "Error, cannot handle BitsPerSample that is not a multiple of 8");
1809 status = 0;
1810 goto done;
1811 }
1812 bytes_per_sample = bps / 8;
1813
1814 for (row = 0; row < imagelength; row += tl)
1815 {
1816 uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
1817 uint32_t colb = 0;
1818 uint32_t col;
1819
1820 for (col = 0; col < imagewidth; col += tw)
1821 {
1822 tsample_t s;
1823
1824 for (s = 0; s < spp; s++)
1825 {
1826 if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0 && !ignore)
1827 {
1828 TIFFError(TIFFFileName(in),
1829 "Error, can't read tile at %" PRIu32 " %" PRIu32
1830 ", "
1831 "sample %" PRIu16,
1832 col, row, s);
1833 status = 0;
1834 goto done;
1835 }
1836 /*
1837 * Tile is clipped horizontally. Calculate
1838 * visible portion and skewing factors.
1839 */
1840 if (colb + tilew * spp > imagew)
1841 {
1842 uint32_t width = imagew - colb;
1843 int oskew = tilew * spp - width;
1844 cpSeparateBufToContigBuf(
1845 bufp + colb + s * bytes_per_sample, tilebuf, nrow,
1846 width / (spp * bytes_per_sample), oskew + iskew,
1847 oskew / spp, spp, bytes_per_sample);
1848 }
1849 else
1850 cpSeparateBufToContigBuf(bufp + colb + s * bytes_per_sample,
1851 tilebuf, nrow, tw, iskew, 0, spp,
1852 bytes_per_sample);
1853 }
1854 colb += tilew * spp;
1855 }
1856 bufp += imagew * nrow;
1857 }
1858 done:
1859 _TIFFfree(tilebuf);
1860 return status;
1861 }
1862
1863 DECLAREwriteFunc(writeBufferToContigStrips)
1864 {
1865 uint32_t row;
1866 tstrip_t strip = 0;
1867
1868 (void)imagewidth;
1869 (void)spp;
1870 (void)TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
1871 for (row = 0; row < imagelength; row += rowsperstrip)
1872 {
1873 uint32_t nrows = (row + rowsperstrip > imagelength) ? imagelength - row
1874 : rowsperstrip;
1875 tsize_t stripsize = TIFFVStripSize(out, nrows);
1876 if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0)
1877 {
1878 TIFFError(TIFFFileName(out), "Error, can't write strip %" PRIu32,
1879 strip - 1u);
1880 return 0;
1881 }
1882 buf += stripsize;
1883 }
1884 return 1;
1885 }
1886
1887 DECLAREwriteFunc(writeBufferToSeparateStrips)
1888 {
1889 uint32_t rowsize = imagewidth * spp;
1890 tsize_t stripsize = TIFFStripSize(out);
1891 tdata_t obuf;
1892 tstrip_t strip = 0;
1893 tsample_t s;
1894 uint16_t bps = 0, bytes_per_sample;
1895
1896 obuf = limitMalloc(stripsize);
1897 if (obuf == NULL)
1898 return (0);
1899 _TIFFmemset(obuf, 0, stripsize);
1900 (void)TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
1901 (void)TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
1902 if (bps == 0)
1903 {
1904 TIFFError(TIFFFileName(out), "Error, cannot read BitsPerSample");
1905 _TIFFfree(obuf);
1906 return 0;
1907 }
1908 if ((bps % 8) != 0)
1909 {
1910 TIFFError(
1911 TIFFFileName(out),
1912 "Error, cannot handle BitsPerSample that is not a multiple of 8");
1913 _TIFFfree(obuf);
1914 return 0;
1915 }
1916 bytes_per_sample = bps / 8;
1917 for (s = 0; s < spp; s++)
1918 {
1919 uint32_t row;
1920 for (row = 0; row < imagelength; row += rowsperstrip)
1921 {
1922 uint32_t nrows = (row + rowsperstrip > imagelength)
1923 ? imagelength - row
1924 : rowsperstrip;
1925 stripsize = TIFFVStripSize(out, nrows);
1926
1927 cpContigBufToSeparateBuf(obuf, (uint8_t *)buf + row * rowsize + s,
1928 nrows, imagewidth, 0, 0, spp,
1929 bytes_per_sample);
1930 if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0)
1931 {
1932 TIFFError(TIFFFileName(out),
1933 "Error, can't write strip %" PRIu32, strip - 1u);
1934 _TIFFfree(obuf);
1935 return 0;
1936 }
1937 }
1938 }
1939 _TIFFfree(obuf);
1940 return 1;
1941 }
1942
1943 DECLAREwriteFunc(writeBufferToContigTiles)
1944 {
1945 uint32_t imagew = TIFFScanlineSize(out);
1946 uint32_t tilew = TIFFTileRowSize(out);
1947 int iskew = imagew - tilew;
1948 tsize_t tilesize = TIFFTileSize(out);
1949 tdata_t obuf;
1950 uint8_t *bufp = (uint8_t *)buf;
1951 uint32_t tl, tw;
1952 uint32_t row;
1953
1954 (void)spp;
1955
1956 obuf = limitMalloc(TIFFTileSize(out));
1957 if (obuf == NULL)
1958 return 0;
1959 _TIFFmemset(obuf, 0, tilesize);
1960 (void)TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
1961 (void)TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
1962 for (row = 0; row < imagelength; row += tilelength)
1963 {
1964 uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
1965 uint32_t colb = 0;
1966 uint32_t col;
1967
1968 for (col = 0; col < imagewidth && colb < imagew; col += tw)
1969 {
1970 /*
1971 * Tile is clipped horizontally. Calculate
1972 * visible portion and skewing factors.
1973 */
1974 if (colb + tilew > imagew)
1975 {
1976 uint32_t width = imagew - colb;
1977 int oskew = tilew - width;
1978 cpStripToTile(obuf, bufp + colb, nrow, width, oskew,
1979 oskew + iskew);
1980 }
1981 else
1982 cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew);
1983 if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0)
1984 {
1985 TIFFError(TIFFFileName(out),
1986 "Error, can't write tile at %" PRIu32 " %" PRIu32,
1987 col, row);
1988 _TIFFfree(obuf);
1989 return 0;
1990 }
1991 colb += tilew;
1992 }
1993 bufp += nrow * imagew;
1994 }
1995 _TIFFfree(obuf);
1996 return 1;
1997 }
1998
1999 DECLAREwriteFunc(writeBufferToSeparateTiles)
2000 {
2001 uint32_t imagew = TIFFScanlineSize(out);
2002 tsize_t tilew = TIFFTileRowSize(out);
2003 uint32_t iimagew = TIFFRasterScanlineSize(out);
2004 int iskew = iimagew - tilew * spp;
2005 tsize_t tilesize = TIFFTileSize(out);
2006 tdata_t obuf;
2007 uint8_t *bufp = (uint8_t *)buf;
2008 uint32_t tl, tw;
2009 uint32_t row;
2010 uint16_t bps = 0, bytes_per_sample;
2011
2012 obuf = limitMalloc(TIFFTileSize(out));
2013 if (obuf == NULL)
2014 return 0;
2015 _TIFFmemset(obuf, 0, tilesize);
2016 (void)TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
2017 (void)TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
2018 (void)TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
2019 if (bps == 0)
2020 {
2021 TIFFError(TIFFFileName(out), "Error, cannot read BitsPerSample");
2022 _TIFFfree(obuf);
2023 return 0;
2024 }
2025 if ((bps % 8) != 0)
2026 {
2027 TIFFError(
2028 TIFFFileName(out),
2029 "Error, cannot handle BitsPerSample that is not a multiple of 8");
2030 _TIFFfree(obuf);
2031 return 0;
2032 }
2033 bytes_per_sample = bps / 8;
2034
2035 for (row = 0; row < imagelength; row += tl)
2036 {
2037 uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
2038 uint32_t colb = 0;
2039 uint32_t col;
2040
2041 for (col = 0; col < imagewidth; col += tw)
2042 {
2043 tsample_t s;
2044 for (s = 0; s < spp; s++)
2045 {
2046 /*
2047 * Tile is clipped horizontally. Calculate
2048 * visible portion and skewing factors.
2049 */
2050 if (colb + tilew > imagew)
2051 {
2052 uint32_t width = (imagew - colb);
2053 int oskew = tilew - width;
2054
2055 cpContigBufToSeparateBuf(obuf, bufp + (colb * spp) + s,
2056 nrow, width / bytes_per_sample,
2057 oskew, (oskew * spp) + iskew, spp,
2058 bytes_per_sample);
2059 }
2060 else
2061 cpContigBufToSeparateBuf(obuf, bufp + (colb * spp) + s,
2062 nrow, tilewidth, 0, iskew, spp,
2063 bytes_per_sample);
2064 if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0)
2065 {
2066 TIFFError(TIFFFileName(out),
2067 "Error, can't write tile at %" PRIu32 " %" PRIu32
2068 " sample %" PRIu16,
2069 col, row, s);
2070 _TIFFfree(obuf);
2071 return 0;
2072 }
2073 }
2074 colb += tilew;
2075 }
2076 bufp += nrow * iimagew;
2077 }
2078 _TIFFfree(obuf);
2079 return 1;
2080 }
2081
2082 /*
2083 * Contig strips -> contig tiles.
2084 */
2085 DECLAREcpFunc(cpContigStrips2ContigTiles)
2086 {
2087 return cpImage(in, out, readContigStripsIntoBuffer,
2088 writeBufferToContigTiles, imagelength, imagewidth, spp);
2089 }
2090
2091 /*
2092 * Contig strips -> separate tiles.
2093 */
2094 DECLAREcpFunc(cpContigStrips2SeparateTiles)
2095 {
2096 return cpImage(in, out, readContigStripsIntoBuffer,
2097 writeBufferToSeparateTiles, imagelength, imagewidth, spp);
2098 }
2099
2100 /*
2101 * Separate strips -> contig tiles.
2102 */
2103 DECLAREcpFunc(cpSeparateStrips2ContigTiles)
2104 {
2105 return cpImage(in, out, readSeparateStripsIntoBuffer,
2106 writeBufferToContigTiles, imagelength, imagewidth, spp);
2107 }
2108
2109 /*
2110 * Separate strips -> separate tiles.
2111 */
2112 DECLAREcpFunc(cpSeparateStrips2SeparateTiles)
2113 {
2114 return cpImage(in, out, readSeparateStripsIntoBuffer,
2115 writeBufferToSeparateTiles, imagelength, imagewidth, spp);
2116 }
2117
2118 /*
2119 * Contig strips -> contig tiles.
2120 */
2121 DECLAREcpFunc(cpContigTiles2ContigTiles)
2122 {
2123 return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigTiles,
2124 imagelength, imagewidth, spp);
2125 }
2126
2127 /*
2128 * Contig tiles -> separate tiles.
2129 */
2130 DECLAREcpFunc(cpContigTiles2SeparateTiles)
2131 {
2132 return cpImage(in, out, readContigTilesIntoBuffer,
2133 writeBufferToSeparateTiles, imagelength, imagewidth, spp);
2134 }
2135
2136 /*
2137 * Separate tiles -> contig tiles.
2138 */
2139 DECLAREcpFunc(cpSeparateTiles2ContigTiles)
2140 {
2141 return cpImage(in, out, readSeparateTilesIntoBuffer,
2142 writeBufferToContigTiles, imagelength, imagewidth, spp);
2143 }
2144
2145 /*
2146 * Separate tiles -> separate tiles (tile dimension change).
2147 */
2148 DECLAREcpFunc(cpSeparateTiles2SeparateTiles)
2149 {
2150 return cpImage(in, out, readSeparateTilesIntoBuffer,
2151 writeBufferToSeparateTiles, imagelength, imagewidth, spp);
2152 }
2153
2154 /*
2155 * Contig tiles -> contig tiles (tile dimension change).
2156 */
2157 DECLAREcpFunc(cpContigTiles2ContigStrips)
2158 {
2159 return cpImage(in, out, readContigTilesIntoBuffer,
2160 writeBufferToContigStrips, imagelength, imagewidth, spp);
2161 }
2162
2163 /*
2164 * Contig tiles -> separate strips.
2165 */
2166 DECLAREcpFunc(cpContigTiles2SeparateStrips)
2167 {
2168 return cpImage(in, out, readContigTilesIntoBuffer,
2169 writeBufferToSeparateStrips, imagelength, imagewidth, spp);
2170 }
2171
2172 /*
2173 * Separate tiles -> contig strips.
2174 */
2175 DECLAREcpFunc(cpSeparateTiles2ContigStrips)
2176 {
2177 return cpImage(in, out, readSeparateTilesIntoBuffer,
2178 writeBufferToContigStrips, imagelength, imagewidth, spp);
2179 }
2180
2181 /*
2182 * Separate tiles -> separate strips.
2183 */
2184 DECLAREcpFunc(cpSeparateTiles2SeparateStrips)
2185 {
2186 return cpImage(in, out, readSeparateTilesIntoBuffer,
2187 writeBufferToSeparateStrips, imagelength, imagewidth, spp);
2188 }
2189
2190 /*
2191 * Select the appropriate copy function to use.
2192 */
2193 static copyFunc pickCopyFunc(TIFF *in, TIFF *out, uint16_t bitspersample,
2194 uint16_t samplesperpixel)
2195 {
2196 uint16_t shortv;
2197 uint32_t w, l, tw, tl;
2198 int bychunk;
2199
2200 (void)TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &shortv);
2201 if (shortv != config && bitspersample != 8 && samplesperpixel > 1)
2202 {
2203 fprintf(stderr,
2204 "%s: Cannot handle different planar configuration w/ "
2205 "bits/sample != 8\n",
2206 TIFFFileName(in));
2207 return (NULL);
2208 }
2209 TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
2210 TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l);
2211 if (!(TIFFIsTiled(out) || TIFFIsTiled(in)))
2212 {
2213 uint32_t irps = (uint32_t)-1L;
2214 TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps);
2215 /* if biased, force decoded copying to allow image subtraction */
2216 bychunk = !bias && (rowsperstrip == irps);
2217 }
2218 else
2219 { /* either in or out is tiled */
2220 if (bias)
2221 {
2222 fprintf(stderr,
2223 "%s: Cannot handle tiled configuration w/bias image\n",
2224 TIFFFileName(in));
2225 return (NULL);
2226 }
2227 if (TIFFIsTiled(out))
2228 {
2229 if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw))
2230 tw = w;
2231 if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl))
2232 tl = l;
2233 bychunk = (tw == tilewidth && tl == tilelength);
2234 }
2235 else
2236 { /* out's not, so in must be tiled */
2237 TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
2238 TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
2239 bychunk = (tw == w && tl == rowsperstrip);
2240 }
2241 }
2242 #define T 1
2243 #define F 0
2244 #define pack(a, b, c, d, e) \
2245 ((long)(((a) << 11) | ((b) << 3) | ((c) << 2) | ((d) << 1) | (e)))
2246 switch (pack(shortv, config, TIFFIsTiled(in), TIFFIsTiled(out), bychunk))
2247 {
2248 /* Strips -> Tiles */
2249 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F, T, F):
2250 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F, T, T):
2251 return cpContigStrips2ContigTiles;
2252 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F, T, F):
2253 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F, T, T):
2254 return cpContigStrips2SeparateTiles;
2255 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F, T, F):
2256 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F, T, T):
2257 return cpSeparateStrips2ContigTiles;
2258 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F, T, F):
2259 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F, T, T):
2260 return cpSeparateStrips2SeparateTiles;
2261 /* Tiles -> Tiles */
2262 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T, T, F):
2263 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T, T, T):
2264 return cpContigTiles2ContigTiles;
2265 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T, T, F):
2266 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T, T, T):
2267 return cpContigTiles2SeparateTiles;
2268 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T, T, F):
2269 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T, T, T):
2270 return cpSeparateTiles2ContigTiles;
2271 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T, T, F):
2272 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T, T, T):
2273 return cpSeparateTiles2SeparateTiles;
2274 /* Tiles -> Strips */
2275 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T, F, F):
2276 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T, F, T):
2277 return cpContigTiles2ContigStrips;
2278 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T, F, F):
2279 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T, F, T):
2280 return cpContigTiles2SeparateStrips;
2281 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T, F, F):
2282 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T, F, T):
2283 return cpSeparateTiles2ContigStrips;
2284 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T, F, F):
2285 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T, F, T):
2286 return cpSeparateTiles2SeparateStrips;
2287 /* Strips -> Strips */
2288 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F, F, F):
2289 return bias ? cpBiasedContig2Contig : cpContig2ContigByRow;
2290 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F, F, T):
2291 return cpDecodedStrips;
2292 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F, F, F):
2293 case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F, F, T):
2294 return cpContig2SeparateByRow;
2295 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F, F, F):
2296 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F, F, T):
2297 return cpSeparate2ContigByRow;
2298 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F, F, F):
2299 case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F, F, T):
2300 return cpSeparate2SeparateByRow;
2301 }
2302 #undef pack
2303 #undef F
2304 #undef T
2305 fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n",
2306 TIFFFileName(in));
2307 return (NULL);
2308 }