summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorpre-commit run by Even Rouault <even.rouault-bot@spatialys.com>2022-12-08 19:19:07 +0100
committerEven Rouault <even.rouault@spatialys.com>2022-12-08 19:19:07 +0100
commitb0ae5d7071890160da67d2e833d84a400e0406d0 (patch)
treeb827d1395fda08ad29130a964a313eccb7d07413
parent42173d6ace476b5228d866640b5355f74e5a108d (diff)
downloadlibtiff-git-b0ae5d7071890160da67d2e833d84a400e0406d0.tar.gz
Reformatting in tools/ using 'pre-commit run'
-rw-r--r--tools/fax2ps.c627
-rw-r--r--tools/fax2tiff.c826
-rw-r--r--tools/pal2rgb.c798
-rw-r--r--tools/ppm2tiff.c911
-rw-r--r--tools/raw2tiff.c1249
-rw-r--r--tools/rgb2ycbcr.c637
-rw-r--r--tools/thumbnail.c1017
-rw-r--r--tools/tiff2bw.c909
-rw-r--r--tools/tiff2pdf.c10424
-rw-r--r--tools/tiff2ps.c5423
-rw-r--r--tools/tiff2rgba.c632
-rw-r--r--tools/tiffcmp.c1144
-rw-r--r--tools/tiffcp.c3604
-rw-r--r--tools/tiffcrop.c17632
-rw-r--r--tools/tiffdither.c569
-rw-r--r--tools/tiffdump.c1503
-rw-r--r--tools/tiffgt.c720
-rw-r--r--tools/tiffinfo.c1192
-rw-r--r--tools/tiffmedian.c1683
-rw-r--r--tools/tiffset.c566
-rw-r--r--tools/tiffsplit.c732
21 files changed, 27745 insertions, 25053 deletions
diff --git a/tools/fax2ps.c b/tools/fax2ps.c
index 93f48f01..50245410 100644
--- a/tools/fax2ps.c
+++ b/tools/fax2ps.c
@@ -2,203 +2,212 @@
* Copyright (c) 1991-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
-#include <stdlib.h>
+#include <math.h>
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
-#include <math.h>
#include <time.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
-# include <fcntl.h>
+#include <fcntl.h>
#endif
#ifdef HAVE_IO_H
-# include <io.h>
+#include <io.h>
#endif
-#include "tiffiop.h"
#include "tiffio.h"
+#include "tiffiop.h"
#ifndef EXIT_SUCCESS
-#define EXIT_SUCCESS 0
+#define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
-#define EXIT_FAILURE 1
+#define EXIT_FAILURE 1
#endif
-float defxres = 204.; /* default x resolution (pixels/inch) */
-float defyres = 98.; /* default y resolution (lines/inch) */
+float defxres = 204.; /* default x resolution (pixels/inch) */
+float defyres = 98.; /* default y resolution (lines/inch) */
const float half = 0.5;
const float points = 72.0;
-float pageWidth = 0; /* image page width (inches) */
-float pageHeight = 0; /* image page length (inches) */
-int scaleToPage = 0; /* if true, scale raster to page dimensions */
-int totalPages = 0; /* total # pages printed */
-int row; /* current output row */
-int maxline = 512; /* max output line of PostScript */
+float pageWidth = 0; /* image page width (inches) */
+float pageHeight = 0; /* image page length (inches) */
+int scaleToPage = 0; /* if true, scale raster to page dimensions */
+int totalPages = 0; /* total # pages printed */
+int row; /* current output row */
+int maxline = 512; /* max output line of PostScript */
/*
* Turn a bit-mapped scanline into the appropriate sequence
* of PostScript characters to be rendered.
- *
+ *
* Original version written by Bret D. Whissel,
* Florida State University Meteorology Department
* March 13-15, 1995.
*/
-static void
-printruns(unsigned char* buf, uint32_t* runs, uint32_t* erun, uint32_t lastx)
+static void printruns(unsigned char *buf, uint32_t *runs, uint32_t *erun,
+ uint32_t lastx)
{
- static struct {
- char white, black;
- unsigned short width;
- } WBarr[] = {
- { 'd', 'n', 512 }, { 'e', 'o', 256 }, { 'f', 'p', 128 },
- { 'g', 'q', 64 }, { 'h', 'r', 32 }, { 'i', 's', 16 },
- { 'j', 't', 8 }, { 'k', 'u', 4 }, { 'l', 'v', 2 },
- { 'm', 'w', 1 }
- };
- static char* svalue =
- " !\"#$&'*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abc";
- int colormode = 1; /* 0 for white, 1 for black */
+ static struct
+ {
+ char white, black;
+ unsigned short width;
+ } WBarr[] = {{'d', 'n', 512}, {'e', 'o', 256}, {'f', 'p', 128},
+ {'g', 'q', 64}, {'h', 'r', 32}, {'i', 's', 16},
+ {'j', 't', 8}, {'k', 'u', 4}, {'l', 'v', 2},
+ {'m', 'w', 1}};
+ static char *svalue =
+ " !\"#$&'*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abc";
+ int colormode = 1; /* 0 for white, 1 for black */
uint32_t runlength = 0;
int n = maxline;
uint32_t x = 0;
int l;
- (void) buf;
+ (void)buf;
printf("%d m(", row++);
- while (runs < erun) {
- if (runlength <= 0) {
- colormode ^= 1;
- runlength = *runs++;
- if (x+runlength > lastx)
- runlength = runs[-1] = lastx-x;
- x += runlength;
- if (!colormode && runs == erun)
- break; /* don't bother printing the final white run */
- }
- /*
- * If a runlength is greater than 6 pixels, then spit out
- * black or white characters until the runlength drops to
- * 6 or less. Once a runlength is <= 6, then combine black
- * and white runlengths until a 6-pixel pattern is obtained.
- * Then write out the special character. Six-pixel patterns
- * were selected since 64 patterns is the largest power of
- * two less than the 92 "easily printable" PostScript
- * characters (i.e., no escape codes or octal chars).
- */
- l = 0;
- while (runlength > 6) { /* Run is greater than six... */
- if (runlength >= WBarr[l].width) {
- if (n == 0) {
- putchar('\n');
- n = maxline;
- }
- putchar(colormode ? WBarr[l].black : WBarr[l].white), n--;
- runlength -= WBarr[l].width;
- } else
- l++;
- }
- while (runlength > 0 && runlength <= 6) {
- uint32_t bitsleft = 6;
- int t = 0;
- while (bitsleft) {
- if (runlength <= bitsleft) {
- if (colormode)
- t |= ((1 << runlength)-1) << (bitsleft-runlength);
- bitsleft -= runlength;
- runlength = 0;
- if (bitsleft) {
- if (runs >= erun)
- break;
- colormode ^= 1;
- runlength = *runs++;
- if (x+runlength > lastx)
- runlength = runs[-1] = lastx-x;
- x += runlength;
- }
- } else { /* runlength exceeds bits left */
- if (colormode)
- t |= ((1 << bitsleft)-1);
- runlength -= bitsleft;
- bitsleft = 0;
- }
- }
- if (n == 0) {
- putchar('\n');
- n = maxline;
- }
- putchar(svalue[t]), n--;
- }
+ while (runs < erun)
+ {
+ if (runlength <= 0)
+ {
+ colormode ^= 1;
+ runlength = *runs++;
+ if (x + runlength > lastx)
+ runlength = runs[-1] = lastx - x;
+ x += runlength;
+ if (!colormode && runs == erun)
+ break; /* don't bother printing the final white run */
+ }
+ /*
+ * If a runlength is greater than 6 pixels, then spit out
+ * black or white characters until the runlength drops to
+ * 6 or less. Once a runlength is <= 6, then combine black
+ * and white runlengths until a 6-pixel pattern is obtained.
+ * Then write out the special character. Six-pixel patterns
+ * were selected since 64 patterns is the largest power of
+ * two less than the 92 "easily printable" PostScript
+ * characters (i.e., no escape codes or octal chars).
+ */
+ l = 0;
+ while (runlength > 6)
+ { /* Run is greater than six... */
+ if (runlength >= WBarr[l].width)
+ {
+ if (n == 0)
+ {
+ putchar('\n');
+ n = maxline;
+ }
+ putchar(colormode ? WBarr[l].black : WBarr[l].white), n--;
+ runlength -= WBarr[l].width;
+ }
+ else
+ l++;
+ }
+ while (runlength > 0 && runlength <= 6)
+ {
+ uint32_t bitsleft = 6;
+ int t = 0;
+ while (bitsleft)
+ {
+ if (runlength <= bitsleft)
+ {
+ if (colormode)
+ t |= ((1 << runlength) - 1) << (bitsleft - runlength);
+ bitsleft -= runlength;
+ runlength = 0;
+ if (bitsleft)
+ {
+ if (runs >= erun)
+ break;
+ colormode ^= 1;
+ runlength = *runs++;
+ if (x + runlength > lastx)
+ runlength = runs[-1] = lastx - x;
+ x += runlength;
+ }
+ }
+ else
+ { /* runlength exceeds bits left */
+ if (colormode)
+ t |= ((1 << bitsleft) - 1);
+ runlength -= bitsleft;
+ bitsleft = 0;
+ }
+ }
+ if (n == 0)
+ {
+ putchar('\n');
+ n = maxline;
+ }
+ putchar(svalue[t]), n--;
+ }
}
printf(")s\n");
}
-/*
+/*
* Create a special PostScript font for printing FAX documents. By taking
- * advantage of the font-cacheing mechanism, a substantial speed-up in
- * rendering time is realized.
+ * advantage of the font-cacheing mechanism, a substantial speed-up in
+ * rendering time is realized.
*/
-static void
-emitFont(FILE* fd)
+static void emitFont(FILE *fd)
{
- static const char* fontPrologue[] = {
- "/newfont 10 dict def newfont begin /FontType 3 def /FontMatrix [1",
- "0 0 1 0 0] def /FontBBox [0 0 512 1] def /Encoding 256 array def",
- "0 1 31{Encoding exch /255 put}for 120 1 255{Encoding exch /255",
- "put}for Encoding 37 /255 put Encoding 40 /255 put Encoding 41 /255",
- "put Encoding 92 /255 put /count 0 def /ls{Encoding exch count 3",
- "string cvs cvn put /count count 1 add def}def 32 1 36{ls}for",
- "38 1 39{ls}for 42 1 91{ls}for 93 1 99{ls}for /count 100",
- "def 100 1 119{ls}for /CharDict 5 dict def CharDict begin /white",
- "{dup 255 eq{pop}{1 dict begin 100 sub neg 512 exch bitshift",
- "/cw exch def cw 0 0 0 cw 1 setcachedevice end}ifelse}def /black",
- "{dup 255 eq{pop}{1 dict begin 110 sub neg 512 exch bitshift",
- "/cw exch def cw 0 0 0 cw 1 setcachedevice 0 0 moveto cw 0 rlineto",
- "0 1 rlineto cw neg 0 rlineto closepath fill end}ifelse}def /numbuild",
- "{dup 255 eq{pop}{6 0 0 0 6 1 setcachedevice 0 1 5{0 moveto",
- "dup 32 and 32 eq{1 0 rlineto 0 1 rlineto -1 0 rlineto closepath",
- "fill newpath}if 1 bitshift}for pop}ifelse}def /.notdef {}",
- "def /255 {}def end /BuildChar{exch begin dup 110 ge{Encoding",
- "exch get 3 string cvs cvi CharDict /black get}{dup 100 ge {Encoding",
- "exch get 3 string cvs cvi CharDict /white get}{Encoding exch get",
- "3 string cvs cvi CharDict /numbuild get}ifelse}ifelse exec end",
- "}def end /Bitfont newfont definefont 1 scalefont setfont",
- NULL
- };
+ static const char *fontPrologue[] = {
+ "/newfont 10 dict def newfont begin /FontType 3 def /FontMatrix [1",
+ "0 0 1 0 0] def /FontBBox [0 0 512 1] def /Encoding 256 array def",
+ "0 1 31{Encoding exch /255 put}for 120 1 255{Encoding exch /255",
+ "put}for Encoding 37 /255 put Encoding 40 /255 put Encoding 41 /255",
+ "put Encoding 92 /255 put /count 0 def /ls{Encoding exch count 3",
+ "string cvs cvn put /count count 1 add def}def 32 1 36{ls}for",
+ "38 1 39{ls}for 42 1 91{ls}for 93 1 99{ls}for /count 100",
+ "def 100 1 119{ls}for /CharDict 5 dict def CharDict begin /white",
+ "{dup 255 eq{pop}{1 dict begin 100 sub neg 512 exch bitshift",
+ "/cw exch def cw 0 0 0 cw 1 setcachedevice end}ifelse}def /black",
+ "{dup 255 eq{pop}{1 dict begin 110 sub neg 512 exch bitshift",
+ "/cw exch def cw 0 0 0 cw 1 setcachedevice 0 0 moveto cw 0 rlineto",
+ "0 1 rlineto cw neg 0 rlineto closepath fill end}ifelse}def /numbuild",
+ "{dup 255 eq{pop}{6 0 0 0 6 1 setcachedevice 0 1 5{0 moveto",
+ "dup 32 and 32 eq{1 0 rlineto 0 1 rlineto -1 0 rlineto closepath",
+ "fill newpath}if 1 bitshift}for pop}ifelse}def /.notdef {}",
+ "def /255 {}def end /BuildChar{exch begin dup 110 ge{Encoding",
+ "exch get 3 string cvs cvi CharDict /black get}{dup 100 ge {Encoding",
+ "exch get 3 string cvs cvi CharDict /white get}{Encoding exch get",
+ "3 string cvs cvi CharDict /numbuild get}ifelse}ifelse exec end",
+ "}def end /Bitfont newfont definefont 1 scalefont setfont",
+ NULL};
int i;
for (i = 0; fontPrologue[i] != NULL; i++)
- fprintf(fd, "%s\n", fontPrologue[i]);
+ fprintf(fd, "%s\n", fontPrologue[i]);
}
-void
-printTIF(TIFF* tif, uint16_t pageNumber)
+void printTIF(TIFF *tif, uint16_t pageNumber)
{
uint32_t w, h;
uint16_t unit, compression;
@@ -208,29 +217,32 @@ printTIF(TIFF* tif, uint16_t pageNumber)
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
- if (!TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression)
- || compression < COMPRESSION_CCITTRLE
- || compression > COMPRESSION_CCITT_T6)
- return;
- if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) || !xres) {
- TIFFWarning(TIFFFileName(tif),
- "No x-resolution, assuming %g dpi", defxres);
- xres = defxres;
+ if (!TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression) ||
+ compression < COMPRESSION_CCITTRLE ||
+ compression > COMPRESSION_CCITT_T6)
+ return;
+ if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) || !xres)
+ {
+ TIFFWarning(TIFFFileName(tif), "No x-resolution, assuming %g dpi",
+ defxres);
+ xres = defxres;
}
- if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) || !yres) {
- TIFFWarning(TIFFFileName(tif),
- "No y-resolution, assuming %g lpi", defyres);
- yres = defyres; /* XXX */
+ if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) || !yres)
+ {
+ TIFFWarning(TIFFFileName(tif), "No y-resolution, assuming %g lpi",
+ defyres);
+ yres = defyres; /* XXX */
}
if (TIFFGetField(tif, TIFFTAG_RESOLUTIONUNIT, &unit) &&
- unit == RESUNIT_CENTIMETER) {
- xres *= 2.54F;
- yres *= 2.54F;
+ unit == RESUNIT_CENTIMETER)
+ {
+ xres *= 2.54F;
+ yres *= 2.54F;
}
if (pageWidth == 0)
- pageWidth = w / xres;
+ pageWidth = w / xres;
if (pageHeight == 0)
- pageHeight = h / yres;
+ pageHeight = h / yres;
printf("%%!PS-Adobe-3.0\n");
printf("%%%%Creator: fax2ps\n");
@@ -240,8 +252,8 @@ printTIF(TIFF* tif, uint16_t pageNumber)
creation_time = time(0);
printf("%%%%CreationDate: %s", ctime(&creation_time));
printf("%%%%Origin: 0 0\n");
- printf("%%%%BoundingBox: 0 0 %u %u\n",
- (int)(pageWidth * points), (int)(pageHeight * points)); /* XXX */
+ printf("%%%%BoundingBox: 0 0 %u %u\n", (int)(pageWidth * points),
+ (int)(pageHeight * points)); /* XXX */
printf("%%%%Pages: (atend)\n");
printf("%%%%EndComments\n");
printf("%%%%BeginProlog\n");
@@ -249,180 +261,195 @@ printTIF(TIFF* tif, uint16_t pageNumber)
printf("/d{bind def}def\n"); /* bind and def proc */
printf("/m{0 exch moveto}d\n");
printf("/s{show}d\n");
- printf("/p{showpage}d \n"); /* end page */
+ printf("/p{showpage}d \n"); /* end page */
printf("%%%%EndProlog\n");
printf("%%%%Page: \"%u\" %u\n", pageNumber, pageNumber);
printf("/$pageTop save def gsave\n");
if (scaleToPage)
- scale = pageHeight / (h/yres) < pageWidth / (w/xres) ?
- pageHeight / (h/yres) : pageWidth / (w/xres);
- printf("%g %g translate\n",
- points * (pageWidth - scale*w/xres) * half,
- points * (scale*h/yres + (pageHeight - scale*h/yres) * half));
- printf("%g %g scale\n", points/xres*scale, -points/yres*scale);
+ scale = pageHeight / (h / yres) < pageWidth / (w / xres)
+ ? pageHeight / (h / yres)
+ : pageWidth / (w / xres);
+ printf("%g %g translate\n", points * (pageWidth - scale * w / xres) * half,
+ points *
+ (scale * h / yres + (pageHeight - scale * h / yres) * half));
+ printf("%g %g scale\n", points / xres * scale, -points / yres * scale);
printf("0 setgray\n");
TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, printruns);
ns = TIFFNumberOfStrips(tif);
row = 0;
for (s = 0; s < ns; s++)
- (void) TIFFReadEncodedStrip(tif, s, (tdata_t) NULL, (tsize_t) -1);
+ (void)TIFFReadEncodedStrip(tif, s, (tdata_t)NULL, (tsize_t)-1);
printf("p\n");
printf("grestore $pageTop restore\n");
totalPages++;
}
-#define GetPageNumber(tif) \
-TIFFGetField(tif, TIFFTAG_PAGENUMBER, &pn, &ptotal)
+#define GetPageNumber(tif) TIFFGetField(tif, TIFFTAG_PAGENUMBER, &pn, &ptotal)
-int
-findPage(TIFF* tif, uint16_t pageNumber)
+int findPage(TIFF *tif, uint16_t pageNumber)
{
- uint16_t pn = (uint16_t) -1;
- uint16_t ptotal = (uint16_t) -1;
- if (GetPageNumber(tif)) {
- while (pn != (pageNumber-1) && TIFFReadDirectory(tif) && GetPageNumber(tif))
- ;
- return (pn == (pageNumber-1));
- } else
- return (TIFFSetDirectory(tif, (tdir_t)(pageNumber-1)));
+ uint16_t pn = (uint16_t)-1;
+ uint16_t ptotal = (uint16_t)-1;
+ if (GetPageNumber(tif))
+ {
+ while (pn != (pageNumber - 1) && TIFFReadDirectory(tif) &&
+ GetPageNumber(tif))
+ ;
+ return (pn == (pageNumber - 1));
+ }
+ else
+ return (TIFFSetDirectory(tif, (tdir_t)(pageNumber - 1)));
}
-void
-fax2ps(TIFF* tif, uint16_t npages, uint16_t* pages, char* filename)
+void fax2ps(TIFF *tif, uint16_t npages, uint16_t *pages, char *filename)
{
- if (npages > 0) {
- uint16_t pn, ptotal;
- int i;
+ if (npages > 0)
+ {
+ uint16_t pn, ptotal;
+ int i;
- if (!GetPageNumber(tif))
- fprintf(stderr, "%s: No page numbers, counting directories.\n",
- filename);
- for (i = 0; i < npages; i++) {
- if (findPage(tif, pages[i]))
- printTIF(tif, pages[i]);
- else
- fprintf(stderr, "%s: No page number %d\n", filename, pages[i]);
- }
- } else {
- uint16_t pageNumber = 0;
- do
- printTIF(tif, pageNumber++);
- while (TIFFReadDirectory(tif));
+ if (!GetPageNumber(tif))
+ fprintf(stderr, "%s: No page numbers, counting directories.\n",
+ filename);
+ for (i = 0; i < npages; i++)
+ {
+ if (findPage(tif, pages[i]))
+ printTIF(tif, pages[i]);
+ else
+ fprintf(stderr, "%s: No page number %d\n", filename, pages[i]);
+ }
+ }
+ else
+ {
+ uint16_t pageNumber = 0;
+ do
+ printTIF(tif, pageNumber++);
+ while (TIFFReadDirectory(tif));
}
}
#undef GetPageNumber
-static int
-pcompar(const void* va, const void* vb)
+static int pcompar(const void *va, const void *vb)
{
- const int* pa = (const int*) va;
- const int* pb = (const int*) vb;
+ const int *pa = (const int *)va;
+ const int *pb = (const int *)vb;
return (*pa - *pb);
}
-static void usage(int code);
+static void usage(int code);
-int
-main(int argc, char** argv)
+int main(int argc, char **argv)
{
#if !HAVE_DECL_OPTARG
extern int optind;
- extern char* optarg;
+ extern char *optarg;
#endif
uint16_t *pages = NULL, npages = 0, pageNumber;
- int c, dowarnings = 0; /* if 1, enable library warnings */
- TIFF* tif;
+ int c, dowarnings = 0; /* if 1, enable library warnings */
+ TIFF *tif;
while ((c = getopt(argc, argv, "l:p:x:y:W:H:wSh")) != -1)
- switch (c) {
- case 'H': /* page height */
- pageHeight = (float)atof(optarg);
- break;
- case 'S': /* scale to page */
- scaleToPage = 1;
- break;
- case 'W': /* page width */
- pageWidth = (float)atof(optarg);
- break;
- case 'p': /* print specific page */
- pageNumber = (uint16_t)atoi(optarg);
- if (pages)
- pages = (uint16_t*) realloc(pages, (npages + 1) * sizeof(uint16_t));
- else
- pages = (uint16_t*) malloc(sizeof(uint16_t));
- if( pages == NULL )
- {
- fprintf(stderr, "Out of memory\n");
- exit(EXIT_FAILURE);
- }
- pages[npages++] = pageNumber;
- break;
- case 'w':
- dowarnings = 1;
- break;
- case 'x':
- defxres = (float)atof(optarg);
- break;
- case 'y':
- defyres = (float)atof(optarg);
- break;
- case 'l':
- maxline = atoi(optarg);
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- break;
- case '?':
- usage(EXIT_FAILURE);
- }
+ switch (c)
+ {
+ case 'H': /* page height */
+ pageHeight = (float)atof(optarg);
+ break;
+ case 'S': /* scale to page */
+ scaleToPage = 1;
+ break;
+ case 'W': /* page width */
+ pageWidth = (float)atof(optarg);
+ break;
+ case 'p': /* print specific page */
+ pageNumber = (uint16_t)atoi(optarg);
+ if (pages)
+ pages = (uint16_t *)realloc(pages, (npages + 1) *
+ sizeof(uint16_t));
+ else
+ pages = (uint16_t *)malloc(sizeof(uint16_t));
+ if (pages == NULL)
+ {
+ fprintf(stderr, "Out of memory\n");
+ exit(EXIT_FAILURE);
+ }
+ pages[npages++] = pageNumber;
+ break;
+ case 'w':
+ dowarnings = 1;
+ break;
+ case 'x':
+ defxres = (float)atof(optarg);
+ break;
+ case 'y':
+ defyres = (float)atof(optarg);
+ break;
+ case 'l':
+ maxline = atoi(optarg);
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ }
if (npages > 0)
- qsort(pages, npages, sizeof(uint16_t), pcompar);
+ qsort(pages, npages, sizeof(uint16_t), pcompar);
if (!dowarnings)
- TIFFSetWarningHandler(0);
- if (optind < argc) {
- do {
- tif = TIFFOpen(argv[optind], "r");
- if (tif) {
- fax2ps(tif, npages, pages, argv[optind]);
- TIFFClose(tif);
- } else
- fprintf(stderr, "%s: Can not open, or not a TIFF file.\n",
- argv[optind]);
- } while (++optind < argc);
- } else {
- int n;
- FILE* fd;
- char buf[16*1024];
+ TIFFSetWarningHandler(0);
+ if (optind < argc)
+ {
+ do
+ {
+ tif = TIFFOpen(argv[optind], "r");
+ if (tif)
+ {
+ fax2ps(tif, npages, pages, argv[optind]);
+ TIFFClose(tif);
+ }
+ else
+ fprintf(stderr, "%s: Can not open, or not a TIFF file.\n",
+ argv[optind]);
+ } while (++optind < argc);
+ }
+ else
+ {
+ int n;
+ FILE *fd;
+ char buf[16 * 1024];
- fd = tmpfile();
- if (fd == NULL) {
- fprintf(stderr, "Could not obtain temporary file.\n");
- exit(EXIT_FAILURE);
- }
+ fd = tmpfile();
+ if (fd == NULL)
+ {
+ fprintf(stderr, "Could not obtain temporary file.\n");
+ exit(EXIT_FAILURE);
+ }
#if defined(HAVE_SETMODE) && defined(O_BINARY)
- setmode(fileno(stdin), O_BINARY);
+ setmode(fileno(stdin), O_BINARY);
#endif
- while ((n = read(fileno(stdin), buf, sizeof (buf))) > 0) {
- if (write(fileno(fd), buf, n) != n) {
- fclose(fd);
- fprintf(stderr,
- "Could not copy stdin to temporary file.\n");
- exit(EXIT_FAILURE);
- }
+ while ((n = read(fileno(stdin), buf, sizeof(buf))) > 0)
+ {
+ if (write(fileno(fd), buf, n) != n)
+ {
+ fclose(fd);
+ fprintf(stderr, "Could not copy stdin to temporary file.\n");
+ exit(EXIT_FAILURE);
+ }
}
- _TIFF_lseek_f(fileno(fd), 0, SEEK_SET);
+ _TIFF_lseek_f(fileno(fd), 0, SEEK_SET);
#if defined(_WIN32) && defined(USE_WIN32_FILEIO)
- tif = TIFFFdOpen(_get_osfhandle(fileno(fd)), "temp", "r");
+ tif = TIFFFdOpen(_get_osfhandle(fileno(fd)), "temp", "r");
#else
- tif = TIFFFdOpen(fileno(fd), "temp", "r");
+ tif = TIFFFdOpen(fileno(fd), "temp", "r");
#endif
- if (tif) {
- fax2ps(tif, npages, pages, "<stdin>");
- TIFFClose(tif);
- } else
- fprintf(stderr, "Can not open, or not a TIFF file.\n");
- fclose(fd);
+ if (tif)
+ {
+ fax2ps(tif, npages, pages, "<stdin>");
+ TIFFClose(tif);
+ }
+ else
+ fprintf(stderr, "Can not open, or not a TIFF file.\n");
+ fclose(fd);
}
printf("%%%%Trailer\n");
printf("%%%%Pages: %u\n", totalPages);
@@ -432,25 +459,23 @@ main(int argc, char** argv)
}
static const char usage_info[] =
-"Convert a TIFF facsimile to compressed PostScript\n\n"
-"usage: fax2ps [options] [input.tif ...]\n"
-"where options are:\n"
-" -w suppress warning messages\n"
-" -l chars set maximum output line length for generated PostScript\n"
-" -p page# select page to print (can use multiple times)\n"
-" -x xres set default horizontal resolution of input data (dpi)\n"
-" -y yres set default vertical resolution of input data (lpi)\n"
-" -S scale output to page size\n"
-" -W width set output page width (inches), default is 8.5\n"
-" -H height set output page height (inches), default is 11\n"
-;
+ "Convert a TIFF facsimile to compressed PostScript\n\n"
+ "usage: fax2ps [options] [input.tif ...]\n"
+ "where options are:\n"
+ " -w suppress warning messages\n"
+ " -l chars set maximum output line length for generated PostScript\n"
+ " -p page# select page to print (can use multiple times)\n"
+ " -x xres set default horizontal resolution of input data (dpi)\n"
+ " -y yres set default vertical resolution of input data (lpi)\n"
+ " -S scale output to page size\n"
+ " -W width set output page width (inches), default is 8.5\n"
+ " -H height set output page height (inches), default is 11\n";
-static void
-usage(int code)
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
diff --git a/tools/fax2tiff.c b/tools/fax2tiff.c
index 2aff478f..27c88c34 100644
--- a/tools/fax2tiff.c
+++ b/tools/fax2tiff.c
@@ -2,70 +2,71 @@
* Copyright (c) 1990-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-/*
+/*
* Convert a CCITT Group 3 or 4 FAX file to TIFF Group 3 or 4 format.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
#include <stdio.h>
-#include <stdlib.h> /* should have atof & getopt */
+#include <stdlib.h> /* should have atof & getopt */
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
-# include <fcntl.h>
+#include <fcntl.h>
#endif
#ifdef HAVE_IO_H
-# include <io.h>
+#include <io.h>
#endif
#include "tiffiop.h"
#ifndef EXIT_SUCCESS
-# define EXIT_SUCCESS 0
+#define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
-# define EXIT_FAILURE 1
+#define EXIT_FAILURE 1
#endif
-#define TIFFhowmany8(x) (((x)&0x07)?((uint32_t)(x)>>3)+1:(uint32_t)(x)>>3)
+#define TIFFhowmany8(x) \
+ (((x)&0x07) ? ((uint32_t)(x) >> 3) + 1 : (uint32_t)(x) >> 3)
-TIFF *faxTIFF;
-char *rowbuf;
-char *refbuf;
+TIFF *faxTIFF;
+char *rowbuf;
+char *refbuf;
-uint32_t xsize = 1728;
-int verbose;
-int stretch;
-uint16_t badfaxrun;
-uint32_t badfaxlines;
+uint32_t xsize = 1728;
+int verbose;
+int stretch;
+uint16_t badfaxrun;
+uint32_t badfaxlines;
-int copyFaxFile(TIFF* tifin, TIFF* tifout);
-static void usage(int code);
+int copyFaxFile(TIFF *tifin, TIFF *tifout);
+static void usage(int code);
/*
Struct to carry client data. Note that it does not appear that the client
@@ -73,405 +74,420 @@ static void usage(int code);
*/
typedef union _FAX_Client_Data
{
- thandle_t fh; /* Operating system file handle */
- int fd; /* Integer file descriptor */
+ thandle_t fh; /* Operating system file handle */
+ int fd; /* Integer file descriptor */
} FAX_Client_Data;
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- FILE *in;
- TIFF *out = NULL;
- FAX_Client_Data client_data;
- TIFFErrorHandler whandler = NULL;
- int compression_in = COMPRESSION_CCITTFAX3;
- int compression_out = COMPRESSION_CCITTFAX3;
- int fillorder_in = FILLORDER_LSB2MSB;
- int fillorder_out = FILLORDER_LSB2MSB;
- uint32_t group3options_in = 0; /* 1d-encoded */
- uint32_t group3options_out = 0; /* 1d-encoded */
- uint32_t group4options_in = 0; /* compressed */
- uint32_t group4options_out = 0; /* compressed */
- uint32_t defrowsperstrip = (uint32_t) 0;
- uint32_t rowsperstrip;
- int photometric_in = PHOTOMETRIC_MINISWHITE;
- int photometric_out = PHOTOMETRIC_MINISWHITE;
- int mode = FAXMODE_CLASSF;
- int rows;
- int c;
- int pn, npages;
- float resY = 196.0;
+ FILE *in;
+ TIFF *out = NULL;
+ FAX_Client_Data client_data;
+ TIFFErrorHandler whandler = NULL;
+ int compression_in = COMPRESSION_CCITTFAX3;
+ int compression_out = COMPRESSION_CCITTFAX3;
+ int fillorder_in = FILLORDER_LSB2MSB;
+ int fillorder_out = FILLORDER_LSB2MSB;
+ uint32_t group3options_in = 0; /* 1d-encoded */
+ uint32_t group3options_out = 0; /* 1d-encoded */
+ uint32_t group4options_in = 0; /* compressed */
+ uint32_t group4options_out = 0; /* compressed */
+ uint32_t defrowsperstrip = (uint32_t)0;
+ uint32_t rowsperstrip;
+ int photometric_in = PHOTOMETRIC_MINISWHITE;
+ int photometric_out = PHOTOMETRIC_MINISWHITE;
+ int mode = FAXMODE_CLASSF;
+ int rows;
+ int c;
+ int pn, npages;
+ float resY = 196.0;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char* optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- while ((c = getopt(argc, argv, "R:X:o:r:1234ABLMPUW5678abcflmprsuvwzh")) != -1)
- switch (c) {
- /* input-related options */
- case '3': /* input is g3-encoded */
- compression_in = COMPRESSION_CCITTFAX3;
- break;
- case '4': /* input is g4-encoded */
- compression_in = COMPRESSION_CCITTFAX4;
- break;
- case 'U': /* input is uncompressed (g3 and g4) */
- group3options_in |= GROUP3OPT_UNCOMPRESSED;
- group4options_in |= GROUP4OPT_UNCOMPRESSED;
- break;
- case '1': /* input is 1d-encoded (g3 only) */
- group3options_in &= ~GROUP3OPT_2DENCODING;
- break;
- case '2': /* input is 2d-encoded (g3 only) */
- group3options_in |= GROUP3OPT_2DENCODING;
- break;
- case 'P': /* input has not-aligned EOL (g3 only) */
- group3options_in &= ~GROUP3OPT_FILLBITS;
- break;
- case 'A': /* input has aligned EOL (g3 only) */
- group3options_in |= GROUP3OPT_FILLBITS;
- break;
- case 'W': /* input has 0 mean white */
- photometric_in = PHOTOMETRIC_MINISWHITE;
- break;
- case 'B': /* input has 0 mean black */
- photometric_in = PHOTOMETRIC_MINISBLACK;
- break;
- case 'L': /* input has lsb-to-msb fillorder */
- fillorder_in = FILLORDER_LSB2MSB;
- break;
- case 'M': /* input has msb-to-lsb fillorder */
- fillorder_in = FILLORDER_MSB2LSB;
- break;
- case 'R': /* input resolution */
- resY = (float) atof(optarg);
- break;
- case 'X': /* input width */
- xsize = (uint32_t) atoi(optarg);
- break;
-
- /* output-related options */
- case '7': /* generate g3-encoded output */
- compression_out = COMPRESSION_CCITTFAX3;
- break;
- case '8': /* generate g4-encoded output */
- compression_out = COMPRESSION_CCITTFAX4;
- break;
- case 'u': /* generate uncompressed output (g3 and g4) */
- group3options_out |= GROUP3OPT_UNCOMPRESSED;
- group4options_out |= GROUP4OPT_UNCOMPRESSED;
- break;
- case '5': /* generate 1d-encoded output (g3 only) */
- group3options_out &= ~GROUP3OPT_2DENCODING;
- break;
- case '6': /* generate 2d-encoded output (g3 only) */
- group3options_out |= GROUP3OPT_2DENCODING;
- break;
- case 'c': /* generate "classic" g3 format */
- mode = FAXMODE_CLASSIC;
- break;
- case 'f': /* generate Class F format */
- mode = FAXMODE_CLASSF;
- break;
- case 'm': /* output's fillorder is msb-to-lsb */
- fillorder_out = FILLORDER_MSB2LSB;
- break;
- case 'l': /* output's fillorder is lsb-to-msb */
- fillorder_out = FILLORDER_LSB2MSB;
- break;
- case 'o':
- out = TIFFOpen(optarg, "w");
- if (out == NULL) {
- fprintf(stderr,
- "%s: Can not create or open %s\n",
- argv[0], optarg);
- return EXIT_FAILURE;
- }
- break;
- case 'a': /* generate EOL-aligned output (g3 only) */
- group3options_out |= GROUP3OPT_FILLBITS;
- break;
- case 'p': /* generate not EOL-aligned output (g3 only) */
- group3options_out &= ~GROUP3OPT_FILLBITS;
- break;
- case 'r': /* rows/strip */
- defrowsperstrip = atol(optarg);
- break;
- case 's': /* stretch image by dup'ng scanlines */
- stretch = 1;
- break;
- case 'w': /* undocumented -- for testing */
- photometric_out = PHOTOMETRIC_MINISWHITE;
- break;
- case 'b': /* undocumented -- for testing */
- photometric_out = PHOTOMETRIC_MINISBLACK;
- break;
- case 'z': /* undocumented -- for testing */
- compression_out = COMPRESSION_LZW;
- break;
- case 'v': /* -v for info */
- verbose++;
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- break;
- case '?':
- usage(EXIT_FAILURE);
- /*NOTREACHED*/
- }
- npages = argc - optind;
- if (npages < 1)
- usage(EXIT_FAILURE);
-
- rowbuf = _TIFFmalloc(TIFFhowmany8(xsize));
- refbuf = _TIFFmalloc(TIFFhowmany8(xsize));
- if (rowbuf == NULL || refbuf == NULL) {
- fprintf(stderr, "%s: Not enough memory\n", argv[0]);
- return (EXIT_FAILURE);
- }
-
- if (out == NULL) {
- out = TIFFOpen("fax.tif", "w");
- if (out == NULL) {
- fprintf(stderr, "%s: Can not create fax.tif\n",
- argv[0]);
- return (EXIT_FAILURE);
- }
- }
-
- faxTIFF = TIFFClientOpen("(FakeInput)", "w",
- /* TIFFClientOpen() fails if we don't set existing value here */
- TIFFClientdata(out),
- TIFFGetReadProc(out), TIFFGetWriteProc(out),
- TIFFGetSeekProc(out), TIFFGetCloseProc(out),
- TIFFGetSizeProc(out), TIFFGetMapFileProc(out),
- TIFFGetUnmapFileProc(out));
- if (faxTIFF == NULL) {
- fprintf(stderr, "%s: Can not create fake input file\n",
- argv[0]);
- return (EXIT_FAILURE);
- }
- TIFFSetMode(faxTIFF, O_RDONLY);
- TIFFSetField(faxTIFF, TIFFTAG_IMAGEWIDTH, xsize);
- TIFFSetField(faxTIFF, TIFFTAG_SAMPLESPERPIXEL, 1);
- TIFFSetField(faxTIFF, TIFFTAG_BITSPERSAMPLE, 1);
- TIFFSetField(faxTIFF, TIFFTAG_FILLORDER, fillorder_in);
- TIFFSetField(faxTIFF, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
- TIFFSetField(faxTIFF, TIFFTAG_PHOTOMETRIC, photometric_in);
- TIFFSetField(faxTIFF, TIFFTAG_YRESOLUTION, resY);
- TIFFSetField(faxTIFF, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
-
- /* NB: this must be done after directory info is setup */
- TIFFSetField(faxTIFF, TIFFTAG_COMPRESSION, compression_in);
- if (compression_in == COMPRESSION_CCITTFAX3)
- TIFFSetField(faxTIFF, TIFFTAG_GROUP3OPTIONS, group3options_in);
- else if (compression_in == COMPRESSION_CCITTFAX4)
- TIFFSetField(faxTIFF, TIFFTAG_GROUP4OPTIONS, group4options_in);
- for (pn = 0; optind < argc; pn++, optind++) {
- in = fopen(argv[optind], "rb");
- if (in == NULL) {
- fprintf(stderr,
- "%s: %s: Can not open\n", argv[0], argv[optind]);
- continue;
- }
+ while ((c = getopt(argc, argv, "R:X:o:r:1234ABLMPUW5678abcflmprsuvwzh")) !=
+ -1)
+ switch (c)
+ {
+ /* input-related options */
+ case '3': /* input is g3-encoded */
+ compression_in = COMPRESSION_CCITTFAX3;
+ break;
+ case '4': /* input is g4-encoded */
+ compression_in = COMPRESSION_CCITTFAX4;
+ break;
+ case 'U': /* input is uncompressed (g3 and g4) */
+ group3options_in |= GROUP3OPT_UNCOMPRESSED;
+ group4options_in |= GROUP4OPT_UNCOMPRESSED;
+ break;
+ case '1': /* input is 1d-encoded (g3 only) */
+ group3options_in &= ~GROUP3OPT_2DENCODING;
+ break;
+ case '2': /* input is 2d-encoded (g3 only) */
+ group3options_in |= GROUP3OPT_2DENCODING;
+ break;
+ case 'P': /* input has not-aligned EOL (g3 only) */
+ group3options_in &= ~GROUP3OPT_FILLBITS;
+ break;
+ case 'A': /* input has aligned EOL (g3 only) */
+ group3options_in |= GROUP3OPT_FILLBITS;
+ break;
+ case 'W': /* input has 0 mean white */
+ photometric_in = PHOTOMETRIC_MINISWHITE;
+ break;
+ case 'B': /* input has 0 mean black */
+ photometric_in = PHOTOMETRIC_MINISBLACK;
+ break;
+ case 'L': /* input has lsb-to-msb fillorder */
+ fillorder_in = FILLORDER_LSB2MSB;
+ break;
+ case 'M': /* input has msb-to-lsb fillorder */
+ fillorder_in = FILLORDER_MSB2LSB;
+ break;
+ case 'R': /* input resolution */
+ resY = (float)atof(optarg);
+ break;
+ case 'X': /* input width */
+ xsize = (uint32_t)atoi(optarg);
+ break;
+
+ /* output-related options */
+ case '7': /* generate g3-encoded output */
+ compression_out = COMPRESSION_CCITTFAX3;
+ break;
+ case '8': /* generate g4-encoded output */
+ compression_out = COMPRESSION_CCITTFAX4;
+ break;
+ case 'u': /* generate uncompressed output (g3 and g4) */
+ group3options_out |= GROUP3OPT_UNCOMPRESSED;
+ group4options_out |= GROUP4OPT_UNCOMPRESSED;
+ break;
+ case '5': /* generate 1d-encoded output (g3 only) */
+ group3options_out &= ~GROUP3OPT_2DENCODING;
+ break;
+ case '6': /* generate 2d-encoded output (g3 only) */
+ group3options_out |= GROUP3OPT_2DENCODING;
+ break;
+ case 'c': /* generate "classic" g3 format */
+ mode = FAXMODE_CLASSIC;
+ break;
+ case 'f': /* generate Class F format */
+ mode = FAXMODE_CLASSF;
+ break;
+ case 'm': /* output's fillorder is msb-to-lsb */
+ fillorder_out = FILLORDER_MSB2LSB;
+ break;
+ case 'l': /* output's fillorder is lsb-to-msb */
+ fillorder_out = FILLORDER_LSB2MSB;
+ break;
+ case 'o':
+ out = TIFFOpen(optarg, "w");
+ if (out == NULL)
+ {
+ fprintf(stderr, "%s: Can not create or open %s\n", argv[0],
+ optarg);
+ return EXIT_FAILURE;
+ }
+ break;
+ case 'a': /* generate EOL-aligned output (g3 only) */
+ group3options_out |= GROUP3OPT_FILLBITS;
+ break;
+ case 'p': /* generate not EOL-aligned output (g3 only) */
+ group3options_out &= ~GROUP3OPT_FILLBITS;
+ break;
+ case 'r': /* rows/strip */
+ defrowsperstrip = atol(optarg);
+ break;
+ case 's': /* stretch image by dup'ng scanlines */
+ stretch = 1;
+ break;
+ case 'w': /* undocumented -- for testing */
+ photometric_out = PHOTOMETRIC_MINISWHITE;
+ break;
+ case 'b': /* undocumented -- for testing */
+ photometric_out = PHOTOMETRIC_MINISBLACK;
+ break;
+ case 'z': /* undocumented -- for testing */
+ compression_out = COMPRESSION_LZW;
+ break;
+ case 'v': /* -v for info */
+ verbose++;
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ /*NOTREACHED*/
+ }
+ npages = argc - optind;
+ if (npages < 1)
+ usage(EXIT_FAILURE);
+
+ rowbuf = _TIFFmalloc(TIFFhowmany8(xsize));
+ refbuf = _TIFFmalloc(TIFFhowmany8(xsize));
+ if (rowbuf == NULL || refbuf == NULL)
+ {
+ fprintf(stderr, "%s: Not enough memory\n", argv[0]);
+ return (EXIT_FAILURE);
+ }
+
+ if (out == NULL)
+ {
+ out = TIFFOpen("fax.tif", "w");
+ if (out == NULL)
+ {
+ fprintf(stderr, "%s: Can not create fax.tif\n", argv[0]);
+ return (EXIT_FAILURE);
+ }
+ }
+
+ faxTIFF = TIFFClientOpen(
+ "(FakeInput)", "w",
+ /* TIFFClientOpen() fails if we don't set existing value here */
+ TIFFClientdata(out), TIFFGetReadProc(out), TIFFGetWriteProc(out),
+ TIFFGetSeekProc(out), TIFFGetCloseProc(out), TIFFGetSizeProc(out),
+ TIFFGetMapFileProc(out), TIFFGetUnmapFileProc(out));
+ if (faxTIFF == NULL)
+ {
+ fprintf(stderr, "%s: Can not create fake input file\n", argv[0]);
+ return (EXIT_FAILURE);
+ }
+ TIFFSetMode(faxTIFF, O_RDONLY);
+ TIFFSetField(faxTIFF, TIFFTAG_IMAGEWIDTH, xsize);
+ TIFFSetField(faxTIFF, TIFFTAG_SAMPLESPERPIXEL, 1);
+ TIFFSetField(faxTIFF, TIFFTAG_BITSPERSAMPLE, 1);
+ TIFFSetField(faxTIFF, TIFFTAG_FILLORDER, fillorder_in);
+ TIFFSetField(faxTIFF, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+ TIFFSetField(faxTIFF, TIFFTAG_PHOTOMETRIC, photometric_in);
+ TIFFSetField(faxTIFF, TIFFTAG_YRESOLUTION, resY);
+ TIFFSetField(faxTIFF, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
+
+ /* NB: this must be done after directory info is setup */
+ TIFFSetField(faxTIFF, TIFFTAG_COMPRESSION, compression_in);
+ if (compression_in == COMPRESSION_CCITTFAX3)
+ TIFFSetField(faxTIFF, TIFFTAG_GROUP3OPTIONS, group3options_in);
+ else if (compression_in == COMPRESSION_CCITTFAX4)
+ TIFFSetField(faxTIFF, TIFFTAG_GROUP4OPTIONS, group4options_in);
+ for (pn = 0; optind < argc; pn++, optind++)
+ {
+ in = fopen(argv[optind], "rb");
+ if (in == NULL)
+ {
+ fprintf(stderr, "%s: %s: Can not open\n", argv[0], argv[optind]);
+ continue;
+ }
#if defined(_WIN32) && defined(USE_WIN32_FILEIO)
- client_data.fh = (thandle_t)_get_osfhandle(fileno(in));
+ client_data.fh = (thandle_t)_get_osfhandle(fileno(in));
#else
- client_data.fd = fileno(in);
+ client_data.fd = fileno(in);
#endif
- TIFFSetClientdata(faxTIFF, client_data.fh);
- TIFFSetFileName(faxTIFF, (const char*)argv[optind]);
- TIFFSetField(out, TIFFTAG_IMAGEWIDTH, xsize);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 1);
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression_out);
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric_out);
- TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 1);
- switch (compression_out) {
- /* g3 */
- case COMPRESSION_CCITTFAX3:
- TIFFSetField(out, TIFFTAG_GROUP3OPTIONS,
- group3options_out);
- TIFFSetField(out, TIFFTAG_FAXMODE, mode);
- rowsperstrip =
- (defrowsperstrip)?defrowsperstrip:(uint32_t)-1L;
- break;
-
- /* g4 */
- case COMPRESSION_CCITTFAX4:
- TIFFSetField(out, TIFFTAG_GROUP4OPTIONS,
- group4options_out);
- TIFFSetField(out, TIFFTAG_FAXMODE, mode);
- rowsperstrip =
- (defrowsperstrip)?defrowsperstrip:(uint32_t)-1L;
- break;
-
- default:
- rowsperstrip = (defrowsperstrip) ?
- defrowsperstrip : TIFFDefaultStripSize(out, 0);
- }
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
- TIFFSetField(out, TIFFTAG_FILLORDER, fillorder_out);
- TIFFSetField(out, TIFFTAG_SOFTWARE, "fax2tiff");
- TIFFSetField(out, TIFFTAG_XRESOLUTION, 204.0);
- if (!stretch) {
- TIFFGetField(faxTIFF, TIFFTAG_YRESOLUTION, &resY);
- TIFFSetField(out, TIFFTAG_YRESOLUTION, resY);
- } else
- TIFFSetField(out, TIFFTAG_YRESOLUTION, 196.);
- TIFFSetField(out, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
- TIFFSetField(out, TIFFTAG_PAGENUMBER, pn, npages);
-
- if (!verbose)
- whandler = TIFFSetWarningHandler(NULL);
- rows = copyFaxFile(faxTIFF, out);
- fclose(in);
- if (!verbose)
- (void) TIFFSetWarningHandler(whandler);
-
- TIFFSetField(out, TIFFTAG_IMAGELENGTH, rows);
-
- if (verbose) {
- fprintf(stderr, "%s:\n", argv[optind]);
- fprintf(stderr, "%d rows in input\n", rows);
- fprintf(stderr, "%"PRIu32" total bad rows\n",
- badfaxlines);
- fprintf(stderr, "%"PRIu16" max consecutive bad rows\n", badfaxrun);
- }
- if (compression_out == COMPRESSION_CCITTFAX3 &&
- mode == FAXMODE_CLASSF) {
- TIFFSetField(out, TIFFTAG_BADFAXLINES, badfaxlines);
- TIFFSetField(out, TIFFTAG_CLEANFAXDATA, badfaxlines ?
- CLEANFAXDATA_REGENERATED : CLEANFAXDATA_CLEAN);
- TIFFSetField(out, TIFFTAG_CONSECUTIVEBADFAXLINES, badfaxrun);
- }
- TIFFWriteDirectory(out);
- }
- TIFFClose(out);
- _TIFFfree(rowbuf);
- _TIFFfree(refbuf);
- return (EXIT_SUCCESS);
+ TIFFSetClientdata(faxTIFF, client_data.fh);
+ TIFFSetFileName(faxTIFF, (const char *)argv[optind]);
+ TIFFSetField(out, TIFFTAG_IMAGEWIDTH, xsize);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 1);
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression_out);
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric_out);
+ TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 1);
+ switch (compression_out)
+ {
+ /* g3 */
+ case COMPRESSION_CCITTFAX3:
+ TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, group3options_out);
+ TIFFSetField(out, TIFFTAG_FAXMODE, mode);
+ rowsperstrip =
+ (defrowsperstrip) ? defrowsperstrip : (uint32_t)-1L;
+ break;
+
+ /* g4 */
+ case COMPRESSION_CCITTFAX4:
+ TIFFSetField(out, TIFFTAG_GROUP4OPTIONS, group4options_out);
+ TIFFSetField(out, TIFFTAG_FAXMODE, mode);
+ rowsperstrip =
+ (defrowsperstrip) ? defrowsperstrip : (uint32_t)-1L;
+ break;
+
+ default:
+ rowsperstrip = (defrowsperstrip) ? defrowsperstrip
+ : TIFFDefaultStripSize(out, 0);
+ }
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+ TIFFSetField(out, TIFFTAG_FILLORDER, fillorder_out);
+ TIFFSetField(out, TIFFTAG_SOFTWARE, "fax2tiff");
+ TIFFSetField(out, TIFFTAG_XRESOLUTION, 204.0);
+ if (!stretch)
+ {
+ TIFFGetField(faxTIFF, TIFFTAG_YRESOLUTION, &resY);
+ TIFFSetField(out, TIFFTAG_YRESOLUTION, resY);
+ }
+ else
+ TIFFSetField(out, TIFFTAG_YRESOLUTION, 196.);
+ TIFFSetField(out, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
+ TIFFSetField(out, TIFFTAG_PAGENUMBER, pn, npages);
+
+ if (!verbose)
+ whandler = TIFFSetWarningHandler(NULL);
+ rows = copyFaxFile(faxTIFF, out);
+ fclose(in);
+ if (!verbose)
+ (void)TIFFSetWarningHandler(whandler);
+
+ TIFFSetField(out, TIFFTAG_IMAGELENGTH, rows);
+
+ if (verbose)
+ {
+ fprintf(stderr, "%s:\n", argv[optind]);
+ fprintf(stderr, "%d rows in input\n", rows);
+ fprintf(stderr, "%" PRIu32 " total bad rows\n", badfaxlines);
+ fprintf(stderr, "%" PRIu16 " max consecutive bad rows\n",
+ badfaxrun);
+ }
+ if (compression_out == COMPRESSION_CCITTFAX3 && mode == FAXMODE_CLASSF)
+ {
+ TIFFSetField(out, TIFFTAG_BADFAXLINES, badfaxlines);
+ TIFFSetField(out, TIFFTAG_CLEANFAXDATA,
+ badfaxlines ? CLEANFAXDATA_REGENERATED
+ : CLEANFAXDATA_CLEAN);
+ TIFFSetField(out, TIFFTAG_CONSECUTIVEBADFAXLINES, badfaxrun);
+ }
+ TIFFWriteDirectory(out);
+ }
+ TIFFClose(out);
+ _TIFFfree(rowbuf);
+ _TIFFfree(refbuf);
+ return (EXIT_SUCCESS);
}
-int
-copyFaxFile(TIFF* tifin, TIFF* tifout)
+int copyFaxFile(TIFF *tifin, TIFF *tifout)
{
- uint32_t row;
- uint32_t linesize = TIFFhowmany8(xsize);
- uint16_t badrun;
- int ok;
-
- tifin->tif_rawdatasize = (tmsize_t)TIFFGetFileSize(tifin);
- if (tifin->tif_rawdatasize == 0) {
- TIFFError(tifin->tif_name, "Empty input file");
- return (0);
- }
- tifin->tif_rawdata = _TIFFmalloc(tifin->tif_rawdatasize);
- if (tifin->tif_rawdata == NULL) {
- TIFFError(tifin->tif_name, "Not enough memory");
- return (0);
- }
- if (!ReadOK(tifin, tifin->tif_rawdata, tifin->tif_rawdatasize)) {
- TIFFError(tifin->tif_name, "Read error at scanline 0");
- return (0);
- }
- tifin->tif_rawcp = tifin->tif_rawdata;
- tifin->tif_rawcc = tifin->tif_rawdatasize;
-
- (*tifin->tif_setupdecode)(tifin);
- (*tifin->tif_predecode)(tifin, (tsample_t) 0);
- tifin->tif_row = 0;
- badfaxlines = 0;
- badfaxrun = 0;
-
- _TIFFmemset(refbuf, 0, linesize);
- row = 0;
- badrun = 0; /* current run of bad lines */
- while (tifin->tif_rawcc > 0) {
- ok = (*tifin->tif_decoderow)(tifin, (tdata_t) rowbuf,
- linesize, 0);
- if (!ok) {
- badfaxlines++;
- badrun++;
- /* regenerate line from previous good line */
- _TIFFmemcpy(rowbuf, refbuf, linesize);
- } else {
- if (badrun > badfaxrun)
- badfaxrun = badrun;
- badrun = 0;
- _TIFFmemcpy(refbuf, rowbuf, linesize);
- }
- tifin->tif_row++;
-
- if (TIFFWriteScanline(tifout, rowbuf, row, 0) < 0) {
- fprintf(stderr, "%s: Write error at row %"PRIu32".\n",
- tifout->tif_name, row);
- break;
- }
- row++;
- if (stretch) {
- if (TIFFWriteScanline(tifout, rowbuf, row, 0) < 0) {
- fprintf(stderr, "%s: Write error at row %"PRIu32".\n",
- tifout->tif_name, row);
- break;
- }
- row++;
- }
- }
- if (badrun > badfaxrun)
- badfaxrun = badrun;
- _TIFFfree(tifin->tif_rawdata);
- return (row);
+ uint32_t row;
+ uint32_t linesize = TIFFhowmany8(xsize);
+ uint16_t badrun;
+ int ok;
+
+ tifin->tif_rawdatasize = (tmsize_t)TIFFGetFileSize(tifin);
+ if (tifin->tif_rawdatasize == 0)
+ {
+ TIFFError(tifin->tif_name, "Empty input file");
+ return (0);
+ }
+ tifin->tif_rawdata = _TIFFmalloc(tifin->tif_rawdatasize);
+ if (tifin->tif_rawdata == NULL)
+ {
+ TIFFError(tifin->tif_name, "Not enough memory");
+ return (0);
+ }
+ if (!ReadOK(tifin, tifin->tif_rawdata, tifin->tif_rawdatasize))
+ {
+ TIFFError(tifin->tif_name, "Read error at scanline 0");
+ return (0);
+ }
+ tifin->tif_rawcp = tifin->tif_rawdata;
+ tifin->tif_rawcc = tifin->tif_rawdatasize;
+
+ (*tifin->tif_setupdecode)(tifin);
+ (*tifin->tif_predecode)(tifin, (tsample_t)0);
+ tifin->tif_row = 0;
+ badfaxlines = 0;
+ badfaxrun = 0;
+
+ _TIFFmemset(refbuf, 0, linesize);
+ row = 0;
+ badrun = 0; /* current run of bad lines */
+ while (tifin->tif_rawcc > 0)
+ {
+ ok = (*tifin->tif_decoderow)(tifin, (tdata_t)rowbuf, linesize, 0);
+ if (!ok)
+ {
+ badfaxlines++;
+ badrun++;
+ /* regenerate line from previous good line */
+ _TIFFmemcpy(rowbuf, refbuf, linesize);
+ }
+ else
+ {
+ if (badrun > badfaxrun)
+ badfaxrun = badrun;
+ badrun = 0;
+ _TIFFmemcpy(refbuf, rowbuf, linesize);
+ }
+ tifin->tif_row++;
+
+ if (TIFFWriteScanline(tifout, rowbuf, row, 0) < 0)
+ {
+ fprintf(stderr, "%s: Write error at row %" PRIu32 ".\n",
+ tifout->tif_name, row);
+ break;
+ }
+ row++;
+ if (stretch)
+ {
+ if (TIFFWriteScanline(tifout, rowbuf, row, 0) < 0)
+ {
+ fprintf(stderr, "%s: Write error at row %" PRIu32 ".\n",
+ tifout->tif_name, row);
+ break;
+ }
+ row++;
+ }
+ }
+ if (badrun > badfaxrun)
+ badfaxrun = badrun;
+ _TIFFfree(tifin->tif_rawdata);
+ return (row);
}
static const char usage_info[] =
-"Create a TIFF Class F fax file from raw fax data\n\n"
-"usage: fax2tiff [options] input.raw...\n"
-"where options are:\n"
-" -3 input data is G3-encoded [default]\n"
-" -4 input data is G4-encoded\n"
-" -U input data is uncompressed (G3 or G4)\n"
-" -1 input data is 1D-encoded (G3 only) [default]\n"
-" -2 input data is 2D-encoded (G3 only)\n"
-" -P input is not EOL-aligned (G3 only) [default]\n"
-" -A input is EOL-aligned (G3 only)\n"
-" -M input data has MSB2LSB bit order\n"
-" -L input data has LSB2MSB bit order [default]\n"
-" -B input data has min 0 means black\n"
-" -W input data has min 0 means white [default]\n"
-" -R # input data has # resolution (lines/inch) [default is 196]\n"
-" -X # input data has # width [default is 1728]\n"
-"\n"
-" -o out.tif write output to out.tif\n"
+ "Create a TIFF Class F fax file from raw fax data\n\n"
+ "usage: fax2tiff [options] input.raw...\n"
+ "where options are:\n"
+ " -3 input data is G3-encoded [default]\n"
+ " -4 input data is G4-encoded\n"
+ " -U input data is uncompressed (G3 or G4)\n"
+ " -1 input data is 1D-encoded (G3 only) [default]\n"
+ " -2 input data is 2D-encoded (G3 only)\n"
+ " -P input is not EOL-aligned (G3 only) [default]\n"
+ " -A input is EOL-aligned (G3 only)\n"
+ " -M input data has MSB2LSB bit order\n"
+ " -L input data has LSB2MSB bit order [default]\n"
+ " -B input data has min 0 means black\n"
+ " -W input data has min 0 means white [default]\n"
+ " -R # input data has # resolution (lines/inch) [default is "
+ "196]\n"
+ " -X # input data has # width [default is "
+ "1728]\n"
+ "\n"
+ " -o out.tif write output to out.tif\n"
#ifdef CCITT_SUPPORT
-" -7 generate G3-encoded output [default]\n"
-" -8 generate G4-encoded output\n"
-" -u generate uncompressed output (G3 or G4)\n"
-" -5 generate 1D-encoded output (G3 only)\n"
-" -6 generate 2D-encoded output (G3 only) [default]\n"
-" -p generate not EOL-aligned output (G3 only)\n"
-" -a generate EOL-aligned output (G3 only) [default]\n"
+ " -7 generate G3-encoded output [default]\n"
+ " -8 generate G4-encoded output\n"
+ " -u generate uncompressed output (G3 or G4)\n"
+ " -5 generate 1D-encoded output (G3 only)\n"
+ " -6 generate 2D-encoded output (G3 only) [default]\n"
+ " -p generate not EOL-aligned output (G3 only)\n"
+ " -a generate EOL-aligned output (G3 only) [default]\n"
#endif
-" -c generate \"classic\" TIFF format\n"
-" -f generate TIFF Class F (TIFF/F) format [default]\n"
-" -m output fill order is MSB2LSB\n"
-" -l output fill order is LSB2MSB [default]\n"
-" -r # make each strip have no more than # rows\n"
-" -s stretch image by duplicating scanlines\n"
-" -v print information about conversion work\n"
+ " -c generate \"classic\" TIFF format\n"
+ " -f generate TIFF Class F (TIFF/F) format [default]\n"
+ " -m output fill order is MSB2LSB\n"
+ " -l output fill order is LSB2MSB [default]\n"
+ " -r # make each strip have no more than # rows\n"
+ " -s stretch image by duplicating scanlines\n"
+ " -v print information about conversion work\n"
#ifdef LZW_SUPPORT
-" -z generate LZW compressed output\n"
+ " -z generate LZW compressed output\n"
#endif
-;
+ ;
-static void
-usage(int code)
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
diff --git a/tools/pal2rgb.c b/tools/pal2rgb.c
index 735a4679..6b111a03 100644
--- a/tools/pal2rgb.c
+++ b/tools/pal2rgb.c
@@ -2,36 +2,36 @@
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
+#include <ctype.h>
#include <stdio.h>
-#include <string.h>
#include <stdlib.h>
-#include <ctype.h>
+#include <string.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#include "tiffio.h"
@@ -43,315 +43,353 @@
#define EXIT_FAILURE 1
#endif
-#define streq(a,b) (strcmp(a,b) == 0)
-#define strneq(a,b,n) (strncmp(a,b,n) == 0)
+#define streq(a, b) (strcmp(a, b) == 0)
+#define strneq(a, b, n) (strncmp(a, b, n) == 0)
-static void usage(int code);
-static void cpTags(TIFF* in, TIFF* out);
+static void usage(int code);
+static void cpTags(TIFF *in, TIFF *out);
-static int
-checkcmap(int n, uint16_t* r, uint16_t* g, uint16_t* b)
+static int checkcmap(int n, uint16_t *r, uint16_t *g, uint16_t *b)
{
- while (n-- > 0)
- if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
- return (16);
- fprintf(stderr, "Warning, assuming 8-bit colormap.\n");
- return (8);
+ while (n-- > 0)
+ if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
+ return (16);
+ fprintf(stderr, "Warning, assuming 8-bit colormap.\n");
+ return (8);
}
-#define CopyField(tag, v) \
- if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
-#define CopyField3(tag, v1, v2, v3) \
- if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
+#define CopyField(tag, v) \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v)
+#define CopyField3(tag, v1, v2, v3) \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) \
+ TIFFSetField(out, tag, v1, v2, v3)
-static uint16_t compression = (uint16_t) -1;
-static uint16_t predictor = 0;
-static int quality = 75; /* JPEG quality */
-static int jpegcolormode = JPEGCOLORMODE_RGB;
-static int processCompressOptions(char*);
+static uint16_t compression = (uint16_t)-1;
+static uint16_t predictor = 0;
+static int quality = 75; /* JPEG quality */
+static int jpegcolormode = JPEGCOLORMODE_RGB;
+static int processCompressOptions(char *);
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- uint16_t bitspersample, shortv;
- uint32_t imagewidth, imagelength;
- uint16_t config = PLANARCONFIG_CONTIG;
- uint32_t rowsperstrip = (uint32_t) -1;
- uint16_t photometric = PHOTOMETRIC_RGB;
- uint16_t *rmap, *gmap, *bmap;
- uint32_t row;
- int cmap = -1;
- TIFF *in, *out;
- int c;
+ uint16_t bitspersample, shortv;
+ uint32_t imagewidth, imagelength;
+ uint16_t config = PLANARCONFIG_CONTIG;
+ uint32_t rowsperstrip = (uint32_t)-1;
+ uint16_t photometric = PHOTOMETRIC_RGB;
+ uint16_t *rmap, *gmap, *bmap;
+ uint32_t row;
+ int cmap = -1;
+ TIFF *in, *out;
+ int c;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char* optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- while ((c = getopt(argc, argv, "C:c:p:r:h")) != -1)
- switch (c) {
- case 'C': /* force colormap interpretation */
- cmap = atoi(optarg);
- break;
- case 'c': /* compression scheme */
- if (!processCompressOptions(optarg))
- usage(EXIT_FAILURE);
- break;
- case 'p': /* planar configuration */
- if (streq(optarg, "separate"))
- config = PLANARCONFIG_SEPARATE;
- else if (streq(optarg, "contig"))
- config = PLANARCONFIG_CONTIG;
- else
- usage(EXIT_FAILURE);
- break;
- case 'r': /* rows/strip */
- rowsperstrip = atoi(optarg);
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- break;
- case '?':
- usage(EXIT_FAILURE);
- /*NOTREACHED*/
- }
- if (argc - optind != 2)
- usage(EXIT_FAILURE);
- in = TIFFOpen(argv[optind], "r");
- if (in == NULL)
- return (EXIT_FAILURE);
- if (!TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &shortv) ||
- shortv != PHOTOMETRIC_PALETTE) {
- fprintf(stderr, "%s: Expecting a palette image.\n",
- argv[optind]);
- (void) TIFFClose(in);
- return (EXIT_FAILURE);
- }
- if (!TIFFGetField(in, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
- fprintf(stderr,
- "%s: No colormap (not a valid palette image).\n",
- argv[optind]);
- (void) TIFFClose(in);
- return (EXIT_FAILURE);
- }
- bitspersample = 0;
- TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
- if (bitspersample != 8) {
- fprintf(stderr, "%s: Sorry, can only handle 8-bit images.\n",
- argv[optind]);
- (void) TIFFClose(in);
- return (EXIT_FAILURE);
- }
- out = TIFFOpen(argv[optind+1], "w");
- if (out == NULL) {
- (void) TIFFClose(in);
- return (EXIT_FAILURE);
- }
- cpTags(in, out);
- TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &imagewidth);
- TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength);
- if (compression != (uint16_t)-1)
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- else
- TIFFGetField(in, TIFFTAG_COMPRESSION, &compression);
- switch (compression) {
- case COMPRESSION_JPEG:
- if (jpegcolormode == JPEGCOLORMODE_RGB)
- photometric = PHOTOMETRIC_YCBCR;
- else
- photometric = PHOTOMETRIC_RGB;
- TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
- TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
- break;
- case COMPRESSION_LZW:
- case COMPRESSION_ADOBE_DEFLATE:
- case COMPRESSION_DEFLATE:
- if (predictor != 0)
- TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
- break;
- }
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
- rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip));
- (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv);
- if (cmap == -1)
- cmap = checkcmap(1<<bitspersample, rmap, gmap, bmap);
- if (cmap == 16) {
- /*
- * Convert 16-bit colormap to 8-bit.
- */
- int i;
+ while ((c = getopt(argc, argv, "C:c:p:r:h")) != -1)
+ switch (c)
+ {
+ case 'C': /* force colormap interpretation */
+ cmap = atoi(optarg);
+ break;
+ case 'c': /* compression scheme */
+ if (!processCompressOptions(optarg))
+ usage(EXIT_FAILURE);
+ break;
+ case 'p': /* planar configuration */
+ if (streq(optarg, "separate"))
+ config = PLANARCONFIG_SEPARATE;
+ else if (streq(optarg, "contig"))
+ config = PLANARCONFIG_CONTIG;
+ else
+ usage(EXIT_FAILURE);
+ break;
+ case 'r': /* rows/strip */
+ rowsperstrip = atoi(optarg);
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ /*NOTREACHED*/
+ }
+ if (argc - optind != 2)
+ usage(EXIT_FAILURE);
+ in = TIFFOpen(argv[optind], "r");
+ if (in == NULL)
+ return (EXIT_FAILURE);
+ if (!TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &shortv) ||
+ shortv != PHOTOMETRIC_PALETTE)
+ {
+ fprintf(stderr, "%s: Expecting a palette image.\n", argv[optind]);
+ (void)TIFFClose(in);
+ return (EXIT_FAILURE);
+ }
+ if (!TIFFGetField(in, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap))
+ {
+ fprintf(stderr, "%s: No colormap (not a valid palette image).\n",
+ argv[optind]);
+ (void)TIFFClose(in);
+ return (EXIT_FAILURE);
+ }
+ bitspersample = 0;
+ TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
+ if (bitspersample != 8)
+ {
+ fprintf(stderr, "%s: Sorry, can only handle 8-bit images.\n",
+ argv[optind]);
+ (void)TIFFClose(in);
+ return (EXIT_FAILURE);
+ }
+ out = TIFFOpen(argv[optind + 1], "w");
+ if (out == NULL)
+ {
+ (void)TIFFClose(in);
+ return (EXIT_FAILURE);
+ }
+ cpTags(in, out);
+ TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &imagewidth);
+ TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength);
+ if (compression != (uint16_t)-1)
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
+ else
+ TIFFGetField(in, TIFFTAG_COMPRESSION, &compression);
+ switch (compression)
+ {
+ case COMPRESSION_JPEG:
+ if (jpegcolormode == JPEGCOLORMODE_RGB)
+ photometric = PHOTOMETRIC_YCBCR;
+ else
+ photometric = PHOTOMETRIC_RGB;
+ TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
+ TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
+ break;
+ case COMPRESSION_LZW:
+ case COMPRESSION_ADOBE_DEFLATE:
+ case COMPRESSION_DEFLATE:
+ if (predictor != 0)
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
+ break;
+ }
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
+ rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip));
+ (void)TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv);
+ if (cmap == -1)
+ cmap = checkcmap(1 << bitspersample, rmap, gmap, bmap);
+ if (cmap == 16)
+ {
+ /*
+ * Convert 16-bit colormap to 8-bit.
+ */
+ int i;
- for (i = (1<<bitspersample)-1; i >= 0; i--) {
-#define CVT(x) (((x) * 255) / ((1L<<16)-1))
- rmap[i] = CVT(rmap[i]);
- gmap[i] = CVT(gmap[i]);
- bmap[i] = CVT(bmap[i]);
- }
- }
- { unsigned char *ibuf, *obuf;
- register unsigned char* pp;
- register uint32_t x;
- tmsize_t tss_in = TIFFScanlineSize(in);
- tmsize_t tss_out = TIFFScanlineSize(out);
- if (tss_out / tss_in < 3) {
- /*
- * BUG 2750: The following code does not know about chroma
- * subsampling of JPEG data. It assumes that the output buffer is 3x
- * the length of the input buffer due to exploding the palette into
- * RGB tuples. If this assumption is incorrect, it could lead to a
- * buffer overflow. Go ahead and fail now to prevent that.
- */
- fprintf(stderr, "Could not determine correct image size for output. Exiting.\n");
- return EXIT_FAILURE;
- }
- ibuf = (unsigned char*)_TIFFmalloc(tss_in);
- obuf = (unsigned char*)_TIFFmalloc(tss_out);
- switch (config) {
- case PLANARCONFIG_CONTIG:
- for (row = 0; row < imagelength; row++) {
- if (!TIFFReadScanline(in, ibuf, row, 0))
- goto done;
- pp = obuf;
- for (x = 0; x < imagewidth; x++) {
- *pp++ = (unsigned char) rmap[ibuf[x]];
- *pp++ = (unsigned char) gmap[ibuf[x]];
- *pp++ = (unsigned char) bmap[ibuf[x]];
- }
- if (!TIFFWriteScanline(out, obuf, row, 0))
- goto done;
- }
- break;
- case PLANARCONFIG_SEPARATE:
- for (row = 0; row < imagelength; row++) {
- if (!TIFFReadScanline(in, ibuf, row, 0))
- goto done;
- for (pp = obuf, x = 0; x < imagewidth; x++)
- *pp++ = (unsigned char) rmap[ibuf[x]];
- if (!TIFFWriteScanline(out, obuf, row, 0))
- goto done;
- for (pp = obuf, x = 0; x < imagewidth; x++)
- *pp++ = (unsigned char) gmap[ibuf[x]];
- if (!TIFFWriteScanline(out, obuf, row, 0))
- goto done;
- for (pp = obuf, x = 0; x < imagewidth; x++)
- *pp++ = (unsigned char) bmap[ibuf[x]];
- if (!TIFFWriteScanline(out, obuf, row, 0))
- goto done;
- }
- break;
- }
- _TIFFfree(ibuf);
- _TIFFfree(obuf);
- }
+ for (i = (1 << bitspersample) - 1; i >= 0; i--)
+ {
+#define CVT(x) (((x)*255) / ((1L << 16) - 1))
+ rmap[i] = CVT(rmap[i]);
+ gmap[i] = CVT(gmap[i]);
+ bmap[i] = CVT(bmap[i]);
+ }
+ }
+ {
+ unsigned char *ibuf, *obuf;
+ register unsigned char *pp;
+ register uint32_t x;
+ tmsize_t tss_in = TIFFScanlineSize(in);
+ tmsize_t tss_out = TIFFScanlineSize(out);
+ if (tss_out / tss_in < 3)
+ {
+ /*
+ * BUG 2750: The following code does not know about chroma
+ * subsampling of JPEG data. It assumes that the output buffer is 3x
+ * the length of the input buffer due to exploding the palette into
+ * RGB tuples. If this assumption is incorrect, it could lead to a
+ * buffer overflow. Go ahead and fail now to prevent that.
+ */
+ fprintf(stderr, "Could not determine correct image size for "
+ "output. Exiting.\n");
+ return EXIT_FAILURE;
+ }
+ ibuf = (unsigned char *)_TIFFmalloc(tss_in);
+ obuf = (unsigned char *)_TIFFmalloc(tss_out);
+ switch (config)
+ {
+ case PLANARCONFIG_CONTIG:
+ for (row = 0; row < imagelength; row++)
+ {
+ if (!TIFFReadScanline(in, ibuf, row, 0))
+ goto done;
+ pp = obuf;
+ for (x = 0; x < imagewidth; x++)
+ {
+ *pp++ = (unsigned char)rmap[ibuf[x]];
+ *pp++ = (unsigned char)gmap[ibuf[x]];
+ *pp++ = (unsigned char)bmap[ibuf[x]];
+ }
+ if (!TIFFWriteScanline(out, obuf, row, 0))
+ goto done;
+ }
+ break;
+ case PLANARCONFIG_SEPARATE:
+ for (row = 0; row < imagelength; row++)
+ {
+ if (!TIFFReadScanline(in, ibuf, row, 0))
+ goto done;
+ for (pp = obuf, x = 0; x < imagewidth; x++)
+ *pp++ = (unsigned char)rmap[ibuf[x]];
+ if (!TIFFWriteScanline(out, obuf, row, 0))
+ goto done;
+ for (pp = obuf, x = 0; x < imagewidth; x++)
+ *pp++ = (unsigned char)gmap[ibuf[x]];
+ if (!TIFFWriteScanline(out, obuf, row, 0))
+ goto done;
+ for (pp = obuf, x = 0; x < imagewidth; x++)
+ *pp++ = (unsigned char)bmap[ibuf[x]];
+ if (!TIFFWriteScanline(out, obuf, row, 0))
+ goto done;
+ }
+ break;
+ }
+ _TIFFfree(ibuf);
+ _TIFFfree(obuf);
+ }
done:
- (void) TIFFClose(in);
- (void) TIFFClose(out);
- return (EXIT_SUCCESS);
+ (void)TIFFClose(in);
+ (void)TIFFClose(out);
+ return (EXIT_SUCCESS);
}
-static int
-processCompressOptions(char* opt)
+static int processCompressOptions(char *opt)
{
- if (streq(opt, "none"))
- compression = COMPRESSION_NONE;
- else if (streq(opt, "packbits"))
- compression = COMPRESSION_PACKBITS;
- else if (strneq(opt, "jpeg", 4)) {
- char* cp = strchr(opt, ':');
+ if (streq(opt, "none"))
+ compression = COMPRESSION_NONE;
+ else if (streq(opt, "packbits"))
+ compression = COMPRESSION_PACKBITS;
+ else if (strneq(opt, "jpeg", 4))
+ {
+ char *cp = strchr(opt, ':');
- compression = COMPRESSION_JPEG;
- while( cp )
- {
- if (isdigit((int)cp[1]))
- quality = atoi(cp+1);
- else if (cp[1] == 'r' )
- jpegcolormode = JPEGCOLORMODE_RAW;
- else
- usage(EXIT_FAILURE);
+ compression = COMPRESSION_JPEG;
+ while (cp)
+ {
+ if (isdigit((int)cp[1]))
+ quality = atoi(cp + 1);
+ else if (cp[1] == 'r')
+ jpegcolormode = JPEGCOLORMODE_RAW;
+ else
+ usage(EXIT_FAILURE);
- cp = strchr(cp+1,':');
- }
- } else if (strneq(opt, "lzw", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_LZW;
- } else if (strneq(opt, "zip", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_ADOBE_DEFLATE;
- } else
- return (0);
- return (1);
+ cp = strchr(cp + 1, ':');
+ }
+ }
+ else if (strneq(opt, "lzw", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_LZW;
+ }
+ else if (strneq(opt, "zip", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_ADOBE_DEFLATE;
+ }
+ else
+ return (0);
+ return (1);
}
-#define CopyField(tag, v) \
- if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
-#define CopyField2(tag, v1, v2) \
- if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
-#define CopyField3(tag, v1, v2, v3) \
- if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
-#define CopyField4(tag, v1, v2, v3, v4) \
- if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
+#define CopyField(tag, v) \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v)
+#define CopyField2(tag, v1, v2) \
+ if (TIFFGetField(in, tag, &v1, &v2)) \
+ TIFFSetField(out, tag, v1, v2)
+#define CopyField3(tag, v1, v2, v3) \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) \
+ TIFFSetField(out, tag, v1, v2, v3)
+#define CopyField4(tag, v1, v2, v3, v4) \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) \
+ TIFFSetField(out, tag, v1, v2, v3, v4)
-static void
-cpTag(TIFF* in, TIFF* out, uint16_t tag, uint16_t count, TIFFDataType type)
+static void cpTag(TIFF *in, TIFF *out, uint16_t tag, uint16_t count,
+ TIFFDataType type)
{
- switch (type) {
- case TIFF_SHORT:
- if (count == 1) {
- uint16_t shortv;
- CopyField(tag, shortv);
- } else if (count == 2) {
- uint16_t shortv1, shortv2;
- CopyField2(tag, shortv1, shortv2);
- } else if (count == 4) {
- uint16_t *tr, *tg, *tb, *ta;
- CopyField4(tag, tr, tg, tb, ta);
- } else if (count == (uint16_t) -1) {
- uint16_t shortv1;
- uint16_t* shortav;
- CopyField2(tag, shortv1, shortav);
- }
- break;
- case TIFF_LONG:
- { uint32_t longv;
- CopyField(tag, longv);
- }
- break;
- case TIFF_RATIONAL:
- if (count == 1) {
- float floatv;
- CopyField(tag, floatv);
- } else if (count == (uint16_t) -1) {
- float* floatav;
- CopyField(tag, floatav);
- }
- break;
- case TIFF_ASCII:
- { char* stringv;
- CopyField(tag, stringv);
- }
- break;
- case TIFF_DOUBLE:
- if (count == 1) {
- double doublev;
- CopyField(tag, doublev);
- } else if (count == (uint16_t) -1) {
- double* doubleav;
- CopyField(tag, doubleav);
- }
- break;
- default:
- TIFFError(TIFFFileName(in),
- "Data type %d is not supported, tag %d skipped.",
- tag, type);
- }
+ switch (type)
+ {
+ case TIFF_SHORT:
+ if (count == 1)
+ {
+ uint16_t shortv;
+ CopyField(tag, shortv);
+ }
+ else if (count == 2)
+ {
+ uint16_t shortv1, shortv2;
+ CopyField2(tag, shortv1, shortv2);
+ }
+ else if (count == 4)
+ {
+ uint16_t *tr, *tg, *tb, *ta;
+ CopyField4(tag, tr, tg, tb, ta);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ uint16_t shortv1;
+ uint16_t *shortav;
+ CopyField2(tag, shortv1, shortav);
+ }
+ break;
+ case TIFF_LONG:
+ {
+ uint32_t longv;
+ CopyField(tag, longv);
+ }
+ break;
+ case TIFF_RATIONAL:
+ if (count == 1)
+ {
+ float floatv;
+ CopyField(tag, floatv);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ float *floatav;
+ CopyField(tag, floatav);
+ }
+ break;
+ case TIFF_ASCII:
+ {
+ char *stringv;
+ CopyField(tag, stringv);
+ }
+ break;
+ case TIFF_DOUBLE:
+ if (count == 1)
+ {
+ double doublev;
+ CopyField(tag, doublev);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ double *doubleav;
+ CopyField(tag, doubleav);
+ }
+ break;
+ default:
+ TIFFError(TIFFFileName(in),
+ "Data type %d is not supported, tag %d skipped.", tag,
+ type);
+ }
}
#undef CopyField4
@@ -359,75 +397,79 @@ cpTag(TIFF* in, TIFF* out, uint16_t tag, uint16_t count, TIFFDataType type)
#undef CopyField2
#undef CopyField
-static const struct cpTag {
- uint16_t tag;
- uint16_t count;
+static const struct cpTag
+{
+ uint16_t tag;
+ uint16_t count;
TIFFDataType type;
} tags[] = {
- { TIFFTAG_IMAGEWIDTH, 1, TIFF_LONG },
- { TIFFTAG_IMAGELENGTH, 1, TIFF_LONG },
- { TIFFTAG_BITSPERSAMPLE, 1, TIFF_SHORT },
- { TIFFTAG_COMPRESSION, 1, TIFF_SHORT },
- { TIFFTAG_FILLORDER, 1, TIFF_SHORT },
- { TIFFTAG_ROWSPERSTRIP, 1, TIFF_LONG },
- { TIFFTAG_GROUP3OPTIONS, 1, TIFF_LONG },
- { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
- { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
- { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
- { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
- { TIFFTAG_MAKE, 1, TIFF_ASCII },
- { TIFFTAG_MODEL, 1, TIFF_ASCII },
- { TIFFTAG_ORIENTATION, 1, TIFF_SHORT },
- { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
- { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
- { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
- { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
- { TIFFTAG_PAGENAME, 1, TIFF_ASCII },
- { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
- { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
- { TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG },
- { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
- { TIFFTAG_PAGENUMBER, 2, TIFF_SHORT },
- { TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
- { TIFFTAG_DATETIME, 1, TIFF_ASCII },
- { TIFFTAG_ARTIST, 1, TIFF_ASCII },
- { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
- { TIFFTAG_WHITEPOINT, 2, TIFF_RATIONAL },
- { TIFFTAG_PRIMARYCHROMATICITIES, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
- { TIFFTAG_BADFAXLINES, 1, TIFF_LONG },
- { TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT },
- { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG },
- { TIFFTAG_INKSET, 1, TIFF_SHORT },
- /*{ TIFFTAG_INKNAMES, 1, TIFF_ASCII },*/ /* Needs much more complicated logic. See tiffcp */
- { TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
- { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
- { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
- { TIFFTAG_YCBCRCOEFFICIENTS, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
- { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
- { TIFFTAG_REFERENCEBLACKWHITE, (uint16_t) -1, TIFF_RATIONAL },
+ {TIFFTAG_IMAGEWIDTH, 1, TIFF_LONG},
+ {TIFFTAG_IMAGELENGTH, 1, TIFF_LONG},
+ {TIFFTAG_BITSPERSAMPLE, 1, TIFF_SHORT},
+ {TIFFTAG_COMPRESSION, 1, TIFF_SHORT},
+ {TIFFTAG_FILLORDER, 1, TIFF_SHORT},
+ {TIFFTAG_ROWSPERSTRIP, 1, TIFF_LONG},
+ {TIFFTAG_GROUP3OPTIONS, 1, TIFF_LONG},
+ {TIFFTAG_SUBFILETYPE, 1, TIFF_LONG},
+ {TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT},
+ {TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII},
+ {TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII},
+ {TIFFTAG_MAKE, 1, TIFF_ASCII},
+ {TIFFTAG_MODEL, 1, TIFF_ASCII},
+ {TIFFTAG_ORIENTATION, 1, TIFF_SHORT},
+ {TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT},
+ {TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT},
+ {TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL},
+ {TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL},
+ {TIFFTAG_PAGENAME, 1, TIFF_ASCII},
+ {TIFFTAG_XPOSITION, 1, TIFF_RATIONAL},
+ {TIFFTAG_YPOSITION, 1, TIFF_RATIONAL},
+ {TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG},
+ {TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT},
+ {TIFFTAG_PAGENUMBER, 2, TIFF_SHORT},
+ {TIFFTAG_SOFTWARE, 1, TIFF_ASCII},
+ {TIFFTAG_DATETIME, 1, TIFF_ASCII},
+ {TIFFTAG_ARTIST, 1, TIFF_ASCII},
+ {TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII},
+ {TIFFTAG_WHITEPOINT, 2, TIFF_RATIONAL},
+ {TIFFTAG_PRIMARYCHROMATICITIES, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT},
+ {TIFFTAG_BADFAXLINES, 1, TIFF_LONG},
+ {TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT},
+ {TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG},
+ {TIFFTAG_INKSET, 1, TIFF_SHORT},
+ /*{ TIFFTAG_INKNAMES, 1, TIFF_ASCII },*/ /* Needs much
+ more
+ complicated
+ logic. See
+ tiffcp */
+ {TIFFTAG_DOTRANGE, 2, TIFF_SHORT},
+ {TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII},
+ {TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT},
+ {TIFFTAG_YCBCRCOEFFICIENTS, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT},
+ {TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT},
+ {TIFFTAG_REFERENCEBLACKWHITE, (uint16_t)-1, TIFF_RATIONAL},
};
-#define NTAGS (sizeof (tags) / sizeof (tags[0]))
+#define NTAGS (sizeof(tags) / sizeof(tags[0]))
-static void
-cpTags(TIFF* in, TIFF* out)
+static void cpTags(TIFF *in, TIFF *out)
{
const struct cpTag *p;
for (p = tags; p < &tags[NTAGS]; p++)
{
- if( p->tag == TIFFTAG_GROUP3OPTIONS )
+ if (p->tag == TIFFTAG_GROUP3OPTIONS)
{
uint16_t compression;
- if( !TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
- compression != COMPRESSION_CCITTFAX3 )
+ if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
+ compression != COMPRESSION_CCITTFAX3)
continue;
}
- if( p->tag == TIFFTAG_GROUP4OPTIONS )
+ if (p->tag == TIFFTAG_GROUP4OPTIONS)
{
uint16_t compression;
- if( !TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
- compression != COMPRESSION_CCITTFAX4 )
+ if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
+ compression != COMPRESSION_CCITTFAX4)
continue;
}
cpTag(in, out, p->tag, p->count, p->type);
@@ -436,40 +478,40 @@ cpTags(TIFF* in, TIFF* out)
#undef NTAGS
static const char usage_info[] =
-"Convert a palette color TIFF image to a full color image\n\n"
-"usage: pal2rgb [options] input.tif output.tif\n"
-"where options are:\n"
-" -p contig pack samples contiguously (e.g. RGBRGB...)\n"
-" -p separate store samples separately (e.g. RRR...GGG...BBB...)\n"
-" -r # make each strip have no more than # rows\n"
-" -C 8 assume 8-bit colormap values (instead of 16-bit)\n"
-" -C 16 assume 16-bit colormap values\n"
-"\n"
+ "Convert a palette color TIFF image to a full color image\n\n"
+ "usage: pal2rgb [options] input.tif output.tif\n"
+ "where options are:\n"
+ " -p contig pack samples contiguously (e.g. RGBRGB...)\n"
+ " -p separate store samples separately (e.g. RRR...GGG...BBB...)\n"
+ " -r # make each strip have no more than # rows\n"
+ " -C 8 assume 8-bit colormap values (instead of 16-bit)\n"
+ " -C 16 assume 16-bit colormap values\n"
+ "\n"
#ifdef LZW_SUPPORT
-" -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
-/* " LZW options:\n" */
-" # set predictor value\n"
-" For example, -c lzw:2 to get LZW-encoded data with horizontal differencing\n"
+ " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
+ /* " LZW options:\n" */
+ " # set predictor value\n"
+ " For example, -c lzw:2 to get LZW-encoded data with horizontal "
+ "differencing\n"
#endif
#ifdef ZIP_SUPPORT
-" -c zip[:opts] compress output with deflate encoding\n"
-/* " Deflate (ZIP) options:\n" */
-" # set predictor value\n"
+ " -c zip[:opts] compress output with deflate encoding\n"
+ /* " Deflate (ZIP) options:\n" */
+ " # set predictor value\n"
#endif
#ifdef PACKBITS_SUPPORT
-" -c packbits compress output with packbits encoding\n"
+ " -c packbits compress output with packbits encoding\n"
#endif
#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(PACKBITS_SUPPORT)
-" -c none use no compression algorithm on output\n"
+ " -c none use no compression algorithm on output\n"
#endif
-;
+ ;
-static void
-usage(int code)
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
diff --git a/tools/ppm2tiff.c b/tools/ppm2tiff.c
index 539dd3d2..e64e26d0 100644
--- a/tools/ppm2tiff.c
+++ b/tools/ppm2tiff.c
@@ -2,44 +2,44 @@
* Copyright (c) 1991-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
+#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <ctype.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
-# include <fcntl.h>
+#include <fcntl.h>
#endif
#ifdef HAVE_IO_H
-# include <io.h>
+#include <io.h>
#endif
#include "tiffio.h"
@@ -51,478 +51,521 @@
#define EXIT_FAILURE 1
#endif
-#define streq(a,b) (strcmp(a,b) == 0)
-#define strneq(a,b,n) (strncmp(a,b,n) == 0)
+#define streq(a, b) (strcmp(a, b) == 0)
+#define strneq(a, b, n) (strncmp(a, b, n) == 0)
-static uint16_t compression = COMPRESSION_PACKBITS;
-static uint16_t predictor = 0;
-static int quality = 75; /* JPEG quality */
-static int jpegcolormode = JPEGCOLORMODE_RGB;
-static uint32_t g3opts;
+static uint16_t compression = COMPRESSION_PACKBITS;
+static uint16_t predictor = 0;
+static int quality = 75; /* JPEG quality */
+static int jpegcolormode = JPEGCOLORMODE_RGB;
+static uint32_t g3opts;
-static void usage(int code);
-static int processCompressOptions(char*);
+static void usage(int code);
+static int processCompressOptions(char *);
-static void
-pack_none (unsigned char *buf, unsigned int smpls, uint16_t bps)
+static void pack_none(unsigned char *buf, unsigned int smpls, uint16_t bps)
{
- (void)buf;
- (void)smpls;
- (void)bps;
- return;
+ (void)buf;
+ (void)smpls;
+ (void)bps;
+ return;
}
-static void
-pack_swab (unsigned char *buf, unsigned int smpls, uint16_t bps)
+static void pack_swab(unsigned char *buf, unsigned int smpls, uint16_t bps)
{
- unsigned int s;
- unsigned char h;
- unsigned char l;
- (void)bps;
+ unsigned int s;
+ unsigned char h;
+ unsigned char l;
+ (void)bps;
- for (s = 0; smpls > s; s++) {
+ for (s = 0; smpls > s; s++)
+ {
- h = buf [s * 2 + 0];
- l = buf [s * 2 + 1];
+ h = buf[s * 2 + 0];
+ l = buf[s * 2 + 1];
- buf [s * 2 + 0] = l;
- buf [s * 2 + 1] = h;
- }
- return;
+ buf[s * 2 + 0] = l;
+ buf[s * 2 + 1] = h;
+ }
+ return;
}
-static void
-pack_bytes (unsigned char *buf, unsigned int smpls, uint16_t bps)
+static void pack_bytes(unsigned char *buf, unsigned int smpls, uint16_t bps)
{
- unsigned int s;
- unsigned int in;
- unsigned int out;
- int bits;
- uint16_t t;
-
- in = 0;
- out = 0;
- bits = 0;
- t = 0;
-
- for (s = 0; smpls > s; s++) {
-
- t <<= bps;
- t |= (uint16_t) buf [in++];
-
- bits += bps;
-
- if (8 <= bits) {
- bits -= 8;
- buf [out++] = (t >> bits) & 0xFF;
- }
- }
- if (0 != bits)
- buf [out] = (t << (8 - bits)) & 0xFF;
+ unsigned int s;
+ unsigned int in;
+ unsigned int out;
+ int bits;
+ uint16_t t;
+
+ in = 0;
+ out = 0;
+ bits = 0;
+ t = 0;
+
+ for (s = 0; smpls > s; s++)
+ {
+
+ t <<= bps;
+ t |= (uint16_t)buf[in++];
+
+ bits += bps;
+
+ if (8 <= bits)
+ {
+ bits -= 8;
+ buf[out++] = (t >> bits) & 0xFF;
+ }
+ }
+ if (0 != bits)
+ buf[out] = (t << (8 - bits)) & 0xFF;
}
-static void
-pack_words (unsigned char *buf, unsigned int smpls, uint16_t bps)
+static void pack_words(unsigned char *buf, unsigned int smpls, uint16_t bps)
{
- unsigned int s;
- unsigned int in;
- unsigned int out;
- int bits;
- uint32_t t;
-
- in = 0;
- out = 0;
- bits = 0;
- t = 0;
-
- for (s = 0; smpls > s; s++) {
-
- t <<= bps;
- t |= (uint32_t) buf [in++] << 8;
- t |= (uint32_t) buf [in++] << 0;
-
- bits += bps;
-
- if (16 <= bits) {
-
- bits -= 16;
- buf [out++] = (t >> (bits + 8));
- buf [out++] = (t >> (bits + 0));
- }
- }
- if (0 != bits) {
- t <<= 16 - bits;
-
- buf [out++] = (t >> (16 + 8));
- buf [out++] = (t >> (16 + 0));
- }
+ unsigned int s;
+ unsigned int in;
+ unsigned int out;
+ int bits;
+ uint32_t t;
+
+ in = 0;
+ out = 0;
+ bits = 0;
+ t = 0;
+
+ for (s = 0; smpls > s; s++)
+ {
+
+ t <<= bps;
+ t |= (uint32_t)buf[in++] << 8;
+ t |= (uint32_t)buf[in++] << 0;
+
+ bits += bps;
+
+ if (16 <= bits)
+ {
+
+ bits -= 16;
+ buf[out++] = (t >> (bits + 8));
+ buf[out++] = (t >> (bits + 0));
+ }
+ }
+ if (0 != bits)
+ {
+ t <<= 16 - bits;
+
+ buf[out++] = (t >> (16 + 8));
+ buf[out++] = (t >> (16 + 0));
+ }
}
-static void
-BadPPM(char* file)
+static void BadPPM(char *file)
{
- fprintf(stderr, "%s: Not a PPM file.\n", file);
- exit(EXIT_FAILURE);
+ fprintf(stderr, "%s: Not a PPM file.\n", file);
+ exit(EXIT_FAILURE);
}
-
-static tmsize_t
-multiply_ms(tmsize_t m1, tmsize_t m2)
+static tmsize_t multiply_ms(tmsize_t m1, tmsize_t m2)
{
- if( m1 == 0 || m2 > TIFF_TMSIZE_T_MAX / m1 )
- return 0;
- return m1 * m2;
+ if (m1 == 0 || m2 > TIFF_TMSIZE_T_MAX / m1)
+ return 0;
+ return m1 * m2;
}
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- uint16_t photometric = 0;
- uint32_t rowsperstrip = (uint32_t) -1;
- double resolution = -1;
- unsigned char *buf = NULL;
- tmsize_t linebytes = 0;
- int pbm;
- uint16_t spp = 1;
- uint16_t bpp = 8;
- void (*pack_func) (unsigned char *buf, unsigned int smpls, uint16_t bps);
- TIFF *out;
- FILE *in;
- unsigned int w, h, prec, row;
- char *infile;
- int c;
+ uint16_t photometric = 0;
+ uint32_t rowsperstrip = (uint32_t)-1;
+ double resolution = -1;
+ unsigned char *buf = NULL;
+ tmsize_t linebytes = 0;
+ int pbm;
+ uint16_t spp = 1;
+ uint16_t bpp = 8;
+ void (*pack_func)(unsigned char *buf, unsigned int smpls, uint16_t bps);
+ TIFF *out;
+ FILE *in;
+ unsigned int w, h, prec, row;
+ char *infile;
+ int c;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char* optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- tmsize_t scanline_size;
-
- if (argc < 2) {
- fprintf(stderr, "%s: Too few arguments\n", argv[0]);
- usage(EXIT_FAILURE);
- }
- while ((c = getopt(argc, argv, "c:r:R:h")) != -1)
- switch (c) {
- case 'c': /* compression scheme */
- if (!processCompressOptions(optarg))
- usage(EXIT_FAILURE);
- break;
- case 'r': /* rows/strip */
- rowsperstrip = atoi(optarg);
- break;
- case 'R': /* resolution */
- resolution = atof(optarg);
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- break;
- case '?':
- usage(EXIT_FAILURE);
- /*NOTREACHED*/
- }
-
- if (optind + 2 < argc) {
- fprintf(stderr, "%s: Too many arguments\n", argv[0]);
- usage(EXIT_FAILURE);
- }
-
- /*
- * If only one file is specified, read input from
- * stdin; otherwise usage is: ppm2tiff input output.
- */
- if (argc - optind > 1) {
- infile = argv[optind++];
- in = fopen(infile, "rb");
- if (in == NULL) {
- fprintf(stderr, "%s: Can not open.\n", infile);
- return (EXIT_FAILURE);
- }
- } else {
- infile = "<stdin>";
- in = stdin;
+ tmsize_t scanline_size;
+
+ if (argc < 2)
+ {
+ fprintf(stderr, "%s: Too few arguments\n", argv[0]);
+ usage(EXIT_FAILURE);
+ }
+ while ((c = getopt(argc, argv, "c:r:R:h")) != -1)
+ switch (c)
+ {
+ case 'c': /* compression scheme */
+ if (!processCompressOptions(optarg))
+ usage(EXIT_FAILURE);
+ break;
+ case 'r': /* rows/strip */
+ rowsperstrip = atoi(optarg);
+ break;
+ case 'R': /* resolution */
+ resolution = atof(optarg);
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ /*NOTREACHED*/
+ }
+
+ if (optind + 2 < argc)
+ {
+ fprintf(stderr, "%s: Too many arguments\n", argv[0]);
+ usage(EXIT_FAILURE);
+ }
+
+ /*
+ * If only one file is specified, read input from
+ * stdin; otherwise usage is: ppm2tiff input output.
+ */
+ if (argc - optind > 1)
+ {
+ infile = argv[optind++];
+ in = fopen(infile, "rb");
+ if (in == NULL)
+ {
+ fprintf(stderr, "%s: Can not open.\n", infile);
+ return (EXIT_FAILURE);
+ }
+ }
+ else
+ {
+ infile = "<stdin>";
+ in = stdin;
#if defined(HAVE_SETMODE) && defined(O_BINARY)
- setmode(fileno(stdin), O_BINARY);
+ setmode(fileno(stdin), O_BINARY);
#endif
- }
-
- if (fgetc(in) != 'P')
- BadPPM(infile);
- switch (fgetc(in)) {
- case '4': /* it's a PBM file */
- pbm = !0;
- spp = 1;
- photometric = PHOTOMETRIC_MINISWHITE;
- break;
- case '5': /* it's a PGM file */
- pbm = 0;
- spp = 1;
- photometric = PHOTOMETRIC_MINISBLACK;
- break;
- case '6': /* it's a PPM file */
- pbm = 0;
- spp = 3;
- photometric = PHOTOMETRIC_RGB;
- if (compression == COMPRESSION_JPEG &&
- jpegcolormode == JPEGCOLORMODE_RGB)
- photometric = PHOTOMETRIC_YCBCR;
- break;
- default:
- BadPPM(infile);
- }
-
- /* Parse header */
- while(1) {
- if (feof(in))
- BadPPM(infile);
- c = fgetc(in);
- /* Skip whitespaces (blanks, TABs, CRs, LFs) */
- if (strchr(" \t\r\n", c))
- continue;
-
- /* Check for comment line */
- if (c == '#') {
- do {
- c = fgetc(in);
- } while(!(strchr("\r\n", c) || feof(in)));
- continue;
- }
-
- ungetc(c, in);
- break;
- }
- if (pbm) {
- if (fscanf(in, " %u %u", &w, &h) != 2)
- BadPPM(infile);
- if (fgetc(in) != '\n')
- BadPPM(infile);
- bpp = 1;
- pack_func = pack_none;
- } else {
- if (fscanf(in, " %u %u %u", &w, &h, &prec) != 3)
- BadPPM(infile);
- if (fgetc(in) != '\n' || 0 == prec || 65535 < prec)
- BadPPM(infile);
-
- if (0 != (prec & (prec + 1))) {
- fprintf(stderr, "%s: unsupported maxval %u.\n",
- infile, prec);
- exit(EXIT_FAILURE);
- }
- bpp = 0;
- if ((prec + 1) & 0xAAAAAAAA) bpp |= 1;
- if ((prec + 1) & 0xCCCCCCCC) bpp |= 2;
- if ((prec + 1) & 0xF0F0F0F0) bpp |= 4;
- if ((prec + 1) & 0xFF00FF00) bpp |= 8;
- if ((prec + 1) & 0xFFFF0000) bpp |= 16;
-
- switch (bpp) {
- case 8:
- pack_func = pack_none;
- break;
- case 16:
- {
- const unsigned short i = 0x0100;
-
- if (0 == *(unsigned char*) &i)
- pack_func = pack_swab;
- else
- pack_func = pack_none;
- }
- break;
- default:
- if (8 >= bpp)
- pack_func = pack_bytes;
- else
- pack_func = pack_words;
- break;
- }
- }
- out = TIFFOpen(argv[optind], "w");
- if (out == NULL)
- return (EXIT_FAILURE);
- TIFFSetField(out, TIFFTAG_IMAGEWIDTH, (uint32_t) w);
- TIFFSetField(out, TIFFTAG_IMAGELENGTH, (uint32_t) h);
- TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bpp);
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- switch (compression) {
- case COMPRESSION_JPEG:
- TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
- TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
- break;
- case COMPRESSION_LZW:
- case COMPRESSION_ADOBE_DEFLATE:
- case COMPRESSION_DEFLATE:
- if (predictor != 0)
- TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
- break;
+ }
+
+ if (fgetc(in) != 'P')
+ BadPPM(infile);
+ switch (fgetc(in))
+ {
+ case '4': /* it's a PBM file */
+ pbm = !0;
+ spp = 1;
+ photometric = PHOTOMETRIC_MINISWHITE;
+ break;
+ case '5': /* it's a PGM file */
+ pbm = 0;
+ spp = 1;
+ photometric = PHOTOMETRIC_MINISBLACK;
+ break;
+ case '6': /* it's a PPM file */
+ pbm = 0;
+ spp = 3;
+ photometric = PHOTOMETRIC_RGB;
+ if (compression == COMPRESSION_JPEG &&
+ jpegcolormode == JPEGCOLORMODE_RGB)
+ photometric = PHOTOMETRIC_YCBCR;
+ break;
+ default:
+ BadPPM(infile);
+ }
+
+ /* Parse header */
+ while (1)
+ {
+ if (feof(in))
+ BadPPM(infile);
+ c = fgetc(in);
+ /* Skip whitespaces (blanks, TABs, CRs, LFs) */
+ if (strchr(" \t\r\n", c))
+ continue;
+
+ /* Check for comment line */
+ if (c == '#')
+ {
+ do
+ {
+ c = fgetc(in);
+ } while (!(strchr("\r\n", c) || feof(in)));
+ continue;
+ }
+
+ ungetc(c, in);
+ break;
+ }
+ if (pbm)
+ {
+ if (fscanf(in, " %u %u", &w, &h) != 2)
+ BadPPM(infile);
+ if (fgetc(in) != '\n')
+ BadPPM(infile);
+ bpp = 1;
+ pack_func = pack_none;
+ }
+ else
+ {
+ if (fscanf(in, " %u %u %u", &w, &h, &prec) != 3)
+ BadPPM(infile);
+ if (fgetc(in) != '\n' || 0 == prec || 65535 < prec)
+ BadPPM(infile);
+
+ if (0 != (prec & (prec + 1)))
+ {
+ fprintf(stderr, "%s: unsupported maxval %u.\n", infile, prec);
+ exit(EXIT_FAILURE);
+ }
+ bpp = 0;
+ if ((prec + 1) & 0xAAAAAAAA)
+ bpp |= 1;
+ if ((prec + 1) & 0xCCCCCCCC)
+ bpp |= 2;
+ if ((prec + 1) & 0xF0F0F0F0)
+ bpp |= 4;
+ if ((prec + 1) & 0xFF00FF00)
+ bpp |= 8;
+ if ((prec + 1) & 0xFFFF0000)
+ bpp |= 16;
+
+ switch (bpp)
+ {
+ case 8:
+ pack_func = pack_none;
+ break;
+ case 16:
+ {
+ const unsigned short i = 0x0100;
+
+ if (0 == *(unsigned char *)&i)
+ pack_func = pack_swab;
+ else
+ pack_func = pack_none;
+ }
+ break;
+ default:
+ if (8 >= bpp)
+ pack_func = pack_bytes;
+ else
+ pack_func = pack_words;
+ break;
+ }
+ }
+ out = TIFFOpen(argv[optind], "w");
+ if (out == NULL)
+ return (EXIT_FAILURE);
+ TIFFSetField(out, TIFFTAG_IMAGEWIDTH, (uint32_t)w);
+ TIFFSetField(out, TIFFTAG_IMAGELENGTH, (uint32_t)h);
+ TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bpp);
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
+ switch (compression)
+ {
+ case COMPRESSION_JPEG:
+ TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
+ TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
+ break;
+ case COMPRESSION_LZW:
+ case COMPRESSION_ADOBE_DEFLATE:
+ case COMPRESSION_DEFLATE:
+ if (predictor != 0)
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
+ break;
case COMPRESSION_CCITTFAX3:
- TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
- break;
- }
- if (pbm) {
- /* if round-up overflows, result will be zero, OK */
- linebytes = (multiply_ms(spp, w) + (8 - 1)) / 8;
- } else if (bpp <= 8) {
- linebytes = multiply_ms(spp, w);
- } else {
- linebytes = multiply_ms(2 * spp, w);
- }
- if (rowsperstrip == (uint32_t) -1) {
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, h);
- } else {
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
- TIFFDefaultStripSize(out, rowsperstrip));
- }
- if (linebytes == 0) {
- fprintf(stderr, "%s: scanline size overflow\n", infile);
- (void) TIFFClose(out);
- exit(EXIT_FAILURE);
- }
- scanline_size = TIFFScanlineSize(out);
- if (scanline_size == 0) {
- /* overflow - TIFFScanlineSize already printed a message */
- (void) TIFFClose(out);
- exit(EXIT_FAILURE);
- }
- if (scanline_size < linebytes)
- buf = (unsigned char *)_TIFFmalloc(linebytes);
- else
- buf = (unsigned char *)_TIFFmalloc(scanline_size);
- if (buf == NULL) {
- fprintf(stderr, "%s: Not enough memory\n", infile);
- (void) TIFFClose(out);
- exit(EXIT_FAILURE);
- }
- if (resolution > 0) {
- TIFFSetField(out, TIFFTAG_XRESOLUTION, resolution);
- TIFFSetField(out, TIFFTAG_YRESOLUTION, resolution);
- TIFFSetField(out, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
- }
- for (row = 0; row < h; row++) {
- if (fread(buf, linebytes, 1, in) != 1) {
- fprintf(stderr, "%s: scanline %u: Read error.\n",
- infile, row);
- break;
- }
- pack_func (buf, w * spp, bpp);
- if (TIFFWriteScanline(out, buf, row, 0) < 0)
- break;
- }
- if (in != stdin)
- fclose(in);
- (void) TIFFClose(out);
- if (buf)
- _TIFFfree(buf);
- return (EXIT_SUCCESS);
+ TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
+ break;
+ }
+ if (pbm)
+ {
+ /* if round-up overflows, result will be zero, OK */
+ linebytes = (multiply_ms(spp, w) + (8 - 1)) / 8;
+ }
+ else if (bpp <= 8)
+ {
+ linebytes = multiply_ms(spp, w);
+ }
+ else
+ {
+ linebytes = multiply_ms(2 * spp, w);
+ }
+ if (rowsperstrip == (uint32_t)-1)
+ {
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, h);
+ }
+ else
+ {
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
+ TIFFDefaultStripSize(out, rowsperstrip));
+ }
+ if (linebytes == 0)
+ {
+ fprintf(stderr, "%s: scanline size overflow\n", infile);
+ (void)TIFFClose(out);
+ exit(EXIT_FAILURE);
+ }
+ scanline_size = TIFFScanlineSize(out);
+ if (scanline_size == 0)
+ {
+ /* overflow - TIFFScanlineSize already printed a message */
+ (void)TIFFClose(out);
+ exit(EXIT_FAILURE);
+ }
+ if (scanline_size < linebytes)
+ buf = (unsigned char *)_TIFFmalloc(linebytes);
+ else
+ buf = (unsigned char *)_TIFFmalloc(scanline_size);
+ if (buf == NULL)
+ {
+ fprintf(stderr, "%s: Not enough memory\n", infile);
+ (void)TIFFClose(out);
+ exit(EXIT_FAILURE);
+ }
+ if (resolution > 0)
+ {
+ TIFFSetField(out, TIFFTAG_XRESOLUTION, resolution);
+ TIFFSetField(out, TIFFTAG_YRESOLUTION, resolution);
+ TIFFSetField(out, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
+ }
+ for (row = 0; row < h; row++)
+ {
+ if (fread(buf, linebytes, 1, in) != 1)
+ {
+ fprintf(stderr, "%s: scanline %u: Read error.\n", infile, row);
+ break;
+ }
+ pack_func(buf, w * spp, bpp);
+ if (TIFFWriteScanline(out, buf, row, 0) < 0)
+ break;
+ }
+ if (in != stdin)
+ fclose(in);
+ (void)TIFFClose(out);
+ if (buf)
+ _TIFFfree(buf);
+ return (EXIT_SUCCESS);
}
-static void
-processG3Options(char* cp)
+static void processG3Options(char *cp)
{
- g3opts = 0;
- if( (cp = strchr(cp, ':')) ) {
- do {
- cp++;
- if (strneq(cp, "1d", 2))
- g3opts &= ~GROUP3OPT_2DENCODING;
- else if (strneq(cp, "2d", 2))
- g3opts |= GROUP3OPT_2DENCODING;
- else if (strneq(cp, "fill", 4))
- g3opts |= GROUP3OPT_FILLBITS;
- else
- usage(EXIT_FAILURE);
- } while( (cp = strchr(cp, ':')) );
- }
+ g3opts = 0;
+ if ((cp = strchr(cp, ':')))
+ {
+ do
+ {
+ cp++;
+ if (strneq(cp, "1d", 2))
+ g3opts &= ~GROUP3OPT_2DENCODING;
+ else if (strneq(cp, "2d", 2))
+ g3opts |= GROUP3OPT_2DENCODING;
+ else if (strneq(cp, "fill", 4))
+ g3opts |= GROUP3OPT_FILLBITS;
+ else
+ usage(EXIT_FAILURE);
+ } while ((cp = strchr(cp, ':')));
+ }
}
-static int
-processCompressOptions(char* opt)
+static int processCompressOptions(char *opt)
{
- if (streq(opt, "none"))
- compression = COMPRESSION_NONE;
- else if (streq(opt, "packbits"))
- compression = COMPRESSION_PACKBITS;
- else if (strneq(opt, "jpeg", 4)) {
- char* cp = strchr(opt, ':');
-
- compression = COMPRESSION_JPEG;
- while (cp)
- {
- if (isdigit((int)cp[1]))
- quality = atoi(cp+1);
- else if (cp[1] == 'r' )
- jpegcolormode = JPEGCOLORMODE_RAW;
- else
- usage(EXIT_FAILURE);
-
- cp = strchr(cp+1,':');
- }
- } else if (strneq(opt, "g3", 2)) {
- processG3Options(opt);
- compression = COMPRESSION_CCITTFAX3;
- } else if (streq(opt, "g4")) {
- compression = COMPRESSION_CCITTFAX4;
- } else if (strneq(opt, "lzw", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_LZW;
- } else if (strneq(opt, "zip", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_ADOBE_DEFLATE;
- } else
- return (0);
- return (1);
+ if (streq(opt, "none"))
+ compression = COMPRESSION_NONE;
+ else if (streq(opt, "packbits"))
+ compression = COMPRESSION_PACKBITS;
+ else if (strneq(opt, "jpeg", 4))
+ {
+ char *cp = strchr(opt, ':');
+
+ compression = COMPRESSION_JPEG;
+ while (cp)
+ {
+ if (isdigit((int)cp[1]))
+ quality = atoi(cp + 1);
+ else if (cp[1] == 'r')
+ jpegcolormode = JPEGCOLORMODE_RAW;
+ else
+ usage(EXIT_FAILURE);
+
+ cp = strchr(cp + 1, ':');
+ }
+ }
+ else if (strneq(opt, "g3", 2))
+ {
+ processG3Options(opt);
+ compression = COMPRESSION_CCITTFAX3;
+ }
+ else if (streq(opt, "g4"))
+ {
+ compression = COMPRESSION_CCITTFAX4;
+ }
+ else if (strneq(opt, "lzw", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_LZW;
+ }
+ else if (strneq(opt, "zip", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_ADOBE_DEFLATE;
+ }
+ else
+ return (0);
+ return (1);
}
static const char usage_info[] =
-"Create a TIFF file from PPM, PGM and PBM image files\n\n"
-"usage: ppm2tiff [options] input.ppm output.tif\n"
-"where options are:\n"
-" -r # make each strip have no more than # rows\n"
-" -R # set x&y resolution (dpi)\n"
-"\n"
+ "Create a TIFF file from PPM, PGM and PBM image files\n\n"
+ "usage: ppm2tiff [options] input.ppm output.tif\n"
+ "where options are:\n"
+ " -r # make each strip have no more than # rows\n"
+ " -R # set x&y resolution (dpi)\n"
+ "\n"
#ifdef JPEG_SUPPORT
-" -c jpeg[:opts] compress output with JPEG encoding\n"
-/* "JPEG options:\n" */
-" # set compression quality level (0-100, default 75)\n"
-" r output color image as RGB rather than YCbCr\n"
+ " -c jpeg[:opts] compress output with JPEG encoding\n"
+ /* "JPEG options:\n" */
+ " # set compression quality level (0-100, default 75)\n"
+ " r output color image as RGB rather than YCbCr\n"
#endif
#ifdef LZW_SUPPORT
-" -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
-/* " LZW options:\n" */
-" # set predictor value\n"
-" For example, -c lzw:2 for LZW-encoded data with horizontal differencing\n"
+ " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
+ /* " LZW options:\n" */
+ " # set predictor value\n"
+ " For example, -c lzw:2 for LZW-encoded data with horizontal "
+ "differencing\n"
#endif
#ifdef ZIP_SUPPORT
-" -c zip[:opts] compress output with deflate encoding\n"
-/* " Deflate (ZIP) options:\n" */
-" # set predictor value\n"
+ " -c zip[:opts] compress output with deflate encoding\n"
+ /* " Deflate (ZIP) options:\n" */
+ " # set predictor value\n"
#endif
#ifdef PACKBITS_SUPPORT
-" -c packbits compress output with packbits encoding (the default)\n"
+ " -c packbits compress output with packbits encoding (the default)\n"
#endif
#ifdef CCITT_SUPPORT
-" -c g3[:opts] compress output with CCITT Group 3 encoding\n"
-" -c g4 compress output with CCITT Group 4 encoding\n"
+ " -c g3[:opts] compress output with CCITT Group 3 encoding\n"
+ " -c g4 compress output with CCITT Group 4 encoding\n"
#endif
-#if defined(JPEG_SUPPORT) || defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(PACKBITS_SUPPORT) || defined(CCITT_SUPPORT)
-" -c none use no compression algorithm on output\n"
+#if defined(JPEG_SUPPORT) || defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || \
+ defined(PACKBITS_SUPPORT) || defined(CCITT_SUPPORT)
+ " -c none use no compression algorithm on output\n"
#endif
-;
+ ;
-static void
-usage(int code)
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
diff --git a/tools/raw2tiff.c b/tools/raw2tiff.c
index 987afd0f..4ee59e5d 100644
--- a/tools/raw2tiff.c
+++ b/tools/raw2tiff.c
@@ -6,55 +6,55 @@
******************************************************************************
* Copyright (c) 2002, Andrey Kiselev <dron@ak4719.spb.edu>
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
+#include <ctype.h>
+#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
-#include <math.h>
-#include <ctype.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#if HAVE_FCNTL_H
-# include <fcntl.h>
+#include <fcntl.h>
#endif
#if HAVE_SYS_TYPES_H
-# include <sys/types.h>
+#include <sys/types.h>
#endif
#if HAVE_IO_H
-# include <io.h>
+#include <io.h>
#endif
-#include "tiffiop.h"
#include "tiffio.h"
+#include "tiffiop.h"
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
@@ -64,638 +64,687 @@
#endif
#ifndef O_BINARY
-# define O_BINARY 0
+#define O_BINARY 0
#endif
-typedef enum {
- PIXEL,
- BAND
+typedef enum
+{
+ PIXEL,
+ BAND
} InterleavingType;
-static uint16_t compression = (uint16_t) -1;
-static int jpegcolormode = JPEGCOLORMODE_RGB;
-static int quality = 75; /* JPEG quality */
-static uint16_t predictor = 0;
+static uint16_t compression = (uint16_t)-1;
+static int jpegcolormode = JPEGCOLORMODE_RGB;
+static int quality = 75; /* JPEG quality */
+static uint16_t predictor = 0;
static void swapBytesInScanline(void *, uint32_t, TIFFDataType);
-static int guessSize(int, TIFFDataType, _TIFF_off_t, uint32_t, int,
- uint32_t *, uint32_t *);
+static int guessSize(int, TIFFDataType, _TIFF_off_t, uint32_t, int, uint32_t *,
+ uint32_t *);
static double correlation(void *, void *, uint32_t, TIFFDataType);
static void usage(int);
-static int processCompressOptions(char*);
+static int processCompressOptions(char *);
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- uint32_t width = 0, length = 0, linebytes, bufsize;
- uint32_t nbands = 1; /* number of bands in input image*/
- _TIFF_off_t hdr_size = 0; /* size of the header to skip */
- TIFFDataType dtype = TIFF_BYTE;
- int16_t depth = 1; /* bytes per pixel in input image */
- int swab = 0; /* byte swapping flag */
- InterleavingType interleaving = 0; /* interleaving type flag */
- uint32_t rowsperstrip = (uint32_t) -1;
- uint16_t photometric = PHOTOMETRIC_MINISBLACK;
- uint16_t config = PLANARCONFIG_CONTIG;
- uint16_t fillorder = FILLORDER_LSB2MSB;
- int fd;
- char *outfilename = NULL;
- TIFF *out;
-
- uint32_t row, col, band;
- int c;
- unsigned char *buf = NULL, *buf1 = NULL;
+ uint32_t width = 0, length = 0, linebytes, bufsize;
+ uint32_t nbands = 1; /* number of bands in input image*/
+ _TIFF_off_t hdr_size = 0; /* size of the header to skip */
+ TIFFDataType dtype = TIFF_BYTE;
+ int16_t depth = 1; /* bytes per pixel in input image */
+ int swab = 0; /* byte swapping flag */
+ InterleavingType interleaving = 0; /* interleaving type flag */
+ uint32_t rowsperstrip = (uint32_t)-1;
+ uint16_t photometric = PHOTOMETRIC_MINISBLACK;
+ uint16_t config = PLANARCONFIG_CONTIG;
+ uint16_t fillorder = FILLORDER_LSB2MSB;
+ int fd;
+ char *outfilename = NULL;
+ TIFF *out;
+
+ uint32_t row, col, band;
+ int c;
+ unsigned char *buf = NULL, *buf1 = NULL;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char* optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- while ((c = getopt(argc, argv, "c:r:H:w:l:b:d:LMp:si:o:h")) != -1) {
- switch (c) {
- case 'c': /* compression scheme */
- if (!processCompressOptions(optarg))
- usage(EXIT_FAILURE);
- break;
- case 'r': /* rows/strip */
- rowsperstrip = atoi(optarg);
- break;
- case 'H': /* size of input image file header */
- hdr_size = atoi(optarg);
- break;
- case 'w': /* input image width */
- width = atoi(optarg);
- break;
- case 'l': /* input image length */
- length = atoi(optarg);
- break;
- case 'b': /* number of bands in input image */
- nbands = atoi(optarg);
- break;
- case 'd': /* type of samples in input image */
- if (strncmp(optarg, "byte", 4) == 0)
- dtype = TIFF_BYTE;
- else if (strncmp(optarg, "short", 5) == 0)
- dtype = TIFF_SHORT;
- else if (strncmp(optarg, "long", 4) == 0)
- dtype = TIFF_LONG;
- else if (strncmp(optarg, "sbyte", 5) == 0)
- dtype = TIFF_SBYTE;
- else if (strncmp(optarg, "sshort", 6) == 0)
- dtype = TIFF_SSHORT;
- else if (strncmp(optarg, "slong", 5) == 0)
- dtype = TIFF_SLONG;
- else if (strncmp(optarg, "float", 5) == 0)
- dtype = TIFF_FLOAT;
- else if (strncmp(optarg, "double", 6) == 0)
- dtype = TIFF_DOUBLE;
- else
- dtype = TIFF_BYTE;
- depth = TIFFDataWidth(dtype);
- break;
- case 'L': /* input has lsb-to-msb fillorder */
- fillorder = FILLORDER_LSB2MSB;
- break;
- case 'M': /* input has msb-to-lsb fillorder */
- fillorder = FILLORDER_MSB2LSB;
- break;
- case 'p': /* photometric interpretation */
- if (strncmp(optarg, "miniswhite", 10) == 0)
- photometric = PHOTOMETRIC_MINISWHITE;
- else if (strncmp(optarg, "minisblack", 10) == 0)
- photometric = PHOTOMETRIC_MINISBLACK;
- else if (strncmp(optarg, "rgb", 3) == 0)
- photometric = PHOTOMETRIC_RGB;
- else if (strncmp(optarg, "cmyk", 4) == 0)
- photometric = PHOTOMETRIC_SEPARATED;
- else if (strncmp(optarg, "ycbcr", 5) == 0)
- photometric = PHOTOMETRIC_YCBCR;
- else if (strncmp(optarg, "cielab", 6) == 0)
- photometric = PHOTOMETRIC_CIELAB;
- else if (strncmp(optarg, "icclab", 6) == 0)
- photometric = PHOTOMETRIC_ICCLAB;
- else if (strncmp(optarg, "itulab", 6) == 0)
- photometric = PHOTOMETRIC_ITULAB;
- else
- photometric = PHOTOMETRIC_MINISBLACK;
- break;
- case 's': /* do we need to swap bytes? */
- swab = 1;
- break;
- case 'i': /* type of interleaving */
- if (strncmp(optarg, "pixel", 4) == 0)
- interleaving = PIXEL;
- else if (strncmp(optarg, "band", 6) == 0)
- interleaving = BAND;
- else
- interleaving = 0;
- break;
- case 'o':
- outfilename = optarg;
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- default:
- break;
- }
+ while ((c = getopt(argc, argv, "c:r:H:w:l:b:d:LMp:si:o:h")) != -1)
+ {
+ switch (c)
+ {
+ case 'c': /* compression scheme */
+ if (!processCompressOptions(optarg))
+ usage(EXIT_FAILURE);
+ break;
+ case 'r': /* rows/strip */
+ rowsperstrip = atoi(optarg);
+ break;
+ case 'H': /* size of input image file header */
+ hdr_size = atoi(optarg);
+ break;
+ case 'w': /* input image width */
+ width = atoi(optarg);
+ break;
+ case 'l': /* input image length */
+ length = atoi(optarg);
+ break;
+ case 'b': /* number of bands in input image */
+ nbands = atoi(optarg);
+ break;
+ case 'd': /* type of samples in input image */
+ if (strncmp(optarg, "byte", 4) == 0)
+ dtype = TIFF_BYTE;
+ else if (strncmp(optarg, "short", 5) == 0)
+ dtype = TIFF_SHORT;
+ else if (strncmp(optarg, "long", 4) == 0)
+ dtype = TIFF_LONG;
+ else if (strncmp(optarg, "sbyte", 5) == 0)
+ dtype = TIFF_SBYTE;
+ else if (strncmp(optarg, "sshort", 6) == 0)
+ dtype = TIFF_SSHORT;
+ else if (strncmp(optarg, "slong", 5) == 0)
+ dtype = TIFF_SLONG;
+ else if (strncmp(optarg, "float", 5) == 0)
+ dtype = TIFF_FLOAT;
+ else if (strncmp(optarg, "double", 6) == 0)
+ dtype = TIFF_DOUBLE;
+ else
+ dtype = TIFF_BYTE;
+ depth = TIFFDataWidth(dtype);
+ break;
+ case 'L': /* input has lsb-to-msb fillorder */
+ fillorder = FILLORDER_LSB2MSB;
+ break;
+ case 'M': /* input has msb-to-lsb fillorder */
+ fillorder = FILLORDER_MSB2LSB;
+ break;
+ case 'p': /* photometric interpretation */
+ if (strncmp(optarg, "miniswhite", 10) == 0)
+ photometric = PHOTOMETRIC_MINISWHITE;
+ else if (strncmp(optarg, "minisblack", 10) == 0)
+ photometric = PHOTOMETRIC_MINISBLACK;
+ else if (strncmp(optarg, "rgb", 3) == 0)
+ photometric = PHOTOMETRIC_RGB;
+ else if (strncmp(optarg, "cmyk", 4) == 0)
+ photometric = PHOTOMETRIC_SEPARATED;
+ else if (strncmp(optarg, "ycbcr", 5) == 0)
+ photometric = PHOTOMETRIC_YCBCR;
+ else if (strncmp(optarg, "cielab", 6) == 0)
+ photometric = PHOTOMETRIC_CIELAB;
+ else if (strncmp(optarg, "icclab", 6) == 0)
+ photometric = PHOTOMETRIC_ICCLAB;
+ else if (strncmp(optarg, "itulab", 6) == 0)
+ photometric = PHOTOMETRIC_ITULAB;
+ else
+ photometric = PHOTOMETRIC_MINISBLACK;
+ break;
+ case 's': /* do we need to swap bytes? */
+ swab = 1;
+ break;
+ case 'i': /* type of interleaving */
+ if (strncmp(optarg, "pixel", 4) == 0)
+ interleaving = PIXEL;
+ else if (strncmp(optarg, "band", 6) == 0)
+ interleaving = BAND;
+ else
+ interleaving = 0;
+ break;
+ case 'o':
+ outfilename = optarg;
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ default:
+ break;
+ }
+ }
+
+ if (argc - optind < 2)
+ usage(EXIT_FAILURE);
+
+ fd = open(argv[optind], O_RDONLY | O_BINARY, 0);
+ if (fd < 0)
+ {
+ fprintf(stderr, "%s: %s: Cannot open input file.\n", argv[0],
+ argv[optind]);
+ return (EXIT_FAILURE);
+ }
+
+ if (nbands == 0)
+ {
+ fprintf(stderr, "The number of bands is illegal.\n");
+ return (-1);
+ }
+
+ if (guessSize(fd, dtype, hdr_size, nbands, swab, &width, &length) < 0)
+ return EXIT_FAILURE;
+
+ if (outfilename == NULL)
+ outfilename = argv[optind + 1];
+ out = TIFFOpen(outfilename, "w");
+ if (out == NULL)
+ {
+ fprintf(stderr, "%s: %s: Cannot open file for output.\n", argv[0],
+ outfilename);
+ return (EXIT_FAILURE);
+ }
+ TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
+ TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
+ TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nbands);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, depth * 8);
+ TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
+ switch (dtype)
+ {
+ case TIFF_BYTE:
+ case TIFF_SHORT:
+ case TIFF_LONG:
+ TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
+ break;
+ case TIFF_SBYTE:
+ case TIFF_SSHORT:
+ case TIFF_SLONG:
+ TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
+ break;
+ case TIFF_FLOAT:
+ case TIFF_DOUBLE:
+ TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
+ break;
+ default:
+ TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_VOID);
+ break;
+ }
+ if (compression == (uint16_t)-1)
+ compression = COMPRESSION_PACKBITS;
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
+ switch (compression)
+ {
+ case COMPRESSION_JPEG:
+ if (photometric == PHOTOMETRIC_RGB &&
+ jpegcolormode == JPEGCOLORMODE_RGB)
+ photometric = PHOTOMETRIC_YCBCR;
+ TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
+ TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
+ break;
+ case COMPRESSION_LZW:
+ case COMPRESSION_ADOBE_DEFLATE:
+ case COMPRESSION_DEFLATE:
+ if (predictor != 0)
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
+ break;
+ }
+ switch (interleaving)
+ {
+ case BAND: /* band interleaved data */
+ linebytes = width * depth;
+ buf = (unsigned char *)_TIFFmalloc(linebytes);
+ break;
+ case PIXEL: /* pixel interleaved data */
+ default:
+ linebytes = width * nbands * depth;
+ break;
+ }
+ bufsize = width * nbands * depth;
+ buf1 = (unsigned char *)_TIFFmalloc(bufsize);
+
+ rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
+ if (rowsperstrip > length)
+ {
+ rowsperstrip = length;
+ }
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
+
+ _TIFF_lseek_f(fd, hdr_size, SEEK_SET); /* Skip the file header */
+ for (row = 0; row < length; row++)
+ {
+ switch (interleaving)
+ {
+ case BAND: /* band interleaved data */
+ for (band = 0; band < nbands; band++)
+ {
+ if (_TIFF_lseek_f(
+ fd, hdr_size + (length * band + row) * linebytes,
+ SEEK_SET) == (_TIFF_off_t)-1)
+ {
+ fprintf(stderr,
+ "%s: %s: scanline %" PRIu32 ": seek error.\n",
+ argv[0], argv[optind], row);
+ break;
+ }
+ if (read(fd, buf, linebytes) < 0)
+ {
+ fprintf(stderr,
+ "%s: %s: scanline %" PRIu32 ": Read error.\n",
+ argv[0], argv[optind], row);
+ break;
+ }
+ if (swab) /* Swap bytes if needed */
+ swapBytesInScanline(buf, width, dtype);
+ for (col = 0; col < width; col++)
+ memcpy(buf1 + (col * nbands + band) * depth,
+ buf + col * depth, depth);
+ }
+ break;
+ case PIXEL: /* pixel interleaved data */
+ default:
+ if (read(fd, buf1, bufsize) < 0)
+ {
+ fprintf(stderr,
+ "%s: %s: scanline %" PRIu32 ": Read error.\n",
+ argv[0], argv[optind], row);
+ break;
+ }
+ if (swab) /* Swap bytes if needed */
+ swapBytesInScanline(buf1, width, dtype);
+ break;
}
- if (argc - optind < 2)
- usage(EXIT_FAILURE);
-
- fd = open(argv[optind], O_RDONLY|O_BINARY, 0);
- if (fd < 0) {
- fprintf(stderr, "%s: %s: Cannot open input file.\n",
- argv[0], argv[optind]);
- return (EXIT_FAILURE);
- }
-
- if (nbands == 0) {
- fprintf(stderr, "The number of bands is illegal.\n");
- return (-1);
- }
-
- if (guessSize(fd, dtype, hdr_size, nbands, swab, &width, &length) < 0)
- return EXIT_FAILURE;
-
- if (outfilename == NULL)
- outfilename = argv[optind+1];
- out = TIFFOpen(outfilename, "w");
- if (out == NULL) {
- fprintf(stderr, "%s: %s: Cannot open file for output.\n",
- argv[0], outfilename);
- return (EXIT_FAILURE);
- }
- TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
- TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
- TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nbands);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, depth * 8);
- TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
- switch (dtype) {
- case TIFF_BYTE:
- case TIFF_SHORT:
- case TIFF_LONG:
- TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
- break;
- case TIFF_SBYTE:
- case TIFF_SSHORT:
- case TIFF_SLONG:
- TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
- break;
- case TIFF_FLOAT:
- case TIFF_DOUBLE:
- TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
- break;
- default:
- TIFFSetField(out, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_VOID);
- break;
- }
- if (compression == (uint16_t) -1)
- compression = COMPRESSION_PACKBITS;
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- switch (compression) {
- case COMPRESSION_JPEG:
- if (photometric == PHOTOMETRIC_RGB
- && jpegcolormode == JPEGCOLORMODE_RGB)
- photometric = PHOTOMETRIC_YCBCR;
- TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
- TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
- break;
- case COMPRESSION_LZW:
- case COMPRESSION_ADOBE_DEFLATE:
- case COMPRESSION_DEFLATE:
- if (predictor != 0)
- TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
- break;
- }
- switch(interleaving) {
- case BAND: /* band interleaved data */
- linebytes = width * depth;
- buf = (unsigned char *)_TIFFmalloc(linebytes);
- break;
- case PIXEL: /* pixel interleaved data */
- default:
- linebytes = width * nbands * depth;
- break;
- }
- bufsize = width * nbands * depth;
- buf1 = (unsigned char *)_TIFFmalloc(bufsize);
-
- rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
- if (rowsperstrip > length) {
- rowsperstrip = length;
- }
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip );
-
- _TIFF_lseek_f(fd, hdr_size, SEEK_SET); /* Skip the file header */
- for (row = 0; row < length; row++) {
- switch(interleaving) {
- case BAND: /* band interleaved data */
- for (band = 0; band < nbands; band++) {
- if (_TIFF_lseek_f(fd,
- hdr_size + (length*band+row)*linebytes,
- SEEK_SET) == (_TIFF_off_t)-1) {
- fprintf(stderr,
- "%s: %s: scanline %"PRIu32": seek error.\n",
- argv[0], argv[optind], row);
- break;
- }
- if (read(fd, buf, linebytes) < 0) {
- fprintf(stderr,
- "%s: %s: scanline %"PRIu32": Read error.\n",
- argv[0], argv[optind], row);
- break;
- }
- if (swab) /* Swap bytes if needed */
- swapBytesInScanline(buf, width, dtype);
- for (col = 0; col < width; col++)
- memcpy(buf1 + (col*nbands+band)*depth,
- buf + col * depth, depth);
- }
- break;
- case PIXEL: /* pixel interleaved data */
- default:
- if (read(fd, buf1, bufsize) < 0) {
- fprintf(stderr,
- "%s: %s: scanline %"PRIu32": Read error.\n",
- argv[0], argv[optind], row);
- break;
- }
- if (swab) /* Swap bytes if needed */
- swapBytesInScanline(buf1, width, dtype);
- break;
- }
-
- if (TIFFWriteScanline(out, buf1, row, 0) < 0) {
- fprintf(stderr, "%s: %s: scanline %"PRIu32": Write error.\n",
- argv[0], outfilename, row);
- break;
- }
- }
- if (buf)
- _TIFFfree(buf);
- if (buf1)
- _TIFFfree(buf1);
- TIFFClose(out);
- return (EXIT_SUCCESS);
+ if (TIFFWriteScanline(out, buf1, row, 0) < 0)
+ {
+ fprintf(stderr, "%s: %s: scanline %" PRIu32 ": Write error.\n",
+ argv[0], outfilename, row);
+ break;
+ }
+ }
+ if (buf)
+ _TIFFfree(buf);
+ if (buf1)
+ _TIFFfree(buf1);
+ TIFFClose(out);
+ return (EXIT_SUCCESS);
}
-static void
-swapBytesInScanline(void *buf, uint32_t width, TIFFDataType dtype)
+static void swapBytesInScanline(void *buf, uint32_t width, TIFFDataType dtype)
{
- switch (dtype) {
- case TIFF_SHORT:
- case TIFF_SSHORT:
- TIFFSwabArrayOfShort((uint16_t*)buf,
- (unsigned long)width);
- break;
- case TIFF_LONG:
- case TIFF_SLONG:
- TIFFSwabArrayOfLong((uint32_t*)buf,
- (unsigned long)width);
- break;
- /* case TIFF_FLOAT: */ /* FIXME */
- case TIFF_DOUBLE:
- TIFFSwabArrayOfDouble((double*)buf,
- (unsigned long)width);
- break;
- default:
- break;
- }
+ switch (dtype)
+ {
+ case TIFF_SHORT:
+ case TIFF_SSHORT:
+ TIFFSwabArrayOfShort((uint16_t *)buf, (unsigned long)width);
+ break;
+ case TIFF_LONG:
+ case TIFF_SLONG:
+ TIFFSwabArrayOfLong((uint32_t *)buf, (unsigned long)width);
+ break;
+ /* case TIFF_FLOAT: */ /* FIXME */
+ case TIFF_DOUBLE:
+ TIFFSwabArrayOfDouble((double *)buf, (unsigned long)width);
+ break;
+ default:
+ break;
+ }
}
-static int
-guessSize(int fd, TIFFDataType dtype, _TIFF_off_t hdr_size, uint32_t nbands,
- int swab, uint32_t *width, uint32_t *length)
+static int guessSize(int fd, TIFFDataType dtype, _TIFF_off_t hdr_size,
+ uint32_t nbands, int swab, uint32_t *width,
+ uint32_t *length)
{
- const float longt = 40.0; /* maximum possible height/width ratio */
- char *buf1, *buf2;
- _TIFF_stat_s filestat;
- uint32_t w, h, scanlinesize, imagesize;
- uint32_t depth = TIFFDataWidth(dtype);
- double cor_coef = 0, tmp;
-
- if (_TIFF_fstat_f(fd, &filestat) == -1) {
- fprintf(stderr, "Failed to obtain file size.\n");
- return -1;
+ const float longt = 40.0; /* maximum possible height/width ratio */
+ char *buf1, *buf2;
+ _TIFF_stat_s filestat;
+ uint32_t w, h, scanlinesize, imagesize;
+ uint32_t depth = TIFFDataWidth(dtype);
+ double cor_coef = 0, tmp;
+
+ if (_TIFF_fstat_f(fd, &filestat) == -1)
+ {
+ fprintf(stderr, "Failed to obtain file size.\n");
+ return -1;
+ }
+
+ if (filestat.st_size < hdr_size)
+ {
+ fprintf(stderr, "Too large header size specified.\n");
+ return -1;
+ }
+
+ imagesize = (filestat.st_size - hdr_size) / nbands / depth;
+
+ if (*width != 0 && *length == 0)
+ {
+ fprintf(stderr, "Image height is not specified.\n");
+
+ *length = imagesize / *width;
+
+ fprintf(stderr, "Height is guessed as %" PRIu32 ".\n", *length);
+
+ return 1;
+ }
+ else if (*width == 0 && *length != 0)
+ {
+ fprintf(stderr, "Image width is not specified.\n");
+
+ *width = imagesize / *length;
+
+ fprintf(stderr, "Width is guessed as %" PRIu32 ".\n", *width);
+
+ return 1;
+ }
+ else if (*width == 0 && *length == 0)
+ {
+ unsigned int fail = 0;
+ fprintf(stderr, "Image width and height are not specified.\n");
+ w = (uint32_t)sqrt(imagesize / longt);
+ if (w == 0)
+ {
+ fprintf(stderr, "Too small image size.\n");
+ return -1;
}
- if (filestat.st_size < hdr_size) {
- fprintf(stderr, "Too large header size specified.\n");
- return -1;
- }
-
- imagesize = (filestat.st_size - hdr_size) / nbands / depth;
-
- if (*width != 0 && *length == 0) {
- fprintf(stderr, "Image height is not specified.\n");
-
- *length = imagesize / *width;
-
- fprintf(stderr, "Height is guessed as %"PRIu32".\n",
- *length);
-
- return 1;
- } else if (*width == 0 && *length != 0) {
- fprintf(stderr, "Image width is not specified.\n");
-
- *width = imagesize / *length;
-
- fprintf(stderr, "Width is guessed as %"PRIu32".\n",
- *width);
-
- return 1;
- } else if (*width == 0 && *length == 0) {
- unsigned int fail = 0;
- fprintf(stderr, "Image width and height are not specified.\n");
- w = (uint32_t) sqrt(imagesize / longt);
- if( w == 0 )
+ for (; w < sqrt(imagesize * longt); w++)
+ {
+ if (imagesize % w == 0)
+ {
+ scanlinesize = w * depth;
+ h = imagesize / w;
+ if (h < 2)
+ continue;
+ /* reads 2 lines at the middle of the image and calculate their
+ * correlation. it works for h >= 2. (in this case it will
+ * compare line 0 and line 1 */
+ buf1 = _TIFFmalloc(scanlinesize);
+ buf2 = _TIFFmalloc(scanlinesize);
+ do
{
- fprintf(stderr, "Too small image size.\n");
- return -1;
- }
+ if (_TIFF_lseek_f(
+ fd, hdr_size + (int)((h - 1) / 2) * scanlinesize,
+ SEEK_SET) == (_TIFF_off_t)-1)
+ {
+ fprintf(stderr, "seek error.\n");
+ fail = 1;
+ break;
+ }
+ /* read line (h-1)/2 */
+ if (read(fd, buf1, scanlinesize) != (long)scanlinesize)
+ {
+ fprintf(stderr, "read error.\n");
+ fail = 1;
+ break;
+ }
+ /* read line ((h-1)/2)+1 */
+ if (read(fd, buf2, scanlinesize) != (long)scanlinesize)
+ {
+ fprintf(stderr, "read error.\n");
+ fail = 1;
+ break;
+ }
+ if (swab)
+ {
+ swapBytesInScanline(buf1, w, dtype);
+ swapBytesInScanline(buf2, w, dtype);
+ }
+ if (0 == memcmp(buf1, buf2, scanlinesize))
+ {
+ *width = w, *length = h;
+ }
+ else
+ {
+ tmp = fabs(correlation(buf1, buf2, w, dtype));
+ if (tmp > cor_coef)
+ {
+ cor_coef = tmp;
+ *width = w, *length = h;
+ }
+ }
+ } while (0);
- for (;
- w < sqrt(imagesize * longt);
- w++) {
- if (imagesize % w == 0) {
- scanlinesize = w * depth;
- h = imagesize / w;
- if (h < 2)
- continue;
- /* reads 2 lines at the middle of the image and calculate their correlation.
- * it works for h >= 2. (in this case it will compare line 0 and line 1 */
- buf1 = _TIFFmalloc(scanlinesize);
- buf2 = _TIFFmalloc(scanlinesize);
- do {
- if (_TIFF_lseek_f(fd, hdr_size + (int)((h - 1)/2)*scanlinesize,
- SEEK_SET) == (_TIFF_off_t)-1) {
- fprintf(stderr, "seek error.\n");
- fail=1;
- break;
- }
- /* read line (h-1)/2 */
- if (read(fd, buf1, scanlinesize) !=
- (long) scanlinesize) {
- fprintf(stderr, "read error.\n");
- fail=1;
- break;
- }
- /* read line ((h-1)/2)+1 */
- if (read(fd, buf2, scanlinesize) !=
- (long) scanlinesize) {
- fprintf(stderr, "read error.\n");
- fail=1;
- break;
- }
- if (swab) {
- swapBytesInScanline(buf1, w, dtype);
- swapBytesInScanline(buf2, w, dtype);
- }
- if (0 == memcmp(buf1, buf2, scanlinesize)) {
- *width = w, *length = h;
- } else {
- tmp = fabs(correlation(buf1, buf2,
- w, dtype));
- if (tmp > cor_coef) {
- cor_coef = tmp;
- *width = w, *length = h;
- }
- }
- } while (0);
-
- _TIFFfree(buf1);
- _TIFFfree(buf2);
- }
- }
-
- if (fail) {
- return -1;
- }
+ _TIFFfree(buf1);
+ _TIFFfree(buf2);
+ }
+ }
- fprintf(stderr,
- "Width is guessed as %"PRIu32", height is guessed as %"PRIu32".\n",
- *width, *length);
+ if (fail)
+ {
+ return -1;
+ }
- return 1;
- } else {
- if (filestat.st_size<(_TIFF_off_t)(hdr_size+(*width)*(*length)*nbands*depth)) {
- fprintf(stderr, "Input file too small.\n");
- return -1;
- }
- }
+ fprintf(stderr,
+ "Width is guessed as %" PRIu32 ", height is guessed as %" PRIu32
+ ".\n",
+ *width, *length);
+
+ return 1;
+ }
+ else
+ {
+ if (filestat.st_size <
+ (_TIFF_off_t)(hdr_size + (*width) * (*length) * nbands * depth))
+ {
+ fprintf(stderr, "Input file too small.\n");
+ return -1;
+ }
+ }
- return 1;
+ return 1;
}
/* Calculate correlation coefficient between two numeric vectors */
-static double
-correlation(void *buf1, void *buf2, uint32_t n_elem, TIFFDataType dtype)
+static double correlation(void *buf1, void *buf2, uint32_t n_elem,
+ TIFFDataType dtype)
{
- double X, Y, M1 = 0.0, M2 = 0.0, D1 = 0.0, D2 = 0.0, K = 0.0;
- uint32_t i;
-
- switch (dtype) {
- case TIFF_BYTE:
- default:
- for (i = 0; i < n_elem; i++) {
- X = ((unsigned char *)buf1)[i];
- Y = ((unsigned char *)buf2)[i];
- M1 += X, M2 += Y;
- D1 += X * X, D2 += Y * Y;
- K += X * Y;
- }
- break;
- case TIFF_SBYTE:
- for (i = 0; i < n_elem; i++) {
- X = ((signed char *)buf1)[i];
- Y = ((signed char *)buf2)[i];
- M1 += X, M2 += Y;
- D1 += X * X, D2 += Y * Y;
- K += X * Y;
- }
- break;
- case TIFF_SHORT:
- for (i = 0; i < n_elem; i++) {
- X = ((uint16_t *)buf1)[i];
- Y = ((uint16_t *)buf2)[i];
- M1 += X, M2 += Y;
- D1 += X * X, D2 += Y * Y;
- K += X * Y;
- }
- break;
- case TIFF_SSHORT:
- for (i = 0; i < n_elem; i++) {
- X = ((int16_t *)buf1)[i];
- Y = ((int16_t *)buf2)[i];
- M1 += X, M2 += Y;
- D1 += X * X, D2 += Y * Y;
- K += X * Y;
- }
- break;
- case TIFF_LONG:
- for (i = 0; i < n_elem; i++) {
- X = ((uint32_t *)buf1)[i];
- Y = ((uint32_t *)buf2)[i];
- M1 += X, M2 += Y;
- D1 += X * X, D2 += Y * Y;
- K += X * Y;
- }
- break;
- case TIFF_SLONG:
- for (i = 0; i < n_elem; i++) {
- X = ((int32_t *)buf1)[i];
- Y = ((int32_t *)buf2)[i];
- M1 += X, M2 += Y;
- D1 += X * X, D2 += Y * Y;
- K += X * Y;
- }
- break;
- case TIFF_FLOAT:
- for (i = 0; i < n_elem; i++) {
- X = ((float *)buf1)[i];
- Y = ((float *)buf2)[i];
- M1 += X, M2 += Y;
- D1 += X * X, D2 += Y * Y;
- K += X * Y;
- }
- break;
- case TIFF_DOUBLE:
- for (i = 0; i < n_elem; i++) {
- X = ((double *)buf1)[i];
- Y = ((double *)buf2)[i];
- M1 += X, M2 += Y;
- D1 += X * X, D2 += Y * Y;
- K += X * Y;
- }
- break;
- }
-
- M1 /= n_elem;
- M2 /= n_elem;
- D1 -= M1 * M1 * n_elem;
- D2 -= M2 * M2 * n_elem;
- if (D1 * D2 == 0.0) return 0.0; /* avoid divide by zero */
- K = (K - M1 * M2 * n_elem) / sqrt(D1 * D2);
-
- return K;
+ double X, Y, M1 = 0.0, M2 = 0.0, D1 = 0.0, D2 = 0.0, K = 0.0;
+ uint32_t i;
+
+ switch (dtype)
+ {
+ case TIFF_BYTE:
+ default:
+ for (i = 0; i < n_elem; i++)
+ {
+ X = ((unsigned char *)buf1)[i];
+ Y = ((unsigned char *)buf2)[i];
+ M1 += X, M2 += Y;
+ D1 += X * X, D2 += Y * Y;
+ K += X * Y;
+ }
+ break;
+ case TIFF_SBYTE:
+ for (i = 0; i < n_elem; i++)
+ {
+ X = ((signed char *)buf1)[i];
+ Y = ((signed char *)buf2)[i];
+ M1 += X, M2 += Y;
+ D1 += X * X, D2 += Y * Y;
+ K += X * Y;
+ }
+ break;
+ case TIFF_SHORT:
+ for (i = 0; i < n_elem; i++)
+ {
+ X = ((uint16_t *)buf1)[i];
+ Y = ((uint16_t *)buf2)[i];
+ M1 += X, M2 += Y;
+ D1 += X * X, D2 += Y * Y;
+ K += X * Y;
+ }
+ break;
+ case TIFF_SSHORT:
+ for (i = 0; i < n_elem; i++)
+ {
+ X = ((int16_t *)buf1)[i];
+ Y = ((int16_t *)buf2)[i];
+ M1 += X, M2 += Y;
+ D1 += X * X, D2 += Y * Y;
+ K += X * Y;
+ }
+ break;
+ case TIFF_LONG:
+ for (i = 0; i < n_elem; i++)
+ {
+ X = ((uint32_t *)buf1)[i];
+ Y = ((uint32_t *)buf2)[i];
+ M1 += X, M2 += Y;
+ D1 += X * X, D2 += Y * Y;
+ K += X * Y;
+ }
+ break;
+ case TIFF_SLONG:
+ for (i = 0; i < n_elem; i++)
+ {
+ X = ((int32_t *)buf1)[i];
+ Y = ((int32_t *)buf2)[i];
+ M1 += X, M2 += Y;
+ D1 += X * X, D2 += Y * Y;
+ K += X * Y;
+ }
+ break;
+ case TIFF_FLOAT:
+ for (i = 0; i < n_elem; i++)
+ {
+ X = ((float *)buf1)[i];
+ Y = ((float *)buf2)[i];
+ M1 += X, M2 += Y;
+ D1 += X * X, D2 += Y * Y;
+ K += X * Y;
+ }
+ break;
+ case TIFF_DOUBLE:
+ for (i = 0; i < n_elem; i++)
+ {
+ X = ((double *)buf1)[i];
+ Y = ((double *)buf2)[i];
+ M1 += X, M2 += Y;
+ D1 += X * X, D2 += Y * Y;
+ K += X * Y;
+ }
+ break;
+ }
+
+ M1 /= n_elem;
+ M2 /= n_elem;
+ D1 -= M1 * M1 * n_elem;
+ D2 -= M2 * M2 * n_elem;
+ if (D1 * D2 == 0.0)
+ return 0.0; /* avoid divide by zero */
+ K = (K - M1 * M2 * n_elem) / sqrt(D1 * D2);
+
+ return K;
}
-static int
-processCompressOptions(char* opt)
+static int processCompressOptions(char *opt)
{
- if (strcmp(opt, "none") == 0)
- compression = COMPRESSION_NONE;
- else if (strcmp(opt, "packbits") == 0)
- compression = COMPRESSION_PACKBITS;
- else if (strncmp(opt, "jpeg", 4) == 0) {
- char* cp = strchr(opt, ':');
-
- compression = COMPRESSION_JPEG;
- while( cp )
- {
- if (isdigit((int)cp[1]))
- quality = atoi(cp+1);
- else if (cp[1] == 'r' )
- jpegcolormode = JPEGCOLORMODE_RAW;
- else
- usage(EXIT_FAILURE);
-
- cp = strchr(cp+1,':');
- }
- } else if (strncmp(opt, "lzw", 3) == 0) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_LZW;
- } else if (strncmp(opt, "zip", 3) == 0) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_ADOBE_DEFLATE;
- } else
- return (0);
- return (1);
+ if (strcmp(opt, "none") == 0)
+ compression = COMPRESSION_NONE;
+ else if (strcmp(opt, "packbits") == 0)
+ compression = COMPRESSION_PACKBITS;
+ else if (strncmp(opt, "jpeg", 4) == 0)
+ {
+ char *cp = strchr(opt, ':');
+
+ compression = COMPRESSION_JPEG;
+ while (cp)
+ {
+ if (isdigit((int)cp[1]))
+ quality = atoi(cp + 1);
+ else if (cp[1] == 'r')
+ jpegcolormode = JPEGCOLORMODE_RAW;
+ else
+ usage(EXIT_FAILURE);
+
+ cp = strchr(cp + 1, ':');
+ }
+ }
+ else if (strncmp(opt, "lzw", 3) == 0)
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_LZW;
+ }
+ else if (strncmp(opt, "zip", 3) == 0)
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_ADOBE_DEFLATE;
+ }
+ else
+ return (0);
+ return (1);
}
static const char usage_info[] =
-"Create a TIFF file from raw data\n\n"
-"usage: raw2tiff [options] input.raw output.tif\n"
-"where options are:\n"
-" -L input data has LSB2MSB bit order (default)\n"
-" -M input data has MSB2LSB bit order\n"
-" -r # make each strip have no more than # rows\n"
-" -H # size of input image file header in bytes (0 by default)\n"
-" -w # width of input image in pixels\n"
-" -l # length of input image in lines\n"
-" -b # number of bands in input image (1 by default)\n"
-"\n"
-" -d data_type type of samples in input image\n"
-"where data_type may be:\n"
-" byte 8-bit unsigned integer (default)\n"
-" short 16-bit unsigned integer\n"
-" long 32-bit unsigned integer\n"
-" sbyte 8-bit signed integer\n"
-" sshort 16-bit signed integer\n"
-" slong 32-bit signed integer\n"
-" float 32-bit IEEE floating point\n"
-" double 64-bit IEEE floating point\n"
-"\n"
-" -p photo photometric interpretation (color space) of the input image\n"
-"where photo may be:\n"
-" miniswhite white color represented with 0 value\n"
-" minisblack black color represented with 0 value (default)\n"
-" rgb image has RGB color model\n"
-" cmyk image has CMYK (separated) color model\n"
-" ycbcr image has YCbCr color model\n"
-" cielab image has CIE L*a*b color model\n"
-" icclab image has ICC L*a*b color model\n"
-" itulab image has ITU L*a*b color model\n"
-"\n"
-" -s swap bytes fetched from input file\n"
-"\n"
-" -i config type of samples interleaving in input image\n"
-"where config may be:\n"
-" pixel pixel interleaved data (default)\n"
-" band band interleaved data\n"
-"\n"
+ "Create a TIFF file from raw data\n\n"
+ "usage: raw2tiff [options] input.raw output.tif\n"
+ "where options are:\n"
+ " -L input data has LSB2MSB bit order (default)\n"
+ " -M input data has MSB2LSB bit order\n"
+ " -r # make each strip have no more than # rows\n"
+ " -H # size of input image file header in bytes (0 by "
+ "default)\n"
+ " -w # width of input image in pixels\n"
+ " -l # length of input image in lines\n"
+ " -b # number of bands in input image (1 by default)\n"
+ "\n"
+ " -d data_type type of samples in input image\n"
+ "where data_type may be:\n"
+ " byte 8-bit unsigned integer (default)\n"
+ " short 16-bit unsigned integer\n"
+ " long 32-bit unsigned integer\n"
+ " sbyte 8-bit signed integer\n"
+ " sshort 16-bit signed integer\n"
+ " slong 32-bit signed integer\n"
+ " float 32-bit IEEE floating point\n"
+ " double 64-bit IEEE floating point\n"
+ "\n"
+ " -p photo photometric interpretation (color space) of the input image\n"
+ "where photo may be:\n"
+ " miniswhite white color represented with 0 value\n"
+ " minisblack black color represented with 0 value (default)\n"
+ " rgb image has RGB color model\n"
+ " cmyk image has CMYK (separated) color model\n"
+ " ycbcr image has YCbCr color model\n"
+ " cielab image has CIE L*a*b color model\n"
+ " icclab image has ICC L*a*b color model\n"
+ " itulab image has ITU L*a*b color model\n"
+ "\n"
+ " -s swap bytes fetched from input file\n"
+ "\n"
+ " -i config type of samples interleaving in input image\n"
+ "where config may be:\n"
+ " pixel pixel interleaved data (default)\n"
+ " band band interleaved data\n"
+ "\n"
#ifdef LZW_SUPPORT
-" -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
-/* " LZW options:\n" */
-" # set predictor value\n"
-" For example, -c lzw:2 for LZW-encoded data with horizontal differencing\n"
+ " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
+ /* " LZW options:\n" */
+ " # set predictor value\n"
+ " For example, -c lzw:2 for LZW-encoded data with horizontal "
+ "differencing\n"
#endif
#ifdef ZIP_SUPPORT
-" -c zip[:opts] compress output with deflate encoding\n"
-/* " Deflate (ZIP) options:\n" */
-" # set predictor value\n"
+ " -c zip[:opts] compress output with deflate encoding\n"
+ /* " Deflate (ZIP) options:\n" */
+ " # set predictor value\n"
#endif
#ifdef JPEG_SUPPORT
-" -c jpeg[:opts] compress output with JPEG encoding\n"
-/* " JPEG options:\n" */
-" # set compression quality level (0-100, default 75)\n"
-" r output color image as RGB rather than YCbCr\n"
-" For example, -c jpeg:r:50 for JPEG-encoded RGB data with 50% comp. quality\n"
+ " -c jpeg[:opts] compress output with JPEG encoding\n"
+ /* " JPEG options:\n" */
+ " # set compression quality level (0-100, default 75)\n"
+ " r output color image as RGB rather than YCbCr\n"
+ " For example, -c jpeg:r:50 for JPEG-encoded RGB data with 50% comp. "
+ "quality\n"
#endif
#ifdef PACKBITS_SUPPORT
-" -c packbits compress output with packbits encoding\n"
+ " -c packbits compress output with packbits encoding\n"
#endif
-#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(JPEG_SUPPORT) || defined(PACKBITS_SUPPORT)
-" -c none use no compression algorithm on output\n"
+#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(JPEG_SUPPORT) || \
+ defined(PACKBITS_SUPPORT)
+ " -c none use no compression algorithm on output\n"
#endif
-"\n"
-" -o out.tif write output to out.tif\n"
-" -h this help message\n"
-;
+ "\n"
+ " -o out.tif write output to out.tif\n"
+ " -h this help message\n";
-static void
-usage(int code)
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
diff --git a/tools/rgb2ycbcr.c b/tools/rgb2ycbcr.c
index fbb712ff..d4eabbb1 100644
--- a/tools/rgb2ycbcr.c
+++ b/tools/rgb2ycbcr.c
@@ -2,39 +2,39 @@
* Copyright (c) 1991-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
#include <stdio.h>
-#include <string.h>
#include <stdlib.h>
+#include <string.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
-#include "tiffiop.h"
#include "tiffio.h"
+#include "tiffiop.h"
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
@@ -43,173 +43,177 @@
#define EXIT_FAILURE 1
#endif
-#define streq(a,b) (strcmp(a,b) == 0)
-#define CopyField(tag, v) \
- if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
+#define streq(a, b) (strcmp(a, b) == 0)
+#define CopyField(tag, v) \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v)
#ifndef howmany
-#define howmany(x, y) (((x)+((y)-1))/(y))
+#define howmany(x, y) (((x) + ((y)-1)) / (y))
#endif
-#define roundup(x, y) (howmany(x,y)*((uint32_t)(y)))
+#define roundup(x, y) (howmany(x, y) * ((uint32_t)(y)))
-#define LumaRed ycbcrCoeffs[0]
-#define LumaGreen ycbcrCoeffs[1]
-#define LumaBlue ycbcrCoeffs[2]
+#define LumaRed ycbcrCoeffs[0]
+#define LumaGreen ycbcrCoeffs[1]
+#define LumaBlue ycbcrCoeffs[2]
-uint16_t compression = COMPRESSION_PACKBITS;
-uint32_t rowsperstrip = (uint32_t) -1;
+uint16_t compression = COMPRESSION_PACKBITS;
+uint32_t rowsperstrip = (uint32_t)-1;
-uint16_t horizSubSampling = 2; /* YCbCr horizontal subsampling */
-uint16_t vertSubSampling = 2; /* YCbCr vertical subsampling */
-float ycbcrCoeffs[3] = { .299F, .587F, .114F };
+uint16_t horizSubSampling = 2; /* YCbCr horizontal subsampling */
+uint16_t vertSubSampling = 2; /* YCbCr vertical subsampling */
+float ycbcrCoeffs[3] = {.299F, .587F, .114F};
/* default coding range is CCIR Rec 601-1 with no headroom/footroom */
-float refBlackWhite[6] = { 0.F, 255.F, 128.F, 255.F, 128.F, 255.F };
+float refBlackWhite[6] = {0.F, 255.F, 128.F, 255.F, 128.F, 255.F};
-static int tiffcvt(TIFF* in, TIFF* out);
-static void usage(int code);
-static void setupLumaTables(void);
+static int tiffcvt(TIFF *in, TIFF *out);
+static void usage(int code);
+static void setupLumaTables(void);
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- TIFF *in, *out;
- int c;
+ TIFF *in, *out;
+ int c;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char *optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- while ((c = getopt(argc, argv, "c:h:r:v:z")) != -1)
- switch (c) {
- case 'c':
- if (streq(optarg, "none"))
- compression = COMPRESSION_NONE;
- else if (streq(optarg, "packbits"))
- compression = COMPRESSION_PACKBITS;
- else if (streq(optarg, "lzw"))
- compression = COMPRESSION_LZW;
- else if (streq(optarg, "jpeg"))
- compression = COMPRESSION_JPEG;
- else if (streq(optarg, "zip"))
- compression = COMPRESSION_ADOBE_DEFLATE;
- else
- usage(EXIT_FAILURE);
- break;
- case 'h':
- horizSubSampling = atoi(optarg);
- if( horizSubSampling != 1 && horizSubSampling != 2 && horizSubSampling != 4 )
+ while ((c = getopt(argc, argv, "c:h:r:v:z")) != -1)
+ switch (c)
+ {
+ case 'c':
+ if (streq(optarg, "none"))
+ compression = COMPRESSION_NONE;
+ else if (streq(optarg, "packbits"))
+ compression = COMPRESSION_PACKBITS;
+ else if (streq(optarg, "lzw"))
+ compression = COMPRESSION_LZW;
+ else if (streq(optarg, "jpeg"))
+ compression = COMPRESSION_JPEG;
+ else if (streq(optarg, "zip"))
+ compression = COMPRESSION_ADOBE_DEFLATE;
+ else
+ usage(EXIT_FAILURE);
+ break;
+ case 'h':
+ horizSubSampling = atoi(optarg);
+ if (horizSubSampling != 1 && horizSubSampling != 2 &&
+ horizSubSampling != 4)
+ usage(EXIT_FAILURE);
+ break;
+ case 'v':
+ vertSubSampling = atoi(optarg);
+ if (vertSubSampling != 1 && vertSubSampling != 2 &&
+ vertSubSampling != 4)
+ usage(EXIT_FAILURE);
+ break;
+ case 'r':
+ rowsperstrip = atoi(optarg);
+ break;
+ case 'z': /* CCIR Rec 601-1 w/ headroom/footroom */
+ refBlackWhite[0] = 16.;
+ refBlackWhite[1] = 235.;
+ refBlackWhite[2] = 128.;
+ refBlackWhite[3] = 240.;
+ refBlackWhite[4] = 128.;
+ refBlackWhite[5] = 240.;
+ break;
+ case '?':
usage(EXIT_FAILURE);
- break;
- case 'v':
- vertSubSampling = atoi(optarg);
- if( vertSubSampling != 1 && vertSubSampling != 2 && vertSubSampling != 4 )
- usage(EXIT_FAILURE);
- break;
- case 'r':
- rowsperstrip = atoi(optarg);
- break;
- case 'z': /* CCIR Rec 601-1 w/ headroom/footroom */
- refBlackWhite[0] = 16.;
- refBlackWhite[1] = 235.;
- refBlackWhite[2] = 128.;
- refBlackWhite[3] = 240.;
- refBlackWhite[4] = 128.;
- refBlackWhite[5] = 240.;
- break;
- case '?':
- usage(EXIT_FAILURE);
- /*NOTREACHED*/
- }
- if (argc - optind < 2)
- usage(EXIT_FAILURE);
- out = TIFFOpen(argv[argc-1], "w");
- if (out == NULL)
- return (EXIT_FAILURE);
- setupLumaTables();
- for (; optind < argc-1; optind++) {
- in = TIFFOpen(argv[optind], "r");
- if (in != NULL) {
- do {
- if (!tiffcvt(in, out) ||
- !TIFFWriteDirectory(out)) {
- (void) TIFFClose(out);
- (void) TIFFClose(in);
- return (1);
- }
- } while (TIFFReadDirectory(in));
- (void) TIFFClose(in);
- }
- }
- (void) TIFFClose(out);
- return (EXIT_SUCCESS);
+ /*NOTREACHED*/
+ }
+ if (argc - optind < 2)
+ usage(EXIT_FAILURE);
+ out = TIFFOpen(argv[argc - 1], "w");
+ if (out == NULL)
+ return (EXIT_FAILURE);
+ setupLumaTables();
+ for (; optind < argc - 1; optind++)
+ {
+ in = TIFFOpen(argv[optind], "r");
+ if (in != NULL)
+ {
+ do
+ {
+ if (!tiffcvt(in, out) || !TIFFWriteDirectory(out))
+ {
+ (void)TIFFClose(out);
+ (void)TIFFClose(in);
+ return (1);
+ }
+ } while (TIFFReadDirectory(in));
+ (void)TIFFClose(in);
+ }
+ }
+ (void)TIFFClose(out);
+ return (EXIT_SUCCESS);
}
-float *lumaRed;
-float *lumaGreen;
-float *lumaBlue;
-float D1, D2;
-int Yzero;
+float *lumaRed;
+float *lumaGreen;
+float *lumaBlue;
+float D1, D2;
+int Yzero;
-static float*
-setupLuma(float c)
+static float *setupLuma(float c)
{
- float *v = (float *)_TIFFmalloc(256 * sizeof (float));
- int i;
- for (i = 0; i < 256; i++)
- v[i] = c * i;
- return (v);
+ float *v = (float *)_TIFFmalloc(256 * sizeof(float));
+ int i;
+ for (i = 0; i < 256; i++)
+ v[i] = c * i;
+ return (v);
}
-static unsigned
-V2Code(float f, float RB, float RW, int CR)
+static unsigned V2Code(float f, float RB, float RW, int CR)
{
- unsigned int c = (unsigned int)((((f)*(RW-RB)/CR)+RB)+.5);
- return (c > 255 ? 255 : c);
+ unsigned int c = (unsigned int)((((f) * (RW - RB) / CR) + RB) + .5);
+ return (c > 255 ? 255 : c);
}
-static void
-setupLumaTables(void)
+static void setupLumaTables(void)
{
- lumaRed = setupLuma(LumaRed);
- lumaGreen = setupLuma(LumaGreen);
- lumaBlue = setupLuma(LumaBlue);
- D1 = 1.F/(2.F - 2.F*LumaBlue);
- D2 = 1.F/(2.F - 2.F*LumaRed);
- Yzero = V2Code(0, refBlackWhite[0], refBlackWhite[1], 255);
+ lumaRed = setupLuma(LumaRed);
+ lumaGreen = setupLuma(LumaGreen);
+ lumaBlue = setupLuma(LumaBlue);
+ D1 = 1.F / (2.F - 2.F * LumaBlue);
+ D2 = 1.F / (2.F - 2.F * LumaRed);
+ Yzero = V2Code(0, refBlackWhite[0], refBlackWhite[1], 255);
}
-static void
-cvtClump(unsigned char* op, uint32_t* raster, uint32_t ch, uint32_t cw, uint32_t w)
+static void cvtClump(unsigned char *op, uint32_t *raster, uint32_t ch,
+ uint32_t cw, uint32_t w)
{
- float Y, Cb = 0, Cr = 0;
- uint32_t j, k;
- /*
- * Convert ch-by-cw block of RGB
- * to YCbCr and sample accordingly.
- */
- for (k = 0; k < ch; k++) {
- for (j = 0; j < cw; j++) {
- uint32_t RGB = (raster - k * w)[j];
- Y = lumaRed[TIFFGetR(RGB)] +
- lumaGreen[TIFFGetG(RGB)] +
- lumaBlue[TIFFGetB(RGB)];
- /* accumulate chrominance */
- Cb += (TIFFGetB(RGB) - Y) * D1;
- Cr += (TIFFGetR(RGB) - Y) * D2;
- /* emit luminence */
- *op++ = V2Code(Y,
- refBlackWhite[0], refBlackWhite[1], 255);
- }
- for (; j < horizSubSampling; j++)
- *op++ = Yzero;
- }
- for (; k < vertSubSampling; k++) {
- for (j = 0; j < horizSubSampling; j++)
- *op++ = Yzero;
- }
- /* emit sampled chrominance values */
- *op++ = V2Code(Cb / (ch*cw), refBlackWhite[2], refBlackWhite[3], 127);
- *op++ = V2Code(Cr / (ch*cw), refBlackWhite[4], refBlackWhite[5], 127);
+ float Y, Cb = 0, Cr = 0;
+ uint32_t j, k;
+ /*
+ * Convert ch-by-cw block of RGB
+ * to YCbCr and sample accordingly.
+ */
+ for (k = 0; k < ch; k++)
+ {
+ for (j = 0; j < cw; j++)
+ {
+ uint32_t RGB = (raster - k * w)[j];
+ Y = lumaRed[TIFFGetR(RGB)] + lumaGreen[TIFFGetG(RGB)] +
+ lumaBlue[TIFFGetB(RGB)];
+ /* accumulate chrominance */
+ Cb += (TIFFGetB(RGB) - Y) * D1;
+ Cr += (TIFFGetR(RGB) - Y) * D2;
+ /* emit luminence */
+ *op++ = V2Code(Y, refBlackWhite[0], refBlackWhite[1], 255);
+ }
+ for (; j < horizSubSampling; j++)
+ *op++ = Yzero;
+ }
+ for (; k < vertSubSampling; k++)
+ {
+ for (j = 0; j < horizSubSampling; j++)
+ *op++ = Yzero;
+ }
+ /* emit sampled chrominance values */
+ *op++ = V2Code(Cb / (ch * cw), refBlackWhite[2], refBlackWhite[3], 127);
+ *op++ = V2Code(Cr / (ch * cw), refBlackWhite[4], refBlackWhite[5], 127);
}
#undef LumaRed
#undef LumaGreen
@@ -220,185 +224,194 @@ cvtClump(unsigned char* op, uint32_t* raster, uint32_t ch, uint32_t cw, uint32_t
* Convert a strip of RGB data to YCbCr and
* sample to generate the output data.
*/
-static void
-cvtStrip(unsigned char* op, uint32_t* raster, uint32_t nrows, uint32_t width)
+static void cvtStrip(unsigned char *op, uint32_t *raster, uint32_t nrows,
+ uint32_t width)
{
- uint32_t x;
- int clumpSize = vertSubSampling * horizSubSampling + 2;
- uint32_t *tp;
-
- for (; nrows >= vertSubSampling; nrows -= vertSubSampling) {
- tp = raster;
- for (x = width; x >= horizSubSampling; x -= horizSubSampling) {
- cvtClump(op, tp,
- vertSubSampling, horizSubSampling, width);
- op += clumpSize;
- tp += horizSubSampling;
- }
- if (x > 0) {
- cvtClump(op, tp, vertSubSampling, x, width);
- op += clumpSize;
- }
- raster -= vertSubSampling*width;
- }
- if (nrows > 0) {
- tp = raster;
- for (x = width; x >= horizSubSampling; x -= horizSubSampling) {
- cvtClump(op, tp, nrows, horizSubSampling, width);
- op += clumpSize;
- tp += horizSubSampling;
- }
- if (x > 0)
- cvtClump(op, tp, nrows, x, width);
- }
+ uint32_t x;
+ int clumpSize = vertSubSampling * horizSubSampling + 2;
+ uint32_t *tp;
+
+ for (; nrows >= vertSubSampling; nrows -= vertSubSampling)
+ {
+ tp = raster;
+ for (x = width; x >= horizSubSampling; x -= horizSubSampling)
+ {
+ cvtClump(op, tp, vertSubSampling, horizSubSampling, width);
+ op += clumpSize;
+ tp += horizSubSampling;
+ }
+ if (x > 0)
+ {
+ cvtClump(op, tp, vertSubSampling, x, width);
+ op += clumpSize;
+ }
+ raster -= vertSubSampling * width;
+ }
+ if (nrows > 0)
+ {
+ tp = raster;
+ for (x = width; x >= horizSubSampling; x -= horizSubSampling)
+ {
+ cvtClump(op, tp, nrows, horizSubSampling, width);
+ op += clumpSize;
+ tp += horizSubSampling;
+ }
+ if (x > 0)
+ cvtClump(op, tp, nrows, x, width);
+ }
}
-static int
-cvtRaster(TIFF* tif, uint32_t* raster, uint32_t width, uint32_t height)
+static int cvtRaster(TIFF *tif, uint32_t *raster, uint32_t width,
+ uint32_t height)
{
- uint32_t y;
- tstrip_t strip = 0;
- tsize_t cc, acc;
- unsigned char* buf;
- uint32_t rwidth = roundup(width, horizSubSampling);
- uint32_t rheight = roundup(height, vertSubSampling);
- uint32_t nrows = (rowsperstrip > rheight ? rheight : rowsperstrip);
- uint32_t rnrows = roundup(nrows, vertSubSampling);
-
- cc = rnrows*rwidth +
- 2*((rnrows*rwidth) / (horizSubSampling*vertSubSampling));
- buf = (unsigned char*)_TIFFmalloc(cc);
- // FIXME unchecked malloc
- for (y = height; (int32_t) y > 0; y -= nrows) {
- uint32_t nr = (y > nrows ? nrows : y);
- cvtStrip(buf, raster + (y-1)*width, nr, width);
- nr = roundup(nr, vertSubSampling);
- acc = nr*rwidth +
- 2*((nr*rwidth)/(horizSubSampling*vertSubSampling));
- if (!TIFFWriteEncodedStrip(tif, strip++, buf, acc)) {
- _TIFFfree(buf);
- return (0);
- }
- }
- _TIFFfree(buf);
- return (1);
+ uint32_t y;
+ tstrip_t strip = 0;
+ tsize_t cc, acc;
+ unsigned char *buf;
+ uint32_t rwidth = roundup(width, horizSubSampling);
+ uint32_t rheight = roundup(height, vertSubSampling);
+ uint32_t nrows = (rowsperstrip > rheight ? rheight : rowsperstrip);
+ uint32_t rnrows = roundup(nrows, vertSubSampling);
+
+ cc = rnrows * rwidth +
+ 2 * ((rnrows * rwidth) / (horizSubSampling * vertSubSampling));
+ buf = (unsigned char *)_TIFFmalloc(cc);
+ // FIXME unchecked malloc
+ for (y = height; (int32_t)y > 0; y -= nrows)
+ {
+ uint32_t nr = (y > nrows ? nrows : y);
+ cvtStrip(buf, raster + (y - 1) * width, nr, width);
+ nr = roundup(nr, vertSubSampling);
+ acc = nr * rwidth +
+ 2 * ((nr * rwidth) / (horizSubSampling * vertSubSampling));
+ if (!TIFFWriteEncodedStrip(tif, strip++, buf, acc))
+ {
+ _TIFFfree(buf);
+ return (0);
+ }
+ }
+ _TIFFfree(buf);
+ return (1);
}
-static int
-tiffcvt(TIFF* in, TIFF* out)
+static int tiffcvt(TIFF *in, TIFF *out)
{
- uint32_t width, height; /* image width & height */
- uint32_t* raster; /* retrieve RGBA image */
- uint16_t shortv;
- float floatv;
- char *stringv;
- uint32_t longv;
- int result;
- size_t pixel_count;
-
- TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width);
- TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height);
- pixel_count = width * height;
-
- /* XXX: Check the integer overflow. */
- if (!width || !height || pixel_count / width != height) {
- TIFFError(TIFFFileName(in),
- "Malformed input file; "
- "can't allocate buffer for raster of %"PRIu32"x%"PRIu32" size",
- width, height);
- return 0;
- }
-
- raster = (uint32_t*)_TIFFCheckMalloc(in, pixel_count, sizeof(uint32_t),
- "raster buffer");
- if (raster == 0) {
- TIFFError(TIFFFileName(in),
- "Failed to allocate buffer (%"TIFF_SIZE_FORMAT" elements of %"TIFF_SIZE_FORMAT" each)",
- pixel_count,
- sizeof(uint32_t));
- return (0);
- }
-
- if (!TIFFReadRGBAImage(in, width, height, raster, 0)) {
- _TIFFfree(raster);
- return (0);
- }
-
- CopyField(TIFFTAG_SUBFILETYPE, longv);
- TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
- TIFFSetField(out, TIFFTAG_IMAGELENGTH, height);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
- if (compression == COMPRESSION_JPEG)
- TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
- CopyField(TIFFTAG_FILLORDER, shortv);
- TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
- CopyField(TIFFTAG_XRESOLUTION, floatv);
- CopyField(TIFFTAG_YRESOLUTION, floatv);
- CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
- { char buf[2048];
- char *cp = strrchr(TIFFFileName(in), '/');
- snprintf(buf, sizeof(buf), "YCbCr conversion of %s",
- cp ? cp+1 : TIFFFileName(in));
- TIFFSetField(out, TIFFTAG_IMAGEDESCRIPTION, buf);
- }
- TIFFSetField(out, TIFFTAG_SOFTWARE, TIFFGetVersion());
- CopyField(TIFFTAG_DOCUMENTNAME, stringv);
-
- TIFFSetField(out, TIFFTAG_REFERENCEBLACKWHITE, refBlackWhite);
- TIFFSetField(out, TIFFTAG_YCBCRSUBSAMPLING,
- horizSubSampling, vertSubSampling);
- TIFFSetField(out, TIFFTAG_YCBCRPOSITIONING, YCBCRPOSITION_CENTERED);
- TIFFSetField(out, TIFFTAG_YCBCRCOEFFICIENTS, ycbcrCoeffs);
- rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
-
- result = cvtRaster(out, raster, width, height);
+ uint32_t width, height; /* image width & height */
+ uint32_t *raster; /* retrieve RGBA image */
+ uint16_t shortv;
+ float floatv;
+ char *stringv;
+ uint32_t longv;
+ int result;
+ size_t pixel_count;
+
+ TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width);
+ TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height);
+ pixel_count = width * height;
+
+ /* XXX: Check the integer overflow. */
+ if (!width || !height || pixel_count / width != height)
+ {
+ TIFFError(TIFFFileName(in),
+ "Malformed input file; "
+ "can't allocate buffer for raster of %" PRIu32 "x%" PRIu32
+ " size",
+ width, height);
+ return 0;
+ }
+
+ raster = (uint32_t *)_TIFFCheckMalloc(in, pixel_count, sizeof(uint32_t),
+ "raster buffer");
+ if (raster == 0)
+ {
+ TIFFError(TIFFFileName(in),
+ "Failed to allocate buffer (%" TIFF_SIZE_FORMAT
+ " elements of %" TIFF_SIZE_FORMAT " each)",
+ pixel_count, sizeof(uint32_t));
+ return (0);
+ }
+
+ if (!TIFFReadRGBAImage(in, width, height, raster, 0))
+ {
_TIFFfree(raster);
- return result;
+ return (0);
+ }
+
+ CopyField(TIFFTAG_SUBFILETYPE, longv);
+ TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
+ TIFFSetField(out, TIFFTAG_IMAGELENGTH, height);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
+ if (compression == COMPRESSION_JPEG)
+ TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
+ CopyField(TIFFTAG_FILLORDER, shortv);
+ TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
+ CopyField(TIFFTAG_XRESOLUTION, floatv);
+ CopyField(TIFFTAG_YRESOLUTION, floatv);
+ CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+ {
+ char buf[2048];
+ char *cp = strrchr(TIFFFileName(in), '/');
+ snprintf(buf, sizeof(buf), "YCbCr conversion of %s",
+ cp ? cp + 1 : TIFFFileName(in));
+ TIFFSetField(out, TIFFTAG_IMAGEDESCRIPTION, buf);
+ }
+ TIFFSetField(out, TIFFTAG_SOFTWARE, TIFFGetVersion());
+ CopyField(TIFFTAG_DOCUMENTNAME, stringv);
+
+ TIFFSetField(out, TIFFTAG_REFERENCEBLACKWHITE, refBlackWhite);
+ TIFFSetField(out, TIFFTAG_YCBCRSUBSAMPLING, horizSubSampling,
+ vertSubSampling);
+ TIFFSetField(out, TIFFTAG_YCBCRPOSITIONING, YCBCRPOSITION_CENTERED);
+ TIFFSetField(out, TIFFTAG_YCBCRCOEFFICIENTS, ycbcrCoeffs);
+ rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
+
+ result = cvtRaster(out, raster, width, height);
+ _TIFFfree(raster);
+ return result;
}
-const char* usage_info[] = {
-/* Help information format modified for the sake of consistency with the other tiff tools */
-/* "usage: rgb2ycbcr [-c comp] [-r rows] [-h N] [-v N] input... output\n", */
-/* "where comp is one of the following compression algorithms:\n", */
-"Convert RGB color, greyscale, or bi-level TIFF images to YCbCr images\n\n"
-"usage: rgb2ycbcr [options] input output",
-"where options are:",
+const char *usage_info[] = {
+ /* Help information format modified for the sake of consistency with the
+ other tiff tools */
+ /* "usage: rgb2ycbcr [-c comp] [-r rows] [-h N] [-v N] input...
+ output\n", */
+ /* "where comp is one of the following compression algorithms:\n", */
+ "Convert RGB color, greyscale, or bi-level TIFF images to YCbCr images\n\n"
+ "usage: rgb2ycbcr [options] input output",
+ "where options are:",
#ifdef JPEG_SUPPORT
-" -c jpeg JPEG encoding",
+ " -c jpeg JPEG encoding",
#endif
#ifdef ZIP_SUPPORT
-" -c zip Zip/Deflate encoding",
+ " -c zip Zip/Deflate encoding",
#endif
#ifdef LZW_SUPPORT
-" -c lzw Lempel-Ziv & Welch encoding",
+ " -c lzw Lempel-Ziv & Welch encoding",
#endif
#ifdef PACKBITS_SUPPORT
-" -c packbits PackBits encoding (default)",
+ " -c packbits PackBits encoding (default)",
#endif
-#if defined(JPEG_SUPPORT) || defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(PACKBITS_SUPPORT)
-" -c none no compression",
+#if defined(JPEG_SUPPORT) || defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || \
+ defined(PACKBITS_SUPPORT)
+ " -c none no compression",
#endif
-"",
-/* "and the other options are:\n", */
-" -r rows/strip",
-" -h horizontal sampling factor (1,2,4)",
-" -v vertical sampling factor (1,2,4)",
-NULL
-};
-
-static void
-usage(int code)
+ "",
+ /* "and the other options are:\n", */
+ " -r rows/strip", " -h horizontal sampling factor (1,2,4)",
+ " -v vertical sampling factor (1,2,4)", NULL};
+
+static void usage(int code)
{
- int i;
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ int i;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- for (i = 0; usage_info[i] != NULL; i++)
- fprintf(out, "%s\n", usage_info[i]);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ for (i = 0; usage_info[i] != NULL; i++)
+ fprintf(out, "%s\n", usage_info[i]);
+ exit(code);
}
diff --git a/tools/thumbnail.c b/tools/thumbnail.c
index 3cd5db76..8ce0d9b0 100644
--- a/tools/thumbnail.c
+++ b/tools/thumbnail.c
@@ -2,36 +2,36 @@
* Copyright (c) 1994-1997 Sam Leffler
* Copyright (c) 1994-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
+#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <math.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#include "tiffio.h"
@@ -43,13 +43,15 @@
#define EXIT_FAILURE 1
#endif
-#define streq(a,b) (strcmp(a,b) == 0)
+#define streq(a, b) (strcmp(a, b) == 0)
#ifndef TIFFhowmany8
-# define TIFFhowmany8(x) (((x)&0x07)?((uint32_t)(x)>>3)+1:(uint32_t)(x)>>3)
+#define TIFFhowmany8(x) \
+ (((x)&0x07) ? ((uint32_t)(x) >> 3) + 1 : (uint32_t)(x) >> 3)
#endif
-typedef enum {
+typedef enum
+{
EXP50,
EXP60,
EXP70,
@@ -59,154 +61,188 @@ typedef enum {
LINEAR
} Contrast;
-static uint32_t tnw = 216; /* thumbnail width */
-static uint32_t tnh = 274; /* thumbnail height */
-static Contrast contrast = LINEAR; /* current contrast */
-static uint8_t* thumbnail;
+static uint32_t tnw = 216; /* thumbnail width */
+static uint32_t tnh = 274; /* thumbnail height */
+static Contrast contrast = LINEAR; /* current contrast */
+static uint8_t *thumbnail;
-static int cpIFD(TIFF*, TIFF*);
-static int generateThumbnail(TIFF*, TIFF*);
-static void initScale();
-static void usage(int code);
+static int cpIFD(TIFF *, TIFF *);
+static int generateThumbnail(TIFF *, TIFF *);
+static void initScale();
+static void usage(int code);
#if !HAVE_DECL_OPTARG
-extern char* optarg;
-extern int optind;
+extern char *optarg;
+extern int optind;
#endif
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- TIFF* in;
- TIFF* out;
+ TIFF *in;
+ TIFF *out;
int c;
- while ((c = getopt(argc, argv, "w:h:c:")) != -1) {
- switch (c) {
- case 'w': tnw = strtoul(optarg, NULL, 0); break;
- case 'h': tnh = strtoul(optarg, NULL, 0); break;
- case 'c': contrast = streq(optarg, "exp50") ? EXP50 :
- streq(optarg, "exp60") ? EXP60 :
- streq(optarg, "exp70") ? EXP70 :
- streq(optarg, "exp80") ? EXP80 :
- streq(optarg, "exp90") ? EXP90 :
- streq(optarg, "exp") ? EXP :
- streq(optarg, "linear")? LINEAR :
- EXP;
- break;
- default: usage(EXIT_FAILURE);
- }
+ while ((c = getopt(argc, argv, "w:h:c:")) != -1)
+ {
+ switch (c)
+ {
+ case 'w':
+ tnw = strtoul(optarg, NULL, 0);
+ break;
+ case 'h':
+ tnh = strtoul(optarg, NULL, 0);
+ break;
+ case 'c':
+ contrast = streq(optarg, "exp50") ? EXP50
+ : streq(optarg, "exp60") ? EXP60
+ : streq(optarg, "exp70") ? EXP70
+ : streq(optarg, "exp80") ? EXP80
+ : streq(optarg, "exp90") ? EXP90
+ : streq(optarg, "exp") ? EXP
+ : streq(optarg, "linear") ? LINEAR
+ : EXP;
+ break;
+ default:
+ usage(EXIT_FAILURE);
+ }
}
- if (argc-optind != 2)
- usage(EXIT_FAILURE);
+ if (argc - optind != 2)
+ usage(EXIT_FAILURE);
- out = TIFFOpen(argv[optind+1], "w");
+ out = TIFFOpen(argv[optind + 1], "w");
if (out == NULL)
- return 2;
+ return 2;
in = TIFFOpen(argv[optind], "r");
- if( in == NULL )
+ if (in == NULL)
return 2;
- thumbnail = (uint8_t*) _TIFFmalloc(tnw * tnh);
- if (!thumbnail) {
- TIFFError(TIFFFileName(in),
- "Can't allocate space for thumbnail buffer.");
- return EXIT_FAILURE;
+ thumbnail = (uint8_t *)_TIFFmalloc(tnw * tnh);
+ if (!thumbnail)
+ {
+ TIFFError(TIFFFileName(in),
+ "Can't allocate space for thumbnail buffer.");
+ return EXIT_FAILURE;
}
- if (in != NULL) {
- initScale();
- do {
- if (!generateThumbnail(in, out))
- goto bad;
- if (!cpIFD(in, out) || !TIFFWriteDirectory(out))
- goto bad;
- } while (TIFFReadDirectory(in));
- (void) TIFFClose(in);
+ if (in != NULL)
+ {
+ initScale();
+ do
+ {
+ if (!generateThumbnail(in, out))
+ goto bad;
+ if (!cpIFD(in, out) || !TIFFWriteDirectory(out))
+ goto bad;
+ } while (TIFFReadDirectory(in));
+ (void)TIFFClose(in);
}
- (void) TIFFClose(out);
+ (void)TIFFClose(out);
return EXIT_SUCCESS;
bad:
- (void) TIFFClose(out);
+ (void)TIFFClose(out);
return EXIT_FAILURE;
}
-#define CopyField(tag, v) \
- if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
-#define CopyField2(tag, v1, v2) \
- if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
-#define CopyField3(tag, v1, v2, v3) \
- if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
-#define CopyField4(tag, v1, v2, v3, v4) \
- if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
-
-static void
-cpTag(TIFF* in, TIFF* out, uint16_t tag, uint16_t count, TIFFDataType type)
+#define CopyField(tag, v) \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v)
+#define CopyField2(tag, v1, v2) \
+ if (TIFFGetField(in, tag, &v1, &v2)) \
+ TIFFSetField(out, tag, v1, v2)
+#define CopyField3(tag, v1, v2, v3) \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) \
+ TIFFSetField(out, tag, v1, v2, v3)
+#define CopyField4(tag, v1, v2, v3, v4) \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) \
+ TIFFSetField(out, tag, v1, v2, v3, v4)
+
+static void cpTag(TIFF *in, TIFF *out, uint16_t tag, uint16_t count,
+ TIFFDataType type)
{
- switch (type) {
- case TIFF_SHORT:
- if (count == 1) {
- uint16_t shortv;
- CopyField(tag, shortv);
- } else if (count == 2) {
- uint16_t shortv1, shortv2;
- CopyField2(tag, shortv1, shortv2);
- } else if (count == 4) {
- uint16_t *tr, *tg, *tb, *ta;
- CopyField4(tag, tr, tg, tb, ta);
- } else if (count == (uint16_t) -1) {
- uint16_t shortv1;
- uint16_t* shortav;
- CopyField2(tag, shortv1, shortav);
- }
- break;
- case TIFF_LONG:
- { uint32_t longv;
- CopyField(tag, longv);
- }
- break;
- case TIFF_LONG8:
- { uint64_t longv8;
- CopyField(tag, longv8);
- }
- break;
- case TIFF_SLONG8:
- { int64_t longv8;
- CopyField(tag, longv8);
- }
- break;
- case TIFF_RATIONAL:
- if (count == 1) {
- float floatv;
- CopyField(tag, floatv);
- } else if (count == (uint16_t) -1) {
- float* floatav;
- CopyField(tag, floatav);
- }
- break;
- case TIFF_ASCII:
- { char* stringv;
- CopyField(tag, stringv);
- }
- break;
- case TIFF_DOUBLE:
- if (count == 1) {
- double doublev;
- CopyField(tag, doublev);
- } else if (count == (uint16_t) -1) {
- double* doubleav;
- CopyField(tag, doubleav);
- }
- break;
- case TIFF_IFD8:
- { toff_t ifd8;
- CopyField(tag, ifd8);
- }
- break; default:
- TIFFError(TIFFFileName(in),
- "Data type %d is not supported, tag %d skipped.",
- tag, type);
- }
+ switch (type)
+ {
+ case TIFF_SHORT:
+ if (count == 1)
+ {
+ uint16_t shortv;
+ CopyField(tag, shortv);
+ }
+ else if (count == 2)
+ {
+ uint16_t shortv1, shortv2;
+ CopyField2(tag, shortv1, shortv2);
+ }
+ else if (count == 4)
+ {
+ uint16_t *tr, *tg, *tb, *ta;
+ CopyField4(tag, tr, tg, tb, ta);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ uint16_t shortv1;
+ uint16_t *shortav;
+ CopyField2(tag, shortv1, shortav);
+ }
+ break;
+ case TIFF_LONG:
+ {
+ uint32_t longv;
+ CopyField(tag, longv);
+ }
+ break;
+ case TIFF_LONG8:
+ {
+ uint64_t longv8;
+ CopyField(tag, longv8);
+ }
+ break;
+ case TIFF_SLONG8:
+ {
+ int64_t longv8;
+ CopyField(tag, longv8);
+ }
+ break;
+ case TIFF_RATIONAL:
+ if (count == 1)
+ {
+ float floatv;
+ CopyField(tag, floatv);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ float *floatav;
+ CopyField(tag, floatav);
+ }
+ break;
+ case TIFF_ASCII:
+ {
+ char *stringv;
+ CopyField(tag, stringv);
+ }
+ break;
+ case TIFF_DOUBLE:
+ if (count == 1)
+ {
+ double doublev;
+ CopyField(tag, doublev);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ double *doubleav;
+ CopyField(tag, doubleav);
+ }
+ break;
+ case TIFF_IFD8:
+ {
+ toff_t ifd8;
+ CopyField(tag, ifd8);
+ }
+ break;
+ default:
+ TIFFError(TIFFFileName(in),
+ "Data type %d is not supported, tag %d skipped.", tag,
+ type);
+ }
}
#undef CopyField4
@@ -214,255 +250,288 @@ cpTag(TIFF* in, TIFF* out, uint16_t tag, uint16_t count, TIFFDataType type)
#undef CopyField2
#undef CopyField
-static const struct cpTag {
- uint16_t tag;
- uint16_t count;
+static const struct cpTag
+{
+ uint16_t tag;
+ uint16_t count;
TIFFDataType type;
} tags[] = {
- { TIFFTAG_IMAGEWIDTH, 1, TIFF_LONG },
- { TIFFTAG_IMAGELENGTH, 1, TIFF_LONG },
- { TIFFTAG_BITSPERSAMPLE, 1, TIFF_SHORT },
- { TIFFTAG_COMPRESSION, 1, TIFF_SHORT },
- { TIFFTAG_FILLORDER, 1, TIFF_SHORT },
- { TIFFTAG_SAMPLESPERPIXEL, 1, TIFF_SHORT },
- { TIFFTAG_ROWSPERSTRIP, 1, TIFF_LONG },
- { TIFFTAG_PLANARCONFIG, 1, TIFF_SHORT },
- { TIFFTAG_GROUP3OPTIONS, 1, TIFF_LONG },
- { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
- { TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT },
- { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
- { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
- { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
- { TIFFTAG_MAKE, 1, TIFF_ASCII },
- { TIFFTAG_MODEL, 1, TIFF_ASCII },
- { TIFFTAG_ORIENTATION, 1, TIFF_SHORT },
- { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
- { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
- { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
- { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
- { TIFFTAG_PAGENAME, 1, TIFF_ASCII },
- { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
- { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
- { TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG },
- { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
- { TIFFTAG_PAGENUMBER, 2, TIFF_SHORT },
- { TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
- { TIFFTAG_DATETIME, 1, TIFF_ASCII },
- { TIFFTAG_ARTIST, 1, TIFF_ASCII },
- { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
- { TIFFTAG_WHITEPOINT, 2, TIFF_RATIONAL },
- { TIFFTAG_PRIMARYCHROMATICITIES, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
- { TIFFTAG_BADFAXLINES, 1, TIFF_LONG },
- { TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT },
- { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG },
- { TIFFTAG_INKSET, 1, TIFF_SHORT },
- /*{ TIFFTAG_INKNAMES, 1, TIFF_ASCII },*/ /* Needs much more complicated logic. See tiffcp */
- { TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
- { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
- { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
- { TIFFTAG_YCBCRCOEFFICIENTS, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
- { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
- { TIFFTAG_REFERENCEBLACKWHITE, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_EXTRASAMPLES, (uint16_t) -1, TIFF_SHORT },
+ {TIFFTAG_IMAGEWIDTH, 1, TIFF_LONG},
+ {TIFFTAG_IMAGELENGTH, 1, TIFF_LONG},
+ {TIFFTAG_BITSPERSAMPLE, 1, TIFF_SHORT},
+ {TIFFTAG_COMPRESSION, 1, TIFF_SHORT},
+ {TIFFTAG_FILLORDER, 1, TIFF_SHORT},
+ {TIFFTAG_SAMPLESPERPIXEL, 1, TIFF_SHORT},
+ {TIFFTAG_ROWSPERSTRIP, 1, TIFF_LONG},
+ {TIFFTAG_PLANARCONFIG, 1, TIFF_SHORT},
+ {TIFFTAG_GROUP3OPTIONS, 1, TIFF_LONG},
+ {TIFFTAG_SUBFILETYPE, 1, TIFF_LONG},
+ {TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT},
+ {TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT},
+ {TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII},
+ {TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII},
+ {TIFFTAG_MAKE, 1, TIFF_ASCII},
+ {TIFFTAG_MODEL, 1, TIFF_ASCII},
+ {TIFFTAG_ORIENTATION, 1, TIFF_SHORT},
+ {TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT},
+ {TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT},
+ {TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL},
+ {TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL},
+ {TIFFTAG_PAGENAME, 1, TIFF_ASCII},
+ {TIFFTAG_XPOSITION, 1, TIFF_RATIONAL},
+ {TIFFTAG_YPOSITION, 1, TIFF_RATIONAL},
+ {TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG},
+ {TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT},
+ {TIFFTAG_PAGENUMBER, 2, TIFF_SHORT},
+ {TIFFTAG_SOFTWARE, 1, TIFF_ASCII},
+ {TIFFTAG_DATETIME, 1, TIFF_ASCII},
+ {TIFFTAG_ARTIST, 1, TIFF_ASCII},
+ {TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII},
+ {TIFFTAG_WHITEPOINT, 2, TIFF_RATIONAL},
+ {TIFFTAG_PRIMARYCHROMATICITIES, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT},
+ {TIFFTAG_BADFAXLINES, 1, TIFF_LONG},
+ {TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT},
+ {TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG},
+ {TIFFTAG_INKSET, 1, TIFF_SHORT},
+ /*{ TIFFTAG_INKNAMES, 1, TIFF_ASCII },*/ /* Needs much
+ more
+ complicated
+ logic. See
+ tiffcp */
+ {TIFFTAG_DOTRANGE, 2, TIFF_SHORT},
+ {TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII},
+ {TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT},
+ {TIFFTAG_YCBCRCOEFFICIENTS, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT},
+ {TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT},
+ {TIFFTAG_REFERENCEBLACKWHITE, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_EXTRASAMPLES, (uint16_t)-1, TIFF_SHORT},
};
-#define NTAGS (sizeof (tags) / sizeof (tags[0]))
+#define NTAGS (sizeof(tags) / sizeof(tags[0]))
-static void
-cpTags(TIFF* in, TIFF* out)
+static void cpTags(TIFF *in, TIFF *out)
{
const struct cpTag *p;
for (p = tags; p < &tags[NTAGS]; p++)
- {
- /* Horrible: but TIFFGetField() expects 2 arguments to be passed */
- /* if we request a tag that is defined in a codec, but that codec */
- /* isn't used */
- if( p->tag == TIFFTAG_GROUP3OPTIONS )
- {
- uint16_t compression;
- if( !TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
- compression != COMPRESSION_CCITTFAX3 )
- continue;
- }
- if( p->tag == TIFFTAG_GROUP4OPTIONS )
- {
- uint16_t compression;
- if( !TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
- compression != COMPRESSION_CCITTFAX4 )
- continue;
- }
- cpTag(in, out, p->tag, p->count, p->type);
- }
+ {
+ /* Horrible: but TIFFGetField() expects 2 arguments to be passed */
+ /* if we request a tag that is defined in a codec, but that codec */
+ /* isn't used */
+ if (p->tag == TIFFTAG_GROUP3OPTIONS)
+ {
+ uint16_t compression;
+ if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
+ compression != COMPRESSION_CCITTFAX3)
+ continue;
+ }
+ if (p->tag == TIFFTAG_GROUP4OPTIONS)
+ {
+ uint16_t compression;
+ if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
+ compression != COMPRESSION_CCITTFAX4)
+ continue;
+ }
+ cpTag(in, out, p->tag, p->count, p->type);
+ }
}
#undef NTAGS
-static int
-cpStrips(TIFF* in, TIFF* out)
+static int cpStrips(TIFF *in, TIFF *out)
{
- tsize_t bufsize = TIFFStripSize(in);
+ tsize_t bufsize = TIFFStripSize(in);
unsigned char *buf = (unsigned char *)_TIFFmalloc(bufsize);
- if (buf) {
- tstrip_t s, ns = TIFFNumberOfStrips(in);
- uint64_t *bytecounts;
-
- TIFFGetField(in, TIFFTAG_STRIPBYTECOUNTS, &bytecounts);
- for (s = 0; s < ns; s++) {
- if (bytecounts[s] > (uint64_t) bufsize) {
- buf = (unsigned char *)_TIFFrealloc(buf, (tmsize_t)bytecounts[s]);
- if (!buf)
- goto bad;
- bufsize = (tmsize_t)bytecounts[s];
- }
- if (TIFFReadRawStrip(in, s, buf, (tmsize_t)bytecounts[s]) < 0 ||
- TIFFWriteRawStrip(out, s, buf, (tmsize_t)bytecounts[s]) < 0) {
- _TIFFfree(buf);
- return 0;
- }
- }
- _TIFFfree(buf);
- return 1;
+ if (buf)
+ {
+ tstrip_t s, ns = TIFFNumberOfStrips(in);
+ uint64_t *bytecounts;
+
+ TIFFGetField(in, TIFFTAG_STRIPBYTECOUNTS, &bytecounts);
+ for (s = 0; s < ns; s++)
+ {
+ if (bytecounts[s] > (uint64_t)bufsize)
+ {
+ buf =
+ (unsigned char *)_TIFFrealloc(buf, (tmsize_t)bytecounts[s]);
+ if (!buf)
+ goto bad;
+ bufsize = (tmsize_t)bytecounts[s];
+ }
+ if (TIFFReadRawStrip(in, s, buf, (tmsize_t)bytecounts[s]) < 0 ||
+ TIFFWriteRawStrip(out, s, buf, (tmsize_t)bytecounts[s]) < 0)
+ {
+ _TIFFfree(buf);
+ return 0;
+ }
+ }
+ _TIFFfree(buf);
+ return 1;
}
bad:
- TIFFError(TIFFFileName(in),
- "Can't allocate space for strip buffer.");
- return 0;
+ TIFFError(TIFFFileName(in), "Can't allocate space for strip buffer.");
+ return 0;
}
-static int
-cpTiles(TIFF* in, TIFF* out)
+static int cpTiles(TIFF *in, TIFF *out)
{
tsize_t bufsize = TIFFTileSize(in);
unsigned char *buf = (unsigned char *)_TIFFmalloc(bufsize);
- if (buf) {
- ttile_t t, nt = TIFFNumberOfTiles(in);
- uint64_t *bytecounts;
-
- TIFFGetField(in, TIFFTAG_TILEBYTECOUNTS, &bytecounts);
- for (t = 0; t < nt; t++) {
- if (bytecounts[t] > (uint64_t) bufsize) {
- buf = (unsigned char *)_TIFFrealloc(buf, (tmsize_t)bytecounts[t]);
- if (!buf)
- goto bad;
- bufsize = (tmsize_t)bytecounts[t];
- }
- if (TIFFReadRawTile(in, t, buf, (tmsize_t)bytecounts[t]) < 0 ||
- TIFFWriteRawTile(out, t, buf, (tmsize_t)bytecounts[t]) < 0) {
- _TIFFfree(buf);
- return 0;
- }
- }
- _TIFFfree(buf);
- return 1;
+ if (buf)
+ {
+ ttile_t t, nt = TIFFNumberOfTiles(in);
+ uint64_t *bytecounts;
+
+ TIFFGetField(in, TIFFTAG_TILEBYTECOUNTS, &bytecounts);
+ for (t = 0; t < nt; t++)
+ {
+ if (bytecounts[t] > (uint64_t)bufsize)
+ {
+ buf =
+ (unsigned char *)_TIFFrealloc(buf, (tmsize_t)bytecounts[t]);
+ if (!buf)
+ goto bad;
+ bufsize = (tmsize_t)bytecounts[t];
+ }
+ if (TIFFReadRawTile(in, t, buf, (tmsize_t)bytecounts[t]) < 0 ||
+ TIFFWriteRawTile(out, t, buf, (tmsize_t)bytecounts[t]) < 0)
+ {
+ _TIFFfree(buf);
+ return 0;
+ }
+ }
+ _TIFFfree(buf);
+ return 1;
}
bad:
- TIFFError(TIFFFileName(in),
- "Can't allocate space for tile buffer.");
- return (0);
+ TIFFError(TIFFFileName(in), "Can't allocate space for tile buffer.");
+ return (0);
}
-static int
-cpIFD(TIFF* in, TIFF* out)
+static int cpIFD(TIFF *in, TIFF *out)
{
cpTags(in, out);
- if (TIFFIsTiled(in)) {
- if (!cpTiles(in, out))
- return (0);
- } else {
- if (!cpStrips(in, out))
- return (0);
+ if (TIFFIsTiled(in))
+ {
+ if (!cpTiles(in, out))
+ return (0);
+ }
+ else
+ {
+ if (!cpStrips(in, out))
+ return (0);
}
return (1);
}
-static uint16_t photometric; /* current photometric of raster */
-static uint16_t filterWidth; /* filter width in pixels */
-static uint32_t stepSrcWidth; /* src image stepping width */
-static uint32_t stepDstWidth; /* dest stepping width */
-static uint8_t* src0; /* horizontal bit stepping (start) */
-static uint8_t* src1; /* horizontal bit stepping (middle) */
-static uint8_t* src2; /* horizontal bit stepping (end) */
-static uint32_t* rowoff; /* row offset for stepping */
-static uint8_t cmap[256]; /* colormap indexes */
-static uint8_t bits[256]; /* count of bits set */
-
-static void
-setupBitsTables()
+static uint16_t photometric; /* current photometric of raster */
+static uint16_t filterWidth; /* filter width in pixels */
+static uint32_t stepSrcWidth; /* src image stepping width */
+static uint32_t stepDstWidth; /* dest stepping width */
+static uint8_t *src0; /* horizontal bit stepping (start) */
+static uint8_t *src1; /* horizontal bit stepping (middle) */
+static uint8_t *src2; /* horizontal bit stepping (end) */
+static uint32_t *rowoff; /* row offset for stepping */
+static uint8_t cmap[256]; /* colormap indexes */
+static uint8_t bits[256]; /* count of bits set */
+
+static void setupBitsTables()
{
int i;
- for (i = 0; i < 256; i++) {
- int n = 0;
- if (i&0x01) n++;
- if (i&0x02) n++;
- if (i&0x04) n++;
- if (i&0x08) n++;
- if (i&0x10) n++;
- if (i&0x20) n++;
- if (i&0x40) n++;
- if (i&0x80) n++;
- bits[i] = n;
+ for (i = 0; i < 256; i++)
+ {
+ int n = 0;
+ if (i & 0x01)
+ n++;
+ if (i & 0x02)
+ n++;
+ if (i & 0x04)
+ n++;
+ if (i & 0x08)
+ n++;
+ if (i & 0x10)
+ n++;
+ if (i & 0x20)
+ n++;
+ if (i & 0x40)
+ n++;
+ if (i & 0x80)
+ n++;
+ bits[i] = n;
}
}
static int clamp(float v, int low, int high)
- { return (v < low ? low : v > high ? high : (int)v); }
+{
+ return (v < low ? low : v > high ? high : (int)v);
+}
#ifndef M_E
-#define M_E 2.7182818284590452354
+#define M_E 2.7182818284590452354
#endif
-static void
-expFill(float pct[], uint32_t p, uint32_t n)
+static void expFill(float pct[], uint32_t p, uint32_t n)
{
uint32_t i;
uint32_t c = (p * n) / 100;
for (i = 1; i < c; i++)
- pct[i] = (float) (1-exp(i/((double)(n-1)))/ M_E);
+ pct[i] = (float)(1 - exp(i / ((double)(n - 1))) / M_E);
for (; i < n; i++)
- pct[i] = 0.;
+ pct[i] = 0.;
}
-static void
-setupCmap()
+static void setupCmap()
{
- float pct[256]; /* known to be large enough */
+ float pct[256]; /* known to be large enough */
uint32_t i;
- pct[0] = 1; /* force white */
- switch (contrast) {
- case EXP50: expFill(pct, 50, 256); break;
- case EXP60: expFill(pct, 60, 256); break;
- case EXP70: expFill(pct, 70, 256); break;
- case EXP80: expFill(pct, 80, 256); break;
- case EXP90: expFill(pct, 90, 256); break;
- case EXP: expFill(pct, 100, 256); break;
- case LINEAR:
- for (i = 1; i < 256; i++)
- pct[i] = 1-((float)i)/(256-1);
- break;
+ pct[0] = 1; /* force white */
+ switch (contrast)
+ {
+ case EXP50:
+ expFill(pct, 50, 256);
+ break;
+ case EXP60:
+ expFill(pct, 60, 256);
+ break;
+ case EXP70:
+ expFill(pct, 70, 256);
+ break;
+ case EXP80:
+ expFill(pct, 80, 256);
+ break;
+ case EXP90:
+ expFill(pct, 90, 256);
+ break;
+ case EXP:
+ expFill(pct, 100, 256);
+ break;
+ case LINEAR:
+ for (i = 1; i < 256; i++)
+ pct[i] = 1 - ((float)i) / (256 - 1);
+ break;
}
- switch (photometric) {
- case PHOTOMETRIC_MINISWHITE:
- for (i = 0; i < 256; i++)
- cmap[i] = clamp(255*pct[(256-1)-i], 0, 255);
- break;
- case PHOTOMETRIC_MINISBLACK:
- for (i = 0; i < 256; i++)
- cmap[i] = clamp(255*pct[i], 0, 255);
- break;
+ switch (photometric)
+ {
+ case PHOTOMETRIC_MINISWHITE:
+ for (i = 0; i < 256; i++)
+ cmap[i] = clamp(255 * pct[(256 - 1) - i], 0, 255);
+ break;
+ case PHOTOMETRIC_MINISBLACK:
+ for (i = 0; i < 256; i++)
+ cmap[i] = clamp(255 * pct[i], 0, 255);
+ break;
}
}
-static void
-initScale()
+static void initScale()
{
- src0 = (uint8_t*) _TIFFmalloc(sizeof (uint8_t) * tnw);
- src1 = (uint8_t*) _TIFFmalloc(sizeof (uint8_t) * tnw);
- src2 = (uint8_t*) _TIFFmalloc(sizeof (uint8_t) * tnw);
- rowoff = (uint32_t*) _TIFFmalloc(sizeof (uint32_t) * tnw);
+ src0 = (uint8_t *)_TIFFmalloc(sizeof(uint8_t) * tnw);
+ src1 = (uint8_t *)_TIFFmalloc(sizeof(uint8_t) * tnw);
+ src2 = (uint8_t *)_TIFFmalloc(sizeof(uint8_t) * tnw);
+ rowoff = (uint32_t *)_TIFFmalloc(sizeof(uint32_t) * tnw);
filterWidth = 0;
stepDstWidth = stepSrcWidth = 0;
setupBitsTables();
@@ -472,73 +541,86 @@ initScale()
* Calculate the horizontal accumulation parameteres
* according to the widths of the src and dst images.
*/
-static void
-setupStepTables(uint32_t sw)
+static void setupStepTables(uint32_t sw)
{
- if (stepSrcWidth != sw || stepDstWidth != tnw) {
- int step = sw;
- int limit = tnw;
- int err = 0;
- uint32_t sx = 0;
- uint32_t x;
- int fw;
- uint8_t b;
- for (x = 0; x < tnw; x++) {
- uint32_t sx0 = sx;
- err += step;
- while (err >= limit) {
- err -= limit;
- sx++;
- }
- rowoff[x] = sx0 >> 3;
- fw = sx - sx0; /* width */
- b = (fw < 8) ? 0xff<<(8-fw) : 0xff;
- src0[x] = b >> (sx0&7);
- fw -= 8 - (sx0&7);
- if (fw < 0)
- fw = 0;
- src1[x] = fw >> 3;
- fw -= (fw>>3)<<3;
- src2[x] = 0xff << (8-fw);
- }
- stepSrcWidth = sw;
- stepDstWidth = tnw;
+ if (stepSrcWidth != sw || stepDstWidth != tnw)
+ {
+ int step = sw;
+ int limit = tnw;
+ int err = 0;
+ uint32_t sx = 0;
+ uint32_t x;
+ int fw;
+ uint8_t b;
+ for (x = 0; x < tnw; x++)
+ {
+ uint32_t sx0 = sx;
+ err += step;
+ while (err >= limit)
+ {
+ err -= limit;
+ sx++;
+ }
+ rowoff[x] = sx0 >> 3;
+ fw = sx - sx0; /* width */
+ b = (fw < 8) ? 0xff << (8 - fw) : 0xff;
+ src0[x] = b >> (sx0 & 7);
+ fw -= 8 - (sx0 & 7);
+ if (fw < 0)
+ fw = 0;
+ src1[x] = fw >> 3;
+ fw -= (fw >> 3) << 3;
+ src2[x] = 0xff << (8 - fw);
+ }
+ stepSrcWidth = sw;
+ stepDstWidth = tnw;
}
}
-static void
-setrow(uint8_t* row, uint32_t nrows, const uint8_t* rows[])
+static void setrow(uint8_t *row, uint32_t nrows, const uint8_t *rows[])
{
uint32_t x;
uint32_t area = nrows * filterWidth;
- for (x = 0; x < tnw; x++) {
- uint32_t mask0 = src0[x];
- uint32_t fw = src1[x];
- uint32_t mask1 = src1[x];
- uint32_t off = rowoff[x];
- uint32_t acc = 0;
- uint32_t y, i;
- for (y = 0; y < nrows; y++) {
- const uint8_t* src = rows[y] + off;
- acc += bits[*src++ & mask0];
- switch (fw) {
- default:
- for (i = fw; i > 8; i--)
- acc += bits[*src++];
- /* fall through... */
- case 8: acc += bits[*src++]; /* fall through */
- case 7: acc += bits[*src++]; /* fall through */
- case 6: acc += bits[*src++]; /* fall through */
- case 5: acc += bits[*src++]; /* fall through */
- case 4: acc += bits[*src++]; /* fall through */
- case 3: acc += bits[*src++]; /* fall through */
- case 2: acc += bits[*src++]; /* fall through */
- case 1: acc += bits[*src++]; /* fall through */
- case 0: break;
- }
- acc += bits[*src & mask1];
- }
- *row++ = cmap[(255*acc)/area];
+ for (x = 0; x < tnw; x++)
+ {
+ uint32_t mask0 = src0[x];
+ uint32_t fw = src1[x];
+ uint32_t mask1 = src1[x];
+ uint32_t off = rowoff[x];
+ uint32_t acc = 0;
+ uint32_t y, i;
+ for (y = 0; y < nrows; y++)
+ {
+ const uint8_t *src = rows[y] + off;
+ acc += bits[*src++ & mask0];
+ switch (fw)
+ {
+ default:
+ for (i = fw; i > 8; i--)
+ acc += bits[*src++];
+ /* fall through... */
+ case 8:
+ acc += bits[*src++]; /* fall through */
+ case 7:
+ acc += bits[*src++]; /* fall through */
+ case 6:
+ acc += bits[*src++]; /* fall through */
+ case 5:
+ acc += bits[*src++]; /* fall through */
+ case 4:
+ acc += bits[*src++]; /* fall through */
+ case 3:
+ acc += bits[*src++]; /* fall through */
+ case 2:
+ acc += bits[*src++]; /* fall through */
+ case 1:
+ acc += bits[*src++]; /* fall through */
+ case 0:
+ break;
+ }
+ acc += bits[*src & mask1];
+ }
+ *row++ = cmap[(255 * acc) / area];
}
}
@@ -548,52 +630,52 @@ setrow(uint8_t* row, uint32_t nrows, const uint8_t* rows[])
* a box filter. The resultant pixels are mapped
* with a user-selectable contrast curve.
*/
-static void
-setImage1(const uint8_t* br, uint32_t rw, uint32_t rh)
+static void setImage1(const uint8_t *br, uint32_t rw, uint32_t rh)
{
int step = rh;
int limit = tnh;
int err = 0;
int bpr = TIFFhowmany8(rw);
int sy = 0;
- uint8_t* row = thumbnail;
+ uint8_t *row = thumbnail;
uint32_t dy;
- for (dy = 0; dy < tnh; dy++) {
- const uint8_t* rows[256];
- uint32_t nrows = 1;
- fprintf(stderr, "bpr=%d, sy=%d, bpr*sy=%d\n", bpr, sy, bpr*sy);
- rows[0] = br + bpr*sy;
- err += step;
- while (err >= limit) {
- err -= limit;
- sy++;
- if (err >= limit)
- {
- /* We should perhaps error loudly, but I can't make sense of that */
- /* code... */
- if( nrows == 256 )
- break;
- rows[nrows++] = br + bpr*sy;
- }
- }
- setrow(row, nrows, rows);
- row += tnw;
+ for (dy = 0; dy < tnh; dy++)
+ {
+ const uint8_t *rows[256];
+ uint32_t nrows = 1;
+ fprintf(stderr, "bpr=%d, sy=%d, bpr*sy=%d\n", bpr, sy, bpr * sy);
+ rows[0] = br + bpr * sy;
+ err += step;
+ while (err >= limit)
+ {
+ err -= limit;
+ sy++;
+ if (err >= limit)
+ {
+ /* We should perhaps error loudly, but I can't make sense of
+ * that */
+ /* code... */
+ if (nrows == 256)
+ break;
+ rows[nrows++] = br + bpr * sy;
+ }
+ }
+ setrow(row, nrows, rows);
+ row += tnw;
}
}
-static void
-setImage(const uint8_t* br, uint32_t rw, uint32_t rh)
+static void setImage(const uint8_t *br, uint32_t rw, uint32_t rh)
{
- filterWidth = (uint16_t) ceil((double) rw / (double) tnw);
+ filterWidth = (uint16_t)ceil((double)rw / (double)tnw);
setupStepTables(rw);
setImage1(br, rw, rh);
}
-static int
-generateThumbnail(TIFF* in, TIFF* out)
+static int generateThumbnail(TIFF *in, TIFF *out)
{
- unsigned char* raster;
- unsigned char* rp;
+ unsigned char *raster;
+ unsigned char *rp;
uint32_t sw, sh, rps;
uint16_t bps, spp;
tsize_t rowsize, rastersize;
@@ -606,25 +688,26 @@ generateThumbnail(TIFF* in, TIFF* out)
TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp);
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
if (spp != 1 || bps != 1)
- return 0;
+ return 0;
rowsize = TIFFScanlineSize(in);
rastersize = sh * rowsize;
fprintf(stderr, "rastersize=%u\n", (unsigned int)rastersize);
- /* +3 : add a few guard bytes since setrow() can read a bit */
- /* outside buffer */
- raster = (unsigned char*)_TIFFmalloc(rastersize+3);
- if (!raster) {
- TIFFError(TIFFFileName(in),
- "Can't allocate space for raster buffer.");
- return 0;
+ /* +3 : add a few guard bytes since setrow() can read a bit */
+ /* outside buffer */
+ raster = (unsigned char *)_TIFFmalloc(rastersize + 3);
+ if (!raster)
+ {
+ TIFFError(TIFFFileName(in), "Can't allocate space for raster buffer.");
+ return 0;
}
raster[rastersize] = 0;
- raster[rastersize+1] = 0;
- raster[rastersize+2] = 0;
+ raster[rastersize + 1] = 0;
+ raster[rastersize + 2] = 0;
rp = raster;
- for (s = 0; s < ns; s++) {
- (void) TIFFReadEncodedStrip(in, s, rp, -1);
- rp += rps * rowsize;
+ for (s = 0; s < ns; s++)
+ {
+ (void)TIFFReadEncodedStrip(in, s, rp, -1);
+ rp += rps * rowsize;
}
TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric);
setupCmap();
@@ -632,49 +715,47 @@ generateThumbnail(TIFF* in, TIFF* out)
_TIFFfree(raster);
TIFFSetField(out, TIFFTAG_SUBFILETYPE, FILETYPE_REDUCEDIMAGE);
- TIFFSetField(out, TIFFTAG_IMAGEWIDTH, (uint32_t) tnw);
- TIFFSetField(out, TIFFTAG_IMAGELENGTH, (uint32_t) tnh);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, (uint16_t) 8);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, (uint16_t) 1);
+ TIFFSetField(out, TIFFTAG_IMAGEWIDTH, (uint32_t)tnw);
+ TIFFSetField(out, TIFFTAG_IMAGELENGTH, (uint32_t)tnh);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, (uint16_t)8);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, (uint16_t)1);
TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_PACKBITS);
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE);
TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
- cpTag(in, out, TIFFTAG_SOFTWARE, (uint16_t) -1, TIFF_ASCII);
- cpTag(in, out, TIFFTAG_IMAGEDESCRIPTION, (uint16_t) -1, TIFF_ASCII);
- cpTag(in, out, TIFFTAG_DATETIME, (uint16_t) -1, TIFF_ASCII);
- cpTag(in, out, TIFFTAG_HOSTCOMPUTER, (uint16_t) -1, TIFF_ASCII);
+ cpTag(in, out, TIFFTAG_SOFTWARE, (uint16_t)-1, TIFF_ASCII);
+ cpTag(in, out, TIFFTAG_IMAGEDESCRIPTION, (uint16_t)-1, TIFF_ASCII);
+ cpTag(in, out, TIFFTAG_DATETIME, (uint16_t)-1, TIFF_ASCII);
+ cpTag(in, out, TIFFTAG_HOSTCOMPUTER, (uint16_t)-1, TIFF_ASCII);
diroff[0] = 0UL;
TIFFSetField(out, TIFFTAG_SUBIFD, 1, diroff);
- return (TIFFWriteEncodedStrip(out, 0, thumbnail, tnw*tnh) != -1 &&
+ return (TIFFWriteEncodedStrip(out, 0, thumbnail, tnw * tnh) != -1 &&
TIFFWriteDirectory(out) != -1);
}
-const char* usage_info[] = {
-"Create a TIFF file with thumbnail images\n\n"
-"usage: thumbnail [options] input.tif output.tif",
-"where options are:",
-" -h # specify thumbnail image height (default is 274)",
-" -w # specify thumbnail image width (default is 216)",
-"",
-" -c linear use linear contrast curve",
-" -c exp50 use 50% exponential contrast curve",
-" -c exp60 use 60% exponential contrast curve",
-" -c exp70 use 70% exponential contrast curve",
-" -c exp80 use 80% exponential contrast curve",
-" -c exp90 use 90% exponential contrast curve",
-" -c exp use pure exponential contrast curve",
-NULL
-};
-
-static void
-usage(int code)
+const char *usage_info[] = {
+ "Create a TIFF file with thumbnail images\n\n"
+ "usage: thumbnail [options] input.tif output.tif",
+ "where options are:",
+ " -h # specify thumbnail image height (default is 274)",
+ " -w # specify thumbnail image width (default is 216)",
+ "",
+ " -c linear use linear contrast curve",
+ " -c exp50 use 50% exponential contrast curve",
+ " -c exp60 use 60% exponential contrast curve",
+ " -c exp70 use 70% exponential contrast curve",
+ " -c exp80 use 80% exponential contrast curve",
+ " -c exp90 use 90% exponential contrast curve",
+ " -c exp use pure exponential contrast curve",
+ NULL};
+
+static void usage(int code)
{
- int i;
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ int i;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- for (i = 0; usage_info[i] != NULL; i++)
- fprintf(out, "%s\n", usage_info[i]);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ for (i = 0; usage_info[i] != NULL; i++)
+ fprintf(out, "%s\n", usage_info[i]);
+ exit(code);
}
diff --git a/tools/tiff2bw.c b/tools/tiff2bw.c
index b3516a65..51f50ca5 100644
--- a/tools/tiff2bw.c
+++ b/tools/tiff2bw.c
@@ -2,36 +2,36 @@
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
+#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <ctype.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#include "tiffio.h"
@@ -45,390 +45,427 @@
#endif
/* x% weighting -> fraction of full color */
-#define PCT(x) (((x)*256+50)/100)
-int RED = PCT(30); /* 30% */
-int GREEN = PCT(59); /* 59% */
-int BLUE = PCT(11); /* 11% */
+#define PCT(x) (((x)*256 + 50) / 100)
+int RED = PCT(30); /* 30% */
+int GREEN = PCT(59); /* 59% */
+int BLUE = PCT(11); /* 11% */
-static void usage(int code);
-static int processCompressOptions(char*);
+static void usage(int code);
+static int processCompressOptions(char *);
-static void
-compresscontig(unsigned char* out, unsigned char* rgb, uint32_t n)
+static void compresscontig(unsigned char *out, unsigned char *rgb, uint32_t n)
{
- register int v, red = RED, green = GREEN, blue = BLUE;
-
- while (n-- > 0) {
- v = red*(*rgb++);
- v += green*(*rgb++);
- v += blue*(*rgb++);
- *out++ = v>>8;
- }
+ register int v, red = RED, green = GREEN, blue = BLUE;
+
+ while (n-- > 0)
+ {
+ v = red * (*rgb++);
+ v += green * (*rgb++);
+ v += blue * (*rgb++);
+ *out++ = v >> 8;
+ }
}
-static void
-compresssep(unsigned char* out,
- unsigned char* r, unsigned char* g, unsigned char* b, uint32_t n)
+static void compresssep(unsigned char *out, unsigned char *r, unsigned char *g,
+ unsigned char *b, uint32_t n)
{
- register uint32_t red = RED, green = GREEN, blue = BLUE;
+ register uint32_t red = RED, green = GREEN, blue = BLUE;
- while (n-- > 0)
- *out++ = (unsigned char)
- ((red*(*r++) + green*(*g++) + blue*(*b++)) >> 8);
+ while (n-- > 0)
+ *out++ =
+ (unsigned char)((red * (*r++) + green * (*g++) + blue * (*b++)) >>
+ 8);
}
-static int
-checkcmap(TIFF* tif, int n, uint16_t* r, uint16_t* g, uint16_t* b)
+static int checkcmap(TIFF *tif, int n, uint16_t *r, uint16_t *g, uint16_t *b)
{
- while (n-- > 0)
- if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
- return (16);
- TIFFWarning(TIFFFileName(tif), "Assuming 8-bit colormap");
- return (8);
+ while (n-- > 0)
+ if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
+ return (16);
+ TIFFWarning(TIFFFileName(tif), "Assuming 8-bit colormap");
+ return (8);
}
-static void
-compresspalette(unsigned char* out, unsigned char* data, uint32_t n, uint16_t* rmap, uint16_t* gmap, uint16_t* bmap)
+static void compresspalette(unsigned char *out, unsigned char *data, uint32_t n,
+ uint16_t *rmap, uint16_t *gmap, uint16_t *bmap)
{
- register int v, red = RED, green = GREEN, blue = BLUE;
-
- while (n-- > 0) {
- unsigned int ix = *data++;
- v = red*rmap[ix];
- v += green*gmap[ix];
- v += blue*bmap[ix];
- *out++ = v>>8;
- }
+ register int v, red = RED, green = GREEN, blue = BLUE;
+
+ while (n-- > 0)
+ {
+ unsigned int ix = *data++;
+ v = red * rmap[ix];
+ v += green * gmap[ix];
+ v += blue * bmap[ix];
+ *out++ = v >> 8;
+ }
}
-static uint16_t compression = (uint16_t) -1;
-static uint16_t predictor = 0;
-static int jpegcolormode = JPEGCOLORMODE_RGB;
-static int quality = 75; /* JPEG quality */
+static uint16_t compression = (uint16_t)-1;
+static uint16_t predictor = 0;
+static int jpegcolormode = JPEGCOLORMODE_RGB;
+static int quality = 75; /* JPEG quality */
-static void cpTags(TIFF* in, TIFF* out);
+static void cpTags(TIFF *in, TIFF *out);
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- uint32_t rowsperstrip = (uint32_t) -1;
- TIFF *in, *out;
- uint32_t w, h;
- uint16_t samplesperpixel;
- uint16_t bitspersample;
- uint16_t config;
- uint16_t photometric;
- uint16_t* red;
- uint16_t* green;
- uint16_t* blue;
- tsize_t rowsize;
- register uint32_t row;
- register tsample_t s;
- unsigned char *inbuf, *outbuf;
- char thing[1024];
- int c;
+ uint32_t rowsperstrip = (uint32_t)-1;
+ TIFF *in, *out;
+ uint32_t w, h;
+ uint16_t samplesperpixel;
+ uint16_t bitspersample;
+ uint16_t config;
+ uint16_t photometric;
+ uint16_t *red;
+ uint16_t *green;
+ uint16_t *blue;
+ tsize_t rowsize;
+ register uint32_t row;
+ register tsample_t s;
+ unsigned char *inbuf, *outbuf;
+ char thing[1024];
+ int c;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char *optarg;
+ extern int optind;
+ extern char *optarg;
#endif
-
- in = (TIFF *) NULL;
- out = (TIFF *) NULL;
- inbuf = (unsigned char *) NULL;
- outbuf = (unsigned char *) NULL;
-
- while ((c = getopt(argc, argv, "c:r:R:G:B:h")) != -1)
- switch (c) {
- case 'c': /* compression scheme */
- if (!processCompressOptions(optarg))
- usage(EXIT_FAILURE);
- break;
- case 'r': /* rows/strip */
- rowsperstrip = atoi(optarg);
- break;
- case 'R':
- RED = PCT(atoi(optarg));
- break;
- case 'G':
- GREEN = PCT(atoi(optarg));
- break;
- case 'B':
- BLUE = PCT(atoi(optarg));
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- /*NOTREACHED*/
- break;
- case '?':
- usage(EXIT_FAILURE);
- /*NOTREACHED*/
- break;
- }
- if (argc - optind < 2)
- usage(EXIT_FAILURE);
- in = TIFFOpen(argv[optind], "r");
- if (in == NULL)
- return (EXIT_FAILURE);
- photometric = 0;
- TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric);
- if (photometric != PHOTOMETRIC_RGB && photometric != PHOTOMETRIC_PALETTE ) {
- fprintf(stderr,
- "%s: Bad photometric; can only handle RGB and Palette images.\n",
- argv[optind]);
- goto tiff2bw_error;
- }
- TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
- if (samplesperpixel != 1 && samplesperpixel != 3) {
- fprintf(stderr, "%s: Bad samples/pixel %u.\n",
- argv[optind], samplesperpixel);
- goto tiff2bw_error;
- }
- if( photometric == PHOTOMETRIC_RGB && samplesperpixel != 3) {
- fprintf(stderr, "%s: Bad samples/pixel %u for PHOTOMETRIC_RGB.\n",
- argv[optind], samplesperpixel);
- goto tiff2bw_error;
- }
- TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
- if (bitspersample != 8) {
- fprintf(stderr,
- " %s: Sorry, only handle 8-bit samples.\n", argv[optind]);
- goto tiff2bw_error;
- }
- TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
- TIFFGetField(in, TIFFTAG_IMAGELENGTH, &h);
- TIFFGetField(in, TIFFTAG_PLANARCONFIG, &config);
-
- out = TIFFOpen(argv[optind+1], "w");
- if (out == NULL)
- {
- goto tiff2bw_error;
- }
- TIFFSetField(out, TIFFTAG_IMAGEWIDTH, w);
- TIFFSetField(out, TIFFTAG_IMAGELENGTH, h);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 1);
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
- cpTags(in, out);
- if (compression != (uint16_t) -1) {
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- switch (compression) {
- case COMPRESSION_JPEG:
- TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
- TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
- break;
- case COMPRESSION_LZW:
- case COMPRESSION_ADOBE_DEFLATE:
- case COMPRESSION_DEFLATE:
- if (predictor != 0)
- TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
- break;
- }
- }
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
- snprintf(thing, sizeof(thing), "B&W version of %s", argv[optind]);
- TIFFSetField(out, TIFFTAG_IMAGEDESCRIPTION, thing);
- TIFFSetField(out, TIFFTAG_SOFTWARE, "tiff2bw");
- outbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(out));
- if( !outbuf )
+
+ in = (TIFF *)NULL;
+ out = (TIFF *)NULL;
+ inbuf = (unsigned char *)NULL;
+ outbuf = (unsigned char *)NULL;
+
+ while ((c = getopt(argc, argv, "c:r:R:G:B:h")) != -1)
+ switch (c)
{
- fprintf(stderr, "Out of memory\n");
- goto tiff2bw_error;
+ case 'c': /* compression scheme */
+ if (!processCompressOptions(optarg))
+ usage(EXIT_FAILURE);
+ break;
+ case 'r': /* rows/strip */
+ rowsperstrip = atoi(optarg);
+ break;
+ case 'R':
+ RED = PCT(atoi(optarg));
+ break;
+ case 'G':
+ GREEN = PCT(atoi(optarg));
+ break;
+ case 'B':
+ BLUE = PCT(atoi(optarg));
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ /*NOTREACHED*/
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ /*NOTREACHED*/
+ break;
}
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
- TIFFDefaultStripSize(out, rowsperstrip));
-
-#define pack(a,b) ((a)<<8 | (b))
- switch (pack(photometric, config)) {
- case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_CONTIG):
- case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_SEPARATE):
- TIFFGetField(in, TIFFTAG_COLORMAP, &red, &green, &blue);
- /*
- * Convert 16-bit colormap to 8-bit (unless it looks
- * like an old-style 8-bit colormap).
- */
- if (checkcmap(in, 1<<bitspersample, red, green, blue) == 16) {
- int i;
-#define CVT(x) (((x) * 255L) / ((1L<<16)-1))
- for (i = (1<<bitspersample)-1; i >= 0; i--) {
- red[i] = CVT(red[i]);
- green[i] = CVT(green[i]);
- blue[i] = CVT(blue[i]);
- }
-#undef CVT
- }
- inbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
- if( !inbuf )
- {
- fprintf(stderr, "Out of memory\n");
- goto tiff2bw_error;
- }
- for (row = 0; row < h; row++) {
- if (TIFFReadScanline(in, inbuf, row, 0) < 0)
- break;
- compresspalette(outbuf, inbuf, w, red, green, blue);
- if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
- break;
- }
- break;
- case pack(PHOTOMETRIC_RGB, PLANARCONFIG_CONTIG):
- inbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
- if( !inbuf )
- {
- fprintf(stderr, "Out of memory\n");
- goto tiff2bw_error;
- }
- for (row = 0; row < h; row++) {
- if (TIFFReadScanline(in, inbuf, row, 0) < 0)
- break;
- compresscontig(outbuf, inbuf, w);
- if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
- break;
- }
- break;
- case pack(PHOTOMETRIC_RGB, PLANARCONFIG_SEPARATE):
+ if (argc - optind < 2)
+ usage(EXIT_FAILURE);
+ in = TIFFOpen(argv[optind], "r");
+ if (in == NULL)
+ return (EXIT_FAILURE);
+ photometric = 0;
+ TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric);
+ if (photometric != PHOTOMETRIC_RGB && photometric != PHOTOMETRIC_PALETTE)
+ {
+ fprintf(
+ stderr,
+ "%s: Bad photometric; can only handle RGB and Palette images.\n",
+ argv[optind]);
+ goto tiff2bw_error;
+ }
+ TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
+ if (samplesperpixel != 1 && samplesperpixel != 3)
+ {
+ fprintf(stderr, "%s: Bad samples/pixel %u.\n", argv[optind],
+ samplesperpixel);
+ goto tiff2bw_error;
+ }
+ if (photometric == PHOTOMETRIC_RGB && samplesperpixel != 3)
+ {
+ fprintf(stderr, "%s: Bad samples/pixel %u for PHOTOMETRIC_RGB.\n",
+ argv[optind], samplesperpixel);
+ goto tiff2bw_error;
+ }
+ TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
+ if (bitspersample != 8)
+ {
+ fprintf(stderr, " %s: Sorry, only handle 8-bit samples.\n",
+ argv[optind]);
+ goto tiff2bw_error;
+ }
+ TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
+ TIFFGetField(in, TIFFTAG_IMAGELENGTH, &h);
+ TIFFGetField(in, TIFFTAG_PLANARCONFIG, &config);
+
+ out = TIFFOpen(argv[optind + 1], "w");
+ if (out == NULL)
+ {
+ goto tiff2bw_error;
+ }
+ TIFFSetField(out, TIFFTAG_IMAGEWIDTH, w);
+ TIFFSetField(out, TIFFTAG_IMAGELENGTH, h);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 1);
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+ cpTags(in, out);
+ if (compression != (uint16_t)-1)
+ {
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
+ switch (compression)
{
- tmsize_t inbufsize;
- rowsize = TIFFScanlineSize(in);
- inbufsize = TIFFSafeMultiply(tmsize_t, 3, rowsize);
- inbuf = (unsigned char *)_TIFFmalloc(inbufsize);
- if( !inbuf )
+ case COMPRESSION_JPEG:
+ TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
+ TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
+ break;
+ case COMPRESSION_LZW:
+ case COMPRESSION_ADOBE_DEFLATE:
+ case COMPRESSION_DEFLATE:
+ if (predictor != 0)
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
+ break;
+ }
+ }
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
+ snprintf(thing, sizeof(thing), "B&W version of %s", argv[optind]);
+ TIFFSetField(out, TIFFTAG_IMAGEDESCRIPTION, thing);
+ TIFFSetField(out, TIFFTAG_SOFTWARE, "tiff2bw");
+ outbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(out));
+ if (!outbuf)
+ {
+ fprintf(stderr, "Out of memory\n");
+ goto tiff2bw_error;
+ }
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
+ TIFFDefaultStripSize(out, rowsperstrip));
+
+#define pack(a, b) ((a) << 8 | (b))
+ switch (pack(photometric, config))
+ {
+ case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_CONTIG):
+ case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_SEPARATE):
+ TIFFGetField(in, TIFFTAG_COLORMAP, &red, &green, &blue);
+ /*
+ * Convert 16-bit colormap to 8-bit (unless it looks
+ * like an old-style 8-bit colormap).
+ */
+ if (checkcmap(in, 1 << bitspersample, red, green, blue) == 16)
+ {
+ int i;
+#define CVT(x) (((x)*255L) / ((1L << 16) - 1))
+ for (i = (1 << bitspersample) - 1; i >= 0; i--)
{
- fprintf(stderr, "Out of memory\n");
- goto tiff2bw_error;
+ red[i] = CVT(red[i]);
+ green[i] = CVT(green[i]);
+ blue[i] = CVT(blue[i]);
}
- for (row = 0; row < h; row++) {
- for (s = 0; s < 3; s++)
- if (TIFFReadScanline(in,
- inbuf+s*rowsize, row, s) < 0)
- goto tiff2bw_error;
- compresssep(outbuf,
- inbuf, inbuf+rowsize, inbuf+2*rowsize, w);
- if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
- break;
- }
- break;
+#undef CVT
+ }
+ inbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
+ if (!inbuf)
+ {
+ fprintf(stderr, "Out of memory\n");
+ goto tiff2bw_error;
+ }
+ for (row = 0; row < h; row++)
+ {
+ if (TIFFReadScanline(in, inbuf, row, 0) < 0)
+ break;
+ compresspalette(outbuf, inbuf, w, red, green, blue);
+ if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
+ break;
+ }
+ break;
+ case pack(PHOTOMETRIC_RGB, PLANARCONFIG_CONTIG):
+ inbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
+ if (!inbuf)
+ {
+ fprintf(stderr, "Out of memory\n");
+ goto tiff2bw_error;
+ }
+ for (row = 0; row < h; row++)
+ {
+ if (TIFFReadScanline(in, inbuf, row, 0) < 0)
+ break;
+ compresscontig(outbuf, inbuf, w);
+ if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
+ break;
+ }
+ break;
+ case pack(PHOTOMETRIC_RGB, PLANARCONFIG_SEPARATE):
+ {
+ tmsize_t inbufsize;
+ rowsize = TIFFScanlineSize(in);
+ inbufsize = TIFFSafeMultiply(tmsize_t, 3, rowsize);
+ inbuf = (unsigned char *)_TIFFmalloc(inbufsize);
+ if (!inbuf)
+ {
+ fprintf(stderr, "Out of memory\n");
+ goto tiff2bw_error;
+ }
+ for (row = 0; row < h; row++)
+ {
+ for (s = 0; s < 3; s++)
+ if (TIFFReadScanline(in, inbuf + s * rowsize, row, s) < 0)
+ goto tiff2bw_error;
+ compresssep(outbuf, inbuf, inbuf + rowsize, inbuf + 2 * rowsize,
+ w);
+ if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
+ break;
+ }
+ break;
}
- }
+ }
#undef pack
- if (inbuf)
- _TIFFfree(inbuf);
- if (outbuf)
- _TIFFfree(outbuf);
+ if (inbuf)
+ _TIFFfree(inbuf);
+ if (outbuf)
+ _TIFFfree(outbuf);
+ TIFFClose(in);
+ TIFFClose(out);
+ return (EXIT_SUCCESS);
+
+tiff2bw_error:
+ if (inbuf)
+ _TIFFfree(inbuf);
+ if (outbuf)
+ _TIFFfree(outbuf);
+ if (out)
+ TIFFClose(out);
+ if (in)
TIFFClose(in);
- TIFFClose(out);
- return (EXIT_SUCCESS);
-
- tiff2bw_error:
- if (inbuf)
- _TIFFfree(inbuf);
- if (outbuf)
- _TIFFfree(outbuf);
- if (out)
- TIFFClose(out);
- if (in)
- TIFFClose(in);
- return (EXIT_FAILURE);
+ return (EXIT_FAILURE);
}
-static int
-processCompressOptions(char* opt)
+static int processCompressOptions(char *opt)
{
- if (streq(opt, "none"))
- compression = COMPRESSION_NONE;
- else if (streq(opt, "packbits"))
- compression = COMPRESSION_PACKBITS;
- else if (strneq(opt, "jpeg", 4)) {
- char* cp = strchr(opt, ':');
-
- compression = COMPRESSION_JPEG;
- while( cp )
- {
- if (isdigit((int)cp[1]))
- quality = atoi(cp+1);
- else if (cp[1] == 'r' )
- jpegcolormode = JPEGCOLORMODE_RAW;
- else
- usage(EXIT_FAILURE);
-
- cp = strchr(cp+1,':');
- }
- } else if (strneq(opt, "lzw", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_LZW;
- } else if (strneq(opt, "zip", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_ADOBE_DEFLATE;
- } else
- return (0);
- return (1);
+ if (streq(opt, "none"))
+ compression = COMPRESSION_NONE;
+ else if (streq(opt, "packbits"))
+ compression = COMPRESSION_PACKBITS;
+ else if (strneq(opt, "jpeg", 4))
+ {
+ char *cp = strchr(opt, ':');
+
+ compression = COMPRESSION_JPEG;
+ while (cp)
+ {
+ if (isdigit((int)cp[1]))
+ quality = atoi(cp + 1);
+ else if (cp[1] == 'r')
+ jpegcolormode = JPEGCOLORMODE_RAW;
+ else
+ usage(EXIT_FAILURE);
+
+ cp = strchr(cp + 1, ':');
+ }
+ }
+ else if (strneq(opt, "lzw", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_LZW;
+ }
+ else if (strneq(opt, "zip", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_ADOBE_DEFLATE;
+ }
+ else
+ return (0);
+ return (1);
}
-#define CopyField(tag, v) \
- if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
-#define CopyField2(tag, v1, v2) \
- if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
-#define CopyField3(tag, v1, v2, v3) \
- if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
-#define CopyField4(tag, v1, v2, v3, v4) \
- if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
-
-static void
-cpTag(TIFF* in, TIFF* out, uint16_t tag, uint16_t count, TIFFDataType type)
+#define CopyField(tag, v) \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v)
+#define CopyField2(tag, v1, v2) \
+ if (TIFFGetField(in, tag, &v1, &v2)) \
+ TIFFSetField(out, tag, v1, v2)
+#define CopyField3(tag, v1, v2, v3) \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) \
+ TIFFSetField(out, tag, v1, v2, v3)
+#define CopyField4(tag, v1, v2, v3, v4) \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) \
+ TIFFSetField(out, tag, v1, v2, v3, v4)
+
+static void cpTag(TIFF *in, TIFF *out, uint16_t tag, uint16_t count,
+ TIFFDataType type)
{
- switch (type) {
- case TIFF_SHORT:
- if (count == 1) {
- uint16_t shortv;
- CopyField(tag, shortv);
- } else if (count == 2) {
- uint16_t shortv1, shortv2;
- CopyField2(tag, shortv1, shortv2);
- } else if (count == 4) {
- uint16_t *tr, *tg, *tb, *ta;
- CopyField4(tag, tr, tg, tb, ta);
- } else if (count == (uint16_t) -1) {
- uint16_t shortv1;
- uint16_t* shortav;
- CopyField2(tag, shortv1, shortav);
- }
- break;
- case TIFF_LONG:
- { uint32_t longv;
- CopyField(tag, longv);
- }
- break;
- case TIFF_RATIONAL:
- if (count == 1) {
- float floatv;
- CopyField(tag, floatv);
- } else if (count == (uint16_t) -1) {
- float* floatav;
- CopyField(tag, floatav);
- }
- break;
- case TIFF_ASCII:
- { char* stringv;
- CopyField(tag, stringv);
- }
- break;
- case TIFF_DOUBLE:
- if (count == 1) {
- double doublev;
- CopyField(tag, doublev);
- } else if (count == (uint16_t) -1) {
- double* doubleav;
- CopyField(tag, doubleav);
- }
- break;
- default:
- TIFFError(TIFFFileName(in),
- "Data type %d is not supported, tag %d skipped.",
- tag, type);
- }
+ switch (type)
+ {
+ case TIFF_SHORT:
+ if (count == 1)
+ {
+ uint16_t shortv;
+ CopyField(tag, shortv);
+ }
+ else if (count == 2)
+ {
+ uint16_t shortv1, shortv2;
+ CopyField2(tag, shortv1, shortv2);
+ }
+ else if (count == 4)
+ {
+ uint16_t *tr, *tg, *tb, *ta;
+ CopyField4(tag, tr, tg, tb, ta);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ uint16_t shortv1;
+ uint16_t *shortav;
+ CopyField2(tag, shortv1, shortav);
+ }
+ break;
+ case TIFF_LONG:
+ {
+ uint32_t longv;
+ CopyField(tag, longv);
+ }
+ break;
+ case TIFF_RATIONAL:
+ if (count == 1)
+ {
+ float floatv;
+ CopyField(tag, floatv);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ float *floatav;
+ CopyField(tag, floatav);
+ }
+ break;
+ case TIFF_ASCII:
+ {
+ char *stringv;
+ CopyField(tag, stringv);
+ }
+ break;
+ case TIFF_DOUBLE:
+ if (count == 1)
+ {
+ double doublev;
+ CopyField(tag, doublev);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ double *doubleav;
+ CopyField(tag, doubleav);
+ }
+ break;
+ default:
+ TIFFError(TIFFFileName(in),
+ "Data type %d is not supported, tag %d skipped.", tag,
+ type);
+ }
}
#undef CopyField4
@@ -436,65 +473,65 @@ cpTag(TIFF* in, TIFF* out, uint16_t tag, uint16_t count, TIFFDataType type)
#undef CopyField2
#undef CopyField
-static const struct cpTag {
- uint16_t tag;
- uint16_t count;
- TIFFDataType type;
+static const struct cpTag
+{
+ uint16_t tag;
+ uint16_t count;
+ TIFFDataType type;
} tags[] = {
- { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
- { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
- { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
- { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
- { TIFFTAG_MAKE, 1, TIFF_ASCII },
- { TIFFTAG_MODEL, 1, TIFF_ASCII },
- { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
- { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
- { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
- { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
- { TIFFTAG_PAGENAME, 1, TIFF_ASCII },
- { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
- { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
- { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
- { TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
- { TIFFTAG_DATETIME, 1, TIFF_ASCII },
- { TIFFTAG_ARTIST, 1, TIFF_ASCII },
- { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
- { TIFFTAG_WHITEPOINT, 2, TIFF_RATIONAL },
- { TIFFTAG_PRIMARYCHROMATICITIES,(uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
- { TIFFTAG_INKSET, 1, TIFF_SHORT },
- { TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
- { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
- { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
- { TIFFTAG_YCBCRCOEFFICIENTS, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
- { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
- { TIFFTAG_REFERENCEBLACKWHITE, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_EXTRASAMPLES, (uint16_t) -1, TIFF_SHORT },
- { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE },
- { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE },
- { TIFFTAG_STONITS, 1, TIFF_DOUBLE },
+ {TIFFTAG_SUBFILETYPE, 1, TIFF_LONG},
+ {TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT},
+ {TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII},
+ {TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII},
+ {TIFFTAG_MAKE, 1, TIFF_ASCII},
+ {TIFFTAG_MODEL, 1, TIFF_ASCII},
+ {TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT},
+ {TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT},
+ {TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL},
+ {TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL},
+ {TIFFTAG_PAGENAME, 1, TIFF_ASCII},
+ {TIFFTAG_XPOSITION, 1, TIFF_RATIONAL},
+ {TIFFTAG_YPOSITION, 1, TIFF_RATIONAL},
+ {TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT},
+ {TIFFTAG_SOFTWARE, 1, TIFF_ASCII},
+ {TIFFTAG_DATETIME, 1, TIFF_ASCII},
+ {TIFFTAG_ARTIST, 1, TIFF_ASCII},
+ {TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII},
+ {TIFFTAG_WHITEPOINT, 2, TIFF_RATIONAL},
+ {TIFFTAG_PRIMARYCHROMATICITIES, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT},
+ {TIFFTAG_INKSET, 1, TIFF_SHORT},
+ {TIFFTAG_DOTRANGE, 2, TIFF_SHORT},
+ {TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII},
+ {TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT},
+ {TIFFTAG_YCBCRCOEFFICIENTS, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT},
+ {TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT},
+ {TIFFTAG_REFERENCEBLACKWHITE, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_EXTRASAMPLES, (uint16_t)-1, TIFF_SHORT},
+ {TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE},
+ {TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE},
+ {TIFFTAG_STONITS, 1, TIFF_DOUBLE},
};
-#define NTAGS (sizeof (tags) / sizeof (tags[0]))
+#define NTAGS (sizeof(tags) / sizeof(tags[0]))
-static void
-cpTags(TIFF* in, TIFF* out)
+static void cpTags(TIFF *in, TIFF *out)
{
const struct cpTag *p;
for (p = tags; p < &tags[NTAGS]; p++)
{
- if( p->tag == TIFFTAG_GROUP3OPTIONS )
+ if (p->tag == TIFFTAG_GROUP3OPTIONS)
{
uint16_t compression;
- if( !TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
- compression != COMPRESSION_CCITTFAX3 )
+ if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
+ compression != COMPRESSION_CCITTFAX3)
continue;
}
- if( p->tag == TIFFTAG_GROUP4OPTIONS )
+ if (p->tag == TIFFTAG_GROUP4OPTIONS)
{
uint16_t compression;
- if( !TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
- compression != COMPRESSION_CCITTFAX4 )
+ if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
+ compression != COMPRESSION_CCITTFAX4)
continue;
}
cpTag(in, out, p->tag, p->count, p->type);
@@ -503,45 +540,45 @@ cpTags(TIFF* in, TIFF* out)
#undef NTAGS
static const char usage_info[] =
-"Convert a color TIFF image to greyscale\n\n"
-"usage: tiff2bw [options] input.tif output.tif\n"
-"where options are:\n"
-" -R % use #% from red channel\n"
-" -G % use #% from green channel\n"
-" -B % use #% from blue channel\n"
-"\n"
-" -r # make each strip have no more than # rows\n"
-"\n"
+ "Convert a color TIFF image to greyscale\n\n"
+ "usage: tiff2bw [options] input.tif output.tif\n"
+ "where options are:\n"
+ " -R % use #% from red channel\n"
+ " -G % use #% from green channel\n"
+ " -B % use #% from blue channel\n"
+ "\n"
+ " -r # make each strip have no more than # rows\n"
+ "\n"
#ifdef LZW_SUPPORT
-" -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
-/* " LZW options:\n" */
-" # set predictor value\n"
-" For example, -c lzw:2 for LZW-encoded data with horizontal differencing\n"
+ " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
+ /* " LZW options:\n" */
+ " # set predictor value\n"
+ " For example, -c lzw:2 for LZW-encoded data with horizontal "
+ "differencing\n"
#endif
#ifdef ZIP_SUPPORT
-" -c zip[:opts] compress output with deflate encoding\n"
-/* " Deflate (ZIP) options:\n" */
-" # set predictor value\n"
+ " -c zip[:opts] compress output with deflate encoding\n"
+ /* " Deflate (ZIP) options:\n" */
+ " # set predictor value\n"
#endif
#ifdef PACKBITS_SUPPORT
-" -c packbits compress output with packbits encoding\n"
+ " -c packbits compress output with packbits encoding\n"
#endif
#ifdef CCITT_SUPPORT
-" -c g3[:opts] compress output with CCITT Group 3 encoding\n"
-" -c g4 compress output with CCITT Group 4 encoding\n"
+ " -c g3[:opts] compress output with CCITT Group 3 encoding\n"
+ " -c g4 compress output with CCITT Group 4 encoding\n"
#endif
-#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(PACKBITS_SUPPORT) || defined(CCITT_SUPPORT)
-" -c none use no compression algorithm on output\n"
+#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || \
+ defined(PACKBITS_SUPPORT) || defined(CCITT_SUPPORT)
+ " -c none use no compression algorithm on output\n"
#endif
-"\n"
-;
+ "\n";
-static void
-usage(int code)
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
diff --git a/tools/tiff2pdf.c b/tools/tiff2pdf.c
index b89014d0..1dbdc87a 100644
--- a/tools/tiff2pdf.c
+++ b/tools/tiff2pdf.c
@@ -4,356 +4,391 @@
*
* Copyright (c) 2003 Ross Finlayson
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the name of
* Ross Finlayson may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Ross Finlayson.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <ctype.h>
#include <time.h>
-#include <errno.h>
-#include <limits.h>
#if HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
-# include <fcntl.h>
+#include <fcntl.h>
#endif
#ifdef HAVE_IO_H
-# include <io.h>
+#include <io.h>
#endif
-#include "tiffiop.h"
-#include "tiffio.h"
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
+#include "tiffio.h"
+#include "tiffiop.h"
#ifndef EXIT_SUCCESS
-# define EXIT_SUCCESS 0
+#define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
-# define EXIT_FAILURE 1
+#define EXIT_FAILURE 1
#endif
#define TIFF2PDF_MODULE "tiff2pdf"
-#define PS_UNIT_SIZE 72.0F
+#define PS_UNIT_SIZE 72.0F
-#define TIFF_DIR_MAX 65534
+#define TIFF_DIR_MAX 65534
#define DEFAULT_MAX_MALLOC (256 * 1024 * 1024)
/* This type is of PDF color spaces. */
-typedef enum {
- T2P_CS_BILEVEL = 0x01, /* Bilevel, black and white */
- T2P_CS_GRAY = 0x02, /* Single channel */
- T2P_CS_RGB = 0x04, /* Three channel tristimulus RGB */
- T2P_CS_CMYK = 0x08, /* Four channel CMYK print inkset */
- T2P_CS_LAB = 0x10, /* Three channel L*a*b* color space */
- T2P_CS_PALETTE = 0x1000,/* One of the above with a color map */
- T2P_CS_CALGRAY = 0x20, /* Calibrated single channel */
- T2P_CS_CALRGB = 0x40, /* Calibrated three channel tristimulus RGB */
- T2P_CS_ICCBASED = 0x80 /* ICC profile color specification */
+typedef enum
+{
+ T2P_CS_BILEVEL = 0x01, /* Bilevel, black and white */
+ T2P_CS_GRAY = 0x02, /* Single channel */
+ T2P_CS_RGB = 0x04, /* Three channel tristimulus RGB */
+ T2P_CS_CMYK = 0x08, /* Four channel CMYK print inkset */
+ T2P_CS_LAB = 0x10, /* Three channel L*a*b* color space */
+ T2P_CS_PALETTE = 0x1000, /* One of the above with a color map */
+ T2P_CS_CALGRAY = 0x20, /* Calibrated single channel */
+ T2P_CS_CALRGB = 0x40, /* Calibrated three channel tristimulus RGB */
+ T2P_CS_ICCBASED = 0x80 /* ICC profile color specification */
} t2p_cs_t;
/* This type is of PDF compression types. */
-typedef enum{
- T2P_COMPRESS_NONE=0x00
+typedef enum
+{
+ T2P_COMPRESS_NONE = 0x00
#ifdef CCITT_SUPPORT
- , T2P_COMPRESS_G4=0x01
+ ,
+ T2P_COMPRESS_G4 = 0x01
#endif
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
- , T2P_COMPRESS_JPEG=0x02
+ ,
+ T2P_COMPRESS_JPEG = 0x02
#endif
#ifdef ZIP_SUPPORT
- , T2P_COMPRESS_ZIP=0x04
+ ,
+ T2P_COMPRESS_ZIP = 0x04
#endif
} t2p_compress_t;
-/* This type is whether TIFF image data can be used in PDF without transcoding. */
-typedef enum{
- T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */
- T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */
+/* This type is whether TIFF image data can be used in PDF without transcoding.
+ */
+typedef enum
+{
+ T2P_TRANSCODE_RAW = 0x01, /* The raw data from the input can be used without
+ recompressing */
+ T2P_TRANSCODE_ENCODE =
+ 0x02 /* The data from the input is perhaps unencoded and reencoded */
} t2p_transcode_t;
/* This type is of information about the data samples of the input image. */
-typedef enum{
- T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */
- T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */
- T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */
- T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */
- T2P_SAMPLE_YCBCR_TO_RGB=0x0008,
- T2P_SAMPLE_YCBCR_TO_LAB=0x0010,
- T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */
- T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */
- T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */
- T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */
+typedef enum
+{
+ T2P_SAMPLE_NOTHING =
+ 0x0000, /* The unencoded samples are normal for the output colorspace */
+ T2P_SAMPLE_ABGR_TO_RGB =
+ 0x0001, /* The unencoded samples are the result of ReadRGBAImage */
+ T2P_SAMPLE_RGBA_TO_RGB =
+ 0x0002, /* The unencoded samples are contiguous RGBA */
+ T2P_SAMPLE_RGBAA_TO_RGB =
+ 0x0004, /* The unencoded samples are RGBA with premultiplied alpha */
+ T2P_SAMPLE_YCBCR_TO_RGB = 0x0008,
+ T2P_SAMPLE_YCBCR_TO_LAB = 0x0010,
+ T2P_SAMPLE_REALIZE_PALETTE =
+ 0x0020, /* The unencoded samples are indexes into the color map */
+ T2P_SAMPLE_SIGNED_TO_UNSIGNED =
+ 0x0040, /* The unencoded samples are signed instead of unsignd */
+ T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED =
+ 0x0040, /* The L*a*b* samples have a* and b* signed */
+ T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG =
+ 0x0100 /* The unencoded samples are separate instead of contiguous */
} t2p_sample_t;
/* This type is of error status of the T2P struct. */
-typedef enum{
- T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */
- T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */
+typedef enum
+{
+ T2P_ERR_OK =
+ 0, /* This is the value of t2p->t2p_error when there is no error */
+ T2P_ERR_ERROR =
+ 1 /* This is the value of t2p->t2p_error when there was an error */
} t2p_err_t;
/* This struct defines a logical page of a TIFF. */
-typedef struct {
- tdir_t page_directory;
- uint32_t page_number;
- ttile_t page_tilecount;
- uint32_t page_extra;
+typedef struct
+{
+ tdir_t page_directory;
+ uint32_t page_number;
+ ttile_t page_tilecount;
+ uint32_t page_extra;
} T2P_PAGE;
/* This struct defines a PDF rectangle's coordinates. */
-typedef struct {
- float x1;
- float y1;
- float x2;
- float y2;
- float mat[9];
+typedef struct
+{
+ float x1;
+ float y1;
+ float x2;
+ float y2;
+ float mat[9];
} T2P_BOX;
/* This struct defines a tile of a PDF. */
-typedef struct {
- T2P_BOX tile_box;
+typedef struct
+{
+ T2P_BOX tile_box;
} T2P_TILE;
/* This struct defines information about the tiles on a PDF page. */
-typedef struct {
- ttile_t tiles_tilecount;
- uint32_t tiles_tilewidth;
- uint32_t tiles_tilelength;
- uint32_t tiles_tilecountx;
- uint32_t tiles_tilecounty;
- uint32_t tiles_edgetilewidth;
- uint32_t tiles_edgetilelength;
- T2P_TILE* tiles_tiles;
+typedef struct
+{
+ ttile_t tiles_tilecount;
+ uint32_t tiles_tilewidth;
+ uint32_t tiles_tilelength;
+ uint32_t tiles_tilecountx;
+ uint32_t tiles_tilecounty;
+ uint32_t tiles_edgetilewidth;
+ uint32_t tiles_edgetilelength;
+ T2P_TILE *tiles_tiles;
} T2P_TILES;
/* This struct is the context of a function to generate PDF from a TIFF. */
-typedef struct {
- t2p_err_t t2p_error;
- T2P_PAGE* tiff_pages;
- T2P_TILES* tiff_tiles;
- tdir_t tiff_pagecount;
- uint16_t tiff_compression;
- uint16_t tiff_photometric;
- uint16_t tiff_fillorder;
- uint16_t tiff_bitspersample;
- uint16_t tiff_samplesperpixel;
- uint16_t tiff_planar;
- uint32_t tiff_width;
- uint32_t tiff_length;
- float tiff_xres;
- float tiff_yres;
- uint16_t tiff_orientation;
- toff_t tiff_dataoffset;
- tsize_t tiff_datasize;
- tsize_t tiff_maxdatasize;
- uint16_t tiff_resunit;
- uint16_t pdf_centimeters;
- uint16_t pdf_overrideres;
- uint16_t pdf_overridepagesize;
- float pdf_defaultxres;
- float pdf_defaultyres;
- float pdf_xres;
- float pdf_yres;
- float pdf_defaultpagewidth;
- float pdf_defaultpagelength;
- float pdf_pagewidth;
- float pdf_pagelength;
- float pdf_imagewidth;
- float pdf_imagelength;
- int pdf_image_fillpage; /* 0 (default: no scaling, 1:scale imagesize to pagesize */
- T2P_BOX pdf_mediabox;
- T2P_BOX pdf_imagebox;
- uint16_t pdf_majorversion;
- uint16_t pdf_minorversion;
- uint32_t pdf_catalog;
- uint32_t pdf_pages;
- uint32_t pdf_info;
- uint32_t pdf_palettecs;
- uint16_t pdf_fitwindow;
- uint32_t pdf_startxref;
+typedef struct
+{
+ t2p_err_t t2p_error;
+ T2P_PAGE *tiff_pages;
+ T2P_TILES *tiff_tiles;
+ tdir_t tiff_pagecount;
+ uint16_t tiff_compression;
+ uint16_t tiff_photometric;
+ uint16_t tiff_fillorder;
+ uint16_t tiff_bitspersample;
+ uint16_t tiff_samplesperpixel;
+ uint16_t tiff_planar;
+ uint32_t tiff_width;
+ uint32_t tiff_length;
+ float tiff_xres;
+ float tiff_yres;
+ uint16_t tiff_orientation;
+ toff_t tiff_dataoffset;
+ tsize_t tiff_datasize;
+ tsize_t tiff_maxdatasize;
+ uint16_t tiff_resunit;
+ uint16_t pdf_centimeters;
+ uint16_t pdf_overrideres;
+ uint16_t pdf_overridepagesize;
+ float pdf_defaultxres;
+ float pdf_defaultyres;
+ float pdf_xres;
+ float pdf_yres;
+ float pdf_defaultpagewidth;
+ float pdf_defaultpagelength;
+ float pdf_pagewidth;
+ float pdf_pagelength;
+ float pdf_imagewidth;
+ float pdf_imagelength;
+ int pdf_image_fillpage; /* 0 (default: no scaling, 1:scale imagesize to
+ pagesize */
+ T2P_BOX pdf_mediabox;
+ T2P_BOX pdf_imagebox;
+ uint16_t pdf_majorversion;
+ uint16_t pdf_minorversion;
+ uint32_t pdf_catalog;
+ uint32_t pdf_pages;
+ uint32_t pdf_info;
+ uint32_t pdf_palettecs;
+ uint16_t pdf_fitwindow;
+ uint32_t pdf_startxref;
#define TIFF2PDF_FILEID_SIZE 33
- char pdf_fileid[TIFF2PDF_FILEID_SIZE];
+ char pdf_fileid[TIFF2PDF_FILEID_SIZE];
#define TIFF2PDF_DATETIME_SIZE 17
- char pdf_datetime[TIFF2PDF_DATETIME_SIZE];
+ char pdf_datetime[TIFF2PDF_DATETIME_SIZE];
#define TIFF2PDF_CREATOR_SIZE 512
- char pdf_creator[TIFF2PDF_CREATOR_SIZE];
- int pdf_creator_set;
+ char pdf_creator[TIFF2PDF_CREATOR_SIZE];
+ int pdf_creator_set;
#define TIFF2PDF_AUTHOR_SIZE 512
- char pdf_author[TIFF2PDF_AUTHOR_SIZE];
- int pdf_author_set;
+ char pdf_author[TIFF2PDF_AUTHOR_SIZE];
+ int pdf_author_set;
#define TIFF2PDF_TITLE_SIZE 512
- char pdf_title[TIFF2PDF_TITLE_SIZE];
- int pdf_title_set;
+ char pdf_title[TIFF2PDF_TITLE_SIZE];
+ int pdf_title_set;
#define TIFF2PDF_SUBJECT_SIZE 512
- char pdf_subject[TIFF2PDF_SUBJECT_SIZE];
- int pdf_subject_set;
+ char pdf_subject[TIFF2PDF_SUBJECT_SIZE];
+ int pdf_subject_set;
#define TIFF2PDF_KEYWORDS_SIZE 512
- char pdf_keywords[TIFF2PDF_KEYWORDS_SIZE];
- int pdf_keywords_set;
- t2p_cs_t pdf_colorspace;
- uint16_t pdf_colorspace_invert;
- uint16_t pdf_switchdecode;
- uint16_t pdf_palettesize;
- unsigned char* pdf_palette;
- int pdf_labrange[4];
- t2p_compress_t pdf_defaultcompression;
- uint16_t pdf_defaultcompressionquality;
- t2p_compress_t pdf_compression;
- uint16_t pdf_compressionquality; /* for deflate : 100 * zipquality + predictor */
- uint16_t pdf_nopassthrough;
- t2p_transcode_t pdf_transcode;
- t2p_sample_t pdf_sample;
- uint32_t* pdf_xrefoffsets;
- uint32_t pdf_xrefcount;
- tdir_t pdf_page;
+ char pdf_keywords[TIFF2PDF_KEYWORDS_SIZE];
+ int pdf_keywords_set;
+ t2p_cs_t pdf_colorspace;
+ uint16_t pdf_colorspace_invert;
+ uint16_t pdf_switchdecode;
+ uint16_t pdf_palettesize;
+ unsigned char *pdf_palette;
+ int pdf_labrange[4];
+ t2p_compress_t pdf_defaultcompression;
+ uint16_t pdf_defaultcompressionquality;
+ t2p_compress_t pdf_compression;
+ uint16_t
+ pdf_compressionquality; /* for deflate : 100 * zipquality + predictor */
+ uint16_t pdf_nopassthrough;
+ t2p_transcode_t pdf_transcode;
+ t2p_sample_t pdf_sample;
+ uint32_t *pdf_xrefoffsets;
+ uint32_t pdf_xrefcount;
+ tdir_t pdf_page;
#ifdef OJPEG_SUPPORT
- tdata_t pdf_ojpegdata;
- uint32_t pdf_ojpegdatalength;
- uint32_t pdf_ojpegiflength;
+ tdata_t pdf_ojpegdata;
+ uint32_t pdf_ojpegdatalength;
+ uint32_t pdf_ojpegiflength;
#endif
- float tiff_whitechromaticities[2];
- float tiff_primarychromaticities[6];
- float tiff_referenceblackwhite[2];
- uint16_t* tiff_transferfunction[3];
- int pdf_image_interpolate; /* 0 (default) : do not interpolate,
- 1 : interpolate */
- uint16_t tiff_transferfunctioncount;
- uint32_t pdf_icccs;
- uint32_t tiff_iccprofilelength;
- tdata_t tiff_iccprofile;
-
- /* fields for custom read/write procedures */
- FILE *outputfile;
- int outputdisable;
- tsize_t outputwritten;
+ float tiff_whitechromaticities[2];
+ float tiff_primarychromaticities[6];
+ float tiff_referenceblackwhite[2];
+ uint16_t *tiff_transferfunction[3];
+ int pdf_image_interpolate; /* 0 (default) : do not interpolate,
+ 1 : interpolate */
+ uint16_t tiff_transferfunctioncount;
+ uint32_t pdf_icccs;
+ uint32_t tiff_iccprofilelength;
+ tdata_t tiff_iccprofile;
+
+ /* fields for custom read/write procedures */
+ FILE *outputfile;
+ int outputdisable;
+ tsize_t outputwritten;
} T2P;
/* These functions are called by main. */
static void usage_info(int);
-int tiff2pdf_match_paper_size(float*, float*, char*);
+int tiff2pdf_match_paper_size(float *, float *, char *);
-/* These functions are used to generate a PDF from a TIFF. */
+/* These functions are used to generate a PDF from a TIFF. */
#ifdef __cplusplus
-extern "C" {
+extern "C"
+{
#endif
-T2P* t2p_init(void);
-void t2p_validate(T2P*);
-tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*);
-void t2p_free(T2P*);
+ T2P *t2p_init(void);
+ void t2p_validate(T2P *);
+ tsize_t t2p_write_pdf(T2P *, TIFF *, TIFF *);
+ void t2p_free(T2P *);
#ifdef __cplusplus
}
#endif
-void t2p_read_tiff_init(T2P*, TIFF*);
-int t2p_cmp_t2p_page(const void*, const void*);
-void t2p_read_tiff_data(T2P*, TIFF*);
-void t2p_read_tiff_size(T2P*, TIFF*);
-void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t);
+void t2p_read_tiff_init(T2P *, TIFF *);
+int t2p_cmp_t2p_page(const void *, const void *);
+void t2p_read_tiff_data(T2P *, TIFF *);
+void t2p_read_tiff_size(T2P *, TIFF *);
+void t2p_read_tiff_size_tile(T2P *, TIFF *, ttile_t);
int t2p_tile_is_right_edge(T2P_TILES, ttile_t);
int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t);
int t2p_tile_is_edge(T2P_TILES, ttile_t);
int t2p_tile_is_corner_edge(T2P_TILES, ttile_t);
-tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*);
-tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t);
+tsize_t t2p_readwrite_pdf_image(T2P *, TIFF *, TIFF *);
+tsize_t t2p_readwrite_pdf_image_tile(T2P *, TIFF *, TIFF *, ttile_t);
#ifdef OJPEG_SUPPORT
-int t2p_process_ojpeg_tables(T2P*, TIFF*);
+int t2p_process_ojpeg_tables(T2P *, TIFF *);
#endif
#ifdef JPEG_SUPPORT
-int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t, tsize_t*, tstrip_t, uint32_t);
+int t2p_process_jpeg_strip(unsigned char *, tsize_t *, unsigned char *, tsize_t,
+ tsize_t *, tstrip_t, uint32_t);
#endif
void t2p_tile_collapse_left(tdata_t, tsize_t, uint32_t, uint32_t, uint32_t);
-void t2p_write_advance_directory(T2P*, TIFF*);
-tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t);
-tsize_t t2p_sample_realize_palette(T2P*, unsigned char*);
+void t2p_write_advance_directory(T2P *, TIFF *);
+tsize_t t2p_sample_planar_separate_to_contig(T2P *, unsigned char *,
+ unsigned char *, tsize_t);
+tsize_t t2p_sample_realize_palette(T2P *, unsigned char *);
tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32_t);
tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32_t);
tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32_t);
tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32_t);
-tsize_t t2p_write_pdf_header(T2P*, TIFF*);
-tsize_t t2p_write_pdf_obj_start(uint32_t, TIFF*);
-tsize_t t2p_write_pdf_obj_end(TIFF*);
-tsize_t t2p_write_pdf_name(const unsigned char*, TIFF*);
-tsize_t t2p_write_pdf_string(const char*, TIFF*);
-tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*);
-tsize_t t2p_write_pdf_stream_start(TIFF*);
-tsize_t t2p_write_pdf_stream_end(TIFF*);
-tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32_t, TIFF*);
-tsize_t t2p_write_pdf_stream_dict_start(TIFF*);
-tsize_t t2p_write_pdf_stream_dict_end(TIFF*);
-tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*);
-tsize_t t2p_write_pdf_catalog(T2P*, TIFF*);
-tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*);
-void t2p_pdf_currenttime(T2P*);
-void t2p_pdf_tifftime(T2P*, TIFF*);
-tsize_t t2p_write_pdf_pages(T2P*, TIFF*);
-tsize_t t2p_write_pdf_page(uint32_t, T2P*, TIFF*);
-void t2p_compose_pdf_page(T2P*);
-void t2p_compose_pdf_page_orient(T2P_BOX*, uint16_t);
-void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16_t);
-tsize_t t2p_write_pdf_page_content(T2P*, TIFF*);
-tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P*, TIFF*);
-tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*);
-tsize_t t2p_write_pdf_transfer(T2P*, TIFF*);
-tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16_t);
-tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16_t);
-tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*);
-tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*);
-tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*);
-tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*);
-tsize_t t2p_write_pdf_xobject_cs_stream(T2P*, TIFF*);
-tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*);
-tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*);
-tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*);
-tsize_t t2p_write_pdf_trailer(T2P*, TIFF*);
-
-#define check_snprintf_ret(t2p, rv, buf) do { \
- if ((rv) < 0) rv = 0; \
- else if((rv) >= (int)sizeof(buf)) (rv) = sizeof(buf) - 1; \
- else break; \
- if ((t2p) != NULL) (t2p)->t2p_error = T2P_ERR_ERROR; \
-} while(0)
-
-static void
-t2p_disable(TIFF *tif)
+tsize_t t2p_write_pdf_header(T2P *, TIFF *);
+tsize_t t2p_write_pdf_obj_start(uint32_t, TIFF *);
+tsize_t t2p_write_pdf_obj_end(TIFF *);
+tsize_t t2p_write_pdf_name(const unsigned char *, TIFF *);
+tsize_t t2p_write_pdf_string(const char *, TIFF *);
+tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF *);
+tsize_t t2p_write_pdf_stream_start(TIFF *);
+tsize_t t2p_write_pdf_stream_end(TIFF *);
+tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32_t, TIFF *);
+tsize_t t2p_write_pdf_stream_dict_start(TIFF *);
+tsize_t t2p_write_pdf_stream_dict_end(TIFF *);
+tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF *);
+tsize_t t2p_write_pdf_catalog(T2P *, TIFF *);
+tsize_t t2p_write_pdf_info(T2P *, TIFF *, TIFF *);
+void t2p_pdf_currenttime(T2P *);
+void t2p_pdf_tifftime(T2P *, TIFF *);
+tsize_t t2p_write_pdf_pages(T2P *, TIFF *);
+tsize_t t2p_write_pdf_page(uint32_t, T2P *, TIFF *);
+void t2p_compose_pdf_page(T2P *);
+void t2p_compose_pdf_page_orient(T2P_BOX *, uint16_t);
+void t2p_compose_pdf_page_orient_flip(T2P_BOX *, uint16_t);
+tsize_t t2p_write_pdf_page_content(T2P *, TIFF *);
+tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P *, TIFF *);
+tsize_t t2p_write_pdf_xobject_cs(T2P *, TIFF *);
+tsize_t t2p_write_pdf_transfer(T2P *, TIFF *);
+tsize_t t2p_write_pdf_transfer_dict(T2P *, TIFF *, uint16_t);
+tsize_t t2p_write_pdf_transfer_stream(T2P *, TIFF *, uint16_t);
+tsize_t t2p_write_pdf_xobject_calcs(T2P *, TIFF *);
+tsize_t t2p_write_pdf_xobject_icccs(T2P *, TIFF *);
+tsize_t t2p_write_pdf_xobject_icccs_dict(T2P *, TIFF *);
+tsize_t t2p_write_pdf_xobject_icccs_stream(T2P *, TIFF *);
+tsize_t t2p_write_pdf_xobject_cs_stream(T2P *, TIFF *);
+tsize_t t2p_write_pdf_xobject_decode(T2P *, TIFF *);
+tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P *, TIFF *);
+tsize_t t2p_write_pdf_xreftable(T2P *, TIFF *);
+tsize_t t2p_write_pdf_trailer(T2P *, TIFF *);
+
+#define check_snprintf_ret(t2p, rv, buf) \
+ do \
+ { \
+ if ((rv) < 0) \
+ rv = 0; \
+ else if ((rv) >= (int)sizeof(buf)) \
+ (rv) = sizeof(buf) - 1; \
+ else \
+ break; \
+ if ((t2p) != NULL) \
+ (t2p)->t2p_error = T2P_ERR_ERROR; \
+ } while (0)
+
+static void t2p_disable(TIFF *tif)
{
- T2P *t2p = (T2P*) TIFFClientdata(tif);
- t2p->outputdisable = 1;
+ T2P *t2p = (T2P *)TIFFClientdata(tif);
+ t2p->outputdisable = 1;
}
-static void
-t2p_enable(TIFF *tif)
+static void t2p_enable(TIFF *tif)
{
- T2P *t2p = (T2P*) TIFFClientdata(tif);
- t2p->outputdisable = 0;
+ T2P *t2p = (T2P *)TIFFClientdata(tif);
+ t2p->outputdisable = 0;
}
/*
@@ -361,189 +396,180 @@ t2p_enable(TIFF *tif)
*/
#ifdef OJPEG_SUPPORT
-static tmsize_t
-t2pReadFile(TIFF *tif, tdata_t data, tmsize_t size)
+static tmsize_t t2pReadFile(TIFF *tif, tdata_t data, tmsize_t size)
{
- thandle_t client = TIFFClientdata(tif);
- TIFFReadWriteProc proc = TIFFGetReadProc(tif);
- if (proc)
- return proc(client, data, size);
- return -1;
+ thandle_t client = TIFFClientdata(tif);
+ TIFFReadWriteProc proc = TIFFGetReadProc(tif);
+ if (proc)
+ return proc(client, data, size);
+ return -1;
}
#endif /* OJPEG_SUPPORT */
-static tmsize_t
-t2pWriteFile(TIFF *tif, tdata_t data, tmsize_t size)
+static tmsize_t t2pWriteFile(TIFF *tif, tdata_t data, tmsize_t size)
{
- thandle_t client = TIFFClientdata(tif);
- TIFFReadWriteProc proc = TIFFGetWriteProc(tif);
- if (proc)
- return proc(client, data, size);
- return -1;
+ thandle_t client = TIFFClientdata(tif);
+ TIFFReadWriteProc proc = TIFFGetWriteProc(tif);
+ if (proc)
+ return proc(client, data, size);
+ return -1;
}
-static uint64_t
-t2pSeekFile(TIFF *tif, toff_t offset, int whence)
+static uint64_t t2pSeekFile(TIFF *tif, toff_t offset, int whence)
{
- thandle_t client = TIFFClientdata(tif);
- TIFFSeekProc proc = TIFFGetSeekProc(tif);
- if (proc)
- return proc(client, offset, whence);
- return -1;
+ thandle_t client = TIFFClientdata(tif);
+ TIFFSeekProc proc = TIFFGetSeekProc(tif);
+ if (proc)
+ return proc(client, offset, whence);
+ return -1;
}
-static tmsize_t
-t2p_readproc(thandle_t handle, tdata_t data, tmsize_t size)
+static tmsize_t t2p_readproc(thandle_t handle, tdata_t data, tmsize_t size)
{
- (void) handle, (void) data, (void) size;
- return -1;
+ (void)handle, (void)data, (void)size;
+ return -1;
}
-static tmsize_t
-t2p_writeproc(thandle_t handle, tdata_t data, tmsize_t size)
+static tmsize_t t2p_writeproc(thandle_t handle, tdata_t data, tmsize_t size)
{
- T2P *t2p = (T2P*) handle;
- if (t2p->outputdisable <= 0 && t2p->outputfile) {
- tsize_t written = fwrite(data, 1, size, t2p->outputfile);
- t2p->outputwritten += written;
- return written;
- }
- return size;
+ T2P *t2p = (T2P *)handle;
+ if (t2p->outputdisable <= 0 && t2p->outputfile)
+ {
+ tsize_t written = fwrite(data, 1, size, t2p->outputfile);
+ t2p->outputwritten += written;
+ return written;
+ }
+ return size;
}
-static uint64_t
-t2p_seekproc(thandle_t handle, uint64_t offset, int whence)
-{
- T2P *t2p = (T2P*) handle;
- if (t2p->outputdisable <= 0 && t2p->outputfile != stdout && t2p->outputfile)
- return _TIFF_fseek_f(t2p->outputfile, (_TIFF_off_t) offset, whence);
- return offset;
+static uint64_t t2p_seekproc(thandle_t handle, uint64_t offset, int whence)
+{
+ T2P *t2p = (T2P *)handle;
+ if (t2p->outputdisable <= 0 && t2p->outputfile != stdout && t2p->outputfile)
+ return _TIFF_fseek_f(t2p->outputfile, (_TIFF_off_t)offset, whence);
+ return offset;
}
-static int
-t2p_closeproc(thandle_t handle)
-{
- T2P *t2p = (T2P*) handle;
- return fclose(t2p->outputfile);
+static int t2p_closeproc(thandle_t handle)
+{
+ T2P *t2p = (T2P *)handle;
+ return fclose(t2p->outputfile);
}
-static uint64_t
-t2p_sizeproc(thandle_t handle)
+static uint64_t t2p_sizeproc(thandle_t handle)
{
- (void) handle;
- return -1;
+ (void)handle;
+ return -1;
}
-static int
-t2p_mapproc(thandle_t handle, void **data, toff_t *offset)
-{
- (void) handle, (void) data, (void) offset;
- return -1;
+static int t2p_mapproc(thandle_t handle, void **data, toff_t *offset)
+{
+ (void)handle, (void)data, (void)offset;
+ return -1;
}
-static void
-t2p_unmapproc(thandle_t handle, void *data, toff_t offset)
-{
- (void) handle, (void) data, (void) offset;
+static void t2p_unmapproc(thandle_t handle, void *data, toff_t offset)
+{
+ (void)handle, (void)data, (void)offset;
}
#if defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT)
-static uint64_t
-checkAdd64(uint64_t summand1, uint64_t summand2, T2P* t2p)
+static uint64_t checkAdd64(uint64_t summand1, uint64_t summand2, T2P *t2p)
{
- uint64_t bytes = summand1 + summand2;
+ uint64_t bytes = summand1 + summand2;
- if (bytes < summand1) {
- TIFFError(TIFF2PDF_MODULE, "Integer overflow");
- t2p->t2p_error = T2P_ERR_ERROR;
- bytes = 0;
- }
+ if (bytes < summand1)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+ t2p->t2p_error = T2P_ERR_ERROR;
+ bytes = 0;
+ }
- return bytes;
+ return bytes;
}
#endif /* defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) */
-static uint64_t
-checkMultiply64(uint64_t first, uint64_t second, T2P* t2p)
+static uint64_t checkMultiply64(uint64_t first, uint64_t second, T2P *t2p)
{
- uint64_t bytes = first * second;
+ uint64_t bytes = first * second;
- if (second && bytes / second != first) {
- TIFFError(TIFF2PDF_MODULE, "Integer overflow");
- t2p->t2p_error = T2P_ERR_ERROR;
- bytes = 0;
- }
+ if (second && bytes / second != first)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+ t2p->t2p_error = T2P_ERR_ERROR;
+ bytes = 0;
+ }
- return bytes;
+ return bytes;
}
/*
This is the main function.
- The program converts one TIFF file to one PDF file, including multiple page
- TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF
- files that contain data of TIFF photometric interpretations of bilevel,
- grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by
+ The program converts one TIFF file to one PDF file, including multiple page
+ TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF
+ files that contain data of TIFF photometric interpretations of bilevel,
+ grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by
libtiff and PDF.
- If you have multiple TIFF files to convert into one PDF file then use tiffcp
- or other program to concatenate the files into a multiple page TIFF file.
+ If you have multiple TIFF files to convert into one PDF file then use tiffcp
+ or other program to concatenate the files into a multiple page TIFF file.
If the input TIFF file is of huge dimensions (greater than 10000 pixels height
or width) convert the input image to a tiled TIFF if it is not already.
- The standard output is standard output. Set the output file name with the
+ The standard output is standard output. Set the output file name with the
"-o output.pdf" option.
- All black and white files are compressed into a single strip CCITT G4 Fax
- compressed PDF, unless tiled, where tiled black and white images are
- compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support
+ All black and white files are compressed into a single strip CCITT G4 Fax
+ compressed PDF, unless tiled, where tiled black and white images are
+ compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support
is assumed.
- Color and grayscale data can be compressed using either JPEG compression,
- ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set
- the compression type using the -j or -z options. JPEG compression support
- requires that libtiff be configured with JPEG support, and Zip/Deflate
- compression support requires that libtiff is configured with Zip support,
- in tiffconf.h. Use only one or the other of -j and -z. The -q option
- sets the image compression quality, that is 1-100 with libjpeg JPEG
- compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression
+ Color and grayscale data can be compressed using either JPEG compression,
+ ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set
+ the compression type using the -j or -z options. JPEG compression support
+ requires that libtiff be configured with JPEG support, and Zip/Deflate
+ compression support requires that libtiff is configured with Zip support,
+ in tiffconf.h. Use only one or the other of -j and -z. The -q option
+ sets the image compression quality, that is 1-100 with libjpeg JPEG
+ compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression
predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9.
PNG Group differencing predictor methods are not currently implemented.
- If the input TIFF contains single strip CCITT G4 Fax compressed information,
- then that is written to the PDF file without transcoding, unless the options
+ If the input TIFF contains single strip CCITT G4 Fax compressed information,
+ then that is written to the PDF file without transcoding, unless the options
of no compression and no passthrough are set, -d and -n.
- If the input TIFF contains JPEG or single strip Zip/Deflate compressed
- information, and they are configured, then that is written to the PDF file
- without transcoding, unless the options of no compression and no passthrough
+ If the input TIFF contains JPEG or single strip Zip/Deflate compressed
+ information, and they are configured, then that is written to the PDF file
+ without transcoding, unless the options of no compression and no passthrough
are set.
- The default page size upon which the TIFF image is placed is determined by
- the resolution and extent of the image data. Default values for the TIFF
- image resolution can be set using the -x and -y options. The page size can
- be set using the -p option for paper size, or -w and -l for paper width and
- length, then each page of the TIFF image is centered on its page. The
- distance unit for default resolution and page width and length can be set
+ The default page size upon which the TIFF image is placed is determined by
+ the resolution and extent of the image data. Default values for the TIFF
+ image resolution can be set using the -x and -y options. The page size can
+ be set using the -p option for paper size, or -w and -l for paper width and
+ length, then each page of the TIFF image is centered on its page. The
+ distance unit for default resolution and page width and length can be set
by the -u option, the default unit is inch.
- Various items of the output document information can be set with the -e, -c,
- -a, -t, -s, and -k tags. Setting the argument of the option to "" for these
- tags causes the relevant document information field to be not written. Some
- of the document information values otherwise get their information from the
+ Various items of the output document information can be set with the -e, -c,
+ -a, -t, -s, and -k tags. Setting the argument of the option to "" for these
+ tags causes the relevant document information field to be not written. Some
+ of the document information values otherwise get their information from the
input TIFF image, the software, author, document name, and image description.
- The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using
- Zip/Deflate compression.
-
- The Portable Document Format (PDF) specification is copyrighted by Adobe
+ The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using
+ Zip/Deflate compression.
+
+ The Portable Document Format (PDF) specification is copyrighted by Adobe
Systems, Incorporated. Todos derechos reservados.
- Here is a listing of the usage example and the options to the tiff2pdf
- program that is part of the libtiff distribution. Options followed by
+ Here is a listing of the usage example and the options to the tiff2pdf
+ program that is part of the libtiff distribution. Options followed by
a colon have a required argument.
-
+
usage: tiff2pdf [options] input.tif
options:
@@ -595,685 +621,741 @@ printf (-z: compress with Zip/Deflate (requires zlib configured with libtiff));
putting the image pages on a letter sized page, compressing the output
with JPEG.
- Please report bugs through:
+ Please report bugs through:
- http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff
+ http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff
See also libtiff.3t, tiffcp.
*/
-int main(int argc, char** argv){
+int main(int argc, char **argv)
+{
#if !HAVE_DECL_OPTARG
- extern char *optarg;
- extern int optind;
+ extern char *optarg;
+ extern int optind;
#endif
- const char *outfilename = NULL;
- T2P *t2p = NULL;
- TIFF *input = NULL, *output = NULL;
- int c, ret = EXIT_SUCCESS;
-
- t2p = t2p_init();
-
- if (t2p == NULL){
- TIFFError(TIFF2PDF_MODULE, "Can't initialize context");
- goto fail;
- }
-
- while (argv &&
- (c = getopt(argc, argv,
- "m:o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbhF")) != -1){
- switch (c) {
- case 'm':
- t2p->tiff_maxdatasize = (tsize_t)strtoul(optarg, NULL, 0) << 20;
- break;
- case 'o':
- outfilename = optarg;
- break;
+ const char *outfilename = NULL;
+ T2P *t2p = NULL;
+ TIFF *input = NULL, *output = NULL;
+ int c, ret = EXIT_SUCCESS;
+
+ t2p = t2p_init();
+
+ if (t2p == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Can't initialize context");
+ goto fail;
+ }
+
+ while (argv &&
+ (c = getopt(argc, argv,
+ "m:o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbhF")) != -1)
+ {
+ switch (c)
+ {
+ case 'm':
+ t2p->tiff_maxdatasize = (tsize_t)strtoul(optarg, NULL, 0) << 20;
+ break;
+ case 'o':
+ outfilename = optarg;
+ break;
#ifdef JPEG_SUPPORT
- case 'j':
- t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG;
- break;
+ case 'j':
+ t2p->pdf_defaultcompression = T2P_COMPRESS_JPEG;
+ break;
#endif
#ifndef JPEG_SUPPORT
- case 'j':
- TIFFWarning(
- TIFF2PDF_MODULE,
- "JPEG support in libtiff required for JPEG compression, ignoring option");
- break;
+ case 'j':
+ TIFFWarning(TIFF2PDF_MODULE,
+ "JPEG support in libtiff required for JPEG "
+ "compression, ignoring option");
+ break;
#endif
#ifdef ZIP_SUPPORT
- case 'z':
- t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP;
- break;
+ case 'z':
+ t2p->pdf_defaultcompression = T2P_COMPRESS_ZIP;
+ break;
#endif
#ifndef ZIP_SUPPORT
- case 'z':
- TIFFWarning(
- TIFF2PDF_MODULE,
- "Zip support in libtiff required for Zip compression, ignoring option");
- break;
+ case 'z':
+ TIFFWarning(TIFF2PDF_MODULE,
+ "Zip support in libtiff required for Zip "
+ "compression, ignoring option");
+ break;
#endif
- case 'q':
- t2p->pdf_defaultcompressionquality=atoi(optarg);
- break;
- case 'n':
- t2p->pdf_nopassthrough=1;
- break;
- case 'd':
- t2p->pdf_defaultcompression=T2P_COMPRESS_NONE;
- break;
- case 'u':
- if(optarg[0]=='m'){
- t2p->pdf_centimeters=1;
- }
- break;
- case 'x':
- t2p->pdf_defaultxres =
- (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
- break;
- case 'y':
- t2p->pdf_defaultyres =
- (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
- break;
- case 'w':
- t2p->pdf_overridepagesize=1;
- t2p->pdf_defaultpagewidth =
- ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F);
- break;
- case 'l':
- t2p->pdf_overridepagesize=1;
- t2p->pdf_defaultpagelength =
- ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F);
- break;
- case 'r':
- if(optarg[0]=='o'){
- t2p->pdf_overrideres=1;
- }
- break;
- case 'p':
- if(tiff2pdf_match_paper_size(
- &(t2p->pdf_defaultpagewidth),
- &(t2p->pdf_defaultpagelength),
- optarg)){
- t2p->pdf_overridepagesize=1;
- } else {
- TIFFWarning(TIFF2PDF_MODULE,
- "Unknown paper size %s, ignoring option",
- optarg);
- }
- break;
- case 'i':
- t2p->pdf_colorspace_invert=1;
- break;
- case 'F':
- t2p->pdf_image_fillpage = 1;
- break;
- case 'f':
- t2p->pdf_fitwindow=1;
- break;
- case 'e':
- if (strlen(optarg) == 0) {
- t2p->pdf_datetime[0] = '\0';
- } else {
- t2p->pdf_datetime[0] = 'D';
- t2p->pdf_datetime[1] = ':';
- strncpy(t2p->pdf_datetime + 2, optarg,
- sizeof(t2p->pdf_datetime) - 3);
- t2p->pdf_datetime[sizeof(t2p->pdf_datetime) - 1] = '\0';
- }
- break;
- case 'c':
- strncpy(t2p->pdf_creator, optarg, sizeof(t2p->pdf_creator) - 1);
- t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0';
- t2p->pdf_creator_set = 1;
- break;
- case 'a':
- strncpy(t2p->pdf_author, optarg, sizeof(t2p->pdf_author) - 1);
- t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0';
- t2p->pdf_author_set = 1;
- break;
- case 't':
- strncpy(t2p->pdf_title, optarg, sizeof(t2p->pdf_title) - 1);
- t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0';
- t2p->pdf_title_set = 1;
- break;
- case 's':
- strncpy(t2p->pdf_subject, optarg, sizeof(t2p->pdf_subject) - 1);
- t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0';
- t2p->pdf_subject_set = 1;
- break;
- case 'k':
- strncpy(t2p->pdf_keywords, optarg, sizeof(t2p->pdf_keywords) - 1);
- t2p->pdf_keywords[sizeof(t2p->pdf_keywords) - 1] = '\0';
- t2p->pdf_keywords_set = 1;
- break;
- case 'b':
- t2p->pdf_image_interpolate = 1;
- break;
- case 'h':
- usage_info(EXIT_SUCCESS);
- goto success;
- case '?':
- usage_info(EXIT_FAILURE);
- goto fail;
- }
- }
-
- /*
- * Input
- */
- if(argc > optind) {
- input = TIFFOpen(argv[optind++], "r");
- if (input==NULL) {
- TIFFError(TIFF2PDF_MODULE,
- "Can't open input file %s for reading",
- argv[optind-1]);
- goto fail;
- }
- } else {
- TIFFError(TIFF2PDF_MODULE, "No input file specified");
- usage_info(EXIT_FAILURE);
- goto fail;
- }
-
- if(argc > optind) {
- TIFFError(TIFF2PDF_MODULE,
- "No support for multiple input files");
- usage_info(EXIT_FAILURE);
- goto fail;
- }
-
- /*
- * Output
- */
- t2p->outputdisable = 1;
- if (outfilename) {
- t2p->outputfile = fopen(outfilename, "wb");
- if (t2p->outputfile == NULL) {
- TIFFError(TIFF2PDF_MODULE,
- "Can't open output file %s for writing",
- outfilename);
- goto fail;
- }
- } else {
- outfilename = "-";
- t2p->outputfile = stdout;
- }
-
- output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p,
- t2p_readproc, t2p_writeproc, t2p_seekproc,
- t2p_closeproc, t2p_sizeproc,
- t2p_mapproc, t2p_unmapproc);
- t2p->outputdisable = 0;
- if (output == NULL) {
- TIFFError(TIFF2PDF_MODULE,
- "Can't initialize output descriptor");
- goto fail;
- }
-
- /*
- * Validate
- */
- t2p_validate(t2p);
- t2pSeekFile(output, (toff_t) 0, SEEK_SET);
-
- /*
- * Write
- */
- t2p_write_pdf(t2p, input, output);
- if (t2p->t2p_error != 0) {
- TIFFError(TIFF2PDF_MODULE,
- "An error occurred creating output PDF file");
- goto fail;
- }
-
- goto success;
+ case 'q':
+ t2p->pdf_defaultcompressionquality = atoi(optarg);
+ break;
+ case 'n':
+ t2p->pdf_nopassthrough = 1;
+ break;
+ case 'd':
+ t2p->pdf_defaultcompression = T2P_COMPRESS_NONE;
+ break;
+ case 'u':
+ if (optarg[0] == 'm')
+ {
+ t2p->pdf_centimeters = 1;
+ }
+ break;
+ case 'x':
+ t2p->pdf_defaultxres =
+ (float)atof(optarg) / (t2p->pdf_centimeters ? 2.54F : 1.0F);
+ break;
+ case 'y':
+ t2p->pdf_defaultyres =
+ (float)atof(optarg) / (t2p->pdf_centimeters ? 2.54F : 1.0F);
+ break;
+ case 'w':
+ t2p->pdf_overridepagesize = 1;
+ t2p->pdf_defaultpagewidth =
+ ((float)atof(optarg) * PS_UNIT_SIZE) /
+ (t2p->pdf_centimeters ? 2.54F : 1.0F);
+ break;
+ case 'l':
+ t2p->pdf_overridepagesize = 1;
+ t2p->pdf_defaultpagelength =
+ ((float)atof(optarg) * PS_UNIT_SIZE) /
+ (t2p->pdf_centimeters ? 2.54F : 1.0F);
+ break;
+ case 'r':
+ if (optarg[0] == 'o')
+ {
+ t2p->pdf_overrideres = 1;
+ }
+ break;
+ case 'p':
+ if (tiff2pdf_match_paper_size(&(t2p->pdf_defaultpagewidth),
+ &(t2p->pdf_defaultpagelength),
+ optarg))
+ {
+ t2p->pdf_overridepagesize = 1;
+ }
+ else
+ {
+ TIFFWarning(TIFF2PDF_MODULE,
+ "Unknown paper size %s, ignoring option",
+ optarg);
+ }
+ break;
+ case 'i':
+ t2p->pdf_colorspace_invert = 1;
+ break;
+ case 'F':
+ t2p->pdf_image_fillpage = 1;
+ break;
+ case 'f':
+ t2p->pdf_fitwindow = 1;
+ break;
+ case 'e':
+ if (strlen(optarg) == 0)
+ {
+ t2p->pdf_datetime[0] = '\0';
+ }
+ else
+ {
+ t2p->pdf_datetime[0] = 'D';
+ t2p->pdf_datetime[1] = ':';
+ strncpy(t2p->pdf_datetime + 2, optarg,
+ sizeof(t2p->pdf_datetime) - 3);
+ t2p->pdf_datetime[sizeof(t2p->pdf_datetime) - 1] = '\0';
+ }
+ break;
+ case 'c':
+ strncpy(t2p->pdf_creator, optarg, sizeof(t2p->pdf_creator) - 1);
+ t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0';
+ t2p->pdf_creator_set = 1;
+ break;
+ case 'a':
+ strncpy(t2p->pdf_author, optarg, sizeof(t2p->pdf_author) - 1);
+ t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0';
+ t2p->pdf_author_set = 1;
+ break;
+ case 't':
+ strncpy(t2p->pdf_title, optarg, sizeof(t2p->pdf_title) - 1);
+ t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0';
+ t2p->pdf_title_set = 1;
+ break;
+ case 's':
+ strncpy(t2p->pdf_subject, optarg, sizeof(t2p->pdf_subject) - 1);
+ t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0';
+ t2p->pdf_subject_set = 1;
+ break;
+ case 'k':
+ strncpy(t2p->pdf_keywords, optarg,
+ sizeof(t2p->pdf_keywords) - 1);
+ t2p->pdf_keywords[sizeof(t2p->pdf_keywords) - 1] = '\0';
+ t2p->pdf_keywords_set = 1;
+ break;
+ case 'b':
+ t2p->pdf_image_interpolate = 1;
+ break;
+ case 'h':
+ usage_info(EXIT_SUCCESS);
+ goto success;
+ case '?':
+ usage_info(EXIT_FAILURE);
+ goto fail;
+ }
+ }
+
+ /*
+ * Input
+ */
+ if (argc > optind)
+ {
+ input = TIFFOpen(argv[optind++], "r");
+ if (input == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Can't open input file %s for reading",
+ argv[optind - 1]);
+ goto fail;
+ }
+ }
+ else
+ {
+ TIFFError(TIFF2PDF_MODULE, "No input file specified");
+ usage_info(EXIT_FAILURE);
+ goto fail;
+ }
+
+ if (argc > optind)
+ {
+ TIFFError(TIFF2PDF_MODULE, "No support for multiple input files");
+ usage_info(EXIT_FAILURE);
+ goto fail;
+ }
+
+ /*
+ * Output
+ */
+ t2p->outputdisable = 1;
+ if (outfilename)
+ {
+ t2p->outputfile = fopen(outfilename, "wb");
+ if (t2p->outputfile == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Can't open output file %s for writing",
+ outfilename);
+ goto fail;
+ }
+ }
+ else
+ {
+ outfilename = "-";
+ t2p->outputfile = stdout;
+ }
+
+ output = TIFFClientOpen(outfilename, "w", (thandle_t)t2p, t2p_readproc,
+ t2p_writeproc, t2p_seekproc, t2p_closeproc,
+ t2p_sizeproc, t2p_mapproc, t2p_unmapproc);
+ t2p->outputdisable = 0;
+ if (output == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor");
+ goto fail;
+ }
+
+ /*
+ * Validate
+ */
+ t2p_validate(t2p);
+ t2pSeekFile(output, (toff_t)0, SEEK_SET);
+
+ /*
+ * Write
+ */
+ t2p_write_pdf(t2p, input, output);
+ if (t2p->t2p_error != 0)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "An error occurred creating output PDF file");
+ goto fail;
+ }
+
+ goto success;
fail:
- ret = EXIT_FAILURE;
+ ret = EXIT_FAILURE;
success:
- if(input != NULL)
- TIFFClose(input);
- if (output != NULL)
- TIFFClose(output);
- if (t2p != NULL)
- t2p_free(t2p);
- return ret;
-
+ if (input != NULL)
+ TIFFClose(input);
+ if (output != NULL)
+ TIFFClose(output);
+ if (t2p != NULL)
+ t2p_free(t2p);
+ return ret;
}
-static void usage_info(int code) {
- static const char lines[]=
- "Convert a TIFF image to a PDF document\n\n"
- "usage: tiff2pdf [options] input.tiff\n"
- "where options are:\n"
- " -o: output to file name\n"
+static void usage_info(int code)
+{
+ static const char lines[] =
+ "Convert a TIFF image to a PDF document\n\n"
+ "usage: tiff2pdf [options] input.tiff\n"
+ "where options are:\n"
+ " -o: output to file name\n"
#ifdef JPEG_SUPPORT
- " -j: compress with JPEG\n"
+ " -j: compress with JPEG\n"
#endif
#ifdef ZIP_SUPPORT
- " -z: compress with Zip/Deflate\n"
+ " -z: compress with Zip/Deflate\n"
#endif
#if defined(JPEG_SUPPORT) || defined(ZIP_SUPPORT)
- " -q: compression quality\n"
- " -n: no compressed data passthrough\n"
- " -d: do not compress (decompress)\n"
+ " -q: compression quality\n"
+ " -n: no compressed data passthrough\n"
+ " -d: do not compress (decompress)\n"
#endif
- " -i: invert colors\n"
- " -u: set distance unit, 'i' for inch, 'm' for centimeter\n"
- " -x: set x resolution default in dots per unit\n"
- " -y: set y resolution default in dots per unit\n"
- " -w: width in units\n"
- " -l: length in units\n"
- " -r: 'd' for resolution default, 'o' for resolution override\n"
- " -p: paper size, eg \"letter\", \"legal\", \"A4\"\n"
- " -F: make the tiff fill the PDF page\n"
- " -f: set PDF \"Fit Window\" user preference\n"
- " -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS\n"
- " -c: sets document creator, overrides image software default\n"
- " -a: sets document author, overrides image artist default\n"
- " -t: sets document title, overrides image document name default\n"
- " -s: sets document subject, overrides image image description default\n"
- " -k: sets document keywords\n"
- " -b: set PDF \"Interpolate\" user preference\n"
- " -m: set memory allocation limit (in MiB). set to 0 to disable limit\n"
- " -h: usage\n"
- ;
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
-
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", lines);
-
- return;
+ " -i: invert colors\n"
+ " -u: set distance unit, 'i' for inch, 'm' for centimeter\n"
+ " -x: set x resolution default in dots per unit\n"
+ " -y: set y resolution default in dots per unit\n"
+ " -w: width in units\n"
+ " -l: length in units\n"
+ " -r: 'd' for resolution default, 'o' for resolution override\n"
+ " -p: paper size, eg \"letter\", \"legal\", \"A4\"\n"
+ " -F: make the tiff fill the PDF page\n"
+ " -f: set PDF \"Fit Window\" user preference\n"
+ " -e: date, overrides image or current date/time default, "
+ "YYYYMMDDHHMMSS\n"
+ " -c: sets document creator, overrides image software default\n"
+ " -a: sets document author, overrides image artist default\n"
+ " -t: sets document title, overrides image document name default\n"
+ " -s: sets document subject, overrides image image description "
+ "default\n"
+ " -k: sets document keywords\n"
+ " -b: set PDF \"Interpolate\" user preference\n"
+ " -m: set memory allocation limit (in MiB). set to 0 to disable limit\n"
+ " -h: usage\n";
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
+
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", lines);
+
+ return;
}
-int tiff2pdf_match_paper_size(float* width, float* length, char* papersize){
-
- size_t i, len;
- const char* sizes[]={
- "LETTER", "A4", "LEGAL",
- "EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID",
- "A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
- "A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0",
- "2A0", "4A0", "2A", "4A",
- "B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0",
- "JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4",
- "JISB3", "JISB2", "JISB1", "JISB0",
- "C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0",
- "RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0",
- "A3EXTRA", "A4EXTRA",
- "STATEMENT", "FOLIO", "QUARTO",
- NULL
- } ;
- const int widths[]={
- 612, 595, 612,
- 522, 612,612,792,792,
- 612,792,1224,1584,2448,2016,792,2016,2448,2880,
- 74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768,
- 88,125,176,249,354,499,709,1001,1417,2004,2835,
- 91,128,181,258,363,516,729,1032,1460,2064,2920,
- 79,113,162,230,323,459,649,918,1298,1298,2599,
- 1219,1729,2438,638,907,1276,1814,2551,
- 914,667,
- 396, 612, 609,
- 0
- };
- const int lengths[]={
- 792,842,1008,
- 756,792,1008,1224,1224,
- 792,1224,1584,2448,3168,2880,6480,10296,12672,10296,
- 105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741,
- 125,176,249,354,499,709,1001,1417,2004,2835,4008,
- 128,181,258,363,516,729,1032,1460,2064,2920,4127,
- 113,162,230,323,459,649,918,1298,1837,1837,3677,
- 1729,2438,3458,907,1276,1814,2551,3628,
- 1262,914,
- 612, 936, 780,
- 0
- };
-
- len=strlen(papersize);
- for(i=0;i<len;i++){
- papersize[i]=toupper((int) papersize[i]);
- }
- for(i=0;sizes[i]!=NULL; i++){
- if (strcmp( (const char*)papersize, sizes[i])==0){
- *width=(float)widths[i];
- *length=(float)lengths[i];
- return(1);
- }
- }
-
- return(0);
+int tiff2pdf_match_paper_size(float *width, float *length, char *papersize)
+{
+
+ size_t i, len;
+ const char *sizes[] = {
+ "LETTER", "A4", "LEGAL", "EXECUTIVE", "LETTER", "LEGAL",
+ "LEDGER", "TABLOID", "A", "B", "C", "D",
+ "E", "F", "G", "H", "J", "K",
+ "A10", "A9", "A8", "A7", "A6", "A5",
+ "A4", "A3", "A2", "A1", "A0", "2A0",
+ "4A0", "2A", "4A", "B10", "B9", "B8",
+ "B7", "B6", "B5", "B4", "B3", "B2",
+ "B1", "B0", "JISB10", "JISB9", "JISB8", "JISB7",
+ "JISB6", "JISB5", "JISB4", "JISB3", "JISB2", "JISB1",
+ "JISB0", "C10", "C9", "C8", "C7", "C6",
+ "C5", "C4", "C3", "C2", "C1", "C0",
+ "RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2",
+ "SRA1", "SRA0", "A3EXTRA", "A4EXTRA", "STATEMENT", "FOLIO",
+ "QUARTO", NULL};
+ const int widths[] = {
+ 612, 595, 612, 522, 612, 612, 792, 792, 612, 792, 1224, 1584,
+ 2448, 2016, 792, 2016, 2448, 2880, 74, 105, 147, 210, 298, 420,
+ 595, 842, 1191, 1684, 2384, 3370, 4768, 3370, 4768, 88, 125, 176,
+ 249, 354, 499, 709, 1001, 1417, 2004, 2835, 91, 128, 181, 258,
+ 363, 516, 729, 1032, 1460, 2064, 2920, 79, 113, 162, 230, 323,
+ 459, 649, 918, 1298, 1298, 2599, 1219, 1729, 2438, 638, 907, 1276,
+ 1814, 2551, 914, 667, 396, 612, 609, 0};
+ const int lengths[] = {
+ 792, 842, 1008, 756, 792, 1008, 1224, 1224, 792, 1224,
+ 1584, 2448, 3168, 2880, 6480, 10296, 12672, 10296, 105, 147,
+ 210, 298, 420, 595, 842, 1191, 1684, 2384, 3370, 4768,
+ 6741, 4768, 6741, 125, 176, 249, 354, 499, 709, 1001,
+ 1417, 2004, 2835, 4008, 128, 181, 258, 363, 516, 729,
+ 1032, 1460, 2064, 2920, 4127, 113, 162, 230, 323, 459,
+ 649, 918, 1298, 1837, 1837, 3677, 1729, 2438, 3458, 907,
+ 1276, 1814, 2551, 3628, 1262, 914, 612, 936, 780, 0};
+
+ len = strlen(papersize);
+ for (i = 0; i < len; i++)
+ {
+ papersize[i] = toupper((int)papersize[i]);
+ }
+ for (i = 0; sizes[i] != NULL; i++)
+ {
+ if (strcmp((const char *)papersize, sizes[i]) == 0)
+ {
+ *width = (float)widths[i];
+ *length = (float)lengths[i];
+ return (1);
+ }
+ }
+
+ return (0);
}
/*
* This function allocates and initializes a T2P context struct pointer.
*/
-T2P* t2p_init()
+T2P *t2p_init()
{
- T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P));
- if(t2p==NULL){
- TIFFError(
- TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SIZE_FORMAT" bytes of memory for t2p_init",
- sizeof(T2P));
- return( (T2P*) NULL );
- }
- _TIFFmemset(t2p, 0x00, sizeof(T2P));
- t2p->pdf_majorversion=1;
- t2p->pdf_minorversion=1;
- t2p->pdf_defaultxres=300.0;
- t2p->pdf_defaultyres=300.0;
- t2p->pdf_defaultpagewidth=612.0;
- t2p->pdf_defaultpagelength=792.0;
- t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */
- t2p->tiff_maxdatasize = DEFAULT_MAX_MALLOC;
-
- return(t2p);
+ T2P *t2p = (T2P *)_TIFFmalloc(sizeof(T2P));
+ if (t2p == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SIZE_FORMAT
+ " bytes of memory for t2p_init",
+ sizeof(T2P));
+ return ((T2P *)NULL);
+ }
+ _TIFFmemset(t2p, 0x00, sizeof(T2P));
+ t2p->pdf_majorversion = 1;
+ t2p->pdf_minorversion = 1;
+ t2p->pdf_defaultxres = 300.0;
+ t2p->pdf_defaultyres = 300.0;
+ t2p->pdf_defaultpagewidth = 612.0;
+ t2p->pdf_defaultpagelength = 792.0;
+ t2p->pdf_xrefcount = 3; /* Catalog, Info, Pages */
+ t2p->tiff_maxdatasize = DEFAULT_MAX_MALLOC;
+
+ return (t2p);
}
/*
- * This function frees a T2P context struct pointer and any allocated data fields of it.
+ * This function frees a T2P context struct pointer and any allocated data
+ * fields of it.
*/
-void t2p_free(T2P* t2p)
+void t2p_free(T2P *t2p)
{
- int i = 0;
-
- if (t2p != NULL) {
- if(t2p->pdf_xrefoffsets != NULL){
- _TIFFfree( (tdata_t) t2p->pdf_xrefoffsets);
- }
- if(t2p->tiff_pages != NULL){
- _TIFFfree( (tdata_t) t2p->tiff_pages);
- }
- for(i=0;i<t2p->tiff_pagecount;i++){
- if(t2p->tiff_tiles[i].tiles_tiles != NULL){
- _TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles);
- }
- }
- if(t2p->tiff_tiles != NULL){
- _TIFFfree( (tdata_t) t2p->tiff_tiles);
- }
- if(t2p->pdf_palette != NULL){
- _TIFFfree( (tdata_t) t2p->pdf_palette);
- }
+ int i = 0;
+
+ if (t2p != NULL)
+ {
+ if (t2p->pdf_xrefoffsets != NULL)
+ {
+ _TIFFfree((tdata_t)t2p->pdf_xrefoffsets);
+ }
+ if (t2p->tiff_pages != NULL)
+ {
+ _TIFFfree((tdata_t)t2p->tiff_pages);
+ }
+ for (i = 0; i < t2p->tiff_pagecount; i++)
+ {
+ if (t2p->tiff_tiles[i].tiles_tiles != NULL)
+ {
+ _TIFFfree((tdata_t)t2p->tiff_tiles[i].tiles_tiles);
+ }
+ }
+ if (t2p->tiff_tiles != NULL)
+ {
+ _TIFFfree((tdata_t)t2p->tiff_tiles);
+ }
+ if (t2p->pdf_palette != NULL)
+ {
+ _TIFFfree((tdata_t)t2p->pdf_palette);
+ }
#ifdef OJPEG_SUPPORT
- if(t2p->pdf_ojpegdata != NULL){
- _TIFFfree( (tdata_t) t2p->pdf_ojpegdata);
- }
+ if (t2p->pdf_ojpegdata != NULL)
+ {
+ _TIFFfree((tdata_t)t2p->pdf_ojpegdata);
+ }
#endif
- _TIFFfree( (tdata_t) t2p );
- }
+ _TIFFfree((tdata_t)t2p);
+ }
- return;
+ return;
}
/*
- This function validates the values of a T2P context struct pointer
+ This function validates the values of a T2P context struct pointer
before calling t2p_write_pdf with it.
*/
-void t2p_validate(T2P* t2p){
- (void) t2p;
+void t2p_validate(T2P *t2p)
+{
+ (void)t2p;
#ifdef JPEG_SUPPORT
- if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
- if(t2p->pdf_defaultcompressionquality>100 ||
- t2p->pdf_defaultcompressionquality<1){
- t2p->pdf_defaultcompressionquality=0;
- }
- }
+ if (t2p->pdf_defaultcompression == T2P_COMPRESS_JPEG)
+ {
+ if (t2p->pdf_defaultcompressionquality > 100 ||
+ t2p->pdf_defaultcompressionquality < 1)
+ {
+ t2p->pdf_defaultcompressionquality = 0;
+ }
+ }
#endif
#ifdef ZIP_SUPPORT
- if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){
- uint16_t m= t2p->pdf_defaultcompressionquality % 100;
- if(t2p->pdf_defaultcompressionquality/100 > 9 ||
- (m>1 && m<10) || m>15){
- t2p->pdf_defaultcompressionquality=0;
- }
- if(t2p->pdf_defaultcompressionquality%100 !=0){
- t2p->pdf_defaultcompressionquality/=100;
- t2p->pdf_defaultcompressionquality*=100;
- TIFFError(
- TIFF2PDF_MODULE,
- "PNG Group predictor differencing not implemented, assuming compression quality %"PRIu16,
- t2p->pdf_defaultcompressionquality);
- }
- t2p->pdf_defaultcompressionquality%=100;
- if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;}
- }
+ if (t2p->pdf_defaultcompression == T2P_COMPRESS_ZIP)
+ {
+ uint16_t m = t2p->pdf_defaultcompressionquality % 100;
+ if (t2p->pdf_defaultcompressionquality / 100 > 9 || (m > 1 && m < 10) ||
+ m > 15)
+ {
+ t2p->pdf_defaultcompressionquality = 0;
+ }
+ if (t2p->pdf_defaultcompressionquality % 100 != 0)
+ {
+ t2p->pdf_defaultcompressionquality /= 100;
+ t2p->pdf_defaultcompressionquality *= 100;
+ TIFFError(TIFF2PDF_MODULE,
+ "PNG Group predictor differencing not implemented, "
+ "assuming compression quality %" PRIu16,
+ t2p->pdf_defaultcompressionquality);
+ }
+ t2p->pdf_defaultcompressionquality %= 100;
+ if (t2p->pdf_minorversion < 2)
+ {
+ t2p->pdf_minorversion = 2;
+ }
+ }
#endif
- return;
+ return;
}
-
/*
- This function scans the input TIFF file for pages. It attempts
+ This function scans the input TIFF file for pages. It attempts
to determine which IFD's of the TIFF file contain image document
pages. For each, it gathers some information that has to do
- with the output of the PDF document as a whole.
+ with the output of the PDF document as a whole.
*/
-void t2p_read_tiff_init(T2P* t2p, TIFF* input){
-
- tdir_t directorycount=0;
- tdir_t i=0;
- uint16_t pagen=0;
- uint16_t paged=0;
- uint16_t xuint16=0;
- uint16_t tiff_transferfunctioncount=0;
- uint16_t* tiff_transferfunction[3];
-
- directorycount=TIFFNumberOfDirectories(input);
- if(directorycount > TIFF_DIR_MAX) {
- TIFFError(
- TIFF2PDF_MODULE,
- "TIFF contains too many directories, %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_PAGE)));
- if(t2p->tiff_pages==NULL){
- TIFFError(
- TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SIZE_FORMAT" bytes of memory for tiff_pages array, %s",
- sizeof(T2P_PAGE) * directorycount,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- _TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE));
- t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_TILES)));
- if(t2p->tiff_tiles==NULL){
- TIFFError(
- TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SIZE_FORMAT" bytes of memory for tiff_tiles array, %s",
- sizeof(T2P_TILES) * directorycount,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- _TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES));
- for(i=0;i<directorycount;i++){
- uint32_t subfiletype = 0;
-
- if(!TIFFSetDirectory(input, i)){
- TIFFError(
- TIFF2PDF_MODULE,
- "Can't set directory %"PRIu16" of input file %s",
- i,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){
- if((pagen>paged) && (paged != 0)){
- t2p->tiff_pages[t2p->tiff_pagecount].page_number =
- paged;
- } else {
- t2p->tiff_pages[t2p->tiff_pagecount].page_number =
- pagen;
- }
- goto ispage2;
- }
- if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){
- if ( ((subfiletype & FILETYPE_PAGE) != 0)
- || (subfiletype == 0)){
- goto ispage;
- } else {
- goto isnotpage;
- }
- }
- if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){
- if ((subfiletype == OFILETYPE_IMAGE)
- || (subfiletype == OFILETYPE_PAGE)
- || (subfiletype == 0) ){
- goto ispage;
- } else {
- goto isnotpage;
- }
- }
- ispage:
- t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount;
- ispage2:
- t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i;
- if(TIFFIsTiled(input)){
- t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount =
- TIFFNumberOfTiles(input);
- }
- t2p->tiff_pagecount++;
- isnotpage:
- (void)0;
- }
-
- qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount,
- sizeof(T2P_PAGE), t2p_cmp_t2p_page);
-
- for(i=0;i<t2p->tiff_pagecount;i++){
- t2p->pdf_xrefcount += 5;
- TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory );
- if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16)
- && (xuint16==PHOTOMETRIC_PALETTE))
- || TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) {
- t2p->tiff_pages[i].page_extra++;
- t2p->pdf_xrefcount++;
- }
+void t2p_read_tiff_init(T2P *t2p, TIFF *input)
+{
+
+ tdir_t directorycount = 0;
+ tdir_t i = 0;
+ uint16_t pagen = 0;
+ uint16_t paged = 0;
+ uint16_t xuint16 = 0;
+ uint16_t tiff_transferfunctioncount = 0;
+ uint16_t *tiff_transferfunction[3];
+
+ directorycount = TIFFNumberOfDirectories(input);
+ if (directorycount > TIFF_DIR_MAX)
+ {
+ TIFFError(TIFF2PDF_MODULE, "TIFF contains too many directories, %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ t2p->tiff_pages = (T2P_PAGE *)_TIFFmalloc(
+ TIFFSafeMultiply(tmsize_t, directorycount, sizeof(T2P_PAGE)));
+ if (t2p->tiff_pages == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SIZE_FORMAT
+ " bytes of memory for tiff_pages array, %s",
+ sizeof(T2P_PAGE) * directorycount, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ _TIFFmemset(t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE));
+ t2p->tiff_tiles = (T2P_TILES *)_TIFFmalloc(
+ TIFFSafeMultiply(tmsize_t, directorycount, sizeof(T2P_TILES)));
+ if (t2p->tiff_tiles == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SIZE_FORMAT
+ " bytes of memory for tiff_tiles array, %s",
+ sizeof(T2P_TILES) * directorycount, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ _TIFFmemset(t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES));
+ for (i = 0; i < directorycount; i++)
+ {
+ uint32_t subfiletype = 0;
+
+ if (!TIFFSetDirectory(input, i))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't set directory %" PRIu16 " of input file %s", i,
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ if (TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged))
+ {
+ if ((pagen > paged) && (paged != 0))
+ {
+ t2p->tiff_pages[t2p->tiff_pagecount].page_number = paged;
+ }
+ else
+ {
+ t2p->tiff_pages[t2p->tiff_pagecount].page_number = pagen;
+ }
+ goto ispage2;
+ }
+ if (TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype))
+ {
+ if (((subfiletype & FILETYPE_PAGE) != 0) || (subfiletype == 0))
+ {
+ goto ispage;
+ }
+ else
+ {
+ goto isnotpage;
+ }
+ }
+ if (TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype))
+ {
+ if ((subfiletype == OFILETYPE_IMAGE) ||
+ (subfiletype == OFILETYPE_PAGE) || (subfiletype == 0))
+ {
+ goto ispage;
+ }
+ else
+ {
+ goto isnotpage;
+ }
+ }
+ ispage:
+ t2p->tiff_pages[t2p->tiff_pagecount].page_number = t2p->tiff_pagecount;
+ ispage2:
+ t2p->tiff_pages[t2p->tiff_pagecount].page_directory = i;
+ if (TIFFIsTiled(input))
+ {
+ t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount =
+ TIFFNumberOfTiles(input);
+ }
+ t2p->tiff_pagecount++;
+ isnotpage:
+ (void)0;
+ }
+
+ qsort((void *)t2p->tiff_pages, t2p->tiff_pagecount, sizeof(T2P_PAGE),
+ t2p_cmp_t2p_page);
+
+ for (i = 0; i < t2p->tiff_pagecount; i++)
+ {
+ t2p->pdf_xrefcount += 5;
+ TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory);
+ if ((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16) &&
+ (xuint16 == PHOTOMETRIC_PALETTE)) ||
+ TIFFGetField(input, TIFFTAG_INDEXED, &xuint16))
+ {
+ t2p->tiff_pages[i].page_extra++;
+ t2p->pdf_xrefcount++;
+ }
#ifdef ZIP_SUPPORT
- if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) {
- if( (xuint16== COMPRESSION_DEFLATE ||
- xuint16== COMPRESSION_ADOBE_DEFLATE) &&
- ((t2p->tiff_pages[i].page_tilecount != 0)
- || TIFFNumberOfStrips(input)==1) &&
- (t2p->pdf_nopassthrough==0) ){
- if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;}
- }
+ if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16))
+ {
+ if ((xuint16 == COMPRESSION_DEFLATE ||
+ xuint16 == COMPRESSION_ADOBE_DEFLATE) &&
+ ((t2p->tiff_pages[i].page_tilecount != 0) ||
+ TIFFNumberOfStrips(input) == 1) &&
+ (t2p->pdf_nopassthrough == 0))
+ {
+ if (t2p->pdf_minorversion < 2)
+ {
+ t2p->pdf_minorversion = 2;
}
+ }
+ }
#endif
- if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION,
- &(tiff_transferfunction[0]),
- &(tiff_transferfunction[1]),
- &(tiff_transferfunction[2]))) {
-
- if((tiff_transferfunction[1] != (uint16_t*) NULL) &&
- (tiff_transferfunction[2] != (uint16_t*) NULL)
- ) {
- tiff_transferfunctioncount=3;
- } else {
- tiff_transferfunctioncount=1;
- }
- } else {
- tiff_transferfunctioncount=0;
- }
-
- if (i > 0){
- if (tiff_transferfunctioncount != t2p->tiff_transferfunctioncount){
- TIFFError(
- TIFF2PDF_MODULE,
- "Different transfer function on page %"PRIu16,
- i);
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- }
+ if (TIFFGetField(
+ input, TIFFTAG_TRANSFERFUNCTION, &(tiff_transferfunction[0]),
+ &(tiff_transferfunction[1]), &(tiff_transferfunction[2])))
+ {
- t2p->tiff_transferfunctioncount = tiff_transferfunctioncount;
- t2p->tiff_transferfunction[0] = tiff_transferfunction[0];
- t2p->tiff_transferfunction[1] = tiff_transferfunction[1];
- t2p->tiff_transferfunction[2] = tiff_transferfunction[2];
- if(tiff_transferfunctioncount == 3){
- t2p->tiff_pages[i].page_extra += 4;
- t2p->pdf_xrefcount += 4;
- if(t2p->pdf_minorversion < 2)
- t2p->pdf_minorversion = 2;
- } else if (tiff_transferfunctioncount == 1){
- t2p->tiff_pages[i].page_extra += 2;
- t2p->pdf_xrefcount += 2;
- if(t2p->pdf_minorversion < 2)
- t2p->pdf_minorversion = 2;
- }
+ if ((tiff_transferfunction[1] != (uint16_t *)NULL) &&
+ (tiff_transferfunction[2] != (uint16_t *)NULL))
+ {
+ tiff_transferfunctioncount = 3;
+ }
+ else
+ {
+ tiff_transferfunctioncount = 1;
+ }
+ }
+ else
+ {
+ tiff_transferfunctioncount = 0;
+ }
- if( TIFFGetField(
- input,
- TIFFTAG_ICCPROFILE,
- &(t2p->tiff_iccprofilelength),
- &(t2p->tiff_iccprofile)) != 0){
- t2p->tiff_pages[i].page_extra++;
- t2p->pdf_xrefcount++;
- if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;}
- }
- t2p->tiff_tiles[i].tiles_tilecount=
- t2p->tiff_pages[i].page_tilecount;
- if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0)
- && (xuint16 == PLANARCONFIG_SEPARATE ) ){
- if( !TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16) )
- {
- TIFFError(
- TIFF2PDF_MODULE,
- "Missing SamplesPerPixel, %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- if( (t2p->tiff_tiles[i].tiles_tilecount % xuint16) != 0 )
- {
- TIFFError(
- TIFF2PDF_MODULE,
- "Invalid tile count, %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- t2p->tiff_tiles[i].tiles_tilecount/= xuint16;
- }
- if( t2p->tiff_tiles[i].tiles_tilecount > 0){
- t2p->pdf_xrefcount +=
- (t2p->tiff_tiles[i].tiles_tilecount -1)*2;
- TIFFGetField(input,
- TIFFTAG_TILEWIDTH,
- &( t2p->tiff_tiles[i].tiles_tilewidth) );
- TIFFGetField(input,
- TIFFTAG_TILELENGTH,
- &( t2p->tiff_tiles[i].tiles_tilelength) );
- t2p->tiff_tiles[i].tiles_tiles =
- (T2P_TILE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->tiff_tiles[i].tiles_tilecount,
- sizeof(T2P_TILE)) );
- if( t2p->tiff_tiles[i].tiles_tiles == NULL){
- TIFFError(
- TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SIZE_FORMAT" bytes of memory for t2p_read_tiff_init, %s",
- sizeof(T2P_TILE) * t2p->tiff_tiles[i].tiles_tilecount,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- }
- }
+ if (i > 0)
+ {
+ if (tiff_transferfunctioncount != t2p->tiff_transferfunctioncount)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Different transfer function on page %" PRIu16, i);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ }
- return;
+ t2p->tiff_transferfunctioncount = tiff_transferfunctioncount;
+ t2p->tiff_transferfunction[0] = tiff_transferfunction[0];
+ t2p->tiff_transferfunction[1] = tiff_transferfunction[1];
+ t2p->tiff_transferfunction[2] = tiff_transferfunction[2];
+ if (tiff_transferfunctioncount == 3)
+ {
+ t2p->tiff_pages[i].page_extra += 4;
+ t2p->pdf_xrefcount += 4;
+ if (t2p->pdf_minorversion < 2)
+ t2p->pdf_minorversion = 2;
+ }
+ else if (tiff_transferfunctioncount == 1)
+ {
+ t2p->tiff_pages[i].page_extra += 2;
+ t2p->pdf_xrefcount += 2;
+ if (t2p->pdf_minorversion < 2)
+ t2p->pdf_minorversion = 2;
+ }
+
+ if (TIFFGetField(input, TIFFTAG_ICCPROFILE,
+ &(t2p->tiff_iccprofilelength),
+ &(t2p->tiff_iccprofile)) != 0)
+ {
+ t2p->tiff_pages[i].page_extra++;
+ t2p->pdf_xrefcount++;
+ if (t2p->pdf_minorversion < 3)
+ {
+ t2p->pdf_minorversion = 3;
+ }
+ }
+ t2p->tiff_tiles[i].tiles_tilecount = t2p->tiff_pages[i].page_tilecount;
+ if ((TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0) &&
+ (xuint16 == PLANARCONFIG_SEPARATE))
+ {
+ if (!TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16))
+ {
+ TIFFError(TIFF2PDF_MODULE, "Missing SamplesPerPixel, %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ if ((t2p->tiff_tiles[i].tiles_tilecount % xuint16) != 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Invalid tile count, %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ t2p->tiff_tiles[i].tiles_tilecount /= xuint16;
+ }
+ if (t2p->tiff_tiles[i].tiles_tilecount > 0)
+ {
+ t2p->pdf_xrefcount += (t2p->tiff_tiles[i].tiles_tilecount - 1) * 2;
+ TIFFGetField(input, TIFFTAG_TILEWIDTH,
+ &(t2p->tiff_tiles[i].tiles_tilewidth));
+ TIFFGetField(input, TIFFTAG_TILELENGTH,
+ &(t2p->tiff_tiles[i].tiles_tilelength));
+ t2p->tiff_tiles[i].tiles_tiles = (T2P_TILE *)_TIFFmalloc(
+ TIFFSafeMultiply(tmsize_t, t2p->tiff_tiles[i].tiles_tilecount,
+ sizeof(T2P_TILE)));
+ if (t2p->tiff_tiles[i].tiles_tiles == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SIZE_FORMAT
+ " bytes of memory for t2p_read_tiff_init, %s",
+ sizeof(T2P_TILE) * t2p->tiff_tiles[i].tiles_tilecount,
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ }
+ }
+
+ return;
}
/*
@@ -1282,906 +1364,1023 @@ void t2p_read_tiff_init(T2P* t2p, TIFF* input){
* directory numbers to preserve the order of the input file.
*/
-int t2p_cmp_t2p_page(const void* e1, const void* e2){
+int t2p_cmp_t2p_page(const void *e1, const void *e2)
+{
- int d;
- d = (int32_t)(((T2P_PAGE*)e1)->page_number) - (int32_t)(((T2P_PAGE*)e2)->page_number);
- if(d == 0){
- d = (int32_t)(((T2P_PAGE*)e1)->page_directory) - (int32_t)(((T2P_PAGE*)e2)->page_directory);
- }
- return d;
+ int d;
+ d = (int32_t)(((T2P_PAGE *)e1)->page_number) -
+ (int32_t)(((T2P_PAGE *)e2)->page_number);
+ if (d == 0)
+ {
+ d = (int32_t)(((T2P_PAGE *)e1)->page_directory) -
+ (int32_t)(((T2P_PAGE *)e2)->page_directory);
+ }
+ return d;
}
/*
- This function sets the input directory to the directory of a given
- page and determines information about the image. It checks
- the image characteristics to determine if it is possible to convert
- the image data into a page of PDF output, setting values of the T2P
- struct for this page. It determines what color space is used in
- the output PDF to represent the image.
-
- It determines if the image can be converted as raw data without
- requiring transcoding of the image data.
+ This function sets the input directory to the directory of a given
+ page and determines information about the image. It checks
+ the image characteristics to determine if it is possible to convert
+ the image data into a page of PDF output, setting values of the T2P
+ struct for this page. It determines what color space is used in
+ the output PDF to represent the image.
+
+ It determines if the image can be converted as raw data without
+ requiring transcoding of the image data.
*/
-void t2p_read_tiff_data(T2P* t2p, TIFF* input){
-
- int i=0;
- uint16_t* r = NULL;
- uint16_t* g = NULL;
- uint16_t* b = NULL;
- uint16_t* a = NULL;
- uint16_t xuint16;
- uint16_t* xuint16p;
- float* xfloatp;
- int palette_16bit = 0;
- int palette_shift = 8;
-
- t2p->pdf_transcode = T2P_TRANSCODE_ENCODE;
- t2p->pdf_sample = T2P_SAMPLE_NOTHING;
- t2p->pdf_switchdecode = t2p->pdf_colorspace_invert;
-
-
- TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory);
-
- TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width));
- if(t2p->tiff_width == 0){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with zero width",
- TIFFFileName(input) );
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
-
- TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length));
- if(t2p->tiff_length == 0){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with zero length",
- TIFFFileName(input) );
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
-
- if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with no compression tag",
- TIFFFileName(input) );
+void t2p_read_tiff_data(T2P *t2p, TIFF *input)
+{
+
+ int i = 0;
+ uint16_t *r = NULL;
+ uint16_t *g = NULL;
+ uint16_t *b = NULL;
+ uint16_t *a = NULL;
+ uint16_t xuint16;
+ uint16_t *xuint16p;
+ float *xfloatp;
+ int palette_16bit = 0;
+ int palette_shift = 8;
+
+ t2p->pdf_transcode = T2P_TRANSCODE_ENCODE;
+ t2p->pdf_sample = T2P_SAMPLE_NOTHING;
+ t2p->pdf_switchdecode = t2p->pdf_colorspace_invert;
+
+ TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory);
+
+ TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width));
+ if (t2p->tiff_width == 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "No support for %s with zero width",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+
+ TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length));
+ if (t2p->tiff_length == 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "No support for %s with zero length",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+
+ if (TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "No support for %s with no compression tag",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ if (TIFFIsCODECConfigured(t2p->tiff_compression) == 0)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for %s with compression type %" PRIu16
+ ": not configured",
+ TIFFFileName(input), t2p->tiff_compression);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+
+ TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE,
+ &(t2p->tiff_bitspersample));
+ switch (t2p->tiff_bitspersample)
+ {
+ case 1:
+ case 2:
+ case 4:
+ case 8:
+ break;
+ case 0:
+ TIFFWarning(TIFF2PDF_MODULE,
+ "Image %s has 0 bits per sample, assuming 1",
+ TIFFFileName(input));
+ t2p->tiff_bitspersample = 1;
+ break;
+ default:
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for %s with %" PRIu16 " bits per sample",
+ TIFFFileName(input), t2p->tiff_bitspersample);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+
+ TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL,
+ &(t2p->tiff_samplesperpixel));
+ if (t2p->tiff_samplesperpixel > 4)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for %s with %" PRIu16 " samples per pixel",
+ TIFFFileName(input), t2p->tiff_samplesperpixel);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ if (t2p->tiff_samplesperpixel == 0)
+ {
+ TIFFWarning(TIFF2PDF_MODULE,
+ "Image %s has 0 samples per pixel, assuming 1",
+ TIFFFileName(input));
+ t2p->tiff_samplesperpixel = 1;
+ }
+
+ if (TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0)
+ {
+ switch (xuint16)
+ {
+ case 0:
+ case 1:
+ case 4:
+ break;
+ default:
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for %s with sample format %" PRIu16,
+ TIFFFileName(input), xuint16);
t2p->t2p_error = T2P_ERR_ERROR;
return;
-
+ break;
}
- if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with compression type %"PRIu16": not configured",
- TIFFFileName(input),
- t2p->tiff_compression
- );
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
-
- }
-
- TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample));
- switch(t2p->tiff_bitspersample){
- case 1:
- case 2:
- case 4:
- case 8:
- break;
- case 0:
- TIFFWarning(
- TIFF2PDF_MODULE,
- "Image %s has 0 bits per sample, assuming 1",
- TIFFFileName(input));
- t2p->tiff_bitspersample=1;
- break;
- default:
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with %"PRIu16" bits per sample",
- TIFFFileName(input),
- t2p->tiff_bitspersample);
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
-
- TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel));
- if(t2p->tiff_samplesperpixel>4){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with %"PRIu16" samples per pixel",
- TIFFFileName(input),
- t2p->tiff_samplesperpixel);
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- if(t2p->tiff_samplesperpixel==0){
- TIFFWarning(
- TIFF2PDF_MODULE,
- "Image %s has 0 samples per pixel, assuming 1",
- TIFFFileName(input));
- t2p->tiff_samplesperpixel=1;
- }
-
- if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){
- switch(xuint16){
- case 0:
- case 1:
- case 4:
- break;
- default:
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with sample format %"PRIu16,
- TIFFFileName(input),
- xuint16);
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- break;
- }
- }
-
- TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder));
-
- if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with no photometric interpretation tag",
- TIFFFileName(input) );
+ }
+
+ TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder));
+
+ if (TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for %s with no photometric interpretation tag",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+
+ switch (t2p->tiff_photometric)
+ {
+ case PHOTOMETRIC_MINISWHITE:
+ case PHOTOMETRIC_MINISBLACK:
+ if (t2p->tiff_bitspersample == 1)
+ {
+ t2p->pdf_colorspace = T2P_CS_BILEVEL;
+ if (t2p->tiff_photometric == PHOTOMETRIC_MINISWHITE)
+ {
+ t2p->pdf_switchdecode ^= 1;
+ }
+ }
+ else
+ {
+ t2p->pdf_colorspace = T2P_CS_GRAY;
+ if (t2p->tiff_photometric == PHOTOMETRIC_MINISWHITE)
+ {
+ t2p->pdf_switchdecode ^= 1;
+ }
+ }
+ break;
+ case PHOTOMETRIC_RGB:
+ t2p->pdf_colorspace = T2P_CS_RGB;
+ if (t2p->tiff_samplesperpixel == 3)
+ {
+ break;
+ }
+ if (TIFFGetField(input, TIFFTAG_INDEXED, &xuint16))
+ {
+ if (xuint16 == 1)
+ goto photometric_palette;
+ }
+ if (t2p->tiff_samplesperpixel > 3)
+ {
+ if (t2p->tiff_samplesperpixel == 4)
+ {
+ t2p->pdf_colorspace = T2P_CS_RGB;
+ if (TIFFGetField(input, TIFFTAG_EXTRASAMPLES, &xuint16,
+ &xuint16p) &&
+ xuint16 == 1)
+ {
+ if (xuint16p[0] == EXTRASAMPLE_ASSOCALPHA)
+ {
+ if (t2p->tiff_bitspersample != 8)
+ {
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "No support for BitsPerSample=%" PRIu16
+ " for RGBA",
+ t2p->tiff_bitspersample);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ t2p->pdf_sample = T2P_SAMPLE_RGBAA_TO_RGB;
+ break;
+ }
+ if (xuint16p[0] == EXTRASAMPLE_UNASSALPHA)
+ {
+ if (t2p->tiff_bitspersample != 8)
+ {
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "No support for BitsPerSample=%" PRIu16
+ " for RGBA",
+ t2p->tiff_bitspersample);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ t2p->pdf_sample = T2P_SAMPLE_RGBA_TO_RGB;
+ break;
+ }
+ TIFFWarning(TIFF2PDF_MODULE,
+ "RGB image %s has 4 samples per pixel, "
+ "assuming RGBA",
+ TIFFFileName(input));
+ break;
+ }
+ t2p->pdf_colorspace = T2P_CS_CMYK;
+ t2p->pdf_switchdecode ^= 1;
+ TIFFWarning(TIFF2PDF_MODULE,
+ "RGB image %s has 4 samples per pixel, "
+ "assuming inverse CMYK",
+ TIFFFileName(input));
+ break;
+ }
+ else
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for RGB image %s with %" PRIu16
+ " samples per pixel",
+ TIFFFileName(input), t2p->tiff_samplesperpixel);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ break;
+ }
+ }
+ else
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for RGB image %s with %" PRIu16
+ " samples per pixel",
+ TIFFFileName(input), t2p->tiff_samplesperpixel);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ break;
+ }
+ case PHOTOMETRIC_PALETTE:
+ photometric_palette:
+ if (t2p->tiff_samplesperpixel != 1)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for palettized image %s with not one "
+ "sample per pixel",
+ TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
-
- }
-
- switch(t2p->tiff_photometric){
- case PHOTOMETRIC_MINISWHITE:
- case PHOTOMETRIC_MINISBLACK:
- if (t2p->tiff_bitspersample==1){
- t2p->pdf_colorspace=T2P_CS_BILEVEL;
- if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){
- t2p->pdf_switchdecode ^= 1;
- }
- } else {
- t2p->pdf_colorspace=T2P_CS_GRAY;
- if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){
- t2p->pdf_switchdecode ^= 1;
- }
- }
- break;
- case PHOTOMETRIC_RGB:
- t2p->pdf_colorspace=T2P_CS_RGB;
- if(t2p->tiff_samplesperpixel == 3){
- break;
- }
- if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){
- if(xuint16==1)
- goto photometric_palette;
- }
- if(t2p->tiff_samplesperpixel > 3) {
- if(t2p->tiff_samplesperpixel == 4) {
- t2p->pdf_colorspace = T2P_CS_RGB;
- if(TIFFGetField(input,
- TIFFTAG_EXTRASAMPLES,
- &xuint16, &xuint16p)
- && xuint16 == 1) {
- if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){
- if( t2p->tiff_bitspersample != 8 )
- {
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for BitsPerSample=%"PRIu16" for RGBA",
- t2p->tiff_bitspersample);
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB;
- break;
- }
- if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){
- if( t2p->tiff_bitspersample != 8 )
- {
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for BitsPerSample=%"PRIu16" for RGBA",
- t2p->tiff_bitspersample);
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB;
- break;
- }
- TIFFWarning(
- TIFF2PDF_MODULE,
- "RGB image %s has 4 samples per pixel, assuming RGBA",
- TIFFFileName(input));
- break;
- }
- t2p->pdf_colorspace=T2P_CS_CMYK;
- t2p->pdf_switchdecode ^= 1;
- TIFFWarning(
- TIFF2PDF_MODULE,
- "RGB image %s has 4 samples per pixel, assuming inverse CMYK",
- TIFFFileName(input));
- break;
- } else {
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for RGB image %s with %"PRIu16" samples per pixel",
- TIFFFileName(input),
- t2p->tiff_samplesperpixel);
- t2p->t2p_error = T2P_ERR_ERROR;
- break;
- }
- } else {
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for RGB image %s with %"PRIu16" samples per pixel",
- TIFFFileName(input),
- t2p->tiff_samplesperpixel);
- t2p->t2p_error = T2P_ERR_ERROR;
- break;
- }
- case PHOTOMETRIC_PALETTE:
- photometric_palette:
- if(t2p->tiff_samplesperpixel!=1){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for palettized image %s with not one sample per pixel",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE;
- t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample;
- if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){
- TIFFError(
- TIFF2PDF_MODULE,
- "Palettized image %s has no color map",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- if(r == NULL || g == NULL || b == NULL){
- TIFFError(
- TIFF2PDF_MODULE,
- "Error getting 3 components from color map");
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- if(t2p->pdf_palette != NULL){
- _TIFFfree(t2p->pdf_palette);
- t2p->pdf_palette=NULL;
- }
- t2p->pdf_palette = (unsigned char*)
- _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,3));
- if(t2p->pdf_palette==NULL){
- TIFFError(
- TIFF2PDF_MODULE,
- "Can't allocate %"PRIu16" bytes of memory for t2p_read_tiff_image, %s",
- t2p->pdf_palettesize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- /* Some older tiffs may have colors in the palette
- * ranging from 0 to 255 rather than 0 to 65535. */
- for(i=0;i<t2p->pdf_palettesize;i++){
- if ((r[i]>255)||(g[i]>255)||(b[i]>255)){
- palette_16bit = 1;
- break;
- }
- }
- if (palette_16bit == 0){
- TIFFWarning(TIFFFileName(input), "Assuming 8-bit colormap");
- palette_shift = 0;
- }
- for(i=0;i<t2p->pdf_palettesize;i++){
- t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>palette_shift);
- t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>palette_shift);
- t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>palette_shift);
- }
- t2p->pdf_palettesize *= 3;
- break;
- case PHOTOMETRIC_SEPARATED:
- if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){
- if(xuint16==1){
- goto photometric_palette_cmyk;
- }
- }
- if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){
- if(xuint16 != INKSET_CMYK){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s because its inkset is not CMYK",
- TIFFFileName(input) );
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- }
- if(t2p->tiff_samplesperpixel==4){
- t2p->pdf_colorspace=T2P_CS_CMYK;
- } else {
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s because it has %"PRIu16" samples per pixel",
- TIFFFileName(input),
- t2p->tiff_samplesperpixel);
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- break;
- photometric_palette_cmyk:
- if(t2p->tiff_samplesperpixel!=1){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for palettized CMYK image %s with not one sample per pixel",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE;
- t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample;
- if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){
- TIFFError(
- TIFF2PDF_MODULE,
- "Palettized image %s has no color map",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- if(r == NULL || g == NULL || b == NULL || a == NULL){
- TIFFError(
- TIFF2PDF_MODULE,
- "Error getting 4 components from color map");
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- if(t2p->pdf_palette != NULL){
- _TIFFfree(t2p->pdf_palette);
- t2p->pdf_palette=NULL;
- }
- t2p->pdf_palette = (unsigned char*)
- _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,4));
- if(t2p->pdf_palette==NULL){
- TIFFError(
- TIFF2PDF_MODULE,
- "Can't allocate %"PRIu16" bytes of memory for t2p_read_tiff_image, %s",
- t2p->pdf_palettesize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- for(i=0;i<t2p->pdf_palettesize;i++){
- t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8);
- t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8);
- t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8);
- t2p->pdf_palette[(i*4)+3]= (unsigned char) (a[i]>>8);
- }
- t2p->pdf_palettesize *= 4;
- break;
- case PHOTOMETRIC_YCBCR:
- t2p->pdf_colorspace=T2P_CS_RGB;
- if(t2p->tiff_samplesperpixel==1){
- t2p->pdf_colorspace=T2P_CS_GRAY;
- t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK;
- break;
- }
- t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB;
+ }
+ t2p->pdf_colorspace = T2P_CS_RGB | T2P_CS_PALETTE;
+ t2p->pdf_palettesize = 0x0001 << t2p->tiff_bitspersample;
+ if (!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Palettized image %s has no color map",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ if (r == NULL || g == NULL || b == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error getting 3 components from color map");
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ if (t2p->pdf_palette != NULL)
+ {
+ _TIFFfree(t2p->pdf_palette);
+ t2p->pdf_palette = NULL;
+ }
+ t2p->pdf_palette = (unsigned char *)_TIFFmalloc(
+ TIFFSafeMultiply(tmsize_t, t2p->pdf_palettesize, 3));
+ if (t2p->pdf_palette == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" PRIu16
+ " bytes of memory for t2p_read_tiff_image, %s",
+ t2p->pdf_palettesize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ /* Some older tiffs may have colors in the palette
+ * ranging from 0 to 255 rather than 0 to 65535. */
+ for (i = 0; i < t2p->pdf_palettesize; i++)
+ {
+ if ((r[i] > 255) || (g[i] > 255) || (b[i] > 255))
+ {
+ palette_16bit = 1;
+ break;
+ }
+ }
+ if (palette_16bit == 0)
+ {
+ TIFFWarning(TIFFFileName(input), "Assuming 8-bit colormap");
+ palette_shift = 0;
+ }
+ for (i = 0; i < t2p->pdf_palettesize; i++)
+ {
+ t2p->pdf_palette[(i * 3)] =
+ (unsigned char)(r[i] >> palette_shift);
+ t2p->pdf_palette[(i * 3) + 1] =
+ (unsigned char)(g[i] >> palette_shift);
+ t2p->pdf_palette[(i * 3) + 2] =
+ (unsigned char)(b[i] >> palette_shift);
+ }
+ t2p->pdf_palettesize *= 3;
+ break;
+ case PHOTOMETRIC_SEPARATED:
+ if (TIFFGetField(input, TIFFTAG_INDEXED, &xuint16))
+ {
+ if (xuint16 == 1)
+ {
+ goto photometric_palette_cmyk;
+ }
+ }
+ if (TIFFGetField(input, TIFFTAG_INKSET, &xuint16))
+ {
+ if (xuint16 != INKSET_CMYK)
+ {
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "No support for %s because its inkset is not CMYK",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ }
+ if (t2p->tiff_samplesperpixel == 4)
+ {
+ t2p->pdf_colorspace = T2P_CS_CMYK;
+ }
+ else
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for %s because it has %" PRIu16
+ " samples per pixel",
+ TIFFFileName(input), t2p->tiff_samplesperpixel);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ break;
+ photometric_palette_cmyk:
+ if (t2p->tiff_samplesperpixel != 1)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for palettized CMYK image %s with not "
+ "one sample per pixel",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ t2p->pdf_colorspace = T2P_CS_CMYK | T2P_CS_PALETTE;
+ t2p->pdf_palettesize = 0x0001 << t2p->tiff_bitspersample;
+ if (!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Palettized image %s has no color map",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ if (r == NULL || g == NULL || b == NULL || a == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error getting 4 components from color map");
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ if (t2p->pdf_palette != NULL)
+ {
+ _TIFFfree(t2p->pdf_palette);
+ t2p->pdf_palette = NULL;
+ }
+ t2p->pdf_palette = (unsigned char *)_TIFFmalloc(
+ TIFFSafeMultiply(tmsize_t, t2p->pdf_palettesize, 4));
+ if (t2p->pdf_palette == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" PRIu16
+ " bytes of memory for t2p_read_tiff_image, %s",
+ t2p->pdf_palettesize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ for (i = 0; i < t2p->pdf_palettesize; i++)
+ {
+ t2p->pdf_palette[(i * 4)] = (unsigned char)(r[i] >> 8);
+ t2p->pdf_palette[(i * 4) + 1] = (unsigned char)(g[i] >> 8);
+ t2p->pdf_palette[(i * 4) + 2] = (unsigned char)(b[i] >> 8);
+ t2p->pdf_palette[(i * 4) + 3] = (unsigned char)(a[i] >> 8);
+ }
+ t2p->pdf_palettesize *= 4;
+ break;
+ case PHOTOMETRIC_YCBCR:
+ t2p->pdf_colorspace = T2P_CS_RGB;
+ if (t2p->tiff_samplesperpixel == 1)
+ {
+ t2p->pdf_colorspace = T2P_CS_GRAY;
+ t2p->tiff_photometric = PHOTOMETRIC_MINISBLACK;
+ break;
+ }
+ t2p->pdf_sample = T2P_SAMPLE_YCBCR_TO_RGB;
#ifdef JPEG_SUPPORT
- if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
- t2p->pdf_sample=T2P_SAMPLE_NOTHING;
- }
+ if (t2p->pdf_defaultcompression == T2P_COMPRESS_JPEG)
+ {
+ t2p->pdf_sample = T2P_SAMPLE_NOTHING;
+ }
#endif
- break;
- case PHOTOMETRIC_CIELAB:
- if( t2p->tiff_samplesperpixel != 3){
- TIFFError(
- TIFF2PDF_MODULE,
- "Unsupported samplesperpixel = %"PRIu16" for CIELAB",
- t2p->tiff_samplesperpixel);
+ break;
+ case PHOTOMETRIC_CIELAB:
+ if (t2p->tiff_samplesperpixel != 3)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Unsupported samplesperpixel = %" PRIu16
+ " for CIELAB",
+ t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
- if( t2p->tiff_bitspersample != 8){
- TIFFError(
- TIFF2PDF_MODULE,
- "Invalid bitspersample = %"PRIu16" for CIELAB",
- t2p->tiff_bitspersample);
+ if (t2p->tiff_bitspersample != 8)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Invalid bitspersample = %" PRIu16 " for CIELAB",
+ t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
- t2p->pdf_labrange[0]= -127;
- t2p->pdf_labrange[1]= 127;
- t2p->pdf_labrange[2]= -127;
- t2p->pdf_labrange[3]= 127;
- t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
- t2p->pdf_colorspace=T2P_CS_LAB;
- break;
- case PHOTOMETRIC_ICCLAB:
- t2p->pdf_labrange[0]= 0;
- t2p->pdf_labrange[1]= 255;
- t2p->pdf_labrange[2]= 0;
- t2p->pdf_labrange[3]= 255;
- t2p->pdf_colorspace=T2P_CS_LAB;
- break;
- case PHOTOMETRIC_ITULAB:
- if( t2p->tiff_samplesperpixel != 3){
- TIFFError(
- TIFF2PDF_MODULE,
- "Unsupported samplesperpixel = %"PRIu16" for ITULAB",
- t2p->tiff_samplesperpixel);
+ t2p->pdf_labrange[0] = -127;
+ t2p->pdf_labrange[1] = 127;
+ t2p->pdf_labrange[2] = -127;
+ t2p->pdf_labrange[3] = 127;
+ t2p->pdf_sample = T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
+ t2p->pdf_colorspace = T2P_CS_LAB;
+ break;
+ case PHOTOMETRIC_ICCLAB:
+ t2p->pdf_labrange[0] = 0;
+ t2p->pdf_labrange[1] = 255;
+ t2p->pdf_labrange[2] = 0;
+ t2p->pdf_labrange[3] = 255;
+ t2p->pdf_colorspace = T2P_CS_LAB;
+ break;
+ case PHOTOMETRIC_ITULAB:
+ if (t2p->tiff_samplesperpixel != 3)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Unsupported samplesperpixel = %" PRIu16
+ " for ITULAB",
+ t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
- if( t2p->tiff_bitspersample != 8){
- TIFFError(
- TIFF2PDF_MODULE,
- "Invalid bitspersample = %"PRIu16" for ITULAB",
- t2p->tiff_bitspersample);
+ if (t2p->tiff_bitspersample != 8)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Invalid bitspersample = %" PRIu16 " for ITULAB",
+ t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
- t2p->pdf_labrange[0]=-85;
- t2p->pdf_labrange[1]=85;
- t2p->pdf_labrange[2]=-75;
- t2p->pdf_labrange[3]=124;
- t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
- t2p->pdf_colorspace=T2P_CS_LAB;
- break;
- case PHOTOMETRIC_LOGL:
- case PHOTOMETRIC_LOGLUV:
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with photometric interpretation LogL/LogLuv",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- default:
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with photometric interpretation %"PRIu16,
- TIFFFileName(input),
- t2p->tiff_photometric);
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
-
- if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){
- switch(t2p->tiff_planar){
- case 0:
- TIFFWarning(
- TIFF2PDF_MODULE,
- "Image %s has planar configuration 0, assuming 1",
- TIFFFileName(input));
- t2p->tiff_planar=PLANARCONFIG_CONTIG;
- case PLANARCONFIG_CONTIG:
- break;
- case PLANARCONFIG_SEPARATE:
- t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG;
- if(t2p->tiff_bitspersample!=8){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with separated planar configuration and %"PRIu16" bits per sample",
- TIFFFileName(input),
- t2p->tiff_bitspersample);
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- break;
- default:
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with planar configuration %"PRIu16,
- TIFFFileName(input),
- t2p->tiff_planar);
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- }
+ t2p->pdf_labrange[0] = -85;
+ t2p->pdf_labrange[1] = 85;
+ t2p->pdf_labrange[2] = -75;
+ t2p->pdf_labrange[3] = 124;
+ t2p->pdf_sample = T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
+ t2p->pdf_colorspace = T2P_CS_LAB;
+ break;
+ case PHOTOMETRIC_LOGL:
+ case PHOTOMETRIC_LOGLUV:
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "No support for %s with photometric interpretation LogL/LogLuv",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ default:
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "No support for %s with photometric interpretation %" PRIu16,
+ TIFFFileName(input), t2p->tiff_photometric);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
- TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION,
- &(t2p->tiff_orientation));
- if(t2p->tiff_orientation>8){
+ if (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar)))
+ {
+ switch (t2p->tiff_planar)
+ {
+ case 0:
TIFFWarning(TIFF2PDF_MODULE,
- "Image %s has orientation %"PRIu16", assuming 0",
- TIFFFileName(input), t2p->tiff_orientation);
- t2p->tiff_orientation=0;
- }
-
- if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){
- t2p->tiff_xres=0.0;
- }
- if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){
- t2p->tiff_yres=0.0;
- }
- TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT,
- &(t2p->tiff_resunit));
- if(t2p->tiff_resunit == RESUNIT_CENTIMETER) {
- t2p->tiff_xres *= 2.54F;
- t2p->tiff_yres *= 2.54F;
- } else if (t2p->tiff_resunit != RESUNIT_INCH
- && t2p->pdf_centimeters != 0) {
- t2p->tiff_xres *= 2.54F;
- t2p->tiff_yres *= 2.54F;
- }
-
- t2p_compose_pdf_page(t2p);
- if( t2p->t2p_error == T2P_ERR_ERROR )
- return;
-
- t2p->pdf_transcode = T2P_TRANSCODE_ENCODE;
- /* It seems that T2P_TRANSCODE_RAW mode doesn't support separate->contig */
- /* conversion. At least t2p_read_tiff_size and t2p_read_tiff_size_tile */
- /* do not take into account the number of samples, and thus */
- /* that can cause heap buffer overflows such as in */
- /* http://bugzilla.maptools.org/show_bug.cgi?id=2715 */
- if(t2p->pdf_nopassthrough==0 && t2p->tiff_planar!=PLANARCONFIG_SEPARATE){
+ "Image %s has planar configuration 0, assuming 1",
+ TIFFFileName(input));
+ t2p->tiff_planar = PLANARCONFIG_CONTIG;
+ case PLANARCONFIG_CONTIG:
+ break;
+ case PLANARCONFIG_SEPARATE:
+ t2p->pdf_sample = T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG;
+ if (t2p->tiff_bitspersample != 8)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for %s with separated planar "
+ "configuration and %" PRIu16 " bits per sample",
+ TIFFFileName(input), t2p->tiff_bitspersample);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ break;
+ default:
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "No support for %s with planar configuration %" PRIu16,
+ TIFFFileName(input), t2p->tiff_planar);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ }
+
+ TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION, &(t2p->tiff_orientation));
+ if (t2p->tiff_orientation > 8)
+ {
+ TIFFWarning(TIFF2PDF_MODULE,
+ "Image %s has orientation %" PRIu16 ", assuming 0",
+ TIFFFileName(input), t2p->tiff_orientation);
+ t2p->tiff_orientation = 0;
+ }
+
+ if (TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres)) == 0)
+ {
+ t2p->tiff_xres = 0.0;
+ }
+ if (TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres)) == 0)
+ {
+ t2p->tiff_yres = 0.0;
+ }
+ TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit));
+ if (t2p->tiff_resunit == RESUNIT_CENTIMETER)
+ {
+ t2p->tiff_xres *= 2.54F;
+ t2p->tiff_yres *= 2.54F;
+ }
+ else if (t2p->tiff_resunit != RESUNIT_INCH && t2p->pdf_centimeters != 0)
+ {
+ t2p->tiff_xres *= 2.54F;
+ t2p->tiff_yres *= 2.54F;
+ }
+
+ t2p_compose_pdf_page(t2p);
+ if (t2p->t2p_error == T2P_ERR_ERROR)
+ return;
+
+ t2p->pdf_transcode = T2P_TRANSCODE_ENCODE;
+ /* It seems that T2P_TRANSCODE_RAW mode doesn't support separate->contig */
+ /* conversion. At least t2p_read_tiff_size and t2p_read_tiff_size_tile */
+ /* do not take into account the number of samples, and thus */
+ /* that can cause heap buffer overflows such as in */
+ /* http://bugzilla.maptools.org/show_bug.cgi?id=2715 */
+ if (t2p->pdf_nopassthrough == 0 &&
+ t2p->tiff_planar != PLANARCONFIG_SEPARATE)
+ {
#ifdef CCITT_SUPPORT
- if(t2p->tiff_compression==COMPRESSION_CCITTFAX4
- ){
- if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){
- t2p->pdf_transcode = T2P_TRANSCODE_RAW;
- t2p->pdf_compression=T2P_COMPRESS_G4;
- }
- }
+ if (t2p->tiff_compression == COMPRESSION_CCITTFAX4)
+ {
+ if (TIFFIsTiled(input) || (TIFFNumberOfStrips(input) == 1))
+ {
+ t2p->pdf_transcode = T2P_TRANSCODE_RAW;
+ t2p->pdf_compression = T2P_COMPRESS_G4;
+ }
+ }
#endif
#ifdef ZIP_SUPPORT
- if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE
- || t2p->tiff_compression==COMPRESSION_DEFLATE){
- if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){
- uint16_t predictor;
- t2p->pdf_transcode = T2P_TRANSCODE_RAW;
- t2p->pdf_compression=T2P_COMPRESS_ZIP;
- if (TIFFGetField(input, TIFFTAG_PREDICTOR, &predictor)) {
- t2p->pdf_compressionquality = predictor;
- } else {
- t2p->pdf_compressionquality = PREDICTOR_NONE;
- }
- /* TIFFTAG_ZIPQUALITY is always Z_DEFAULT_COMPRESSION on reading */
- }
- }
+ if (t2p->tiff_compression == COMPRESSION_ADOBE_DEFLATE ||
+ t2p->tiff_compression == COMPRESSION_DEFLATE)
+ {
+ if (TIFFIsTiled(input) || (TIFFNumberOfStrips(input) == 1))
+ {
+ uint16_t predictor;
+ t2p->pdf_transcode = T2P_TRANSCODE_RAW;
+ t2p->pdf_compression = T2P_COMPRESS_ZIP;
+ if (TIFFGetField(input, TIFFTAG_PREDICTOR, &predictor))
+ {
+ t2p->pdf_compressionquality = predictor;
+ }
+ else
+ {
+ t2p->pdf_compressionquality = PREDICTOR_NONE;
+ }
+ /* TIFFTAG_ZIPQUALITY is always Z_DEFAULT_COMPRESSION on reading
+ */
+ }
+ }
#endif
#ifdef OJPEG_SUPPORT
- if(t2p->tiff_compression==COMPRESSION_OJPEG){
- t2p->pdf_transcode = T2P_TRANSCODE_RAW;
- t2p->pdf_compression=T2P_COMPRESS_JPEG;
- t2p_process_ojpeg_tables(t2p, input);
- }
+ if (t2p->tiff_compression == COMPRESSION_OJPEG)
+ {
+ t2p->pdf_transcode = T2P_TRANSCODE_RAW;
+ t2p->pdf_compression = T2P_COMPRESS_JPEG;
+ t2p_process_ojpeg_tables(t2p, input);
+ }
#endif
#ifdef JPEG_SUPPORT
- if(t2p->tiff_compression==COMPRESSION_JPEG){
- t2p->pdf_transcode = T2P_TRANSCODE_RAW;
- t2p->pdf_compression=T2P_COMPRESS_JPEG;
- }
+ if (t2p->tiff_compression == COMPRESSION_JPEG)
+ {
+ t2p->pdf_transcode = T2P_TRANSCODE_RAW;
+ t2p->pdf_compression = T2P_COMPRESS_JPEG;
+ }
#endif
- (void)0;
- }
+ (void)0;
+ }
- if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){
- t2p->pdf_compression = t2p->pdf_defaultcompression;
- }
+ if (t2p->pdf_transcode != T2P_TRANSCODE_RAW)
+ {
+ t2p->pdf_compression = t2p->pdf_defaultcompression;
+ }
#ifdef JPEG_SUPPORT
- if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
- if(t2p->pdf_colorspace & T2P_CS_PALETTE){
- t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE;
- t2p->pdf_colorspace ^= T2P_CS_PALETTE;
- t2p->tiff_pages[t2p->pdf_page].page_extra--;
- }
- }
- if(t2p->tiff_compression==COMPRESSION_JPEG){
- if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with JPEG compression and separated planar configuration",
- TIFFFileName(input));
- t2p->t2p_error=T2P_ERR_ERROR;
- return;
- }
- }
+ if (t2p->pdf_defaultcompression == T2P_COMPRESS_JPEG)
+ {
+ if (t2p->pdf_colorspace & T2P_CS_PALETTE)
+ {
+ t2p->pdf_sample |= T2P_SAMPLE_REALIZE_PALETTE;
+ t2p->pdf_colorspace ^= T2P_CS_PALETTE;
+ t2p->tiff_pages[t2p->pdf_page].page_extra--;
+ }
+ }
+ if (t2p->tiff_compression == COMPRESSION_JPEG)
+ {
+ if (t2p->tiff_planar == PLANARCONFIG_SEPARATE)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for %s with JPEG compression and separated "
+ "planar configuration",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ }
#endif
#ifdef OJPEG_SUPPORT
- if(t2p->tiff_compression==COMPRESSION_OJPEG){
- if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
- TIFFError(
- TIFF2PDF_MODULE,
- "No support for %s with OJPEG compression and separated planar configuration",
- TIFFFileName(input));
- t2p->t2p_error=T2P_ERR_ERROR;
- return;
- }
- }
+ if (t2p->tiff_compression == COMPRESSION_OJPEG)
+ {
+ if (t2p->tiff_planar == PLANARCONFIG_SEPARATE)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for %s with OJPEG compression and separated "
+ "planar configuration",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ }
#endif
- if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){
- if(t2p->pdf_colorspace & T2P_CS_CMYK){
- t2p->tiff_samplesperpixel=4;
- t2p->tiff_photometric=PHOTOMETRIC_SEPARATED;
- } else {
- t2p->tiff_samplesperpixel=3;
- t2p->tiff_photometric=PHOTOMETRIC_RGB;
- }
- }
-
- if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION,
- &(t2p->tiff_transferfunction[0]),
- &(t2p->tiff_transferfunction[1]),
- &(t2p->tiff_transferfunction[2]))) {
- if((t2p->tiff_transferfunction[1] != (uint16_t*) NULL) &&
- (t2p->tiff_transferfunction[2] != (uint16_t*) NULL)
- ) {
- t2p->tiff_transferfunctioncount=3;
- } else {
- t2p->tiff_transferfunctioncount=1;
- }
- } else {
- t2p->tiff_transferfunctioncount=0;
- }
- if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){
- t2p->tiff_whitechromaticities[0]=xfloatp[0];
- t2p->tiff_whitechromaticities[1]=xfloatp[1];
- if(t2p->pdf_colorspace & T2P_CS_GRAY){
- t2p->pdf_colorspace |= T2P_CS_CALGRAY;
- }
- if(t2p->pdf_colorspace & T2P_CS_RGB){
- t2p->pdf_colorspace |= T2P_CS_CALRGB;
- }
- }
- if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){
- t2p->tiff_primarychromaticities[0]=xfloatp[0];
- t2p->tiff_primarychromaticities[1]=xfloatp[1];
- t2p->tiff_primarychromaticities[2]=xfloatp[2];
- t2p->tiff_primarychromaticities[3]=xfloatp[3];
- t2p->tiff_primarychromaticities[4]=xfloatp[4];
- t2p->tiff_primarychromaticities[5]=xfloatp[5];
- if(t2p->pdf_colorspace & T2P_CS_RGB){
- t2p->pdf_colorspace |= T2P_CS_CALRGB;
- }
- }
- if(t2p->pdf_colorspace & T2P_CS_LAB){
- if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){
- t2p->tiff_whitechromaticities[0]=xfloatp[0];
- t2p->tiff_whitechromaticities[1]=xfloatp[1];
- } else {
- t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */
- t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */
- }
- }
- if(TIFFGetField(input,
- TIFFTAG_ICCPROFILE,
- &(t2p->tiff_iccprofilelength),
- &(t2p->tiff_iccprofile))!=0){
- t2p->pdf_colorspace |= T2P_CS_ICCBASED;
- } else {
- t2p->tiff_iccprofilelength=0;
- t2p->tiff_iccprofile=NULL;
- }
-
+ if (t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE)
+ {
+ if (t2p->pdf_colorspace & T2P_CS_CMYK)
+ {
+ t2p->tiff_samplesperpixel = 4;
+ t2p->tiff_photometric = PHOTOMETRIC_SEPARATED;
+ }
+ else
+ {
+ t2p->tiff_samplesperpixel = 3;
+ t2p->tiff_photometric = PHOTOMETRIC_RGB;
+ }
+ }
+
+ if (TIFFGetField(
+ input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]),
+ &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2])))
+ {
+ if ((t2p->tiff_transferfunction[1] != (uint16_t *)NULL) &&
+ (t2p->tiff_transferfunction[2] != (uint16_t *)NULL))
+ {
+ t2p->tiff_transferfunctioncount = 3;
+ }
+ else
+ {
+ t2p->tiff_transferfunctioncount = 1;
+ }
+ }
+ else
+ {
+ t2p->tiff_transferfunctioncount = 0;
+ }
+ if (TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0)
+ {
+ t2p->tiff_whitechromaticities[0] = xfloatp[0];
+ t2p->tiff_whitechromaticities[1] = xfloatp[1];
+ if (t2p->pdf_colorspace & T2P_CS_GRAY)
+ {
+ t2p->pdf_colorspace |= T2P_CS_CALGRAY;
+ }
+ if (t2p->pdf_colorspace & T2P_CS_RGB)
+ {
+ t2p->pdf_colorspace |= T2P_CS_CALRGB;
+ }
+ }
+ if (TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp) != 0)
+ {
+ t2p->tiff_primarychromaticities[0] = xfloatp[0];
+ t2p->tiff_primarychromaticities[1] = xfloatp[1];
+ t2p->tiff_primarychromaticities[2] = xfloatp[2];
+ t2p->tiff_primarychromaticities[3] = xfloatp[3];
+ t2p->tiff_primarychromaticities[4] = xfloatp[4];
+ t2p->tiff_primarychromaticities[5] = xfloatp[5];
+ if (t2p->pdf_colorspace & T2P_CS_RGB)
+ {
+ t2p->pdf_colorspace |= T2P_CS_CALRGB;
+ }
+ }
+ if (t2p->pdf_colorspace & T2P_CS_LAB)
+ {
+ if (TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0)
+ {
+ t2p->tiff_whitechromaticities[0] = xfloatp[0];
+ t2p->tiff_whitechromaticities[1] = xfloatp[1];
+ }
+ else
+ {
+ t2p->tiff_whitechromaticities[0] = 0.3457F; /* 0.3127F; */
+ t2p->tiff_whitechromaticities[1] = 0.3585F; /* 0.3290F; */
+ }
+ }
+ if (TIFFGetField(input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength),
+ &(t2p->tiff_iccprofile)) != 0)
+ {
+ t2p->pdf_colorspace |= T2P_CS_ICCBASED;
+ }
+ else
+ {
+ t2p->tiff_iccprofilelength = 0;
+ t2p->tiff_iccprofile = NULL;
+ }
+
#ifdef CCITT_SUPPORT
- if( t2p->tiff_bitspersample==1 &&
- t2p->tiff_samplesperpixel==1){
- t2p->pdf_compression = T2P_COMPRESS_G4;
- }
+ if (t2p->tiff_bitspersample == 1 && t2p->tiff_samplesperpixel == 1)
+ {
+ t2p->pdf_compression = T2P_COMPRESS_G4;
+ }
#endif
-
- return;
+ return;
}
/**
* checks for overflow
*/
-static void t2p_set_tiff_datasize(T2P* t2p, uint64_t k) {
- if (k != (uint64_t)(tmsize_t)k || (tmsize_t)k < 0) {
- TIFFError(TIFF2PDF_MODULE, "Integer overflow");
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- t2p->tiff_datasize = (tmsize_t)k;
+static void t2p_set_tiff_datasize(T2P *t2p, uint64_t k)
+{
+ if (k != (uint64_t)(tmsize_t)k || (tmsize_t)k < 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ t2p->tiff_datasize = (tmsize_t)k;
}
/**
- This function returns the necessary size of a data buffer to contain the raw or
- uncompressed image data from the input TIFF for a page.
+ This function returns the necessary size of a data buffer to contain the
+ raw or uncompressed image data from the input TIFF for a page.
*/
-void t2p_read_tiff_size(T2P* t2p, TIFF* input){
+void t2p_read_tiff_size(T2P *t2p, TIFF *input)
+{
- uint64_t* sbc=NULL;
+ uint64_t *sbc = NULL;
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
- unsigned char* jpt=NULL;
- tstrip_t i=0;
- tstrip_t stripcount=0;
+ unsigned char *jpt = NULL;
+ tstrip_t i = 0;
+ tstrip_t stripcount = 0;
#endif
- uint64_t k = 0;
+ uint64_t k = 0;
- if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){
+ if (t2p->pdf_transcode == T2P_TRANSCODE_RAW)
+ {
#if defined(CCITT_SUPPORT) || defined(ZIP_SUPPORT)
#if defined(CCITT_SUPPORT) && defined(ZIP_SUPPORT)
- if(t2p->pdf_compression == T2P_COMPRESS_G4 || t2p->pdf_compression == T2P_COMPRESS_ZIP)
+ if (t2p->pdf_compression == T2P_COMPRESS_G4 ||
+ t2p->pdf_compression == T2P_COMPRESS_ZIP)
#elif defined(CCITT_SUPPORT)
- if(t2p->pdf_compression == T2P_COMPRESS_G4)
+ if (t2p->pdf_compression == T2P_COMPRESS_G4)
#else
- if(t2p->pdf_compression == T2P_COMPRESS_ZIP)
+ if (t2p->pdf_compression == T2P_COMPRESS_ZIP)
#endif
- {
- if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){
- TIFFError(TIFF2PDF_MODULE,
- "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- t2p_set_tiff_datasize(t2p, sbc[0]);
- return;
- }
+ {
+ if (!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc))
+ {
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ t2p_set_tiff_datasize(t2p, sbc[0]);
+ return;
+ }
#endif
#ifdef OJPEG_SUPPORT
- if(t2p->tiff_compression == COMPRESSION_OJPEG){
- if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){
- TIFFError(TIFF2PDF_MODULE,
- "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- stripcount=TIFFNumberOfStrips(input);
- for(i=0;i<stripcount;i++){
- k = checkAdd64(k, sbc[i], t2p);
- }
- if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){
- if(t2p->tiff_dataoffset != 0){
- if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){
- if((uint64_t)t2p->tiff_datasize < k) {
- TIFFWarning(TIFF2PDF_MODULE,
- "Input file %s has short JPEG interchange file byte count",
- TIFFFileName(input));
- t2p->pdf_ojpegiflength=t2p->tiff_datasize;
- k = checkAdd64(k, t2p->tiff_datasize, t2p);
- k = checkAdd64(k, 6, t2p);
- k = checkAdd64(k, stripcount, t2p);
- k = checkAdd64(k, stripcount, t2p);
- t2p_set_tiff_datasize(t2p, k);
- return;
- }
- return;
- }else {
- TIFFError(TIFF2PDF_MODULE,
- "Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- }
- }
- k = checkAdd64(k, stripcount, t2p);
- k = checkAdd64(k, stripcount, t2p);
- k = checkAdd64(k, 2048, t2p);
- t2p_set_tiff_datasize(t2p, k);
- return;
- }
+ if (t2p->tiff_compression == COMPRESSION_OJPEG)
+ {
+ if (!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc))
+ {
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ stripcount = TIFFNumberOfStrips(input);
+ for (i = 0; i < stripcount; i++)
+ {
+ k = checkAdd64(k, sbc[i], t2p);
+ }
+ if (TIFFGetField(input, TIFFTAG_JPEGIFOFFSET,
+ &(t2p->tiff_dataoffset)))
+ {
+ if (t2p->tiff_dataoffset != 0)
+ {
+ if (TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT,
+ &(t2p->tiff_datasize)) != 0)
+ {
+ if ((uint64_t)t2p->tiff_datasize < k)
+ {
+ TIFFWarning(TIFF2PDF_MODULE,
+ "Input file %s has short JPEG "
+ "interchange file byte count",
+ TIFFFileName(input));
+ t2p->pdf_ojpegiflength = t2p->tiff_datasize;
+ k = checkAdd64(k, t2p->tiff_datasize, t2p);
+ k = checkAdd64(k, 6, t2p);
+ k = checkAdd64(k, stripcount, t2p);
+ k = checkAdd64(k, stripcount, t2p);
+ t2p_set_tiff_datasize(t2p, k);
+ return;
+ }
+ return;
+ }
+ else
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Input file %s missing field: "
+ "TIFFTAG_JPEGIFBYTECOUNT",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ }
+ }
+ k = checkAdd64(k, stripcount, t2p);
+ k = checkAdd64(k, stripcount, t2p);
+ k = checkAdd64(k, 2048, t2p);
+ t2p_set_tiff_datasize(t2p, k);
+ return;
+ }
#endif
#ifdef JPEG_SUPPORT
- if(t2p->tiff_compression == COMPRESSION_JPEG) {
- uint32_t count = 0;
- if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){
- if(count > 4){
- k += count;
- k -= 2; /* don't use EOI of header */
- }
- } else {
- k = 2; /* SOI for first strip */
- }
- stripcount=TIFFNumberOfStrips(input);
- if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){
- TIFFError(TIFF2PDF_MODULE,
- "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- for(i=0;i<stripcount;i++){
- k = checkAdd64(k, sbc[i], t2p);
- k -=2; /* don't use EOI of strip */
- k +=2; /* add space for restart marker */
- }
- k = checkAdd64(k, 2, t2p); /* use EOI of last strip */
- k = checkAdd64(k, 6, t2p); /* for DRI marker of first strip */
- t2p_set_tiff_datasize(t2p, k);
- return;
- }
+ if (t2p->tiff_compression == COMPRESSION_JPEG)
+ {
+ uint32_t count = 0;
+ if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0)
+ {
+ if (count > 4)
+ {
+ k += count;
+ k -= 2; /* don't use EOI of header */
+ }
+ }
+ else
+ {
+ k = 2; /* SOI for first strip */
+ }
+ stripcount = TIFFNumberOfStrips(input);
+ if (!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc))
+ {
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ for (i = 0; i < stripcount; i++)
+ {
+ k = checkAdd64(k, sbc[i], t2p);
+ k -= 2; /* don't use EOI of strip */
+ k += 2; /* add space for restart marker */
+ }
+ k = checkAdd64(k, 2, t2p); /* use EOI of last strip */
+ k = checkAdd64(k, 6, t2p); /* for DRI marker of first strip */
+ t2p_set_tiff_datasize(t2p, k);
+ return;
+ }
#endif
- (void) 0;
- }
+ (void)0;
+ }
#ifdef JPEG_SUPPORT
- if(t2p->pdf_compression == T2P_COMPRESS_JPEG
- && t2p->tiff_photometric == PHOTOMETRIC_YCBCR) {
- k = checkMultiply64(TIFFNumberOfStrips(input), TIFFStripSize(input), t2p);
- } else
+ if (t2p->pdf_compression == T2P_COMPRESS_JPEG &&
+ t2p->tiff_photometric == PHOTOMETRIC_YCBCR)
+ {
+ k = checkMultiply64(TIFFNumberOfStrips(input), TIFFStripSize(input),
+ t2p);
+ }
+ else
#endif
- {
- k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p);
- if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
- k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p);
- }
- }
- if (k == 0) {
- /* Assume we had overflow inside TIFFScanlineSize */
- t2p->t2p_error = T2P_ERR_ERROR;
- }
-
- t2p_set_tiff_datasize(t2p, k);
-
- return;
+ {
+ k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p);
+ if (t2p->tiff_planar == PLANARCONFIG_SEPARATE)
+ {
+ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p);
+ }
+ }
+ if (k == 0)
+ {
+ /* Assume we had overflow inside TIFFScanlineSize */
+ t2p->t2p_error = T2P_ERR_ERROR;
+ }
+
+ t2p_set_tiff_datasize(t2p, k);
+
+ return;
}
/*
- This function returns the necessary size of a data buffer to contain the raw or
- uncompressed image data from the input TIFF for a tile of a page.
+ This function returns the necessary size of a data buffer to contain the
+ raw or uncompressed image data from the input TIFF for a tile of a page.
*/
-void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){
+void t2p_read_tiff_size_tile(T2P *t2p, TIFF *input, ttile_t tile)
+{
- uint64_t* tbc = NULL;
- uint16_t edge=0;
+ uint64_t *tbc = NULL;
+ uint16_t edge = 0;
#ifdef JPEG_SUPPORT
- unsigned char* jpt;
+ unsigned char *jpt;
#endif
- uint64_t k;
+ uint64_t k;
- edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
- edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
-
- if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){
- if(edge
+ edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
+ edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
+
+ if (t2p->pdf_transcode == T2P_TRANSCODE_RAW)
+ {
+ if (edge
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
- && !(t2p->pdf_compression==T2P_COMPRESS_JPEG)
+ && !(t2p->pdf_compression == T2P_COMPRESS_JPEG)
#endif
- ){
- t2p->tiff_datasize=TIFFTileSize(input);
- if (t2p->tiff_datasize == 0) {
- /* Assume we had overflow inside TIFFTileSize */
- t2p->t2p_error = T2P_ERR_ERROR;
- }
- return;
- } else {
- TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc);
- k=tbc[tile];
+ )
+ {
+ t2p->tiff_datasize = TIFFTileSize(input);
+ if (t2p->tiff_datasize == 0)
+ {
+ /* Assume we had overflow inside TIFFTileSize */
+ t2p->t2p_error = T2P_ERR_ERROR;
+ }
+ return;
+ }
+ else
+ {
+ TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc);
+ k = tbc[tile];
#ifdef OJPEG_SUPPORT
- if(t2p->tiff_compression==COMPRESSION_OJPEG){
- k = checkAdd64(k, 2048, t2p);
- }
+ if (t2p->tiff_compression == COMPRESSION_OJPEG)
+ {
+ k = checkAdd64(k, 2048, t2p);
+ }
#endif
#ifdef JPEG_SUPPORT
- if(t2p->tiff_compression==COMPRESSION_JPEG) {
- uint32_t count = 0;
- if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt)!=0){
- if(count > 4){
- k = checkAdd64(k, count, t2p);
- k -= 2; /* don't use EOI of header or SOI of tile */
- }
- }
- }
+ if (t2p->tiff_compression == COMPRESSION_JPEG)
+ {
+ uint32_t count = 0;
+ if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0)
+ {
+ if (count > 4)
+ {
+ k = checkAdd64(k, count, t2p);
+ k -= 2; /* don't use EOI of header or SOI of tile */
+ }
+ }
+ }
#endif
- t2p_set_tiff_datasize(t2p, k);
- return;
- }
- }
- k = TIFFTileSize(input);
- if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
- k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p);
- }
- if (k == 0) {
- /* Assume we had overflow inside TIFFTileSize */
- t2p->t2p_error = T2P_ERR_ERROR;
- }
-
- t2p_set_tiff_datasize(t2p, k);
-
- return;
+ t2p_set_tiff_datasize(t2p, k);
+ return;
+ }
+ }
+ k = TIFFTileSize(input);
+ if (t2p->tiff_planar == PLANARCONFIG_SEPARATE)
+ {
+ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p);
+ }
+ if (k == 0)
+ {
+ /* Assume we had overflow inside TIFFTileSize */
+ t2p->t2p_error = T2P_ERR_ERROR;
+ }
+
+ t2p_set_tiff_datasize(t2p, k);
+
+ return;
}
/*
@@ -2189,14 +2388,18 @@ void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){
* and does not have full imaged tile width.
*/
-int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){
+int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile)
+{
- if( ((tile+1) % tiles.tiles_tilecountx == 0)
- && (tiles.tiles_edgetilewidth != 0) ){
- return(1);
- } else {
- return(0);
- }
+ if (((tile + 1) % tiles.tiles_tilecountx == 0) &&
+ (tiles.tiles_edgetilewidth != 0))
+ {
+ return (1);
+ }
+ else
+ {
+ return (0);
+ }
}
/*
@@ -2204,14 +2407,18 @@ int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){
* and does not have full imaged tile length.
*/
-int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){
+int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile)
+{
- if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) )
- && (tiles.tiles_edgetilelength != 0) ){
- return(1);
- } else {
- return(0);
- }
+ if (((tile + 1) > (tiles.tiles_tilecount - tiles.tiles_tilecountx)) &&
+ (tiles.tiles_edgetilelength != 0))
+ {
+ return (1);
+ }
+ else
+ {
+ return (0);
+ }
}
/*
@@ -2219,249 +2426,261 @@ int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){
* or a bottom edge tile.
*/
-int t2p_tile_is_edge(T2P_TILES tiles, ttile_t tile){
+int t2p_tile_is_edge(T2P_TILES tiles, ttile_t tile)
+{
- return(t2p_tile_is_right_edge(tiles, tile) | t2p_tile_is_bottom_edge(tiles, tile) );
+ return (t2p_tile_is_right_edge(tiles, tile) |
+ t2p_tile_is_bottom_edge(tiles, tile));
}
/*
- This function returns a non-zero value when the tile is a right edge tile and a bottom
- edge tile.
+ This function returns a non-zero value when the tile is a right edge
+ tile and a bottom edge tile.
*/
-int t2p_tile_is_corner_edge(T2P_TILES tiles, ttile_t tile){
+int t2p_tile_is_corner_edge(T2P_TILES tiles, ttile_t tile)
+{
- return(t2p_tile_is_right_edge(tiles, tile) & t2p_tile_is_bottom_edge(tiles, tile) );
+ return (t2p_tile_is_right_edge(tiles, tile) &
+ t2p_tile_is_bottom_edge(tiles, tile));
}
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
-static const unsigned char jpeg_eof_marker[] = { 0xff, 0xd9 };
+static const unsigned char jpeg_eof_marker[] = {0xff, 0xd9};
#endif
/*
- This function reads the raster image data from the input TIFF for an image and writes
- the data to the output PDF XObject image dictionary stream. It returns the amount written
- or zero on error.
+ This function reads the raster image data from the input TIFF for an
+ image and writes the data to the output PDF XObject image dictionary stream.
+ It returns the amount written or zero on error.
*/
-tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){
-
- tsize_t written=0;
- unsigned char* buffer=NULL;
- unsigned char* samplebuffer=NULL;
- tsize_t bufferoffset=0;
- tsize_t samplebufferoffset=0;
- tsize_t read=0;
- tstrip_t i=0;
- tstrip_t j=0;
- tstrip_t stripcount=0;
- tsize_t stripsize=0;
- tsize_t sepstripcount=0;
- tsize_t sepstripsize=0;
+tsize_t t2p_readwrite_pdf_image(T2P *t2p, TIFF *input, TIFF *output)
+{
+
+ tsize_t written = 0;
+ unsigned char *buffer = NULL;
+ unsigned char *samplebuffer = NULL;
+ tsize_t bufferoffset = 0;
+ tsize_t samplebufferoffset = 0;
+ tsize_t read = 0;
+ tstrip_t i = 0;
+ tstrip_t j = 0;
+ tstrip_t stripcount = 0;
+ tsize_t stripsize = 0;
+ tsize_t sepstripcount = 0;
+ tsize_t sepstripsize = 0;
#ifdef OJPEG_SUPPORT
- toff_t inputoffset=0;
- uint16_t h_samp=1;
- uint16_t v_samp=1;
- uint16_t ri=1;
- uint32_t rows=0;
+ toff_t inputoffset = 0;
+ uint16_t h_samp = 1;
+ uint16_t v_samp = 1;
+ uint16_t ri = 1;
+ uint32_t rows = 0;
#endif /* ifdef OJPEG_SUPPORT */
#ifdef JPEG_SUPPORT
- unsigned char* jpt;
- float* xfloatp;
- uint64_t* sbc;
- unsigned char* stripbuffer;
- tsize_t striplength=0;
- uint32_t max_striplength=0;
+ unsigned char *jpt;
+ float *xfloatp;
+ uint64_t *sbc;
+ unsigned char *stripbuffer;
+ tsize_t striplength = 0;
+ uint32_t max_striplength = 0;
#endif /* ifdef JPEG_SUPPORT */
- /* Fail if prior error (in particular, can't trust tiff_datasize) */
- if (t2p->t2p_error != T2P_ERR_OK)
- return(0);
+ /* Fail if prior error (in particular, can't trust tiff_datasize) */
+ if (t2p->t2p_error != T2P_ERR_OK)
+ return (0);
- if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){
+ if (t2p->pdf_transcode == T2P_TRANSCODE_RAW)
+ {
#ifdef CCITT_SUPPORT
- if(t2p->pdf_compression == T2P_COMPRESS_G4){
- buffer = (unsigned char*)
- _TIFFmalloc(t2p->tiff_datasize);
- if (buffer == NULL) {
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for "
- "t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- if (TIFFReadRawStrip(input, 0, (tdata_t) buffer,
- t2p->tiff_datasize) < 0) {
- TIFFError(TIFF2PDF_MODULE,
- "TIFFReadRawStrip() failed");
- _TIFFfree(buffer);
- return(0);
- }
- if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
- /*
- * make sure is lsb-to-msb
- * bit-endianness fill order
- */
- TIFFReverseBits(buffer,
- t2p->tiff_datasize);
- }
- t2pWriteFile(output, (tdata_t) buffer,
- t2p->tiff_datasize);
- _TIFFfree(buffer);
- return(t2p->tiff_datasize);
- }
+ if (t2p->pdf_compression == T2P_COMPRESS_G4)
+ {
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for "
+ "t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ if (TIFFReadRawStrip(input, 0, (tdata_t)buffer,
+ t2p->tiff_datasize) < 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "TIFFReadRawStrip() failed");
+ _TIFFfree(buffer);
+ return (0);
+ }
+ if (t2p->tiff_fillorder == FILLORDER_LSB2MSB)
+ {
+ /*
+ * make sure is lsb-to-msb
+ * bit-endianness fill order
+ */
+ TIFFReverseBits(buffer, t2p->tiff_datasize);
+ }
+ t2pWriteFile(output, (tdata_t)buffer, t2p->tiff_datasize);
+ _TIFFfree(buffer);
+ return (t2p->tiff_datasize);
+ }
#endif /* ifdef CCITT_SUPPORT */
#ifdef ZIP_SUPPORT
- if (t2p->pdf_compression == T2P_COMPRESS_ZIP) {
- buffer = (unsigned char*)
- _TIFFmalloc(t2p->tiff_datasize);
- if(buffer == NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- if (TIFFReadRawStrip(input, 0, (tdata_t) buffer,
- t2p->tiff_datasize) < 0) {
- TIFFError(TIFF2PDF_MODULE,
- "TIFFReadRawStrip() failed");
- _TIFFfree(buffer);
- return(0);
- }
- if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) {
- TIFFReverseBits(buffer,
- t2p->tiff_datasize);
- }
- t2pWriteFile(output, (tdata_t) buffer,
- t2p->tiff_datasize);
- _TIFFfree(buffer);
- return(t2p->tiff_datasize);
- }
+ if (t2p->pdf_compression == T2P_COMPRESS_ZIP)
+ {
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ if (TIFFReadRawStrip(input, 0, (tdata_t)buffer,
+ t2p->tiff_datasize) < 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "TIFFReadRawStrip() failed");
+ _TIFFfree(buffer);
+ return (0);
+ }
+ if (t2p->tiff_fillorder == FILLORDER_LSB2MSB)
+ {
+ TIFFReverseBits(buffer, t2p->tiff_datasize);
+ }
+ t2pWriteFile(output, (tdata_t)buffer, t2p->tiff_datasize);
+ _TIFFfree(buffer);
+ return (t2p->tiff_datasize);
+ }
#endif /* ifdef ZIP_SUPPORT */
#ifdef OJPEG_SUPPORT
- if(t2p->tiff_compression == COMPRESSION_OJPEG) {
-
- if(t2p->tiff_dataoffset != 0) {
- buffer = (unsigned char*)
- _TIFFmalloc(t2p->tiff_datasize);
- if(buffer == NULL) {
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- if(t2p->pdf_ojpegiflength==0){
- inputoffset=t2pSeekFile(input, 0,
- SEEK_CUR);
- t2pSeekFile(input,
- t2p->tiff_dataoffset,
- SEEK_SET);
- t2pReadFile(input, (tdata_t) buffer,
- t2p->tiff_datasize);
- t2pSeekFile(input, inputoffset,
- SEEK_SET);
- t2pWriteFile(output, (tdata_t) buffer,
- t2p->tiff_datasize);
- _TIFFfree(buffer);
- return(t2p->tiff_datasize);
- } else {
- inputoffset=t2pSeekFile(input, 0,
- SEEK_CUR);
- t2pSeekFile(input,
- t2p->tiff_dataoffset,
- SEEK_SET);
- bufferoffset = t2pReadFile(input,
- (tdata_t) buffer,
- t2p->pdf_ojpegiflength);
- t2p->pdf_ojpegiflength = 0;
- t2pSeekFile(input, inputoffset,
- SEEK_SET);
- TIFFGetField(input,
- TIFFTAG_YCBCRSUBSAMPLING,
- &h_samp, &v_samp);
- buffer[bufferoffset++]= 0xff;
- buffer[bufferoffset++]= 0xdd;
- buffer[bufferoffset++]= 0x00;
- buffer[bufferoffset++]= 0x04;
- h_samp*=8;
- v_samp*=8;
- ri=(t2p->tiff_width+h_samp-1) / h_samp;
- TIFFGetField(input,
- TIFFTAG_ROWSPERSTRIP,
- &rows);
- ri*=(rows+v_samp-1)/v_samp;
- buffer[bufferoffset++]= (ri>>8) & 0xff;
- buffer[bufferoffset++]= ri & 0xff;
- stripcount=TIFFNumberOfStrips(input);
- for(i=0;i<stripcount;i++){
- if(i != 0 ){
- buffer[bufferoffset++]=0xff;
- buffer[bufferoffset++]=(0xd0 | ((i-1)%8));
- }
- bufferoffset+=TIFFReadRawStrip(input,
- i,
- (tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
- -1);
- }
- t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
- _TIFFfree(buffer);
- return(bufferoffset);
- }
- } else {
- if(! t2p->pdf_ojpegdata){
- TIFFError(TIFF2PDF_MODULE,
- "No support for OJPEG image %s with bad tables",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- buffer = (unsigned char*)
- _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
- bufferoffset=t2p->pdf_ojpegdatalength;
- stripcount=TIFFNumberOfStrips(input);
- for(i=0;i<stripcount;i++){
- tsize_t retTIFFReadRawStrip;
- if(i != 0){
- buffer[bufferoffset++]=0xff;
- buffer[bufferoffset++]=(0xd0 | ((i-1)%8));
- }
- retTIFFReadRawStrip = TIFFReadRawStrip(input,
- i,
- (tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
- -1);
- if (retTIFFReadRawStrip < 0) {
- TIFFError(TIFF2PDF_MODULE, "TIFFReadRawStrip()");
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- bufferoffset += retTIFFReadRawStrip;
- }
- t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
- if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){
- t2pWriteFile(output, (tdata_t) jpeg_eof_marker, sizeof(jpeg_eof_marker));
- }
- _TIFFfree(buffer);
- return(bufferoffset);
+ if (t2p->tiff_compression == COMPRESSION_OJPEG)
+ {
+
+ if (t2p->tiff_dataoffset != 0)
+ {
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ if (t2p->pdf_ojpegiflength == 0)
+ {
+ inputoffset = t2pSeekFile(input, 0, SEEK_CUR);
+ t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET);
+ t2pReadFile(input, (tdata_t)buffer, t2p->tiff_datasize);
+ t2pSeekFile(input, inputoffset, SEEK_SET);
+ t2pWriteFile(output, (tdata_t)buffer, t2p->tiff_datasize);
+ _TIFFfree(buffer);
+ return (t2p->tiff_datasize);
+ }
+ else
+ {
+ inputoffset = t2pSeekFile(input, 0, SEEK_CUR);
+ t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET);
+ bufferoffset = t2pReadFile(input, (tdata_t)buffer,
+ t2p->pdf_ojpegiflength);
+ t2p->pdf_ojpegiflength = 0;
+ t2pSeekFile(input, inputoffset, SEEK_SET);
+ TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp,
+ &v_samp);
+ buffer[bufferoffset++] = 0xff;
+ buffer[bufferoffset++] = 0xdd;
+ buffer[bufferoffset++] = 0x00;
+ buffer[bufferoffset++] = 0x04;
+ h_samp *= 8;
+ v_samp *= 8;
+ ri = (t2p->tiff_width + h_samp - 1) / h_samp;
+ TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows);
+ ri *= (rows + v_samp - 1) / v_samp;
+ buffer[bufferoffset++] = (ri >> 8) & 0xff;
+ buffer[bufferoffset++] = ri & 0xff;
+ stripcount = TIFFNumberOfStrips(input);
+ for (i = 0; i < stripcount; i++)
+ {
+ if (i != 0)
+ {
+ buffer[bufferoffset++] = 0xff;
+ buffer[bufferoffset++] = (0xd0 | ((i - 1) % 8));
+ }
+ bufferoffset += TIFFReadRawStrip(
+ input, i,
+ (tdata_t) &
+ (((unsigned char *)buffer)[bufferoffset]),
+ -1);
+ }
+ t2pWriteFile(output, (tdata_t)buffer, bufferoffset);
+ _TIFFfree(buffer);
+ return (bufferoffset);
+ }
+ }
+ else
+ {
+ if (!t2p->pdf_ojpegdata)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for OJPEG image %s with bad tables",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ _TIFFmemcpy(buffer, t2p->pdf_ojpegdata,
+ t2p->pdf_ojpegdatalength);
+ bufferoffset = t2p->pdf_ojpegdatalength;
+ stripcount = TIFFNumberOfStrips(input);
+ for (i = 0; i < stripcount; i++)
+ {
+ tsize_t retTIFFReadRawStrip;
+ if (i != 0)
+ {
+ buffer[bufferoffset++] = 0xff;
+ buffer[bufferoffset++] = (0xd0 | ((i - 1) % 8));
+ }
+ retTIFFReadRawStrip = TIFFReadRawStrip(
+ input, i,
+ (tdata_t) & (((unsigned char *)buffer)[bufferoffset]),
+ -1);
+ if (retTIFFReadRawStrip < 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "TIFFReadRawStrip()");
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ bufferoffset += retTIFFReadRawStrip;
+ }
+ t2pWriteFile(output, (tdata_t)buffer, bufferoffset);
+ if (!((buffer[bufferoffset - 1] == 0xd9) &&
+ (buffer[bufferoffset - 2] == 0xff)))
+ {
+ t2pWriteFile(output, (tdata_t)jpeg_eof_marker,
+ sizeof(jpeg_eof_marker));
+ }
+ _TIFFfree(buffer);
+ return (bufferoffset);
#if 0
/*
This hunk of code removed code is clearly
@@ -2474,392 +2693,426 @@ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
#endif
- }
- }
+ }
+ }
#endif /* ifdef OJPEG_SUPPORT */
#ifdef JPEG_SUPPORT
- if(t2p->tiff_compression == COMPRESSION_JPEG) {
- uint32_t count = 0;
- buffer = (unsigned char*)
- _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
- if(count > 4) {
- _TIFFmemcpy(buffer, jpt, count);
- bufferoffset += count - 2;
- }
- }
- stripcount=TIFFNumberOfStrips(input);
- TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
- for(i=0;i<stripcount;i++){
- if(sbc[i]>max_striplength) max_striplength=sbc[i];
- }
- stripbuffer = (unsigned char*)
- _TIFFmalloc(max_striplength);
- if(stripbuffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"PRId32" bytes of memory for t2p_readwrite_pdf_image, %s",
- max_striplength,
- TIFFFileName(input));
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(stripbuffer, 0, max_striplength);
- for(i=0;i<stripcount;i++){
- striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1);
- if (striplength < 0) {
- TIFFError(TIFF2PDF_MODULE, "TIFFReadRawStrip() failed");
- _TIFFfree(samplebuffer);
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- if(!t2p_process_jpeg_strip(
- stripbuffer,
- &striplength,
- buffer,
- t2p->tiff_datasize,
- &bufferoffset,
- i,
- t2p->tiff_length)){
- TIFFError(TIFF2PDF_MODULE,
- "Can't process JPEG data in input file %s",
- TIFFFileName(input));
- _TIFFfree(samplebuffer);
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- }
- t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
- t2pWriteFile(output, (tdata_t) jpeg_eof_marker, sizeof(jpeg_eof_marker));
- _TIFFfree(stripbuffer);
- _TIFFfree(buffer);
- return(bufferoffset);
- }
+ if (t2p->tiff_compression == COMPRESSION_JPEG)
+ {
+ uint32_t count = 0;
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0)
+ {
+ if (count > 4)
+ {
+ _TIFFmemcpy(buffer, jpt, count);
+ bufferoffset += count - 2;
+ }
+ }
+ stripcount = TIFFNumberOfStrips(input);
+ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
+ for (i = 0; i < stripcount; i++)
+ {
+ if (sbc[i] > max_striplength)
+ max_striplength = sbc[i];
+ }
+ stripbuffer = (unsigned char *)_TIFFmalloc(max_striplength);
+ if (stripbuffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" PRId32
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ max_striplength, TIFFFileName(input));
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(stripbuffer, 0, max_striplength);
+ for (i = 0; i < stripcount; i++)
+ {
+ striplength =
+ TIFFReadRawStrip(input, i, (tdata_t)stripbuffer, -1);
+ if (striplength < 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "TIFFReadRawStrip() failed");
+ _TIFFfree(samplebuffer);
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ if (!t2p_process_jpeg_strip(stripbuffer, &striplength, buffer,
+ t2p->tiff_datasize, &bufferoffset,
+ i, t2p->tiff_length))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't process JPEG data in input file %s",
+ TIFFFileName(input));
+ _TIFFfree(samplebuffer);
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ }
+ t2pWriteFile(output, (tdata_t)buffer, bufferoffset);
+ t2pWriteFile(output, (tdata_t)jpeg_eof_marker,
+ sizeof(jpeg_eof_marker));
+ _TIFFfree(stripbuffer);
+ _TIFFfree(buffer);
+ return (bufferoffset);
+ }
#endif /* ifdef JPEG_SUPPORT */
- (void)0;
- }
-
- if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
- buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- stripsize=TIFFStripSize(input);
- stripcount=TIFFNumberOfStrips(input);
- for(i=0;i<stripcount;i++){
- read =
- TIFFReadEncodedStrip(input,
- i,
- (tdata_t) &buffer[bufferoffset],
- TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset));
- if(read==-1){
- TIFFError(TIFF2PDF_MODULE,
- "Error on decoding strip %"PRIu32" of %s",
- i,
- TIFFFileName(input));
- _TIFFfree(buffer);
- t2p->t2p_error=T2P_ERR_ERROR;
- return(0);
- }
- bufferoffset+=read;
- }
- } else {
- if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
-
- sepstripsize=TIFFStripSize(input);
- sepstripcount=TIFFNumberOfStrips(input);
-
- stripsize=sepstripsize*t2p->tiff_samplesperpixel;
- stripcount=sepstripcount/t2p->tiff_samplesperpixel;
-
- buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- samplebuffer = (unsigned char*) _TIFFmalloc(stripsize);
- if(samplebuffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- _TIFFfree(buffer);
- return(0);
- }
- for(i=0;i<stripcount;i++){
- samplebufferoffset=0;
- for(j=0;j<t2p->tiff_samplesperpixel;j++){
- read =
- TIFFReadEncodedStrip(input,
- i + j*stripcount,
- (tdata_t) &(samplebuffer[samplebufferoffset]),
- TIFFmin(sepstripsize, stripsize - samplebufferoffset));
- if(read==-1){
- TIFFError(TIFF2PDF_MODULE,
- "Error on decoding strip %"PRIu32" of %s",
- i + j*stripcount,
- TIFFFileName(input));
- t2p->t2p_error=T2P_ERR_ERROR;
- _TIFFfree(samplebuffer);
- _TIFFfree(buffer);
- return(0);
- }
- samplebufferoffset+=read;
- }
- t2p_sample_planar_separate_to_contig(
- t2p,
- &(buffer[bufferoffset]),
- samplebuffer,
- samplebufferoffset);
- bufferoffset+=samplebufferoffset;
- }
- _TIFFfree(samplebuffer);
- goto dataready;
- }
-
- buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- stripsize=TIFFStripSize(input);
- stripcount=TIFFNumberOfStrips(input);
- for(i=0;i<stripcount;i++){
- read =
- TIFFReadEncodedStrip(input,
- i,
- (tdata_t) &buffer[bufferoffset],
- TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset));
- if(read==-1){
- TIFFError(TIFF2PDF_MODULE,
- "Error on decoding strip %"PRIu32" of %s",
- i,
- TIFFFileName(input));
- _TIFFfree(samplebuffer);
- _TIFFfree(buffer);
- t2p->t2p_error=T2P_ERR_ERROR;
- return(0);
- }
- bufferoffset+=read;
- }
-
- if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){
- // FIXME: overflow?
- samplebuffer=(unsigned char*)_TIFFrealloc(
- (tdata_t) buffer,
- t2p->tiff_datasize * t2p->tiff_samplesperpixel);
- if(samplebuffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- _TIFFfree(buffer);
- return(0);
- } else {
- buffer=samplebuffer;
- t2p->tiff_datasize *= t2p->tiff_samplesperpixel;
- }
- t2p_sample_realize_palette(t2p, buffer);
- }
-
- if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
- t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
- (tdata_t)buffer,
- t2p->tiff_width*t2p->tiff_length);
- }
-
- if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
- t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
- (tdata_t)buffer,
- t2p->tiff_width*t2p->tiff_length);
- }
-
- if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
- samplebuffer=(unsigned char*)_TIFFrealloc(
- (tdata_t)buffer,
- t2p->tiff_width*t2p->tiff_length*4);
- if(samplebuffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- _TIFFfree(buffer);
- return(0);
- } else {
- buffer=samplebuffer;
- }
- if(!TIFFReadRGBAImageOriented(
- input,
- t2p->tiff_width,
- t2p->tiff_length,
- (uint32_t*)buffer,
- ORIENTATION_TOPLEFT,
- 0)){
- TIFFError(TIFF2PDF_MODULE,
- "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- t2p->tiff_datasize=t2p_sample_abgr_to_rgb(
- (tdata_t) buffer,
- t2p->tiff_width*t2p->tiff_length);
+ (void)0;
+ }
+
+ if (t2p->pdf_sample == T2P_SAMPLE_NOTHING)
+ {
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ stripsize = TIFFStripSize(input);
+ stripcount = TIFFNumberOfStrips(input);
+ for (i = 0; i < stripcount; i++)
+ {
+ read = TIFFReadEncodedStrip(
+ input, i, (tdata_t)&buffer[bufferoffset],
+ TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset));
+ if (read == -1)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error on decoding strip %" PRIu32 " of %s", i,
+ TIFFFileName(input));
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ bufferoffset += read;
+ }
+ }
+ else
+ {
+ if (t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG)
+ {
- }
+ sepstripsize = TIFFStripSize(input);
+ sepstripcount = TIFFNumberOfStrips(input);
+
+ stripsize = sepstripsize * t2p->tiff_samplesperpixel;
+ stripcount = sepstripcount / t2p->tiff_samplesperpixel;
+
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ samplebuffer = (unsigned char *)_TIFFmalloc(stripsize);
+ if (samplebuffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ _TIFFfree(buffer);
+ return (0);
+ }
+ for (i = 0; i < stripcount; i++)
+ {
+ samplebufferoffset = 0;
+ for (j = 0; j < t2p->tiff_samplesperpixel; j++)
+ {
+ read = TIFFReadEncodedStrip(
+ input, i + j * stripcount,
+ (tdata_t) & (samplebuffer[samplebufferoffset]),
+ TIFFmin(sepstripsize, stripsize - samplebufferoffset));
+ if (read == -1)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error on decoding strip %" PRIu32 " of %s",
+ i + j * stripcount, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ _TIFFfree(samplebuffer);
+ _TIFFfree(buffer);
+ return (0);
+ }
+ samplebufferoffset += read;
+ }
+ t2p_sample_planar_separate_to_contig(
+ t2p, &(buffer[bufferoffset]), samplebuffer,
+ samplebufferoffset);
+ bufferoffset += samplebufferoffset;
+ }
+ _TIFFfree(samplebuffer);
+ goto dataready;
+ }
+
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ stripsize = TIFFStripSize(input);
+ stripcount = TIFFNumberOfStrips(input);
+ for (i = 0; i < stripcount; i++)
+ {
+ read = TIFFReadEncodedStrip(
+ input, i, (tdata_t)&buffer[bufferoffset],
+ TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset));
+ if (read == -1)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error on decoding strip %" PRIu32 " of %s", i,
+ TIFFFileName(input));
+ _TIFFfree(samplebuffer);
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ bufferoffset += read;
+ }
+
+ if (t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE)
+ {
+ // FIXME: overflow?
+ samplebuffer = (unsigned char *)_TIFFrealloc(
+ (tdata_t)buffer,
+ t2p->tiff_datasize * t2p->tiff_samplesperpixel);
+ if (samplebuffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ _TIFFfree(buffer);
+ return (0);
+ }
+ else
+ {
+ buffer = samplebuffer;
+ t2p->tiff_datasize *= t2p->tiff_samplesperpixel;
+ }
+ t2p_sample_realize_palette(t2p, buffer);
+ }
+
+ if (t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB)
+ {
+ t2p->tiff_datasize = t2p_sample_rgba_to_rgb(
+ (tdata_t)buffer, t2p->tiff_width * t2p->tiff_length);
+ }
+
+ if (t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB)
+ {
+ t2p->tiff_datasize = t2p_sample_rgbaa_to_rgb(
+ (tdata_t)buffer, t2p->tiff_width * t2p->tiff_length);
+ }
+
+ if (t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB)
+ {
+ samplebuffer = (unsigned char *)_TIFFrealloc(
+ (tdata_t)buffer, t2p->tiff_width * t2p->tiff_length * 4);
+ if (samplebuffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ _TIFFfree(buffer);
+ return (0);
+ }
+ else
+ {
+ buffer = samplebuffer;
+ }
+ if (!TIFFReadRGBAImageOriented(input, t2p->tiff_width,
+ t2p->tiff_length, (uint32_t *)buffer,
+ ORIENTATION_TOPLEFT, 0))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't use TIFFReadRGBAImageOriented to extract RGB "
+ "image from %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ t2p->tiff_datasize = t2p_sample_abgr_to_rgb(
+ (tdata_t)buffer, t2p->tiff_width * t2p->tiff_length);
+ }
- if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
- t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
- (tdata_t)buffer,
- t2p->tiff_width*t2p->tiff_length);
- }
- }
+ if (t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED)
+ {
+ t2p->tiff_datasize = t2p_sample_lab_signed_to_unsigned(
+ (tdata_t)buffer, t2p->tiff_width * t2p->tiff_length);
+ }
+ }
dataready:
- t2p_disable(output);
- TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
- TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
- TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
- TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width);
- TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length);
- TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length);
- TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
- TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
-
- switch(t2p->pdf_compression){
- case T2P_COMPRESS_NONE:
- TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
- break;
+ t2p_disable(output);
+ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
+ TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
+ TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
+ TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width);
+ TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length);
+ TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length);
+ TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+ TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
+
+ switch (t2p->pdf_compression)
+ {
+ case T2P_COMPRESS_NONE:
+ TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
+ break;
#ifdef CCITT_SUPPORT
- case T2P_COMPRESS_G4:
- TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
- break;
+ case T2P_COMPRESS_G4:
+ TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
+ break;
#endif /* ifdef CCITT_SUPPORT */
#ifdef JPEG_SUPPORT
- case T2P_COMPRESS_JPEG:
- if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
- uint16_t hor = 0, ver = 0;
- if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) {
- if(hor != 0 && ver != 0){
- TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
- }
- }
- if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
- TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
- }
- }
- if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){
- TIFFError(TIFF2PDF_MODULE,
- "Unable to use JPEG compression for input %s and output %s",
- TIFFFileName(input),
- TIFFFileName(output));
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0);
-
- if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
- TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
- if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
- TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
- } else {
- TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
- }
- }
- if(t2p->pdf_colorspace & T2P_CS_GRAY){
- (void)0;
- }
- if(t2p->pdf_colorspace & T2P_CS_CMYK){
- (void)0;
- }
- if(t2p->pdf_defaultcompressionquality != 0){
- TIFFSetField(output,
- TIFFTAG_JPEGQUALITY,
- t2p->pdf_defaultcompressionquality);
- }
-
- break;
+ case T2P_COMPRESS_JPEG:
+ if (t2p->tiff_photometric == PHOTOMETRIC_YCBCR)
+ {
+ uint16_t hor = 0, ver = 0;
+ if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=
+ 0)
+ {
+ if (hor != 0 && ver != 0)
+ {
+ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor,
+ ver);
+ }
+ }
+ if (TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE,
+ &xfloatp) != 0)
+ {
+ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
+ }
+ }
+ if (TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG) ==
+ 0)
+ {
+ TIFFError(
+ TIFF2PDF_MODULE,
+ "Unable to use JPEG compression for input %s and output %s",
+ TIFFFileName(input), TIFFFileName(output));
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0);
+
+ if (t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB))
+ {
+ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
+ if (t2p->tiff_photometric != PHOTOMETRIC_YCBCR)
+ {
+ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE,
+ JPEGCOLORMODE_RGB);
+ }
+ else
+ {
+ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE,
+ JPEGCOLORMODE_RAW);
+ }
+ }
+ if (t2p->pdf_colorspace & T2P_CS_GRAY)
+ {
+ (void)0;
+ }
+ if (t2p->pdf_colorspace & T2P_CS_CMYK)
+ {
+ (void)0;
+ }
+ if (t2p->pdf_defaultcompressionquality != 0)
+ {
+ TIFFSetField(output, TIFFTAG_JPEGQUALITY,
+ t2p->pdf_defaultcompressionquality);
+ }
+
+ break;
#endif /* ifdef JPEG_SUPPORT */
#ifdef ZIP_SUPPORT
- case T2P_COMPRESS_ZIP:
- TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_ADOBE_DEFLATE);
- if(t2p->pdf_defaultcompressionquality%100 != 0){
- TIFFSetField(output,
- TIFFTAG_PREDICTOR,
- t2p->pdf_defaultcompressionquality % 100);
- }
- if(t2p->pdf_defaultcompressionquality/100 != 0){
- TIFFSetField(output,
- TIFFTAG_ZIPQUALITY,
- (t2p->pdf_defaultcompressionquality / 100));
- }
- break;
+ case T2P_COMPRESS_ZIP:
+ TIFFSetField(output, TIFFTAG_COMPRESSION,
+ COMPRESSION_ADOBE_DEFLATE);
+ if (t2p->pdf_defaultcompressionquality % 100 != 0)
+ {
+ TIFFSetField(output, TIFFTAG_PREDICTOR,
+ t2p->pdf_defaultcompressionquality % 100);
+ }
+ if (t2p->pdf_defaultcompressionquality / 100 != 0)
+ {
+ TIFFSetField(output, TIFFTAG_ZIPQUALITY,
+ (t2p->pdf_defaultcompressionquality / 100));
+ }
+ break;
#endif /* ifdef ZIP_SUPPORT */
- default:
- break;
- }
+ default:
+ break;
+ }
- t2p_enable(output);
- t2p->outputwritten = 0;
+ t2p_enable(output);
+ t2p->outputwritten = 0;
#ifdef JPEG_SUPPORT
- if(t2p->pdf_compression == T2P_COMPRESS_JPEG
- && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){
- bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0,
- buffer,
- stripsize * stripcount);
- } else
+ if (t2p->pdf_compression == T2P_COMPRESS_JPEG &&
+ t2p->tiff_photometric == PHOTOMETRIC_YCBCR)
+ {
+ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer,
+ stripsize * stripcount);
+ }
+ else
#endif /* ifdef JPEG_SUPPORT */
- {
- bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0,
- buffer,
- t2p->tiff_datasize);
- }
- if (buffer != NULL) {
- _TIFFfree(buffer);
- buffer=NULL;
- }
-
- if (bufferoffset == (tsize_t)-1) {
- TIFFError(TIFF2PDF_MODULE,
- "Error writing encoded strip to output PDF %s",
- TIFFFileName(output));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
-
- written = t2p->outputwritten;
- return(written);
+ {
+ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer,
+ t2p->tiff_datasize);
+ }
+ if (buffer != NULL)
+ {
+ _TIFFfree(buffer);
+ buffer = NULL;
+ }
+
+ if (bufferoffset == (tsize_t)-1)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error writing encoded strip to output PDF %s",
+ TIFFFileName(output));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+
+ written = t2p->outputwritten;
+ return (written);
}
/*
@@ -2868,896 +3121,990 @@ dataready:
* for the tile. It returns the amount written or zero on error.
*/
-tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){
-
- uint16_t edge=0;
- tsize_t written=0;
- unsigned char* buffer=NULL;
- tsize_t bufferoffset=0;
- unsigned char* samplebuffer=NULL;
- tsize_t samplebufferoffset=0;
- tsize_t read=0;
- uint16_t i=0;
- ttile_t tilecount=0;
- /* tsize_t tilesize=0; */
- ttile_t septilecount=0;
- tsize_t septilesize=0;
+tsize_t t2p_readwrite_pdf_image_tile(T2P *t2p, TIFF *input, TIFF *output,
+ ttile_t tile)
+{
+
+ uint16_t edge = 0;
+ tsize_t written = 0;
+ unsigned char *buffer = NULL;
+ tsize_t bufferoffset = 0;
+ unsigned char *samplebuffer = NULL;
+ tsize_t samplebufferoffset = 0;
+ tsize_t read = 0;
+ uint16_t i = 0;
+ ttile_t tilecount = 0;
+ /* tsize_t tilesize=0; */
+ ttile_t septilecount = 0;
+ tsize_t septilesize = 0;
#ifdef JPEG_SUPPORT
- unsigned char* jpt;
- float* xfloatp;
- uint32_t xuint32=0;
+ unsigned char *jpt;
+ float *xfloatp;
+ uint32_t xuint32 = 0;
#endif
- /* Fail if prior error (in particular, can't trust tiff_datasize) */
- if (t2p->t2p_error != T2P_ERR_OK)
- return(0);
+ /* Fail if prior error (in particular, can't trust tiff_datasize) */
+ if (t2p->t2p_error != T2P_ERR_OK)
+ return (0);
- edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
- edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
+ edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
+ edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
- if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0)
+ if ((t2p->pdf_transcode == T2P_TRANSCODE_RAW) &&
+ ((edge == 0)
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
- || (t2p->pdf_compression == T2P_COMPRESS_JPEG)
+ || (t2p->pdf_compression == T2P_COMPRESS_JPEG)
#endif
- )
- ){
+ ))
+ {
#ifdef CCITT_SUPPORT
- if(t2p->pdf_compression == T2P_COMPRESS_G4){
- buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory "
- "for t2p_readwrite_pdf_image_tile, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- if (TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize) < 0) {
- TIFFError(TIFF2PDF_MODULE,
- "TIFFReadRawTile() failed");
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
- TIFFReverseBits(buffer, t2p->tiff_datasize);
- }
- t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
- _TIFFfree(buffer);
- return(t2p->tiff_datasize);
- }
+ if (t2p->pdf_compression == T2P_COMPRESS_G4)
+ {
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory "
+ "for t2p_readwrite_pdf_image_tile, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ if (TIFFReadRawTile(input, tile, (tdata_t)buffer,
+ t2p->tiff_datasize) < 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "TIFFReadRawTile() failed");
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ if (t2p->tiff_fillorder == FILLORDER_LSB2MSB)
+ {
+ TIFFReverseBits(buffer, t2p->tiff_datasize);
+ }
+ t2pWriteFile(output, (tdata_t)buffer, t2p->tiff_datasize);
+ _TIFFfree(buffer);
+ return (t2p->tiff_datasize);
+ }
#endif
#ifdef ZIP_SUPPORT
- if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
- buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory "
- "for t2p_readwrite_pdf_image_tile, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- if (TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize) < 0) {
- TIFFError(TIFF2PDF_MODULE,
- "TIFFReadRawTile() failed");
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
- TIFFReverseBits(buffer, t2p->tiff_datasize);
- }
- t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
- _TIFFfree(buffer);
- return(t2p->tiff_datasize);
- }
+ if (t2p->pdf_compression == T2P_COMPRESS_ZIP)
+ {
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory "
+ "for t2p_readwrite_pdf_image_tile, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ if (TIFFReadRawTile(input, tile, (tdata_t)buffer,
+ t2p->tiff_datasize) < 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "TIFFReadRawTile() failed");
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ if (t2p->tiff_fillorder == FILLORDER_LSB2MSB)
+ {
+ TIFFReverseBits(buffer, t2p->tiff_datasize);
+ }
+ t2pWriteFile(output, (tdata_t)buffer, t2p->tiff_datasize);
+ _TIFFfree(buffer);
+ return (t2p->tiff_datasize);
+ }
#endif
#ifdef OJPEG_SUPPORT
- if(t2p->tiff_compression == COMPRESSION_OJPEG){
- tsize_t retTIFFReadRawTile;
- if(! t2p->pdf_ojpegdata){
- TIFFError(TIFF2PDF_MODULE,
- "No support for OJPEG image %s with "
- "bad tables",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory "
- "for t2p_readwrite_pdf_image, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
- if(edge!=0){
- if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
- buffer[7]=
- (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff;
- buffer[8]=
- (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff;
- }
- if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
- buffer[9]=
- (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff;
- buffer[10]=
- (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff;
- }
- }
- bufferoffset = t2p->pdf_ojpegdatalength;
- retTIFFReadRawTile = TIFFReadRawTile(input,
- tile,
- (tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
- -1);
- if (retTIFFReadRawTile < 0) {
- TIFFError(TIFF2PDF_MODULE, "TIFFReadRawTile() failed");
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- bufferoffset += retTIFFReadRawTile;
- t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
- t2pWriteFile(output, (tdata_t) jpeg_eof_marker, sizeof(jpeg_eof_marker));
- _TIFFfree(buffer);
- return(bufferoffset);
- }
+ if (t2p->tiff_compression == COMPRESSION_OJPEG)
+ {
+ tsize_t retTIFFReadRawTile;
+ if (!t2p->pdf_ojpegdata)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for OJPEG image %s with "
+ "bad tables",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory "
+ "for t2p_readwrite_pdf_image, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
+ if (edge != 0)
+ {
+ if (t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page],
+ tile))
+ {
+ buffer[7] =
+ (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >>
+ 8) &
+ 0xff;
+ buffer[8] =
+ (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength) &
+ 0xff;
+ }
+ if (t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page],
+ tile))
+ {
+ buffer[9] =
+ (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >>
+ 8) &
+ 0xff;
+ buffer[10] =
+ (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth) &
+ 0xff;
+ }
+ }
+ bufferoffset = t2p->pdf_ojpegdatalength;
+ retTIFFReadRawTile = TIFFReadRawTile(
+ input, tile,
+ (tdata_t) & (((unsigned char *)buffer)[bufferoffset]), -1);
+ if (retTIFFReadRawTile < 0)
+ {
+ TIFFError(TIFF2PDF_MODULE, "TIFFReadRawTile() failed");
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ bufferoffset += retTIFFReadRawTile;
+ t2pWriteFile(output, (tdata_t)buffer, bufferoffset);
+ t2pWriteFile(output, (tdata_t)jpeg_eof_marker,
+ sizeof(jpeg_eof_marker));
+ _TIFFfree(buffer);
+ return (bufferoffset);
+ }
#endif
#ifdef JPEG_SUPPORT
- if(t2p->tiff_compression == COMPRESSION_JPEG){
- unsigned char table_end[2];
- uint32_t count = 0;
- buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory "
- "for t2p_readwrite_pdf_image_tile, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
- if (count > 4) {
- tsize_t retTIFFReadRawTile;
+ if (t2p->tiff_compression == COMPRESSION_JPEG)
+ {
+ unsigned char table_end[2];
+ uint32_t count = 0;
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory "
+ "for t2p_readwrite_pdf_image_tile, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0)
+ {
+ if (count > 4)
+ {
+ tsize_t retTIFFReadRawTile;
/* Ignore EOI marker of JpegTables */
- _TIFFmemcpy(buffer, jpt, count - 2);
- bufferoffset += count - 2;
+ _TIFFmemcpy(buffer, jpt, count - 2);
+ bufferoffset += count - 2;
/* Store last 2 bytes of the JpegTables */
- table_end[0] = buffer[bufferoffset-2];
- table_end[1] = buffer[bufferoffset-1];
- xuint32 = bufferoffset;
- bufferoffset -= 2;
- retTIFFReadRawTile = TIFFReadRawTile(
- input,
- tile,
- (tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
- -1);
- if( retTIFFReadRawTile < 0 )
- {
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- bufferoffset += retTIFFReadRawTile;
+ table_end[0] = buffer[bufferoffset - 2];
+ table_end[1] = buffer[bufferoffset - 1];
+ xuint32 = bufferoffset;
+ bufferoffset -= 2;
+ retTIFFReadRawTile = TIFFReadRawTile(
+ input, tile,
+ (tdata_t) & (((unsigned char *)buffer)[bufferoffset]),
+ -1);
+ if (retTIFFReadRawTile < 0)
+ {
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ bufferoffset += retTIFFReadRawTile;
/* Overwrite SOI marker of image scan with previously */
/* saved end of JpegTables */
- buffer[xuint32-2]=table_end[0];
- buffer[xuint32-1]=table_end[1];
- }
- }
- t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
- _TIFFfree(buffer);
- return(bufferoffset);
- }
+ buffer[xuint32 - 2] = table_end[0];
+ buffer[xuint32 - 1] = table_end[1];
+ }
+ }
+ t2pWriteFile(output, (tdata_t)buffer, bufferoffset);
+ _TIFFfree(buffer);
+ return (bufferoffset);
+ }
#endif
- (void)0;
- }
-
- if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
- buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory for "
- "t2p_readwrite_pdf_image_tile, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
-
- read = TIFFReadEncodedTile(
- input,
- tile,
- (tdata_t) &buffer[bufferoffset],
- t2p->tiff_datasize);
- if(read==-1){
- TIFFError(TIFF2PDF_MODULE,
- "Error on decoding tile %"PRIu32" of %s",
- tile,
- TIFFFileName(input));
- _TIFFfree(buffer);
- t2p->t2p_error=T2P_ERR_ERROR;
- return(0);
- }
-
- } else {
-
- if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
- septilesize=TIFFTileSize(input);
- septilecount=TIFFNumberOfTiles(input);
- /* tilesize=septilesize*t2p->tiff_samplesperpixel; */
- tilecount=septilecount/t2p->tiff_samplesperpixel;
- buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory "
- "for t2p_readwrite_pdf_image_tile, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(samplebuffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory "
- "for t2p_readwrite_pdf_image_tile, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(samplebuffer, 0, t2p->tiff_datasize);
- samplebufferoffset=0;
- for(i=0;i<t2p->tiff_samplesperpixel;i++){
- read =
- TIFFReadEncodedTile(input,
- tile + i*tilecount,
- (tdata_t) &(samplebuffer[samplebufferoffset]),
- septilesize);
- if(read==-1){
- TIFFError(TIFF2PDF_MODULE,
- "Error on decoding tile %"PRIu32" of %s",
- tile + i*tilecount,
- TIFFFileName(input));
- _TIFFfree(samplebuffer);
- _TIFFfree(buffer);
- t2p->t2p_error=T2P_ERR_ERROR;
- return(0);
- }
- samplebufferoffset+=read;
- }
- t2p_sample_planar_separate_to_contig(
- t2p,
- &(buffer[bufferoffset]),
- samplebuffer,
- samplebufferoffset);
- bufferoffset+=samplebufferoffset;
- _TIFFfree(samplebuffer);
- }
-
- if(buffer==NULL){
- buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
- if(buffer==NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SSIZE_FORMAT" bytes of memory "
- "for t2p_readwrite_pdf_image_tile, %s",
- t2p->tiff_datasize,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- memset(buffer, 0, t2p->tiff_datasize);
- read = TIFFReadEncodedTile(
- input,
- tile,
- (tdata_t) &buffer[bufferoffset],
- t2p->tiff_datasize);
- if(read==-1){
- TIFFError(TIFF2PDF_MODULE,
- "Error on decoding tile %"PRIu32" of %s",
- tile,
- TIFFFileName(input));
- _TIFFfree(buffer);
- t2p->t2p_error=T2P_ERR_ERROR;
- return(0);
- }
- }
-
- if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
- t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
- (tdata_t)buffer,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
- *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
- }
-
- if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
- t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
- (tdata_t)buffer,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
- *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
- }
-
- if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
- TIFFError(TIFF2PDF_MODULE,
- "No support for YCbCr to RGB in tile for %s",
- TIFFFileName(input));
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
-
- if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
- t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
- (tdata_t)buffer,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
- *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
- }
- }
-
- if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){
- if ((uint64_t)t2p->tiff_datasize < (uint64_t)TIFFTileRowSize(input) * (uint64_t)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength) {
- /* we don't know how to handle PLANARCONFIG_CONTIG, PHOTOMETRIC_YCBCR with 3 samples per pixel */
- TIFFWarning(
- TIFF2PDF_MODULE,
- "Don't know how to collapse tile to the left");
- } else {
- t2p_tile_collapse_left(
- buffer,
- TIFFTileRowSize(input),
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth,
- t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
- }
- }
-
-
- t2p_disable(output);
- TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
- TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
- TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
- if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
- TIFFSetField(
- output,
- TIFFTAG_IMAGEWIDTH,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
- } else {
- TIFFSetField(
- output,
- TIFFTAG_IMAGEWIDTH,
- t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
- }
- if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
- TIFFSetField(
- output,
- TIFFTAG_IMAGELENGTH,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
- TIFFSetField(
- output,
- TIFFTAG_ROWSPERSTRIP,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
- } else {
- TIFFSetField(
- output,
- TIFFTAG_IMAGELENGTH,
- t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
- TIFFSetField(
- output,
- TIFFTAG_ROWSPERSTRIP,
- t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
- }
- TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
- TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
-
- switch(t2p->pdf_compression){
- case T2P_COMPRESS_NONE:
- TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
- break;
+ (void)0;
+ }
+
+ if (t2p->pdf_sample == T2P_SAMPLE_NOTHING)
+ {
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory for "
+ "t2p_readwrite_pdf_image_tile, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+
+ read = TIFFReadEncodedTile(input, tile, (tdata_t)&buffer[bufferoffset],
+ t2p->tiff_datasize);
+ if (read == -1)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error on decoding tile %" PRIu32 " of %s", tile,
+ TIFFFileName(input));
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ }
+ else
+ {
+
+ if (t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG)
+ {
+ septilesize = TIFFTileSize(input);
+ septilecount = TIFFNumberOfTiles(input);
+ /* tilesize=septilesize*t2p->tiff_samplesperpixel; */
+ tilecount = septilecount / t2p->tiff_samplesperpixel;
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory "
+ "for t2p_readwrite_pdf_image_tile, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ samplebuffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (samplebuffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory "
+ "for t2p_readwrite_pdf_image_tile, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(samplebuffer, 0, t2p->tiff_datasize);
+ samplebufferoffset = 0;
+ for (i = 0; i < t2p->tiff_samplesperpixel; i++)
+ {
+ read = TIFFReadEncodedTile(
+ input, tile + i * tilecount,
+ (tdata_t) & (samplebuffer[samplebufferoffset]),
+ septilesize);
+ if (read == -1)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error on decoding tile %" PRIu32 " of %s",
+ tile + i * tilecount, TIFFFileName(input));
+ _TIFFfree(samplebuffer);
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ samplebufferoffset += read;
+ }
+ t2p_sample_planar_separate_to_contig(
+ t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset);
+ bufferoffset += samplebufferoffset;
+ _TIFFfree(samplebuffer);
+ }
+
+ if (buffer == NULL)
+ {
+ buffer = (unsigned char *)_TIFFmalloc(t2p->tiff_datasize);
+ if (buffer == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes of memory "
+ "for t2p_readwrite_pdf_image_tile, %s",
+ t2p->tiff_datasize, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ memset(buffer, 0, t2p->tiff_datasize);
+ read =
+ TIFFReadEncodedTile(input, tile, (tdata_t)&buffer[bufferoffset],
+ t2p->tiff_datasize);
+ if (read == -1)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error on decoding tile %" PRIu32 " of %s", tile,
+ TIFFFileName(input));
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ }
+
+ if (t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB)
+ {
+ t2p->tiff_datasize = t2p_sample_rgba_to_rgb(
+ (tdata_t)buffer,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
+ }
+
+ if (t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB)
+ {
+ t2p->tiff_datasize = t2p_sample_rgbaa_to_rgb(
+ (tdata_t)buffer,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
+ }
+
+ if (t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "No support for YCbCr to RGB in tile for %s",
+ TIFFFileName(input));
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+
+ if (t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED)
+ {
+ t2p->tiff_datasize = t2p_sample_lab_signed_to_unsigned(
+ (tdata_t)buffer,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
+ }
+ }
+
+ if (t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0)
+ {
+ if ((uint64_t)t2p->tiff_datasize <
+ (uint64_t)TIFFTileRowSize(input) *
+ (uint64_t)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength)
+ {
+ /* we don't know how to handle PLANARCONFIG_CONTIG,
+ * PHOTOMETRIC_YCBCR with 3 samples per pixel */
+ TIFFWarning(TIFF2PDF_MODULE,
+ "Don't know how to collapse tile to the left");
+ }
+ else
+ {
+ t2p_tile_collapse_left(
+ buffer, TIFFTileRowSize(input),
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
+ }
+ }
+
+ t2p_disable(output);
+ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
+ TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
+ TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
+ if (t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0)
+ {
+ TIFFSetField(output, TIFFTAG_IMAGEWIDTH,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
+ }
+ else
+ {
+ TIFFSetField(output, TIFFTAG_IMAGEWIDTH,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
+ }
+ if (t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0)
+ {
+ TIFFSetField(output, TIFFTAG_IMAGELENGTH,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
+ TIFFSetField(output, TIFFTAG_ROWSPERSTRIP,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
+ }
+ else
+ {
+ TIFFSetField(output, TIFFTAG_IMAGELENGTH,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
+ TIFFSetField(output, TIFFTAG_ROWSPERSTRIP,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
+ }
+ TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+ TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
+
+ switch (t2p->pdf_compression)
+ {
+ case T2P_COMPRESS_NONE:
+ TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
+ break;
#ifdef CCITT_SUPPORT
- case T2P_COMPRESS_G4:
- TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
- break;
+ case T2P_COMPRESS_G4:
+ TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
+ break;
#endif
#ifdef JPEG_SUPPORT
- case T2P_COMPRESS_JPEG:
- if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
- uint16_t hor = 0, ver = 0;
- if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) {
- if (hor != 0 && ver != 0) {
- TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
- }
- }
- if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
- TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
- }
- }
- TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
- TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */
- if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
- TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
- if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
- TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
- } else {
- TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
- }
- }
- if(t2p->pdf_colorspace & T2P_CS_GRAY){
- (void)0;
- }
- if(t2p->pdf_colorspace & T2P_CS_CMYK){
- (void)0;
- }
- if(t2p->pdf_defaultcompressionquality != 0){
- TIFFSetField(output,
- TIFFTAG_JPEGQUALITY,
- t2p->pdf_defaultcompressionquality);
- }
- break;
+ case T2P_COMPRESS_JPEG:
+ if (t2p->tiff_photometric == PHOTOMETRIC_YCBCR)
+ {
+ uint16_t hor = 0, ver = 0;
+ if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=
+ 0)
+ {
+ if (hor != 0 && ver != 0)
+ {
+ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor,
+ ver);
+ }
+ }
+ if (TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE,
+ &xfloatp) != 0)
+ {
+ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
+ }
+ }
+ TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
+ TIFFSetField(output, TIFFTAG_JPEGTABLESMODE,
+ 0); /* JPEGTABLESMODE_NONE */
+ if (t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB))
+ {
+ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
+ if (t2p->tiff_photometric != PHOTOMETRIC_YCBCR)
+ {
+ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE,
+ JPEGCOLORMODE_RGB);
+ }
+ else
+ {
+ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE,
+ JPEGCOLORMODE_RAW);
+ }
+ }
+ if (t2p->pdf_colorspace & T2P_CS_GRAY)
+ {
+ (void)0;
+ }
+ if (t2p->pdf_colorspace & T2P_CS_CMYK)
+ {
+ (void)0;
+ }
+ if (t2p->pdf_defaultcompressionquality != 0)
+ {
+ TIFFSetField(output, TIFFTAG_JPEGQUALITY,
+ t2p->pdf_defaultcompressionquality);
+ }
+ break;
#endif
#ifdef ZIP_SUPPORT
- case T2P_COMPRESS_ZIP:
- TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_ADOBE_DEFLATE);
- if(t2p->pdf_defaultcompressionquality%100 != 0){
- TIFFSetField(output,
- TIFFTAG_PREDICTOR,
- t2p->pdf_defaultcompressionquality % 100);
- }
- if(t2p->pdf_defaultcompressionquality/100 != 0){
- TIFFSetField(output,
- TIFFTAG_ZIPQUALITY,
- (t2p->pdf_defaultcompressionquality / 100));
- }
- break;
+ case T2P_COMPRESS_ZIP:
+ TIFFSetField(output, TIFFTAG_COMPRESSION,
+ COMPRESSION_ADOBE_DEFLATE);
+ if (t2p->pdf_defaultcompressionquality % 100 != 0)
+ {
+ TIFFSetField(output, TIFFTAG_PREDICTOR,
+ t2p->pdf_defaultcompressionquality % 100);
+ }
+ if (t2p->pdf_defaultcompressionquality / 100 != 0)
+ {
+ TIFFSetField(output, TIFFTAG_ZIPQUALITY,
+ (t2p->pdf_defaultcompressionquality / 100));
+ }
+ break;
#endif
- default:
- break;
- }
-
- if (TIFFStripSize(output) > t2p->tiff_datasize) {
- TIFFError(TIFF2PDF_MODULE,
- "Size mismatch input %" PRId64 ", output %" PRId64,
- (int64_t) t2p->tiff_datasize, (int64_t) TIFFStripSize(output));
- _TIFFfree(buffer);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- t2p_enable(output);
- t2p->outputwritten = 0;
- bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer,
- TIFFStripSize(output));
- if (buffer != NULL) {
- _TIFFfree(buffer);
- buffer = NULL;
- }
- if (bufferoffset == -1) {
- TIFFError(TIFF2PDF_MODULE,
- "Error writing encoded tile to output PDF %s",
- TIFFFileName(output));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
-
- written = t2p->outputwritten;
-
- return(written);
+ default:
+ break;
+ }
+
+ if (TIFFStripSize(output) > t2p->tiff_datasize)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Size mismatch input %" PRId64 ", output %" PRId64,
+ (int64_t)t2p->tiff_datasize, (int64_t)TIFFStripSize(output));
+ _TIFFfree(buffer);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ t2p_enable(output);
+ t2p->outputwritten = 0;
+ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer,
+ TIFFStripSize(output));
+ if (buffer != NULL)
+ {
+ _TIFFfree(buffer);
+ buffer = NULL;
+ }
+ if (bufferoffset == -1)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error writing encoded tile to output PDF %s",
+ TIFFFileName(output));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+
+ written = t2p->outputwritten;
+
+ return (written);
}
#ifdef OJPEG_SUPPORT
-int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){
- uint16_t proc=0;
- void* q;
- uint32_t q_length=0;
- void* dc;
- uint32_t dc_length=0;
- void* ac;
- uint32_t ac_length=0;
- uint16_t* lp;
- uint16_t* pt;
- uint16_t h_samp=1;
- uint16_t v_samp=1;
- unsigned char* ojpegdata;
- uint16_t table_count;
- uint32_t offset_table;
- uint32_t offset_ms_l;
- uint32_t code_count;
- uint32_t i=0;
- uint32_t dest=0;
- uint16_t ri=0;
- uint32_t rows=0;
-
- if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){
- TIFFError(TIFF2PDF_MODULE,
- "Missing JPEGProc field in OJPEG image %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){
- TIFFError(TIFF2PDF_MODULE,
- "Bad JPEGProc field in OJPEG image %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){
- TIFFError(TIFF2PDF_MODULE,
- "Missing JPEGQTables field in OJPEG image %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- if(q_length < (64U * t2p->tiff_samplesperpixel)){
- TIFFError(TIFF2PDF_MODULE,
- "Bad JPEGQTables field in OJPEG image %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){
- TIFFError(TIFF2PDF_MODULE,
- "Missing JPEGDCTables field in OJPEG image %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- if(proc==JPEGPROC_BASELINE){
- if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){
- TIFFError(TIFF2PDF_MODULE,
- "Missing JPEGACTables field in OJPEG image %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- } else {
- if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){
- TIFFError(TIFF2PDF_MODULE,
- "Missing JPEGLosslessPredictors field in OJPEG image %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){
- TIFFError(TIFF2PDF_MODULE,
- "Missing JPEGPointTransform field in OJPEG image %s",
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- }
- if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){
- h_samp=1;
- v_samp=1;
- }
- if(t2p->pdf_ojpegdata != NULL){
- _TIFFfree(t2p->pdf_ojpegdata);
- t2p->pdf_ojpegdata=NULL;
- }
- t2p->pdf_ojpegdata = _TIFFmalloc(2048);
- if(t2p->pdf_ojpegdata == NULL){
- TIFFError(TIFF2PDF_MODULE,
- "Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s",
- 2048u,
- TIFFFileName(input));
- t2p->t2p_error = T2P_ERR_ERROR;
- return(0);
- }
- _TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048);
- t2p->pdf_ojpegdatalength = 0;
- table_count=t2p->tiff_samplesperpixel;
- if(proc==JPEGPROC_BASELINE){
- if(table_count>2) table_count=2;
- }
- ojpegdata=(unsigned char*)t2p->pdf_ojpegdata;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
- if(proc==JPEGPROC_BASELINE){
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0;
- } else {
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3;
- }
- ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
- ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel);
- ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff);
- if(TIFFIsTiled(input)){
- ojpegdata[t2p->pdf_ojpegdatalength++]=
- (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=
- (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=
- (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=
- (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff;
- } else {
- ojpegdata[t2p->pdf_ojpegdatalength++]=
- (t2p->tiff_length >> 8) & 0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=
- (t2p->tiff_length ) & 0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=
- (t2p->tiff_width >> 8) & 0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=
- (t2p->tiff_width ) & 0xff;
- }
- ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff);
- for(i=0;i<t2p->tiff_samplesperpixel;i++){
- ojpegdata[t2p->pdf_ojpegdatalength++]=i;
- if(i==0){
- ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;;
- ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f;
- } else {
- ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11;
- }
- ojpegdata[t2p->pdf_ojpegdatalength++]=i;
- }
- for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0x43;
- ojpegdata[t2p->pdf_ojpegdatalength++]=dest;
- _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]),
- &(((unsigned char*)q)[64*dest]), 64);
- t2p->pdf_ojpegdatalength+=64;
- }
- offset_table=0;
- for(dest=0;dest<table_count;dest++){
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4;
- offset_ms_l=t2p->pdf_ojpegdatalength;
- t2p->pdf_ojpegdatalength+=2;
- ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f;
- _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
- &(((unsigned char*)dc)[offset_table]), 16);
- code_count=0;
- offset_table+=16;
- for(i=0;i<16;i++){
- code_count+=ojpegdata[t2p->pdf_ojpegdatalength++];
- }
- ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff;
- ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff;
- _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
- &(((unsigned char*)dc)[offset_table]), code_count);
- offset_table+=code_count;
- t2p->pdf_ojpegdatalength+=code_count;
- }
- if(proc==JPEGPROC_BASELINE){
- offset_table=0;
- for(dest=0;dest<table_count;dest++){
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4;
- offset_ms_l=t2p->pdf_ojpegdatalength;
- t2p->pdf_ojpegdatalength+=2;
- ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10;
- ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f;
- _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
- &(((unsigned char*)ac)[offset_table]), 16);
- code_count=0;
- offset_table+=16;
- for(i=0;i<16;i++){
- code_count+=ojpegdata[t2p->pdf_ojpegdatalength++];
- }
- ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff;
- ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff;
- _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
- &(((unsigned char*)ac)[offset_table]), code_count);
- offset_table+=code_count;
- t2p->pdf_ojpegdatalength+=code_count;
- }
- }
- if(TIFFNumberOfStrips(input)>1){
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0x04;
- h_samp*=8;
- v_samp*=8;
- ri=(t2p->tiff_width+h_samp-1) / h_samp;
- TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows);
- ri*=(rows+v_samp-1)/v_samp;
- ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff;
- }
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0xda;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
- ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel);
- ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff;
- for(i=0;i<t2p->tiff_samplesperpixel;i++){
- ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff;
- if(proc==JPEGPROC_BASELINE){
- ojpegdata[t2p->pdf_ojpegdatalength] |=
- ( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0;
- ojpegdata[t2p->pdf_ojpegdatalength++] |=
- ( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f;
- } else {
- ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0;
- }
- }
- if(proc==JPEGPROC_BASELINE){
- t2p->pdf_ojpegdatalength++;
- ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f;
- t2p->pdf_ojpegdatalength++;
- } else {
- ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff);
- t2p->pdf_ojpegdatalength++;
- ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f);
- }
-
- return(1);
+int t2p_process_ojpeg_tables(T2P *t2p, TIFF *input)
+{
+ uint16_t proc = 0;
+ void *q;
+ uint32_t q_length = 0;
+ void *dc;
+ uint32_t dc_length = 0;
+ void *ac;
+ uint32_t ac_length = 0;
+ uint16_t *lp;
+ uint16_t *pt;
+ uint16_t h_samp = 1;
+ uint16_t v_samp = 1;
+ unsigned char *ojpegdata;
+ uint16_t table_count;
+ uint32_t offset_table;
+ uint32_t offset_ms_l;
+ uint32_t code_count;
+ uint32_t i = 0;
+ uint32_t dest = 0;
+ uint16_t ri = 0;
+ uint32_t rows = 0;
+
+ if (!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc))
+ {
+ TIFFError(TIFF2PDF_MODULE, "Missing JPEGProc field in OJPEG image %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ if (proc != JPEGPROC_BASELINE && proc != JPEGPROC_LOSSLESS)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Bad JPEGProc field in OJPEG image %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ if (!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Missing JPEGQTables field in OJPEG image %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ if (q_length < (64U * t2p->tiff_samplesperpixel))
+ {
+ TIFFError(TIFF2PDF_MODULE, "Bad JPEGQTables field in OJPEG image %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ if (!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Missing JPEGDCTables field in OJPEG image %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ if (proc == JPEGPROC_BASELINE)
+ {
+ if (!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Missing JPEGACTables field in OJPEG image %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ }
+ else
+ {
+ if (!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Missing JPEGLosslessPredictors field in OJPEG image %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ if (!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Missing JPEGPointTransform field in OJPEG image %s",
+ TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ }
+ if (!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp))
+ {
+ h_samp = 1;
+ v_samp = 1;
+ }
+ if (t2p->pdf_ojpegdata != NULL)
+ {
+ _TIFFfree(t2p->pdf_ojpegdata);
+ t2p->pdf_ojpegdata = NULL;
+ }
+ t2p->pdf_ojpegdata = _TIFFmalloc(2048);
+ if (t2p->pdf_ojpegdata == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %u bytes of memory for "
+ "t2p_process_ojpeg_tables, %s",
+ 2048u, TIFFFileName(input));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ _TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048);
+ t2p->pdf_ojpegdatalength = 0;
+ table_count = t2p->tiff_samplesperpixel;
+ if (proc == JPEGPROC_BASELINE)
+ {
+ if (table_count > 2)
+ table_count = 2;
+ }
+ ojpegdata = (unsigned char *)t2p->pdf_ojpegdata;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xd8;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xff;
+ if (proc == JPEGPROC_BASELINE)
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xc0;
+ }
+ else
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xc3;
+ }
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0x00;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (8 + 3 * t2p->tiff_samplesperpixel);
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (t2p->tiff_bitspersample & 0xff);
+ if (TIFFIsTiled(input))
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] =
+ (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] =
+ (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength) & 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] =
+ (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] =
+ (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth) & 0xff;
+ }
+ else
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (t2p->tiff_length >> 8) & 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (t2p->tiff_length) & 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (t2p->tiff_width >> 8) & 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (t2p->tiff_width) & 0xff;
+ }
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (t2p->tiff_samplesperpixel & 0xff);
+ for (i = 0; i < t2p->tiff_samplesperpixel; i++)
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = i;
+ if (i == 0)
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp << 4 & 0xf0;
+ ;
+ ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f;
+ }
+ else
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0x11;
+ }
+ ojpegdata[t2p->pdf_ojpegdatalength++] = i;
+ }
+ for (dest = 0; dest < t2p->tiff_samplesperpixel; dest++)
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xdb;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0x00;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0x43;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = dest;
+ _TIFFmemcpy(&(ojpegdata[t2p->pdf_ojpegdatalength++]),
+ &(((unsigned char *)q)[64 * dest]), 64);
+ t2p->pdf_ojpegdatalength += 64;
+ }
+ offset_table = 0;
+ for (dest = 0; dest < table_count; dest++)
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xc4;
+ offset_ms_l = t2p->pdf_ojpegdatalength;
+ t2p->pdf_ojpegdatalength += 2;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = dest & 0x0f;
+ _TIFFmemcpy(&(ojpegdata[t2p->pdf_ojpegdatalength]),
+ &(((unsigned char *)dc)[offset_table]), 16);
+ code_count = 0;
+ offset_table += 16;
+ for (i = 0; i < 16; i++)
+ {
+ code_count += ojpegdata[t2p->pdf_ojpegdatalength++];
+ }
+ ojpegdata[offset_ms_l] = ((19 + code_count) >> 8) & 0xff;
+ ojpegdata[offset_ms_l + 1] = (19 + code_count) & 0xff;
+ _TIFFmemcpy(&(ojpegdata[t2p->pdf_ojpegdatalength]),
+ &(((unsigned char *)dc)[offset_table]), code_count);
+ offset_table += code_count;
+ t2p->pdf_ojpegdatalength += code_count;
+ }
+ if (proc == JPEGPROC_BASELINE)
+ {
+ offset_table = 0;
+ for (dest = 0; dest < table_count; dest++)
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xc4;
+ offset_ms_l = t2p->pdf_ojpegdatalength;
+ t2p->pdf_ojpegdatalength += 2;
+ ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10;
+ ojpegdata[t2p->pdf_ojpegdatalength++] |= dest & 0x0f;
+ _TIFFmemcpy(&(ojpegdata[t2p->pdf_ojpegdatalength]),
+ &(((unsigned char *)ac)[offset_table]), 16);
+ code_count = 0;
+ offset_table += 16;
+ for (i = 0; i < 16; i++)
+ {
+ code_count += ojpegdata[t2p->pdf_ojpegdatalength++];
+ }
+ ojpegdata[offset_ms_l] = ((19 + code_count) >> 8) & 0xff;
+ ojpegdata[offset_ms_l + 1] = (19 + code_count) & 0xff;
+ _TIFFmemcpy(&(ojpegdata[t2p->pdf_ojpegdatalength]),
+ &(((unsigned char *)ac)[offset_table]), code_count);
+ offset_table += code_count;
+ t2p->pdf_ojpegdatalength += code_count;
+ }
+ }
+ if (TIFFNumberOfStrips(input) > 1)
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xdd;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0x00;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0x04;
+ h_samp *= 8;
+ v_samp *= 8;
+ ri = (t2p->tiff_width + h_samp - 1) / h_samp;
+ TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows);
+ ri *= (rows + v_samp - 1) / v_samp;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (ri >> 8) & 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = ri & 0xff;
+ }
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xff;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0xda;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0x00;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (6 + 2 * t2p->tiff_samplesperpixel);
+ ojpegdata[t2p->pdf_ojpegdatalength++] = t2p->tiff_samplesperpixel & 0xff;
+ for (i = 0; i < t2p->tiff_samplesperpixel; i++)
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = i & 0xff;
+ if (proc == JPEGPROC_BASELINE)
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength] |=
+ (((i > (table_count - 1U)) ? (table_count - 1U) : i) << 4U) &
+ 0xf0;
+ ojpegdata[t2p->pdf_ojpegdatalength++] |=
+ ((i > (table_count - 1U)) ? (table_count - 1U) : i) & 0x0f;
+ }
+ else
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0;
+ }
+ }
+ if (proc == JPEGPROC_BASELINE)
+ {
+ t2p->pdf_ojpegdatalength++;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = 0x3f;
+ t2p->pdf_ojpegdatalength++;
+ }
+ else
+ {
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (lp[0] & 0xff);
+ t2p->pdf_ojpegdatalength++;
+ ojpegdata[t2p->pdf_ojpegdatalength++] = (pt[0] & 0x0f);
+ }
+
+ return (1);
}
#endif
#ifdef JPEG_SUPPORT
-int t2p_process_jpeg_strip(
- unsigned char* strip,
- tsize_t* striplength,
- unsigned char* buffer,
- tsize_t buffersize,
- tsize_t* bufferoffset,
- tstrip_t no,
- uint32_t height){
-
- tsize_t i=0;
-
- while (i < *striplength) {
- tsize_t datalen;
- uint16_t ri;
- uint16_t v_samp;
- uint16_t h_samp;
- int j;
- int ncomp;
-
- /* marker header: one or more FFs */
- if (strip[i] != 0xff)
- return(0);
- i++;
- while (i < *striplength && strip[i] == 0xff)
- i++;
- if (i >= *striplength)
- return(0);
- /* SOI is the only pre-SOS marker without a length word */
- if (strip[i] == 0xd8)
- datalen = 0;
- else {
- if ((*striplength - i) <= 2)
- return(0);
- datalen = (strip[i+1] << 8) | strip[i+2];
- if (datalen < 2 || datalen >= (*striplength - i))
- return(0);
- }
- switch( strip[i] ){
- case 0xd8: /* SOI - start of image */
- if( *bufferoffset + 2 > buffersize )
- return(0);
- _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2);
- *bufferoffset+=2;
- break;
- case 0xc0: /* SOF0 */
- case 0xc1: /* SOF1 */
- case 0xc3: /* SOF3 */
- case 0xc9: /* SOF9 */
- case 0xca: /* SOF10 */
- if(no==0){
- if( *bufferoffset + datalen + 2 + 6 > buffersize )
- return(0);
- _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
- if( *bufferoffset + 9 >= buffersize )
- return(0);
- ncomp = buffer[*bufferoffset+9];
- if (ncomp < 1 || ncomp > 4)
- return(0);
- v_samp=1;
- h_samp=1;
- if( *bufferoffset + 11 + 3*(ncomp-1) >= buffersize )
- return(0);
- for(j=0;j<ncomp;j++){
- uint16_t samp = buffer[*bufferoffset + 11 + (3 * j)];
- if( (samp>>4) > h_samp)
- h_samp = (samp>>4);
- if( (samp & 0x0f) > v_samp)
- v_samp = (samp & 0x0f);
- }
- v_samp*=8;
- h_samp*=8;
- ri=(((((uint16_t)(buffer[*bufferoffset + 5]) << 8) |
- (uint16_t)(buffer[*bufferoffset + 6]) ) + v_samp - 1) /
- v_samp);
- ri*=(((((uint16_t)(buffer[*bufferoffset + 7]) << 8) |
- (uint16_t)(buffer[*bufferoffset + 8]) ) + h_samp - 1) /
- h_samp);
- buffer[*bufferoffset+5]=
- (unsigned char) ((height>>8) & 0xff);
- buffer[*bufferoffset+6]=
- (unsigned char) (height & 0xff);
- *bufferoffset+=datalen+2;
- /* insert a DRI marker */
- buffer[(*bufferoffset)++]=0xff;
- buffer[(*bufferoffset)++]=0xdd;
- buffer[(*bufferoffset)++]=0x00;
- buffer[(*bufferoffset)++]=0x04;
- buffer[(*bufferoffset)++]=(ri >> 8) & 0xff;
- buffer[(*bufferoffset)++]= ri & 0xff;
- }
- break;
- case 0xc4: /* DHT */
- case 0xdb: /* DQT */
- if( *bufferoffset + datalen + 2 > buffersize )
- return(0);
- _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
- *bufferoffset+=datalen+2;
- break;
- case 0xda: /* SOS */
- if(no==0){
- if( *bufferoffset + datalen + 2 > buffersize )
- return(0);
- _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
- *bufferoffset+=datalen+2;
- } else {
- if( *bufferoffset + 2 > buffersize )
- return(0);
- buffer[(*bufferoffset)++]=0xff;
- buffer[(*bufferoffset)++]=
- (unsigned char)(0xd0 | ((no-1)%8));
- }
- i += datalen + 1;
- /* copy remainder of strip */
- if( *bufferoffset + *striplength - i > buffersize )
- return(0);
- _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i);
- *bufferoffset+= *striplength - i;
- return(1);
- default:
- /* ignore any other marker */
- break;
- }
- i += datalen + 1;
- }
-
- /* failed to find SOS marker */
- return(0);
+int t2p_process_jpeg_strip(unsigned char *strip, tsize_t *striplength,
+ unsigned char *buffer, tsize_t buffersize,
+ tsize_t *bufferoffset, tstrip_t no, uint32_t height)
+{
+
+ tsize_t i = 0;
+
+ while (i < *striplength)
+ {
+ tsize_t datalen;
+ uint16_t ri;
+ uint16_t v_samp;
+ uint16_t h_samp;
+ int j;
+ int ncomp;
+
+ /* marker header: one or more FFs */
+ if (strip[i] != 0xff)
+ return (0);
+ i++;
+ while (i < *striplength && strip[i] == 0xff)
+ i++;
+ if (i >= *striplength)
+ return (0);
+ /* SOI is the only pre-SOS marker without a length word */
+ if (strip[i] == 0xd8)
+ datalen = 0;
+ else
+ {
+ if ((*striplength - i) <= 2)
+ return (0);
+ datalen = (strip[i + 1] << 8) | strip[i + 2];
+ if (datalen < 2 || datalen >= (*striplength - i))
+ return (0);
+ }
+ switch (strip[i])
+ {
+ case 0xd8: /* SOI - start of image */
+ if (*bufferoffset + 2 > buffersize)
+ return (0);
+ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i - 1]), 2);
+ *bufferoffset += 2;
+ break;
+ case 0xc0: /* SOF0 */
+ case 0xc1: /* SOF1 */
+ case 0xc3: /* SOF3 */
+ case 0xc9: /* SOF9 */
+ case 0xca: /* SOF10 */
+ if (no == 0)
+ {
+ if (*bufferoffset + datalen + 2 + 6 > buffersize)
+ return (0);
+ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i - 1]),
+ datalen + 2);
+ if (*bufferoffset + 9 >= buffersize)
+ return (0);
+ ncomp = buffer[*bufferoffset + 9];
+ if (ncomp < 1 || ncomp > 4)
+ return (0);
+ v_samp = 1;
+ h_samp = 1;
+ if (*bufferoffset + 11 + 3 * (ncomp - 1) >= buffersize)
+ return (0);
+ for (j = 0; j < ncomp; j++)
+ {
+ uint16_t samp = buffer[*bufferoffset + 11 + (3 * j)];
+ if ((samp >> 4) > h_samp)
+ h_samp = (samp >> 4);
+ if ((samp & 0x0f) > v_samp)
+ v_samp = (samp & 0x0f);
+ }
+ v_samp *= 8;
+ h_samp *= 8;
+ ri = (((((uint16_t)(buffer[*bufferoffset + 5]) << 8) |
+ (uint16_t)(buffer[*bufferoffset + 6])) +
+ v_samp - 1) /
+ v_samp);
+ ri *= (((((uint16_t)(buffer[*bufferoffset + 7]) << 8) |
+ (uint16_t)(buffer[*bufferoffset + 8])) +
+ h_samp - 1) /
+ h_samp);
+ buffer[*bufferoffset + 5] =
+ (unsigned char)((height >> 8) & 0xff);
+ buffer[*bufferoffset + 6] = (unsigned char)(height & 0xff);
+ *bufferoffset += datalen + 2;
+ /* insert a DRI marker */
+ buffer[(*bufferoffset)++] = 0xff;
+ buffer[(*bufferoffset)++] = 0xdd;
+ buffer[(*bufferoffset)++] = 0x00;
+ buffer[(*bufferoffset)++] = 0x04;
+ buffer[(*bufferoffset)++] = (ri >> 8) & 0xff;
+ buffer[(*bufferoffset)++] = ri & 0xff;
+ }
+ break;
+ case 0xc4: /* DHT */
+ case 0xdb: /* DQT */
+ if (*bufferoffset + datalen + 2 > buffersize)
+ return (0);
+ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i - 1]),
+ datalen + 2);
+ *bufferoffset += datalen + 2;
+ break;
+ case 0xda: /* SOS */
+ if (no == 0)
+ {
+ if (*bufferoffset + datalen + 2 > buffersize)
+ return (0);
+ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i - 1]),
+ datalen + 2);
+ *bufferoffset += datalen + 2;
+ }
+ else
+ {
+ if (*bufferoffset + 2 > buffersize)
+ return (0);
+ buffer[(*bufferoffset)++] = 0xff;
+ buffer[(*bufferoffset)++] =
+ (unsigned char)(0xd0 | ((no - 1) % 8));
+ }
+ i += datalen + 1;
+ /* copy remainder of strip */
+ if (*bufferoffset + *striplength - i > buffersize)
+ return (0);
+ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]),
+ *striplength - i);
+ *bufferoffset += *striplength - i;
+ return (1);
+ default:
+ /* ignore any other marker */
+ break;
+ }
+ i += datalen + 1;
+ }
+
+ /* failed to find SOS marker */
+ return (0);
}
#endif
/*
- This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x
- tilelength buffer of samples.
+ This functions converts a tilewidth x tilelength buffer of samples into
+ an edgetilewidth x tilelength buffer of samples.
*/
-void t2p_tile_collapse_left(
- tdata_t buffer,
- tsize_t scanwidth,
- uint32_t tilewidth,
- uint32_t edgetilewidth,
- uint32_t tilelength){
-
- uint32_t i;
- tsize_t edgescanwidth=0;
-
- edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth;
- for(i=0;i<tilelength;i++){
- /* We use memmove() since there can be overlaps in src and dst buffers for the first items */
- memmove(
- &(((char*)buffer)[edgescanwidth*i]),
- &(((char*)buffer)[scanwidth*i]),
- edgescanwidth);
- }
-
- return;
-}
+void t2p_tile_collapse_left(tdata_t buffer, tsize_t scanwidth,
+ uint32_t tilewidth, uint32_t edgetilewidth,
+ uint32_t tilelength)
+{
+ uint32_t i;
+ tsize_t edgescanwidth = 0;
+
+ edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1)) / tilewidth;
+ for (i = 0; i < tilelength; i++)
+ {
+ /* We use memmove() since there can be overlaps in src and dst buffers
+ * for the first items */
+ memmove(&(((char *)buffer)[edgescanwidth * i]),
+ &(((char *)buffer)[scanwidth * i]), edgescanwidth);
+ }
+
+ return;
+}
/*
* This function calls TIFFWriteDirectory on the output after blanking its
@@ -3765,96 +4112,104 @@ void t2p_tile_collapse_left(
* implementations, then it replaces the original implementations.
*/
-void
-t2p_write_advance_directory(T2P* t2p, TIFF* output)
+void t2p_write_advance_directory(T2P *t2p, TIFF *output)
{
- t2p_disable(output);
- if(!TIFFWriteDirectory(output)){
- TIFFError(TIFF2PDF_MODULE,
- "Error writing virtual directory to output PDF %s",
- TIFFFileName(output));
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- t2p_enable(output);
- return;
+ t2p_disable(output);
+ if (!TIFFWriteDirectory(output))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error writing virtual directory to output PDF %s",
+ TIFFFileName(output));
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ t2p_enable(output);
+ return;
}
-tsize_t t2p_sample_planar_separate_to_contig(
- T2P* t2p,
- unsigned char* buffer,
- unsigned char* samplebuffer,
- tsize_t samplebuffersize){
-
- tsize_t stride=0;
- tsize_t i=0;
- tsize_t j=0;
-
- stride=samplebuffersize/t2p->tiff_samplesperpixel;
- for(i=0;i<stride;i++){
- for(j=0;j<t2p->tiff_samplesperpixel;j++){
- buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride];
- }
- }
-
- return(samplebuffersize);
+tsize_t t2p_sample_planar_separate_to_contig(T2P *t2p, unsigned char *buffer,
+ unsigned char *samplebuffer,
+ tsize_t samplebuffersize)
+{
+
+ tsize_t stride = 0;
+ tsize_t i = 0;
+ tsize_t j = 0;
+
+ stride = samplebuffersize / t2p->tiff_samplesperpixel;
+ for (i = 0; i < stride; i++)
+ {
+ for (j = 0; j < t2p->tiff_samplesperpixel; j++)
+ {
+ buffer[i * t2p->tiff_samplesperpixel + j] =
+ samplebuffer[i + j * stride];
+ }
+ }
+
+ return (samplebuffersize);
}
-tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){
-
- uint32_t sample_count=0;
- uint16_t component_count=0;
- uint32_t palette_offset=0;
- uint32_t sample_offset=0;
- uint32_t i=0;
- uint32_t j=0;
- size_t data_size;
- sample_count=t2p->tiff_width*t2p->tiff_length;
- component_count=t2p->tiff_samplesperpixel;
- data_size=TIFFSafeMultiply(size_t,sample_count,component_count);
- if( (data_size == 0U) || (t2p->tiff_datasize < 0) ||
- (data_size > (size_t) t2p->tiff_datasize) )
+tsize_t t2p_sample_realize_palette(T2P *t2p, unsigned char *buffer)
+{
+
+ uint32_t sample_count = 0;
+ uint16_t component_count = 0;
+ uint32_t palette_offset = 0;
+ uint32_t sample_offset = 0;
+ uint32_t i = 0;
+ uint32_t j = 0;
+ size_t data_size;
+ sample_count = t2p->tiff_width * t2p->tiff_length;
+ component_count = t2p->tiff_samplesperpixel;
+ data_size = TIFFSafeMultiply(size_t, sample_count, component_count);
+ if ((data_size == 0U) || (t2p->tiff_datasize < 0) ||
+ (data_size > (size_t)t2p->tiff_datasize))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Error: sample_count * component_count > t2p->tiff_datasize");
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return 1;
+ }
+
+ for (i = sample_count; i > 0; i--)
+ {
+ palette_offset = buffer[i - 1] * component_count;
+ sample_offset = (i - 1) * component_count;
+ if (palette_offset + component_count > t2p->pdf_palettesize)
{
TIFFError(TIFF2PDF_MODULE,
- "Error: sample_count * component_count > t2p->tiff_datasize");
- t2p->t2p_error = T2P_ERR_ERROR;
+ "Error: palette_offset + component_count > "
+ "t2p->pdf_palettesize");
return 1;
}
-
- for(i=sample_count;i>0;i--){
- palette_offset=buffer[i-1] * component_count;
- sample_offset= (i-1) * component_count;
- if(palette_offset + component_count > t2p->pdf_palettesize){
- TIFFError(TIFF2PDF_MODULE,
- "Error: palette_offset + component_count > t2p->pdf_palettesize");
- return 1;
- }
- for(j=0;j<component_count;j++){
- buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j];
- }
- }
-
- return(0);
+ for (j = 0; j < component_count; j++)
+ {
+ buffer[sample_offset + j] = t2p->pdf_palette[palette_offset + j];
+ }
+ }
+
+ return (0);
}
/*
- This functions converts in place a buffer of ABGR interleaved data
- into RGB interleaved data, discarding A.
+ This functions converts in place a buffer of ABGR interleaved data
+ into RGB interleaved data, discarding A.
*/
tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32_t samplecount)
{
- uint32_t i=0;
- uint32_t sample=0;
-
- for(i=0;i<samplecount;i++){
- sample=((uint32_t*)data)[i];
- ((char*)data)[i*3]= (char) (sample & 0xff);
- ((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff);
- ((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff);
- }
-
- return(i*3);
+ uint32_t i = 0;
+ uint32_t sample = 0;
+
+ for (i = 0; i < samplecount; i++)
+ {
+ sample = ((uint32_t *)data)[i];
+ ((char *)data)[i * 3] = (char)(sample & 0xff);
+ ((char *)data)[i * 3 + 1] = (char)((sample >> 8) & 0xff);
+ ((char *)data)[i * 3 + 2] = (char)((sample >> 16) & 0xff);
+ }
+
+ return (i * 3);
}
/*
@@ -3862,21 +4217,20 @@ tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32_t samplecount)
* into RGB interleaved data, discarding A.
*/
-tsize_t
-t2p_sample_rgbaa_to_rgb(tdata_t data, uint32_t samplecount)
+tsize_t t2p_sample_rgbaa_to_rgb(tdata_t data, uint32_t samplecount)
{
- uint32_t i;
-
- /* For the 3 first samples, there is overlap between source and
- * destination, so use memmove().
- * See http://bugzilla.maptools.org/show_bug.cgi?id=2577
- */
- for(i = 0; i < 3 && i < samplecount; i++)
- memmove((uint8_t*)data + i * 3, (uint8_t*)data + i * 4, 3);
- for(; i < samplecount; i++)
- memcpy((uint8_t*)data + i * 3, (uint8_t*)data + i * 4, 3);
-
- return(i * 3);
+ uint32_t i;
+
+ /* For the 3 first samples, there is overlap between source and
+ * destination, so use memmove().
+ * See http://bugzilla.maptools.org/show_bug.cgi?id=2577
+ */
+ for (i = 0; i < 3 && i < samplecount; i++)
+ memmove((uint8_t *)data + i * 3, (uint8_t *)data + i * 4, 3);
+ for (; i < samplecount; i++)
+ memcpy((uint8_t *)data + i * 3, (uint8_t *)data + i * 4, 3);
+
+ return (i * 3);
}
/*
@@ -3884,464 +4238,512 @@ t2p_sample_rgbaa_to_rgb(tdata_t data, uint32_t samplecount)
* into RGB interleaved data, adding 255-A to each component sample.
*/
-tsize_t
-t2p_sample_rgba_to_rgb(tdata_t data, uint32_t samplecount)
+tsize_t t2p_sample_rgba_to_rgb(tdata_t data, uint32_t samplecount)
{
- uint32_t i = 0;
- uint32_t sample = 0;
- uint8_t alpha = 0;
-
- for (i = 0; i < samplecount; i++) {
- sample=((uint32_t*)data)[i];
- alpha=(uint8_t)((255 - ((sample >> 24) & 0xff)));
- ((uint8_t *)data)[i * 3] = (uint8_t) ((sample >> 16) & 0xff) + alpha;
- ((uint8_t *)data)[i * 3 + 1] = (uint8_t) ((sample >> 8) & 0xff) + alpha;
- ((uint8_t *)data)[i * 3 + 2] = (uint8_t) (sample & 0xff) + alpha;
- }
-
- return (i * 3);
+ uint32_t i = 0;
+ uint32_t sample = 0;
+ uint8_t alpha = 0;
+
+ for (i = 0; i < samplecount; i++)
+ {
+ sample = ((uint32_t *)data)[i];
+ alpha = (uint8_t)((255 - ((sample >> 24) & 0xff)));
+ ((uint8_t *)data)[i * 3] = (uint8_t)((sample >> 16) & 0xff) + alpha;
+ ((uint8_t *)data)[i * 3 + 1] = (uint8_t)((sample >> 8) & 0xff) + alpha;
+ ((uint8_t *)data)[i * 3 + 2] = (uint8_t)(sample & 0xff) + alpha;
+ }
+
+ return (i * 3);
}
/*
- This function converts the a and b samples of Lab data from signed
- to unsigned.
+ This function converts the a and b samples of Lab data from signed
+ to unsigned.
*/
-tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32_t samplecount){
-
- uint32_t i=0;
-
- for(i=0;i<samplecount;i++){
- if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){
- ((unsigned char*)buffer)[(i*3)+1] =
- (unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]);
- } else {
- ((unsigned char*)buffer)[(i*3)+1] |= 0x80;
- }
- if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){
- ((unsigned char*)buffer)[(i*3)+2] =
- (unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]);
- } else {
- ((unsigned char*)buffer)[(i*3)+2] |= 0x80;
- }
- }
-
- return(samplecount*3);
+tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32_t samplecount)
+{
+
+ uint32_t i = 0;
+
+ for (i = 0; i < samplecount; i++)
+ {
+ if ((((unsigned char *)buffer)[(i * 3) + 1] & 0x80) != 0)
+ {
+ ((unsigned char *)buffer)[(i * 3) + 1] =
+ (unsigned char)(0x80 + ((char *)buffer)[(i * 3) + 1]);
+ }
+ else
+ {
+ ((unsigned char *)buffer)[(i * 3) + 1] |= 0x80;
+ }
+ if ((((unsigned char *)buffer)[(i * 3) + 2] & 0x80) != 0)
+ {
+ ((unsigned char *)buffer)[(i * 3) + 2] =
+ (unsigned char)(0x80 + ((char *)buffer)[(i * 3) + 2]);
+ }
+ else
+ {
+ ((unsigned char *)buffer)[(i * 3) + 2] |= 0x80;
+ }
+ }
+
+ return (samplecount * 3);
}
-/*
- This function writes the PDF header to output.
+/*
+ This function writes the PDF header to output.
*/
-tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){
+tsize_t t2p_write_pdf_header(T2P *t2p, TIFF *output)
+{
+
+ tsize_t written = 0;
+ char buffer[16];
+ int buflen = 0;
- tsize_t written=0;
- char buffer[16];
- int buflen=0;
-
- buflen = snprintf(buffer, sizeof(buffer), "%%PDF-%"PRIu16".%"PRIu16" ",
- (uint16_t) (t2p->pdf_majorversion&0xff),
- (uint16_t) (t2p->pdf_minorversion&0xff));
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t)"\n%\342\343\317\323\n", 7);
+ buflen = snprintf(buffer, sizeof(buffer), "%%PDF-%" PRIu16 ".%" PRIu16 " ",
+ (uint16_t)(t2p->pdf_majorversion & 0xff),
+ (uint16_t)(t2p->pdf_minorversion & 0xff));
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "\n%\342\343\317\323\n", 7);
- return(written);
+ return (written);
}
/*
- This function writes the beginning of a PDF object to output.
+ This function writes the beginning of a PDF object to output.
*/
-tsize_t t2p_write_pdf_obj_start(uint32_t number, TIFF* output){
+tsize_t t2p_write_pdf_obj_start(uint32_t number, TIFF *output)
+{
- tsize_t written=0;
- char buffer[32];
- int buflen=0;
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, number);
- check_snprintf_ret((T2P*)NULL, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen );
- written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, number);
+ check_snprintf_ret((T2P *)NULL, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7);
- return(written);
+ return (written);
}
/*
- This function writes the end of a PDF object to output.
+ This function writes the end of a PDF object to output.
*/
-tsize_t t2p_write_pdf_obj_end(TIFF* output){
+tsize_t t2p_write_pdf_obj_end(TIFF *output)
+{
- tsize_t written=0;
+ tsize_t written = 0;
- written += t2pWriteFile(output, (tdata_t) "endobj\n", 7);
+ written += t2pWriteFile(output, (tdata_t) "endobj\n", 7);
- return(written);
+ return (written);
}
/*
- This function writes a PDF name object to output.
+ This function writes a PDF name object to output.
*/
-tsize_t t2p_write_pdf_name(const unsigned char* name, TIFF* output){
-
- tsize_t written=0;
- uint32_t i=0;
- char buffer[64];
- uint16_t nextchar=0;
- size_t namelen=0;
-
- namelen = strlen((char *)name);
- if (namelen>126) {
- namelen=126;
- }
- written += t2pWriteFile(output, (tdata_t) "/", 1);
- for (i=0;i<namelen;i++){
- if ( ((unsigned char)name[i]) < 0x21){
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- nextchar=1;
- }
- if ( ((unsigned char)name[i]) > 0x7E){
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- nextchar=1;
- }
- if (nextchar==0){
- switch (name[i]){
- case 0x23:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- case 0x25:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- case 0x28:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- case 0x29:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- case 0x2F:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- case 0x3C:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- case 0x3E:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- case 0x5B:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- case 0x5D:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- case 0x7B:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- case 0x7D:
- snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
- buffer[sizeof(buffer) - 1] = '\0';
- written += t2pWriteFile(output, (tdata_t) buffer, 3);
- break;
- default:
- written += t2pWriteFile(output, (tdata_t) &name[i], 1);
- }
- }
- nextchar=0;
- }
- written += t2pWriteFile(output, (tdata_t) " ", 1);
-
- return(written);
+tsize_t t2p_write_pdf_name(const unsigned char *name, TIFF *output)
+{
+
+ tsize_t written = 0;
+ uint32_t i = 0;
+ char buffer[64];
+ uint16_t nextchar = 0;
+ size_t namelen = 0;
+
+ namelen = strlen((char *)name);
+ if (namelen > 126)
+ {
+ namelen = 126;
+ }
+ written += t2pWriteFile(output, (tdata_t) "/", 1);
+ for (i = 0; i < namelen; i++)
+ {
+ if (((unsigned char)name[i]) < 0x21)
+ {
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ nextchar = 1;
+ }
+ if (((unsigned char)name[i]) > 0x7E)
+ {
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ nextchar = 1;
+ }
+ if (nextchar == 0)
+ {
+ switch (name[i])
+ {
+ case 0x23:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ case 0x25:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ case 0x28:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ case 0x29:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ case 0x2F:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ case 0x3C:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ case 0x3E:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ case 0x5B:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ case 0x5D:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ case 0x7B:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ case 0x7D:
+ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
+ buffer[sizeof(buffer) - 1] = '\0';
+ written += t2pWriteFile(output, (tdata_t)buffer, 3);
+ break;
+ default:
+ written += t2pWriteFile(output, (tdata_t)&name[i], 1);
+ }
+ }
+ nextchar = 0;
+ }
+ written += t2pWriteFile(output, (tdata_t) " ", 1);
+
+ return (written);
}
/*
* This function writes a PDF string object to output.
*/
-
-tsize_t t2p_write_pdf_string(const char* pdfstr, TIFF* output)
+
+tsize_t t2p_write_pdf_string(const char *pdfstr, TIFF *output)
{
- tsize_t written = 0;
- uint32_t i = 0;
- char buffer[64];
- size_t len = 0;
-
- len = strlen(pdfstr);
- written += t2pWriteFile(output, (tdata_t) "(", 1);
- for (i=0; i<len; i++) {
- if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){
- snprintf(buffer, sizeof(buffer), "\\%.3o", ((unsigned char)pdfstr[i]));
- written += t2pWriteFile(output, (tdata_t)buffer, 4);
- } else {
- switch (pdfstr[i]){
- case 0x08:
- written += t2pWriteFile(output, (tdata_t) "\\b", 2);
- break;
- case 0x09:
- written += t2pWriteFile(output, (tdata_t) "\\t", 2);
- break;
- case 0x0A:
- written += t2pWriteFile(output, (tdata_t) "\\n", 2);
- break;
- case 0x0C:
- written += t2pWriteFile(output, (tdata_t) "\\f", 2);
- break;
- case 0x0D:
- written += t2pWriteFile(output, (tdata_t) "\\r", 2);
- break;
- case 0x28:
- written += t2pWriteFile(output, (tdata_t) "\\(", 2);
- break;
- case 0x29:
- written += t2pWriteFile(output, (tdata_t) "\\)", 2);
- break;
- case 0x5C:
- written += t2pWriteFile(output, (tdata_t) "\\\\", 2);
- break;
- default:
- written += t2pWriteFile(output, (tdata_t) &pdfstr[i], 1);
- }
- }
- }
- written += t2pWriteFile(output, (tdata_t) ") ", 1);
-
- return(written);
-}
+ tsize_t written = 0;
+ uint32_t i = 0;
+ char buffer[64];
+ size_t len = 0;
+
+ len = strlen(pdfstr);
+ written += t2pWriteFile(output, (tdata_t) "(", 1);
+ for (i = 0; i < len; i++)
+ {
+ if ((pdfstr[i] & 0x80) || (pdfstr[i] == 127) || (pdfstr[i] < 32))
+ {
+ snprintf(buffer, sizeof(buffer), "\\%.3o",
+ ((unsigned char)pdfstr[i]));
+ written += t2pWriteFile(output, (tdata_t)buffer, 4);
+ }
+ else
+ {
+ switch (pdfstr[i])
+ {
+ case 0x08:
+ written += t2pWriteFile(output, (tdata_t) "\\b", 2);
+ break;
+ case 0x09:
+ written += t2pWriteFile(output, (tdata_t) "\\t", 2);
+ break;
+ case 0x0A:
+ written += t2pWriteFile(output, (tdata_t) "\\n", 2);
+ break;
+ case 0x0C:
+ written += t2pWriteFile(output, (tdata_t) "\\f", 2);
+ break;
+ case 0x0D:
+ written += t2pWriteFile(output, (tdata_t) "\\r", 2);
+ break;
+ case 0x28:
+ written += t2pWriteFile(output, (tdata_t) "\\(", 2);
+ break;
+ case 0x29:
+ written += t2pWriteFile(output, (tdata_t) "\\)", 2);
+ break;
+ case 0x5C:
+ written += t2pWriteFile(output, (tdata_t) "\\\\", 2);
+ break;
+ default:
+ written += t2pWriteFile(output, (tdata_t)&pdfstr[i], 1);
+ }
+ }
+ }
+ written += t2pWriteFile(output, (tdata_t) ") ", 1);
+ return (written);
+}
/*
- This function writes a buffer of data to output.
+ This function writes a buffer of data to output.
*/
-tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){
+tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF *output)
+{
- tsize_t written=0;
+ tsize_t written = 0;
- written += t2pWriteFile(output, (tdata_t) buffer, len);
+ written += t2pWriteFile(output, (tdata_t)buffer, len);
- return(written);
+ return (written);
}
/*
- This functions writes the beginning of a PDF stream to output.
+ This functions writes the beginning of a PDF stream to output.
*/
-tsize_t t2p_write_pdf_stream_start(TIFF* output){
+tsize_t t2p_write_pdf_stream_start(TIFF *output)
+{
- tsize_t written=0;
+ tsize_t written = 0;
- written += t2pWriteFile(output, (tdata_t) "stream\n", 7);
+ written += t2pWriteFile(output, (tdata_t) "stream\n", 7);
- return(written);
+ return (written);
}
/*
- This function writes the end of a PDF stream to output.
+ This function writes the end of a PDF stream to output.
*/
-tsize_t t2p_write_pdf_stream_end(TIFF* output){
+tsize_t t2p_write_pdf_stream_end(TIFF *output)
+{
- tsize_t written=0;
+ tsize_t written = 0;
- written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11);
+ written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11);
- return(written);
+ return (written);
}
/*
- This function writes a stream dictionary for a PDF stream to output.
+ This function writes a stream dictionary for a PDF stream to output.
*/
-tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32_t number, TIFF* output){
-
- tsize_t written=0;
- char buffer[32];
- int buflen=0;
-
- written += t2pWriteFile(output, (tdata_t) "/Length ", 8);
- if(len!=0){
- written += t2p_write_pdf_stream_length(len, output);
- } else {
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, number);
- check_snprintf_ret((T2P*)NULL, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
- }
-
- return(written);
+tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32_t number, TIFF *output)
+{
+
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
+
+ written += t2pWriteFile(output, (tdata_t) "/Length ", 8);
+ if (len != 0)
+ {
+ written += t2p_write_pdf_stream_length(len, output);
+ }
+ else
+ {
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, number);
+ check_snprintf_ret((T2P *)NULL, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
+ }
+
+ return (written);
}
/*
- This functions writes the beginning of a PDF stream dictionary to output.
+ This functions writes the beginning of a PDF stream dictionary to
+ output.
*/
-tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){
+tsize_t t2p_write_pdf_stream_dict_start(TIFF *output)
+{
- tsize_t written=0;
+ tsize_t written = 0;
- written += t2pWriteFile(output, (tdata_t) "<< \n", 4);
+ written += t2pWriteFile(output, (tdata_t) "<< \n", 4);
- return(written);
+ return (written);
}
/*
- This function writes the end of a PDF stream dictionary to output.
+ This function writes the end of a PDF stream dictionary to output.
*/
-tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){
+tsize_t t2p_write_pdf_stream_dict_end(TIFF *output)
+{
- tsize_t written=0;
+ tsize_t written = 0;
- written += t2pWriteFile(output, (tdata_t) " >>\n", 4);
+ written += t2pWriteFile(output, (tdata_t) " >>\n", 4);
- return(written);
+ return (written);
}
/*
- This function writes a number to output.
+ This function writes a number to output.
*/
-tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){
+tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF *output)
+{
- tsize_t written=0;
- char buffer[32];
- int buflen=0;
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
- buflen=snprintf(buffer, sizeof(buffer), "%"TIFF_SSIZE_FORMAT, len);
- check_snprintf_ret((T2P*)NULL, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "\n", 1);
+ buflen = snprintf(buffer, sizeof(buffer), "%" TIFF_SSIZE_FORMAT, len);
+ check_snprintf_ret((T2P *)NULL, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "\n", 1);
- return(written);
+ return (written);
}
/*
* This function writes the PDF Catalog structure to output.
*/
-tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output)
+tsize_t t2p_write_pdf_catalog(T2P *t2p, TIFF *output)
{
- tsize_t written = 0;
- char buffer[32];
- int buflen = 0;
-
- written += t2pWriteFile(output,
- (tdata_t)"<< \n/Type /Catalog \n/Pages ",
- 27);
- buflen = snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->pdf_pages);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer,
- TIFFmin((size_t)buflen, sizeof(buffer) - 1));
- written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
- if(t2p->pdf_fitwindow){
- written += t2pWriteFile(output,
- (tdata_t) "/ViewerPreferences <</FitWindow true>>\n",
- 39);
- }
- written += t2pWriteFile(output, (tdata_t)">>\n", 3);
-
- return(written);
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
+
+ written +=
+ t2pWriteFile(output, (tdata_t) "<< \n/Type /Catalog \n/Pages ", 27);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->pdf_pages);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer,
+ TIFFmin((size_t)buflen, sizeof(buffer) - 1));
+ written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
+ if (t2p->pdf_fitwindow)
+ {
+ written += t2pWriteFile(
+ output, (tdata_t) "/ViewerPreferences <</FitWindow true>>\n", 39);
+ }
+ written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
+
+ return (written);
}
/*
- This function writes the PDF Info structure to output.
+ This function writes the PDF Info structure to output.
*/
-tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output)
+tsize_t t2p_write_pdf_info(T2P *t2p, TIFF *input, TIFF *output)
{
- tsize_t written = 0;
- const char* info;
- char buffer[512];
-
- if(t2p->pdf_datetime[0] == '\0')
- t2p_pdf_tifftime(t2p, input);
- if (strlen(t2p->pdf_datetime) > 0) {
- written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18);
- written += t2p_write_pdf_string(t2p->pdf_datetime, output);
- written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10);
- written += t2p_write_pdf_string(t2p->pdf_datetime, output);
- }
- written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11);
- snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d", TIFFLIB_VERSION);
- written += t2p_write_pdf_string(buffer, output);
- written += t2pWriteFile(output, (tdata_t) "\n", 1);
- if (!t2p->pdf_creator_set) {
- if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info) {
- strncpy(t2p->pdf_creator, info, sizeof(t2p->pdf_creator) - 1);
- t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0';
- }
- }
- if (t2p->pdf_creator[0] != '\0') {
- written += t2pWriteFile(output, (tdata_t) "/Creator ", 9);
- written += t2p_write_pdf_string(t2p->pdf_creator, output);
- written += t2pWriteFile(output, (tdata_t) "\n", 1);
- }
- if (!t2p->pdf_author_set) {
- if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0
- || TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0)
- && info) {
- strncpy(t2p->pdf_author, info, sizeof(t2p->pdf_author) - 1);
- t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0';
- }
- }
- if (t2p->pdf_author[0] != '\0') {
- written += t2pWriteFile(output, (tdata_t) "/Author ", 8);
- written += t2p_write_pdf_string(t2p->pdf_author, output);
- written += t2pWriteFile(output, (tdata_t) "\n", 1);
- }
- if (!t2p->pdf_title_set) {
- if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0 && info) {
- strncpy(t2p->pdf_title, info, sizeof(t2p->pdf_title) - 1);
- t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0';
- }
- }
- if (t2p->pdf_title[0] != '\0') {
- written += t2pWriteFile(output, (tdata_t) "/Title ", 7);
- written += t2p_write_pdf_string(t2p->pdf_title, output);
- written += t2pWriteFile(output, (tdata_t) "\n", 1);
- }
- if (!t2p->pdf_subject_set) {
- if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info) {
- strncpy(t2p->pdf_subject, info, sizeof(t2p->pdf_subject) - 1);
- t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0';
- }
- }
- if (t2p->pdf_subject[0] != '\0') {
- written += t2pWriteFile(output, (tdata_t) "/Subject ", 9);
- written += t2p_write_pdf_string(t2p->pdf_subject, output);
- written += t2pWriteFile(output, (tdata_t) "\n", 1);
- }
- if (t2p->pdf_keywords[0] != '\0') {
- written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10);
- written += t2p_write_pdf_string(t2p->pdf_keywords, output);
- written += t2pWriteFile(output, (tdata_t) "\n", 1);
- }
- written += t2pWriteFile(output, (tdata_t) ">> \n", 4);
-
- return(written);
+ tsize_t written = 0;
+ const char *info;
+ char buffer[512];
+
+ if (t2p->pdf_datetime[0] == '\0')
+ t2p_pdf_tifftime(t2p, input);
+ if (strlen(t2p->pdf_datetime) > 0)
+ {
+ written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18);
+ written += t2p_write_pdf_string(t2p->pdf_datetime, output);
+ written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10);
+ written += t2p_write_pdf_string(t2p->pdf_datetime, output);
+ }
+ written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11);
+ snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d",
+ TIFFLIB_VERSION);
+ written += t2p_write_pdf_string(buffer, output);
+ written += t2pWriteFile(output, (tdata_t) "\n", 1);
+ if (!t2p->pdf_creator_set)
+ {
+ if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info)
+ {
+ strncpy(t2p->pdf_creator, info, sizeof(t2p->pdf_creator) - 1);
+ t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0';
+ }
+ }
+ if (t2p->pdf_creator[0] != '\0')
+ {
+ written += t2pWriteFile(output, (tdata_t) "/Creator ", 9);
+ written += t2p_write_pdf_string(t2p->pdf_creator, output);
+ written += t2pWriteFile(output, (tdata_t) "\n", 1);
+ }
+ if (!t2p->pdf_author_set)
+ {
+ if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0 ||
+ TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0) &&
+ info)
+ {
+ strncpy(t2p->pdf_author, info, sizeof(t2p->pdf_author) - 1);
+ t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0';
+ }
+ }
+ if (t2p->pdf_author[0] != '\0')
+ {
+ written += t2pWriteFile(output, (tdata_t) "/Author ", 8);
+ written += t2p_write_pdf_string(t2p->pdf_author, output);
+ written += t2pWriteFile(output, (tdata_t) "\n", 1);
+ }
+ if (!t2p->pdf_title_set)
+ {
+ if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0 && info)
+ {
+ strncpy(t2p->pdf_title, info, sizeof(t2p->pdf_title) - 1);
+ t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0';
+ }
+ }
+ if (t2p->pdf_title[0] != '\0')
+ {
+ written += t2pWriteFile(output, (tdata_t) "/Title ", 7);
+ written += t2p_write_pdf_string(t2p->pdf_title, output);
+ written += t2pWriteFile(output, (tdata_t) "\n", 1);
+ }
+ if (!t2p->pdf_subject_set)
+ {
+ if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info)
+ {
+ strncpy(t2p->pdf_subject, info, sizeof(t2p->pdf_subject) - 1);
+ t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0';
+ }
+ }
+ if (t2p->pdf_subject[0] != '\0')
+ {
+ written += t2pWriteFile(output, (tdata_t) "/Subject ", 9);
+ written += t2p_write_pdf_string(t2p->pdf_subject, output);
+ written += t2pWriteFile(output, (tdata_t) "\n", 1);
+ }
+ if (t2p->pdf_keywords[0] != '\0')
+ {
+ written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10);
+ written += t2p_write_pdf_string(t2p->pdf_keywords, output);
+ written += t2pWriteFile(output, (tdata_t) "\n", 1);
+ }
+ written += t2pWriteFile(output, (tdata_t) ">> \n", 4);
+
+ return (written);
}
/*
@@ -4349,28 +4751,29 @@ tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output)
* date string, it is called by t2p_pdf_tifftime.
*/
-void t2p_pdf_currenttime(T2P* t2p)
+void t2p_pdf_currenttime(T2P *t2p)
{
- struct tm* currenttime;
- time_t timenow;
-
- if (time(&timenow) == (time_t) -1) {
- TIFFError(TIFF2PDF_MODULE,
- "Can't get the current time: %s", strerror(errno));
- timenow = (time_t) 0;
- }
-
- currenttime = localtime(&timenow);
- snprintf(t2p->pdf_datetime, sizeof(t2p->pdf_datetime),
- "D:%.4u%.2u%.2u%.2u%.2u%.2u",
- TIFFmin((unsigned) currenttime->tm_year + 1900U,9999U),
- TIFFmin((unsigned) currenttime->tm_mon + 1U,12U), /* 0-11 + 1 */
- TIFFmin((unsigned) currenttime->tm_mday,31U), /* 1-31 */
- TIFFmin((unsigned) currenttime->tm_hour,23U), /* 0-23 */
- TIFFmin((unsigned) currenttime->tm_min,59U), /* 0-59 */
- TIFFmin((unsigned) (currenttime->tm_sec),60U)); /* 0-60 */
-
- return;
+ struct tm *currenttime;
+ time_t timenow;
+
+ if (time(&timenow) == (time_t)-1)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Can't get the current time: %s",
+ strerror(errno));
+ timenow = (time_t)0;
+ }
+
+ currenttime = localtime(&timenow);
+ snprintf(t2p->pdf_datetime, sizeof(t2p->pdf_datetime),
+ "D:%.4u%.2u%.2u%.2u%.2u%.2u",
+ TIFFmin((unsigned)currenttime->tm_year + 1900U, 9999U),
+ TIFFmin((unsigned)currenttime->tm_mon + 1U, 12U), /* 0-11 + 1 */
+ TIFFmin((unsigned)currenttime->tm_mday, 31U), /* 1-31 */
+ TIFFmin((unsigned)currenttime->tm_hour, 23U), /* 0-23 */
+ TIFFmin((unsigned)currenttime->tm_min, 59U), /* 0-59 */
+ TIFFmin((unsigned)(currenttime->tm_sec), 60U)); /* 0-60 */
+
+ return;
}
/*
@@ -4378,1371 +4781,1536 @@ void t2p_pdf_currenttime(T2P* t2p)
* TIFF file if it exists or the current time as a PDF date string.
*/
-void t2p_pdf_tifftime(T2P* t2p, TIFF* input)
+void t2p_pdf_tifftime(T2P *t2p, TIFF *input)
{
- char* datetime;
-
- if (TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0
- && (strlen(datetime) >= 19) ){
- t2p->pdf_datetime[0]='D';
- t2p->pdf_datetime[1]=':';
- t2p->pdf_datetime[2]=datetime[0];
- t2p->pdf_datetime[3]=datetime[1];
- t2p->pdf_datetime[4]=datetime[2];
- t2p->pdf_datetime[5]=datetime[3];
- t2p->pdf_datetime[6]=datetime[5];
- t2p->pdf_datetime[7]=datetime[6];
- t2p->pdf_datetime[8]=datetime[8];
- t2p->pdf_datetime[9]=datetime[9];
- t2p->pdf_datetime[10]=datetime[11];
- t2p->pdf_datetime[11]=datetime[12];
- t2p->pdf_datetime[12]=datetime[14];
- t2p->pdf_datetime[13]=datetime[15];
- t2p->pdf_datetime[14]=datetime[17];
- t2p->pdf_datetime[15]=datetime[18];
- t2p->pdf_datetime[16] = '\0';
- } else {
- t2p_pdf_currenttime(t2p);
- }
-
- return;
+ char *datetime;
+
+ if (TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0 &&
+ (strlen(datetime) >= 19))
+ {
+ t2p->pdf_datetime[0] = 'D';
+ t2p->pdf_datetime[1] = ':';
+ t2p->pdf_datetime[2] = datetime[0];
+ t2p->pdf_datetime[3] = datetime[1];
+ t2p->pdf_datetime[4] = datetime[2];
+ t2p->pdf_datetime[5] = datetime[3];
+ t2p->pdf_datetime[6] = datetime[5];
+ t2p->pdf_datetime[7] = datetime[6];
+ t2p->pdf_datetime[8] = datetime[8];
+ t2p->pdf_datetime[9] = datetime[9];
+ t2p->pdf_datetime[10] = datetime[11];
+ t2p->pdf_datetime[11] = datetime[12];
+ t2p->pdf_datetime[12] = datetime[14];
+ t2p->pdf_datetime[13] = datetime[15];
+ t2p->pdf_datetime[14] = datetime[17];
+ t2p->pdf_datetime[15] = datetime[18];
+ t2p->pdf_datetime[16] = '\0';
+ }
+ else
+ {
+ t2p_pdf_currenttime(t2p);
+ }
+
+ return;
}
/*
* This function writes a PDF Pages Tree structure to output.
*/
-tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output)
+tsize_t t2p_write_pdf_pages(T2P *t2p, TIFF *output)
{
- tsize_t written=0;
- tdir_t i=0;
- char buffer[32];
- int buflen=0;
-
- int page=0;
- written += t2pWriteFile(output,
- (tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26);
- page = t2p->pdf_pages+1;
- for (i=0;i<t2p->tiff_pagecount;i++){
- buflen=snprintf(buffer, sizeof(buffer), "%d", page);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
- if ( ((i+1)%8)==0 ) {
- written += t2pWriteFile(output, (tdata_t) "\n", 1);
- }
- page +=3;
- page += t2p->tiff_pages[i].page_extra;
- if(t2p->tiff_pages[i].page_tilecount>0){
- page += (2 * t2p->tiff_pages[i].page_tilecount);
- } else {
- page +=2;
- }
- }
- written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu16, t2p->tiff_pagecount);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6);
-
- return(written);
+ tsize_t written = 0;
+ tdir_t i = 0;
+ char buffer[32];
+ int buflen = 0;
+
+ int page = 0;
+ written +=
+ t2pWriteFile(output, (tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26);
+ page = t2p->pdf_pages + 1;
+ for (i = 0; i < t2p->tiff_pagecount; i++)
+ {
+ buflen = snprintf(buffer, sizeof(buffer), "%d", page);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+ if (((i + 1) % 8) == 0)
+ {
+ written += t2pWriteFile(output, (tdata_t) "\n", 1);
+ }
+ page += 3;
+ page += t2p->tiff_pages[i].page_extra;
+ if (t2p->tiff_pages[i].page_tilecount > 0)
+ {
+ page += (2 * t2p->tiff_pages[i].page_tilecount);
+ }
+ else
+ {
+ page += 2;
+ }
+ }
+ written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu16, t2p->tiff_pagecount);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6);
+
+ return (written);
}
/*
- This function writes a PDF Page structure to output.
+ This function writes a PDF Page structure to output.
*/
-tsize_t t2p_write_pdf_page(uint32_t object, T2P* t2p, TIFF* output){
-
- unsigned int i=0;
- tsize_t written=0;
- char buffer[256];
- int buflen=0;
-
- written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->pdf_pages);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
- written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11);
- buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x1);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " ", 1);
- buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y1);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " ", 1);
- buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x2);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " ", 1);
- buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y2);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "] \n", 3);
- written += t2pWriteFile(output, (tdata_t) "/Contents ", 10);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, object + 1u);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
- written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15);
- if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){
- written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12);
- for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){
- written += t2pWriteFile(output, (tdata_t) "/Im", 3);
- buflen = snprintf(buffer, sizeof(buffer), "%"PRIu16, (uint16_t)(t2p->pdf_page+1u));
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "_", 1);
- buflen = snprintf(buffer, sizeof(buffer), "%u", i+1u);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " ", 1);
- buflen = snprintf(buffer, sizeof(buffer), "%"PRIu32,
- object+3u+(2u*i)+t2p->tiff_pages[t2p->pdf_page].page_extra);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
- if(i%4==3){
- written += t2pWriteFile(output, (tdata_t) "\n", 1);
- }
- }
- written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
- } else {
- written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12);
- written += t2pWriteFile(output, (tdata_t) "/Im", 3);
- buflen = snprintf(buffer, sizeof(buffer), "%"PRIu16, (uint16_t)(t2p->pdf_page+1u));
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " ", 1);
- buflen = snprintf(buffer, sizeof(buffer), "%"PRIu32,
- object+3u+(2u*i)+t2p->tiff_pages[t2p->pdf_page].page_extra);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
- written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
- }
- if(t2p->tiff_transferfunctioncount != 0) {
- written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13);
- t2pWriteFile(output, (tdata_t) "/GS1 ", 5);
- buflen = snprintf(buffer, sizeof(buffer), "%"PRIu32,
- object + 3u);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
- written += t2pWriteFile(output, (tdata_t) ">> \n", 4);
- }
- written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11);
- if(t2p->pdf_colorspace & T2P_CS_BILEVEL
- || t2p->pdf_colorspace & T2P_CS_GRAY
- ){
- written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8);
- } else {
- written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8);
- if(t2p->pdf_colorspace & T2P_CS_PALETTE){
- written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8);
- }
- }
- written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8);
-
- return(written);
+tsize_t t2p_write_pdf_page(uint32_t object, T2P *t2p, TIFF *output)
+{
+
+ unsigned int i = 0;
+ tsize_t written = 0;
+ char buffer[256];
+ int buflen = 0;
+
+ written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->pdf_pages);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
+ written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11);
+ buflen = snprintf(buffer, sizeof(buffer), "%.4f", t2p->pdf_mediabox.x1);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " ", 1);
+ buflen = snprintf(buffer, sizeof(buffer), "%.4f", t2p->pdf_mediabox.y1);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " ", 1);
+ buflen = snprintf(buffer, sizeof(buffer), "%.4f", t2p->pdf_mediabox.x2);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " ", 1);
+ buflen = snprintf(buffer, sizeof(buffer), "%.4f", t2p->pdf_mediabox.y2);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "] \n", 3);
+ written += t2pWriteFile(output, (tdata_t) "/Contents ", 10);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, object + 1u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
+ written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15);
+ if (t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12);
+ for (i = 0; i < t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/Im", 3);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu16,
+ (uint16_t)(t2p->pdf_page + 1u));
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "_", 1);
+ buflen = snprintf(buffer, sizeof(buffer), "%u", i + 1u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " ", 1);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ object + 3u + (2u * i) +
+ t2p->tiff_pages[t2p->pdf_page].page_extra);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+ if (i % 4 == 3)
+ {
+ written += t2pWriteFile(output, (tdata_t) "\n", 1);
+ }
+ }
+ written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
+ }
+ else
+ {
+ written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12);
+ written += t2pWriteFile(output, (tdata_t) "/Im", 3);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu16,
+ (uint16_t)(t2p->pdf_page + 1u));
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " ", 1);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ object + 3u + (2u * i) +
+ t2p->tiff_pages[t2p->pdf_page].page_extra);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+ written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
+ }
+ if (t2p->tiff_transferfunctioncount != 0)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13);
+ t2pWriteFile(output, (tdata_t) "/GS1 ", 5);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, object + 3u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+ written += t2pWriteFile(output, (tdata_t) ">> \n", 4);
+ }
+ written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11);
+ if (t2p->pdf_colorspace & T2P_CS_BILEVEL ||
+ t2p->pdf_colorspace & T2P_CS_GRAY)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8);
+ }
+ else
+ {
+ written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8);
+ if (t2p->pdf_colorspace & T2P_CS_PALETTE)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8);
+ }
+ }
+ written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8);
+
+ return (written);
}
/*
- This function composes the page size and image and tile locations on a page.
+ This function composes the page size and image and tile locations on a
+ page.
*/
-void t2p_compose_pdf_page(T2P* t2p){
-
- uint32_t i=0;
- uint32_t i2=0;
- T2P_TILE* tiles=NULL;
- T2P_BOX* boxp=NULL;
- uint32_t tilecountx=0;
- uint32_t tilecounty=0;
- uint32_t tilewidth=0;
- uint32_t tilelength=0;
- int istiled=0;
- float f=0;
- float width_ratio=0;
- float length_ratio=0;
-
- t2p->pdf_xres = t2p->tiff_xres;
- t2p->pdf_yres = t2p->tiff_yres;
- if(t2p->pdf_overrideres) {
- t2p->pdf_xres = t2p->pdf_defaultxres;
- t2p->pdf_yres = t2p->pdf_defaultyres;
- }
- if(t2p->pdf_xres == 0.0)
- t2p->pdf_xres = t2p->pdf_defaultxres;
- if(t2p->pdf_yres == 0.0)
- t2p->pdf_yres = t2p->pdf_defaultyres;
- if (t2p->pdf_image_fillpage) {
- width_ratio = t2p->pdf_defaultpagewidth/t2p->tiff_width;
- length_ratio = t2p->pdf_defaultpagelength/t2p->tiff_length;
- if (width_ratio < length_ratio ) {
- t2p->pdf_imagewidth = t2p->pdf_defaultpagewidth;
- t2p->pdf_imagelength = t2p->tiff_length * width_ratio;
- } else {
- t2p->pdf_imagewidth = t2p->tiff_width * length_ratio;
- t2p->pdf_imagelength = t2p->pdf_defaultpagelength;
- }
- } else if (t2p->tiff_resunit != RESUNIT_CENTIMETER /* RESUNIT_NONE and */
- && t2p->tiff_resunit != RESUNIT_INCH) { /* other cases */
- t2p->pdf_imagewidth = ((float)(t2p->tiff_width))/t2p->pdf_xres;
- t2p->pdf_imagelength = ((float)(t2p->tiff_length))/t2p->pdf_yres;
- } else {
- t2p->pdf_imagewidth =
- ((float)(t2p->tiff_width))*PS_UNIT_SIZE/t2p->pdf_xres;
- t2p->pdf_imagelength =
- ((float)(t2p->tiff_length))*PS_UNIT_SIZE/t2p->pdf_yres;
- }
- if(t2p->pdf_overridepagesize != 0) {
- t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth;
- t2p->pdf_pagelength = t2p->pdf_defaultpagelength;
- } else {
- t2p->pdf_pagewidth = t2p->pdf_imagewidth;
- t2p->pdf_pagelength = t2p->pdf_imagelength;
- }
- t2p->pdf_mediabox.x1=0.0;
- t2p->pdf_mediabox.y1=0.0;
- t2p->pdf_mediabox.x2=t2p->pdf_pagewidth;
- t2p->pdf_mediabox.y2=t2p->pdf_pagelength;
- t2p->pdf_imagebox.x1=0.0;
- t2p->pdf_imagebox.y1=0.0;
- t2p->pdf_imagebox.x2=t2p->pdf_imagewidth;
- t2p->pdf_imagebox.y2=t2p->pdf_imagelength;
- if(t2p->pdf_overridepagesize!=0){
- t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F);
- t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F);
- t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F);
- t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F);
- }
- if(t2p->tiff_orientation > 4){
- f=t2p->pdf_mediabox.x2;
- t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2;
- t2p->pdf_mediabox.y2=f;
- }
- istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1;
- if(istiled==0){
- t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation);
- return;
- } else {
- tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth;
- tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength;
- if( tilewidth > INT_MAX ||
- tilelength > INT_MAX ||
- t2p->tiff_width > INT_MAX - tilewidth ||
- t2p->tiff_length > INT_MAX - tilelength )
- {
- TIFFError(TIFF2PDF_MODULE, "Integer overflow");
- t2p->t2p_error = T2P_ERR_ERROR;
- return;
- }
- tilecountx=(t2p->tiff_width +
- tilewidth -1)/
- tilewidth;
- (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx;
- tilecounty=(t2p->tiff_length +
- tilelength -1)/
- tilelength;
- (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty;
- (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth=
- t2p->tiff_width % tilewidth;
- (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength=
- t2p->tiff_length % tilelength;
- tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles;
- for(i2=0;i2<tilecounty-1;i2++){
- for(i=0;i<tilecountx-1;i++){
- boxp=&(tiles[i2*tilecountx+i].tile_box);
- boxp->x1 =
- t2p->pdf_imagebox.x1
- + ((float)(t2p->pdf_imagewidth * i * tilewidth)
- / (float)t2p->tiff_width);
- boxp->x2 =
- t2p->pdf_imagebox.x1
- + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth)
- / (float)t2p->tiff_width);
- boxp->y1 =
- t2p->pdf_imagebox.y2
- - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength)
- / (float)t2p->tiff_length);
- boxp->y2 =
- t2p->pdf_imagebox.y2
- - ((float)(t2p->pdf_imagelength * i2 * tilelength)
- / (float)t2p->tiff_length);
- }
- boxp=&(tiles[i2*tilecountx+i].tile_box);
- boxp->x1 =
- t2p->pdf_imagebox.x1
- + ((float)(t2p->pdf_imagewidth * i * tilewidth)
- / (float)t2p->tiff_width);
- boxp->x2 = t2p->pdf_imagebox.x2;
- boxp->y1 =
- t2p->pdf_imagebox.y2
- - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength)
- / (float)t2p->tiff_length);
- boxp->y2 =
- t2p->pdf_imagebox.y2
- - ((float)(t2p->pdf_imagelength * i2 * tilelength)
- / (float)t2p->tiff_length);
- }
- for(i=0;i<tilecountx-1;i++){
- boxp=&(tiles[i2*tilecountx+i].tile_box);
- boxp->x1 =
- t2p->pdf_imagebox.x1
- + ((float)(t2p->pdf_imagewidth * i * tilewidth)
- / (float)t2p->tiff_width);
- boxp->x2 =
- t2p->pdf_imagebox.x1
- + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth)
- / (float)t2p->tiff_width);
- boxp->y1 = t2p->pdf_imagebox.y1;
- boxp->y2 =
- t2p->pdf_imagebox.y2
- - ((float)(t2p->pdf_imagelength * i2 * tilelength)
- / (float)t2p->tiff_length);
- }
- boxp=&(tiles[i2*tilecountx+i].tile_box);
- boxp->x1 =
- t2p->pdf_imagebox.x1
- + ((float)(t2p->pdf_imagewidth * i * tilewidth)
- / (float)t2p->tiff_width);
- boxp->x2 = t2p->pdf_imagebox.x2;
- boxp->y1 = t2p->pdf_imagebox.y1;
- boxp->y2 =
- t2p->pdf_imagebox.y2
- - ((float)(t2p->pdf_imagelength * i2 * tilelength)
- / (float)t2p->tiff_length);
- }
- if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){
- for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){
- t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0);
- }
- return;
- }
- for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){
- boxp=&(tiles[i].tile_box);
- boxp->x1 -= t2p->pdf_imagebox.x1;
- boxp->x2 -= t2p->pdf_imagebox.x1;
- boxp->y1 -= t2p->pdf_imagebox.y1;
- boxp->y2 -= t2p->pdf_imagebox.y1;
- if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){
- boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1;
- boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2;
- }
- if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){
- boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1;
- boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2;
- }
- if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){
- boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1;
- boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2;
- }
- if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){
- boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1;
- boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2;
- }
- if(t2p->tiff_orientation > 4){
- f=boxp->x1;
- boxp->x1 = boxp->y1;
- boxp->y1 = f;
- f=boxp->x2;
- boxp->x2 = boxp->y2;
- boxp->y2 = f;
- t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation);
- } else {
- t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation);
- }
-
- }
-
- return;
+void t2p_compose_pdf_page(T2P *t2p)
+{
+
+ uint32_t i = 0;
+ uint32_t i2 = 0;
+ T2P_TILE *tiles = NULL;
+ T2P_BOX *boxp = NULL;
+ uint32_t tilecountx = 0;
+ uint32_t tilecounty = 0;
+ uint32_t tilewidth = 0;
+ uint32_t tilelength = 0;
+ int istiled = 0;
+ float f = 0;
+ float width_ratio = 0;
+ float length_ratio = 0;
+
+ t2p->pdf_xres = t2p->tiff_xres;
+ t2p->pdf_yres = t2p->tiff_yres;
+ if (t2p->pdf_overrideres)
+ {
+ t2p->pdf_xres = t2p->pdf_defaultxres;
+ t2p->pdf_yres = t2p->pdf_defaultyres;
+ }
+ if (t2p->pdf_xres == 0.0)
+ t2p->pdf_xres = t2p->pdf_defaultxres;
+ if (t2p->pdf_yres == 0.0)
+ t2p->pdf_yres = t2p->pdf_defaultyres;
+ if (t2p->pdf_image_fillpage)
+ {
+ width_ratio = t2p->pdf_defaultpagewidth / t2p->tiff_width;
+ length_ratio = t2p->pdf_defaultpagelength / t2p->tiff_length;
+ if (width_ratio < length_ratio)
+ {
+ t2p->pdf_imagewidth = t2p->pdf_defaultpagewidth;
+ t2p->pdf_imagelength = t2p->tiff_length * width_ratio;
+ }
+ else
+ {
+ t2p->pdf_imagewidth = t2p->tiff_width * length_ratio;
+ t2p->pdf_imagelength = t2p->pdf_defaultpagelength;
+ }
+ }
+ else if (t2p->tiff_resunit != RESUNIT_CENTIMETER /* RESUNIT_NONE and */
+ && t2p->tiff_resunit != RESUNIT_INCH)
+ { /* other cases */
+ t2p->pdf_imagewidth = ((float)(t2p->tiff_width)) / t2p->pdf_xres;
+ t2p->pdf_imagelength = ((float)(t2p->tiff_length)) / t2p->pdf_yres;
+ }
+ else
+ {
+ t2p->pdf_imagewidth =
+ ((float)(t2p->tiff_width)) * PS_UNIT_SIZE / t2p->pdf_xres;
+ t2p->pdf_imagelength =
+ ((float)(t2p->tiff_length)) * PS_UNIT_SIZE / t2p->pdf_yres;
+ }
+ if (t2p->pdf_overridepagesize != 0)
+ {
+ t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth;
+ t2p->pdf_pagelength = t2p->pdf_defaultpagelength;
+ }
+ else
+ {
+ t2p->pdf_pagewidth = t2p->pdf_imagewidth;
+ t2p->pdf_pagelength = t2p->pdf_imagelength;
+ }
+ t2p->pdf_mediabox.x1 = 0.0;
+ t2p->pdf_mediabox.y1 = 0.0;
+ t2p->pdf_mediabox.x2 = t2p->pdf_pagewidth;
+ t2p->pdf_mediabox.y2 = t2p->pdf_pagelength;
+ t2p->pdf_imagebox.x1 = 0.0;
+ t2p->pdf_imagebox.y1 = 0.0;
+ t2p->pdf_imagebox.x2 = t2p->pdf_imagewidth;
+ t2p->pdf_imagebox.y2 = t2p->pdf_imagelength;
+ if (t2p->pdf_overridepagesize != 0)
+ {
+ t2p->pdf_imagebox.x1 +=
+ ((t2p->pdf_pagewidth - t2p->pdf_imagewidth) / 2.0F);
+ t2p->pdf_imagebox.y1 +=
+ ((t2p->pdf_pagelength - t2p->pdf_imagelength) / 2.0F);
+ t2p->pdf_imagebox.x2 +=
+ ((t2p->pdf_pagewidth - t2p->pdf_imagewidth) / 2.0F);
+ t2p->pdf_imagebox.y2 +=
+ ((t2p->pdf_pagelength - t2p->pdf_imagelength) / 2.0F);
+ }
+ if (t2p->tiff_orientation > 4)
+ {
+ f = t2p->pdf_mediabox.x2;
+ t2p->pdf_mediabox.x2 = t2p->pdf_mediabox.y2;
+ t2p->pdf_mediabox.y2 = f;
+ }
+ istiled = ((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount == 0) ? 0 : 1;
+ if (istiled == 0)
+ {
+ t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox),
+ t2p->tiff_orientation);
+ return;
+ }
+ else
+ {
+ tilewidth = (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth;
+ tilelength = (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength;
+ if (tilewidth > INT_MAX || tilelength > INT_MAX ||
+ t2p->tiff_width > INT_MAX - tilewidth ||
+ t2p->tiff_length > INT_MAX - tilelength)
+ {
+ TIFFError(TIFF2PDF_MODULE, "Integer overflow");
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return;
+ }
+ tilecountx = (t2p->tiff_width + tilewidth - 1) / tilewidth;
+ (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx = tilecountx;
+ tilecounty = (t2p->tiff_length + tilelength - 1) / tilelength;
+ (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty = tilecounty;
+ (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth =
+ t2p->tiff_width % tilewidth;
+ (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength =
+ t2p->tiff_length % tilelength;
+ tiles = (t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles;
+ for (i2 = 0; i2 < tilecounty - 1; i2++)
+ {
+ for (i = 0; i < tilecountx - 1; i++)
+ {
+ boxp = &(tiles[i2 * tilecountx + i].tile_box);
+ boxp->x1 = t2p->pdf_imagebox.x1 +
+ ((float)(t2p->pdf_imagewidth * i * tilewidth) /
+ (float)t2p->tiff_width);
+ boxp->x2 = t2p->pdf_imagebox.x1 +
+ ((float)(t2p->pdf_imagewidth * (i + 1) * tilewidth) /
+ (float)t2p->tiff_width);
+ boxp->y1 =
+ t2p->pdf_imagebox.y2 -
+ ((float)(t2p->pdf_imagelength * (i2 + 1) * tilelength) /
+ (float)t2p->tiff_length);
+ boxp->y2 = t2p->pdf_imagebox.y2 -
+ ((float)(t2p->pdf_imagelength * i2 * tilelength) /
+ (float)t2p->tiff_length);
+ }
+ boxp = &(tiles[i2 * tilecountx + i].tile_box);
+ boxp->x1 = t2p->pdf_imagebox.x1 +
+ ((float)(t2p->pdf_imagewidth * i * tilewidth) /
+ (float)t2p->tiff_width);
+ boxp->x2 = t2p->pdf_imagebox.x2;
+ boxp->y1 = t2p->pdf_imagebox.y2 -
+ ((float)(t2p->pdf_imagelength * (i2 + 1) * tilelength) /
+ (float)t2p->tiff_length);
+ boxp->y2 = t2p->pdf_imagebox.y2 -
+ ((float)(t2p->pdf_imagelength * i2 * tilelength) /
+ (float)t2p->tiff_length);
+ }
+ for (i = 0; i < tilecountx - 1; i++)
+ {
+ boxp = &(tiles[i2 * tilecountx + i].tile_box);
+ boxp->x1 = t2p->pdf_imagebox.x1 +
+ ((float)(t2p->pdf_imagewidth * i * tilewidth) /
+ (float)t2p->tiff_width);
+ boxp->x2 = t2p->pdf_imagebox.x1 +
+ ((float)(t2p->pdf_imagewidth * (i + 1) * tilewidth) /
+ (float)t2p->tiff_width);
+ boxp->y1 = t2p->pdf_imagebox.y1;
+ boxp->y2 = t2p->pdf_imagebox.y2 -
+ ((float)(t2p->pdf_imagelength * i2 * tilelength) /
+ (float)t2p->tiff_length);
+ }
+ boxp = &(tiles[i2 * tilecountx + i].tile_box);
+ boxp->x1 = t2p->pdf_imagebox.x1 +
+ ((float)(t2p->pdf_imagewidth * i * tilewidth) /
+ (float)t2p->tiff_width);
+ boxp->x2 = t2p->pdf_imagebox.x2;
+ boxp->y1 = t2p->pdf_imagebox.y1;
+ boxp->y2 = t2p->pdf_imagebox.y2 -
+ ((float)(t2p->pdf_imagelength * i2 * tilelength) /
+ (float)t2p->tiff_length);
+ }
+ if (t2p->tiff_orientation == 0 || t2p->tiff_orientation == 1)
+ {
+ for (i = 0; i < (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount; i++)
+ {
+ t2p_compose_pdf_page_orient(&(tiles[i].tile_box), 0);
+ }
+ return;
+ }
+ for (i = 0; i < (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount; i++)
+ {
+ boxp = &(tiles[i].tile_box);
+ boxp->x1 -= t2p->pdf_imagebox.x1;
+ boxp->x2 -= t2p->pdf_imagebox.x1;
+ boxp->y1 -= t2p->pdf_imagebox.y1;
+ boxp->y2 -= t2p->pdf_imagebox.y1;
+ if (t2p->tiff_orientation == 2 || t2p->tiff_orientation == 3)
+ {
+ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1;
+ boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2;
+ }
+ if (t2p->tiff_orientation == 3 || t2p->tiff_orientation == 4)
+ {
+ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1;
+ boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2;
+ }
+ if (t2p->tiff_orientation == 8 || t2p->tiff_orientation == 5)
+ {
+ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1;
+ boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2;
+ }
+ if (t2p->tiff_orientation == 5 || t2p->tiff_orientation == 6)
+ {
+ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1;
+ boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2;
+ }
+ if (t2p->tiff_orientation > 4)
+ {
+ f = boxp->x1;
+ boxp->x1 = boxp->y1;
+ boxp->y1 = f;
+ f = boxp->x2;
+ boxp->x2 = boxp->y2;
+ boxp->y2 = f;
+ t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation);
+ }
+ else
+ {
+ t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation);
+ }
+ }
+
+ return;
}
-void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16_t orientation){
-
- float m1[9];
- float f=0.0;
-
- if( boxp->x1 > boxp->x2){
- f=boxp->x1;
- boxp->x1=boxp->x2;
- boxp->x2 = f;
- }
- if( boxp->y1 > boxp->y2){
- f=boxp->y1;
- boxp->y1=boxp->y2;
- boxp->y2 = f;
- }
- boxp->mat[0]=m1[0]=boxp->x2-boxp->x1;
- boxp->mat[1]=m1[1]=0.0;
- boxp->mat[2]=m1[2]=0.0;
- boxp->mat[3]=m1[3]=0.0;
- boxp->mat[4]=m1[4]=boxp->y2-boxp->y1;
- boxp->mat[5]=m1[5]=0.0;
- boxp->mat[6]=m1[6]=boxp->x1;
- boxp->mat[7]=m1[7]=boxp->y1;
- boxp->mat[8]=m1[8]=1.0;
- switch(orientation){
- case 0:
- case 1:
- break;
- case 2:
- boxp->mat[0]=0.0F-m1[0];
- boxp->mat[6]+=m1[0];
- break;
- case 3:
- boxp->mat[0]=0.0F-m1[0];
- boxp->mat[4]=0.0F-m1[4];
- boxp->mat[6]+=m1[0];
- boxp->mat[7]+=m1[4];
- break;
- case 4:
- boxp->mat[4]=0.0F-m1[4];
- boxp->mat[7]+=m1[4];
- break;
- case 5:
- boxp->mat[0]=0.0F;
- boxp->mat[1]=0.0F-m1[0];
- boxp->mat[3]=0.0F-m1[4];
- boxp->mat[4]=0.0F;
- boxp->mat[6]+=m1[4];
- boxp->mat[7]+=m1[0];
- break;
- case 6:
- boxp->mat[0]=0.0F;
- boxp->mat[1]=0.0F-m1[0];
- boxp->mat[3]=m1[4];
- boxp->mat[4]=0.0F;
- boxp->mat[7]+=m1[0];
- break;
- case 7:
- boxp->mat[0]=0.0F;
- boxp->mat[1]=m1[0];
- boxp->mat[3]=m1[4];
- boxp->mat[4]=0.0F;
- break;
- case 8:
- boxp->mat[0]=0.0F;
- boxp->mat[1]=m1[0];
- boxp->mat[3]=0.0F-m1[4];
- boxp->mat[4]=0.0F;
- boxp->mat[6]+=m1[4];
- break;
- }
-
- return;
+void t2p_compose_pdf_page_orient(T2P_BOX *boxp, uint16_t orientation)
+{
+
+ float m1[9];
+ float f = 0.0;
+
+ if (boxp->x1 > boxp->x2)
+ {
+ f = boxp->x1;
+ boxp->x1 = boxp->x2;
+ boxp->x2 = f;
+ }
+ if (boxp->y1 > boxp->y2)
+ {
+ f = boxp->y1;
+ boxp->y1 = boxp->y2;
+ boxp->y2 = f;
+ }
+ boxp->mat[0] = m1[0] = boxp->x2 - boxp->x1;
+ boxp->mat[1] = m1[1] = 0.0;
+ boxp->mat[2] = m1[2] = 0.0;
+ boxp->mat[3] = m1[3] = 0.0;
+ boxp->mat[4] = m1[4] = boxp->y2 - boxp->y1;
+ boxp->mat[5] = m1[5] = 0.0;
+ boxp->mat[6] = m1[6] = boxp->x1;
+ boxp->mat[7] = m1[7] = boxp->y1;
+ boxp->mat[8] = m1[8] = 1.0;
+ switch (orientation)
+ {
+ case 0:
+ case 1:
+ break;
+ case 2:
+ boxp->mat[0] = 0.0F - m1[0];
+ boxp->mat[6] += m1[0];
+ break;
+ case 3:
+ boxp->mat[0] = 0.0F - m1[0];
+ boxp->mat[4] = 0.0F - m1[4];
+ boxp->mat[6] += m1[0];
+ boxp->mat[7] += m1[4];
+ break;
+ case 4:
+ boxp->mat[4] = 0.0F - m1[4];
+ boxp->mat[7] += m1[4];
+ break;
+ case 5:
+ boxp->mat[0] = 0.0F;
+ boxp->mat[1] = 0.0F - m1[0];
+ boxp->mat[3] = 0.0F - m1[4];
+ boxp->mat[4] = 0.0F;
+ boxp->mat[6] += m1[4];
+ boxp->mat[7] += m1[0];
+ break;
+ case 6:
+ boxp->mat[0] = 0.0F;
+ boxp->mat[1] = 0.0F - m1[0];
+ boxp->mat[3] = m1[4];
+ boxp->mat[4] = 0.0F;
+ boxp->mat[7] += m1[0];
+ break;
+ case 7:
+ boxp->mat[0] = 0.0F;
+ boxp->mat[1] = m1[0];
+ boxp->mat[3] = m1[4];
+ boxp->mat[4] = 0.0F;
+ break;
+ case 8:
+ boxp->mat[0] = 0.0F;
+ boxp->mat[1] = m1[0];
+ boxp->mat[3] = 0.0F - m1[4];
+ boxp->mat[4] = 0.0F;
+ boxp->mat[6] += m1[4];
+ break;
+ }
+
+ return;
}
-void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16_t orientation){
-
- float m1[9];
- float f=0.0;
-
- if( boxp->x1 > boxp->x2){
- f=boxp->x1;
- boxp->x1=boxp->x2;
- boxp->x2 = f;
- }
- if( boxp->y1 > boxp->y2){
- f=boxp->y1;
- boxp->y1=boxp->y2;
- boxp->y2 = f;
- }
- boxp->mat[0]=m1[0]=boxp->x2-boxp->x1;
- boxp->mat[1]=m1[1]=0.0F;
- boxp->mat[2]=m1[2]=0.0F;
- boxp->mat[3]=m1[3]=0.0F;
- boxp->mat[4]=m1[4]=boxp->y2-boxp->y1;
- boxp->mat[5]=m1[5]=0.0F;
- boxp->mat[6]=m1[6]=boxp->x1;
- boxp->mat[7]=m1[7]=boxp->y1;
- boxp->mat[8]=m1[8]=1.0F;
- switch(orientation){
- case 5:
- boxp->mat[0]=0.0F;
- boxp->mat[1]=0.0F-m1[4];
- boxp->mat[3]=0.0F-m1[0];
- boxp->mat[4]=0.0F;
- boxp->mat[6]+=m1[0];
- boxp->mat[7]+=m1[4];
- break;
- case 6:
- boxp->mat[0]=0.0F;
- boxp->mat[1]=0.0F-m1[4];
- boxp->mat[3]=m1[0];
- boxp->mat[4]=0.0F;
- boxp->mat[7]+=m1[4];
- break;
- case 7:
- boxp->mat[0]=0.0F;
- boxp->mat[1]=m1[4];
- boxp->mat[3]=m1[0];
- boxp->mat[4]=0.0F;
- break;
- case 8:
- boxp->mat[0]=0.0F;
- boxp->mat[1]=m1[4];
- boxp->mat[3]=0.0F-m1[0];
- boxp->mat[4]=0.0F;
- boxp->mat[6]+=m1[0];
- break;
- }
-
- return;
+void t2p_compose_pdf_page_orient_flip(T2P_BOX *boxp, uint16_t orientation)
+{
+
+ float m1[9];
+ float f = 0.0;
+
+ if (boxp->x1 > boxp->x2)
+ {
+ f = boxp->x1;
+ boxp->x1 = boxp->x2;
+ boxp->x2 = f;
+ }
+ if (boxp->y1 > boxp->y2)
+ {
+ f = boxp->y1;
+ boxp->y1 = boxp->y2;
+ boxp->y2 = f;
+ }
+ boxp->mat[0] = m1[0] = boxp->x2 - boxp->x1;
+ boxp->mat[1] = m1[1] = 0.0F;
+ boxp->mat[2] = m1[2] = 0.0F;
+ boxp->mat[3] = m1[3] = 0.0F;
+ boxp->mat[4] = m1[4] = boxp->y2 - boxp->y1;
+ boxp->mat[5] = m1[5] = 0.0F;
+ boxp->mat[6] = m1[6] = boxp->x1;
+ boxp->mat[7] = m1[7] = boxp->y1;
+ boxp->mat[8] = m1[8] = 1.0F;
+ switch (orientation)
+ {
+ case 5:
+ boxp->mat[0] = 0.0F;
+ boxp->mat[1] = 0.0F - m1[4];
+ boxp->mat[3] = 0.0F - m1[0];
+ boxp->mat[4] = 0.0F;
+ boxp->mat[6] += m1[0];
+ boxp->mat[7] += m1[4];
+ break;
+ case 6:
+ boxp->mat[0] = 0.0F;
+ boxp->mat[1] = 0.0F - m1[4];
+ boxp->mat[3] = m1[0];
+ boxp->mat[4] = 0.0F;
+ boxp->mat[7] += m1[4];
+ break;
+ case 7:
+ boxp->mat[0] = 0.0F;
+ boxp->mat[1] = m1[4];
+ boxp->mat[3] = m1[0];
+ boxp->mat[4] = 0.0F;
+ break;
+ case 8:
+ boxp->mat[0] = 0.0F;
+ boxp->mat[1] = m1[4];
+ boxp->mat[3] = 0.0F - m1[0];
+ boxp->mat[4] = 0.0F;
+ boxp->mat[6] += m1[0];
+ break;
+ }
+
+ return;
}
/*
- This function writes a PDF Contents stream to output.
+ This function writes a PDF Contents stream to output.
*/
-tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){
-
- tsize_t written=0;
- ttile_t i=0;
- char buffer[512];
- int buflen=0;
- T2P_BOX box;
-
- if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){
- for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){
- box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box;
- buflen=snprintf(buffer, sizeof(buffer),
- "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%"PRIu16"_%"PRIu32" Do Q\n",
- t2p->tiff_transferfunctioncount?"/GS1 gs ":"",
- box.mat[0],
- box.mat[1],
- box.mat[3],
- box.mat[4],
- box.mat[6],
- box.mat[7],
- (uint16_t)(t2p->pdf_page + 1u),
- i + 1u);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2p_write_pdf_stream(buffer, buflen, output);
- }
- } else {
- box=t2p->pdf_imagebox;
- buflen=snprintf(buffer, sizeof(buffer),
- "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%"PRIu16" Do Q\n",
- t2p->tiff_transferfunctioncount?"/GS1 gs ":"",
- box.mat[0],
- box.mat[1],
- box.mat[3],
- box.mat[4],
- box.mat[6],
- box.mat[7],
- (uint16_t)(t2p->pdf_page+1u));
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2p_write_pdf_stream(buffer, buflen, output);
- }
-
- return(written);
+tsize_t t2p_write_pdf_page_content_stream(T2P *t2p, TIFF *output)
+{
+
+ tsize_t written = 0;
+ ttile_t i = 0;
+ char buffer[512];
+ int buflen = 0;
+ T2P_BOX box;
+
+ if (t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount > 0)
+ {
+ for (i = 0; i < t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++)
+ {
+ box = t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box;
+ buflen = snprintf(
+ buffer, sizeof(buffer),
+ "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%" PRIu16 "_%" PRIu32
+ " Do Q\n",
+ t2p->tiff_transferfunctioncount ? "/GS1 gs " : "", box.mat[0],
+ box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7],
+ (uint16_t)(t2p->pdf_page + 1u), i + 1u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2p_write_pdf_stream(buffer, buflen, output);
+ }
+ }
+ else
+ {
+ box = t2p->pdf_imagebox;
+ buflen = snprintf(
+ buffer, sizeof(buffer),
+ "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%" PRIu16 " Do Q\n",
+ t2p->tiff_transferfunctioncount ? "/GS1 gs " : "", box.mat[0],
+ box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7],
+ (uint16_t)(t2p->pdf_page + 1u));
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2p_write_pdf_stream(buffer, buflen, output);
+ }
+
+ return (written);
}
/*
- This function writes a PDF Image XObject stream dictionary to output.
+ This function writes a PDF Image XObject stream dictionary to output.
*/
-tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile,
- T2P* t2p,
- TIFF* output){
-
- tsize_t written=0;
- char buffer[32];
- int buflen=0;
-
- written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output);
- written += t2pWriteFile(output,
- (tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im",
- 42);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu16, (uint16_t)(t2p->pdf_page+1u));
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- if(tile != 0){
- written += t2pWriteFile(output, (tdata_t) "_", 1);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, tile);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- }
- written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8);
- if(tile==0){
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->tiff_width);
- } else {
- if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
- } else {
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
- }
- }
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9);
- if(tile==0){
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->tiff_length);
- } else {
- if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
- } else {
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
- }
- }
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu16, t2p->tiff_bitspersample);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13);
- written += t2p_write_pdf_xobject_cs(t2p, output);
- if (t2p->pdf_image_interpolate)
- written += t2pWriteFile(output,
- (tdata_t) "\n/Interpolate true", 18);
- if( (t2p->pdf_switchdecode != 0)
+tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile, T2P *t2p, TIFF *output)
+{
+
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
+
+ written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount + 1, output);
+ written += t2pWriteFile(
+ output, (tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im", 42);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu16,
+ (uint16_t)(t2p->pdf_page + 1u));
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ if (tile != 0)
+ {
+ written += t2pWriteFile(output, (tdata_t) "_", 1);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, tile);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ }
+ written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8);
+ if (tile == 0)
+ {
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->tiff_width);
+ }
+ else
+ {
+ if (t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile - 1) !=
+ 0)
+ {
+ buflen =
+ snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
+ }
+ else
+ {
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
+ }
+ }
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9);
+ if (tile == 0)
+ {
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->tiff_length);
+ }
+ else
+ {
+ if (t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile - 1) !=
+ 0)
+ {
+ buflen =
+ snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
+ }
+ else
+ {
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
+ }
+ }
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19);
+ buflen =
+ snprintf(buffer, sizeof(buffer), "%" PRIu16, t2p->tiff_bitspersample);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13);
+ written += t2p_write_pdf_xobject_cs(t2p, output);
+ if (t2p->pdf_image_interpolate)
+ written += t2pWriteFile(output, (tdata_t) "\n/Interpolate true", 18);
+ if ((t2p->pdf_switchdecode != 0)
#ifdef CCITT_SUPPORT
- && ! (t2p->pdf_colorspace & T2P_CS_BILEVEL
- && t2p->pdf_compression == T2P_COMPRESS_G4)
+ && !(t2p->pdf_colorspace & T2P_CS_BILEVEL &&
+ t2p->pdf_compression == T2P_COMPRESS_G4)
#endif
- ){
- written += t2p_write_pdf_xobject_decode(t2p, output);
- }
- written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output);
-
- return(written);
-}
+ )
+ {
+ written += t2p_write_pdf_xobject_decode(t2p, output);
+ }
+ written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output);
+ return (written);
+}
/* used to normalize the White Point */
-#define normalizePoint(x,y,z) do { \
- if (y != 0.0F) { \
- x /= y; \
- z /= y; \
- y = 1.0F; \
- } \
-} while(0)
+#define normalizePoint(x, y, z) \
+ do \
+ { \
+ if (y != 0.0F) \
+ { \
+ x /= y; \
+ z /= y; \
+ y = 1.0F; \
+ } \
+ } while (0)
/*
* This function writes a PDF Image XObject Colorspace name to output.
*/
+tsize_t t2p_write_pdf_xobject_cs(T2P *t2p, TIFF *output)
+{
-tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){
-
- tsize_t written=0;
- char buffer[128];
- int buflen=0;
-
- float X_W=1.0;
- float Y_W=1.0;
- float Z_W=1.0;
-
- if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){
- written += t2p_write_pdf_xobject_icccs(t2p, output);
- return(written);
- }
- if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){
- written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11);
- t2p->pdf_colorspace ^= T2P_CS_PALETTE;
- written += t2p_write_pdf_xobject_cs(t2p, output);
- t2p->pdf_colorspace |= T2P_CS_PALETTE;
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, (uint32_t)(0x1u << t2p->tiff_bitspersample)-1u );
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " ", 1);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->pdf_palettecs );
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7);
- return(written);
- }
- if(t2p->pdf_colorspace & T2P_CS_BILEVEL){
- written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13);
- }
- if(t2p->pdf_colorspace & T2P_CS_GRAY){
- if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
- written += t2p_write_pdf_xobject_calcs(t2p, output);
- } else {
- written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13);
- }
- }
- if(t2p->pdf_colorspace & T2P_CS_RGB){
- if(t2p->pdf_colorspace & T2P_CS_CALRGB){
- written += t2p_write_pdf_xobject_calcs(t2p, output);
- } else {
- written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12);
- }
- }
- if(t2p->pdf_colorspace & T2P_CS_CMYK){
- written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13);
- }
- if(t2p->pdf_colorspace & T2P_CS_LAB){
- written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10);
- written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
- X_W = t2p->tiff_whitechromaticities[0];
- Y_W = t2p->tiff_whitechromaticities[1];
- Z_W = 1.0F - (X_W + Y_W);
- normalizePoint(X_W, Y_W, Z_W);
- buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "/Range ", 7);
- buflen=snprintf(buffer, sizeof(buffer), "[%d %d %d %d] \n",
- t2p->pdf_labrange[0],
- t2p->pdf_labrange[1],
- t2p->pdf_labrange[2],
- t2p->pdf_labrange[3]);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) ">>] \n", 5);
-
- }
-
- return(written);
-}
-
-tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){
-
- tsize_t written=0;
- char buffer[32];
- int buflen=0;
-
- written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25);
- if(t2p->tiff_transferfunctioncount == 1){
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->pdf_xrefcount + 1u);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
- } else {
- written += t2pWriteFile(output, (tdata_t) "[ ", 2);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->pdf_xrefcount + 1u);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->pdf_xrefcount + 2u);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->pdf_xrefcount + 3u);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
- written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12);
- }
-
- written += t2pWriteFile(output, (tdata_t) " >> \n", 5);
-
- return(written);
+ tsize_t written = 0;
+ char buffer[128];
+ int buflen = 0;
+
+ float X_W = 1.0;
+ float Y_W = 1.0;
+ float Z_W = 1.0;
+
+ if ((t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0)
+ {
+ written += t2p_write_pdf_xobject_icccs(t2p, output);
+ return (written);
+ }
+ if ((t2p->pdf_colorspace & T2P_CS_PALETTE) != 0)
+ {
+ written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11);
+ t2p->pdf_colorspace ^= T2P_CS_PALETTE;
+ written += t2p_write_pdf_xobject_cs(t2p, output);
+ t2p->pdf_colorspace |= T2P_CS_PALETTE;
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ (uint32_t)(0x1u << t2p->tiff_bitspersample) - 1u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " ", 1);
+ buflen =
+ snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->pdf_palettecs);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7);
+ return (written);
+ }
+ if (t2p->pdf_colorspace & T2P_CS_BILEVEL)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13);
+ }
+ if (t2p->pdf_colorspace & T2P_CS_GRAY)
+ {
+ if (t2p->pdf_colorspace & T2P_CS_CALGRAY)
+ {
+ written += t2p_write_pdf_xobject_calcs(t2p, output);
+ }
+ else
+ {
+ written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13);
+ }
+ }
+ if (t2p->pdf_colorspace & T2P_CS_RGB)
+ {
+ if (t2p->pdf_colorspace & T2P_CS_CALRGB)
+ {
+ written += t2p_write_pdf_xobject_calcs(t2p, output);
+ }
+ else
+ {
+ written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12);
+ }
+ }
+ if (t2p->pdf_colorspace & T2P_CS_CMYK)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13);
+ }
+ if (t2p->pdf_colorspace & T2P_CS_LAB)
+ {
+ written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10);
+ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
+ X_W = t2p->tiff_whitechromaticities[0];
+ Y_W = t2p->tiff_whitechromaticities[1];
+ Z_W = 1.0F - (X_W + Y_W);
+ normalizePoint(X_W, Y_W, Z_W);
+ buflen = snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W,
+ Y_W, Z_W);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "/Range ", 7);
+ buflen = snprintf(buffer, sizeof(buffer), "[%d %d %d %d] \n",
+ t2p->pdf_labrange[0], t2p->pdf_labrange[1],
+ t2p->pdf_labrange[2], t2p->pdf_labrange[3]);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) ">>] \n", 5);
+ }
+
+ return (written);
}
-tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16_t i){
+tsize_t t2p_write_pdf_transfer(T2P *t2p, TIFF *output)
+{
- tsize_t written=0;
- char buffer[32];
- int buflen=0;
- (void)i; /* XXX */
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
+
+ written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25);
+ if (t2p->tiff_transferfunctioncount == 1)
+ {
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->pdf_xrefcount + 1u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+ }
+ else
+ {
+ written += t2pWriteFile(output, (tdata_t) "[ ", 2);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->pdf_xrefcount + 1u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->pdf_xrefcount + 2u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->pdf_xrefcount + 3u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
+ written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12);
+ }
+
+ written += t2pWriteFile(output, (tdata_t) " >> \n", 5);
+
+ return (written);
+}
- written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17);
- written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19);
- written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18);
- buflen=snprintf(buffer, sizeof(buffer), "/Size [%"PRIu16"] \n", (uint16_t)(1u<<t2p->tiff_bitspersample));
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19);
- written += t2p_write_pdf_stream_dict(((tsize_t)1)<<(t2p->tiff_bitspersample+1), 0, output);
+tsize_t t2p_write_pdf_transfer_dict(T2P *t2p, TIFF *output, uint16_t i)
+{
- return(written);
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
+ (void)i; /* XXX */
+
+ written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17);
+ written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19);
+ written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18);
+ buflen = snprintf(buffer, sizeof(buffer), "/Size [%" PRIu16 "] \n",
+ (uint16_t)(1u << t2p->tiff_bitspersample));
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19);
+ written += t2p_write_pdf_stream_dict(
+ ((tsize_t)1) << (t2p->tiff_bitspersample + 1), 0, output);
+
+ return (written);
}
-tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16_t i){
+tsize_t t2p_write_pdf_transfer_stream(T2P *t2p, TIFF *output, uint16_t i)
+{
- tsize_t written=0;
+ tsize_t written = 0;
- written += t2p_write_pdf_stream(
- t2p->tiff_transferfunction[i],
- (((tsize_t)1)<<(t2p->tiff_bitspersample+1)),
- output);
+ written += t2p_write_pdf_stream(
+ t2p->tiff_transferfunction[i],
+ (((tsize_t)1) << (t2p->tiff_bitspersample + 1)), output);
- return(written);
+ return (written);
}
/*
- This function writes a PDF Image XObject Colorspace array to output.
+ This function writes a PDF Image XObject Colorspace array to output.
*/
-tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){
-
- tsize_t written=0;
- char buffer[256];
- int buflen=0;
-
- float X_W=0.0;
- float Y_W=0.0;
- float Z_W=0.0;
- float X_R=0.0;
- float Y_R=0.0;
- float Z_R=0.0;
- float X_G=0.0;
- float Y_G=0.0;
- float Z_G=0.0;
- float X_B=0.0;
- float Y_B=0.0;
- float Z_B=0.0;
- float x_w=0.0;
- float y_w=0.0;
- float z_w=0.0;
- float x_r=0.0;
- float y_r=0.0;
- float x_g=0.0;
- float y_g=0.0;
- float x_b=0.0;
- float y_b=0.0;
- float R=1.0;
- float G=1.0;
- float B=1.0;
-
- written += t2pWriteFile(output, (tdata_t) "[", 1);
- if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
- written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9);
- X_W = t2p->tiff_whitechromaticities[0];
- Y_W = t2p->tiff_whitechromaticities[1];
- Z_W = 1.0F - (X_W + Y_W);
- normalizePoint(X_W, Y_W, Z_W);
- }
- if(t2p->pdf_colorspace & T2P_CS_CALRGB){
- written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8);
- x_w = t2p->tiff_whitechromaticities[0];
- y_w = t2p->tiff_whitechromaticities[1];
- x_r = t2p->tiff_primarychromaticities[0];
- y_r = t2p->tiff_primarychromaticities[1];
- x_g = t2p->tiff_primarychromaticities[2];
- y_g = t2p->tiff_primarychromaticities[3];
- x_b = t2p->tiff_primarychromaticities[4];
- y_b = t2p->tiff_primarychromaticities[5];
- z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b);
- Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w;
- X_R = Y_R * x_r / y_r;
- Z_R = Y_R * (((1-x_r)/y_r)-1);
- Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w;
- X_G = Y_G * x_g / y_g;
- Z_G = Y_G * (((1-x_g)/y_g)-1);
- Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w;
- X_B = Y_B * x_b / y_b;
- Z_B = Y_B * (((1-x_b)/y_b)-1);
- X_W = (X_R * R) + (X_G * G) + (X_B * B);
- Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B);
- Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B);
- normalizePoint(X_W, Y_W, Z_W);
- }
- written += t2pWriteFile(output, (tdata_t) "<< \n", 4);
- if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
- written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
- buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12);
- }
- if(t2p->pdf_colorspace & T2P_CS_CALRGB){
- written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
- buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8);
- buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n",
- X_R, Y_R, Z_R,
- X_G, Y_G, Z_G,
- X_B, Y_B, Z_B);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22);
- }
- written += t2pWriteFile(output, (tdata_t) ">>] \n", 5);
-
- return(written);
+tsize_t t2p_write_pdf_xobject_calcs(T2P *t2p, TIFF *output)
+{
+
+ tsize_t written = 0;
+ char buffer[256];
+ int buflen = 0;
+
+ float X_W = 0.0;
+ float Y_W = 0.0;
+ float Z_W = 0.0;
+ float X_R = 0.0;
+ float Y_R = 0.0;
+ float Z_R = 0.0;
+ float X_G = 0.0;
+ float Y_G = 0.0;
+ float Z_G = 0.0;
+ float X_B = 0.0;
+ float Y_B = 0.0;
+ float Z_B = 0.0;
+ float x_w = 0.0;
+ float y_w = 0.0;
+ float z_w = 0.0;
+ float x_r = 0.0;
+ float y_r = 0.0;
+ float x_g = 0.0;
+ float y_g = 0.0;
+ float x_b = 0.0;
+ float y_b = 0.0;
+ float R = 1.0;
+ float G = 1.0;
+ float B = 1.0;
+
+ written += t2pWriteFile(output, (tdata_t) "[", 1);
+ if (t2p->pdf_colorspace & T2P_CS_CALGRAY)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9);
+ X_W = t2p->tiff_whitechromaticities[0];
+ Y_W = t2p->tiff_whitechromaticities[1];
+ Z_W = 1.0F - (X_W + Y_W);
+ normalizePoint(X_W, Y_W, Z_W);
+ }
+ if (t2p->pdf_colorspace & T2P_CS_CALRGB)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8);
+ x_w = t2p->tiff_whitechromaticities[0];
+ y_w = t2p->tiff_whitechromaticities[1];
+ x_r = t2p->tiff_primarychromaticities[0];
+ y_r = t2p->tiff_primarychromaticities[1];
+ x_g = t2p->tiff_primarychromaticities[2];
+ y_g = t2p->tiff_primarychromaticities[3];
+ x_b = t2p->tiff_primarychromaticities[4];
+ y_b = t2p->tiff_primarychromaticities[5];
+ z_w = y_w * ((x_g - x_b) * y_r - (x_r - x_b) * y_g + (x_r - x_g) * y_b);
+ Y_R = (y_r / R) *
+ ((x_g - x_b) * y_w - (x_w - x_b) * y_g + (x_w - x_g) * y_b) / z_w;
+ X_R = Y_R * x_r / y_r;
+ Z_R = Y_R * (((1 - x_r) / y_r) - 1);
+ Y_G = ((0.0F - (y_g)) / G) *
+ ((x_r - x_b) * y_w - (x_w - x_b) * y_r + (x_w - x_r) * y_b) / z_w;
+ X_G = Y_G * x_g / y_g;
+ Z_G = Y_G * (((1 - x_g) / y_g) - 1);
+ Y_B = (y_b / B) *
+ ((x_r - x_g) * y_w - (x_w - x_g) * y_r + (x_w - x_r) * y_g) / z_w;
+ X_B = Y_B * x_b / y_b;
+ Z_B = Y_B * (((1 - x_b) / y_b) - 1);
+ X_W = (X_R * R) + (X_G * G) + (X_B * B);
+ Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B);
+ Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B);
+ normalizePoint(X_W, Y_W, Z_W);
+ }
+ written += t2pWriteFile(output, (tdata_t) "<< \n", 4);
+ if (t2p->pdf_colorspace & T2P_CS_CALGRAY)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
+ buflen = snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W,
+ Y_W, Z_W);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12);
+ }
+ if (t2p->pdf_colorspace & T2P_CS_CALRGB)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
+ buflen = snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W,
+ Y_W, Z_W);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8);
+ buflen = snprintf(buffer, sizeof(buffer),
+ "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n",
+ X_R, Y_R, Z_R, X_G, Y_G, Z_G, X_B, Y_B, Z_B);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written +=
+ t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22);
+ }
+ written += t2pWriteFile(output, (tdata_t) ">>] \n", 5);
+
+ return (written);
}
/*
- This function writes a PDF Image XObject Colorspace array to output.
+ This function writes a PDF Image XObject Colorspace array to output.
*/
-tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){
+tsize_t t2p_write_pdf_xobject_icccs(T2P *t2p, TIFF *output)
+{
+
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
- tsize_t written=0;
- char buffer[32];
- int buflen=0;
-
- written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->pdf_icccs);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7);
+ written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->pdf_icccs);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7);
- return(written);
+ return (written);
}
-tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){
-
- tsize_t written=0;
- char buffer[32];
- int buflen=0;
-
- written += t2pWriteFile(output, (tdata_t) "/N ", 3);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu16" \n", t2p->tiff_samplesperpixel);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11);
- t2p->pdf_colorspace ^= T2P_CS_ICCBASED;
- written += t2p_write_pdf_xobject_cs(t2p, output);
- t2p->pdf_colorspace |= T2P_CS_ICCBASED;
- written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output);
-
- return(written);
+tsize_t t2p_write_pdf_xobject_icccs_dict(T2P *t2p, TIFF *output)
+{
+
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
+
+ written += t2pWriteFile(output, (tdata_t) "/N ", 3);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu16 " \n",
+ t2p->tiff_samplesperpixel);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11);
+ t2p->pdf_colorspace ^= T2P_CS_ICCBASED;
+ written += t2p_write_pdf_xobject_cs(t2p, output);
+ t2p->pdf_colorspace |= T2P_CS_ICCBASED;
+ written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output);
+
+ return (written);
}
-tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){
+tsize_t t2p_write_pdf_xobject_icccs_stream(T2P *t2p, TIFF *output)
+{
+
+ tsize_t written = 0;
- tsize_t written=0;
+ written +=
+ t2p_write_pdf_stream((tdata_t)t2p->tiff_iccprofile,
+ (tsize_t)t2p->tiff_iccprofilelength, output);
- written += t2p_write_pdf_stream(
- (tdata_t) t2p->tiff_iccprofile,
- (tsize_t) t2p->tiff_iccprofilelength,
- output);
-
- return(written);
+ return (written);
}
/*
- This function writes a palette stream for an indexed color space to output.
+ This function writes a palette stream for an indexed color space to
+ output.
*/
-tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){
+tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P *t2p, TIFF *output)
+{
+
+ tsize_t written = 0;
- tsize_t written=0;
+ written += t2p_write_pdf_stream((tdata_t)t2p->pdf_palette,
+ (tsize_t)t2p->pdf_palettesize, output);
- written += t2p_write_pdf_stream(
- (tdata_t) t2p->pdf_palette,
- (tsize_t) t2p->pdf_palettesize,
- output);
-
- return(written);
+ return (written);
}
/*
- This function writes a PDF Image XObject Decode array to output.
+ This function writes a PDF Image XObject Decode array to output.
*/
-tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){
+tsize_t t2p_write_pdf_xobject_decode(T2P *t2p, TIFF *output)
+{
- tsize_t written=0;
- int i=0;
+ tsize_t written = 0;
+ int i = 0;
- written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10);
- for (i=0;i<t2p->tiff_samplesperpixel;i++){
- written += t2pWriteFile(output, (tdata_t) "1 0 ", 4);
- }
- written += t2pWriteFile(output, (tdata_t) "]\n", 2);
+ written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10);
+ for (i = 0; i < t2p->tiff_samplesperpixel; i++)
+ {
+ written += t2pWriteFile(output, (tdata_t) "1 0 ", 4);
+ }
+ written += t2pWriteFile(output, (tdata_t) "]\n", 2);
- return(written);
+ return (written);
}
/*
- This function writes a PDF Image XObject stream filter name and parameters to
- output.
+ This function writes a PDF Image XObject stream filter name and
+ parameters to output.
*/
-tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){
-
- tsize_t written=0;
- char buffer[32];
- int buflen=0;
+tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P *t2p,
+ TIFF *output)
+{
- if(t2p->pdf_compression==T2P_COMPRESS_NONE){
- return(written);
- }
- written += t2pWriteFile(output, (tdata_t) "/Filter ", 8);
- switch(t2p->pdf_compression){
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
+
+ if (t2p->pdf_compression == T2P_COMPRESS_NONE)
+ {
+ return (written);
+ }
+ written += t2pWriteFile(output, (tdata_t) "/Filter ", 8);
+ switch (t2p->pdf_compression)
+ {
#ifdef CCITT_SUPPORT
- case T2P_COMPRESS_G4:
- written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16);
- written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
- written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9);
- if(tile==0){
- written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_width);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_length);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- } else {
- if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){
- written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- } else {
- written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- }
- if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){
- written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- } else {
- written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- }
- }
- if(t2p->pdf_switchdecode == 0){
- written += t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16);
- }
- written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
- break;
+ case T2P_COMPRESS_G4:
+ written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16);
+ written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
+ written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9);
+ if (tile == 0)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_width);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_length);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ }
+ else
+ {
+ if (t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page],
+ tile - 1) == 0)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
+ buflen = snprintf(
+ buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ }
+ else
+ {
+ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
+ buflen = snprintf(
+ buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ }
+ if (t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page],
+ tile - 1) == 0)
+ {
+ written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
+ buflen = snprintf(
+ buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ }
+ else
+ {
+ written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
+ buflen = snprintf(
+ buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ }
+ }
+ if (t2p->pdf_switchdecode == 0)
+ {
+ written +=
+ t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16);
+ }
+ written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
+ break;
#endif
#ifdef JPEG_SUPPORT
- case T2P_COMPRESS_JPEG:
- written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11);
-
- if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) {
- written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
- written += t2pWriteFile(output, (tdata_t) "<< /ColorTransform 1 >>\n", 24);
- }
- break;
+ case T2P_COMPRESS_JPEG:
+ written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11);
+
+ if (t2p->tiff_photometric != PHOTOMETRIC_YCBCR)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
+ written += t2pWriteFile(
+ output, (tdata_t) "<< /ColorTransform 1 >>\n", 24);
+ }
+ break;
#endif
#ifdef ZIP_SUPPORT
- case T2P_COMPRESS_ZIP:
- written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13);
- if(t2p->pdf_compressionquality%100){
- written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
- written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu16, (uint16_t)(t2p->pdf_compressionquality % 100u));
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " /Columns ", 10);
- buflen = snprintf(buffer, sizeof(buffer), "%"PRIu32,
- t2p->tiff_width);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " /Colors ", 9);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu16, t2p->tiff_samplesperpixel);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu16, t2p->tiff_bitspersample);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
- }
- break;
+ case T2P_COMPRESS_ZIP:
+ written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13);
+ if (t2p->pdf_compressionquality % 100)
+ {
+ written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
+ written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14);
+ buflen =
+ snprintf(buffer, sizeof(buffer), "%" PRIu16,
+ (uint16_t)(t2p->pdf_compressionquality % 100u));
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " /Columns ", 10);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32,
+ t2p->tiff_width);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " /Colors ", 9);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu16,
+ t2p->tiff_samplesperpixel);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written +=
+ t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu16,
+ t2p->tiff_bitspersample);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
+ }
+ break;
#endif
- default:
- break;
- }
+ default:
+ break;
+ }
- return(written);
+ return (written);
}
/*
- This function writes a PDF xref table to output.
+ This function writes a PDF xref table to output.
*/
-tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){
-
- tsize_t written=0;
- char buffer[64];
- int buflen=0;
- uint32_t i=0;
-
- written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->pdf_xrefcount + 1u);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22);
- for (i=0;i<t2p->pdf_xrefcount;i++){
- snprintf(buffer, sizeof(buffer), "%.10lu 00000 n \n",
- (unsigned long)t2p->pdf_xrefoffsets[i]);
- written += t2pWriteFile(output, (tdata_t) buffer, 20);
- }
-
- return(written);
+tsize_t t2p_write_pdf_xreftable(T2P *t2p, TIFF *output)
+{
+
+ tsize_t written = 0;
+ char buffer[64];
+ int buflen = 0;
+ uint32_t i = 0;
+
+ written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7);
+ buflen =
+ snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->pdf_xrefcount + 1u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22);
+ for (i = 0; i < t2p->pdf_xrefcount; i++)
+ {
+ snprintf(buffer, sizeof(buffer), "%.10lu 00000 n \n",
+ (unsigned long)t2p->pdf_xrefoffsets[i]);
+ written += t2pWriteFile(output, (tdata_t)buffer, 20);
+ }
+
+ return (written);
}
/*
* This function writes a PDF trailer to output.
*/
-tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output)
+tsize_t t2p_write_pdf_trailer(T2P *t2p, TIFF *output)
{
- tsize_t written = 0;
- char buffer[32];
- int buflen = 0;
- size_t i = 0;
-
- for (i = 0; i < sizeof(t2p->pdf_fileid) - 8; i += 8)
- snprintf(t2p->pdf_fileid + i, 9, "%.8X", rand());
-
- written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17);
- buflen = snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->pdf_xrefcount+1u);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->pdf_catalog);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->pdf_info);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11);
- written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid,
- sizeof(t2p->pdf_fileid) - 1);
- written += t2pWriteFile(output, (tdata_t) "><", 2);
- written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid,
- sizeof(t2p->pdf_fileid) - 1);
- written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16);
- buflen=snprintf(buffer, sizeof(buffer), "%"PRIu32, t2p->pdf_startxref);
- check_snprintf_ret(t2p, buflen, buffer);
- written += t2pWriteFile(output, (tdata_t) buffer, buflen);
- written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7);
-
- return(written);
+ tsize_t written = 0;
+ char buffer[32];
+ int buflen = 0;
+ size_t i = 0;
+
+ for (i = 0; i < sizeof(t2p->pdf_fileid) - 8; i += 8)
+ snprintf(t2p->pdf_fileid + i, 9, "%.8X", rand());
+
+ written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17);
+ buflen =
+ snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->pdf_xrefcount + 1u);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->pdf_catalog);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->pdf_info);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11);
+ written += t2pWriteFile(output, (tdata_t)t2p->pdf_fileid,
+ sizeof(t2p->pdf_fileid) - 1);
+ written += t2pWriteFile(output, (tdata_t) "><", 2);
+ written += t2pWriteFile(output, (tdata_t)t2p->pdf_fileid,
+ sizeof(t2p->pdf_fileid) - 1);
+ written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16);
+ buflen = snprintf(buffer, sizeof(buffer), "%" PRIu32, t2p->pdf_startxref);
+ check_snprintf_ret(t2p, buflen, buffer);
+ written += t2pWriteFile(output, (tdata_t)buffer, buflen);
+ written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7);
+
+ return (written);
}
-
+
/*
This function writes a PDF to a file given a pointer to a TIFF.
- The idea with using a TIFF* as output for a PDF file is that the file
- can be created with TIFFClientOpen for memory-mapped use within the TIFF
- library, and TIFFWriteEncodedStrip can be used to write compressed data to
- the output. The output is not actually a TIFF file, it is a PDF file.
+ The idea with using a TIFF* as output for a PDF file is that the file
+ can be created with TIFFClientOpen for memory-mapped use within the TIFF
+ library, and TIFFWriteEncodedStrip can be used to write compressed data to
+ the output. The output is not actually a TIFF file, it is a PDF file.
- This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to
- the output TIFF file. When libtiff would otherwise be writing data to the
- output file, the write procedure of the TIFF structure is replaced with an
+ This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to
+ the output TIFF file. When libtiff would otherwise be writing data to the
+ output file, the write procedure of the TIFF structure is replaced with an
empty implementation.
- The first argument to the function is an initialized and validated T2P
+ The first argument to the function is an initialized and validated T2P
context struct pointer.
- The second argument to the function is the TIFF* that is the input that has
+ The second argument to the function is the TIFF* that is the input that has
been opened for reading and no other functions have been called upon it.
- The third argument to the function is the TIFF* that is the output that has
- been opened for writing. It has to be opened so that it hasn't written any
- data to the output. If the output is seekable then it's OK to seek to the
- beginning of the file. The function only writes to the output PDF and does
+ The third argument to the function is the TIFF* that is the output that has
+ been opened for writing. It has to be opened so that it hasn't written any
+ data to the output. If the output is seekable then it's OK to seek to the
+ beginning of the file. The function only writes to the output PDF and does
not seek. See the example usage in the main() function.
- TIFF* output = TIFFOpen("output.pdf", "w");
- assert(output != NULL);
+ TIFF* output = TIFFOpen("output.pdf", "w");
+ assert(output != NULL);
- if(output->tif_seekproc != NULL){
- t2pSeekFile(output, (toff_t) 0, SEEK_SET);
- }
+ if(output->tif_seekproc != NULL){
+ t2pSeekFile(output, (toff_t) 0, SEEK_SET);
+ }
- This function returns the file size of the output PDF file. On error it
+ This function returns the file size of the output PDF file. On error it
returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR.
- After this function completes, call t2p_free on t2p, TIFFClose on input,
+ After this function completes, call t2p_free on t2p, TIFFClose on input,
and TIFFClose on output.
*/
-tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){
-
- tsize_t written=0;
- ttile_t i2=0;
- tsize_t streamlen=0;
- uint16_t i=0;
-
- t2p_read_tiff_init(t2p, input);
- if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
- t2p->pdf_xrefoffsets= (uint32_t*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t, t2p->pdf_xrefcount, sizeof(uint32_t)) );
- if(t2p->pdf_xrefoffsets==NULL){
- TIFFError(
- TIFF2PDF_MODULE,
- "Can't allocate %"TIFF_SIZE_FORMAT" bytes of memory for t2p_write_pdf",
- sizeof(uint32_t) * t2p->pdf_xrefcount);
- t2p->t2p_error = T2P_ERR_ERROR;
- return(written);
- }
- t2p->pdf_xrefcount=0;
- t2p->pdf_catalog=1;
- t2p->pdf_info=2;
- t2p->pdf_pages=3;
- written += t2p_write_pdf_header(t2p, output);
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- t2p->pdf_catalog=t2p->pdf_xrefcount;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_catalog(t2p, output);
- written += t2p_write_pdf_obj_end(output);
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- t2p->pdf_info=t2p->pdf_xrefcount;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_info(t2p, input, output);
- written += t2p_write_pdf_obj_end(output);
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- t2p->pdf_pages=t2p->pdf_xrefcount;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_pages(t2p, output);
- written += t2p_write_pdf_obj_end(output);
- for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){
- t2p_read_tiff_data(t2p, input);
- if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output);
- written += t2p_write_pdf_obj_end(output);
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_stream_dict_start(output);
- written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output);
- written += t2p_write_pdf_stream_dict_end(output);
- written += t2p_write_pdf_stream_start(output);
- streamlen=written;
- written += t2p_write_pdf_page_content_stream(t2p, output);
- streamlen=written-streamlen;
- written += t2p_write_pdf_stream_end(output);
- written += t2p_write_pdf_obj_end(output);
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_stream_length(streamlen, output);
- written += t2p_write_pdf_obj_end(output);
- if(t2p->tiff_transferfunctioncount != 0){
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_transfer(t2p, output);
- written += t2p_write_pdf_obj_end(output);
- for(i=0; i < t2p->tiff_transferfunctioncount; i++){
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_stream_dict_start(output);
- written += t2p_write_pdf_transfer_dict(t2p, output, i);
- written += t2p_write_pdf_stream_dict_end(output);
- written += t2p_write_pdf_stream_start(output);
- /* streamlen=written; */ /* value not used */
- written += t2p_write_pdf_transfer_stream(t2p, output, i);
- /* streamlen=written-streamlen; */ /* value not used */
- written += t2p_write_pdf_stream_end(output);
- written += t2p_write_pdf_obj_end(output);
- }
- }
- if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- t2p->pdf_palettecs=t2p->pdf_xrefcount;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_stream_dict_start(output);
- written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output);
- written += t2p_write_pdf_stream_dict_end(output);
- written += t2p_write_pdf_stream_start(output);
- /* streamlen=written; */ /* value not used */
- written += t2p_write_pdf_xobject_palettecs_stream(t2p, output);
- /* streamlen=written-streamlen; */ /* value not used */
- written += t2p_write_pdf_stream_end(output);
- written += t2p_write_pdf_obj_end(output);
- }
- if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- t2p->pdf_icccs=t2p->pdf_xrefcount;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_stream_dict_start(output);
- written += t2p_write_pdf_xobject_icccs_dict(t2p, output);
- written += t2p_write_pdf_stream_dict_end(output);
- written += t2p_write_pdf_stream_start(output);
- /* streamlen=written; */ /* value not used */
- written += t2p_write_pdf_xobject_icccs_stream(t2p, output);
- /* streamlen=written-streamlen; */ /* value not used */
- written += t2p_write_pdf_stream_end(output);
- written += t2p_write_pdf_obj_end(output);
- }
- if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){
- for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_stream_dict_start(output);
- written += t2p_write_pdf_xobject_stream_dict(
- i2+1,
- t2p,
- output);
- written += t2p_write_pdf_stream_dict_end(output);
- written += t2p_write_pdf_stream_start(output);
- streamlen=written;
- t2p_read_tiff_size_tile(t2p, input, i2);
- if (t2p->tiff_maxdatasize && (t2p->tiff_datasize > t2p->tiff_maxdatasize)) {
- TIFFError(TIFF2PDF_MODULE,
- "Allocation of %" PRIu64 " bytes is forbidden. Limit is %" PRIu64 ". Use -m option to change limit",
- (uint64_t)t2p->tiff_datasize, (uint64_t)t2p->tiff_maxdatasize);
- t2p->t2p_error = T2P_ERR_ERROR;
- return (0);
- }
- written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2);
- t2p_write_advance_directory(t2p, output);
- if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
- streamlen=written-streamlen;
- written += t2p_write_pdf_stream_end(output);
- written += t2p_write_pdf_obj_end(output);
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_stream_length(streamlen, output);
- written += t2p_write_pdf_obj_end(output);
- }
- } else {
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_stream_dict_start(output);
- written += t2p_write_pdf_xobject_stream_dict(
- 0,
- t2p,
- output);
- written += t2p_write_pdf_stream_dict_end(output);
- written += t2p_write_pdf_stream_start(output);
- streamlen=written;
- t2p_read_tiff_size(t2p, input);
- if (t2p->tiff_maxdatasize && (t2p->tiff_datasize > t2p->tiff_maxdatasize)) {
- TIFFError(TIFF2PDF_MODULE,
- "Allocation of %" PRIu64 " bytes is forbidden. Limit is %" PRIu64 ". Use -m option to change limit",
- (uint64_t)t2p->tiff_datasize, (uint64_t)t2p->tiff_maxdatasize);
- t2p->t2p_error = T2P_ERR_ERROR;
- return (0);
- }
- written += t2p_readwrite_pdf_image(t2p, input, output);
- t2p_write_advance_directory(t2p, output);
- if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
- streamlen=written-streamlen;
- written += t2p_write_pdf_stream_end(output);
- written += t2p_write_pdf_obj_end(output);
- t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
- written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
- written += t2p_write_pdf_stream_length(streamlen, output);
- written += t2p_write_pdf_obj_end(output);
- }
- }
- t2p->pdf_startxref = written;
- written += t2p_write_pdf_xreftable(t2p, output);
- written += t2p_write_pdf_trailer(t2p, output);
- t2p_disable(output);
-
- return(written);
+tsize_t t2p_write_pdf(T2P *t2p, TIFF *input, TIFF *output)
+{
+
+ tsize_t written = 0;
+ ttile_t i2 = 0;
+ tsize_t streamlen = 0;
+ uint16_t i = 0;
+
+ t2p_read_tiff_init(t2p, input);
+ if (t2p->t2p_error != T2P_ERR_OK)
+ {
+ return (0);
+ }
+ t2p->pdf_xrefoffsets = (uint32_t *)_TIFFmalloc(
+ TIFFSafeMultiply(tmsize_t, t2p->pdf_xrefcount, sizeof(uint32_t)));
+ if (t2p->pdf_xrefoffsets == NULL)
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Can't allocate %" TIFF_SIZE_FORMAT
+ " bytes of memory for t2p_write_pdf",
+ sizeof(uint32_t) * t2p->pdf_xrefcount);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (written);
+ }
+ t2p->pdf_xrefcount = 0;
+ t2p->pdf_catalog = 1;
+ t2p->pdf_info = 2;
+ t2p->pdf_pages = 3;
+ written += t2p_write_pdf_header(t2p, output);
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ t2p->pdf_catalog = t2p->pdf_xrefcount;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_catalog(t2p, output);
+ written += t2p_write_pdf_obj_end(output);
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ t2p->pdf_info = t2p->pdf_xrefcount;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_info(t2p, input, output);
+ written += t2p_write_pdf_obj_end(output);
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ t2p->pdf_pages = t2p->pdf_xrefcount;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_pages(t2p, output);
+ written += t2p_write_pdf_obj_end(output);
+ for (t2p->pdf_page = 0; t2p->pdf_page < t2p->tiff_pagecount;
+ t2p->pdf_page++)
+ {
+ t2p_read_tiff_data(t2p, input);
+ if (t2p->t2p_error != T2P_ERR_OK)
+ {
+ return (0);
+ }
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output);
+ written += t2p_write_pdf_obj_end(output);
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_stream_dict_start(output);
+ written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount + 1, output);
+ written += t2p_write_pdf_stream_dict_end(output);
+ written += t2p_write_pdf_stream_start(output);
+ streamlen = written;
+ written += t2p_write_pdf_page_content_stream(t2p, output);
+ streamlen = written - streamlen;
+ written += t2p_write_pdf_stream_end(output);
+ written += t2p_write_pdf_obj_end(output);
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_stream_length(streamlen, output);
+ written += t2p_write_pdf_obj_end(output);
+ if (t2p->tiff_transferfunctioncount != 0)
+ {
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_transfer(t2p, output);
+ written += t2p_write_pdf_obj_end(output);
+ for (i = 0; i < t2p->tiff_transferfunctioncount; i++)
+ {
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_stream_dict_start(output);
+ written += t2p_write_pdf_transfer_dict(t2p, output, i);
+ written += t2p_write_pdf_stream_dict_end(output);
+ written += t2p_write_pdf_stream_start(output);
+ /* streamlen=written; */ /* value not used */
+ written += t2p_write_pdf_transfer_stream(t2p, output, i);
+ /* streamlen=written-streamlen; */ /* value not used */
+ written += t2p_write_pdf_stream_end(output);
+ written += t2p_write_pdf_obj_end(output);
+ }
+ }
+ if ((t2p->pdf_colorspace & T2P_CS_PALETTE) != 0)
+ {
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ t2p->pdf_palettecs = t2p->pdf_xrefcount;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_stream_dict_start(output);
+ written +=
+ t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output);
+ written += t2p_write_pdf_stream_dict_end(output);
+ written += t2p_write_pdf_stream_start(output);
+ /* streamlen=written; */ /* value not used */
+ written += t2p_write_pdf_xobject_palettecs_stream(t2p, output);
+ /* streamlen=written-streamlen; */ /* value not used */
+ written += t2p_write_pdf_stream_end(output);
+ written += t2p_write_pdf_obj_end(output);
+ }
+ if ((t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0)
+ {
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ t2p->pdf_icccs = t2p->pdf_xrefcount;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_stream_dict_start(output);
+ written += t2p_write_pdf_xobject_icccs_dict(t2p, output);
+ written += t2p_write_pdf_stream_dict_end(output);
+ written += t2p_write_pdf_stream_start(output);
+ /* streamlen=written; */ /* value not used */
+ written += t2p_write_pdf_xobject_icccs_stream(t2p, output);
+ /* streamlen=written-streamlen; */ /* value not used */
+ written += t2p_write_pdf_stream_end(output);
+ written += t2p_write_pdf_obj_end(output);
+ }
+ if (t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0)
+ {
+ for (i2 = 0; i2 < t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;
+ i2++)
+ {
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_stream_dict_start(output);
+ written +=
+ t2p_write_pdf_xobject_stream_dict(i2 + 1, t2p, output);
+ written += t2p_write_pdf_stream_dict_end(output);
+ written += t2p_write_pdf_stream_start(output);
+ streamlen = written;
+ t2p_read_tiff_size_tile(t2p, input, i2);
+ if (t2p->tiff_maxdatasize &&
+ (t2p->tiff_datasize > t2p->tiff_maxdatasize))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Allocation of %" PRIu64
+ " bytes is forbidden. Limit is %" PRIu64
+ ". Use -m option to change limit",
+ (uint64_t)t2p->tiff_datasize,
+ (uint64_t)t2p->tiff_maxdatasize);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2);
+ t2p_write_advance_directory(t2p, output);
+ if (t2p->t2p_error != T2P_ERR_OK)
+ {
+ return (0);
+ }
+ streamlen = written - streamlen;
+ written += t2p_write_pdf_stream_end(output);
+ written += t2p_write_pdf_obj_end(output);
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_stream_length(streamlen, output);
+ written += t2p_write_pdf_obj_end(output);
+ }
+ }
+ else
+ {
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_stream_dict_start(output);
+ written += t2p_write_pdf_xobject_stream_dict(0, t2p, output);
+ written += t2p_write_pdf_stream_dict_end(output);
+ written += t2p_write_pdf_stream_start(output);
+ streamlen = written;
+ t2p_read_tiff_size(t2p, input);
+ if (t2p->tiff_maxdatasize &&
+ (t2p->tiff_datasize > t2p->tiff_maxdatasize))
+ {
+ TIFFError(TIFF2PDF_MODULE,
+ "Allocation of %" PRIu64
+ " bytes is forbidden. Limit is %" PRIu64
+ ". Use -m option to change limit",
+ (uint64_t)t2p->tiff_datasize,
+ (uint64_t)t2p->tiff_maxdatasize);
+ t2p->t2p_error = T2P_ERR_ERROR;
+ return (0);
+ }
+ written += t2p_readwrite_pdf_image(t2p, input, output);
+ t2p_write_advance_directory(t2p, output);
+ if (t2p->t2p_error != T2P_ERR_OK)
+ {
+ return (0);
+ }
+ streamlen = written - streamlen;
+ written += t2p_write_pdf_stream_end(output);
+ written += t2p_write_pdf_obj_end(output);
+ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++] = written;
+ written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
+ written += t2p_write_pdf_stream_length(streamlen, output);
+ written += t2p_write_pdf_obj_end(output);
+ }
+ }
+ t2p->pdf_startxref = written;
+ written += t2p_write_pdf_xreftable(t2p, output);
+ written += t2p_write_pdf_trailer(t2p, output);
+ t2p_disable(output);
+
+ return (written);
}
diff --git a/tools/tiff2ps.c b/tools/tiff2ps.c
index 0d1656b9..541495d2 100644
--- a/tools/tiff2ps.c
+++ b/tools/tiff2ps.c
@@ -2,37 +2,37 @@
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
-#include <stdio.h>
-#include <stdlib.h> /* for atof */
#include <math.h>
-#include <time.h>
+#include <stdio.h>
+#include <stdlib.h> /* for atof */
#include <string.h>
+#include <time.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#include "tiffio.h"
@@ -88,7 +88,7 @@
* -H was not handled properly if -h and/or -w were specified.
* It should only clip the masked images if the scaled image
* exceeds the maxPageHeight specified with -H.
- *
+ *
* New design allows for all of the following combinations:
* Conversion of TIFF to Postscript with optional rotations
* of 90, 180, 270, or auto degrees counterclockwise
@@ -99,7 +99,7 @@
* viewport to height specified with -H, producing multiple
* pages at this height and original width as needed.
* Same rotations apply.
- * Conversion of TIFF to Postscript with image scaled to
+ * Conversion of TIFF to Postscript with image scaled to
* maximum specified by -h and -w and the resulting scaled
* image is presented in an output viewport clipped by -H height.
* The same rotations apply.
@@ -168,11 +168,11 @@
* routine. So user beware, you have been warned!
*/
-#define EXP_ASCII85ENCODER
+#define EXP_ASCII85ENCODER
#ifndef TRUE
-#define TRUE 1
-#define FALSE 0
+#define TRUE 1
+#define FALSE 0
#endif
#define DEFAULT_MAX_MALLOC (256 * 1024 * 1024)
@@ -181,430 +181,470 @@
* disabled when set to 0 */
static tmsize_t maxMalloc = DEFAULT_MAX_MALLOC;
-int ascii85 = FALSE; /* use ASCII85 encoding */
-int interpolate = TRUE; /* interpolate level2 image */
-int level2 = FALSE; /* generate PostScript level 2 */
-int level3 = FALSE; /* generate PostScript level 3 */
-int printAll = FALSE; /* print all images in file */
-int generateEPSF = TRUE; /* generate Encapsulated PostScript */
-int PSduplex = FALSE; /* enable duplex printing */
-int PStumble = FALSE; /* enable top edge binding */
-int PSavoiddeadzone = TRUE; /* enable avoiding printer deadzone */
-double maxPageHeight = 0; /* maximum height to select from image and print per page */
-double maxPageWidth = 0; /* maximum width to select from image and print per page */
-double splitOverlap = 0; /* amount for split pages to overlag */
-int rotation = 0; /* optional value for rotation angle */
-int auto_rotate = 0; /* rotate image for best fit on the page */
-char *filename = NULL; /* input filename */
-char *title = NULL; /* optional document title string */
-char *creator = NULL; /* optional document creator string */
-char pageOrientation[12]; /* set optional PageOrientation DSC to Landscape or Portrait */
-int useImagemask = FALSE; /* Use imagemask instead of image operator */
-uint16_t res_unit = 0; /* Resolution units: 2 - inches, 3 - cm */
+int ascii85 = FALSE; /* use ASCII85 encoding */
+int interpolate = TRUE; /* interpolate level2 image */
+int level2 = FALSE; /* generate PostScript level 2 */
+int level3 = FALSE; /* generate PostScript level 3 */
+int printAll = FALSE; /* print all images in file */
+int generateEPSF = TRUE; /* generate Encapsulated PostScript */
+int PSduplex = FALSE; /* enable duplex printing */
+int PStumble = FALSE; /* enable top edge binding */
+int PSavoiddeadzone = TRUE; /* enable avoiding printer deadzone */
+double maxPageHeight =
+ 0; /* maximum height to select from image and print per page */
+double maxPageWidth =
+ 0; /* maximum width to select from image and print per page */
+double splitOverlap = 0; /* amount for split pages to overlag */
+int rotation = 0; /* optional value for rotation angle */
+int auto_rotate = 0; /* rotate image for best fit on the page */
+char *filename = NULL; /* input filename */
+char *title = NULL; /* optional document title string */
+char *creator = NULL; /* optional document creator string */
+char pageOrientation[12]; /* set optional PageOrientation DSC to Landscape or
+ Portrait */
+int useImagemask = FALSE; /* Use imagemask instead of image operator */
+uint16_t res_unit = 0; /* Resolution units: 2 - inches, 3 - cm */
/*
* ASCII85 Encoding Support.
*/
unsigned char ascii85buf[10];
-int ascii85count;
-int ascii85breaklen;
-
-int TIFF2PS(FILE*, TIFF*, double, double, double, double, int);
-void PSpage(FILE*, TIFF*, uint32_t, uint32_t);
-void PSColorContigPreamble(FILE*, uint32_t, uint32_t, int);
-void PSColorSeparatePreamble(FILE*, uint32_t, uint32_t, int);
-void PSDataColorContig(FILE*, TIFF*, uint32_t, uint32_t, int);
-void PSDataColorSeparate(FILE*, TIFF*, uint32_t, uint32_t, int);
-void PSDataPalette(FILE*, TIFF*, uint32_t, uint32_t);
-void PSDataBW(FILE*, TIFF*, uint32_t, uint32_t);
-void PSRawDataBW(FILE*, TIFF*, uint32_t, uint32_t);
-void Ascii85Init(void);
-void Ascii85Put(unsigned char code, FILE* fd);
-void Ascii85Flush(FILE* fd);
-void PSHead(FILE*, double, double, double, double);
-void PSTail(FILE*, int);
-int psStart(FILE *, int, int, int *, double *, double, double, double,
- double, double, double, double, double, double, double);
-int psPageSize(FILE *, int, double, double, double, double, double, double);
-int psRotateImage(FILE *, int, double, double, double, double);
-int psMaskImage(FILE *, TIFF *, int, int, int *, double, double,
- double, double, double, double, double, double, double);
-int psScaleImage(FILE *, double, int, int, double, double, double, double,
- double, double);
-int get_viewport (double, double, double, double, double *, double *, int);
-int exportMaskedImage(FILE *, double, double, double, double, int, int,
- double, double, double, int, int);
-
-#if defined( EXP_ASCII85ENCODER)
-tsize_t Ascii85EncodeBlock(uint8_t * ascii85_p, unsigned f_eod, const uint8_t * raw_p, tsize_t raw_l );
+int ascii85count;
+int ascii85breaklen;
+
+int TIFF2PS(FILE *, TIFF *, double, double, double, double, int);
+void PSpage(FILE *, TIFF *, uint32_t, uint32_t);
+void PSColorContigPreamble(FILE *, uint32_t, uint32_t, int);
+void PSColorSeparatePreamble(FILE *, uint32_t, uint32_t, int);
+void PSDataColorContig(FILE *, TIFF *, uint32_t, uint32_t, int);
+void PSDataColorSeparate(FILE *, TIFF *, uint32_t, uint32_t, int);
+void PSDataPalette(FILE *, TIFF *, uint32_t, uint32_t);
+void PSDataBW(FILE *, TIFF *, uint32_t, uint32_t);
+void PSRawDataBW(FILE *, TIFF *, uint32_t, uint32_t);
+void Ascii85Init(void);
+void Ascii85Put(unsigned char code, FILE *fd);
+void Ascii85Flush(FILE *fd);
+void PSHead(FILE *, double, double, double, double);
+void PSTail(FILE *, int);
+int psStart(FILE *, int, int, int *, double *, double, double, double, double,
+ double, double, double, double, double, double);
+int psPageSize(FILE *, int, double, double, double, double, double, double);
+int psRotateImage(FILE *, int, double, double, double, double);
+int psMaskImage(FILE *, TIFF *, int, int, int *, double, double, double, double,
+ double, double, double, double, double);
+int psScaleImage(FILE *, double, int, int, double, double, double, double,
+ double, double);
+int get_viewport(double, double, double, double, double *, double *, int);
+int exportMaskedImage(FILE *, double, double, double, double, int, int, double,
+ double, double, int, int);
+
+#if defined(EXP_ASCII85ENCODER)
+tsize_t Ascii85EncodeBlock(uint8_t *ascii85_p, unsigned f_eod,
+ const uint8_t *raw_p, tsize_t raw_l);
#endif
-static void usage(int);
+static void usage(int);
/**
* This custom malloc function enforce a maximum allocation size
*/
-static void* limitMalloc(tmsize_t s)
+static void *limitMalloc(tmsize_t s)
{
- /* tmsize_t is signed and _TIFFmalloc() converts s to size_t. Therefore check for negative s. */
- if (maxMalloc && ((s > maxMalloc) || (s < 0))) {
- fprintf(stderr, "MemoryLimitError: allocation of %" TIFF_SSIZE_FORMAT " bytes is forbidden. Limit is %" TIFF_SSIZE_FORMAT ".\n",
+ /* tmsize_t is signed and _TIFFmalloc() converts s to size_t. Therefore
+ * check for negative s. */
+ if (maxMalloc && ((s > maxMalloc) || (s < 0)))
+ {
+ fprintf(stderr,
+ "MemoryLimitError: allocation of %" TIFF_SSIZE_FORMAT
+ " bytes is forbidden. Limit is %" TIFF_SSIZE_FORMAT ".\n",
s, maxMalloc);
- fprintf(stderr, " use -M option to change limit.\n");
- return NULL;
- }
- return _TIFFmalloc(s);
+ fprintf(stderr, " use -M option to change limit.\n");
+ return NULL;
+ }
+ return _TIFFmalloc(s);
}
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- int dirnum = -1, c, np = 0;
- int centered = 0;
- double bottommargin = 0;
- double leftmargin = 0;
- double pageWidth = 0;
- double pageHeight = 0;
- uint32_t diroff = 0;
+ int dirnum = -1, c, np = 0;
+ int centered = 0;
+ double bottommargin = 0;
+ double leftmargin = 0;
+ double pageWidth = 0;
+ double pageHeight = 0;
+ uint32_t diroff = 0;
#if !HAVE_DECL_OPTARG
- extern char *optarg;
- extern int optind;
+ extern char *optarg;
+ extern int optind;
#endif
- FILE* output = stdout;
-
- pageOrientation[0] = '\0';
-
- while ((c = getopt(argc, argv, "b:d:h:H:W:L:M:i:w:l:o:O:P:C:r:t:acemxyzps1238DT")) != -1)
- switch (c) {
- case 'M':
- maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
- break;
- case 'b':
- bottommargin = atof(optarg);
- break;
- case 'c':
- centered = 1;
- break;
- case 'C':
- creator = optarg;
- break;
- case 'd': /* without -a, this only processes one image at this IFD */
- dirnum = atoi(optarg);
- break;
- case 'D':
- PSduplex = TRUE;
- break;
- case 'i':
- interpolate = atoi(optarg) ? TRUE:FALSE;
- break;
- case 'T':
- PStumble = TRUE;
- break;
- case 'e':
- PSavoiddeadzone = FALSE;
- generateEPSF = TRUE;
- break;
- case 'h':
- pageHeight = atof(optarg);
- break;
- case 'H':
- maxPageHeight = atof(optarg);
- break;
- case 'W':
- maxPageWidth = atof(optarg);
- break;
- case 'L':
- splitOverlap = atof(optarg);
- break;
- case 'm':
- useImagemask = TRUE;
- break;
- case 'o':
- switch (optarg[0])
- {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9': diroff = (uint32_t) strtoul(optarg, NULL, 0);
- break;
- default: TIFFError ("-o", "Offset must be a numeric value.");
- exit (EXIT_FAILURE);
- }
- break;
- case 'O': /* XXX too bad -o is already taken */
- output = fopen(optarg, "w");
- if (output == NULL) {
- fprintf(stderr,
- "%s: %s: Cannot open output file.\n",
- argv[0], optarg);
- exit (EXIT_FAILURE);
- }
- break;
- case 'P':
- switch (optarg[0])
- {
- case 'l':
- case 'L': strcpy (pageOrientation, "Landscape");
- break;
- case 'p':
- case 'P': strcpy (pageOrientation, "Portrait");
- break;
- default: TIFFError ("-P", "Page orientation must be Landscape or Portrait");
- exit (EXIT_FAILURE);
- }
- break;
- case 'l':
- leftmargin = atof(optarg);
- break;
- case 'a': /* removed fall through to generate warning below, R Nolde 09-01-2010 */
- printAll = TRUE;
- break;
- case 'p':
- generateEPSF = FALSE;
- break;
- case 'r':
- if (strcmp (optarg, "auto") == 0)
- {
- rotation = 0;
- auto_rotate = TRUE;
- }
- else
- {
- rotation = atoi(optarg);
- auto_rotate = FALSE;
- }
- switch (rotation)
- {
- case 0:
- case 90:
- case 180:
- case 270:
- break;
- default:
- fprintf (stderr, "Rotation angle must be 90, 180, 270 (degrees ccw) or auto\n");
- exit (EXIT_FAILURE);
- }
- break;
- case 's':
- printAll = FALSE;
- break;
- case 't':
- title = optarg;
+ FILE *output = stdout;
+
+ pageOrientation[0] = '\0';
+
+ while ((c = getopt(argc, argv,
+ "b:d:h:H:W:L:M:i:w:l:o:O:P:C:r:t:acemxyzps1238DT")) !=
+ -1)
+ switch (c)
+ {
+ case 'M':
+ maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
+ break;
+ case 'b':
+ bottommargin = atof(optarg);
+ break;
+ case 'c':
+ centered = 1;
+ break;
+ case 'C':
+ creator = optarg;
+ break;
+ case 'd': /* without -a, this only processes one image at this IFD
+ */
+ dirnum = atoi(optarg);
+ break;
+ case 'D':
+ PSduplex = TRUE;
+ break;
+ case 'i':
+ interpolate = atoi(optarg) ? TRUE : FALSE;
+ break;
+ case 'T':
+ PStumble = TRUE;
+ break;
+ case 'e':
+ PSavoiddeadzone = FALSE;
+ generateEPSF = TRUE;
+ break;
+ case 'h':
+ pageHeight = atof(optarg);
+ break;
+ case 'H':
+ maxPageHeight = atof(optarg);
+ break;
+ case 'W':
+ maxPageWidth = atof(optarg);
+ break;
+ case 'L':
+ splitOverlap = atof(optarg);
+ break;
+ case 'm':
+ useImagemask = TRUE;
+ break;
+ case 'o':
+ switch (optarg[0])
+ {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ diroff = (uint32_t)strtoul(optarg, NULL, 0);
+ break;
+ default:
+ TIFFError("-o", "Offset must be a numeric value.");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'O': /* XXX too bad -o is already taken */
+ output = fopen(optarg, "w");
+ if (output == NULL)
+ {
+ fprintf(stderr, "%s: %s: Cannot open output file.\n",
+ argv[0], optarg);
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'P':
+ switch (optarg[0])
+ {
+ case 'l':
+ case 'L':
+ strcpy(pageOrientation, "Landscape");
+ break;
+ case 'p':
+ case 'P':
+ strcpy(pageOrientation, "Portrait");
+ break;
+ default:
+ TIFFError(
+ "-P",
+ "Page orientation must be Landscape or Portrait");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'l':
+ leftmargin = atof(optarg);
+ break;
+ case 'a': /* removed fall through to generate warning below, R Nolde
+ 09-01-2010 */
+ printAll = TRUE;
+ break;
+ case 'p':
+ generateEPSF = FALSE;
+ break;
+ case 'r':
+ if (strcmp(optarg, "auto") == 0)
+ {
+ rotation = 0;
+ auto_rotate = TRUE;
+ }
+ else
+ {
+ rotation = atoi(optarg);
+ auto_rotate = FALSE;
+ }
+ switch (rotation)
+ {
+ case 0:
+ case 90:
+ case 180:
+ case 270:
break;
- case 'w':
- pageWidth = atof(optarg);
- break;
- case 'z':
- PSavoiddeadzone = FALSE;
- break;
- case '1':
- level2 = FALSE;
- level3 = FALSE;
- ascii85 = FALSE;
- break;
- case '2':
- level2 = TRUE;
- ascii85 = TRUE; /* default to yes */
- break;
- case '3':
- level3 = TRUE;
- ascii85 = TRUE; /* default to yes */
- break;
- case '8':
- ascii85 = FALSE;
- break;
- case 'x':
- res_unit = RESUNIT_CENTIMETER;
- break;
- case 'y':
- res_unit = RESUNIT_INCH;
- break;
- case '?':
- usage(EXIT_FAILURE);
- }
-
- if (useImagemask == TRUE)
- {
- if ((level2 == FALSE) && (level3 == FALSE))
+ default:
+ fprintf(stderr, "Rotation angle must be 90, 180, 270 "
+ "(degrees ccw) or auto\n");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 's':
+ printAll = FALSE;
+ break;
+ case 't':
+ title = optarg;
+ break;
+ case 'w':
+ pageWidth = atof(optarg);
+ break;
+ case 'z':
+ PSavoiddeadzone = FALSE;
+ break;
+ case '1':
+ level2 = FALSE;
+ level3 = FALSE;
+ ascii85 = FALSE;
+ break;
+ case '2':
+ level2 = TRUE;
+ ascii85 = TRUE; /* default to yes */
+ break;
+ case '3':
+ level3 = TRUE;
+ ascii85 = TRUE; /* default to yes */
+ break;
+ case '8':
+ ascii85 = FALSE;
+ break;
+ case 'x':
+ res_unit = RESUNIT_CENTIMETER;
+ break;
+ case 'y':
+ res_unit = RESUNIT_INCH;
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ }
+
+ if (useImagemask == TRUE)
+ {
+ if ((level2 == FALSE) && (level3 == FALSE))
+ {
+ TIFFError(
+ "-m ",
+ " imagemask operator requires Postscript Level2 or Level3");
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ if (pageWidth && (maxPageWidth > pageWidth))
+ {
+ TIFFError("-W", "Max viewport width cannot exceed page width");
+ exit(EXIT_FAILURE);
+ }
+
+ /* auto rotate requires a specified page width and height */
+ if (auto_rotate == TRUE)
+ {
+ /*
+ if ((pageWidth == 0) || (pageHeight == 0))
+ TIFFWarning ("-r auto", " requires page height and width specified with
+ -h and -w");
+ */
+ if ((maxPageWidth > 0) || (maxPageHeight > 0))
+ {
+ TIFFError("-r auto", " is incompatible with maximum page "
+ "width/height specified by -H or -W");
+ exit(EXIT_FAILURE);
+ }
+ }
+ if ((maxPageWidth > 0) && (maxPageHeight > 0))
+ {
+ TIFFError("-H and -W",
+ " Use only one of -H or -W to define a viewport");
+ exit(EXIT_FAILURE);
+ }
+
+ if ((generateEPSF == TRUE) && (printAll == TRUE))
+ {
+ TIFFError(" -e and -a", "Warning: Cannot generate Encapsulated "
+ "Postscript for multiple images");
+ generateEPSF = FALSE;
+ }
+
+ if ((generateEPSF == TRUE) && (PSduplex == TRUE))
+ {
+ TIFFError(
+ " -e and -D",
+ "Warning: Encapsulated Postscript does not support Duplex option");
+ PSduplex = FALSE;
+ }
+
+ if ((generateEPSF == TRUE) && (PStumble == TRUE))
+ {
+ TIFFError(" -e and -T", "Warning: Encapsulated Postscript does not "
+ "support Top Edge Binding option");
+ PStumble = FALSE;
+ }
+
+ if ((generateEPSF == TRUE) && (PSavoiddeadzone == TRUE))
+ PSavoiddeadzone = FALSE;
+
+ for (; argc - optind > 0; optind++)
+ {
+ TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
+ if (opts == NULL)
+ {
+ return EXIT_FAILURE;
+ }
+ TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
+ TIFF *tif = TIFFOpenExt(filename = argv[optind], "r", opts);
+ TIFFOpenOptionsFree(opts);
+ if (tif != NULL)
+ {
+ if (dirnum != -1 && !TIFFSetDirectory(tif, (tdir_t)dirnum))
{
- TIFFError ("-m "," imagemask operator requires Postscript Level2 or Level3");
- exit (EXIT_FAILURE);
+ TIFFClose(tif);
+ return (EXIT_FAILURE);
}
- }
-
- if (pageWidth && (maxPageWidth > pageWidth))
- {
- TIFFError ("-W", "Max viewport width cannot exceed page width");
- exit (EXIT_FAILURE);
- }
-
- /* auto rotate requires a specified page width and height */
- if (auto_rotate == TRUE)
- {
- /*
- if ((pageWidth == 0) || (pageHeight == 0))
- TIFFWarning ("-r auto", " requires page height and width specified with -h and -w");
- */
- if ((maxPageWidth > 0) || (maxPageHeight > 0))
+ else if (diroff != 0 && !TIFFSetSubDirectory(tif, diroff))
{
- TIFFError ("-r auto", " is incompatible with maximum page width/height specified by -H or -W");
- exit (EXIT_FAILURE);
+ TIFFClose(tif);
+ return (EXIT_FAILURE);
}
- }
- if ((maxPageWidth > 0) && (maxPageHeight > 0))
+ np = TIFF2PS(output, tif, pageWidth, pageHeight, leftmargin,
+ bottommargin, centered);
+ if (np < 0)
{
- TIFFError ("-H and -W", " Use only one of -H or -W to define a viewport");
- exit (EXIT_FAILURE);
+ TIFFError("Error", "Unable to process %s", filename);
}
-
- if ((generateEPSF == TRUE) && (printAll == TRUE))
- {
- TIFFError(" -e and -a", "Warning: Cannot generate Encapsulated Postscript for multiple images");
- generateEPSF = FALSE;
- }
-
- if ((generateEPSF == TRUE) && (PSduplex == TRUE))
- {
- TIFFError(" -e and -D", "Warning: Encapsulated Postscript does not support Duplex option");
- PSduplex = FALSE;
- }
-
- if ((generateEPSF == TRUE) && (PStumble == TRUE))
- {
- TIFFError(" -e and -T", "Warning: Encapsulated Postscript does not support Top Edge Binding option");
- PStumble = FALSE;
- }
-
- if ((generateEPSF == TRUE) && (PSavoiddeadzone == TRUE))
- PSavoiddeadzone = FALSE;
-
- for (; argc - optind > 0; optind++) {
- TIFFOpenOptions* opts = TIFFOpenOptionsAlloc();
- if (opts == NULL) {
- return EXIT_FAILURE;
- }
- TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
- TIFF* tif = TIFFOpenExt(filename = argv[optind], "r", opts);
- TIFFOpenOptionsFree(opts);
- if (tif != NULL) {
- if (dirnum != -1
- && !TIFFSetDirectory(tif, (tdir_t)dirnum))
- {
- TIFFClose(tif);
- return (EXIT_FAILURE);
- }
- else if (diroff != 0 &&
- !TIFFSetSubDirectory(tif, diroff))
- {
- TIFFClose(tif);
- return (EXIT_FAILURE);
- }
- np = TIFF2PS(output, tif, pageWidth, pageHeight,
- leftmargin, bottommargin, centered);
- if (np < 0)
- {
- TIFFError("Error", "Unable to process %s", filename);
- }
- TIFFClose(tif);
- }
- }
- if (np)
- PSTail(output, np);
- else
- usage(EXIT_FAILURE);
- if (output != stdout)
- fclose(output);
- return (EXIT_SUCCESS);
+ TIFFClose(tif);
+ }
+ }
+ if (np)
+ PSTail(output, np);
+ else
+ usage(EXIT_FAILURE);
+ if (output != stdout)
+ fclose(output);
+ return (EXIT_SUCCESS);
}
-static uint16_t samplesperpixel;
-static uint16_t bitspersample;
-static uint16_t planarconfiguration;
-static uint16_t photometric;
-static uint16_t compression;
-static uint16_t extrasamples;
-static int alpha;
+static uint16_t samplesperpixel;
+static uint16_t bitspersample;
+static uint16_t planarconfiguration;
+static uint16_t photometric;
+static uint16_t compression;
+static uint16_t extrasamples;
+static int alpha;
-static int
-checkImage(TIFF* tif)
+static int checkImage(TIFF *tif)
{
- switch (photometric) {
- case PHOTOMETRIC_YCBCR:
- if ((compression == COMPRESSION_JPEG || compression == COMPRESSION_OJPEG)
- && planarconfiguration == PLANARCONFIG_CONTIG) {
- /* can rely on libjpeg to convert to RGB */
- TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE,
- JPEGCOLORMODE_RGB);
- photometric = PHOTOMETRIC_RGB;
- } else {
- if (level2 || level3)
- break;
- TIFFError(filename, "Can not handle image with %s",
- "PhotometricInterpretation=YCbCr");
- return (0);
- }
- /* fall through... */
- case PHOTOMETRIC_RGB:
- if (alpha && bitspersample != 8) {
- TIFFError(filename,
- "Can not handle %"PRIu16"-bit/sample RGB image with alpha",
- bitspersample);
- return (0);
- }
- /* fall through... */
- case PHOTOMETRIC_SEPARATED:
- case PHOTOMETRIC_PALETTE:
- case PHOTOMETRIC_MINISBLACK:
- case PHOTOMETRIC_MINISWHITE:
- break;
- case PHOTOMETRIC_LOGL:
- case PHOTOMETRIC_LOGLUV:
- if (compression != COMPRESSION_SGILOG &&
- compression != COMPRESSION_SGILOG24) {
- TIFFError(filename,
- "Can not handle %s data with compression other than SGILog",
- (photometric == PHOTOMETRIC_LOGL) ?
- "LogL" : "LogLuv"
- );
- return (0);
- }
- /* rely on library to convert to RGB/greyscale */
- TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT);
- photometric = (photometric == PHOTOMETRIC_LOGL) ?
- PHOTOMETRIC_MINISBLACK : PHOTOMETRIC_RGB;
- bitspersample = 8;
- break;
- case PHOTOMETRIC_CIELAB:
- /* fall through... */
- default:
- TIFFError(filename,
- "Can not handle image with PhotometricInterpretation=%"PRIu16,
- photometric);
- return (0);
- }
- switch (bitspersample) {
- case 1: case 2:
- case 4: case 8:
- case 16:
- break;
- default:
- TIFFError(filename, "Can not handle %"PRIu16"-bit/sample image",
- bitspersample);
- return (0);
- }
- if (planarconfiguration == PLANARCONFIG_SEPARATE && extrasamples > 0)
- TIFFWarning(filename, "Ignoring extra samples");
- return (1);
+ switch (photometric)
+ {
+ case PHOTOMETRIC_YCBCR:
+ if ((compression == COMPRESSION_JPEG ||
+ compression == COMPRESSION_OJPEG) &&
+ planarconfiguration == PLANARCONFIG_CONTIG)
+ {
+ /* can rely on libjpeg to convert to RGB */
+ TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
+ photometric = PHOTOMETRIC_RGB;
+ }
+ else
+ {
+ if (level2 || level3)
+ break;
+ TIFFError(filename, "Can not handle image with %s",
+ "PhotometricInterpretation=YCbCr");
+ return (0);
+ }
+ /* fall through... */
+ case PHOTOMETRIC_RGB:
+ if (alpha && bitspersample != 8)
+ {
+ TIFFError(filename,
+ "Can not handle %" PRIu16
+ "-bit/sample RGB image with alpha",
+ bitspersample);
+ return (0);
+ }
+ /* fall through... */
+ case PHOTOMETRIC_SEPARATED:
+ case PHOTOMETRIC_PALETTE:
+ case PHOTOMETRIC_MINISBLACK:
+ case PHOTOMETRIC_MINISWHITE:
+ break;
+ case PHOTOMETRIC_LOGL:
+ case PHOTOMETRIC_LOGLUV:
+ if (compression != COMPRESSION_SGILOG &&
+ compression != COMPRESSION_SGILOG24)
+ {
+ TIFFError(
+ filename,
+ "Can not handle %s data with compression other than SGILog",
+ (photometric == PHOTOMETRIC_LOGL) ? "LogL" : "LogLuv");
+ return (0);
+ }
+ /* rely on library to convert to RGB/greyscale */
+ TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT);
+ photometric = (photometric == PHOTOMETRIC_LOGL)
+ ? PHOTOMETRIC_MINISBLACK
+ : PHOTOMETRIC_RGB;
+ bitspersample = 8;
+ break;
+ case PHOTOMETRIC_CIELAB:
+ /* fall through... */
+ default:
+ TIFFError(
+ filename,
+ "Can not handle image with PhotometricInterpretation=%" PRIu16,
+ photometric);
+ return (0);
+ }
+ switch (bitspersample)
+ {
+ case 1:
+ case 2:
+ case 4:
+ case 8:
+ case 16:
+ break;
+ default:
+ TIFFError(filename, "Can not handle %" PRIu16 "-bit/sample image",
+ bitspersample);
+ return (0);
+ }
+ if (planarconfiguration == PLANARCONFIG_SEPARATE && extrasamples > 0)
+ TIFFWarning(filename, "Ignoring extra samples");
+ return (1);
}
-#define PS_UNIT_SIZE 72.0F
-#define PSUNITS(npix,res) ((npix) * (PS_UNIT_SIZE / (res)))
+#define PS_UNIT_SIZE 72.0F
+#define PSUNITS(npix, res) ((npix) * (PS_UNIT_SIZE / (res)))
static const char RGBcolorimage[] = "\
/bwproc {\n\
@@ -635,87 +675,88 @@ static const char RGBcolorimage[] = "\
*
* It is claimed to be part of some future revision of the EPS spec.
*/
-static void
-PhotoshopBanner(FILE* fd, uint32_t w, uint32_t h, int bs, int nc, const char* startline)
+static void PhotoshopBanner(FILE *fd, uint32_t w, uint32_t h, int bs, int nc,
+ const char *startline)
{
- fprintf(fd, "%%ImageData: %"PRIu32" %"PRIu32" %"PRIu16" %d 0 %d 2 \"",
- w, h, bitspersample, nc, bs);
- fprintf(fd, startline, nc);
- fprintf(fd, "\"\n");
+ fprintf(fd, "%%ImageData: %" PRIu32 " %" PRIu32 " %" PRIu16 " %d 0 %d 2 \"",
+ w, h, bitspersample, nc, bs);
+ fprintf(fd, startline, nc);
+ fprintf(fd, "\"\n");
}
-/* Convert pixel width and height pw, ph, to points pprw, pprh
+/* Convert pixel width and height pw, ph, to points pprw, pprh
* using image resolution and resolution units from TIFF tags.
* pw : image width in pixels
* ph : image height in pixels
* pprw : image width in PS units (72 dpi)
* pprh : image height in PS units (72 dpi)
*/
-static void
-setupPageState(TIFF* tif, uint32_t* pw, uint32_t* ph, double* pprw, double* pprh)
+static void setupPageState(TIFF *tif, uint32_t *pw, uint32_t *ph, double *pprw,
+ double *pprh)
{
- float xres = 0.0F, yres = 0.0F;
-
- TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw);
- TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph);
- if (res_unit == 0) /* Not specified as command line option */
- if (!TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &res_unit))
- res_unit = RESUNIT_INCH;
- /*
- * Calculate printable area.
- */
- if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres)
- || fabs(xres) < 0.0000001)
- xres = PS_UNIT_SIZE;
- if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres)
- || fabs(yres) < 0.0000001)
- yres = PS_UNIT_SIZE;
- switch (res_unit) {
- case RESUNIT_CENTIMETER:
- xres *= 2.54F, yres *= 2.54F;
- break;
- case RESUNIT_INCH:
- break;
- case RESUNIT_NONE: /* Subsequent code assumes we have converted to inches! */
- res_unit = RESUNIT_INCH;
- break;
- default: /* Last ditch guess for unspecified RESUNIT case
- * check that the resolution is not inches before scaling it.
- * Moved to end of function with additional check, RJN, 08-31-2010
- * if (xres != PS_UNIT_SIZE || yres != PS_UNIT_SIZE)
- * xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE;
- */
- break;
- }
- /* This is a hack to deal with images that have no meaningful Resolution Size
- * but may have x and/or y resolutions of 1 pixel per undefined unit.
- */
- if ((xres > 1.0) && (xres != PS_UNIT_SIZE))
- *pprw = PSUNITS(*pw, xres);
- else
- *pprw = PSUNITS(*pw, PS_UNIT_SIZE);
- if ((yres > 1.0) && (yres != PS_UNIT_SIZE))
- *pprh = PSUNITS(*ph, yres);
- else
- *pprh = PSUNITS(*ph, PS_UNIT_SIZE);
+ float xres = 0.0F, yres = 0.0F;
+
+ TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw);
+ TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph);
+ if (res_unit == 0) /* Not specified as command line option */
+ if (!TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &res_unit))
+ res_unit = RESUNIT_INCH;
+ /*
+ * Calculate printable area.
+ */
+ if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) ||
+ fabs(xres) < 0.0000001)
+ xres = PS_UNIT_SIZE;
+ if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) ||
+ fabs(yres) < 0.0000001)
+ yres = PS_UNIT_SIZE;
+ switch (res_unit)
+ {
+ case RESUNIT_CENTIMETER:
+ xres *= 2.54F, yres *= 2.54F;
+ break;
+ case RESUNIT_INCH:
+ break;
+ case RESUNIT_NONE: /* Subsequent code assumes we have converted to
+ inches! */
+ res_unit = RESUNIT_INCH;
+ break;
+ default: /* Last ditch guess for unspecified RESUNIT case
+ * check that the resolution is not inches before scaling it.
+ * Moved to end of function with additional check, RJN,
+ * 08-31-2010 if (xres != PS_UNIT_SIZE || yres != PS_UNIT_SIZE)
+ * xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE;
+ */
+ break;
+ }
+ /* This is a hack to deal with images that have no meaningful Resolution
+ * Size but may have x and/or y resolutions of 1 pixel per undefined unit.
+ */
+ if ((xres > 1.0) && (xres != PS_UNIT_SIZE))
+ *pprw = PSUNITS(*pw, xres);
+ else
+ *pprw = PSUNITS(*pw, PS_UNIT_SIZE);
+ if ((yres > 1.0) && (yres != PS_UNIT_SIZE))
+ *pprh = PSUNITS(*ph, yres);
+ else
+ *pprh = PSUNITS(*ph, PS_UNIT_SIZE);
}
-static int
-isCCITTCompression(TIFF* tif)
+static int isCCITTCompression(TIFF *tif)
{
uint16_t compress;
TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress);
return (compress == COMPRESSION_CCITTFAX3 ||
- compress == COMPRESSION_CCITTFAX4 ||
- compress == COMPRESSION_CCITTRLE ||
- compress == COMPRESSION_CCITTRLEW);
+ compress == COMPRESSION_CCITTFAX4 ||
+ compress == COMPRESSION_CCITTRLE ||
+ compress == COMPRESSION_CCITTRLEW);
}
-static tsize_t tf_bytesperrow;
-static tsize_t ps_bytesperrow;
-static uint32_t tf_rowsperstrip;
-static uint32_t tf_numberstrips;
-static char *hex = "0123456789abcdef";
+static tsize_t tf_bytesperrow;
+static tsize_t ps_bytesperrow;
+static uint32_t tf_rowsperstrip;
+static uint32_t tf_numberstrips;
+static char *hex = "0123456789abcdef";
/*
* Pagewidth and pageheight are the output size in points,
@@ -726,932 +767,1103 @@ static char *hex = "0123456789abcdef";
* Only one of maxPageHeight or maxPageWidth can be used.
* These are global variables unfortunately.
*/
-int get_subimage_count(double pagewidth, double pageheight,
- double imagewidth, double imageheight,
- int *ximages, int *yimages,
- int rotation, double scale)
+int get_subimage_count(double pagewidth, double pageheight, double imagewidth,
+ double imageheight, int *ximages, int *yimages,
+ int rotation, double scale)
{
- int pages = 1;
- double splitheight = 0; /* Requested Max Height in points */
- double splitwidth = 0; /* Requested Max Width in points */
- double overlap = 0; /* Repeated edge width in points */
-
- splitheight = maxPageHeight * PS_UNIT_SIZE;
- splitwidth = maxPageWidth * PS_UNIT_SIZE;
- overlap = splitOverlap * PS_UNIT_SIZE;
- pagewidth *= PS_UNIT_SIZE;
- pageheight *= PS_UNIT_SIZE;
-
- if ((imagewidth < 1.0) || (imageheight < 1.0))
- {
- TIFFError("get_subimage_count", "Invalid image width or height");
- return (0);
- }
-
- switch (rotation)
- {
- case 0:
- case 180: if (splitheight > 0) /* -H maxPageHeight */
+ int pages = 1;
+ double splitheight = 0; /* Requested Max Height in points */
+ double splitwidth = 0; /* Requested Max Width in points */
+ double overlap = 0; /* Repeated edge width in points */
+
+ splitheight = maxPageHeight * PS_UNIT_SIZE;
+ splitwidth = maxPageWidth * PS_UNIT_SIZE;
+ overlap = splitOverlap * PS_UNIT_SIZE;
+ pagewidth *= PS_UNIT_SIZE;
+ pageheight *= PS_UNIT_SIZE;
+
+ if ((imagewidth < 1.0) || (imageheight < 1.0))
+ {
+ TIFFError("get_subimage_count", "Invalid image width or height");
+ return (0);
+ }
+
+ switch (rotation)
+ {
+ case 0:
+ case 180:
+ if (splitheight > 0) /* -H maxPageHeight */
+ {
+ if (imageheight >
+ splitheight) /* More than one vertical image segment */
{
- if (imageheight > splitheight) /* More than one vertical image segment */
- {
- if (pagewidth)
- *ximages = (int)ceil((scale * imagewidth) / (pagewidth - overlap));
- else
- *ximages = 1;
- *yimages = (int)ceil((scale * imageheight) / (splitheight - overlap)); /* Max vert pages needed */
- }
+ if (pagewidth)
+ *ximages = (int)ceil((scale * imagewidth) /
+ (pagewidth - overlap));
+ else
+ *ximages = 1;
+ *yimages = (int)ceil(
+ (scale * imageheight) /
+ (splitheight - overlap)); /* Max vert pages needed */
+ }
else
- {
- if (pagewidth)
- *ximages = (int)ceil((scale * imagewidth) / (pagewidth - overlap)); /* Max horz pages needed */
- else
- *ximages = 1;
- *yimages = 1; /* Max vert pages needed */
- }
- }
- else
- {
- if (splitwidth > 0) /* -W maxPageWidth */
- {
- if (imagewidth >splitwidth)
- {
- *ximages = (int)ceil((scale * imagewidth) / (splitwidth - overlap)); /* Max horz pages needed */
- if (pageheight)
- *yimages = (int)ceil((scale * imageheight) / (pageheight - overlap)); /* Max vert pages needed */
+ {
+ if (pagewidth)
+ *ximages = (int)ceil(
+ (scale * imagewidth) /
+ (pagewidth - overlap)); /* Max horz pages needed */
else
- *yimages = 1;
- }
- else
- {
- *ximages = 1; /* Max vert pages needed */
- if (pageheight)
- *yimages = (int)ceil((scale * imageheight) / (pageheight - overlap)); /* Max vert pages needed */
+ *ximages = 1;
+ *yimages = 1; /* Max vert pages needed */
+ }
+ }
+ else
+ {
+ if (splitwidth > 0) /* -W maxPageWidth */
+ {
+ if (imagewidth > splitwidth)
+ {
+ *ximages = (int)ceil(
+ (scale * imagewidth) /
+ (splitwidth - overlap)); /* Max horz pages needed */
+ if (pageheight)
+ *yimages = (int)ceil(
+ (scale * imageheight) /
+ (pageheight -
+ overlap)); /* Max vert pages needed */
+ else
+ *yimages = 1;
+ }
else
- *yimages = 1;
- }
- }
+ {
+ *ximages = 1; /* Max vert pages needed */
+ if (pageheight)
+ *yimages = (int)ceil(
+ (scale * imageheight) /
+ (pageheight -
+ overlap)); /* Max vert pages needed */
+ else
+ *yimages = 1;
+ }
+ }
else
- {
- *ximages = 1;
- *yimages = 1;
- }
- }
- break;
- case 90:
- case 270: if (splitheight > 0) /* -H maxPageHeight */
{
- if (imagewidth > splitheight) /* More than one vertical image segment */
- {
- *yimages = (int)ceil((scale * imagewidth) / (splitheight - overlap)); /* Max vert pages needed */
- if (pagewidth)
- *ximages = (int)ceil((scale * imageheight) / (pagewidth - overlap)); /* Max horz pages needed */
- else
- *ximages = 1;
- }
+ *ximages = 1;
+ *yimages = 1;
+ }
+ }
+ break;
+ case 90:
+ case 270:
+ if (splitheight > 0) /* -H maxPageHeight */
+ {
+ if (imagewidth >
+ splitheight) /* More than one vertical image segment */
+ {
+ *yimages = (int)ceil(
+ (scale * imagewidth) /
+ (splitheight - overlap)); /* Max vert pages needed */
+ if (pagewidth)
+ *ximages = (int)ceil(
+ (scale * imageheight) /
+ (pagewidth - overlap)); /* Max horz pages needed */
+ else
+ *ximages = 1;
+ }
else
- {
- *yimages = 1; /* Max vert pages needed */
- if (pagewidth)
- *ximages = (int)ceil((scale * imageheight) / (pagewidth - overlap)); /* Max horz pages needed */
- else
- *ximages = 1;
- }
- }
- else
- {
- if (splitwidth > 0) /* -W maxPageWidth */
- {
- if (imageheight > splitwidth)
- {
- if (pageheight)
- *yimages = (int)ceil((scale * imagewidth) / (pageheight - overlap)); /* Max vert pages needed */
+ {
+ *yimages = 1; /* Max vert pages needed */
+ if (pagewidth)
+ *ximages = (int)ceil(
+ (scale * imageheight) /
+ (pagewidth - overlap)); /* Max horz pages needed */
else
- *yimages = 1;
- *ximages = (int)ceil((scale * imageheight) / (splitwidth - overlap)); /* Max horz pages needed */
- }
- else
- {
- if (pageheight)
- *yimages = (int)ceil((scale * imagewidth) / (pageheight - overlap)); /* Max horz pages needed */
+ *ximages = 1;
+ }
+ }
+ else
+ {
+ if (splitwidth > 0) /* -W maxPageWidth */
+ {
+ if (imageheight > splitwidth)
+ {
+ if (pageheight)
+ *yimages = (int)ceil(
+ (scale * imagewidth) /
+ (pageheight -
+ overlap)); /* Max vert pages needed */
+ else
+ *yimages = 1;
+ *ximages = (int)ceil(
+ (scale * imageheight) /
+ (splitwidth - overlap)); /* Max horz pages needed */
+ }
else
- *yimages = 1;
- *ximages = 1; /* Max vert pages needed */
- }
- }
+ {
+ if (pageheight)
+ *yimages = (int)ceil(
+ (scale * imagewidth) /
+ (pageheight -
+ overlap)); /* Max horz pages needed */
+ else
+ *yimages = 1;
+ *ximages = 1; /* Max vert pages needed */
+ }
+ }
else
- {
- *ximages = 1;
- *yimages = 1;
- }
- }
- break;
- default: *ximages = 1;
- *yimages = 1;
- }
- pages = (*ximages) * (*yimages);
- return (pages);
- }
+ {
+ *ximages = 1;
+ *yimages = 1;
+ }
+ }
+ break;
+ default:
+ *ximages = 1;
+ *yimages = 1;
+ }
+ pages = (*ximages) * (*yimages);
+ return (pages);
+}
/* New version of PlaceImage that handles only the translation and rotation
* for a single output page.
*/
int exportMaskedImage(FILE *fp, double pagewidth, double pageheight,
- double imagewidth, double imageheight,
- int row, int column,
- double left_offset, double bott_offset,
- double scale, int center, int rotation)
- {
- double xtran = 0.0;
- double ytran = 0.0;
+ double imagewidth, double imageheight, int row,
+ int column, double left_offset, double bott_offset,
+ double scale, int center, int rotation)
+{
+ double xtran = 0.0;
+ double ytran = 0.0;
- double xscale = 1.0;
- double yscale = 1.0;
+ double xscale = 1.0;
+ double yscale = 1.0;
- double splitheight = 0; /* Requested Max Height in points */
- double splitwidth = 0; /* Requested Max Width in points */
- double overlap = 0; /* Repeated edge width in points */
- double subimage_height = 0.0;
+ double splitheight = 0; /* Requested Max Height in points */
+ double splitwidth = 0; /* Requested Max Width in points */
+ double overlap = 0; /* Repeated edge width in points */
+ double subimage_height = 0.0;
- splitheight = maxPageHeight * PS_UNIT_SIZE;
- splitwidth = maxPageWidth * PS_UNIT_SIZE;
- overlap = splitOverlap * PS_UNIT_SIZE;
- xscale = scale * imagewidth;
- yscale = scale * imageheight;
+ splitheight = maxPageHeight * PS_UNIT_SIZE;
+ splitwidth = maxPageWidth * PS_UNIT_SIZE;
+ overlap = splitOverlap * PS_UNIT_SIZE;
+ xscale = scale * imagewidth;
+ yscale = scale * imageheight;
- if ((xscale < 0.0) || (yscale < 0.0))
+ if ((xscale < 0.0) || (yscale < 0.0))
{
- TIFFError("exportMaskedImage", "Invalid parameters.");
- return (-1);
+ TIFFError("exportMaskedImage", "Invalid parameters.");
+ return (-1);
}
- /* If images are cropped to a vewport with -H or -W, the output pages are shifted to
- * the top of each output page rather than the Postscript default lower edge.
- */
- switch (rotation)
+ /* If images are cropped to a vewport with -H or -W, the output pages are
+ * shifted to the top of each output page rather than the Postscript default
+ * lower edge.
+ */
+ switch (rotation)
{
- case 0:
- case 180: if (splitheight > 0) /* -H maxPageHeight */
+ case 0:
+ case 180:
+ if (splitheight > 0) /* -H maxPageHeight */
+ {
+ if (splitheight <
+ imageheight) /* More than one vertical image segments */
+ {
+ /* Intra2net: Keep correct apspect ratio */
+ xscale = (imagewidth + overlap) *
+ (pageheight / splitheight) * scale;
+
+ xtran = -1.0 * column * (pagewidth - overlap);
+ subimage_height =
+ imageheight - ((splitheight - overlap) * row);
+ ytran = pageheight -
+ subimage_height * (pageheight / splitheight);
+ }
+ else /* Only one page in vertical direction */
{
- if (splitheight < imageheight) /* More than one vertical image segments */
- {
- /* Intra2net: Keep correct apspect ratio */
- xscale = (imagewidth + overlap) * (pageheight / splitheight) * scale;
-
- xtran = -1.0 * column * (pagewidth - overlap);
- subimage_height = imageheight - ((splitheight - overlap) * row);
- ytran = pageheight - subimage_height * (pageheight / splitheight);
- }
- else /* Only one page in vertical direction */
- {
- xtran = -1.0 * column * (pagewidth - overlap);
- ytran = splitheight - imageheight;
- }
- }
- else
- {
+ xtran = -1.0 * column * (pagewidth - overlap);
+ ytran = splitheight - imageheight;
+ }
+ }
+ else
+ {
if (splitwidth > 0) /* maxPageWidth */
- {
- if (splitwidth < imagewidth)
- {
- xtran = -1.0 * column * splitwidth;
- ytran = -1.0 * row * (pageheight - overlap);
+ {
+ if (splitwidth < imagewidth)
+ {
+ xtran = -1.0 * column * splitwidth;
+ ytran = -1.0 * row * (pageheight - overlap);
}
- else /* Only one page in horizontal direction */
- {
- ytran = -1.0 * row * (pageheight - overlap);
+ else /* Only one page in horizontal direction */
+ {
+ ytran = -1.0 * row * (pageheight - overlap);
+ xtran = 0;
+ }
+ }
+ else /* Simple case, no splitting */
+ {
+ ytran = pageheight - imageheight;
xtran = 0;
- }
- }
- else /* Simple case, no splitting */
- {
- ytran = pageheight - imageheight;
- xtran = 0;
- }
}
+ }
- if (imagewidth <= pagewidth) {
- /* Intra2net: Crop page at the bottom instead of the top (-> output starts at the top).
- Only do this in non-page-split mode */
- if (imageheight <= splitheight) {
- ytran = pageheight - imageheight; /* Note: Will be negative for images longer than page size */
+ if (imagewidth <= pagewidth)
+ {
+ /* Intra2net: Crop page at the bottom instead of the top (->
+ output starts at the top). Only do this in non-page-split
+ mode */
+ if (imageheight <= splitheight)
+ {
+ ytran = pageheight -
+ imageheight; /* Note: Will be negative for images
+ longer than page size */
}
}
- bott_offset += ytran / (center ? 2 : 1);
- left_offset += xtran / (center ? 2 : 1);
- break;
- case 90:
- case 270: if (splitheight > 0) /* -H maxPageHeight */
+ bott_offset += ytran / (center ? 2 : 1);
+ left_offset += xtran / (center ? 2 : 1);
+ break;
+ case 90:
+ case 270:
+ if (splitheight > 0) /* -H maxPageHeight */
+ {
+ if (splitheight <
+ imagewidth) /* More than one vertical image segments */
{
- if (splitheight < imagewidth) /* More than one vertical image segments */
- {
- xtran = -1.0 * column * (pageheight - overlap);
- /* Commented code places image at bottom of page instead of top.
- ytran = -1.0 * row * splitheight;
- */
- if (row == 0)
- ytran = -1.0 * (imagewidth - splitheight);
- else
- ytran = -1.0 * (imagewidth - (splitheight - overlap) * (row + 1));
- }
- else /* Only one page in vertical direction */
- {
- xtran = -1.0 * column * (pageheight - overlap);
- ytran = splitheight - imagewidth;
- }
- }
- else
- {
+ xtran = -1.0 * column * (pageheight - overlap);
+ /* Commented code places image at bottom of page instead of
+ top. ytran = -1.0 * row * splitheight;
+ */
+ if (row == 0)
+ ytran = -1.0 * (imagewidth - splitheight);
+ else
+ ytran = -1.0 * (imagewidth -
+ (splitheight - overlap) * (row + 1));
+ }
+ else /* Only one page in vertical direction */
+ {
+ xtran = -1.0 * column * (pageheight - overlap);
+ ytran = splitheight - imagewidth;
+ }
+ }
+ else
+ {
if (splitwidth > 0) /* maxPageWidth */
- {
- if (splitwidth < imageheight)
- {
- xtran = -1.0 * column * splitwidth;
- ytran = -1.0 * row * (pagewidth - overlap);
+ {
+ if (splitwidth < imageheight)
+ {
+ xtran = -1.0 * column * splitwidth;
+ ytran = -1.0 * row * (pagewidth - overlap);
+ }
+ else /* Only one page in horizontal direction */
+ {
+ ytran = -1.0 * row * (pagewidth - overlap);
+ xtran = 0;
}
- else /* Only one page in horizontal direction */
- {
- ytran = -1.0 * row * (pagewidth - overlap);
- xtran = 0;
- }
- }
- else /* Simple case, no splitting */
- {
- ytran = pageheight - imageheight;
- xtran = 0; /* pagewidth - imagewidth; */
- }
}
- bott_offset += ytran / (center ? 2 : 1);
- left_offset += xtran / (center ? 2 : 1);
- break;
- default: xtran = 0;
- ytran = 0;
- }
-
- switch (rotation)
- {
- case 0: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
- fprintf(fp, "%f %f scale\n", xscale, yscale);
- break;
- case 180: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
- fprintf(fp, "%f %f scale\n1 1 translate 180 rotate\n", xscale, yscale);
- break;
- case 90: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
- fprintf(fp, "%f %f scale\n1 0 translate 90 rotate\n", yscale, xscale);
- break;
- case 270: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
- fprintf(fp, "%f %f scale\n0 1 translate 270 rotate\n", yscale, xscale);
- break;
- default: TIFFError ("exportMaskedImage", "Unsupported rotation angle %d. No rotation", rotation);
- fprintf( fp, "%f %f scale\n", xscale, yscale);
- break;
- }
-
- return (0);
- }
+ else /* Simple case, no splitting */
+ {
+ ytran = pageheight - imageheight;
+ xtran = 0; /* pagewidth - imagewidth; */
+ }
+ }
+ bott_offset += ytran / (center ? 2 : 1);
+ left_offset += xtran / (center ? 2 : 1);
+ break;
+ default:
+ xtran = 0;
+ ytran = 0;
+ }
+
+ switch (rotation)
+ {
+ case 0:
+ fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
+ fprintf(fp, "%f %f scale\n", xscale, yscale);
+ break;
+ case 180:
+ fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
+ fprintf(fp, "%f %f scale\n1 1 translate 180 rotate\n", xscale,
+ yscale);
+ break;
+ case 90:
+ fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
+ fprintf(fp, "%f %f scale\n1 0 translate 90 rotate\n", yscale,
+ xscale);
+ break;
+ case 270:
+ fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
+ fprintf(fp, "%f %f scale\n0 1 translate 270 rotate\n", yscale,
+ xscale);
+ break;
+ default:
+ TIFFError("exportMaskedImage",
+ "Unsupported rotation angle %d. No rotation", rotation);
+ fprintf(fp, "%f %f scale\n", xscale, yscale);
+ break;
+ }
+
+ return (0);
+}
/* Rotate an image without scaling or clipping */
-int psRotateImage (FILE * fd, int rotation, double pswidth, double psheight,
- double left_offset, double bottom_offset)
- {
- if ((left_offset != 0.0) || (bottom_offset != 0))
- fprintf (fd, "%f %f translate\n", left_offset, bottom_offset);
-
- /* Exchange width and height for 90/270 rotations */
- switch (rotation)
- {
- case 0: fprintf (fd, "%f %f scale\n", pswidth, psheight);
- break;
- case 90: fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight, pswidth);
- break;
- case 180: fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth, psheight);
- break;
- case 270: fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight, pswidth);
- break;
- default: TIFFError ("psRotateImage", "Unsupported rotation %d.", rotation);
- fprintf( fd, "%f %f scale\n", pswidth, psheight);
- return (1);
- }
- return (0);
- }
+int psRotateImage(FILE *fd, int rotation, double pswidth, double psheight,
+ double left_offset, double bottom_offset)
+{
+ if ((left_offset != 0.0) || (bottom_offset != 0))
+ fprintf(fd, "%f %f translate\n", left_offset, bottom_offset);
+
+ /* Exchange width and height for 90/270 rotations */
+ switch (rotation)
+ {
+ case 0:
+ fprintf(fd, "%f %f scale\n", pswidth, psheight);
+ break;
+ case 90:
+ fprintf(fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight,
+ pswidth);
+ break;
+ case 180:
+ fprintf(fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth,
+ psheight);
+ break;
+ case 270:
+ fprintf(fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight,
+ pswidth);
+ break;
+ default:
+ TIFFError("psRotateImage", "Unsupported rotation %d.", rotation);
+ fprintf(fd, "%f %f scale\n", pswidth, psheight);
+ return (1);
+ }
+ return (0);
+}
/* Scale and rotate an image to a single output page. */
-int psScaleImage(FILE * fd, double scale, int rotation, int center,
- double reqwidth, double reqheight, double pswidth, double psheight,
- double left_offset, double bottom_offset)
- {
- double hcenter = 0.0, vcenter = 0.0;
+int psScaleImage(FILE *fd, double scale, int rotation, int center,
+ double reqwidth, double reqheight, double pswidth,
+ double psheight, double left_offset, double bottom_offset)
+{
+ double hcenter = 0.0, vcenter = 0.0;
- /* Adjust offsets for centering */
- if (center)
+ /* Adjust offsets for centering */
+ if (center)
{
- switch (rotation)
- {
- case 90: vcenter = (reqheight - pswidth * scale) / 2;
+ switch (rotation)
+ {
+ case 90:
+ vcenter = (reqheight - pswidth * scale) / 2;
hcenter = (reqwidth - psheight * scale) / 2;
- fprintf (fd, "%f %f translate\n", hcenter, vcenter);
- fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight * scale, pswidth * scale);
- break;
- case 180: hcenter = (reqwidth - pswidth * scale) / 2;
+ fprintf(fd, "%f %f translate\n", hcenter, vcenter);
+ fprintf(fd, "%f %f scale\n1 0 translate 90 rotate\n",
+ psheight * scale, pswidth * scale);
+ break;
+ case 180:
+ hcenter = (reqwidth - pswidth * scale) / 2;
vcenter = (reqheight - psheight * scale) / 2;
- fprintf (fd, "%f %f translate\n", hcenter, vcenter);
- fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth * scale, psheight * scale);
- break;
- case 270: vcenter = (reqheight - pswidth * scale) / 2;
+ fprintf(fd, "%f %f translate\n", hcenter, vcenter);
+ fprintf(fd, "%f %f scale\n1 1 translate 180 rotate\n",
+ pswidth * scale, psheight * scale);
+ break;
+ case 270:
+ vcenter = (reqheight - pswidth * scale) / 2;
hcenter = (reqwidth - psheight * scale) / 2;
- fprintf (fd, "%f %f translate\n", hcenter, vcenter);
- fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight * scale, pswidth * scale);
- break;
- case 0:
- default: hcenter = (reqwidth - pswidth * scale) / 2;
+ fprintf(fd, "%f %f translate\n", hcenter, vcenter);
+ fprintf(fd, "%f %f scale\n0 1 translate 270 rotate\n",
+ psheight * scale, pswidth * scale);
+ break;
+ case 0:
+ default:
+ hcenter = (reqwidth - pswidth * scale) / 2;
vcenter = (reqheight - psheight * scale) / 2;
- fprintf (fd, "%f %f translate\n", hcenter, vcenter);
- fprintf (fd, "%f %f scale\n", pswidth * scale, psheight * scale);
- break;
- }
+ fprintf(fd, "%f %f translate\n", hcenter, vcenter);
+ fprintf(fd, "%f %f scale\n", pswidth * scale, psheight * scale);
+ break;
+ }
}
- else /* Not centered */
+ else /* Not centered */
{
- switch (rotation)
- {
- case 0: fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
- bottom_offset ? bottom_offset : reqheight - (psheight * scale));
- fprintf (fd, "%f %f scale\n", pswidth * scale, psheight * scale);
+ switch (rotation)
+ {
+ case 0:
+ fprintf(fd, "%f %f translate\n",
+ left_offset ? left_offset : 0.0,
+ bottom_offset ? bottom_offset
+ : reqheight - (psheight * scale));
+ fprintf(fd, "%f %f scale\n", pswidth * scale, psheight * scale);
break;
- case 90: fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
- bottom_offset ? bottom_offset : reqheight - (pswidth * scale));
- fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight * scale, pswidth * scale);
+ case 90:
+ fprintf(fd, "%f %f translate\n",
+ left_offset ? left_offset : 0.0,
+ bottom_offset ? bottom_offset
+ : reqheight - (pswidth * scale));
+ fprintf(fd, "%f %f scale\n1 0 translate 90 rotate\n",
+ psheight * scale, pswidth * scale);
break;
- case 180: fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
- bottom_offset ? bottom_offset : reqheight - (psheight * scale));
- fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth * scale, psheight * scale);
+ case 180:
+ fprintf(fd, "%f %f translate\n",
+ left_offset ? left_offset : 0.0,
+ bottom_offset ? bottom_offset
+ : reqheight - (psheight * scale));
+ fprintf(fd, "%f %f scale\n1 1 translate 180 rotate\n",
+ pswidth * scale, psheight * scale);
break;
- case 270: fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
- bottom_offset ? bottom_offset : reqheight - (pswidth * scale));
- fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight * scale, pswidth * scale);
+ case 270:
+ fprintf(fd, "%f %f translate\n",
+ left_offset ? left_offset : 0.0,
+ bottom_offset ? bottom_offset
+ : reqheight - (pswidth * scale));
+ fprintf(fd, "%f %f scale\n0 1 translate 270 rotate\n",
+ psheight * scale, pswidth * scale);
break;
- default: TIFFError ("psScaleImage", "Unsupported rotation %d", rotation);
- fprintf (fd, "%f %f scale\n", pswidth * scale, psheight * scale);
+ default:
+ TIFFError("psScaleImage", "Unsupported rotation %d", rotation);
+ fprintf(fd, "%f %f scale\n", pswidth * scale, psheight * scale);
return (1);
- }
+ }
}
- return (0);
- }
+ return (0);
+}
/* This controls the visible portion of the page which is displayed.
* N.B. Setting maxPageHeight no longer sets pageheight if not set explicitly
*/
-int psPageSize (FILE * fd, int rotation, double pgwidth, double pgheight,
- double reqwidth, double reqheight, double pswidth, double psheight)
- {
- double xscale = 1.0, yscale = 1.0, scale = 1.0;
- double splitheight;
- double splitwidth;
- double new_width;
- double new_height;
-
- splitheight = maxPageHeight * PS_UNIT_SIZE;
- splitwidth = maxPageWidth * PS_UNIT_SIZE;
-
- switch (rotation)
- {
- case 0:
- case 180: if ((splitheight > 0) || (splitwidth > 0))
+int psPageSize(FILE *fd, int rotation, double pgwidth, double pgheight,
+ double reqwidth, double reqheight, double pswidth,
+ double psheight)
+{
+ double xscale = 1.0, yscale = 1.0, scale = 1.0;
+ double splitheight;
+ double splitwidth;
+ double new_width;
+ double new_height;
+
+ splitheight = maxPageHeight * PS_UNIT_SIZE;
+ splitwidth = maxPageWidth * PS_UNIT_SIZE;
+
+ switch (rotation)
+ {
+ case 0:
+ case 180:
+ if ((splitheight > 0) || (splitwidth > 0))
+ {
+ if (pgwidth != 0 || pgheight != 0)
{
- if (pgwidth != 0 || pgheight != 0)
- {
- xscale = reqwidth / (splitwidth ? splitwidth : pswidth);
- yscale = reqheight / (splitheight ? splitheight : psheight);
- scale = (xscale < yscale) ? xscale : yscale;
- }
+ xscale = reqwidth / (splitwidth ? splitwidth : pswidth);
+ yscale = reqheight / (splitheight ? splitheight : psheight);
+ scale = (xscale < yscale) ? xscale : yscale;
+ }
new_width = splitwidth ? splitwidth : scale * pswidth;
new_height = splitheight ? splitheight : scale * psheight;
if (strlen(pageOrientation))
- fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
+ fprintf(fd, "%%%%PageOrientation: %s\n", pageOrientation);
else
- fprintf (fd, "%%%%PageOrientation: %s\n", (new_width > new_height) ? "Landscape" : "Portrait");
- fprintf (fd, "%%%%PageBoundingBox: 0 0 %"PRId32" %"PRId32"\n", (int32_t)new_width, (int32_t)new_height);
- fprintf (fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
- new_width, new_height);
+ fprintf(fd, "%%%%PageOrientation: %s\n",
+ (new_width > new_height) ? "Landscape"
+ : "Portrait");
+ fprintf(fd,
+ "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32 "\n",
+ (int32_t)new_width, (int32_t)new_height);
+ fprintf(fd,
+ "1 dict begin /PageSize [ %f %f ] def currentdict end "
+ "setpagedevice\n",
+ new_width, new_height);
+ }
+ else /* No viewport defined with -H or -W */
+ {
+ if ((pgwidth == 0) && (pgheight == 0)) /* Image not scaled */
+ {
+ if (strlen(pageOrientation))
+ fprintf(fd, "%%%%PageOrientation: %s\n",
+ pageOrientation);
+ else
+ fprintf(fd, "%%%%PageOrientation: %s\n",
+ (pswidth > psheight) ? "Landscape"
+ : "Portrait");
+ fprintf(fd,
+ "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32
+ "\n",
+ (int32_t)pswidth, (int32_t)psheight);
+ fprintf(fd,
+ "1 dict begin /PageSize [ %f %f ] def currentdict "
+ "end setpagedevice\n",
+ pswidth, psheight);
}
- else /* No viewport defined with -H or -W */
+ else /* Image scaled */
{
- if ((pgwidth == 0) && (pgheight == 0)) /* Image not scaled */
- {
- if (strlen(pageOrientation))
- fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
- else
- fprintf (fd, "%%%%PageOrientation: %s\n", (pswidth > psheight) ? "Landscape" : "Portrait");
- fprintf (fd, "%%%%PageBoundingBox: 0 0 %"PRId32" %"PRId32"\n", (int32_t)pswidth, (int32_t)psheight);
- fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
- pswidth, psheight);
- }
- else /* Image scaled */
- {
- if (strlen(pageOrientation))
- fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
- else
- fprintf (fd, "%%%%PageOrientation: %s\n", (reqwidth > reqheight) ? "Landscape" : "Portrait");
- fprintf (fd, "%%%%PageBoundingBox: 0 0 %"PRId32" %"PRId32"\n", (int32_t)reqwidth, (int32_t)reqheight);
- fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
- reqwidth, reqheight);
- }
+ if (strlen(pageOrientation))
+ fprintf(fd, "%%%%PageOrientation: %s\n",
+ pageOrientation);
+ else
+ fprintf(fd, "%%%%PageOrientation: %s\n",
+ (reqwidth > reqheight) ? "Landscape"
+ : "Portrait");
+ fprintf(fd,
+ "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32
+ "\n",
+ (int32_t)reqwidth, (int32_t)reqheight);
+ fprintf(fd,
+ "1 dict begin /PageSize [ %f %f ] def currentdict "
+ "end setpagedevice\n",
+ reqwidth, reqheight);
+ }
+ }
+ break;
+ case 90:
+ case 270:
+ if ((splitheight > 0) || (splitwidth > 0))
+ {
+ if (pgwidth != 0 || pgheight != 0)
+ {
+ xscale = reqwidth / (splitwidth ? splitwidth : pswidth);
+ yscale = reqheight / (splitheight ? splitheight : psheight);
+ scale = (xscale < yscale) ? xscale : yscale;
}
- break;
- case 90:
- case 270: if ((splitheight > 0) || (splitwidth > 0))
- {
- if (pgwidth != 0 || pgheight != 0)
- {
- xscale = reqwidth / (splitwidth ? splitwidth : pswidth);
- yscale = reqheight / (splitheight ? splitheight : psheight);
- scale = (xscale < yscale) ? xscale : yscale;
- }
new_width = splitwidth ? splitwidth : scale * psheight;
new_height = splitheight ? splitheight : scale * pswidth;
if (strlen(pageOrientation))
- fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
+ fprintf(fd, "%%%%PageOrientation: %s\n", pageOrientation);
else
- fprintf (fd, "%%%%PageOrientation: %s\n", (new_width > new_height) ? "Landscape" : "Portrait");
- fprintf (fd, "%%%%PageBoundingBox: 0 0 %"PRId32" %"PRId32"\n", (int32_t)new_width, (int32_t)new_height);
- fprintf (fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
- new_width, new_height);
+ fprintf(fd, "%%%%PageOrientation: %s\n",
+ (new_width > new_height) ? "Landscape"
+ : "Portrait");
+ fprintf(fd,
+ "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32 "\n",
+ (int32_t)new_width, (int32_t)new_height);
+ fprintf(fd,
+ "1 dict begin /PageSize [ %f %f ] def currentdict end "
+ "setpagedevice\n",
+ new_width, new_height);
+ }
+ else
+ {
+ if ((pgwidth == 0) && (pgheight == 0)) /* Image not scaled */
+ {
+ if (strlen(pageOrientation))
+ fprintf(fd, "%%%%PageOrientation: %s\n",
+ pageOrientation);
+ else
+ fprintf(fd, "%%%%PageOrientation: %s\n",
+ (psheight > pswidth) ? "Landscape"
+ : "Portrait");
+ fprintf(fd,
+ "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32
+ "\n",
+ (int32_t)psheight, (int32_t)pswidth);
+ fprintf(fd,
+ "1 dict begin /PageSize [ %f %f ] def currentdict "
+ "end setpagedevice\n",
+ psheight, pswidth);
}
- else
+ else /* Image scaled */
{
- if ((pgwidth == 0) && (pgheight == 0)) /* Image not scaled */
- {
- if (strlen(pageOrientation))
- fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
- else
- fprintf (fd, "%%%%PageOrientation: %s\n", (psheight > pswidth) ? "Landscape" : "Portrait");
- fprintf (fd, "%%%%PageBoundingBox: 0 0 %"PRId32" %"PRId32"\n", (int32_t)psheight, (int32_t)pswidth);
- fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
- psheight, pswidth);
- }
- else /* Image scaled */
- {
- if (strlen(pageOrientation))
- fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
- else
- fprintf (fd, "%%%%PageOrientation: %s\n", (reqwidth > reqheight) ? "Landscape" : "Portrait");
- fprintf (fd, "%%%%PageBoundingBox: 0 0 %"PRId32" %"PRId32"\n", (int32_t)reqwidth, (int32_t)reqheight);
- fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
- reqwidth, reqheight);
- }
- }
- break;
- default: TIFFError ("psPageSize", "Invalid rotation %d", rotation);
- return (1);
- }
- fputs("<<\n /Policies <<\n /PageSize 3\n >>\n>> setpagedevice\n", fd);
-
- return (0);
- } /* end psPageSize */
+ if (strlen(pageOrientation))
+ fprintf(fd, "%%%%PageOrientation: %s\n",
+ pageOrientation);
+ else
+ fprintf(fd, "%%%%PageOrientation: %s\n",
+ (reqwidth > reqheight) ? "Landscape"
+ : "Portrait");
+ fprintf(fd,
+ "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32
+ "\n",
+ (int32_t)reqwidth, (int32_t)reqheight);
+ fprintf(fd,
+ "1 dict begin /PageSize [ %f %f ] def currentdict "
+ "end setpagedevice\n",
+ reqwidth, reqheight);
+ }
+ }
+ break;
+ default:
+ TIFFError("psPageSize", "Invalid rotation %d", rotation);
+ return (1);
+ }
+ fputs("<<\n /Policies <<\n /PageSize 3\n >>\n>> setpagedevice\n", fd);
+
+ return (0);
+} /* end psPageSize */
/* Mask an image as a series of pages, each only showing a section defined
* by the maxPageHeight or maxPageWidth options.
*/
-int psMaskImage(FILE *fd, TIFF *tif, int rotation, int center,
- int *npages, double pixwidth, double pixheight,
- double left_margin, double bottom_margin,
- double pgwidth, double pgheight,
- double pswidth, double psheight, double scale)
- {
- int i, j;
- int ximages = 1, yimages = 1;
- int pages = *npages;
- double view_width = 0;
- double view_height = 0;
-
- if (get_viewport (pgwidth, pgheight, pswidth, psheight, &view_width, &view_height, rotation))
+int psMaskImage(FILE *fd, TIFF *tif, int rotation, int center, int *npages,
+ double pixwidth, double pixheight, double left_margin,
+ double bottom_margin, double pgwidth, double pgheight,
+ double pswidth, double psheight, double scale)
+{
+ int i, j;
+ int ximages = 1, yimages = 1;
+ int pages = *npages;
+ double view_width = 0;
+ double view_height = 0;
+
+ if (get_viewport(pgwidth, pgheight, pswidth, psheight, &view_width,
+ &view_height, rotation))
{
- TIFFError ("get_viewport", "Unable to set image viewport");
- return (-1);
+ TIFFError("get_viewport", "Unable to set image viewport");
+ return (-1);
}
- if (get_subimage_count(pgwidth, pgheight, pswidth, psheight,
- &ximages, &yimages, rotation, scale) < 1)
+ if (get_subimage_count(pgwidth, pgheight, pswidth, psheight, &ximages,
+ &yimages, rotation, scale) < 1)
{
- TIFFError("get_subimage_count", "Invalid image count: %d columns, %d rows", ximages, yimages);
- return (-1);
+ TIFFError("get_subimage_count",
+ "Invalid image count: %d columns, %d rows", ximages, yimages);
+ return (-1);
}
- for (i = 0; i < yimages; i++)
+ for (i = 0; i < yimages; i++)
{
- for (j = 0; j < ximages; j++)
- {
- pages++;
- *npages = pages;
- fprintf(fd, "%%%%Page: %d %d\n", pages, pages);
-
- /* Write out the PageSize info for non EPS files */
- if (!generateEPSF && ( level2 || level3 ))
- {
- if (psPageSize(fd, rotation, pgwidth, pgheight,
- view_width, view_height, pswidth, psheight))
- return (-1);
- }
- fprintf(fd, "gsave\n");
- fprintf(fd, "100 dict begin\n");
- if (exportMaskedImage(fd, view_width, view_height, pswidth, psheight,
- i, j, left_margin, bottom_margin,
- scale, center, rotation))
+ for (j = 0; j < ximages; j++)
{
- TIFFError("exportMaskedImage", "Invalid image parameters.");
- return (-1);
+ pages++;
+ *npages = pages;
+ fprintf(fd, "%%%%Page: %d %d\n", pages, pages);
+
+ /* Write out the PageSize info for non EPS files */
+ if (!generateEPSF && (level2 || level3))
+ {
+ if (psPageSize(fd, rotation, pgwidth, pgheight, view_width,
+ view_height, pswidth, psheight))
+ return (-1);
+ }
+ fprintf(fd, "gsave\n");
+ fprintf(fd, "100 dict begin\n");
+ if (exportMaskedImage(fd, view_width, view_height, pswidth,
+ psheight, i, j, left_margin, bottom_margin,
+ scale, center, rotation))
+ {
+ TIFFError("exportMaskedImage", "Invalid image parameters.");
+ return (-1);
+ }
+ PSpage(fd, tif, pixwidth, pixheight);
+ fprintf(fd, "end\n");
+ fprintf(fd, "grestore\n");
+ fprintf(fd, "showpage\n");
}
- PSpage(fd, tif, pixwidth, pixheight);
- fprintf(fd, "end\n");
- fprintf(fd, "grestore\n");
- fprintf(fd, "showpage\n");
- }
}
- return (pages);
- }
+ return (pages);
+}
/* Compute scale factor and write out file header */
int psStart(FILE *fd, int npages, int auto_rotate, int *rotation, double *scale,
double ox, double oy, double pgwidth, double pgheight,
- double reqwidth, double reqheight, double pswidth, double psheight,
- double left_offset, double bottom_offset)
- {
- double maxsource = 0.0; /* Used for auto rotations */
- double maxtarget = 0.0;
- double xscale = 1.0, yscale = 1.0;
- double splitheight;
- double splitwidth;
- double view_width = 0.0, view_height = 0.0;
- double page_width = 0.0, page_height = 0.0;
-
- /* Splitheight and splitwidth are in inches */
- splitheight = maxPageHeight * PS_UNIT_SIZE;
- splitwidth = maxPageWidth * PS_UNIT_SIZE;
-
- page_width = pgwidth * PS_UNIT_SIZE;
- page_height = pgheight * PS_UNIT_SIZE;
-
- /* If user has specified a page width and height and requested the
- * image to be auto-rotated to fit on that media, we match the
- * longest dimension of the image to the longest dimension of the
- * target media but we have to ignore auto rotate if user specified
- * maxPageHeight since this makes life way too complicated. */
- if (auto_rotate)
- {
- if ((splitheight != 0) || (splitwidth != 0))
- {
- TIFFError ("psStart", "Auto-rotate is incompatible with page splitting ");
- return (1);
- }
-
- /* Find longest edges in image and output media */
- maxsource = (pswidth >= psheight) ? pswidth : psheight;
- maxtarget = (reqwidth >= reqheight) ? reqwidth : reqheight;
-
- if (((maxsource == pswidth) && (maxtarget != reqwidth)) ||
- ((maxsource == psheight) && (maxtarget != reqheight)))
- { /* optimal orientation does not match input orientation */
- *rotation = 90;
- xscale = (reqwidth - left_offset)/psheight;
- yscale = (reqheight - bottom_offset)/pswidth;
- }
- else /* optimal orientation matches input orientation */
- {
- xscale = (reqwidth - left_offset)/pswidth;
- yscale = (reqheight - bottom_offset)/psheight;
- }
- *scale = (xscale < yscale) ? xscale : yscale;
+ double reqwidth, double reqheight, double pswidth, double psheight,
+ double left_offset, double bottom_offset)
+{
+ double maxsource = 0.0; /* Used for auto rotations */
+ double maxtarget = 0.0;
+ double xscale = 1.0, yscale = 1.0;
+ double splitheight;
+ double splitwidth;
+ double view_width = 0.0, view_height = 0.0;
+ double page_width = 0.0, page_height = 0.0;
+
+ /* Splitheight and splitwidth are in inches */
+ splitheight = maxPageHeight * PS_UNIT_SIZE;
+ splitwidth = maxPageWidth * PS_UNIT_SIZE;
+
+ page_width = pgwidth * PS_UNIT_SIZE;
+ page_height = pgheight * PS_UNIT_SIZE;
+
+ /* If user has specified a page width and height and requested the
+ * image to be auto-rotated to fit on that media, we match the
+ * longest dimension of the image to the longest dimension of the
+ * target media but we have to ignore auto rotate if user specified
+ * maxPageHeight since this makes life way too complicated. */
+ if (auto_rotate)
+ {
+ if ((splitheight != 0) || (splitwidth != 0))
+ {
+ TIFFError("psStart",
+ "Auto-rotate is incompatible with page splitting ");
+ return (1);
+ }
- /* Do not scale image beyond original size */
- if (*scale > 1.0)
- *scale = 1.0;
+ /* Find longest edges in image and output media */
+ maxsource = (pswidth >= psheight) ? pswidth : psheight;
+ maxtarget = (reqwidth >= reqheight) ? reqwidth : reqheight;
- /* Set the size of the displayed image to requested page size
- * and optimal orientation.
- */
- if (!npages)
- PSHead(fd, reqwidth, reqheight, ox, oy);
+ if (((maxsource == pswidth) && (maxtarget != reqwidth)) ||
+ ((maxsource == psheight) && (maxtarget != reqheight)))
+ { /* optimal orientation does not match input orientation */
+ *rotation = 90;
+ xscale = (reqwidth - left_offset) / psheight;
+ yscale = (reqheight - bottom_offset) / pswidth;
+ }
+ else /* optimal orientation matches input orientation */
+ {
+ xscale = (reqwidth - left_offset) / pswidth;
+ yscale = (reqheight - bottom_offset) / psheight;
+ }
+ *scale = (xscale < yscale) ? xscale : yscale;
- return (0);
+ /* Do not scale image beyond original size */
+ if (*scale > 1.0)
+ *scale = 1.0;
+
+ /* Set the size of the displayed image to requested page size
+ * and optimal orientation.
+ */
+ if (!npages)
+ PSHead(fd, reqwidth, reqheight, ox, oy);
+
+ return (0);
}
- /* N.B. If pgwidth or pgheight are set from maxPageHeight/Width,
- * we have a problem with the tests below under splitheight.
- */
+ /* N.B. If pgwidth or pgheight are set from maxPageHeight/Width,
+ * we have a problem with the tests below under splitheight.
+ */
- switch (*rotation) /* Auto rotate has NOT been specified */
+ switch (*rotation) /* Auto rotate has NOT been specified */
{
- case 0:
- case 180: if ((splitheight != 0) || (splitwidth != 0))
- { /* Viewport clipped to maxPageHeight or maxPageWidth */
+ case 0:
+ case 180:
+ if ((splitheight != 0) || (splitwidth != 0))
+ { /* Viewport clipped to maxPageHeight or maxPageWidth */
if ((page_width != 0) || (page_height != 0)) /* Image scaled */
- {
- xscale = (reqwidth - left_offset) / (page_width ? page_width : pswidth);
- yscale = (reqheight - bottom_offset) / (page_height ? page_height : psheight);
- *scale = (xscale < yscale) ? xscale : yscale;
- /*
- if (*scale > 1.0)
+ {
+ xscale = (reqwidth - left_offset) /
+ (page_width ? page_width : pswidth);
+ yscale = (reqheight - bottom_offset) /
+ (page_height ? page_height : psheight);
+ *scale = (xscale < yscale) ? xscale : yscale;
+ /*
+ if (*scale > 1.0)
+ *scale = 1.0;
+ */
+ }
+ else /* Image clipped but not scaled */
*scale = 1.0;
- */
- }
- else /* Image clipped but not scaled */
- *scale = 1.0;
view_width = splitwidth ? splitwidth : *scale * pswidth;
- view_height = splitheight ? splitheight: *scale * psheight;
- }
- else /* Viewport not clipped to maxPageHeight or maxPageWidth */
- {
+ view_height = splitheight ? splitheight : *scale * psheight;
+ }
+ else /* Viewport not clipped to maxPageHeight or maxPageWidth */
+ {
if ((page_width != 0) || (page_height != 0))
- { /* Image scaled */
- xscale = (reqwidth - left_offset) / pswidth;
- yscale = (reqheight - bottom_offset) / psheight;
+ { /* Image scaled */
+ xscale = (reqwidth - left_offset) / pswidth;
+ yscale = (reqheight - bottom_offset) / psheight;
- view_width = reqwidth;
- view_height = reqheight;
- }
+ view_width = reqwidth;
+ view_height = reqheight;
+ }
else
- { /* Image not scaled */
- xscale = (pswidth - left_offset)/pswidth;
- yscale = (psheight - bottom_offset)/psheight;
-
- view_width = pswidth;
- view_height = psheight;
- }
- }
- break;
- case 90:
- case 270: if ((splitheight != 0) || (splitwidth != 0))
- { /* Viewport clipped to maxPageHeight or maxPageWidth */
+ { /* Image not scaled */
+ xscale = (pswidth - left_offset) / pswidth;
+ yscale = (psheight - bottom_offset) / psheight;
+
+ view_width = pswidth;
+ view_height = psheight;
+ }
+ }
+ break;
+ case 90:
+ case 270:
+ if ((splitheight != 0) || (splitwidth != 0))
+ { /* Viewport clipped to maxPageHeight or maxPageWidth */
if ((page_width != 0) || (page_height != 0)) /* Image scaled */
- {
- xscale = (reqwidth - left_offset)/ psheight;
- yscale = (reqheight - bottom_offset)/ pswidth;
- *scale = (xscale < yscale) ? xscale : yscale;
- /*
- if (*scale > 1.0)
+ {
+ xscale = (reqwidth - left_offset) / psheight;
+ yscale = (reqheight - bottom_offset) / pswidth;
+ *scale = (xscale < yscale) ? xscale : yscale;
+ /*
+ if (*scale > 1.0)
+ *scale = 1.0;
+ */
+ }
+ else /* Image clipped but not scaled */
*scale = 1.0;
- */
- }
- else /* Image clipped but not scaled */
- *scale = 1.0;
view_width = splitwidth ? splitwidth : *scale * psheight;
view_height = splitheight ? splitheight : *scale * pswidth;
- }
- else /* Viewport not clipped to maxPageHeight or maxPageWidth */
- {
+ }
+ else /* Viewport not clipped to maxPageHeight or maxPageWidth */
+ {
if ((page_width != 0) || (page_height != 0)) /* Image scaled */
- {
- xscale = (reqwidth - left_offset) / psheight;
- yscale = (reqheight - bottom_offset) / pswidth;
+ {
+ xscale = (reqwidth - left_offset) / psheight;
+ yscale = (reqheight - bottom_offset) / pswidth;
- view_width = reqwidth;
- view_height = reqheight;
- }
+ view_width = reqwidth;
+ view_height = reqheight;
+ }
else
- {
- xscale = (pswidth - left_offset)/ psheight;
- yscale = (psheight - bottom_offset)/ pswidth;
+ {
+ xscale = (pswidth - left_offset) / psheight;
+ yscale = (psheight - bottom_offset) / pswidth;
- view_width = psheight;
- view_height = pswidth;
- }
+ view_width = psheight;
+ view_height = pswidth;
}
- break;
- default: TIFFError ("psPageSize", "Invalid rotation %d", *rotation);
- return (1);
+ }
+ break;
+ default:
+ TIFFError("psPageSize", "Invalid rotation %d", *rotation);
+ return (1);
}
- if (!npages)
- PSHead(fd, (page_width ? page_width : view_width), (page_height ? page_height : view_height), ox, oy);
+ if (!npages)
+ PSHead(fd, (page_width ? page_width : view_width),
+ (page_height ? page_height : view_height), ox, oy);
- *scale = (xscale < yscale) ? xscale : yscale;
- if (*scale > 1.0)
- *scale = 1.0;
+ *scale = (xscale < yscale) ? xscale : yscale;
+ if (*scale > 1.0)
+ *scale = 1.0;
- return (0);
- }
+ return (0);
+}
-int get_viewport (double pgwidth, double pgheight, double pswidth, double psheight,
- double *view_width, double *view_height, int rotation)
- {
- /* Only one of maxPageHeight or maxPageWidth can be specified */
- if (maxPageHeight != 0) /* Clip the viewport to maxPageHeight on each page */
+int get_viewport(double pgwidth, double pgheight, double pswidth,
+ double psheight, double *view_width, double *view_height,
+ int rotation)
+{
+ /* Only one of maxPageHeight or maxPageWidth can be specified */
+ if (maxPageHeight !=
+ 0) /* Clip the viewport to maxPageHeight on each page */
{
- if (pgheight != 0 && pgheight < maxPageHeight)
- *view_height = pgheight * PS_UNIT_SIZE;
- else
- *view_height = maxPageHeight * PS_UNIT_SIZE;
- /*
- * if (res_unit == RESUNIT_CENTIMETER)
- * *view_height /= 2.54F;
- */
+ if (pgheight != 0 && pgheight < maxPageHeight)
+ *view_height = pgheight * PS_UNIT_SIZE;
+ else
+ *view_height = maxPageHeight * PS_UNIT_SIZE;
+ /*
+ * if (res_unit == RESUNIT_CENTIMETER)
+ * *view_height /= 2.54F;
+ */
}
- else
- {
- if (pgheight != 0) /* User has set PageHeight with -h flag */
- {
- *view_height = pgheight * PS_UNIT_SIZE; /* Postscript size for Page Height in inches */
- /* if (res_unit == RESUNIT_CENTIMETER)
- * *view_height /= 2.54F;
- */
- }
- else /* If no width or height are specified, use the original size from image */
- switch (rotation)
+ else
+ {
+ if (pgheight != 0) /* User has set PageHeight with -h flag */
{
- default:
- case 0:
- case 180: *view_height = psheight;
- break;
- case 90:
- case 270: *view_height = pswidth;
- break;
- }
+ *view_height =
+ pgheight *
+ PS_UNIT_SIZE; /* Postscript size for Page Height in inches */
+ /* if (res_unit == RESUNIT_CENTIMETER)
+ * *view_height /= 2.54F;
+ */
+ }
+ else /* If no width or height are specified, use the original size from
+ image */
+ switch (rotation)
+ {
+ default:
+ case 0:
+ case 180:
+ *view_height = psheight;
+ break;
+ case 90:
+ case 270:
+ *view_height = pswidth;
+ break;
+ }
}
- if (maxPageWidth != 0) /* Clip the viewport to maxPageWidth on each page */
+ if (maxPageWidth != 0) /* Clip the viewport to maxPageWidth on each page */
{
- if (pgwidth != 0 && pgwidth < maxPageWidth)
- *view_width = pgwidth * PS_UNIT_SIZE;
- else
- *view_width = maxPageWidth * PS_UNIT_SIZE;
- /* if (res_unit == RESUNIT_CENTIMETER)
- * *view_width /= 2.54F;
- */
+ if (pgwidth != 0 && pgwidth < maxPageWidth)
+ *view_width = pgwidth * PS_UNIT_SIZE;
+ else
+ *view_width = maxPageWidth * PS_UNIT_SIZE;
+ /* if (res_unit == RESUNIT_CENTIMETER)
+ * *view_width /= 2.54F;
+ */
}
- else
- {
- if (pgwidth != 0) /* User has set PageWidth with -w flag */
- {
- *view_width = pgwidth * PS_UNIT_SIZE; /* Postscript size for Page Width in inches */
- /* if (res_unit == RESUNIT_CENTIMETER)
- * *view_width /= 2.54F;
- */
- }
- else /* If no width or height are specified, use the original size from image */
- switch (rotation)
+ else
+ {
+ if (pgwidth != 0) /* User has set PageWidth with -w flag */
{
- default:
- case 0:
- case 180: *view_width = pswidth;
- break;
- case 90:
- case 270: *view_width = psheight; /* (*view_height / psheight) * psheight; */
- break;
- }
- }
-
- return (0);
- }
-
-/* pgwidth and pgheight specify page width and height in inches from -h and -w flags
- * lm and bm are the LeftMargin and BottomMargin in inches
- * center causes the image to be centered on the page if the paper size is
- * larger than the image size
- * returns the sequence number of the page processed or -1 on error
+ *view_width =
+ pgwidth *
+ PS_UNIT_SIZE; /* Postscript size for Page Width in inches */
+ /* if (res_unit == RESUNIT_CENTIMETER)
+ * *view_width /= 2.54F;
+ */
+ }
+ else /* If no width or height are specified, use the original size from
+ image */
+ switch (rotation)
+ {
+ default:
+ case 0:
+ case 180:
+ *view_width = pswidth;
+ break;
+ case 90:
+ case 270:
+ *view_width =
+ psheight; /* (*view_height / psheight) * psheight; */
+ break;
+ }
+ }
+
+ return (0);
+}
+
+/* pgwidth and pgheight specify page width and height in inches from -h and -w
+ * flags lm and bm are the LeftMargin and BottomMargin in inches center causes
+ * the image to be centered on the page if the paper size is larger than the
+ * image size returns the sequence number of the page processed or -1 on error
*/
-int TIFF2PS(FILE* fd, TIFF* tif, double pgwidth, double pgheight, double lm, double bm, int center)
- {
- uint32_t pixwidth = 0, pixheight = 0; /* Image width and height in pixels */
- double ox = 0.0, oy = 0.0; /* Offset from current Postscript origin */
- double pswidth, psheight; /* Original raw image width and height in points */
- double view_width, view_height; /* Viewport width and height in points */
- double scale = 1.0;
- double left_offset = lm * PS_UNIT_SIZE;
- double bottom_offset = bm * PS_UNIT_SIZE;
- uint32_t subfiletype;
- uint16_t* sampleinfo;
- static int npages = 0;
-
- if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox))
- ox = 0;
- if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy))
- oy = 0;
-
- /* Consolidated all the tag information into one code segment, Richard Nolde */
- do {
- tf_numberstrips = TIFFNumberOfStrips(tif);
- TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &tf_rowsperstrip);
- TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bitspersample);
- TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
- TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfiguration);
- TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);
- TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo);
- alpha = (extrasamples == 1 && sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
- if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric))
- {
- switch (samplesperpixel - extrasamples)
- {
- case 1: if (isCCITTCompression(tif))
- photometric = PHOTOMETRIC_MINISWHITE;
+int TIFF2PS(FILE *fd, TIFF *tif, double pgwidth, double pgheight, double lm,
+ double bm, int center)
+{
+ uint32_t pixwidth = 0, pixheight = 0; /* Image width and height in pixels */
+ double ox = 0.0, oy = 0.0; /* Offset from current Postscript origin */
+ double pswidth,
+ psheight; /* Original raw image width and height in points */
+ double view_width, view_height; /* Viewport width and height in points */
+ double scale = 1.0;
+ double left_offset = lm * PS_UNIT_SIZE;
+ double bottom_offset = bm * PS_UNIT_SIZE;
+ uint32_t subfiletype;
+ uint16_t *sampleinfo;
+ static int npages = 0;
+
+ if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox))
+ ox = 0;
+ if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy))
+ oy = 0;
+
+ /* Consolidated all the tag information into one code segment, Richard Nolde
+ */
+ do
+ {
+ tf_numberstrips = TIFFNumberOfStrips(tif);
+ TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &tf_rowsperstrip);
+ TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bitspersample);
+ TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
+ TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfiguration);
+ TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);
+ TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &extrasamples,
+ &sampleinfo);
+ alpha = (extrasamples == 1 && sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
+ if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric))
+ {
+ switch (samplesperpixel - extrasamples)
+ {
+ case 1:
+ if (isCCITTCompression(tif))
+ photometric = PHOTOMETRIC_MINISWHITE;
else
- photometric = PHOTOMETRIC_MINISBLACK;
+ photometric = PHOTOMETRIC_MINISBLACK;
break;
- case 3: photometric = PHOTOMETRIC_RGB;
+ case 3:
+ photometric = PHOTOMETRIC_RGB;
break;
- case 4: photometric = PHOTOMETRIC_SEPARATED;
+ case 4:
+ photometric = PHOTOMETRIC_SEPARATED;
break;
}
- }
-
- /* Read image tags for width and height in pixels pixwidth, pixheight,
- * and convert to points pswidth, psheight
- */
- setupPageState(tif, &pixwidth, &pixheight, &pswidth, &psheight);
- view_width = pswidth;
- view_height = psheight;
-
- if (get_viewport (pgwidth, pgheight, pswidth, psheight, &view_width, &view_height, rotation))
- {
- TIFFError("get_viewport", "Unable to set image viewport");
- return (1);
- }
-
- /* Write the Postscript file header with Bounding Box and Page Size definitions */
- if (psStart(fd, npages, auto_rotate, &rotation, &scale, ox, oy,
- pgwidth, pgheight, view_width, view_height, pswidth, psheight,
- left_offset, bottom_offset))
- return (-1);
-
- if (checkImage(tif)) /* Aborts if unsupported image parameters */
- {
- tf_bytesperrow = TIFFScanlineSize(tif);
-
- /* Set viewport clipping and scaling options */
- if ((maxPageHeight) || (maxPageWidth) || (pgwidth != 0) || (pgheight != 0))
- {
- if ((maxPageHeight) || (maxPageWidth)) /* used -H or -W option */
- {
- if (psMaskImage(fd, tif, rotation, center, &npages, pixwidth, pixheight,
- left_offset, bottom_offset, pgwidth, pgheight,
- pswidth, psheight, scale) < 0)
+ }
+
+ /* Read image tags for width and height in pixels pixwidth, pixheight,
+ * and convert to points pswidth, psheight
+ */
+ setupPageState(tif, &pixwidth, &pixheight, &pswidth, &psheight);
+ view_width = pswidth;
+ view_height = psheight;
+
+ if (get_viewport(pgwidth, pgheight, pswidth, psheight, &view_width,
+ &view_height, rotation))
+ {
+ TIFFError("get_viewport", "Unable to set image viewport");
+ return (1);
+ }
+
+ /* Write the Postscript file header with Bounding Box and Page Size
+ * definitions */
+ if (psStart(fd, npages, auto_rotate, &rotation, &scale, ox, oy, pgwidth,
+ pgheight, view_width, view_height, pswidth, psheight,
+ left_offset, bottom_offset))
return (-1);
- }
- else /* N.B. Setting maxPageHeight no longer sets pgheight */
- {
- if (pgwidth != 0 || pgheight != 0)
- {
- /* User did not specify a maximum page height or width using -H or -W flag
- * but did use -h or -w flag to scale to a specific size page.
- */
- npages++;
- fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
-
- if (!generateEPSF && ( level2 || level3 ))
- {
- /* Write out the PageSize info for non EPS files */
- if (psPageSize(fd, rotation, pgwidth, pgheight,
- view_width, view_height, pswidth, psheight))
- return (-1);
- }
- fprintf(fd, "gsave\n");
- fprintf(fd, "100 dict begin\n");
- if (psScaleImage(fd, scale, rotation, center, view_width, view_height,
- pswidth, psheight, left_offset, bottom_offset))
- return (-1);
-
- PSpage(fd, tif, pixwidth, pixheight);
- fprintf(fd, "end\n");
- fprintf(fd, "grestore\n");
- fprintf(fd, "showpage\n");
+
+ if (checkImage(tif)) /* Aborts if unsupported image parameters */
+ {
+ tf_bytesperrow = TIFFScanlineSize(tif);
+
+ /* Set viewport clipping and scaling options */
+ if ((maxPageHeight) || (maxPageWidth) || (pgwidth != 0) ||
+ (pgheight != 0))
+ {
+ if ((maxPageHeight) ||
+ (maxPageWidth)) /* used -H or -W option */
+ {
+ if (psMaskImage(fd, tif, rotation, center, &npages,
+ pixwidth, pixheight, left_offset,
+ bottom_offset, pgwidth, pgheight, pswidth,
+ psheight, scale) < 0)
+ return (-1);
+ }
+ else /* N.B. Setting maxPageHeight no longer sets pgheight */
+ {
+ if (pgwidth != 0 || pgheight != 0)
+ {
+ /* User did not specify a maximum page height or width
+ * using -H or -W flag but did use -h or -w flag to
+ * scale to a specific size page.
+ */
+ npages++;
+ fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
+
+ if (!generateEPSF && (level2 || level3))
+ {
+ /* Write out the PageSize info for non EPS files */
+ if (psPageSize(fd, rotation, pgwidth, pgheight,
+ view_width, view_height, pswidth,
+ psheight))
+ return (-1);
+ }
+ fprintf(fd, "gsave\n");
+ fprintf(fd, "100 dict begin\n");
+ if (psScaleImage(fd, scale, rotation, center,
+ view_width, view_height, pswidth,
+ psheight, left_offset, bottom_offset))
+ return (-1);
+
+ PSpage(fd, tif, pixwidth, pixheight);
+ fprintf(fd, "end\n");
+ fprintf(fd, "grestore\n");
+ fprintf(fd, "showpage\n");
+ }
+ }
+ }
+ else /* Simple rotation: user did not use -H, -W, -h or -w */
+ {
+ npages++;
+ fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
+
+ if (!generateEPSF && (level2 || level3))
+ {
+ /* Write out the PageSize info for non EPS files */
+ if (psPageSize(fd, rotation, pgwidth, pgheight, view_width,
+ view_height, pswidth, psheight))
+ return (-1);
+ }
+ fprintf(fd, "gsave\n");
+ fprintf(fd, "100 dict begin\n");
+ if (psRotateImage(fd, rotation, pswidth, psheight, left_offset,
+ bottom_offset))
+ return (-1);
+
+ PSpage(fd, tif, pixwidth, pixheight);
+ fprintf(fd, "end\n");
+ fprintf(fd, "grestore\n");
+ fprintf(fd, "showpage\n");
}
- }
}
- else /* Simple rotation: user did not use -H, -W, -h or -w */
- {
- npages++;
- fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
-
- if (!generateEPSF && ( level2 || level3 ))
- {
- /* Write out the PageSize info for non EPS files */
- if (psPageSize(fd, rotation, pgwidth, pgheight,
- view_width, view_height, pswidth, psheight))
- return (-1);
- }
- fprintf(fd, "gsave\n");
- fprintf(fd, "100 dict begin\n");
- if (psRotateImage(fd, rotation, pswidth, psheight, left_offset, bottom_offset))
- return (-1);
-
- PSpage(fd, tif, pixwidth, pixheight);
- fprintf(fd, "end\n");
- fprintf(fd, "grestore\n");
- fprintf(fd, "showpage\n");
- }
- }
- if (generateEPSF)
- break;
- if (auto_rotate)
- rotation = 0.0;
- TIFFGetFieldDefaulted(tif, TIFFTAG_SUBFILETYPE, &subfiletype);
- } while (((subfiletype & FILETYPE_PAGE) || printAll) && TIFFReadDirectory(tif));
-
-return(npages);
+ if (generateEPSF)
+ break;
+ if (auto_rotate)
+ rotation = 0.0;
+ TIFFGetFieldDefaulted(tif, TIFFTAG_SUBFILETYPE, &subfiletype);
+ } while (((subfiletype & FILETYPE_PAGE) || printAll) &&
+ TIFFReadDirectory(tif));
+
+ return (npages);
}
static const char DuplexPreamble[] = "\
@@ -1686,1391 +1898,1506 @@ gsave newpath clippath pathbbox grestore\n\
dup 1 lt { dup scale } { pop } ifelse\n\
";
-void
-PSHead(FILE *fd, double pagewidth, double pageheight, double xoff, double yoff)
+void PSHead(FILE *fd, double pagewidth, double pageheight, double xoff,
+ double yoff)
{
- time_t t;
-
- t = time(0);
- fprintf(fd, "%%!PS-Adobe-3.0%s\n", generateEPSF ? " EPSF-3.0" : "");
- fprintf(fd, "%%%%Creator: %s\n", creator ? creator : "tiff2ps");
- fprintf(fd, "%%%%Title: %s\n", title ? title : filename);
- fprintf(fd, "%%%%CreationDate: %s", ctime(&t));
- fprintf(fd, "%%%%DocumentData: Clean7Bit\n");
- /* NB: should use PageBoundingBox for each page instead of BoundingBox *
- * PageBoundingBox DSC added in PSPageSize function, R Nolde 09-01-2010
- */
- fprintf(fd, "%%%%Origin: %"PRId32" %"PRId32"\n", (int32_t) xoff, (int32_t) yoff);
- fprintf(fd, "%%%%BoundingBox: 0 0 %"PRId32" %"PRId32"\n",
- (int32_t) ceil(pagewidth), (int32_t) ceil(pageheight));
-
- fprintf(fd, "%%%%LanguageLevel: %d\n", (level3 ? 3 : (level2 ? 2 : 1)));
- if (generateEPSF == TRUE)
- fprintf(fd, "%%%%Pages: 1 1\n");
- else
- fprintf(fd, "%%%%Pages: (atend)\n");
- fprintf(fd, "%%%%EndComments\n");
- if (generateEPSF == FALSE)
- {
- fprintf(fd, "%%%%BeginSetup\n");
- if (PSduplex)
- fprintf(fd, "%s", DuplexPreamble);
- if (PStumble)
- fprintf(fd, "%s", TumblePreamble);
- if (PSavoiddeadzone && (level2 || level3))
- fprintf(fd, "%s", AvoidDeadZonePreamble);
- fprintf(fd, "%%%%EndSetup\n");
- }
+ time_t t;
+
+ t = time(0);
+ fprintf(fd, "%%!PS-Adobe-3.0%s\n", generateEPSF ? " EPSF-3.0" : "");
+ fprintf(fd, "%%%%Creator: %s\n", creator ? creator : "tiff2ps");
+ fprintf(fd, "%%%%Title: %s\n", title ? title : filename);
+ fprintf(fd, "%%%%CreationDate: %s", ctime(&t));
+ fprintf(fd, "%%%%DocumentData: Clean7Bit\n");
+ /* NB: should use PageBoundingBox for each page instead of BoundingBox *
+ * PageBoundingBox DSC added in PSPageSize function, R Nolde 09-01-2010
+ */
+ fprintf(fd, "%%%%Origin: %" PRId32 " %" PRId32 "\n", (int32_t)xoff,
+ (int32_t)yoff);
+ fprintf(fd, "%%%%BoundingBox: 0 0 %" PRId32 " %" PRId32 "\n",
+ (int32_t)ceil(pagewidth), (int32_t)ceil(pageheight));
+
+ fprintf(fd, "%%%%LanguageLevel: %d\n", (level3 ? 3 : (level2 ? 2 : 1)));
+ if (generateEPSF == TRUE)
+ fprintf(fd, "%%%%Pages: 1 1\n");
+ else
+ fprintf(fd, "%%%%Pages: (atend)\n");
+ fprintf(fd, "%%%%EndComments\n");
+ if (generateEPSF == FALSE)
+ {
+ fprintf(fd, "%%%%BeginSetup\n");
+ if (PSduplex)
+ fprintf(fd, "%s", DuplexPreamble);
+ if (PStumble)
+ fprintf(fd, "%s", TumblePreamble);
+ if (PSavoiddeadzone && (level2 || level3))
+ fprintf(fd, "%s", AvoidDeadZonePreamble);
+ fprintf(fd, "%%%%EndSetup\n");
+ }
}
-void
-PSTail(FILE *fd, int npages)
+void PSTail(FILE *fd, int npages)
{
- fprintf(fd, "%%%%Trailer\n");
- if (generateEPSF == FALSE)
- fprintf(fd, "%%%%Pages: %d\n", npages);
- fprintf(fd, "%%%%EOF\n");
+ fprintf(fd, "%%%%Trailer\n");
+ if (generateEPSF == FALSE)
+ fprintf(fd, "%%%%Pages: %d\n", npages);
+ fprintf(fd, "%%%%EOF\n");
}
-static int
-checkcmap(TIFF* tif, int n, uint16_t* r, uint16_t* g, uint16_t* b)
+static int checkcmap(TIFF *tif, int n, uint16_t *r, uint16_t *g, uint16_t *b)
{
- (void) tif;
- while (n-- > 0)
- if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
- return (16);
- TIFFWarning(filename, "Assuming 8-bit colormap");
- return (8);
+ (void)tif;
+ while (n-- > 0)
+ if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
+ return (16);
+ TIFFWarning(filename, "Assuming 8-bit colormap");
+ return (8);
}
-static void
-PS_Lvl2colorspace(FILE* fd, TIFF* tif)
+static void PS_Lvl2colorspace(FILE *fd, TIFF *tif)
{
- uint16_t *rmap, *gmap, *bmap;
- int i, num_colors;
- const char * colorspace_p;
-
- switch ( photometric )
- {
- case PHOTOMETRIC_SEPARATED:
- colorspace_p = "CMYK";
- break;
-
- case PHOTOMETRIC_RGB:
- colorspace_p = "RGB";
- break;
-
- default:
- colorspace_p = "Gray";
- }
-
- /*
- * Set up PostScript Level 2 colorspace according to
- * section 4.8 in the PostScript reference manual.
- */
- fputs("% PostScript Level 2 only.\n", fd);
- if (photometric != PHOTOMETRIC_PALETTE) {
- if (photometric == PHOTOMETRIC_YCBCR) {
- /* MORE CODE HERE */
- }
- fprintf(fd, "/Device%s setcolorspace\n", colorspace_p );
- return;
- }
-
- /*
- * Set up an indexed/palette colorspace
- */
- num_colors = (1 << bitspersample);
- if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
- TIFFError(filename,
- "Palette image w/o \"Colormap\" tag");
- return;
- }
- if (checkcmap(tif, num_colors, rmap, gmap, bmap) == 16) {
- /*
- * Convert colormap to 8-bits values.
- */
-#define CVT(x) (((x) * 255) / ((1L<<16)-1))
- for (i = 0; i < num_colors; i++) {
- rmap[i] = CVT(rmap[i]);
- gmap[i] = CVT(gmap[i]);
- bmap[i] = CVT(bmap[i]);
- }
+ uint16_t *rmap, *gmap, *bmap;
+ int i, num_colors;
+ const char *colorspace_p;
+
+ switch (photometric)
+ {
+ case PHOTOMETRIC_SEPARATED:
+ colorspace_p = "CMYK";
+ break;
+
+ case PHOTOMETRIC_RGB:
+ colorspace_p = "RGB";
+ break;
+
+ default:
+ colorspace_p = "Gray";
+ }
+
+ /*
+ * Set up PostScript Level 2 colorspace according to
+ * section 4.8 in the PostScript reference manual.
+ */
+ fputs("% PostScript Level 2 only.\n", fd);
+ if (photometric != PHOTOMETRIC_PALETTE)
+ {
+ if (photometric == PHOTOMETRIC_YCBCR)
+ {
+ /* MORE CODE HERE */
+ }
+ fprintf(fd, "/Device%s setcolorspace\n", colorspace_p);
+ return;
+ }
+
+ /*
+ * Set up an indexed/palette colorspace
+ */
+ num_colors = (1 << bitspersample);
+ if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap))
+ {
+ TIFFError(filename, "Palette image w/o \"Colormap\" tag");
+ return;
+ }
+ if (checkcmap(tif, num_colors, rmap, gmap, bmap) == 16)
+ {
+ /*
+ * Convert colormap to 8-bits values.
+ */
+#define CVT(x) (((x)*255) / ((1L << 16) - 1))
+ for (i = 0; i < num_colors; i++)
+ {
+ rmap[i] = CVT(rmap[i]);
+ gmap[i] = CVT(gmap[i]);
+ bmap[i] = CVT(bmap[i]);
+ }
#undef CVT
- }
- fprintf(fd, "[ /Indexed /DeviceRGB %d", num_colors - 1);
- if (ascii85) {
- Ascii85Init();
- fputs("\n<~", fd);
- ascii85breaklen -= 2;
- } else
- fputs(" <", fd);
- for (i = 0; i < num_colors; i++) {
- if (ascii85) {
- Ascii85Put((unsigned char)rmap[i], fd);
- Ascii85Put((unsigned char)gmap[i], fd);
- Ascii85Put((unsigned char)bmap[i], fd);
- } else {
- fputs((i % 8) ? " " : "\n ", fd);
- fprintf(fd, "%02"PRIx16"%02"PRIx16"%02"PRIx16"",
- rmap[i], gmap[i], bmap[i]);
- }
- }
- if (ascii85)
- Ascii85Flush(fd);
- else
- fputs(">\n", fd);
- fputs("] setcolorspace\n", fd);
+ }
+ fprintf(fd, "[ /Indexed /DeviceRGB %d", num_colors - 1);
+ if (ascii85)
+ {
+ Ascii85Init();
+ fputs("\n<~", fd);
+ ascii85breaklen -= 2;
+ }
+ else
+ fputs(" <", fd);
+ for (i = 0; i < num_colors; i++)
+ {
+ if (ascii85)
+ {
+ Ascii85Put((unsigned char)rmap[i], fd);
+ Ascii85Put((unsigned char)gmap[i], fd);
+ Ascii85Put((unsigned char)bmap[i], fd);
+ }
+ else
+ {
+ fputs((i % 8) ? " " : "\n ", fd);
+ fprintf(fd, "%02" PRIx16 "%02" PRIx16 "%02" PRIx16 "", rmap[i],
+ gmap[i], bmap[i]);
+ }
+ }
+ if (ascii85)
+ Ascii85Flush(fd);
+ else
+ fputs(">\n", fd);
+ fputs("] setcolorspace\n", fd);
}
-static int
-PS_Lvl2ImageDict(FILE* fd, TIFF* tif, uint32_t w, uint32_t h)
+static int PS_Lvl2ImageDict(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
{
- int use_rawdata;
- uint32_t tile_width, tile_height;
- uint16_t predictor, minsamplevalue, maxsamplevalue;
- uint32_t repeat_count;
- char im_h[64], im_x[64], im_y[64];
- const char * imageOp = "image";
-
- if ( useImagemask && (bitspersample == 1) )
- imageOp = "imagemask";
-
- (void)strcpy(im_x, "0");
- (void)snprintf(im_y, sizeof(im_y), "%"PRIu32, h);
- (void)snprintf(im_h, sizeof(im_h), "%"PRIu32, h);
- tile_width = w;
- tile_height = h;
- if (TIFFIsTiled(tif)) {
- repeat_count = TIFFNumberOfTiles(tif);
- TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
- TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
- if (tile_width > w || tile_height > h ||
- (w % tile_width) != 0 || (h % tile_height != 0)) {
- /*
- * The tiles does not fit image width and height.
- * Set up a clip rectangle for the image unit square.
- */
- fputs("0 0 1 1 rectclip\n", fd);
- }
- if (tile_width < w) {
- fputs("/im_x 0 def\n", fd);
- (void)strcpy(im_x, "im_x neg");
- }
- if (tile_height < h) {
- fputs("/im_y 0 def\n", fd);
- (void)snprintf(im_y, sizeof(im_y), "%"PRIu32" im_y sub", h);
- }
- } else {
- repeat_count = tf_numberstrips;
- tile_height = tf_rowsperstrip;
- if (tile_height > h)
- tile_height = h;
- if (repeat_count > 1) {
- fputs("/im_y 0 def\n", fd);
- fprintf(fd, "/im_h %"PRIu32" def\n", tile_height);
- (void)strcpy(im_h, "im_h");
- (void)snprintf(im_y, sizeof(im_y), "%"PRIu32" im_y sub", h);
- }
- }
-
- /*
- * Output start of exec block
- */
- fputs("{ % exec\n", fd);
-
- if (repeat_count > 1)
- fprintf(fd, "%"PRIu32" { %% repeat\n", repeat_count);
-
- /*
- * Output filter options and image dictionary.
- */
- if (ascii85)
- fputs(" /im_stream currentfile /ASCII85Decode filter def\n",
- fd);
- fputs(" <<\n", fd);
- fputs(" /ImageType 1\n", fd);
- fprintf(fd, " /Width %"PRIu32"\n", tile_width);
- /*
- * Workaround for some software that may crash when last strip
- * of image contains fewer number of scanlines than specified
- * by the `/Height' variable. So for stripped images with multiple
- * strips we will set `/Height' as `im_h', because one is
- * recalculated for each strip - including the (smaller) final strip.
- * For tiled images and images with only one strip `/Height' will
- * contain number of scanlines in tile (or image height in case of
- * one-stripped image).
- */
- if (TIFFIsTiled(tif) || tf_numberstrips == 1)
- fprintf(fd, " /Height %"PRIu32"\n", tile_height);
- else
- fprintf(fd, " /Height im_h\n");
-
- if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
- fputs(" /MultipleDataSources true\n", fd);
- fprintf(fd, " /ImageMatrix [ %"PRIu32" 0 0 %"PRId32" %s %s ]\n",
- w, - (int32_t)h, im_x, im_y);
- fprintf(fd, " /BitsPerComponent %"PRIu16"\n", bitspersample);
- fprintf(fd, " /Interpolate %s\n", interpolate ? "true" : "false");
-
- switch (samplesperpixel - extrasamples) {
- case 1:
- switch (photometric) {
- case PHOTOMETRIC_MINISBLACK:
- fputs(" /Decode [0 1]\n", fd);
- break;
- case PHOTOMETRIC_MINISWHITE:
- switch (compression) {
- case COMPRESSION_CCITTRLE:
- case COMPRESSION_CCITTRLEW:
- case COMPRESSION_CCITTFAX3:
- case COMPRESSION_CCITTFAX4:
- /*
- * Manage inverting with /Blackis1 flag
- * since there might be uncompressed parts
- */
- fputs(" /Decode [0 1]\n", fd);
- break;
- default:
- /*
- * ERROR...
- */
- fputs(" /Decode [1 0]\n", fd);
- break;
- }
- break;
- case PHOTOMETRIC_PALETTE:
- TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE,
- &minsamplevalue);
- TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE,
- &maxsamplevalue);
- fprintf(fd, " /Decode [%"PRIu16" %"PRIu16"]\n",
- minsamplevalue, maxsamplevalue);
- break;
- default:
- /*
- * ERROR ?
- */
- fputs(" /Decode [0 1]\n", fd);
- break;
- }
- break;
- case 3:
- switch (photometric) {
- case PHOTOMETRIC_RGB:
- fputs(" /Decode [0 1 0 1 0 1]\n", fd);
- break;
- case PHOTOMETRIC_MINISWHITE:
- case PHOTOMETRIC_MINISBLACK:
- default:
- /*
- * ERROR??
- */
- fputs(" /Decode [0 1 0 1 0 1]\n", fd);
- break;
- }
- break;
- case 4:
- /*
- * ERROR??
- */
- fputs(" /Decode [0 1 0 1 0 1 0 1]\n", fd);
- break;
- }
- fputs(" /DataSource", fd);
- if (planarconfiguration == PLANARCONFIG_SEPARATE &&
- samplesperpixel > 1)
- fputs(" [", fd);
- if (ascii85)
- fputs(" im_stream", fd);
- else
- fputs(" currentfile /ASCIIHexDecode filter", fd);
-
- use_rawdata = TRUE;
- switch (compression) {
- case COMPRESSION_NONE: /* 1: uncompressed */
- break;
- case COMPRESSION_CCITTRLE: /* 2: CCITT modified Huffman RLE */
- case COMPRESSION_CCITTRLEW: /* 32771: #1 w/ word alignment */
- case COMPRESSION_CCITTFAX3: /* 3: CCITT Group 3 fax encoding */
- case COMPRESSION_CCITTFAX4: /* 4: CCITT Group 4 fax encoding */
- fputs("\n\t<<\n", fd);
- if (compression == COMPRESSION_CCITTFAX3) {
- uint32_t g3_options;
-
- fputs("\t /EndOfLine true\n", fd);
- fputs("\t /EndOfBlock false\n", fd);
- if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS,
- &g3_options))
- g3_options = 0;
- if (g3_options & GROUP3OPT_2DENCODING)
- fprintf(fd, "\t /K %s\n", im_h);
- if (g3_options & GROUP3OPT_UNCOMPRESSED)
- fputs("\t /Uncompressed true\n", fd);
- if (g3_options & GROUP3OPT_FILLBITS)
- fputs("\t /EncodedByteAlign true\n", fd);
- }
- if (compression == COMPRESSION_CCITTFAX4) {
- uint32_t g4_options;
-
- fputs("\t /K -1\n", fd);
- TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS,
- &g4_options);
- if (g4_options & GROUP4OPT_UNCOMPRESSED)
- fputs("\t /Uncompressed true\n", fd);
- }
- if (!(tile_width == w && w == 1728U))
- fprintf(fd, "\t /Columns %"PRIu32"\n",
- tile_width);
- fprintf(fd, "\t /Rows %s\n", im_h);
- if (compression == COMPRESSION_CCITTRLE ||
- compression == COMPRESSION_CCITTRLEW) {
- fputs("\t /EncodedByteAlign true\n", fd);
- fputs("\t /EndOfBlock false\n", fd);
- }
- if (photometric == PHOTOMETRIC_MINISBLACK)
- fputs("\t /BlackIs1 true\n", fd);
- fprintf(fd, "\t>> /CCITTFaxDecode filter");
- break;
- case COMPRESSION_LZW: /* 5: Lempel-Ziv & Welch */
- TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
- if (predictor == 2) {
- fputs("\n\t<<\n", fd);
- fprintf(fd, "\t /Predictor %"PRIu16"\n", predictor);
- fprintf(fd, "\t /Columns %"PRIu32"\n",
- tile_width);
- fprintf(fd, "\t /Colors %"PRIu16"\n", samplesperpixel);
- fprintf(fd, "\t /BitsPerComponent %"PRIu16"\n",
- bitspersample);
- fputs("\t>>", fd);
- }
- fputs(" /LZWDecode filter", fd);
- break;
- case COMPRESSION_DEFLATE: /* 5: ZIP */
- case COMPRESSION_ADOBE_DEFLATE:
- if ( level3 ) {
- TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
- if (predictor > 1) {
- fprintf(fd, "\t %% PostScript Level 3 only.");
- fputs("\n\t<<\n", fd);
- fprintf(fd, "\t /Predictor %"PRIu16"\n", predictor);
- fprintf(fd, "\t /Columns %"PRIu32"\n",
- tile_width);
- fprintf(fd, "\t /Colors %"PRIu16"\n", samplesperpixel);
- fprintf(fd, "\t /BitsPerComponent %"PRIu16"\n",
- bitspersample);
- fputs("\t>>", fd);
- }
- fputs(" /FlateDecode filter", fd);
- } else {
- use_rawdata = FALSE ;
- }
- break;
- case COMPRESSION_PACKBITS: /* 32773: Macintosh RLE */
- fputs(" /RunLengthDecode filter", fd);
- use_rawdata = TRUE;
- break;
- case COMPRESSION_OJPEG: /* 6: !6.0 JPEG */
- case COMPRESSION_JPEG: /* 7: %JPEG DCT compression */
+ int use_rawdata;
+ uint32_t tile_width, tile_height;
+ uint16_t predictor, minsamplevalue, maxsamplevalue;
+ uint32_t repeat_count;
+ char im_h[64], im_x[64], im_y[64];
+ const char *imageOp = "image";
+
+ if (useImagemask && (bitspersample == 1))
+ imageOp = "imagemask";
+
+ (void)strcpy(im_x, "0");
+ (void)snprintf(im_y, sizeof(im_y), "%" PRIu32, h);
+ (void)snprintf(im_h, sizeof(im_h), "%" PRIu32, h);
+ tile_width = w;
+ tile_height = h;
+ if (TIFFIsTiled(tif))
+ {
+ repeat_count = TIFFNumberOfTiles(tif);
+ TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
+ TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
+ if (tile_width > w || tile_height > h || (w % tile_width) != 0 ||
+ (h % tile_height != 0))
+ {
+ /*
+ * The tiles does not fit image width and height.
+ * Set up a clip rectangle for the image unit square.
+ */
+ fputs("0 0 1 1 rectclip\n", fd);
+ }
+ if (tile_width < w)
+ {
+ fputs("/im_x 0 def\n", fd);
+ (void)strcpy(im_x, "im_x neg");
+ }
+ if (tile_height < h)
+ {
+ fputs("/im_y 0 def\n", fd);
+ (void)snprintf(im_y, sizeof(im_y), "%" PRIu32 " im_y sub", h);
+ }
+ }
+ else
+ {
+ repeat_count = tf_numberstrips;
+ tile_height = tf_rowsperstrip;
+ if (tile_height > h)
+ tile_height = h;
+ if (repeat_count > 1)
+ {
+ fputs("/im_y 0 def\n", fd);
+ fprintf(fd, "/im_h %" PRIu32 " def\n", tile_height);
+ (void)strcpy(im_h, "im_h");
+ (void)snprintf(im_y, sizeof(im_y), "%" PRIu32 " im_y sub", h);
+ }
+ }
+
+ /*
+ * Output start of exec block
+ */
+ fputs("{ % exec\n", fd);
+
+ if (repeat_count > 1)
+ fprintf(fd, "%" PRIu32 " { %% repeat\n", repeat_count);
+
+ /*
+ * Output filter options and image dictionary.
+ */
+ if (ascii85)
+ fputs(" /im_stream currentfile /ASCII85Decode filter def\n", fd);
+ fputs(" <<\n", fd);
+ fputs(" /ImageType 1\n", fd);
+ fprintf(fd, " /Width %" PRIu32 "\n", tile_width);
+ /*
+ * Workaround for some software that may crash when last strip
+ * of image contains fewer number of scanlines than specified
+ * by the `/Height' variable. So for stripped images with multiple
+ * strips we will set `/Height' as `im_h', because one is
+ * recalculated for each strip - including the (smaller) final strip.
+ * For tiled images and images with only one strip `/Height' will
+ * contain number of scanlines in tile (or image height in case of
+ * one-stripped image).
+ */
+ if (TIFFIsTiled(tif) || tf_numberstrips == 1)
+ fprintf(fd, " /Height %" PRIu32 "\n", tile_height);
+ else
+ fprintf(fd, " /Height im_h\n");
+
+ if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
+ fputs(" /MultipleDataSources true\n", fd);
+ fprintf(fd, " /ImageMatrix [ %" PRIu32 " 0 0 %" PRId32 " %s %s ]\n", w,
+ -(int32_t)h, im_x, im_y);
+ fprintf(fd, " /BitsPerComponent %" PRIu16 "\n", bitspersample);
+ fprintf(fd, " /Interpolate %s\n", interpolate ? "true" : "false");
+
+ switch (samplesperpixel - extrasamples)
+ {
+ case 1:
+ switch (photometric)
+ {
+ case PHOTOMETRIC_MINISBLACK:
+ fputs(" /Decode [0 1]\n", fd);
+ break;
+ case PHOTOMETRIC_MINISWHITE:
+ switch (compression)
+ {
+ case COMPRESSION_CCITTRLE:
+ case COMPRESSION_CCITTRLEW:
+ case COMPRESSION_CCITTFAX3:
+ case COMPRESSION_CCITTFAX4:
+ /*
+ * Manage inverting with /Blackis1 flag
+ * since there might be uncompressed parts
+ */
+ fputs(" /Decode [0 1]\n", fd);
+ break;
+ default:
+ /*
+ * ERROR...
+ */
+ fputs(" /Decode [1 0]\n", fd);
+ break;
+ }
+ break;
+ case PHOTOMETRIC_PALETTE:
+ TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE,
+ &minsamplevalue);
+ TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE,
+ &maxsamplevalue);
+ fprintf(fd, " /Decode [%" PRIu16 " %" PRIu16 "]\n",
+ minsamplevalue, maxsamplevalue);
+ break;
+ default:
+ /*
+ * ERROR ?
+ */
+ fputs(" /Decode [0 1]\n", fd);
+ break;
+ }
+ break;
+ case 3:
+ switch (photometric)
+ {
+ case PHOTOMETRIC_RGB:
+ fputs(" /Decode [0 1 0 1 0 1]\n", fd);
+ break;
+ case PHOTOMETRIC_MINISWHITE:
+ case PHOTOMETRIC_MINISBLACK:
+ default:
+ /*
+ * ERROR??
+ */
+ fputs(" /Decode [0 1 0 1 0 1]\n", fd);
+ break;
+ }
+ break;
+ case 4:
+ /*
+ * ERROR??
+ */
+ fputs(" /Decode [0 1 0 1 0 1 0 1]\n", fd);
+ break;
+ }
+ fputs(" /DataSource", fd);
+ if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
+ fputs(" [", fd);
+ if (ascii85)
+ fputs(" im_stream", fd);
+ else
+ fputs(" currentfile /ASCIIHexDecode filter", fd);
+
+ use_rawdata = TRUE;
+ switch (compression)
+ {
+ case COMPRESSION_NONE: /* 1: uncompressed */
+ break;
+ case COMPRESSION_CCITTRLE: /* 2: CCITT modified Huffman RLE */
+ case COMPRESSION_CCITTRLEW: /* 32771: #1 w/ word alignment */
+ case COMPRESSION_CCITTFAX3: /* 3: CCITT Group 3 fax encoding */
+ case COMPRESSION_CCITTFAX4: /* 4: CCITT Group 4 fax encoding */
+ fputs("\n\t<<\n", fd);
+ if (compression == COMPRESSION_CCITTFAX3)
+ {
+ uint32_t g3_options;
+
+ fputs("\t /EndOfLine true\n", fd);
+ fputs("\t /EndOfBlock false\n", fd);
+ if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS, &g3_options))
+ g3_options = 0;
+ if (g3_options & GROUP3OPT_2DENCODING)
+ fprintf(fd, "\t /K %s\n", im_h);
+ if (g3_options & GROUP3OPT_UNCOMPRESSED)
+ fputs("\t /Uncompressed true\n", fd);
+ if (g3_options & GROUP3OPT_FILLBITS)
+ fputs("\t /EncodedByteAlign true\n", fd);
+ }
+ if (compression == COMPRESSION_CCITTFAX4)
+ {
+ uint32_t g4_options;
+
+ fputs("\t /K -1\n", fd);
+ TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS, &g4_options);
+ if (g4_options & GROUP4OPT_UNCOMPRESSED)
+ fputs("\t /Uncompressed true\n", fd);
+ }
+ if (!(tile_width == w && w == 1728U))
+ fprintf(fd, "\t /Columns %" PRIu32 "\n", tile_width);
+ fprintf(fd, "\t /Rows %s\n", im_h);
+ if (compression == COMPRESSION_CCITTRLE ||
+ compression == COMPRESSION_CCITTRLEW)
+ {
+ fputs("\t /EncodedByteAlign true\n", fd);
+ fputs("\t /EndOfBlock false\n", fd);
+ }
+ if (photometric == PHOTOMETRIC_MINISBLACK)
+ fputs("\t /BlackIs1 true\n", fd);
+ fprintf(fd, "\t>> /CCITTFaxDecode filter");
+ break;
+ case COMPRESSION_LZW: /* 5: Lempel-Ziv & Welch */
+ TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
+ if (predictor == 2)
+ {
+ fputs("\n\t<<\n", fd);
+ fprintf(fd, "\t /Predictor %" PRIu16 "\n", predictor);
+ fprintf(fd, "\t /Columns %" PRIu32 "\n", tile_width);
+ fprintf(fd, "\t /Colors %" PRIu16 "\n", samplesperpixel);
+ fprintf(fd, "\t /BitsPerComponent %" PRIu16 "\n",
+ bitspersample);
+ fputs("\t>>", fd);
+ }
+ fputs(" /LZWDecode filter", fd);
+ break;
+ case COMPRESSION_DEFLATE: /* 5: ZIP */
+ case COMPRESSION_ADOBE_DEFLATE:
+ if (level3)
+ {
+ TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
+ if (predictor > 1)
+ {
+ fprintf(fd, "\t %% PostScript Level 3 only.");
+ fputs("\n\t<<\n", fd);
+ fprintf(fd, "\t /Predictor %" PRIu16 "\n", predictor);
+ fprintf(fd, "\t /Columns %" PRIu32 "\n", tile_width);
+ fprintf(fd, "\t /Colors %" PRIu16 "\n", samplesperpixel);
+ fprintf(fd, "\t /BitsPerComponent %" PRIu16 "\n",
+ bitspersample);
+ fputs("\t>>", fd);
+ }
+ fputs(" /FlateDecode filter", fd);
+ }
+ else
+ {
+ use_rawdata = FALSE;
+ }
+ break;
+ case COMPRESSION_PACKBITS: /* 32773: Macintosh RLE */
+ fputs(" /RunLengthDecode filter", fd);
+ use_rawdata = TRUE;
+ break;
+ case COMPRESSION_OJPEG: /* 6: !6.0 JPEG */
+ case COMPRESSION_JPEG: /* 7: %JPEG DCT compression */
#ifdef notdef
- /*
- * Code not tested yet
- */
- fputs(" /DCTDecode filter", fd);
- use_rawdata = TRUE;
+ /*
+ * Code not tested yet
+ */
+ fputs(" /DCTDecode filter", fd);
+ use_rawdata = TRUE;
#else
- use_rawdata = FALSE;
+ use_rawdata = FALSE;
#endif
- break;
- case COMPRESSION_NEXT: /* 32766: NeXT 2-bit RLE */
- case COMPRESSION_THUNDERSCAN: /* 32809: ThunderScan RLE */
- case COMPRESSION_PIXARFILM: /* 32908: Pixar companded 10bit LZW */
- case COMPRESSION_JBIG: /* 34661: ISO JBIG */
- use_rawdata = FALSE;
- break;
- case COMPRESSION_SGILOG: /* 34676: SGI LogL or LogLuv */
- case COMPRESSION_SGILOG24: /* 34677: SGI 24-bit LogLuv */
- use_rawdata = FALSE;
- break;
- default:
- /*
- * ERROR...
- */
- use_rawdata = FALSE;
- break;
- }
- if (planarconfiguration == PLANARCONFIG_SEPARATE &&
- samplesperpixel > 1) {
- uint16_t i;
-
- /*
- * NOTE: This code does not work yet...
- */
- for (i = 1; i < samplesperpixel; i++)
- fputs(" dup", fd);
- fputs(" ]", fd);
- }
-
- fprintf( fd, "\n >> %s\n", imageOp );
- if (ascii85)
- fputs(" im_stream status { im_stream flushfile } if\n", fd);
- if (repeat_count > 1) {
- if (tile_width < w) {
- fprintf(fd, " /im_x im_x %"PRIu32" add def\n",
- tile_width);
- if (tile_height < h) {
- fprintf(fd, " im_x %"PRIu32" ge {\n",
- w);
- fputs(" /im_x 0 def\n", fd);
- fprintf(fd, " /im_y im_y %"PRIu32" add def\n",
- tile_height);
- fputs(" } if\n", fd);
- }
- }
- if (tile_height < h) {
- if (tile_width >= w) {
- fprintf(fd, " /im_y im_y %"PRIu32" add def\n",
- tile_height);
- if (!TIFFIsTiled(tif)) {
- fprintf(fd, " /im_h %"PRIu32" im_y sub",
- h);
- fprintf(fd, " dup %"PRIu32" gt { pop",
- tile_height);
- fprintf(fd, " %"PRIu32" } if def\n",
- tile_height);
- }
- }
- }
- fputs("} repeat\n", fd);
- }
- /*
- * End of exec function
- */
- fputs("}\n", fd);
-
- return(use_rawdata);
+ break;
+ case COMPRESSION_NEXT: /* 32766: NeXT 2-bit RLE */
+ case COMPRESSION_THUNDERSCAN: /* 32809: ThunderScan RLE */
+ case COMPRESSION_PIXARFILM: /* 32908: Pixar companded 10bit LZW */
+ case COMPRESSION_JBIG: /* 34661: ISO JBIG */
+ use_rawdata = FALSE;
+ break;
+ case COMPRESSION_SGILOG: /* 34676: SGI LogL or LogLuv */
+ case COMPRESSION_SGILOG24: /* 34677: SGI 24-bit LogLuv */
+ use_rawdata = FALSE;
+ break;
+ default:
+ /*
+ * ERROR...
+ */
+ use_rawdata = FALSE;
+ break;
+ }
+ if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
+ {
+ uint16_t i;
+
+ /*
+ * NOTE: This code does not work yet...
+ */
+ for (i = 1; i < samplesperpixel; i++)
+ fputs(" dup", fd);
+ fputs(" ]", fd);
+ }
+
+ fprintf(fd, "\n >> %s\n", imageOp);
+ if (ascii85)
+ fputs(" im_stream status { im_stream flushfile } if\n", fd);
+ if (repeat_count > 1)
+ {
+ if (tile_width < w)
+ {
+ fprintf(fd, " /im_x im_x %" PRIu32 " add def\n", tile_width);
+ if (tile_height < h)
+ {
+ fprintf(fd, " im_x %" PRIu32 " ge {\n", w);
+ fputs(" /im_x 0 def\n", fd);
+ fprintf(fd, " /im_y im_y %" PRIu32 " add def\n", tile_height);
+ fputs(" } if\n", fd);
+ }
+ }
+ if (tile_height < h)
+ {
+ if (tile_width >= w)
+ {
+ fprintf(fd, " /im_y im_y %" PRIu32 " add def\n", tile_height);
+ if (!TIFFIsTiled(tif))
+ {
+ fprintf(fd, " /im_h %" PRIu32 " im_y sub", h);
+ fprintf(fd, " dup %" PRIu32 " gt { pop", tile_height);
+ fprintf(fd, " %" PRIu32 " } if def\n", tile_height);
+ }
+ }
+ }
+ fputs("} repeat\n", fd);
+ }
+ /*
+ * End of exec function
+ */
+ fputs("}\n", fd);
+
+ return (use_rawdata);
}
/* Flip the byte order of buffers with 16 bit samples */
-static void
-PS_FlipBytes(unsigned char* buf, tsize_t count)
+static void PS_FlipBytes(unsigned char *buf, tsize_t count)
{
- int i;
- unsigned char temp;
+ int i;
+ unsigned char temp;
- if (count <= 0 || bitspersample <= 8) {
- return;
- }
+ if (count <= 0 || bitspersample <= 8)
+ {
+ return;
+ }
- count--;
+ count--;
- for (i = 0; i < count; i += 2) {
- temp = buf[i];
- buf[i] = buf[i + 1];
- buf[i + 1] = temp;
- }
+ for (i = 0; i < count; i += 2)
+ {
+ temp = buf[i];
+ buf[i] = buf[i + 1];
+ buf[i + 1] = temp;
+ }
}
-#define MAXLINE 36
+#define MAXLINE 36
-int
-PS_Lvl2page(FILE* fd, TIFF* tif, uint32_t w, uint32_t h)
+int PS_Lvl2page(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
{
- uint16_t fillorder;
- int use_rawdata, tiled_image, breaklen = MAXLINE;
- uint32_t chunk_no, num_chunks;
- uint64_t *bc;
- unsigned char *buf_data, *cp;
- tsize_t chunk_size, byte_count;
-
-#if defined( EXP_ASCII85ENCODER )
- tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
- uint8_t * ascii85_p = 0; /* Holds ASCII85 encoded data */
+ uint16_t fillorder;
+ int use_rawdata, tiled_image, breaklen = MAXLINE;
+ uint32_t chunk_no, num_chunks;
+ uint64_t *bc;
+ unsigned char *buf_data, *cp;
+ tsize_t chunk_size, byte_count;
+
+#if defined(EXP_ASCII85ENCODER)
+ tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
+ uint8_t *ascii85_p = 0; /* Holds ASCII85 encoded data */
#endif
- PS_Lvl2colorspace(fd, tif);
- use_rawdata = PS_Lvl2ImageDict(fd, tif, w, h);
+ PS_Lvl2colorspace(fd, tif);
+ use_rawdata = PS_Lvl2ImageDict(fd, tif, w, h);
/* See http://bugzilla.remotesensing.org/show_bug.cgi?id=80 */
#ifdef ENABLE_BROKEN_BEGINENDDATA
- fputs("%%BeginData:\n", fd);
+ fputs("%%BeginData:\n", fd);
#endif
- fputs("exec\n", fd);
-
- tiled_image = TIFFIsTiled(tif);
- if (tiled_image) {
- num_chunks = TIFFNumberOfTiles(tif);
- TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc);
- } else {
- num_chunks = TIFFNumberOfStrips(tif);
- TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
- }
-
- if (use_rawdata) {
- chunk_size = (tsize_t) bc[0];
- for (chunk_no = 1; chunk_no < num_chunks; chunk_no++)
- if ((tsize_t) bc[chunk_no] > chunk_size)
- chunk_size = (tsize_t) bc[chunk_no];
- } else {
- if (tiled_image)
- chunk_size = TIFFTileSize(tif);
- else
- chunk_size = TIFFStripSize(tif);
- }
- buf_data = (unsigned char *)limitMalloc(chunk_size);
- if (!buf_data) {
- TIFFError(filename, "Can't alloc %"TIFF_SSIZE_FORMAT" bytes for %s.",
- chunk_size, tiled_image ? "tiles" : "strips");
- return(FALSE);
- }
-
-#if defined( EXP_ASCII85ENCODER )
- if ( ascii85 ) {
- /*
- * Allocate a buffer to hold the ASCII85 encoded data. Note
- * that it is allocated with sufficient room to hold the
- * encoded data (5*chunk_size/4) plus the EOD marker (+8)
- * and formatting line breaks. The line breaks are more
- * than taken care of by using 6*chunk_size/4 rather than
- * 5*chunk_size/4.
- */
-
- ascii85_p = limitMalloc( (chunk_size+(chunk_size/2)) + 8 );
-
- if ( !ascii85_p ) {
- _TIFFfree( buf_data );
-
- TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
- return ( FALSE );
- }
- }
+ fputs("exec\n", fd);
+
+ tiled_image = TIFFIsTiled(tif);
+ if (tiled_image)
+ {
+ num_chunks = TIFFNumberOfTiles(tif);
+ TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc);
+ }
+ else
+ {
+ num_chunks = TIFFNumberOfStrips(tif);
+ TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
+ }
+
+ if (use_rawdata)
+ {
+ chunk_size = (tsize_t)bc[0];
+ for (chunk_no = 1; chunk_no < num_chunks; chunk_no++)
+ if ((tsize_t)bc[chunk_no] > chunk_size)
+ chunk_size = (tsize_t)bc[chunk_no];
+ }
+ else
+ {
+ if (tiled_image)
+ chunk_size = TIFFTileSize(tif);
+ else
+ chunk_size = TIFFStripSize(tif);
+ }
+ buf_data = (unsigned char *)limitMalloc(chunk_size);
+ if (!buf_data)
+ {
+ TIFFError(filename, "Can't alloc %" TIFF_SSIZE_FORMAT " bytes for %s.",
+ chunk_size, tiled_image ? "tiles" : "strips");
+ return (FALSE);
+ }
+
+#if defined(EXP_ASCII85ENCODER)
+ if (ascii85)
+ {
+ /*
+ * Allocate a buffer to hold the ASCII85 encoded data. Note
+ * that it is allocated with sufficient room to hold the
+ * encoded data (5*chunk_size/4) plus the EOD marker (+8)
+ * and formatting line breaks. The line breaks are more
+ * than taken care of by using 6*chunk_size/4 rather than
+ * 5*chunk_size/4.
+ */
+
+ ascii85_p = limitMalloc((chunk_size + (chunk_size / 2)) + 8);
+
+ if (!ascii85_p)
+ {
+ _TIFFfree(buf_data);
+
+ TIFFError(filename, "Cannot allocate ASCII85 encoding buffer.");
+ return (FALSE);
+ }
+ }
#endif
- TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
- for (chunk_no = 0; chunk_no < num_chunks; chunk_no++) {
- if (ascii85)
- Ascii85Init();
- else
- breaklen = MAXLINE;
- if (use_rawdata) {
- if (tiled_image)
- byte_count = TIFFReadRawTile(tif, chunk_no,
- buf_data, chunk_size);
- else
- byte_count = TIFFReadRawStrip(tif, chunk_no,
- buf_data, chunk_size);
- if (fillorder == FILLORDER_LSB2MSB)
- TIFFReverseBits(buf_data, byte_count);
- } else {
- if (tiled_image)
- byte_count = TIFFReadEncodedTile(tif,
- chunk_no, buf_data,
- chunk_size);
- else
- byte_count = TIFFReadEncodedStrip(tif,
- chunk_no, buf_data,
- chunk_size);
- }
- if (byte_count < 0) {
- TIFFError(filename, "Can't read %s %"PRIu32".",
- tiled_image ? "tile" : "strip", chunk_no);
- if (ascii85)
- Ascii85Put('\0', fd);
- }
- /*
- * for 16 bits, the two bytes must be most significant
- * byte first
- */
- if (bitspersample == 16 && !TIFFIsBigEndian(tif)) {
- PS_FlipBytes(buf_data, byte_count);
- }
- /*
- * For images with alpha, matte against a white background;
- * i.e. Cback * (1 - Aimage) where Cback = 1. We will fill the
- * lower part of the buffer with the modified values.
- *
- * XXX: needs better solution
- */
- if (alpha) {
- int adjust, i, j = 0;
- int ncomps = samplesperpixel - extrasamples;
- for (i = 0; (i + ncomps) < byte_count; i+=samplesperpixel) {
- adjust = 255 - buf_data[i + ncomps];
- switch (ncomps) {
- case 1:
- buf_data[j++] = buf_data[i] + adjust;
- break;
- case 2:
- buf_data[j++] = buf_data[i] + adjust;
- buf_data[j++] = buf_data[i+1] + adjust;
- break;
- case 3:
- buf_data[j++] = buf_data[i] + adjust;
- buf_data[j++] = buf_data[i+1] + adjust;
- buf_data[j++] = buf_data[i+2] + adjust;
- break;
- }
- }
- byte_count -= j;
- }
-
- if (ascii85) {
-#if defined( EXP_ASCII85ENCODER )
- ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, buf_data, byte_count );
-
- if ( ascii85_l > 0 )
- fwrite( ascii85_p, ascii85_l, 1, fd );
+ TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
+ for (chunk_no = 0; chunk_no < num_chunks; chunk_no++)
+ {
+ if (ascii85)
+ Ascii85Init();
+ else
+ breaklen = MAXLINE;
+ if (use_rawdata)
+ {
+ if (tiled_image)
+ byte_count =
+ TIFFReadRawTile(tif, chunk_no, buf_data, chunk_size);
+ else
+ byte_count =
+ TIFFReadRawStrip(tif, chunk_no, buf_data, chunk_size);
+ if (fillorder == FILLORDER_LSB2MSB)
+ TIFFReverseBits(buf_data, byte_count);
+ }
+ else
+ {
+ if (tiled_image)
+ byte_count =
+ TIFFReadEncodedTile(tif, chunk_no, buf_data, chunk_size);
+ else
+ byte_count =
+ TIFFReadEncodedStrip(tif, chunk_no, buf_data, chunk_size);
+ }
+ if (byte_count < 0)
+ {
+ TIFFError(filename, "Can't read %s %" PRIu32 ".",
+ tiled_image ? "tile" : "strip", chunk_no);
+ if (ascii85)
+ Ascii85Put('\0', fd);
+ }
+ /*
+ * for 16 bits, the two bytes must be most significant
+ * byte first
+ */
+ if (bitspersample == 16 && !TIFFIsBigEndian(tif))
+ {
+ PS_FlipBytes(buf_data, byte_count);
+ }
+ /*
+ * For images with alpha, matte against a white background;
+ * i.e. Cback * (1 - Aimage) where Cback = 1. We will fill the
+ * lower part of the buffer with the modified values.
+ *
+ * XXX: needs better solution
+ */
+ if (alpha)
+ {
+ int adjust, i, j = 0;
+ int ncomps = samplesperpixel - extrasamples;
+ for (i = 0; (i + ncomps) < byte_count; i += samplesperpixel)
+ {
+ adjust = 255 - buf_data[i + ncomps];
+ switch (ncomps)
+ {
+ case 1:
+ buf_data[j++] = buf_data[i] + adjust;
+ break;
+ case 2:
+ buf_data[j++] = buf_data[i] + adjust;
+ buf_data[j++] = buf_data[i + 1] + adjust;
+ break;
+ case 3:
+ buf_data[j++] = buf_data[i] + adjust;
+ buf_data[j++] = buf_data[i + 1] + adjust;
+ buf_data[j++] = buf_data[i + 2] + adjust;
+ break;
+ }
+ }
+ byte_count -= j;
+ }
+
+ if (ascii85)
+ {
+#if defined(EXP_ASCII85ENCODER)
+ ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, buf_data, byte_count);
+
+ if (ascii85_l > 0)
+ fwrite(ascii85_p, ascii85_l, 1, fd);
#else
- for (cp = buf_data; byte_count > 0; byte_count--)
- Ascii85Put(*cp++, fd);
+ for (cp = buf_data; byte_count > 0; byte_count--)
+ Ascii85Put(*cp++, fd);
#endif
- }
- else
- {
- for (cp = buf_data; byte_count > 0; byte_count--) {
- putc(hex[((*cp)>>4)&0xf], fd);
- putc(hex[(*cp)&0xf], fd);
- cp++;
-
- if (--breaklen <= 0) {
- putc('\n', fd);
- breaklen = MAXLINE;
- }
- }
- }
-
- if ( !ascii85 ) {
- if ( level2 || level3 )
- putc( '>', fd );
- putc('\n', fd);
- }
-#if !defined( EXP_ASCII85ENCODER )
- else
- Ascii85Flush(fd);
+ }
+ else
+ {
+ for (cp = buf_data; byte_count > 0; byte_count--)
+ {
+ putc(hex[((*cp) >> 4) & 0xf], fd);
+ putc(hex[(*cp) & 0xf], fd);
+ cp++;
+
+ if (--breaklen <= 0)
+ {
+ putc('\n', fd);
+ breaklen = MAXLINE;
+ }
+ }
+ }
+
+ if (!ascii85)
+ {
+ if (level2 || level3)
+ putc('>', fd);
+ putc('\n', fd);
+ }
+#if !defined(EXP_ASCII85ENCODER)
+ else
+ Ascii85Flush(fd);
#endif
- }
+ }
-#if defined( EXP_ASCII85ENCODER )
- if ( ascii85_p )
- _TIFFfree( ascii85_p );
+#if defined(EXP_ASCII85ENCODER)
+ if (ascii85_p)
+ _TIFFfree(ascii85_p);
#endif
-
- _TIFFfree(buf_data);
+
+ _TIFFfree(buf_data);
#ifdef ENABLE_BROKEN_BEGINENDDATA
- fputs("%%EndData\n", fd);
+ fputs("%%EndData\n", fd);
#endif
- return(TRUE);
+ return (TRUE);
}
-void
-PSpage(FILE* fd, TIFF* tif, uint32_t w, uint32_t h)
+void PSpage(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
{
- char * imageOp = "image";
-
- if ( useImagemask && (bitspersample == 1) )
- imageOp = "imagemask";
-
- if ((level2 || level3) && PS_Lvl2page(fd, tif, w, h))
- return;
- ps_bytesperrow = tf_bytesperrow - (extrasamples * bitspersample / 8)*w;
- switch (photometric) {
- case PHOTOMETRIC_RGB:
- if (planarconfiguration == PLANARCONFIG_CONTIG) {
- fprintf(fd, "%s", RGBcolorimage);
- PSColorContigPreamble(fd, w, h, 3);
- PSDataColorContig(fd, tif, w, h, 3);
- } else {
- PSColorSeparatePreamble(fd, w, h, 3);
- PSDataColorSeparate(fd, tif, w, h, 3);
- }
- break;
- case PHOTOMETRIC_SEPARATED:
- /* XXX should emit CMYKcolorimage */
- if (planarconfiguration == PLANARCONFIG_CONTIG) {
- PSColorContigPreamble(fd, w, h, 4);
- PSDataColorContig(fd, tif, w, h, 4);
- } else {
- PSColorSeparatePreamble(fd, w, h, 4);
- PSDataColorSeparate(fd, tif, w, h, 4);
- }
- break;
- case PHOTOMETRIC_PALETTE:
- fprintf(fd, "%s", RGBcolorimage);
- PhotoshopBanner(fd, w, h, 1, 3, "false 3 colorimage");
- fprintf(fd, "/scanLine %"TIFF_SSIZE_FORMAT" string def\n",
- ps_bytesperrow * 3);
- fprintf(fd, "%"PRIu32" %"PRIu32" 8\n",
- w, h);
- fprintf(fd, "[%"PRIu32" 0 0 -%"PRIu32" 0 %"PRIu32"]\n",
- w, h, h);
- fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n");
- fprintf(fd, "false 3 colorimage\n");
- PSDataPalette(fd, tif, w, h);
- break;
- case PHOTOMETRIC_MINISBLACK:
- case PHOTOMETRIC_MINISWHITE:
- PhotoshopBanner(fd, w, h, 1, 1, imageOp);
- fprintf(fd, "/scanLine %"TIFF_SSIZE_FORMAT" string def\n",
- ps_bytesperrow);
- fprintf(fd, "%"PRIu32" %"PRIu32" %"PRIu16"\n",
- w, h, bitspersample);
- fprintf(fd, "[%"PRIu32" 0 0 -%"PRIu32" 0 %"PRIu32"]\n",
- w, h, h);
- fprintf(fd,
- "{currentfile scanLine readhexstring pop} bind\n");
- fprintf(fd, "%s\n", imageOp);
- PSDataBW(fd, tif, w, h);
- break;
- }
- putc('\n', fd);
+ char *imageOp = "image";
+
+ if (useImagemask && (bitspersample == 1))
+ imageOp = "imagemask";
+
+ if ((level2 || level3) && PS_Lvl2page(fd, tif, w, h))
+ return;
+ ps_bytesperrow = tf_bytesperrow - (extrasamples * bitspersample / 8) * w;
+ switch (photometric)
+ {
+ case PHOTOMETRIC_RGB:
+ if (planarconfiguration == PLANARCONFIG_CONTIG)
+ {
+ fprintf(fd, "%s", RGBcolorimage);
+ PSColorContigPreamble(fd, w, h, 3);
+ PSDataColorContig(fd, tif, w, h, 3);
+ }
+ else
+ {
+ PSColorSeparatePreamble(fd, w, h, 3);
+ PSDataColorSeparate(fd, tif, w, h, 3);
+ }
+ break;
+ case PHOTOMETRIC_SEPARATED:
+ /* XXX should emit CMYKcolorimage */
+ if (planarconfiguration == PLANARCONFIG_CONTIG)
+ {
+ PSColorContigPreamble(fd, w, h, 4);
+ PSDataColorContig(fd, tif, w, h, 4);
+ }
+ else
+ {
+ PSColorSeparatePreamble(fd, w, h, 4);
+ PSDataColorSeparate(fd, tif, w, h, 4);
+ }
+ break;
+ case PHOTOMETRIC_PALETTE:
+ fprintf(fd, "%s", RGBcolorimage);
+ PhotoshopBanner(fd, w, h, 1, 3, "false 3 colorimage");
+ fprintf(fd, "/scanLine %" TIFF_SSIZE_FORMAT " string def\n",
+ ps_bytesperrow * 3);
+ fprintf(fd, "%" PRIu32 " %" PRIu32 " 8\n", w, h);
+ fprintf(fd, "[%" PRIu32 " 0 0 -%" PRIu32 " 0 %" PRIu32 "]\n", w, h,
+ h);
+ fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n");
+ fprintf(fd, "false 3 colorimage\n");
+ PSDataPalette(fd, tif, w, h);
+ break;
+ case PHOTOMETRIC_MINISBLACK:
+ case PHOTOMETRIC_MINISWHITE:
+ PhotoshopBanner(fd, w, h, 1, 1, imageOp);
+ fprintf(fd, "/scanLine %" TIFF_SSIZE_FORMAT " string def\n",
+ ps_bytesperrow);
+ fprintf(fd, "%" PRIu32 " %" PRIu32 " %" PRIu16 "\n", w, h,
+ bitspersample);
+ fprintf(fd, "[%" PRIu32 " 0 0 -%" PRIu32 " 0 %" PRIu32 "]\n", w, h,
+ h);
+ fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n");
+ fprintf(fd, "%s\n", imageOp);
+ PSDataBW(fd, tif, w, h);
+ break;
+ }
+ putc('\n', fd);
}
-void
-PSColorContigPreamble(FILE* fd, uint32_t w, uint32_t h, int nc)
+void PSColorContigPreamble(FILE *fd, uint32_t w, uint32_t h, int nc)
{
- ps_bytesperrow = nc * (tf_bytesperrow / samplesperpixel);
- PhotoshopBanner(fd, w, h, 1, nc, "false %d colorimage");
- fprintf(fd, "/line %"TIFF_SSIZE_FORMAT" string def\n", ps_bytesperrow);
- fprintf(fd, "%"PRIu32" %"PRIu32" %"PRIu16"\n",
- w, h, bitspersample);
- fprintf(fd, "[%"PRIu32" 0 0 -%"PRIu32" 0 %"PRIu32"]\n",
- w, h, h);
- fprintf(fd, "{currentfile line readhexstring pop} bind\n");
- fprintf(fd, "false %d colorimage\n", nc);
+ ps_bytesperrow = nc * (tf_bytesperrow / samplesperpixel);
+ PhotoshopBanner(fd, w, h, 1, nc, "false %d colorimage");
+ fprintf(fd, "/line %" TIFF_SSIZE_FORMAT " string def\n", ps_bytesperrow);
+ fprintf(fd, "%" PRIu32 " %" PRIu32 " %" PRIu16 "\n", w, h, bitspersample);
+ fprintf(fd, "[%" PRIu32 " 0 0 -%" PRIu32 " 0 %" PRIu32 "]\n", w, h, h);
+ fprintf(fd, "{currentfile line readhexstring pop} bind\n");
+ fprintf(fd, "false %d colorimage\n", nc);
}
-void
-PSColorSeparatePreamble(FILE* fd, uint32_t w, uint32_t h, int nc)
+void PSColorSeparatePreamble(FILE *fd, uint32_t w, uint32_t h, int nc)
{
- int i;
-
- PhotoshopBanner(fd, w, h, ps_bytesperrow, nc, "true %d colorimage");
- for (i = 0; i < nc; i++)
- fprintf(fd, "/line%d %"TIFF_SSIZE_FORMAT" string def\n",
- i, ps_bytesperrow);
- fprintf(fd, "%"PRIu32" %"PRIu32" %"PRIu16"\n",
- w, h, bitspersample);
- fprintf(fd, "[%"PRIu32" 0 0 -%"PRIu32" 0 %"PRIu32"] \n",
- w, h, h);
- for (i = 0; i < nc; i++)
- fprintf(fd, "{currentfile line%d readhexstring pop}bind\n", i);
- fprintf(fd, "true %d colorimage\n", nc);
+ int i;
+
+ PhotoshopBanner(fd, w, h, ps_bytesperrow, nc, "true %d colorimage");
+ for (i = 0; i < nc; i++)
+ fprintf(fd, "/line%d %" TIFF_SSIZE_FORMAT " string def\n", i,
+ ps_bytesperrow);
+ fprintf(fd, "%" PRIu32 " %" PRIu32 " %" PRIu16 "\n", w, h, bitspersample);
+ fprintf(fd, "[%" PRIu32 " 0 0 -%" PRIu32 " 0 %" PRIu32 "] \n", w, h, h);
+ for (i = 0; i < nc; i++)
+ fprintf(fd, "{currentfile line%d readhexstring pop}bind\n", i);
+ fprintf(fd, "true %d colorimage\n", nc);
}
-#define DOBREAK(len, howmany, fd) \
- if (((len) -= (howmany)) <= 0) { \
- putc('\n', fd); \
- (len) = MAXLINE-(howmany); \
- }
+#define DOBREAK(len, howmany, fd) \
+ if (((len) -= (howmany)) <= 0) \
+ { \
+ putc('\n', fd); \
+ (len) = MAXLINE - (howmany); \
+ }
-static inline void
-puthex(unsigned int c, FILE *fd)
+static inline void puthex(unsigned int c, FILE *fd)
{
- putc(hex[((c)>>4)&0xf],fd);
- putc(hex[(c)&0xf],fd);
+ putc(hex[((c) >> 4) & 0xf], fd);
+ putc(hex[(c)&0xf], fd);
}
-void
-PSDataColorContig(FILE* fd, TIFF* tif, uint32_t w, uint32_t h, int nc)
+void PSDataColorContig(FILE *fd, TIFF *tif, uint32_t w, uint32_t h, int nc)
{
- uint32_t row;
- int breaklen = MAXLINE, es = samplesperpixel - nc;
- tsize_t cc;
- unsigned char *tf_buf;
- unsigned char *cp, c;
-
- (void) w;
- if( es < 0 )
+ uint32_t row;
+ int breaklen = MAXLINE, es = samplesperpixel - nc;
+ tsize_t cc;
+ unsigned char *tf_buf;
+ unsigned char *cp, c;
+
+ (void)w;
+ if (es < 0)
+ {
+ TIFFError(filename,
+ "Inconsistent value of es: %d (samplesperpixel=%" PRIu16
+ ", nc=%d)",
+ es, samplesperpixel, nc);
+ return;
+ }
+ tf_buf = (unsigned char *)limitMalloc(tf_bytesperrow);
+ if (tf_buf == NULL)
+ {
+ TIFFError(filename, "No space for scanline buffer");
+ return;
+ }
+ for (row = 0; row < h; row++)
+ {
+ if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
+ break;
+ cp = tf_buf;
+ /*
+ * for 16 bits, the two bytes must be most significant
+ * byte first
+ */
+ if (bitspersample == 16 && !HOST_BIGENDIAN)
{
- TIFFError(filename, "Inconsistent value of es: %d (samplesperpixel=%"PRIu16", nc=%d)", es, samplesperpixel, nc);
- return;
+ PS_FlipBytes(cp, tf_bytesperrow);
}
- tf_buf = (unsigned char *) limitMalloc(tf_bytesperrow);
- if (tf_buf == NULL) {
- TIFFError(filename, "No space for scanline buffer");
- return;
- }
- for (row = 0; row < h; row++) {
- if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
- break;
- cp = tf_buf;
- /*
- * for 16 bits, the two bytes must be most significant
- * byte first
- */
- if (bitspersample == 16 && !HOST_BIGENDIAN) {
- PS_FlipBytes(cp, tf_bytesperrow);
- }
- if (alpha) {
- int adjust;
- /*
- * the code inside this loop reads nc bytes + 1 extra byte (for adjust)
- */
- for (cc = 0; (cc + nc) < tf_bytesperrow; cc += samplesperpixel) {
- DOBREAK(breaklen, nc, fd);
- /*
- * For images with alpha, matte against
- * a white background; i.e.
- * Cback * (1 - Aimage)
- * where Cback = 1.
- */
- adjust = 255 - cp[nc];
- for (int i = 0; i < nc; ++i)
+ if (alpha)
+ {
+ int adjust;
+ /*
+ * the code inside this loop reads nc bytes + 1 extra byte (for
+ * adjust)
+ */
+ for (cc = 0; (cc + nc) < tf_bytesperrow; cc += samplesperpixel)
+ {
+ DOBREAK(breaklen, nc, fd);
+ /*
+ * For images with alpha, matte against
+ * a white background; i.e.
+ * Cback * (1 - Aimage)
+ * where Cback = 1.
+ */
+ adjust = 255 - cp[nc];
+ for (int i = 0; i < nc; ++i)
{
c = *cp++ + adjust;
- puthex(c,fd);
+ puthex(c, fd);
}
- cp += es;
- }
- } else {
- /*
- * the code inside this loop reads nc bytes per iteration
- */
- for (cc = 0; (cc + nc) <= tf_bytesperrow; cc += samplesperpixel) {
- DOBREAK(breaklen, nc, fd);
- for (int i = 0; i < nc; ++i)
+ cp += es;
+ }
+ }
+ else
+ {
+ /*
+ * the code inside this loop reads nc bytes per iteration
+ */
+ for (cc = 0; (cc + nc) <= tf_bytesperrow; cc += samplesperpixel)
+ {
+ DOBREAK(breaklen, nc, fd);
+ for (int i = 0; i < nc; ++i)
{
c = *cp++;
- puthex(c,fd);
+ puthex(c, fd);
}
- cp += es;
- }
- }
- }
- _TIFFfree((char *) tf_buf);
+ cp += es;
+ }
+ }
+ }
+ _TIFFfree((char *)tf_buf);
}
-void
-PSDataColorSeparate(FILE* fd, TIFF* tif, uint32_t w, uint32_t h, int nc)
+void PSDataColorSeparate(FILE *fd, TIFF *tif, uint32_t w, uint32_t h, int nc)
{
- uint32_t row;
- int breaklen = MAXLINE;
- tsize_t cc;
- tsample_t s, maxs;
- unsigned char *tf_buf;
- unsigned char *cp, c;
-
- (void) w;
- tf_buf = (unsigned char *) limitMalloc(tf_bytesperrow);
- if (tf_buf == NULL) {
- TIFFError(filename, "No space for scanline buffer");
- return;
- }
- maxs = (samplesperpixel > nc ? nc : samplesperpixel);
- for (row = 0; row < h; row++) {
- for (s = 0; s < maxs; s++) {
- if (TIFFReadScanline(tif, tf_buf, row, s) < 0)
- goto end_loop;
- for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
- DOBREAK(breaklen, 1, fd);
- c = *cp++;
- puthex(c,fd);
- }
- }
- }
+ uint32_t row;
+ int breaklen = MAXLINE;
+ tsize_t cc;
+ tsample_t s, maxs;
+ unsigned char *tf_buf;
+ unsigned char *cp, c;
+
+ (void)w;
+ tf_buf = (unsigned char *)limitMalloc(tf_bytesperrow);
+ if (tf_buf == NULL)
+ {
+ TIFFError(filename, "No space for scanline buffer");
+ return;
+ }
+ maxs = (samplesperpixel > nc ? nc : samplesperpixel);
+ for (row = 0; row < h; row++)
+ {
+ for (s = 0; s < maxs; s++)
+ {
+ if (TIFFReadScanline(tif, tf_buf, row, s) < 0)
+ goto end_loop;
+ for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++)
+ {
+ DOBREAK(breaklen, 1, fd);
+ c = *cp++;
+ puthex(c, fd);
+ }
+ }
+ }
end_loop:
- _TIFFfree((char *) tf_buf);
+ _TIFFfree((char *)tf_buf);
}
-#define PUTRGBHEX(c,fd) \
- puthex(rmap[c],fd); puthex(gmap[c],fd); puthex(bmap[c],fd)
+#define PUTRGBHEX(c, fd) \
+ puthex(rmap[c], fd); \
+ puthex(gmap[c], fd); \
+ puthex(bmap[c], fd)
-void
-PSDataPalette(FILE* fd, TIFF* tif, uint32_t w, uint32_t h)
+void PSDataPalette(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
{
- uint16_t *rmap, *gmap, *bmap;
- uint32_t row;
- int breaklen = MAXLINE, nc;
- tsize_t cc;
- unsigned char *tf_buf;
- unsigned char *cp, c;
-
- (void) w;
- if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
- TIFFError(filename, "Palette image w/o \"Colormap\" tag");
- return;
- }
- switch (bitspersample) {
- case 8: case 4: case 2: case 1:
- break;
- default:
- TIFFError(filename, "Depth %"PRIu16" not supported", bitspersample);
- return;
- }
- nc = 3 * (8 / bitspersample);
- tf_buf = (unsigned char *) limitMalloc(tf_bytesperrow);
- if (tf_buf == NULL) {
- TIFFError(filename, "No space for scanline buffer");
- return;
- }
- if (checkcmap(tif, 1<<bitspersample, rmap, gmap, bmap) == 16) {
- int i;
-#define CVT(x) ((unsigned short) (((x) * 255) / ((1U<<16)-1)))
- for (i = (1<<bitspersample)-1; i >= 0; i--) {
- rmap[i] = CVT(rmap[i]);
- gmap[i] = CVT(gmap[i]);
- bmap[i] = CVT(bmap[i]);
- }
+ uint16_t *rmap, *gmap, *bmap;
+ uint32_t row;
+ int breaklen = MAXLINE, nc;
+ tsize_t cc;
+ unsigned char *tf_buf;
+ unsigned char *cp, c;
+
+ (void)w;
+ if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap))
+ {
+ TIFFError(filename, "Palette image w/o \"Colormap\" tag");
+ return;
+ }
+ switch (bitspersample)
+ {
+ case 8:
+ case 4:
+ case 2:
+ case 1:
+ break;
+ default:
+ TIFFError(filename, "Depth %" PRIu16 " not supported",
+ bitspersample);
+ return;
+ }
+ nc = 3 * (8 / bitspersample);
+ tf_buf = (unsigned char *)limitMalloc(tf_bytesperrow);
+ if (tf_buf == NULL)
+ {
+ TIFFError(filename, "No space for scanline buffer");
+ return;
+ }
+ if (checkcmap(tif, 1 << bitspersample, rmap, gmap, bmap) == 16)
+ {
+ int i;
+#define CVT(x) ((unsigned short)(((x)*255) / ((1U << 16) - 1)))
+ for (i = (1 << bitspersample) - 1; i >= 0; i--)
+ {
+ rmap[i] = CVT(rmap[i]);
+ gmap[i] = CVT(gmap[i]);
+ bmap[i] = CVT(bmap[i]);
+ }
#undef CVT
- }
- for (row = 0; row < h; row++) {
- if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
- goto end_loop;
- for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
- DOBREAK(breaklen, nc, fd);
- switch (bitspersample) {
- case 8:
- c = *cp++; PUTRGBHEX(c, fd);
- break;
- case 4:
- c = *cp++; PUTRGBHEX(c&0xf, fd);
- c >>= 4; PUTRGBHEX(c, fd);
- break;
- case 2:
- c = *cp++; PUTRGBHEX(c&0x3, fd);
- c >>= 2; PUTRGBHEX(c&0x3, fd);
- c >>= 2; PUTRGBHEX(c&0x3, fd);
- c >>= 2; PUTRGBHEX(c, fd);
- break;
- case 1:
- c = *cp++; PUTRGBHEX(c&0x1, fd);
- c >>= 1; PUTRGBHEX(c&0x1, fd);
- c >>= 1; PUTRGBHEX(c&0x1, fd);
- c >>= 1; PUTRGBHEX(c&0x1, fd);
- c >>= 1; PUTRGBHEX(c&0x1, fd);
- c >>= 1; PUTRGBHEX(c&0x1, fd);
- c >>= 1; PUTRGBHEX(c&0x1, fd);
- c >>= 1; PUTRGBHEX(c, fd);
- break;
- }
- }
- }
+ }
+ for (row = 0; row < h; row++)
+ {
+ if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
+ goto end_loop;
+ for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++)
+ {
+ DOBREAK(breaklen, nc, fd);
+ switch (bitspersample)
+ {
+ case 8:
+ c = *cp++;
+ PUTRGBHEX(c, fd);
+ break;
+ case 4:
+ c = *cp++;
+ PUTRGBHEX(c & 0xf, fd);
+ c >>= 4;
+ PUTRGBHEX(c, fd);
+ break;
+ case 2:
+ c = *cp++;
+ PUTRGBHEX(c & 0x3, fd);
+ c >>= 2;
+ PUTRGBHEX(c & 0x3, fd);
+ c >>= 2;
+ PUTRGBHEX(c & 0x3, fd);
+ c >>= 2;
+ PUTRGBHEX(c, fd);
+ break;
+ case 1:
+ c = *cp++;
+ PUTRGBHEX(c & 0x1, fd);
+ c >>= 1;
+ PUTRGBHEX(c & 0x1, fd);
+ c >>= 1;
+ PUTRGBHEX(c & 0x1, fd);
+ c >>= 1;
+ PUTRGBHEX(c & 0x1, fd);
+ c >>= 1;
+ PUTRGBHEX(c & 0x1, fd);
+ c >>= 1;
+ PUTRGBHEX(c & 0x1, fd);
+ c >>= 1;
+ PUTRGBHEX(c & 0x1, fd);
+ c >>= 1;
+ PUTRGBHEX(c, fd);
+ break;
+ }
+ }
+ }
end_loop:
- _TIFFfree((char *) tf_buf);
+ _TIFFfree((char *)tf_buf);
}
-void
-PSDataBW(FILE* fd, TIFF* tif, uint32_t w, uint32_t h)
+void PSDataBW(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
{
- int breaklen = MAXLINE;
- unsigned char* tf_buf;
- unsigned char* cp;
- tsize_t stripsize = TIFFStripSize(tif);
- tstrip_t s;
-
-#if defined( EXP_ASCII85ENCODER )
- tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
- uint8_t *ascii85_p = 0; /* Holds ASCII85 encoded data */
+ int breaklen = MAXLINE;
+ unsigned char *tf_buf;
+ unsigned char *cp;
+ tsize_t stripsize = TIFFStripSize(tif);
+ tstrip_t s;
+
+#if defined(EXP_ASCII85ENCODER)
+ tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
+ uint8_t *ascii85_p = 0; /* Holds ASCII85 encoded data */
#endif
- (void) w; (void) h;
- tf_buf = (unsigned char *) limitMalloc(stripsize);
- if (tf_buf == NULL) {
- TIFFError(filename, "No space for scanline buffer");
- return;
- }
-
- // FIXME
- memset(tf_buf, 0, stripsize);
-
-#if defined( EXP_ASCII85ENCODER )
- if ( ascii85 ) {
- /*
- * Allocate a buffer to hold the ASCII85 encoded data. Note
- * that it is allocated with sufficient room to hold the
- * encoded data (5*stripsize/4) plus the EOD marker (+8)
- * and formatting line breaks. The line breaks are more
- * than taken care of by using 6*stripsize/4 rather than
- * 5*stripsize/4.
- */
-
- ascii85_p = limitMalloc( (stripsize+(stripsize/2)) + 8 );
-
- if ( !ascii85_p ) {
- _TIFFfree( tf_buf );
-
- TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
- return;
- }
- }
+ (void)w;
+ (void)h;
+ tf_buf = (unsigned char *)limitMalloc(stripsize);
+ if (tf_buf == NULL)
+ {
+ TIFFError(filename, "No space for scanline buffer");
+ return;
+ }
+
+ // FIXME
+ memset(tf_buf, 0, stripsize);
+
+#if defined(EXP_ASCII85ENCODER)
+ if (ascii85)
+ {
+ /*
+ * Allocate a buffer to hold the ASCII85 encoded data. Note
+ * that it is allocated with sufficient room to hold the
+ * encoded data (5*stripsize/4) plus the EOD marker (+8)
+ * and formatting line breaks. The line breaks are more
+ * than taken care of by using 6*stripsize/4 rather than
+ * 5*stripsize/4.
+ */
+
+ ascii85_p = limitMalloc((stripsize + (stripsize / 2)) + 8);
+
+ if (!ascii85_p)
+ {
+ _TIFFfree(tf_buf);
+
+ TIFFError(filename, "Cannot allocate ASCII85 encoding buffer.");
+ return;
+ }
+ }
#endif
- if (ascii85)
- Ascii85Init();
-
- for (s = 0; s < TIFFNumberOfStrips(tif); s++) {
- tmsize_t cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize);
- if (cc < 0) {
- TIFFError(filename, "Can't read strip");
- break;
- }
- cp = tf_buf;
- if (photometric == PHOTOMETRIC_MINISWHITE) {
- for (cp += cc; --cp >= tf_buf;)
- *cp = ~*cp;
- cp++;
- }
- /*
- * for 16 bits, the two bytes must be most significant
- * byte first
- */
- if (bitspersample == 16 && !HOST_BIGENDIAN) {
- PS_FlipBytes(cp, cc);
- }
- if (ascii85) {
-#if defined( EXP_ASCII85ENCODER )
- if (alpha) {
- int adjust, i;
- for (i = 0; i < (cc - 1); i+=2) {
- adjust = 255 - cp[i + 1];
- cp[i / 2] = cp[i] + adjust;
- }
- cc /= 2;
- }
-
- ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, cp, cc );
-
- if ( ascii85_l > 0 )
- fwrite( ascii85_p, ascii85_l, 1, fd );
+ if (ascii85)
+ Ascii85Init();
+
+ for (s = 0; s < TIFFNumberOfStrips(tif); s++)
+ {
+ tmsize_t cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize);
+ if (cc < 0)
+ {
+ TIFFError(filename, "Can't read strip");
+ break;
+ }
+ cp = tf_buf;
+ if (photometric == PHOTOMETRIC_MINISWHITE)
+ {
+ for (cp += cc; --cp >= tf_buf;)
+ *cp = ~*cp;
+ cp++;
+ }
+ /*
+ * for 16 bits, the two bytes must be most significant
+ * byte first
+ */
+ if (bitspersample == 16 && !HOST_BIGENDIAN)
+ {
+ PS_FlipBytes(cp, cc);
+ }
+ if (ascii85)
+ {
+#if defined(EXP_ASCII85ENCODER)
+ if (alpha)
+ {
+ int adjust, i;
+ for (i = 0; i < (cc - 1); i += 2)
+ {
+ adjust = 255 - cp[i + 1];
+ cp[i / 2] = cp[i] + adjust;
+ }
+ cc /= 2;
+ }
+
+ ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, cp, cc);
+
+ if (ascii85_l > 0)
+ fwrite(ascii85_p, ascii85_l, 1, fd);
#else
- while (cc-- > 0)
- Ascii85Put(*cp++, fd);
+ while (cc-- > 0)
+ Ascii85Put(*cp++, fd);
#endif /* EXP_ASCII85_ENCODER */
- } else {
- unsigned char c;
-
- if (alpha) {
- int adjust;
- while (cc-- > 1) {
- DOBREAK(breaklen, 1, fd);
- /*
- * For images with alpha, matte against
- * a white background; i.e.
- * Cback * (1 - Aimage)
- * where Cback = 1.
- */
- adjust = 255 - cp[1];
- c = *cp++ + adjust; puthex(c,fd);
- cp++, cc--;
- }
- } else {
- while (cc-- > 0) {
- c = *cp++;
- DOBREAK(breaklen, 1, fd);
- puthex(c, fd);
- }
- }
- }
- }
-
- if ( !ascii85 )
- {
- if ( level2 || level3)
- fputs(">\n", fd);
- }
-#if !defined( EXP_ASCII85ENCODER )
- else
- Ascii85Flush(fd);
+ }
+ else
+ {
+ unsigned char c;
+
+ if (alpha)
+ {
+ int adjust;
+ while (cc-- > 1)
+ {
+ DOBREAK(breaklen, 1, fd);
+ /*
+ * For images with alpha, matte against
+ * a white background; i.e.
+ * Cback * (1 - Aimage)
+ * where Cback = 1.
+ */
+ adjust = 255 - cp[1];
+ c = *cp++ + adjust;
+ puthex(c, fd);
+ cp++, cc--;
+ }
+ }
+ else
+ {
+ while (cc-- > 0)
+ {
+ c = *cp++;
+ DOBREAK(breaklen, 1, fd);
+ puthex(c, fd);
+ }
+ }
+ }
+ }
+
+ if (!ascii85)
+ {
+ if (level2 || level3)
+ fputs(">\n", fd);
+ }
+#if !defined(EXP_ASCII85ENCODER)
+ else
+ Ascii85Flush(fd);
#else
- if ( ascii85_p )
- _TIFFfree( ascii85_p );
+ if (ascii85_p)
+ _TIFFfree(ascii85_p);
#endif
- _TIFFfree(tf_buf);
+ _TIFFfree(tf_buf);
}
-void
-PSRawDataBW(FILE* fd, TIFF* tif, uint32_t w, uint32_t h)
+void PSRawDataBW(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
{
- uint64_t *bc;
- uint32_t bufsize;
- int breaklen = MAXLINE;
- tmsize_t cc;
- uint16_t fillorder;
- unsigned char *tf_buf;
- unsigned char *cp, c;
- tstrip_t s;
-
-#if defined( EXP_ASCII85ENCODER )
- tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
- uint8_t * ascii85_p = 0; /* Holds ASCII85 encoded data */
+ uint64_t *bc;
+ uint32_t bufsize;
+ int breaklen = MAXLINE;
+ tmsize_t cc;
+ uint16_t fillorder;
+ unsigned char *tf_buf;
+ unsigned char *cp, c;
+ tstrip_t s;
+
+#if defined(EXP_ASCII85ENCODER)
+ tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
+ uint8_t *ascii85_p = 0; /* Holds ASCII85 encoded data */
#endif
- (void) w; (void) h;
- TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
- TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
-
- /*
- * Find largest strip:
- */
-
- bufsize = (uint32_t) bc[0];
-
- for ( s = 0; ++s < tf_numberstrips; ) {
- if ( bc[s] > bufsize )
- bufsize = (uint32_t) bc[s];
- }
-
- tf_buf = (unsigned char*) limitMalloc(bufsize);
- if (tf_buf == NULL) {
- TIFFError(filename, "No space for strip buffer");
- return;
- }
-
-#if defined( EXP_ASCII85ENCODER )
- if ( ascii85 ) {
- /*
- * Allocate a buffer to hold the ASCII85 encoded data. Note
- * that it is allocated with sufficient room to hold the
- * encoded data (5*bufsize/4) plus the EOD marker (+8)
- * and formatting line breaks. The line breaks are more
- * than taken care of by using 6*bufsize/4 rather than
- * 5*bufsize/4.
- */
-
- ascii85_p = limitMalloc( (bufsize+(bufsize/2)) + 8 );
-
- if ( !ascii85_p ) {
- _TIFFfree( tf_buf );
-
- TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
- return;
- }
- }
+ (void)w;
+ (void)h;
+ TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
+ TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
+
+ /*
+ * Find largest strip:
+ */
+
+ bufsize = (uint32_t)bc[0];
+
+ for (s = 0; ++s < tf_numberstrips;)
+ {
+ if (bc[s] > bufsize)
+ bufsize = (uint32_t)bc[s];
+ }
+
+ tf_buf = (unsigned char *)limitMalloc(bufsize);
+ if (tf_buf == NULL)
+ {
+ TIFFError(filename, "No space for strip buffer");
+ return;
+ }
+
+#if defined(EXP_ASCII85ENCODER)
+ if (ascii85)
+ {
+ /*
+ * Allocate a buffer to hold the ASCII85 encoded data. Note
+ * that it is allocated with sufficient room to hold the
+ * encoded data (5*bufsize/4) plus the EOD marker (+8)
+ * and formatting line breaks. The line breaks are more
+ * than taken care of by using 6*bufsize/4 rather than
+ * 5*bufsize/4.
+ */
+
+ ascii85_p = limitMalloc((bufsize + (bufsize / 2)) + 8);
+
+ if (!ascii85_p)
+ {
+ _TIFFfree(tf_buf);
+
+ TIFFError(filename, "Cannot allocate ASCII85 encoding buffer.");
+ return;
+ }
+ }
#endif
- for (s = 0; s < tf_numberstrips; s++) {
- cc = TIFFReadRawStrip(tif, s, tf_buf, (tmsize_t) bc[s]);
- if (cc < 0) {
- TIFFError(filename, "Can't read strip");
- break;
- }
- if (fillorder == FILLORDER_LSB2MSB)
- TIFFReverseBits(tf_buf, cc);
- if (!ascii85) {
- for (cp = tf_buf; cc > 0; cc--) {
- DOBREAK(breaklen, 1, fd);
- c = *cp++;
- puthex(c, fd);
- }
- fputs(">\n", fd);
- breaklen = MAXLINE;
- } else {
- Ascii85Init();
-#if defined( EXP_ASCII85ENCODER )
- ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, tf_buf, cc );
-
- if ( ascii85_l > 0 )
- fwrite( ascii85_p, ascii85_l, 1, fd );
+ for (s = 0; s < tf_numberstrips; s++)
+ {
+ cc = TIFFReadRawStrip(tif, s, tf_buf, (tmsize_t)bc[s]);
+ if (cc < 0)
+ {
+ TIFFError(filename, "Can't read strip");
+ break;
+ }
+ if (fillorder == FILLORDER_LSB2MSB)
+ TIFFReverseBits(tf_buf, cc);
+ if (!ascii85)
+ {
+ for (cp = tf_buf; cc > 0; cc--)
+ {
+ DOBREAK(breaklen, 1, fd);
+ c = *cp++;
+ puthex(c, fd);
+ }
+ fputs(">\n", fd);
+ breaklen = MAXLINE;
+ }
+ else
+ {
+ Ascii85Init();
+#if defined(EXP_ASCII85ENCODER)
+ ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, tf_buf, cc);
+
+ if (ascii85_l > 0)
+ fwrite(ascii85_p, ascii85_l, 1, fd);
#else
- for (cp = tf_buf; cc > 0; cc--)
- Ascii85Put(*cp++, fd);
- Ascii85Flush(fd);
-#endif /* EXP_ASCII85ENCODER */
- }
- }
- _TIFFfree((char *) tf_buf);
-
-#if defined( EXP_ASCII85ENCODER )
- if ( ascii85_p )
- _TIFFfree( ascii85_p );
+ for (cp = tf_buf; cc > 0; cc--)
+ Ascii85Put(*cp++, fd);
+ Ascii85Flush(fd);
+#endif /* EXP_ASCII85ENCODER */
+ }
+ }
+ _TIFFfree((char *)tf_buf);
+
+#if defined(EXP_ASCII85ENCODER)
+ if (ascii85_p)
+ _TIFFfree(ascii85_p);
#endif
}
-void
-Ascii85Init(void)
+void Ascii85Init(void)
{
- ascii85breaklen = 2*MAXLINE;
- ascii85count = 0;
+ ascii85breaklen = 2 * MAXLINE;
+ ascii85count = 0;
}
-static char*
-Ascii85Encode(unsigned char* raw)
+static char *Ascii85Encode(unsigned char *raw)
{
- static char encoded[6];
- uint32_t word;
-
- word = (((raw[0]<<8)+raw[1])<<16) + (raw[2]<<8) + raw[3];
- if (word != 0L) {
- uint32_t q;
- uint16_t w1;
-
- q = word / (85L*85*85*85); /* actually only a byte */
- encoded[0] = (char) (q + '!');
-
- word -= q * (85L*85*85*85); q = word / (85L*85*85);
- encoded[1] = (char) (q + '!');
-
- word -= q * (85L*85*85); q = word / (85*85);
- encoded[2] = (char) (q + '!');
-
- w1 = (uint16_t) (word - q * (85L * 85));
- encoded[3] = (char) ((w1 / 85) + '!');
- encoded[4] = (char) ((w1 % 85) + '!');
- encoded[5] = '\0';
- } else
- encoded[0] = 'z', encoded[1] = '\0';
- return (encoded);
+ static char encoded[6];
+ uint32_t word;
+
+ word = (((raw[0] << 8) + raw[1]) << 16) + (raw[2] << 8) + raw[3];
+ if (word != 0L)
+ {
+ uint32_t q;
+ uint16_t w1;
+
+ q = word / (85L * 85 * 85 * 85); /* actually only a byte */
+ encoded[0] = (char)(q + '!');
+
+ word -= q * (85L * 85 * 85 * 85);
+ q = word / (85L * 85 * 85);
+ encoded[1] = (char)(q + '!');
+
+ word -= q * (85L * 85 * 85);
+ q = word / (85 * 85);
+ encoded[2] = (char)(q + '!');
+
+ w1 = (uint16_t)(word - q * (85L * 85));
+ encoded[3] = (char)((w1 / 85) + '!');
+ encoded[4] = (char)((w1 % 85) + '!');
+ encoded[5] = '\0';
+ }
+ else
+ encoded[0] = 'z', encoded[1] = '\0';
+ return (encoded);
}
-void
-Ascii85Put(unsigned char code, FILE* fd)
+void Ascii85Put(unsigned char code, FILE *fd)
{
- ascii85buf[ascii85count++] = code;
- if (ascii85count >= 4) {
- unsigned char* p;
- int n;
-
- for (n = ascii85count, p = ascii85buf; n >= 4; n -= 4, p += 4) {
- char* cp;
- for (cp = Ascii85Encode(p); *cp; cp++) {
- putc(*cp, fd);
- if (--ascii85breaklen == 0) {
- putc('\n', fd);
- ascii85breaklen = 2*MAXLINE;
- }
- }
- }
- _TIFFmemcpy(ascii85buf, p, n);
- ascii85count = n;
- }
+ ascii85buf[ascii85count++] = code;
+ if (ascii85count >= 4)
+ {
+ unsigned char *p;
+ int n;
+
+ for (n = ascii85count, p = ascii85buf; n >= 4; n -= 4, p += 4)
+ {
+ char *cp;
+ for (cp = Ascii85Encode(p); *cp; cp++)
+ {
+ putc(*cp, fd);
+ if (--ascii85breaklen == 0)
+ {
+ putc('\n', fd);
+ ascii85breaklen = 2 * MAXLINE;
+ }
+ }
+ }
+ _TIFFmemcpy(ascii85buf, p, n);
+ ascii85count = n;
+ }
}
-void
-Ascii85Flush(FILE* fd)
+void Ascii85Flush(FILE *fd)
{
- if (ascii85count > 0) {
- char* res;
- _TIFFmemset(&ascii85buf[ascii85count], 0, 3);
- res = Ascii85Encode(ascii85buf);
- fwrite(res[0] == 'z' ? "!!!!" : res, ascii85count + 1, 1, fd);
- }
- fputs("~>\n", fd);
+ if (ascii85count > 0)
+ {
+ char *res;
+ _TIFFmemset(&ascii85buf[ascii85count], 0, 3);
+ res = Ascii85Encode(ascii85buf);
+ fwrite(res[0] == 'z' ? "!!!!" : res, ascii85count + 1, 1, fd);
+ }
+ fputs("~>\n", fd);
}
-#if defined( EXP_ASCII85ENCODER)
-
-#define A85BREAKCNTR ascii85breaklen
-#define A85BREAKLEN (2*MAXLINE)
+#if defined(EXP_ASCII85ENCODER)
+
+#define A85BREAKCNTR ascii85breaklen
+#define A85BREAKLEN (2 * MAXLINE)
/*****************************************************************************
-*
-* Name: Ascii85EncodeBlock( ascii85_p, f_eod, raw_p, raw_l )
-*
-* Description: This routine will encode the raw data in the buffer described
-* by raw_p and raw_l into ASCII85 format and store the encoding
-* in the buffer given by ascii85_p.
-*
-* Parameters: ascii85_p - A buffer supplied by the caller which will
-* contain the encoded ASCII85 data.
-* f_eod - Flag: Nz means to end the encoded buffer with
-* an End-Of-Data marker.
-* raw_p - Pointer to the buffer of data to be encoded
-* raw_l - Number of bytes in raw_p[] to be encoded
-*
-* Returns: (int) < 0 Error, see errno
-* >= 0 Number of bytes written to ascii85_p[].
-*
-* Notes: An external variable given by A85BREAKCNTR is used to
-* determine when to insert newline characters into the
-* encoded data. As each byte is placed into ascii85_p this
-* external is decremented. If the variable is decrement to
-* or past zero then a newline is inserted into ascii85_p
-* and the A85BREAKCNTR is then reset to A85BREAKLEN.
-* Note: for efficiency reasons the A85BREAKCNTR variable
-* is not actually checked on *every* character
-* placed into ascii85_p but often only for every
-* 5 characters.
-*
-* THE CALLER IS RESPONSIBLE FOR ENSURING THAT ASCII85_P[] IS
-* SUFFICIENTLY LARGE TO THE ENCODED DATA!
-* You will need at least 5 * (raw_l/4) bytes plus space for
-* newline characters and space for an EOD marker (if
-* requested). A safe calculation is to use 6*(raw_l/4) + 8
-* to size ascii85_p.
-*
-*****************************************************************************/
-
-tsize_t Ascii85EncodeBlock(uint8_t * ascii85_p, unsigned f_eod, const uint8_t * raw_p, tsize_t raw_l )
+ *
+ * Name: Ascii85EncodeBlock( ascii85_p, f_eod, raw_p, raw_l )
+ *
+ * Description: This routine will encode the raw data in the buffer described
+ * by raw_p and raw_l into ASCII85 format and store the encoding
+ * in the buffer given by ascii85_p.
+ *
+ * Parameters: ascii85_p - A buffer supplied by the caller which will
+ * contain the encoded ASCII85 data.
+ * f_eod - Flag: Nz means to end the encoded buffer with
+ * an End-Of-Data marker.
+ * raw_p - Pointer to the buffer of data to be encoded
+ * raw_l - Number of bytes in raw_p[] to be encoded
+ *
+ * Returns: (int) < 0 Error, see errno
+ * >= 0 Number of bytes written to ascii85_p[].
+ *
+ * Notes: An external variable given by A85BREAKCNTR is used to
+ * determine when to insert newline characters into the
+ * encoded data. As each byte is placed into ascii85_p this
+ * external is decremented. If the variable is decrement to
+ * or past zero then a newline is inserted into ascii85_p
+ * and the A85BREAKCNTR is then reset to A85BREAKLEN.
+ * Note: for efficiency reasons the A85BREAKCNTR variable
+ * is not actually checked on *every* character
+ * placed into ascii85_p but often only for every
+ * 5 characters.
+ *
+ * THE CALLER IS RESPONSIBLE FOR ENSURING THAT ASCII85_P[] IS
+ * SUFFICIENTLY LARGE TO THE ENCODED DATA!
+ * You will need at least 5 * (raw_l/4) bytes plus space for
+ * newline characters and space for an EOD marker (if
+ * requested). A safe calculation is to use 6*(raw_l/4) + 8
+ * to size ascii85_p.
+ *
+ *****************************************************************************/
+
+tsize_t Ascii85EncodeBlock(uint8_t *ascii85_p, unsigned f_eod,
+ const uint8_t *raw_p, tsize_t raw_l)
{
- char ascii85[5]; /* Encoded 5 tuple */
- tsize_t ascii85_l; /* Number of bytes written to ascii85_p[] */
- int rc; /* Return code */
- uint32_t val32; /* Unencoded 4 tuple */
+ char ascii85[5]; /* Encoded 5 tuple */
+ tsize_t ascii85_l; /* Number of bytes written to ascii85_p[] */
+ int rc; /* Return code */
+ uint32_t val32; /* Unencoded 4 tuple */
- ascii85_l = 0; /* Nothing written yet */
+ ascii85_l = 0; /* Nothing written yet */
- if ( raw_p )
+ if (raw_p)
{
- --raw_p; /* Prepare for pre-increment fetches */
+ --raw_p; /* Prepare for pre-increment fetches */
- for ( ; raw_l > 3; raw_l -= 4 )
+ for (; raw_l > 3; raw_l -= 4)
{
- val32 = (uint32_t)*(++raw_p) << 24;
- val32 += (uint32_t)*(++raw_p) << 16;
- val32 += (uint32_t)*(++raw_p) << 8;
- val32 += (uint32_t)*(++raw_p);
-
- if ( val32 == 0 ) /* Special case */
+ val32 = (uint32_t) * (++raw_p) << 24;
+ val32 += (uint32_t) * (++raw_p) << 16;
+ val32 += (uint32_t) * (++raw_p) << 8;
+ val32 += (uint32_t) * (++raw_p);
+
+ if (val32 == 0) /* Special case */
{
ascii85_p[ascii85_l] = 'z';
rc = 1;
}
-
+
else
{
- ascii85[4] = (char) ((val32 % 85) + 33);
+ ascii85[4] = (char)((val32 % 85) + 33);
val32 /= 85;
-
- ascii85[3] = (char) ((val32 % 85) + 33);
+
+ ascii85[3] = (char)((val32 % 85) + 33);
val32 /= 85;
-
- ascii85[2] = (char) ((val32 % 85) + 33);
+
+ ascii85[2] = (char)((val32 % 85) + 33);
val32 /= 85;
-
- ascii85[1] = (char) ((val32 % 85) + 33);
- ascii85[0] = (char) ((val32 / 85) + 33);
- _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, sizeof(ascii85) );
+ ascii85[1] = (char)((val32 % 85) + 33);
+ ascii85[0] = (char)((val32 / 85) + 33);
+
+ _TIFFmemcpy(&ascii85_p[ascii85_l], ascii85, sizeof(ascii85));
rc = sizeof(ascii85);
}
-
+
ascii85_l += rc;
-
- if ( (A85BREAKCNTR -= rc) <= 0 )
+
+ if ((A85BREAKCNTR -= rc) <= 0)
{
ascii85_p[ascii85_l] = '\n';
++ascii85_l;
A85BREAKCNTR = A85BREAKLEN;
}
}
-
+
/*
* Output any straggler bytes:
*/
-
- if ( raw_l > 0 )
+
+ if (raw_l > 0)
{
- tsize_t len; /* Output this many bytes */
-
+ tsize_t len; /* Output this many bytes */
+
len = raw_l + 1;
- val32 = (uint32_t)*++raw_p << 24; /* Prime the pump */
-
- if ( --raw_l > 0 ) val32 += *(++raw_p) << 16;
- if ( --raw_l > 0 ) val32 += *(++raw_p) << 8;
-
+ val32 = (uint32_t) * ++raw_p << 24; /* Prime the pump */
+
+ if (--raw_l > 0)
+ val32 += *(++raw_p) << 16;
+ if (--raw_l > 0)
+ val32 += *(++raw_p) << 8;
+
val32 /= 85;
-
- ascii85[3] = (char) ((val32 % 85) + 33);
+
+ ascii85[3] = (char)((val32 % 85) + 33);
val32 /= 85;
-
- ascii85[2] = (char) ((val32 % 85) + 33);
+
+ ascii85[2] = (char)((val32 % 85) + 33);
val32 /= 85;
-
- ascii85[1] = (char) ((val32 % 85) + 33);
- ascii85[0] = (char) ((val32 / 85) + 33);
-
- _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, len );
+
+ ascii85[1] = (char)((val32 % 85) + 33);
+ ascii85[0] = (char)((val32 / 85) + 33);
+
+ _TIFFmemcpy(&ascii85_p[ascii85_l], ascii85, len);
ascii85_l += len;
}
}
@@ -3079,64 +3406,66 @@ tsize_t Ascii85EncodeBlock(uint8_t * ascii85_p, unsigned f_eod, const uint8_t *
* If requested add an ASCII85 End Of Data marker:
*/
- if ( f_eod )
+ if (f_eod)
{
ascii85_p[ascii85_l++] = '~';
ascii85_p[ascii85_l++] = '>';
ascii85_p[ascii85_l++] = '\n';
}
- return ( ascii85_l );
-
-} /* Ascii85EncodeBlock() */
+ return (ascii85_l);
-#endif /* EXP_ASCII85ENCODER */
+} /* Ascii85EncodeBlock() */
+#endif /* EXP_ASCII85ENCODER */
static const char usage_info[] =
-"Convert a TIFF image to PostScript\n\n"
-"usage: tiff2ps [options] input.tif ...\n"
-"where options are:\n"
-" -1 generate PostScript Level 1 (default)\n"
-" -2 generate PostScript Level 2\n"
-" -3 generate PostScript Level 3\n"
-" -8 disable use of ASCII85 encoding with PostScript Level 2/3\n"
-" -a convert all directories in file (default is first), Not EPS\n"
-" -b # set the bottom margin to # inches\n"
-" -c center image (-b and -l still add to this)\n"
-" -C name set postscript document creator name\n"
-" -d # set initial directory to # counting from zero\n"
-" -D enable duplex printing (two pages per sheet of paper)\n"
-" -e generate Encapsulated PostScript (EPS) (implies -z)\n"
-" -h # set printed page height to # inches (no default)\n"
-" -w # set printed page width to # inches (no default)\n"
-" -H # split image if height is more than # inches\n"
-" -W # split image if width is more than # inches\n"
-" -L # overLap split images by # inches\n"
-" -i # enable/disable (Nz/0) pixel interpolation (default: enable)\n"
-" -l # set the left margin to # inches\n"
-" -m use \"imagemask\" operator instead of \"image\"\n"
-" -M size set the memory allocation limit in MiB. 0 to disable limit\n"
-" -o # convert directory at file offset # bytes\n"
-" -O file write PostScript to file instead of standard output\n"
-" -p generate regular (non-encapsulated) PostScript\n"
-" -P L or P set optional PageOrientation DSC comment to Landscape or Portrait\n"
-" -r # or auto rotate by 90, 180, 270 degrees or auto\n"
-" -s generate PostScript for a single image\n"
-" -t name set postscript document title. Otherwise the filename is used\n"
-" -T print pages for top edge binding\n"
-" -x override resolution units as centimeters\n"
-" -y override resolution units as inches\n"
-" -z enable printing in the deadzone (only for PostScript Level 2/3)\n"
-;
-
-static void
-usage(int code)
+ "Convert a TIFF image to PostScript\n\n"
+ "usage: tiff2ps [options] input.tif ...\n"
+ "where options are:\n"
+ " -1 generate PostScript Level 1 (default)\n"
+ " -2 generate PostScript Level 2\n"
+ " -3 generate PostScript Level 3\n"
+ " -8 disable use of ASCII85 encoding with PostScript Level 2/3\n"
+ " -a convert all directories in file (default is first), Not "
+ "EPS\n"
+ " -b # set the bottom margin to # inches\n"
+ " -c center image (-b and -l still add to this)\n"
+ " -C name set postscript document creator name\n"
+ " -d # set initial directory to # counting from zero\n"
+ " -D enable duplex printing (two pages per sheet of paper)\n"
+ " -e generate Encapsulated PostScript (EPS) (implies -z)\n"
+ " -h # set printed page height to # inches (no default)\n"
+ " -w # set printed page width to # inches (no default)\n"
+ " -H # split image if height is more than # inches\n"
+ " -W # split image if width is more than # inches\n"
+ " -L # overLap split images by # inches\n"
+ " -i # enable/disable (Nz/0) pixel interpolation (default: "
+ "enable)\n"
+ " -l # set the left margin to # inches\n"
+ " -m use \"imagemask\" operator instead of \"image\"\n"
+ " -M size set the memory allocation limit in MiB. 0 to disable "
+ "limit\n"
+ " -o # convert directory at file offset # bytes\n"
+ " -O file write PostScript to file instead of standard output\n"
+ " -p generate regular (non-encapsulated) PostScript\n"
+ " -P L or P set optional PageOrientation DSC comment to Landscape or "
+ "Portrait\n"
+ " -r # or auto rotate by 90, 180, 270 degrees or auto\n"
+ " -s generate PostScript for a single image\n"
+ " -t name set postscript document title. Otherwise the filename is "
+ "used\n"
+ " -T print pages for top edge binding\n"
+ " -x override resolution units as centimeters\n"
+ " -y override resolution units as inches\n"
+ " -z enable printing in the deadzone (only for PostScript Level "
+ "2/3)\n";
+
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
-
diff --git a/tools/tiff2rgba.c b/tools/tiff2rgba.c
index feeeaac1..693fc814 100644
--- a/tools/tiff2rgba.c
+++ b/tools/tiff2rgba.c
@@ -2,7 +2,7 @@
* Copyright (c) 1991-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
@@ -22,19 +22,19 @@
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
#include <stdio.h>
-#include <string.h>
#include <stdlib.h>
+#include <string.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
-#include "tiffiop.h"
#include "tiffio.h"
+#include "tiffiop.h"
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
@@ -43,17 +43,18 @@
#define EXIT_FAILURE 1
#endif
-#define streq(a,b) (strcmp(a,b) == 0)
-#define CopyField(tag, v) \
- if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
+#define streq(a, b) (strcmp(a, b) == 0)
+#define CopyField(tag, v) \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v)
#ifndef howmany
-#define howmany(x, y) (((x)+((y)-1))/(y))
+#define howmany(x, y) (((x) + ((y)-1)) / (y))
#endif
-#define roundup(x, y) (howmany(x,y)*((uint32_t)(y)))
+#define roundup(x, y) (howmany(x, y) * ((uint32_t)(y)))
static uint16_t compression = COMPRESSION_PACKBITS;
-static uint32_t rowsperstrip = (uint32_t) -1;
+static uint32_t rowsperstrip = (uint32_t)-1;
static int process_by_block = 0; /* default is whole image at once */
static int no_alpha = 0;
static int bigtiff_output = 0;
@@ -62,139 +63,145 @@ static int bigtiff_output = 0;
* disabled when set to 0 */
static tmsize_t maxMalloc = DEFAULT_MAX_MALLOC;
-
-static int tiffcvt(TIFF* in, TIFF* out);
+static int tiffcvt(TIFF *in, TIFF *out);
static void usage(int code);
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- TIFF *in, *out;
- int c;
+ TIFF *in, *out;
+ int c;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char *optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- while ((c = getopt(argc, argv, "c:r:t:bn8hM:")) != -1)
- switch (c) {
- case 'M':
- maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
- break;
- case 'b':
- process_by_block = 1;
- break;
-
- case 'c':
- if (streq(optarg, "none"))
- compression = COMPRESSION_NONE;
- else if (streq(optarg, "packbits"))
- compression = COMPRESSION_PACKBITS;
- else if (streq(optarg, "lzw"))
- compression = COMPRESSION_LZW;
- else if (streq(optarg, "jpeg"))
- compression = COMPRESSION_JPEG;
- else if (streq(optarg, "zip"))
- compression = COMPRESSION_ADOBE_DEFLATE;
- else
- usage(EXIT_FAILURE);
- break;
-
- case 'r':
- rowsperstrip = atoi(optarg);
- break;
-
- case 't':
- rowsperstrip = atoi(optarg);
- break;
-
- case 'n':
- no_alpha = 1;
- break;
-
- case '8':
- bigtiff_output = 1;
- break;
-
- case 'h':
- usage(EXIT_SUCCESS);
- /*NOTREACHED*/
- break;
- case '?':
- usage(EXIT_FAILURE);
- /*NOTREACHED*/
- break;
- }
-
- if (argc - optind < 2)
- usage(EXIT_FAILURE);
-
- TIFFOpenOptions* opts = TIFFOpenOptionsAlloc();
- if (opts == NULL) {
- return EXIT_FAILURE;
- }
- TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
- out = TIFFOpenExt(argv[argc-1], bigtiff_output?"w8":"w", opts);
- if (out == NULL) {
- TIFFOpenOptionsFree(opts);
- return (EXIT_FAILURE);
- }
-
- for (; optind < argc-1; optind++) {
- in = TIFFOpenExt(argv[optind], "r", opts);
- if (in != NULL) {
- do {
- if (!tiffcvt(in, out) ||
- !TIFFWriteDirectory(out)) {
- (void) TIFFClose(out);
- (void) TIFFClose(in);
- TIFFOpenOptionsFree(opts);
- return (1);
- }
- } while (TIFFReadDirectory(in));
- (void) TIFFClose(in);
- }
- }
- TIFFOpenOptionsFree(opts);
- (void) TIFFClose(out);
- return (EXIT_SUCCESS);
+ while ((c = getopt(argc, argv, "c:r:t:bn8hM:")) != -1)
+ switch (c)
+ {
+ case 'M':
+ maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
+ break;
+ case 'b':
+ process_by_block = 1;
+ break;
+
+ case 'c':
+ if (streq(optarg, "none"))
+ compression = COMPRESSION_NONE;
+ else if (streq(optarg, "packbits"))
+ compression = COMPRESSION_PACKBITS;
+ else if (streq(optarg, "lzw"))
+ compression = COMPRESSION_LZW;
+ else if (streq(optarg, "jpeg"))
+ compression = COMPRESSION_JPEG;
+ else if (streq(optarg, "zip"))
+ compression = COMPRESSION_ADOBE_DEFLATE;
+ else
+ usage(EXIT_FAILURE);
+ break;
+
+ case 'r':
+ rowsperstrip = atoi(optarg);
+ break;
+
+ case 't':
+ rowsperstrip = atoi(optarg);
+ break;
+
+ case 'n':
+ no_alpha = 1;
+ break;
+
+ case '8':
+ bigtiff_output = 1;
+ break;
+
+ case 'h':
+ usage(EXIT_SUCCESS);
+ /*NOTREACHED*/
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ /*NOTREACHED*/
+ break;
+ }
+
+ if (argc - optind < 2)
+ usage(EXIT_FAILURE);
+
+ TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
+ if (opts == NULL)
+ {
+ return EXIT_FAILURE;
+ }
+ TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
+ out = TIFFOpenExt(argv[argc - 1], bigtiff_output ? "w8" : "w", opts);
+ if (out == NULL)
+ {
+ TIFFOpenOptionsFree(opts);
+ return (EXIT_FAILURE);
+ }
+
+ for (; optind < argc - 1; optind++)
+ {
+ in = TIFFOpenExt(argv[optind], "r", opts);
+ if (in != NULL)
+ {
+ do
+ {
+ if (!tiffcvt(in, out) || !TIFFWriteDirectory(out))
+ {
+ (void)TIFFClose(out);
+ (void)TIFFClose(in);
+ TIFFOpenOptionsFree(opts);
+ return (1);
+ }
+ } while (TIFFReadDirectory(in));
+ (void)TIFFClose(in);
+ }
+ }
+ TIFFOpenOptionsFree(opts);
+ (void)TIFFClose(out);
+ return (EXIT_SUCCESS);
}
-static int
-cvt_by_tile( TIFF *in, TIFF *out )
+static int cvt_by_tile(TIFF *in, TIFF *out)
{
- uint32_t* raster; /* retrieve RGBA image */
- uint32_t width, height; /* image width & height */
- uint32_t tile_width, tile_height;
- uint32_t row, col;
- uint32_t *wrk_line;
- int ok = 1;
- uint32_t rastersize, wrk_linesize;
+ uint32_t *raster; /* retrieve RGBA image */
+ uint32_t width, height; /* image width & height */
+ uint32_t tile_width, tile_height;
+ uint32_t row, col;
+ uint32_t *wrk_line;
+ int ok = 1;
+ uint32_t rastersize, wrk_linesize;
TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height);
- if( !TIFFGetField(in, TIFFTAG_TILEWIDTH, &tile_width)
- || !TIFFGetField(in, TIFFTAG_TILELENGTH, &tile_height) ) {
+ if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tile_width) ||
+ !TIFFGetField(in, TIFFTAG_TILELENGTH, &tile_height))
+ {
TIFFError(TIFFFileName(in), "Source image not tiled");
return (0);
}
-
- TIFFSetField(out, TIFFTAG_TILEWIDTH, tile_width );
- TIFFSetField(out, TIFFTAG_TILELENGTH, tile_height );
+
+ TIFFSetField(out, TIFFTAG_TILEWIDTH, tile_width);
+ TIFFSetField(out, TIFFTAG_TILELENGTH, tile_height);
/*
* Allocate tile buffer
*/
- rastersize = tile_width * tile_height * sizeof (uint32_t);
- if (tile_width != (rastersize / tile_height) / sizeof( uint32_t))
+ rastersize = tile_width * tile_height * sizeof(uint32_t);
+ if (tile_width != (rastersize / tile_height) / sizeof(uint32_t))
{
- TIFFError(TIFFFileName(in), "Integer overflow when calculating raster buffer");
- exit(EXIT_FAILURE);
+ TIFFError(TIFFFileName(in),
+ "Integer overflow when calculating raster buffer");
+ exit(EXIT_FAILURE);
}
- raster = (uint32_t*)_TIFFmalloc(rastersize);
- if (raster == 0) {
+ raster = (uint32_t *)_TIFFmalloc(rastersize);
+ if (raster == 0)
+ {
TIFFError(TIFFFileName(in), "No space for raster buffer");
return (0);
}
@@ -203,66 +210,67 @@ cvt_by_tile( TIFF *in, TIFF *out )
* Allocate a scanline buffer for swapping during the vertical
* mirroring pass.
*/
- wrk_linesize = tile_width * sizeof (uint32_t);
- if (tile_width != wrk_linesize / sizeof (uint32_t))
+ wrk_linesize = tile_width * sizeof(uint32_t);
+ if (tile_width != wrk_linesize / sizeof(uint32_t))
{
- TIFFError(TIFFFileName(in), "Integer overflow when calculating wrk_line buffer");
- exit(EXIT_FAILURE);
+ TIFFError(TIFFFileName(in),
+ "Integer overflow when calculating wrk_line buffer");
+ exit(EXIT_FAILURE);
}
- wrk_line = (uint32_t*)_TIFFmalloc(wrk_linesize);
- if (!wrk_line) {
+ wrk_line = (uint32_t *)_TIFFmalloc(wrk_linesize);
+ if (!wrk_line)
+ {
TIFFError(TIFFFileName(in), "No space for raster scanline buffer");
ok = 0;
}
-
+
/*
* Loop over the tiles.
*/
- for( row = 0; ok && row < height; row += tile_height )
+ for (row = 0; ok && row < height; row += tile_height)
{
- for( col = 0; ok && col < width; col += tile_width )
+ for (col = 0; ok && col < width; col += tile_width)
{
uint32_t i_row;
/* Read the tile into an RGBA array */
- if (!TIFFReadRGBATile(in, col, row, raster)) {
+ if (!TIFFReadRGBATile(in, col, row, raster))
+ {
ok = 0;
break;
}
-
- /*
- * XXX: raster array has 4-byte unsigned integer type, that is why
- * we should rearrange it here.
- */
+ /*
+ * XXX: raster array has 4-byte unsigned integer type, that is why
+ * we should rearrange it here.
+ */
#if HOST_BIGENDIAN
- TIFFSwabArrayOfLong(raster, tile_width * tile_height);
+ TIFFSwabArrayOfLong(raster, tile_width * tile_height);
#endif
/*
* For some reason the TIFFReadRGBATile() function chooses the
* lower left corner as the origin. Vertically mirror scanlines.
*/
- for( i_row = 0; i_row < tile_height / 2; i_row++ )
+ for (i_row = 0; i_row < tile_height / 2; i_row++)
{
- uint32_t *top_line, *bottom_line;
+ uint32_t *top_line, *bottom_line;
top_line = raster + tile_width * i_row;
- bottom_line = raster + tile_width * (tile_height-i_row-1);
+ bottom_line = raster + tile_width * (tile_height - i_row - 1);
- _TIFFmemcpy(wrk_line, top_line, 4*tile_width);
- _TIFFmemcpy(top_line, bottom_line, 4*tile_width);
- _TIFFmemcpy(bottom_line, wrk_line, 4*tile_width);
+ _TIFFmemcpy(wrk_line, top_line, 4 * tile_width);
+ _TIFFmemcpy(top_line, bottom_line, 4 * tile_width);
+ _TIFFmemcpy(bottom_line, wrk_line, 4 * tile_width);
}
/*
* Write out the result in a tile.
*/
- if( TIFFWriteEncodedTile( out,
- TIFFComputeTile( out, col, row, 0, 0),
- raster,
- 4 * tile_width * tile_height ) == -1 )
+ if (TIFFWriteEncodedTile(out, TIFFComputeTile(out, col, row, 0, 0),
+ raster,
+ 4 * tile_width * tile_height) == -1)
{
ok = 0;
break;
@@ -270,44 +278,46 @@ cvt_by_tile( TIFF *in, TIFF *out )
}
}
- _TIFFfree( raster );
- _TIFFfree( wrk_line );
+ _TIFFfree(raster);
+ _TIFFfree(wrk_line);
return ok;
}
-static int
-cvt_by_strip( TIFF *in, TIFF *out )
+static int cvt_by_strip(TIFF *in, TIFF *out)
{
- uint32_t* raster; /* retrieve RGBA image */
- uint32_t width, height; /* image width & height */
- uint32_t row;
- uint32_t *wrk_line;
- int ok = 1;
- uint32_t rastersize, wrk_linesize;
+ uint32_t *raster; /* retrieve RGBA image */
+ uint32_t width, height; /* image width & height */
+ uint32_t row;
+ uint32_t *wrk_line;
+ int ok = 1;
+ uint32_t rastersize, wrk_linesize;
TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height);
- if( !TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip) ) {
+ if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
+ {
TIFFError(TIFFFileName(in), "Source image not in strips");
return (0);
}
-
+
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
/*
* Allocate strip buffer
*/
- rastersize = width * rowsperstrip * sizeof (uint32_t);
- if (width != (rastersize / rowsperstrip) / sizeof( uint32_t))
+ rastersize = width * rowsperstrip * sizeof(uint32_t);
+ if (width != (rastersize / rowsperstrip) / sizeof(uint32_t))
{
- TIFFError(TIFFFileName(in), "Integer overflow when calculating raster buffer");
- exit(EXIT_FAILURE);
+ TIFFError(TIFFFileName(in),
+ "Integer overflow when calculating raster buffer");
+ exit(EXIT_FAILURE);
}
- raster = (uint32_t*)_TIFFmalloc(rastersize);
- if (raster == 0) {
+ raster = (uint32_t *)_TIFFmalloc(rastersize);
+ if (raster == 0)
+ {
TIFFError(TIFFFileName(in), "No space for raster buffer");
return (0);
}
@@ -316,43 +326,46 @@ cvt_by_strip( TIFF *in, TIFF *out )
* Allocate a scanline buffer for swapping during the vertical
* mirroring pass.
*/
- wrk_linesize = width * sizeof (uint32_t);
- if (width != wrk_linesize / sizeof (uint32_t))
+ wrk_linesize = width * sizeof(uint32_t);
+ if (width != wrk_linesize / sizeof(uint32_t))
{
- TIFFError(TIFFFileName(in), "Integer overflow when calculating wrk_line buffer");
- exit(EXIT_FAILURE);
+ TIFFError(TIFFFileName(in),
+ "Integer overflow when calculating wrk_line buffer");
+ exit(EXIT_FAILURE);
}
- wrk_line = (uint32_t*)_TIFFmalloc(wrk_linesize);
- if (!wrk_line) {
+ wrk_line = (uint32_t *)_TIFFmalloc(wrk_linesize);
+ if (!wrk_line)
+ {
TIFFError(TIFFFileName(in), "No space for raster scanline buffer");
ok = 0;
}
-
+
/*
* Loop over the strips.
*/
- for( row = 0; ok && row < height; row += rowsperstrip )
+ for (row = 0; ok && row < height; row += rowsperstrip)
{
- int rows_to_write, i_row;
+ int rows_to_write, i_row;
/* Read the strip into an RGBA array */
- if (!TIFFReadRGBAStrip(in, row, raster)) {
+ if (!TIFFReadRGBAStrip(in, row, raster))
+ {
ok = 0;
break;
}
- /*
- * XXX: raster array has 4-byte unsigned integer type, that is why
- * we should rearrange it here.
- */
+ /*
+ * XXX: raster array has 4-byte unsigned integer type, that is why
+ * we should rearrange it here.
+ */
#if HOST_BIGENDIAN
- TIFFSwabArrayOfLong(raster, width * rowsperstrip);
+ TIFFSwabArrayOfLong(raster, width * rowsperstrip);
#endif
/*
* Figure out the number of scanlines actually in this strip.
*/
- if( row + rowsperstrip > height )
+ if (row + rowsperstrip > height)
rows_to_write = height - row;
else
rows_to_write = rowsperstrip;
@@ -362,32 +375,32 @@ cvt_by_strip( TIFF *in, TIFF *out )
* lower left corner as the origin. Vertically mirror scanlines.
*/
- for( i_row = 0; i_row < rows_to_write / 2; i_row++ )
+ for (i_row = 0; i_row < rows_to_write / 2; i_row++)
{
- uint32_t *top_line, *bottom_line;
+ uint32_t *top_line, *bottom_line;
top_line = raster + width * i_row;
- bottom_line = raster + width * (rows_to_write-i_row-1);
+ bottom_line = raster + width * (rows_to_write - i_row - 1);
- _TIFFmemcpy(wrk_line, top_line, 4*width);
- _TIFFmemcpy(top_line, bottom_line, 4*width);
- _TIFFmemcpy(bottom_line, wrk_line, 4*width);
+ _TIFFmemcpy(wrk_line, top_line, 4 * width);
+ _TIFFmemcpy(top_line, bottom_line, 4 * width);
+ _TIFFmemcpy(bottom_line, wrk_line, 4 * width);
}
/*
* Write out the result in a strip
*/
- if( TIFFWriteEncodedStrip( out, row / rowsperstrip, raster,
- 4 * rows_to_write * width ) == -1 )
+ if (TIFFWriteEncodedStrip(out, row / rowsperstrip, raster,
+ 4 * rows_to_write * width) == -1)
{
ok = 0;
break;
}
}
- _TIFFfree( raster );
- _TIFFfree( wrk_line );
+ _TIFFfree(raster);
+ _TIFFfree(wrk_line);
return ok;
}
@@ -400,46 +413,56 @@ cvt_by_strip( TIFF *in, TIFF *out )
* API that we trust.
*/
-static int
-cvt_whole_image( TIFF *in, TIFF *out )
+static int cvt_whole_image(TIFF *in, TIFF *out)
{
- uint32_t* raster; /* retrieve RGBA image */
- uint32_t width, height; /* image width & height */
- uint32_t row;
+ uint32_t *raster; /* retrieve RGBA image */
+ uint32_t width, height; /* image width & height */
+ uint32_t row;
size_t pixel_count;
-
+
TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height);
pixel_count = width * height;
/* XXX: Check the integer overflow. */
- if (!width || !height || pixel_count / width != height) {
- TIFFError(TIFFFileName(in),
- "Malformed input file; can't allocate buffer for raster of %"PRIu32"x%"PRIu32" size",
- width, height);
+ if (!width || !height || pixel_count / width != height)
+ {
+ TIFFError(
+ TIFFFileName(in),
+ "Malformed input file; can't allocate buffer for raster of %" PRIu32
+ "x%" PRIu32 " size",
+ width, height);
return 0;
}
- if (maxMalloc != 0 && (tmsize_t)pixel_count * (tmsize_t)sizeof(uint32_t) > maxMalloc) {
- TIFFError(TIFFFileName(in),
- "Raster size %"TIFF_SIZE_FORMAT" over memory limit (%" TIFF_SSIZE_FORMAT "), try -b option.",
- pixel_count * sizeof(uint32_t), maxMalloc);
+ if (maxMalloc != 0 &&
+ (tmsize_t)pixel_count * (tmsize_t)sizeof(uint32_t) > maxMalloc)
+ {
+ TIFFError(TIFFFileName(in),
+ "Raster size %" TIFF_SIZE_FORMAT
+ " over memory limit (%" TIFF_SSIZE_FORMAT "), try -b option.",
+ pixel_count * sizeof(uint32_t), maxMalloc);
return 0;
}
rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
- raster = (uint32_t*)_TIFFCheckMalloc(in, pixel_count, sizeof(uint32_t), "raster buffer");
- if (raster == 0) {
- TIFFError(TIFFFileName(in), "Failed to allocate buffer (%"TIFF_SIZE_FORMAT" elements of %"TIFF_SIZE_FORMAT" each)",
- pixel_count, sizeof(uint32_t));
+ raster = (uint32_t *)_TIFFCheckMalloc(in, pixel_count, sizeof(uint32_t),
+ "raster buffer");
+ if (raster == 0)
+ {
+ TIFFError(TIFFFileName(in),
+ "Failed to allocate buffer (%" TIFF_SIZE_FORMAT
+ " elements of %" TIFF_SIZE_FORMAT " each)",
+ pixel_count, sizeof(uint32_t));
return (0);
}
/* Read the image in one chunk into an RGBA array */
if (!TIFFReadRGBAImageOriented(in, width, height, raster,
- ORIENTATION_TOPLEFT, 0)) {
+ ORIENTATION_TOPLEFT, 0))
+ {
_TIFFfree(raster);
return (0);
}
@@ -460,14 +483,14 @@ cvt_whole_image( TIFF *in, TIFF *out )
size_t count = pixel_count;
unsigned char *src, *dst;
- src = dst = (unsigned char *) raster;
+ src = dst = (unsigned char *)raster;
while (count > 0)
{
- *(dst++) = *(src++);
- *(dst++) = *(src++);
- *(dst++) = *(src++);
- src++;
- count--;
+ *(dst++) = *(src++);
+ *(dst++) = *(src++);
+ *(dst++) = *(src++);
+ src++;
+ count--;
}
}
@@ -476,133 +499,134 @@ cvt_whole_image( TIFF *in, TIFF *out )
*/
for (row = 0; row < height; row += rowsperstrip)
{
- unsigned char * raster_strip;
- int rows_to_write;
- int bytes_per_pixel;
+ unsigned char *raster_strip;
+ int rows_to_write;
+ int bytes_per_pixel;
if (no_alpha)
{
- raster_strip = ((unsigned char *) raster) + 3 * row * width;
+ raster_strip = ((unsigned char *)raster) + 3 * row * width;
bytes_per_pixel = 3;
}
else
{
- raster_strip = (unsigned char *) (raster + row * width);
+ raster_strip = (unsigned char *)(raster + row * width);
bytes_per_pixel = 4;
}
- if( row + rowsperstrip > height )
+ if (row + rowsperstrip > height)
rows_to_write = height - row;
else
rows_to_write = rowsperstrip;
- if( TIFFWriteEncodedStrip( out, row / rowsperstrip, raster_strip,
- bytes_per_pixel * rows_to_write * width ) == -1 )
+ if (TIFFWriteEncodedStrip(out, row / rowsperstrip, raster_strip,
+ bytes_per_pixel * rows_to_write * width) ==
+ -1)
{
- _TIFFfree( raster );
+ _TIFFfree(raster);
return 0;
}
}
- _TIFFfree( raster );
+ _TIFFfree(raster);
return 1;
}
-
-static int
-tiffcvt(TIFF* in, TIFF* out)
+static int tiffcvt(TIFF *in, TIFF *out)
{
- uint32_t width, height; /* image width & height */
- uint16_t shortv;
- float floatv;
- char *stringv;
- uint32_t longv;
- uint16_t v[1];
-
- TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width);
- TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height);
-
- CopyField(TIFFTAG_SUBFILETYPE, longv);
- TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
- TIFFSetField(out, TIFFTAG_IMAGELENGTH, height);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
-
- CopyField(TIFFTAG_FILLORDER, shortv);
- TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
-
- if( no_alpha )
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
- else
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 4);
+ uint32_t width, height; /* image width & height */
+ uint16_t shortv;
+ float floatv;
+ char *stringv;
+ uint32_t longv;
+ uint16_t v[1];
- if( !no_alpha )
- {
- v[0] = EXTRASAMPLE_ASSOCALPHA;
- TIFFSetField(out, TIFFTAG_EXTRASAMPLES, 1, v);
- }
+ TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width);
+ TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height);
+
+ CopyField(TIFFTAG_SUBFILETYPE, longv);
+ TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
+ TIFFSetField(out, TIFFTAG_IMAGELENGTH, height);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
- CopyField(TIFFTAG_XRESOLUTION, floatv);
- CopyField(TIFFTAG_YRESOLUTION, floatv);
- CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
- TIFFSetField(out, TIFFTAG_SOFTWARE, TIFFGetVersion());
- CopyField(TIFFTAG_DOCUMENTNAME, stringv);
-
- if (maxMalloc != 0 && TIFFStripSize(in) > maxMalloc)
- {
- TIFFError(TIFFFileName(in),
- "Strip Size %" TIFF_SSIZE_FORMAT " over memory limit (%" TIFF_SSIZE_FORMAT ")",
+ CopyField(TIFFTAG_FILLORDER, shortv);
+ TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
+
+ if (no_alpha)
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
+ else
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 4);
+
+ if (!no_alpha)
+ {
+ v[0] = EXTRASAMPLE_ASSOCALPHA;
+ TIFFSetField(out, TIFFTAG_EXTRASAMPLES, 1, v);
+ }
+
+ CopyField(TIFFTAG_XRESOLUTION, floatv);
+ CopyField(TIFFTAG_YRESOLUTION, floatv);
+ CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+ TIFFSetField(out, TIFFTAG_SOFTWARE, TIFFGetVersion());
+ CopyField(TIFFTAG_DOCUMENTNAME, stringv);
+
+ if (maxMalloc != 0 && TIFFStripSize(in) > maxMalloc)
+ {
+ TIFFError(TIFFFileName(in),
+ "Strip Size %" TIFF_SSIZE_FORMAT
+ " over memory limit (%" TIFF_SSIZE_FORMAT ")",
TIFFStripSize(in), maxMalloc);
- return 0;
- }
- if( process_by_block && TIFFIsTiled( in ) )
- return( cvt_by_tile( in, out ) );
- else if( process_by_block )
- return( cvt_by_strip( in, out ) );
- else
- return( cvt_whole_image( in, out ) );
+ return 0;
+ }
+ if (process_by_block && TIFFIsTiled(in))
+ return (cvt_by_tile(in, out));
+ else if (process_by_block)
+ return (cvt_by_strip(in, out));
+ else
+ return (cvt_whole_image(in, out));
}
static const char usage_info[] =
-/* Help information format modified for the sake of consistency with the other tiff tools */
-/* "usage: tiff2rgba [-c comp] [-r rows] [-b] [-n] [-8] [-M size] input... output" */
-/* "where comp is one of the following compression algorithms:" */
-"Convert a TIFF image to RGBA color space\n\n"
-"usage: tiff2rgba [options] input output\n"
-"where options are:\n"
+ /* Help information format modified for the sake of consistency with the
+ other tiff tools */
+ /* "usage: tiff2rgba [-c comp] [-r rows] [-b] [-n] [-8] [-M size]
+ input... output" */
+ /* "where comp is one of the following compression algorithms:" */
+ "Convert a TIFF image to RGBA color space\n\n"
+ "usage: tiff2rgba [options] input output\n"
+ "where options are:\n"
#ifdef JPEG_SUPPORT
-" -c jpeg JPEG encoding\n"
+ " -c jpeg JPEG encoding\n"
#endif
#ifdef ZIP_SUPPORT
-" -c zip Zip/Deflate encoding\n"
+ " -c zip Zip/Deflate encoding\n"
#endif
#ifdef LZW_SUPPORT
-" -c lzw Lempel-Ziv & Welch encoding\n"
+ " -c lzw Lempel-Ziv & Welch encoding\n"
#endif
#ifdef PACKBITS_SUPPORT
-" -c packbits PackBits encoding\n"
+ " -c packbits PackBits encoding\n"
#endif
-#if defined(JPEG_SUPPORT) || defined(ZIP_SUPPORT) || defined(LZW_SUPPORT) || defined(PACKBITS_SUPPORT)
-" -c none no compression\n"
+#if defined(JPEG_SUPPORT) || defined(ZIP_SUPPORT) || defined(LZW_SUPPORT) || \
+ defined(PACKBITS_SUPPORT)
+ " -c none no compression\n"
#endif
-"\n"
-/* "and the other options are:\n" */
-" -r rows/strip\n"
-" -b (progress by block rather than as a whole image)\n"
-" -n don't emit alpha component.\n"
-" -8 write BigTIFF file instead of ClassicTIFF\n"
-" -M set the memory allocation limit in MiB. 0 to disable limit\n"
-;
-
-static void
-usage(int code)
+ "\n"
+ /* "and the other options are:\n" */
+ " -r rows/strip\n"
+ " -b (progress by block rather than as a whole image)\n"
+ " -n don't emit alpha component.\n"
+ " -8 write BigTIFF file instead of ClassicTIFF\n"
+ " -M set the memory allocation limit in MiB. 0 to disable limit\n";
+
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
diff --git a/tools/tiffcmp.c b/tools/tiffcmp.c
index f13e3711..529c1cdc 100644
--- a/tools/tiffcmp.c
+++ b/tools/tiffcmp.c
@@ -2,36 +2,36 @@
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
+#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <math.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#include "tiffio.h"
@@ -43,23 +43,25 @@
#define EXIT_FAILURE 1
#endif
-static int stopondiff = 1;
-static int stoponfirsttag = 1;
-static uint16_t bitspersample = 1;
-static uint16_t samplesperpixel = 1;
-static uint16_t sampleformat = SAMPLEFORMAT_UINT;
-static uint32_t imagewidth;
-static uint32_t imagelength;
-
-static void usage(int code);
-static int tiffcmp(TIFF*, TIFF*);
-static int cmptags(TIFF*, TIFF*);
-static int ContigCompare(int, uint32_t, unsigned char*, unsigned char*, tsize_t);
-static int SeparateCompare(int, int, uint32_t, unsigned char*, unsigned char*);
-static void PrintIntDiff(uint32_t, int, uint32_t, uint32_t, uint32_t);
-static void PrintFloatDiff(uint32_t, int, uint32_t, double, double);
-
-static void leof(const char*, uint32_t, int);
+static int stopondiff = 1;
+static int stoponfirsttag = 1;
+static uint16_t bitspersample = 1;
+static uint16_t samplesperpixel = 1;
+static uint16_t sampleformat = SAMPLEFORMAT_UINT;
+static uint32_t imagewidth;
+static uint32_t imagelength;
+
+static void usage(int code);
+static int tiffcmp(TIFF *, TIFF *);
+static int cmptags(TIFF *, TIFF *);
+static int ContigCompare(int, uint32_t, unsigned char *, unsigned char *,
+ tsize_t);
+static int SeparateCompare(int, int, uint32_t, unsigned char *,
+ unsigned char *);
+static void PrintIntDiff(uint32_t, int, uint32_t, uint32_t, uint32_t);
+static void PrintFloatDiff(uint32_t, int, uint32_t, double, double);
+
+static void leof(const char *, uint32_t, int);
/*
* exit with status :
@@ -67,592 +69,642 @@ static void leof(const char*, uint32_t, int);
* 1 Differences were found.
* >1 An error occurred.
*/
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- TIFF *tif1, *tif2;
- int c, dirnum;
+ TIFF *tif1, *tif2;
+ int c, dirnum;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char* optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- while ((c = getopt(argc, argv, "ltz:h")) != -1)
- switch (c) {
- case 'l':
- stopondiff = 0;
- break;
- case 'z':
- stopondiff = atoi(optarg);
- break;
- case 't':
- stoponfirsttag = 0;
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- break;
- case '?':
- usage(2);
- /*NOTREACHED*/
- break;
- }
- if (argc - optind < 2)
- usage(2);
- tif1 = TIFFOpen(argv[optind], "r");
- if (tif1 == NULL)
- return (2);
- tif2 = TIFFOpen(argv[optind+1], "r");
- if (tif2 == NULL)
- return (2);
- dirnum = 0;
- while (tiffcmp(tif1, tif2)) {
- if (!TIFFReadDirectory(tif1)) {
- if (!TIFFReadDirectory(tif2))
- break;
- printf("No more directories for %s\n",
- TIFFFileName(tif1));
- return (1);
- } else if (!TIFFReadDirectory(tif2)) {
- printf("No more directories for %s\n",
- TIFFFileName(tif2));
- return (1);
- }
- printf("Directory %d:\n", ++dirnum);
- }
-
- TIFFClose(tif1);
- TIFFClose(tif2);
- return (0);
+ while ((c = getopt(argc, argv, "ltz:h")) != -1)
+ switch (c)
+ {
+ case 'l':
+ stopondiff = 0;
+ break;
+ case 'z':
+ stopondiff = atoi(optarg);
+ break;
+ case 't':
+ stoponfirsttag = 0;
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ break;
+ case '?':
+ usage(2);
+ /*NOTREACHED*/
+ break;
+ }
+ if (argc - optind < 2)
+ usage(2);
+ tif1 = TIFFOpen(argv[optind], "r");
+ if (tif1 == NULL)
+ return (2);
+ tif2 = TIFFOpen(argv[optind + 1], "r");
+ if (tif2 == NULL)
+ return (2);
+ dirnum = 0;
+ while (tiffcmp(tif1, tif2))
+ {
+ if (!TIFFReadDirectory(tif1))
+ {
+ if (!TIFFReadDirectory(tif2))
+ break;
+ printf("No more directories for %s\n", TIFFFileName(tif1));
+ return (1);
+ }
+ else if (!TIFFReadDirectory(tif2))
+ {
+ printf("No more directories for %s\n", TIFFFileName(tif2));
+ return (1);
+ }
+ printf("Directory %d:\n", ++dirnum);
+ }
+
+ TIFFClose(tif1);
+ TIFFClose(tif2);
+ return (0);
}
static const char usage_info[] =
-"Compare the tags and data in two TIFF files\n\n"
-"usage: tiffcmp [options] file1 file2\n"
-"where options are:\n"
-" -l list each byte of image data that differs between the files\n"
-" -z # list specified number of bytes that differs between the files\n"
-" -t ignore any differences in directory tags\n"
-;
-
-static void
-usage(int code)
+ "Compare the tags and data in two TIFF files\n\n"
+ "usage: tiffcmp [options] file1 file2\n"
+ "where options are:\n"
+ " -l list each byte of image data that differs between the "
+ "files\n"
+ " -z # list specified number of bytes that differs between "
+ "the files\n"
+ " -t ignore any differences in directory tags\n";
+
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
-#define checkEOF(tif, row, sample) { \
- leof(TIFFFileName(tif), row, sample); \
- goto bad; \
-}
+#define checkEOF(tif, row, sample) \
+ { \
+ leof(TIFFFileName(tif), row, sample); \
+ goto bad; \
+ }
-static int CheckShortTag(TIFF*, TIFF*, int, char*);
-static int CheckShort2Tag(TIFF*, TIFF*, int, char*);
-static int CheckShortArrayTag(TIFF*, TIFF*, int, char*);
-static int CheckLongTag(TIFF*, TIFF*, int, char*);
-static int CheckFloatTag(TIFF*, TIFF*, int, char*);
-static int CheckStringTag(TIFF*, TIFF*, int, char*);
+static int CheckShortTag(TIFF *, TIFF *, int, char *);
+static int CheckShort2Tag(TIFF *, TIFF *, int, char *);
+static int CheckShortArrayTag(TIFF *, TIFF *, int, char *);
+static int CheckLongTag(TIFF *, TIFF *, int, char *);
+static int CheckFloatTag(TIFF *, TIFF *, int, char *);
+static int CheckStringTag(TIFF *, TIFF *, int, char *);
-static int
-tiffcmp(TIFF* tif1, TIFF* tif2)
+static int tiffcmp(TIFF *tif1, TIFF *tif2)
{
- uint16_t config1, config2;
- tsize_t size1;
- uint32_t row;
- tsample_t s;
- unsigned char *buf1, *buf2;
-
- if (!CheckShortTag(tif1, tif2, TIFFTAG_BITSPERSAMPLE, "BitsPerSample"))
- return (0);
- if (!CheckShortTag(tif1, tif2, TIFFTAG_SAMPLESPERPIXEL, "SamplesPerPixel"))
- return (0);
- if (!CheckLongTag(tif1, tif2, TIFFTAG_IMAGEWIDTH, "ImageWidth"))
- return (0);
- if (!cmptags(tif1, tif2))
- return (1);
- (void) TIFFGetField(tif1, TIFFTAG_BITSPERSAMPLE, &bitspersample);
- (void) TIFFGetField(tif1, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
- (void) TIFFGetField(tif1, TIFFTAG_SAMPLEFORMAT, &sampleformat);
- (void) TIFFGetField(tif1, TIFFTAG_IMAGEWIDTH, &imagewidth);
- (void) TIFFGetField(tif1, TIFFTAG_IMAGELENGTH, &imagelength);
- (void) TIFFGetField(tif1, TIFFTAG_PLANARCONFIG, &config1);
- (void) TIFFGetField(tif2, TIFFTAG_PLANARCONFIG, &config2);
- buf1 = (unsigned char *)_TIFFmalloc(size1 = TIFFScanlineSize(tif1));
- buf2 = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif2));
- if (buf1 == NULL || buf2 == NULL) {
- fprintf(stderr, "No space for scanline buffers\n");
- exit(2);
- }
- if (config1 != config2 && bitspersample != 8 && samplesperpixel > 1) {
- fprintf(stderr,
-"Can't handle different planar configuration w/ different bits/sample\n");
- goto bad;
- }
-#define pack(a,b) ((a)<<8)|(b)
- switch (pack(config1, config2)) {
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG):
- for (row = 0; row < imagelength; row++) {
- if (TIFFReadScanline(tif2, buf2, row, 0) < 0)
- checkEOF(tif2, row, -1)
- for (s = 0; s < samplesperpixel; s++) {
- if (TIFFReadScanline(tif1, buf1, row, s) < 0)
- checkEOF(tif1, row, s)
- if (SeparateCompare(1, s, row, buf2, buf1) < 0)
- goto bad1;
- }
- }
- break;
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE):
- for (row = 0; row < imagelength; row++) {
- if (TIFFReadScanline(tif1, buf1, row, 0) < 0)
- checkEOF(tif1, row, -1)
- for (s = 0; s < samplesperpixel; s++) {
- if (TIFFReadScanline(tif2, buf2, row, s) < 0)
- checkEOF(tif2, row, s)
- if (SeparateCompare(0, s, row, buf1, buf2) < 0)
- goto bad1;
- }
- }
- break;
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE):
- for (s = 0; s < samplesperpixel; s++)
- for (row = 0; row < imagelength; row++) {
- if (TIFFReadScanline(tif1, buf1, row, s) < 0)
- checkEOF(tif1, row, s)
- if (TIFFReadScanline(tif2, buf2, row, s) < 0)
- checkEOF(tif2, row, s)
- if (ContigCompare(s, row, buf1, buf2, size1) < 0)
- goto bad1;
- }
- break;
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG):
- for (row = 0; row < imagelength; row++) {
- if (TIFFReadScanline(tif1, buf1, row, 0) < 0)
- checkEOF(tif1, row, -1)
- if (TIFFReadScanline(tif2, buf2, row, 0) < 0)
- checkEOF(tif2, row, -1)
- if (ContigCompare(-1, row, buf1, buf2, size1) < 0)
- goto bad1;
- }
- break;
- }
- if (buf1) _TIFFfree(buf1);
- if (buf2) _TIFFfree(buf2);
- return (1);
+ uint16_t config1, config2;
+ tsize_t size1;
+ uint32_t row;
+ tsample_t s;
+ unsigned char *buf1, *buf2;
+
+ if (!CheckShortTag(tif1, tif2, TIFFTAG_BITSPERSAMPLE, "BitsPerSample"))
+ return (0);
+ if (!CheckShortTag(tif1, tif2, TIFFTAG_SAMPLESPERPIXEL, "SamplesPerPixel"))
+ return (0);
+ if (!CheckLongTag(tif1, tif2, TIFFTAG_IMAGEWIDTH, "ImageWidth"))
+ return (0);
+ if (!cmptags(tif1, tif2))
+ return (1);
+ (void)TIFFGetField(tif1, TIFFTAG_BITSPERSAMPLE, &bitspersample);
+ (void)TIFFGetField(tif1, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
+ (void)TIFFGetField(tif1, TIFFTAG_SAMPLEFORMAT, &sampleformat);
+ (void)TIFFGetField(tif1, TIFFTAG_IMAGEWIDTH, &imagewidth);
+ (void)TIFFGetField(tif1, TIFFTAG_IMAGELENGTH, &imagelength);
+ (void)TIFFGetField(tif1, TIFFTAG_PLANARCONFIG, &config1);
+ (void)TIFFGetField(tif2, TIFFTAG_PLANARCONFIG, &config2);
+ buf1 = (unsigned char *)_TIFFmalloc(size1 = TIFFScanlineSize(tif1));
+ buf2 = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif2));
+ if (buf1 == NULL || buf2 == NULL)
+ {
+ fprintf(stderr, "No space for scanline buffers\n");
+ exit(2);
+ }
+ if (config1 != config2 && bitspersample != 8 && samplesperpixel > 1)
+ {
+ fprintf(stderr, "Can't handle different planar configuration w/ "
+ "different bits/sample\n");
+ goto bad;
+ }
+#define pack(a, b) ((a) << 8) | (b)
+ switch (pack(config1, config2))
+ {
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG):
+ for (row = 0; row < imagelength; row++)
+ {
+ if (TIFFReadScanline(tif2, buf2, row, 0) < 0)
+ checkEOF(tif2, row, -1) for (s = 0; s < samplesperpixel;
+ s++)
+ {
+ if (TIFFReadScanline(tif1, buf1, row, s) < 0)
+ checkEOF(tif1, row, s) if (SeparateCompare(
+ 1, s, row, buf2,
+ buf1) < 0) goto bad1;
+ }
+ }
+ break;
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE):
+ for (row = 0; row < imagelength; row++)
+ {
+ if (TIFFReadScanline(tif1, buf1, row, 0) < 0)
+ checkEOF(tif1, row, -1) for (s = 0; s < samplesperpixel;
+ s++)
+ {
+ if (TIFFReadScanline(tif2, buf2, row, s) < 0)
+ checkEOF(tif2, row, s) if (SeparateCompare(
+ 0, s, row, buf1,
+ buf2) < 0) goto bad1;
+ }
+ }
+ break;
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE):
+ for (s = 0; s < samplesperpixel; s++)
+ for (row = 0; row < imagelength; row++)
+ {
+ if (TIFFReadScanline(tif1, buf1, row, s) < 0)
+ checkEOF(tif1, row, s) if (TIFFReadScanline(tif2, buf2,
+ row, s) < 0)
+ checkEOF(tif2, row,
+ s) if (ContigCompare(s, row, buf1, buf2,
+ size1) < 0) goto bad1;
+ }
+ break;
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG):
+ for (row = 0; row < imagelength; row++)
+ {
+ if (TIFFReadScanline(tif1, buf1, row, 0) < 0)
+ checkEOF(tif1, row,
+ -1) if (TIFFReadScanline(tif2, buf2, row, 0) < 0)
+ checkEOF(tif2, row,
+ -1) if (ContigCompare(-1, row, buf1, buf2,
+ size1) < 0) goto bad1;
+ }
+ break;
+ }
+ if (buf1)
+ _TIFFfree(buf1);
+ if (buf2)
+ _TIFFfree(buf2);
+ return (1);
bad:
- if (stopondiff)
- exit(1);
+ if (stopondiff)
+ exit(1);
bad1:
- if (buf1) _TIFFfree(buf1);
- if (buf2) _TIFFfree(buf2);
- return (0);
+ if (buf1)
+ _TIFFfree(buf1);
+ if (buf2)
+ _TIFFfree(buf2);
+ return (0);
}
-#define CmpShortField(tag, name) \
- if (!CheckShortTag(tif1, tif2, tag, name) && stoponfirsttag) return (0)
-#define CmpShortField2(tag, name) \
- if (!CheckShort2Tag(tif1, tif2, tag, name) && stoponfirsttag) return (0)
-#define CmpLongField(tag, name) \
- if (!CheckLongTag(tif1, tif2, tag, name) && stoponfirsttag) return (0)
-#define CmpFloatField(tag, name) \
- if (!CheckFloatTag(tif1, tif2, tag, name) && stoponfirsttag) return (0)
-#define CmpStringField(tag, name) \
- if (!CheckStringTag(tif1, tif2, tag, name) && stoponfirsttag) return (0)
-#define CmpShortArrayField(tag, name) \
- if (!CheckShortArrayTag(tif1, tif2, tag, name) && stoponfirsttag) return (0)
-
-static int
-cmptags(TIFF* tif1, TIFF* tif2)
+#define CmpShortField(tag, name) \
+ if (!CheckShortTag(tif1, tif2, tag, name) && stoponfirsttag) \
+ return (0)
+#define CmpShortField2(tag, name) \
+ if (!CheckShort2Tag(tif1, tif2, tag, name) && stoponfirsttag) \
+ return (0)
+#define CmpLongField(tag, name) \
+ if (!CheckLongTag(tif1, tif2, tag, name) && stoponfirsttag) \
+ return (0)
+#define CmpFloatField(tag, name) \
+ if (!CheckFloatTag(tif1, tif2, tag, name) && stoponfirsttag) \
+ return (0)
+#define CmpStringField(tag, name) \
+ if (!CheckStringTag(tif1, tif2, tag, name) && stoponfirsttag) \
+ return (0)
+#define CmpShortArrayField(tag, name) \
+ if (!CheckShortArrayTag(tif1, tif2, tag, name) && stoponfirsttag) \
+ return (0)
+
+static int cmptags(TIFF *tif1, TIFF *tif2)
{
- uint16_t compression1, compression2;
- CmpLongField(TIFFTAG_SUBFILETYPE, "SubFileType");
- CmpLongField(TIFFTAG_IMAGEWIDTH, "ImageWidth");
- CmpLongField(TIFFTAG_IMAGELENGTH, "ImageLength");
- CmpShortField(TIFFTAG_BITSPERSAMPLE, "BitsPerSample");
- CmpShortField(TIFFTAG_COMPRESSION, "Compression");
- CmpShortField(TIFFTAG_PREDICTOR, "Predictor");
- CmpShortField(TIFFTAG_PHOTOMETRIC, "PhotometricInterpretation");
- CmpShortField(TIFFTAG_THRESHHOLDING, "Thresholding");
- CmpShortField(TIFFTAG_FILLORDER, "FillOrder");
- CmpShortField(TIFFTAG_ORIENTATION, "Orientation");
- CmpShortField(TIFFTAG_SAMPLESPERPIXEL, "SamplesPerPixel");
- CmpShortField(TIFFTAG_MINSAMPLEVALUE, "MinSampleValue");
- CmpShortField(TIFFTAG_MAXSAMPLEVALUE, "MaxSampleValue");
- CmpShortField(TIFFTAG_SAMPLEFORMAT, "SampleFormat");
- CmpFloatField(TIFFTAG_XRESOLUTION, "XResolution");
- CmpFloatField(TIFFTAG_YRESOLUTION, "YResolution");
- if( TIFFGetField(tif1, TIFFTAG_COMPRESSION, &compression1) &&
- compression1 == COMPRESSION_CCITTFAX3 &&
- TIFFGetField(tif2, TIFFTAG_COMPRESSION, &compression2) &&
- compression2 == COMPRESSION_CCITTFAX3 )
- {
- CmpLongField(TIFFTAG_GROUP3OPTIONS, "Group3Options");
- }
- if( TIFFGetField(tif1, TIFFTAG_COMPRESSION, &compression1) &&
- compression1 == COMPRESSION_CCITTFAX4 &&
- TIFFGetField(tif2, TIFFTAG_COMPRESSION, &compression2) &&
- compression2 == COMPRESSION_CCITTFAX4 )
- {
- CmpLongField(TIFFTAG_GROUP4OPTIONS, "Group4Options");
- }
- CmpShortField(TIFFTAG_RESOLUTIONUNIT, "ResolutionUnit");
- CmpShortField(TIFFTAG_PLANARCONFIG, "PlanarConfiguration");
- CmpLongField(TIFFTAG_ROWSPERSTRIP, "RowsPerStrip");
- CmpFloatField(TIFFTAG_XPOSITION, "XPosition");
- CmpFloatField(TIFFTAG_YPOSITION, "YPosition");
- CmpShortField(TIFFTAG_GRAYRESPONSEUNIT, "GrayResponseUnit");
- CmpShortField(TIFFTAG_COLORRESPONSEUNIT, "ColorResponseUnit");
+ uint16_t compression1, compression2;
+ CmpLongField(TIFFTAG_SUBFILETYPE, "SubFileType");
+ CmpLongField(TIFFTAG_IMAGEWIDTH, "ImageWidth");
+ CmpLongField(TIFFTAG_IMAGELENGTH, "ImageLength");
+ CmpShortField(TIFFTAG_BITSPERSAMPLE, "BitsPerSample");
+ CmpShortField(TIFFTAG_COMPRESSION, "Compression");
+ CmpShortField(TIFFTAG_PREDICTOR, "Predictor");
+ CmpShortField(TIFFTAG_PHOTOMETRIC, "PhotometricInterpretation");
+ CmpShortField(TIFFTAG_THRESHHOLDING, "Thresholding");
+ CmpShortField(TIFFTAG_FILLORDER, "FillOrder");
+ CmpShortField(TIFFTAG_ORIENTATION, "Orientation");
+ CmpShortField(TIFFTAG_SAMPLESPERPIXEL, "SamplesPerPixel");
+ CmpShortField(TIFFTAG_MINSAMPLEVALUE, "MinSampleValue");
+ CmpShortField(TIFFTAG_MAXSAMPLEVALUE, "MaxSampleValue");
+ CmpShortField(TIFFTAG_SAMPLEFORMAT, "SampleFormat");
+ CmpFloatField(TIFFTAG_XRESOLUTION, "XResolution");
+ CmpFloatField(TIFFTAG_YRESOLUTION, "YResolution");
+ if (TIFFGetField(tif1, TIFFTAG_COMPRESSION, &compression1) &&
+ compression1 == COMPRESSION_CCITTFAX3 &&
+ TIFFGetField(tif2, TIFFTAG_COMPRESSION, &compression2) &&
+ compression2 == COMPRESSION_CCITTFAX3)
+ {
+ CmpLongField(TIFFTAG_GROUP3OPTIONS, "Group3Options");
+ }
+ if (TIFFGetField(tif1, TIFFTAG_COMPRESSION, &compression1) &&
+ compression1 == COMPRESSION_CCITTFAX4 &&
+ TIFFGetField(tif2, TIFFTAG_COMPRESSION, &compression2) &&
+ compression2 == COMPRESSION_CCITTFAX4)
+ {
+ CmpLongField(TIFFTAG_GROUP4OPTIONS, "Group4Options");
+ }
+ CmpShortField(TIFFTAG_RESOLUTIONUNIT, "ResolutionUnit");
+ CmpShortField(TIFFTAG_PLANARCONFIG, "PlanarConfiguration");
+ CmpLongField(TIFFTAG_ROWSPERSTRIP, "RowsPerStrip");
+ CmpFloatField(TIFFTAG_XPOSITION, "XPosition");
+ CmpFloatField(TIFFTAG_YPOSITION, "YPosition");
+ CmpShortField(TIFFTAG_GRAYRESPONSEUNIT, "GrayResponseUnit");
+ CmpShortField(TIFFTAG_COLORRESPONSEUNIT, "ColorResponseUnit");
#ifdef notdef
- { uint16_t *graycurve;
- CmpField(TIFFTAG_GRAYRESPONSECURVE, graycurve);
- }
- { uint16_t *red, *green, *blue;
- CmpField3(TIFFTAG_COLORRESPONSECURVE, red, green, blue);
- }
- { uint16_t *red, *green, *blue;
- CmpField3(TIFFTAG_COLORMAP, red, green, blue);
- }
+ {
+ uint16_t *graycurve;
+ CmpField(TIFFTAG_GRAYRESPONSECURVE, graycurve);
+ }
+ {
+ uint16_t *red, *green, *blue;
+ CmpField3(TIFFTAG_COLORRESPONSECURVE, red, green, blue);
+ }
+ {
+ uint16_t *red, *green, *blue;
+ CmpField3(TIFFTAG_COLORMAP, red, green, blue);
+ }
#endif
- CmpShortField2(TIFFTAG_PAGENUMBER, "PageNumber");
- CmpStringField(TIFFTAG_ARTIST, "Artist");
- CmpStringField(TIFFTAG_IMAGEDESCRIPTION,"ImageDescription");
- CmpStringField(TIFFTAG_MAKE, "Make");
- CmpStringField(TIFFTAG_MODEL, "Model");
- CmpStringField(TIFFTAG_SOFTWARE, "Software");
- CmpStringField(TIFFTAG_DATETIME, "DateTime");
- CmpStringField(TIFFTAG_HOSTCOMPUTER, "HostComputer");
- CmpStringField(TIFFTAG_PAGENAME, "PageName");
- CmpStringField(TIFFTAG_DOCUMENTNAME, "DocumentName");
- CmpShortField(TIFFTAG_MATTEING, "Matteing");
- CmpShortArrayField(TIFFTAG_EXTRASAMPLES,"ExtraSamples");
- return (1);
+ CmpShortField2(TIFFTAG_PAGENUMBER, "PageNumber");
+ CmpStringField(TIFFTAG_ARTIST, "Artist");
+ CmpStringField(TIFFTAG_IMAGEDESCRIPTION, "ImageDescription");
+ CmpStringField(TIFFTAG_MAKE, "Make");
+ CmpStringField(TIFFTAG_MODEL, "Model");
+ CmpStringField(TIFFTAG_SOFTWARE, "Software");
+ CmpStringField(TIFFTAG_DATETIME, "DateTime");
+ CmpStringField(TIFFTAG_HOSTCOMPUTER, "HostComputer");
+ CmpStringField(TIFFTAG_PAGENAME, "PageName");
+ CmpStringField(TIFFTAG_DOCUMENTNAME, "DocumentName");
+ CmpShortField(TIFFTAG_MATTEING, "Matteing");
+ CmpShortArrayField(TIFFTAG_EXTRASAMPLES, "ExtraSamples");
+ return (1);
}
-static int
-ContigCompare(int sample, uint32_t row,
- unsigned char* p1, unsigned char* p2, tsize_t size)
+static int ContigCompare(int sample, uint32_t row, unsigned char *p1,
+ unsigned char *p2, tsize_t size)
{
uint32_t pix;
- int samples_to_test;
+ int samples_to_test;
if (memcmp(p1, p2, size) == 0)
return 0;
samples_to_test = (sample == -1) ? samplesperpixel : 1;
- switch (bitspersample) {
- case 1: case 2: case 4: case 8:
- {
- unsigned char *pix1 = p1, *pix2 = p2;
- unsigned bits = 0;
-
- for (pix = 0; pix < imagewidth; pix++) {
- int s;
-
- for(s = 0; s < samples_to_test; s++) {
- if (*pix1 != *pix2) {
- if( sample == -1 )
- PrintIntDiff(row, s, pix, *pix1, *pix2);
- else
- PrintIntDiff(row, sample, pix, *pix1, *pix2);
- }
-
- bits += bitspersample;
- pix1 += (bits / 8);
- pix2 += (bits / 8);
- bits &= 7;
- }
- }
- break;
- }
- case 16:
- {
- uint16_t *pix1 = (uint16_t *)p1, *pix2 = (uint16_t *)p2;
-
- for (pix = 0; pix < imagewidth; pix++) {
- int s;
-
- for(s = 0; s < samples_to_test; s++) {
- if (*pix1 != *pix2)
- PrintIntDiff(row, sample, pix, *pix1, *pix2);
-
- pix1++;
- pix2++;
- }
- }
- break;
- }
- case 32:
- if (sampleformat == SAMPLEFORMAT_UINT
- || sampleformat == SAMPLEFORMAT_INT) {
- uint32_t *pix1 = (uint32_t *)p1, *pix2 = (uint32_t *)p2;
-
- for (pix = 0; pix < imagewidth; pix++) {
- int s;
-
- for(s = 0; s < samples_to_test; s++) {
- if (*pix1 != *pix2) {
- PrintIntDiff(row, sample, pix,
- *pix1, *pix2);
- }
-
- pix1++;
- pix2++;
- }
- }
- } else if (sampleformat == SAMPLEFORMAT_IEEEFP) {
- float *pix1 = (float *)p1, *pix2 = (float *)p2;
-
- for (pix = 0; pix < imagewidth; pix++) {
- int s;
-
- for(s = 0; s < samples_to_test; s++) {
- if (fabs(*pix1 - *pix2) < 0.000000000001) {
- PrintFloatDiff(row, sample, pix,
- *pix1, *pix2);
- }
-
- pix1++;
- pix2++;
- }
- }
- } else {
- fprintf(stderr, "Sample format %"PRIu16" is not supported.\n",
- sampleformat);
- return -1;
- }
- break;
- default:
- fprintf(stderr, "Bit depth %"PRIu16" is not supported.\n", bitspersample);
- return -1;
+ switch (bitspersample)
+ {
+ case 1:
+ case 2:
+ case 4:
+ case 8:
+ {
+ unsigned char *pix1 = p1, *pix2 = p2;
+ unsigned bits = 0;
+
+ for (pix = 0; pix < imagewidth; pix++)
+ {
+ int s;
+
+ for (s = 0; s < samples_to_test; s++)
+ {
+ if (*pix1 != *pix2)
+ {
+ if (sample == -1)
+ PrintIntDiff(row, s, pix, *pix1, *pix2);
+ else
+ PrintIntDiff(row, sample, pix, *pix1, *pix2);
+ }
+
+ bits += bitspersample;
+ pix1 += (bits / 8);
+ pix2 += (bits / 8);
+ bits &= 7;
+ }
+ }
+ break;
+ }
+ case 16:
+ {
+ uint16_t *pix1 = (uint16_t *)p1, *pix2 = (uint16_t *)p2;
+
+ for (pix = 0; pix < imagewidth; pix++)
+ {
+ int s;
+
+ for (s = 0; s < samples_to_test; s++)
+ {
+ if (*pix1 != *pix2)
+ PrintIntDiff(row, sample, pix, *pix1, *pix2);
+
+ pix1++;
+ pix2++;
+ }
+ }
+ break;
+ }
+ case 32:
+ if (sampleformat == SAMPLEFORMAT_UINT ||
+ sampleformat == SAMPLEFORMAT_INT)
+ {
+ uint32_t *pix1 = (uint32_t *)p1, *pix2 = (uint32_t *)p2;
+
+ for (pix = 0; pix < imagewidth; pix++)
+ {
+ int s;
+
+ for (s = 0; s < samples_to_test; s++)
+ {
+ if (*pix1 != *pix2)
+ {
+ PrintIntDiff(row, sample, pix, *pix1, *pix2);
+ }
+
+ pix1++;
+ pix2++;
+ }
+ }
+ }
+ else if (sampleformat == SAMPLEFORMAT_IEEEFP)
+ {
+ float *pix1 = (float *)p1, *pix2 = (float *)p2;
+
+ for (pix = 0; pix < imagewidth; pix++)
+ {
+ int s;
+
+ for (s = 0; s < samples_to_test; s++)
+ {
+ if (fabs(*pix1 - *pix2) < 0.000000000001)
+ {
+ PrintFloatDiff(row, sample, pix, *pix1, *pix2);
+ }
+
+ pix1++;
+ pix2++;
+ }
+ }
+ }
+ else
+ {
+ fprintf(stderr, "Sample format %" PRIu16 " is not supported.\n",
+ sampleformat);
+ return -1;
+ }
+ break;
+ default:
+ fprintf(stderr, "Bit depth %" PRIu16 " is not supported.\n",
+ bitspersample);
+ return -1;
}
return 0;
}
-static void
-PrintIntDiff(uint32_t row, int sample, uint32_t pix, uint32_t w1, uint32_t w2)
+static void PrintIntDiff(uint32_t row, int sample, uint32_t pix, uint32_t w1,
+ uint32_t w2)
{
- if (sample < 0)
- sample = 0;
- switch (bitspersample) {
- case 1:
- case 2:
- case 4:
- {
- int32_t mask1, mask2, s;
-
- /* mask1 should have the n lowest bits set, where n == bitspersample */
- mask1 = ((int32_t)1 << bitspersample) - 1;
- s = (8 - bitspersample);
- mask2 = mask1 << s;
- for (; mask2 && pix < imagewidth;
- mask2 >>= bitspersample, s -= bitspersample, pix++) {
- if ((w1 & mask2) ^ (w2 & mask2)) {
- printf(
- "Scanline %"PRIu32", pixel %"PRIu32", sample %d: %01"PRIx32" %01"PRIx32"\n",
- row,
- pix,
- sample,
- (w1 >> s) & mask1,
- (w2 >> s) & mask1);
- if (--stopondiff == 0)
- exit(1);
- }
- }
- break;
- }
- case 8:
- printf("Scanline %"PRIu32", pixel %"PRIu32", sample %d: %02"PRIx32" %02"PRIx32"\n",
- row, pix, sample,
- w1, w2);
- if (--stopondiff == 0)
- exit(1);
- break;
- case 16:
- printf("Scanline %"PRIu32", pixel %"PRIu32", sample %d: %04"PRIx32" %04"PRIx32"\n",
- row, pix, sample,
- w1, w2);
- if (--stopondiff == 0)
- exit(1);
- break;
- case 32:
- printf("Scanline %"PRIu32", pixel %"PRIu32", sample %d: %08"PRIx32" %08"PRIx32"\n",
- row, pix, sample,
- w1, w2);
- if (--stopondiff == 0)
- exit(1);
- break;
- default:
- break;
- }
+ if (sample < 0)
+ sample = 0;
+ switch (bitspersample)
+ {
+ case 1:
+ case 2:
+ case 4:
+ {
+ int32_t mask1, mask2, s;
+
+ /* mask1 should have the n lowest bits set, where n == bitspersample
+ */
+ mask1 = ((int32_t)1 << bitspersample) - 1;
+ s = (8 - bitspersample);
+ mask2 = mask1 << s;
+ for (; mask2 && pix < imagewidth;
+ mask2 >>= bitspersample, s -= bitspersample, pix++)
+ {
+ if ((w1 & mask2) ^ (w2 & mask2))
+ {
+ printf("Scanline %" PRIu32 ", pixel %" PRIu32
+ ", sample %d: %01" PRIx32 " %01" PRIx32 "\n",
+ row, pix, sample, (w1 >> s) & mask1,
+ (w2 >> s) & mask1);
+ if (--stopondiff == 0)
+ exit(1);
+ }
+ }
+ break;
+ }
+ case 8:
+ printf("Scanline %" PRIu32 ", pixel %" PRIu32
+ ", sample %d: %02" PRIx32 " %02" PRIx32 "\n",
+ row, pix, sample, w1, w2);
+ if (--stopondiff == 0)
+ exit(1);
+ break;
+ case 16:
+ printf("Scanline %" PRIu32 ", pixel %" PRIu32
+ ", sample %d: %04" PRIx32 " %04" PRIx32 "\n",
+ row, pix, sample, w1, w2);
+ if (--stopondiff == 0)
+ exit(1);
+ break;
+ case 32:
+ printf("Scanline %" PRIu32 ", pixel %" PRIu32
+ ", sample %d: %08" PRIx32 " %08" PRIx32 "\n",
+ row, pix, sample, w1, w2);
+ if (--stopondiff == 0)
+ exit(1);
+ break;
+ default:
+ break;
+ }
}
-static void
-PrintFloatDiff(uint32_t row, int sample, uint32_t pix, double w1, double w2)
+static void PrintFloatDiff(uint32_t row, int sample, uint32_t pix, double w1,
+ double w2)
{
- if (sample < 0)
- sample = 0;
- switch (bitspersample) {
- case 32:
- printf("Scanline %"PRIu32", pixel %"PRIu32", sample %d: %g %g\n",
- row, pix, sample, w1, w2);
- if (--stopondiff == 0)
- exit(1);
- break;
- default:
- break;
- }
+ if (sample < 0)
+ sample = 0;
+ switch (bitspersample)
+ {
+ case 32:
+ printf("Scanline %" PRIu32 ", pixel %" PRIu32
+ ", sample %d: %g %g\n",
+ row, pix, sample, w1, w2);
+ if (--stopondiff == 0)
+ exit(1);
+ break;
+ default:
+ break;
+ }
}
-static int
-SeparateCompare(int reversed, int sample, uint32_t row,
- unsigned char* cp1, unsigned char* p2)
+static int SeparateCompare(int reversed, int sample, uint32_t row,
+ unsigned char *cp1, unsigned char *p2)
{
- uint32_t npixels = imagewidth;
- int pixel;
-
- cp1 += sample;
- for (pixel = 0; npixels-- > 0; pixel++, cp1 += samplesperpixel, p2++) {
- if (*cp1 != *p2) {
- printf("Scanline %"PRIu32", pixel %"PRIu32", sample %d: ",
- row, pixel, sample);
- if (reversed)
- printf("%02x %02x\n", *p2, *cp1);
- else
- printf("%02x %02x\n", *cp1, *p2);
- if (--stopondiff == 0)
- exit(1);
- }
- }
-
- return 0;
+ uint32_t npixels = imagewidth;
+ int pixel;
+
+ cp1 += sample;
+ for (pixel = 0; npixels-- > 0; pixel++, cp1 += samplesperpixel, p2++)
+ {
+ if (*cp1 != *p2)
+ {
+ printf("Scanline %" PRIu32 ", pixel %" PRIu32 ", sample %d: ", row,
+ pixel, sample);
+ if (reversed)
+ printf("%02x %02x\n", *p2, *cp1);
+ else
+ printf("%02x %02x\n", *cp1, *p2);
+ if (--stopondiff == 0)
+ exit(1);
+ }
+ }
+
+ return 0;
}
-static int
-checkTag(TIFF* tif1, TIFF* tif2, int tag, char* name, void* p1, void* p2)
+static int checkTag(TIFF *tif1, TIFF *tif2, int tag, char *name, void *p1,
+ void *p2)
{
- if (TIFFGetField(tif1, tag, p1)) {
- if (!TIFFGetField(tif2, tag, p2)) {
- printf("%s tag appears only in %s\n",
- name, TIFFFileName(tif1));
- return (0);
- }
- return (1);
- } else if (TIFFGetField(tif2, tag, p2)) {
- printf("%s tag appears only in %s\n", name, TIFFFileName(tif2));
- return (0);
- }
- return (-1);
+ if (TIFFGetField(tif1, tag, p1))
+ {
+ if (!TIFFGetField(tif2, tag, p2))
+ {
+ printf("%s tag appears only in %s\n", name, TIFFFileName(tif1));
+ return (0);
+ }
+ return (1);
+ }
+ else if (TIFFGetField(tif2, tag, p2))
+ {
+ printf("%s tag appears only in %s\n", name, TIFFFileName(tif2));
+ return (0);
+ }
+ return (-1);
}
-#define CHECK(cmp, fmt) { \
- switch (checkTag(tif1,tif2,tag,name,&v1,&v2)) { \
- case 1: if (cmp) \
- case -1: return (1); \
- printf(fmt, name, v1, v2); \
- } \
- return (0); \
-}
+#define CHECK(cmp, fmt) \
+ { \
+ switch (checkTag(tif1, tif2, tag, name, &v1, &v2)) \
+ { \
+ case 1: \
+ if (cmp) \
+ case -1: \
+ return (1); \
+ printf(fmt, name, v1, v2); \
+ } \
+ return (0); \
+ }
-static int
-CheckShortTag(TIFF* tif1, TIFF* tif2, int tag, char* name)
+static int CheckShortTag(TIFF *tif1, TIFF *tif2, int tag, char *name)
{
- uint16_t v1, v2;
- CHECK(v1 == v2, "%s: %"PRIu16" %"PRIu16"\n");
+ uint16_t v1, v2;
+ CHECK(v1 == v2, "%s: %" PRIu16 " %" PRIu16 "\n");
}
-static int
-CheckShort2Tag(TIFF* tif1, TIFF* tif2, int tag, char* name)
+static int CheckShort2Tag(TIFF *tif1, TIFF *tif2, int tag, char *name)
{
- uint16_t v11, v12, v21, v22;
-
- if (TIFFGetField(tif1, tag, &v11, &v12)) {
- if (!TIFFGetField(tif2, tag, &v21, &v22)) {
- printf("%s tag appears only in %s\n",
- name, TIFFFileName(tif1));
- return (0);
- }
- if (v11 == v21 && v12 == v22)
- return (1);
- printf("%s: <%"PRIu16",%"PRIu16"> <%"PRIu16",%"PRIu16">\n", name, v11, v12, v21, v22);
- } else if (TIFFGetField(tif2, tag, &v21, &v22))
- printf("%s tag appears only in %s\n", name, TIFFFileName(tif2));
- else
- return (1);
- return (0);
+ uint16_t v11, v12, v21, v22;
+
+ if (TIFFGetField(tif1, tag, &v11, &v12))
+ {
+ if (!TIFFGetField(tif2, tag, &v21, &v22))
+ {
+ printf("%s tag appears only in %s\n", name, TIFFFileName(tif1));
+ return (0);
+ }
+ if (v11 == v21 && v12 == v22)
+ return (1);
+ printf("%s: <%" PRIu16 ",%" PRIu16 "> <%" PRIu16 ",%" PRIu16 ">\n",
+ name, v11, v12, v21, v22);
+ }
+ else if (TIFFGetField(tif2, tag, &v21, &v22))
+ printf("%s tag appears only in %s\n", name, TIFFFileName(tif2));
+ else
+ return (1);
+ return (0);
}
-static int
-CheckShortArrayTag(TIFF* tif1, TIFF* tif2, int tag, char* name)
+static int CheckShortArrayTag(TIFF *tif1, TIFF *tif2, int tag, char *name)
{
- uint16_t n1, *a1;
- uint16_t n2, *a2;
-
- if (TIFFGetField(tif1, tag, &n1, &a1)) {
- if (!TIFFGetField(tif2, tag, &n2, &a2)) {
- printf("%s tag appears only in %s\n",
- name, TIFFFileName(tif1));
- return (0);
- }
- if (n1 == n2) {
- char* sep;
- uint16_t i;
-
- if (memcmp(a1, a2, n1 * sizeof(uint16_t)) == 0)
- return (1);
- printf("%s: value mismatch, <%"PRIu16":", name, n1);
- sep = "";
- for (i = 0; i < n1; i++)
- printf("%s%"PRIu16, sep, a1[i]), sep = ",";
- printf("> and <%"PRIu16": ", n2);
- sep = "";
- for (i = 0; i < n2; i++)
- printf("%s%"PRIu16, sep, a2[i]), sep = ",";
- printf(">\n");
- } else
- printf("%s: %"PRIu16" items in %s, %"PRIu16" items in %s", name,
- n1, TIFFFileName(tif1),
- n2, TIFFFileName(tif2)
- );
- } else if (TIFFGetField(tif2, tag, &n2, &a2))
- printf("%s tag appears only in %s\n", name, TIFFFileName(tif2));
- else
- return (1);
- return (0);
+ uint16_t n1, *a1;
+ uint16_t n2, *a2;
+
+ if (TIFFGetField(tif1, tag, &n1, &a1))
+ {
+ if (!TIFFGetField(tif2, tag, &n2, &a2))
+ {
+ printf("%s tag appears only in %s\n", name, TIFFFileName(tif1));
+ return (0);
+ }
+ if (n1 == n2)
+ {
+ char *sep;
+ uint16_t i;
+
+ if (memcmp(a1, a2, n1 * sizeof(uint16_t)) == 0)
+ return (1);
+ printf("%s: value mismatch, <%" PRIu16 ":", name, n1);
+ sep = "";
+ for (i = 0; i < n1; i++)
+ printf("%s%" PRIu16, sep, a1[i]), sep = ",";
+ printf("> and <%" PRIu16 ": ", n2);
+ sep = "";
+ for (i = 0; i < n2; i++)
+ printf("%s%" PRIu16, sep, a2[i]), sep = ",";
+ printf(">\n");
+ }
+ else
+ printf("%s: %" PRIu16 " items in %s, %" PRIu16 " items in %s", name,
+ n1, TIFFFileName(tif1), n2, TIFFFileName(tif2));
+ }
+ else if (TIFFGetField(tif2, tag, &n2, &a2))
+ printf("%s tag appears only in %s\n", name, TIFFFileName(tif2));
+ else
+ return (1);
+ return (0);
}
-static int
-CheckLongTag(TIFF* tif1, TIFF* tif2, int tag, char* name)
+static int CheckLongTag(TIFF *tif1, TIFF *tif2, int tag, char *name)
{
- uint32_t v1, v2;
- CHECK(v1 == v2, "%s: %"PRIu32" %"PRIu32"\n");
+ uint32_t v1, v2;
+ CHECK(v1 == v2, "%s: %" PRIu32 " %" PRIu32 "\n");
}
-static int
-CheckFloatTag(TIFF* tif1, TIFF* tif2, int tag, char* name)
+static int CheckFloatTag(TIFF *tif1, TIFF *tif2, int tag, char *name)
{
- float v1, v2;
- CHECK(v1 == v2, "%s: %g %g\n");
+ float v1, v2;
+ CHECK(v1 == v2, "%s: %g %g\n");
}
-static int
-CheckStringTag(TIFF* tif1, TIFF* tif2, int tag, char* name)
+static int CheckStringTag(TIFF *tif1, TIFF *tif2, int tag, char *name)
{
- char *v1, *v2;
- CHECK(strcmp(v1, v2) == 0, "%s: \"%s\" \"%s\"\n");
+ char *v1, *v2;
+ CHECK(strcmp(v1, v2) == 0, "%s: \"%s\" \"%s\"\n");
}
-static void
-leof(const char* name, uint32_t row, int s)
+static void leof(const char *name, uint32_t row, int s)
{
- printf("%s: EOF at scanline %"PRIu32, name, row);
- if (s >= 0)
- printf(", sample %d", s);
- printf("\n");
+ printf("%s: EOF at scanline %" PRIu32, name, row);
+ if (s >= 0)
+ printf(", sample %d", s);
+ printf("\n");
}
diff --git a/tools/tiffcp.c b/tools/tiffcp.c
index fd99d63d..3b2d1dda 100644
--- a/tools/tiffcp.c
+++ b/tools/tiffcp.c
@@ -16,38 +16,38 @@
* Copies the 2nd image in source.tif to the destination.
*
*****
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
+#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <limits.h>
#include <ctype.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#include "tiffio.h"
@@ -59,11 +59,11 @@
#define EXIT_FAILURE 1
#endif
-#define streq(a,b) (strcmp(a,b) == 0)
-#define strneq(a,b,n) (strncmp(a,b,n) == 0)
+#define streq(a, b) (strcmp(a, b) == 0)
+#define strneq(a, b, n) (strncmp(a, b, n) == 0)
-#define TRUE 1
-#define FALSE 0
+#define TRUE 1
+#define FALSE 0
#define DEFAULT_MAX_MALLOC (256 * 1024 * 1024)
@@ -84,991 +84,1126 @@ static uint16_t fillorder;
static uint16_t orientation;
static uint32_t rowsperstrip;
static uint32_t g3opts;
-static int ignore = FALSE; /* if true, ignore read errors */
-static uint32_t defg3opts = (uint32_t) -1;
-static int quality = 75; /* JPEG quality */
+static int ignore = FALSE; /* if true, ignore read errors */
+static uint32_t defg3opts = (uint32_t)-1;
+static int quality = 75; /* JPEG quality */
static int jpegcolormode = JPEGCOLORMODE_RGB;
-static uint16_t defcompression = (uint16_t) -1;
-static uint16_t defpredictor = (uint16_t) -1;
-static int defpreset = -1;
+static uint16_t defcompression = (uint16_t)-1;
+static uint16_t defpredictor = (uint16_t)-1;
+static int defpreset = -1;
static int subcodec = -1;
-static int tiffcp(TIFF*, TIFF*);
-static int processCompressOptions(char*);
+static int tiffcp(TIFF *, TIFF *);
+static int processCompressOptions(char *);
static void usage(int code);
-static char comma = ','; /* (default) comma separator character */
-static TIFF* bias = NULL;
+static char comma = ','; /* (default) comma separator character */
+static TIFF *bias = NULL;
static int pageNum = 0;
static int pageInSeq = 0;
/**
* This custom malloc function enforce a maximum allocation size
*/
-static void* limitMalloc(tmsize_t s)
+static void *limitMalloc(tmsize_t s)
{
- if (maxMalloc && (s > maxMalloc)) {
- fprintf(stderr, "MemoryLimitError: allocation of %" TIFF_SSIZE_FORMAT " bytes is forbidden. Limit is %" TIFF_SSIZE_FORMAT ".\n",
+ if (maxMalloc && (s > maxMalloc))
+ {
+ fprintf(stderr,
+ "MemoryLimitError: allocation of %" TIFF_SSIZE_FORMAT
+ " bytes is forbidden. Limit is %" TIFF_SSIZE_FORMAT ".\n",
s, maxMalloc);
- fprintf(stderr, " use -m option to change limit.\n");
- return NULL;
- }
- return _TIFFmalloc(s);
+ fprintf(stderr, " use -m option to change limit.\n");
+ return NULL;
+ }
+ return _TIFFmalloc(s);
}
-static int nextSrcImage (TIFF *tif, char **imageSpec)
+static int nextSrcImage(TIFF *tif, char **imageSpec)
/*
seek to the next image specified in *imageSpec
returns 1 if success, 0 if no more images to process
*imageSpec=NULL if subsequent images should be processed in sequence
*/
{
- if (**imageSpec == comma) { /* if not @comma, we've done all images */
- char *start = *imageSpec + 1;
- tdir_t nextImage = (tdir_t)strtol(start, imageSpec, 0);
- if (start == *imageSpec) nextImage = TIFFCurrentDirectory (tif);
- if (**imageSpec)
- {
- if (**imageSpec == comma) {
- /* a trailing comma denotes remaining images in sequence */
- if ((*imageSpec)[1] == '\0') *imageSpec = NULL;
- }else{
- fprintf (stderr,
- "Expected a %c separated image # list after %s\n",
- comma, TIFFFileName (tif));
- exit (EXIT_FAILURE); /* syntax error */
- }
- }
- if (TIFFSetDirectory (tif, nextImage)) return 1;
- fprintf (stderr, "%s%c%"PRIu16" not found!\n",
- TIFFFileName(tif), comma, nextImage);
- }
- return 0;
+ if (**imageSpec == comma)
+ { /* if not @comma, we've done all images */
+ char *start = *imageSpec + 1;
+ tdir_t nextImage = (tdir_t)strtol(start, imageSpec, 0);
+ if (start == *imageSpec)
+ nextImage = TIFFCurrentDirectory(tif);
+ if (**imageSpec)
+ {
+ if (**imageSpec == comma)
+ {
+ /* a trailing comma denotes remaining images in sequence */
+ if ((*imageSpec)[1] == '\0')
+ *imageSpec = NULL;
+ }
+ else
+ {
+ fprintf(stderr,
+ "Expected a %c separated image # list after %s\n",
+ comma, TIFFFileName(tif));
+ exit(EXIT_FAILURE); /* syntax error */
+ }
+ }
+ if (TIFFSetDirectory(tif, nextImage))
+ return 1;
+ fprintf(stderr, "%s%c%" PRIu16 " not found!\n", TIFFFileName(tif),
+ comma, nextImage);
+ }
+ return 0;
}
-
-static TIFF* openSrcImage (char **imageSpec)
+static TIFF *openSrcImage(char **imageSpec)
/*
imageSpec points to a pointer to a filename followed by optional ,image#'s
Open the TIFF file and assign *imageSpec to either NULL if there are
no images specified, or a pointer to the next image number text
*/
{
- /* disable strip shopping when using jbig compression */
- const char *mode = (defcompression == COMPRESSION_JBIG) ? "rc" : "r";
- TIFF *tif;
- char *fn = *imageSpec;
- *imageSpec = strchr (fn, comma);
- TIFFOpenOptions* opts = TIFFOpenOptionsAlloc();
- if (opts == NULL) {
- return NULL;
- }
+ /* disable strip shopping when using jbig compression */
+ const char *mode = (defcompression == COMPRESSION_JBIG) ? "rc" : "r";
+ TIFF *tif;
+ char *fn = *imageSpec;
+ *imageSpec = strchr(fn, comma);
+ TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
+ if (opts == NULL)
+ {
+ return NULL;
+ }
TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
- if (*imageSpec) { /* there is at least one image number specifier */
- **imageSpec = '\0';
- tif = TIFFOpenExt (fn, mode, opts);
- /* but, ignore any single trailing comma */
- if (!(*imageSpec)[1]) {
- *imageSpec = NULL;
- TIFFOpenOptionsFree(opts);
- return tif;
- }
- if (tif) {
- **imageSpec = comma; /* replace the comma */
- if (!nextSrcImage(tif, imageSpec)) {
- TIFFClose (tif);
- tif = NULL;
- }
- }
- }else
- tif = TIFFOpenExt (fn, mode, opts);
- TIFFOpenOptionsFree(opts);
- return tif;
+ if (*imageSpec)
+ { /* there is at least one image number specifier */
+ **imageSpec = '\0';
+ tif = TIFFOpenExt(fn, mode, opts);
+ /* but, ignore any single trailing comma */
+ if (!(*imageSpec)[1])
+ {
+ *imageSpec = NULL;
+ TIFFOpenOptionsFree(opts);
+ return tif;
+ }
+ if (tif)
+ {
+ **imageSpec = comma; /* replace the comma */
+ if (!nextSrcImage(tif, imageSpec))
+ {
+ TIFFClose(tif);
+ tif = NULL;
+ }
+ }
+ }
+ else
+ tif = TIFFOpenExt(fn, mode, opts);
+ TIFFOpenOptionsFree(opts);
+ return tif;
}
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- uint16_t defconfig = (uint16_t) -1;
- uint16_t deffillorder = 0;
- uint32_t deftilewidth = (uint32_t) -1;
- uint32_t deftilelength = (uint32_t) -1;
- uint32_t defrowsperstrip = (uint32_t) 0;
- uint64_t diroff = 0;
- TIFF* in;
- TIFF* out;
- char mode[10];
- char* mp = mode;
- int c;
+ uint16_t defconfig = (uint16_t)-1;
+ uint16_t deffillorder = 0;
+ uint32_t deftilewidth = (uint32_t)-1;
+ uint32_t deftilelength = (uint32_t)-1;
+ uint32_t defrowsperstrip = (uint32_t)0;
+ uint64_t diroff = 0;
+ TIFF *in;
+ TIFF *out;
+ char mode[10];
+ char *mp = mode;
+ int c;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char* optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- *mp++ = 'w';
- *mp = '\0';
- while ((c = getopt(argc, argv, "m:,:b:c:f:l:o:p:r:w:aistBLMC8xh")) != -1)
- switch (c) {
- case 'm':
- maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
- break;
- case ',':
- if (optarg[0] != '=') usage(EXIT_FAILURE);
- comma = optarg[1];
- break;
- case 'b': /* this file is bias image subtracted from others */
- if (bias) {
- fputs ("Only 1 bias image may be specified\n", stderr);
- exit (EXIT_FAILURE);
- }
- {
- uint16_t samples = (uint16_t) -1;
- char **biasFn = &optarg;
- bias = openSrcImage (biasFn);
- if (!bias) exit (EXIT_FAILURE);
- if (TIFFIsTiled (bias)) {
- fputs ("Bias image must be organized in strips\n", stderr);
- exit (EXIT_FAILURE);
- }
- TIFFGetField(bias, TIFFTAG_SAMPLESPERPIXEL, &samples);
- if (samples != 1) {
- fputs ("Bias image must be monochrome\n", stderr);
- exit (EXIT_FAILURE);
- }
- }
- break;
- case 'a': /* append to output */
- mode[0] = 'a';
- break;
- case 'c': /* compression scheme */
- if (!processCompressOptions(optarg))
- usage(EXIT_FAILURE);
- break;
- case 'f': /* fill order */
- if (streq(optarg, "lsb2msb"))
- deffillorder = FILLORDER_LSB2MSB;
- else if (streq(optarg, "msb2lsb"))
- deffillorder = FILLORDER_MSB2LSB;
- else
- usage(EXIT_FAILURE);
- break;
- case 'i': /* ignore errors */
- ignore = TRUE;
- break;
- case 'l': /* tile length */
- outtiled = TRUE;
- deftilelength = atoi(optarg);
- break;
- case 'o': /* initial directory offset */
- diroff = strtoul(optarg, NULL, 0);
- break;
- case 'p': /* planar configuration */
- if (streq(optarg, "separate"))
- defconfig = PLANARCONFIG_SEPARATE;
- else if (streq(optarg, "contig"))
- defconfig = PLANARCONFIG_CONTIG;
- else
- usage(EXIT_FAILURE);
- break;
- case 'r': /* rows/strip */
- defrowsperstrip = atol(optarg);
- break;
- case 's': /* generate stripped output */
- outtiled = FALSE;
- break;
- case 't': /* generate tiled output */
- outtiled = TRUE;
- break;
- case 'w': /* tile width */
- outtiled = TRUE;
- deftilewidth = atoi(optarg);
- break;
- case 'B':
- if (strlen(mode) < (sizeof(mode) - 1))
- {
- *mp++ = 'b'; *mp = '\0';
- }
- break;
- case 'L':
- if (strlen(mode) < (sizeof(mode) - 1))
- {
- *mp++ = 'l'; *mp = '\0';
- }
- break;
- case 'M':
- if (strlen(mode) < (sizeof(mode) - 1))
- {
- *mp++ = 'm'; *mp = '\0';
- }
- break;
- case 'C':
- if (strlen(mode) < (sizeof(mode) - 1))
- {
- *mp++ = 'c'; *mp = '\0';
- }
- break;
- case '8':
- if (strlen(mode) < (sizeof(mode)-1))
- {
- *mp++ = '8'; *mp = '\0';
- }
- break;
- case 'x':
- pageInSeq = 1;
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- /*NOTREACHED*/
- break;
- case '?':
- usage(EXIT_FAILURE);
- /*NOTREACHED*/
- break;
- }
- if (argc - optind < 2)
- usage(EXIT_FAILURE);
- TIFFOpenOptions* opts = TIFFOpenOptionsAlloc();
- if (opts == NULL) {
- return EXIT_FAILURE;
- }
- TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
- out = TIFFOpenExt(argv[argc-1], mode, opts);
- TIFFOpenOptionsFree(opts);
- if (out == NULL)
- return (EXIT_FAILURE);
- if ((argc - optind) == 2)
- pageNum = -1;
- for (; optind < argc-1 ; optind++) {
- char *imageCursor = argv[optind];
- in = openSrcImage (&imageCursor);
- if (in == NULL) {
- (void) TIFFClose(out);
- return (EXIT_FAILURE);
- }
- if (diroff != 0 && !TIFFSetSubDirectory(in, diroff)) {
- TIFFError(TIFFFileName(in),
- "Error, setting subdirectory at %" PRIu64, diroff);
- (void) TIFFClose(in);
- (void) TIFFClose(out);
- return (EXIT_FAILURE);
- }
- for (;;) {
- config = defconfig;
- compression = defcompression;
- predictor = defpredictor;
- preset = defpreset;
- fillorder = deffillorder;
- rowsperstrip = defrowsperstrip;
- tilewidth = deftilewidth;
- tilelength = deftilelength;
- g3opts = defg3opts;
- if (!tiffcp(in, out) || !TIFFWriteDirectory(out)) {
- (void) TIFFClose(in);
- (void) TIFFClose(out);
- return (EXIT_FAILURE);
- }
- if (imageCursor) { /* seek next image directory */
- if (!nextSrcImage(in, &imageCursor)) break;
- }else
- if (!TIFFReadDirectory(in)) break;
- }
- (void) TIFFClose(in);
- }
-
- (void) TIFFClose(out);
- return (EXIT_SUCCESS);
+ *mp++ = 'w';
+ *mp = '\0';
+ while ((c = getopt(argc, argv, "m:,:b:c:f:l:o:p:r:w:aistBLMC8xh")) != -1)
+ switch (c)
+ {
+ case 'm':
+ maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
+ break;
+ case ',':
+ if (optarg[0] != '=')
+ usage(EXIT_FAILURE);
+ comma = optarg[1];
+ break;
+ case 'b': /* this file is bias image subtracted from others */
+ if (bias)
+ {
+ fputs("Only 1 bias image may be specified\n", stderr);
+ exit(EXIT_FAILURE);
+ }
+ {
+ uint16_t samples = (uint16_t)-1;
+ char **biasFn = &optarg;
+ bias = openSrcImage(biasFn);
+ if (!bias)
+ exit(EXIT_FAILURE);
+ if (TIFFIsTiled(bias))
+ {
+ fputs("Bias image must be organized in strips\n",
+ stderr);
+ exit(EXIT_FAILURE);
+ }
+ TIFFGetField(bias, TIFFTAG_SAMPLESPERPIXEL, &samples);
+ if (samples != 1)
+ {
+ fputs("Bias image must be monochrome\n", stderr);
+ exit(EXIT_FAILURE);
+ }
+ }
+ break;
+ case 'a': /* append to output */
+ mode[0] = 'a';
+ break;
+ case 'c': /* compression scheme */
+ if (!processCompressOptions(optarg))
+ usage(EXIT_FAILURE);
+ break;
+ case 'f': /* fill order */
+ if (streq(optarg, "lsb2msb"))
+ deffillorder = FILLORDER_LSB2MSB;
+ else if (streq(optarg, "msb2lsb"))
+ deffillorder = FILLORDER_MSB2LSB;
+ else
+ usage(EXIT_FAILURE);
+ break;
+ case 'i': /* ignore errors */
+ ignore = TRUE;
+ break;
+ case 'l': /* tile length */
+ outtiled = TRUE;
+ deftilelength = atoi(optarg);
+ break;
+ case 'o': /* initial directory offset */
+ diroff = strtoul(optarg, NULL, 0);
+ break;
+ case 'p': /* planar configuration */
+ if (streq(optarg, "separate"))
+ defconfig = PLANARCONFIG_SEPARATE;
+ else if (streq(optarg, "contig"))
+ defconfig = PLANARCONFIG_CONTIG;
+ else
+ usage(EXIT_FAILURE);
+ break;
+ case 'r': /* rows/strip */
+ defrowsperstrip = atol(optarg);
+ break;
+ case 's': /* generate stripped output */
+ outtiled = FALSE;
+ break;
+ case 't': /* generate tiled output */
+ outtiled = TRUE;
+ break;
+ case 'w': /* tile width */
+ outtiled = TRUE;
+ deftilewidth = atoi(optarg);
+ break;
+ case 'B':
+ if (strlen(mode) < (sizeof(mode) - 1))
+ {
+ *mp++ = 'b';
+ *mp = '\0';
+ }
+ break;
+ case 'L':
+ if (strlen(mode) < (sizeof(mode) - 1))
+ {
+ *mp++ = 'l';
+ *mp = '\0';
+ }
+ break;
+ case 'M':
+ if (strlen(mode) < (sizeof(mode) - 1))
+ {
+ *mp++ = 'm';
+ *mp = '\0';
+ }
+ break;
+ case 'C':
+ if (strlen(mode) < (sizeof(mode) - 1))
+ {
+ *mp++ = 'c';
+ *mp = '\0';
+ }
+ break;
+ case '8':
+ if (strlen(mode) < (sizeof(mode) - 1))
+ {
+ *mp++ = '8';
+ *mp = '\0';
+ }
+ break;
+ case 'x':
+ pageInSeq = 1;
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ /*NOTREACHED*/
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ /*NOTREACHED*/
+ break;
+ }
+ if (argc - optind < 2)
+ usage(EXIT_FAILURE);
+ TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
+ if (opts == NULL)
+ {
+ return EXIT_FAILURE;
+ }
+ TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
+ out = TIFFOpenExt(argv[argc - 1], mode, opts);
+ TIFFOpenOptionsFree(opts);
+ if (out == NULL)
+ return (EXIT_FAILURE);
+ if ((argc - optind) == 2)
+ pageNum = -1;
+ for (; optind < argc - 1; optind++)
+ {
+ char *imageCursor = argv[optind];
+ in = openSrcImage(&imageCursor);
+ if (in == NULL)
+ {
+ (void)TIFFClose(out);
+ return (EXIT_FAILURE);
+ }
+ if (diroff != 0 && !TIFFSetSubDirectory(in, diroff))
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, setting subdirectory at %" PRIu64, diroff);
+ (void)TIFFClose(in);
+ (void)TIFFClose(out);
+ return (EXIT_FAILURE);
+ }
+ for (;;)
+ {
+ config = defconfig;
+ compression = defcompression;
+ predictor = defpredictor;
+ preset = defpreset;
+ fillorder = deffillorder;
+ rowsperstrip = defrowsperstrip;
+ tilewidth = deftilewidth;
+ tilelength = deftilelength;
+ g3opts = defg3opts;
+ if (!tiffcp(in, out) || !TIFFWriteDirectory(out))
+ {
+ (void)TIFFClose(in);
+ (void)TIFFClose(out);
+ return (EXIT_FAILURE);
+ }
+ if (imageCursor)
+ { /* seek next image directory */
+ if (!nextSrcImage(in, &imageCursor))
+ break;
+ }
+ else if (!TIFFReadDirectory(in))
+ break;
+ }
+ (void)TIFFClose(in);
+ }
+
+ (void)TIFFClose(out);
+ return (EXIT_SUCCESS);
}
-static void
-processZIPOptions(char* cp)
+static void processZIPOptions(char *cp)
{
- if ( (cp = strchr(cp, ':')) ) {
- do {
- cp++;
- if (isdigit((int)*cp))
- defpredictor = atoi(cp);
- else if (*cp == 'p')
- defpreset = atoi(++cp);
- else if (*cp == 's')
- subcodec = atoi(++cp);
- else
- usage(EXIT_FAILURE);
- } while( (cp = strchr(cp, ':')) );
- }
+ if ((cp = strchr(cp, ':')))
+ {
+ do
+ {
+ cp++;
+ if (isdigit((int)*cp))
+ defpredictor = atoi(cp);
+ else if (*cp == 'p')
+ defpreset = atoi(++cp);
+ else if (*cp == 's')
+ subcodec = atoi(++cp);
+ else
+ usage(EXIT_FAILURE);
+ } while ((cp = strchr(cp, ':')));
+ }
}
-static void
-processLERCOptions(char* cp)
+static void processLERCOptions(char *cp)
{
- if ( (cp = strchr(cp, ':')) ) {
- do {
- cp++;
- if (isdigit((int)*cp))
- max_z_error = atof(cp);
- else if (*cp == 's')
- subcodec = atoi(++cp);
- else if (*cp == 'p')
- defpreset = atoi(++cp);
- else
- usage(EXIT_FAILURE);
- } while( (cp = strchr(cp, ':')) );
- }
+ if ((cp = strchr(cp, ':')))
+ {
+ do
+ {
+ cp++;
+ if (isdigit((int)*cp))
+ max_z_error = atof(cp);
+ else if (*cp == 's')
+ subcodec = atoi(++cp);
+ else if (*cp == 'p')
+ defpreset = atoi(++cp);
+ else
+ usage(EXIT_FAILURE);
+ } while ((cp = strchr(cp, ':')));
+ }
}
-static void
-processG3Options(char* cp)
+static void processG3Options(char *cp)
{
- if( (cp = strchr(cp, ':')) ) {
- if (defg3opts == (uint32_t) -1)
- defg3opts = 0;
- do {
- cp++;
- if (strneq(cp, "1d", 2))
- defg3opts &= ~GROUP3OPT_2DENCODING;
- else if (strneq(cp, "2d", 2))
- defg3opts |= GROUP3OPT_2DENCODING;
- else if (strneq(cp, "fill", 4))
- defg3opts |= GROUP3OPT_FILLBITS;
- else
- usage(EXIT_FAILURE);
- } while( (cp = strchr(cp, ':')) );
- }
+ if ((cp = strchr(cp, ':')))
+ {
+ if (defg3opts == (uint32_t)-1)
+ defg3opts = 0;
+ do
+ {
+ cp++;
+ if (strneq(cp, "1d", 2))
+ defg3opts &= ~GROUP3OPT_2DENCODING;
+ else if (strneq(cp, "2d", 2))
+ defg3opts |= GROUP3OPT_2DENCODING;
+ else if (strneq(cp, "fill", 4))
+ defg3opts |= GROUP3OPT_FILLBITS;
+ else
+ usage(EXIT_FAILURE);
+ } while ((cp = strchr(cp, ':')));
+ }
}
-static int
-processCompressOptions(char* opt)
+static int processCompressOptions(char *opt)
{
- if (streq(opt, "none")) {
- defcompression = COMPRESSION_NONE;
- } else if (streq(opt, "packbits")) {
- defcompression = COMPRESSION_PACKBITS;
- } else if (strneq(opt, "jpeg", 4)) {
- char* cp = strchr(opt, ':');
-
- defcompression = COMPRESSION_JPEG;
- while( cp )
- {
- if (isdigit((int)cp[1]))
- quality = atoi(cp+1);
- else if (cp[1] == 'r' )
- jpegcolormode = JPEGCOLORMODE_RAW;
- else
- usage(EXIT_FAILURE);
-
- cp = strchr(cp+1,':');
- }
- } else if (strneq(opt, "g3", 2)) {
- processG3Options(opt);
- defcompression = COMPRESSION_CCITTFAX3;
- } else if (streq(opt, "g4")) {
- defcompression = COMPRESSION_CCITTFAX4;
- } else if (strneq(opt, "lzw", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- defpredictor = atoi(cp+1);
- defcompression = COMPRESSION_LZW;
- } else if (strneq(opt, "zip", 3)) {
- processZIPOptions(opt);
- defcompression = COMPRESSION_ADOBE_DEFLATE;
- } else if (strneq(opt, "lerc", 4)) {
- processLERCOptions(opt);
- defcompression = COMPRESSION_LERC;
- } else if (strneq(opt, "lzma", 4)) {
- processZIPOptions(opt);
- defcompression = COMPRESSION_LZMA;
- } else if (strneq(opt, "zstd", 4)) {
- processZIPOptions(opt);
- defcompression = COMPRESSION_ZSTD;
- } else if (strneq(opt, "webp", 4)) {
- processZIPOptions(opt);
- defcompression = COMPRESSION_WEBP;
- } else if (strneq(opt, "jbig", 4)) {
- defcompression = COMPRESSION_JBIG;
- } else if (strneq(opt, "sgilog", 6)) {
- defcompression = COMPRESSION_SGILOG;
- } else
- return (0);
- return (1);
+ if (streq(opt, "none"))
+ {
+ defcompression = COMPRESSION_NONE;
+ }
+ else if (streq(opt, "packbits"))
+ {
+ defcompression = COMPRESSION_PACKBITS;
+ }
+ else if (strneq(opt, "jpeg", 4))
+ {
+ char *cp = strchr(opt, ':');
+
+ defcompression = COMPRESSION_JPEG;
+ while (cp)
+ {
+ if (isdigit((int)cp[1]))
+ quality = atoi(cp + 1);
+ else if (cp[1] == 'r')
+ jpegcolormode = JPEGCOLORMODE_RAW;
+ else
+ usage(EXIT_FAILURE);
+
+ cp = strchr(cp + 1, ':');
+ }
+ }
+ else if (strneq(opt, "g3", 2))
+ {
+ processG3Options(opt);
+ defcompression = COMPRESSION_CCITTFAX3;
+ }
+ else if (streq(opt, "g4"))
+ {
+ defcompression = COMPRESSION_CCITTFAX4;
+ }
+ else if (strneq(opt, "lzw", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ defpredictor = atoi(cp + 1);
+ defcompression = COMPRESSION_LZW;
+ }
+ else if (strneq(opt, "zip", 3))
+ {
+ processZIPOptions(opt);
+ defcompression = COMPRESSION_ADOBE_DEFLATE;
+ }
+ else if (strneq(opt, "lerc", 4))
+ {
+ processLERCOptions(opt);
+ defcompression = COMPRESSION_LERC;
+ }
+ else if (strneq(opt, "lzma", 4))
+ {
+ processZIPOptions(opt);
+ defcompression = COMPRESSION_LZMA;
+ }
+ else if (strneq(opt, "zstd", 4))
+ {
+ processZIPOptions(opt);
+ defcompression = COMPRESSION_ZSTD;
+ }
+ else if (strneq(opt, "webp", 4))
+ {
+ processZIPOptions(opt);
+ defcompression = COMPRESSION_WEBP;
+ }
+ else if (strneq(opt, "jbig", 4))
+ {
+ defcompression = COMPRESSION_JBIG;
+ }
+ else if (strneq(opt, "sgilog", 6))
+ {
+ defcompression = COMPRESSION_SGILOG;
+ }
+ else
+ return (0);
+ return (1);
}
static const char usage_info[] =
-"Copy, convert, or combine TIFF files\n\n"
-"usage: tiffcp [options] input... output\n"
-"where options are:\n"
-" -a append to output instead of overwriting\n"
-" -o offset set initial directory offset\n"
-" -p contig pack samples contiguously (e.g. RGBRGB...)\n"
-" -p separate store samples separately (e.g. RRR...GGG...BBB...)\n"
-" -s write output in strips\n"
-" -t write output in tiles\n"
-" -x force the merged tiff pages in sequence\n"
-" -8 write BigTIFF instead of default ClassicTIFF\n"
-" -B write big-endian instead of native byte order\n"
-" -L write little-endian instead of native byte order\n"
-" -M disable use of memory-mapped files\n"
-" -C disable strip chopping\n"
-" -i ignore read errors\n"
-" -b file[,#] bias (dark) monochrome image to be subtracted from all others\n"
-" -,=% use % rather than , to separate image #'s (per Note below)\n"
-" -m size set maximum memory allocation size (MiB). 0 to disable limit.\n"
-"\n"
-" -r # make each strip have no more than # rows\n"
-" -w # set output tile width (pixels)\n"
-" -l # set output tile length (pixels)\n"
-"\n"
-" -f lsb2msb force lsb-to-msb FillOrder for output\n"
-" -f msb2lsb force msb-to-lsb FillOrder for output\n"
-"\n"
+ "Copy, convert, or combine TIFF files\n\n"
+ "usage: tiffcp [options] input... output\n"
+ "where options are:\n"
+ " -a append to output instead of overwriting\n"
+ " -o offset set initial directory offset\n"
+ " -p contig pack samples contiguously (e.g. RGBRGB...)\n"
+ " -p separate store samples separately (e.g. RRR...GGG...BBB...)\n"
+ " -s write output in strips\n"
+ " -t write output in tiles\n"
+ " -x force the merged tiff pages in sequence\n"
+ " -8 write BigTIFF instead of default ClassicTIFF\n"
+ " -B write big-endian instead of native byte order\n"
+ " -L write little-endian instead of native byte order\n"
+ " -M disable use of memory-mapped files\n"
+ " -C disable strip chopping\n"
+ " -i ignore read errors\n"
+ " -b file[,#] bias (dark) monochrome image to be subtracted from all "
+ "others\n"
+ " -,=% use % rather than , to separate image #'s (per Note "
+ "below)\n"
+ " -m size set maximum memory allocation size (MiB). 0 to disable "
+ "limit.\n"
+ "\n"
+ " -r # make each strip have no more than # rows\n"
+ " -w # set output tile width (pixels)\n"
+ " -l # set output tile length (pixels)\n"
+ "\n"
+ " -f lsb2msb force lsb-to-msb FillOrder for output\n"
+ " -f msb2lsb force msb-to-lsb FillOrder for output\n"
+ "\n"
#ifdef LZW_SUPPORT
-" -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
-/* " LZW options:" */
-" # set predictor value\n"
-" For example, -c lzw:2 for LZW-encoded data with horizontal differencing\n"
+ " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
+ /* " LZW options:" */
+ " # set predictor value\n"
+ " For example, -c lzw:2 for LZW-encoded data with horizontal "
+ "differencing\n"
#endif
#ifdef ZIP_SUPPORT
-" -c zip[:opts] compress output with deflate encoding\n"
-/* " Deflate (ZIP) options:", */
-" # set predictor value\n"
-" p# set compression level (preset)\n"
-" For example, -c zip:3:p9 for maximum compression level and floating\n"
-" point predictor.\n"
+ " -c zip[:opts] compress output with deflate encoding\n"
+ /* " Deflate (ZIP) options:", */
+ " # set predictor value\n"
+ " p# set compression level (preset)\n"
+ " For example, -c zip:3:p9 for maximum compression level and floating\n"
+ " point predictor.\n"
#endif
#if defined(ZIP_SUPPORT) && defined(LIBDEFLATE_SUPPORT)
-" s# set subcodec: 0=zlib, 1=libdeflate (default 1)\n"
+ " s# set subcodec: 0=zlib, 1=libdeflate (default 1)\n"
/* " (only for Deflate/ZIP)", */
#endif
#ifdef LERC_SUPPORT
-" -c lerc[:opts] compress output with LERC encoding\n"
-/* " LERC options:", */
-" # set max_z_error value\n"
-" p# set compression level (preset)\n"
- #ifdef ZSTD_SUPPORT
+ " -c lerc[:opts] compress output with LERC encoding\n"
+ /* " LERC options:", */
+ " # set max_z_error value\n"
+ " p# set compression level (preset)\n"
+#ifdef ZSTD_SUPPORT
" s# set subcodec: 0=none, 1=deflate, 2=zstd (default 0)\n"
" For example, -c lerc:0.5:s2:p22 for max_z_error 0.5,\n"
" zstd additional compression with maximum compression level.\n"
- #else
+#else
" s# set subcodec: 0=none, 1=deflate (default 0)\n"
" For example, -c lerc:0.5:s1:p12 for max_z_error 0.5,\n"
" deflate additional compression with maximum compression level.\n"
- #endif
+#endif
#endif
#ifdef LZMA_SUPPORT
-" -c lzma[:opts] compress output with LZMA2 encoding\n"
-/* " LZMA options:", */
-" # set predictor value\n"
-" p# set compression level (preset)\n"
+ " -c lzma[:opts] compress output with LZMA2 encoding\n"
+ /* " LZMA options:", */
+ " # set predictor value\n"
+ " p# set compression level (preset)\n"
#endif
#ifdef ZSTD_SUPPORT
-" -c zstd[:opts] compress output with ZSTD encoding\n"
-/* " ZSTD options:", */
-" # set predictor value\n"
-" p# set compression level (preset)\n"
+ " -c zstd[:opts] compress output with ZSTD encoding\n"
+ /* " ZSTD options:", */
+ " # set predictor value\n"
+ " p# set compression level (preset)\n"
#endif
#ifdef WEBP_SUPPORT
-" -c webp[:opts] compress output with WEBP encoding\n"
-/* " WEBP options:", */
-" # set predictor value\n"
-" p# set compression level (preset)\n"
+ " -c webp[:opts] compress output with WEBP encoding\n"
+ /* " WEBP options:", */
+ " # set predictor value\n"
+ " p# set compression level (preset)\n"
#endif
#ifdef JPEG_SUPPORT
-" -c jpeg[:opts] compress output with JPEG encoding\n"
-/* " JPEG options:", */
-" # set compression quality level (0-100, default 75)\n"
-" r output color image as RGB rather than YCbCr\n"
-" For example, -c jpeg:r:50 for JPEG-encoded RGB with 50% comp. quality\n"
+ " -c jpeg[:opts] compress output with JPEG encoding\n"
+ /* " JPEG options:", */
+ " # set compression quality level (0-100, default 75)\n"
+ " r output color image as RGB rather than YCbCr\n"
+ " For example, -c jpeg:r:50 for JPEG-encoded RGB with 50% comp. "
+ "quality\n"
#endif
#ifdef JBIG_SUPPORT
-" -c jbig compress output with ISO JBIG encoding\n"
+ " -c jbig compress output with ISO JBIG encoding\n"
#endif
#ifdef PACKBITS_SUPPORT
-" -c packbits compress output with packbits encoding\n"
+ " -c packbits compress output with packbits encoding\n"
#endif
#ifdef CCITT_SUPPORT
-" -c g3[:opts] compress output with CCITT Group 3 encoding\n"
-/* " CCITT Group 3 options:", */
-" 1d use default CCITT Group 3 1D-encoding\n"
-" 2d use optional CCITT Group 3 2D-encoding\n"
-" fill byte-align EOL codes\n"
-" For example, -c g3:2d:fill for G3-2D-encoded data with byte-aligned EOLs\n"
-" -c g4 compress output with CCITT Group 4 encoding\n"
+ " -c g3[:opts] compress output with CCITT Group 3 encoding\n"
+ /* " CCITT Group 3 options:", */
+ " 1d use default CCITT Group 3 1D-encoding\n"
+ " 2d use optional CCITT Group 3 2D-encoding\n"
+ " fill byte-align EOL codes\n"
+ " For example, -c g3:2d:fill for G3-2D-encoded data with byte-aligned "
+ "EOLs\n"
+ " -c g4 compress output with CCITT Group 4 encoding\n"
#endif
#ifdef LOGLUV_SUPPORT
-" -c sgilog compress output with SGILOG encoding\n"
+ " -c sgilog compress output with SGILOG encoding\n"
#endif
-#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(LZMA_SUPPORT) || defined(ZSTD_SUPPORT) || defined(WEBP_SUPPORT) || defined(JPEG_SUPPORT) || defined(JBIG_SUPPORT) || defined(PACKBITS_SUPPORT) || defined(CCITT_SUPPORT) || defined(LOGLUV_SUPPORT) || defined(LERC_SUPPORT)
-" -c none use no compression algorithm on output\n"
+#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(LZMA_SUPPORT) || \
+ defined(ZSTD_SUPPORT) || defined(WEBP_SUPPORT) || defined(JPEG_SUPPORT) || \
+ defined(JBIG_SUPPORT) || defined(PACKBITS_SUPPORT) || \
+ defined(CCITT_SUPPORT) || defined(LOGLUV_SUPPORT) || defined(LERC_SUPPORT)
+ " -c none use no compression algorithm on output\n"
#endif
-"\n"
-"Note that input filenames may be of the form filename,x,y,z\n"
-"where x, y, and z specify image numbers in the filename to copy.\n"
-"example: tiffcp -b esp.tif,1 esp.tif,0 test.tif\n"
-" subtract 2nd image in esp.tif from 1st yielding result test.tif\n"
-;
-
-static void
-usage(int code)
+ "\n"
+ "Note that input filenames may be of the form filename,x,y,z\n"
+ "where x, y, and z specify image numbers in the filename to copy.\n"
+ "example: tiffcp -b esp.tif,1 esp.tif,0 test.tif\n"
+ " subtract 2nd image in esp.tif from 1st yielding result test.tif\n";
+
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
-#define CopyField(tag, v) \
- do { if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v); } while(0)
-#define CopyField2(tag, v1, v2) \
- do { if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2); } while(0)
-#define CopyField3(tag, v1, v2, v3) \
- do { if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3); } while(0)
-#define CopyField4(tag, v1, v2, v3, v4) \
- do { if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4); } while(0)
-
-static void
-cpTag(TIFF* in, TIFF* out, uint16_t tag, uint16_t count, TIFFDataType type)
+#define CopyField(tag, v) \
+ do \
+ { \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v); \
+ } while (0)
+#define CopyField2(tag, v1, v2) \
+ do \
+ { \
+ if (TIFFGetField(in, tag, &v1, &v2)) \
+ TIFFSetField(out, tag, v1, v2); \
+ } while (0)
+#define CopyField3(tag, v1, v2, v3) \
+ do \
+ { \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) \
+ TIFFSetField(out, tag, v1, v2, v3); \
+ } while (0)
+#define CopyField4(tag, v1, v2, v3, v4) \
+ do \
+ { \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) \
+ TIFFSetField(out, tag, v1, v2, v3, v4); \
+ } while (0)
+
+static void cpTag(TIFF *in, TIFF *out, uint16_t tag, uint16_t count,
+ TIFFDataType type)
{
- switch (type) {
- case TIFF_SHORT:
- if (count == 1) {
- uint16_t shortv;
- CopyField(tag, shortv);
- } else if (count == 2) {
- uint16_t shortv1, shortv2;
- CopyField2(tag, shortv1, shortv2);
- } else if (count == 4) {
- uint16_t *tr, *tg, *tb, *ta;
- CopyField4(tag, tr, tg, tb, ta);
- } else if (count == (uint16_t) -1) {
- uint16_t shortv1;
- uint16_t* shortav;
- CopyField2(tag, shortv1, shortav);
- }
- break;
- case TIFF_LONG:
- { uint32_t longv;
- CopyField(tag, longv);
- }
- break;
- case TIFF_RATIONAL:
- if (count == 1) {
- float floatv;
- CopyField(tag, floatv);
- } else if (count == (uint16_t) -1) {
- float* floatav;
- CopyField(tag, floatav);
- }
- break;
- case TIFF_ASCII:
- { char* stringv;
- CopyField(tag, stringv);
- }
- break;
- case TIFF_DOUBLE:
- if (count == 1) {
- double doublev;
- CopyField(tag, doublev);
- } else if (count == (uint16_t) -1) {
- double* doubleav;
- CopyField(tag, doubleav);
- }
- break;
- default:
- TIFFError(TIFFFileName(in),
- "Data type %"PRIu16" is not supported, tag %d skipped.",
- tag, type);
- }
+ switch (type)
+ {
+ case TIFF_SHORT:
+ if (count == 1)
+ {
+ uint16_t shortv;
+ CopyField(tag, shortv);
+ }
+ else if (count == 2)
+ {
+ uint16_t shortv1, shortv2;
+ CopyField2(tag, shortv1, shortv2);
+ }
+ else if (count == 4)
+ {
+ uint16_t *tr, *tg, *tb, *ta;
+ CopyField4(tag, tr, tg, tb, ta);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ uint16_t shortv1;
+ uint16_t *shortav;
+ CopyField2(tag, shortv1, shortav);
+ }
+ break;
+ case TIFF_LONG:
+ {
+ uint32_t longv;
+ CopyField(tag, longv);
+ }
+ break;
+ case TIFF_RATIONAL:
+ if (count == 1)
+ {
+ float floatv;
+ CopyField(tag, floatv);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ float *floatav;
+ CopyField(tag, floatav);
+ }
+ break;
+ case TIFF_ASCII:
+ {
+ char *stringv;
+ CopyField(tag, stringv);
+ }
+ break;
+ case TIFF_DOUBLE:
+ if (count == 1)
+ {
+ double doublev;
+ CopyField(tag, doublev);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ double *doubleav;
+ CopyField(tag, doubleav);
+ }
+ break;
+ default:
+ TIFFError(TIFFFileName(in),
+ "Data type %" PRIu16 " is not supported, tag %d skipped.",
+ tag, type);
+ }
}
-static const struct cpTag {
- uint16_t tag;
- uint16_t count;
- TIFFDataType type;
+static const struct cpTag
+{
+ uint16_t tag;
+ uint16_t count;
+ TIFFDataType type;
} tags[] = {
- { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
- { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
- { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
- { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
- { TIFFTAG_MAKE, 1, TIFF_ASCII },
- { TIFFTAG_MODEL, 1, TIFF_ASCII },
- { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
- { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
- { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
- { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
- { TIFFTAG_PAGENAME, 1, TIFF_ASCII },
- { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
- { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
- { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
- { TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
- { TIFFTAG_DATETIME, 1, TIFF_ASCII },
- { TIFFTAG_ARTIST, 1, TIFF_ASCII },
- { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
- { TIFFTAG_WHITEPOINT, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_PRIMARYCHROMATICITIES,(uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
- { TIFFTAG_INKSET, 1, TIFF_SHORT },
- { TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
- { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
- { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
- { TIFFTAG_YCBCRCOEFFICIENTS, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
- { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
- { TIFFTAG_REFERENCEBLACKWHITE, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_EXTRASAMPLES, (uint16_t) -1, TIFF_SHORT },
- { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE },
- { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE },
- { TIFFTAG_STONITS, 1, TIFF_DOUBLE },
+ {TIFFTAG_SUBFILETYPE, 1, TIFF_LONG},
+ {TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT},
+ {TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII},
+ {TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII},
+ {TIFFTAG_MAKE, 1, TIFF_ASCII},
+ {TIFFTAG_MODEL, 1, TIFF_ASCII},
+ {TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT},
+ {TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT},
+ {TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL},
+ {TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL},
+ {TIFFTAG_PAGENAME, 1, TIFF_ASCII},
+ {TIFFTAG_XPOSITION, 1, TIFF_RATIONAL},
+ {TIFFTAG_YPOSITION, 1, TIFF_RATIONAL},
+ {TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT},
+ {TIFFTAG_SOFTWARE, 1, TIFF_ASCII},
+ {TIFFTAG_DATETIME, 1, TIFF_ASCII},
+ {TIFFTAG_ARTIST, 1, TIFF_ASCII},
+ {TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII},
+ {TIFFTAG_WHITEPOINT, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_PRIMARYCHROMATICITIES, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT},
+ {TIFFTAG_INKSET, 1, TIFF_SHORT},
+ {TIFFTAG_DOTRANGE, 2, TIFF_SHORT},
+ {TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII},
+ {TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT},
+ {TIFFTAG_YCBCRCOEFFICIENTS, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT},
+ {TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT},
+ {TIFFTAG_REFERENCEBLACKWHITE, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_EXTRASAMPLES, (uint16_t)-1, TIFF_SHORT},
+ {TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE},
+ {TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE},
+ {TIFFTAG_STONITS, 1, TIFF_DOUBLE},
};
-#define NTAGS (sizeof (tags) / sizeof (tags[0]))
+#define NTAGS (sizeof(tags) / sizeof(tags[0]))
-#define CopyTag(tag, count, type) cpTag(in, out, tag, count, type)
+#define CopyTag(tag, count, type) cpTag(in, out, tag, count, type)
-typedef int (*copyFunc)
- (TIFF* in, TIFF* out, uint32_t l, uint32_t w, uint16_t samplesperpixel);
-static copyFunc pickCopyFunc(TIFF*, TIFF*, uint16_t, uint16_t);
+typedef int (*copyFunc)(TIFF *in, TIFF *out, uint32_t l, uint32_t w,
+ uint16_t samplesperpixel);
+static copyFunc pickCopyFunc(TIFF *, TIFF *, uint16_t, uint16_t);
/* PODD */
-static int
-tiffcp(TIFF* in, TIFF* out)
+static int tiffcp(TIFF *in, TIFF *out)
{
- uint16_t bitspersample = 1, samplesperpixel = 1;
- uint16_t input_compression, input_photometric = PHOTOMETRIC_MINISBLACK;
- copyFunc cf;
- uint32_t width, length;
- const struct cpTag* p;
-
- CopyField(TIFFTAG_IMAGEWIDTH, width);
- CopyField(TIFFTAG_IMAGELENGTH, length);
- CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample);
- CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
- if (compression != (uint16_t)-1)
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- else
- CopyField(TIFFTAG_COMPRESSION, compression);
- if( !TIFFIsCODECConfigured(compression) )
- return FALSE;
- TIFFGetFieldDefaulted(in, TIFFTAG_COMPRESSION, &input_compression);
- TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric);
- if (input_compression == COMPRESSION_JPEG) {
- /* Force conversion to RGB */
- TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
- } else if (input_photometric == PHOTOMETRIC_YCBCR) {
- /* Otherwise, can't handle subsampled input */
- uint16_t subsamplinghor,subsamplingver;
-
- TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
- &subsamplinghor, &subsamplingver);
- if (subsamplinghor!=1 || subsamplingver!=1) {
- fprintf(stderr, "tiffcp: %s: Can't copy/convert subsampled image.\n",
- TIFFFileName(in));
- return FALSE;
- }
- }
- if (compression == COMPRESSION_JPEG) {
- if (input_photometric == PHOTOMETRIC_RGB &&
- jpegcolormode == JPEGCOLORMODE_RGB)
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
- else
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
- }
- else if (compression == COMPRESSION_SGILOG
- || compression == COMPRESSION_SGILOG24)
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC,
- samplesperpixel == 1 ?
- PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
- else if (input_compression == COMPRESSION_JPEG &&
- samplesperpixel == 3 ) {
- /* RGB conversion was forced above
- hence the output will be of the same type */
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
- }
- else
- CopyTag(TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT);
- if (fillorder != 0)
- TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
- else
- CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
- /*
- * Will copy `Orientation' tag from input image
- */
- TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
- TIFFSetField(out, TIFFTAG_ORIENTATION, orientation);
- /*
- * Choose tiles/strip for the output image according to
- * the command line arguments (-tiles, -strips) and the
- * structure of the input image.
- */
- if (outtiled == -1)
- outtiled = TIFFIsTiled(in);
- if (outtiled) {
- /*
- * Setup output file's tile width&height. If either
- * is not specified, use either the value from the
- * input image or, if nothing is defined, use the
- * library default.
- */
- if (tilewidth == (uint32_t) -1)
- TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
- if (tilelength == (uint32_t) -1)
- TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
- TIFFDefaultTileSize(out, &tilewidth, &tilelength);
- TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
- TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
- } else {
- /*
- * RowsPerStrip is left unspecified: use either the
- * value from the input image or, if nothing is defined,
- * use the library default.
- */
- if (rowsperstrip == (uint32_t) 0) {
- if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP,
- &rowsperstrip)) {
- rowsperstrip =
- TIFFDefaultStripSize(out, rowsperstrip);
- }
- if (rowsperstrip > length && rowsperstrip != (uint32_t)-1)
- rowsperstrip = length;
- }
- else if (rowsperstrip == (uint32_t) -1)
- rowsperstrip = length;
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
- }
- if (config != (uint16_t) -1)
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
- else
- CopyField(TIFFTAG_PLANARCONFIG, config);
- if (samplesperpixel <= 4)
- CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
- CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
-/* SMinSampleValue & SMaxSampleValue */
- switch (compression) {
- case COMPRESSION_JPEG:
- TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
- TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
- break;
- case COMPRESSION_JBIG:
- CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
- CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
- CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
- CopyTag(TIFFTAG_FAXDCS, 1, TIFF_ASCII);
- break;
- case COMPRESSION_LERC:
- if( max_z_error > 0 )
- {
- if( TIFFSetField(out, TIFFTAG_LERC_MAXZERROR, max_z_error) != 1 )
- {
- return FALSE;
- }
- }
- if( subcodec != -1 )
- {
- if( TIFFSetField(out, TIFFTAG_LERC_ADD_COMPRESSION, subcodec) != 1 )
- {
- return FALSE;
- }
- }
- if( preset != -1 )
- {
- switch (subcodec) {
- case LERC_ADD_COMPRESSION_DEFLATE:
- if( TIFFSetField(out, TIFFTAG_ZIPQUALITY, preset) != 1 )
- {
- return FALSE;
- }
- break;
- case LERC_ADD_COMPRESSION_ZSTD:
- if( TIFFSetField( out, TIFFTAG_ZSTD_LEVEL, preset ) != 1 )
- {
- return FALSE;
- }
- break;
- }
- }
- break;
- case COMPRESSION_LZW:
- case COMPRESSION_ADOBE_DEFLATE:
- case COMPRESSION_DEFLATE:
- case COMPRESSION_LZMA:
- case COMPRESSION_ZSTD:
- if (predictor != (uint16_t)-1)
- TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
- else if( input_compression == COMPRESSION_LZW ||
- input_compression == COMPRESSION_ADOBE_DEFLATE ||
- input_compression == COMPRESSION_DEFLATE ||
- input_compression == COMPRESSION_LZMA ||
- input_compression == COMPRESSION_ZSTD ) {
- CopyField(TIFFTAG_PREDICTOR, predictor);
+ uint16_t bitspersample = 1, samplesperpixel = 1;
+ uint16_t input_compression, input_photometric = PHOTOMETRIC_MINISBLACK;
+ copyFunc cf;
+ uint32_t width, length;
+ const struct cpTag *p;
+
+ CopyField(TIFFTAG_IMAGEWIDTH, width);
+ CopyField(TIFFTAG_IMAGELENGTH, length);
+ CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample);
+ CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
+ if (compression != (uint16_t)-1)
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
+ else
+ CopyField(TIFFTAG_COMPRESSION, compression);
+ if (!TIFFIsCODECConfigured(compression))
+ return FALSE;
+ TIFFGetFieldDefaulted(in, TIFFTAG_COMPRESSION, &input_compression);
+ TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric);
+ if (input_compression == COMPRESSION_JPEG)
+ {
+ /* Force conversion to RGB */
+ TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
+ }
+ else if (input_photometric == PHOTOMETRIC_YCBCR)
+ {
+ /* Otherwise, can't handle subsampled input */
+ uint16_t subsamplinghor, subsamplingver;
+
+ TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor,
+ &subsamplingver);
+ if (subsamplinghor != 1 || subsamplingver != 1)
+ {
+ fprintf(stderr,
+ "tiffcp: %s: Can't copy/convert subsampled image.\n",
+ TIFFFileName(in));
+ return FALSE;
+ }
+ }
+ if (compression == COMPRESSION_JPEG)
+ {
+ if (input_photometric == PHOTOMETRIC_RGB &&
+ jpegcolormode == JPEGCOLORMODE_RGB)
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
+ else
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
+ }
+ else if (compression == COMPRESSION_SGILOG ||
+ compression == COMPRESSION_SGILOG24)
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC,
+ samplesperpixel == 1 ? PHOTOMETRIC_LOGL
+ : PHOTOMETRIC_LOGLUV);
+ else if (input_compression == COMPRESSION_JPEG && samplesperpixel == 3)
+ {
+ /* RGB conversion was forced above
+ hence the output will be of the same type */
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
+ }
+ else
+ CopyTag(TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT);
+ if (fillorder != 0)
+ TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
+ else
+ CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
+ /*
+ * Will copy `Orientation' tag from input image
+ */
+ TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
+ TIFFSetField(out, TIFFTAG_ORIENTATION, orientation);
+ /*
+ * Choose tiles/strip for the output image according to
+ * the command line arguments (-tiles, -strips) and the
+ * structure of the input image.
+ */
+ if (outtiled == -1)
+ outtiled = TIFFIsTiled(in);
+ if (outtiled)
+ {
+ /*
+ * Setup output file's tile width&height. If either
+ * is not specified, use either the value from the
+ * input image or, if nothing is defined, use the
+ * library default.
+ */
+ if (tilewidth == (uint32_t)-1)
+ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
+ if (tilelength == (uint32_t)-1)
+ TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
+ TIFFDefaultTileSize(out, &tilewidth, &tilelength);
+ TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
+ TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
+ }
+ else
+ {
+ /*
+ * RowsPerStrip is left unspecified: use either the
+ * value from the input image or, if nothing is defined,
+ * use the library default.
+ */
+ if (rowsperstrip == (uint32_t)0)
+ {
+ if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
+ {
+ rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
}
- if( compression == COMPRESSION_ADOBE_DEFLATE ||
- compression == COMPRESSION_DEFLATE )
+ if (rowsperstrip > length && rowsperstrip != (uint32_t)-1)
+ rowsperstrip = length;
+ }
+ else if (rowsperstrip == (uint32_t)-1)
+ rowsperstrip = length;
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
+ }
+ if (config != (uint16_t)-1)
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
+ else
+ CopyField(TIFFTAG_PLANARCONFIG, config);
+ if (samplesperpixel <= 4)
+ CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
+ CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
+ /* SMinSampleValue & SMaxSampleValue */
+ switch (compression)
+ {
+ case COMPRESSION_JPEG:
+ TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
+ TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
+ break;
+ case COMPRESSION_JBIG:
+ CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
+ CopyTag(TIFFTAG_FAXDCS, 1, TIFF_ASCII);
+ break;
+ case COMPRESSION_LERC:
+ if (max_z_error > 0)
+ {
+ if (TIFFSetField(out, TIFFTAG_LERC_MAXZERROR, max_z_error) != 1)
+ {
+ return FALSE;
+ }
+ }
+ if (subcodec != -1)
+ {
+ if (TIFFSetField(out, TIFFTAG_LERC_ADD_COMPRESSION, subcodec) !=
+ 1)
+ {
+ return FALSE;
+ }
+ }
+ if (preset != -1)
+ {
+ switch (subcodec)
+ {
+ case LERC_ADD_COMPRESSION_DEFLATE:
+ if (TIFFSetField(out, TIFFTAG_ZIPQUALITY, preset) != 1)
{
- if( subcodec != -1 )
- {
- if( TIFFSetField(out, TIFFTAG_DEFLATE_SUBCODEC, subcodec) != 1 )
- {
- return FALSE;
- }
- }
+ return FALSE;
}
- /*fallthrough*/
- case COMPRESSION_WEBP:
- if (preset != -1) {
- if (preset == 100) {
- TIFFSetField(out, TIFFTAG_WEBP_LOSSLESS, TRUE);
- } else {
- TIFFSetField(out, TIFFTAG_WEBP_LEVEL, preset);
- }
- }
- break;
- case COMPRESSION_CCITTFAX3:
- case COMPRESSION_CCITTFAX4:
- if (compression == COMPRESSION_CCITTFAX3) {
- if (g3opts != (uint32_t) -1)
- TIFFSetField(out, TIFFTAG_GROUP3OPTIONS,
- g3opts);
- else if( input_compression == COMPRESSION_CCITTFAX3 )
- CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
- } else if( input_compression == COMPRESSION_CCITTFAX4 )
- CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
- if( input_compression == COMPRESSION_CCITTFAX3 || input_compression == COMPRESSION_CCITTFAX4 ) {
- CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
- CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
- CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
- }
- CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
- CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
- CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
- break;
- }
- {
- uint32_t len32;
- void** data;
- if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
- TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
- }
- {
- uint16_t ninks;
- const char* inknames;
- if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
- TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
- if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
- int inknameslen = strlen(inknames) + 1;
- const char* cp = inknames;
- while (ninks > 1) {
- cp = strchr(cp, '\0');
- cp++;
- inknameslen += (strlen(cp) + 1);
- ninks--;
- }
- TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
- }
- }
- }
- {
- unsigned short pg0, pg1;
-
- if (pageInSeq == 1) {
- if (pageNum < 0) /* only one input file */ {
- if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1))
- TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
- } else
- TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
-
- } else {
- if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
- if (pageNum < 0) /* only one input file */
- TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
- else
- TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
- }
- }
- }
-
- for (p = tags; p < &tags[NTAGS]; p++)
- CopyTag(p->tag, p->count, p->type);
-
- cf = pickCopyFunc(in, out, bitspersample, samplesperpixel);
- return (cf ? (*cf)(in, out, length, width, samplesperpixel) : FALSE);
+ break;
+ case LERC_ADD_COMPRESSION_ZSTD:
+ if (TIFFSetField(out, TIFFTAG_ZSTD_LEVEL, preset) != 1)
+ {
+ return FALSE;
+ }
+ break;
+ }
+ }
+ break;
+ case COMPRESSION_LZW:
+ case COMPRESSION_ADOBE_DEFLATE:
+ case COMPRESSION_DEFLATE:
+ case COMPRESSION_LZMA:
+ case COMPRESSION_ZSTD:
+ if (predictor != (uint16_t)-1)
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
+ else if (input_compression == COMPRESSION_LZW ||
+ input_compression == COMPRESSION_ADOBE_DEFLATE ||
+ input_compression == COMPRESSION_DEFLATE ||
+ input_compression == COMPRESSION_LZMA ||
+ input_compression == COMPRESSION_ZSTD)
+ {
+ CopyField(TIFFTAG_PREDICTOR, predictor);
+ }
+ if (compression == COMPRESSION_ADOBE_DEFLATE ||
+ compression == COMPRESSION_DEFLATE)
+ {
+ if (subcodec != -1)
+ {
+ if (TIFFSetField(out, TIFFTAG_DEFLATE_SUBCODEC, subcodec) !=
+ 1)
+ {
+ return FALSE;
+ }
+ }
+ }
+ /*fallthrough*/
+ case COMPRESSION_WEBP:
+ if (preset != -1)
+ {
+ if (preset == 100)
+ {
+ TIFFSetField(out, TIFFTAG_WEBP_LOSSLESS, TRUE);
+ }
+ else
+ {
+ TIFFSetField(out, TIFFTAG_WEBP_LEVEL, preset);
+ }
+ }
+ break;
+ case COMPRESSION_CCITTFAX3:
+ case COMPRESSION_CCITTFAX4:
+ if (compression == COMPRESSION_CCITTFAX3)
+ {
+ if (g3opts != (uint32_t)-1)
+ TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
+ else if (input_compression == COMPRESSION_CCITTFAX3)
+ CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
+ }
+ else if (input_compression == COMPRESSION_CCITTFAX4)
+ CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
+ if (input_compression == COMPRESSION_CCITTFAX3 ||
+ input_compression == COMPRESSION_CCITTFAX4)
+ {
+ CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
+ }
+ CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
+ break;
+ }
+ {
+ uint32_t len32;
+ void **data;
+ if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
+ TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
+ }
+ {
+ uint16_t ninks;
+ const char *inknames;
+ if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks))
+ {
+ TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
+ if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames))
+ {
+ int inknameslen = strlen(inknames) + 1;
+ const char *cp = inknames;
+ while (ninks > 1)
+ {
+ cp = strchr(cp, '\0');
+ cp++;
+ inknameslen += (strlen(cp) + 1);
+ ninks--;
+ }
+ TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
+ }
+ }
+ }
+ {
+ unsigned short pg0, pg1;
+
+ if (pageInSeq == 1)
+ {
+ if (pageNum < 0) /* only one input file */
+ {
+ if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1))
+ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
+ }
+ else
+ TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
+ }
+ else
+ {
+ if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1))
+ {
+ if (pageNum < 0) /* only one input file */
+ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
+ else
+ TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
+ }
+ }
+ }
+
+ for (p = tags; p < &tags[NTAGS]; p++)
+ CopyTag(p->tag, p->count, p->type);
+
+ cf = pickCopyFunc(in, out, bitspersample, samplesperpixel);
+ return (cf ? (*cf)(in, out, length, width, samplesperpixel) : FALSE);
}
/*
* Copy Functions.
*/
-#define DECLAREcpFunc(x) \
-static int x(TIFF* in, TIFF* out, \
- uint32_t imagelength, uint32_t imagewidth, tsample_t spp)
+#define DECLAREcpFunc(x) \
+ static int x(TIFF *in, TIFF *out, uint32_t imagelength, \
+ uint32_t imagewidth, tsample_t spp)
-#define DECLAREreadFunc(x) \
-static int x(TIFF* in, \
- uint8_t* buf, uint32_t imagelength, uint32_t imagewidth, tsample_t spp)
-typedef int (*readFunc)(TIFF*, uint8_t*, uint32_t, uint32_t, tsample_t);
+#define DECLAREreadFunc(x) \
+ static int x(TIFF *in, uint8_t *buf, uint32_t imagelength, \
+ uint32_t imagewidth, tsample_t spp)
+typedef int (*readFunc)(TIFF *, uint8_t *, uint32_t, uint32_t, tsample_t);
-#define DECLAREwriteFunc(x) \
-static int x(TIFF* out, \
- uint8_t* buf, uint32_t imagelength, uint32_t imagewidth, tsample_t spp)
-typedef int (*writeFunc)(TIFF*, uint8_t*, uint32_t, uint32_t, tsample_t);
+#define DECLAREwriteFunc(x) \
+ static int x(TIFF *out, uint8_t *buf, uint32_t imagelength, \
+ uint32_t imagewidth, tsample_t spp)
+typedef int (*writeFunc)(TIFF *, uint8_t *, uint32_t, uint32_t, tsample_t);
/*
* Contig -> contig by scanline for rows/strip change.
*/
DECLAREcpFunc(cpContig2ContigByRow)
{
- tsize_t scanlinesize = TIFFScanlineSize(in);
- tdata_t buf;
- uint32_t row;
-
- buf = limitMalloc(scanlinesize);
- if (!buf)
- return 0;
- _TIFFmemset(buf, 0, scanlinesize);
- (void) imagewidth; (void) spp;
- for (row = 0; row < imagelength; row++) {
- if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read scanline %"PRIu32,
- row);
- goto bad;
- }
- if (TIFFWriteScanline(out, buf, row, 0) < 0) {
- TIFFError(TIFFFileName(out),
- "Error, can't write scanline %"PRIu32,
- row);
- goto bad;
- }
- }
- _TIFFfree(buf);
- return 1;
+ tsize_t scanlinesize = TIFFScanlineSize(in);
+ tdata_t buf;
+ uint32_t row;
+
+ buf = limitMalloc(scanlinesize);
+ if (!buf)
+ return 0;
+ _TIFFmemset(buf, 0, scanlinesize);
+ (void)imagewidth;
+ (void)spp;
+ for (row = 0; row < imagelength; row++)
+ {
+ if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in), "Error, can't read scanline %" PRIu32,
+ row);
+ goto bad;
+ }
+ if (TIFFWriteScanline(out, buf, row, 0) < 0)
+ {
+ TIFFError(TIFFFileName(out), "Error, can't write scanline %" PRIu32,
+ row);
+ goto bad;
+ }
+ }
+ _TIFFfree(buf);
+ return 1;
bad:
- _TIFFfree(buf);
- return 0;
+ _TIFFfree(buf);
+ return 0;
}
+typedef void biasFn(void *image, void *bias, uint32_t pixels);
-typedef void biasFn (void *image, void *bias, uint32_t pixels);
+#define subtract(bits) \
+ static void subtract##bits(void *i, void *b, uint32_t pixels) \
+ { \
+ uint##bits##_t *image = i; \
+ uint##bits##_t *bias = b; \
+ while (pixels--) \
+ { \
+ *image = *image > *bias ? *image - *bias : 0; \
+ image++, bias++; \
+ } \
+ }
-#define subtract(bits) \
-static void subtract##bits (void *i, void *b, uint32_t pixels)\
-{\
- uint##bits##_t *image = i;\
- uint##bits##_t *bias = b;\
- while (pixels--) {\
- *image = *image > *bias ? *image-*bias : 0;\
- image++, bias++; \
- } \
-}
-
-subtract(8)
-subtract(16)
-subtract(32)
+subtract(8) subtract(16) subtract(32)
-static biasFn *lineSubtractFn (unsigned bits)
+ static biasFn *lineSubtractFn(unsigned bits)
{
- switch (bits) {
- case 8: return subtract8;
- case 16: return subtract16;
- case 32: return subtract32;
- }
- return NULL;
+ switch (bits)
+ {
+ case 8:
+ return subtract8;
+ case 16:
+ return subtract16;
+ case 32:
+ return subtract32;
+ }
+ return NULL;
}
/*
@@ -1076,121 +1211,133 @@ static biasFn *lineSubtractFn (unsigned bits)
*/
DECLAREcpFunc(cpBiasedContig2Contig)
{
- if (spp == 1) {
- tsize_t biasSize = TIFFScanlineSize(bias);
- tsize_t bufSize = TIFFScanlineSize(in);
- tdata_t buf, biasBuf;
- uint32_t biasWidth = 0, biasLength = 0;
- TIFFGetField(bias, TIFFTAG_IMAGEWIDTH, &biasWidth);
- TIFFGetField(bias, TIFFTAG_IMAGELENGTH, &biasLength);
- if (biasSize == bufSize &&
- imagelength == biasLength && imagewidth == biasWidth) {
- uint16_t sampleBits = 0;
- biasFn *subtractLine;
- TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &sampleBits);
- subtractLine = lineSubtractFn (sampleBits);
- if (subtractLine) {
- uint32_t row;
- buf = limitMalloc(bufSize);
- biasBuf = limitMalloc(bufSize);
- for (row = 0; row < imagelength; row++) {
- if (TIFFReadScanline(in, buf, row, 0) < 0
- && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read scanline %"PRIu32,
- row);
- goto bad;
- }
- if (TIFFReadScanline(bias, biasBuf, row, 0) < 0
- && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read biased scanline %"PRIu32,
- row);
- goto bad;
- }
- subtractLine (buf, biasBuf, imagewidth);
- if (TIFFWriteScanline(out, buf, row, 0) < 0) {
- TIFFError(TIFFFileName(out),
- "Error, can't write scanline %"PRIu32,
- row);
- goto bad;
- }
- }
-
- _TIFFfree(buf);
- _TIFFfree(biasBuf);
- TIFFSetDirectory(bias,
- TIFFCurrentDirectory(bias)); /* rewind */
- return 1;
-bad:
- _TIFFfree(buf);
- _TIFFfree(biasBuf);
- return 0;
- } else {
- TIFFError(TIFFFileName(in),
- "No support for biasing %"PRIu16" bit pixels\n",
- sampleBits);
- return 0;
- }
- }
- TIFFError(TIFFFileName(in),
- "Bias image %s,%"PRIu16"\nis not the same size as %s,%"PRIu16"\n",
- TIFFFileName(bias), TIFFCurrentDirectory(bias),
- TIFFFileName(in), TIFFCurrentDirectory(in));
- return 0;
- } else {
- TIFFError(TIFFFileName(in),
- "Can't bias %s,%"PRIu16" as it has >1 Sample/Pixel\n",
- TIFFFileName(in), TIFFCurrentDirectory(in));
- return 0;
- }
-
+ if (spp == 1)
+ {
+ tsize_t biasSize = TIFFScanlineSize(bias);
+ tsize_t bufSize = TIFFScanlineSize(in);
+ tdata_t buf, biasBuf;
+ uint32_t biasWidth = 0, biasLength = 0;
+ TIFFGetField(bias, TIFFTAG_IMAGEWIDTH, &biasWidth);
+ TIFFGetField(bias, TIFFTAG_IMAGELENGTH, &biasLength);
+ if (biasSize == bufSize && imagelength == biasLength &&
+ imagewidth == biasWidth)
+ {
+ uint16_t sampleBits = 0;
+ biasFn *subtractLine;
+ TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &sampleBits);
+ subtractLine = lineSubtractFn(sampleBits);
+ if (subtractLine)
+ {
+ uint32_t row;
+ buf = limitMalloc(bufSize);
+ biasBuf = limitMalloc(bufSize);
+ for (row = 0; row < imagelength; row++)
+ {
+ if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read scanline %" PRIu32, row);
+ goto bad;
+ }
+ if (TIFFReadScanline(bias, biasBuf, row, 0) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read biased scanline %" PRIu32,
+ row);
+ goto bad;
+ }
+ subtractLine(buf, biasBuf, imagewidth);
+ if (TIFFWriteScanline(out, buf, row, 0) < 0)
+ {
+ TIFFError(TIFFFileName(out),
+ "Error, can't write scanline %" PRIu32, row);
+ goto bad;
+ }
+ }
+
+ _TIFFfree(buf);
+ _TIFFfree(biasBuf);
+ TIFFSetDirectory(bias, TIFFCurrentDirectory(bias)); /* rewind */
+ return 1;
+ bad:
+ _TIFFfree(buf);
+ _TIFFfree(biasBuf);
+ return 0;
+ }
+ else
+ {
+ TIFFError(TIFFFileName(in),
+ "No support for biasing %" PRIu16 " bit pixels\n",
+ sampleBits);
+ return 0;
+ }
+ }
+ TIFFError(TIFFFileName(in),
+ "Bias image %s,%" PRIu16
+ "\nis not the same size as %s,%" PRIu16 "\n",
+ TIFFFileName(bias), TIFFCurrentDirectory(bias),
+ TIFFFileName(in), TIFFCurrentDirectory(in));
+ return 0;
+ }
+ else
+ {
+ TIFFError(TIFFFileName(in),
+ "Can't bias %s,%" PRIu16 " as it has >1 Sample/Pixel\n",
+ TIFFFileName(in), TIFFCurrentDirectory(in));
+ return 0;
+ }
}
-
/*
* Strip -> strip for change in encoding.
*/
DECLAREcpFunc(cpDecodedStrips)
{
- tsize_t stripsize = TIFFStripSize(in);
- tdata_t buf = limitMalloc(stripsize);
-
- (void) imagewidth; (void) spp;
- if (buf) {
- tstrip_t s, ns = TIFFNumberOfStrips(in);
- uint32_t row = 0;
- _TIFFmemset(buf, 0, stripsize);
- for (s = 0; s < ns && row < imagelength; s++) {
- tsize_t cc = (row + rowsperstrip > imagelength) ?
- TIFFVStripSize(in, imagelength - row) : stripsize;
- if (TIFFReadEncodedStrip(in, s, buf, cc) < 0
- && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read strip %"PRIu32,
- s);
- goto bad;
- }
- if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) {
- TIFFError(TIFFFileName(out),
- "Error, can't write strip %"PRIu32,
- s);
- goto bad;
- }
- row += rowsperstrip;
- }
- _TIFFfree(buf);
- return 1;
- } else {
- TIFFError(TIFFFileName(in),
- "Error, can't allocate memory buffer of size %"TIFF_SSIZE_FORMAT
- " to read strips", stripsize);
- return 0;
- }
+ tsize_t stripsize = TIFFStripSize(in);
+ tdata_t buf = limitMalloc(stripsize);
+
+ (void)imagewidth;
+ (void)spp;
+ if (buf)
+ {
+ tstrip_t s, ns = TIFFNumberOfStrips(in);
+ uint32_t row = 0;
+ _TIFFmemset(buf, 0, stripsize);
+ for (s = 0; s < ns && row < imagelength; s++)
+ {
+ tsize_t cc = (row + rowsperstrip > imagelength)
+ ? TIFFVStripSize(in, imagelength - row)
+ : stripsize;
+ if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in), "Error, can't read strip %" PRIu32,
+ s);
+ goto bad;
+ }
+ if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0)
+ {
+ TIFFError(TIFFFileName(out),
+ "Error, can't write strip %" PRIu32, s);
+ goto bad;
+ }
+ row += rowsperstrip;
+ }
+ _TIFFfree(buf);
+ return 1;
+ }
+ else
+ {
+ TIFFError(
+ TIFFFileName(in),
+ "Error, can't allocate memory buffer of size %" TIFF_SSIZE_FORMAT
+ " to read strips",
+ stripsize);
+ return 0;
+ }
bad:
- _TIFFfree(buf);
- return 0;
+ _TIFFfree(buf);
+ return 0;
}
/*
@@ -1198,37 +1345,39 @@ bad:
*/
DECLAREcpFunc(cpSeparate2SeparateByRow)
{
- tsize_t scanlinesize = TIFFScanlineSize(in);
- tdata_t buf;
- uint32_t row;
- tsample_t s;
-
- (void) imagewidth;
- buf = limitMalloc(scanlinesize);
- if (!buf)
- return 0;
- _TIFFmemset(buf, 0, scanlinesize);
- for (s = 0; s < spp; s++) {
- for (row = 0; row < imagelength; row++) {
- if (TIFFReadScanline(in, buf, row, s) < 0 && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read scanline %"PRIu32,
- row);
- goto bad;
- }
- if (TIFFWriteScanline(out, buf, row, s) < 0) {
- TIFFError(TIFFFileName(out),
- "Error, can't write scanline %"PRIu32,
- row);
- goto bad;
- }
- }
- }
- _TIFFfree(buf);
- return 1;
+ tsize_t scanlinesize = TIFFScanlineSize(in);
+ tdata_t buf;
+ uint32_t row;
+ tsample_t s;
+
+ (void)imagewidth;
+ buf = limitMalloc(scanlinesize);
+ if (!buf)
+ return 0;
+ _TIFFmemset(buf, 0, scanlinesize);
+ for (s = 0; s < spp; s++)
+ {
+ for (row = 0; row < imagelength; row++)
+ {
+ if (TIFFReadScanline(in, buf, row, s) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read scanline %" PRIu32, row);
+ goto bad;
+ }
+ if (TIFFWriteScanline(out, buf, row, s) < 0)
+ {
+ TIFFError(TIFFFileName(out),
+ "Error, can't write scanline %" PRIu32, row);
+ goto bad;
+ }
+ }
+ }
+ _TIFFfree(buf);
+ return 1;
bad:
- _TIFFfree(buf);
- return 0;
+ _TIFFfree(buf);
+ return 0;
}
/*
@@ -1236,62 +1385,68 @@ bad:
*/
DECLAREcpFunc(cpContig2SeparateByRow)
{
- tsize_t scanlinesizein = TIFFScanlineSize(in);
- tsize_t scanlinesizeout = TIFFScanlineSize(out);
- tdata_t inbuf;
- tdata_t outbuf;
- register uint8_t *inp, *outp;
- register uint32_t n;
- uint32_t row;
- tsample_t s;
- uint16_t bps = 0;
-
- (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
- if( bps != 8 )
+ tsize_t scanlinesizein = TIFFScanlineSize(in);
+ tsize_t scanlinesizeout = TIFFScanlineSize(out);
+ tdata_t inbuf;
+ tdata_t outbuf;
+ register uint8_t *inp, *outp;
+ register uint32_t n;
+ uint32_t row;
+ tsample_t s;
+ uint16_t bps = 0;
+
+ (void)TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
+ if (bps != 8)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can only handle BitsPerSample=8 in %s",
+ "cpContig2SeparateByRow");
+ return 0;
+ }
+
+ inbuf = limitMalloc(scanlinesizein);
+ outbuf = limitMalloc(scanlinesizeout);
+ if (!inbuf || !outbuf)
+ goto bad;
+ _TIFFmemset(inbuf, 0, scanlinesizein);
+ _TIFFmemset(outbuf, 0, scanlinesizeout);
+ /* unpack channels */
+ for (s = 0; s < spp; s++)
+ {
+ for (row = 0; row < imagelength; row++)
{
- TIFFError(TIFFFileName(in),
- "Error, can only handle BitsPerSample=8 in %s",
- "cpContig2SeparateByRow");
- return 0;
+ if (TIFFReadScanline(in, inbuf, row, 0) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read scanline %" PRIu32, row);
+ goto bad;
+ }
+ inp = ((uint8_t *)inbuf) + s;
+ outp = (uint8_t *)outbuf;
+ for (n = imagewidth; n-- > 0;)
+ {
+ *outp++ = *inp;
+ inp += spp;
+ }
+ if (TIFFWriteScanline(out, outbuf, row, s) < 0)
+ {
+ TIFFError(TIFFFileName(out),
+ "Error, can't write scanline %" PRIu32, row);
+ goto bad;
+ }
}
-
- inbuf = limitMalloc(scanlinesizein);
- outbuf = limitMalloc(scanlinesizeout);
- if (!inbuf || !outbuf)
- goto bad;
- _TIFFmemset(inbuf, 0, scanlinesizein);
- _TIFFmemset(outbuf, 0, scanlinesizeout);
- /* unpack channels */
- for (s = 0; s < spp; s++) {
- for (row = 0; row < imagelength; row++) {
- if (TIFFReadScanline(in, inbuf, row, 0) < 0
- && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read scanline %"PRIu32,
- row);
- goto bad;
- }
- inp = ((uint8_t*)inbuf) + s;
- outp = (uint8_t*)outbuf;
- for (n = imagewidth; n-- > 0;) {
- *outp++ = *inp;
- inp += spp;
- }
- if (TIFFWriteScanline(out, outbuf, row, s) < 0) {
- TIFFError(TIFFFileName(out),
- "Error, can't write scanline %"PRIu32,
- row);
- goto bad;
- }
- }
- }
- if (inbuf) _TIFFfree(inbuf);
- if (outbuf) _TIFFfree(outbuf);
- return 1;
+ }
+ if (inbuf)
+ _TIFFfree(inbuf);
+ if (outbuf)
+ _TIFFfree(outbuf);
+ return 1;
bad:
- if (inbuf) _TIFFfree(inbuf);
- if (outbuf) _TIFFfree(outbuf);
- return 0;
+ if (inbuf)
+ _TIFFfree(inbuf);
+ if (outbuf)
+ _TIFFfree(outbuf);
+ return 0;
}
/*
@@ -1299,559 +1454,597 @@ bad:
*/
DECLAREcpFunc(cpSeparate2ContigByRow)
{
- tsize_t scanlinesizein = TIFFScanlineSize(in);
- tsize_t scanlinesizeout = TIFFScanlineSize(out);
- tdata_t inbuf;
- tdata_t outbuf;
- register uint8_t *inp, *outp;
- register uint32_t n;
- uint32_t row;
- tsample_t s;
- uint16_t bps = 0;
-
- (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
- if( bps != 8 )
+ tsize_t scanlinesizein = TIFFScanlineSize(in);
+ tsize_t scanlinesizeout = TIFFScanlineSize(out);
+ tdata_t inbuf;
+ tdata_t outbuf;
+ register uint8_t *inp, *outp;
+ register uint32_t n;
+ uint32_t row;
+ tsample_t s;
+ uint16_t bps = 0;
+
+ (void)TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
+ if (bps != 8)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can only handle BitsPerSample=8 in %s",
+ "cpSeparate2ContigByRow");
+ return 0;
+ }
+
+ inbuf = limitMalloc(scanlinesizein);
+ outbuf = limitMalloc(scanlinesizeout);
+ if (!inbuf || !outbuf)
+ goto bad;
+ _TIFFmemset(inbuf, 0, scanlinesizein);
+ _TIFFmemset(outbuf, 0, scanlinesizeout);
+ for (row = 0; row < imagelength; row++)
+ {
+ /* merge channels */
+ for (s = 0; s < spp; s++)
{
- TIFFError(TIFFFileName(in),
- "Error, can only handle BitsPerSample=8 in %s",
- "cpSeparate2ContigByRow");
- return 0;
- }
-
- inbuf = limitMalloc(scanlinesizein);
- outbuf = limitMalloc(scanlinesizeout);
- if (!inbuf || !outbuf)
+ if (TIFFReadScanline(in, inbuf, row, s) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read scanline %" PRIu32, row);
goto bad;
- _TIFFmemset(inbuf, 0, scanlinesizein);
- _TIFFmemset(outbuf, 0, scanlinesizeout);
- for (row = 0; row < imagelength; row++) {
- /* merge channels */
- for (s = 0; s < spp; s++) {
- if (TIFFReadScanline(in, inbuf, row, s) < 0
- && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read scanline %"PRIu32,
- row);
- goto bad;
- }
- inp = (uint8_t*)inbuf;
- outp = ((uint8_t*)outbuf) + s;
- for (n = imagewidth; n-- > 0;) {
- *outp = *inp++;
- outp += spp;
- }
- }
- if (TIFFWriteScanline(out, outbuf, row, 0) < 0) {
- TIFFError(TIFFFileName(out),
- "Error, can't write scanline %"PRIu32,
- row);
- goto bad;
- }
- }
- if (inbuf) _TIFFfree(inbuf);
- if (outbuf) _TIFFfree(outbuf);
- return 1;
+ }
+ inp = (uint8_t *)inbuf;
+ outp = ((uint8_t *)outbuf) + s;
+ for (n = imagewidth; n-- > 0;)
+ {
+ *outp = *inp++;
+ outp += spp;
+ }
+ }
+ if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
+ {
+ TIFFError(TIFFFileName(out), "Error, can't write scanline %" PRIu32,
+ row);
+ goto bad;
+ }
+ }
+ if (inbuf)
+ _TIFFfree(inbuf);
+ if (outbuf)
+ _TIFFfree(outbuf);
+ return 1;
bad:
- if (inbuf) _TIFFfree(inbuf);
- if (outbuf) _TIFFfree(outbuf);
- return 0;
+ if (inbuf)
+ _TIFFfree(inbuf);
+ if (outbuf)
+ _TIFFfree(outbuf);
+ return 0;
}
-static void
-cpStripToTile(uint8_t* out, uint8_t* in,
- uint32_t rows, uint32_t cols, int outskew, int64_t inskew)
+static void cpStripToTile(uint8_t *out, uint8_t *in, uint32_t rows,
+ uint32_t cols, int outskew, int64_t inskew)
{
- while (rows-- > 0) {
- uint32_t j = cols;
- while (j-- > 0)
- *out++ = *in++;
- out += outskew;
- in += inskew;
- }
+ while (rows-- > 0)
+ {
+ uint32_t j = cols;
+ while (j-- > 0)
+ *out++ = *in++;
+ out += outskew;
+ in += inskew;
+ }
}
-static void
-cpContigBufToSeparateBuf(uint8_t* out, uint8_t* in,
- uint32_t rows, uint32_t cols, int outskew, int inskew, tsample_t spp,
- int bytes_per_sample )
+static void cpContigBufToSeparateBuf(uint8_t *out, uint8_t *in, uint32_t rows,
+ uint32_t cols, int outskew, int inskew,
+ tsample_t spp, int bytes_per_sample)
{
- while (rows-- > 0) {
- uint32_t j = cols;
- while (j-- > 0)
- {
- int n = bytes_per_sample;
-
- while( n-- ) {
- *out++ = *in++;
- }
- in += (spp-1) * bytes_per_sample;
- }
- out += outskew;
- in += inskew;
- }
+ while (rows-- > 0)
+ {
+ uint32_t j = cols;
+ while (j-- > 0)
+ {
+ int n = bytes_per_sample;
+
+ while (n--)
+ {
+ *out++ = *in++;
+ }
+ in += (spp - 1) * bytes_per_sample;
+ }
+ out += outskew;
+ in += inskew;
+ }
}
-static void
-cpSeparateBufToContigBuf(uint8_t* out, uint8_t* in,
- uint32_t rows, uint32_t cols, int outskew, int inskew, tsample_t spp,
- int bytes_per_sample)
+static void cpSeparateBufToContigBuf(uint8_t *out, uint8_t *in, uint32_t rows,
+ uint32_t cols, int outskew, int inskew,
+ tsample_t spp, int bytes_per_sample)
{
- while (rows-- > 0) {
- uint32_t j = cols;
- while (j-- > 0) {
- int n = bytes_per_sample;
-
- while( n-- ) {
- *out++ = *in++;
- }
- out += (spp-1)*bytes_per_sample;
- }
- out += outskew;
- in += inskew;
- }
+ while (rows-- > 0)
+ {
+ uint32_t j = cols;
+ while (j-- > 0)
+ {
+ int n = bytes_per_sample;
+
+ while (n--)
+ {
+ *out++ = *in++;
+ }
+ out += (spp - 1) * bytes_per_sample;
+ }
+ out += outskew;
+ in += inskew;
+ }
}
-static int
-cpImage(TIFF* in, TIFF* out, readFunc fin, writeFunc fout,
- uint32_t imagelength, uint32_t imagewidth, tsample_t spp)
+static int cpImage(TIFF *in, TIFF *out, readFunc fin, writeFunc fout,
+ uint32_t imagelength, uint32_t imagewidth, tsample_t spp)
{
- int status = 0;
- tdata_t buf = NULL;
- tsize_t scanlinesize = TIFFRasterScanlineSize(in);
- tsize_t bytes = scanlinesize * (tsize_t)imagelength;
- /*
- * XXX: Check for integer overflow.
- */
- if (scanlinesize
- && imagelength
- && bytes / (tsize_t)imagelength == scanlinesize) {
- buf = limitMalloc(bytes);
- if (buf) {
- if ((*fin)(in, (uint8_t*)buf, imagelength,
- imagewidth, spp)) {
- status = (*fout)(out, (uint8_t*)buf,
- imagelength, imagewidth, spp);
- }
- _TIFFfree(buf);
- } else {
- TIFFError(TIFFFileName(in),
- "Error, can't allocate space for image buffer");
- }
- } else {
- TIFFError(TIFFFileName(in), "Error, no space for image buffer");
- }
-
- return status;
+ int status = 0;
+ tdata_t buf = NULL;
+ tsize_t scanlinesize = TIFFRasterScanlineSize(in);
+ tsize_t bytes = scanlinesize * (tsize_t)imagelength;
+ /*
+ * XXX: Check for integer overflow.
+ */
+ if (scanlinesize && imagelength &&
+ bytes / (tsize_t)imagelength == scanlinesize)
+ {
+ buf = limitMalloc(bytes);
+ if (buf)
+ {
+ if ((*fin)(in, (uint8_t *)buf, imagelength, imagewidth, spp))
+ {
+ status =
+ (*fout)(out, (uint8_t *)buf, imagelength, imagewidth, spp);
+ }
+ _TIFFfree(buf);
+ }
+ else
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't allocate space for image buffer");
+ }
+ }
+ else
+ {
+ TIFFError(TIFFFileName(in), "Error, no space for image buffer");
+ }
+
+ return status;
}
DECLAREreadFunc(readContigStripsIntoBuffer)
{
- tsize_t scanlinesize = TIFFScanlineSize(in);
- uint8_t* bufp = buf;
- uint32_t row;
-
- (void) imagewidth; (void) spp;
- for (row = 0; row < imagelength; row++) {
- if (TIFFReadScanline(in, (tdata_t) bufp, row, 0) < 0
- && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read scanline %"PRIu32,
- row);
- return 0;
- }
- bufp += scanlinesize;
- }
-
- return 1;
+ tsize_t scanlinesize = TIFFScanlineSize(in);
+ uint8_t *bufp = buf;
+ uint32_t row;
+
+ (void)imagewidth;
+ (void)spp;
+ for (row = 0; row < imagelength; row++)
+ {
+ if (TIFFReadScanline(in, (tdata_t)bufp, row, 0) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in), "Error, can't read scanline %" PRIu32,
+ row);
+ return 0;
+ }
+ bufp += scanlinesize;
+ }
+
+ return 1;
}
DECLAREreadFunc(readSeparateStripsIntoBuffer)
{
- int status = 1;
- tsize_t scanlinesize = TIFFScanlineSize(in);
- tdata_t scanline;
- if (!scanlinesize)
- return 0;
-
- scanline = limitMalloc(scanlinesize);
- if (!scanline)
- return 0;
- _TIFFmemset(scanline, 0, scanlinesize);
- (void) imagewidth;
- if (scanline) {
- uint8_t* bufp = (uint8_t*) buf;
- uint32_t row;
- tsample_t s;
- for (row = 0; row < imagelength; row++) {
- /* merge channels */
- for (s = 0; s < spp; s++) {
- uint8_t* bp = bufp + s;
- tsize_t n = scanlinesize;
- uint8_t* sbuf = scanline;
-
- if (TIFFReadScanline(in, scanline, row, s) < 0
- && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read scanline %"PRIu32,
- row);
- status = 0;
- goto done;
- }
- while (n-- > 0)
- *bp = *sbuf++, bp += spp;
- }
- bufp += scanlinesize * spp;
- }
- }
+ int status = 1;
+ tsize_t scanlinesize = TIFFScanlineSize(in);
+ tdata_t scanline;
+ if (!scanlinesize)
+ return 0;
+
+ scanline = limitMalloc(scanlinesize);
+ if (!scanline)
+ return 0;
+ _TIFFmemset(scanline, 0, scanlinesize);
+ (void)imagewidth;
+ if (scanline)
+ {
+ uint8_t *bufp = (uint8_t *)buf;
+ uint32_t row;
+ tsample_t s;
+ for (row = 0; row < imagelength; row++)
+ {
+ /* merge channels */
+ for (s = 0; s < spp; s++)
+ {
+ uint8_t *bp = bufp + s;
+ tsize_t n = scanlinesize;
+ uint8_t *sbuf = scanline;
+
+ if (TIFFReadScanline(in, scanline, row, s) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read scanline %" PRIu32, row);
+ status = 0;
+ goto done;
+ }
+ while (n-- > 0)
+ *bp = *sbuf++, bp += spp;
+ }
+ bufp += scanlinesize * spp;
+ }
+ }
done:
- _TIFFfree(scanline);
- return status;
+ _TIFFfree(scanline);
+ return status;
}
DECLAREreadFunc(readContigTilesIntoBuffer)
{
- int status = 1;
- tsize_t tilesize = TIFFTileSize(in);
- tdata_t tilebuf;
- uint32_t imagew = TIFFScanlineSize(in);
- uint32_t tilew = TIFFTileRowSize(in);
- int64_t iskew = (int64_t)imagew - (int64_t)tilew;
- uint8_t* bufp = (uint8_t*) buf;
- uint32_t tw, tl;
- uint32_t row;
-
- (void) spp;
- tilebuf = limitMalloc(tilesize);
- if (tilebuf == 0)
- return 0;
- _TIFFmemset(tilebuf, 0, tilesize);
- (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
- (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
-
- for (row = 0; row < imagelength; row += tl) {
- uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
- uint32_t colb = 0;
- uint32_t col;
-
- for (col = 0; col < imagewidth && colb < imagew; col += tw) {
- if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0
- && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read tile at %"PRIu32" %"PRIu32,
- col, row);
- status = 0;
- goto done;
- }
- if (colb > iskew) {
- uint32_t width = imagew - colb;
- uint32_t oskew = tilew - width;
- cpStripToTile(bufp + colb,
- tilebuf, nrow, width,
- oskew + iskew, oskew );
- } else
- cpStripToTile(bufp + colb,
- tilebuf, nrow, tilew,
- iskew, 0);
- colb += tilew;
- }
- bufp += imagew * nrow;
- }
+ int status = 1;
+ tsize_t tilesize = TIFFTileSize(in);
+ tdata_t tilebuf;
+ uint32_t imagew = TIFFScanlineSize(in);
+ uint32_t tilew = TIFFTileRowSize(in);
+ int64_t iskew = (int64_t)imagew - (int64_t)tilew;
+ uint8_t *bufp = (uint8_t *)buf;
+ uint32_t tw, tl;
+ uint32_t row;
+
+ (void)spp;
+ tilebuf = limitMalloc(tilesize);
+ if (tilebuf == 0)
+ return 0;
+ _TIFFmemset(tilebuf, 0, tilesize);
+ (void)TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
+ (void)TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
+
+ for (row = 0; row < imagelength; row += tl)
+ {
+ uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
+ uint32_t colb = 0;
+ uint32_t col;
+
+ for (col = 0; col < imagewidth && colb < imagew; col += tw)
+ {
+ if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read tile at %" PRIu32 " %" PRIu32, col,
+ row);
+ status = 0;
+ goto done;
+ }
+ if (colb > iskew)
+ {
+ uint32_t width = imagew - colb;
+ uint32_t oskew = tilew - width;
+ cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew,
+ oskew);
+ }
+ else
+ cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0);
+ colb += tilew;
+ }
+ bufp += imagew * nrow;
+ }
done:
- _TIFFfree(tilebuf);
- return status;
+ _TIFFfree(tilebuf);
+ return status;
}
DECLAREreadFunc(readSeparateTilesIntoBuffer)
{
- int status = 1;
- uint32_t imagew = TIFFRasterScanlineSize(in);
- uint32_t tilew = TIFFTileRowSize(in);
- int iskew;
- tsize_t tilesize = TIFFTileSize(in);
- tdata_t tilebuf;
- uint8_t* bufp = (uint8_t*) buf;
- uint32_t tw, tl;
- uint32_t row;
- uint16_t bps = 0, bytes_per_sample;
-
- if (tilew && spp > (INT_MAX / tilew))
- {
- TIFFError(TIFFFileName(in), "Error, cannot handle that much samples per tile row (Tile Width * Samples/Pixel)");
- return 0;
- }
- iskew = imagew - tilew*spp;
- tilebuf = limitMalloc(tilesize);
- if (tilebuf == 0)
- return 0;
- _TIFFmemset(tilebuf, 0, tilesize);
- (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
- (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
- (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
- if( bps == 0 )
+ int status = 1;
+ uint32_t imagew = TIFFRasterScanlineSize(in);
+ uint32_t tilew = TIFFTileRowSize(in);
+ int iskew;
+ tsize_t tilesize = TIFFTileSize(in);
+ tdata_t tilebuf;
+ uint8_t *bufp = (uint8_t *)buf;
+ uint32_t tw, tl;
+ uint32_t row;
+ uint16_t bps = 0, bytes_per_sample;
+
+ if (tilew && spp > (INT_MAX / tilew))
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, cannot handle that much samples per tile row (Tile "
+ "Width * Samples/Pixel)");
+ return 0;
+ }
+ iskew = imagew - tilew * spp;
+ tilebuf = limitMalloc(tilesize);
+ if (tilebuf == 0)
+ return 0;
+ _TIFFmemset(tilebuf, 0, tilesize);
+ (void)TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
+ (void)TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
+ (void)TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
+ if (bps == 0)
+ {
+ TIFFError(TIFFFileName(in), "Error, cannot read BitsPerSample");
+ status = 0;
+ goto done;
+ }
+ if ((bps % 8) != 0)
+ {
+ TIFFError(
+ TIFFFileName(in),
+ "Error, cannot handle BitsPerSample that is not a multiple of 8");
+ status = 0;
+ goto done;
+ }
+ bytes_per_sample = bps / 8;
+
+ for (row = 0; row < imagelength; row += tl)
+ {
+ uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
+ uint32_t colb = 0;
+ uint32_t col;
+
+ for (col = 0; col < imagewidth; col += tw)
{
- TIFFError(TIFFFileName(in), "Error, cannot read BitsPerSample");
- status = 0;
- goto done;
- }
- if( (bps % 8) != 0 )
- {
- TIFFError(TIFFFileName(in), "Error, cannot handle BitsPerSample that is not a multiple of 8");
- status = 0;
- goto done;
+ tsample_t s;
+
+ for (s = 0; s < spp; s++)
+ {
+ if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read tile at %" PRIu32 " %" PRIu32
+ ", "
+ "sample %" PRIu16,
+ col, row, s);
+ status = 0;
+ goto done;
+ }
+ /*
+ * Tile is clipped horizontally. Calculate
+ * visible portion and skewing factors.
+ */
+ if (colb + tilew * spp > imagew)
+ {
+ uint32_t width = imagew - colb;
+ int oskew = tilew * spp - width;
+ cpSeparateBufToContigBuf(
+ bufp + colb + s * bytes_per_sample, tilebuf, nrow,
+ width / (spp * bytes_per_sample), oskew + iskew,
+ oskew / spp, spp, bytes_per_sample);
+ }
+ else
+ cpSeparateBufToContigBuf(bufp + colb + s * bytes_per_sample,
+ tilebuf, nrow, tw, iskew, 0, spp,
+ bytes_per_sample);
+ }
+ colb += tilew * spp;
}
- bytes_per_sample = bps/8;
-
- for (row = 0; row < imagelength; row += tl) {
- uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
- uint32_t colb = 0;
- uint32_t col;
-
- for (col = 0; col < imagewidth; col += tw) {
- tsample_t s;
-
- for (s = 0; s < spp; s++) {
- if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0
- && !ignore) {
- TIFFError(TIFFFileName(in),
- "Error, can't read tile at %"PRIu32" %"PRIu32", "
- "sample %"PRIu16,
- col, row, s);
- status = 0;
- goto done;
- }
- /*
- * Tile is clipped horizontally. Calculate
- * visible portion and skewing factors.
- */
- if (colb + tilew*spp > imagew) {
- uint32_t width = imagew - colb;
- int oskew = tilew*spp - width;
- cpSeparateBufToContigBuf(
- bufp+colb+s*bytes_per_sample,
- tilebuf, nrow,
- width/(spp*bytes_per_sample),
- oskew + iskew,
- oskew/spp, spp,
- bytes_per_sample);
- } else
- cpSeparateBufToContigBuf(
- bufp+colb+s*bytes_per_sample,
- tilebuf, nrow, tw,
- iskew, 0, spp,
- bytes_per_sample);
- }
- colb += tilew*spp;
- }
- bufp += imagew * nrow;
- }
+ bufp += imagew * nrow;
+ }
done:
- _TIFFfree(tilebuf);
- return status;
+ _TIFFfree(tilebuf);
+ return status;
}
DECLAREwriteFunc(writeBufferToContigStrips)
{
- uint32_t row, rowsperstrip;
- tstrip_t strip = 0;
-
- (void) imagewidth; (void) spp;
- (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
- for (row = 0; row < imagelength; row += rowsperstrip) {
- uint32_t nrows = (row + rowsperstrip > imagelength) ?
- imagelength-row : rowsperstrip;
- tsize_t stripsize = TIFFVStripSize(out, nrows);
- if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) {
- TIFFError(TIFFFileName(out),
- "Error, can't write strip %"PRIu32, strip - 1u);
- return 0;
- }
- buf += stripsize;
- }
- return 1;
+ uint32_t row, rowsperstrip;
+ tstrip_t strip = 0;
+
+ (void)imagewidth;
+ (void)spp;
+ (void)TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
+ for (row = 0; row < imagelength; row += rowsperstrip)
+ {
+ uint32_t nrows = (row + rowsperstrip > imagelength) ? imagelength - row
+ : rowsperstrip;
+ tsize_t stripsize = TIFFVStripSize(out, nrows);
+ if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0)
+ {
+ TIFFError(TIFFFileName(out), "Error, can't write strip %" PRIu32,
+ strip - 1u);
+ return 0;
+ }
+ buf += stripsize;
+ }
+ return 1;
}
DECLAREwriteFunc(writeBufferToSeparateStrips)
{
- uint32_t rowsize = imagewidth * spp;
- uint32_t rowsperstrip;
- tsize_t stripsize = TIFFStripSize(out);
- tdata_t obuf;
- tstrip_t strip = 0;
- tsample_t s;
- uint16_t bps = 0, bytes_per_sample;
-
- obuf = limitMalloc(stripsize);
- if (obuf == NULL)
- return (0);
- _TIFFmemset(obuf, 0, stripsize);
- (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
- (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
- if( bps == 0 )
- {
- TIFFError(TIFFFileName(out), "Error, cannot read BitsPerSample");
- _TIFFfree(obuf);
- return 0;
- }
- if( (bps % 8) != 0 )
+ uint32_t rowsize = imagewidth * spp;
+ uint32_t rowsperstrip;
+ tsize_t stripsize = TIFFStripSize(out);
+ tdata_t obuf;
+ tstrip_t strip = 0;
+ tsample_t s;
+ uint16_t bps = 0, bytes_per_sample;
+
+ obuf = limitMalloc(stripsize);
+ if (obuf == NULL)
+ return (0);
+ _TIFFmemset(obuf, 0, stripsize);
+ (void)TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
+ (void)TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
+ if (bps == 0)
+ {
+ TIFFError(TIFFFileName(out), "Error, cannot read BitsPerSample");
+ _TIFFfree(obuf);
+ return 0;
+ }
+ if ((bps % 8) != 0)
+ {
+ TIFFError(
+ TIFFFileName(out),
+ "Error, cannot handle BitsPerSample that is not a multiple of 8");
+ _TIFFfree(obuf);
+ return 0;
+ }
+ bytes_per_sample = bps / 8;
+ for (s = 0; s < spp; s++)
+ {
+ uint32_t row;
+ for (row = 0; row < imagelength; row += rowsperstrip)
{
- TIFFError(TIFFFileName(out), "Error, cannot handle BitsPerSample that is not a multiple of 8");
- _TIFFfree(obuf);
- return 0;
+ uint32_t nrows = (row + rowsperstrip > imagelength)
+ ? imagelength - row
+ : rowsperstrip;
+ tsize_t stripsize = TIFFVStripSize(out, nrows);
+
+ cpContigBufToSeparateBuf(obuf, (uint8_t *)buf + row * rowsize + s,
+ nrows, imagewidth, 0, 0, spp,
+ bytes_per_sample);
+ if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0)
+ {
+ TIFFError(TIFFFileName(out),
+ "Error, can't write strip %" PRIu32, strip - 1u);
+ _TIFFfree(obuf);
+ return 0;
+ }
}
- bytes_per_sample = bps/8;
- for (s = 0; s < spp; s++) {
- uint32_t row;
- for (row = 0; row < imagelength; row += rowsperstrip) {
- uint32_t nrows = (row + rowsperstrip > imagelength) ?
- imagelength-row : rowsperstrip;
- tsize_t stripsize = TIFFVStripSize(out, nrows);
-
- cpContigBufToSeparateBuf(
- obuf, (uint8_t*) buf + row * rowsize + s,
- nrows, imagewidth, 0, 0, spp, bytes_per_sample);
- if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) {
- TIFFError(TIFFFileName(out),
- "Error, can't write strip %"PRIu32,
- strip - 1u);
- _TIFFfree(obuf);
- return 0;
- }
- }
- }
- _TIFFfree(obuf);
- return 1;
-
+ }
+ _TIFFfree(obuf);
+ return 1;
}
DECLAREwriteFunc(writeBufferToContigTiles)
{
- uint32_t imagew = TIFFScanlineSize(out);
- uint32_t tilew = TIFFTileRowSize(out);
- int iskew = imagew - tilew;
- tsize_t tilesize = TIFFTileSize(out);
- tdata_t obuf;
- uint8_t* bufp = (uint8_t*) buf;
- uint32_t tl, tw;
- uint32_t row;
-
- (void) spp;
-
- obuf = limitMalloc(TIFFTileSize(out));
- if (obuf == NULL)
- return 0;
- _TIFFmemset(obuf, 0, tilesize);
- (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
- (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
- for (row = 0; row < imagelength; row += tilelength) {
- uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
- uint32_t colb = 0;
- uint32_t col;
-
- for (col = 0; col < imagewidth && colb < imagew; col += tw) {
- /*
- * Tile is clipped horizontally. Calculate
- * visible portion and skewing factors.
- */
- if (colb + tilew > imagew) {
- uint32_t width = imagew - colb;
- int oskew = tilew - width;
- cpStripToTile(obuf, bufp + colb, nrow, width,
- oskew, oskew + iskew);
- } else
- cpStripToTile(obuf, bufp + colb, nrow, tilew,
- 0, iskew);
- if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) {
- TIFFError(TIFFFileName(out),
- "Error, can't write tile at %"PRIu32" %"PRIu32,
- col, row);
- _TIFFfree(obuf);
- return 0;
- }
- colb += tilew;
- }
- bufp += nrow * imagew;
- }
- _TIFFfree(obuf);
- return 1;
+ uint32_t imagew = TIFFScanlineSize(out);
+ uint32_t tilew = TIFFTileRowSize(out);
+ int iskew = imagew - tilew;
+ tsize_t tilesize = TIFFTileSize(out);
+ tdata_t obuf;
+ uint8_t *bufp = (uint8_t *)buf;
+ uint32_t tl, tw;
+ uint32_t row;
+
+ (void)spp;
+
+ obuf = limitMalloc(TIFFTileSize(out));
+ if (obuf == NULL)
+ return 0;
+ _TIFFmemset(obuf, 0, tilesize);
+ (void)TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
+ (void)TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
+ for (row = 0; row < imagelength; row += tilelength)
+ {
+ uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
+ uint32_t colb = 0;
+ uint32_t col;
+
+ for (col = 0; col < imagewidth && colb < imagew; col += tw)
+ {
+ /*
+ * Tile is clipped horizontally. Calculate
+ * visible portion and skewing factors.
+ */
+ if (colb + tilew > imagew)
+ {
+ uint32_t width = imagew - colb;
+ int oskew = tilew - width;
+ cpStripToTile(obuf, bufp + colb, nrow, width, oskew,
+ oskew + iskew);
+ }
+ else
+ cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew);
+ if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0)
+ {
+ TIFFError(TIFFFileName(out),
+ "Error, can't write tile at %" PRIu32 " %" PRIu32,
+ col, row);
+ _TIFFfree(obuf);
+ return 0;
+ }
+ colb += tilew;
+ }
+ bufp += nrow * imagew;
+ }
+ _TIFFfree(obuf);
+ return 1;
}
DECLAREwriteFunc(writeBufferToSeparateTiles)
{
- uint32_t imagew = TIFFScanlineSize(out);
- tsize_t tilew = TIFFTileRowSize(out);
- uint32_t iimagew = TIFFRasterScanlineSize(out);
- int iskew = iimagew - tilew*spp;
- tsize_t tilesize = TIFFTileSize(out);
- tdata_t obuf;
- uint8_t* bufp = (uint8_t*) buf;
- uint32_t tl, tw;
- uint32_t row;
- uint16_t bps = 0, bytes_per_sample;
-
- obuf = limitMalloc(TIFFTileSize(out));
- if (obuf == NULL)
- return 0;
- _TIFFmemset(obuf, 0, tilesize);
- (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
- (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
- (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
- if( bps == 0 )
+ uint32_t imagew = TIFFScanlineSize(out);
+ tsize_t tilew = TIFFTileRowSize(out);
+ uint32_t iimagew = TIFFRasterScanlineSize(out);
+ int iskew = iimagew - tilew * spp;
+ tsize_t tilesize = TIFFTileSize(out);
+ tdata_t obuf;
+ uint8_t *bufp = (uint8_t *)buf;
+ uint32_t tl, tw;
+ uint32_t row;
+ uint16_t bps = 0, bytes_per_sample;
+
+ obuf = limitMalloc(TIFFTileSize(out));
+ if (obuf == NULL)
+ return 0;
+ _TIFFmemset(obuf, 0, tilesize);
+ (void)TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
+ (void)TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
+ (void)TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
+ if (bps == 0)
+ {
+ TIFFError(TIFFFileName(out), "Error, cannot read BitsPerSample");
+ _TIFFfree(obuf);
+ return 0;
+ }
+ if ((bps % 8) != 0)
+ {
+ TIFFError(
+ TIFFFileName(out),
+ "Error, cannot handle BitsPerSample that is not a multiple of 8");
+ _TIFFfree(obuf);
+ return 0;
+ }
+ bytes_per_sample = bps / 8;
+
+ for (row = 0; row < imagelength; row += tl)
+ {
+ uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
+ uint32_t colb = 0;
+ uint32_t col;
+
+ for (col = 0; col < imagewidth; col += tw)
{
- TIFFError(TIFFFileName(out), "Error, cannot read BitsPerSample");
- _TIFFfree(obuf);
- return 0;
- }
- if( (bps % 8) != 0 )
- {
- TIFFError(TIFFFileName(out), "Error, cannot handle BitsPerSample that is not a multiple of 8");
- _TIFFfree(obuf);
- return 0;
+ tsample_t s;
+ for (s = 0; s < spp; s++)
+ {
+ /*
+ * Tile is clipped horizontally. Calculate
+ * visible portion and skewing factors.
+ */
+ if (colb + tilew > imagew)
+ {
+ uint32_t width = (imagew - colb);
+ int oskew = tilew - width;
+
+ cpContigBufToSeparateBuf(obuf, bufp + (colb * spp) + s,
+ nrow, width / bytes_per_sample,
+ oskew, (oskew * spp) + iskew, spp,
+ bytes_per_sample);
+ }
+ else
+ cpContigBufToSeparateBuf(obuf, bufp + (colb * spp) + s,
+ nrow, tilewidth, 0, iskew, spp,
+ bytes_per_sample);
+ if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0)
+ {
+ TIFFError(TIFFFileName(out),
+ "Error, can't write tile at %" PRIu32 " %" PRIu32
+ " sample %" PRIu16,
+ col, row, s);
+ _TIFFfree(obuf);
+ return 0;
+ }
+ }
+ colb += tilew;
}
- bytes_per_sample = bps/8;
-
- for (row = 0; row < imagelength; row += tl) {
- uint32_t nrow = (row + tl > imagelength) ? imagelength - row : tl;
- uint32_t colb = 0;
- uint32_t col;
-
- for (col = 0; col < imagewidth; col += tw) {
- tsample_t s;
- for (s = 0; s < spp; s++) {
- /*
- * Tile is clipped horizontally. Calculate
- * visible portion and skewing factors.
- */
- if (colb + tilew > imagew) {
- uint32_t width = (imagew - colb);
- int oskew = tilew - width;
-
- cpContigBufToSeparateBuf(obuf,
- bufp + (colb*spp) + s,
- nrow, width/bytes_per_sample,
- oskew, (oskew*spp)+iskew, spp,
- bytes_per_sample);
- } else
- cpContigBufToSeparateBuf(obuf,
- bufp + (colb*spp) + s,
- nrow, tilewidth,
- 0, iskew, spp,
- bytes_per_sample);
- if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) {
- TIFFError(TIFFFileName(out),
- "Error, can't write tile at %"PRIu32" %"PRIu32
- " sample %"PRIu16,
- col, row, s);
- _TIFFfree(obuf);
- return 0;
- }
- }
- colb += tilew;
- }
- bufp += nrow * iimagew;
- }
- _TIFFfree(obuf);
- return 1;
+ bufp += nrow * iimagew;
+ }
+ _TIFFfree(obuf);
+ return 1;
}
/*
@@ -1859,10 +2052,8 @@ DECLAREwriteFunc(writeBufferToSeparateTiles)
*/
DECLAREcpFunc(cpContigStrips2ContigTiles)
{
- return cpImage(in, out,
- readContigStripsIntoBuffer,
- writeBufferToContigTiles,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readContigStripsIntoBuffer,
+ writeBufferToContigTiles, imagelength, imagewidth, spp);
}
/*
@@ -1870,10 +2061,8 @@ DECLAREcpFunc(cpContigStrips2ContigTiles)
*/
DECLAREcpFunc(cpContigStrips2SeparateTiles)
{
- return cpImage(in, out,
- readContigStripsIntoBuffer,
- writeBufferToSeparateTiles,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readContigStripsIntoBuffer,
+ writeBufferToSeparateTiles, imagelength, imagewidth, spp);
}
/*
@@ -1881,10 +2070,8 @@ DECLAREcpFunc(cpContigStrips2SeparateTiles)
*/
DECLAREcpFunc(cpSeparateStrips2ContigTiles)
{
- return cpImage(in, out,
- readSeparateStripsIntoBuffer,
- writeBufferToContigTiles,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readSeparateStripsIntoBuffer,
+ writeBufferToContigTiles, imagelength, imagewidth, spp);
}
/*
@@ -1892,10 +2079,8 @@ DECLAREcpFunc(cpSeparateStrips2ContigTiles)
*/
DECLAREcpFunc(cpSeparateStrips2SeparateTiles)
{
- return cpImage(in, out,
- readSeparateStripsIntoBuffer,
- writeBufferToSeparateTiles,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readSeparateStripsIntoBuffer,
+ writeBufferToSeparateTiles, imagelength, imagewidth, spp);
}
/*
@@ -1903,10 +2088,8 @@ DECLAREcpFunc(cpSeparateStrips2SeparateTiles)
*/
DECLAREcpFunc(cpContigTiles2ContigTiles)
{
- return cpImage(in, out,
- readContigTilesIntoBuffer,
- writeBufferToContigTiles,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigTiles,
+ imagelength, imagewidth, spp);
}
/*
@@ -1914,10 +2097,8 @@ DECLAREcpFunc(cpContigTiles2ContigTiles)
*/
DECLAREcpFunc(cpContigTiles2SeparateTiles)
{
- return cpImage(in, out,
- readContigTilesIntoBuffer,
- writeBufferToSeparateTiles,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readContigTilesIntoBuffer,
+ writeBufferToSeparateTiles, imagelength, imagewidth, spp);
}
/*
@@ -1925,10 +2106,8 @@ DECLAREcpFunc(cpContigTiles2SeparateTiles)
*/
DECLAREcpFunc(cpSeparateTiles2ContigTiles)
{
- return cpImage(in, out,
- readSeparateTilesIntoBuffer,
- writeBufferToContigTiles,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readSeparateTilesIntoBuffer,
+ writeBufferToContigTiles, imagelength, imagewidth, spp);
}
/*
@@ -1936,10 +2115,8 @@ DECLAREcpFunc(cpSeparateTiles2ContigTiles)
*/
DECLAREcpFunc(cpSeparateTiles2SeparateTiles)
{
- return cpImage(in, out,
- readSeparateTilesIntoBuffer,
- writeBufferToSeparateTiles,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readSeparateTilesIntoBuffer,
+ writeBufferToSeparateTiles, imagelength, imagewidth, spp);
}
/*
@@ -1947,10 +2124,8 @@ DECLAREcpFunc(cpSeparateTiles2SeparateTiles)
*/
DECLAREcpFunc(cpContigTiles2ContigStrips)
{
- return cpImage(in, out,
- readContigTilesIntoBuffer,
- writeBufferToContigStrips,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readContigTilesIntoBuffer,
+ writeBufferToContigStrips, imagelength, imagewidth, spp);
}
/*
@@ -1958,10 +2133,8 @@ DECLAREcpFunc(cpContigTiles2ContigStrips)
*/
DECLAREcpFunc(cpContigTiles2SeparateStrips)
{
- return cpImage(in, out,
- readContigTilesIntoBuffer,
- writeBufferToSeparateStrips,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readContigTilesIntoBuffer,
+ writeBufferToSeparateStrips, imagelength, imagewidth, spp);
}
/*
@@ -1969,10 +2142,8 @@ DECLAREcpFunc(cpContigTiles2SeparateStrips)
*/
DECLAREcpFunc(cpSeparateTiles2ContigStrips)
{
- return cpImage(in, out,
- readSeparateTilesIntoBuffer,
- writeBufferToContigStrips,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readSeparateTilesIntoBuffer,
+ writeBufferToContigStrips, imagelength, imagewidth, spp);
}
/*
@@ -1980,117 +2151,126 @@ DECLAREcpFunc(cpSeparateTiles2ContigStrips)
*/
DECLAREcpFunc(cpSeparateTiles2SeparateStrips)
{
- return cpImage(in, out,
- readSeparateTilesIntoBuffer,
- writeBufferToSeparateStrips,
- imagelength, imagewidth, spp);
+ return cpImage(in, out, readSeparateTilesIntoBuffer,
+ writeBufferToSeparateStrips, imagelength, imagewidth, spp);
}
/*
* Select the appropriate copy function to use.
*/
-static copyFunc
-pickCopyFunc(TIFF* in, TIFF* out, uint16_t bitspersample, uint16_t samplesperpixel)
+static copyFunc pickCopyFunc(TIFF *in, TIFF *out, uint16_t bitspersample,
+ uint16_t samplesperpixel)
{
- uint16_t shortv;
- uint32_t w, l, tw, tl;
- int bychunk;
-
- (void) TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &shortv);
- if (shortv != config && bitspersample != 8 && samplesperpixel > 1) {
- fprintf(stderr,
- "%s: Cannot handle different planar configuration w/ bits/sample != 8\n",
- TIFFFileName(in));
- return (NULL);
- }
- TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
- TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l);
- if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) {
- uint32_t irps = (uint32_t) -1L;
- TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps);
- /* if biased, force decoded copying to allow image subtraction */
- bychunk = !bias && (rowsperstrip == irps);
- }else{ /* either in or out is tiled */
- if (bias) {
- fprintf(stderr,
- "%s: Cannot handle tiled configuration w/bias image\n",
- TIFFFileName(in));
- return (NULL);
- }
- if (TIFFIsTiled(out)) {
- if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw))
- tw = w;
- if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl))
- tl = l;
- bychunk = (tw == tilewidth && tl == tilelength);
- } else { /* out's not, so in must be tiled */
- TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
- TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
- bychunk = (tw == w && tl == rowsperstrip);
- }
- }
-#define T 1
-#define F 0
-#define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e)))
- switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) {
- /* Strips -> Tiles */
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F):
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T):
- return cpContigStrips2ContigTiles;
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F):
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T):
- return cpContigStrips2SeparateTiles;
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F):
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T):
- return cpSeparateStrips2ContigTiles;
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F):
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T):
- return cpSeparateStrips2SeparateTiles;
- /* Tiles -> Tiles */
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F):
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T):
- return cpContigTiles2ContigTiles;
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F):
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T):
- return cpContigTiles2SeparateTiles;
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F):
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T):
- return cpSeparateTiles2ContigTiles;
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F):
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T):
- return cpSeparateTiles2SeparateTiles;
- /* Tiles -> Strips */
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F):
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T):
- return cpContigTiles2ContigStrips;
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F):
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T):
- return cpContigTiles2SeparateStrips;
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F):
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T):
- return cpSeparateTiles2ContigStrips;
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F):
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T):
- return cpSeparateTiles2SeparateStrips;
- /* Strips -> Strips */
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F):
- return bias ? cpBiasedContig2Contig : cpContig2ContigByRow;
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T):
- return cpDecodedStrips;
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F):
- case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T):
- return cpContig2SeparateByRow;
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F):
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T):
- return cpSeparate2ContigByRow;
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F):
- case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T):
- return cpSeparate2SeparateByRow;
- }
+ uint16_t shortv;
+ uint32_t w, l, tw, tl;
+ int bychunk;
+
+ (void)TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &shortv);
+ if (shortv != config && bitspersample != 8 && samplesperpixel > 1)
+ {
+ fprintf(stderr,
+ "%s: Cannot handle different planar configuration w/ "
+ "bits/sample != 8\n",
+ TIFFFileName(in));
+ return (NULL);
+ }
+ TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
+ TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l);
+ if (!(TIFFIsTiled(out) || TIFFIsTiled(in)))
+ {
+ uint32_t irps = (uint32_t)-1L;
+ TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps);
+ /* if biased, force decoded copying to allow image subtraction */
+ bychunk = !bias && (rowsperstrip == irps);
+ }
+ else
+ { /* either in or out is tiled */
+ if (bias)
+ {
+ fprintf(stderr,
+ "%s: Cannot handle tiled configuration w/bias image\n",
+ TIFFFileName(in));
+ return (NULL);
+ }
+ if (TIFFIsTiled(out))
+ {
+ if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw))
+ tw = w;
+ if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl))
+ tl = l;
+ bychunk = (tw == tilewidth && tl == tilelength);
+ }
+ else
+ { /* out's not, so in must be tiled */
+ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
+ TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
+ bychunk = (tw == w && tl == rowsperstrip);
+ }
+ }
+#define T 1
+#define F 0
+#define pack(a, b, c, d, e) \
+ ((long)(((a) << 11) | ((b) << 3) | ((c) << 2) | ((d) << 1) | (e)))
+ switch (pack(shortv, config, TIFFIsTiled(in), TIFFIsTiled(out), bychunk))
+ {
+ /* Strips -> Tiles */
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F, T, F):
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F, T, T):
+ return cpContigStrips2ContigTiles;
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F, T, F):
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F, T, T):
+ return cpContigStrips2SeparateTiles;
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F, T, F):
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F, T, T):
+ return cpSeparateStrips2ContigTiles;
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F, T, F):
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F, T, T):
+ return cpSeparateStrips2SeparateTiles;
+ /* Tiles -> Tiles */
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T, T, F):
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T, T, T):
+ return cpContigTiles2ContigTiles;
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T, T, F):
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T, T, T):
+ return cpContigTiles2SeparateTiles;
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T, T, F):
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T, T, T):
+ return cpSeparateTiles2ContigTiles;
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T, T, F):
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T, T, T):
+ return cpSeparateTiles2SeparateTiles;
+ /* Tiles -> Strips */
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T, F, F):
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T, F, T):
+ return cpContigTiles2ContigStrips;
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T, F, F):
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T, F, T):
+ return cpContigTiles2SeparateStrips;
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T, F, F):
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T, F, T):
+ return cpSeparateTiles2ContigStrips;
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T, F, F):
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T, F, T):
+ return cpSeparateTiles2SeparateStrips;
+ /* Strips -> Strips */
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F, F, F):
+ return bias ? cpBiasedContig2Contig : cpContig2ContigByRow;
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F, F, T):
+ return cpDecodedStrips;
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F, F, F):
+ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F, F, T):
+ return cpContig2SeparateByRow;
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F, F, F):
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F, F, T):
+ return cpSeparate2ContigByRow;
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F, F, F):
+ case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F, F, T):
+ return cpSeparate2SeparateByRow;
+ }
#undef pack
#undef F
#undef T
- fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n",
- TIFFFileName(in));
- return (NULL);
+ fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n",
+ TIFFFileName(in));
+ return (NULL);
}
diff --git a/tools/tiffcrop.c b/tools/tiffcrop.c
index b97ef370..c7154789 100644
--- a/tools/tiffcrop.c
+++ b/tools/tiffcrop.c
@@ -4,135 +4,122 @@
* Original code:
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
- * Additions (c) Richard Nolde 2006-2010
+ * Additions (c) Richard Nolde 2006-2010
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
- * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS OR ANY OTHER COPYRIGHT
- * HOLDERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL
- * DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS OR ANY OTHER COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL
+ * DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND
* ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOFTWARE.
*
- * Some portions of the current code are derived from tiffcp, primarily in
+ * Some portions of the current code are derived from tiffcp, primarily in
* the areas of lowlevel reading and writing of TAGS, scanlines and tiles though
* some of the original functions have been extended to support arbitrary bit
* depths. These functions are presented at the top of this file.
*
- * Add support for the options below to extract sections of image(s)
+ * Add support for the options below to extract sections of image(s)
* and to modify the whole image or selected portions of each image by
* rotations, mirroring, and colorscale/colormap inversion of selected
- * types of TIFF images when appropriate. Some color model dependent
+ * types of TIFF images when appropriate. Some color model dependent
* functions are restricted to bilevel or 8 bit per sample data.
* See the man page for the full explanations.
*
- * New Options:
+ * New Options:
* -h Display the syntax guide.
- * -v Report the version and last build date for tiffcrop and libtiff.
- * -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1
- * Specify a series of coordinates to define rectangular
- * regions by the top left and lower right corners.
- * -e c|d|i|m|s export mode for images and selections from input images
- * combined All images and selections are written to a single file (default)
- * with multiple selections from one image combined into a single image
- * divided All images and selections are written to a single file
+ * -v Report the version and last build date for tiffcrop and
+ * libtiff. -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1 Specify a series
+ * of coordinates to define rectangular regions by the top left and lower right
+ * corners. -e c|d|i|m|s export mode for images and selections from input
+ * images combined All images and selections are written to a single file
+ * (default) with multiple selections from one image combined into a single
+ * image divided All images and selections are written to a single file
* with each selection from one image written to a new image
- * image Each input image is written to a new file (numeric filename sequence)
- * with multiple selections from the image combined into one image
- * multiple Each input image is written to a new file (numeric filename sequence)
- * with each selection from the image written to a new image
- * separated Individual selections from each image are written to separate files
- * -U units [in, cm, px ] inches, centimeters or pixels
- * -H # Set horizontal resolution of output images to #
- * -V # Set vertical resolution of output images to #
- * -J # Horizontal margin of output page to # expressed in current
- * units when sectioning image into columns x rows
- * using the -S cols:rows option.
- * -K # Vertical margin of output page to # expressed in current
- * units when sectioning image into columns x rows
- * using the -S cols:rows option.
- * -X # Horizontal dimension of region to extract expressed in current
- * units, relative to the specified origin reference 'edge' left (default for X) or right.
- * -Y # Vertical dimension of region to extract expressed in current
- * units, relative to the specified origin reference 'edge' top (default for Y) or bottom.
- * -O orient Orientation for output image, portrait, landscape, auto
- * -P page Page size for output image segments, eg letter, legal, tabloid,
- * etc.
- * -S cols:rows Divide the image into equal sized segments using cols across
- * and rows down
- * -E t|l|r|b Edge to use as origin (i.e. 'side' of the image not 'corner')
- * top = width from left, zones from top to bottom (default)
- * bottom = width from left, zones from bottom to top
- * left = zones from left to right, length from top
- * right = zones from right to left, length from top
- * -m #,#,#,# Margins from edges for selection: top, left, bottom, right
- * (commas separated)
- * -Z #:#,#:# Zones of the image designated as zone X of Y,
- * eg 1:3 would be first of three equal portions measured
- * from reference edge (i.e. 'side' not corner)
- * -N odd|even|#,#-#,#|last
- * Select sequences and/or ranges of images within file
- * to process. The words odd or even may be used to specify
- * all odd or even numbered images the word last may be used
- * in place of a number in the sequence to indicate the final
- * image in the file without knowing how many images there are.
- * -R # Rotate image or crop selection by 90,180,or 270 degrees
- * clockwise
- * -F h|v Flip (mirror) image or crop selection horizontally
- * or vertically
- * -I [black|white|data|both]
- * Invert color space, eg dark to light for bilevel and grayscale images
- * If argument is white or black, set the PHOTOMETRIC_INTERPRETATION
- * tag to MinIsBlack or MinIsWhite without altering the image data
- * If the argument is data or both, the image data are modified:
- * both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,
- * data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag
- * -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N
- * Dump raw data for input and/or output images to individual files
- * in raw (binary) format or text (ASCII) representing binary data
- * as strings of 1s and 0s. The filename arguments are used as stems
- * from which individual files are created for each image. Text format
- * includes annotations for image parameters and scanline info. Level
- * selects which functions dump data, with higher numbers selecting
- * lower level, scanline level routines. Debug reports a limited set
+ * image Each input image is written to a new file (numeric filename
+ * sequence) with multiple selections from the image combined into one image
+ * multiple Each input image is written to a new file (numeric filename
+ * sequence) with each selection from the image written to a new image separated
+ * Individual selections from each image are written to separate files -U units
+ * [in, cm, px ] inches, centimeters or pixels -H # Set horizontal
+ * resolution of output images to # -V # Set vertical resolution of
+ * output images to # -J # Horizontal margin of output page to #
+ * expressed in current units when sectioning image into columns x rows using
+ * the -S cols:rows option. -K # Vertical margin of output page to #
+ * expressed in current units when sectioning image into columns x rows using
+ * the -S cols:rows option. -X # Horizontal dimension of region to
+ * extract expressed in current units, relative to the specified origin
+ * reference 'edge' left (default for X) or right. -Y # Vertical
+ * dimension of region to extract expressed in current units, relative to the
+ * specified origin reference 'edge' top (default for Y) or bottom. -O orient
+ * Orientation for output image, portrait, landscape, auto -P page Page
+ * size for output image segments, eg letter, legal, tabloid, etc. -S cols:rows
+ * Divide the image into equal sized segments using cols across and rows down -E
+ * t|l|r|b Edge to use as origin (i.e. 'side' of the image not 'corner') top
+ * = width from left, zones from top to bottom (default) bottom = width from
+ * left, zones from bottom to top left = zones from left to right, length from
+ * top right = zones from right to left, length from top -m #,#,#,# Margins
+ * from edges for selection: top, left, bottom, right (commas separated) -Z
+ * #:#,#:# Zones of the image designated as zone X of Y, eg 1:3 would be
+ * first of three equal portions measured from reference edge (i.e. 'side' not
+ * corner) -N odd|even|#,#-#,#|last Select sequences and/or ranges of images
+ * within file to process. The words odd or even may be used to specify all odd
+ * or even numbered images the word last may be used in place of a number in the
+ * sequence to indicate the final image in the file without knowing how many
+ * images there are. -R # Rotate image or crop selection by 90,180,or
+ * 270 degrees clockwise -F h|v Flip (mirror) image or crop selection
+ * horizontally or vertically -I [black|white|data|both] Invert color space, eg
+ * dark to light for bilevel and grayscale images If argument is white or black,
+ * set the PHOTOMETRIC_INTERPRETATION tag to MinIsBlack or MinIsWhite without
+ * altering the image data If the argument is data or both, the image data are
+ * modified: both inverts the data and the PHOTOMETRIC_INTERPRETATION tag, data
+ * inverts the data but not the PHOTOMETRIC_INTERPRETATION tag -D
+ * input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N Dump
+ * raw data for input and/or output images to individual files in raw (binary)
+ * format or text (ASCII) representing binary data as strings of 1s and 0s. The
+ * filename arguments are used as stems from which individual files are created
+ * for each image. Text format includes annotations for image parameters and
+ * scanline info. Level selects which functions dump data, with higher numbers
+ * selecting lower level, scanline level routines. Debug reports a limited set
* of messages to monitor progress without enabling dump logs.
*
* Note 1: The (-X|-Y), -Z, -z and -S options are mutually exclusive.
- * In no case should the options be applied to a given selection successively.
- * Note 2: Any of the -X, -Y, -Z and -z options together with other PAGE_MODE_x options
- * such as -H, -V, -P, -J or -K are not supported and may cause buffer overflows.
- */
+ * In no case should the options be applied to a given selection
+ * successively. Note 2: Any of the -X, -Y, -Z and -z options together with
+ * other PAGE_MODE_x options such as -H, -V, -P, -J or -K are not supported and
+ * may cause buffer overflows.
+ */
-static char tiffcrop_version_id[] = "2.5.4";
-static char tiffcrop_rev_date[] = "27-08-2022";
+static char tiffcrop_version_id[] = "2.5.4";
+static char tiffcrop_rev_date[] = "27-08-2022";
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
#include "tiffiop.h"
+#include <assert.h>
+#include <ctype.h>
+#include <limits.h>
+#include <math.h>
+#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
-#include <stdint.h>
#include <string.h>
-#include <math.h>
-#include <ctype.h>
-#include <limits.h>
#include <sys/stat.h>
-#include <assert.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#ifndef EXIT_SUCCESS
@@ -148,12 +135,14 @@ static char tiffcrop_rev_date[] = "27-08-2022";
#define PATH_MAX 1024
#endif
-#define TRUE 1
-#define FALSE 0
+#define TRUE 1
+#define FALSE 0
#ifndef TIFFhowmany
-#define TIFFhowmany(x, y) ((((uint32_t)(x))+(((uint32_t)(y))-1))/((uint32_t)(y)))
-#define TIFFhowmany8(x) (((x)&0x07)?((uint32_t)(x)>>3)+1:(uint32_t)(x)>>3)
+#define TIFFhowmany(x, y) \
+ ((((uint32_t)(x)) + (((uint32_t)(y)) - 1)) / ((uint32_t)(y)))
+#define TIFFhowmany8(x) \
+ (((x)&0x07) ? ((uint32_t)(x) >> 3) + 1 : (uint32_t)(x) >> 3)
#endif
/*
@@ -161,283 +150,309 @@ static char tiffcrop_rev_date[] = "27-08-2022";
* manipulations.
*/
-#define EDGE_TOP 1
-#define EDGE_LEFT 2
-#define EDGE_BOTTOM 3
-#define EDGE_RIGHT 4
-#define EDGE_CENTER 5
+#define EDGE_TOP 1
+#define EDGE_LEFT 2
+#define EDGE_BOTTOM 3
+#define EDGE_RIGHT 4
+#define EDGE_CENTER 5
-#define MIRROR_HORIZ 1
-#define MIRROR_VERT 2
-#define MIRROR_BOTH 3
-#define ROTATECW_90 8
+#define MIRROR_HORIZ 1
+#define MIRROR_VERT 2
+#define MIRROR_BOTH 3
+#define ROTATECW_90 8
#define ROTATECW_180 16
#define ROTATECW_270 32
#define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270)
-#define CROP_NONE 0 /* "-S" -> Page_MODE_ROWSCOLS and page->rows/->cols != 0 */
-#define CROP_MARGINS 1 /* "-m" */
-#define CROP_WIDTH 2 /* "-X" */
-#define CROP_LENGTH 4 /* "-Y" */
-#define CROP_ZONES 8 /* "-Z" */
-#define CROP_REGIONS 16 /* "-z" */
-#define CROP_ROTATE 32
-#define CROP_MIRROR 64
+#define CROP_NONE \
+ 0 /* "-S" -> Page_MODE_ROWSCOLS and page->rows/->cols != 0 \
+ */
+#define CROP_MARGINS 1 /* "-m" */
+#define CROP_WIDTH 2 /* "-X" */
+#define CROP_LENGTH 4 /* "-Y" */
+#define CROP_ZONES 8 /* "-Z" */
+#define CROP_REGIONS 16 /* "-z" */
+#define CROP_ROTATE 32
+#define CROP_MIRROR 64
#define CROP_INVERT 128
/* Modes for writing out images and selections */
-#define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */
-#define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */
+#define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */
+#define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */
#define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */
#define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */
-#define FILE_PER_SELECTION 4 /* One file per selection */
+#define FILE_PER_SELECTION 4 /* One file per selection */
-#define COMPOSITE_IMAGES 0 /* Selections combined into one image */
-#define SEPARATED_IMAGES 1 /* Selections saved to separate images */
+#define COMPOSITE_IMAGES 0 /* Selections combined into one image */
+#define SEPARATED_IMAGES 1 /* Selections saved to separate images */
-#define STRIP 1
-#define TILE 2
+#define STRIP 1
+#define TILE 2
-#define MAX_REGIONS 8 /* number of regions to extract from a single page */
-#define MAX_OUTBUFFS 8 /* must match larger of zones or regions */
-#define MAX_SECTIONS 32 /* number of sections per page to write to output */
-#define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */
-#define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */
-#define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */
-#define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */
+#define MAX_REGIONS 8 /* number of regions to extract from a single page */
+#define MAX_OUTBUFFS 8 /* must match larger of zones or regions */
+#define MAX_SECTIONS 32 /* number of sections per page to write to output */
+#define MAX_IMAGES \
+ 2048 /* number of images in descrete list, not in the file \
+ */
+#define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */
+#define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */
+#define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */
-#define DUMP_NONE 0
-#define DUMP_TEXT 1
-#define DUMP_RAW 2
-
-#define TIFF_DIR_MAX 65534
+#define DUMP_NONE 0
+#define DUMP_TEXT 1
+#define DUMP_RAW 2
+#define TIFF_DIR_MAX 65534
/* To avoid mode buffer overflow */
-#define MAX_MODESTRING_LEN 9
+#define MAX_MODESTRING_LEN 9
/* Some conversion subroutines require image buffers, which are at least 3 bytes
* larger than the necessary size for the image itself. */
-#define NUM_BUFF_OVERSIZE_BYTES 3
+#define NUM_BUFF_OVERSIZE_BYTES 3
/* Offsets into buffer for margins and fixed width and length segments */
-struct offset {
- uint32_t tmargin;
- uint32_t lmargin;
- uint32_t bmargin;
- uint32_t rmargin;
- uint32_t crop_width;
- uint32_t crop_length;
- uint32_t startx;
- uint32_t endx;
- uint32_t starty;
- uint32_t endy;
+struct offset
+{
+ uint32_t tmargin;
+ uint32_t lmargin;
+ uint32_t bmargin;
+ uint32_t rmargin;
+ uint32_t crop_width;
+ uint32_t crop_length;
+ uint32_t startx;
+ uint32_t endx;
+ uint32_t starty;
+ uint32_t endy;
};
-/* Description of a zone within the image. Position 1 of 3 zones would be
- * the first third of the image. These are computed after margins and
- * width/length requests are applied so that you can extract multiple
+/* Description of a zone within the image. Position 1 of 3 zones would be
+ * the first third of the image. These are computed after margins and
+ * width/length requests are applied so that you can extract multiple
* zones from within a larger region for OCR or barcode recognition.
*/
-struct buffinfo {
- size_t size; /* size of this buffer */
- unsigned char *buffer; /* address of the allocated buffer */
+struct buffinfo
+{
+ size_t size; /* size of this buffer */
+ unsigned char *buffer; /* address of the allocated buffer */
};
-struct zone {
- int position; /* ordinal of segment to be extracted */
- int total; /* total equal sized divisions of crop area */
- };
-
-struct pageseg {
- uint32_t x1; /* index of left edge */
- uint32_t x2; /* index of right edge */
- uint32_t y1; /* index of top edge */
- uint32_t y2; /* index of bottom edge */
- int position; /* ordinal of segment to be extracted */
- int total; /* total equal sized divisions of crop area */
- uint32_t buffsize; /* size of buffer needed to hold the cropped zone */
+struct zone
+{
+ int position; /* ordinal of segment to be extracted */
+ int total; /* total equal sized divisions of crop area */
};
-struct coordpairs {
- double X1; /* index of left edge in current units */
- double X2; /* index of right edge in current units */
- double Y1; /* index of top edge in current units */
- double Y2; /* index of bottom edge in current units */
+struct pageseg
+{
+ uint32_t x1; /* index of left edge */
+ uint32_t x2; /* index of right edge */
+ uint32_t y1; /* index of top edge */
+ uint32_t y2; /* index of bottom edge */
+ int position; /* ordinal of segment to be extracted */
+ int total; /* total equal sized divisions of crop area */
+ uint32_t buffsize; /* size of buffer needed to hold the cropped zone */
};
-struct region {
- uint32_t x1; /* pixel offset of left edge */
- uint32_t x2; /* pixel offset of right edge */
- uint32_t y1; /* pixel offset of top edge */
- uint32_t y2; /* picel offset of bottom edge */
- uint32_t width; /* width in pixels */
- uint32_t length; /* length in pixels */
- uint32_t buffsize; /* size of buffer needed to hold the cropped region */
- unsigned char *buffptr; /* address of start of the region */
+struct coordpairs
+{
+ double X1; /* index of left edge in current units */
+ double X2; /* index of right edge in current units */
+ double Y1; /* index of top edge in current units */
+ double Y2; /* index of bottom edge in current units */
};
-/* Cropping parameters from command line and image data
- * Note: This should be renamed to proc_opts and expanded to include all current globals
- * if possible, but each function that accesses global variables will have to be redone.
+struct region
+{
+ uint32_t x1; /* pixel offset of left edge */
+ uint32_t x2; /* pixel offset of right edge */
+ uint32_t y1; /* pixel offset of top edge */
+ uint32_t y2; /* picel offset of bottom edge */
+ uint32_t width; /* width in pixels */
+ uint32_t length; /* length in pixels */
+ uint32_t buffsize; /* size of buffer needed to hold the cropped region */
+ unsigned char *buffptr; /* address of start of the region */
+};
+
+/* Cropping parameters from command line and image data
+ * Note: This should be renamed to proc_opts and expanded to include all current
+ * globals if possible, but each function that accesses global variables will
+ * have to be redone.
*/
-struct crop_mask {
- double width; /* Selection width for master crop region in requested units */
- double length; /* Selection length for master crop region in requesed units */
- double margins[4]; /* Top, left, bottom, right margins */
- float xres; /* Horizontal resolution read from image*/
- float yres; /* Vertical resolution read from image */
- uint32_t combined_width; /* Width of combined cropped zones */
- uint32_t combined_length; /* Length of combined cropped zones */
- uint32_t bufftotal; /* Size of buffer needed to hold all the cropped region */
- uint16_t img_mode; /* Composite or separate images created from zones or regions */
- uint16_t exp_mode; /* Export input images or selections to one or more files */
- uint16_t crop_mode; /* Crop options to be applied */
- uint16_t res_unit; /* Resolution unit for margins and selections */
- uint16_t edge_ref; /* Reference edge for sections extraction and combination */
- uint16_t rotation; /* Clockwise rotation of the extracted region or image */
- uint16_t mirror; /* Mirror extracted region or image horizontally or vertically */
- uint16_t invert; /* Invert the color map of image or region */
- uint16_t photometric; /* Status of photometric interpretation for inverted image */
- uint16_t selections; /* Number of regions or zones selected */
- uint16_t regions; /* Number of regions delimited by corner coordinates */
- struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */
- uint16_t zones; /* Number of zones delimited by Ordinal:Total requested */
- struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */
- struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */
+struct crop_mask
+{
+ double
+ width; /* Selection width for master crop region in requested units */
+ double
+ length; /* Selection length for master crop region in requesed units */
+ double margins[4]; /* Top, left, bottom, right margins */
+ float xres; /* Horizontal resolution read from image*/
+ float yres; /* Vertical resolution read from image */
+ uint32_t combined_width; /* Width of combined cropped zones */
+ uint32_t combined_length; /* Length of combined cropped zones */
+ uint32_t
+ bufftotal; /* Size of buffer needed to hold all the cropped region */
+ uint16_t img_mode; /* Composite or separate images created from zones or
+ regions */
+ uint16_t
+ exp_mode; /* Export input images or selections to one or more files */
+ uint16_t crop_mode; /* Crop options to be applied */
+ uint16_t res_unit; /* Resolution unit for margins and selections */
+ uint16_t
+ edge_ref; /* Reference edge for sections extraction and combination */
+ uint16_t rotation; /* Clockwise rotation of the extracted region or image */
+ uint16_t mirror; /* Mirror extracted region or image horizontally or
+ vertically */
+ uint16_t invert; /* Invert the color map of image or region */
+ uint16_t photometric; /* Status of photometric interpretation for inverted
+ image */
+ uint16_t selections; /* Number of regions or zones selected */
+ uint16_t regions; /* Number of regions delimited by corner coordinates */
+ struct region
+ regionlist[MAX_REGIONS]; /* Regions within page or master crop region */
+ uint16_t zones; /* Number of zones delimited by Ordinal:Total requested */
+ struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */
+ struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and
+ lower right corner */
};
-#define MAX_PAPERNAMES (sizeof(PaperTable)/sizeof(PaperTable[0])) /* was 49 */
+#define MAX_PAPERNAMES \
+ (sizeof(PaperTable) / sizeof(PaperTable[0])) /* was 49 \
+ */
#define MAX_PAPERNAME_LENGTH 15
-#define DEFAULT_RESUNIT RESUNIT_INCH
-#define DEFAULT_PAGE_HEIGHT 14.0
-#define DEFAULT_PAGE_WIDTH 8.5
-#define DEFAULT_RESOLUTION 300
-#define DEFAULT_PAPER_SIZE "legal"
-
-#define ORIENTATION_NONE 0
-#define ORIENTATION_PORTRAIT 1
-#define ORIENTATION_LANDSCAPE 2
-#define ORIENTATION_SEASCAPE 4
-#define ORIENTATION_AUTO 16
-
-#define PAGE_MODE_NONE 0
-#define PAGE_MODE_RESOLUTION 1
-#define PAGE_MODE_PAPERSIZE 2
-#define PAGE_MODE_MARGINS 4
-#define PAGE_MODE_ROWSCOLS 8 /* for -S option */
-
-#define INVERT_DATA_ONLY 10
-#define INVERT_DATA_AND_TAG 11
-
-struct paperdef {
- char name[MAX_PAPERNAME_LENGTH];
- double width;
- double length;
- double asratio;
- };
-
-/* European page sizes corrected from update sent by
+#define DEFAULT_RESUNIT RESUNIT_INCH
+#define DEFAULT_PAGE_HEIGHT 14.0
+#define DEFAULT_PAGE_WIDTH 8.5
+#define DEFAULT_RESOLUTION 300
+#define DEFAULT_PAPER_SIZE "legal"
+
+#define ORIENTATION_NONE 0
+#define ORIENTATION_PORTRAIT 1
+#define ORIENTATION_LANDSCAPE 2
+#define ORIENTATION_SEASCAPE 4
+#define ORIENTATION_AUTO 16
+
+#define PAGE_MODE_NONE 0
+#define PAGE_MODE_RESOLUTION 1
+#define PAGE_MODE_PAPERSIZE 2
+#define PAGE_MODE_MARGINS 4
+#define PAGE_MODE_ROWSCOLS 8 /* for -S option */
+
+#define INVERT_DATA_ONLY 10
+#define INVERT_DATA_AND_TAG 11
+
+struct paperdef
+{
+ char name[MAX_PAPERNAME_LENGTH];
+ double width;
+ double length;
+ double asratio;
+};
+
+/* European page sizes corrected from update sent by
* thomas . jarosch @ intra2net . com on 5/7/2010
* Paper Size Width Length Aspect Ratio */
static const struct paperdef PaperTable[/*MAX_PAPERNAMES*/] = {
- {"default", 8.500, 14.000, 0.607},
- {"pa4", 8.264, 11.000, 0.751},
- {"letter", 8.500, 11.000, 0.773},
- {"legal", 8.500, 14.000, 0.607},
- {"half-letter", 8.500, 5.514, 1.542},
- {"executive", 7.264, 10.528, 0.690},
- {"tabloid", 11.000, 17.000, 0.647},
- {"11x17", 11.000, 17.000, 0.647},
- {"ledger", 17.000, 11.000, 1.545},
- {"archa", 9.000, 12.000, 0.750},
- {"archb", 12.000, 18.000, 0.667},
- {"archc", 18.000, 24.000, 0.750},
- {"archd", 24.000, 36.000, 0.667},
- {"arche", 36.000, 48.000, 0.750},
- {"csheet", 17.000, 22.000, 0.773},
- {"dsheet", 22.000, 34.000, 0.647},
- {"esheet", 34.000, 44.000, 0.773},
- {"superb", 11.708, 17.042, 0.687},
- {"commercial", 4.139, 9.528, 0.434},
- {"monarch", 3.889, 7.528, 0.517},
- {"envelope-dl", 4.333, 8.681, 0.499},
- {"envelope-c5", 6.389, 9.028, 0.708},
- {"europostcard", 4.139, 5.833, 0.710},
- {"a0", 33.110, 46.811, 0.707},
- {"a1", 23.386, 33.110, 0.706},
- {"a2", 16.535, 23.386, 0.707},
- {"a3", 11.693, 16.535, 0.707},
- {"a4", 8.268, 11.693, 0.707},
- {"a5", 5.827, 8.268, 0.705},
- {"a6", 4.134, 5.827, 0.709},
- {"a7", 2.913, 4.134, 0.705},
- {"a8", 2.047, 2.913, 0.703},
- {"a9", 1.457, 2.047, 0.712},
- {"a10", 1.024, 1.457, 0.703},
- {"b0", 39.370, 55.669, 0.707},
- {"b1", 27.835, 39.370, 0.707},
- {"b2", 19.685, 27.835, 0.707},
- {"b3", 13.898, 19.685, 0.706},
- {"b4", 9.843, 13.898, 0.708},
- {"b5", 6.929, 9.843, 0.704},
- {"b6", 4.921, 6.929, 0.710},
- {"c0", 36.102, 51.063, 0.707},
- {"c1", 25.512, 36.102, 0.707},
- {"c2", 18.031, 25.512, 0.707},
- {"c3", 12.756, 18.031, 0.707},
- {"c4", 9.016, 12.756, 0.707},
- {"c5", 6.378, 9.016, 0.707},
- {"c6", 4.488, 6.378, 0.704},
- {"", 0.000, 0.000, 1.000}
-};
+ {"default", 8.500, 14.000, 0.607},
+ {"pa4", 8.264, 11.000, 0.751},
+ {"letter", 8.500, 11.000, 0.773},
+ {"legal", 8.500, 14.000, 0.607},
+ {"half-letter", 8.500, 5.514, 1.542},
+ {"executive", 7.264, 10.528, 0.690},
+ {"tabloid", 11.000, 17.000, 0.647},
+ {"11x17", 11.000, 17.000, 0.647},
+ {"ledger", 17.000, 11.000, 1.545},
+ {"archa", 9.000, 12.000, 0.750},
+ {"archb", 12.000, 18.000, 0.667},
+ {"archc", 18.000, 24.000, 0.750},
+ {"archd", 24.000, 36.000, 0.667},
+ {"arche", 36.000, 48.000, 0.750},
+ {"csheet", 17.000, 22.000, 0.773},
+ {"dsheet", 22.000, 34.000, 0.647},
+ {"esheet", 34.000, 44.000, 0.773},
+ {"superb", 11.708, 17.042, 0.687},
+ {"commercial", 4.139, 9.528, 0.434},
+ {"monarch", 3.889, 7.528, 0.517},
+ {"envelope-dl", 4.333, 8.681, 0.499},
+ {"envelope-c5", 6.389, 9.028, 0.708},
+ {"europostcard", 4.139, 5.833, 0.710},
+ {"a0", 33.110, 46.811, 0.707},
+ {"a1", 23.386, 33.110, 0.706},
+ {"a2", 16.535, 23.386, 0.707},
+ {"a3", 11.693, 16.535, 0.707},
+ {"a4", 8.268, 11.693, 0.707},
+ {"a5", 5.827, 8.268, 0.705},
+ {"a6", 4.134, 5.827, 0.709},
+ {"a7", 2.913, 4.134, 0.705},
+ {"a8", 2.047, 2.913, 0.703},
+ {"a9", 1.457, 2.047, 0.712},
+ {"a10", 1.024, 1.457, 0.703},
+ {"b0", 39.370, 55.669, 0.707},
+ {"b1", 27.835, 39.370, 0.707},
+ {"b2", 19.685, 27.835, 0.707},
+ {"b3", 13.898, 19.685, 0.706},
+ {"b4", 9.843, 13.898, 0.708},
+ {"b5", 6.929, 9.843, 0.704},
+ {"b6", 4.921, 6.929, 0.710},
+ {"c0", 36.102, 51.063, 0.707},
+ {"c1", 25.512, 36.102, 0.707},
+ {"c2", 18.031, 25.512, 0.707},
+ {"c3", 12.756, 18.031, 0.707},
+ {"c4", 9.016, 12.756, 0.707},
+ {"c5", 6.378, 9.016, 0.707},
+ {"c6", 4.488, 6.378, 0.704},
+ {"", 0.000, 0.000, 1.000}};
/* Structure to define input image parameters */
-struct image_data {
- float xres;
- float yres;
- uint32_t width;
- uint32_t length;
- uint16_t res_unit;
- uint16_t bps;
- uint16_t spp;
- uint16_t planar;
- uint16_t photometric;
- uint16_t orientation;
- uint16_t compression;
- uint16_t adjustments;
+struct image_data
+{
+ float xres;
+ float yres;
+ uint32_t width;
+ uint32_t length;
+ uint16_t res_unit;
+ uint16_t bps;
+ uint16_t spp;
+ uint16_t planar;
+ uint16_t photometric;
+ uint16_t orientation;
+ uint16_t compression;
+ uint16_t adjustments;
};
/* Structure to define the output image modifiers */
-struct pagedef {
- char name[16];
- double width; /* width in pixels */
- double length; /* length in pixels */
- double hmargin; /* margins to subtract from width of sections */
- double vmargin; /* margins to subtract from height of sections */
- double hres; /* horizontal resolution for output */
- double vres; /* vertical resolution for output */
- uint32_t mode; /* bitmask of modifiers to page format */
- uint16_t res_unit; /* resolution unit for output image */
- unsigned int rows; /* number of section rows */
- unsigned int cols; /* number of section cols */
- unsigned int orient; /* portrait, landscape, seascape, auto */
+struct pagedef
+{
+ char name[16];
+ double width; /* width in pixels */
+ double length; /* length in pixels */
+ double hmargin; /* margins to subtract from width of sections */
+ double vmargin; /* margins to subtract from height of sections */
+ double hres; /* horizontal resolution for output */
+ double vres; /* vertical resolution for output */
+ uint32_t mode; /* bitmask of modifiers to page format */
+ uint16_t res_unit; /* resolution unit for output image */
+ unsigned int rows; /* number of section rows */
+ unsigned int cols; /* number of section cols */
+ unsigned int orient; /* portrait, landscape, seascape, auto */
};
-struct dump_opts {
- int debug;
- int format;
- int level;
- char mode[4];
- char infilename[PATH_MAX + 1];
- char outfilename[PATH_MAX + 1];
- FILE *infile;
- FILE *outfile;
- };
+struct dump_opts
+{
+ int debug;
+ int format;
+ int level;
+ char mode[4];
+ char infilename[PATH_MAX + 1];
+ char outfilename[PATH_MAX + 1];
+ FILE *infile;
+ FILE *outfile;
+};
/* globals */
-static int outtiled = -1;
+static int outtiled = -1;
static uint32_t tilewidth = 0;
static uint32_t tilelength = 0;
@@ -447,78 +462,87 @@ static uint16_t predictor = 0;
static uint16_t fillorder = 0;
static uint32_t rowsperstrip = 0;
static uint32_t g3opts = 0;
-static int ignore = FALSE; /* if true, ignore read errors */
-static uint32_t defg3opts = (uint32_t) -1;
-static int quality = 100; /* JPEG quality */
+static int ignore = FALSE; /* if true, ignore read errors */
+static uint32_t defg3opts = (uint32_t)-1;
+static int quality = 100; /* JPEG quality */
/* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */
-static int jpegcolormode = JPEGCOLORMODE_RGB;
-static uint16_t defcompression = (uint16_t) -1;
-static uint16_t defpredictor = (uint16_t) -1;
-static int pageNum = 0;
-static int little_endian = 1;
+static int jpegcolormode = JPEGCOLORMODE_RGB;
+static uint16_t defcompression = (uint16_t)-1;
+static uint16_t defpredictor = (uint16_t)-1;
+static int pageNum = 0;
+static int little_endian = 1;
/* Functions adapted from tiffcp with additions or significant modifications */
-static int readContigStripsIntoBuffer (TIFF*, uint8_t*);
-static int readSeparateStripsIntoBuffer (TIFF*, uint8_t*, uint32_t, uint32_t, tsample_t, struct dump_opts *);
-static int readContigTilesIntoBuffer (TIFF*, uint8_t*, uint32_t, uint32_t, uint32_t, uint32_t, tsample_t, uint16_t);
-static int readSeparateTilesIntoBuffer (TIFF*, uint8_t*, uint32_t, uint32_t, uint32_t, uint32_t, tsample_t, uint16_t);
-static int writeBufferToContigStrips (TIFF*, uint8_t*, uint32_t);
-static int writeBufferToContigTiles (TIFF*, uint8_t*, uint32_t, uint32_t, tsample_t, struct dump_opts *);
-static int writeBufferToSeparateStrips (TIFF*, uint8_t*, uint32_t, uint32_t, tsample_t, struct dump_opts *);
-static int writeBufferToSeparateTiles (TIFF*, uint8_t*, uint32_t, uint32_t, tsample_t, struct dump_opts *);
-static int extractContigSamplesToBuffer (uint8_t *, uint8_t *, uint32_t, uint32_t, tsample_t,
- uint16_t, uint16_t, struct dump_opts *);
-static int processCompressOptions(char*);
+static int readContigStripsIntoBuffer(TIFF *, uint8_t *);
+static int readSeparateStripsIntoBuffer(TIFF *, uint8_t *, uint32_t, uint32_t,
+ tsample_t, struct dump_opts *);
+static int readContigTilesIntoBuffer(TIFF *, uint8_t *, uint32_t, uint32_t,
+ uint32_t, uint32_t, tsample_t, uint16_t);
+static int readSeparateTilesIntoBuffer(TIFF *, uint8_t *, uint32_t, uint32_t,
+ uint32_t, uint32_t, tsample_t, uint16_t);
+static int writeBufferToContigStrips(TIFF *, uint8_t *, uint32_t);
+static int writeBufferToContigTiles(TIFF *, uint8_t *, uint32_t, uint32_t,
+ tsample_t, struct dump_opts *);
+static int writeBufferToSeparateStrips(TIFF *, uint8_t *, uint32_t, uint32_t,
+ tsample_t, struct dump_opts *);
+static int writeBufferToSeparateTiles(TIFF *, uint8_t *, uint32_t, uint32_t,
+ tsample_t, struct dump_opts *);
+static int extractContigSamplesToBuffer(uint8_t *, uint8_t *, uint32_t,
+ uint32_t, tsample_t, uint16_t, uint16_t,
+ struct dump_opts *);
+static int processCompressOptions(char *);
static void usage(int code);
/* All other functions by Richard Nolde, not found in tiffcp */
-static void initImageData (struct image_data *);
-static void initCropMasks (struct crop_mask *);
-static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []);
+static void initImageData(struct image_data *);
+static void initCropMasks(struct crop_mask *);
+static void initPageSetup(struct pagedef *, struct pageseg *,
+ struct buffinfo[]);
static void initDumpOptions(struct dump_opts *);
/* Command line and file naming functions */
-void process_command_opts (int, char *[], char *, char *, uint32_t *,
- uint16_t *, uint16_t *, uint32_t *, uint32_t *, uint32_t *,
- struct crop_mask *, struct pagedef *,
- struct dump_opts *,
- unsigned int *, unsigned int *);
-static int update_output_file (TIFF **, char *, int, char *, unsigned int *);
-
+void process_command_opts(int, char *[], char *, char *, uint32_t *, uint16_t *,
+ uint16_t *, uint32_t *, uint32_t *, uint32_t *,
+ struct crop_mask *, struct pagedef *,
+ struct dump_opts *, unsigned int *, unsigned int *);
+static int update_output_file(TIFF **, char *, int, char *, unsigned int *);
/* * High level functions for whole image manipulation */
-static int get_page_geometry (char *, struct pagedef*);
-static int computeInputPixelOffsets(struct crop_mask *, struct image_data *,
- struct offset *);
-static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *,
- struct pagedef *, struct pageseg *,
- struct dump_opts *);
-static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **);
-static int correct_orientation(struct image_data *, unsigned char **);
-static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *);
-static int processCropSelections(struct image_data *, struct crop_mask *,
- unsigned char **, struct buffinfo []);
-static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *,
- struct dump_opts *, struct buffinfo [],
- char *, char *, unsigned int*, unsigned int);
+static int get_page_geometry(char *, struct pagedef *);
+static int computeInputPixelOffsets(struct crop_mask *, struct image_data *,
+ struct offset *);
+static int computeOutputPixelOffsets(struct crop_mask *, struct image_data *,
+ struct pagedef *, struct pageseg *,
+ struct dump_opts *);
+static int loadImage(TIFF *, struct image_data *, struct dump_opts *,
+ unsigned char **);
+static int correct_orientation(struct image_data *, unsigned char **);
+static int getCropOffsets(struct image_data *, struct crop_mask *,
+ struct dump_opts *);
+static int processCropSelections(struct image_data *, struct crop_mask *,
+ unsigned char **, struct buffinfo[]);
+static int writeSelections(TIFF *, TIFF **, struct crop_mask *,
+ struct image_data *, struct dump_opts *,
+ struct buffinfo[], char *, char *, unsigned int *,
+ unsigned int);
/* Section functions */
-static int createImageSection(uint32_t, unsigned char **);
-static int extractImageSection(struct image_data *, struct pageseg *,
- unsigned char *, unsigned char *);
-static int writeSingleSection(TIFF *, TIFF *, struct image_data *,
- struct dump_opts *, uint32_t, uint32_t,
- double, double, unsigned char *);
-static int writeImageSections(TIFF *, TIFF *, struct image_data *,
- struct pagedef *, struct pageseg *,
- struct dump_opts *, unsigned char *,
- unsigned char **);
+static int createImageSection(uint32_t, unsigned char **);
+static int extractImageSection(struct image_data *, struct pageseg *,
+ unsigned char *, unsigned char *);
+static int writeSingleSection(TIFF *, TIFF *, struct image_data *,
+ struct dump_opts *, uint32_t, uint32_t, double,
+ double, unsigned char *);
+static int writeImageSections(TIFF *, TIFF *, struct image_data *,
+ struct pagedef *, struct pageseg *,
+ struct dump_opts *, unsigned char *,
+ unsigned char **);
/* Whole image functions */
-static int createCroppedImage(struct image_data *, struct crop_mask *,
- unsigned char **, unsigned char **);
-static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image,
- struct dump_opts * dump,
- uint32_t, uint32_t, unsigned char *, int, int);
+static int createCroppedImage(struct image_data *, struct crop_mask *,
+ unsigned char **, unsigned char **);
+static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image,
+ struct dump_opts *dump, uint32_t, uint32_t,
+ unsigned char *, int, int);
/* Image manipulation functions */
static int rotateContigSamples8bits(uint16_t, uint16_t, uint16_t, uint32_t,
@@ -537,89 +561,104 @@ static int invertImage(uint16_t, uint16_t, uint16_t, uint32_t, uint32_t,
unsigned char *);
/* Functions to reverse the sequence of samples in a scanline */
-static int reverseSamples8bits (uint16_t, uint16_t, uint32_t, uint8_t *, uint8_t *);
-static int reverseSamples16bits (uint16_t, uint16_t, uint32_t, uint8_t *, uint8_t *);
-static int reverseSamples24bits (uint16_t, uint16_t, uint32_t, uint8_t *, uint8_t *);
-static int reverseSamples32bits (uint16_t, uint16_t, uint32_t, uint8_t *, uint8_t *);
-static int reverseSamplesBytes (uint16_t, uint16_t, uint32_t, uint8_t *, uint8_t *);
+static int reverseSamples8bits(uint16_t, uint16_t, uint32_t, uint8_t *,
+ uint8_t *);
+static int reverseSamples16bits(uint16_t, uint16_t, uint32_t, uint8_t *,
+ uint8_t *);
+static int reverseSamples24bits(uint16_t, uint16_t, uint32_t, uint8_t *,
+ uint8_t *);
+static int reverseSamples32bits(uint16_t, uint16_t, uint32_t, uint8_t *,
+ uint8_t *);
+static int reverseSamplesBytes(uint16_t, uint16_t, uint32_t, uint8_t *,
+ uint8_t *);
/* Functions for manipulating individual samples in an image */
static int extractSeparateRegion(struct image_data *, struct crop_mask *,
- unsigned char *, unsigned char *, int);
-static int extractCompositeRegions(struct image_data *, struct crop_mask *,
- unsigned char *, unsigned char *);
-static int extractContigSamples8bits (uint8_t *, uint8_t *, uint32_t,
- tsample_t, uint16_t, uint16_t,
- tsample_t, uint32_t, uint32_t);
-static int extractContigSamples16bits (uint8_t *, uint8_t *, uint32_t,
- tsample_t, uint16_t, uint16_t,
- tsample_t, uint32_t, uint32_t);
-static int extractContigSamples24bits (uint8_t *, uint8_t *, uint32_t,
- tsample_t, uint16_t, uint16_t,
- tsample_t, uint32_t, uint32_t);
-static int extractContigSamples32bits (uint8_t *, uint8_t *, uint32_t,
- tsample_t, uint16_t, uint16_t,
- tsample_t, uint32_t, uint32_t);
-static int extractContigSamplesBytes (uint8_t *, uint8_t *, uint32_t,
- tsample_t, uint16_t, uint16_t,
- tsample_t, uint32_t, uint32_t);
-static int extractContigSamplesShifted8bits (uint8_t *, uint8_t *, uint32_t,
+ unsigned char *, unsigned char *, int);
+static int extractCompositeRegions(struct image_data *, struct crop_mask *,
+ unsigned char *, unsigned char *);
+static int extractContigSamples8bits(uint8_t *, uint8_t *, uint32_t, tsample_t,
+ uint16_t, uint16_t, tsample_t, uint32_t,
+ uint32_t);
+static int extractContigSamples16bits(uint8_t *, uint8_t *, uint32_t, tsample_t,
+ uint16_t, uint16_t, tsample_t, uint32_t,
+ uint32_t);
+static int extractContigSamples24bits(uint8_t *, uint8_t *, uint32_t, tsample_t,
+ uint16_t, uint16_t, tsample_t, uint32_t,
+ uint32_t);
+static int extractContigSamples32bits(uint8_t *, uint8_t *, uint32_t, tsample_t,
+ uint16_t, uint16_t, tsample_t, uint32_t,
+ uint32_t);
+static int extractContigSamplesBytes(uint8_t *, uint8_t *, uint32_t, tsample_t,
+ uint16_t, uint16_t, tsample_t, uint32_t,
+ uint32_t);
+static int extractContigSamplesShifted8bits(uint8_t *, uint8_t *, uint32_t,
+ tsample_t, uint16_t, uint16_t,
+ tsample_t, uint32_t, uint32_t, int);
+static int extractContigSamplesShifted16bits(uint8_t *, uint8_t *, uint32_t,
+ tsample_t, uint16_t, uint16_t,
+ tsample_t, uint32_t, uint32_t,
+ int);
+static int extractContigSamplesShifted24bits(uint8_t *, uint8_t *, uint32_t,
+ tsample_t, uint16_t, uint16_t,
+ tsample_t, uint32_t, uint32_t,
+ int);
+static int extractContigSamplesShifted32bits(uint8_t *, uint8_t *, uint32_t,
tsample_t, uint16_t, uint16_t,
tsample_t, uint32_t, uint32_t,
int);
-static int extractContigSamplesShifted16bits (uint8_t *, uint8_t *, uint32_t,
- tsample_t, uint16_t, uint16_t,
- tsample_t, uint32_t, uint32_t,
- int);
-static int extractContigSamplesShifted24bits (uint8_t *, uint8_t *, uint32_t,
- tsample_t, uint16_t, uint16_t,
- tsample_t, uint32_t, uint32_t,
- int);
-static int extractContigSamplesShifted32bits (uint8_t *, uint8_t *, uint32_t,
- tsample_t, uint16_t, uint16_t,
- tsample_t, uint32_t, uint32_t,
- int);
-static int extractContigSamplesToTileBuffer(uint8_t *, uint8_t *, uint32_t, uint32_t,
- uint32_t, uint32_t, tsample_t, uint16_t,
- uint16_t, uint16_t, struct dump_opts *);
+static int extractContigSamplesToTileBuffer(uint8_t *, uint8_t *, uint32_t,
+ uint32_t, uint32_t, uint32_t,
+ tsample_t, uint16_t, uint16_t,
+ uint16_t, struct dump_opts *);
/* Functions to combine separate planes into interleaved planes */
-static int combineSeparateSamples8bits (uint8_t *[], uint8_t *, uint32_t, uint32_t,
- uint16_t, uint16_t, FILE *, int, int);
-static int combineSeparateSamples16bits (uint8_t *[], uint8_t *, uint32_t, uint32_t,
- uint16_t, uint16_t, FILE *, int, int);
-static int combineSeparateSamples24bits (uint8_t *[], uint8_t *, uint32_t, uint32_t,
- uint16_t, uint16_t, FILE *, int, int);
-static int combineSeparateSamples32bits (uint8_t *[], uint8_t *, uint32_t, uint32_t,
- uint16_t, uint16_t, FILE *, int, int);
-static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *,
- uint32_t, uint32_t, tsample_t, uint16_t,
- FILE *, int, int);
-
-static int combineSeparateTileSamples8bits (uint8_t *[], uint8_t *, uint32_t, uint32_t,
- uint32_t, uint32_t, uint16_t, uint16_t,
- FILE *, int, int);
-static int combineSeparateTileSamples16bits (uint8_t *[], uint8_t *, uint32_t, uint32_t,
- uint32_t, uint32_t, uint16_t, uint16_t,
- FILE *, int, int);
-static int combineSeparateTileSamples24bits (uint8_t *[], uint8_t *, uint32_t, uint32_t,
- uint32_t, uint32_t, uint16_t, uint16_t,
- FILE *, int, int);
-static int combineSeparateTileSamples32bits (uint8_t *[], uint8_t *, uint32_t, uint32_t,
- uint32_t, uint32_t, uint16_t, uint16_t,
- FILE *, int, int);
-static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *,
- uint32_t, uint32_t, uint32_t, uint32_t,
- tsample_t, uint16_t, FILE *, int, int);
+static int combineSeparateSamples8bits(uint8_t *[], uint8_t *, uint32_t,
+ uint32_t, uint16_t, uint16_t, FILE *,
+ int, int);
+static int combineSeparateSamples16bits(uint8_t *[], uint8_t *, uint32_t,
+ uint32_t, uint16_t, uint16_t, FILE *,
+ int, int);
+static int combineSeparateSamples24bits(uint8_t *[], uint8_t *, uint32_t,
+ uint32_t, uint16_t, uint16_t, FILE *,
+ int, int);
+static int combineSeparateSamples32bits(uint8_t *[], uint8_t *, uint32_t,
+ uint32_t, uint16_t, uint16_t, FILE *,
+ int, int);
+static int combineSeparateSamplesBytes(unsigned char *[], unsigned char *,
+ uint32_t, uint32_t, tsample_t, uint16_t,
+ FILE *, int, int);
+
+static int combineSeparateTileSamples8bits(uint8_t *[], uint8_t *, uint32_t,
+ uint32_t, uint32_t, uint32_t,
+ uint16_t, uint16_t, FILE *, int,
+ int);
+static int combineSeparateTileSamples16bits(uint8_t *[], uint8_t *, uint32_t,
+ uint32_t, uint32_t, uint32_t,
+ uint16_t, uint16_t, FILE *, int,
+ int);
+static int combineSeparateTileSamples24bits(uint8_t *[], uint8_t *, uint32_t,
+ uint32_t, uint32_t, uint32_t,
+ uint16_t, uint16_t, FILE *, int,
+ int);
+static int combineSeparateTileSamples32bits(uint8_t *[], uint8_t *, uint32_t,
+ uint32_t, uint32_t, uint32_t,
+ uint16_t, uint16_t, FILE *, int,
+ int);
+static int combineSeparateTileSamplesBytes(unsigned char *[], unsigned char *,
+ uint32_t, uint32_t, uint32_t,
+ uint32_t, tsample_t, uint16_t,
+ FILE *, int, int);
/* Dump functions for debugging */
-static void dump_info (FILE *, int, char *, char *, ...);
-static int dump_data (FILE *, int, char *, unsigned char *, uint32_t);
-static int dump_byte (FILE *, int, char *, unsigned char);
-static int dump_short (FILE *, int, char *, uint16_t);
-static int dump_long (FILE *, int, char *, uint32_t);
-static int dump_wide (FILE *, int, char *, uint64_t);
-static int dump_buffer (FILE *, int, uint32_t, uint32_t, uint32_t, unsigned char *);
+static void dump_info(FILE *, int, char *, char *, ...);
+static int dump_data(FILE *, int, char *, unsigned char *, uint32_t);
+static int dump_byte(FILE *, int, char *, unsigned char);
+static int dump_short(FILE *, int, char *, uint16_t);
+static int dump_long(FILE *, int, char *, uint32_t);
+static int dump_wide(FILE *, int, char *, uint64_t);
+static int dump_buffer(FILE *, int, uint32_t, uint32_t, uint32_t,
+ unsigned char *);
/* End function declarations */
/* Functions derived in whole or in part from tiffcp */
@@ -634,7285 +673,8023 @@ static tmsize_t maxMalloc = DEFAULT_MAX_MALLOC;
/**
* This custom malloc function enforce a maximum allocation size
*/
-static void* limitMalloc(tmsize_t s)
+static void *limitMalloc(tmsize_t s)
{
- if (maxMalloc && (s > maxMalloc)) {
- fprintf(stderr, "MemoryLimitError: allocation of %" PRIu64 " bytes is forbidden. Limit is %" PRIu64 ".\n",
- (uint64_t)s, (uint64_t)maxMalloc);
- fprintf(stderr, " use -k option to change limit.\n"); return NULL;
- }
- return _TIFFmalloc(s);
+ if (maxMalloc && (s > maxMalloc))
+ {
+ fprintf(stderr,
+ "MemoryLimitError: allocation of %" PRIu64
+ " bytes is forbidden. Limit is %" PRIu64 ".\n",
+ (uint64_t)s, (uint64_t)maxMalloc);
+ fprintf(stderr, " use -k option to change limit.\n");
+ return NULL;
+ }
+ return _TIFFmalloc(s);
}
-
-
static const char usage_info[] =
-"Copy, crop, convert, extract, and/or process TIFF files\n\n"
-"usage: tiffcrop [options] source1 ... sourceN destination\n"
-"where options are:\n"
-" -h Print this syntax listing\n"
-" -v Print tiffcrop version identifier and last revision date\n"
-" \n"
-" -a Append to output instead of overwriting\n"
-" -B Force output to be written with Big - Endian byte order.\n"
-" -L Force output to be written with Little-Endian byte order.\n"
-" -M Suppress the use of memory-mapped files when reading images.\n"
-" -C Suppress the use of \"strip chopping\" when reading images that have a single strip/tile of uncompressed data.\n"
-" \n"
-" -d offset Set initial directory offset, counting first image as one, not zero\n"
-" -p contig Pack samples contiguously (e.g. RGBRGB...)\n"
-" -p separate Store samples separately (e.g. RRR...GGG...BBB...)\n"
-" -s Write output in strips\n"
-" -t Write output in tiles\n"
-" -i Ignore read errors\n"
-" -k size Set the memory allocation limit in MiB. 0 to disable limit\n"
-" \n"
-" -r # Make each strip have no more than # rows\n"
-" -w # Set output tile width (pixels)\n"
-" -l # Set output tile length (pixels)\n"
-" \n"
-" -f lsb2msb Force lsb-to-msb FillOrder for output\n"
-" -f msb2lsb Force msb-to-lsb FillOrder for output\n"
-"\n"
+ "Copy, crop, convert, extract, and/or process TIFF files\n\n"
+ "usage: tiffcrop [options] source1 ... sourceN destination\n"
+ "where options are:\n"
+ " -h Print this syntax listing\n"
+ " -v Print tiffcrop version identifier and last revision date\n"
+ " \n"
+ " -a Append to output instead of overwriting\n"
+ " -B Force output to be written with Big - Endian byte order.\n"
+ " -L Force output to be written with Little-Endian byte order.\n"
+ " -M Suppress the use of memory-mapped files when reading images.\n"
+ " -C Suppress the use of \"strip chopping\" when reading images that "
+ "have a single strip/tile of uncompressed data.\n"
+ " \n"
+ " -d offset Set initial directory offset, counting first image as one, "
+ "not zero\n"
+ " -p contig Pack samples contiguously (e.g. RGBRGB...)\n"
+ " -p separate Store samples separately (e.g. RRR...GGG...BBB...)\n"
+ " -s Write output in strips\n"
+ " -t Write output in tiles\n"
+ " -i Ignore read errors\n"
+ " -k size Set the memory allocation limit in MiB. 0 to disable limit\n"
+ " \n"
+ " -r # Make each strip have no more than # rows\n"
+ " -w # Set output tile width (pixels)\n"
+ " -l # Set output tile length (pixels)\n"
+ " \n"
+ " -f lsb2msb Force lsb-to-msb FillOrder for output\n"
+ " -f msb2lsb Force msb-to-lsb FillOrder for output\n"
+ "\n"
#ifdef LZW_SUPPORT
-" -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding\n"
-/* " LZW options:\n" */
-" # Set predictor value\n"
-" For example, -c lzw:2 for LZW-encoded data with horizontal differencing\n"
+ " -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding\n"
+ /* " LZW options:\n" */
+ " # Set predictor value\n"
+ " For example, -c lzw:2 for LZW-encoded data with horizontal "
+ "differencing\n"
#endif
#ifdef ZIP_SUPPORT
-" -c zip[:opts] Compress output with deflate encoding\n"
-/* " Deflate (ZIP) options:\n" */
-" # Set predictor value\n"
+ " -c zip[:opts] Compress output with deflate encoding\n"
+ /* " Deflate (ZIP) options:\n" */
+ " # Set predictor value\n"
#endif
#ifdef JPEG_SUPPORT
-" -c jpeg[:opts] Compress output with JPEG encoding\n"
-/* " JPEG options:\n" */
-" # Set compression quality level (0-100, default 100)\n"
-" raw Output color image as raw YCbCr (default)\n"
-" rgb Output color image as RGB\n"
-" For example, -c jpeg:rgb:50 for JPEG-encoded RGB with 50% comp. quality\n"
+ " -c jpeg[:opts] Compress output with JPEG encoding\n"
+ /* " JPEG options:\n" */
+ " # Set compression quality level (0-100, default 100)\n"
+ " raw Output color image as raw YCbCr (default)\n"
+ " rgb Output color image as RGB\n"
+ " For example, -c jpeg:rgb:50 for JPEG-encoded RGB with 50% comp. "
+ "quality\n"
#endif
#ifdef PACKBITS_SUPPORT
-" -c packbits Compress output with packbits encoding\n"
+ " -c packbits Compress output with packbits encoding\n"
#endif
#ifdef CCITT_SUPPORT
-" -c g3[:opts] Compress output with CCITT Group 3 encoding\n"
-/* " CCITT Group 3 options:\n" */
-" 1d Use default CCITT Group 3 1D-encoding\n"
-" 2d Use optional CCITT Group 3 2D-encoding\n"
-" fill Byte-align EOL codes\n"
-" For example, -c g3:2d:fill for G3-2D-encoded data with byte-aligned EOLs\n"
-" -c g4 Compress output with CCITT Group 4 encoding\n"
+ " -c g3[:opts] Compress output with CCITT Group 3 encoding\n"
+ /* " CCITT Group 3 options:\n" */
+ " 1d Use default CCITT Group 3 1D-encoding\n"
+ " 2d Use optional CCITT Group 3 2D-encoding\n"
+ " fill Byte-align EOL codes\n"
+ " For example, -c g3:2d:fill for G3-2D-encoded data with byte-aligned "
+ "EOLs\n"
+ " -c g4 Compress output with CCITT Group 4 encoding\n"
#endif
-#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(JPEG_SUPPORT) || defined(PACKBITS_SUPPORT) || defined(CCITT_SUPPORT)
-" -c none Use no compression algorithm on output\n"
+#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(JPEG_SUPPORT) || \
+ defined(PACKBITS_SUPPORT) || defined(CCITT_SUPPORT)
+ " -c none Use no compression algorithm on output\n"
#endif
-"\n"
-"Page and selection options:\n"
-" -N odd|even|#,#-#,#|last sequences and ranges of images within file to process\n"
-" The words odd or even may be used to specify all odd or even numbered images.\n"
-" The word last may be used in place of a number in the sequence to indicate.\n"
-" The final image in the file without knowing how many images there are.\n"
-" Numbers are counted from one even though TIFF IFDs are counted from zero.\n"
-"\n"
-" -E t|l|r|b edge to use as origin for width and length of crop region\n"
-" -U units [in, cm, px ] inches, centimeters or pixels\n"
-" \n"
-" -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas\n"
-" -X # horizontal dimension of region to extract expressed in current units\n"
-" -Y # vertical dimension of region to extract expressed in current units\n"
-" -Z #:#,#:# zones of the image designated as position X of Y,\n"
-" eg 1:3 would be first of three equal portions measured from reference edge\n"
-" -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1\n"
-" regions of the image designated by upper left and lower right coordinates\n"
-"\n"
-"Export grouping options:\n"
-" -e c|d|i|m|s export mode for images and selections from input images.\n"
-" When exporting a composite image from multiple zones or regions\n"
-" (combined and image modes), the selections must have equal sizes\n"
-" for the axis perpendicular to the edge specified with -E.\n"
-" c|combined All images and selections are written to a single file (default).\n"
-" with multiple selections from one image combined into a single image.\n"
-" d|divided All images and selections are written to a single file\n"
-" with each selection from one image written to a new image.\n"
-" i|image Each input image is written to a new file (numeric filename sequence)\n"
-" with multiple selections from the image combined into one image.\n"
-" m|multiple Each input image is written to a new file (numeric filename sequence)\n"
-" with each selection from the image written to a new image.\n"
-" s|separated Individual selections from each image are written to separate files.\n"
-"\n"
-"Output options:\n"
-" -H # Set horizontal resolution of output images to #\n"
-" -V # Set vertical resolution of output images to #\n"
-" -J # Set horizontal margin of output page to # expressed in current units\n"
-" when sectioning image into columns x rows using the -S cols:rows option\n"
-" -K # Set verticalal margin of output page to # expressed in current units\n"
-" when sectioning image into columns x rows using the -S cols:rows option\n"
-" \n"
-" -O orient orientation for output image, portrait, landscape, auto\n"
-" -P page page size for output image segments, eg letter, legal, tabloid, etc\n"
-" use #.#x#.# to specify a custom page size in the currently defined units\n"
-" where #.# represents the width and length\n"
-" -S cols:rows Divide the image into equal sized segments using cols across and rows down.\n"
-"\n"
-" -F hor|vert|both\n"
-" flip (mirror) image or region horizontally, vertically, or both\n"
-" -R # [90,180,or 270] degrees clockwise rotation of image or extracted region\n"
-" -I [black|white|data|both]\n"
-" invert color space, eg dark to light for bilevel and grayscale images\n"
-" If argument is white or black, set the PHOTOMETRIC_INTERPRETATION \n"
-" tag to MinIsBlack or MinIsWhite without altering the image data\n"
-" If the argument is data or both, the image data are modified:\n"
-" both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,\n"
-" data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag\n"
-"\n"
-"-D opt1:value1,opt2:value2,opt3:value3:opt4:value4\n"
-" Debug/dump program progress and/or data to non-TIFF files.\n"
-" Options include the following and must be joined as a comma\n"
-" separate list. The use of this option is generally limited to\n"
-" program debugging and development of future options.\n"
-"\n"
-" debug:N Display limited program progress indicators where larger N\n"
-" increase the level of detail. Note: Tiffcrop may be compiled with\n"
-" -DDEVELMODE to enable additional very low level debug reporting.\n"
-"\n"
-" Format:txt|raw Format any logged data as ASCII text or raw binary \n"
-" values. ASCII text dumps include strings of ones and zeroes\n"
-" representing the binary values in the image data plus identifying headers.\n"
-"\n"
-" level:N Specify the level of detail presented in the dump files.\n"
-" This can vary from dumps of the entire input or output image data to dumps\n"
-" of data processed by specific functions. Current range of levels is 1 to 3.\n"
-"\n"
-" input:full-path-to-directory/input-dumpname\n"
-"\n"
-" output:full-path-to-directory/output-dumpnaem\n"
-"\n"
-" When dump files are being written, each image will be written to a separate\n"
-" file with the name built by adding a numeric sequence value to the dumpname\n"
-" and an extension of .txt for ASCII dumps or .bin for binary dumps.\n"
-"\n"
-" The four debug/dump options are independent, though it makes little sense to\n"
-" specify a dump file without specifying a detail level.\n"
-"\n"
-"Note 1: The (-X|-Y), -Z, -z and -S options are mutually exclusive.\n"
-" In no case should the options be applied to a given selection successively.\n"
-"\n"
-"Note 2: Any of the -X, -Y, -Z and -z options together with other PAGE_MODE_x options\n"
-" such as - H, -V, -P, -J or -K are not supported and may cause buffer overflows.\n"
-"\n"
-;
-
-/* This function could be modified to pass starting sample offset
+ "\n"
+ "Page and selection options:\n"
+ " -N odd|even|#,#-#,#|last sequences and ranges of images within "
+ "file to process\n"
+ " The words odd or even may be used to specify all odd or even "
+ "numbered images.\n"
+ " The word last may be used in place of a number in the "
+ "sequence to indicate.\n"
+ " The final image in the file without knowing how many images "
+ "there are.\n"
+ " Numbers are counted from one even though TIFF IFDs are "
+ "counted from zero.\n"
+ "\n"
+ " -E t|l|r|b edge to use as origin for width and length of crop region\n"
+ " -U units [in, cm, px ] inches, centimeters or pixels\n"
+ " \n"
+ " -m #,#,#,# margins from edges for selection: top, left, bottom, right "
+ "separated by commas\n"
+ " -X # horizontal dimension of region to extract expressed in "
+ "current units\n"
+ " -Y # vertical dimension of region to extract expressed in current "
+ "units\n"
+ " -Z #:#,#:# zones of the image designated as position X of Y,\n"
+ " eg 1:3 would be first of three equal portions measured from "
+ "reference edge\n"
+ " -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1\n"
+ " regions of the image designated by upper left and lower "
+ "right coordinates\n"
+ "\n"
+ "Export grouping options:\n"
+ " -e c|d|i|m|s export mode for images and selections from input "
+ "images.\n"
+ " When exporting a composite image from multiple zones or "
+ "regions\n"
+ " (combined and image modes), the selections must have "
+ "equal sizes\n"
+ " for the axis perpendicular to the edge specified with "
+ "-E.\n"
+ " c|combined All images and selections are written to a single file "
+ "(default).\n"
+ " with multiple selections from one image combined into a "
+ "single image.\n"
+ " d|divided All images and selections are written to a single file\n"
+ " with each selection from one image written to a new "
+ "image.\n"
+ " i|image Each input image is written to a new file (numeric "
+ "filename sequence)\n"
+ " with multiple selections from the image combined into "
+ "one image.\n"
+ " m|multiple Each input image is written to a new file (numeric "
+ "filename sequence)\n"
+ " with each selection from the image written to a new "
+ "image.\n"
+ " s|separated Individual selections from each image are written to "
+ "separate files.\n"
+ "\n"
+ "Output options:\n"
+ " -H # Set horizontal resolution of output images to #\n"
+ " -V # Set vertical resolution of output images to #\n"
+ " -J # Set horizontal margin of output page to # expressed in "
+ "current units\n"
+ " when sectioning image into columns x rows using the -S "
+ "cols:rows option\n"
+ " -K # Set verticalal margin of output page to # expressed in "
+ "current units\n"
+ " when sectioning image into columns x rows using the -S "
+ "cols:rows option\n"
+ " \n"
+ " -O orient orientation for output image, portrait, landscape, auto\n"
+ " -P page page size for output image segments, eg letter, legal, "
+ "tabloid, etc\n"
+ " use #.#x#.# to specify a custom page size in the currently "
+ "defined units\n"
+ " where #.# represents the width and length\n"
+ " -S cols:rows Divide the image into equal sized segments using cols "
+ "across and rows down.\n"
+ "\n"
+ " -F hor|vert|both\n"
+ " flip (mirror) image or region horizontally, vertically, or "
+ "both\n"
+ " -R # [90,180,or 270] degrees clockwise rotation of image or "
+ "extracted region\n"
+ " -I [black|white|data|both]\n"
+ " invert color space, eg dark to light for bilevel and "
+ "grayscale images\n"
+ " If argument is white or black, set the "
+ "PHOTOMETRIC_INTERPRETATION \n"
+ " tag to MinIsBlack or MinIsWhite without altering the image "
+ "data\n"
+ " If the argument is data or both, the image data are "
+ "modified:\n"
+ " both inverts the data and the PHOTOMETRIC_INTERPRETATION "
+ "tag,\n"
+ " data inverts the data but not the PHOTOMETRIC_INTERPRETATION "
+ "tag\n"
+ "\n"
+ "-D opt1:value1,opt2:value2,opt3:value3:opt4:value4\n"
+ " Debug/dump program progress and/or data to non-TIFF files.\n"
+ " Options include the following and must be joined as a comma\n"
+ " separate list. The use of this option is generally limited "
+ "to\n"
+ " program debugging and development of future options.\n"
+ "\n"
+ " debug:N Display limited program progress indicators where larger N\n"
+ " increase the level of detail. Note: Tiffcrop may be compiled "
+ "with\n"
+ " -DDEVELMODE to enable additional very low level debug "
+ "reporting.\n"
+ "\n"
+ " Format:txt|raw Format any logged data as ASCII text or raw binary \n"
+ " values. ASCII text dumps include strings of ones and zeroes\n"
+ " representing the binary values in the image data plus "
+ "identifying headers.\n"
+ "\n"
+ " level:N Specify the level of detail presented in the dump files.\n"
+ " This can vary from dumps of the entire input or output image "
+ "data to dumps\n"
+ " of data processed by specific functions. Current range of "
+ "levels is 1 to 3.\n"
+ "\n"
+ " input:full-path-to-directory/input-dumpname\n"
+ "\n"
+ " output:full-path-to-directory/output-dumpnaem\n"
+ "\n"
+ " When dump files are being written, each image will be "
+ "written to a separate\n"
+ " file with the name built by adding a numeric sequence value "
+ "to the dumpname\n"
+ " and an extension of .txt for ASCII dumps or .bin for binary "
+ "dumps.\n"
+ "\n"
+ " The four debug/dump options are independent, though it makes "
+ "little sense to\n"
+ " specify a dump file without specifying a detail level.\n"
+ "\n"
+ "Note 1: The (-X|-Y), -Z, -z and -S options are mutually exclusive.\n"
+ " In no case should the options be applied to a given "
+ "selection successively.\n"
+ "\n"
+ "Note 2: Any of the -X, -Y, -Z and -z options together with other "
+ "PAGE_MODE_x options\n"
+ " such as - H, -V, -P, -J or -K are not supported and may "
+ "cause buffer overflows.\n"
+ "\n";
+
+/* This function could be modified to pass starting sample offset
* and number of samples as args to select fewer than spp
- * from input image. These would then be passed to individual
+ * from input image. These would then be passed to individual
* extractContigSampleXX routines.
*/
-static int readContigTilesIntoBuffer (TIFF* in, uint8_t* buf,
- uint32_t imagelength,
- uint32_t imagewidth,
- uint32_t tw, uint32_t tl,
- tsample_t spp, uint16_t bps)
- {
- int status = 1;
- tsample_t sample = 0;
- tsample_t count = spp;
- uint32_t row, col, trow;
- uint32_t nrow, ncol;
- uint32_t dst_rowsize, shift_width;
- uint32_t bytes_per_sample, bytes_per_pixel;
- uint32_t trailing_bits, prev_trailing_bits;
- tmsize_t tile_rowsize = TIFFTileRowSize(in);
- tmsize_t src_offset, dst_offset;
- uint32_t row_offset, col_offset;
- uint8_t *bufp = (uint8_t*) buf;
- unsigned char *src = NULL;
- unsigned char *dst = NULL;
- tsize_t tbytes = 0, tile_buffsize = 0;
- tsize_t tilesize = TIFFTileSize(in);
- unsigned char *tilebuf = NULL;
-
- bytes_per_sample = (bps + 7) / 8;
- bytes_per_pixel = ((bps * spp) + 7) / 8;
-
- if ((bps % 8) == 0)
- shift_width = 0;
- else
- {
- if (bytes_per_pixel < (bytes_per_sample + 1))
- shift_width = bytes_per_pixel;
+static int readContigTilesIntoBuffer(TIFF *in, uint8_t *buf,
+ uint32_t imagelength, uint32_t imagewidth,
+ uint32_t tw, uint32_t tl, tsample_t spp,
+ uint16_t bps)
+{
+ int status = 1;
+ tsample_t sample = 0;
+ tsample_t count = spp;
+ uint32_t row, col, trow;
+ uint32_t nrow, ncol;
+ uint32_t dst_rowsize, shift_width;
+ uint32_t bytes_per_sample, bytes_per_pixel;
+ uint32_t trailing_bits, prev_trailing_bits;
+ tmsize_t tile_rowsize = TIFFTileRowSize(in);
+ tmsize_t src_offset, dst_offset;
+ uint32_t row_offset, col_offset;
+ uint8_t *bufp = (uint8_t *)buf;
+ unsigned char *src = NULL;
+ unsigned char *dst = NULL;
+ tsize_t tbytes = 0, tile_buffsize = 0;
+ tsize_t tilesize = TIFFTileSize(in);
+ unsigned char *tilebuf = NULL;
+
+ bytes_per_sample = (bps + 7) / 8;
+ bytes_per_pixel = ((bps * spp) + 7) / 8;
+
+ if ((bps % 8) == 0)
+ shift_width = 0;
else
- shift_width = bytes_per_sample + 1;
+ {
+ if (bytes_per_pixel < (bytes_per_sample + 1))
+ shift_width = bytes_per_pixel;
+ else
+ shift_width = bytes_per_sample + 1;
}
- tile_buffsize = tilesize;
- if (tilesize == 0 || tile_rowsize == 0)
- {
- TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero");
- exit(EXIT_FAILURE);
- }
+ tile_buffsize = tilesize;
+ if (tilesize == 0 || tile_rowsize == 0)
+ {
+ TIFFError("readContigTilesIntoBuffer",
+ "Tile size or tile rowsize is zero");
+ exit(EXIT_FAILURE);
+ }
- if (tilesize < (tsize_t)(tl * tile_rowsize))
+ if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
- TIFFError("readContigTilesIntoBuffer",
- "Tilesize %"PRId64" is too small, using alternate calculation %"PRIu64,
- tilesize, tl * tile_rowsize);
+ TIFFError("readContigTilesIntoBuffer",
+ "Tilesize %" PRId64
+ " is too small, using alternate calculation %" PRIu64,
+ tilesize, tl * tile_rowsize);
#endif
- if (tile_rowsize != 0 && (tmsize_t)tl > (TIFF_TMSIZE_T_MAX / tile_rowsize))
+ if (tile_rowsize != 0 &&
+ (tmsize_t)tl > (TIFF_TMSIZE_T_MAX / tile_rowsize))
+ {
+ TIFFError("readContigTilesIntoBuffer",
+ "Integer overflow when calculating buffer size.");
+ exit(EXIT_FAILURE);
+ }
+ tile_buffsize = tl * tile_rowsize;
+ }
+
+ /* Add 3 padding bytes for extractContigSamplesShifted32bits */
+ if ((size_t)tile_buffsize > TIFF_TMSIZE_T_MAX - NUM_BUFF_OVERSIZE_BYTES)
{
- TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
+ TIFFError("readContigTilesIntoBuffer",
+ "Integer overflow when calculating buffer size.");
exit(EXIT_FAILURE);
}
- tile_buffsize = tl * tile_rowsize;
+ tilebuf = limitMalloc(tile_buffsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (tilebuf == 0)
+ return 0;
+ tilebuf[tile_buffsize] = 0;
+ tilebuf[tile_buffsize + 1] = 0;
+ tilebuf[tile_buffsize + 2] = 0;
+
+ dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
+ for (row = 0; row < imagelength; row += tl)
+ {
+ nrow = (row + tl > imagelength) ? imagelength - row : tl;
+ for (col = 0; col < imagewidth; col += tw)
+ {
+ tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0);
+ if (tbytes < tilesize && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read tile at row %" PRIu32
+ " col %" PRIu32 ", Read %" TIFF_SSIZE_FORMAT
+ " bytes of %" TIFF_SSIZE_FORMAT,
+ col, row, tbytes, tilesize);
+ status = 0;
+ _TIFFfree(tilebuf);
+ return status;
+ }
+
+ row_offset = row * dst_rowsize;
+ col_offset = ((col * bps * spp) + 7) / 8;
+ bufp = buf + row_offset + col_offset;
+
+ if (col + tw > imagewidth)
+ ncol = imagewidth - col;
+ else
+ ncol = tw;
+
+ /* Each tile scanline will start on a byte boundary but it
+ * has to be merged into the scanline for the entire
+ * image buffer and the previous segment may not have
+ * ended on a byte boundary
+ */
+ /* Optimization for common bit depths, all samples */
+ if (((bps % 8) == 0) && (count == spp))
+ {
+ for (trow = 0; trow < nrow; trow++)
+ {
+ src_offset = trow * tile_rowsize;
+ _TIFFmemcpy(bufp, tilebuf + src_offset,
+ (ncol * spp * bps) / 8);
+ bufp += (imagewidth * bps * spp) / 8;
+ }
+ }
+ else
+ {
+ /* Bit depths not a multiple of 8 and/or extract fewer than spp
+ * samples */
+ prev_trailing_bits = trailing_bits = 0;
+ trailing_bits = (ncol * bps * spp) % 8;
+
+ /* for (trow = 0; tl < nrow; trow++) */
+ for (trow = 0; trow < nrow; trow++)
+ {
+ src_offset = trow * tile_rowsize;
+ src = tilebuf + src_offset;
+ dst_offset = (row + trow) * (tmsize_t)dst_rowsize;
+ dst = buf + dst_offset + col_offset;
+ switch (shift_width)
+ {
+ case 0:
+ if (extractContigSamplesBytes(src, dst, ncol,
+ sample, spp, bps,
+ count, 0, ncol))
+ {
+ TIFFError("readContigTilesIntoBuffer",
+ "Unable to extract row %" PRIu32
+ " from tile %" PRIu32,
+ row, TIFFCurrentTile(in));
+ return 1;
+ }
+ break;
+ case 1:
+ if (bps == 1)
+ {
+ if (extractContigSamplesShifted8bits(
+ src, dst, ncol, sample, spp, bps, count,
+ 0, ncol, prev_trailing_bits))
+ {
+ TIFFError("readContigTilesIntoBuffer",
+ "Unable to extract row %" PRIu32
+ " from tile %" PRIu32,
+ row, TIFFCurrentTile(in));
+ return 1;
+ }
+ break;
+ }
+ else if (extractContigSamplesShifted16bits(
+ src, dst, ncol, sample, spp, bps,
+ count, 0, ncol, prev_trailing_bits))
+ {
+ TIFFError("readContigTilesIntoBuffer",
+ "Unable to extract row %" PRIu32
+ " from tile %" PRIu32,
+ row, TIFFCurrentTile(in));
+ return 1;
+ }
+ break;
+ case 2:
+ if (extractContigSamplesShifted24bits(
+ src, dst, ncol, sample, spp, bps, count, 0,
+ ncol, prev_trailing_bits))
+ {
+ TIFFError("readContigTilesIntoBuffer",
+ "Unable to extract row %" PRIu32
+ " from tile %" PRIu32,
+ row, TIFFCurrentTile(in));
+ return 1;
+ }
+ break;
+ case 3:
+ case 4:
+ case 5:
+ if (extractContigSamplesShifted32bits(
+ src, dst, ncol, sample, spp, bps, count, 0,
+ ncol, prev_trailing_bits))
+ {
+ TIFFError("readContigTilesIntoBuffer",
+ "Unable to extract row %" PRIu32
+ " from tile %" PRIu32,
+ row, TIFFCurrentTile(in));
+ return 1;
+ }
+ break;
+ default:
+ TIFFError("readContigTilesIntoBuffer",
+ "Unsupported bit depth %" PRIu16, bps);
+ return 1;
+ }
+ }
+ prev_trailing_bits += trailing_bits;
+ /* if (prev_trailing_bits > 7) */
+ /* prev_trailing_bits-= 8; */
+ }
+ }
}
- /* Add 3 padding bytes for extractContigSamplesShifted32bits */
- if( (size_t) tile_buffsize > TIFF_TMSIZE_T_MAX - NUM_BUFF_OVERSIZE_BYTES)
- {
- TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
- exit(EXIT_FAILURE);
- }
- tilebuf = limitMalloc(tile_buffsize + NUM_BUFF_OVERSIZE_BYTES);
- if (tilebuf == 0)
- return 0;
- tilebuf[tile_buffsize] = 0;
- tilebuf[tile_buffsize+1] = 0;
- tilebuf[tile_buffsize+2] = 0;
-
- dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
- for (row = 0; row < imagelength; row += tl)
- {
- nrow = (row + tl > imagelength) ? imagelength - row : tl;
- for (col = 0; col < imagewidth; col += tw)
- {
- tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0);
- if (tbytes < tilesize && !ignore)
- {
- TIFFError(TIFFFileName(in),
- "Error, can't read tile at row %"PRIu32" col %"PRIu32", Read %"TIFF_SSIZE_FORMAT" bytes of %"TIFF_SSIZE_FORMAT,
- col, row, tbytes, tilesize);
- status = 0;
- _TIFFfree(tilebuf);
- return status;
- }
-
- row_offset = row * dst_rowsize;
- col_offset = ((col * bps * spp) + 7)/ 8;
- bufp = buf + row_offset + col_offset;
-
- if (col + tw > imagewidth)
- ncol = imagewidth - col;
- else
- ncol = tw;
-
- /* Each tile scanline will start on a byte boundary but it
- * has to be merged into the scanline for the entire
- * image buffer and the previous segment may not have
- * ended on a byte boundary
- */
- /* Optimization for common bit depths, all samples */
- if (((bps % 8) == 0) && (count == spp))
- {
- for (trow = 0; trow < nrow; trow++)
- {
- src_offset = trow * tile_rowsize;
- _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8);
- bufp += (imagewidth * bps * spp) / 8;
- }
- }
- else
- {
- /* Bit depths not a multiple of 8 and/or extract fewer than spp samples */
- prev_trailing_bits = trailing_bits = 0;
- trailing_bits = (ncol * bps * spp) % 8;
-
- /* for (trow = 0; tl < nrow; trow++) */
- for (trow = 0; trow < nrow; trow++)
- {
- src_offset = trow * tile_rowsize;
- src = tilebuf + src_offset;
- dst_offset = (row + trow) * (tmsize_t)dst_rowsize;
- dst = buf + dst_offset + col_offset;
- switch (shift_width)
- {
- case 0: if (extractContigSamplesBytes (src, dst, ncol, sample,
- spp, bps, count, 0, ncol))
- {
- TIFFError("readContigTilesIntoBuffer",
- "Unable to extract row %"PRIu32" from tile %"PRIu32,
- row, TIFFCurrentTile(in));
- return 1;
- }
- break;
- case 1: if (bps == 1)
- {
- if (extractContigSamplesShifted8bits (src, dst, ncol,
- sample, spp,
- bps, count,
- 0, ncol,
- prev_trailing_bits))
- {
- TIFFError("readContigTilesIntoBuffer",
- "Unable to extract row %"PRIu32" from tile %"PRIu32,
- row, TIFFCurrentTile(in));
- return 1;
- }
- break;
- }
- else
- if (extractContigSamplesShifted16bits (src, dst, ncol,
- sample, spp,
- bps, count,
- 0, ncol,
- prev_trailing_bits))
- {
- TIFFError("readContigTilesIntoBuffer",
- "Unable to extract row %"PRIu32" from tile %"PRIu32,
- row, TIFFCurrentTile(in));
- return 1;
- }
- break;
- case 2: if (extractContigSamplesShifted24bits (src, dst, ncol,
- sample, spp,
- bps, count,
- 0, ncol,
- prev_trailing_bits))
- {
- TIFFError("readContigTilesIntoBuffer",
- "Unable to extract row %"PRIu32" from tile %"PRIu32,
- row, TIFFCurrentTile(in));
- return 1;
- }
- break;
- case 3:
- case 4:
- case 5: if (extractContigSamplesShifted32bits (src, dst, ncol,
- sample, spp,
- bps, count,
- 0, ncol,
- prev_trailing_bits))
- {
- TIFFError("readContigTilesIntoBuffer",
- "Unable to extract row %"PRIu32" from tile %"PRIu32,
- row, TIFFCurrentTile(in));
- return 1;
- }
- break;
- default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %"PRIu16, bps);
- return 1;
- }
- }
- prev_trailing_bits += trailing_bits;
- /* if (prev_trailing_bits > 7) */
- /* prev_trailing_bits-= 8; */
- }
- }
- }
-
- _TIFFfree(tilebuf);
- return status;
- }
-
-static int readSeparateTilesIntoBuffer (TIFF* in, uint8_t *obuf,
- uint32_t imagelength, uint32_t imagewidth,
- uint32_t tw, uint32_t tl,
- uint16_t spp, uint16_t bps)
- {
- int i, status = 1, sample;
- int shift_width, bytes_per_pixel;
- uint16_t bytes_per_sample;
- uint32_t row, col; /* Current row and col of image */
- uint32_t nrow, ncol; /* Number of rows and cols in current tile */
- uint32_t row_offset, col_offset; /* Output buffer offsets */
- tsize_t tbytes = 0, tilesize = TIFFTileSize(in);
- tsample_t s;
- uint8_t* bufp = (uint8_t*)obuf;
- unsigned char *srcbuffs[MAX_SAMPLES];
- unsigned char *tbuff = NULL;
-
- bytes_per_sample = (bps + 7) / 8;
-
- for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
- {
- srcbuffs[sample] = NULL;
- tbuff = (unsigned char *)limitMalloc(tilesize + NUM_BUFF_OVERSIZE_BYTES);
- if (!tbuff)
- {
- TIFFError ("readSeparateTilesIntoBuffer",
- "Unable to allocate tile read buffer for sample %d", sample);
- for (i = 0; i < sample; i++)
- _TIFFfree (srcbuffs[i]);
- return 0;
- }
- srcbuffs[sample] = tbuff;
- }
- /* Each tile contains only the data for a single plane
- * arranged in scanlines of tw * bytes_per_sample bytes.
- */
- for (row = 0; row < imagelength; row += tl)
- {
- nrow = (row + tl > imagelength) ? imagelength - row : tl;
- for (col = 0; col < imagewidth; col += tw)
- {
- for (s = 0; s < spp && s < MAX_SAMPLES; s++)
- { /* Read each plane of a tile set into srcbuffs[s] */
- tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s);
- if (tbytes < 0 && !ignore)
- {
- TIFFError(TIFFFileName(in),
- "Error, can't read tile for row %"PRIu32" col %"PRIu32", "
- "sample %"PRIu16,
- col, row, s);
- status = 0;
- for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
- {
- tbuff = srcbuffs[sample];
- if (tbuff != NULL)
- _TIFFfree(tbuff);
- }
- return status;
- }
- }
- /* Tiles on the right edge may be padded out to tw
- * which must be a multiple of 16.
- * Ncol represents the visible (non padding) portion.
- */
- if (col + tw > imagewidth)
- ncol = imagewidth - col;
- else
- ncol = tw;
-
- row_offset = row * (((imagewidth * spp * bps) + 7) / 8);
- col_offset = ((col * spp * bps) + 7) / 8;
- bufp = obuf + row_offset + col_offset;
-
- if ((bps % 8) == 0)
- {
- if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth,
- tw, spp, bps, NULL, 0, 0))
- {
- status = 0;
- break;
- }
- }
- else
- {
- bytes_per_pixel = ((bps * spp) + 7) / 8;
- if (bytes_per_pixel < (bytes_per_sample + 1))
- shift_width = bytes_per_pixel;
- else
- shift_width = bytes_per_sample + 1;
+ _TIFFfree(tilebuf);
+ return status;
+}
- switch (shift_width)
- {
- case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow,
- imagewidth, tw, spp, bps,
- NULL, 0, 0))
- {
- status = 0;
- break;
- }
- break;
- case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow,
- imagewidth, tw, spp, bps,
- NULL, 0, 0))
- {
- status = 0;
- break;
- }
- break;
- case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow,
- imagewidth, tw, spp, bps,
- NULL, 0, 0))
- {
+static int readSeparateTilesIntoBuffer(TIFF *in, uint8_t *obuf,
+ uint32_t imagelength,
+ uint32_t imagewidth, uint32_t tw,
+ uint32_t tl, uint16_t spp, uint16_t bps)
+{
+ int i, status = 1, sample;
+ int shift_width, bytes_per_pixel;
+ uint16_t bytes_per_sample;
+ uint32_t row, col; /* Current row and col of image */
+ uint32_t nrow, ncol; /* Number of rows and cols in current tile */
+ uint32_t row_offset, col_offset; /* Output buffer offsets */
+ tsize_t tbytes = 0, tilesize = TIFFTileSize(in);
+ tsample_t s;
+ uint8_t *bufp = (uint8_t *)obuf;
+ unsigned char *srcbuffs[MAX_SAMPLES];
+ unsigned char *tbuff = NULL;
+
+ bytes_per_sample = (bps + 7) / 8;
+
+ for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
+ {
+ srcbuffs[sample] = NULL;
+ tbuff =
+ (unsigned char *)limitMalloc(tilesize + NUM_BUFF_OVERSIZE_BYTES);
+ if (!tbuff)
+ {
+ TIFFError("readSeparateTilesIntoBuffer",
+ "Unable to allocate tile read buffer for sample %d",
+ sample);
+ for (i = 0; i < sample; i++)
+ _TIFFfree(srcbuffs[i]);
+ return 0;
+ }
+ srcbuffs[sample] = tbuff;
+ }
+ /* Each tile contains only the data for a single plane
+ * arranged in scanlines of tw * bytes_per_sample bytes.
+ */
+ for (row = 0; row < imagelength; row += tl)
+ {
+ nrow = (row + tl > imagelength) ? imagelength - row : tl;
+ for (col = 0; col < imagewidth; col += tw)
+ {
+ for (s = 0; s < spp && s < MAX_SAMPLES; s++)
+ { /* Read each plane of a tile set into srcbuffs[s] */
+ tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s);
+ if (tbytes < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read tile for row %" PRIu32
+ " col %" PRIu32 ", "
+ "sample %" PRIu16,
+ col, row, s);
status = 0;
- break;
- }
- break;
- case 4:
- case 5:
- case 6:
- case 7:
- case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow,
- imagewidth, tw, spp, bps,
- NULL, 0, 0))
- {
+ for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES);
+ sample++)
+ {
+ tbuff = srcbuffs[sample];
+ if (tbuff != NULL)
+ _TIFFfree(tbuff);
+ }
+ return status;
+ }
+ }
+ /* Tiles on the right edge may be padded out to tw
+ * which must be a multiple of 16.
+ * Ncol represents the visible (non padding) portion.
+ */
+ if (col + tw > imagewidth)
+ ncol = imagewidth - col;
+ else
+ ncol = tw;
+
+ row_offset = row * (((imagewidth * spp * bps) + 7) / 8);
+ col_offset = ((col * spp * bps) + 7) / 8;
+ bufp = obuf + row_offset + col_offset;
+
+ if ((bps % 8) == 0)
+ {
+ if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow,
+ imagewidth, tw, spp, bps,
+ NULL, 0, 0))
+ {
status = 0;
break;
- }
- break;
- default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %"PRIu16, bps);
- status = 0;
- break;
- }
+ }
+ }
+ else
+ {
+ bytes_per_pixel = ((bps * spp) + 7) / 8;
+ if (bytes_per_pixel < (bytes_per_sample + 1))
+ shift_width = bytes_per_pixel;
+ else
+ shift_width = bytes_per_sample + 1;
+
+ switch (shift_width)
+ {
+ case 1:
+ if (combineSeparateTileSamples8bits(
+ srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp,
+ bps, NULL, 0, 0))
+ {
+ status = 0;
+ break;
+ }
+ break;
+ case 2:
+ if (combineSeparateTileSamples16bits(
+ srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp,
+ bps, NULL, 0, 0))
+ {
+ status = 0;
+ break;
+ }
+ break;
+ case 3:
+ if (combineSeparateTileSamples24bits(
+ srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp,
+ bps, NULL, 0, 0))
+ {
+ status = 0;
+ break;
+ }
+ break;
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ if (combineSeparateTileSamples32bits(
+ srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp,
+ bps, NULL, 0, 0))
+ {
+ status = 0;
+ break;
+ }
+ break;
+ default:
+ TIFFError("readSeparateTilesIntoBuffer",
+ "Unsupported bit depth: %" PRIu16, bps);
+ status = 0;
+ break;
+ }
+ }
}
- }
}
- for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
+ for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
- tbuff = srcbuffs[sample];
- if (tbuff != NULL)
- _TIFFfree(tbuff);
+ tbuff = srcbuffs[sample];
+ if (tbuff != NULL)
+ _TIFFfree(tbuff);
}
-
- return status;
- }
-static int writeBufferToContigStrips(TIFF* out, uint8_t* buf, uint32_t imagelength)
- {
- uint32_t row, nrows, rowsperstrip;
- tstrip_t strip = 0;
- tsize_t stripsize;
+ return status;
+}
+
+static int writeBufferToContigStrips(TIFF *out, uint8_t *buf,
+ uint32_t imagelength)
+{
+ uint32_t row, nrows, rowsperstrip;
+ tstrip_t strip = 0;
+ tsize_t stripsize;
- TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
- for (row = 0; row < imagelength; row += rowsperstrip)
+ TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
+ for (row = 0; row < imagelength; row += rowsperstrip)
{
- nrows = (row + rowsperstrip > imagelength) ?
- imagelength - row : rowsperstrip;
- stripsize = TIFFVStripSize(out, nrows);
- if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0)
- {
- TIFFError(TIFFFileName(out), "Error, can't write strip %"PRIu32, strip - 1);
- return 1;
- }
- buf += stripsize;
+ nrows = (row + rowsperstrip > imagelength) ? imagelength - row
+ : rowsperstrip;
+ stripsize = TIFFVStripSize(out, nrows);
+ if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0)
+ {
+ TIFFError(TIFFFileName(out), "Error, can't write strip %" PRIu32,
+ strip - 1);
+ return 1;
+ }
+ buf += stripsize;
}
- return 0;
- }
+ return 0;
+}
/* Abandon plans to modify code so that plannar orientation separate images
* do not have all samples for each channel written before all samples
* for the next channel have been abandoned.
* Libtiff internals seem to depend on all data for a given sample
- * being contiguous within a strip or tile when PLANAR_CONFIG is
+ * being contiguous within a strip or tile when PLANAR_CONFIG is
* separate. All strips or tiles of a given plane are written
* before any strips or tiles of a different plane are stored.
*/
-static int
-writeBufferToSeparateStrips (TIFF* out, uint8_t* buf,
- uint32_t length, uint32_t width, uint16_t spp,
- struct dump_opts *dump)
- {
- uint8_t *src;
- uint16_t bps;
- uint32_t row, nrows, rowsize, rowsperstrip;
- uint32_t bytes_per_sample;
- tsample_t s;
- tstrip_t strip = 0;
- tsize_t stripsize = TIFFStripSize(out);
- tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out);
- tdata_t obuf;
-
- (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
- (void) TIFFGetFieldDefaulted(out, TIFFTAG_BITSPERSAMPLE, &bps);
- bytes_per_sample = (bps + 7) / 8;
- if( width == 0 ||
- (uint32_t)bps * (uint32_t)spp > UINT32_MAX / width ||
- bps * spp * width > UINT32_MAX - 7U )
- {
- TIFFError(TIFFFileName(out),
+static int writeBufferToSeparateStrips(TIFF *out, uint8_t *buf, uint32_t length,
+ uint32_t width, uint16_t spp,
+ struct dump_opts *dump)
+{
+ uint8_t *src;
+ uint16_t bps;
+ uint32_t row, nrows, rowsize, rowsperstrip;
+ uint32_t bytes_per_sample;
+ tsample_t s;
+ tstrip_t strip = 0;
+ tsize_t stripsize = TIFFStripSize(out);
+ tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out);
+ tdata_t obuf;
+
+ (void)TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
+ (void)TIFFGetFieldDefaulted(out, TIFFTAG_BITSPERSAMPLE, &bps);
+ bytes_per_sample = (bps + 7) / 8;
+ if (width == 0 || (uint32_t)bps * (uint32_t)spp > UINT32_MAX / width ||
+ bps * spp * width > UINT32_MAX - 7U)
+ {
+ TIFFError(
+ TIFFFileName(out),
"Error, uint32_t overflow when computing (bps * spp * width) + 7");
- return 1;
- }
- rowsize = ((bps * spp * width) + 7U) / 8; /* source has interleaved samples */
- if( bytes_per_sample == 0 ||
- rowsperstrip > UINT32_MAX / bytes_per_sample ||
- rowsperstrip * bytes_per_sample > UINT32_MAX / (width + 1) )
- {
- TIFFError(TIFFFileName(out),
- "Error, uint32_t overflow when computing rowsperstrip * "
- "bytes_per_sample * (width + 1)");
- return 1;
- }
- rowstripsize = rowsperstrip * bytes_per_sample * (width + 1);
-
- /* Add 3 padding bytes for extractContigSamples32bits */
- obuf = limitMalloc (rowstripsize + NUM_BUFF_OVERSIZE_BYTES);
- if (obuf == NULL)
- return 1;
-
- for (s = 0; s < spp; s++)
+ return 1;
+ }
+ rowsize =
+ ((bps * spp * width) + 7U) / 8; /* source has interleaved samples */
+ if (bytes_per_sample == 0 || rowsperstrip > UINT32_MAX / bytes_per_sample ||
+ rowsperstrip * bytes_per_sample > UINT32_MAX / (width + 1))
{
- for (row = 0; row < length; row += rowsperstrip)
- {
- nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip;
+ TIFFError(TIFFFileName(out),
+ "Error, uint32_t overflow when computing rowsperstrip * "
+ "bytes_per_sample * (width + 1)");
+ return 1;
+ }
+ rowstripsize = rowsperstrip * bytes_per_sample * (width + 1);
- stripsize = TIFFVStripSize(out, nrows);
- src = buf + (row * rowsize);
- memset (obuf, '\0',rowstripsize + NUM_BUFF_OVERSIZE_BYTES);
- if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump))
- {
- _TIFFfree(obuf);
+ /* Add 3 padding bytes for extractContigSamples32bits */
+ obuf = limitMalloc(rowstripsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (obuf == NULL)
return 1;
- }
- if ((dump->outfile != NULL) && (dump->level == 1))
- {
- if ((uint64_t)scanlinesize > 0x0ffffffffULL) {
- dump_info(dump->infile, dump->format, "loadImage",
- "Attention: scanlinesize %"PRIu64" is larger than UINT32_MAX.\nFollowing dump might be wrong.",
- (uint64_t)scanlinesize);
- }
- dump_info(dump->outfile, dump->format,"",
- "Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d",
- s + 1, strip + 1, stripsize, row + 1, (uint32_t)scanlinesize, src - buf);
- dump_buffer(dump->outfile, dump->format, nrows, (uint32_t)scanlinesize, row, obuf);
- }
-
- if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0)
- {
- TIFFError(TIFFFileName(out), "Error, can't write strip %"PRIu32, strip - 1);
- _TIFFfree(obuf);
- return 1;
- }
- }
- }
-
- _TIFFfree(obuf);
- return 0;
+
+ for (s = 0; s < spp; s++)
+ {
+ for (row = 0; row < length; row += rowsperstrip)
+ {
+ nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip;
+
+ stripsize = TIFFVStripSize(out, nrows);
+ src = buf + (row * rowsize);
+ memset(obuf, '\0', rowstripsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp,
+ bps, dump))
+ {
+ _TIFFfree(obuf);
+ return 1;
+ }
+ if ((dump->outfile != NULL) && (dump->level == 1))
+ {
+ if ((uint64_t)scanlinesize > 0x0ffffffffULL)
+ {
+ dump_info(dump->infile, dump->format, "loadImage",
+ "Attention: scanlinesize %" PRIu64
+ " is larger than UINT32_MAX.\nFollowing dump "
+ "might be wrong.",
+ (uint64_t)scanlinesize);
+ }
+ dump_info(dump->outfile, dump->format, "",
+ "Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: "
+ "%4d, Input offset: %6d",
+ s + 1, strip + 1, stripsize, row + 1,
+ (uint32_t)scanlinesize, src - buf);
+ dump_buffer(dump->outfile, dump->format, nrows,
+ (uint32_t)scanlinesize, row, obuf);
+ }
+
+ if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0)
+ {
+ TIFFError(TIFFFileName(out),
+ "Error, can't write strip %" PRIu32, strip - 1);
+ _TIFFfree(obuf);
+ return 1;
+ }
+ }
+ }
+
+ _TIFFfree(obuf);
+ return 0;
}
-/* Extract all planes from contiguous buffer into a single tile buffer
+/* Extract all planes from contiguous buffer into a single tile buffer
* to be written out as a tile.
*/
-static int writeBufferToContigTiles (TIFF* out, uint8_t* buf, uint32_t imagelength,
- uint32_t imagewidth, tsample_t spp,
- struct dump_opts* dump)
- {
- uint16_t bps;
- uint32_t tl, tw;
- uint32_t row, col, nrow, ncol;
- uint32_t src_rowsize, col_offset;
- tmsize_t tile_rowsize = TIFFTileRowSize(out);
- uint8_t* bufp = (uint8_t*) buf;
- tsize_t tile_buffsize = 0;
- tsize_t tilesize = TIFFTileSize(out);
- unsigned char *tilebuf = NULL;
-
- if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||
- !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||
- !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) )
- return 1;
-
- if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0)
- {
- TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero");
- exit(EXIT_FAILURE);
- }
-
- tile_buffsize = tilesize;
- if (tilesize < (tsize_t)(tl * tile_rowsize))
+static int writeBufferToContigTiles(TIFF *out, uint8_t *buf,
+ uint32_t imagelength, uint32_t imagewidth,
+ tsample_t spp, struct dump_opts *dump)
+{
+ uint16_t bps;
+ uint32_t tl, tw;
+ uint32_t row, col, nrow, ncol;
+ uint32_t src_rowsize, col_offset;
+ tmsize_t tile_rowsize = TIFFTileRowSize(out);
+ uint8_t *bufp = (uint8_t *)buf;
+ tsize_t tile_buffsize = 0;
+ tsize_t tilesize = TIFFTileSize(out);
+ unsigned char *tilebuf = NULL;
+
+ if (!TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||
+ !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||
+ !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps))
+ return 1;
+
+ if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0)
+ {
+ TIFFError(
+ "writeBufferToContigTiles",
+ "Tile size, tile row size, tile width, or tile length is zero");
+ exit(EXIT_FAILURE);
+ }
+
+ tile_buffsize = tilesize;
+ if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
- TIFFError("writeBufferToContigTiles",
- "Tilesize %"PRId64" is too small, using alternate calculation %"PRIu32,
- tilesize, tl * tile_rowsize);
+ TIFFError("writeBufferToContigTiles",
+ "Tilesize %" PRId64
+ " is too small, using alternate calculation %" PRIu32,
+ tilesize, tl * tile_rowsize);
#endif
- if (tile_rowsize != 0 && (tmsize_t)tl > (TIFF_TMSIZE_T_MAX / tile_rowsize))
+ if (tile_rowsize != 0 &&
+ (tmsize_t)tl > (TIFF_TMSIZE_T_MAX / tile_rowsize))
+ {
+ TIFFError("writeBufferToContigTiles",
+ "Integer overflow when calculating buffer size");
+ exit(EXIT_FAILURE);
+ }
+ tile_buffsize = tl * tile_rowsize;
+ }
+
+ if (imagewidth == 0 ||
+ (uint32_t)bps * (uint32_t)spp > UINT32_MAX / imagewidth ||
+ bps * spp * imagewidth > UINT32_MAX - 7U)
{
- TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size");
- exit(EXIT_FAILURE);
+ TIFFError(TIFFFileName(out), "Error, uint32_t overflow when computing "
+ "(imagewidth * bps * spp) + 7");
+ return 1;
}
- tile_buffsize = tl * tile_rowsize;
+ src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
+
+ /* Add 3 padding bytes for extractContigSamples32bits */
+ tilebuf = limitMalloc(tile_buffsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (tilebuf == 0)
+ return 1;
+ memset(tilebuf, 0, tile_buffsize + NUM_BUFF_OVERSIZE_BYTES);
+ for (row = 0; row < imagelength; row += tl)
+ {
+ nrow = (row + tl > imagelength) ? imagelength - row : tl;
+ for (col = 0; col < imagewidth; col += tw)
+ {
+ /* Calculate visible portion of tile. */
+ if (col + tw > imagewidth)
+ ncol = imagewidth - col;
+ else
+ ncol = tw;
+
+ col_offset = (((col * bps * spp) + 7) / 8);
+ bufp = buf + (row * src_rowsize) + col_offset;
+ if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol,
+ imagewidth, tw, 0, spp, spp,
+ bps, dump) > 0)
+ {
+ TIFFError("writeBufferToContigTiles",
+ "Unable to extract data to tile for row %" PRIu32
+ ", col %" PRIu32,
+ row, col);
+ _TIFFfree(tilebuf);
+ return 1;
+ }
+
+ if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0)
+ {
+ TIFFError("writeBufferToContigTiles",
+ "Cannot write tile at %" PRIu32 " %" PRIu32, col,
+ row);
+ _TIFFfree(tilebuf);
+ return 1;
+ }
+ }
}
+ _TIFFfree(tilebuf);
- if( imagewidth == 0 ||
- (uint32_t)bps * (uint32_t)spp > UINT32_MAX / imagewidth ||
- bps * spp * imagewidth > UINT32_MAX - 7U )
- {
- TIFFError(TIFFFileName(out),
- "Error, uint32_t overflow when computing (imagewidth * bps * spp) + 7");
- return 1;
- }
- src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
+ return 0;
+} /* end writeBufferToContigTiles */
- /* Add 3 padding bytes for extractContigSamples32bits */
- tilebuf = limitMalloc(tile_buffsize + NUM_BUFF_OVERSIZE_BYTES);
- if (tilebuf == 0)
- return 1;
- memset(tilebuf, 0, tile_buffsize + NUM_BUFF_OVERSIZE_BYTES);
- for (row = 0; row < imagelength; row += tl)
- {
- nrow = (row + tl > imagelength) ? imagelength - row : tl;
- for (col = 0; col < imagewidth; col += tw)
- {
- /* Calculate visible portion of tile. */
- if (col + tw > imagewidth)
- ncol = imagewidth - col;
- else
- ncol = tw;
-
- col_offset = (((col * bps * spp) + 7) / 8);
- bufp = buf + (row * src_rowsize) + col_offset;
- if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth,
- tw, 0, spp, spp, bps, dump) > 0)
- {
- TIFFError("writeBufferToContigTiles",
- "Unable to extract data to tile for row %"PRIu32", col %"PRIu32,
- row, col);
- _TIFFfree(tilebuf);
- return 1;
- }
-
- if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0)
- {
- TIFFError("writeBufferToContigTiles",
- "Cannot write tile at %"PRIu32" %"PRIu32,
- col, row);
- _TIFFfree(tilebuf);
- return 1;
- }
- }
- }
- _TIFFfree(tilebuf);
-
- return 0;
- } /* end writeBufferToContigTiles */
-
-/* Extract each plane from contiguous buffer into a single tile buffer
+/* Extract each plane from contiguous buffer into a single tile buffer
* to be written out as a tile.
*/
-static int writeBufferToSeparateTiles (TIFF* out, uint8_t* buf, uint32_t imagelength,
- uint32_t imagewidth, tsample_t spp,
- struct dump_opts * dump)
- {
- /* Add 3 padding bytes for extractContigSamples32bits */
- tdata_t obuf = limitMalloc(TIFFTileSize(out) + NUM_BUFF_OVERSIZE_BYTES);
- uint32_t tl, tw;
- uint32_t row, col, nrow, ncol;
- uint32_t src_rowsize, col_offset;
- uint16_t bps;
- tsample_t s;
- uint8_t* bufp = (uint8_t*) buf;
-
- if (obuf == NULL)
- return 1;
- memset(obuf, 0, TIFFTileSize(out) + NUM_BUFF_OVERSIZE_BYTES);
-
- if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||
- !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||
- !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) )
- {
- _TIFFfree(obuf);
- return 1;
- }
-
- if( imagewidth == 0 ||
- (uint32_t)bps * (uint32_t)spp > UINT32_MAX / imagewidth ||
- bps * spp * imagewidth > UINT32_MAX - 7 )
- {
- TIFFError(TIFFFileName(out),
- "Error, uint32_t overflow when computing (imagewidth * bps * spp) + 7");
- _TIFFfree(obuf);
- return 1;
- }
- src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
-
- for (row = 0; row < imagelength; row += tl)
- {
- nrow = (row + tl > imagelength) ? imagelength - row : tl;
- for (col = 0; col < imagewidth; col += tw)
- {
- /* Calculate visible portion of tile. */
- if (col + tw > imagewidth)
- ncol = imagewidth - col;
- else
- ncol = tw;
-
- col_offset = (((col * bps * spp) + 7) / 8);
- bufp = buf + (row * src_rowsize) + col_offset;
-
- for (s = 0; s < spp; s++)
- {
- if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth,
- tw, s, 1, spp, bps, dump) > 0)
- {
- TIFFError("writeBufferToSeparateTiles",
- "Unable to extract data to tile for row %"PRIu32", col %"PRIu32" sample %"PRIu16,
- row, col, s);
- _TIFFfree(obuf);
- return 1;
- }
-
- if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0)
- {
- TIFFError("writeBufferToseparateTiles",
- "Cannot write tile at %"PRIu32" %"PRIu32" sample %"PRIu16,
- col, row, s);
- _TIFFfree(obuf);
- return 1;
- }
- }
- }
- }
- _TIFFfree(obuf);
-
- return 0;
- } /* end writeBufferToSeparateTiles */
-
-static void
-processG3Options(char* cp)
+static int writeBufferToSeparateTiles(TIFF *out, uint8_t *buf,
+ uint32_t imagelength, uint32_t imagewidth,
+ tsample_t spp, struct dump_opts *dump)
+{
+ /* Add 3 padding bytes for extractContigSamples32bits */
+ tdata_t obuf = limitMalloc(TIFFTileSize(out) + NUM_BUFF_OVERSIZE_BYTES);
+ uint32_t tl, tw;
+ uint32_t row, col, nrow, ncol;
+ uint32_t src_rowsize, col_offset;
+ uint16_t bps;
+ tsample_t s;
+ uint8_t *bufp = (uint8_t *)buf;
+
+ if (obuf == NULL)
+ return 1;
+ memset(obuf, 0, TIFFTileSize(out) + NUM_BUFF_OVERSIZE_BYTES);
+
+ if (!TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||
+ !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||
+ !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps))
+ {
+ _TIFFfree(obuf);
+ return 1;
+ }
+
+ if (imagewidth == 0 ||
+ (uint32_t)bps * (uint32_t)spp > UINT32_MAX / imagewidth ||
+ bps * spp * imagewidth > UINT32_MAX - 7)
+ {
+ TIFFError(TIFFFileName(out), "Error, uint32_t overflow when computing "
+ "(imagewidth * bps * spp) + 7");
+ _TIFFfree(obuf);
+ return 1;
+ }
+ src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
+
+ for (row = 0; row < imagelength; row += tl)
+ {
+ nrow = (row + tl > imagelength) ? imagelength - row : tl;
+ for (col = 0; col < imagewidth; col += tw)
+ {
+ /* Calculate visible portion of tile. */
+ if (col + tw > imagewidth)
+ ncol = imagewidth - col;
+ else
+ ncol = tw;
+
+ col_offset = (((col * bps * spp) + 7) / 8);
+ bufp = buf + (row * src_rowsize) + col_offset;
+
+ for (s = 0; s < spp; s++)
+ {
+ if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol,
+ imagewidth, tw, s, 1, spp,
+ bps, dump) > 0)
+ {
+ TIFFError("writeBufferToSeparateTiles",
+ "Unable to extract data to tile for row %" PRIu32
+ ", col %" PRIu32 " sample %" PRIu16,
+ row, col, s);
+ _TIFFfree(obuf);
+ return 1;
+ }
+
+ if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0)
+ {
+ TIFFError("writeBufferToseparateTiles",
+ "Cannot write tile at %" PRIu32 " %" PRIu32
+ " sample %" PRIu16,
+ col, row, s);
+ _TIFFfree(obuf);
+ return 1;
+ }
+ }
+ }
+ }
+ _TIFFfree(obuf);
+
+ return 0;
+} /* end writeBufferToSeparateTiles */
+
+static void processG3Options(char *cp)
{
- if( (cp = strchr(cp, ':')) ) {
- if (defg3opts == (uint32_t) -1)
- defg3opts = 0;
- do {
- cp++;
- if (strneq(cp, "1d", 2))
- defg3opts &= ~GROUP3OPT_2DENCODING;
- else if (strneq(cp, "2d", 2))
- defg3opts |= GROUP3OPT_2DENCODING;
- else if (strneq(cp, "fill", 4))
- defg3opts |= GROUP3OPT_FILLBITS;
- else
- usage(EXIT_FAILURE);
- } while( (cp = strchr(cp, ':')) );
- }
+ if ((cp = strchr(cp, ':')))
+ {
+ if (defg3opts == (uint32_t)-1)
+ defg3opts = 0;
+ do
+ {
+ cp++;
+ if (strneq(cp, "1d", 2))
+ defg3opts &= ~GROUP3OPT_2DENCODING;
+ else if (strneq(cp, "2d", 2))
+ defg3opts |= GROUP3OPT_2DENCODING;
+ else if (strneq(cp, "fill", 4))
+ defg3opts |= GROUP3OPT_FILLBITS;
+ else
+ usage(EXIT_FAILURE);
+ } while ((cp = strchr(cp, ':')));
+ }
}
-static int
-processCompressOptions(char* opt)
- {
- char* cp = NULL;
+static int processCompressOptions(char *opt)
+{
+ char *cp = NULL;
- if (strneq(opt, "none",4))
+ if (strneq(opt, "none", 4))
{
- defcompression = COMPRESSION_NONE;
+ defcompression = COMPRESSION_NONE;
}
- else if (streq(opt, "packbits"))
+ else if (streq(opt, "packbits"))
{
- defcompression = COMPRESSION_PACKBITS;
+ defcompression = COMPRESSION_PACKBITS;
}
- else if (strneq(opt, "jpeg", 4))
+ else if (strneq(opt, "jpeg", 4))
{
- cp = strchr(opt, ':');
- defcompression = COMPRESSION_JPEG;
+ cp = strchr(opt, ':');
+ defcompression = COMPRESSION_JPEG;
- while (cp)
- {
- if (isdigit((int)cp[1]))
- quality = atoi(cp + 1);
- else if (strneq(cp + 1, "raw", 3 ))
- jpegcolormode = JPEGCOLORMODE_RAW;
- else if (strneq(cp + 1, "rgb", 3 ))
- jpegcolormode = JPEGCOLORMODE_RGB;
- else
- usage(EXIT_FAILURE);
- cp = strchr(cp + 1, ':');
- }
+ while (cp)
+ {
+ if (isdigit((int)cp[1]))
+ quality = atoi(cp + 1);
+ else if (strneq(cp + 1, "raw", 3))
+ jpegcolormode = JPEGCOLORMODE_RAW;
+ else if (strneq(cp + 1, "rgb", 3))
+ jpegcolormode = JPEGCOLORMODE_RGB;
+ else
+ usage(EXIT_FAILURE);
+ cp = strchr(cp + 1, ':');
+ }
}
- else if (strneq(opt, "g3", 2))
+ else if (strneq(opt, "g3", 2))
{
- processG3Options(opt);
- defcompression = COMPRESSION_CCITTFAX3;
+ processG3Options(opt);
+ defcompression = COMPRESSION_CCITTFAX3;
}
- else if (streq(opt, "g4"))
+ else if (streq(opt, "g4"))
{
- defcompression = COMPRESSION_CCITTFAX4;
+ defcompression = COMPRESSION_CCITTFAX4;
}
- else if (strneq(opt, "lzw", 3))
+ else if (strneq(opt, "lzw", 3))
{
- cp = strchr(opt, ':');
- if (cp)
- defpredictor = atoi(cp+1);
- defcompression = COMPRESSION_LZW;
+ cp = strchr(opt, ':');
+ if (cp)
+ defpredictor = atoi(cp + 1);
+ defcompression = COMPRESSION_LZW;
}
- else if (strneq(opt, "zip", 3))
+ else if (strneq(opt, "zip", 3))
{
- cp = strchr(opt, ':');
- if (cp)
- defpredictor = atoi(cp+1);
- defcompression = COMPRESSION_ADOBE_DEFLATE;
- }
- else
- return (0);
+ cp = strchr(opt, ':');
+ if (cp)
+ defpredictor = atoi(cp + 1);
+ defcompression = COMPRESSION_ADOBE_DEFLATE;
+ }
+ else
+ return (0);
- return (1);
- }
+ return (1);
+}
-static void
-usage(int code)
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "\n%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "\n%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
-#define CopyField(tag, v) \
- if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
-#define CopyField2(tag, v1, v2) \
- if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
-#define CopyField3(tag, v1, v2, v3) \
- if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
-#define CopyField4(tag, v1, v2, v3, v4) \
- if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
-
-static void
-cpTag(TIFF* in, TIFF* out, uint16_t tag, uint16_t count, TIFFDataType type)
+#define CopyField(tag, v) \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v)
+#define CopyField2(tag, v1, v2) \
+ if (TIFFGetField(in, tag, &v1, &v2)) \
+ TIFFSetField(out, tag, v1, v2)
+#define CopyField3(tag, v1, v2, v3) \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) \
+ TIFFSetField(out, tag, v1, v2, v3)
+#define CopyField4(tag, v1, v2, v3, v4) \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) \
+ TIFFSetField(out, tag, v1, v2, v3, v4)
+
+static void cpTag(TIFF *in, TIFF *out, uint16_t tag, uint16_t count,
+ TIFFDataType type)
{
- switch (type) {
- case TIFF_SHORT:
- if (count == 1) {
- uint16_t shortv;
- CopyField(tag, shortv);
- } else if (count == 2) {
- uint16_t shortv1, shortv2;
- CopyField2(tag, shortv1, shortv2);
- } else if (count == 4) {
- uint16_t *tr, *tg, *tb, *ta;
- CopyField4(tag, tr, tg, tb, ta);
- } else if (count == (uint16_t) -1) {
- uint16_t shortv1;
- uint16_t* shortav;
- CopyField2(tag, shortv1, shortav);
- }
- break;
- case TIFF_LONG:
- { uint32_t longv;
- CopyField(tag, longv);
- }
- break;
- case TIFF_RATIONAL:
- if (count == 1) {
- float floatv;
- CopyField(tag, floatv);
- } else if (count == (uint16_t) -1) {
- float* floatav;
- CopyField(tag, floatav);
- }
- break;
- case TIFF_ASCII:
- { char* stringv;
- CopyField(tag, stringv);
- }
- break;
- case TIFF_DOUBLE:
- if (count == 1) {
- double doublev;
- CopyField(tag, doublev);
- } else if (count == (uint16_t) -1) {
- double* doubleav;
- CopyField(tag, doubleav);
- }
- break;
- default:
- TIFFError(TIFFFileName(in),
- "Data type %"PRIu16" is not supported, tag %d skipped",
- tag, type);
- }
+ switch (type)
+ {
+ case TIFF_SHORT:
+ if (count == 1)
+ {
+ uint16_t shortv;
+ CopyField(tag, shortv);
+ }
+ else if (count == 2)
+ {
+ uint16_t shortv1, shortv2;
+ CopyField2(tag, shortv1, shortv2);
+ }
+ else if (count == 4)
+ {
+ uint16_t *tr, *tg, *tb, *ta;
+ CopyField4(tag, tr, tg, tb, ta);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ uint16_t shortv1;
+ uint16_t *shortav;
+ CopyField2(tag, shortv1, shortav);
+ }
+ break;
+ case TIFF_LONG:
+ {
+ uint32_t longv;
+ CopyField(tag, longv);
+ }
+ break;
+ case TIFF_RATIONAL:
+ if (count == 1)
+ {
+ float floatv;
+ CopyField(tag, floatv);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ float *floatav;
+ CopyField(tag, floatav);
+ }
+ break;
+ case TIFF_ASCII:
+ {
+ char *stringv;
+ CopyField(tag, stringv);
+ }
+ break;
+ case TIFF_DOUBLE:
+ if (count == 1)
+ {
+ double doublev;
+ CopyField(tag, doublev);
+ }
+ else if (count == (uint16_t)-1)
+ {
+ double *doubleav;
+ CopyField(tag, doubleav);
+ }
+ break;
+ default:
+ TIFFError(TIFFFileName(in),
+ "Data type %" PRIu16 " is not supported, tag %d skipped",
+ tag, type);
+ }
}
-static const struct cpTag {
- uint16_t tag;
- uint16_t count;
- TIFFDataType type;
+static const struct cpTag
+{
+ uint16_t tag;
+ uint16_t count;
+ TIFFDataType type;
} tags[] = {
- { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
- { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
- { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
- { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
- { TIFFTAG_MAKE, 1, TIFF_ASCII },
- { TIFFTAG_MODEL, 1, TIFF_ASCII },
- { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
- { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
- { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
- { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
- { TIFFTAG_PAGENAME, 1, TIFF_ASCII },
- { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
- { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
- { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
- { TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
- { TIFFTAG_DATETIME, 1, TIFF_ASCII },
- { TIFFTAG_ARTIST, 1, TIFF_ASCII },
- { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
- { TIFFTAG_WHITEPOINT, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_PRIMARYCHROMATICITIES,(uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
- { TIFFTAG_INKSET, 1, TIFF_SHORT },
- { TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
- { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
- { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
- { TIFFTAG_YCBCRCOEFFICIENTS, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
- { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
- { TIFFTAG_REFERENCEBLACKWHITE, (uint16_t) -1, TIFF_RATIONAL },
- { TIFFTAG_EXTRASAMPLES, (uint16_t) -1, TIFF_SHORT },
- { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE },
- { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE },
- { TIFFTAG_STONITS, 1, TIFF_DOUBLE },
+ {TIFFTAG_SUBFILETYPE, 1, TIFF_LONG},
+ {TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT},
+ {TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII},
+ {TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII},
+ {TIFFTAG_MAKE, 1, TIFF_ASCII},
+ {TIFFTAG_MODEL, 1, TIFF_ASCII},
+ {TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT},
+ {TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT},
+ {TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL},
+ {TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL},
+ {TIFFTAG_PAGENAME, 1, TIFF_ASCII},
+ {TIFFTAG_XPOSITION, 1, TIFF_RATIONAL},
+ {TIFFTAG_YPOSITION, 1, TIFF_RATIONAL},
+ {TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT},
+ {TIFFTAG_SOFTWARE, 1, TIFF_ASCII},
+ {TIFFTAG_DATETIME, 1, TIFF_ASCII},
+ {TIFFTAG_ARTIST, 1, TIFF_ASCII},
+ {TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII},
+ {TIFFTAG_WHITEPOINT, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_PRIMARYCHROMATICITIES, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT},
+ {TIFFTAG_INKSET, 1, TIFF_SHORT},
+ {TIFFTAG_DOTRANGE, 2, TIFF_SHORT},
+ {TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII},
+ {TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT},
+ {TIFFTAG_YCBCRCOEFFICIENTS, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT},
+ {TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT},
+ {TIFFTAG_REFERENCEBLACKWHITE, (uint16_t)-1, TIFF_RATIONAL},
+ {TIFFTAG_EXTRASAMPLES, (uint16_t)-1, TIFF_SHORT},
+ {TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE},
+ {TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE},
+ {TIFFTAG_STONITS, 1, TIFF_DOUBLE},
};
-#define NTAGS (sizeof (tags) / sizeof (tags[0]))
+#define NTAGS (sizeof(tags) / sizeof(tags[0]))
-#define CopyTag(tag, count, type) cpTag(in, out, tag, count, type)
+#define CopyTag(tag, count, type) cpTag(in, out, tag, count, type)
/* Functions written by Richard Nolde, with exceptions noted. */
-void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32_t *dirnum,
- uint16_t *defconfig, uint16_t *deffillorder, uint32_t *deftilewidth,
- uint32_t *deftilelength, uint32_t *defrowsperstrip,
- struct crop_mask *crop_data, struct pagedef *page,
- struct dump_opts *dump,
- unsigned int *imagelist, unsigned int *image_count )
- {
- int c, good_args = 0;
- char *opt_offset = NULL; /* Position in string of value sought */
- char *opt_ptr = NULL; /* Pointer to next token in option set */
- char *sep = NULL; /* Pointer to a token separator */
- unsigned int i, j, start, end;
+void process_command_opts(int argc, char *argv[], char *mp, char *mode,
+ uint32_t *dirnum, uint16_t *defconfig,
+ uint16_t *deffillorder, uint32_t *deftilewidth,
+ uint32_t *deftilelength, uint32_t *defrowsperstrip,
+ struct crop_mask *crop_data, struct pagedef *page,
+ struct dump_opts *dump, unsigned int *imagelist,
+ unsigned int *image_count)
+{
+ int c, good_args = 0;
+ char *opt_offset = NULL; /* Position in string of value sought */
+ char *opt_ptr = NULL; /* Pointer to next token in option set */
+ char *sep = NULL; /* Pointer to a token separator */
+ unsigned int i, j, start, end;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char* optarg;
+ extern int optind;
+ extern char *optarg;
#endif
*mp++ = 'w';
*mp = '\0';
while ((c = getopt(argc, argv,
- "ac:d:e:f:hik:l:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1)
- {
- good_args++;
- switch (c) {
- case 'a': mode[0] = 'a'; /* append to output */
- break;
- case 'c': if (!processCompressOptions(optarg)) /* compression scheme */
- {
- TIFFError ("Unknown compression option", "%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- break;
- case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */
- if (start == 0)
- {
- TIFFError ("","Directory offset must be greater than zero");
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- *dirnum = start - 1;
- break;
- case 'e': switch (tolower((int) optarg[0])) /* image export modes*/
- {
- case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE;
- crop_data->img_mode = COMPOSITE_IMAGES;
- break; /* Composite */
- case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED;
- crop_data->img_mode = SEPARATED_IMAGES;
- break; /* Divided */
- case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE;
- crop_data->img_mode = COMPOSITE_IMAGES;
- break; /* Image */
- case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED;
- crop_data->img_mode = SEPARATED_IMAGES;
- break; /* Multiple */
- case 's': crop_data->exp_mode = FILE_PER_SELECTION;
- crop_data->img_mode = SEPARATED_IMAGES;
- break; /* Sections */
- default: TIFFError ("Unknown export mode","%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- break;
- case 'f': if (streq(optarg, "lsb2msb")) /* fill order */
- *deffillorder = FILLORDER_LSB2MSB;
- else if (streq(optarg, "msb2lsb"))
- *deffillorder = FILLORDER_MSB2LSB;
- else
- {
- TIFFError ("Unknown fill order", "%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- break;
- case 'h': usage(EXIT_SUCCESS);
- break;
- case 'i': ignore = TRUE; /* ignore errors */
- break;
- case 'k': maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
- break;
- case 'l': outtiled = TRUE; /* tile length */
- *deftilelength = atoi(optarg);
- break;
- case 'p': /* planar configuration */
- if (streq(optarg, "separate"))
- *defconfig = PLANARCONFIG_SEPARATE;
- else if (streq(optarg, "contig"))
- *defconfig = PLANARCONFIG_CONTIG;
- else
- {
- TIFFError ("Unknown planar configuration", "%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- break;
- case 'r': /* rows/strip */
- *defrowsperstrip = atol(optarg);
- break;
- case 's': /* generate stripped output */
- outtiled = FALSE;
- break;
- case 't': /* generate tiled output */
- outtiled = TRUE;
- break;
- case 'v': printf("Library Release: %s\n", TIFFGetVersion());
- printf("Tiffcrop version: %s, last updated: %s\n",
- tiffcrop_version_id, tiffcrop_rev_date);
- printf("Tiffcp code: Copyright (c) 1988-1997 Sam Leffler\n");
- printf(" : Copyright (c) 1991-1997 Silicon Graphics, Inc\n");
- printf("Tiffcrop additions: Copyright (c) 2007-2010 Richard Nolde\n");
- exit (EXIT_SUCCESS);
- break;
- case 'w': /* tile width */
- outtiled = TRUE;
- *deftilewidth = atoi(optarg);
- break;
- case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */
- crop_data->crop_mode |= CROP_REGIONS;
- for (i = 0, opt_ptr = strtok (optarg, ":");
- ((opt_ptr != NULL) && (i < MAX_REGIONS));
- (opt_ptr = strtok (NULL, ":")), i++)
- {
- crop_data->regions++;
- if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf",
- &crop_data->corners[i].X1, &crop_data->corners[i].Y1,
- &crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4)
- {
- TIFFError ("Unable to parse coordinates for region", "%u %s", i, optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- }
- /* check for remaining elements over MAX_REGIONS */
- if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
- {
- TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
+ "ac:d:e:f:hik:l:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:"
+ "S:U:V:X:Y:Z:")) != -1)
+ {
+ good_args++;
+ switch (c)
+ {
+ case 'a':
+ mode[0] = 'a'; /* append to output */
+ break;
+ case 'c':
+ if (!processCompressOptions(optarg)) /* compression scheme */
+ {
+ TIFFError("Unknown compression option", "%s", optarg);
+ TIFFError("For valid options type", "tiffcrop -h");
exit(EXIT_FAILURE);
- }
- break;
- /* options for file open modes */
- case 'B':
+ }
+ break;
+ case 'd':
+ start = strtoul(optarg, NULL, 0); /* initial IFD offset */
+ if (start == 0)
{
- if (mp < mode + MAX_MODESTRING_LEN)
- {
- *mp++ = 'b'; *mp = '\0';
- } else {
- TIFFError("To many options for output file open modes. Maximum allowed ", "%d", MAX_MODESTRING_LEN);
+ TIFFError("", "Directory offset must be greater than zero");
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ *dirnum = start - 1;
+ break;
+ case 'e':
+ switch (tolower((int)optarg[0])) /* image export modes*/
+ {
+ case 'c':
+ crop_data->exp_mode = ONE_FILE_COMPOSITE;
+ crop_data->img_mode = COMPOSITE_IMAGES;
+ break; /* Composite */
+ case 'd':
+ crop_data->exp_mode = ONE_FILE_SEPARATED;
+ crop_data->img_mode = SEPARATED_IMAGES;
+ break; /* Divided */
+ case 'i':
+ crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE;
+ crop_data->img_mode = COMPOSITE_IMAGES;
+ break; /* Image */
+ case 'm':
+ crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED;
+ crop_data->img_mode = SEPARATED_IMAGES;
+ break; /* Multiple */
+ case 's':
+ crop_data->exp_mode = FILE_PER_SELECTION;
+ crop_data->img_mode = SEPARATED_IMAGES;
+ break; /* Sections */
+ default:
+ TIFFError("Unknown export mode", "%s", optarg);
TIFFError("For valid options type", "tiffcrop -h");
exit(EXIT_FAILURE);
- }
}
break;
- case 'L':
+ case 'f':
+ if (streq(optarg, "lsb2msb")) /* fill order */
+ *deffillorder = FILLORDER_LSB2MSB;
+ else if (streq(optarg, "msb2lsb"))
+ *deffillorder = FILLORDER_MSB2LSB;
+ else
+ {
+ TIFFError("Unknown fill order", "%s", optarg);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ break;
+ case 'i':
+ ignore = TRUE; /* ignore errors */
+ break;
+ case 'k':
+ maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
+ break;
+ case 'l':
+ outtiled = TRUE; /* tile length */
+ *deftilelength = atoi(optarg);
+ break;
+ case 'p': /* planar configuration */
+ if (streq(optarg, "separate"))
+ *defconfig = PLANARCONFIG_SEPARATE;
+ else if (streq(optarg, "contig"))
+ *defconfig = PLANARCONFIG_CONTIG;
+ else
+ {
+ TIFFError("Unknown planar configuration", "%s", optarg);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'r': /* rows/strip */
+ *defrowsperstrip = atol(optarg);
+ break;
+ case 's': /* generate stripped output */
+ outtiled = FALSE;
+ break;
+ case 't': /* generate tiled output */
+ outtiled = TRUE;
+ break;
+ case 'v':
+ printf("Library Release: %s\n", TIFFGetVersion());
+ printf("Tiffcrop version: %s, last updated: %s\n",
+ tiffcrop_version_id, tiffcrop_rev_date);
+ printf("Tiffcp code: Copyright (c) 1988-1997 Sam Leffler\n");
+ printf(" : Copyright (c) 1991-1997 Silicon Graphics, "
+ "Inc\n");
+ printf("Tiffcrop additions: Copyright (c) 2007-2010 Richard "
+ "Nolde\n");
+ exit(EXIT_SUCCESS);
+ break;
+ case 'w': /* tile width */
+ outtiled = TRUE;
+ *deftilewidth = atoi(optarg);
+ break;
+ case 'z': /* regions of an image specified as
+ x1,y1,x2,y2:x3,y3,x4,y4 etc */
+ crop_data->crop_mode |= CROP_REGIONS;
+ for (i = 0, opt_ptr = strtok(optarg, ":");
+ ((opt_ptr != NULL) && (i < MAX_REGIONS));
+ (opt_ptr = strtok(NULL, ":")), i++)
{
- if (mp < mode + MAX_MODESTRING_LEN)
+ crop_data->regions++;
+ if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf",
+ &crop_data->corners[i].X1,
+ &crop_data->corners[i].Y1,
+ &crop_data->corners[i].X2,
+ &crop_data->corners[i].Y2) != 4)
{
- *mp++ = 'l'; *mp = '\0';
- } else {
- TIFFError("To many options for output file open modes. Maximum allowed ", "%d", MAX_MODESTRING_LEN);
+ TIFFError("Unable to parse coordinates for region",
+ "%u %s", i, optarg);
TIFFError("For valid options type", "tiffcrop -h");
exit(EXIT_FAILURE);
}
}
+ /* check for remaining elements over MAX_REGIONS */
+ if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
+ {
+ TIFFError("Region list exceeds limit of", "%d regions %s",
+ MAX_REGIONS, optarg);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ /* options for file open modes */
+ case 'B':
+ {
+ if (mp < mode + MAX_MODESTRING_LEN)
+ {
+ *mp++ = 'b';
+ *mp = '\0';
+ }
+ else
+ {
+ TIFFError("To many options for output file open modes. "
+ "Maximum allowed ",
+ "%d", MAX_MODESTRING_LEN);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ }
+ break;
+ case 'L':
+ {
+ if (mp < mode + MAX_MODESTRING_LEN)
+ {
+ *mp++ = 'l';
+ *mp = '\0';
+ }
+ else
+ {
+ TIFFError("To many options for output file open modes. "
+ "Maximum allowed ",
+ "%d", MAX_MODESTRING_LEN);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ }
break;
case 'M':
+ {
+ if (mp < mode + MAX_MODESTRING_LEN)
{
- if (mp < mode + MAX_MODESTRING_LEN)
- {
- *mp++ = 'm'; *mp = '\0';
- } else {
- TIFFError("To many options for output file open modes. Maximum allowed ", "%d", MAX_MODESTRING_LEN);
- TIFFError("For valid options type", "tiffcrop -h");
- exit(EXIT_FAILURE);
- }
+ *mp++ = 'm';
+ *mp = '\0';
}
+ else
+ {
+ TIFFError("To many options for output file open modes. "
+ "Maximum allowed ",
+ "%d", MAX_MODESTRING_LEN);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ }
break;
case 'C':
+ {
+ if (mp < mode + MAX_MODESTRING_LEN)
+ {
+ *mp++ = 'c';
+ *mp = '\0';
+ }
+ else
+ {
+ TIFFError("To many options for output file open modes. "
+ "Maximum allowed ",
+ "%d", MAX_MODESTRING_LEN);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ }
+ break;
+ /* options for Debugging / data dump */
+ case 'D':
+ for (i = 0, opt_ptr = strtok(optarg, ","); (opt_ptr != NULL);
+ (opt_ptr = strtok(NULL, ",")), i++)
{
- if (mp < mode + MAX_MODESTRING_LEN)
+ opt_offset = strpbrk(opt_ptr, ":=");
+ if (opt_offset == NULL)
{
- *mp++ = 'c'; *mp = '\0';
- } else {
- TIFFError("To many options for output file open modes. Maximum allowed ", "%d", MAX_MODESTRING_LEN);
+ TIFFError("Invalid dump option", "%s", optarg);
TIFFError("For valid options type", "tiffcrop -h");
exit(EXIT_FAILURE);
}
- }
- break;
- /* options for Debugging / data dump */
- case 'D': for (i = 0, opt_ptr = strtok (optarg, ",");
- (opt_ptr != NULL);
- (opt_ptr = strtok (NULL, ",")), i++)
- {
- opt_offset = strpbrk(opt_ptr, ":=");
- if (opt_offset == NULL)
- {
- TIFFError("Invalid dump option", "%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
-
+
*opt_offset = '\0';
/* convert option to lowercase */
- end = (unsigned int)strlen (opt_ptr);
+ end = (unsigned int)strlen(opt_ptr);
for (i = 0; i < end; i++)
- *(opt_ptr + i) = tolower((int) *(opt_ptr + i));
+ *(opt_ptr + i) = tolower((int)*(opt_ptr + i));
/* Look for dump format specification */
if (strncmp(opt_ptr, "for", 3) == 0)
- {
- /* convert value to lowercase */
- end = (unsigned int)strlen (opt_offset + 1);
- for (i = 1; i <= end; i++)
- *(opt_offset + i) = tolower((int) *(opt_offset + i));
- /* check dump format value */
- if (strncmp (opt_offset + 1, "txt", 3) == 0)
+ {
+ /* convert value to lowercase */
+ end = (unsigned int)strlen(opt_offset + 1);
+ for (i = 1; i <= end; i++)
+ *(opt_offset + i) = tolower((int)*(opt_offset + i));
+ /* check dump format value */
+ if (strncmp(opt_offset + 1, "txt", 3) == 0)
{
- dump->format = DUMP_TEXT;
- strcpy (dump->mode, "w");
+ dump->format = DUMP_TEXT;
+ strcpy(dump->mode, "w");
}
- else
- {
- if (strncmp(opt_offset + 1, "raw", 3) == 0)
- {
- dump->format = DUMP_RAW;
- strcpy (dump->mode, "wb");
- }
else
- {
- TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- }
- }
- else
- { /* Look for dump level specification */
- if (strncmp (opt_ptr, "lev", 3) == 0)
- dump->level = atoi(opt_offset + 1);
+ {
+ if (strncmp(opt_offset + 1, "raw", 3) == 0)
+ {
+ dump->format = DUMP_RAW;
+ strcpy(dump->mode, "wb");
+ }
+ else
+ {
+ TIFFError("parse_command_opts",
+ "Unknown dump format %s",
+ opt_offset + 1);
+ TIFFError("For valid options type",
+ "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ }
+ }
+ else
+ { /* Look for dump level specification */
+ if (strncmp(opt_ptr, "lev", 3) == 0)
+ dump->level = atoi(opt_offset + 1);
/* Look for input data dump file name */
- if (strncmp (opt_ptr, "in", 2) == 0)
- {
- strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20);
- dump->infilename[PATH_MAX - 20] = '\0';
+ if (strncmp(opt_ptr, "in", 2) == 0)
+ {
+ strncpy(dump->infilename, opt_offset + 1,
+ PATH_MAX - 20);
+ dump->infilename[PATH_MAX - 20] = '\0';
}
/* Look for output data dump file name */
- if (strncmp (opt_ptr, "out", 3) == 0)
- {
- strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20);
- dump->outfilename[PATH_MAX - 20] = '\0';
+ if (strncmp(opt_ptr, "out", 3) == 0)
+ {
+ strncpy(dump->outfilename, opt_offset + 1,
+ PATH_MAX - 20);
+ dump->outfilename[PATH_MAX - 20] = '\0';
}
- if (strncmp (opt_ptr, "deb", 3) == 0)
- dump->debug = atoi(opt_offset + 1);
- }
+ if (strncmp(opt_ptr, "deb", 3) == 0)
+ dump->debug = atoi(opt_offset + 1);
}
- if ((strlen(dump->infilename)) || (strlen(dump->outfilename)))
- {
- if (dump->level == 1)
- TIFFError("","Defaulting to dump level 1, no data.");
- if (dump->format == DUMP_NONE)
- {
- TIFFError("", "You must specify a dump format for dump files");
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- }
- break;
-
- /* image manipulation routine options */
- case 'm': /* margins to exclude from selection, uppercase M was already used */
- /* order of values must be TOP, LEFT, BOTTOM, RIGHT */
- crop_data->crop_mode |= CROP_MARGINS;
- for (i = 0, opt_ptr = strtok (optarg, ",:");
- ((opt_ptr != NULL) && (i < 4));
- (opt_ptr = strtok (NULL, ",:")), i++)
+ }
+ if ((strlen(dump->infilename)) || (strlen(dump->outfilename)))
+ {
+ if (dump->level == 1)
+ TIFFError("", "Defaulting to dump level 1, no data.");
+ if (dump->format == DUMP_NONE)
{
- crop_data->margins[i] = atof(opt_ptr);
+ TIFFError(
+ "",
+ "You must specify a dump format for dump files");
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
}
- break;
- case 'E': /* edge reference */
- switch (tolower((int) optarg[0]))
- {
- case 't': crop_data->edge_ref = EDGE_TOP;
- break;
- case 'b': crop_data->edge_ref = EDGE_BOTTOM;
- break;
- case 'l': crop_data->edge_ref = EDGE_LEFT;
- break;
- case 'r': crop_data->edge_ref = EDGE_RIGHT;
- break;
- default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- break;
- case 'F': /* flip eg mirror image or cropped segment, M was already used */
- crop_data->crop_mode |= CROP_MIRROR;
- switch (tolower((int) optarg[0]))
- {
- case 'h': crop_data->mirror = MIRROR_HORIZ;
- break;
- case 'v': crop_data->mirror = MIRROR_VERT;
- break;
- case 'b': crop_data->mirror = MIRROR_BOTH;
- break;
- default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- break;
- case 'H': /* set horizontal resolution to new value */
- page->hres = atof (optarg);
+ }
+ break;
+
+ /* image manipulation routine options */
+ case 'm': /* margins to exclude from selection, uppercase M was
+ already used */
+ /* order of values must be TOP, LEFT, BOTTOM, RIGHT */
+ crop_data->crop_mode |= CROP_MARGINS;
+ for (i = 0, opt_ptr = strtok(optarg, ",:");
+ ((opt_ptr != NULL) && (i < 4));
+ (opt_ptr = strtok(NULL, ",:")), i++)
+ {
+ crop_data->margins[i] = atof(opt_ptr);
+ }
+ break;
+ case 'E': /* edge reference */
+ switch (tolower((int)optarg[0]))
+ {
+ case 't':
+ crop_data->edge_ref = EDGE_TOP;
+ break;
+ case 'b':
+ crop_data->edge_ref = EDGE_BOTTOM;
+ break;
+ case 'l':
+ crop_data->edge_ref = EDGE_LEFT;
+ break;
+ case 'r':
+ crop_data->edge_ref = EDGE_RIGHT;
+ break;
+ default:
+ TIFFError("Edge reference must be top, bottom, left, "
+ "or right",
+ "%s", optarg);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'F': /* flip eg mirror image or cropped segment, M was already
+ used */
+ crop_data->crop_mode |= CROP_MIRROR;
+ switch (tolower((int)optarg[0]))
+ {
+ case 'h':
+ crop_data->mirror = MIRROR_HORIZ;
+ break;
+ case 'v':
+ crop_data->mirror = MIRROR_VERT;
+ break;
+ case 'b':
+ crop_data->mirror = MIRROR_BOTH;
+ break;
+ default:
+ TIFFError("Flip mode must be horiz, vert, or both",
+ "%s", optarg);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'H': /* set horizontal resolution to new value */
+ page->hres = atof(optarg);
page->mode |= PAGE_MODE_RESOLUTION;
- break;
- case 'I': /* invert the color space, eg black to white */
- crop_data->crop_mode |= CROP_INVERT;
+ break;
+ case 'I': /* invert the color space, eg black to white */
+ crop_data->crop_mode |= CROP_INVERT;
/* The PHOTOMETIC_INTERPRETATION tag may be updated */
if (streq(optarg, "black"))
- {
- crop_data->photometric = PHOTOMETRIC_MINISBLACK;
- continue;
- }
+ {
+ crop_data->photometric = PHOTOMETRIC_MINISBLACK;
+ continue;
+ }
if (streq(optarg, "white"))
- {
- crop_data->photometric = PHOTOMETRIC_MINISWHITE;
- continue;
- }
- if (streq(optarg, "data"))
- {
- crop_data->photometric = INVERT_DATA_ONLY;
- continue;
- }
+ {
+ crop_data->photometric = PHOTOMETRIC_MINISWHITE;
+ continue;
+ }
+ if (streq(optarg, "data"))
+ {
+ crop_data->photometric = INVERT_DATA_ONLY;
+ continue;
+ }
if (streq(optarg, "both"))
- {
- crop_data->photometric = INVERT_DATA_AND_TAG;
- continue;
- }
+ {
+ crop_data->photometric = INVERT_DATA_AND_TAG;
+ continue;
+ }
- TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- break;
- case 'J': /* horizontal margin for sectioned output pages */
- page->hmargin = atof(optarg);
+ TIFFError("Missing or unknown option for inverting "
+ "PHOTOMETRIC_INTERPRETATION",
+ "%s", optarg);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ break;
+ case 'J': /* horizontal margin for sectioned output pages */
+ page->hmargin = atof(optarg);
page->mode |= PAGE_MODE_MARGINS;
- break;
- case 'K': /* vertical margin for sectioned output pages*/
+ break;
+ case 'K': /* vertical margin for sectioned output pages*/
page->vmargin = atof(optarg);
page->mode |= PAGE_MODE_MARGINS;
- break;
- case 'N': /* list of images to process */
- for (i = 0, opt_ptr = strtok (optarg, ",");
- ((opt_ptr != NULL) && (i < MAX_IMAGES));
- (opt_ptr = strtok (NULL, ",")))
- { /* We do not know how many images are in file yet
- * so we build a list to include the maximum allowed
- * and follow it until we hit the end of the file.
- * Image count is not accurate for odd, even, last
- * so page numbers won't be valid either.
- */
- if (streq(opt_ptr, "odd"))
- {
- for (j = 1; j <= MAX_IMAGES; j += 2)
- imagelist[i++] = j;
- *image_count = (MAX_IMAGES - 1) / 2;
- break;
- }
- else
- {
- if (streq(opt_ptr, "even"))
- {
- for (j = 2; j <= MAX_IMAGES; j += 2)
- imagelist[i++] = j;
- *image_count = MAX_IMAGES / 2;
- break;
- }
- else
- {
- if (streq(opt_ptr, "last"))
- imagelist[i++] = MAX_IMAGES;
- else /* single value between commas */
- {
- sep = strpbrk(opt_ptr, ":-");
- if (!sep)
- imagelist[i++] = atoi(opt_ptr);
- else
- {
- *sep = '\0';
- start = atoi (opt_ptr);
- if (!strcmp((sep + 1), "last"))
- end = MAX_IMAGES;
- else
- end = atoi (sep + 1);
- for (j = start; j <= end && j - start + i < MAX_IMAGES; j++)
- imagelist[i++] = j;
- }
- }
- }
- }
- }
+ break;
+ case 'N': /* list of images to process */
+ for (i = 0, opt_ptr = strtok(optarg, ",");
+ ((opt_ptr != NULL) && (i < MAX_IMAGES));
+ (opt_ptr = strtok(NULL, ",")))
+ { /* We do not know how many images are in file yet
+ * so we build a list to include the maximum allowed
+ * and follow it until we hit the end of the file.
+ * Image count is not accurate for odd, even, last
+ * so page numbers won't be valid either.
+ */
+ if (streq(opt_ptr, "odd"))
+ {
+ for (j = 1; j <= MAX_IMAGES; j += 2)
+ imagelist[i++] = j;
+ *image_count = (MAX_IMAGES - 1) / 2;
+ break;
+ }
+ else
+ {
+ if (streq(opt_ptr, "even"))
+ {
+ for (j = 2; j <= MAX_IMAGES; j += 2)
+ imagelist[i++] = j;
+ *image_count = MAX_IMAGES / 2;
+ break;
+ }
+ else
+ {
+ if (streq(opt_ptr, "last"))
+ imagelist[i++] = MAX_IMAGES;
+ else /* single value between commas */
+ {
+ sep = strpbrk(opt_ptr, ":-");
+ if (!sep)
+ imagelist[i++] = atoi(opt_ptr);
+ else
+ {
+ *sep = '\0';
+ start = atoi(opt_ptr);
+ if (!strcmp((sep + 1), "last"))
+ end = MAX_IMAGES;
+ else
+ end = atoi(sep + 1);
+ for (j = start;
+ j <= end && j - start + i < MAX_IMAGES;
+ j++)
+ imagelist[i++] = j;
+ }
+ }
+ }
+ }
+ }
*image_count = i;
- break;
- case 'O': /* page orientation */
- switch (tolower((int) optarg[0]))
- {
- case 'a': page->orient = ORIENTATION_AUTO;
- break;
- case 'p': page->orient = ORIENTATION_PORTRAIT;
- break;
- case 'l': page->orient = ORIENTATION_LANDSCAPE;
- break;
- default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- break;
- case 'P': /* page size selection */
- if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2)
- {
- strcpy (page->name, "Custom");
- page->mode |= PAGE_MODE_PAPERSIZE;
- break;
- }
- if (get_page_geometry (optarg, page))
- {
- if (!strcmp(optarg, "list"))
+ break;
+ case 'O': /* page orientation */
+ switch (tolower((int)optarg[0]))
+ {
+ case 'a':
+ page->orient = ORIENTATION_AUTO;
+ break;
+ case 'p':
+ page->orient = ORIENTATION_PORTRAIT;
+ break;
+ case 'l':
+ page->orient = ORIENTATION_LANDSCAPE;
+ break;
+ default:
+ TIFFError(
+ "Orientation must be portrait, landscape, or auto.",
+ "%s", optarg);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'P': /* page size selection */
+ if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2)
+ {
+ strcpy(page->name, "Custom");
+ page->mode |= PAGE_MODE_PAPERSIZE;
+ break;
+ }
+ if (get_page_geometry(optarg, page))
+ {
+ if (!strcmp(optarg, "list"))
{
- TIFFError("", "Name Width Length (in inches)");
- for (i = 0; i < MAX_PAPERNAMES - 1; i++)
- TIFFError ("", "%-15.15s %5.2f %5.2f",
- PaperTable[i].name, PaperTable[i].width,
- PaperTable[i].length);
- exit (EXIT_FAILURE);
+ TIFFError("",
+ "Name Width Length (in inches)");
+ for (i = 0; i < MAX_PAPERNAMES - 1; i++)
+ TIFFError("", "%-15.15s %5.2f %5.2f",
+ PaperTable[i].name, PaperTable[i].width,
+ PaperTable[i].length);
+ exit(EXIT_FAILURE);
}
-
- TIFFError ("Invalid paper size", "%s", optarg);
- TIFFError ("", "Select one of:");
- TIFFError("", "Name Width Length (in inches)");
- for (i = 0; i < MAX_PAPERNAMES - 1; i++)
- TIFFError ("", "%-15.15s %5.2f %5.2f",
- PaperTable[i].name, PaperTable[i].width,
- PaperTable[i].length);
- exit (EXIT_FAILURE);
- }
- else
- {
- page->mode |= PAGE_MODE_PAPERSIZE;
- }
- break;
- case 'R': /* rotate image or cropped segment */
- crop_data->crop_mode |= CROP_ROTATE;
- switch (strtoul(optarg, NULL, 0))
- {
- case 90: crop_data->rotation = (uint16_t)90;
- break;
- case 180: crop_data->rotation = (uint16_t)180;
- break;
- case 270: crop_data->rotation = (uint16_t)270;
- break;
- default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- break;
- case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */
- sep = strpbrk(optarg, ",:");
- if (sep)
- {
- *sep = '\0';
- page->cols = atoi(optarg);
- page->rows = atoi(sep +1);
- }
+
+ TIFFError("Invalid paper size", "%s", optarg);
+ TIFFError("", "Select one of:");
+ TIFFError("", "Name Width Length (in inches)");
+ for (i = 0; i < MAX_PAPERNAMES - 1; i++)
+ TIFFError("", "%-15.15s %5.2f %5.2f",
+ PaperTable[i].name, PaperTable[i].width,
+ PaperTable[i].length);
+ exit(EXIT_FAILURE);
+ }
else
- {
- page->cols = atoi(optarg);
- page->rows = atoi(optarg);
- }
+ {
+ page->mode |= PAGE_MODE_PAPERSIZE;
+ }
+ break;
+ case 'R': /* rotate image or cropped segment */
+ crop_data->crop_mode |= CROP_ROTATE;
+ switch (strtoul(optarg, NULL, 0))
+ {
+ case 90:
+ crop_data->rotation = (uint16_t)90;
+ break;
+ case 180:
+ crop_data->rotation = (uint16_t)180;
+ break;
+ case 270:
+ crop_data->rotation = (uint16_t)270;
+ break;
+ default:
+ TIFFError("Rotation must be 90, 180, or 270 degrees "
+ "clockwise",
+ "%s", optarg);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3
+ across and 2 down */
+ sep = strpbrk(optarg, ",:");
+ if (sep)
+ {
+ *sep = '\0';
+ page->cols = atoi(optarg);
+ page->rows = atoi(sep + 1);
+ }
+ else
+ {
+ page->cols = atoi(optarg);
+ page->rows = atoi(optarg);
+ }
if ((page->cols * page->rows) > MAX_SECTIONS)
- {
- TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS);
- exit (EXIT_FAILURE);
- }
+ {
+ TIFFError(
+ "Limit for subdivisions, ie rows x columns, exceeded",
+ "%d", MAX_SECTIONS);
+ exit(EXIT_FAILURE);
+ }
page->mode |= PAGE_MODE_ROWSCOLS;
- break;
- case 'U': /* units for measurements and offsets */
- if (streq(optarg, "in"))
- {
- crop_data->res_unit = RESUNIT_INCH;
- page->res_unit = RESUNIT_INCH;
- }
- else if (streq(optarg, "cm"))
- {
- crop_data->res_unit = RESUNIT_CENTIMETER;
- page->res_unit = RESUNIT_CENTIMETER;
- }
- else if (streq(optarg, "px"))
- {
- crop_data->res_unit = RESUNIT_NONE;
- page->res_unit = RESUNIT_NONE;
- }
- else
- {
- TIFFError ("Illegal unit of measure","%s", optarg);
- TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- }
- break;
- case 'V': /* set vertical resolution to new value */
- page->vres = atof (optarg);
+ break;
+ case 'U': /* units for measurements and offsets */
+ if (streq(optarg, "in"))
+ {
+ crop_data->res_unit = RESUNIT_INCH;
+ page->res_unit = RESUNIT_INCH;
+ }
+ else if (streq(optarg, "cm"))
+ {
+ crop_data->res_unit = RESUNIT_CENTIMETER;
+ page->res_unit = RESUNIT_CENTIMETER;
+ }
+ else if (streq(optarg, "px"))
+ {
+ crop_data->res_unit = RESUNIT_NONE;
+ page->res_unit = RESUNIT_NONE;
+ }
+ else
+ {
+ TIFFError("Illegal unit of measure", "%s", optarg);
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case 'V': /* set vertical resolution to new value */
+ page->vres = atof(optarg);
page->mode |= PAGE_MODE_RESOLUTION;
- break;
- case 'X': /* selection width */
- crop_data->crop_mode |= CROP_WIDTH;
- crop_data->width = atof(optarg);
- break;
- case 'Y': /* selection length */
- crop_data->crop_mode |= CROP_LENGTH;
- crop_data->length = atof(optarg);
- break;
- case 'Z': /* zones of an image X:Y read as zone X of Y */
- crop_data->crop_mode |= CROP_ZONES;
- for (i = 0, opt_ptr = strtok (optarg, ",");
- ((opt_ptr != NULL) && (i < MAX_REGIONS));
- (opt_ptr = strtok (NULL, ",")), i++)
+ break;
+ case 'X': /* selection width */
+ crop_data->crop_mode |= CROP_WIDTH;
+ crop_data->width = atof(optarg);
+ break;
+ case 'Y': /* selection length */
+ crop_data->crop_mode |= CROP_LENGTH;
+ crop_data->length = atof(optarg);
+ break;
+ case 'Z': /* zones of an image X:Y read as zone X of Y */
+ crop_data->crop_mode |= CROP_ZONES;
+ for (i = 0, opt_ptr = strtok(optarg, ",");
+ ((opt_ptr != NULL) && (i < MAX_REGIONS));
+ (opt_ptr = strtok(NULL, ",")), i++)
+ {
+ crop_data->zones++;
+ opt_offset = strchr(opt_ptr, ':');
+ if (!opt_offset)
{
- crop_data->zones++;
- opt_offset = strchr(opt_ptr, ':');
- if (!opt_offset) {
- TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h");
- exit(EXIT_FAILURE);
- }
+ TIFFError("Wrong parameter syntax for -Z",
+ "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ }
*opt_offset = '\0';
crop_data->zonelist[i].position = atoi(opt_ptr);
- crop_data->zonelist[i].total = atoi(opt_offset + 1);
- }
+ crop_data->zonelist[i].total = atoi(opt_offset + 1);
+ }
/* check for remaining elements over MAX_REGIONS */
if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
- {
- TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS);
- exit (EXIT_FAILURE);
- }
- break;
- case '?': TIFFError ("For valid options type", "tiffcrop -h");
- exit (EXIT_FAILURE);
- /*NOTREACHED*/
- }
+ {
+ TIFFError("Zone list exceeds region limit", "%d",
+ MAX_REGIONS);
+ exit(EXIT_FAILURE);
+ }
+ break;
+ case '?':
+ TIFFError("For valid options type", "tiffcrop -h");
+ exit(EXIT_FAILURE);
+ /*NOTREACHED*/
+ }
}
- /*-- Check for not allowed combinations (e.g. -X, -Y and -Z, -z and -S are mutually exclusive) --*/
+ /*-- Check for not allowed combinations (e.g. -X, -Y and -Z, -z and -S are
+ * mutually exclusive) --*/
char XY, Z, R, S;
- XY = ((crop_data->crop_mode & CROP_WIDTH) || (crop_data->crop_mode & CROP_LENGTH)) ? 1 : 0;
+ XY = ((crop_data->crop_mode & CROP_WIDTH) ||
+ (crop_data->crop_mode & CROP_LENGTH))
+ ? 1
+ : 0;
Z = (crop_data->crop_mode & CROP_ZONES) ? 1 : 0;
R = (crop_data->crop_mode & CROP_REGIONS) ? 1 : 0;
S = (page->mode & PAGE_MODE_ROWSCOLS) ? 1 : 0;
- if (XY + Z + R + S > 1) {
- TIFFError("tiffcrop input error", "The crop options(-X|-Y), -Z, -z and -S are mutually exclusive.->exit");
+ if (XY + Z + R + S > 1)
+ {
+ TIFFError("tiffcrop input error", "The crop options(-X|-Y), -Z, -z and "
+ "-S are mutually exclusive.->exit");
exit(EXIT_FAILURE);
}
/* Check for not allowed combination:
- * Any of the -X, -Y, -Z and -z options together with other PAGE_MODE_x options
- * such as -H, -V, -P, -J or -K are not supported and may cause buffer overflows.
+ * Any of the -X, -Y, -Z and -z options together with other PAGE_MODE_x
+options
+ * such as -H, -V, -P, -J or -K are not supported and may cause buffer
+overflows.
. */
- if ((XY + Z + R > 0) && page->mode != PAGE_MODE_NONE) {
+ if ((XY + Z + R > 0) && page->mode != PAGE_MODE_NONE)
+ {
TIFFError("tiffcrop input error",
- "Any of the crop options -X, -Y, -Z and -z together with other PAGE_MODE_x options such as - H, -V, -P, -J or -K is not supported and may cause buffer overflows..->exit");
+ "Any of the crop options -X, -Y, -Z and -z together with "
+ "other PAGE_MODE_x options such as - H, -V, -P, -J or -K is "
+ "not supported and may cause buffer overflows..->exit");
exit(EXIT_FAILURE);
}
- } /* end process_command_opts */
+} /* end process_command_opts */
/* Start a new output file if one has not been previously opened or
* autoindex is set to non-zero. Update page and file counters
* so TIFFTAG PAGENUM will be correct in image.
*/
-static int
-update_output_file (TIFF **tiffout, char *mode, int autoindex,
- char *outname, unsigned int *page)
- {
- static int findex = 0; /* file sequence indicator */
- size_t basename_len;
- char *sep;
- char export_ext[16];
- char exportname[PATH_MAX];
+static int update_output_file(TIFF **tiffout, char *mode, int autoindex,
+ char *outname, unsigned int *page)
+{
+ static int findex = 0; /* file sequence indicator */
+ size_t basename_len;
+ char *sep;
+ char export_ext[16];
+ char exportname[PATH_MAX];
- if (autoindex && (*tiffout != NULL))
+ if (autoindex && (*tiffout != NULL))
{
- /* Close any export file that was previously opened */
- TIFFClose (*tiffout);
- *tiffout = NULL;
+ /* Close any export file that was previously opened */
+ TIFFClose(*tiffout);
+ *tiffout = NULL;
}
- memcpy (export_ext, ".tiff", 6);
- memset (exportname, '\0', sizeof(exportname));
+ memcpy(export_ext, ".tiff", 6);
+ memset(exportname, '\0', sizeof(exportname));
- /* Leave room for page number portion of the new filename :
- * hyphen + 6 digits + dot + 4 extension characters + null terminator */
- #define FILENUM_MAX_LENGTH (1+6+1+4+1)
- strncpy (exportname, outname, sizeof(exportname) - FILENUM_MAX_LENGTH);
- if (*tiffout == NULL) /* This is a new export file */
+/* Leave room for page number portion of the new filename :
+ * hyphen + 6 digits + dot + 4 extension characters + null terminator */
+#define FILENUM_MAX_LENGTH (1 + 6 + 1 + 4 + 1)
+ strncpy(exportname, outname, sizeof(exportname) - FILENUM_MAX_LENGTH);
+ if (*tiffout == NULL) /* This is a new export file */
{
- if (autoindex)
- { /* create a new filename for each export */
- findex++;
- if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF")))
- {
- strncpy (export_ext, sep, 5);
- *sep = '\0';
+ if (autoindex)
+ { /* create a new filename for each export */
+ findex++;
+ if ((sep = strstr(exportname, ".tif")) ||
+ (sep = strstr(exportname, ".TIF")))
+ {
+ strncpy(export_ext, sep, 5);
+ *sep = '\0';
+ }
+ else
+ memcpy(export_ext, ".tiff", 5);
+ export_ext[5] = '\0';
+ basename_len = strlen(exportname);
+
+ /* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow
+ * of pathname */
+ if (findex > MAX_EXPORT_PAGES)
+ {
+ TIFFError("update_output_file",
+ "Maximum of %d pages per file exceeded",
+ MAX_EXPORT_PAGES);
+ return 1;
+ }
+
+ /* We previously assured that there will be space left */
+ snprintf(exportname + basename_len,
+ sizeof(exportname) - basename_len, "-%03d%.5s", findex,
+ export_ext);
}
- else
- memcpy (export_ext, ".tiff", 5);
- export_ext[5] = '\0';
- basename_len = strlen(exportname);
+ exportname[sizeof(exportname) - 1] = '\0';
- /* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */
- if (findex > MAX_EXPORT_PAGES)
+ TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
+ if (opts == NULL)
{
- TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES);
- return 1;
+ return 1;
}
+ TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
+ *tiffout = TIFFOpenExt(exportname, mode, opts);
+ TIFFOpenOptionsFree(opts);
+ if (*tiffout == NULL)
+ {
+ TIFFError("update_output_file", "Unable to open output file %s",
+ exportname);
+ return 1;
+ }
+ *page = 0;
- /* We previously assured that there will be space left */
- snprintf(exportname + basename_len, sizeof(exportname) - basename_len, "-%03d%.5s", findex, export_ext);
- }
- exportname[sizeof(exportname) - 1] = '\0';
-
- TIFFOpenOptions* opts = TIFFOpenOptionsAlloc();
- if (opts == NULL) {
- return 1;
+ return 0;
}
- TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
- *tiffout = TIFFOpenExt(exportname, mode, opts);
- TIFFOpenOptionsFree(opts);
- if (*tiffout == NULL)
- {
- TIFFError("update_output_file", "Unable to open output file %s", exportname);
- return 1;
- }
- *page = 0;
+ else
+ (*page)++;
return 0;
- }
- else
- (*page)++;
-
- return 0;
- } /* end update_output_file */
+} /* end update_output_file */
-
-int
-main(int argc, char* argv[])
- {
+int main(int argc, char *argv[])
+{
#if !HAVE_DECL_OPTARG
- extern int optind;
+ extern int optind;
#endif
- uint16_t defconfig = (uint16_t) -1;
- uint16_t deffillorder = 0;
- uint32_t deftilewidth = (uint32_t) 0;
- uint32_t deftilelength = (uint32_t) 0;
- uint32_t defrowsperstrip = (uint32_t) 0;
- uint32_t dirnum = 0;
-
- TIFF *in = NULL;
- TIFF *out = NULL;
- char mode[10];
- char *mp = mode;
-
- /** RJN additions **/
- struct image_data image; /* Image parameters for one image */
- struct crop_mask crop; /* Cropping parameters for all images */
- struct pagedef page; /* Page definition for output pages */
- struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */
- struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */
- struct dump_opts dump; /* Data dump options */
- unsigned char *read_buff = NULL; /* Input image data buffer */
- unsigned char *crop_buff = NULL; /* Crop area buffer */
- unsigned char *sect_buff = NULL; /* Image section buffer */
- unsigned char *sect_src = NULL; /* Image section buffer pointer */
- unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */
- unsigned int image_count = 0;
- unsigned int dump_images = 0;
- unsigned int next_image = 0;
- unsigned int next_page = 0;
- unsigned int total_pages = 0;
- unsigned int total_images = 0;
- unsigned int end_of_input = FALSE;
- int seg;
- size_t length;
- char temp_filename[PATH_MAX + 16]; /* Extra space keeps the compiler from complaining */
-
- assert(NUM_BUFF_OVERSIZE_BYTES >= 3);
-
- little_endian = *((unsigned char *)&little_endian) & '1';
-
- initImageData(&image);
- initCropMasks(&crop);
- initPageSetup(&page, sections, seg_buffs);
- initDumpOptions(&dump);
-
- process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig,
- &deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip,
- &crop, &page, &dump, imagelist, &image_count);
-
- if (argc - optind < 2)
- usage(EXIT_FAILURE);
-
- if ((argc - optind) == 2)
- pageNum = -1;
- else
- total_images = 0;
- /* Read multiple input files and write to output file(s) */
- while (optind < argc - 1)
- {
-
- TIFFOpenOptions* opts = TIFFOpenOptionsAlloc();
- if (opts == NULL) {
- return -3;
- }
- TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
- in = TIFFOpenExt(argv[optind], "r", opts);
- TIFFOpenOptionsFree(opts);
- if (in == NULL)
- return (-3);
-
- /* If only one input file is specified, we can use directory count */
- total_images = TIFFNumberOfDirectories(in);
- if (total_images > TIFF_DIR_MAX)
- {
- TIFFError (TIFFFileName(in), "File contains too many directories");
- if (out != NULL)
- (void) TIFFClose(out);
- return (1);
- }
- if (image_count == 0)
- {
- dirnum = 0;
- total_pages = total_images; /* Only valid with single input file */
- }
+ uint16_t defconfig = (uint16_t)-1;
+ uint16_t deffillorder = 0;
+ uint32_t deftilewidth = (uint32_t)0;
+ uint32_t deftilelength = (uint32_t)0;
+ uint32_t defrowsperstrip = (uint32_t)0;
+ uint32_t dirnum = 0;
+
+ TIFF *in = NULL;
+ TIFF *out = NULL;
+ char mode[10];
+ char *mp = mode;
+
+ /** RJN additions **/
+ struct image_data image; /* Image parameters for one image */
+ struct crop_mask crop; /* Cropping parameters for all images */
+ struct pagedef page; /* Page definition for output pages */
+ struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */
+ struct buffinfo
+ seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */
+ struct dump_opts dump; /* Data dump options */
+ unsigned char *read_buff = NULL; /* Input image data buffer */
+ unsigned char *crop_buff = NULL; /* Crop area buffer */
+ unsigned char *sect_buff = NULL; /* Image section buffer */
+ unsigned char *sect_src = NULL; /* Image section buffer pointer */
+ unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */
+ unsigned int image_count = 0;
+ unsigned int dump_images = 0;
+ unsigned int next_image = 0;
+ unsigned int next_page = 0;
+ unsigned int total_pages = 0;
+ unsigned int total_images = 0;
+ unsigned int end_of_input = FALSE;
+ int seg;
+ size_t length;
+ char temp_filename[PATH_MAX + 16]; /* Extra space keeps the compiler from
+ complaining */
+
+ assert(NUM_BUFF_OVERSIZE_BYTES >= 3);
+
+ little_endian = *((unsigned char *)&little_endian) & '1';
+
+ initImageData(&image);
+ initCropMasks(&crop);
+ initPageSetup(&page, sections, seg_buffs);
+ initDumpOptions(&dump);
+
+ process_command_opts(argc, argv, mp, mode, &dirnum, &defconfig,
+ &deffillorder, &deftilewidth, &deftilelength,
+ &defrowsperstrip, &crop, &page, &dump, imagelist,
+ &image_count);
+
+ if (argc - optind < 2)
+ usage(EXIT_FAILURE);
+
+ if ((argc - optind) == 2)
+ pageNum = -1;
else
- {
- dirnum = (tdir_t)(imagelist[next_image] - 1);
- next_image++;
+ total_images = 0;
+ /* Read multiple input files and write to output file(s) */
+ while (optind < argc - 1)
+ {
- /* Total pages only valid for enumerated list of pages not derived
- * using odd, even, or last keywords.
- */
- if (image_count > total_images)
- image_count = total_images;
-
- total_pages = image_count;
- }
-
- /* MAX_IMAGES is used for special case "last" in selection list */
- if (dirnum == (MAX_IMAGES - 1))
- dirnum = total_images - 1;
-
- if (dirnum > (total_images))
- {
- TIFFError (TIFFFileName(in),
- "Invalid image number %"PRIu32", File contains only %"PRIu32" images",
- dirnum + 1u, total_images);
- if (out != NULL)
- (void) TIFFClose(out);
- return (1);
- }
-
- if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum))
- {
- TIFFError(TIFFFileName(in),"Error, setting subdirectory at %"PRIu32, dirnum);
- if (out != NULL)
- (void) TIFFClose(out);
- return (1);
- }
-
- end_of_input = FALSE;
- while (end_of_input == FALSE)
- {
- config = defconfig;
- compression = defcompression;
- predictor = defpredictor;
- fillorder = deffillorder;
- rowsperstrip = defrowsperstrip;
- tilewidth = deftilewidth;
- tilelength = deftilelength;
- g3opts = defg3opts;
-
- if (dump.format != DUMP_NONE)
- {
- /* manage input and/or output dump files here */
- dump_images++;
- length = strlen(dump.infilename);
- if (length > 0)
- {
- if (dump.infile != NULL)
- fclose (dump.infile);
-
- /* dump.infilename is guaranteed to be NUL terminated and have 20 bytes
- fewer than PATH_MAX */
- snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s",
- dump.infilename, dump_images,
- (dump.format == DUMP_TEXT) ? "txt" : "raw");
- if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL)
- {
- TIFFError ("Unable to open dump file for writing", "%s", temp_filename);
- exit (EXIT_FAILURE);
- }
- dump_info(dump.infile, dump.format, "Reading image","%u from %s",
- dump_images, TIFFFileName(in));
- }
- length = strlen(dump.outfilename);
- if (length > 0)
- {
- if (dump.outfile != NULL)
- fclose (dump.outfile);
-
- /* dump.outfilename is guaranteed to be NUL terminated and have 20 bytes
- fewer than PATH_MAX */
- snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s",
- dump.outfilename, dump_images,
- (dump.format == DUMP_TEXT) ? "txt" : "raw");
- if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL)
- {
- TIFFError ("Unable to open dump file for writing", "%s", temp_filename);
- exit (EXIT_FAILURE);
- }
- dump_info(dump.outfile, dump.format, "Writing image","%u from %s",
- dump_images, TIFFFileName(in));
- }
- }
-
- if (dump.debug)
- TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages);
-
- if (loadImage(in, &image, &dump, &read_buff))
- {
- TIFFError("main", "Unable to load source image");
- exit (EXIT_FAILURE);
- }
-
- /* Correct the image orientation if it was not ORIENTATION_TOPLEFT.
- */
- if (image.adjustments != 0)
- {
- if (correct_orientation(&image, &read_buff))
- TIFFError("main", "Unable to correct image orientation");
- }
-
- if (getCropOffsets(&image, &crop, &dump))
- {
- TIFFError("main", "Unable to define crop regions");
- exit (EXIT_FAILURE);
- }
-
- /* Crop input image and copy zones and regions from input image into seg_buffs or crop_buff. */
- if (crop.selections > 0)
- {
- if (processCropSelections(&image, &crop, &read_buff, seg_buffs))
- {
- TIFFError("main", "Unable to process image selections");
- exit (EXIT_FAILURE);
- }
- }
- else /* Single image segment without zones or regions */
- {
- if (createCroppedImage(&image, &crop, &read_buff, &crop_buff))
- {
- TIFFError("main", "Unable to create output image");
- exit (EXIT_FAILURE);
- }
- }
- /* Format and write selected image parts to output file(s). */
- if (page.mode == PAGE_MODE_NONE)
- { /* Whole image or sections not based on output page size */
- if (crop.selections > 0)
- {
- writeSelections(in, &out, &crop, &image, &dump, seg_buffs,
- mp, argv[argc - 1], &next_page, total_pages);
- }
- else /* One file all images and sections */
- {
- if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1],
- &next_page))
- exit (EXIT_FAILURE);
- if (writeCroppedImage(in, out, &image, &dump,crop.combined_width,
- crop.combined_length, crop_buff, next_page, total_pages))
- {
- TIFFError("main", "Unable to write new image");
- exit (EXIT_FAILURE);
- }
- }
- }
- else
- {
- /* If we used a crop buffer, our data is there, otherwise it is
- * in the read_buffer
- */
- if (crop_buff != NULL)
- sect_src = crop_buff;
+ TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
+ if (opts == NULL)
+ {
+ return -3;
+ }
+ TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
+ in = TIFFOpenExt(argv[optind], "r", opts);
+ TIFFOpenOptionsFree(opts);
+ if (in == NULL)
+ return (-3);
+
+ /* If only one input file is specified, we can use directory count */
+ total_images = TIFFNumberOfDirectories(in);
+ if (total_images > TIFF_DIR_MAX)
+ {
+ TIFFError(TIFFFileName(in), "File contains too many directories");
+ if (out != NULL)
+ (void)TIFFClose(out);
+ return (1);
+ }
+ if (image_count == 0)
+ {
+ dirnum = 0;
+ total_pages = total_images; /* Only valid with single input file */
+ }
else
- sect_src = read_buff;
- /* Break input image into pages or rows and columns */
- if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump))
- {
- TIFFError("main", "Unable to compute output section data");
- exit (EXIT_FAILURE);
- }
- /* If there are multiple files on the command line, the final one is assumed
- * to be the output filename into which the images are written.
- */
- if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page))
- exit (EXIT_FAILURE);
+ {
+ dirnum = (tdir_t)(imagelist[next_image] - 1);
+ next_image++;
+
+ /* Total pages only valid for enumerated list of pages not derived
+ * using odd, even, or last keywords.
+ */
+ if (image_count > total_images)
+ image_count = total_images;
- if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, &sect_buff))
- {
- TIFFError("main", "Unable to write image sections");
- exit (EXIT_FAILURE);
- }
+ total_pages = image_count;
}
- /* No image list specified, just read the next image */
- if (image_count == 0)
- dirnum++;
- else
+ /* MAX_IMAGES is used for special case "last" in selection list */
+ if (dirnum == (MAX_IMAGES - 1))
+ dirnum = total_images - 1;
+
+ if (dirnum > (total_images))
{
- dirnum = (tdir_t)(imagelist[next_image] - 1);
- next_image++;
+ TIFFError(TIFFFileName(in),
+ "Invalid image number %" PRIu32
+ ", File contains only %" PRIu32 " images",
+ dirnum + 1u, total_images);
+ if (out != NULL)
+ (void)TIFFClose(out);
+ return (1);
}
- if (dirnum == MAX_IMAGES - 1)
- dirnum = TIFFNumberOfDirectories(in) - 1;
+ if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum))
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, setting subdirectory at %" PRIu32, dirnum);
+ if (out != NULL)
+ (void)TIFFClose(out);
+ return (1);
+ }
- if (!TIFFSetDirectory(in, (tdir_t)dirnum))
- end_of_input = TRUE;
- }
- TIFFClose(in);
- optind++;
+ end_of_input = FALSE;
+ while (end_of_input == FALSE)
+ {
+ config = defconfig;
+ compression = defcompression;
+ predictor = defpredictor;
+ fillorder = deffillorder;
+ rowsperstrip = defrowsperstrip;
+ tilewidth = deftilewidth;
+ tilelength = deftilelength;
+ g3opts = defg3opts;
+
+ if (dump.format != DUMP_NONE)
+ {
+ /* manage input and/or output dump files here */
+ dump_images++;
+ length = strlen(dump.infilename);
+ if (length > 0)
+ {
+ if (dump.infile != NULL)
+ fclose(dump.infile);
+
+ /* dump.infilename is guaranteed to be NUL terminated and
+ have 20 bytes fewer than PATH_MAX */
+ snprintf(temp_filename, sizeof(temp_filename),
+ "%s-read-%03d.%s", dump.infilename, dump_images,
+ (dump.format == DUMP_TEXT) ? "txt" : "raw");
+ if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL)
+ {
+ TIFFError("Unable to open dump file for writing", "%s",
+ temp_filename);
+ exit(EXIT_FAILURE);
+ }
+ dump_info(dump.infile, dump.format, "Reading image",
+ "%u from %s", dump_images, TIFFFileName(in));
+ }
+ length = strlen(dump.outfilename);
+ if (length > 0)
+ {
+ if (dump.outfile != NULL)
+ fclose(dump.outfile);
+
+ /* dump.outfilename is guaranteed to be NUL terminated and
+ have 20 bytes fewer than PATH_MAX */
+ snprintf(temp_filename, sizeof(temp_filename),
+ "%s-write-%03d.%s", dump.outfilename, dump_images,
+ (dump.format == DUMP_TEXT) ? "txt" : "raw");
+ if ((dump.outfile = fopen(temp_filename, dump.mode)) ==
+ NULL)
+ {
+ TIFFError("Unable to open dump file for writing", "%s",
+ temp_filename);
+ exit(EXIT_FAILURE);
+ }
+ dump_info(dump.outfile, dump.format, "Writing image",
+ "%u from %s", dump_images, TIFFFileName(in));
+ }
+ }
+
+ if (dump.debug)
+ TIFFError("main", "Reading image %4d of %4d total pages.",
+ dirnum + 1, total_pages);
+
+ if (loadImage(in, &image, &dump, &read_buff))
+ {
+ TIFFError("main", "Unable to load source image");
+ exit(EXIT_FAILURE);
+ }
+
+ /* Correct the image orientation if it was not ORIENTATION_TOPLEFT.
+ */
+ if (image.adjustments != 0)
+ {
+ if (correct_orientation(&image, &read_buff))
+ TIFFError("main", "Unable to correct image orientation");
+ }
+
+ if (getCropOffsets(&image, &crop, &dump))
+ {
+ TIFFError("main", "Unable to define crop regions");
+ exit(EXIT_FAILURE);
+ }
+
+ /* Crop input image and copy zones and regions from input image into
+ * seg_buffs or crop_buff. */
+ if (crop.selections > 0)
+ {
+ if (processCropSelections(&image, &crop, &read_buff, seg_buffs))
+ {
+ TIFFError("main", "Unable to process image selections");
+ exit(EXIT_FAILURE);
+ }
+ }
+ else /* Single image segment without zones or regions */
+ {
+ if (createCroppedImage(&image, &crop, &read_buff, &crop_buff))
+ {
+ TIFFError("main", "Unable to create output image");
+ exit(EXIT_FAILURE);
+ }
+ }
+ /* Format and write selected image parts to output file(s). */
+ if (page.mode == PAGE_MODE_NONE)
+ { /* Whole image or sections not based on output page size */
+ if (crop.selections > 0)
+ {
+ writeSelections(in, &out, &crop, &image, &dump, seg_buffs,
+ mp, argv[argc - 1], &next_page,
+ total_pages);
+ }
+ else /* One file all images and sections */
+ {
+ if (update_output_file(&out, mp, crop.exp_mode,
+ argv[argc - 1], &next_page))
+ exit(EXIT_FAILURE);
+ if (writeCroppedImage(in, out, &image, &dump,
+ crop.combined_width,
+ crop.combined_length, crop_buff,
+ next_page, total_pages))
+ {
+ TIFFError("main", "Unable to write new image");
+ exit(EXIT_FAILURE);
+ }
+ }
+ }
+ else
+ {
+ /* If we used a crop buffer, our data is there, otherwise it is
+ * in the read_buffer
+ */
+ if (crop_buff != NULL)
+ sect_src = crop_buff;
+ else
+ sect_src = read_buff;
+ /* Break input image into pages or rows and columns */
+ if (computeOutputPixelOffsets(&crop, &image, &page, sections,
+ &dump))
+ {
+ TIFFError("main", "Unable to compute output section data");
+ exit(EXIT_FAILURE);
+ }
+ /* If there are multiple files on the command line, the final
+ * one is assumed to be the output filename into which the
+ * images are written.
+ */
+ if (update_output_file(&out, mp, crop.exp_mode, argv[argc - 1],
+ &next_page))
+ exit(EXIT_FAILURE);
+
+ if (writeImageSections(in, out, &image, &page, sections, &dump,
+ sect_src, &sect_buff))
+ {
+ TIFFError("main", "Unable to write image sections");
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ /* No image list specified, just read the next image */
+ if (image_count == 0)
+ dirnum++;
+ else
+ {
+ dirnum = (tdir_t)(imagelist[next_image] - 1);
+ next_image++;
+ }
+
+ if (dirnum == MAX_IMAGES - 1)
+ dirnum = TIFFNumberOfDirectories(in) - 1;
+
+ if (!TIFFSetDirectory(in, (tdir_t)dirnum))
+ end_of_input = TRUE;
+ }
+ TIFFClose(in);
+ optind++;
}
- /* If we did not use the read buffer as the crop buffer */
- if (read_buff)
- _TIFFfree(read_buff);
+ /* If we did not use the read buffer as the crop buffer */
+ if (read_buff)
+ _TIFFfree(read_buff);
- if (crop_buff)
- _TIFFfree(crop_buff);
+ if (crop_buff)
+ _TIFFfree(crop_buff);
- if (sect_buff)
- _TIFFfree(sect_buff);
+ if (sect_buff)
+ _TIFFfree(sect_buff);
- /* Clean up any segment buffers used for zones or regions */
- for (seg = 0; seg < crop.selections; seg++)
- _TIFFfree (seg_buffs[seg].buffer);
+ /* Clean up any segment buffers used for zones or regions */
+ for (seg = 0; seg < crop.selections; seg++)
+ _TIFFfree(seg_buffs[seg].buffer);
- if (dump.format != DUMP_NONE)
+ if (dump.format != DUMP_NONE)
{
- if (dump.infile != NULL)
- fclose (dump.infile);
+ if (dump.infile != NULL)
+ fclose(dump.infile);
- if (dump.outfile != NULL)
- {
- dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out));
- fclose (dump.outfile);
- }
+ if (dump.outfile != NULL)
+ {
+ dump_info(dump.outfile, dump.format, "", "Completed run for %s",
+ TIFFFileName(out));
+ fclose(dump.outfile);
+ }
}
- TIFFClose(out);
-
- return (0);
- } /* end main */
+ TIFFClose(out);
+ return (0);
+} /* end main */
/* Debugging functions */
-static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32_t count)
- {
- int j, k;
- uint32_t i;
- char dump_array[10];
- unsigned char bitset;
+static int dump_data(FILE *dumpfile, int format, char *dump_tag,
+ unsigned char *data, uint32_t count)
+{
+ int j, k;
+ uint32_t i;
+ char dump_array[10];
+ unsigned char bitset;
- if (dumpfile == NULL)
+ if (dumpfile == NULL)
{
- TIFFError ("", "Invalid FILE pointer for dump file");
- return (1);
+ TIFFError("", "Invalid FILE pointer for dump file");
+ return (1);
}
- if (format == DUMP_TEXT)
+ if (format == DUMP_TEXT)
{
- fprintf (dumpfile," %s ", dump_tag);
- for (i = 0; i < count; i++)
- {
- for (j = 0, k = 7; j < 8; j++, k--)
+ fprintf(dumpfile, " %s ", dump_tag);
+ for (i = 0; i < count; i++)
{
- bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0;
- sprintf(&dump_array[j], (bitset) ? "1" : "0");
+ for (j = 0, k = 7; j < 8; j++, k--)
+ {
+ bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0;
+ sprintf(&dump_array[j], (bitset) ? "1" : "0");
+ }
+ dump_array[8] = '\0';
+ fprintf(dumpfile, " %s", dump_array);
}
- dump_array[8] = '\0';
- fprintf (dumpfile," %s", dump_array);
- }
- fprintf (dumpfile,"\n");
+ fprintf(dumpfile, "\n");
}
- else
+ else
{
- if ((fwrite (data, 1, count, dumpfile)) != count)
- {
- TIFFError ("", "Unable to write binary data to dump file");
- return (1);
- }
+ if ((fwrite(data, 1, count, dumpfile)) != count)
+ {
+ TIFFError("", "Unable to write binary data to dump file");
+ return (1);
+ }
}
- return (0);
- }
+ return (0);
+}
-static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data)
- {
- int j, k;
- char dump_array[10];
- unsigned char bitset;
+static int dump_byte(FILE *dumpfile, int format, char *dump_tag,
+ unsigned char data)
+{
+ int j, k;
+ char dump_array[10];
+ unsigned char bitset;
- if (dumpfile == NULL)
+ if (dumpfile == NULL)
{
- TIFFError ("", "Invalid FILE pointer for dump file");
- return (1);
+ TIFFError("", "Invalid FILE pointer for dump file");
+ return (1);
}
- if (format == DUMP_TEXT)
+ if (format == DUMP_TEXT)
{
- fprintf (dumpfile," %s ", dump_tag);
- for (j = 0, k = 7; j < 8; j++, k--)
- {
- bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
- sprintf(&dump_array[j], (bitset) ? "1" : "0");
- }
- dump_array[8] = '\0';
- fprintf (dumpfile," %s\n", dump_array);
+ fprintf(dumpfile, " %s ", dump_tag);
+ for (j = 0, k = 7; j < 8; j++, k--)
+ {
+ bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
+ sprintf(&dump_array[j], (bitset) ? "1" : "0");
+ }
+ dump_array[8] = '\0';
+ fprintf(dumpfile, " %s\n", dump_array);
}
- else
+ else
{
- if ((fwrite (&data, 1, 1, dumpfile)) != 1)
- {
- TIFFError ("", "Unable to write binary data to dump file");
- return (1);
- }
+ if ((fwrite(&data, 1, 1, dumpfile)) != 1)
+ {
+ TIFFError("", "Unable to write binary data to dump file");
+ return (1);
+ }
}
- return (0);
- }
+ return (0);
+}
-static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16_t data)
- {
- int j, k;
- char dump_array[20];
- unsigned char bitset;
+static int dump_short(FILE *dumpfile, int format, char *dump_tag, uint16_t data)
+{
+ int j, k;
+ char dump_array[20];
+ unsigned char bitset;
- if (dumpfile == NULL)
+ if (dumpfile == NULL)
{
- TIFFError ("", "Invalid FILE pointer for dump file");
- return (1);
+ TIFFError("", "Invalid FILE pointer for dump file");
+ return (1);
}
- if (format == DUMP_TEXT)
+ if (format == DUMP_TEXT)
{
- fprintf (dumpfile," %s ", dump_tag);
- for (j = 0, k = 15; k >= 0; j++, k--)
- {
- bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
- sprintf(&dump_array[j], (bitset) ? "1" : "0");
- if ((k % 8) == 0)
- sprintf(&dump_array[++j], " ");
- }
- dump_array[17] = '\0';
- fprintf (dumpfile," %s\n", dump_array);
+ fprintf(dumpfile, " %s ", dump_tag);
+ for (j = 0, k = 15; k >= 0; j++, k--)
+ {
+ bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
+ sprintf(&dump_array[j], (bitset) ? "1" : "0");
+ if ((k % 8) == 0)
+ sprintf(&dump_array[++j], " ");
+ }
+ dump_array[17] = '\0';
+ fprintf(dumpfile, " %s\n", dump_array);
}
- else
+ else
{
- if ((fwrite (&data, 2, 1, dumpfile)) != 2)
- {
- TIFFError ("", "Unable to write binary data to dump file");
- return (1);
- }
+ if ((fwrite(&data, 2, 1, dumpfile)) != 2)
+ {
+ TIFFError("", "Unable to write binary data to dump file");
+ return (1);
+ }
}
- return (0);
- }
+ return (0);
+}
-static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32_t data)
- {
- int j, k;
- char dump_array[40];
- unsigned char bitset;
+static int dump_long(FILE *dumpfile, int format, char *dump_tag, uint32_t data)
+{
+ int j, k;
+ char dump_array[40];
+ unsigned char bitset;
- if (dumpfile == NULL)
+ if (dumpfile == NULL)
{
- TIFFError ("", "Invalid FILE pointer for dump file");
- return (1);
+ TIFFError("", "Invalid FILE pointer for dump file");
+ return (1);
}
- if (format == DUMP_TEXT)
+ if (format == DUMP_TEXT)
{
- fprintf (dumpfile," %s ", dump_tag);
- for (j = 0, k = 31; k >= 0; j++, k--)
- {
- bitset = data & (((uint32_t)1 << k)) ? 1 : 0;
- sprintf(&dump_array[j], (bitset) ? "1" : "0");
- if ((k % 8) == 0)
- sprintf(&dump_array[++j], " ");
- }
- dump_array[35] = '\0';
- fprintf (dumpfile," %s\n", dump_array);
+ fprintf(dumpfile, " %s ", dump_tag);
+ for (j = 0, k = 31; k >= 0; j++, k--)
+ {
+ bitset = data & (((uint32_t)1 << k)) ? 1 : 0;
+ sprintf(&dump_array[j], (bitset) ? "1" : "0");
+ if ((k % 8) == 0)
+ sprintf(&dump_array[++j], " ");
+ }
+ dump_array[35] = '\0';
+ fprintf(dumpfile, " %s\n", dump_array);
}
- else
+ else
{
- if ((fwrite (&data, 4, 1, dumpfile)) != 4)
- {
- TIFFError ("", "Unable to write binary data to dump file");
- return (1);
- }
+ if ((fwrite(&data, 4, 1, dumpfile)) != 4)
+ {
+ TIFFError("", "Unable to write binary data to dump file");
+ return (1);
+ }
}
- return (0);
- }
+ return (0);
+}
-static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64_t data)
- {
- int j, k;
- char dump_array[80];
- unsigned char bitset;
+static int dump_wide(FILE *dumpfile, int format, char *dump_tag, uint64_t data)
+{
+ int j, k;
+ char dump_array[80];
+ unsigned char bitset;
- if (dumpfile == NULL)
+ if (dumpfile == NULL)
{
- TIFFError ("", "Invalid FILE pointer for dump file");
- return (1);
+ TIFFError("", "Invalid FILE pointer for dump file");
+ return (1);
}
- if (format == DUMP_TEXT)
+ if (format == DUMP_TEXT)
{
- fprintf (dumpfile," %s ", dump_tag);
- for (j = 0, k = 63; k >= 0; j++, k--)
- {
- bitset = data & (((uint64_t)1 << k)) ? 1 : 0;
- sprintf(&dump_array[j], (bitset) ? "1" : "0");
- if ((k % 8) == 0)
- sprintf(&dump_array[++j], " ");
- }
- dump_array[71] = '\0';
- fprintf (dumpfile," %s\n", dump_array);
+ fprintf(dumpfile, " %s ", dump_tag);
+ for (j = 0, k = 63; k >= 0; j++, k--)
+ {
+ bitset = data & (((uint64_t)1 << k)) ? 1 : 0;
+ sprintf(&dump_array[j], (bitset) ? "1" : "0");
+ if ((k % 8) == 0)
+ sprintf(&dump_array[++j], " ");
+ }
+ dump_array[71] = '\0';
+ fprintf(dumpfile, " %s\n", dump_array);
}
- else
+ else
{
- if ((fwrite (&data, 8, 1, dumpfile)) != 8)
- {
- TIFFError ("", "Unable to write binary data to dump file");
- return (1);
- }
+ if ((fwrite(&data, 8, 1, dumpfile)) != 8)
+ {
+ TIFFError("", "Unable to write binary data to dump file");
+ return (1);
+ }
}
- return (0);
- }
+ return (0);
+}
static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...)
- {
- if (format == DUMP_TEXT)
+{
+ if (format == DUMP_TEXT)
{
- va_list ap;
- va_start(ap, msg);
- fprintf(dumpfile, "%s ", prefix);
- vfprintf(dumpfile, msg, ap);
- fprintf(dumpfile, "\n");
- va_end(ap);
+ va_list ap;
+ va_start(ap, msg);
+ fprintf(dumpfile, "%s ", prefix);
+ vfprintf(dumpfile, msg, ap);
+ fprintf(dumpfile, "\n");
+ va_end(ap);
}
- }
+}
-static int dump_buffer (FILE* dumpfile, int format, uint32_t rows, uint32_t width,
- uint32_t row, unsigned char *buff)
- {
- int k;
- uint32_t i;
- unsigned char * dump_ptr;
+static int dump_buffer(FILE *dumpfile, int format, uint32_t rows,
+ uint32_t width, uint32_t row, unsigned char *buff)
+{
+ int k;
+ uint32_t i;
+ unsigned char *dump_ptr;
- if (dumpfile == NULL)
+ if (dumpfile == NULL)
{
- TIFFError ("", "Invalid FILE pointer for dump file");
- return (1);
+ TIFFError("", "Invalid FILE pointer for dump file");
+ return (1);
}
- for (i = 0; i < rows; i++)
+ for (i = 0; i < rows; i++)
{
- dump_ptr = buff + (i * width);
- if (format == DUMP_TEXT)
- dump_info (dumpfile, format, "",
- "Row %4"PRIu32", %"PRIu32" bytes at offset %"PRIu32,
- row + i + 1u, width, row * width);
-
- for (k = width; k >= 10; k -= 10, dump_ptr += 10)
- dump_data (dumpfile, format, "", dump_ptr, 10);
- if (k > 0)
- dump_data (dumpfile, format, "", dump_ptr, k);
- }
- return (0);
- }
+ dump_ptr = buff + (i * width);
+ if (format == DUMP_TEXT)
+ dump_info(dumpfile, format, "",
+ "Row %4" PRIu32 ", %" PRIu32 " bytes at offset %" PRIu32,
+ row + i + 1u, width, row * width);
+
+ for (k = width; k >= 10; k -= 10, dump_ptr += 10)
+ dump_data(dumpfile, format, "", dump_ptr, 10);
+ if (k > 0)
+ dump_data(dumpfile, format, "", dump_ptr, k);
+ }
+ return (0);
+}
/* Extract one or more samples from an interleaved buffer. If count == 1,
- * only the sample plane indicated by sample will be extracted. If count > 1,
- * count samples beginning at sample will be extracted. Portions of a
+ * only the sample plane indicated by sample will be extracted. If count > 1,
+ * count samples beginning at sample will be extracted. Portions of a
* scanline can be extracted by specifying a start and end value.
*/
-static int
-extractContigSamplesBytes (uint8_t *in, uint8_t *out, uint32_t cols,
- tsample_t sample, uint16_t spp, uint16_t bps,
- tsample_t count, uint32_t start, uint32_t end)
- {
- int i, bytes_per_sample, sindex;
- uint32_t col, dst_rowsize, bit_offset, numcols;
- uint32_t src_byte /*, src_bit */;
- uint8_t *src = in;
- uint8_t *dst = out;
+static int extractContigSamplesBytes(uint8_t *in, uint8_t *out, uint32_t cols,
+ tsample_t sample, uint16_t spp,
+ uint16_t bps, tsample_t count,
+ uint32_t start, uint32_t end)
+{
+ int i, bytes_per_sample, sindex;
+ uint32_t col, dst_rowsize, bit_offset, numcols;
+ uint32_t src_byte /*, src_bit */;
+ uint8_t *src = in;
+ uint8_t *dst = out;
- if ((src == NULL) || (dst == NULL))
+ if ((src == NULL) || (dst == NULL))
{
- TIFFError("extractContigSamplesBytes","Invalid input or output buffer");
- return (1);
+ TIFFError("extractContigSamplesBytes",
+ "Invalid input or output buffer");
+ return (1);
}
- /* Number of extracted columns shall be kept as (end-start + 1). Otherwise buffer-overflow might occur.
- * 'start' and 'col' count from 0 to (cols-1) but 'end' is to be set one after the index of the last column to be copied!
- */
- if (end >= start) numcols = end - start; else numcols = start - end;
- if ((start > end) || (start > cols))
+ /* Number of extracted columns shall be kept as (end-start + 1). Otherwise
+ * buffer-overflow might occur. 'start' and 'col' count from 0 to (cols-1)
+ * but 'end' is to be set one after the index of the last column to be
+ * copied!
+ */
+ if (end >= start)
+ numcols = end - start;
+ else
+ numcols = start - end;
+ if ((start > end) || (start > cols))
+ {
+ TIFFError("extractContigSamplesBytes",
+ "Invalid start column value %" PRIu32 " ignored", start);
+ start = 0;
+ }
+ if ((end == 0) || (end > cols))
{
- TIFFError ("extractContigSamplesBytes",
- "Invalid start column value %"PRIu32" ignored", start);
- start = 0;
+ TIFFError("extractContigSamplesBytes",
+ "Invalid end column value %" PRIu32 " ignored", end);
+ end = cols;
}
- if ((end == 0) || (end > cols))
+ if ((end - start) > numcols)
{
- TIFFError ("extractContigSamplesBytes",
- "Invalid end column value %"PRIu32" ignored", end);
- end = cols;
+ end = start + numcols;
}
- if ((end - start) > numcols) {
- end = start + numcols;
- }
- dst_rowsize = (bps * (end - start) * count) / 8;
+ dst_rowsize = (bps * (end - start) * count) / 8;
- bytes_per_sample = (bps + 7) / 8;
- /* Optimize case for copying all samples */
- if (count == spp)
+ bytes_per_sample = (bps + 7) / 8;
+ /* Optimize case for copying all samples */
+ if (count == spp)
{
- src = in + (start * spp * bytes_per_sample);
- _TIFFmemcpy (dst, src, dst_rowsize);
+ src = in + (start * spp * bytes_per_sample);
+ _TIFFmemcpy(dst, src, dst_rowsize);
}
- else
+ else
{
- for (col = start; col < end; col++)
- {
- for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
+ for (col = start; col < end; col++)
{
- bit_offset = col * bps * spp;
- if (sindex == 0)
- {
- src_byte = bit_offset / 8;
- /* src_bit = bit_offset % 8; */
- }
- else
- {
- src_byte = (bit_offset + (sindex * bps)) / 8;
- /* src_bit = (bit_offset + (sindex * bps)) % 8; */
- }
- src = in + src_byte;
- for (i = 0; i < bytes_per_sample; i++)
- *dst++ = *src++;
- }
- }
- }
-
- return (0);
- } /* end extractContigSamplesBytes */
-
-static int
-extractContigSamples8bits (uint8_t *in, uint8_t *out, uint32_t cols,
- tsample_t sample, uint16_t spp, uint16_t bps,
- tsample_t count, uint32_t start, uint32_t end)
- {
- int ready_bits = 0, sindex = 0;
- uint32_t col, src_byte, src_bit, bit_offset, numcols;
- uint8_t maskbits = 0, matchbits = 0;
- uint8_t buff1 = 0, buff2 = 0;
- uint8_t *src = in;
- uint8_t *dst = out;
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("extractContigSamples8bits","Invalid input or output buffer");
- return (1);
+ for (sindex = sample; (sindex < spp) && (sindex < (sample + count));
+ sindex++)
+ {
+ bit_offset = col * bps * spp;
+ if (sindex == 0)
+ {
+ src_byte = bit_offset / 8;
+ /* src_bit = bit_offset % 8; */
+ }
+ else
+ {
+ src_byte = (bit_offset + (sindex * bps)) / 8;
+ /* src_bit = (bit_offset + (sindex * bps)) % 8; */
+ }
+ src = in + src_byte;
+ for (i = 0; i < bytes_per_sample; i++)
+ *dst++ = *src++;
+ }
+ }
+ }
+
+ return (0);
+} /* end extractContigSamplesBytes */
+
+static int extractContigSamples8bits(uint8_t *in, uint8_t *out, uint32_t cols,
+ tsample_t sample, uint16_t spp,
+ uint16_t bps, tsample_t count,
+ uint32_t start, uint32_t end)
+{
+ int ready_bits = 0, sindex = 0;
+ uint32_t col, src_byte, src_bit, bit_offset, numcols;
+ uint8_t maskbits = 0, matchbits = 0;
+ uint8_t buff1 = 0, buff2 = 0;
+ uint8_t *src = in;
+ uint8_t *dst = out;
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("extractContigSamples8bits",
+ "Invalid input or output buffer");
+ return (1);
}
- /* Number of extracted columns shall be kept as (end-start + 1). Otherwise buffer-overflow might occur.
- * 'start' and 'col' count from 0 to (cols-1) but 'end' is to be set one after the index of the last column to be copied!
- */
- if (end >= start) numcols = end - start; else numcols = start - end;
- if ((start > end) || (start > cols))
+ /* Number of extracted columns shall be kept as (end-start + 1). Otherwise
+ * buffer-overflow might occur. 'start' and 'col' count from 0 to (cols-1)
+ * but 'end' is to be set one after the index of the last column to be
+ * copied!
+ */
+ if (end >= start)
+ numcols = end - start;
+ else
+ numcols = start - end;
+ if ((start > end) || (start > cols))
+ {
+ TIFFError("extractContigSamples8bits",
+ "Invalid start column value %" PRIu32 " ignored", start);
+ start = 0;
+ }
+ if ((end == 0) || (end > cols))
{
- TIFFError ("extractContigSamples8bits",
- "Invalid start column value %"PRIu32" ignored", start);
- start = 0;
+ TIFFError("extractContigSamples8bits",
+ "Invalid end column value %" PRIu32 " ignored", end);
+ end = cols;
}
- if ((end == 0) || (end > cols))
+ if ((end - start) > numcols)
{
- TIFFError ("extractContigSamples8bits",
- "Invalid end column value %"PRIu32" ignored", end);
- end = cols;
+ end = start + numcols;
}
- if ((end - start) > numcols) {
- end = start + numcols;
- }
- ready_bits = 0;
- maskbits = (uint8_t)-1 >> (8 - bps);
- buff1 = buff2 = 0;
- for (col = start; col < end; col++)
- { /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps * spp;
- for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
- {
- if (sindex == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ ready_bits = 0;
+ maskbits = (uint8_t)-1 >> (8 - bps);
+ buff1 = buff2 = 0;
+ for (col = start; col < end; col++)
+ { /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps * spp;
+ for (sindex = sample; (sindex < spp) && (sindex < (sample + count));
+ sindex++)
{
- src_byte = (bit_offset + (sindex * bps)) / 8;
- src_bit = (bit_offset + (sindex * bps)) % 8;
- }
+ if (sindex == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sindex * bps)) / 8;
+ src_bit = (bit_offset + (sindex * bps)) % 8;
+ }
- src = in + src_byte;
- matchbits = maskbits << (8 - src_bit - bps);
- buff1 = ((*src) & matchbits) << (src_bit);
+ src = in + src_byte;
+ matchbits = maskbits << (8 - src_bit - bps);
+ buff1 = ((*src) & matchbits) << (src_bit);
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 8)
- {
- *dst++ = buff2;
- buff2 = buff1;
- ready_bits -= 8;
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 8)
+ {
+ *dst++ = buff2;
+ buff2 = buff1;
+ ready_bits -= 8;
+ }
+ else
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ ready_bits += bps;
}
- else
- buff2 = (buff2 | (buff1 >> ready_bits));
- ready_bits += bps;
- }
}
- while (ready_bits > 0)
+ while (ready_bits > 0)
{
- buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
- *dst++ = buff1;
- ready_bits -= 8;
+ buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
+ *dst++ = buff1;
+ ready_bits -= 8;
}
- return (0);
- } /* end extractContigSamples8bits */
+ return (0);
+} /* end extractContigSamples8bits */
-static int
-extractContigSamples16bits (uint8_t *in, uint8_t *out, uint32_t cols,
- tsample_t sample, uint16_t spp, uint16_t bps,
- tsample_t count, uint32_t start, uint32_t end)
- {
- int ready_bits = 0, sindex = 0;
- uint32_t col, src_byte, src_bit, bit_offset, numcols;
- uint16_t maskbits = 0, matchbits = 0;
- uint16_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff = 0;
- uint8_t *src = in;
- uint8_t *dst = out;
+static int extractContigSamples16bits(uint8_t *in, uint8_t *out, uint32_t cols,
+ tsample_t sample, uint16_t spp,
+ uint16_t bps, tsample_t count,
+ uint32_t start, uint32_t end)
+{
+ int ready_bits = 0, sindex = 0;
+ uint32_t col, src_byte, src_bit, bit_offset, numcols;
+ uint16_t maskbits = 0, matchbits = 0;
+ uint16_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff = 0;
+ uint8_t *src = in;
+ uint8_t *dst = out;
- if ((src == NULL) || (dst == NULL))
+ if ((src == NULL) || (dst == NULL))
{
- TIFFError("extractContigSamples16bits","Invalid input or output buffer");
- return (1);
+ TIFFError("extractContigSamples16bits",
+ "Invalid input or output buffer");
+ return (1);
}
- /* Number of extracted columns shall be kept as (end-start + 1). Otherwise buffer-overflow might occur.
- * 'start' and 'col' count from 0 to (cols-1) but 'end' is to be set one after the index of the last column to be copied!
- */
- if (end >= start) numcols = end - start; else numcols = start - end;
- if ((start > end) || (start > cols))
+ /* Number of extracted columns shall be kept as (end-start + 1). Otherwise
+ * buffer-overflow might occur. 'start' and 'col' count from 0 to (cols-1)
+ * but 'end' is to be set one after the index of the last column to be
+ * copied!
+ */
+ if (end >= start)
+ numcols = end - start;
+ else
+ numcols = start - end;
+ if ((start > end) || (start > cols))
+ {
+ TIFFError("extractContigSamples16bits",
+ "Invalid start column value %" PRIu32 " ignored", start);
+ start = 0;
+ }
+ if ((end == 0) || (end > cols))
{
- TIFFError ("extractContigSamples16bits",
- "Invalid start column value %"PRIu32" ignored", start);
- start = 0;
+ TIFFError("extractContigSamples16bits",
+ "Invalid end column value %" PRIu32 " ignored", end);
+ end = cols;
}
- if ((end == 0) || (end > cols))
+ if ((end - start) > numcols)
{
- TIFFError ("extractContigSamples16bits",
- "Invalid end column value %"PRIu32" ignored", end);
- end = cols;
+ end = start + numcols;
}
- if ((end - start) > numcols) {
- end = start + numcols;
- }
- ready_bits = 0;
- maskbits = (uint16_t)-1 >> (16 - bps);
+ ready_bits = 0;
+ maskbits = (uint16_t)-1 >> (16 - bps);
- for (col = start; col < end; col++)
- { /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps * spp;
- for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
- {
- if (sindex == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ for (col = start; col < end; col++)
+ { /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps * spp;
+ for (sindex = sample; (sindex < spp) && (sindex < (sample + count));
+ sindex++)
{
- src_byte = (bit_offset + (sindex * bps)) / 8;
- src_bit = (bit_offset + (sindex * bps)) % 8;
- }
+ if (sindex == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sindex * bps)) / 8;
+ src_bit = (bit_offset + (sindex * bps)) % 8;
+ }
- src = in + src_byte;
- matchbits = maskbits << (16 - src_bit - bps);
+ src = in + src_byte;
+ matchbits = maskbits << (16 - src_bit - bps);
- if (little_endian)
- buff1 = (src[0] << 8) | src[1];
- else
- buff1 = (src[1] << 8) | src[0];
+ if (little_endian)
+ buff1 = (src[0] << 8) | src[1];
+ else
+ buff1 = (src[1] << 8) | src[0];
- buff1 = (buff1 & matchbits) << (src_bit);
- if (ready_bits < 8) /* add another bps bits to the buffer */
- {
- bytebuff = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- }
- else /* If we have a full buffer's worth, write it out */
- {
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
- ready_bits -= 8;
- /* shift in new bits */
- buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
+ buff1 = (buff1 & matchbits) << (src_bit);
+ if (ready_bits < 8) /* add another bps bits to the buffer */
+ {
+ bytebuff = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ else /* If we have a full buffer's worth, write it out */
+ {
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
+ ready_bits -= 8;
+ /* shift in new bits */
+ buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- ready_bits += bps;
- }
}
- /* catch any trailing bits at the end of the line */
- while (ready_bits > 0)
+ /* catch any trailing bits at the end of the line */
+ while (ready_bits > 0)
{
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
- ready_bits -= 8;
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
+ ready_bits -= 8;
}
-
- return (0);
- } /* end extractContigSamples16bits */
+ return (0);
+} /* end extractContigSamples16bits */
-static int
-extractContigSamples24bits (uint8_t *in, uint8_t *out, uint32_t cols,
- tsample_t sample, uint16_t spp, uint16_t bps,
- tsample_t count, uint32_t start, uint32_t end)
- {
- int ready_bits = 0, sindex = 0;
- uint32_t col, src_byte, src_bit, bit_offset, numcols;
- uint32_t maskbits = 0, matchbits = 0;
- uint32_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0;
- uint8_t *src = in;
- uint8_t *dst = out;
+static int extractContigSamples24bits(uint8_t *in, uint8_t *out, uint32_t cols,
+ tsample_t sample, uint16_t spp,
+ uint16_t bps, tsample_t count,
+ uint32_t start, uint32_t end)
+{
+ int ready_bits = 0, sindex = 0;
+ uint32_t col, src_byte, src_bit, bit_offset, numcols;
+ uint32_t maskbits = 0, matchbits = 0;
+ uint32_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0;
+ uint8_t *src = in;
+ uint8_t *dst = out;
- if ((in == NULL) || (out == NULL))
+ if ((in == NULL) || (out == NULL))
{
- TIFFError("extractContigSamples24bits","Invalid input or output buffer");
- return (1);
+ TIFFError("extractContigSamples24bits",
+ "Invalid input or output buffer");
+ return (1);
}
- /* Number of extracted columns shall be kept as (end-start + 1). Otherwise buffer-overflow might occur.
- * 'start' and 'col' count from 0 to (cols-1) but 'end' is to be set one after the index of the last column to be copied!
- */
- if (end >= start) numcols = end - start; else numcols = start - end;
- if ((start > end) || (start > cols))
+ /* Number of extracted columns shall be kept as (end-start + 1). Otherwise
+ * buffer-overflow might occur. 'start' and 'col' count from 0 to (cols-1)
+ * but 'end' is to be set one after the index of the last column to be
+ * copied!
+ */
+ if (end >= start)
+ numcols = end - start;
+ else
+ numcols = start - end;
+ if ((start > end) || (start > cols))
+ {
+ TIFFError("extractContigSamples24bits",
+ "Invalid start column value %" PRIu32 " ignored", start);
+ start = 0;
+ }
+ if ((end == 0) || (end > cols))
{
- TIFFError ("extractContigSamples24bits",
- "Invalid start column value %"PRIu32" ignored", start);
- start = 0;
+ TIFFError("extractContigSamples24bits",
+ "Invalid end column value %" PRIu32 " ignored", end);
+ end = cols;
}
- if ((end == 0) || (end > cols))
+ if ((end - start) > numcols)
{
- TIFFError ("extractContigSamples24bits",
- "Invalid end column value %"PRIu32" ignored", end);
- end = cols;
+ end = start + numcols;
}
- if ((end - start) > numcols) {
- end = start + numcols;
- }
- ready_bits = 0;
- maskbits = (uint32_t)-1 >> (32 - bps);
- for (col = start; col < end; col++)
+ ready_bits = 0;
+ maskbits = (uint32_t)-1 >> (32 - bps);
+ for (col = start; col < end; col++)
{
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps * spp;
- for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
- {
- if (sindex == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps * spp;
+ for (sindex = sample; (sindex < spp) && (sindex < (sample + count));
+ sindex++)
{
- src_byte = (bit_offset + (sindex * bps)) / 8;
- src_bit = (bit_offset + (sindex * bps)) % 8;
- }
+ if (sindex == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sindex * bps)) / 8;
+ src_bit = (bit_offset + (sindex * bps)) % 8;
+ }
- src = in + src_byte;
- matchbits = maskbits << (32 - src_bit - bps);
- if (little_endian)
- {
- buff1 = (src[0] << 24);
- if (matchbits & 0x00ff0000)
- buff1 |= (src[1] << 16);
- if (matchbits & 0x0000ff00)
- buff1 |= (src[2] << 8);
- if (matchbits & 0x000000ff)
- buff1 |= src[3];
- }
- else
- {
- buff1 = src[0];
- if (matchbits & 0x0000ff00)
- buff1 |= (src[1] << 8);
- if (matchbits & 0x00ff0000)
- buff1 |= (src[2] << 16);
- if (matchbits & 0xff000000)
- buff1 |= (src[3] << 24);
- }
- buff1 = (buff1 & matchbits) << (src_bit);
+ src = in + src_byte;
+ matchbits = maskbits << (32 - src_bit - bps);
+ if (little_endian)
+ {
+ buff1 = (src[0] << 24);
+ if (matchbits & 0x00ff0000)
+ buff1 |= (src[1] << 16);
+ if (matchbits & 0x0000ff00)
+ buff1 |= (src[2] << 8);
+ if (matchbits & 0x000000ff)
+ buff1 |= src[3];
+ }
+ else
+ {
+ buff1 = src[0];
+ if (matchbits & 0x0000ff00)
+ buff1 |= (src[1] << 8);
+ if (matchbits & 0x00ff0000)
+ buff1 |= (src[2] << 16);
+ if (matchbits & 0xff000000)
+ buff1 |= (src[3] << 24);
+ }
+ buff1 = (buff1 & matchbits) << (src_bit);
- if (ready_bits < 16) /* add another bps bits to the buffer */
- {
- bytebuff1 = bytebuff2 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
+ if (ready_bits < 16) /* add another bps bits to the buffer */
+ {
+ bytebuff1 = bytebuff2 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ else /* If we have a full buffer's worth, write it out */
+ {
+ bytebuff1 = (buff2 >> 24);
+ *dst++ = bytebuff1;
+ bytebuff2 = (buff2 >> 16);
+ *dst++ = bytebuff2;
+ ready_bits -= 16;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- else /* If we have a full buffer's worth, write it out */
- {
+ }
+
+ /* catch any trailing bits at the end of the line */
+ while (ready_bits > 0)
+ {
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
- bytebuff2 = (buff2 >> 16);
- *dst++ = bytebuff2;
- ready_bits -= 16;
-
- /* shift in new bits */
- buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
- }
- ready_bits += bps;
- }
- }
-
- /* catch any trailing bits at the end of the line */
- while (ready_bits > 0)
- {
- bytebuff1 = (buff2 >> 24);
- *dst++ = bytebuff1;
-
- buff2 = (buff2 << 8);
- bytebuff2 = bytebuff1;
- ready_bits -= 8;
- }
-
- return (0);
- } /* end extractContigSamples24bits */
-
-static int
-extractContigSamples32bits (uint8_t *in, uint8_t *out, uint32_t cols,
- tsample_t sample, uint16_t spp, uint16_t bps,
- tsample_t count, uint32_t start, uint32_t end)
- {
- int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
- uint32_t col, src_byte, src_bit, bit_offset, numcols;
- uint32_t longbuff1 = 0, longbuff2 = 0;
- uint64_t maskbits = 0, matchbits = 0;
- uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
- uint8_t *src = in;
- uint8_t *dst = out;
-
- if ((in == NULL) || (out == NULL))
- {
- TIFFError("extractContigSamples32bits","Invalid input or output buffer");
- return (1);
+
+ buff2 = (buff2 << 8);
+ bytebuff2 = bytebuff1;
+ ready_bits -= 8;
}
+ return (0);
+} /* end extractContigSamples24bits */
- /* Number of extracted columns shall be kept as (end-start + 1). Otherwise buffer-overflow might occur.
- * 'start' and 'col' count from 0 to (cols-1) but 'end' is to be set one after the index of the last column to be copied!
- */
- if (end >= start) numcols = end - start; else numcols = start - end;
- if ((start > end) || (start > cols))
+static int extractContigSamples32bits(uint8_t *in, uint8_t *out, uint32_t cols,
+ tsample_t sample, uint16_t spp,
+ uint16_t bps, tsample_t count,
+ uint32_t start, uint32_t end)
+{
+ int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
+ uint32_t col, src_byte, src_bit, bit_offset, numcols;
+ uint32_t longbuff1 = 0, longbuff2 = 0;
+ uint64_t maskbits = 0, matchbits = 0;
+ uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
+ uint8_t *src = in;
+ uint8_t *dst = out;
+
+ if ((in == NULL) || (out == NULL))
+ {
+ TIFFError("extractContigSamples32bits",
+ "Invalid input or output buffer");
+ return (1);
+ }
+
+ /* Number of extracted columns shall be kept as (end-start + 1). Otherwise
+ * buffer-overflow might occur. 'start' and 'col' count from 0 to (cols-1)
+ * but 'end' is to be set one after the index of the last column to be
+ * copied!
+ */
+ if (end >= start)
+ numcols = end - start;
+ else
+ numcols = start - end;
+ if ((start > end) || (start > cols))
+ {
+ TIFFError("extractContigSamples32bits",
+ "Invalid start column value %" PRIu32 " ignored", start);
+ start = 0;
+ }
+ if ((end == 0) || (end > cols))
{
- TIFFError ("extractContigSamples32bits",
- "Invalid start column value %"PRIu32" ignored", start);
- start = 0;
+ TIFFError("extractContigSamples32bits",
+ "Invalid end column value %" PRIu32 " ignored", end);
+ end = cols;
}
- if ((end == 0) || (end > cols))
+ if ((end - start) > numcols)
{
- TIFFError ("extractContigSamples32bits",
- "Invalid end column value %"PRIu32" ignored", end);
- end = cols;
+ end = start + numcols;
}
- if ((end - start) > numcols) {
- end = start + numcols;
- }
- /* shift_width = ((bps + 7) / 8) + 1; */
- ready_bits = 0;
- maskbits = (uint64_t)-1 >> (64 - bps);
- for (col = start; col < end; col++)
+ /* shift_width = ((bps + 7) / 8) + 1; */
+ ready_bits = 0;
+ maskbits = (uint64_t)-1 >> (64 - bps);
+ for (col = start; col < end; col++)
{
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps * spp;
- for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
- {
- if (sindex == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps * spp;
+ for (sindex = sample; (sindex < spp) && (sindex < (sample + count));
+ sindex++)
{
- src_byte = (bit_offset + (sindex * bps)) / 8;
- src_bit = (bit_offset + (sindex * bps)) % 8;
- }
+ if (sindex == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sindex * bps)) / 8;
+ src_bit = (bit_offset + (sindex * bps)) % 8;
+ }
- src = in + src_byte;
- matchbits = maskbits << (64 - src_bit - bps);
- if (little_endian)
- {
- longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
- longbuff2 = longbuff1;
- }
- else
- {
- longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
- longbuff2 = longbuff1;
- }
+ src = in + src_byte;
+ matchbits = maskbits << (64 - src_bit - bps);
+ if (little_endian)
+ {
+ longbuff1 =
+ (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
+ longbuff2 = longbuff1;
+ }
+ else
+ {
+ longbuff1 =
+ (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
+ longbuff2 = longbuff1;
+ }
- buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
- buff1 = (buff3 & matchbits) << (src_bit);
+ buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
+ buff1 = (buff3 & matchbits) << (src_bit);
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 32)
- {
- bytebuff1 = (uint8_t)(buff2 >> 56);
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 32)
+ {
+ bytebuff1 = (uint8_t)(buff2 >> 56);
+ *dst++ = bytebuff1;
+ bytebuff2 = (uint8_t)(buff2 >> 48);
+ *dst++ = bytebuff2;
+ bytebuff3 = (uint8_t)(buff2 >> 40);
+ *dst++ = bytebuff3;
+ bytebuff4 = (uint8_t)(buff2 >> 32);
+ *dst++ = bytebuff4;
+ ready_bits -= 32;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
+ }
+ else
+ { /* add another bps bits to the buffer */
+ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
+ }
+ }
+ while (ready_bits > 0)
+ {
+ bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
- bytebuff2 = (uint8_t)(buff2 >> 48);
- *dst++ = bytebuff2;
- bytebuff3 = (uint8_t)(buff2 >> 40);
- *dst++ = bytebuff3;
- bytebuff4 = (uint8_t)(buff2 >> 32);
- *dst++ = bytebuff4;
- ready_bits -= 32;
-
- /* shift in new bits */
- buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
- }
- else
- { /* add another bps bits to the buffer */
- bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- }
- ready_bits += bps;
- }
- }
- while (ready_bits > 0)
- {
- bytebuff1 = (buff2 >> 56);
- *dst++ = bytebuff1;
- buff2 = (buff2 << 8);
- ready_bits -= 8;
- }
-
- return (0);
- } /* end extractContigSamples32bits */
-
-static int
-extractContigSamplesShifted8bits (uint8_t *in, uint8_t *out, uint32_t cols,
- tsample_t sample, uint16_t spp, uint16_t bps,
- tsample_t count, uint32_t start, uint32_t end,
- int shift)
- {
- int ready_bits = 0, sindex = 0;
- uint32_t col, src_byte, src_bit, bit_offset, numcols;
- uint8_t maskbits = 0, matchbits = 0;
- uint8_t buff1 = 0, buff2 = 0;
- uint8_t *src = in;
- uint8_t *dst = out;
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer");
- return (1);
+ buff2 = (buff2 << 8);
+ ready_bits -= 8;
+ }
+
+ return (0);
+} /* end extractContigSamples32bits */
+
+static int extractContigSamplesShifted8bits(uint8_t *in, uint8_t *out,
+ uint32_t cols, tsample_t sample,
+ uint16_t spp, uint16_t bps,
+ tsample_t count, uint32_t start,
+ uint32_t end, int shift)
+{
+ int ready_bits = 0, sindex = 0;
+ uint32_t col, src_byte, src_bit, bit_offset, numcols;
+ uint8_t maskbits = 0, matchbits = 0;
+ uint8_t buff1 = 0, buff2 = 0;
+ uint8_t *src = in;
+ uint8_t *dst = out;
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("extractContigSamplesShifted8bits",
+ "Invalid input or output buffer");
+ return (1);
}
- /* Number of extracted columns shall be kept as (end-start + 1). Otherwise buffer-overflow might occur.
- * 'start' and 'col' count from 0 to (cols-1) but 'end' is to be set one after the index of the last column to be copied!
- */
- if (end >= start) numcols = end - start; else numcols = start - end;
- if ((start > end) || (start > cols))
+ /* Number of extracted columns shall be kept as (end-start + 1). Otherwise
+ * buffer-overflow might occur. 'start' and 'col' count from 0 to (cols-1)
+ * but 'end' is to be set one after the index of the last column to be
+ * copied!
+ */
+ if (end >= start)
+ numcols = end - start;
+ else
+ numcols = start - end;
+ if ((start > end) || (start > cols))
+ {
+ TIFFError("extractContigSamplesShifted8bits",
+ "Invalid start column value %" PRIu32 " ignored", start);
+ start = 0;
+ }
+ if ((end == 0) || (end > cols))
{
- TIFFError ("extractContigSamplesShifted8bits",
- "Invalid start column value %"PRIu32" ignored", start);
- start = 0;
+ TIFFError("extractContigSamplesShifted8bits",
+ "Invalid end column value %" PRIu32 " ignored", end);
+ end = cols;
}
- if ((end == 0) || (end > cols))
+ if ((end - start) > numcols)
{
- TIFFError ("extractContigSamplesShifted8bits",
- "Invalid end column value %"PRIu32" ignored", end);
- end = cols;
+ end = start + numcols;
}
- if ((end - start) > numcols) {
- end = start + numcols;
- }
- ready_bits = shift;
- maskbits = (uint8_t)-1 >> (8 - bps);
- buff1 = buff2 = 0;
- for (col = start; col < end; col++)
- { /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps * spp;
- for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
- {
- if (sindex == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ ready_bits = shift;
+ maskbits = (uint8_t)-1 >> (8 - bps);
+ buff1 = buff2 = 0;
+ for (col = start; col < end; col++)
+ { /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps * spp;
+ for (sindex = sample; (sindex < spp) && (sindex < (sample + count));
+ sindex++)
{
- src_byte = (bit_offset + (sindex * bps)) / 8;
- src_bit = (bit_offset + (sindex * bps)) % 8;
- }
+ if (sindex == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sindex * bps)) / 8;
+ src_bit = (bit_offset + (sindex * bps)) % 8;
+ }
- src = in + src_byte;
- matchbits = maskbits << (8 - src_bit - bps);
- buff1 = ((*src) & matchbits) << (src_bit);
- if ((col == start) && (sindex == sample))
- buff2 = *src & ((uint8_t)-1) << (shift);
+ src = in + src_byte;
+ matchbits = maskbits << (8 - src_bit - bps);
+ buff1 = ((*src) & matchbits) << (src_bit);
+ if ((col == start) && (sindex == sample))
+ buff2 = *src & ((uint8_t)-1) << (shift);
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 8)
- {
- *dst++ |= buff2;
- buff2 = buff1;
- ready_bits -= 8;
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 8)
+ {
+ *dst++ |= buff2;
+ buff2 = buff1;
+ ready_bits -= 8;
+ }
+ else
+ buff2 = buff2 | (buff1 >> ready_bits);
+ ready_bits += bps;
}
- else
- buff2 = buff2 | (buff1 >> ready_bits);
- ready_bits += bps;
- }
}
- while (ready_bits > 0)
+ while (ready_bits > 0)
{
- buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
- *dst++ = buff1;
- ready_bits -= 8;
+ buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
+ *dst++ = buff1;
+ ready_bits -= 8;
}
- return (0);
- } /* end extractContigSamplesShifted8bits */
+ return (0);
+} /* end extractContigSamplesShifted8bits */
+
+static int extractContigSamplesShifted16bits(uint8_t *in, uint8_t *out,
+ uint32_t cols, tsample_t sample,
+ uint16_t spp, uint16_t bps,
+ tsample_t count, uint32_t start,
+ uint32_t end, int shift)
+{
+ int ready_bits = 0, sindex = 0;
+ uint32_t col, src_byte, src_bit, bit_offset, numcols;
+ uint16_t maskbits = 0, matchbits = 0;
+ uint16_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff = 0;
+ uint8_t *src = in;
+ uint8_t *dst = out;
-static int
-extractContigSamplesShifted16bits (uint8_t *in, uint8_t *out, uint32_t cols,
- tsample_t sample, uint16_t spp, uint16_t bps,
- tsample_t count, uint32_t start, uint32_t end,
- int shift)
- {
- int ready_bits = 0, sindex = 0;
- uint32_t col, src_byte, src_bit, bit_offset, numcols;
- uint16_t maskbits = 0, matchbits = 0;
- uint16_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff = 0;
- uint8_t *src = in;
- uint8_t *dst = out;
-
- if ((src == NULL) || (dst == NULL))
+ if ((src == NULL) || (dst == NULL))
{
- TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer");
- return (1);
+ TIFFError("extractContigSamplesShifted16bits",
+ "Invalid input or output buffer");
+ return (1);
}
- /* Number of extracted columns shall be kept as (end-start + 1). Otherwise buffer-overflow might occur.
- * 'start' and 'col' count from 0 to (cols-1) but 'end' is to be set one after the index of the last column to be copied!
- */
- if (end >= start) numcols = end - start; else numcols = start - end;
- if ((start > end) || (start > cols))
+ /* Number of extracted columns shall be kept as (end-start + 1). Otherwise
+ * buffer-overflow might occur. 'start' and 'col' count from 0 to (cols-1)
+ * but 'end' is to be set one after the index of the last column to be
+ * copied!
+ */
+ if (end >= start)
+ numcols = end - start;
+ else
+ numcols = start - end;
+ if ((start > end) || (start > cols))
{
- TIFFError ("extractContigSamplesShifted16bits",
- "Invalid start column value %"PRIu32" ignored", start);
- start = 0;
+ TIFFError("extractContigSamplesShifted16bits",
+ "Invalid start column value %" PRIu32 " ignored", start);
+ start = 0;
}
- if ((end == 0) || (end > cols))
+ if ((end == 0) || (end > cols))
{
- TIFFError ("extractContigSamplesShifted16bits",
- "Invalid end column value %"PRIu32" ignored", end);
- end = cols;
+ TIFFError("extractContigSamplesShifted16bits",
+ "Invalid end column value %" PRIu32 " ignored", end);
+ end = cols;
+ }
+ if ((end - start) > numcols)
+ {
+ end = start + numcols;
}
- if ((end - start) > numcols) {
- end = start + numcols;
- }
- ready_bits = shift;
- maskbits = (uint16_t)-1 >> (16 - bps);
- for (col = start; col < end; col++)
- { /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps * spp;
- for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
- {
- if (sindex == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ ready_bits = shift;
+ maskbits = (uint16_t)-1 >> (16 - bps);
+ for (col = start; col < end; col++)
+ { /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps * spp;
+ for (sindex = sample; (sindex < spp) && (sindex < (sample + count));
+ sindex++)
{
- src_byte = (bit_offset + (sindex * bps)) / 8;
- src_bit = (bit_offset + (sindex * bps)) % 8;
- }
+ if (sindex == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sindex * bps)) / 8;
+ src_bit = (bit_offset + (sindex * bps)) % 8;
+ }
- src = in + src_byte;
- matchbits = maskbits << (16 - src_bit - bps);
- if (little_endian)
- buff1 = (src[0] << 8) | src[1];
- else
- buff1 = (src[1] << 8) | src[0];
+ src = in + src_byte;
+ matchbits = maskbits << (16 - src_bit - bps);
+ if (little_endian)
+ buff1 = (src[0] << 8) | src[1];
+ else
+ buff1 = (src[1] << 8) | src[0];
- if ((col == start) && (sindex == sample))
- buff2 = buff1 & ((uint16_t)-1) << (8 - shift);
+ if ((col == start) && (sindex == sample))
+ buff2 = buff1 & ((uint16_t)-1) << (8 - shift);
- buff1 = (buff1 & matchbits) << (src_bit);
+ buff1 = (buff1 & matchbits) << (src_bit);
- if (ready_bits < 8) /* add another bps bits to the buffer */
- buff2 = buff2 | (buff1 >> ready_bits);
- else /* If we have a full buffer's worth, write it out */
- {
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
- ready_bits -= 8;
- /* shift in new bits */
- buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
- }
+ if (ready_bits < 8) /* add another bps bits to the buffer */
+ buff2 = buff2 | (buff1 >> ready_bits);
+ else /* If we have a full buffer's worth, write it out */
+ {
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
+ ready_bits -= 8;
+ /* shift in new bits */
+ buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
+ }
- ready_bits += bps;
- }
+ ready_bits += bps;
+ }
}
- /* catch any trailing bits at the end of the line */
- while (ready_bits > 0)
+ /* catch any trailing bits at the end of the line */
+ while (ready_bits > 0)
{
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
- ready_bits -= 8;
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
+ ready_bits -= 8;
}
-
- return (0);
- } /* end extractContigSamplesShifted16bits */
+ return (0);
+} /* end extractContigSamplesShifted16bits */
-static int
-extractContigSamplesShifted24bits (uint8_t *in, uint8_t *out, uint32_t cols,
- tsample_t sample, uint16_t spp, uint16_t bps,
- tsample_t count, uint32_t start, uint32_t end,
- int shift)
- {
- int ready_bits = 0, sindex = 0;
- uint32_t col, src_byte, src_bit, bit_offset, numcols;
- uint32_t maskbits = 0, matchbits = 0;
- uint32_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0;
- uint8_t *src = in;
- uint8_t *dst = out;
+static int extractContigSamplesShifted24bits(uint8_t *in, uint8_t *out,
+ uint32_t cols, tsample_t sample,
+ uint16_t spp, uint16_t bps,
+ tsample_t count, uint32_t start,
+ uint32_t end, int shift)
+{
+ int ready_bits = 0, sindex = 0;
+ uint32_t col, src_byte, src_bit, bit_offset, numcols;
+ uint32_t maskbits = 0, matchbits = 0;
+ uint32_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0;
+ uint8_t *src = in;
+ uint8_t *dst = out;
- if ((in == NULL) || (out == NULL))
+ if ((in == NULL) || (out == NULL))
{
- TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer");
- return (1);
+ TIFFError("extractContigSamplesShifted24bits",
+ "Invalid input or output buffer");
+ return (1);
}
- /* Number of extracted columns shall be kept as (end-start + 1). Otherwise buffer-overflow might occur.
- * 'start' and 'col' count from 0 to (cols-1) but 'end' is to be set one after the index of the last column to be copied!
- */
- /*--- Remark, which is true for all those functions extractCongigSamplesXXX() --
- * The mitigation of the start/end test does not allways make sense, because the function is often called with e.g.:
- * start = 31; end = 32; cols = 32 to extract the last column in a 32x32 sample image.
- * If then, a worng parameter (e.g. cols = 10) is provided, the mitigated settings would be start=0; end=1.
- * Therefore, an error message and no copy action might be the better reaction to wrong parameter configurations.
- */
- if (end >= start) numcols = end - start; else numcols = start - end;
- if ((start > end) || (start > cols))
+ /* Number of extracted columns shall be kept as (end-start + 1). Otherwise
+ * buffer-overflow might occur. 'start' and 'col' count from 0 to (cols-1)
+ * but 'end' is to be set one after the index of the last column to be
+ * copied!
+ */
+ /*--- Remark, which is true for all those functions
+ * extractCongigSamplesXXX() -- The mitigation of the start/end test does
+ * not allways make sense, because the function is often called with e.g.:
+ * start = 31; end = 32; cols = 32 to extract the last column in a 32x32
+ * sample image. If then, a worng parameter (e.g. cols = 10) is provided,
+ * the mitigated settings would be start=0; end=1. Therefore, an error
+ * message and no copy action might be the better reaction to wrong
+ * parameter configurations.
+ */
+ if (end >= start)
+ numcols = end - start;
+ else
+ numcols = start - end;
+ if ((start > end) || (start > cols))
{
- TIFFError ("extractContigSamplesShifted24bits",
- "Invalid start column value %"PRIu32" ignored", start);
- start = 0;
+ TIFFError("extractContigSamplesShifted24bits",
+ "Invalid start column value %" PRIu32 " ignored", start);
+ start = 0;
}
- if ((end == 0) || (end > cols))
+ if ((end == 0) || (end > cols))
{
- TIFFError ("extractContigSamplesShifted24bits",
- "Invalid end column value %"PRIu32" ignored", end);
- end = cols;
+ TIFFError("extractContigSamplesShifted24bits",
+ "Invalid end column value %" PRIu32 " ignored", end);
+ end = cols;
+ }
+ if ((end - start) > numcols)
+ {
+ end = start + numcols;
}
- if ((end - start) > numcols) {
- end = start + numcols;
- }
- ready_bits = shift;
- maskbits = (uint32_t)-1 >> (32 - bps);
- for (col = start; col < end; col++)
+ ready_bits = shift;
+ maskbits = (uint32_t)-1 >> (32 - bps);
+ for (col = start; col < end; col++)
{
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps * spp;
- for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
- {
- if (sindex == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps * spp;
+ for (sindex = sample; (sindex < spp) && (sindex < (sample + count));
+ sindex++)
{
- src_byte = (bit_offset + (sindex * bps)) / 8;
- src_bit = (bit_offset + (sindex * bps)) % 8;
- }
+ if (sindex == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sindex * bps)) / 8;
+ src_bit = (bit_offset + (sindex * bps)) % 8;
+ }
- src = in + src_byte;
- matchbits = maskbits << (32 - src_bit - bps);
- if (little_endian)
- buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
- else
- buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
+ src = in + src_byte;
+ matchbits = maskbits << (32 - src_bit - bps);
+ if (little_endian)
+ buff1 =
+ (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
+ else
+ buff1 =
+ (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
- if ((col == start) && (sindex == sample))
- buff2 = buff1 & ((uint32_t)-1) << (16 - shift);
+ if ((col == start) && (sindex == sample))
+ buff2 = buff1 & ((uint32_t)-1) << (16 - shift);
- buff1 = (buff1 & matchbits) << (src_bit);
+ buff1 = (buff1 & matchbits) << (src_bit);
- if (ready_bits < 16) /* add another bps bits to the buffer */
- {
- bytebuff1 = bytebuff2 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
+ if (ready_bits < 16) /* add another bps bits to the buffer */
+ {
+ bytebuff1 = bytebuff2 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ else /* If we have a full buffer's worth, write it out */
+ {
+ bytebuff1 = (buff2 >> 24);
+ *dst++ = bytebuff1;
+ bytebuff2 = (buff2 >> 16);
+ *dst++ = bytebuff2;
+ ready_bits -= 16;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- else /* If we have a full buffer's worth, write it out */
- {
+ }
+
+ /* catch any trailing bits at the end of the line */
+ while (ready_bits > 0)
+ {
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
- bytebuff2 = (buff2 >> 16);
- *dst++ = bytebuff2;
- ready_bits -= 16;
-
- /* shift in new bits */
- buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
- }
- ready_bits += bps;
- }
- }
-
- /* catch any trailing bits at the end of the line */
- while (ready_bits > 0)
- {
- bytebuff1 = (buff2 >> 24);
- *dst++ = bytebuff1;
-
- buff2 = (buff2 << 8);
- bytebuff2 = bytebuff1;
- ready_bits -= 8;
- }
-
- return (0);
- } /* end extractContigSamplesShifted24bits */
-
-static int
-extractContigSamplesShifted32bits (uint8_t *in, uint8_t *out, uint32_t cols,
- tsample_t sample, uint16_t spp, uint16_t bps,
- tsample_t count, uint32_t start, uint32_t end,
- int shift)
- {
- int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
- uint32_t col, src_byte, src_bit, bit_offset, numcols;
- uint32_t longbuff1 = 0, longbuff2 = 0;
- uint64_t maskbits = 0, matchbits = 0;
- uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
- uint8_t *src = in;
- uint8_t *dst = out;
-
- if ((in == NULL) || (out == NULL))
- {
- TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer");
- return (1);
+
+ buff2 = (buff2 << 8);
+ bytebuff2 = bytebuff1;
+ ready_bits -= 8;
}
+ return (0);
+} /* end extractContigSamplesShifted24bits */
- /* Number of extracted columns shall be kept as (end-start + 1). Otherwise buffer-overflow might occur.
- * 'start' and 'col' count from 0 to (cols-1) but 'end' is to be set one after the index of the last column to be copied!
- */
- if (end >= start) numcols = end - start; else numcols = start - end;
- if ((start > end) || (start > cols))
+static int extractContigSamplesShifted32bits(uint8_t *in, uint8_t *out,
+ uint32_t cols, tsample_t sample,
+ uint16_t spp, uint16_t bps,
+ tsample_t count, uint32_t start,
+ uint32_t end, int shift)
+{
+ int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
+ uint32_t col, src_byte, src_bit, bit_offset, numcols;
+ uint32_t longbuff1 = 0, longbuff2 = 0;
+ uint64_t maskbits = 0, matchbits = 0;
+ uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
+ uint8_t *src = in;
+ uint8_t *dst = out;
+
+ if ((in == NULL) || (out == NULL))
+ {
+ TIFFError("extractContigSamplesShifted32bits",
+ "Invalid input or output buffer");
+ return (1);
+ }
+
+ /* Number of extracted columns shall be kept as (end-start + 1). Otherwise
+ * buffer-overflow might occur. 'start' and 'col' count from 0 to (cols-1)
+ * but 'end' is to be set one after the index of the last column to be
+ * copied!
+ */
+ if (end >= start)
+ numcols = end - start;
+ else
+ numcols = start - end;
+ if ((start > end) || (start > cols))
{
- TIFFError ("extractContigSamplesShifted32bits",
- "Invalid start column value %"PRIu32" ignored", start);
- start = 0;
+ TIFFError("extractContigSamplesShifted32bits",
+ "Invalid start column value %" PRIu32 " ignored", start);
+ start = 0;
}
- if ((end == 0) || (end > cols))
+ if ((end == 0) || (end > cols))
{
- TIFFError ("extractContigSamplesShifted32bits",
- "Invalid end column value %"PRIu32" ignored", end);
- end = cols;
+ TIFFError("extractContigSamplesShifted32bits",
+ "Invalid end column value %" PRIu32 " ignored", end);
+ end = cols;
+ }
+ if ((end - start) > numcols)
+ {
+ end = start + numcols;
}
- if ((end - start) > numcols) {
- end = start + numcols;
- }
- /* shift_width = ((bps + 7) / 8) + 1; */
- ready_bits = shift;
- maskbits = (uint64_t)-1 >> (64 - bps);
- for (col = start; col < end; col++)
+ /* shift_width = ((bps + 7) / 8) + 1; */
+ ready_bits = shift;
+ maskbits = (uint64_t)-1 >> (64 - bps);
+ for (col = start; col < end; col++)
{
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps * spp;
- for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
- {
- if (sindex == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps * spp;
+ for (sindex = sample; (sindex < spp) && (sindex < (sample + count));
+ sindex++)
{
- src_byte = (bit_offset + (sindex * bps)) / 8;
- src_bit = (bit_offset + (sindex * bps)) % 8;
- }
+ if (sindex == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sindex * bps)) / 8;
+ src_bit = (bit_offset + (sindex * bps)) % 8;
+ }
- src = in + src_byte;
- matchbits = maskbits << (64 - src_bit - bps);
- if (little_endian)
- {
- longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
- longbuff2 = longbuff1;
- }
- else
- {
- longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
- longbuff2 = longbuff1;
- }
+ src = in + src_byte;
+ matchbits = maskbits << (64 - src_bit - bps);
+ if (little_endian)
+ {
+ longbuff1 =
+ (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
+ longbuff2 = longbuff1;
+ }
+ else
+ {
+ longbuff1 =
+ (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
+ longbuff2 = longbuff1;
+ }
- buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
- if ((col == start) && (sindex == sample))
- buff2 = buff3 & ((uint64_t)-1) << (32 - shift);
+ buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
+ if ((col == start) && (sindex == sample))
+ buff2 = buff3 & ((uint64_t)-1) << (32 - shift);
- buff1 = (buff3 & matchbits) << (src_bit);
+ buff1 = (buff3 & matchbits) << (src_bit);
- if (ready_bits < 32)
- { /* add another bps bits to the buffer */
- bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
+ if (ready_bits < 32)
+ { /* add another bps bits to the buffer */
+ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ else /* If we have a full buffer's worth, write it out */
+ {
+ bytebuff1 = (uint8_t)(buff2 >> 56);
+ *dst++ = bytebuff1;
+ bytebuff2 = (uint8_t)(buff2 >> 48);
+ *dst++ = bytebuff2;
+ bytebuff3 = (uint8_t)(buff2 >> 40);
+ *dst++ = bytebuff3;
+ bytebuff4 = (uint8_t)(buff2 >> 32);
+ *dst++ = bytebuff4;
+ ready_bits -= 32;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- else /* If we have a full buffer's worth, write it out */
- {
- bytebuff1 = (uint8_t)(buff2 >> 56);
- *dst++ = bytebuff1;
- bytebuff2 = (uint8_t)(buff2 >> 48);
- *dst++ = bytebuff2;
- bytebuff3 = (uint8_t)(buff2 >> 40);
- *dst++ = bytebuff3;
- bytebuff4 = (uint8_t)(buff2 >> 32);
- *dst++ = bytebuff4;
- ready_bits -= 32;
-
- /* shift in new bits */
- buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
- }
- ready_bits += bps;
- }
- }
- while (ready_bits > 0)
- {
- bytebuff1 = (buff2 >> 56);
- *dst++ = bytebuff1;
- buff2 = (buff2 << 8);
- ready_bits -= 8;
- }
-
- return (0);
- } /* end extractContigSamplesShifted32bits */
-
-static int
-extractContigSamplesToBuffer(uint8_t *out, uint8_t *in, uint32_t rows, uint32_t cols,
- tsample_t sample, uint16_t spp, uint16_t bps,
- struct dump_opts *dump)
- {
- int shift_width, bytes_per_sample, bytes_per_pixel;
- uint32_t src_rowsize, src_offset, row, first_col = 0;
- uint32_t dst_rowsize, dst_offset;
- tsample_t count = 1;
- uint8_t *src, *dst;
-
- bytes_per_sample = (bps + 7) / 8;
- bytes_per_pixel = ((bps * spp) + 7) / 8;
- if ((bps % 8) == 0)
- shift_width = 0;
- else
+ }
+ while (ready_bits > 0)
{
- if (bytes_per_pixel < (bytes_per_sample + 1))
- shift_width = bytes_per_pixel;
+ bytebuff1 = (buff2 >> 56);
+ *dst++ = bytebuff1;
+ buff2 = (buff2 << 8);
+ ready_bits -= 8;
+ }
+
+ return (0);
+} /* end extractContigSamplesShifted32bits */
+
+static int extractContigSamplesToBuffer(uint8_t *out, uint8_t *in,
+ uint32_t rows, uint32_t cols,
+ tsample_t sample, uint16_t spp,
+ uint16_t bps, struct dump_opts *dump)
+{
+ int shift_width, bytes_per_sample, bytes_per_pixel;
+ uint32_t src_rowsize, src_offset, row, first_col = 0;
+ uint32_t dst_rowsize, dst_offset;
+ tsample_t count = 1;
+ uint8_t *src, *dst;
+
+ bytes_per_sample = (bps + 7) / 8;
+ bytes_per_pixel = ((bps * spp) + 7) / 8;
+ if ((bps % 8) == 0)
+ shift_width = 0;
else
- shift_width = bytes_per_sample + 1;
+ {
+ if (bytes_per_pixel < (bytes_per_sample + 1))
+ shift_width = bytes_per_pixel;
+ else
+ shift_width = bytes_per_sample + 1;
}
- src_rowsize = ((bps * spp * cols) + 7) / 8;
- dst_rowsize = ((bps * cols) + 7) / 8;
+ src_rowsize = ((bps * spp * cols) + 7) / 8;
+ dst_rowsize = ((bps * cols) + 7) / 8;
- if ((dump->outfile != NULL) && (dump->level == 4))
+ if ((dump->outfile != NULL) && (dump->level == 4))
{
- dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer",
- "Sample %"PRIu32", %"PRIu32" rows", sample + 1u, rows + 1u);
+ dump_info(dump->outfile, dump->format, "extractContigSamplesToBuffer",
+ "Sample %" PRIu32 ", %" PRIu32 " rows", sample + 1u,
+ rows + 1u);
}
- for (row = 0; row < rows; row++)
+ for (row = 0; row < rows; row++)
{
- src_offset = row * src_rowsize;
- dst_offset = row * dst_rowsize;
- src = in + src_offset;
- dst = out + dst_offset;
+ src_offset = row * src_rowsize;
+ dst_offset = row * dst_rowsize;
+ src = in + src_offset;
+ dst = out + dst_offset;
- /* pack the data into the scanline */
- switch (shift_width)
- {
- case 0: if (extractContigSamplesBytes (src, dst, cols, sample,
- spp, bps, count, first_col, cols))
+ /* pack the data into the scanline */
+ switch (shift_width)
+ {
+ case 0:
+ if (extractContigSamplesBytes(src, dst, cols, sample, spp, bps,
+ count, first_col, cols))
+ return (1);
+ break;
+ case 1:
+ if (bps == 1)
+ {
+ if (extractContigSamples8bits(src, dst, cols, sample, spp,
+ bps, count, first_col, cols))
+ return (1);
+ break;
+ }
+ else if (extractContigSamples16bits(src, dst, cols, sample, spp,
+ bps, count, first_col,
+ cols))
+ return (1);
+ break;
+ case 2:
+ if (extractContigSamples24bits(src, dst, cols, sample, spp, bps,
+ count, first_col, cols))
+ return (1);
+ break;
+ case 3:
+ case 4:
+ case 5:
+ if (extractContigSamples32bits(src, dst, cols, sample, spp, bps,
+ count, first_col, cols))
+ return (1);
+ break;
+ default:
+ TIFFError("extractContigSamplesToBuffer",
+ "Unsupported bit depth: %" PRIu16, bps);
return (1);
- break;
- case 1: if (bps == 1)
- {
- if (extractContigSamples8bits (src, dst, cols, sample,
- spp, bps, count, first_col, cols))
- return (1);
- break;
- }
- else
- if (extractContigSamples16bits (src, dst, cols, sample,
- spp, bps, count, first_col, cols))
- return (1);
- break;
- case 2: if (extractContigSamples24bits (src, dst, cols, sample,
- spp, bps, count, first_col, cols))
- return (1);
- break;
- case 3:
- case 4:
- case 5: if (extractContigSamples32bits (src, dst, cols, sample,
- spp, bps, count, first_col, cols))
- return (1);
- break;
- default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %"PRIu16, bps);
- return (1);
- }
- if ((dump->outfile != NULL) && (dump->level == 4))
- dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
+ }
+ if ((dump->outfile != NULL) && (dump->level == 4))
+ dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
}
- return (0);
- } /* end extractContigSamplesToBuffer */
+ return (0);
+} /* end extractContigSamplesToBuffer */
-static int
-extractContigSamplesToTileBuffer(uint8_t *out, uint8_t *in, uint32_t rows, uint32_t cols,
- uint32_t imagewidth, uint32_t tilewidth, tsample_t sample,
- uint16_t count, uint16_t spp, uint16_t bps, struct dump_opts *dump)
- {
- int shift_width, bytes_per_sample, bytes_per_pixel;
- uint32_t src_rowsize, src_offset, row;
- uint32_t dst_rowsize, dst_offset;
- uint8_t *src, *dst;
+static int extractContigSamplesToTileBuffer(
+ uint8_t *out, uint8_t *in, uint32_t rows, uint32_t cols,
+ uint32_t imagewidth, uint32_t tilewidth, tsample_t sample, uint16_t count,
+ uint16_t spp, uint16_t bps, struct dump_opts *dump)
+{
+ int shift_width, bytes_per_sample, bytes_per_pixel;
+ uint32_t src_rowsize, src_offset, row;
+ uint32_t dst_rowsize, dst_offset;
+ uint8_t *src, *dst;
- bytes_per_sample = (bps + 7) / 8;
- bytes_per_pixel = ((bps * spp) + 7) / 8;
- if ((bps % 8) == 0)
- shift_width = 0;
- else
- {
- if (bytes_per_pixel < (bytes_per_sample + 1))
- shift_width = bytes_per_pixel;
+ bytes_per_sample = (bps + 7) / 8;
+ bytes_per_pixel = ((bps * spp) + 7) / 8;
+ if ((bps % 8) == 0)
+ shift_width = 0;
else
- shift_width = bytes_per_sample + 1;
+ {
+ if (bytes_per_pixel < (bytes_per_sample + 1))
+ shift_width = bytes_per_pixel;
+ else
+ shift_width = bytes_per_sample + 1;
}
- if ((dump->outfile != NULL) && (dump->level == 4))
+ if ((dump->outfile != NULL) && (dump->level == 4))
{
- dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer",
- "Sample %"PRIu32", %"PRIu32" rows", sample + 1u, rows + 1u);
+ dump_info(
+ dump->outfile, dump->format, "extractContigSamplesToTileBuffer",
+ "Sample %" PRIu32 ", %" PRIu32 " rows", sample + 1u, rows + 1u);
}
- src_rowsize = ((bps * spp * imagewidth) + 7) / 8;
- dst_rowsize = ((bps * tilewidth * count) + 7) / 8;
+ src_rowsize = ((bps * spp * imagewidth) + 7) / 8;
+ dst_rowsize = ((bps * tilewidth * count) + 7) / 8;
- for (row = 0; row < rows; row++)
+ for (row = 0; row < rows; row++)
{
- src_offset = row * src_rowsize;
- dst_offset = row * dst_rowsize;
- src = in + src_offset;
- dst = out + dst_offset;
+ src_offset = row * src_rowsize;
+ dst_offset = row * dst_rowsize;
+ src = in + src_offset;
+ dst = out + dst_offset;
- /* pack the data into the scanline */
- switch (shift_width)
- {
- case 0: if (extractContigSamplesBytes (src, dst, cols, sample,
- spp, bps, count, 0, cols))
+ /* pack the data into the scanline */
+ switch (shift_width)
+ {
+ case 0:
+ if (extractContigSamplesBytes(src, dst, cols, sample, spp, bps,
+ count, 0, cols))
+ return (1);
+ break;
+ case 1:
+ if (bps == 1)
+ {
+ if (extractContigSamples8bits(src, dst, cols, sample, spp,
+ bps, count, 0, cols))
+ return (1);
+ break;
+ }
+ else if (extractContigSamples16bits(src, dst, cols, sample, spp,
+ bps, count, 0, cols))
+ return (1);
+ break;
+ case 2:
+ if (extractContigSamples24bits(src, dst, cols, sample, spp, bps,
+ count, 0, cols))
+ return (1);
+ break;
+ case 3:
+ case 4:
+ case 5:
+ if (extractContigSamples32bits(src, dst, cols, sample, spp, bps,
+ count, 0, cols))
+ return (1);
+ break;
+ default:
+ TIFFError("extractContigSamplesToTileBuffer",
+ "Unsupported bit depth: %" PRIu16, bps);
return (1);
- break;
- case 1: if (bps == 1)
- {
- if (extractContigSamples8bits (src, dst, cols, sample,
- spp, bps, count, 0, cols))
- return (1);
- break;
- }
- else
- if (extractContigSamples16bits (src, dst, cols, sample,
- spp, bps, count, 0, cols))
- return (1);
- break;
- case 2: if (extractContigSamples24bits (src, dst, cols, sample,
- spp, bps, count, 0, cols))
- return (1);
- break;
- case 3:
- case 4:
- case 5: if (extractContigSamples32bits (src, dst, cols, sample,
- spp, bps, count, 0, cols))
- return (1);
- break;
- default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %"PRIu16, bps);
- return (1);
- }
- if ((dump->outfile != NULL) && (dump->level == 4))
- dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
+ }
+ if ((dump->outfile != NULL) && (dump->level == 4))
+ dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
}
- return (0);
- } /* end extractContigSamplesToTileBuffer */
+ return (0);
+} /* end extractContigSamplesToTileBuffer */
-static int readContigStripsIntoBuffer (TIFF* in, uint8_t* buf)
+static int readContigStripsIntoBuffer(TIFF *in, uint8_t *buf)
{
- uint8_t* bufp = buf;
- tmsize_t bytes_read = 0;
- uint32_t strip, nstrips = TIFFNumberOfStrips(in);
- tmsize_t stripsize = TIFFStripSize(in);
- tmsize_t rows = 0;
- uint32_t rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
- tsize_t scanline_size = TIFFScanlineSize(in);
+ uint8_t *bufp = buf;
+ tmsize_t bytes_read = 0;
+ uint32_t strip, nstrips = TIFFNumberOfStrips(in);
+ tmsize_t stripsize = TIFFStripSize(in);
+ tmsize_t rows = 0;
+ uint32_t rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
+ tsize_t scanline_size = TIFFScanlineSize(in);
+
+ if (scanline_size == 0)
+ {
+ TIFFError("", "TIFF scanline size is zero!");
+ return 0;
+ }
+
+ for (strip = 0; strip < nstrips; strip++)
+ {
+ bytes_read = TIFFReadEncodedStrip(in, strip, bufp, -1);
+ rows = bytes_read / scanline_size;
+ if ((strip < (nstrips - 1)) && (bytes_read != (int32_t)stripsize))
+ TIFFError("",
+ "Strip %" PRIu32 ": read %" PRId64
+ " bytes, strip size %" PRIu64,
+ strip + 1, (uint64_t)bytes_read, (uint64_t)stripsize);
- if (scanline_size == 0) {
- TIFFError("", "TIFF scanline size is zero!");
- return 0;
+ if (bytes_read < 0 && !ignore)
+ {
+ TIFFError("",
+ "Error reading strip %" PRIu32 " after %" PRIu64 " rows",
+ strip, (uint64_t)rows);
+ return 0;
}
+ bufp += stripsize;
+ }
+
+ return 1;
+} /* end readContigStripsIntoBuffer */
- for (strip = 0; strip < nstrips; strip++) {
- bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
- rows = bytes_read / scanline_size;
- if ((strip < (nstrips - 1)) && (bytes_read != (int32_t)stripsize))
- TIFFError("", "Strip %"PRIu32": read %"PRId64" bytes, strip size %"PRIu64,
- strip + 1, (uint64_t)bytes_read, (uint64_t)stripsize);
+static int combineSeparateSamplesBytes(unsigned char *srcbuffs[],
+ unsigned char *out, uint32_t cols,
+ uint32_t rows, uint16_t spp,
+ uint16_t bps, FILE *dumpfile, int format,
+ int level)
+{
+ int i, bytes_per_sample;
+ uint32_t row, col, col_offset, src_rowsize, dst_rowsize, row_offset;
+ unsigned char *src;
+ unsigned char *dst;
+ tsample_t s;
+
+ src = srcbuffs[0];
+ dst = out;
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("combineSeparateSamplesBytes", "Invalid buffer address");
+ return (1);
+ }
+
+ bytes_per_sample = (bps + 7) / 8;
+
+ src_rowsize = ((bps * cols) + 7) / 8;
+ dst_rowsize = ((bps * spp * cols) + 7) / 8;
+ for (row = 0; row < rows; row++)
+ {
+ if ((dumpfile != NULL) && (level == 2))
+ {
+ for (s = 0; s < spp; s++)
+ {
+ dump_info(dumpfile, format, "combineSeparateSamplesBytes",
+ "Input data, Sample %" PRIu16, s);
+ dump_buffer(dumpfile, format, 1, cols, row,
+ srcbuffs[s] + (row * src_rowsize));
+ }
+ }
+ dst = out + (row * dst_rowsize);
+ row_offset = row * src_rowsize;
+ for (col = 0; col < cols; col++)
+ {
+ col_offset = row_offset + (col * (bps / 8));
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ src = srcbuffs[s] + col_offset;
+ for (i = 0; i < bytes_per_sample; i++)
+ *(dst + i) = *(src + i);
+ src += bytes_per_sample;
+ dst += bytes_per_sample;
+ }
+ }
+
+ if ((dumpfile != NULL) && (level == 2))
+ {
+ dump_info(dumpfile, format, "combineSeparateSamplesBytes",
+ "Output data, combined samples");
+ dump_buffer(dumpfile, format, 1, dst_rowsize, row,
+ out + (row * dst_rowsize));
+ }
+ }
+
+ return (0);
+} /* end combineSeparateSamplesBytes */
+
+static int combineSeparateSamples8bits(uint8_t *in[], uint8_t *out,
+ uint32_t cols, uint32_t rows,
+ uint16_t spp, uint16_t bps,
+ FILE *dumpfile, int format, int level)
+{
+ int ready_bits = 0;
+ /* int bytes_per_sample = 0; */
+ uint32_t src_rowsize, dst_rowsize, src_offset;
+ uint32_t bit_offset;
+ uint32_t row, col, src_byte = 0, src_bit = 0;
+ uint8_t maskbits = 0, matchbits = 0;
+ uint8_t buff1 = 0, buff2 = 0;
+ tsample_t s;
+ unsigned char *src = in[0];
+ unsigned char *dst = out;
+ char action[32];
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("combineSeparateSamples8bits",
+ "Invalid input or output buffer");
+ return (1);
+ }
+
+ /* bytes_per_sample = (bps + 7) / 8; */
+ src_rowsize = ((bps * cols) + 7) / 8;
+ dst_rowsize = ((bps * cols * spp) + 7) / 8;
+ maskbits = (uint8_t)-1 >> (8 - bps);
+
+ for (row = 0; row < rows; row++)
+ {
+ ready_bits = 0;
+ buff1 = buff2 = 0;
+ dst = out + (row * dst_rowsize);
+ src_offset = row * src_rowsize;
+ for (col = 0; col < cols; col++)
+ {
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps;
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+
+ matchbits = maskbits << (8 - src_bit - bps);
+ /* load up next sample from each plane */
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ src = in[s] + src_offset + src_byte;
+ buff1 = ((*src) & matchbits) << (src_bit);
+
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 8)
+ {
+ *dst++ = buff2;
+ buff2 = buff1;
+ ready_bits -= 8;
+ strcpy(action, "Flush");
+ }
+ else
+ {
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ strcpy(action, "Update");
+ }
+ ready_bits += bps;
- if (bytes_read < 0 && !ignore) {
- TIFFError("", "Error reading strip %"PRIu32" after %"PRIu64" rows",
- strip, (uint64_t)rows);
- return 0;
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3" PRIu32 ", Col %3" PRIu32
+ ", Samples %" PRIu16 ", Src byte offset %3" PRIu32
+ " bit offset %2" PRIu32 " Dst offset %3td",
+ row + 1u, col + 1u, s, src_byte, src_bit,
+ dst - out);
+ dump_byte(dumpfile, format, "Match bits", matchbits);
+ dump_byte(dumpfile, format, "Src bits", *src);
+ dump_byte(dumpfile, format, "Buff1 bits", buff1);
+ dump_byte(dumpfile, format, "Buff2 bits", buff2);
+ dump_info(dumpfile, format, "", "%s", action);
}
- bufp += stripsize;
+ }
}
- return 1;
-} /* end readContigStripsIntoBuffer */
+ if (ready_bits > 0)
+ {
+ buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
+ *dst++ = buff1;
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3" PRIu32 ", Col %3" PRIu32
+ ", Src byte offset %3" PRIu32 " bit offset %2" PRIu32
+ " Dst offset %3td",
+ row + 1u, col + 1u, src_byte, src_bit, dst - out);
+ dump_byte(dumpfile, format, "Final bits", buff1);
+ }
+ }
-static int
-combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out,
- uint32_t cols, uint32_t rows, uint16_t spp, uint16_t bps,
- FILE *dumpfile, int format, int level)
- {
- int i, bytes_per_sample;
- uint32_t row, col, col_offset, src_rowsize, dst_rowsize, row_offset;
- unsigned char *src;
- unsigned char *dst;
- tsample_t s;
-
- src = srcbuffs[0];
- dst = out;
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("combineSeparateSamplesBytes","Invalid buffer address");
- return (1);
+ if ((dumpfile != NULL) && (level >= 2))
+ {
+ dump_info(dumpfile, format, "combineSeparateSamples8bits",
+ "Output data");
+ dump_buffer(dumpfile, format, 1, dst_rowsize, row,
+ out + (row * dst_rowsize));
+ }
}
- bytes_per_sample = (bps + 7) / 8;
-
- src_rowsize = ((bps * cols) + 7) / 8;
- dst_rowsize = ((bps * spp * cols) + 7) / 8;
- for (row = 0; row < rows; row++)
- {
- if ((dumpfile != NULL) && (level == 2))
- {
- for (s = 0; s < spp; s++)
- {
- dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %"PRIu16, s);
- dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize));
- }
- }
- dst = out + (row * dst_rowsize);
- row_offset = row * src_rowsize;
- for (col = 0; col < cols; col++)
- {
- col_offset = row_offset + (col * (bps / 8));
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- src = srcbuffs[s] + col_offset;
- for (i = 0; i < bytes_per_sample; i++)
- *(dst + i) = *(src + i);
- src += bytes_per_sample;
- dst += bytes_per_sample;
- }
- }
-
- if ((dumpfile != NULL) && (level == 2))
- {
- dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples");
- dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
- }
- }
-
- return (0);
- } /* end combineSeparateSamplesBytes */
-
-static int
-combineSeparateSamples8bits (uint8_t *in[], uint8_t *out, uint32_t cols,
- uint32_t rows, uint16_t spp, uint16_t bps,
- FILE *dumpfile, int format, int level)
- {
- int ready_bits = 0;
- /* int bytes_per_sample = 0; */
- uint32_t src_rowsize, dst_rowsize, src_offset;
- uint32_t bit_offset;
- uint32_t row, col, src_byte = 0, src_bit = 0;
- uint8_t maskbits = 0, matchbits = 0;
- uint8_t buff1 = 0, buff2 = 0;
- tsample_t s;
- unsigned char *src = in[0];
- unsigned char *dst = out;
- char action[32];
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("combineSeparateSamples8bits","Invalid input or output buffer");
- return (1);
+ return (0);
+} /* end combineSeparateSamples8bits */
+
+static int combineSeparateSamples16bits(uint8_t *in[], uint8_t *out,
+ uint32_t cols, uint32_t rows,
+ uint16_t spp, uint16_t bps,
+ FILE *dumpfile, int format, int level)
+{
+ int ready_bits = 0 /*, bytes_per_sample = 0 */;
+ uint32_t src_rowsize, dst_rowsize;
+ uint32_t bit_offset, src_offset;
+ uint32_t row, col, src_byte = 0, src_bit = 0;
+ uint16_t maskbits = 0, matchbits = 0;
+ uint16_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff = 0;
+ tsample_t s;
+ unsigned char *src = in[0];
+ unsigned char *dst = out;
+ char action[8];
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("combineSeparateSamples16bits",
+ "Invalid input or output buffer");
+ return (1);
+ }
+
+ /* bytes_per_sample = (bps + 7) / 8; */
+ src_rowsize = ((bps * cols) + 7) / 8;
+ dst_rowsize = ((bps * cols * spp) + 7) / 8;
+ maskbits = (uint16_t)-1 >> (16 - bps);
+
+ for (row = 0; row < rows; row++)
+ {
+ ready_bits = 0;
+ buff1 = buff2 = 0;
+ dst = out + (row * dst_rowsize);
+ src_offset = row * src_rowsize;
+ for (col = 0; col < cols; col++)
+ {
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps;
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+
+ matchbits = maskbits << (16 - src_bit - bps);
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ src = in[s] + src_offset + src_byte;
+ if (little_endian)
+ buff1 = (src[0] << 8) | src[1];
+ else
+ buff1 = (src[1] << 8) | src[0];
+
+ buff1 = (buff1 & matchbits) << (src_bit);
+
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 8)
+ {
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
+ ready_bits -= 8;
+ /* shift in new bits */
+ buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
+ strcpy(action, "Flush");
+ }
+ else
+ { /* add another bps bits to the buffer */
+ bytebuff = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ strcpy(action, "Update");
+ }
+ ready_bits += bps;
+
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3" PRIu32 ", Col %3" PRIu32
+ ", Samples %" PRIu16 ", Src byte offset %3" PRIu32
+ " bit offset %2" PRIu32 " Dst offset %3td",
+ row + 1u, col + 1u, s, src_byte, src_bit,
+ dst - out);
+
+ dump_short(dumpfile, format, "Match bits", matchbits);
+ dump_data(dumpfile, format, "Src bits", src, 2);
+ dump_short(dumpfile, format, "Buff1 bits", buff1);
+ dump_short(dumpfile, format, "Buff2 bits", buff2);
+ dump_byte(dumpfile, format, "Write byte", bytebuff);
+ dump_info(dumpfile, format, "", "Ready bits: %d, %s",
+ ready_bits, action);
+ }
+ }
+ }
+
+ /* catch any trailing bits at the end of the line */
+ if (ready_bits > 0)
+ {
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3d, Col %3d, Src byte offset %3d bit offset "
+ "%2d Dst offset %3d",
+ row + 1, col + 1, src_byte, src_bit, dst - out);
+ dump_byte(dumpfile, format, "Final bits", bytebuff);
+ }
+ }
+
+ if ((dumpfile != NULL) && (level == 2))
+ {
+ dump_info(dumpfile, format, "combineSeparateSamples16bits",
+ "Output data");
+ dump_buffer(dumpfile, format, 1, dst_rowsize, row,
+ out + (row * dst_rowsize));
+ }
}
- /* bytes_per_sample = (bps + 7) / 8; */
- src_rowsize = ((bps * cols) + 7) / 8;
- dst_rowsize = ((bps * cols * spp) + 7) / 8;
- maskbits = (uint8_t)-1 >> (8 - bps);
+ return (0);
+} /* end combineSeparateSamples16bits */
+
+static int combineSeparateSamples24bits(uint8_t *in[], uint8_t *out,
+ uint32_t cols, uint32_t rows,
+ uint16_t spp, uint16_t bps,
+ FILE *dumpfile, int format, int level)
+{
+ int ready_bits = 0 /*, bytes_per_sample = 0 */;
+ uint32_t src_rowsize, dst_rowsize;
+ uint32_t bit_offset, src_offset;
+ uint32_t row, col, src_byte = 0, src_bit = 0;
+ uint32_t maskbits = 0, matchbits = 0;
+ uint32_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0;
+ tsample_t s;
+ unsigned char *src = in[0];
+ unsigned char *dst = out;
+ char action[8];
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("combineSeparateSamples24bits",
+ "Invalid input or output buffer");
+ return (1);
+ }
+
+ /* bytes_per_sample = (bps + 7) / 8; */
+ src_rowsize = ((bps * cols) + 7) / 8;
+ dst_rowsize = ((bps * cols * spp) + 7) / 8;
+ maskbits = (uint32_t)-1 >> (32 - bps);
+
+ for (row = 0; row < rows; row++)
+ {
+ ready_bits = 0;
+ buff1 = buff2 = 0;
+ dst = out + (row * dst_rowsize);
+ src_offset = row * src_rowsize;
+ for (col = 0; col < cols; col++)
+ {
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps;
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+
+ matchbits = maskbits << (32 - src_bit - bps);
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ src = in[s] + src_offset + src_byte;
+ if (little_endian)
+ buff1 = ((uint32_t)src[0] << 24) |
+ ((uint32_t)src[1] << 16) | ((uint32_t)src[2] << 8) |
+ (uint32_t)src[3];
+ else
+ buff1 = ((uint32_t)src[3] << 24) |
+ ((uint32_t)src[2] << 16) | ((uint32_t)src[1] << 8) |
+ (uint32_t)src[0];
+ buff1 = (buff1 & matchbits) << (src_bit);
+
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 16)
+ {
+ bytebuff1 = (buff2 >> 24);
+ *dst++ = bytebuff1;
+ bytebuff2 = (buff2 >> 16);
+ *dst++ = bytebuff2;
+ ready_bits -= 16;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
+ strcpy(action, "Flush");
+ }
+ else
+ { /* add another bps bits to the buffer */
+ bytebuff1 = bytebuff2 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ strcpy(action, "Update");
+ }
+ ready_bits += bps;
+
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3" PRIu32 ", Col %3" PRIu32
+ ", Samples %" PRIu16 ", Src byte offset %3" PRIu32
+ " bit offset %2" PRIu32 " Dst offset %3td",
+ row + 1u, col + 1u, s, src_byte, src_bit,
+ dst - out);
+ dump_long(dumpfile, format, "Match bits ", matchbits);
+ dump_data(dumpfile, format, "Src bits ", src, 4);
+ dump_long(dumpfile, format, "Buff1 bits ", buff1);
+ dump_long(dumpfile, format, "Buff2 bits ", buff2);
+ dump_byte(dumpfile, format, "Write bits1", bytebuff1);
+ dump_byte(dumpfile, format, "Write bits2", bytebuff2);
+ dump_info(dumpfile, format, "", "Ready bits: %d, %s",
+ ready_bits, action);
+ }
+ }
+ }
+
+ /* catch any trailing bits at the end of the line */
+ while (ready_bits > 0)
+ {
+ bytebuff1 = (buff2 >> 24);
+ *dst++ = bytebuff1;
+
+ buff2 = (buff2 << 8);
+ bytebuff2 = bytebuff1;
+ ready_bits -= 8;
+ }
- for (row = 0; row < rows; row++)
- {
- ready_bits = 0;
- buff1 = buff2 = 0;
- dst = out + (row * dst_rowsize);
- src_offset = row * src_rowsize;
- for (col = 0; col < cols; col++)
- {
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps;
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
-
- matchbits = maskbits << (8 - src_bit - bps);
- /* load up next sample from each plane */
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- src = in[s] + src_offset + src_byte;
- buff1 = ((*src) & matchbits) << (src_bit);
-
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 8)
- {
- *dst++ = buff2;
- buff2 = buff1;
- ready_bits -= 8;
- strcpy (action, "Flush");
- }
- else
- {
- buff2 = (buff2 | (buff1 >> ready_bits));
- strcpy (action, "Update");
- }
- ready_bits += bps;
-
if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3"PRIu32", Col %3"PRIu32", Samples %"PRIu16", Src byte offset %3"PRIu32" bit offset %2"PRIu32" Dst offset %3td",
- row + 1u, col + 1u, s, src_byte, src_bit, dst - out);
- dump_byte (dumpfile, format, "Match bits", matchbits);
- dump_byte (dumpfile, format, "Src bits", *src);
- dump_byte (dumpfile, format, "Buff1 bits", buff1);
- dump_byte (dumpfile, format, "Buff2 bits", buff2);
- dump_info (dumpfile, format, "","%s", action);
- }
- }
- }
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3d, Col %3d, Src byte offset %3d bit offset %2d "
+ "Dst offset %3d",
+ row + 1, col + 1, src_byte, src_bit, dst - out);
+
+ dump_long(dumpfile, format, "Match bits ", matchbits);
+ dump_data(dumpfile, format, "Src bits ", src, 4);
+ dump_long(dumpfile, format, "Buff1 bits ", buff1);
+ dump_long(dumpfile, format, "Buff2 bits ", buff2);
+ dump_byte(dumpfile, format, "Write bits1", bytebuff1);
+ dump_byte(dumpfile, format, "Write bits2", bytebuff2);
+ dump_info(dumpfile, format, "", "Ready bits: %2d", ready_bits);
+ }
- if (ready_bits > 0)
- {
- buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
- *dst++ = buff1;
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3"PRIu32", Col %3"PRIu32", Src byte offset %3"PRIu32" bit offset %2"PRIu32" Dst offset %3td",
- row + 1u, col + 1u, src_byte, src_bit, dst - out);
- dump_byte (dumpfile, format, "Final bits", buff1);
- }
- }
-
- if ((dumpfile != NULL) && (level >= 2))
- {
- dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data");
- dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
- }
- }
-
- return (0);
- } /* end combineSeparateSamples8bits */
-
-static int
-combineSeparateSamples16bits (uint8_t *in[], uint8_t *out, uint32_t cols,
- uint32_t rows, uint16_t spp, uint16_t bps,
- FILE *dumpfile, int format, int level)
- {
- int ready_bits = 0 /*, bytes_per_sample = 0 */;
- uint32_t src_rowsize, dst_rowsize;
- uint32_t bit_offset, src_offset;
- uint32_t row, col, src_byte = 0, src_bit = 0;
- uint16_t maskbits = 0, matchbits = 0;
- uint16_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff = 0;
- tsample_t s;
- unsigned char *src = in[0];
- unsigned char *dst = out;
- char action[8];
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("combineSeparateSamples16bits","Invalid input or output buffer");
- return (1);
+ if ((dumpfile != NULL) && (level == 2))
+ {
+ dump_info(dumpfile, format, "combineSeparateSamples24bits",
+ "Output data");
+ dump_buffer(dumpfile, format, 1, dst_rowsize, row,
+ out + (row * dst_rowsize));
+ }
}
- /* bytes_per_sample = (bps + 7) / 8; */
- src_rowsize = ((bps * cols) + 7) / 8;
- dst_rowsize = ((bps * cols * spp) + 7) / 8;
- maskbits = (uint16_t)-1 >> (16 - bps);
+ return (0);
+} /* end combineSeparateSamples24bits */
- for (row = 0; row < rows; row++)
- {
- ready_bits = 0;
- buff1 = buff2 = 0;
- dst = out + (row * dst_rowsize);
- src_offset = row * src_rowsize;
- for (col = 0; col < cols; col++)
- {
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps;
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
-
- matchbits = maskbits << (16 - src_bit - bps);
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- src = in[s] + src_offset + src_byte;
- if (little_endian)
- buff1 = (src[0] << 8) | src[1];
- else
- buff1 = (src[1] << 8) | src[0];
-
- buff1 = (buff1 & matchbits) << (src_bit);
-
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 8)
- {
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
- ready_bits -= 8;
- /* shift in new bits */
- buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
- strcpy (action, "Flush");
- }
- else
- { /* add another bps bits to the buffer */
- bytebuff = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- strcpy (action, "Update");
- }
- ready_bits += bps;
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3"PRIu32", Col %3"PRIu32", Samples %"PRIu16", Src byte offset %3"PRIu32" bit offset %2"PRIu32" Dst offset %3td",
- row + 1u, col + 1u, s, src_byte, src_bit, dst - out);
-
- dump_short (dumpfile, format, "Match bits", matchbits);
- dump_data (dumpfile, format, "Src bits", src, 2);
- dump_short (dumpfile, format, "Buff1 bits", buff1);
- dump_short (dumpfile, format, "Buff2 bits", buff2);
- dump_byte (dumpfile, format, "Write byte", bytebuff);
- dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
- }
- }
- }
+static int combineSeparateSamples32bits(uint8_t *in[], uint8_t *out,
+ uint32_t cols, uint32_t rows,
+ uint16_t spp, uint16_t bps,
+ FILE *dumpfile, int format, int level)
+{
+ int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */;
+ uint32_t src_rowsize, dst_rowsize, bit_offset, src_offset;
+ uint32_t src_byte = 0, src_bit = 0;
+ uint32_t row, col;
+ uint32_t longbuff1 = 0, longbuff2 = 0;
+ uint64_t maskbits = 0, matchbits = 0;
+ uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
+ tsample_t s;
+ unsigned char *src = in[0];
+ unsigned char *dst = out;
+ char action[8];
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("combineSeparateSamples32bits",
+ "Invalid input or output buffer");
+ return (1);
+ }
+
+ /* bytes_per_sample = (bps + 7) / 8; */
+ src_rowsize = ((bps * cols) + 7) / 8;
+ dst_rowsize = ((bps * cols * spp) + 7) / 8;
+ maskbits = (uint64_t)-1 >> (64 - bps);
+ /* shift_width = ((bps + 7) / 8) + 1; */
+
+ for (row = 0; row < rows; row++)
+ {
+ ready_bits = 0;
+ buff1 = buff2 = 0;
+ dst = out + (row * dst_rowsize);
+ src_offset = row * src_rowsize;
+ for (col = 0; col < cols; col++)
+ {
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps;
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
- /* catch any trailing bits at the end of the line */
- if (ready_bits > 0)
- {
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
- row + 1, col + 1, src_byte, src_bit, dst - out);
- dump_byte (dumpfile, format, "Final bits", bytebuff);
- }
- }
-
- if ((dumpfile != NULL) && (level == 2))
- {
- dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data");
- dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
- }
- }
-
- return (0);
- } /* end combineSeparateSamples16bits */
-
-static int
-combineSeparateSamples24bits (uint8_t *in[], uint8_t *out, uint32_t cols,
- uint32_t rows, uint16_t spp, uint16_t bps,
- FILE *dumpfile, int format, int level)
- {
- int ready_bits = 0 /*, bytes_per_sample = 0 */;
- uint32_t src_rowsize, dst_rowsize;
- uint32_t bit_offset, src_offset;
- uint32_t row, col, src_byte = 0, src_bit = 0;
- uint32_t maskbits = 0, matchbits = 0;
- uint32_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0;
- tsample_t s;
- unsigned char *src = in[0];
- unsigned char *dst = out;
- char action[8];
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("combineSeparateSamples24bits","Invalid input or output buffer");
- return (1);
- }
+ matchbits = maskbits << (64 - src_bit - bps);
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ src = in[s] + src_offset + src_byte;
+ if (little_endian)
+ {
+ longbuff1 = (src[0] << 24) | (src[1] << 16) |
+ (src[2] << 8) | src[3];
+ longbuff2 = longbuff1;
+ }
+ else
+ {
+ longbuff1 = (src[3] << 24) | (src[2] << 16) |
+ (src[1] << 8) | src[0];
+ longbuff2 = longbuff1;
+ }
+ buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
+ buff1 = (buff3 & matchbits) << (src_bit);
- /* bytes_per_sample = (bps + 7) / 8; */
- src_rowsize = ((bps * cols) + 7) / 8;
- dst_rowsize = ((bps * cols * spp) + 7) / 8;
- maskbits = (uint32_t)-1 >> (32 - bps);
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 32)
+ {
+ bytebuff1 = (uint8_t)(buff2 >> 56);
+ *dst++ = bytebuff1;
+ bytebuff2 = (uint8_t)(buff2 >> 48);
+ *dst++ = bytebuff2;
+ bytebuff3 = (uint8_t)(buff2 >> 40);
+ *dst++ = bytebuff3;
+ bytebuff4 = (uint8_t)(buff2 >> 32);
+ *dst++ = bytebuff4;
+ ready_bits -= 32;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
+ strcpy(action, "Flush");
+ }
+ else
+ { /* add another bps bits to the buffer */
+ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ strcpy(action, "Update");
+ }
+ ready_bits += bps;
- for (row = 0; row < rows; row++)
- {
- ready_bits = 0;
- buff1 = buff2 = 0;
- dst = out + (row * dst_rowsize);
- src_offset = row * src_rowsize;
- for (col = 0; col < cols; col++)
- {
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps;
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
-
- matchbits = maskbits << (32 - src_bit - bps);
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- src = in[s] + src_offset + src_byte;
- if (little_endian)
- buff1 = ((uint32_t)src[0] << 24) | ((uint32_t)src[1] << 16) | ((uint32_t)src[2] << 8) | (uint32_t)src[3];
- else
- buff1 = ((uint32_t)src[3] << 24) | ((uint32_t)src[2] << 16) | ((uint32_t)src[1] << 8) | (uint32_t)src[0];
- buff1 = (buff1 & matchbits) << (src_bit);
-
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 16)
- {
- bytebuff1 = (buff2 >> 24);
- *dst++ = bytebuff1;
- bytebuff2 = (buff2 >> 16);
- *dst++ = bytebuff2;
- ready_bits -= 16;
-
- /* shift in new bits */
- buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
- strcpy (action, "Flush");
- }
- else
- { /* add another bps bits to the buffer */
- bytebuff1 = bytebuff2 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- strcpy (action, "Update");
- }
- ready_bits += bps;
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3"PRIu32", Col %3"PRIu32", Samples %"PRIu16", Src byte offset %3"PRIu32" bit offset %2"PRIu32" Dst offset %3td",
- row + 1u, col + 1u, s, src_byte, src_bit, dst - out);
- dump_long (dumpfile, format, "Match bits ", matchbits);
- dump_data (dumpfile, format, "Src bits ", src, 4);
- dump_long (dumpfile, format, "Buff1 bits ", buff1);
- dump_long (dumpfile, format, "Buff2 bits ", buff2);
- dump_byte (dumpfile, format, "Write bits1", bytebuff1);
- dump_byte (dumpfile, format, "Write bits2", bytebuff2);
- dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
- }
- }
- }
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3" PRIu32 ", Col %3" PRIu32
+ ", Sample %" PRIu16 ", Src byte offset %3" PRIu32
+ " bit offset %2" PRIu32 " Dst offset %3td",
+ row + 1u, col + 1u, s, src_byte, src_bit,
+ dst - out);
+ dump_wide(dumpfile, format, "Match bits ", matchbits);
+ dump_data(dumpfile, format, "Src bits ", src, 8);
+ dump_wide(dumpfile, format, "Buff1 bits ", buff1);
+ dump_wide(dumpfile, format, "Buff2 bits ", buff2);
+ dump_info(dumpfile, format, "", "Ready bits: %d, %s",
+ ready_bits, action);
+ }
+ }
+ }
+ while (ready_bits > 0)
+ {
+ bytebuff1 = (buff2 >> 56);
+ *dst++ = bytebuff1;
+ buff2 = (buff2 << 8);
+ ready_bits -= 8;
+ }
- /* catch any trailing bits at the end of the line */
- while (ready_bits > 0)
- {
- bytebuff1 = (buff2 >> 24);
- *dst++ = bytebuff1;
-
- buff2 = (buff2 << 8);
- bytebuff2 = bytebuff1;
- ready_bits -= 8;
- }
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
- row + 1, col + 1, src_byte, src_bit, dst - out);
-
- dump_long (dumpfile, format, "Match bits ", matchbits);
- dump_data (dumpfile, format, "Src bits ", src, 4);
- dump_long (dumpfile, format, "Buff1 bits ", buff1);
- dump_long (dumpfile, format, "Buff2 bits ", buff2);
- dump_byte (dumpfile, format, "Write bits1", bytebuff1);
- dump_byte (dumpfile, format, "Write bits2", bytebuff2);
- dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
- }
-
- if ((dumpfile != NULL) && (level == 2))
- {
- dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data");
- dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
- }
- }
-
- return (0);
- } /* end combineSeparateSamples24bits */
-
-static int
-combineSeparateSamples32bits (uint8_t *in[], uint8_t *out, uint32_t cols,
- uint32_t rows, uint16_t spp, uint16_t bps,
- FILE *dumpfile, int format, int level)
- {
- int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */;
- uint32_t src_rowsize, dst_rowsize, bit_offset, src_offset;
- uint32_t src_byte = 0, src_bit = 0;
- uint32_t row, col;
- uint32_t longbuff1 = 0, longbuff2 = 0;
- uint64_t maskbits = 0, matchbits = 0;
- uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
- tsample_t s;
- unsigned char *src = in[0];
- unsigned char *dst = out;
- char action[8];
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("combineSeparateSamples32bits","Invalid input or output buffer");
- return (1);
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3d, Col %3d, Src byte offset %3d bit offset %2d "
+ "Dst offset %3d",
+ row + 1, col + 1, src_byte, src_bit, dst - out);
+
+ dump_wide(dumpfile, format, "Match bits ", matchbits);
+ dump_data(dumpfile, format, "Src bits ", src, 4);
+ dump_wide(dumpfile, format, "Buff1 bits ", buff1);
+ dump_wide(dumpfile, format, "Buff2 bits ", buff2);
+ dump_byte(dumpfile, format, "Write bits1", bytebuff1);
+ dump_byte(dumpfile, format, "Write bits2", bytebuff2);
+ dump_info(dumpfile, format, "", "Ready bits: %2d", ready_bits);
+ }
+
+ if ((dumpfile != NULL) && (level == 2))
+ {
+ dump_info(dumpfile, format, "combineSeparateSamples32bits",
+ "Output data");
+ dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
+ }
}
- /* bytes_per_sample = (bps + 7) / 8; */
- src_rowsize = ((bps * cols) + 7) / 8;
- dst_rowsize = ((bps * cols * spp) + 7) / 8;
- maskbits = (uint64_t)-1 >> (64 - bps);
- /* shift_width = ((bps + 7) / 8) + 1; */
+ return (0);
+} /* end combineSeparateSamples32bits */
+
+static int combineSeparateTileSamplesBytes(unsigned char *srcbuffs[],
+ unsigned char *out, uint32_t cols,
+ uint32_t rows, uint32_t imagewidth,
+ uint32_t tw, uint16_t spp,
+ uint16_t bps, FILE *dumpfile,
+ int format, int level)
+{
+ int i, bytes_per_sample;
+ uint32_t row, col, col_offset, src_rowsize, dst_rowsize, src_offset;
+ unsigned char *src;
+ unsigned char *dst;
+ tsample_t s;
- for (row = 0; row < rows; row++)
+ src = srcbuffs[0];
+ dst = out;
+ if ((src == NULL) || (dst == NULL))
{
- ready_bits = 0;
- buff1 = buff2 = 0;
- dst = out + (row * dst_rowsize);
- src_offset = row * src_rowsize;
- for (col = 0; col < cols; col++)
- {
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps;
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
-
- matchbits = maskbits << (64 - src_bit - bps);
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- src = in[s] + src_offset + src_byte;
- if (little_endian)
- {
- longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
- longbuff2 = longbuff1;
- }
- else
- {
- longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
- longbuff2 = longbuff1;
- }
- buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
- buff1 = (buff3 & matchbits) << (src_bit);
-
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 32)
- {
- bytebuff1 = (uint8_t)(buff2 >> 56);
- *dst++ = bytebuff1;
- bytebuff2 = (uint8_t)(buff2 >> 48);
- *dst++ = bytebuff2;
- bytebuff3 = (uint8_t)(buff2 >> 40);
- *dst++ = bytebuff3;
- bytebuff4 = (uint8_t)(buff2 >> 32);
- *dst++ = bytebuff4;
- ready_bits -= 32;
-
- /* shift in new bits */
- buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
- strcpy (action, "Flush");
- }
- else
- { /* add another bps bits to the buffer */
- bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- strcpy (action, "Update");
- }
- ready_bits += bps;
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3"PRIu32", Col %3"PRIu32", Sample %"PRIu16", Src byte offset %3"PRIu32" bit offset %2"PRIu32" Dst offset %3td",
- row + 1u, col + 1u, s, src_byte, src_bit, dst - out);
- dump_wide (dumpfile, format, "Match bits ", matchbits);
- dump_data (dumpfile, format, "Src bits ", src, 8);
- dump_wide (dumpfile, format, "Buff1 bits ", buff1);
- dump_wide (dumpfile, format, "Buff2 bits ", buff2);
- dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action);
- }
- }
- }
- while (ready_bits > 0)
- {
- bytebuff1 = (buff2 >> 56);
- *dst++ = bytebuff1;
- buff2 = (buff2 << 8);
- ready_bits -= 8;
- }
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
- row + 1, col + 1, src_byte, src_bit, dst - out);
-
- dump_wide (dumpfile, format, "Match bits ", matchbits);
- dump_data (dumpfile, format, "Src bits ", src, 4);
- dump_wide (dumpfile, format, "Buff1 bits ", buff1);
- dump_wide (dumpfile, format, "Buff2 bits ", buff2);
- dump_byte (dumpfile, format, "Write bits1", bytebuff1);
- dump_byte (dumpfile, format, "Write bits2", bytebuff2);
- dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
- }
-
- if ((dumpfile != NULL) && (level == 2))
- {
- dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data");
- dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
- }
- }
-
- return (0);
- } /* end combineSeparateSamples32bits */
-
-static int
-combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out,
- uint32_t cols, uint32_t rows, uint32_t imagewidth,
- uint32_t tw, uint16_t spp, uint16_t bps,
- FILE *dumpfile, int format, int level)
- {
- int i, bytes_per_sample;
- uint32_t row, col, col_offset, src_rowsize, dst_rowsize, src_offset;
- unsigned char *src;
- unsigned char *dst;
- tsample_t s;
-
- src = srcbuffs[0];
- dst = out;
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address");
- return (1);
+ TIFFError("combineSeparateTileSamplesBytes", "Invalid buffer address");
+ return (1);
}
- bytes_per_sample = (bps + 7) / 8;
- src_rowsize = ((bps * tw) + 7) / 8;
- dst_rowsize = imagewidth * bytes_per_sample * spp;
- for (row = 0; row < rows; row++)
+ bytes_per_sample = (bps + 7) / 8;
+ src_rowsize = ((bps * tw) + 7) / 8;
+ dst_rowsize = imagewidth * bytes_per_sample * spp;
+ for (row = 0; row < rows; row++)
{
- if ((dumpfile != NULL) && (level == 2))
- {
- for (s = 0; s < spp; s++)
+ if ((dumpfile != NULL) && (level == 2))
{
- dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %"PRIu16, s);
- dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize));
+ for (s = 0; s < spp; s++)
+ {
+ dump_info(dumpfile, format, "combineSeparateTileSamplesBytes",
+ "Input data, Sample %" PRIu16, s);
+ dump_buffer(dumpfile, format, 1, cols, row,
+ srcbuffs[s] + (row * src_rowsize));
+ }
}
- }
- dst = out + (row * dst_rowsize);
- src_offset = row * src_rowsize;
+ dst = out + (row * dst_rowsize);
+ src_offset = row * src_rowsize;
#ifdef DEVELMODE
- TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d",
- row, src_offset, dst - out);
+ TIFFError("", "Tile row %4d, Src offset %6d Dst offset %6d", row,
+ src_offset, dst - out);
#endif
- for (col = 0; col < cols; col++)
- {
- col_offset = src_offset + (col * (bps / 8));
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- src = srcbuffs[s] + col_offset;
- for (i = 0; i < bytes_per_sample; i++)
- *(dst + i) = *(src + i);
- dst += bytes_per_sample;
- }
- }
-
- if ((dumpfile != NULL) && (level == 2))
- {
- dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples");
- dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
- }
- }
-
- return (0);
- } /* end combineSeparateTileSamplesBytes */
-
-static int
-combineSeparateTileSamples8bits (uint8_t *in[], uint8_t *out, uint32_t cols,
- uint32_t rows, uint32_t imagewidth,
- uint32_t tw, uint16_t spp, uint16_t bps,
- FILE *dumpfile, int format, int level)
- {
- int ready_bits = 0;
- uint32_t src_rowsize, dst_rowsize, src_offset;
- uint32_t bit_offset;
- uint32_t row, col, src_byte = 0, src_bit = 0;
- uint8_t maskbits = 0, matchbits = 0;
- uint8_t buff1 = 0, buff2 = 0;
- tsample_t s;
- unsigned char *src = in[0];
- unsigned char *dst = out;
- char action[32];
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer");
- return (1);
+ for (col = 0; col < cols; col++)
+ {
+ col_offset = src_offset + (col * (bps / 8));
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ src = srcbuffs[s] + col_offset;
+ for (i = 0; i < bytes_per_sample; i++)
+ *(dst + i) = *(src + i);
+ dst += bytes_per_sample;
+ }
+ }
+
+ if ((dumpfile != NULL) && (level == 2))
+ {
+ dump_info(dumpfile, format, "combineSeparateTileSamplesBytes",
+ "Output data, combined samples");
+ dump_buffer(dumpfile, format, 1, dst_rowsize, row,
+ out + (row * dst_rowsize));
+ }
}
- src_rowsize = ((bps * tw) + 7) / 8;
- dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
- maskbits = (uint8_t)-1 >> (8 - bps);
+ return (0);
+} /* end combineSeparateTileSamplesBytes */
+
+static int combineSeparateTileSamples8bits(uint8_t *in[], uint8_t *out,
+ uint32_t cols, uint32_t rows,
+ uint32_t imagewidth, uint32_t tw,
+ uint16_t spp, uint16_t bps,
+ FILE *dumpfile, int format,
+ int level)
+{
+ int ready_bits = 0;
+ uint32_t src_rowsize, dst_rowsize, src_offset;
+ uint32_t bit_offset;
+ uint32_t row, col, src_byte = 0, src_bit = 0;
+ uint8_t maskbits = 0, matchbits = 0;
+ uint8_t buff1 = 0, buff2 = 0;
+ tsample_t s;
+ unsigned char *src = in[0];
+ unsigned char *dst = out;
+ char action[32];
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("combineSeparateTileSamples8bits",
+ "Invalid input or output buffer");
+ return (1);
+ }
+
+ src_rowsize = ((bps * tw) + 7) / 8;
+ dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
+ maskbits = (uint8_t)-1 >> (8 - bps);
+
+ for (row = 0; row < rows; row++)
+ {
+ ready_bits = 0;
+ buff1 = buff2 = 0;
+ dst = out + (row * dst_rowsize);
+ src_offset = row * src_rowsize;
+ for (col = 0; col < cols; col++)
+ {
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps;
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+
+ matchbits = maskbits << (8 - src_bit - bps);
+ /* load up next sample from each plane */
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ src = in[s] + src_offset + src_byte;
+ buff1 = ((*src) & matchbits) << (src_bit);
- for (row = 0; row < rows; row++)
- {
- ready_bits = 0;
- buff1 = buff2 = 0;
- dst = out + (row * dst_rowsize);
- src_offset = row * src_rowsize;
- for (col = 0; col < cols; col++)
- {
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps;
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
-
- matchbits = maskbits << (8 - src_bit - bps);
- /* load up next sample from each plane */
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- src = in[s] + src_offset + src_byte;
- buff1 = ((*src) & matchbits) << (src_bit);
-
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 8)
- {
- *dst++ = buff2;
- buff2 = buff1;
- ready_bits -= 8;
- strcpy (action, "Flush");
- }
- else
- {
- buff2 = (buff2 | (buff1 >> ready_bits));
- strcpy (action, "Update");
- }
- ready_bits += bps;
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3"PRIu32", Col %3"PRIu32", Samples %"PRIu16", Src byte offset %3"PRIu32" bit offset %2"PRIu32" Dst offset %3td",
- row + 1u, col + 1u, s, src_byte, src_bit, dst - out);
- dump_byte (dumpfile, format, "Match bits", matchbits);
- dump_byte (dumpfile, format, "Src bits", *src);
- dump_byte (dumpfile, format, "Buff1 bits", buff1);
- dump_byte (dumpfile, format, "Buff2 bits", buff2);
- dump_info (dumpfile, format, "","%s", action);
- }
- }
- }
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 8)
+ {
+ *dst++ = buff2;
+ buff2 = buff1;
+ ready_bits -= 8;
+ strcpy(action, "Flush");
+ }
+ else
+ {
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ strcpy(action, "Update");
+ }
+ ready_bits += bps;
- if (ready_bits > 0)
- {
- buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
- *dst++ = buff1;
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
- row + 1, col + 1, src_byte, src_bit, dst - out);
- dump_byte (dumpfile, format, "Final bits", buff1);
- }
- }
-
- if ((dumpfile != NULL) && (level >= 2))
- {
- dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data");
- dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
- }
- }
-
- return (0);
- } /* end combineSeparateTileSamples8bits */
-
-static int
-combineSeparateTileSamples16bits (uint8_t *in[], uint8_t *out, uint32_t cols,
- uint32_t rows, uint32_t imagewidth,
- uint32_t tw, uint16_t spp, uint16_t bps,
- FILE *dumpfile, int format, int level)
- {
- int ready_bits = 0;
- uint32_t src_rowsize, dst_rowsize;
- uint32_t bit_offset, src_offset;
- uint32_t row, col, src_byte = 0, src_bit = 0;
- uint16_t maskbits = 0, matchbits = 0;
- uint16_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff = 0;
- tsample_t s;
- unsigned char *src = in[0];
- unsigned char *dst = out;
- char action[8];
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer");
- return (1);
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3" PRIu32 ", Col %3" PRIu32
+ ", Samples %" PRIu16 ", Src byte offset %3" PRIu32
+ " bit offset %2" PRIu32 " Dst offset %3td",
+ row + 1u, col + 1u, s, src_byte, src_bit,
+ dst - out);
+ dump_byte(dumpfile, format, "Match bits", matchbits);
+ dump_byte(dumpfile, format, "Src bits", *src);
+ dump_byte(dumpfile, format, "Buff1 bits", buff1);
+ dump_byte(dumpfile, format, "Buff2 bits", buff2);
+ dump_info(dumpfile, format, "", "%s", action);
+ }
+ }
+ }
+
+ if (ready_bits > 0)
+ {
+ buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
+ *dst++ = buff1;
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3d, Col %3d, Src byte offset %3d bit offset "
+ "%2d Dst offset %3d",
+ row + 1, col + 1, src_byte, src_bit, dst - out);
+ dump_byte(dumpfile, format, "Final bits", buff1);
+ }
+ }
+
+ if ((dumpfile != NULL) && (level >= 2))
+ {
+ dump_info(dumpfile, format, "combineSeparateTileSamples8bits",
+ "Output data");
+ dump_buffer(dumpfile, format, 1, dst_rowsize, row,
+ out + (row * dst_rowsize));
+ }
}
- src_rowsize = ((bps * tw) + 7) / 8;
- dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
- maskbits = (uint16_t)-1 >> (16 - bps);
+ return (0);
+} /* end combineSeparateTileSamples8bits */
+
+static int combineSeparateTileSamples16bits(uint8_t *in[], uint8_t *out,
+ uint32_t cols, uint32_t rows,
+ uint32_t imagewidth, uint32_t tw,
+ uint16_t spp, uint16_t bps,
+ FILE *dumpfile, int format,
+ int level)
+{
+ int ready_bits = 0;
+ uint32_t src_rowsize, dst_rowsize;
+ uint32_t bit_offset, src_offset;
+ uint32_t row, col, src_byte = 0, src_bit = 0;
+ uint16_t maskbits = 0, matchbits = 0;
+ uint16_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff = 0;
+ tsample_t s;
+ unsigned char *src = in[0];
+ unsigned char *dst = out;
+ char action[8];
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("combineSeparateTileSamples16bits",
+ "Invalid input or output buffer");
+ return (1);
+ }
+
+ src_rowsize = ((bps * tw) + 7) / 8;
+ dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
+ maskbits = (uint16_t)-1 >> (16 - bps);
+
+ for (row = 0; row < rows; row++)
+ {
+ ready_bits = 0;
+ buff1 = buff2 = 0;
+ dst = out + (row * dst_rowsize);
+ src_offset = row * src_rowsize;
+ for (col = 0; col < cols; col++)
+ {
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps;
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
- for (row = 0; row < rows; row++)
- {
- ready_bits = 0;
- buff1 = buff2 = 0;
- dst = out + (row * dst_rowsize);
- src_offset = row * src_rowsize;
- for (col = 0; col < cols; col++)
- {
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps;
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
-
- matchbits = maskbits << (16 - src_bit - bps);
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- src = in[s] + src_offset + src_byte;
- if (little_endian)
- buff1 = (src[0] << 8) | src[1];
- else
- buff1 = (src[1] << 8) | src[0];
- buff1 = (buff1 & matchbits) << (src_bit);
-
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 8)
- {
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
- ready_bits -= 8;
- /* shift in new bits */
- buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
- strcpy (action, "Flush");
- }
- else
- { /* add another bps bits to the buffer */
- bytebuff = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- strcpy (action, "Update");
- }
- ready_bits += bps;
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3"PRIu32", Col %3"PRIu32", Samples %"PRIu16", Src byte offset %3"PRIu32" bit offset %2"PRIu32" Dst offset %3td",
- row + 1u, col + 1u, s, src_byte, src_bit, dst - out);
-
- dump_short (dumpfile, format, "Match bits", matchbits);
- dump_data (dumpfile, format, "Src bits", src, 2);
- dump_short (dumpfile, format, "Buff1 bits", buff1);
- dump_short (dumpfile, format, "Buff2 bits", buff2);
- dump_byte (dumpfile, format, "Write byte", bytebuff);
- dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
- }
- }
- }
+ matchbits = maskbits << (16 - src_bit - bps);
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ src = in[s] + src_offset + src_byte;
+ if (little_endian)
+ buff1 = (src[0] << 8) | src[1];
+ else
+ buff1 = (src[1] << 8) | src[0];
+ buff1 = (buff1 & matchbits) << (src_bit);
- /* catch any trailing bits at the end of the line */
- if (ready_bits > 0)
- {
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
- row + 1, col + 1, src_byte, src_bit, dst - out);
- dump_byte (dumpfile, format, "Final bits", bytebuff);
- }
- }
-
- if ((dumpfile != NULL) && (level == 2))
- {
- dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data");
- dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
- }
- }
-
- return (0);
- } /* end combineSeparateTileSamples16bits */
-
-static int
-combineSeparateTileSamples24bits (uint8_t *in[], uint8_t *out, uint32_t cols,
- uint32_t rows, uint32_t imagewidth,
- uint32_t tw, uint16_t spp, uint16_t bps,
- FILE *dumpfile, int format, int level)
- {
- int ready_bits = 0;
- uint32_t src_rowsize, dst_rowsize;
- uint32_t bit_offset, src_offset;
- uint32_t row, col, src_byte = 0, src_bit = 0;
- uint32_t maskbits = 0, matchbits = 0;
- uint32_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0;
- tsample_t s;
- unsigned char *src = in[0];
- unsigned char *dst = out;
- char action[8];
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer");
- return (1);
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 8)
+ {
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
+ ready_bits -= 8;
+ /* shift in new bits */
+ buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
+ strcpy(action, "Flush");
+ }
+ else
+ { /* add another bps bits to the buffer */
+ bytebuff = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ strcpy(action, "Update");
+ }
+ ready_bits += bps;
+
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3" PRIu32 ", Col %3" PRIu32
+ ", Samples %" PRIu16 ", Src byte offset %3" PRIu32
+ " bit offset %2" PRIu32 " Dst offset %3td",
+ row + 1u, col + 1u, s, src_byte, src_bit,
+ dst - out);
+
+ dump_short(dumpfile, format, "Match bits", matchbits);
+ dump_data(dumpfile, format, "Src bits", src, 2);
+ dump_short(dumpfile, format, "Buff1 bits", buff1);
+ dump_short(dumpfile, format, "Buff2 bits", buff2);
+ dump_byte(dumpfile, format, "Write byte", bytebuff);
+ dump_info(dumpfile, format, "", "Ready bits: %d, %s",
+ ready_bits, action);
+ }
+ }
+ }
+
+ /* catch any trailing bits at the end of the line */
+ if (ready_bits > 0)
+ {
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3d, Col %3d, Src byte offset %3d bit offset "
+ "%2d Dst offset %3d",
+ row + 1, col + 1, src_byte, src_bit, dst - out);
+ dump_byte(dumpfile, format, "Final bits", bytebuff);
+ }
+ }
+
+ if ((dumpfile != NULL) && (level == 2))
+ {
+ dump_info(dumpfile, format, "combineSeparateTileSamples16bits",
+ "Output data");
+ dump_buffer(dumpfile, format, 1, dst_rowsize, row,
+ out + (row * dst_rowsize));
+ }
}
- src_rowsize = ((bps * tw) + 7) / 8;
- dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
- maskbits = (uint32_t)-1 >> (32 - bps);
+ return (0);
+} /* end combineSeparateTileSamples16bits */
+
+static int combineSeparateTileSamples24bits(uint8_t *in[], uint8_t *out,
+ uint32_t cols, uint32_t rows,
+ uint32_t imagewidth, uint32_t tw,
+ uint16_t spp, uint16_t bps,
+ FILE *dumpfile, int format,
+ int level)
+{
+ int ready_bits = 0;
+ uint32_t src_rowsize, dst_rowsize;
+ uint32_t bit_offset, src_offset;
+ uint32_t row, col, src_byte = 0, src_bit = 0;
+ uint32_t maskbits = 0, matchbits = 0;
+ uint32_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0;
+ tsample_t s;
+ unsigned char *src = in[0];
+ unsigned char *dst = out;
+ char action[8];
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("combineSeparateTileSamples24bits",
+ "Invalid input or output buffer");
+ return (1);
+ }
+
+ src_rowsize = ((bps * tw) + 7) / 8;
+ dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
+ maskbits = (uint32_t)-1 >> (32 - bps);
+
+ for (row = 0; row < rows; row++)
+ {
+ ready_bits = 0;
+ buff1 = buff2 = 0;
+ dst = out + (row * dst_rowsize);
+ src_offset = row * src_rowsize;
+ for (col = 0; col < cols; col++)
+ {
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps;
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
- for (row = 0; row < rows; row++)
- {
- ready_bits = 0;
- buff1 = buff2 = 0;
- dst = out + (row * dst_rowsize);
- src_offset = row * src_rowsize;
- for (col = 0; col < cols; col++)
- {
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps;
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
-
- matchbits = maskbits << (32 - src_bit - bps);
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- src = in[s] + src_offset + src_byte;
- if (little_endian)
- buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
- else
- buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
- buff1 = (buff1 & matchbits) << (src_bit);
-
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 16)
- {
- bytebuff1 = (buff2 >> 24);
- *dst++ = bytebuff1;
- bytebuff2 = (buff2 >> 16);
- *dst++ = bytebuff2;
- ready_bits -= 16;
-
- /* shift in new bits */
- buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
- strcpy (action, "Flush");
- }
- else
- { /* add another bps bits to the buffer */
- bytebuff1 = bytebuff2 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- strcpy (action, "Update");
- }
- ready_bits += bps;
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3"PRIu32", Col %3"PRIu32", Samples %"PRIu16", Src byte offset %3"PRIu32" bit offset %2"PRIu32" Dst offset %3td",
- row + 1u, col + 1u, s, src_byte, src_bit, dst - out);
- dump_long (dumpfile, format, "Match bits ", matchbits);
- dump_data (dumpfile, format, "Src bits ", src, 4);
- dump_long (dumpfile, format, "Buff1 bits ", buff1);
- dump_long (dumpfile, format, "Buff2 bits ", buff2);
- dump_byte (dumpfile, format, "Write bits1", bytebuff1);
- dump_byte (dumpfile, format, "Write bits2", bytebuff2);
- dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
- }
- }
- }
+ matchbits = maskbits << (32 - src_bit - bps);
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ src = in[s] + src_offset + src_byte;
+ if (little_endian)
+ buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) |
+ src[3];
+ else
+ buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) |
+ src[0];
+ buff1 = (buff1 & matchbits) << (src_bit);
- /* catch any trailing bits at the end of the line */
- while (ready_bits > 0)
- {
- bytebuff1 = (buff2 >> 24);
- *dst++ = bytebuff1;
-
- buff2 = (buff2 << 8);
- bytebuff2 = bytebuff1;
- ready_bits -= 8;
- }
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
- row + 1, col + 1, src_byte, src_bit, dst - out);
-
- dump_long (dumpfile, format, "Match bits ", matchbits);
- dump_data (dumpfile, format, "Src bits ", src, 4);
- dump_long (dumpfile, format, "Buff1 bits ", buff1);
- dump_long (dumpfile, format, "Buff2 bits ", buff2);
- dump_byte (dumpfile, format, "Write bits1", bytebuff1);
- dump_byte (dumpfile, format, "Write bits2", bytebuff2);
- dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
- }
-
- if ((dumpfile != NULL) && (level == 2))
- {
- dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data");
- dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
- }
- }
-
- return (0);
- } /* end combineSeparateTileSamples24bits */
-
-static int
-combineSeparateTileSamples32bits (uint8_t *in[], uint8_t *out, uint32_t cols,
- uint32_t rows, uint32_t imagewidth,
- uint32_t tw, uint16_t spp, uint16_t bps,
- FILE *dumpfile, int format, int level)
- {
- int ready_bits = 0 /*, shift_width = 0 */;
- uint32_t src_rowsize, dst_rowsize, bit_offset, src_offset;
- uint32_t src_byte = 0, src_bit = 0;
- uint32_t row, col;
- uint32_t longbuff1 = 0, longbuff2 = 0;
- uint64_t maskbits = 0, matchbits = 0;
- uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
- tsample_t s;
- unsigned char *src = in[0];
- unsigned char *dst = out;
- char action[8];
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer");
- return (1);
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 16)
+ {
+ bytebuff1 = (buff2 >> 24);
+ *dst++ = bytebuff1;
+ bytebuff2 = (buff2 >> 16);
+ *dst++ = bytebuff2;
+ ready_bits -= 16;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
+ strcpy(action, "Flush");
+ }
+ else
+ { /* add another bps bits to the buffer */
+ bytebuff1 = bytebuff2 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ strcpy(action, "Update");
+ }
+ ready_bits += bps;
+
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3" PRIu32 ", Col %3" PRIu32
+ ", Samples %" PRIu16 ", Src byte offset %3" PRIu32
+ " bit offset %2" PRIu32 " Dst offset %3td",
+ row + 1u, col + 1u, s, src_byte, src_bit,
+ dst - out);
+ dump_long(dumpfile, format, "Match bits ", matchbits);
+ dump_data(dumpfile, format, "Src bits ", src, 4);
+ dump_long(dumpfile, format, "Buff1 bits ", buff1);
+ dump_long(dumpfile, format, "Buff2 bits ", buff2);
+ dump_byte(dumpfile, format, "Write bits1", bytebuff1);
+ dump_byte(dumpfile, format, "Write bits2", bytebuff2);
+ dump_info(dumpfile, format, "", "Ready bits: %d, %s",
+ ready_bits, action);
+ }
+ }
+ }
+
+ /* catch any trailing bits at the end of the line */
+ while (ready_bits > 0)
+ {
+ bytebuff1 = (buff2 >> 24);
+ *dst++ = bytebuff1;
+
+ buff2 = (buff2 << 8);
+ bytebuff2 = bytebuff1;
+ ready_bits -= 8;
+ }
+
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3d, Col %3d, Src byte offset %3d bit offset %2d "
+ "Dst offset %3d",
+ row + 1, col + 1, src_byte, src_bit, dst - out);
+
+ dump_long(dumpfile, format, "Match bits ", matchbits);
+ dump_data(dumpfile, format, "Src bits ", src, 4);
+ dump_long(dumpfile, format, "Buff1 bits ", buff1);
+ dump_long(dumpfile, format, "Buff2 bits ", buff2);
+ dump_byte(dumpfile, format, "Write bits1", bytebuff1);
+ dump_byte(dumpfile, format, "Write bits2", bytebuff2);
+ dump_info(dumpfile, format, "", "Ready bits: %2d", ready_bits);
+ }
+
+ if ((dumpfile != NULL) && (level == 2))
+ {
+ dump_info(dumpfile, format, "combineSeparateTileSamples24bits",
+ "Output data");
+ dump_buffer(dumpfile, format, 1, dst_rowsize, row,
+ out + (row * dst_rowsize));
+ }
}
- src_rowsize = ((bps * tw) + 7) / 8;
- dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
- maskbits = (uint64_t)-1 >> (64 - bps);
- /* shift_width = ((bps + 7) / 8) + 1; */
+ return (0);
+} /* end combineSeparateTileSamples24bits */
+
+static int combineSeparateTileSamples32bits(uint8_t *in[], uint8_t *out,
+ uint32_t cols, uint32_t rows,
+ uint32_t imagewidth, uint32_t tw,
+ uint16_t spp, uint16_t bps,
+ FILE *dumpfile, int format,
+ int level)
+{
+ int ready_bits = 0 /*, shift_width = 0 */;
+ uint32_t src_rowsize, dst_rowsize, bit_offset, src_offset;
+ uint32_t src_byte = 0, src_bit = 0;
+ uint32_t row, col;
+ uint32_t longbuff1 = 0, longbuff2 = 0;
+ uint64_t maskbits = 0, matchbits = 0;
+ uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
+ tsample_t s;
+ unsigned char *src = in[0];
+ unsigned char *dst = out;
+ char action[8];
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("combineSeparateTileSamples32bits",
+ "Invalid input or output buffer");
+ return (1);
+ }
+
+ src_rowsize = ((bps * tw) + 7) / 8;
+ dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
+ maskbits = (uint64_t)-1 >> (64 - bps);
+ /* shift_width = ((bps + 7) / 8) + 1; */
+
+ for (row = 0; row < rows; row++)
+ {
+ ready_bits = 0;
+ buff1 = buff2 = 0;
+ dst = out + (row * dst_rowsize);
+ src_offset = row * src_rowsize;
+ for (col = 0; col < cols; col++)
+ {
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = col * bps;
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+
+ matchbits = maskbits << (64 - src_bit - bps);
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ src = in[s] + src_offset + src_byte;
+ if (little_endian)
+ {
+ longbuff1 = (src[0] << 24) | (src[1] << 16) |
+ (src[2] << 8) | src[3];
+ longbuff2 = longbuff1;
+ }
+ else
+ {
+ longbuff1 = (src[3] << 24) | (src[2] << 16) |
+ (src[1] << 8) | src[0];
+ longbuff2 = longbuff1;
+ }
+
+ buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
+ buff1 = (buff3 & matchbits) << (src_bit);
+
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 32)
+ {
+ bytebuff1 = (uint8_t)(buff2 >> 56);
+ *dst++ = bytebuff1;
+ bytebuff2 = (uint8_t)(buff2 >> 48);
+ *dst++ = bytebuff2;
+ bytebuff3 = (uint8_t)(buff2 >> 40);
+ *dst++ = bytebuff3;
+ bytebuff4 = (uint8_t)(buff2 >> 32);
+ *dst++ = bytebuff4;
+ ready_bits -= 32;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
+ strcpy(action, "Flush");
+ }
+ else
+ { /* add another bps bits to the buffer */
+ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ strcpy(action, "Update");
+ }
+ ready_bits += bps;
+
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3" PRIu32 ", Col %3" PRIu32
+ ", Sample %" PRIu16 ", Src byte offset %3" PRIu32
+ " bit offset %2" PRIu32 " Dst offset %3td",
+ row + 1u, col + 1u, s, src_byte, src_bit,
+ dst - out);
+ dump_wide(dumpfile, format, "Match bits ", matchbits);
+ dump_data(dumpfile, format, "Src bits ", src, 8);
+ dump_wide(dumpfile, format, "Buff1 bits ", buff1);
+ dump_wide(dumpfile, format, "Buff2 bits ", buff2);
+ dump_info(dumpfile, format, "", "Ready bits: %d, %s",
+ ready_bits, action);
+ }
+ }
+ }
+ while (ready_bits > 0)
+ {
+ bytebuff1 = (buff2 >> 56);
+ *dst++ = bytebuff1;
+ buff2 = (buff2 << 8);
+ ready_bits -= 8;
+ }
+
+ if ((dumpfile != NULL) && (level == 3))
+ {
+ dump_info(dumpfile, format, "",
+ "Row %3d, Col %3d, Src byte offset %3d bit offset %2d "
+ "Dst offset %3d",
+ row + 1, col + 1, src_byte, src_bit, dst - out);
+
+ dump_wide(dumpfile, format, "Match bits ", matchbits);
+ dump_data(dumpfile, format, "Src bits ", src, 4);
+ dump_wide(dumpfile, format, "Buff1 bits ", buff1);
+ dump_wide(dumpfile, format, "Buff2 bits ", buff2);
+ dump_byte(dumpfile, format, "Write bits1", bytebuff1);
+ dump_byte(dumpfile, format, "Write bits2", bytebuff2);
+ dump_info(dumpfile, format, "", "Ready bits: %2d", ready_bits);
+ }
+
+ if ((dumpfile != NULL) && (level == 2))
+ {
+ dump_info(dumpfile, format, "combineSeparateTileSamples32bits",
+ "Output data");
+ dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
+ }
+ }
- for (row = 0; row < rows; row++)
- {
- ready_bits = 0;
- buff1 = buff2 = 0;
- dst = out + (row * dst_rowsize);
- src_offset = row * src_rowsize;
- for (col = 0; col < cols; col++)
- {
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = col * bps;
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
-
- matchbits = maskbits << (64 - src_bit - bps);
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- src = in[s] + src_offset + src_byte;
- if (little_endian)
- {
- longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
- longbuff2 = longbuff1;
- }
- else
- {
- longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
- longbuff2 = longbuff1;
- }
-
- buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
- buff1 = (buff3 & matchbits) << (src_bit);
-
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 32)
- {
- bytebuff1 = (uint8_t)(buff2 >> 56);
- *dst++ = bytebuff1;
- bytebuff2 = (uint8_t)(buff2 >> 48);
- *dst++ = bytebuff2;
- bytebuff3 = (uint8_t)(buff2 >> 40);
- *dst++ = bytebuff3;
- bytebuff4 = (uint8_t)(buff2 >> 32);
- *dst++ = bytebuff4;
- ready_bits -= 32;
-
- /* shift in new bits */
- buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
- strcpy (action, "Flush");
- }
- else
- { /* add another bps bits to the buffer */
- bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- strcpy (action, "Update");
- }
- ready_bits += bps;
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3"PRIu32", Col %3"PRIu32", Sample %"PRIu16", Src byte offset %3"PRIu32" bit offset %2"PRIu32" Dst offset %3td",
- row + 1u, col + 1u, s, src_byte, src_bit, dst - out);
- dump_wide (dumpfile, format, "Match bits ", matchbits);
- dump_data (dumpfile, format, "Src bits ", src, 8);
- dump_wide (dumpfile, format, "Buff1 bits ", buff1);
- dump_wide (dumpfile, format, "Buff2 bits ", buff2);
- dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action);
- }
- }
- }
- while (ready_bits > 0)
- {
- bytebuff1 = (buff2 >> 56);
- *dst++ = bytebuff1;
- buff2 = (buff2 << 8);
- ready_bits -= 8;
- }
-
- if ((dumpfile != NULL) && (level == 3))
- {
- dump_info (dumpfile, format, "",
- "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
- row + 1, col + 1, src_byte, src_bit, dst - out);
-
- dump_wide (dumpfile, format, "Match bits ", matchbits);
- dump_data (dumpfile, format, "Src bits ", src, 4);
- dump_wide (dumpfile, format, "Buff1 bits ", buff1);
- dump_wide (dumpfile, format, "Buff2 bits ", buff2);
- dump_byte (dumpfile, format, "Write bits1", bytebuff1);
- dump_byte (dumpfile, format, "Write bits2", bytebuff2);
- dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
- }
-
- if ((dumpfile != NULL) && (level == 2))
- {
- dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data");
- dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
- }
- }
-
- return (0);
- } /* end combineSeparateTileSamples32bits */
-
-
-static int readSeparateStripsIntoBuffer (TIFF *in, uint8_t *obuf, uint32_t length,
- uint32_t width, uint16_t spp,
- struct dump_opts *dump)
- {
- int i, bytes_per_sample, bytes_per_pixel, shift_width, result = 1;
- uint32_t j;
- tmsize_t bytes_read = 0;
- uint16_t bps = 0, planar;
- uint32_t nstrips;
- uint32_t strips_per_sample;
- uint32_t src_rowsize, dst_rowsize, rows_processed, rps;
- uint32_t rows_this_strip = 0;
- tsample_t s;
- tstrip_t strip;
- tsize_t scanlinesize = TIFFScanlineSize(in);
- tsize_t stripsize = TIFFStripSize(in);
- unsigned char *srcbuffs[MAX_SAMPLES];
- unsigned char *buff = NULL;
- unsigned char *dst = NULL;
-
- if (obuf == NULL)
- {
- TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument");
return (0);
+} /* end combineSeparateTileSamples32bits */
+
+static int readSeparateStripsIntoBuffer(TIFF *in, uint8_t *obuf,
+ uint32_t length, uint32_t width,
+ uint16_t spp, struct dump_opts *dump)
+{
+ int i, bytes_per_sample, bytes_per_pixel, shift_width, result = 1;
+ uint32_t j;
+ tmsize_t bytes_read = 0;
+ uint16_t bps = 0, planar;
+ uint32_t nstrips;
+ uint32_t strips_per_sample;
+ uint32_t src_rowsize, dst_rowsize, rows_processed, rps;
+ uint32_t rows_this_strip = 0;
+ tsample_t s;
+ tstrip_t strip;
+ tsize_t scanlinesize = TIFFScanlineSize(in);
+ tsize_t stripsize = TIFFStripSize(in);
+ unsigned char *srcbuffs[MAX_SAMPLES];
+ unsigned char *buff = NULL;
+ unsigned char *dst = NULL;
+
+ if (obuf == NULL)
+ {
+ TIFFError("readSeparateStripsIntoBuffer", "Invalid buffer argument");
+ return (0);
+ }
+
+ memset(srcbuffs, '\0', sizeof(srcbuffs));
+ TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
+ TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
+ TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
+ if (rps > length)
+ rps = length;
+
+ bytes_per_sample = (bps + 7) / 8;
+ bytes_per_pixel = ((bps * spp) + 7) / 8;
+ if (bytes_per_pixel < (bytes_per_sample + 1))
+ shift_width = bytes_per_pixel;
+ else
+ shift_width = bytes_per_sample + 1;
+
+ src_rowsize = ((bps * width) + 7) / 8;
+ dst_rowsize = ((bps * width * spp) + 7) / 8;
+ dst = obuf;
+
+ if ((dump->infile != NULL) && (dump->level == 3))
+ {
+ dump_info(dump->infile, dump->format, "",
+ "Image width %" PRIu32 ", length %" PRIu32
+ ", Scanline size, %4" PRId64 " bytes",
+ width, length, scanlinesize);
+ dump_info(dump->infile, dump->format, "",
+ "Bits per sample %" PRIu16 ", Samples per pixel %" PRIu16
+ ", Shift width %d",
+ bps, spp, shift_width);
}
- memset (srcbuffs, '\0', sizeof(srcbuffs));
- TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
- TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
- TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
- if (rps > length)
- rps = length;
-
- bytes_per_sample = (bps + 7) / 8;
- bytes_per_pixel = ((bps * spp) + 7) / 8;
- if (bytes_per_pixel < (bytes_per_sample + 1))
- shift_width = bytes_per_pixel;
- else
- shift_width = bytes_per_sample + 1;
-
- src_rowsize = ((bps * width) + 7) / 8;
- dst_rowsize = ((bps * width * spp) + 7) / 8;
- dst = obuf;
-
- if ((dump->infile != NULL) && (dump->level == 3))
- {
- dump_info (dump->infile, dump->format, "",
- "Image width %"PRIu32", length %"PRIu32", Scanline size, %4"PRId64" bytes",
- width, length, scanlinesize);
- dump_info (dump->infile, dump->format, "",
- "Bits per sample %"PRIu16", Samples per pixel %"PRIu16", Shift width %d",
- bps, spp, shift_width);
- }
-
- /* Libtiff seems to assume/require that data for separate planes are
- * written one complete plane after another and not interleaved in any way.
- * Multiple scanlines and possibly strips of the same plane must be
- * written before data for any other plane.
- */
- nstrips = TIFFNumberOfStrips(in);
- strips_per_sample = nstrips /spp;
-
- /* Add 3 padding bytes for combineSeparateSamples32bits */
- if( (size_t) stripsize > TIFF_TMSIZE_T_MAX - NUM_BUFF_OVERSIZE_BYTES)
- {
- TIFFError("readSeparateStripsIntoBuffer", "Integer overflow when calculating buffer size.");
- exit(EXIT_FAILURE);
- }
-
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- srcbuffs[s] = NULL;
- buff = limitMalloc(stripsize + NUM_BUFF_OVERSIZE_BYTES);
- if (!buff)
- {
- TIFFError ("readSeparateStripsIntoBuffer",
- "Unable to allocate strip read buffer for sample %"PRIu16, s);
- for (i = 0; i < s; i++)
- _TIFFfree (srcbuffs[i]);
- return 0;
- }
- buff[stripsize] = 0;
- buff[stripsize+1] = 0;
- buff[stripsize+2] = 0;
- srcbuffs[s] = buff;
- }
-
- rows_processed = 0;
- for (j = 0; (j < strips_per_sample) && (result == 1); j++)
+ /* Libtiff seems to assume/require that data for separate planes are
+ * written one complete plane after another and not interleaved in any way.
+ * Multiple scanlines and possibly strips of the same plane must be
+ * written before data for any other plane.
+ */
+ nstrips = TIFFNumberOfStrips(in);
+ strips_per_sample = nstrips / spp;
+
+ /* Add 3 padding bytes for combineSeparateSamples32bits */
+ if ((size_t)stripsize > TIFF_TMSIZE_T_MAX - NUM_BUFF_OVERSIZE_BYTES)
{
+ TIFFError("readSeparateStripsIntoBuffer",
+ "Integer overflow when calculating buffer size.");
+ exit(EXIT_FAILURE);
+ }
+
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
- {
- buff = srcbuffs[s];
- strip = (s * strips_per_sample) + j;
- bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize);
- rows_this_strip = (uint32_t)(bytes_read / src_rowsize);
- if (bytes_read < 0 && !ignore)
- {
- TIFFError(TIFFFileName(in),
- "Error, can't read strip %"PRIu32" for sample %"PRIu32,
- strip, s + 1u);
- result = 0;
- break;
+ {
+ srcbuffs[s] = NULL;
+ buff = limitMalloc(stripsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (!buff)
+ {
+ TIFFError(
+ "readSeparateStripsIntoBuffer",
+ "Unable to allocate strip read buffer for sample %" PRIu16, s);
+ for (i = 0; i < s; i++)
+ _TIFFfree(srcbuffs[i]);
+ return 0;
}
+ buff[stripsize] = 0;
+ buff[stripsize + 1] = 0;
+ buff[stripsize + 2] = 0;
+ srcbuffs[s] = buff;
+ }
+
+ rows_processed = 0;
+ for (j = 0; (j < strips_per_sample) && (result == 1); j++)
+ {
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ {
+ buff = srcbuffs[s];
+ strip = (s * strips_per_sample) + j;
+ bytes_read = TIFFReadEncodedStrip(in, strip, buff, stripsize);
+ rows_this_strip = (uint32_t)(bytes_read / src_rowsize);
+ if (bytes_read < 0 && !ignore)
+ {
+ TIFFError(TIFFFileName(in),
+ "Error, can't read strip %" PRIu32
+ " for sample %" PRIu32,
+ strip, s + 1u);
+ result = 0;
+ break;
+ }
#ifdef DEVELMODE
- TIFFError("", "Strip %2"PRIu32", read %5"PRId32" bytes for %4"PRIu32" scanlines, shift width %d",
- strip, bytes_read, rows_this_strip, shift_width);
+ TIFFError("",
+ "Strip %2" PRIu32 ", read %5" PRId32
+ " bytes for %4" PRIu32 " scanlines, shift width %d",
+ strip, bytes_read, rows_this_strip, shift_width);
#endif
- }
+ }
- if (rps > rows_this_strip)
- rps = rows_this_strip;
- dst = obuf + (dst_rowsize * rows_processed);
- if ((bps % 8) == 0)
- {
- if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps,
- spp, bps, dump->infile,
- dump->format, dump->level))
+ if (rps > rows_this_strip)
+ rps = rows_this_strip;
+ dst = obuf + (dst_rowsize * rows_processed);
+ if ((bps % 8) == 0)
{
- result = 0;
- break;
- }
- }
- else
- {
- switch (shift_width)
- {
- case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps,
- spp, bps, dump->infile,
- dump->format, dump->level))
- {
- result = 0;
- break;
- }
- break;
- case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps,
- spp, bps, dump->infile,
- dump->format, dump->level))
- {
- result = 0;
- break;
- }
- break;
- case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps,
- spp, bps, dump->infile,
- dump->format, dump->level))
- {
- result = 0;
- break;
- }
+ if (combineSeparateSamplesBytes(srcbuffs, dst, width, rps, spp, bps,
+ dump->infile, dump->format,
+ dump->level))
+ {
+ result = 0;
break;
- case 4:
- case 5:
- case 6:
- case 7:
- case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps,
- spp, bps, dump->infile,
- dump->format, dump->level))
- {
- result = 0;
- break;
- }
- break;
- default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %"PRIu16, bps);
- result = 0;
- break;
- }
- }
-
- if ((rows_processed + rps) > length)
- {
- rows_processed = length;
- rps = length - rows_processed;
- }
- else
- rows_processed += rps;
+ }
+ }
+ else
+ {
+ switch (shift_width)
+ {
+ case 1:
+ if (combineSeparateSamples8bits(srcbuffs, dst, width, rps,
+ spp, bps, dump->infile,
+ dump->format, dump->level))
+ {
+ result = 0;
+ break;
+ }
+ break;
+ case 2:
+ if (combineSeparateSamples16bits(srcbuffs, dst, width, rps,
+ spp, bps, dump->infile,
+ dump->format, dump->level))
+ {
+ result = 0;
+ break;
+ }
+ break;
+ case 3:
+ if (combineSeparateSamples24bits(srcbuffs, dst, width, rps,
+ spp, bps, dump->infile,
+ dump->format, dump->level))
+ {
+ result = 0;
+ break;
+ }
+ break;
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ if (combineSeparateSamples32bits(srcbuffs, dst, width, rps,
+ spp, bps, dump->infile,
+ dump->format, dump->level))
+ {
+ result = 0;
+ break;
+ }
+ break;
+ default:
+ TIFFError("readSeparateStripsIntoBuffer",
+ "Unsupported bit depth: %" PRIu16, bps);
+ result = 0;
+ break;
+ }
+ }
+
+ if ((rows_processed + rps) > length)
+ {
+ rows_processed = length;
+ rps = length - rows_processed;
+ }
+ else
+ rows_processed += rps;
}
- /* free any buffers allocated for each plane or scanline and
- * any temporary buffers
- */
- for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
+ /* free any buffers allocated for each plane or scanline and
+ * any temporary buffers
+ */
+ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
- buff = srcbuffs[s];
- if (buff != NULL)
- _TIFFfree(buff);
+ buff = srcbuffs[s];
+ if (buff != NULL)
+ _TIFFfree(buff);
}
- return (result);
- } /* end readSeparateStripsIntoBuffer */
+ return (result);
+} /* end readSeparateStripsIntoBuffer */
-static int
-get_page_geometry (char *name, struct pagedef *page)
- {
+static int get_page_geometry(char *name, struct pagedef *page)
+{
char *ptr;
unsigned int n;
for (ptr = name; *ptr; ptr++)
- *ptr = (char)tolower((int)*ptr);
+ *ptr = (char)tolower((int)*ptr);
for (n = 0; n < MAX_PAPERNAMES; n++)
- {
- if (strcmp(name, PaperTable[n].name) == 0)
+ {
+ if (strcmp(name, PaperTable[n].name) == 0)
{
- page->width = PaperTable[n].width;
- page->length = PaperTable[n].length;
- strncpy (page->name, PaperTable[n].name, 15);
- page->name[15] = '\0';
- return (0);
+ page->width = PaperTable[n].width;
+ page->length = PaperTable[n].length;
+ strncpy(page->name, PaperTable[n].name, 15);
+ page->name[15] = '\0';
+ return (0);
}
- }
-
- return (1);
- }
-
-
-static void
-initPageSetup (struct pagedef *page, struct pageseg *pagelist,
- struct buffinfo seg_buffs[])
- {
- int i;
-
- strcpy (page->name, "");
- page->mode = PAGE_MODE_NONE;
- page->res_unit = RESUNIT_NONE;
- page->hres = 0.0;
- page->vres = 0.0;
- page->width = 0.0;
- page->length = 0.0;
- page->hmargin = 0.0;
- page->vmargin = 0.0;
- page->rows = 0;
- page->cols = 0;
- page->orient = ORIENTATION_NONE;
-
- for (i = 0; i < MAX_SECTIONS; i++)
- {
- pagelist[i].x1 = (uint32_t)0;
- pagelist[i].x2 = (uint32_t)0;
- pagelist[i].y1 = (uint32_t)0;
- pagelist[i].y2 = (uint32_t)0;
- pagelist[i].buffsize = (uint32_t)0;
- pagelist[i].position = 0;
- pagelist[i].total = 0;
- }
-
- for (i = 0; i < MAX_OUTBUFFS; i++)
- {
- seg_buffs[i].size = 0;
- seg_buffs[i].buffer = NULL;
- }
- }
-
-static void
-initImageData (struct image_data *image)
- {
- image->xres = 0.0;
- image->yres = 0.0;
- image->width = 0;
- image->length = 0;
- image->res_unit = RESUNIT_NONE;
- image->bps = 0;
- image->spp = 0;
- image->planar = 0;
- image->photometric = 0;
- image->orientation = 0;
- image->compression = COMPRESSION_NONE;
- image->adjustments = 0;
- }
-
-static void
-initCropMasks (struct crop_mask *cps)
- {
- int i;
-
- cps->crop_mode = CROP_NONE;
- cps->res_unit = RESUNIT_NONE;
- cps->edge_ref = EDGE_TOP;
- cps->width = 0;
- cps->length = 0;
- for (i = 0; i < 4; i++)
- cps->margins[i] = 0.0;
- cps->bufftotal = (uint32_t)0;
- cps->combined_width = (uint32_t)0;
- cps->combined_length = (uint32_t)0;
- cps->rotation = (uint16_t)0;
- cps->photometric = INVERT_DATA_AND_TAG;
- cps->mirror = (uint16_t)0;
- cps->invert = (uint16_t)0;
- cps->zones = (uint32_t)0;
- cps->regions = (uint32_t)0;
- for (i = 0; i < MAX_REGIONS; i++)
- {
- cps->corners[i].X1 = 0.0;
- cps->corners[i].X2 = 0.0;
- cps->corners[i].Y1 = 0.0;
- cps->corners[i].Y2 = 0.0;
- cps->regionlist[i].x1 = 0;
- cps->regionlist[i].x2 = 0;
- cps->regionlist[i].y1 = 0;
- cps->regionlist[i].y2 = 0;
- cps->regionlist[i].width = 0;
- cps->regionlist[i].length = 0;
- cps->regionlist[i].buffsize = 0;
- cps->regionlist[i].buffptr = NULL;
- cps->zonelist[i].position = 0;
- cps->zonelist[i].total = 0;
- }
- cps->exp_mode = ONE_FILE_COMPOSITE;
- cps->img_mode = COMPOSITE_IMAGES;
- }
+ }
+
+ return (1);
+}
+
+static void initPageSetup(struct pagedef *page, struct pageseg *pagelist,
+ struct buffinfo seg_buffs[])
+{
+ int i;
+
+ strcpy(page->name, "");
+ page->mode = PAGE_MODE_NONE;
+ page->res_unit = RESUNIT_NONE;
+ page->hres = 0.0;
+ page->vres = 0.0;
+ page->width = 0.0;
+ page->length = 0.0;
+ page->hmargin = 0.0;
+ page->vmargin = 0.0;
+ page->rows = 0;
+ page->cols = 0;
+ page->orient = ORIENTATION_NONE;
+
+ for (i = 0; i < MAX_SECTIONS; i++)
+ {
+ pagelist[i].x1 = (uint32_t)0;
+ pagelist[i].x2 = (uint32_t)0;
+ pagelist[i].y1 = (uint32_t)0;
+ pagelist[i].y2 = (uint32_t)0;
+ pagelist[i].buffsize = (uint32_t)0;
+ pagelist[i].position = 0;
+ pagelist[i].total = 0;
+ }
+
+ for (i = 0; i < MAX_OUTBUFFS; i++)
+ {
+ seg_buffs[i].size = 0;
+ seg_buffs[i].buffer = NULL;
+ }
+}
+
+static void initImageData(struct image_data *image)
+{
+ image->xres = 0.0;
+ image->yres = 0.0;
+ image->width = 0;
+ image->length = 0;
+ image->res_unit = RESUNIT_NONE;
+ image->bps = 0;
+ image->spp = 0;
+ image->planar = 0;
+ image->photometric = 0;
+ image->orientation = 0;
+ image->compression = COMPRESSION_NONE;
+ image->adjustments = 0;
+}
+
+static void initCropMasks(struct crop_mask *cps)
+{
+ int i;
+
+ cps->crop_mode = CROP_NONE;
+ cps->res_unit = RESUNIT_NONE;
+ cps->edge_ref = EDGE_TOP;
+ cps->width = 0;
+ cps->length = 0;
+ for (i = 0; i < 4; i++)
+ cps->margins[i] = 0.0;
+ cps->bufftotal = (uint32_t)0;
+ cps->combined_width = (uint32_t)0;
+ cps->combined_length = (uint32_t)0;
+ cps->rotation = (uint16_t)0;
+ cps->photometric = INVERT_DATA_AND_TAG;
+ cps->mirror = (uint16_t)0;
+ cps->invert = (uint16_t)0;
+ cps->zones = (uint32_t)0;
+ cps->regions = (uint32_t)0;
+ for (i = 0; i < MAX_REGIONS; i++)
+ {
+ cps->corners[i].X1 = 0.0;
+ cps->corners[i].X2 = 0.0;
+ cps->corners[i].Y1 = 0.0;
+ cps->corners[i].Y2 = 0.0;
+ cps->regionlist[i].x1 = 0;
+ cps->regionlist[i].x2 = 0;
+ cps->regionlist[i].y1 = 0;
+ cps->regionlist[i].y2 = 0;
+ cps->regionlist[i].width = 0;
+ cps->regionlist[i].length = 0;
+ cps->regionlist[i].buffsize = 0;
+ cps->regionlist[i].buffptr = NULL;
+ cps->zonelist[i].position = 0;
+ cps->zonelist[i].total = 0;
+ }
+ cps->exp_mode = ONE_FILE_COMPOSITE;
+ cps->img_mode = COMPOSITE_IMAGES;
+}
static void initDumpOptions(struct dump_opts *dump)
- {
- dump->debug = 0;
- dump->format = DUMP_NONE;
- dump->level = 1;
- sprintf (dump->mode, "w");
- memset (dump->infilename, '\0', PATH_MAX + 1);
- memset (dump->outfilename, '\0',PATH_MAX + 1);
- dump->infile = NULL;
- dump->outfile = NULL;
- }
+{
+ dump->debug = 0;
+ dump->format = DUMP_NONE;
+ dump->level = 1;
+ sprintf(dump->mode, "w");
+ memset(dump->infilename, '\0', PATH_MAX + 1);
+ memset(dump->outfilename, '\0', PATH_MAX + 1);
+ dump->infile = NULL;
+ dump->outfile = NULL;
+}
/* Compute pixel offsets into the image for margins and fixed regions */
-static int
-computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image,
- struct offset *off)
- {
- double scale;
- float xres, yres;
- /* Values for these offsets are in pixels from start of image, not bytes,
- * and are indexed from zero to width - 1 or length - 1 */
- uint32_t tmargin, bmargin, lmargin, rmargin;
- uint32_t startx, endx; /* offsets of first and last columns to extract */
- uint32_t starty, endy; /* offsets of first and last row to extract */
- uint32_t width, length, crop_width, crop_length;
- uint32_t i, max_width, max_length, zwidth, zlength, buffsize;
- uint32_t x1, x2, y1, y2;
-
- if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER)
- {
- xres = 1.0;
- yres = 1.0;
- }
- else
- {
- if (((image->xres == 0) || (image->yres == 0)) &&
- (crop->res_unit != RESUNIT_NONE) &&
- ((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) ||
- (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)))
- {
- TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution");
- TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again");
- return (-1);
- }
- xres = image->xres;
- yres = image->yres;
- }
-
- /* Translate user units to image units */
- scale = 1.0;
- switch (crop->res_unit) {
- case RESUNIT_CENTIMETER:
- if (image->res_unit == RESUNIT_INCH)
- scale = 1.0/2.54;
- break;
- case RESUNIT_INCH:
- if (image->res_unit == RESUNIT_CENTIMETER)
- scale = 2.54;
- break;
- case RESUNIT_NONE: /* Dimensions in pixels */
- default:
- break;
- }
-
- if (crop->crop_mode & CROP_REGIONS)
- {
- max_width = max_length = 0;
- for (i = 0; i < crop->regions; i++)
- {
- if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER))
- {
- x1 = _TIFFClampDoubleToUInt32(crop->corners[i].X1 * scale * xres);
- x2 = _TIFFClampDoubleToUInt32(crop->corners[i].X2 * scale * xres);
- y1 = _TIFFClampDoubleToUInt32(crop->corners[i].Y1 * scale * yres);
- y2 = _TIFFClampDoubleToUInt32(crop->corners[i].Y2 * scale * yres);
- }
- else
- {
- x1 = _TIFFClampDoubleToUInt32(crop->corners[i].X1);
- x2 = _TIFFClampDoubleToUInt32(crop->corners[i].X2);
- y1 = _TIFFClampDoubleToUInt32(crop->corners[i].Y1);
- y2 = _TIFFClampDoubleToUInt32(crop->corners[i].Y2);
- }
- /* a) Region needs to be within image sizes 0.. width-1; 0..length-1
- * b) Corners are expected to be submitted as top-left to bottom-right.
- * Therefore, check that and reorder input.
- * (be aware x,y are already casted to (uint32_t) and avoid (0 - 1) )
- */
- uint32_t aux;
- if (x1 > x2) {
- aux = x1;
- x1 = x2;
- x2 = aux;
- }
- if (y1 > y2) {
- aux = y1;
- y1 = y2;
- y2 = aux;
- }
- if (x1 > image->width - 1)
- crop->regionlist[i].x1 = image->width - 1;
- else if (x1 > 0)
- crop->regionlist[i].x1 = (uint32_t)(x1 - 1);
-
- if (x2 > image->width - 1)
- crop->regionlist[i].x2 = image->width - 1;
- else if (x2 > 0)
- crop->regionlist[i].x2 = (uint32_t)(x2 - 1);
-
- zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
-
- if (y1 > image->length - 1)
- crop->regionlist[i].y1 = image->length - 1;
- else if (y1 > 0)
- crop->regionlist[i].y1 = (uint32_t)(y1 - 1);
-
- if (y2 > image->length - 1)
- crop->regionlist[i].y2 = image->length - 1;
- else if (y2 > 0)
- crop->regionlist[i].y2 = (uint32_t)(y2 - 1);
-
- zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
- if (zwidth > max_width)
- max_width = zwidth;
- if (zlength > max_length)
- max_length = zlength;
-
- buffsize = (uint32_t)
- (((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1));
-
- crop->regionlist[i].buffsize = buffsize;
- crop->bufftotal += buffsize;
- if (crop->img_mode == COMPOSITE_IMAGES)
+static int computeInputPixelOffsets(struct crop_mask *crop,
+ struct image_data *image,
+ struct offset *off)
+{
+ double scale;
+ float xres, yres;
+ /* Values for these offsets are in pixels from start of image, not bytes,
+ * and are indexed from zero to width - 1 or length - 1 */
+ uint32_t tmargin, bmargin, lmargin, rmargin;
+ uint32_t startx, endx; /* offsets of first and last columns to extract */
+ uint32_t starty, endy; /* offsets of first and last row to extract */
+ uint32_t width, length, crop_width, crop_length;
+ uint32_t i, max_width, max_length, zwidth, zlength, buffsize;
+ uint32_t x1, x2, y1, y2;
+
+ if (image->res_unit != RESUNIT_INCH &&
+ image->res_unit != RESUNIT_CENTIMETER)
+ {
+ xres = 1.0;
+ yres = 1.0;
+ }
+ else
+ {
+ if (((image->xres == 0) || (image->yres == 0)) &&
+ (crop->res_unit != RESUNIT_NONE) &&
+ ((crop->crop_mode & CROP_REGIONS) ||
+ (crop->crop_mode & CROP_MARGINS) ||
+ (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)))
{
- switch (crop->edge_ref)
- {
- case EDGE_LEFT:
- case EDGE_RIGHT:
- crop->combined_length = zlength;
- crop->combined_width += zwidth;
- break;
- case EDGE_BOTTOM:
- case EDGE_TOP: /* width from left, length from top */
- default:
- crop->combined_width = zwidth;
- crop->combined_length += zlength;
- break;
- }
- }
- }
- return (0);
- } /* crop_mode == CROP_REGIONS */
-
- /* Convert crop margins into offsets into image
- * Margins are expressed as pixel rows and columns, not bytes
- */
- if (crop->crop_mode & CROP_MARGINS)
+ TIFFError("computeInputPixelOffsets",
+ "Cannot compute margins or fixed size sections without "
+ "image resolution");
+ TIFFError("computeInputPixelOffsets",
+ "Specify units in pixels and try again");
+ return (-1);
+ }
+ xres = image->xres;
+ yres = image->yres;
+ }
+
+ /* Translate user units to image units */
+ scale = 1.0;
+ switch (crop->res_unit)
{
- if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
- { /* User has specified pixels as reference unit */
- tmargin = _TIFFClampDoubleToUInt32(crop->margins[0]);
- lmargin = _TIFFClampDoubleToUInt32(crop->margins[1]);
- bmargin = _TIFFClampDoubleToUInt32(crop->margins[2]);
- rmargin = _TIFFClampDoubleToUInt32(crop->margins[3]);
- }
+ case RESUNIT_CENTIMETER:
+ if (image->res_unit == RESUNIT_INCH)
+ scale = 1.0 / 2.54;
+ break;
+ case RESUNIT_INCH:
+ if (image->res_unit == RESUNIT_CENTIMETER)
+ scale = 2.54;
+ break;
+ case RESUNIT_NONE: /* Dimensions in pixels */
+ default:
+ break;
+ }
+
+ if (crop->crop_mode & CROP_REGIONS)
+ {
+ max_width = max_length = 0;
+ for (i = 0; i < crop->regions; i++)
+ {
+ if ((crop->res_unit == RESUNIT_INCH) ||
+ (crop->res_unit == RESUNIT_CENTIMETER))
+ {
+ x1 = _TIFFClampDoubleToUInt32(crop->corners[i].X1 * scale *
+ xres);
+ x2 = _TIFFClampDoubleToUInt32(crop->corners[i].X2 * scale *
+ xres);
+ y1 = _TIFFClampDoubleToUInt32(crop->corners[i].Y1 * scale *
+ yres);
+ y2 = _TIFFClampDoubleToUInt32(crop->corners[i].Y2 * scale *
+ yres);
+ }
+ else
+ {
+ x1 = _TIFFClampDoubleToUInt32(crop->corners[i].X1);
+ x2 = _TIFFClampDoubleToUInt32(crop->corners[i].X2);
+ y1 = _TIFFClampDoubleToUInt32(crop->corners[i].Y1);
+ y2 = _TIFFClampDoubleToUInt32(crop->corners[i].Y2);
+ }
+ /* a) Region needs to be within image sizes 0.. width-1; 0..length-1
+ * b) Corners are expected to be submitted as top-left to
+ * bottom-right. Therefore, check that and reorder input. (be aware
+ * x,y are already casted to (uint32_t) and avoid (0 - 1) )
+ */
+ uint32_t aux;
+ if (x1 > x2)
+ {
+ aux = x1;
+ x1 = x2;
+ x2 = aux;
+ }
+ if (y1 > y2)
+ {
+ aux = y1;
+ y1 = y2;
+ y2 = aux;
+ }
+ if (x1 > image->width - 1)
+ crop->regionlist[i].x1 = image->width - 1;
+ else if (x1 > 0)
+ crop->regionlist[i].x1 = (uint32_t)(x1 - 1);
+
+ if (x2 > image->width - 1)
+ crop->regionlist[i].x2 = image->width - 1;
+ else if (x2 > 0)
+ crop->regionlist[i].x2 = (uint32_t)(x2 - 1);
+
+ zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
+
+ if (y1 > image->length - 1)
+ crop->regionlist[i].y1 = image->length - 1;
+ else if (y1 > 0)
+ crop->regionlist[i].y1 = (uint32_t)(y1 - 1);
+
+ if (y2 > image->length - 1)
+ crop->regionlist[i].y2 = image->length - 1;
+ else if (y2 > 0)
+ crop->regionlist[i].y2 = (uint32_t)(y2 - 1);
+
+ zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
+ if (zwidth > max_width)
+ max_width = zwidth;
+ if (zlength > max_length)
+ max_length = zlength;
+
+ buffsize = (uint32_t)(((zwidth * image->bps * image->spp + 7) / 8) *
+ (zlength + 1));
+
+ crop->regionlist[i].buffsize = buffsize;
+ crop->bufftotal += buffsize;
+ if (crop->img_mode == COMPOSITE_IMAGES)
+ {
+ switch (crop->edge_ref)
+ {
+ case EDGE_LEFT:
+ case EDGE_RIGHT:
+ crop->combined_length = zlength;
+ crop->combined_width += zwidth;
+ break;
+ case EDGE_BOTTOM:
+ case EDGE_TOP: /* width from left, length from top */
+ default:
+ crop->combined_width = zwidth;
+ crop->combined_length += zlength;
+ break;
+ }
+ }
+ }
+ return (0);
+ } /* crop_mode == CROP_REGIONS */
+
+ /* Convert crop margins into offsets into image
+ * Margins are expressed as pixel rows and columns, not bytes
+ */
+ if (crop->crop_mode & CROP_MARGINS)
+ {
+ if (crop->res_unit != RESUNIT_INCH &&
+ crop->res_unit != RESUNIT_CENTIMETER)
+ { /* User has specified pixels as reference unit */
+ tmargin = _TIFFClampDoubleToUInt32(crop->margins[0]);
+ lmargin = _TIFFClampDoubleToUInt32(crop->margins[1]);
+ bmargin = _TIFFClampDoubleToUInt32(crop->margins[2]);
+ rmargin = _TIFFClampDoubleToUInt32(crop->margins[3]);
+ }
+ else
+ { /* inches or centimeters specified */
+ tmargin = _TIFFClampDoubleToUInt32(crop->margins[0] * scale * yres);
+ lmargin = _TIFFClampDoubleToUInt32(crop->margins[1] * scale * xres);
+ bmargin = _TIFFClampDoubleToUInt32(crop->margins[2] * scale * yres);
+ rmargin = _TIFFClampDoubleToUInt32(crop->margins[3] * scale * xres);
+ }
+
+ if ((lmargin + rmargin) > image->width)
+ {
+ TIFFError("computeInputPixelOffsets",
+ "Combined left and right margins exceed image width");
+ lmargin = (uint32_t)0;
+ rmargin = (uint32_t)0;
+ return (-1);
+ }
+ if ((tmargin + bmargin) > image->length)
+ {
+ TIFFError("computeInputPixelOffsets",
+ "Combined top and bottom margins exceed image length");
+ tmargin = (uint32_t)0;
+ bmargin = (uint32_t)0;
+ return (-1);
+ }
+ } /* crop_mode == CROP_MARGINS */
else
- { /* inches or centimeters specified */
- tmargin = _TIFFClampDoubleToUInt32(crop->margins[0] * scale * yres);
- lmargin = _TIFFClampDoubleToUInt32(crop->margins[1] * scale * xres);
- bmargin = _TIFFClampDoubleToUInt32(crop->margins[2] * scale * yres);
- rmargin = _TIFFClampDoubleToUInt32(crop->margins[3] * scale * xres);
- }
-
- if ((lmargin + rmargin) > image->width)
- {
- TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width");
- lmargin = (uint32_t) 0;
- rmargin = (uint32_t) 0;
- return (-1);
- }
- if ((tmargin + bmargin) > image->length)
- {
- TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length");
- tmargin = (uint32_t) 0;
- bmargin = (uint32_t) 0;
- return (-1);
- }
- } /* crop_mode == CROP_MARGINS */
- else
{ /* no margins requested */
- tmargin = (uint32_t) 0;
- lmargin = (uint32_t) 0;
- bmargin = (uint32_t) 0;
- rmargin = (uint32_t) 0;
+ tmargin = (uint32_t)0;
+ lmargin = (uint32_t)0;
+ bmargin = (uint32_t)0;
+ rmargin = (uint32_t)0;
}
- /* Width, height, and margins are expressed as pixel offsets into image */
- if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
+ /* Width, height, and margins are expressed as pixel offsets into image */
+ if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
{
- if (crop->crop_mode & CROP_WIDTH)
- width = _TIFFClampDoubleToUInt32(crop->width);
- else
- width = image->width - lmargin - rmargin;
+ if (crop->crop_mode & CROP_WIDTH)
+ width = _TIFFClampDoubleToUInt32(crop->width);
+ else
+ width = image->width - lmargin - rmargin;
- if (crop->crop_mode & CROP_LENGTH)
- length = _TIFFClampDoubleToUInt32(crop->length);
+ if (crop->crop_mode & CROP_LENGTH)
+ length = _TIFFClampDoubleToUInt32(crop->length);
+ else
+ length = image->length - tmargin - bmargin;
+ }
else
- length = image->length - tmargin - bmargin;
+ {
+ if (crop->crop_mode & CROP_WIDTH)
+ width = _TIFFClampDoubleToUInt32(crop->width * scale * image->xres);
+ else
+ width = image->width - lmargin - rmargin;
+
+ if (crop->crop_mode & CROP_LENGTH)
+ length =
+ _TIFFClampDoubleToUInt32(crop->length * scale * image->yres);
+ else
+ length = image->length - tmargin - bmargin;
}
- else
+
+ off->tmargin = tmargin;
+ off->bmargin = bmargin;
+ off->lmargin = lmargin;
+ off->rmargin = rmargin;
+
+ /* Calculate regions defined by margins, width, and length.
+ * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1,
+ * since they are used to compute offsets into buffers */
+ switch (crop->edge_ref)
{
- if (crop->crop_mode & CROP_WIDTH)
- width = _TIFFClampDoubleToUInt32(crop->width * scale * image->xres);
- else
- width = image->width - lmargin - rmargin;
+ case EDGE_BOTTOM:
+ startx = lmargin;
+ if ((startx + width) >= (image->width - rmargin))
+ endx = image->width - rmargin - 1;
+ else
+ endx = startx + width - 1;
+
+ endy = image->length - bmargin - 1;
+ if ((endy - length) <= tmargin)
+ starty = tmargin;
+ else
+ starty = endy - length + 1;
+ break;
+ case EDGE_RIGHT:
+ endx = image->width - rmargin - 1;
+ if ((endx - width) <= lmargin)
+ startx = lmargin;
+ else
+ startx = endx - width + 1;
+
+ starty = tmargin;
+ if ((starty + length) >= (image->length - bmargin))
+ endy = image->length - bmargin - 1;
+ else
+ endy = starty + length - 1;
+ break;
+ case EDGE_TOP: /* width from left, length from top */
+ case EDGE_LEFT:
+ default:
+ startx = lmargin;
+ if ((startx + width) >= (image->width - rmargin))
+ endx = image->width - rmargin - 1;
+ else
+ endx = startx + width - 1;
+
+ starty = tmargin;
+ if ((starty + length) >= (image->length - bmargin))
+ endy = image->length - bmargin - 1;
+ else
+ endy = starty + length - 1;
+ break;
+ }
+ off->startx = startx;
+ off->starty = starty;
+ off->endx = endx;
+ off->endy = endy;
- if (crop->crop_mode & CROP_LENGTH)
- length = _TIFFClampDoubleToUInt32(crop->length * scale * image->yres);
- else
- length = image->length - tmargin - bmargin;
- }
-
- off->tmargin = tmargin;
- off->bmargin = bmargin;
- off->lmargin = lmargin;
- off->rmargin = rmargin;
-
- /* Calculate regions defined by margins, width, and length.
- * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1,
- * since they are used to compute offsets into buffers */
- switch (crop->edge_ref) {
- case EDGE_BOTTOM:
- startx = lmargin;
- if ((startx + width) >= (image->width - rmargin))
- endx = image->width - rmargin - 1;
- else
- endx = startx + width - 1;
-
- endy = image->length - bmargin - 1;
- if ((endy - length) <= tmargin)
- starty = tmargin;
- else
- starty = endy - length + 1;
- break;
- case EDGE_RIGHT:
- endx = image->width - rmargin - 1;
- if ((endx - width) <= lmargin)
- startx = lmargin;
- else
- startx = endx - width + 1;
-
- starty = tmargin;
- if ((starty + length) >= (image->length - bmargin))
- endy = image->length - bmargin - 1;
- else
- endy = starty + length - 1;
- break;
- case EDGE_TOP: /* width from left, length from top */
- case EDGE_LEFT:
- default:
- startx = lmargin;
- if ((startx + width) >= (image->width - rmargin))
- endx = image->width - rmargin - 1;
- else
- endx = startx + width - 1;
-
- starty = tmargin;
- if ((starty + length) >= (image->length - bmargin))
- endy = image->length - bmargin - 1;
- else
- endy = starty + length - 1;
- break;
- }
- off->startx = startx;
- off->starty = starty;
- off->endx = endx;
- off->endy = endy;
-
- if (endx + 1 <= startx)
- {
- TIFFError("computeInputPixelOffsets",
- "Invalid left/right margins and /or image crop width requested");
- return (-1);
- }
- crop_width = endx - startx + 1;
- if (crop_width > image->width)
- crop_width = image->width;
-
- if (endy + 1 <= starty)
- {
- TIFFError("computeInputPixelOffsets",
- "Invalid top/bottom margins and /or image crop length requested");
- return (-1);
- }
- crop_length = endy - starty + 1;
- if (crop_length > image->length)
- crop_length = image->length;
-
- off->crop_width = crop_width;
- off->crop_length = crop_length;
-
- return (0);
- } /* end computeInputPixelOffsets */
-
-/*
- * Translate crop options into pixel offsets for one or more regions of the image.
- * Options are applied in this order: margins, specific width and length, zones,
- * but all are optional. Margins are relative to each edge. Width, length and
- * zones are relative to the specified reference edge. Zones are expressed as
- * X:Y where X is the ordinal value in a set of Y equal sized portions. eg.
+ if (endx + 1 <= startx)
+ {
+ TIFFError(
+ "computeInputPixelOffsets",
+ "Invalid left/right margins and /or image crop width requested");
+ return (-1);
+ }
+ crop_width = endx - startx + 1;
+ if (crop_width > image->width)
+ crop_width = image->width;
+
+ if (endy + 1 <= starty)
+ {
+ TIFFError(
+ "computeInputPixelOffsets",
+ "Invalid top/bottom margins and /or image crop length requested");
+ return (-1);
+ }
+ crop_length = endy - starty + 1;
+ if (crop_length > image->length)
+ crop_length = image->length;
+
+ off->crop_width = crop_width;
+ off->crop_length = crop_length;
+
+ return (0);
+} /* end computeInputPixelOffsets */
+
+/*
+ * Translate crop options into pixel offsets for one or more regions of the
+ * image. Options are applied in this order: margins, specific width and length,
+ * zones, but all are optional. Margins are relative to each edge. Width, length
+ * and zones are relative to the specified reference edge. Zones are expressed
+ * as X:Y where X is the ordinal value in a set of Y equal sized portions. eg.
* 2:3 would indicate the middle third of the region qualified by margins and
* any explicit width and length specified. Regions are specified by coordinates
* of the top left and lower right corners with range 1 to width or height.
*/
-static int
-getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump)
- {
- struct offset offsets;
- int i;
- uint32_t uaux;
- uint32_t seg, total, need_buff = 0;
- uint32_t buffsize;
- uint32_t zwidth, zlength;
-
- memset(&offsets, '\0', sizeof(struct offset));
- crop->bufftotal = 0;
- crop->combined_width = (uint32_t)0;
- crop->combined_length = (uint32_t)0;
- crop->selections = 0;
-
- /* Compute pixel offsets if margins or fixed width or length specified */
- if ((crop->crop_mode & CROP_MARGINS) ||
- (crop->crop_mode & CROP_REGIONS) ||
- (crop->crop_mode & CROP_LENGTH) ||
- (crop->crop_mode & CROP_WIDTH))
- {
- if (computeInputPixelOffsets(crop, image, &offsets))
- {
- TIFFError ("getCropOffsets", "Unable to compute crop margins");
- return (-1);
- }
- need_buff = TRUE;
- crop->selections = crop->regions;
- /* Regions are only calculated from top and left edges with no margins */
- if (crop->crop_mode & CROP_REGIONS)
- return (0);
+static int getCropOffsets(struct image_data *image, struct crop_mask *crop,
+ struct dump_opts *dump)
+{
+ struct offset offsets;
+ int i;
+ uint32_t uaux;
+ uint32_t seg, total, need_buff = 0;
+ uint32_t buffsize;
+ uint32_t zwidth, zlength;
+
+ memset(&offsets, '\0', sizeof(struct offset));
+ crop->bufftotal = 0;
+ crop->combined_width = (uint32_t)0;
+ crop->combined_length = (uint32_t)0;
+ crop->selections = 0;
+
+ /* Compute pixel offsets if margins or fixed width or length specified */
+ if ((crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_REGIONS) ||
+ (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH))
+ {
+ if (computeInputPixelOffsets(crop, image, &offsets))
+ {
+ TIFFError("getCropOffsets", "Unable to compute crop margins");
+ return (-1);
+ }
+ need_buff = TRUE;
+ crop->selections = crop->regions;
+ /* Regions are only calculated from top and left edges with no margins
+ */
+ if (crop->crop_mode & CROP_REGIONS)
+ return (0);
}
- else
+ else
{ /* cropped area is the full image */
- offsets.tmargin = 0;
- offsets.lmargin = 0;
- offsets.bmargin = 0;
- offsets.rmargin = 0;
- offsets.crop_width = image->width;
- offsets.crop_length = image->length;
- offsets.startx = 0;
- offsets.endx = image->width - 1;
- offsets.starty = 0;
- offsets.endy = image->length - 1;
- need_buff = FALSE;
- }
-
- if (dump->outfile != NULL)
- {
- dump_info (dump->outfile, dump->format, "", "Margins: Top: %"PRIu32" Left: %"PRIu32" Bottom: %"PRIu32" Right: %"PRIu32,
- offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin);
- dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6"PRIu32" Length: %6"PRIu32,
- offsets.crop_width, offsets.crop_length);
- }
-
- if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */
- {
- if (need_buff == FALSE) /* No margins or fixed width or length areas */
- {
- crop->selections = 0;
- crop->combined_width = image->width;
- crop->combined_length = image->length;
- return (0);
- }
- else
- {
- /* Use one region for margins and fixed width or length areas
- * even though it was not formally declared as a region.
- */
- crop->selections = 1;
- crop->zones = 1;
- crop->zonelist[0].total = 1;
- crop->zonelist[0].position = 1;
- }
- }
- else
- crop->selections = crop->zones;
-
- /* Initialize regions iterator i */
- i = 0;
- for (int j = 0; j < crop->zones; j++)
- {
- seg = crop->zonelist[j].position;
- total = crop->zonelist[j].total;
-
- /* check for not allowed zone cases like 0:0; 4:3; or negative ones etc. and skip that input */
- if (crop->zonelist[j].position < 0 || crop->zonelist[j].total < 0) {
- TIFFError("getCropOffsets", "Negative crop zone values %d:%d are not allowed, thus skipped.", crop->zonelist[j].position, crop->zonelist[j].total);
- continue;
- }
- if (seg == 0 || total == 0 || seg > total) {
- TIFFError("getCropOffsets", "Crop zone %d:%d is out of specification, thus skipped.", seg, total);
- continue;
- }
-
- switch (crop->edge_ref)
- {
- case EDGE_LEFT: /* zones from left to right, length from top */
- zlength = offsets.crop_length;
- crop->regionlist[i].y1 = offsets.starty;
- crop->regionlist[i].y2 = offsets.endy;
-
- crop->regionlist[i].x1 = offsets.startx +
- (uint32_t)(offsets.crop_width * 1.0 * (seg - 1) / total);
- /* FAULT: IMHO in the old code here, the calculation of x2 was based on wrong assumtions. The whole image was assumed and 'endy' and 'starty' are not respected anymore!*/
- /* NEW PROPOSED Code: Assumption: offsets are within image with top left corner as origin (0,0) and 'start' <= 'end'. */
- if (crop->regionlist[i].x1 > offsets.endx) {
- crop->regionlist[i].x1 = offsets.endx;
- } else if (crop->regionlist[i].x1 >= image->width) {
- crop->regionlist[i].x1 = image->width - 1;
- }
-
- crop->regionlist[i].x2 = offsets.startx + (uint32_t)(offsets.crop_width * 1.0 * seg / total);
- if (crop->regionlist[i].x2 > 0) crop->regionlist[i].x2 = crop->regionlist[i].x2 - 1;
- if (crop->regionlist[i].x2 < crop->regionlist[i].x1) {
- crop->regionlist[i].x2 = crop->regionlist[i].x1;
- } else if (crop->regionlist[i].x2 > offsets.endx) {
- crop->regionlist[i].x2 = offsets.endx;
- } else if (crop->regionlist[i].x2 >= image->width) {
- crop->regionlist[i].x2 = image->width - 1;
- }
- zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
-
- /* This is passed to extractCropZone or extractCompositeZones */
- crop->combined_length = (uint32_t)zlength;
- if (crop->exp_mode == COMPOSITE_IMAGES)
- crop->combined_width += (uint32_t)zwidth;
- else
- crop->combined_width = (uint32_t)zwidth;
- break;
- case EDGE_BOTTOM: /* width from left, zones from bottom to top */
- zwidth = offsets.crop_width;
- crop->regionlist[i].x1 = offsets.startx;
- crop->regionlist[i].x2 = offsets.endx;
-
- /* FAULT: IMHO in the old code here, the calculation of y1/y2 was based on wrong assumtions. The whole image was assumed and 'endy' and 'starty' are not respected anymore!*/
- /* NEW PROPOSED Code: Assumption: offsets are within image with top left corner as origin (0,0) and 'start' <= 'end'. */
- uaux = (uint32_t)(offsets.crop_length * 1.0 * seg / total);
- if (uaux <= offsets.endy + 1) {
- crop->regionlist[i].y1 = offsets.endy - uaux + 1;
- } else {
- crop->regionlist[i].y1 = 0;
- }
- if (crop->regionlist[i].y1 < offsets.starty) {
- crop->regionlist[i].y1 = offsets.starty;
- }
-
- uaux = (uint32_t)(offsets.crop_length * 1.0 * (seg - 1) / total);
- if (uaux <= offsets.endy) {
- crop->regionlist[i].y2 = offsets.endy - uaux;
- } else {
- crop->regionlist[i].y2 = 0;
- }
- if (crop->regionlist[i].y2 < offsets.starty) {
- crop->regionlist[i].y2 = offsets.starty;
- }
- zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
-
- /* This is passed to extractCropZone or extractCompositeZones */
- if (crop->exp_mode == COMPOSITE_IMAGES)
- crop->combined_length += (uint32_t)zlength;
- else
- crop->combined_length = (uint32_t)zlength;
- crop->combined_width = (uint32_t)zwidth;
- break;
- case EDGE_RIGHT: /* zones from right to left, length from top */
- zlength = offsets.crop_length;
- crop->regionlist[i].y1 = offsets.starty;
- crop->regionlist[i].y2 = offsets.endy;
-
- crop->regionlist[i].x1 = offsets.startx +
- (uint32_t)(offsets.crop_width * (total - seg) * 1.0 / total);
- /* FAULT: IMHO from here on, the calculation of y2 are based on wrong assumtions. The whole image is assumed and 'endy' and 'starty' are not respected anymore!*/
- /* NEW PROPOSED Code: Assumption: offsets are within image with top left corner as origin (0,0) and 'start' <= 'end'. */
- uaux = (uint32_t)(offsets.crop_width * 1.0 * seg / total);
- if (uaux <= offsets.endx + 1) {
- crop->regionlist[i].x1 = offsets.endx - uaux + 1;
- } else {
- crop->regionlist[i].x1 = 0;
- }
- if (crop->regionlist[i].x1 < offsets.startx) {
- crop->regionlist[i].x1 = offsets.startx;
- }
-
- uaux = (uint32_t)(offsets.crop_width * 1.0 * (seg - 1) / total);
- if (uaux <= offsets.endx) {
- crop->regionlist[i].x2 = offsets.endx - uaux;
- } else {
- crop->regionlist[i].x2 = 0;
- }
- if (crop->regionlist[i].x2 < offsets.startx) {
- crop->regionlist[i].x2 = offsets.startx;
- }
- zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
-
- /* This is passed to extractCropZone or extractCompositeZones */
- crop->combined_length = (uint32_t)zlength;
- if (crop->exp_mode == COMPOSITE_IMAGES)
- crop->combined_width += (uint32_t)zwidth;
- else
- crop->combined_width = (uint32_t)zwidth;
- break;
- case EDGE_TOP: /* width from left, zones from top to bottom */
- default:
- zwidth = offsets.crop_width;
- crop->regionlist[i].x1 = offsets.startx;
- crop->regionlist[i].x2 = offsets.endx;
-
- crop->regionlist[i].y1 = offsets.starty + (uint32_t)(offsets.crop_length * 1.0 * (seg - 1) / total);
- if (crop->regionlist[i].y1 > offsets.endy) {
- crop->regionlist[i].y1 = offsets.endy;
- } else if (crop->regionlist[i].y1 >= image->length) {
- crop->regionlist[i].y1 = image->length - 1;
- }
-
- /* FAULT: IMHO from here on, the calculation of y2 are based on wrong assumtions. The whole image is assumed and 'endy' and 'starty' are not respected anymore!*/
- /* OLD Code:
- test = offsets.starty + (uint32_t)(offsets.crop_length * 1.0 * seg / total);
- if (test < 1 )
- crop->regionlist[i].y2 = 0;
- else
- {
- if (test > (int32_t)(image->length - 1))
- crop->regionlist[i].y2 = image->length - 1;
- else
- crop->regionlist[i].y2 = test - 1;
- }
- */
- /* NEW PROPOSED Code: Assumption: offsets are within image with top left corner as origin (0,0) and 'start' <= 'end'. */
- crop->regionlist[i].y2 = offsets.starty + (uint32_t)(offsets.crop_length * 1.0 * seg / total);
- if (crop->regionlist[i].y2 > 0)crop->regionlist[i].y2 = crop->regionlist[i].y2 - 1;
- if (crop->regionlist[i].y2 < crop->regionlist[i].y1) {
- crop->regionlist[i].y2 = crop->regionlist[i].y1;
- } else if (crop->regionlist[i].y2 > offsets.endy) {
- crop->regionlist[i].y2 = offsets.endy;
- } else if (crop->regionlist[i].y2 >= image->length) {
- crop->regionlist[i].y2 = image->length - 1;
- }
-
- zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
-
- /* This is passed to extractCropZone or extractCompositeZones */
- if (crop->exp_mode == COMPOSITE_IMAGES)
- crop->combined_length += (uint32_t)zlength;
- else
- crop->combined_length = (uint32_t)zlength;
- crop->combined_width = (uint32_t)zwidth;
- break;
- } /* end switch statement */
-
- buffsize = (uint32_t)
- ((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1));
- crop->regionlist[i].width = (uint32_t) zwidth;
- crop->regionlist[i].length = (uint32_t) zlength;
- crop->regionlist[i].buffsize = buffsize;
- crop->bufftotal += buffsize;
-
-
- if (dump->outfile != NULL)
- dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4"PRIu32", length: %4"PRIu32", x1: %4"PRIu32" x2: %4"PRIu32" y1: %4"PRIu32" y2: %4"PRIu32,
- i + 1, zwidth, zlength,
- crop->regionlist[i].x1, crop->regionlist[i].x2,
- crop->regionlist[i].y1, crop->regionlist[i].y2);
- /* increment regions iterator */
- i++;
+ offsets.tmargin = 0;
+ offsets.lmargin = 0;
+ offsets.bmargin = 0;
+ offsets.rmargin = 0;
+ offsets.crop_width = image->width;
+ offsets.crop_length = image->length;
+ offsets.startx = 0;
+ offsets.endx = image->width - 1;
+ offsets.starty = 0;
+ offsets.endy = image->length - 1;
+ need_buff = FALSE;
+ }
+
+ if (dump->outfile != NULL)
+ {
+ dump_info(dump->outfile, dump->format, "",
+ "Margins: Top: %" PRIu32 " Left: %" PRIu32
+ " Bottom: %" PRIu32 " Right: %" PRIu32,
+ offsets.tmargin, offsets.lmargin, offsets.bmargin,
+ offsets.rmargin);
+ dump_info(dump->outfile, dump->format, "",
+ "Crop region within margins: Adjusted Width: %6" PRIu32
+ " Length: %6" PRIu32,
+ offsets.crop_width, offsets.crop_length);
+ }
+
+ if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */
+ {
+ if (need_buff == FALSE) /* No margins or fixed width or length areas */
+ {
+ crop->selections = 0;
+ crop->combined_width = image->width;
+ crop->combined_length = image->length;
+ return (0);
+ }
+ else
+ {
+ /* Use one region for margins and fixed width or length areas
+ * even though it was not formally declared as a region.
+ */
+ crop->selections = 1;
+ crop->zones = 1;
+ crop->zonelist[0].total = 1;
+ crop->zonelist[0].position = 1;
+ }
+ }
+ else
+ crop->selections = crop->zones;
+
+ /* Initialize regions iterator i */
+ i = 0;
+ for (int j = 0; j < crop->zones; j++)
+ {
+ seg = crop->zonelist[j].position;
+ total = crop->zonelist[j].total;
+
+ /* check for not allowed zone cases like 0:0; 4:3; or negative ones etc.
+ * and skip that input */
+ if (crop->zonelist[j].position < 0 || crop->zonelist[j].total < 0)
+ {
+ TIFFError("getCropOffsets",
+ "Negative crop zone values %d:%d are not allowed, thus "
+ "skipped.",
+ crop->zonelist[j].position, crop->zonelist[j].total);
+ continue;
+ }
+ if (seg == 0 || total == 0 || seg > total)
+ {
+ TIFFError("getCropOffsets",
+ "Crop zone %d:%d is out of specification, thus skipped.",
+ seg, total);
+ continue;
+ }
+
+ switch (crop->edge_ref)
+ {
+ case EDGE_LEFT: /* zones from left to right, length from top */
+ zlength = offsets.crop_length;
+ crop->regionlist[i].y1 = offsets.starty;
+ crop->regionlist[i].y2 = offsets.endy;
+
+ crop->regionlist[i].x1 =
+ offsets.startx +
+ (uint32_t)(offsets.crop_width * 1.0 * (seg - 1) / total);
+ /* FAULT: IMHO in the old code here, the calculation of x2 was
+ * based on wrong assumtions. The whole image was assumed and
+ * 'endy' and 'starty' are not respected anymore!*/
+ /* NEW PROPOSED Code: Assumption: offsets are within image with
+ * top left corner as origin (0,0) and 'start' <= 'end'. */
+ if (crop->regionlist[i].x1 > offsets.endx)
+ {
+ crop->regionlist[i].x1 = offsets.endx;
+ }
+ else if (crop->regionlist[i].x1 >= image->width)
+ {
+ crop->regionlist[i].x1 = image->width - 1;
+ }
+
+ crop->regionlist[i].x2 =
+ offsets.startx +
+ (uint32_t)(offsets.crop_width * 1.0 * seg / total);
+ if (crop->regionlist[i].x2 > 0)
+ crop->regionlist[i].x2 = crop->regionlist[i].x2 - 1;
+ if (crop->regionlist[i].x2 < crop->regionlist[i].x1)
+ {
+ crop->regionlist[i].x2 = crop->regionlist[i].x1;
+ }
+ else if (crop->regionlist[i].x2 > offsets.endx)
+ {
+ crop->regionlist[i].x2 = offsets.endx;
+ }
+ else if (crop->regionlist[i].x2 >= image->width)
+ {
+ crop->regionlist[i].x2 = image->width - 1;
+ }
+ zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
+
+ /* This is passed to extractCropZone or extractCompositeZones */
+ crop->combined_length = (uint32_t)zlength;
+ if (crop->exp_mode == COMPOSITE_IMAGES)
+ crop->combined_width += (uint32_t)zwidth;
+ else
+ crop->combined_width = (uint32_t)zwidth;
+ break;
+ case EDGE_BOTTOM: /* width from left, zones from bottom to top */
+ zwidth = offsets.crop_width;
+ crop->regionlist[i].x1 = offsets.startx;
+ crop->regionlist[i].x2 = offsets.endx;
+
+ /* FAULT: IMHO in the old code here, the calculation of y1/y2
+ * was based on wrong assumtions. The whole image was assumed
+ * and 'endy' and 'starty' are not respected anymore!*/
+ /* NEW PROPOSED Code: Assumption: offsets are within image with
+ * top left corner as origin (0,0) and 'start' <= 'end'. */
+ uaux = (uint32_t)(offsets.crop_length * 1.0 * seg / total);
+ if (uaux <= offsets.endy + 1)
+ {
+ crop->regionlist[i].y1 = offsets.endy - uaux + 1;
+ }
+ else
+ {
+ crop->regionlist[i].y1 = 0;
+ }
+ if (crop->regionlist[i].y1 < offsets.starty)
+ {
+ crop->regionlist[i].y1 = offsets.starty;
+ }
+
+ uaux =
+ (uint32_t)(offsets.crop_length * 1.0 * (seg - 1) / total);
+ if (uaux <= offsets.endy)
+ {
+ crop->regionlist[i].y2 = offsets.endy - uaux;
+ }
+ else
+ {
+ crop->regionlist[i].y2 = 0;
+ }
+ if (crop->regionlist[i].y2 < offsets.starty)
+ {
+ crop->regionlist[i].y2 = offsets.starty;
+ }
+ zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
+
+ /* This is passed to extractCropZone or extractCompositeZones */
+ if (crop->exp_mode == COMPOSITE_IMAGES)
+ crop->combined_length += (uint32_t)zlength;
+ else
+ crop->combined_length = (uint32_t)zlength;
+ crop->combined_width = (uint32_t)zwidth;
+ break;
+ case EDGE_RIGHT: /* zones from right to left, length from top */
+ zlength = offsets.crop_length;
+ crop->regionlist[i].y1 = offsets.starty;
+ crop->regionlist[i].y2 = offsets.endy;
+
+ crop->regionlist[i].x1 =
+ offsets.startx + (uint32_t)(offsets.crop_width *
+ (total - seg) * 1.0 / total);
+ /* FAULT: IMHO from here on, the calculation of y2 are based on
+ * wrong assumtions. The whole image is assumed and 'endy' and
+ * 'starty' are not respected anymore!*/
+ /* NEW PROPOSED Code: Assumption: offsets are within image with
+ * top left corner as origin (0,0) and 'start' <= 'end'. */
+ uaux = (uint32_t)(offsets.crop_width * 1.0 * seg / total);
+ if (uaux <= offsets.endx + 1)
+ {
+ crop->regionlist[i].x1 = offsets.endx - uaux + 1;
+ }
+ else
+ {
+ crop->regionlist[i].x1 = 0;
+ }
+ if (crop->regionlist[i].x1 < offsets.startx)
+ {
+ crop->regionlist[i].x1 = offsets.startx;
+ }
+
+ uaux = (uint32_t)(offsets.crop_width * 1.0 * (seg - 1) / total);
+ if (uaux <= offsets.endx)
+ {
+ crop->regionlist[i].x2 = offsets.endx - uaux;
+ }
+ else
+ {
+ crop->regionlist[i].x2 = 0;
+ }
+ if (crop->regionlist[i].x2 < offsets.startx)
+ {
+ crop->regionlist[i].x2 = offsets.startx;
+ }
+ zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
+
+ /* This is passed to extractCropZone or extractCompositeZones */
+ crop->combined_length = (uint32_t)zlength;
+ if (crop->exp_mode == COMPOSITE_IMAGES)
+ crop->combined_width += (uint32_t)zwidth;
+ else
+ crop->combined_width = (uint32_t)zwidth;
+ break;
+ case EDGE_TOP: /* width from left, zones from top to bottom */
+ default:
+ zwidth = offsets.crop_width;
+ crop->regionlist[i].x1 = offsets.startx;
+ crop->regionlist[i].x2 = offsets.endx;
+
+ crop->regionlist[i].y1 =
+ offsets.starty +
+ (uint32_t)(offsets.crop_length * 1.0 * (seg - 1) / total);
+ if (crop->regionlist[i].y1 > offsets.endy)
+ {
+ crop->regionlist[i].y1 = offsets.endy;
+ }
+ else if (crop->regionlist[i].y1 >= image->length)
+ {
+ crop->regionlist[i].y1 = image->length - 1;
+ }
+
+ /* FAULT: IMHO from here on, the calculation of y2 are based on
+ * wrong assumtions. The whole image is assumed and 'endy' and
+ * 'starty' are not respected anymore!*/
+ /* OLD Code:
+ test = offsets.starty + (uint32_t)(offsets.crop_length * 1.0 *
+ seg / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else
+ {
+ if (test > (int32_t)(image->length - 1))
+ crop->regionlist[i].y2 = image->length - 1;
+ else
+ crop->regionlist[i].y2 = test - 1;
+ }
+ */
+ /* NEW PROPOSED Code: Assumption: offsets are within image with
+ * top left corner as origin (0,0) and 'start' <= 'end'. */
+ crop->regionlist[i].y2 =
+ offsets.starty +
+ (uint32_t)(offsets.crop_length * 1.0 * seg / total);
+ if (crop->regionlist[i].y2 > 0)
+ crop->regionlist[i].y2 = crop->regionlist[i].y2 - 1;
+ if (crop->regionlist[i].y2 < crop->regionlist[i].y1)
+ {
+ crop->regionlist[i].y2 = crop->regionlist[i].y1;
+ }
+ else if (crop->regionlist[i].y2 > offsets.endy)
+ {
+ crop->regionlist[i].y2 = offsets.endy;
+ }
+ else if (crop->regionlist[i].y2 >= image->length)
+ {
+ crop->regionlist[i].y2 = image->length - 1;
+ }
+
+ zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
+
+ /* This is passed to extractCropZone or extractCompositeZones */
+ if (crop->exp_mode == COMPOSITE_IMAGES)
+ crop->combined_length += (uint32_t)zlength;
+ else
+ crop->combined_length = (uint32_t)zlength;
+ crop->combined_width = (uint32_t)zwidth;
+ break;
+ } /* end switch statement */
+
+ buffsize = (uint32_t)((((zwidth * image->bps * image->spp) + 7) / 8) *
+ (zlength + 1));
+ crop->regionlist[i].width = (uint32_t)zwidth;
+ crop->regionlist[i].length = (uint32_t)zlength;
+ crop->regionlist[i].buffsize = buffsize;
+ crop->bufftotal += buffsize;
+
+ if (dump->outfile != NULL)
+ dump_info(dump->outfile, dump->format, "",
+ "Zone %d, width: %4" PRIu32 ", length: %4" PRIu32
+ ", x1: %4" PRIu32 " x2: %4" PRIu32 " y1: %4" PRIu32
+ " y2: %4" PRIu32,
+ i + 1, zwidth, zlength, crop->regionlist[i].x1,
+ crop->regionlist[i].x2, crop->regionlist[i].y1,
+ crop->regionlist[i].y2);
+ /* increment regions iterator */
+ i++;
}
/* set number of generated regions out of given zones */
crop->selections = i;
- return (0);
- } /* end getCropOffsets */
-
-
-static int
-computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image,
- struct pagedef *page, struct pageseg *sections,
- struct dump_opts* dump)
- {
- double scale;
- double pwidth, plength; /* Output page width and length in user units*/
- uint32_t iwidth, ilength; /* Input image width and length in pixels*/
- uint32_t owidth, olength; /* Output image width and length in pixels*/
- uint32_t orows, ocols; /* rows and cols for output */
- uint32_t hmargin, vmargin; /* Horizontal and vertical margins */
- uint32_t x1, x2, y1, y2, line_bytes;
- /* unsigned int orientation; */
- uint32_t i, j, k;
-
- scale = 1.0;
- if (page->res_unit == RESUNIT_NONE)
- page->res_unit = image->res_unit;
-
- switch (image->res_unit) {
- case RESUNIT_CENTIMETER:
- if (page->res_unit == RESUNIT_INCH)
- scale = 1.0/2.54;
- break;
- case RESUNIT_INCH:
- if (page->res_unit == RESUNIT_CENTIMETER)
- scale = 2.54;
- break;
- case RESUNIT_NONE: /* Dimensions in pixels */
- default:
- break;
- }
-
- /* get width, height, resolutions of input image selection */
- if (crop->combined_width > 0)
- iwidth = crop->combined_width;
- else
- iwidth = image->width;
- if (crop->combined_length > 0)
- ilength = crop->combined_length;
- else
- ilength = image->length;
-
- if (page->hres <= 1.0)
- page->hres = image->xres;
- if (page->vres <= 1.0)
- page->vres = image->yres;
-
- if ((page->hres < 1.0) || (page->vres < 1.0))
- {
- TIFFError("computeOutputPixelOffsets",
- "Invalid horizontal or vertical resolution specified or read from input image");
- return (1);
+ return (0);
+} /* end getCropOffsets */
+
+static int computeOutputPixelOffsets(struct crop_mask *crop,
+ struct image_data *image,
+ struct pagedef *page,
+ struct pageseg *sections,
+ struct dump_opts *dump)
+{
+ double scale;
+ double pwidth, plength; /* Output page width and length in user units*/
+ uint32_t iwidth, ilength; /* Input image width and length in pixels*/
+ uint32_t owidth, olength; /* Output image width and length in pixels*/
+ uint32_t orows, ocols; /* rows and cols for output */
+ uint32_t hmargin, vmargin; /* Horizontal and vertical margins */
+ uint32_t x1, x2, y1, y2, line_bytes;
+ /* unsigned int orientation; */
+ uint32_t i, j, k;
+
+ scale = 1.0;
+ if (page->res_unit == RESUNIT_NONE)
+ page->res_unit = image->res_unit;
+
+ switch (image->res_unit)
+ {
+ case RESUNIT_CENTIMETER:
+ if (page->res_unit == RESUNIT_INCH)
+ scale = 1.0 / 2.54;
+ break;
+ case RESUNIT_INCH:
+ if (page->res_unit == RESUNIT_CENTIMETER)
+ scale = 2.54;
+ break;
+ case RESUNIT_NONE: /* Dimensions in pixels */
+ default:
+ break;
}
- /* If no page sizes are being specified, we just use the input image size to
- * calculate maximum margins that can be taken from image.
- */
- if (page->width <= 0)
- pwidth = iwidth;
- else
- pwidth = page->width;
+ /* get width, height, resolutions of input image selection */
+ if (crop->combined_width > 0)
+ iwidth = crop->combined_width;
+ else
+ iwidth = image->width;
+ if (crop->combined_length > 0)
+ ilength = crop->combined_length;
+ else
+ ilength = image->length;
- if (page->length <= 0)
- plength = ilength;
- else
- plength = page->length;
+ if (page->hres <= 1.0)
+ page->hres = image->xres;
+ if (page->vres <= 1.0)
+ page->vres = image->yres;
- if (dump->debug)
+ if ((page->hres < 1.0) || (page->vres < 1.0))
{
- TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, "
- "Hmargin: %3.2f, Vmargin: %3.2f",
- page->name, page->vres, page->hres,
- page->hmargin, page->vmargin);
- TIFFError("", "Res_unit: %"PRIu16", Scale: %3.2f, Page width: %3.2f, length: %3.2f",
- page->res_unit, scale, pwidth, plength);
+ TIFFError("computeOutputPixelOffsets",
+ "Invalid horizontal or vertical resolution specified or read "
+ "from input image");
+ return (1);
}
- /* compute margins at specified unit and resolution */
- if (page->mode & PAGE_MODE_MARGINS)
- {
- if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER)
- { /* inches or centimeters specified */
- hmargin = _TIFFClampDoubleToUInt32(page->hmargin * scale * page->hres * ((image->bps + 7) / 8));
- vmargin = _TIFFClampDoubleToUInt32(page->vmargin * scale * page->vres * ((image->bps + 7) / 8));
- }
+ /* If no page sizes are being specified, we just use the input image size to
+ * calculate maximum margins that can be taken from image.
+ */
+ if (page->width <= 0)
+ pwidth = iwidth;
+ else
+ pwidth = page->width;
+
+ if (page->length <= 0)
+ plength = ilength;
else
- { /* Otherwise user has specified pixels as reference unit */
- hmargin = _TIFFClampDoubleToUInt32(page->hmargin * scale * ((image->bps + 7) / 8));
- vmargin = _TIFFClampDoubleToUInt32(page->vmargin * scale * ((image->bps + 7) / 8));
- }
-
- if ((hmargin * 2.0) > (pwidth * page->hres))
- {
- TIFFError("computeOutputPixelOffsets",
- "Combined left and right margins exceed page width");
- hmargin = (uint32_t) 0;
- return (-1);
- }
- if ((vmargin * 2.0) > (plength * page->vres))
- {
- TIFFError("computeOutputPixelOffsets",
- "Combined top and bottom margins exceed page length");
- vmargin = (uint32_t) 0;
- return (-1);
- }
- }
- else
- {
- hmargin = 0;
- vmargin = 0;
- }
-
- if (page->mode & PAGE_MODE_ROWSCOLS )
- {
- /* Maybe someday but not for now */
+ plength = page->length;
+
+ if (dump->debug)
+ {
+ TIFFError("",
+ "Page size: %s, Vres: %3.2f, Hres: %3.2f, "
+ "Hmargin: %3.2f, Vmargin: %3.2f",
+ page->name, page->vres, page->hres, page->hmargin,
+ page->vmargin);
+ TIFFError("",
+ "Res_unit: %" PRIu16
+ ", Scale: %3.2f, Page width: %3.2f, length: %3.2f",
+ page->res_unit, scale, pwidth, plength);
+ }
+
+ /* compute margins at specified unit and resolution */
if (page->mode & PAGE_MODE_MARGINS)
- TIFFError("computeOutputPixelOffsets",
- "Output margins cannot be specified with rows and columns");
+ {
+ if (page->res_unit == RESUNIT_INCH ||
+ page->res_unit == RESUNIT_CENTIMETER)
+ { /* inches or centimeters specified */
+ hmargin = _TIFFClampDoubleToUInt32(
+ page->hmargin * scale * page->hres * ((image->bps + 7) / 8));
+ vmargin = _TIFFClampDoubleToUInt32(
+ page->vmargin * scale * page->vres * ((image->bps + 7) / 8));
+ }
+ else
+ { /* Otherwise user has specified pixels as reference unit */
+ hmargin = _TIFFClampDoubleToUInt32(page->hmargin * scale *
+ ((image->bps + 7) / 8));
+ vmargin = _TIFFClampDoubleToUInt32(page->vmargin * scale *
+ ((image->bps + 7) / 8));
+ }
- owidth = TIFFhowmany(iwidth, page->cols);
- olength = TIFFhowmany(ilength, page->rows);
+ if ((hmargin * 2.0) > (pwidth * page->hres))
+ {
+ TIFFError("computeOutputPixelOffsets",
+ "Combined left and right margins exceed page width");
+ hmargin = (uint32_t)0;
+ return (-1);
+ }
+ if ((vmargin * 2.0) > (plength * page->vres))
+ {
+ TIFFError("computeOutputPixelOffsets",
+ "Combined top and bottom margins exceed page length");
+ vmargin = (uint32_t)0;
+ return (-1);
+ }
}
- else
+ else
{
- if (page->mode & PAGE_MODE_PAPERSIZE )
- {
- owidth = _TIFFClampDoubleToUInt32((pwidth * page->hres) - (hmargin * 2));
- olength = _TIFFClampDoubleToUInt32((plength * page->vres) - (vmargin * 2));
- }
+ hmargin = 0;
+ vmargin = 0;
+ }
+
+ if (page->mode & PAGE_MODE_ROWSCOLS)
+ {
+ /* Maybe someday but not for now */
+ if (page->mode & PAGE_MODE_MARGINS)
+ TIFFError(
+ "computeOutputPixelOffsets",
+ "Output margins cannot be specified with rows and columns");
+
+ owidth = TIFFhowmany(iwidth, page->cols);
+ olength = TIFFhowmany(ilength, page->rows);
+ }
else
- {
- owidth = _TIFFClampDoubleToUInt32(iwidth - (hmargin * 2 * page->hres));
- olength = _TIFFClampDoubleToUInt32(ilength - (vmargin * 2 * page->vres));
- }
- }
-
- if (owidth > iwidth)
- owidth = iwidth;
- if (olength > ilength)
- olength = ilength;
-
- if (owidth == 0 || olength == 0)
- {
- TIFFError("computeOutputPixelOffsets", "Integer overflow when calculating the number of pages");
- exit(EXIT_FAILURE);
- }
-
- /* Compute the number of pages required for Portrait or Landscape */
- switch (page->orient)
- {
- case ORIENTATION_NONE:
- case ORIENTATION_PORTRAIT:
- ocols = TIFFhowmany(iwidth, owidth);
- orows = TIFFhowmany(ilength, olength);
- /* orientation = ORIENTATION_PORTRAIT; */
- break;
-
- case ORIENTATION_LANDSCAPE:
- ocols = TIFFhowmany(iwidth, olength);
- orows = TIFFhowmany(ilength, owidth);
- x1 = olength;
- olength = owidth;
- owidth = x1;
- /* orientation = ORIENTATION_LANDSCAPE; */
- break;
-
- case ORIENTATION_AUTO:
- default:
- x1 = TIFFhowmany(iwidth, owidth);
- x2 = TIFFhowmany(ilength, olength);
- y1 = TIFFhowmany(iwidth, olength);
- y2 = TIFFhowmany(ilength, owidth);
-
- if ( (x1 * x2) < (y1 * y2))
- { /* Portrait */
- ocols = x1;
- orows = x2;
- /* orientation = ORIENTATION_PORTRAIT; */
- }
- else
- { /* Landscape */
- ocols = y1;
- orows = y2;
- x1 = olength;
- olength = owidth;
- owidth = x1;
- /* orientation = ORIENTATION_LANDSCAPE; */
- }
- }
-
- if (ocols < 1)
- ocols = 1;
- if (orows < 1)
- orows = 1;
-
- /* Always return rows and cols from calcuation above.
- * (correct values needed external to this function)
- * Warn, if user input settings has been changed.
- */
-
- if ((page->rows > 0) && (page->rows != orows)) {
- TIFFError("computeOutputPixelOffsets",
- "Number of user input section rows down (%"PRIu32") was changed to (%"PRIu32")", page->rows, orows);
- }
- page->rows = orows;
- if ((page->cols > 0) && (page->cols != ocols)) {
- TIFFError("computeOutputPixelOffsets",
- "Number of user input section cols across (%"PRIu32") was changed to (%"PRIu32")", page->cols, ocols);
- }
- page->cols = ocols;
-
- line_bytes = TIFFhowmany8(owidth * image->spp * image->bps);
-
- if ((orows * ocols) > MAX_SECTIONS)
- {
- TIFFError("computeOutputPixelOffsets",
- "Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections");
- return (-1);
- }
-
- /* build the list of offsets for each output section */
- for (k = 0, i = 0; i < orows; i++)
- {
- y1 = (uint32_t)(olength * i);
- y2 = (uint32_t)(olength * (i + 1) - 1);
- if (y2 >= ilength)
- y2 = ilength - 1;
- for (j = 0; (j < ocols) && (k < MAX_SECTIONS); j++, k++)
- {
- x1 = (uint32_t)(owidth * j);
- x2 = (uint32_t)(owidth * (j + 1) - 1);
- if (x2 >= iwidth)
- x2 = iwidth - 1;
- sections[k].x1 = x1;
- sections[k].x2 = x2;
- sections[k].y1 = y1;
- sections[k].y2 = y2;
- sections[k].buffsize = line_bytes * olength;
- sections[k].position = k + 1;
- sections[k].total = orows * ocols;
- }
- }
- return (0);
- } /* end computeOutputPixelOffsets */
-
-static int
-loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr)
- {
- uint32_t i;
- float xres = 0.0, yres = 0.0;
- uint32_t nstrips = 0, ntiles = 0;
- uint16_t planar = 0;
- uint16_t bps = 0, spp = 0, res_unit = 0;
- uint16_t orientation = 0;
- uint16_t input_compression = 0, input_photometric = 0;
- uint16_t subsampling_horiz, subsampling_vert;
- uint32_t width = 0, length = 0;
- tmsize_t stsize = 0, tlsize = 0, buffsize = 0;
- tmsize_t scanlinesize = 0;
- uint32_t tw = 0, tl = 0; /* Tile width and length */
- tmsize_t tile_rowsize = 0;
- unsigned char *read_buff = NULL;
- unsigned char *new_buff = NULL;
- int readunit = 0;
- static tmsize_t prev_readsize = 0;
-
- TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
- TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp);
- TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
- TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
- if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric))
- TIFFError("loadImage","Image lacks Photometric interpretation tag");
- if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width))
- TIFFError("loadimage","Image lacks image width tag");
- if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length))
- TIFFError("loadimage","Image lacks image length tag");
- TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres);
- TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres);
- if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit))
- res_unit = RESUNIT_INCH;
- if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression))
- input_compression = COMPRESSION_NONE;
+ {
+ if (page->mode & PAGE_MODE_PAPERSIZE)
+ {
+ owidth =
+ _TIFFClampDoubleToUInt32((pwidth * page->hres) - (hmargin * 2));
+ olength = _TIFFClampDoubleToUInt32((plength * page->vres) -
+ (vmargin * 2));
+ }
+ else
+ {
+ owidth =
+ _TIFFClampDoubleToUInt32(iwidth - (hmargin * 2 * page->hres));
+ olength =
+ _TIFFClampDoubleToUInt32(ilength - (vmargin * 2 * page->vres));
+ }
+ }
+
+ if (owidth > iwidth)
+ owidth = iwidth;
+ if (olength > ilength)
+ olength = ilength;
+
+ if (owidth == 0 || olength == 0)
+ {
+ TIFFError("computeOutputPixelOffsets",
+ "Integer overflow when calculating the number of pages");
+ exit(EXIT_FAILURE);
+ }
+
+ /* Compute the number of pages required for Portrait or Landscape */
+ switch (page->orient)
+ {
+ case ORIENTATION_NONE:
+ case ORIENTATION_PORTRAIT:
+ ocols = TIFFhowmany(iwidth, owidth);
+ orows = TIFFhowmany(ilength, olength);
+ /* orientation = ORIENTATION_PORTRAIT; */
+ break;
+
+ case ORIENTATION_LANDSCAPE:
+ ocols = TIFFhowmany(iwidth, olength);
+ orows = TIFFhowmany(ilength, owidth);
+ x1 = olength;
+ olength = owidth;
+ owidth = x1;
+ /* orientation = ORIENTATION_LANDSCAPE; */
+ break;
+
+ case ORIENTATION_AUTO:
+ default:
+ x1 = TIFFhowmany(iwidth, owidth);
+ x2 = TIFFhowmany(ilength, olength);
+ y1 = TIFFhowmany(iwidth, olength);
+ y2 = TIFFhowmany(ilength, owidth);
+
+ if ((x1 * x2) < (y1 * y2))
+ { /* Portrait */
+ ocols = x1;
+ orows = x2;
+ /* orientation = ORIENTATION_PORTRAIT; */
+ }
+ else
+ { /* Landscape */
+ ocols = y1;
+ orows = y2;
+ x1 = olength;
+ olength = owidth;
+ owidth = x1;
+ /* orientation = ORIENTATION_LANDSCAPE; */
+ }
+ }
+
+ if (ocols < 1)
+ ocols = 1;
+ if (orows < 1)
+ orows = 1;
+
+ /* Always return rows and cols from calcuation above.
+ * (correct values needed external to this function)
+ * Warn, if user input settings has been changed.
+ */
+
+ if ((page->rows > 0) && (page->rows != orows))
+ {
+ TIFFError("computeOutputPixelOffsets",
+ "Number of user input section rows down (%" PRIu32
+ ") was changed to (%" PRIu32 ")",
+ page->rows, orows);
+ }
+ page->rows = orows;
+ if ((page->cols > 0) && (page->cols != ocols))
+ {
+ TIFFError("computeOutputPixelOffsets",
+ "Number of user input section cols across (%" PRIu32
+ ") was changed to (%" PRIu32 ")",
+ page->cols, ocols);
+ }
+ page->cols = ocols;
+
+ line_bytes = TIFFhowmany8(owidth * image->spp * image->bps);
+
+ if ((orows * ocols) > MAX_SECTIONS)
+ {
+ TIFFError("computeOutputPixelOffsets",
+ "Rows and Columns exceed maximum sections\nIncrease "
+ "resolution or reduce sections");
+ return (-1);
+ }
+
+ /* build the list of offsets for each output section */
+ for (k = 0, i = 0; i < orows; i++)
+ {
+ y1 = (uint32_t)(olength * i);
+ y2 = (uint32_t)(olength * (i + 1) - 1);
+ if (y2 >= ilength)
+ y2 = ilength - 1;
+ for (j = 0; (j < ocols) && (k < MAX_SECTIONS); j++, k++)
+ {
+ x1 = (uint32_t)(owidth * j);
+ x2 = (uint32_t)(owidth * (j + 1) - 1);
+ if (x2 >= iwidth)
+ x2 = iwidth - 1;
+ sections[k].x1 = x1;
+ sections[k].x2 = x2;
+ sections[k].y1 = y1;
+ sections[k].y2 = y2;
+ sections[k].buffsize = line_bytes * olength;
+ sections[k].position = k + 1;
+ sections[k].total = orows * ocols;
+ }
+ }
+ return (0);
+} /* end computeOutputPixelOffsets */
+
+static int loadImage(TIFF *in, struct image_data *image, struct dump_opts *dump,
+ unsigned char **read_ptr)
+{
+ uint32_t i;
+ float xres = 0.0, yres = 0.0;
+ uint32_t nstrips = 0, ntiles = 0;
+ uint16_t planar = 0;
+ uint16_t bps = 0, spp = 0, res_unit = 0;
+ uint16_t orientation = 0;
+ uint16_t input_compression = 0, input_photometric = 0;
+ uint16_t subsampling_horiz, subsampling_vert;
+ uint32_t width = 0, length = 0;
+ tmsize_t stsize = 0, tlsize = 0, buffsize = 0;
+ tmsize_t scanlinesize = 0;
+ uint32_t tw = 0, tl = 0; /* Tile width and length */
+ tmsize_t tile_rowsize = 0;
+ unsigned char *read_buff = NULL;
+ unsigned char *new_buff = NULL;
+ int readunit = 0;
+ static tmsize_t prev_readsize = 0;
+
+ TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
+ TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp);
+ TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
+ TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
+ if (!TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric))
+ TIFFError("loadImage", "Image lacks Photometric interpretation tag");
+ if (!TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width))
+ TIFFError("loadimage", "Image lacks image width tag");
+ if (!TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length))
+ TIFFError("loadimage", "Image lacks image length tag");
+ TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres);
+ TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres);
+ if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit))
+ res_unit = RESUNIT_INCH;
+ if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression))
+ input_compression = COMPRESSION_NONE;
#ifdef DEBUG2
- char compressionid[16];
-
- switch (input_compression)
- {
- case COMPRESSION_NONE: /* 1 dump mode */
- strcpy (compressionid, "None/dump");
- break;
- case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */
- strcpy (compressionid, "Huffman RLE");
- break;
- case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */
- strcpy (compressionid, "Group3 Fax");
- break;
- case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */
- strcpy (compressionid, "Group4 Fax");
- break;
- case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */
- strcpy (compressionid, "LZW");
- break;
- case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */
- strcpy (compressionid, "Old Jpeg");
- break;
- case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */
- strcpy (compressionid, "New Jpeg");
- break;
- case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */
- strcpy (compressionid, "Next RLE");
- break;
- case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */
- strcpy (compressionid, "CITTRLEW");
- break;
- case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */
- strcpy (compressionid, "Mac Packbits");
- break;
- case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */
- strcpy (compressionid, "Thunderscan");
- break;
- case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */
- strcpy (compressionid, "IT8 padded");
- break;
- case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */
- strcpy (compressionid, "IT8 RLE");
- break;
- case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */
- strcpy (compressionid, "IT8 mono");
- break;
- case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */
- strcpy (compressionid, "IT8 lineart");
- break;
- case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */
- strcpy (compressionid, "Pixar 10 bit");
- break;
- case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */
- strcpy (compressionid, "Pixar 11bit");
- break;
- case COMPRESSION_DEFLATE: /* 32946 Deflate compression */
- strcpy (compressionid, "Deflate");
- break;
- case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */
- strcpy (compressionid, "Adobe deflate");
- break;
- default:
- strcpy (compressionid, "None/unknown");
- break;
- }
- TIFFError("loadImage", "Input compression %s", compressionid);
+ char compressionid[16];
+
+ switch (input_compression)
+ {
+ case COMPRESSION_NONE: /* 1 dump mode */
+ strcpy(compressionid, "None/dump");
+ break;
+ case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */
+ strcpy(compressionid, "Huffman RLE");
+ break;
+ case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */
+ strcpy(compressionid, "Group3 Fax");
+ break;
+ case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */
+ strcpy(compressionid, "Group4 Fax");
+ break;
+ case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */
+ strcpy(compressionid, "LZW");
+ break;
+ case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */
+ strcpy(compressionid, "Old Jpeg");
+ break;
+ case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */
+ strcpy(compressionid, "New Jpeg");
+ break;
+ case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */
+ strcpy(compressionid, "Next RLE");
+ break;
+ case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */
+ strcpy(compressionid, "CITTRLEW");
+ break;
+ case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */
+ strcpy(compressionid, "Mac Packbits");
+ break;
+ case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */
+ strcpy(compressionid, "Thunderscan");
+ break;
+ case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */
+ strcpy(compressionid, "IT8 padded");
+ break;
+ case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */
+ strcpy(compressionid, "IT8 RLE");
+ break;
+ case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */
+ strcpy(compressionid, "IT8 mono");
+ break;
+ case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */
+ strcpy(compressionid, "IT8 lineart");
+ break;
+ case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */
+ strcpy(compressionid, "Pixar 10 bit");
+ break;
+ case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */
+ strcpy(compressionid, "Pixar 11bit");
+ break;
+ case COMPRESSION_DEFLATE: /* 32946 Deflate compression */
+ strcpy(compressionid, "Deflate");
+ break;
+ case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */
+ strcpy(compressionid, "Adobe deflate");
+ break;
+ default:
+ strcpy(compressionid, "None/unknown");
+ break;
+ }
+ TIFFError("loadImage", "Input compression %s", compressionid);
#endif
- scanlinesize = TIFFScanlineSize(in);
- image->bps = bps;
- image->spp = spp;
- image->planar = planar;
- image->width = width;
- image->length = length;
- image->xres = xres;
- image->yres = yres;
- image->res_unit = res_unit;
- image->compression = input_compression;
- image->photometric = input_photometric;
+ scanlinesize = TIFFScanlineSize(in);
+ image->bps = bps;
+ image->spp = spp;
+ image->planar = planar;
+ image->width = width;
+ image->length = length;
+ image->xres = xres;
+ image->yres = yres;
+ image->res_unit = res_unit;
+ image->compression = input_compression;
+ image->photometric = input_photometric;
#ifdef DEBUG2
- char photometricid[12];
-
- switch (input_photometric)
- {
- case PHOTOMETRIC_MINISWHITE:
- strcpy (photometricid, "MinIsWhite");
- break;
- case PHOTOMETRIC_MINISBLACK:
- strcpy (photometricid, "MinIsBlack");
- break;
- case PHOTOMETRIC_RGB:
- strcpy (photometricid, "RGB");
- break;
- case PHOTOMETRIC_PALETTE:
- strcpy (photometricid, "Palette");
- break;
- case PHOTOMETRIC_MASK:
- strcpy (photometricid, "Mask");
- break;
- case PHOTOMETRIC_SEPARATED:
- strcpy (photometricid, "Separated");
- break;
- case PHOTOMETRIC_YCBCR:
- strcpy (photometricid, "YCBCR");
- break;
- case PHOTOMETRIC_CIELAB:
- strcpy (photometricid, "CIELab");
- break;
- case PHOTOMETRIC_ICCLAB:
- strcpy (photometricid, "ICCLab");
- break;
- case PHOTOMETRIC_ITULAB:
- strcpy (photometricid, "ITULab");
- break;
- case PHOTOMETRIC_LOGL:
- strcpy (photometricid, "LogL");
- break;
- case PHOTOMETRIC_LOGLUV:
- strcpy (photometricid, "LOGLuv");
- break;
- default:
- strcpy (photometricid, "Unknown");
- break;
- }
- TIFFError("loadImage", "Input photometric interpretation %s", photometricid);
+ char photometricid[12];
+
+ switch (input_photometric)
+ {
+ case PHOTOMETRIC_MINISWHITE:
+ strcpy(photometricid, "MinIsWhite");
+ break;
+ case PHOTOMETRIC_MINISBLACK:
+ strcpy(photometricid, "MinIsBlack");
+ break;
+ case PHOTOMETRIC_RGB:
+ strcpy(photometricid, "RGB");
+ break;
+ case PHOTOMETRIC_PALETTE:
+ strcpy(photometricid, "Palette");
+ break;
+ case PHOTOMETRIC_MASK:
+ strcpy(photometricid, "Mask");
+ break;
+ case PHOTOMETRIC_SEPARATED:
+ strcpy(photometricid, "Separated");
+ break;
+ case PHOTOMETRIC_YCBCR:
+ strcpy(photometricid, "YCBCR");
+ break;
+ case PHOTOMETRIC_CIELAB:
+ strcpy(photometricid, "CIELab");
+ break;
+ case PHOTOMETRIC_ICCLAB:
+ strcpy(photometricid, "ICCLab");
+ break;
+ case PHOTOMETRIC_ITULAB:
+ strcpy(photometricid, "ITULab");
+ break;
+ case PHOTOMETRIC_LOGL:
+ strcpy(photometricid, "LogL");
+ break;
+ case PHOTOMETRIC_LOGLUV:
+ strcpy(photometricid, "LOGLuv");
+ break;
+ default:
+ strcpy(photometricid, "Unknown");
+ break;
+ }
+ TIFFError("loadImage", "Input photometric interpretation %s",
+ photometricid);
#endif
- image->orientation = orientation;
- switch (orientation)
- {
- case 0:
- case ORIENTATION_TOPLEFT:
- image->adjustments = 0;
- break;
- case ORIENTATION_TOPRIGHT:
- image->adjustments = MIRROR_HORIZ;
- break;
- case ORIENTATION_BOTRIGHT:
- image->adjustments = ROTATECW_180;
- break;
- case ORIENTATION_BOTLEFT:
- image->adjustments = MIRROR_VERT;
- break;
- case ORIENTATION_LEFTTOP:
- image->adjustments = MIRROR_VERT | ROTATECW_90;
- break;
- case ORIENTATION_RIGHTTOP:
- image->adjustments = ROTATECW_90;
- break;
- case ORIENTATION_RIGHTBOT:
- image->adjustments = MIRROR_VERT | ROTATECW_270;
- break;
- case ORIENTATION_LEFTBOT:
- image->adjustments = ROTATECW_270;
- break;
- default:
- image->adjustments = 0;
- image->orientation = ORIENTATION_TOPLEFT;
- }
-
- if ((bps == 0) || (spp == 0))
- {
- TIFFError("loadImage", "Invalid samples per pixel (%"PRIu16") or bits per sample (%"PRIu16")",
- spp, bps);
- return (-1);
- }
-
- if (TIFFIsTiled(in))
- {
- readunit = TILE;
- tlsize = TIFFTileSize(in);
- ntiles = TIFFNumberOfTiles(in);
- TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
- TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
-
- tile_rowsize = TIFFTileRowSize(in);
- if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0)
- {
- TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero.");
- exit(EXIT_FAILURE);
- }
- if (ntiles != 0 && tlsize > (tmsize_t)(TIFF_TMSIZE_T_MAX / ntiles))
- {
- TIFFError("loadImage", "Integer overflow when calculating buffer size");
- exit(EXIT_FAILURE);
- }
- buffsize = tlsize * ntiles;
-
- if (tl != 0 && ntiles != 0 && tile_rowsize > (tmsize_t)(TIFF_TMSIZE_T_MAX / tl / ntiles))
- {
- TIFFError("loadImage", "Integer overflow when calculating buffer size");
- exit(EXIT_FAILURE);
+ image->orientation = orientation;
+ switch (orientation)
+ {
+ case 0:
+ case ORIENTATION_TOPLEFT:
+ image->adjustments = 0;
+ break;
+ case ORIENTATION_TOPRIGHT:
+ image->adjustments = MIRROR_HORIZ;
+ break;
+ case ORIENTATION_BOTRIGHT:
+ image->adjustments = ROTATECW_180;
+ break;
+ case ORIENTATION_BOTLEFT:
+ image->adjustments = MIRROR_VERT;
+ break;
+ case ORIENTATION_LEFTTOP:
+ image->adjustments = MIRROR_VERT | ROTATECW_90;
+ break;
+ case ORIENTATION_RIGHTTOP:
+ image->adjustments = ROTATECW_90;
+ break;
+ case ORIENTATION_RIGHTBOT:
+ image->adjustments = MIRROR_VERT | ROTATECW_270;
+ break;
+ case ORIENTATION_LEFTBOT:
+ image->adjustments = ROTATECW_270;
+ break;
+ default:
+ image->adjustments = 0;
+ image->orientation = ORIENTATION_TOPLEFT;
+ }
+
+ if ((bps == 0) || (spp == 0))
+ {
+ TIFFError("loadImage",
+ "Invalid samples per pixel (%" PRIu16
+ ") or bits per sample (%" PRIu16 ")",
+ spp, bps);
+ return (-1);
}
- if (buffsize < (tmsize_t)(ntiles * tl * tile_rowsize))
+
+ if (TIFFIsTiled(in))
{
- buffsize = ntiles * tl * tile_rowsize;
-
+ readunit = TILE;
+ tlsize = TIFFTileSize(in);
+ ntiles = TIFFNumberOfTiles(in);
+ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
+ TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
+
+ tile_rowsize = TIFFTileRowSize(in);
+ if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0)
+ {
+ TIFFError("loadImage",
+ "File appears to be tiled, but the number of tiles, tile "
+ "size, or tile rowsize is zero.");
+ exit(EXIT_FAILURE);
+ }
+ if (ntiles != 0 && tlsize > (tmsize_t)(TIFF_TMSIZE_T_MAX / ntiles))
+ {
+ TIFFError("loadImage",
+ "Integer overflow when calculating buffer size");
+ exit(EXIT_FAILURE);
+ }
+ buffsize = tlsize * ntiles;
+
+ if (tl != 0 && ntiles != 0 &&
+ tile_rowsize > (tmsize_t)(TIFF_TMSIZE_T_MAX / tl / ntiles))
+ {
+ TIFFError("loadImage",
+ "Integer overflow when calculating buffer size");
+ exit(EXIT_FAILURE);
+ }
+ if (buffsize < (tmsize_t)(ntiles * tl * tile_rowsize))
+ {
+ buffsize = ntiles * tl * tile_rowsize;
+
#ifdef DEBUG2
- TIFFError("loadImage",
- "Tilesize %"PRIu32" is too small, using ntiles * tilelength * tilerowsize %"PRIu32,
- tlsize, buffsize);
+ TIFFError("loadImage",
+ "Tilesize %" PRIu32 " is too small, using ntiles * "
+ "tilelength * tilerowsize %" PRIu32,
+ tlsize, buffsize);
#endif
+ }
+
+ if (dump->infile != NULL)
+ dump_info(dump->infile, dump->format, "",
+ "Tilesize: %" TIFF_SSIZE_FORMAT
+ ", Number of Tiles: %" PRIu32
+ ", Tile row size: %" TIFF_SSIZE_FORMAT,
+ tlsize, ntiles, tile_rowsize);
}
-
- if (dump->infile != NULL)
- dump_info (dump->infile, dump->format, "",
- "Tilesize: %"TIFF_SSIZE_FORMAT", Number of Tiles: %"PRIu32", Tile row size: %"TIFF_SSIZE_FORMAT,
- tlsize, ntiles, tile_rowsize);
- }
- else
- {
- tmsize_t buffsize_check;
- readunit = STRIP;
- TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
- stsize = TIFFStripSize(in);
- nstrips = TIFFNumberOfStrips(in);
- if (nstrips == 0 || stsize == 0)
+ else
{
- TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero.");
- exit(EXIT_FAILURE);
+ tmsize_t buffsize_check;
+ readunit = STRIP;
+ TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
+ stsize = TIFFStripSize(in);
+ nstrips = TIFFNumberOfStrips(in);
+ if (nstrips == 0 || stsize == 0)
+ {
+ TIFFError("loadImage", "File appears to be striped, but the number "
+ "of stipes or stripe size is zero.");
+ exit(EXIT_FAILURE);
+ }
+
+ if (nstrips != 0 && stsize > (tmsize_t)(TIFF_TMSIZE_T_MAX / nstrips))
+ {
+ TIFFError("loadImage",
+ "Integer overflow when calculating buffer size");
+ exit(EXIT_FAILURE);
+ }
+ buffsize = stsize * nstrips;
+ /* The buffsize_check and the possible adaptation of buffsize
+ * has to account also for padding of each line to a byte boundary.
+ * This is assumed by mirrorImage() and rotateImage().
+ * Furthermore, functions like extractContigSamplesShifted32bits()
+ * need a buffer, which is at least 3 bytes larger than the actual
+ * image. Otherwise buffer-overflow might occur there.
+ */
+ if ((spp != 0 && bps != 0 &&
+ width > (uint32_t)((UINT32_MAX - 7) / spp / bps)) ||
+ (width != 0 && spp != 0 && bps != 0 &&
+ length > (tmsize_t)(TIFF_TMSIZE_T_MAX /
+ (uint32_t)(((width * spp * bps) + 7) / 8))))
+ {
+ TIFFError("loadImage", "Integer overflow detected.");
+ exit(EXIT_FAILURE);
+ }
+ buffsize_check =
+ (tmsize_t)length * (uint32_t)(((width * spp * bps) + 7) / 8);
+ if (buffsize < buffsize_check)
+ {
+ buffsize = buffsize_check;
+#ifdef DEBUG2
+ TIFFError("loadImage",
+ "Stripsize %" PRIu32 " is too small, using imagelength * "
+ "width * spp * bps / 8 = %" PRIu32,
+ stsize, (unsigned long)buffsize);
+#endif
+ }
+
+ if (dump->infile != NULL)
+ dump_info(dump->infile, dump->format, "",
+ "Stripsize: %" TIFF_SSIZE_FORMAT
+ ", Number of Strips: %" PRIu32
+ ", Rows per Strip: %" PRIu32
+ ", Scanline size: %" TIFF_SSIZE_FORMAT,
+ stsize, nstrips, rowsperstrip, scanlinesize);
}
- if (nstrips != 0 && stsize > (tmsize_t)(TIFF_TMSIZE_T_MAX / nstrips))
- {
- TIFFError("loadImage", "Integer overflow when calculating buffer size");
- exit(EXIT_FAILURE);
+ if (input_compression == COMPRESSION_JPEG)
+ { /* Force conversion to RGB */
+ jpegcolormode = JPEGCOLORMODE_RGB;
+ TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
- buffsize = stsize * nstrips;
- /* The buffsize_check and the possible adaptation of buffsize
- * has to account also for padding of each line to a byte boundary.
- * This is assumed by mirrorImage() and rotateImage().
- * Furthermore, functions like extractContigSamplesShifted32bits()
- * need a buffer, which is at least 3 bytes larger than the actual image.
- * Otherwise buffer-overflow might occur there.
+ /* The clause up to the read statement is taken from Tom Lane's tiffcp patch
*/
- if ( (spp != 0 && bps != 0 && width > (uint32_t)((UINT32_MAX - 7) / spp / bps)) ||
- (width != 0 && spp != 0 && bps != 0 && length > (tmsize_t)(TIFF_TMSIZE_T_MAX / (uint32_t)(((width * spp * bps) + 7) / 8))) )
+ else
+ { /* Otherwise, can't handle subsampled input */
+ if (input_photometric == PHOTOMETRIC_YCBCR)
+ {
+ TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
+ &subsampling_horiz, &subsampling_vert);
+ if (subsampling_horiz != 1 || subsampling_vert != 1)
+ {
+ TIFFError("loadImage",
+ "Can't copy/convert subsampled image with "
+ "subsampling %" PRIu16 " horiz %" PRIu16 " vert",
+ subsampling_horiz, subsampling_vert);
+ return (-1);
+ }
+ }
+ }
+
+ read_buff = *read_ptr;
+ /* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */
+ /* outside buffer */
+ if (!read_buff)
{
- TIFFError("loadImage", "Integer overflow detected.");
- exit(EXIT_FAILURE);
+ if (buffsize > 0xFFFFFFFFU - 3)
+ {
+ TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
+ return (-1);
+ }
+ read_buff =
+ (unsigned char *)limitMalloc(buffsize + NUM_BUFF_OVERSIZE_BYTES);
}
- buffsize_check = (tmsize_t)length * (uint32_t)(((width * spp * bps) + 7) / 8);
- if (buffsize < buffsize_check)
- {
- buffsize = buffsize_check;
-#ifdef DEBUG2
- TIFFError("loadImage",
- "Stripsize %"PRIu32" is too small, using imagelength * width * spp * bps / 8 = %"PRIu32,
- stsize, (unsigned long)buffsize);
-#endif
- }
-
- if (dump->infile != NULL)
- dump_info (dump->infile, dump->format, "",
- "Stripsize: %"TIFF_SSIZE_FORMAT", Number of Strips: %"PRIu32", Rows per Strip: %"PRIu32", Scanline size: %"TIFF_SSIZE_FORMAT,
- stsize, nstrips, rowsperstrip, scanlinesize);
- }
-
- if (input_compression == COMPRESSION_JPEG)
- { /* Force conversion to RGB */
- jpegcolormode = JPEGCOLORMODE_RGB;
- TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
- }
- /* The clause up to the read statement is taken from Tom Lane's tiffcp patch */
- else
- { /* Otherwise, can't handle subsampled input */
- if (input_photometric == PHOTOMETRIC_YCBCR)
- {
- TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
- &subsampling_horiz, &subsampling_vert);
- if (subsampling_horiz != 1 || subsampling_vert != 1)
- {
- TIFFError("loadImage",
- "Can't copy/convert subsampled image with subsampling %"PRIu16" horiz %"PRIu16" vert",
- subsampling_horiz, subsampling_vert);
- return (-1);
+ else
+ {
+ if (prev_readsize < buffsize)
+ {
+ if (buffsize > 0xFFFFFFFFU - 3)
+ {
+ TIFFError("loadImage",
+ "Unable to allocate/reallocate read buffer");
+ return (-1);
+ }
+ new_buff =
+ _TIFFrealloc(read_buff, buffsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (!new_buff)
+ {
+ free(read_buff);
+ read_buff = (unsigned char *)limitMalloc(
+ buffsize + NUM_BUFF_OVERSIZE_BYTES);
+ }
+ else
+ read_buff = new_buff;
}
- }
}
-
- read_buff = *read_ptr;
- /* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */
- /* outside buffer */
- if (!read_buff)
- {
- if( buffsize > 0xFFFFFFFFU - 3 )
+ if (!read_buff)
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
- read_buff = (unsigned char *)limitMalloc(buffsize + NUM_BUFF_OVERSIZE_BYTES);
- }
- else
- {
- if (prev_readsize < buffsize)
- {
- if( buffsize > 0xFFFFFFFFU - 3 )
- {
- TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
- return (-1);
- }
- new_buff = _TIFFrealloc(read_buff, buffsize + NUM_BUFF_OVERSIZE_BYTES);
- if (!new_buff)
- {
- free (read_buff);
- read_buff = (unsigned char *)limitMalloc(buffsize + NUM_BUFF_OVERSIZE_BYTES);
- }
- else
- read_buff = new_buff;
- }
- }
- if (!read_buff)
- {
- TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
- return (-1);
- }
-
- read_buff[buffsize] = 0;
- read_buff[buffsize+1] = 0;
- read_buff[buffsize+2] = 0;
-
- prev_readsize = buffsize;
- *read_ptr = read_buff;
-
- /* N.B. The read functions used copy separate plane data into a buffer as interleaved
- * samples rather than separate planes so the same logic works to extract regions
- * regardless of the way the data are organized in the input file.
- */
- switch (readunit) {
- case STRIP:
- if (planar == PLANARCONFIG_CONTIG)
- {
- if (!(readContigStripsIntoBuffer(in, read_buff)))
- {
- TIFFError("loadImage", "Unable to read contiguous strips into buffer");
- return (-1);
- }
- }
- else
- {
- if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump)))
- {
- TIFFError("loadImage", "Unable to read separate strips into buffer");
- return (-1);
- }
- }
- break;
-
- case TILE:
- if (planar == PLANARCONFIG_CONTIG)
- {
- if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
- {
- TIFFError("loadImage", "Unable to read contiguous tiles into buffer");
- return (-1);
- }
- }
- else
- {
- if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
- {
- TIFFError("loadImage", "Unable to read separate tiles into buffer");
- return (-1);
- }
- }
- break;
- default: TIFFError("loadImage", "Unsupported image file format");
- return (-1);
- break;
- }
- if ((dump->infile != NULL) && (dump->level == 2))
- {
- dump_info (dump->infile, dump->format, "loadImage",
- "Image width %"PRIu32", length %"PRIu32", Raw image data, %4"TIFF_SSIZE_FORMAT" bytes",
- width, length, buffsize);
- dump_info (dump->infile, dump->format, "",
- "Bits per sample %"PRIu16", Samples per pixel %"PRIu16, bps, spp);
-
- if ((uint64_t)scanlinesize > 0x0ffffffffULL) {
- dump_info(dump->infile, dump->format, "loadImage",
- "Attention: scanlinesize %"PRIu64" is larger than UINT32_MAX.\nFollowing dump might be wrong.",
- (uint64_t)scanlinesize);
+
+ read_buff[buffsize] = 0;
+ read_buff[buffsize + 1] = 0;
+ read_buff[buffsize + 2] = 0;
+
+ prev_readsize = buffsize;
+ *read_ptr = read_buff;
+
+ /* N.B. The read functions used copy separate plane data into a buffer as
+ * interleaved samples rather than separate planes so the same logic works
+ * to extract regions regardless of the way the data are organized in the
+ * input file.
+ */
+ switch (readunit)
+ {
+ case STRIP:
+ if (planar == PLANARCONFIG_CONTIG)
+ {
+ if (!(readContigStripsIntoBuffer(in, read_buff)))
+ {
+ TIFFError("loadImage",
+ "Unable to read contiguous strips into buffer");
+ return (-1);
+ }
+ }
+ else
+ {
+ if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width,
+ spp, dump)))
+ {
+ TIFFError("loadImage",
+ "Unable to read separate strips into buffer");
+ return (-1);
+ }
+ }
+ break;
+
+ case TILE:
+ if (planar == PLANARCONFIG_CONTIG)
+ {
+ if (!(readContigTilesIntoBuffer(in, read_buff, length, width,
+ tw, tl, spp, bps)))
+ {
+ TIFFError("loadImage",
+ "Unable to read contiguous tiles into buffer");
+ return (-1);
+ }
+ }
+ else
+ {
+ if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width,
+ tw, tl, spp, bps)))
+ {
+ TIFFError("loadImage",
+ "Unable to read separate tiles into buffer");
+ return (-1);
+ }
+ }
+ break;
+ default:
+ TIFFError("loadImage", "Unsupported image file format");
+ return (-1);
+ break;
}
- for (i = 0; i < length; i++)
- dump_buffer(dump->infile, dump->format, 1, (uint32_t)scanlinesize,
- i, read_buff + (i * scanlinesize));
+ if ((dump->infile != NULL) && (dump->level == 2))
+ {
+ dump_info(dump->infile, dump->format, "loadImage",
+ "Image width %" PRIu32 ", length %" PRIu32
+ ", Raw image data, %4" TIFF_SSIZE_FORMAT " bytes",
+ width, length, buffsize);
+ dump_info(dump->infile, dump->format, "",
+ "Bits per sample %" PRIu16 ", Samples per pixel %" PRIu16,
+ bps, spp);
+
+ if ((uint64_t)scanlinesize > 0x0ffffffffULL)
+ {
+ dump_info(
+ dump->infile, dump->format, "loadImage",
+ "Attention: scanlinesize %" PRIu64
+ " is larger than UINT32_MAX.\nFollowing dump might be wrong.",
+ (uint64_t)scanlinesize);
+ }
+ for (i = 0; i < length; i++)
+ dump_buffer(dump->infile, dump->format, 1, (uint32_t)scanlinesize,
+ i, read_buff + (i * scanlinesize));
}
- return (0);
- } /* end loadImage */
+ return (0);
+} /* end loadImage */
-static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr)
- {
- uint16_t mirror, rotation;
- unsigned char *work_buff;
+static int correct_orientation(struct image_data *image,
+ unsigned char **work_buff_ptr)
+{
+ uint16_t mirror, rotation;
+ unsigned char *work_buff;
- work_buff = *work_buff_ptr;
- if ((image == NULL) || (work_buff == NULL))
+ work_buff = *work_buff_ptr;
+ if ((image == NULL) || (work_buff == NULL))
{
- TIFFError ("correct_orientatin", "Invalid image or buffer pointer");
- return (-1);
+ TIFFError("correct_orientatin", "Invalid image or buffer pointer");
+ return (-1);
}
- if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT))
+ if ((image->adjustments & MIRROR_HORIZ) ||
+ (image->adjustments & MIRROR_VERT))
{
- mirror = (uint16_t)(image->adjustments & MIRROR_BOTH);
- if (mirrorImage(image->spp, image->bps, mirror,
- image->width, image->length, work_buff))
- {
- TIFFError ("correct_orientation", "Unable to mirror image");
- return (-1);
- }
+ mirror = (uint16_t)(image->adjustments & MIRROR_BOTH);
+ if (mirrorImage(image->spp, image->bps, mirror, image->width,
+ image->length, work_buff))
+ {
+ TIFFError("correct_orientation", "Unable to mirror image");
+ return (-1);
+ }
}
- if (image->adjustments & ROTATE_ANY)
+ if (image->adjustments & ROTATE_ANY)
{
- if (image->adjustments & ROTATECW_90)
- rotation = (uint16_t) 90;
- else
- if (image->adjustments & ROTATECW_180)
- rotation = (uint16_t) 180;
- else
- if (image->adjustments & ROTATECW_270)
- rotation = (uint16_t) 270;
+ if (image->adjustments & ROTATECW_90)
+ rotation = (uint16_t)90;
+ else if (image->adjustments & ROTATECW_180)
+ rotation = (uint16_t)180;
+ else if (image->adjustments & ROTATECW_270)
+ rotation = (uint16_t)270;
+ else
+ {
+ TIFFError("correct_orientation", "Invalid rotation value: %" PRIu16,
+ (uint16_t)(image->adjustments & ROTATE_ANY));
+ return (-1);
+ }
+
+ if (rotateImage(rotation, image, &image->width, &image->length,
+ work_buff_ptr))
+ {
+ TIFFError("correct_orientation", "Unable to rotate image");
+ return (-1);
+ }
+ image->orientation = ORIENTATION_TOPLEFT;
+ }
+
+ return (0);
+} /* end correct_orientation */
+
+/* Extract multiple zones from an image and combine into a single composite
+ * image */
+static int extractCompositeRegions(struct image_data *image,
+ struct crop_mask *crop,
+ unsigned char *read_buff,
+ unsigned char *crop_buff)
+{
+ int shift_width, bytes_per_sample, bytes_per_pixel;
+ uint32_t i, trailing_bits, prev_trailing_bits;
+ uint32_t row, first_row, last_row, first_col, last_col;
+ uint32_t src_rowsize, dst_rowsize, src_offset, dst_offset;
+ uint32_t crop_width, crop_length, img_width /*, img_length */;
+ uint32_t prev_length, prev_width, composite_width;
+ uint16_t bps, spp;
+ uint8_t *src, *dst;
+ tsample_t count, sample = 0; /* Update to extract one or more samples */
+
+ img_width = image->width;
+ /* img_length = image->length; */
+ bps = image->bps;
+ spp = image->spp;
+ count = spp;
+
+ bytes_per_sample = (bps + 7) / 8;
+ bytes_per_pixel = ((bps * spp) + 7) / 8;
+ if ((bps % 8) == 0)
+ shift_width = 0;
else
- {
- TIFFError ("correct_orientation", "Invalid rotation value: %"PRIu16,
- (uint16_t) (image->adjustments & ROTATE_ANY));
- return (-1);
- }
-
- if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr))
- {
- TIFFError ("correct_orientation", "Unable to rotate image");
- return (-1);
- }
- image->orientation = ORIENTATION_TOPLEFT;
- }
-
- return (0);
- } /* end correct_orientation */
-
-
-/* Extract multiple zones from an image and combine into a single composite image */
-static int
-extractCompositeRegions(struct image_data *image, struct crop_mask *crop,
- unsigned char *read_buff, unsigned char *crop_buff)
- {
- int shift_width, bytes_per_sample, bytes_per_pixel;
- uint32_t i, trailing_bits, prev_trailing_bits;
- uint32_t row, first_row, last_row, first_col, last_col;
- uint32_t src_rowsize, dst_rowsize, src_offset, dst_offset;
- uint32_t crop_width, crop_length, img_width /*, img_length */;
- uint32_t prev_length, prev_width, composite_width;
- uint16_t bps, spp;
- uint8_t *src, *dst;
- tsample_t count, sample = 0; /* Update to extract one or more samples */
-
- img_width = image->width;
- /* img_length = image->length; */
- bps = image->bps;
- spp = image->spp;
- count = spp;
-
- bytes_per_sample = (bps + 7) / 8;
- bytes_per_pixel = ((bps * spp) + 7) / 8;
- if ((bps % 8) == 0)
- shift_width = 0;
- else
{
- if (bytes_per_pixel < (bytes_per_sample + 1))
- shift_width = bytes_per_pixel;
- else
- shift_width = bytes_per_sample + 1;
+ if (bytes_per_pixel < (bytes_per_sample + 1))
+ shift_width = bytes_per_pixel;
+ else
+ shift_width = bytes_per_sample + 1;
}
- src = read_buff;
- dst = crop_buff;
+ src = read_buff;
+ dst = crop_buff;
- /* These are setup for adding additional sections */
- prev_width = prev_length = 0;
- prev_trailing_bits = trailing_bits = 0;
- composite_width = crop->combined_width;
- crop->combined_width = 0;
- crop->combined_length = 0;
+ /* These are setup for adding additional sections */
+ prev_width = prev_length = 0;
+ prev_trailing_bits = trailing_bits = 0;
+ composite_width = crop->combined_width;
+ crop->combined_width = 0;
+ crop->combined_length = 0;
- for (i = 0; i < crop->selections; i++)
+ for (i = 0; i < crop->selections; i++)
{
- /* rows, columns, width, length are expressed in pixels */
- first_row = crop->regionlist[i].y1;
- last_row = crop->regionlist[i].y2;
- first_col = crop->regionlist[i].x1;
- last_col = crop->regionlist[i].x2;
+ /* rows, columns, width, length are expressed in pixels */
+ first_row = crop->regionlist[i].y1;
+ last_row = crop->regionlist[i].y2;
+ first_col = crop->regionlist[i].x1;
+ last_col = crop->regionlist[i].x2;
- crop_width = last_col - first_col + 1;
- crop_length = last_row - first_row + 1;
+ crop_width = last_col - first_col + 1;
+ crop_length = last_row - first_row + 1;
- /* These should not be needed for composite images */
- crop->regionlist[i].width = crop_width;
- crop->regionlist[i].length = crop_length;
- crop->regionlist[i].buffptr = crop_buff;
+ /* These should not be needed for composite images */
+ crop->regionlist[i].width = crop_width;
+ crop->regionlist[i].length = crop_length;
+ crop->regionlist[i].buffptr = crop_buff;
- src_rowsize = ((img_width * bps * spp) + 7) / 8;
- dst_rowsize = (((crop_width * bps * count) + 7) / 8);
+ src_rowsize = ((img_width * bps * spp) + 7) / 8;
+ dst_rowsize = (((crop_width * bps * count) + 7) / 8);
- switch (crop->edge_ref)
- {
- default:
- case EDGE_TOP:
- case EDGE_BOTTOM:
- if ((i > 0) && (crop_width != crop->regionlist[i - 1].width))
- {
- TIFFError ("extractCompositeRegions",
- "Only equal width regions can be combined for -E top or bottom");
- return (1);
- }
-
- crop->combined_width = crop_width;
- crop->combined_length += crop_length;
-
- for (row = first_row; row <= last_row; row++)
- {
- src_offset = row * src_rowsize;
- dst_offset = (row - first_row) * dst_rowsize;
- src = read_buff + src_offset;
- dst = crop_buff + dst_offset + (prev_length * dst_rowsize);
- switch (shift_width)
- {
- case 0: if (extractContigSamplesBytes (src, dst, img_width, sample,
- spp, bps, count, first_col,
- last_col + 1))
- {
- TIFFError("extractCompositeRegions",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- case 1: if (bps == 1)
- {
- if (extractContigSamplesShifted8bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractCompositeRegions",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- }
- else
- if (extractContigSamplesShifted16bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractCompositeRegions",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractCompositeRegions",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- case 3:
- case 4:
- case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractCompositeRegions",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- default: TIFFError("extractCompositeRegions", "Unsupported bit depth %"PRIu16, bps);
- return (1);
- }
- }
- prev_length += crop_length;
- break;
- case EDGE_LEFT: /* splice the pieces of each row together, side by side */
- case EDGE_RIGHT:
- if ((i > 0) && (crop_length != crop->regionlist[i - 1].length))
- {
- TIFFError ("extractCompositeRegions",
- "Only equal length regions can be combined for -E left or right");
- return (1);
- }
- crop->combined_width += crop_width;
- crop->combined_length = crop_length;
- dst_rowsize = (((composite_width * bps * count) + 7) / 8);
- trailing_bits = (crop_width * bps * count) % 8;
- for (row = first_row; row <= last_row; row++)
- {
- src_offset = row * src_rowsize;
- dst_offset = (row - first_row) * dst_rowsize;
- src = read_buff + src_offset;
- dst = crop_buff + dst_offset + prev_width;
-
- switch (shift_width)
- {
- case 0: if (extractContigSamplesBytes (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1))
- {
- TIFFError("extractCompositeRegions",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- case 1: if (bps == 1)
- {
- if (extractContigSamplesShifted8bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractCompositeRegions",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- }
- else
- if (extractContigSamplesShifted16bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractCompositeRegions",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractCompositeRegions",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- case 3:
- case 4:
- case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractCompositeRegions",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- default: TIFFError("extractCompositeRegions", "Unsupported bit depth %"PRIu16, bps);
- return (1);
- }
- }
- prev_width += (crop_width * bps * count) / 8;
- prev_trailing_bits += trailing_bits;
- if (prev_trailing_bits > 7)
- prev_trailing_bits-= 8;
- break;
- }
- }
- if (crop->combined_width != composite_width)
- TIFFError("combineSeparateRegions","Combined width does not match composite width");
-
- return (0);
- } /* end extractCompositeRegions */
-
-/* Copy a single region of input buffer to an output buffer.
- * The read functions used copy separate plane data into a buffer
+ switch (crop->edge_ref)
+ {
+ default:
+ case EDGE_TOP:
+ case EDGE_BOTTOM:
+ if ((i > 0) && (crop_width != crop->regionlist[i - 1].width))
+ {
+ TIFFError("extractCompositeRegions",
+ "Only equal width regions can be combined for -E "
+ "top or bottom");
+ return (1);
+ }
+
+ crop->combined_width = crop_width;
+ crop->combined_length += crop_length;
+
+ for (row = first_row; row <= last_row; row++)
+ {
+ src_offset = row * src_rowsize;
+ dst_offset = (row - first_row) * dst_rowsize;
+ src = read_buff + src_offset;
+ dst = crop_buff + dst_offset + (prev_length * dst_rowsize);
+ switch (shift_width)
+ {
+ case 0:
+ if (extractContigSamplesBytes(
+ src, dst, img_width, sample, spp, bps,
+ count, first_col, last_col + 1))
+ {
+ TIFFError("extractCompositeRegions",
+ "Unable to extract row %" PRIu32,
+ row);
+ return (1);
+ }
+ break;
+ case 1:
+ if (bps == 1)
+ {
+ if (extractContigSamplesShifted8bits(
+ src, dst, img_width, sample, spp, bps,
+ count, first_col, last_col + 1,
+ prev_trailing_bits))
+ {
+ TIFFError("extractCompositeRegions",
+ "Unable to extract row %" PRIu32,
+ row);
+ return (1);
+ }
+ break;
+ }
+ else if (extractContigSamplesShifted16bits(
+ src, dst, img_width, sample, spp, bps,
+ count, first_col, last_col + 1,
+ prev_trailing_bits))
+ {
+ TIFFError("extractCompositeRegions",
+ "Unable to extract row %" PRIu32,
+ row);
+ return (1);
+ }
+ break;
+ case 2:
+ if (extractContigSamplesShifted24bits(
+ src, dst, img_width, sample, spp, bps,
+ count, first_col, last_col + 1,
+ prev_trailing_bits))
+ {
+ TIFFError("extractCompositeRegions",
+ "Unable to extract row %" PRIu32,
+ row);
+ return (1);
+ }
+ break;
+ case 3:
+ case 4:
+ case 5:
+ if (extractContigSamplesShifted32bits(
+ src, dst, img_width, sample, spp, bps,
+ count, first_col, last_col + 1,
+ prev_trailing_bits))
+ {
+ TIFFError("extractCompositeRegions",
+ "Unable to extract row %" PRIu32,
+ row);
+ return (1);
+ }
+ break;
+ default:
+ TIFFError("extractCompositeRegions",
+ "Unsupported bit depth %" PRIu16, bps);
+ return (1);
+ }
+ }
+ prev_length += crop_length;
+ break;
+ case EDGE_LEFT: /* splice the pieces of each row together, side by
+ side */
+ case EDGE_RIGHT:
+ if ((i > 0) && (crop_length != crop->regionlist[i - 1].length))
+ {
+ TIFFError("extractCompositeRegions",
+ "Only equal length regions can be combined for "
+ "-E left or right");
+ return (1);
+ }
+ crop->combined_width += crop_width;
+ crop->combined_length = crop_length;
+ dst_rowsize = (((composite_width * bps * count) + 7) / 8);
+ trailing_bits = (crop_width * bps * count) % 8;
+ for (row = first_row; row <= last_row; row++)
+ {
+ src_offset = row * src_rowsize;
+ dst_offset = (row - first_row) * dst_rowsize;
+ src = read_buff + src_offset;
+ dst = crop_buff + dst_offset + prev_width;
+
+ switch (shift_width)
+ {
+ case 0:
+ if (extractContigSamplesBytes(
+ src, dst, img_width, sample, spp, bps,
+ count, first_col, last_col + 1))
+ {
+ TIFFError("extractCompositeRegions",
+ "Unable to extract row %" PRIu32,
+ row);
+ return (1);
+ }
+ break;
+ case 1:
+ if (bps == 1)
+ {
+ if (extractContigSamplesShifted8bits(
+ src, dst, img_width, sample, spp, bps,
+ count, first_col, last_col + 1,
+ prev_trailing_bits))
+ {
+ TIFFError("extractCompositeRegions",
+ "Unable to extract row %" PRIu32,
+ row);
+ return (1);
+ }
+ break;
+ }
+ else if (extractContigSamplesShifted16bits(
+ src, dst, img_width, sample, spp, bps,
+ count, first_col, last_col + 1,
+ prev_trailing_bits))
+ {
+ TIFFError("extractCompositeRegions",
+ "Unable to extract row %" PRIu32,
+ row);
+ return (1);
+ }
+ break;
+ case 2:
+ if (extractContigSamplesShifted24bits(
+ src, dst, img_width, sample, spp, bps,
+ count, first_col, last_col + 1,
+ prev_trailing_bits))
+ {
+ TIFFError("extractCompositeRegions",
+ "Unable to extract row %" PRIu32,
+ row);
+ return (1);
+ }
+ break;
+ case 3:
+ case 4:
+ case 5:
+ if (extractContigSamplesShifted32bits(
+ src, dst, img_width, sample, spp, bps,
+ count, first_col, last_col + 1,
+ prev_trailing_bits))
+ {
+ TIFFError("extractCompositeRegions",
+ "Unable to extract row %" PRIu32,
+ row);
+ return (1);
+ }
+ break;
+ default:
+ TIFFError("extractCompositeRegions",
+ "Unsupported bit depth %" PRIu16, bps);
+ return (1);
+ }
+ }
+ prev_width += (crop_width * bps * count) / 8;
+ prev_trailing_bits += trailing_bits;
+ if (prev_trailing_bits > 7)
+ prev_trailing_bits -= 8;
+ break;
+ }
+ }
+ if (crop->combined_width != composite_width)
+ TIFFError("combineSeparateRegions",
+ "Combined width does not match composite width");
+
+ return (0);
+} /* end extractCompositeRegions */
+
+/* Copy a single region of input buffer to an output buffer.
+ * The read functions used copy separate plane data into a buffer
* as interleaved samples rather than separate planes so the same
- * logic works to extract regions regardless of the way the data
+ * logic works to extract regions regardless of the way the data
* are organized in the input file. This function can be used to
- * extract one or more samples from the input image by updating the
+ * extract one or more samples from the input image by updating the
* parameters for starting sample and number of samples to copy in the
* fifth and eighth arguments of the call to extractContigSamples.
* They would be passed as new elements of the crop_mask struct.
*/
-static int
-extractSeparateRegion(struct image_data *image, struct crop_mask *crop,
- unsigned char *read_buff, unsigned char *crop_buff,
- int region)
- {
- int shift_width, prev_trailing_bits = 0;
- uint32_t bytes_per_sample, bytes_per_pixel;
- uint32_t src_rowsize, dst_rowsize;
- uint32_t row, first_row, last_row, first_col, last_col;
- uint32_t src_offset, dst_offset;
- uint32_t crop_width, crop_length, img_width /*, img_length */;
- uint16_t bps, spp;
- uint8_t *src, *dst;
- tsample_t count, sample = 0; /* Update to extract more or more samples */
-
- img_width = image->width;
- /* img_length = image->length; */
- bps = image->bps;
- spp = image->spp;
- count = spp;
-
- bytes_per_sample = (bps + 7) / 8;
- bytes_per_pixel = ((bps * spp) + 7) / 8;
- if ((bps % 8) == 0)
- shift_width = 0; /* Byte aligned data only */
- else
- {
- if (bytes_per_pixel < (bytes_per_sample + 1))
- shift_width = bytes_per_pixel;
+static int extractSeparateRegion(struct image_data *image,
+ struct crop_mask *crop,
+ unsigned char *read_buff,
+ unsigned char *crop_buff, int region)
+{
+ int shift_width, prev_trailing_bits = 0;
+ uint32_t bytes_per_sample, bytes_per_pixel;
+ uint32_t src_rowsize, dst_rowsize;
+ uint32_t row, first_row, last_row, first_col, last_col;
+ uint32_t src_offset, dst_offset;
+ uint32_t crop_width, crop_length, img_width /*, img_length */;
+ uint16_t bps, spp;
+ uint8_t *src, *dst;
+ tsample_t count, sample = 0; /* Update to extract more or more samples */
+
+ img_width = image->width;
+ /* img_length = image->length; */
+ bps = image->bps;
+ spp = image->spp;
+ count = spp;
+
+ bytes_per_sample = (bps + 7) / 8;
+ bytes_per_pixel = ((bps * spp) + 7) / 8;
+ if ((bps % 8) == 0)
+ shift_width = 0; /* Byte aligned data only */
else
- shift_width = bytes_per_sample + 1;
- }
-
- /* rows, columns, width, length are expressed in pixels */
- first_row = crop->regionlist[region].y1;
- last_row = crop->regionlist[region].y2;
- first_col = crop->regionlist[region].x1;
- last_col = crop->regionlist[region].x2;
-
- crop_width = last_col - first_col + 1;
- crop_length = last_row - first_row + 1;
-
- crop->regionlist[region].width = crop_width;
- crop->regionlist[region].length = crop_length;
- crop->regionlist[region].buffptr = crop_buff;
-
- src = read_buff;
- dst = crop_buff;
- src_rowsize = ((img_width * bps * spp) + 7) / 8;
- dst_rowsize = (((crop_width * bps * spp) + 7) / 8);
-
- for (row = first_row; row <= last_row; row++)
- {
- src_offset = row * src_rowsize;
- dst_offset = (row - first_row) * dst_rowsize;
- src = read_buff + src_offset;
- dst = crop_buff + dst_offset;
-
- switch (shift_width)
- {
- case 0: if (extractContigSamplesBytes (src, dst, img_width, sample,
- spp, bps, count, first_col,
- last_col + 1))
- {
- TIFFError("extractSeparateRegion",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- case 1: if (bps == 1)
- {
- if (extractContigSamplesShifted8bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractSeparateRegion",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- }
- else
- if (extractContigSamplesShifted16bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractSeparateRegion",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractSeparateRegion",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- case 3:
- case 4:
- case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
- sample, spp, bps, count,
- first_col, last_col + 1,
- prev_trailing_bits))
- {
- TIFFError("extractSeparateRegion",
- "Unable to extract row %"PRIu32, row);
- return (1);
- }
- break;
- default: TIFFError("extractSeparateRegion", "Unsupported bit depth %"PRIu16, bps);
- return (1);
- }
- }
-
- return (0);
- } /* end extractSeparateRegion */
-
-static int
-extractImageSection(struct image_data *image, struct pageseg *section,
- unsigned char *src_buff, unsigned char *sect_buff)
- {
- unsigned char bytebuff1, bytebuff2;
+ {
+ if (bytes_per_pixel < (bytes_per_sample + 1))
+ shift_width = bytes_per_pixel;
+ else
+ shift_width = bytes_per_sample + 1;
+ }
+
+ /* rows, columns, width, length are expressed in pixels */
+ first_row = crop->regionlist[region].y1;
+ last_row = crop->regionlist[region].y2;
+ first_col = crop->regionlist[region].x1;
+ last_col = crop->regionlist[region].x2;
+
+ crop_width = last_col - first_col + 1;
+ crop_length = last_row - first_row + 1;
+
+ crop->regionlist[region].width = crop_width;
+ crop->regionlist[region].length = crop_length;
+ crop->regionlist[region].buffptr = crop_buff;
+
+ src = read_buff;
+ dst = crop_buff;
+ src_rowsize = ((img_width * bps * spp) + 7) / 8;
+ dst_rowsize = (((crop_width * bps * spp) + 7) / 8);
+
+ for (row = first_row; row <= last_row; row++)
+ {
+ src_offset = row * src_rowsize;
+ dst_offset = (row - first_row) * dst_rowsize;
+ src = read_buff + src_offset;
+ dst = crop_buff + dst_offset;
+
+ switch (shift_width)
+ {
+ case 0:
+ if (extractContigSamplesBytes(src, dst, img_width, sample, spp,
+ bps, count, first_col,
+ last_col + 1))
+ {
+ TIFFError("extractSeparateRegion",
+ "Unable to extract row %" PRIu32, row);
+ return (1);
+ }
+ break;
+ case 1:
+ if (bps == 1)
+ {
+ if (extractContigSamplesShifted8bits(
+ src, dst, img_width, sample, spp, bps, count,
+ first_col, last_col + 1, prev_trailing_bits))
+ {
+ TIFFError("extractSeparateRegion",
+ "Unable to extract row %" PRIu32, row);
+ return (1);
+ }
+ break;
+ }
+ else if (extractContigSamplesShifted16bits(
+ src, dst, img_width, sample, spp, bps, count,
+ first_col, last_col + 1, prev_trailing_bits))
+ {
+ TIFFError("extractSeparateRegion",
+ "Unable to extract row %" PRIu32, row);
+ return (1);
+ }
+ break;
+ case 2:
+ if (extractContigSamplesShifted24bits(
+ src, dst, img_width, sample, spp, bps, count, first_col,
+ last_col + 1, prev_trailing_bits))
+ {
+ TIFFError("extractSeparateRegion",
+ "Unable to extract row %" PRIu32, row);
+ return (1);
+ }
+ break;
+ case 3:
+ case 4:
+ case 5:
+ if (extractContigSamplesShifted32bits(
+ src, dst, img_width, sample, spp, bps, count, first_col,
+ last_col + 1, prev_trailing_bits))
+ {
+ TIFFError("extractSeparateRegion",
+ "Unable to extract row %" PRIu32, row);
+ return (1);
+ }
+ break;
+ default:
+ TIFFError("extractSeparateRegion",
+ "Unsupported bit depth %" PRIu16, bps);
+ return (1);
+ }
+ }
+
+ return (0);
+} /* end extractSeparateRegion */
+
+static int extractImageSection(struct image_data *image,
+ struct pageseg *section, unsigned char *src_buff,
+ unsigned char *sect_buff)
+{
+ unsigned char bytebuff1, bytebuff2;
#ifdef DEVELMODE
- /* unsigned char *src, *dst; */
+ /* unsigned char *src, *dst; */
#endif
- uint32_t img_width, img_rowsize;
+ uint32_t img_width, img_rowsize;
#ifdef DEVELMODE
- uint32_t img_length;
+ uint32_t img_length;
#endif
- uint32_t j, shift1, trailing_bits;
- uint32_t row, first_row, last_row, first_col, last_col;
- uint32_t src_offset, dst_offset, row_offset, col_offset;
- uint32_t offset1, full_bytes;
- uint32_t sect_width;
+ uint32_t j, shift1, trailing_bits;
+ uint32_t row, first_row, last_row, first_col, last_col;
+ uint32_t src_offset, dst_offset, row_offset, col_offset;
+ uint32_t offset1, full_bytes;
+ uint32_t sect_width;
#ifdef DEVELMODE
- uint32_t sect_length;
+ uint32_t sect_length;
#endif
- uint16_t bps, spp;
+ uint16_t bps, spp;
#ifdef DEVELMODE
- int k;
- unsigned char bitset;
+ int k;
+ unsigned char bitset;
#endif
- img_width = image->width;
+ img_width = image->width;
#ifdef DEVELMODE
- img_length = image->length;
+ img_length = image->length;
#endif
- bps = image->bps;
- spp = image->spp;
+ bps = image->bps;
+ spp = image->spp;
#ifdef DEVELMODE
- /* src = src_buff; */
- /* dst = sect_buff; */
+ /* src = src_buff; */
+ /* dst = sect_buff; */
#endif
- src_offset = 0;
- dst_offset = 0;
+ src_offset = 0;
+ dst_offset = 0;
#ifdef DEVELMODE
- char bitarray[39];
+ char bitarray[39];
#endif
- /* rows, columns, width, length are expressed in pixels
- * first_row, last_row, .. are index into image array starting at 0 to width-1,
- * last_col shall be also extracted. */
- first_row = section->y1;
- last_row = section->y2;
- first_col = section->x1;
- last_col = section->x2;
+ /* rows, columns, width, length are expressed in pixels
+ * first_row, last_row, .. are index into image array starting at 0 to
+ * width-1, last_col shall be also extracted. */
+ first_row = section->y1;
+ last_row = section->y2;
+ first_col = section->x1;
+ last_col = section->x2;
- sect_width = last_col - first_col + 1;
+ sect_width = last_col - first_col + 1;
#ifdef DEVELMODE
- sect_length = last_row - first_row + 1;
+ sect_length = last_row - first_row + 1;
#endif
- /* The read function loadImage() used copy separate plane data into a buffer as interleaved
- * samples rather than separate planes so the same logic works to extract regions
- * regardless of the way the data are organized in the input file.
- * Furthermore, bytes and bits are arranged in buffer according to COMPRESSION=1 and FILLORDER=1
+ /* The read function loadImage() used copy separate plane data into a buffer
+ * as interleaved samples rather than separate planes so the same logic
+ * works to extract regions regardless of the way the data are organized in
+ * the input file. Furthermore, bytes and bits are arranged in buffer
+ * according to COMPRESSION=1 and FILLORDER=1
*/
- img_rowsize = (((img_width * spp * bps) + 7) / 8); /* row size in full bytes of source image */
- full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */
- trailing_bits = (sect_width * spp * bps) % 8; /* trailing bits within the last byte of destination buffer */
+ img_rowsize = (((img_width * spp * bps) + 7) /
+ 8); /* row size in full bytes of source image */
+ full_bytes = (sect_width * spp * bps) /
+ 8; /* number of COMPLETE bytes per row in section */
+ trailing_bits =
+ (sect_width * spp * bps) %
+ 8; /* trailing bits within the last byte of destination buffer */
#ifdef DEVELMODE
- TIFFError ("", "First row: %"PRIu32", last row: %"PRIu32", First col: %"PRIu32", last col: %"PRIu32"\n",
- first_row, last_row, first_col, last_col);
- TIFFError ("", "Image width: %"PRIu32", Image length: %"PRIu32", bps: %"PRIu16", spp: %"PRIu16"\n",
- img_width, img_length, bps, spp);
- TIFFError ("", "Sect width: %"PRIu32", Sect length: %"PRIu32", full bytes: %"PRIu32" trailing bits %"PRIu32"\n",
- sect_width, sect_length, full_bytes, trailing_bits);
+ TIFFError("",
+ "First row: %" PRIu32 ", last row: %" PRIu32
+ ", First col: %" PRIu32 ", last col: %" PRIu32 "\n",
+ first_row, last_row, first_col, last_col);
+ TIFFError("",
+ "Image width: %" PRIu32 ", Image length: %" PRIu32
+ ", bps: %" PRIu16 ", spp: %" PRIu16 "\n",
+ img_width, img_length, bps, spp);
+ TIFFError("",
+ "Sect width: %" PRIu32 ", Sect length: %" PRIu32
+ ", full bytes: %" PRIu32 " trailing bits %" PRIu32 "\n",
+ sect_width, sect_length, full_bytes, trailing_bits);
#endif
- if ((bps % 8) == 0)
+ if ((bps % 8) == 0)
{
- col_offset = (first_col * spp * bps) / 8;
- for (row = first_row; row <= last_row; row++)
- {
- row_offset = row * img_rowsize;
- src_offset = row_offset + col_offset;
+ col_offset = (first_col * spp * bps) / 8;
+ for (row = first_row; row <= last_row; row++)
+ {
+ row_offset = row * img_rowsize;
+ src_offset = row_offset + col_offset;
#ifdef DEVELMODE
- TIFFError ("", "Src offset: %8"PRIu32", Dst offset: %8"PRIu32, src_offset, dst_offset);
+ TIFFError("", "Src offset: %8" PRIu32 ", Dst offset: %8" PRIu32,
+ src_offset, dst_offset);
#endif
- _TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes);
- dst_offset += full_bytes;
- }
+ _TIFFmemcpy(sect_buff + dst_offset, src_buff + src_offset,
+ full_bytes);
+ dst_offset += full_bytes;
+ }
}
- else
+ else
{ /* bps != 8 */
- shift1 = ((first_col * spp * bps) % 8); /* shift1 = bits to skip in the first byte of source buffer*/
- for (row = first_row; row <= last_row; row++)
- {
- /* pull out the first byte */
- row_offset = row * img_rowsize;
- offset1 = row_offset + ((first_col * spp * bps) / 8); /* offset1 = offset into source of byte with first bits to be extracted */
+ shift1 =
+ ((first_col * spp * bps) %
+ 8); /* shift1 = bits to skip in the first byte of source buffer*/
+ for (row = first_row; row <= last_row; row++)
+ {
+ /* pull out the first byte */
+ row_offset = row * img_rowsize;
+ offset1 = row_offset + ((first_col * spp * bps) /
+ 8); /* offset1 = offset into source of byte
+ with first bits to be extracted */
#ifdef DEVELMODE
- for (j = 0, k = 7; j < 8; j++, k--)
- {
- bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0;
- sprintf(&bitarray[j], (bitset) ? "1" : "0");
- }
- sprintf(&bitarray[8], " ");
- sprintf(&bitarray[9], " ");
- for (j = 10, k = 7; j < 18; j++, k--)
- {
- bitset = *(src_buff + offset1 + full_bytes) & (((unsigned char)1 << k)) ? 1 : 0;
- sprintf(&bitarray[j], (bitset) ? "1" : "0");
- }
- bitarray[18] = '\0';
- TIFFError ("", "Row: %3d Offset1: %"PRIu32", Shift1: %"PRIu32", Offset2: %"PRIu32", Trailing_bits: %"PRIu32"\n",
- row, offset1, shift1, offset1+full_bytes, trailing_bits);
+ for (j = 0, k = 7; j < 8; j++, k--)
+ {
+ bitset =
+ *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0;
+ sprintf(&bitarray[j], (bitset) ? "1" : "0");
+ }
+ sprintf(&bitarray[8], " ");
+ sprintf(&bitarray[9], " ");
+ for (j = 10, k = 7; j < 18; j++, k--)
+ {
+ bitset = *(src_buff + offset1 + full_bytes) &
+ (((unsigned char)1 << k))
+ ? 1
+ : 0;
+ sprintf(&bitarray[j], (bitset) ? "1" : "0");
+ }
+ bitarray[18] = '\0';
+ TIFFError(
+ "",
+ "Row: %3d Offset1: %" PRIu32 ", Shift1: %" PRIu32
+ ", Offset2: %" PRIu32 ", Trailing_bits: %" PRIu32 "\n",
+ row, offset1, shift1, offset1 + full_bytes, trailing_bits);
#endif
- bytebuff1 = bytebuff2 = 0;
- if (shift1 == 0) /* the region is byte and sample aligned */
- {
- _TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes);
+ bytebuff1 = bytebuff2 = 0;
+ if (shift1 == 0) /* the region is byte and sample aligned */
+ {
+ _TIFFmemcpy(sect_buff + dst_offset, src_buff + offset1,
+ full_bytes);
#ifdef DEVELMODE
- TIFFError ("", " Aligned data src offset1: %8"PRIu32", Dst offset: %8"PRIu32"\n", offset1, dst_offset);
- sprintf(&bitarray[18], "\n");
- sprintf(&bitarray[19], "\t");
- for (j = 20, k = 7; j < 28; j++, k--)
- {
- bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
- sprintf(&bitarray[j], (bitset) ? "1" : "0");
- }
- bitarray[28] = ' ';
- bitarray[29] = ' ';
+ TIFFError("",
+ " Aligned data src offset1: %8" PRIu32
+ ", Dst offset: %8" PRIu32 "\n",
+ offset1, dst_offset);
+ sprintf(&bitarray[18], "\n");
+ sprintf(&bitarray[19], "\t");
+ for (j = 20, k = 7; j < 28; j++, k--)
+ {
+ bitset =
+ *(sect_buff + dst_offset) & (((unsigned char)1 << k))
+ ? 1
+ : 0;
+ sprintf(&bitarray[j], (bitset) ? "1" : "0");
+ }
+ bitarray[28] = ' ';
+ bitarray[29] = ' ';
#endif
- dst_offset += full_bytes;
+ dst_offset += full_bytes;
- if (trailing_bits != 0)
- {
- /* Only copy higher bits of samples and mask lower bits of not wanted column samples to zero */
- bytebuff2 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (8 - trailing_bits));
- sect_buff[dst_offset] = bytebuff2;
+ if (trailing_bits != 0)
+ {
+ /* Only copy higher bits of samples and mask lower bits of
+ * not wanted column samples to zero */
+ bytebuff2 = src_buff[offset1 + full_bytes] &
+ ((unsigned char)255 << (8 - trailing_bits));
+ sect_buff[dst_offset] = bytebuff2;
#ifdef DEVELMODE
- TIFFError ("", " Trailing bits src offset: %8"PRIu32", Dst offset: %8"PRIu32"\n",
- offset1 + full_bytes, dst_offset);
- for (j = 30, k = 7; j < 38; j++, k--)
- {
- bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
- sprintf(&bitarray[j], (bitset) ? "1" : "0");
- }
- bitarray[38] = '\0';
- TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray);
+ TIFFError("",
+ " Trailing bits src offset: %8" PRIu32
+ ", Dst offset: %8" PRIu32 "\n",
+ offset1 + full_bytes, dst_offset);
+ for (j = 30, k = 7; j < 38; j++, k--)
+ {
+ bitset = *(sect_buff + dst_offset) &
+ (((unsigned char)1 << k))
+ ? 1
+ : 0;
+ sprintf(&bitarray[j], (bitset) ? "1" : "0");
+ }
+ bitarray[38] = '\0';
+ TIFFError("",
+ "\tFirst and last bytes before and after "
+ "masking:\n\t%s\n\n",
+ bitarray);
#endif
- dst_offset++;
- }
- }
- else /* each destination byte will have to be built from two source bytes*/
- {
+ dst_offset++;
+ }
+ }
+ else /* each destination byte will have to be built from two source
+ bytes*/
+ {
#ifdef DEVELMODE
- TIFFError ("", " Unalligned data src offset: %8"PRIu32", Dst offset: %8"PRIu32"\n", offset1 , dst_offset);
+ TIFFError("",
+ " Unalligned data src offset: %8" PRIu32
+ ", Dst offset: %8" PRIu32 "\n",
+ offset1, dst_offset);
#endif
- for (j = 0; j <= full_bytes; j++)
- {
- /* Skip the first shift1 bits and shift the source up by shift1 bits before save to destination.*/
- /* Attention: src_buff size needs to be some bytes larger than image size, because could read behind image here. */
- bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1);
- bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (8 - shift1));
- sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1));
- }
+ for (j = 0; j <= full_bytes; j++)
+ {
+ /* Skip the first shift1 bits and shift the source up by
+ * shift1 bits before save to destination.*/
+ /* Attention: src_buff size needs to be some bytes larger
+ * than image size, because could read behind image here. */
+ bytebuff1 =
+ src_buff[offset1 + j] & ((unsigned char)255 >> shift1);
+ bytebuff2 = src_buff[offset1 + j + 1] &
+ ((unsigned char)255 << (8 - shift1));
+ sect_buff[dst_offset + j] =
+ (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1));
+ }
#ifdef DEVELMODE
- sprintf(&bitarray[18], "\n");
- sprintf(&bitarray[19], "\t");
- for (j = 20, k = 7; j < 28; j++, k--)
- {
- bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
- sprintf(&bitarray[j], (bitset) ? "1" : "0");
- }
- bitarray[28] = ' ';
- bitarray[29] = ' ';
+ sprintf(&bitarray[18], "\n");
+ sprintf(&bitarray[19], "\t");
+ for (j = 20, k = 7; j < 28; j++, k--)
+ {
+ bitset =
+ *(sect_buff + dst_offset) & (((unsigned char)1 << k))
+ ? 1
+ : 0;
+ sprintf(&bitarray[j], (bitset) ? "1" : "0");
+ }
+ bitarray[28] = ' ';
+ bitarray[29] = ' ';
#endif
- dst_offset += full_bytes;
+ dst_offset += full_bytes;
- /* Copy the trailing_bits for the last byte in the destination buffer.
- Could come from one ore two bytes of the source buffer. */
- if (trailing_bits != 0)
- {
+ /* Copy the trailing_bits for the last byte in the destination
+ buffer. Could come from one ore two bytes of the source
+ buffer. */
+ if (trailing_bits != 0)
+ {
#ifdef DEVELMODE
- TIFFError("", " Trailing bits %4"PRIu32" src offset: %8"PRIu32", Dst offset: %8"PRIu32"\n", trailing_bits, offset1 + full_bytes, dst_offset);
+ TIFFError("",
+ " Trailing bits %4" PRIu32
+ " src offset: %8" PRIu32
+ ", Dst offset: %8" PRIu32 "\n",
+ trailing_bits, offset1 + full_bytes, dst_offset);
#endif
- /* More than necessary bits are already copied into last destination buffer,
- * only masking of last byte in destination buffer is necessary.*/
- sect_buff[dst_offset] &= ((uint8_t)0xFF << (8 - trailing_bits));
- }
+ /* More than necessary bits are already copied into last
+ * destination buffer, only masking of last byte in
+ * destination buffer is necessary.*/
+ sect_buff[dst_offset] &=
+ ((uint8_t)0xFF << (8 - trailing_bits));
+ }
#ifdef DEVELMODE
- sprintf(&bitarray[28], " ");
- sprintf(&bitarray[29], " ");
- for (j = 30, k = 7; j < 38; j++, k--)
+ sprintf(&bitarray[28], " ");
+ sprintf(&bitarray[29], " ");
+ for (j = 30, k = 7; j < 38; j++, k--)
+ {
+ bitset =
+ *(sect_buff + dst_offset) & (((unsigned char)1 << k))
+ ? 1
+ : 0;
+ sprintf(&bitarray[j], (bitset) ? "1" : "0");
+ }
+ bitarray[38] = '\0';
+ TIFFError("",
+ "\tFirst and last bytes before and after "
+ "masking:\n\t%s\n\n",
+ bitarray);
+#endif
+ dst_offset++;
+ }
+ }
+ }
+
+ return (0);
+} /* end extractImageSection */
+
+static int writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop,
+ struct image_data *image, struct dump_opts *dump,
+ struct buffinfo seg_buffs[], char *mp,
+ char *filename, unsigned int *page,
+ unsigned int total_pages)
+{
+ int i, page_count;
+ int autoindex = 0;
+ unsigned char *crop_buff = NULL;
+
+ /* Where we open a new file depends on the export mode */
+ switch (crop->exp_mode)
+ {
+ case ONE_FILE_COMPOSITE: /* Regions combined into single image */
+ autoindex = 0;
+ crop_buff = seg_buffs[0].buffer;
+ if (update_output_file(out, mp, autoindex, filename, page))
+ return (1);
+ page_count = total_pages;
+ if (writeCroppedImage(in, *out, image, dump, crop->combined_width,
+ crop->combined_length, crop_buff, *page,
+ total_pages))
{
- bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
- sprintf(&bitarray[j], (bitset) ? "1" : "0");
+ TIFFError("writeRegions", "Unable to write new image");
+ return (-1);
}
- bitarray[38] = '\0';
- TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray);
-#endif
- dst_offset++;
- }
- }
- }
-
- return (0);
- } /* end extractImageSection */
-
-static int
-writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop,
- struct image_data *image, struct dump_opts *dump,
- struct buffinfo seg_buffs[], char *mp, char *filename,
- unsigned int *page, unsigned int total_pages)
- {
- int i, page_count;
- int autoindex = 0;
- unsigned char *crop_buff = NULL;
-
- /* Where we open a new file depends on the export mode */
- switch (crop->exp_mode)
- {
- case ONE_FILE_COMPOSITE: /* Regions combined into single image */
- autoindex = 0;
- crop_buff = seg_buffs[0].buffer;
- if (update_output_file (out, mp, autoindex, filename, page))
- return (1);
- page_count = total_pages;
- if (writeCroppedImage(in, *out, image, dump,
- crop->combined_width,
- crop->combined_length,
- crop_buff, *page, total_pages))
- {
- TIFFError("writeRegions", "Unable to write new image");
- return (-1);
- }
- break;
- case ONE_FILE_SEPARATED: /* Regions as separated images */
- autoindex = 0;
- if (update_output_file (out, mp, autoindex, filename, page))
- return (1);
- page_count = crop->selections * total_pages;
- for (i = 0; i < crop->selections; i++)
- {
- crop_buff = seg_buffs[i].buffer;
- if (writeCroppedImage(in, *out, image, dump,
- crop->regionlist[i].width,
- crop->regionlist[i].length,
- crop_buff, *page, page_count))
- {
- TIFFError("writeRegions", "Unable to write new image");
- return (-1);
- }
- }
- break;
- case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */
- autoindex = 1;
- if (update_output_file (out, mp, autoindex, filename, page))
- return (1);
-
- crop_buff = seg_buffs[0].buffer;
- if (writeCroppedImage(in, *out, image, dump,
- crop->combined_width,
- crop->combined_length,
- crop_buff, *page, total_pages))
- {
- TIFFError("writeRegions", "Unable to write new image");
- return (-1);
- }
- break;
- case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */
- autoindex = 1;
- page_count = crop->selections;
- if (update_output_file (out, mp, autoindex, filename, page))
- return (1);
-
- for (i = 0; i < crop->selections; i++)
- {
- crop_buff = seg_buffs[i].buffer;
- /* Write the current region to the current file */
- if (writeCroppedImage(in, *out, image, dump,
- crop->regionlist[i].width,
- crop->regionlist[i].length,
- crop_buff, *page, page_count))
- {
- TIFFError("writeRegions", "Unable to write new image");
- return (-1);
- }
- }
- break;
- case FILE_PER_SELECTION:
- autoindex = 1;
- page_count = 1;
- for (i = 0; i < crop->selections; i++)
- {
- if (update_output_file (out, mp, autoindex, filename, page))
- return (1);
-
- crop_buff = seg_buffs[i].buffer;
- /* Write the current region to the current file */
- if (writeCroppedImage(in, *out, image, dump,
- crop->regionlist[i].width,
- crop->regionlist[i].length,
- crop_buff, *page, page_count))
- {
- TIFFError("writeRegions", "Unable to write new image");
- return (-1);
- }
- }
- break;
- default: return (1);
- }
-
- return (0);
- } /* end writeRegions */
-
-static int
-writeImageSections(TIFF *in, TIFF *out, struct image_data *image,
- struct pagedef *page, struct pageseg *sections,
- struct dump_opts * dump, unsigned char *src_buff,
- unsigned char **sect_buff_ptr)
- {
- double hres, vres;
- uint32_t i, k, width, length, sectsize;
- unsigned char *sect_buff = *sect_buff_ptr;
-
- hres = page->hres;
- vres = page->vres;
-
- k = page->cols * page->rows;
- if ((k < 1) || (k > MAX_SECTIONS))
- {
- TIFFError("writeImageSections",
- "%"PRIu32" Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k);
- return (-1);
- }
-
- for (i = 0; i < k; i++)
- {
- width = sections[i].x2 - sections[i].x1 + 1;
- length = sections[i].y2 - sections[i].y1 + 1;
- sectsize = (uint32_t)
- ceil((width * image->bps * image->spp + 7) / (double)8) * length;
- /* allocate a buffer if we don't have one already */
- if (createImageSection(sectsize, sect_buff_ptr))
- {
- TIFFError("writeImageSections", "Unable to allocate section buffer");
- exit(EXIT_FAILURE);
- }
- sect_buff = *sect_buff_ptr;
+ break;
+ case ONE_FILE_SEPARATED: /* Regions as separated images */
+ autoindex = 0;
+ if (update_output_file(out, mp, autoindex, filename, page))
+ return (1);
+ page_count = crop->selections * total_pages;
+ for (i = 0; i < crop->selections; i++)
+ {
+ crop_buff = seg_buffs[i].buffer;
+ if (writeCroppedImage(in, *out, image, dump,
+ crop->regionlist[i].width,
+ crop->regionlist[i].length, crop_buff,
+ *page, page_count))
+ {
+ TIFFError("writeRegions", "Unable to write new image");
+ return (-1);
+ }
+ }
+ break;
+ case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */
+ autoindex = 1;
+ if (update_output_file(out, mp, autoindex, filename, page))
+ return (1);
- if (extractImageSection (image, &sections[i], src_buff, sect_buff))
- {
- TIFFError("writeImageSections", "Unable to extract image sections");
- exit(EXIT_FAILURE);
- }
+ crop_buff = seg_buffs[0].buffer;
+ if (writeCroppedImage(in, *out, image, dump, crop->combined_width,
+ crop->combined_length, crop_buff, *page,
+ total_pages))
+ {
+ TIFFError("writeRegions", "Unable to write new image");
+ return (-1);
+ }
+ break;
+ case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */
+ autoindex = 1;
+ page_count = crop->selections;
+ if (update_output_file(out, mp, autoindex, filename, page))
+ return (1);
- /* call the write routine here instead of outside the loop */
- if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff))
- {
- TIFFError("writeImageSections", "Unable to write image section");
- exit(EXIT_FAILURE);
- }
+ for (i = 0; i < crop->selections; i++)
+ {
+ crop_buff = seg_buffs[i].buffer;
+ /* Write the current region to the current file */
+ if (writeCroppedImage(in, *out, image, dump,
+ crop->regionlist[i].width,
+ crop->regionlist[i].length, crop_buff,
+ *page, page_count))
+ {
+ TIFFError("writeRegions", "Unable to write new image");
+ return (-1);
+ }
+ }
+ break;
+ case FILE_PER_SELECTION:
+ autoindex = 1;
+ page_count = 1;
+ for (i = 0; i < crop->selections; i++)
+ {
+ if (update_output_file(out, mp, autoindex, filename, page))
+ return (1);
+
+ crop_buff = seg_buffs[i].buffer;
+ /* Write the current region to the current file */
+ if (writeCroppedImage(in, *out, image, dump,
+ crop->regionlist[i].width,
+ crop->regionlist[i].length, crop_buff,
+ *page, page_count))
+ {
+ TIFFError("writeRegions", "Unable to write new image");
+ return (-1);
+ }
+ }
+ break;
+ default:
+ return (1);
}
- return (0);
- } /* end writeImageSections */
+ return (0);
+} /* end writeRegions */
+
+static int writeImageSections(TIFF *in, TIFF *out, struct image_data *image,
+ struct pagedef *page, struct pageseg *sections,
+ struct dump_opts *dump, unsigned char *src_buff,
+ unsigned char **sect_buff_ptr)
+{
+ double hres, vres;
+ uint32_t i, k, width, length, sectsize;
+ unsigned char *sect_buff = *sect_buff_ptr;
+
+ hres = page->hres;
+ vres = page->vres;
+
+ k = page->cols * page->rows;
+ if ((k < 1) || (k > MAX_SECTIONS))
+ {
+ TIFFError("writeImageSections",
+ "%" PRIu32 " Rows and Columns exceed maximum "
+ "sections\nIncrease resolution or reduce sections",
+ k);
+ return (-1);
+ }
+
+ for (i = 0; i < k; i++)
+ {
+ width = sections[i].x2 - sections[i].x1 + 1;
+ length = sections[i].y2 - sections[i].y1 + 1;
+ sectsize =
+ (uint32_t)ceil((width * image->bps * image->spp + 7) / (double)8) *
+ length;
+ /* allocate a buffer if we don't have one already */
+ if (createImageSection(sectsize, sect_buff_ptr))
+ {
+ TIFFError("writeImageSections",
+ "Unable to allocate section buffer");
+ exit(EXIT_FAILURE);
+ }
+ sect_buff = *sect_buff_ptr;
+
+ if (extractImageSection(image, &sections[i], src_buff, sect_buff))
+ {
+ TIFFError("writeImageSections", "Unable to extract image sections");
+ exit(EXIT_FAILURE);
+ }
+
+ /* call the write routine here instead of outside the loop */
+ if (writeSingleSection(in, out, image, dump, width, length, hres, vres,
+ sect_buff))
+ {
+ TIFFError("writeImageSections", "Unable to write image section");
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ return (0);
+} /* end writeImageSections */
/* Code in this function is heavily indebted to code in tiffcp
* with modifications by Richard Nolde to handle orientation correctly.
* It will have to be updated significantly if support is added to
- * extract one or more samples from original image since the
+ * extract one or more samples from original image since the
* original code assumes we are always copying all samples.
*/
-static int
-writeSingleSection(TIFF *in, TIFF *out, struct image_data *image,
- struct dump_opts *dump, uint32_t width, uint32_t length,
- double hres, double vres,
- unsigned char *sect_buff)
- {
- uint16_t bps, spp;
- uint16_t input_compression, input_photometric;
- uint16_t input_planar;
- const struct cpTag* p;
-
- /* Calling this seems to reset the compression mode on the TIFF *in file.
- TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode);
- */
- input_compression = image->compression;
- input_photometric = image->photometric;
-
- spp = image->spp;
- bps = image->bps;
- TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
- TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
+static int writeSingleSection(TIFF *in, TIFF *out, struct image_data *image,
+ struct dump_opts *dump, uint32_t width,
+ uint32_t length, double hres, double vres,
+ unsigned char *sect_buff)
+{
+ uint16_t bps, spp;
+ uint16_t input_compression, input_photometric;
+ uint16_t input_planar;
+ const struct cpTag *p;
+
+ /* Calling this seems to reset the compression mode on the TIFF *in file.
+ TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode);
+ */
+ input_compression = image->compression;
+ input_photometric = image->photometric;
+
+ spp = image->spp;
+ bps = image->bps;
+ TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
+ TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
#ifdef DEBUG2
- TIFFError("writeSingleSection", "Input compression: %s",
- (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" :
- ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg"));
+ TIFFError("writeSingleSection", "Input compression: %s",
+ (input_compression == COMPRESSION_OJPEG)
+ ? "Old Jpeg"
+ : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg"
+ : "Non Jpeg"));
#endif
- /* This is the global variable compression which is set
- * if the user has specified a command line option for
- * a compression option. Should be passed around in one
- * of the parameters instead of as a global. If no user
- * option specified it will still be (uint16_t) -1. */
- if (compression != (uint16_t)-1)
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- else
- { /* OJPEG is no longer supported for writing so upgrade to JPEG */
- if (input_compression == COMPRESSION_OJPEG)
- {
- compression = COMPRESSION_JPEG;
- jpegcolormode = JPEGCOLORMODE_RAW;
- TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
- }
- else /* Use the compression from the input file */
- CopyField(TIFFTAG_COMPRESSION, compression);
- }
-
- if (compression == COMPRESSION_JPEG)
- {
- if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */
- (input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */
- {
- TIFFError ("writeSingleSection",
- "JPEG compression cannot be used with %s image data",
- (input_photometric == PHOTOMETRIC_PALETTE) ?
- "palette" : "mask");
- return (-1);
- }
- if ((input_photometric == PHOTOMETRIC_RGB) &&
- (jpegcolormode == JPEGCOLORMODE_RGB))
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
+ /* This is the global variable compression which is set
+ * if the user has specified a command line option for
+ * a compression option. Should be passed around in one
+ * of the parameters instead of as a global. If no user
+ * option specified it will still be (uint16_t) -1. */
+ if (compression != (uint16_t)-1)
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
+ { /* OJPEG is no longer supported for writing so upgrade to JPEG */
+ if (input_compression == COMPRESSION_OJPEG)
+ {
+ compression = COMPRESSION_JPEG;
+ jpegcolormode = JPEGCOLORMODE_RAW;
+ TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
+ }
+ else /* Use the compression from the input file */
+ CopyField(TIFFTAG_COMPRESSION, compression);
}
- else
+
+ if (compression == COMPRESSION_JPEG)
{
- if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24)
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
- PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
+ if ((input_photometric ==
+ PHOTOMETRIC_PALETTE) || /* color map indexed */
+ (input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */
+ {
+ TIFFError("writeSingleSection",
+ "JPEG compression cannot be used with %s image data",
+ (input_photometric == PHOTOMETRIC_PALETTE) ? "palette"
+ : "mask");
+ return (-1);
+ }
+ if ((input_photometric == PHOTOMETRIC_RGB) &&
+ (jpegcolormode == JPEGCOLORMODE_RGB))
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
+ else
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
+ }
else
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
+ {
+ if (compression == COMPRESSION_SGILOG ||
+ compression == COMPRESSION_SGILOG24)
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC,
+ spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
+ else
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
}
#ifdef DEBUG2
- TIFFError("writeSingleSection", "Input photometric: %s",
- (input_photometric == PHOTOMETRIC_RGB) ? "RGB" :
- ((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr"));
+ TIFFError("writeSingleSection", "Input photometric: %s",
+ (input_photometric == PHOTOMETRIC_RGB)
+ ? "RGB"
+ : ((input_photometric == PHOTOMETRIC_YCBCR)
+ ? "YCbCr"
+ : "Not RGB or YCbCr"));
#endif
- if (((input_photometric == PHOTOMETRIC_LOGL) ||
- (input_photometric == PHOTOMETRIC_LOGLUV)) &&
- ((compression != COMPRESSION_SGILOG) &&
- (compression != COMPRESSION_SGILOG24)))
- {
- TIFFError("writeSingleSection",
- "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression");
- return (-1);
- }
-
- if (fillorder != 0)
- TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
- else
- CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
-
- /* The loadimage function reads input orientation and sets
- * image->orientation. The correct_image_orientation function
- * applies the required rotation and mirror operations to
- * present the data in TOPLEFT orientation and updates
- * image->orientation if any transforms are performed,
- * as per EXIF standard.
- */
- TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
-
- /*
- * Choose tiles/strip for the output image according to
- * the command line arguments (-tiles, -strips) and the
- * structure of the input image.
- */
- if (outtiled == -1)
- outtiled = TIFFIsTiled(in);
- if (outtiled) {
- /*
- * Setup output file's tile width&height. If either
- * is not specified, use either the value from the
- * input image or, if nothing is defined, use the
- * library default.
+ if (((input_photometric == PHOTOMETRIC_LOGL) ||
+ (input_photometric == PHOTOMETRIC_LOGLUV)) &&
+ ((compression != COMPRESSION_SGILOG) &&
+ (compression != COMPRESSION_SGILOG24)))
+ {
+ TIFFError("writeSingleSection", "LogL and LogLuv source data require "
+ "SGI_LOG or SGI_LOG24 compression");
+ return (-1);
+ }
+
+ if (fillorder != 0)
+ TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
+ else
+ CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
+
+ /* The loadimage function reads input orientation and sets
+ * image->orientation. The correct_image_orientation function
+ * applies the required rotation and mirror operations to
+ * present the data in TOPLEFT orientation and updates
+ * image->orientation if any transforms are performed,
+ * as per EXIF standard.
*/
- if (tilewidth == (uint32_t) 0)
- TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
- if (tilelength == (uint32_t) 0)
- TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
-
- if (tilewidth == 0 || tilelength == 0)
- TIFFDefaultTileSize(out, &tilewidth, &tilelength);
- TIFFDefaultTileSize(out, &tilewidth, &tilelength);
- TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
- TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
- } else {
- /*
- * RowsPerStrip is left unspecified: use either the
- * value from the input image or, if nothing is defined,
- * use the library default.
- */
- if (rowsperstrip == (uint32_t) 0)
- {
- if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
- rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
- if (compression != COMPRESSION_JPEG)
- {
- if (rowsperstrip > length)
- rowsperstrip = length;
- }
- }
- else
- if (rowsperstrip == (uint32_t) -1)
- rowsperstrip = length;
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
- }
-
- TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
- if (config != (uint16_t) -1)
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
- else
- CopyField(TIFFTAG_PLANARCONFIG, config);
- if (spp <= 4)
- CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
- CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
-
-/* SMinSampleValue & SMaxSampleValue */
- switch (compression) {
- /* These are references to GLOBAL variables set by defaults
- * and /or the compression flag
+ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
+
+ /*
+ * Choose tiles/strip for the output image according to
+ * the command line arguments (-tiles, -strips) and the
+ * structure of the input image.
*/
- case COMPRESSION_JPEG:
- if (((bps % 8) == 0) || ((bps % 12) == 0))
- {
- TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
- TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
- }
- else
- {
- TIFFError("writeSingleSection",
- "JPEG compression requires 8 or 12 bits per sample");
- return (-1);
- }
- break;
- case COMPRESSION_LZW:
- case COMPRESSION_ADOBE_DEFLATE:
- case COMPRESSION_DEFLATE:
- if (predictor != (uint16_t)-1)
- TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
- else
- CopyField(TIFFTAG_PREDICTOR, predictor);
- break;
- case COMPRESSION_CCITTFAX3:
- case COMPRESSION_CCITTFAX4:
- if (bps != 1) {
- TIFFError("writeCroppedImage",
- "Group 3/4 compression is not usable with bps > 1");
- return (-1);
- }
- if (compression == COMPRESSION_CCITTFAX3) {
- if (g3opts != (uint32_t) -1)
- TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
- else
- CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
- } else {
- CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
- }
- CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
- CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
- CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
- CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
- CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
- CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
- break;
- }
- { uint32_t len32;
- void** data;
- if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
- TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
- }
- { uint16_t ninks;
- const char* inknames;
- if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
- TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
- if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
- int inknameslen = (int)strlen(inknames) + 1;
- const char* cp = inknames;
- while (ninks > 1) {
- cp = strchr(cp, '\0');
- if (cp) {
- cp++;
- inknameslen += ((int)strlen(cp) + 1);
- }
- ninks--;
- }
- TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
- }
- }
- }
- {
- unsigned short pg0, pg1;
- if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
- if (pageNum < 0) /* only one input file */
- TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
- else
- TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
- }
- }
-
- for (p = tags; p < &tags[NTAGS]; p++)
- CopyTag(p->tag, p->count, p->type);
-
- /* Update these since they are overwritten from input res by loop above */
- TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres);
- TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres);
-
- /* Compute the tile or strip dimensions and write to disk */
- if (outtiled)
- {
- if (config == PLANARCONFIG_CONTIG)
- writeBufferToContigTiles (out, sect_buff, length, width, spp, dump);
- else
- writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump);
+ if (outtiled == -1)
+ outtiled = TIFFIsTiled(in);
+ if (outtiled)
+ {
+ /*
+ * Setup output file's tile width&height. If either
+ * is not specified, use either the value from the
+ * input image or, if nothing is defined, use the
+ * library default.
+ */
+ if (tilewidth == (uint32_t)0)
+ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
+ if (tilelength == (uint32_t)0)
+ TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
+
+ if (tilewidth == 0 || tilelength == 0)
+ TIFFDefaultTileSize(out, &tilewidth, &tilelength);
+ TIFFDefaultTileSize(out, &tilewidth, &tilelength);
+ TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
+ TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
}
- else
+ else
{
- if (config == PLANARCONFIG_CONTIG)
- writeBufferToContigStrips (out, sect_buff, length);
+ /*
+ * RowsPerStrip is left unspecified: use either the
+ * value from the input image or, if nothing is defined,
+ * use the library default.
+ */
+ if (rowsperstrip == (uint32_t)0)
+ {
+ if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
+ rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
+ if (compression != COMPRESSION_JPEG)
+ {
+ if (rowsperstrip > length)
+ rowsperstrip = length;
+ }
+ }
+ else if (rowsperstrip == (uint32_t)-1)
+ rowsperstrip = length;
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
+ }
+
+ TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
+ if (config != (uint16_t)-1)
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
- writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump);
+ CopyField(TIFFTAG_PLANARCONFIG, config);
+ if (spp <= 4)
+ CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
+ CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
+
+ /* SMinSampleValue & SMaxSampleValue */
+ switch (compression)
+ {
+ /* These are references to GLOBAL variables set by defaults
+ * and /or the compression flag
+ */
+ case COMPRESSION_JPEG:
+ if (((bps % 8) == 0) || ((bps % 12) == 0))
+ {
+ TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
+ TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
+ }
+ else
+ {
+ TIFFError("writeSingleSection",
+ "JPEG compression requires 8 or 12 bits per sample");
+ return (-1);
+ }
+ break;
+ case COMPRESSION_LZW:
+ case COMPRESSION_ADOBE_DEFLATE:
+ case COMPRESSION_DEFLATE:
+ if (predictor != (uint16_t)-1)
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
+ else
+ CopyField(TIFFTAG_PREDICTOR, predictor);
+ break;
+ case COMPRESSION_CCITTFAX3:
+ case COMPRESSION_CCITTFAX4:
+ if (bps != 1)
+ {
+ TIFFError("writeCroppedImage",
+ "Group 3/4 compression is not usable with bps > 1");
+ return (-1);
+ }
+ if (compression == COMPRESSION_CCITTFAX3)
+ {
+ if (g3opts != (uint32_t)-1)
+ TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
+ else
+ CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
+ }
+ else
+ {
+ CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
+ }
+ CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
+ break;
+ }
+ {
+ uint32_t len32;
+ void **data;
+ if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
+ TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
+ }
+ {
+ uint16_t ninks;
+ const char *inknames;
+ if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks))
+ {
+ TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
+ if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames))
+ {
+ int inknameslen = (int)strlen(inknames) + 1;
+ const char *cp = inknames;
+ while (ninks > 1)
+ {
+ cp = strchr(cp, '\0');
+ if (cp)
+ {
+ cp++;
+ inknameslen += ((int)strlen(cp) + 1);
+ }
+ ninks--;
+ }
+ TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
+ }
+ }
+ }
+ {
+ unsigned short pg0, pg1;
+ if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1))
+ {
+ if (pageNum < 0) /* only one input file */
+ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
+ else
+ TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
+ }
}
- if (!TIFFWriteDirectory(out))
+ for (p = tags; p < &tags[NTAGS]; p++)
+ CopyTag(p->tag, p->count, p->type);
+
+ /* Update these since they are overwritten from input res by loop above */
+ TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres);
+ TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres);
+
+ /* Compute the tile or strip dimensions and write to disk */
+ if (outtiled)
{
- TIFFClose(out);
- return (-1);
+ if (config == PLANARCONFIG_CONTIG)
+ writeBufferToContigTiles(out, sect_buff, length, width, spp, dump);
+ else
+ writeBufferToSeparateTiles(out, sect_buff, length, width, spp,
+ dump);
+ }
+ else
+ {
+ if (config == PLANARCONFIG_CONTIG)
+ writeBufferToContigStrips(out, sect_buff, length);
+ else
+ writeBufferToSeparateStrips(out, sect_buff, length, width, spp,
+ dump);
}
- return (0);
- } /* end writeSingleSection */
+ if (!TIFFWriteDirectory(out))
+ {
+ TIFFClose(out);
+ return (-1);
+ }
+ return (0);
+} /* end writeSingleSection */
/* Create a buffer to write one section at a time */
-static int
-createImageSection(uint32_t sectsize, unsigned char **sect_buff_ptr)
- {
- unsigned char *sect_buff = NULL;
- unsigned char *new_buff = NULL;
- static uint32_t prev_sectsize = 0;
-
- sect_buff = *sect_buff_ptr;
-
- if (!sect_buff)
- {
- sect_buff = (unsigned char *)limitMalloc(sectsize + NUM_BUFF_OVERSIZE_BYTES);
+static int createImageSection(uint32_t sectsize, unsigned char **sect_buff_ptr)
+{
+ unsigned char *sect_buff = NULL;
+ unsigned char *new_buff = NULL;
+ static uint32_t prev_sectsize = 0;
+
+ sect_buff = *sect_buff_ptr;
+
if (!sect_buff)
{
- TIFFError("createImageSection", "Unable to allocate/reallocate section buffer");
- return (-1);
- }
- _TIFFmemset(sect_buff, 0, sectsize + NUM_BUFF_OVERSIZE_BYTES);
+ sect_buff =
+ (unsigned char *)limitMalloc(sectsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (!sect_buff)
+ {
+ TIFFError("createImageSection",
+ "Unable to allocate/reallocate section buffer");
+ return (-1);
+ }
+ _TIFFmemset(sect_buff, 0, sectsize + NUM_BUFF_OVERSIZE_BYTES);
}
- else
+ else
{
- if (prev_sectsize < sectsize)
- {
- new_buff = _TIFFrealloc(sect_buff, sectsize + NUM_BUFF_OVERSIZE_BYTES);
- if (!new_buff)
+ if (prev_sectsize < sectsize)
{
- _TIFFfree (sect_buff);
- sect_buff = (unsigned char *)limitMalloc(sectsize + NUM_BUFF_OVERSIZE_BYTES);
- }
- else
- sect_buff = new_buff;
+ new_buff =
+ _TIFFrealloc(sect_buff, sectsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (!new_buff)
+ {
+ _TIFFfree(sect_buff);
+ sect_buff = (unsigned char *)limitMalloc(
+ sectsize + NUM_BUFF_OVERSIZE_BYTES);
+ }
+ else
+ sect_buff = new_buff;
- if (!sect_buff)
- {
- TIFFError("createImageSection", "Unable to allocate/reallocate section buffer");
- return (-1);
- }
- _TIFFmemset(sect_buff, 0, sectsize + NUM_BUFF_OVERSIZE_BYTES);
- }
+ if (!sect_buff)
+ {
+ TIFFError("createImageSection",
+ "Unable to allocate/reallocate section buffer");
+ return (-1);
+ }
+ _TIFFmemset(sect_buff, 0, sectsize + NUM_BUFF_OVERSIZE_BYTES);
+ }
}
- prev_sectsize = sectsize;
- *sect_buff_ptr = sect_buff;
-
- return (0);
- } /* end createImageSection */
+ prev_sectsize = sectsize;
+ *sect_buff_ptr = sect_buff;
+ return (0);
+} /* end createImageSection */
-/* Process selections defined by regions, zones, margins, or fixed sized areas */
-static int
-processCropSelections(struct image_data *image, struct crop_mask *crop,
- unsigned char **read_buff_ptr, struct buffinfo seg_buffs[])
- {
- int i;
- uint32_t width, length, total_width, total_length;
- tsize_t cropsize;
- unsigned char *crop_buff = NULL;
- unsigned char *read_buff = NULL;
- unsigned char *next_buff = NULL;
- tsize_t prev_cropsize = 0;
+/* Process selections defined by regions, zones, margins, or fixed sized areas
+ */
+static int processCropSelections(struct image_data *image,
+ struct crop_mask *crop,
+ unsigned char **read_buff_ptr,
+ struct buffinfo seg_buffs[])
+{
+ int i;
+ uint32_t width, length, total_width, total_length;
+ tsize_t cropsize;
+ unsigned char *crop_buff = NULL;
+ unsigned char *read_buff = NULL;
+ unsigned char *next_buff = NULL;
+ tsize_t prev_cropsize = 0;
- read_buff = *read_buff_ptr;
+ read_buff = *read_buff_ptr;
- if (crop->img_mode == COMPOSITE_IMAGES)
+ if (crop->img_mode == COMPOSITE_IMAGES)
{
- cropsize = crop->bufftotal;
- crop_buff = seg_buffs[0].buffer;
- if (!crop_buff)
- crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
- else
- {
- prev_cropsize = seg_buffs[0].size;
- if (prev_cropsize < cropsize)
- {
- next_buff = _TIFFrealloc(crop_buff, cropsize + NUM_BUFF_OVERSIZE_BYTES);
- if (! next_buff)
- {
- _TIFFfree (crop_buff);
- crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
- }
+ cropsize = crop->bufftotal;
+ crop_buff = seg_buffs[0].buffer;
+ if (!crop_buff)
+ crop_buff = (unsigned char *)limitMalloc(cropsize +
+ NUM_BUFF_OVERSIZE_BYTES);
else
- crop_buff = next_buff;
- }
- }
-
- if (!crop_buff)
- {
- TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer");
- return (-1);
- }
-
- _TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
- seg_buffs[0].buffer = crop_buff;
- seg_buffs[0].size = cropsize;
-
- /* Checks for matching width or length as required */
- if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0)
- return (1);
-
- if (crop->crop_mode & CROP_INVERT)
- {
- switch (crop->photometric)
- {
- /* Just change the interpretation */
- case PHOTOMETRIC_MINISWHITE:
- case PHOTOMETRIC_MINISBLACK:
- image->photometric = crop->photometric;
- break;
- case INVERT_DATA_ONLY:
- case INVERT_DATA_AND_TAG:
- if (invertImage(image->photometric, image->spp, image->bps,
- crop->combined_width, crop->combined_length, crop_buff))
- {
- TIFFError("processCropSelections",
- "Failed to invert colorspace for composite regions");
- return (-1);
- }
- if (crop->photometric == INVERT_DATA_AND_TAG)
- {
- switch (image->photometric)
- {
- case PHOTOMETRIC_MINISWHITE:
- image->photometric = PHOTOMETRIC_MINISBLACK;
- break;
- case PHOTOMETRIC_MINISBLACK:
- image->photometric = PHOTOMETRIC_MINISWHITE;
- break;
- default:
- break;
- }
- }
- break;
- default: break;
- }
- }
-
- /* Mirror and Rotate will not work with multiple regions unless they are the same width */
- if (crop->crop_mode & CROP_MIRROR)
- {
- if (mirrorImage(image->spp, image->bps, crop->mirror,
- crop->combined_width, crop->combined_length, crop_buff))
{
- TIFFError("processCropSelections", "Failed to mirror composite regions %s",
- (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
- return (-1);
+ prev_cropsize = seg_buffs[0].size;
+ if (prev_cropsize < cropsize)
+ {
+ next_buff =
+ _TIFFrealloc(crop_buff, cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (!next_buff)
+ {
+ _TIFFfree(crop_buff);
+ crop_buff = (unsigned char *)limitMalloc(
+ cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ }
+ else
+ crop_buff = next_buff;
+ }
}
- }
- if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
- {
- if (rotateImage(crop->rotation, image, &crop->combined_width,
- &crop->combined_length, &crop_buff))
+ if (!crop_buff)
{
- TIFFError("processCropSelections",
- "Failed to rotate composite regions by %"PRIu32" degrees", crop->rotation);
- return (-1);
+ TIFFError("processCropSelections",
+ "Unable to allocate/reallocate crop buffer");
+ return (-1);
}
- seg_buffs[0].buffer = crop_buff;
- seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8)
- * image->spp) * crop->combined_length;
- }
- }
- else /* Separated Images */
- {
- total_width = total_length = 0;
- for (i = 0; i < crop->selections; i++)
- {
- cropsize = crop->bufftotal;
- crop_buff = seg_buffs[i].buffer;
- if (!crop_buff)
- crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
- else
+ _TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ seg_buffs[0].buffer = crop_buff;
+ seg_buffs[0].size = cropsize;
+
+ /* Checks for matching width or length as required */
+ if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0)
+ return (1);
+
+ if (crop->crop_mode & CROP_INVERT)
{
- prev_cropsize = seg_buffs[0].size;
- if (prev_cropsize < cropsize)
- {
- next_buff = _TIFFrealloc(crop_buff, cropsize + NUM_BUFF_OVERSIZE_BYTES);
- if (! next_buff)
+ switch (crop->photometric)
{
- _TIFFfree (crop_buff);
- crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ /* Just change the interpretation */
+ case PHOTOMETRIC_MINISWHITE:
+ case PHOTOMETRIC_MINISBLACK:
+ image->photometric = crop->photometric;
+ break;
+ case INVERT_DATA_ONLY:
+ case INVERT_DATA_AND_TAG:
+ if (invertImage(image->photometric, image->spp, image->bps,
+ crop->combined_width, crop->combined_length,
+ crop_buff))
+ {
+ TIFFError("processCropSelections",
+ "Failed to invert colorspace for composite "
+ "regions");
+ return (-1);
+ }
+ if (crop->photometric == INVERT_DATA_AND_TAG)
+ {
+ switch (image->photometric)
+ {
+ case PHOTOMETRIC_MINISWHITE:
+ image->photometric = PHOTOMETRIC_MINISBLACK;
+ break;
+ case PHOTOMETRIC_MINISBLACK:
+ image->photometric = PHOTOMETRIC_MINISWHITE;
+ break;
+ default:
+ break;
+ }
+ }
+ break;
+ default:
+ break;
}
- else
- crop_buff = next_buff;
- }
}
- if (!crop_buff)
+ /* Mirror and Rotate will not work with multiple regions unless they are
+ * the same width */
+ if (crop->crop_mode & CROP_MIRROR)
{
- TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer");
- return (-1);
+ if (mirrorImage(image->spp, image->bps, crop->mirror,
+ crop->combined_width, crop->combined_length,
+ crop_buff))
+ {
+ TIFFError("processCropSelections",
+ "Failed to mirror composite regions %s",
+ (crop->rotation == MIRROR_HORIZ) ? "horizontally"
+ : "vertically");
+ return (-1);
+ }
}
-
- _TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
- seg_buffs[i].buffer = crop_buff;
- seg_buffs[i].size = cropsize;
- if (extractSeparateRegion(image, crop, read_buff, crop_buff, i))
+ if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can
+ reallocate the buffer */
{
- TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i);
- return (-1);
+ if (rotateImage(crop->rotation, image, &crop->combined_width,
+ &crop->combined_length, &crop_buff))
+ {
+ TIFFError("processCropSelections",
+ "Failed to rotate composite regions by %" PRIu32
+ " degrees",
+ crop->rotation);
+ return (-1);
+ }
+ seg_buffs[0].buffer = crop_buff;
+ seg_buffs[0].size =
+ (((crop->combined_width * image->bps + 7) / 8) * image->spp) *
+ crop->combined_length;
}
-
- width = crop->regionlist[i].width;
- length = crop->regionlist[i].length;
-
- if (crop->crop_mode & CROP_INVERT)
+ }
+ else /* Separated Images */
+ {
+ total_width = total_length = 0;
+ for (i = 0; i < crop->selections; i++)
{
- switch (crop->photometric)
- {
- /* Just change the interpretation */
- case PHOTOMETRIC_MINISWHITE:
- case PHOTOMETRIC_MINISBLACK:
- image->photometric = crop->photometric;
- break;
- case INVERT_DATA_ONLY:
- case INVERT_DATA_AND_TAG:
- if (invertImage(image->photometric, image->spp, image->bps,
- width, length, crop_buff))
- {
- TIFFError("processCropSelections",
- "Failed to invert colorspace for region");
- return (-1);
- }
- if (crop->photometric == INVERT_DATA_AND_TAG)
- {
- switch (image->photometric)
- {
- case PHOTOMETRIC_MINISWHITE:
- image->photometric = PHOTOMETRIC_MINISBLACK;
- break;
- case PHOTOMETRIC_MINISBLACK:
- image->photometric = PHOTOMETRIC_MINISWHITE;
- break;
- default:
- break;
- }
- }
- break;
- default: break;
- }
- }
-
- if (crop->crop_mode & CROP_MIRROR)
- {
- if (mirrorImage(image->spp, image->bps, crop->mirror,
- width, length, crop_buff))
- {
- TIFFError("processCropSelections", "Failed to mirror crop region %s",
- (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
- return (-1);
- }
- }
-
- if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
- {
- /* rotateImage() changes image->width, ->length, ->xres and ->yres, what it schouldn't do here, when more than one section is processed.
- * ToDo: Therefore rotateImage() and its usage has to be reworked (e.g. like mirrorImage()) !!
- */
- if (rotateImage(crop->rotation, image, &crop->regionlist[i].width,
- &crop->regionlist[i].length, &crop_buff))
- {
- TIFFError("processCropSelections",
- "Failed to rotate crop region by %"PRIu16" degrees", crop->rotation);
- return (-1);
- }
- total_width += crop->regionlist[i].width;
- total_length += crop->regionlist[i].length;
- crop->combined_width = total_width;
- crop->combined_length = total_length;
- seg_buffs[i].buffer = crop_buff;
- seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8)
- * image->spp) * crop->regionlist[i].length;
- }
- } /* for crop->selections loop */
- } /* Separated Images (else case) */
- return (0);
- } /* end processCropSelections */
+
+ cropsize = crop->bufftotal;
+ crop_buff = seg_buffs[i].buffer;
+ if (!crop_buff)
+ crop_buff = (unsigned char *)limitMalloc(
+ cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ else
+ {
+ prev_cropsize = seg_buffs[0].size;
+ if (prev_cropsize < cropsize)
+ {
+ next_buff = _TIFFrealloc(
+ crop_buff, cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (!next_buff)
+ {
+ _TIFFfree(crop_buff);
+ crop_buff = (unsigned char *)limitMalloc(
+ cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ }
+ else
+ crop_buff = next_buff;
+ }
+ }
+
+ if (!crop_buff)
+ {
+ TIFFError("processCropSelections",
+ "Unable to allocate/reallocate crop buffer");
+ return (-1);
+ }
+
+ _TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ seg_buffs[i].buffer = crop_buff;
+ seg_buffs[i].size = cropsize;
+
+ if (extractSeparateRegion(image, crop, read_buff, crop_buff, i))
+ {
+ TIFFError("processCropSelections",
+ "Unable to extract cropped region %d from image", i);
+ return (-1);
+ }
+
+ width = crop->regionlist[i].width;
+ length = crop->regionlist[i].length;
+
+ if (crop->crop_mode & CROP_INVERT)
+ {
+ switch (crop->photometric)
+ {
+ /* Just change the interpretation */
+ case PHOTOMETRIC_MINISWHITE:
+ case PHOTOMETRIC_MINISBLACK:
+ image->photometric = crop->photometric;
+ break;
+ case INVERT_DATA_ONLY:
+ case INVERT_DATA_AND_TAG:
+ if (invertImage(image->photometric, image->spp,
+ image->bps, width, length, crop_buff))
+ {
+ TIFFError("processCropSelections",
+ "Failed to invert colorspace for region");
+ return (-1);
+ }
+ if (crop->photometric == INVERT_DATA_AND_TAG)
+ {
+ switch (image->photometric)
+ {
+ case PHOTOMETRIC_MINISWHITE:
+ image->photometric = PHOTOMETRIC_MINISBLACK;
+ break;
+ case PHOTOMETRIC_MINISBLACK:
+ image->photometric = PHOTOMETRIC_MINISWHITE;
+ break;
+ default:
+ break;
+ }
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ if (crop->crop_mode & CROP_MIRROR)
+ {
+ if (mirrorImage(image->spp, image->bps, crop->mirror, width,
+ length, crop_buff))
+ {
+ TIFFError("processCropSelections",
+ "Failed to mirror crop region %s",
+ (crop->rotation == MIRROR_HORIZ) ? "horizontally"
+ : "vertically");
+ return (-1);
+ }
+ }
+
+ if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it
+ can reallocate the buffer */
+ {
+ /* rotateImage() changes image->width, ->length, ->xres and
+ * ->yres, what it schouldn't do here, when more than one
+ * section is processed. ToDo: Therefore rotateImage() and its
+ * usage has to be reworked (e.g. like mirrorImage()) !!
+ */
+ if (rotateImage(crop->rotation, image,
+ &crop->regionlist[i].width,
+ &crop->regionlist[i].length, &crop_buff))
+ {
+ TIFFError("processCropSelections",
+ "Failed to rotate crop region by %" PRIu16
+ " degrees",
+ crop->rotation);
+ return (-1);
+ }
+ total_width += crop->regionlist[i].width;
+ total_length += crop->regionlist[i].length;
+ crop->combined_width = total_width;
+ crop->combined_length = total_length;
+ seg_buffs[i].buffer = crop_buff;
+ seg_buffs[i].size =
+ (((crop->regionlist[i].width * image->bps + 7) / 8) *
+ image->spp) *
+ crop->regionlist[i].length;
+ }
+ } /* for crop->selections loop */
+ } /* Separated Images (else case) */
+ return (0);
+} /* end processCropSelections */
/* Copy the crop section of the data from the current image into a buffer
* and adjust the IFD values to reflect the new size. If no cropping is
@@ -7922,1607 +8699,1732 @@ processCropSelections(struct image_data *image, struct crop_mask *crop,
* specialized processCropSelections, but this provides
* the most optimized path when no Zones or Regions are required.
*/
-static int
-createCroppedImage(struct image_data *image, struct crop_mask *crop,
- unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr)
- {
- tsize_t cropsize;
- unsigned char *read_buff = NULL;
- unsigned char *crop_buff = NULL;
- unsigned char *new_buff = NULL;
- static tsize_t prev_cropsize = 0;
-
- read_buff = *read_buff_ptr;
-
- /* process full image, no crop buffer needed */
- crop_buff = read_buff;
- *crop_buff_ptr = read_buff;
- crop->combined_width = image->width;
- crop->combined_length = image->length;
-
- cropsize = crop->bufftotal;
- crop_buff = *crop_buff_ptr;
- if (!crop_buff)
- {
- crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
+static int createCroppedImage(struct image_data *image, struct crop_mask *crop,
+ unsigned char **read_buff_ptr,
+ unsigned char **crop_buff_ptr)
+{
+ tsize_t cropsize;
+ unsigned char *read_buff = NULL;
+ unsigned char *crop_buff = NULL;
+ unsigned char *new_buff = NULL;
+ static tsize_t prev_cropsize = 0;
+
+ read_buff = *read_buff_ptr;
+
+ /* process full image, no crop buffer needed */
+ crop_buff = read_buff;
+ *crop_buff_ptr = read_buff;
+ crop->combined_width = image->width;
+ crop->combined_length = image->length;
+
+ cropsize = crop->bufftotal;
+ crop_buff = *crop_buff_ptr;
if (!crop_buff)
{
- TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer");
- return (-1);
+ crop_buff =
+ (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (!crop_buff)
+ {
+ TIFFError("createCroppedImage",
+ "Unable to allocate/reallocate crop buffer");
+ return (-1);
+ }
+ _TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ prev_cropsize = cropsize;
+ }
+ else
+ {
+ if (prev_cropsize < cropsize)
+ {
+ new_buff =
+ _TIFFrealloc(crop_buff, cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (!new_buff)
+ {
+ free(crop_buff);
+ crop_buff = (unsigned char *)limitMalloc(
+ cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ }
+ else
+ crop_buff = new_buff;
+ if (!crop_buff)
+ {
+ TIFFError("createCroppedImage",
+ "Unable to allocate/reallocate crop buffer");
+ return (-1);
+ }
+ _TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
+ }
+ }
+
+ *crop_buff_ptr = crop_buff;
+
+ if (crop->crop_mode & CROP_INVERT)
+ {
+ switch (crop->photometric)
+ {
+ /* Just change the interpretation */
+ case PHOTOMETRIC_MINISWHITE:
+ case PHOTOMETRIC_MINISBLACK:
+ image->photometric = crop->photometric;
+ break;
+ case INVERT_DATA_ONLY:
+ case INVERT_DATA_AND_TAG:
+ if (invertImage(image->photometric, image->spp, image->bps,
+ crop->combined_width, crop->combined_length,
+ crop_buff))
+ {
+ TIFFError("createCroppedImage",
+ "Failed to invert colorspace for image or "
+ "cropped selection");
+ return (-1);
+ }
+ if (crop->photometric == INVERT_DATA_AND_TAG)
+ {
+ switch (image->photometric)
+ {
+ case PHOTOMETRIC_MINISWHITE:
+ image->photometric = PHOTOMETRIC_MINISBLACK;
+ break;
+ case PHOTOMETRIC_MINISBLACK:
+ image->photometric = PHOTOMETRIC_MINISWHITE;
+ break;
+ default:
+ break;
+ }
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ if (crop->crop_mode & CROP_MIRROR)
+ {
+ if (mirrorImage(image->spp, image->bps, crop->mirror,
+ crop->combined_width, crop->combined_length, crop_buff))
+ {
+ TIFFError("createCroppedImage",
+ "Failed to mirror image or cropped selection %s",
+ (crop->rotation == MIRROR_HORIZ) ? "horizontally"
+ : "vertically");
+ return (-1);
+ }
+ }
+
+ if (crop->crop_mode &
+ CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
+ {
+ if (rotateImage(crop->rotation, image, &crop->combined_width,
+ &crop->combined_length, crop_buff_ptr))
+ {
+ TIFFError("createCroppedImage",
+ "Failed to rotate image or cropped selection by %" PRIu16
+ " degrees",
+ crop->rotation);
+ return (-1);
+ }
}
- _TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
- prev_cropsize = cropsize;
- }
- else
- {
- if (prev_cropsize < cropsize)
- {
- new_buff = _TIFFrealloc(crop_buff, cropsize + NUM_BUFF_OVERSIZE_BYTES);
- if (!new_buff)
- {
- free (crop_buff);
- crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
- }
- else
- crop_buff = new_buff;
- if (!crop_buff)
- {
- TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer");
- return (-1);
- }
- _TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
- }
- }
-
- *crop_buff_ptr = crop_buff;
-
- if (crop->crop_mode & CROP_INVERT)
- {
- switch (crop->photometric)
- {
- /* Just change the interpretation */
- case PHOTOMETRIC_MINISWHITE:
- case PHOTOMETRIC_MINISBLACK:
- image->photometric = crop->photometric;
- break;
- case INVERT_DATA_ONLY:
- case INVERT_DATA_AND_TAG:
- if (invertImage(image->photometric, image->spp, image->bps,
- crop->combined_width, crop->combined_length, crop_buff))
- {
- TIFFError("createCroppedImage",
- "Failed to invert colorspace for image or cropped selection");
- return (-1);
- }
- if (crop->photometric == INVERT_DATA_AND_TAG)
- {
- switch (image->photometric)
- {
- case PHOTOMETRIC_MINISWHITE:
- image->photometric = PHOTOMETRIC_MINISBLACK;
- break;
- case PHOTOMETRIC_MINISBLACK:
- image->photometric = PHOTOMETRIC_MINISWHITE;
- break;
- default:
- break;
- }
- }
- break;
- default: break;
- }
- }
-
- if (crop->crop_mode & CROP_MIRROR)
- {
- if (mirrorImage(image->spp, image->bps, crop->mirror,
- crop->combined_width, crop->combined_length, crop_buff))
- {
- TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s",
- (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
- return (-1);
- }
- }
-
- if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
- {
- if (rotateImage(crop->rotation, image, &crop->combined_width,
- &crop->combined_length, crop_buff_ptr))
- {
- TIFFError("createCroppedImage",
- "Failed to rotate image or cropped selection by %"PRIu16" degrees", crop->rotation);
- return (-1);
- }
- }
-
- if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */
- *read_buff_ptr = NULL; /* so we don't try to free it later */
-
- return (0);
- } /* end createCroppedImage */
+ if (crop_buff ==
+ read_buff) /* we used the read buffer for the crop buffer */
+ *read_buff_ptr = NULL; /* so we don't try to free it later */
+
+ return (0);
+} /* end createCroppedImage */
/* Code in this function is heavily indebted to code in tiffcp
* with modifications by Richard Nolde to handle orientation correctly.
* It will have to be updated significantly if support is added to
- * extract one or more samples from original image since the
+ * extract one or more samples from original image since the
* original code assumes we are always copying all samples.
* Use of global variables for config, compression and others
* should be replaced by addition to the crop_mask struct (which
* will be renamed to proc_opts indicating that is controls
- * user supplied processing options, not just cropping) and
+ * user supplied processing options, not just cropping) and
* then passed in as an argument.
*/
-static int
-writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image,
- struct dump_opts *dump, uint32_t width, uint32_t length,
- unsigned char *crop_buff, int pagenum, int total_pages)
- {
- uint16_t bps, spp;
- uint16_t input_compression, input_photometric;
- uint16_t input_planar;
- const struct cpTag* p;
-
- input_compression = image->compression;
- input_photometric = image->photometric;
- spp = image->spp;
- bps = image->bps;
-
- TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
- TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
+static int writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image,
+ struct dump_opts *dump, uint32_t width,
+ uint32_t length, unsigned char *crop_buff,
+ int pagenum, int total_pages)
+{
+ uint16_t bps, spp;
+ uint16_t input_compression, input_photometric;
+ uint16_t input_planar;
+ const struct cpTag *p;
+
+ input_compression = image->compression;
+ input_photometric = image->photometric;
+ spp = image->spp;
+ bps = image->bps;
+
+ TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
+ TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
#ifdef DEBUG2
- TIFFError("writeCroppedImage", "Input compression: %s",
- (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" :
- ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg"));
+ TIFFError("writeCroppedImage", "Input compression: %s",
+ (input_compression == COMPRESSION_OJPEG)
+ ? "Old Jpeg"
+ : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg"
+ : "Non Jpeg"));
#endif
- if (compression != (uint16_t)-1)
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- else
- {
- if (input_compression == COMPRESSION_OJPEG)
- {
- compression = COMPRESSION_JPEG;
- jpegcolormode = JPEGCOLORMODE_RAW;
- TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
- }
- else
- CopyField(TIFFTAG_COMPRESSION, compression);
- }
-
- if (compression == COMPRESSION_JPEG)
- {
- if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */
- (input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */
- {
- TIFFError ("writeCroppedImage",
- "JPEG compression cannot be used with %s image data",
- (input_photometric == PHOTOMETRIC_PALETTE) ?
- "palette" : "mask");
- return (-1);
- }
- if ((input_photometric == PHOTOMETRIC_RGB) &&
- (jpegcolormode == JPEGCOLORMODE_RGB))
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
+ if (compression != (uint16_t)-1)
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
+ {
+ if (input_compression == COMPRESSION_OJPEG)
+ {
+ compression = COMPRESSION_JPEG;
+ jpegcolormode = JPEGCOLORMODE_RAW;
+ TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
+ }
+ else
+ CopyField(TIFFTAG_COMPRESSION, compression);
}
- else
+
+ if (compression == COMPRESSION_JPEG)
{
- if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24)
- {
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
- PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
- }
- else
- {
- if (input_compression == COMPRESSION_SGILOG ||
- input_compression == COMPRESSION_SGILOG24)
- {
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
- PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
- }
- else
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
- }
- }
-
- if (((input_photometric == PHOTOMETRIC_LOGL) ||
- (input_photometric == PHOTOMETRIC_LOGLUV)) &&
- ((compression != COMPRESSION_SGILOG) &&
- (compression != COMPRESSION_SGILOG24)))
- {
- TIFFError("writeCroppedImage",
- "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression");
- return (-1);
- }
-
- if (fillorder != 0)
- TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
- else
- CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
-
- /* The loadimage function reads input orientation and sets
- * image->orientation. The correct_image_orientation function
- * applies the required rotation and mirror operations to
- * present the data in TOPLEFT orientation and updates
- * image->orientation if any transforms are performed,
- * as per EXIF standard.
- */
- TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
-
- /*
- * Choose tiles/strip for the output image according to
- * the command line arguments (-tiles, -strips) and the
- * structure of the input image.
- */
- if (outtiled == -1)
- outtiled = TIFFIsTiled(in);
- if (outtiled) {
- /*
- * Setup output file's tile width&height. If either
- * is not specified, use either the value from the
- * input image or, if nothing is defined, use the
- * library default.
- */
- if (tilewidth == (uint32_t) 0)
- TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
- if (tilelength == (uint32_t) 0)
- TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
-
- if (tilewidth == 0 || tilelength == 0)
- TIFFDefaultTileSize(out, &tilewidth, &tilelength);
- TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
- TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
- } else {
- /*
- * RowsPerStrip is left unspecified: use either the
- * value from the input image or, if nothing is defined,
- * use the library default.
- */
- if (rowsperstrip == (uint32_t) 0)
- {
- if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
- rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
- if (compression != COMPRESSION_JPEG)
- {
- if (rowsperstrip > length)
- rowsperstrip = length;
- }
- }
- else
- if (rowsperstrip == (uint32_t) -1)
- rowsperstrip = length;
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
- }
-
- TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
- if (config != (uint16_t) -1)
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
- else
- CopyField(TIFFTAG_PLANARCONFIG, config);
- if (spp <= 4)
- CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
- CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
-
-/* SMinSampleValue & SMaxSampleValue */
- switch (compression) {
- case COMPRESSION_JPEG:
- if (((bps % 8) == 0) || ((bps % 12) == 0))
- {
- TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
- TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
- }
- else
- {
- TIFFError("writeCroppedImage",
- "JPEG compression requires 8 or 12 bits per sample");
- return (-1);
- }
- break;
- case COMPRESSION_LZW:
- case COMPRESSION_ADOBE_DEFLATE:
- case COMPRESSION_DEFLATE:
- if (predictor != (uint16_t)-1)
- TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
- else
- CopyField(TIFFTAG_PREDICTOR, predictor);
- break;
- case COMPRESSION_CCITTFAX3:
- case COMPRESSION_CCITTFAX4:
- if (bps != 1)
- {
- TIFFError("writeCroppedImage",
- "Group 3/4 compression is not usable with bps > 1");
- return (-1);
- }
- if (compression == COMPRESSION_CCITTFAX3) {
- if (g3opts != (uint32_t) -1)
- TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
- else
- CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
- } else {
- CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
- }
- CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
- CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
- CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
- CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
- CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
- CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
- break;
- case COMPRESSION_NONE:
- break;
- default: break;
- }
- { uint32_t len32;
- void** data;
- if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
- TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
- }
- { uint16_t ninks;
- const char* inknames;
- if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
- TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
- if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
- int inknameslen = (int)strlen(inknames) + 1;
- const char* cp = inknames;
- while (ninks > 1) {
- cp = strchr(cp, '\0');
- if (cp) {
- cp++;
- inknameslen += ((int)strlen(cp) + 1);
- }
- ninks--;
- }
- TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
- }
- }
- }
- {
- unsigned short pg0, pg1;
- if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
- TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages);
- }
- }
-
- for (p = tags; p < &tags[NTAGS]; p++)
- CopyTag(p->tag, p->count, p->type);
-
- /* Compute the tile or strip dimensions and write to disk */
- if (outtiled)
- {
- if (config == PLANARCONFIG_CONTIG)
- {
- if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump))
- TIFFError("","Unable to write contiguous tile data for page %d", pagenum);
- }
- else
- {
- if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump))
- TIFFError("","Unable to write separate tile data for page %d", pagenum);
- }
- }
- else
- {
- if (config == PLANARCONFIG_CONTIG)
- {
- if (writeBufferToContigStrips (out, crop_buff, length))
- TIFFError("","Unable to write contiguous strip data for page %d", pagenum);
- }
+ if ((input_photometric ==
+ PHOTOMETRIC_PALETTE) || /* color map indexed */
+ (input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */
+ {
+ TIFFError("writeCroppedImage",
+ "JPEG compression cannot be used with %s image data",
+ (input_photometric == PHOTOMETRIC_PALETTE) ? "palette"
+ : "mask");
+ return (-1);
+ }
+ if ((input_photometric == PHOTOMETRIC_RGB) &&
+ (jpegcolormode == JPEGCOLORMODE_RGB))
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
+ else
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
+ }
else
- {
- if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump))
- TIFFError("","Unable to write separate strip data for page %d", pagenum);
- }
+ {
+ if (compression == COMPRESSION_SGILOG ||
+ compression == COMPRESSION_SGILOG24)
+ {
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC,
+ spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
+ }
+ else
+ {
+ if (input_compression == COMPRESSION_SGILOG ||
+ input_compression == COMPRESSION_SGILOG24)
+ {
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC,
+ spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
+ }
+ else
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
+ }
}
- if (!TIFFWriteDirectory(out))
+ if (((input_photometric == PHOTOMETRIC_LOGL) ||
+ (input_photometric == PHOTOMETRIC_LOGLUV)) &&
+ ((compression != COMPRESSION_SGILOG) &&
+ (compression != COMPRESSION_SGILOG24)))
{
- TIFFError("","Failed to write IFD for page number %d", pagenum);
- return (-1);
+ TIFFError("writeCroppedImage", "LogL and LogLuv source data require "
+ "SGI_LOG or SGI_LOG24 compression");
+ return (-1);
}
- return (0);
- } /* end writeCroppedImage */
+ if (fillorder != 0)
+ TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
+ else
+ CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
+
+ /* The loadimage function reads input orientation and sets
+ * image->orientation. The correct_image_orientation function
+ * applies the required rotation and mirror operations to
+ * present the data in TOPLEFT orientation and updates
+ * image->orientation if any transforms are performed,
+ * as per EXIF standard.
+ */
+ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
-static int
-rotateContigSamples8bits(uint16_t rotation, uint16_t spp, uint16_t bps, uint32_t width,
- uint32_t length, uint32_t col, uint8_t *src, uint8_t *dst)
- {
- int ready_bits = 0;
- uint32_t src_byte = 0, src_bit = 0;
- uint32_t row, rowsize = 0, bit_offset = 0;
- uint8_t matchbits = 0, maskbits = 0;
- uint8_t buff1 = 0, buff2 = 0;
- uint8_t *next;
- tsample_t sample;
+ /*
+ * Choose tiles/strip for the output image according to
+ * the command line arguments (-tiles, -strips) and the
+ * structure of the input image.
+ */
+ if (outtiled == -1)
+ outtiled = TIFFIsTiled(in);
+ if (outtiled)
+ {
+ /*
+ * Setup output file's tile width&height. If either
+ * is not specified, use either the value from the
+ * input image or, if nothing is defined, use the
+ * library default.
+ */
+ if (tilewidth == (uint32_t)0)
+ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
+ if (tilelength == (uint32_t)0)
+ TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
- if ((src == NULL) || (dst == NULL))
+ if (tilewidth == 0 || tilelength == 0)
+ TIFFDefaultTileSize(out, &tilewidth, &tilelength);
+ TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
+ TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
+ }
+ else
{
- TIFFError("rotateContigSamples8bits","Invalid src or destination buffer");
- return (1);
+ /*
+ * RowsPerStrip is left unspecified: use either the
+ * value from the input image or, if nothing is defined,
+ * use the library default.
+ */
+ if (rowsperstrip == (uint32_t)0)
+ {
+ if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
+ rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
+ if (compression != COMPRESSION_JPEG)
+ {
+ if (rowsperstrip > length)
+ rowsperstrip = length;
+ }
+ }
+ else if (rowsperstrip == (uint32_t)-1)
+ rowsperstrip = length;
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
- rowsize = ((bps * spp * width) + 7) / 8;
- ready_bits = 0;
- maskbits = (uint8_t)-1 >> (8 - bps);
- buff1 = buff2 = 0;
+ TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
+ if (config != (uint16_t)-1)
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
+ else
+ CopyField(TIFFTAG_PLANARCONFIG, config);
+ if (spp <= 4)
+ CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
+ CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
- for (row = 0; row < length ; row++)
+ /* SMinSampleValue & SMaxSampleValue */
+ switch (compression)
{
- bit_offset = col * bps * spp;
- for (sample = 0; sample < spp; sample++)
- {
- if (sample == 0)
+ case COMPRESSION_JPEG:
+ if (((bps % 8) == 0) || ((bps % 12) == 0))
+ {
+ TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
+ TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
+ }
+ else
+ {
+ TIFFError("writeCroppedImage",
+ "JPEG compression requires 8 or 12 bits per sample");
+ return (-1);
+ }
+ break;
+ case COMPRESSION_LZW:
+ case COMPRESSION_ADOBE_DEFLATE:
+ case COMPRESSION_DEFLATE:
+ if (predictor != (uint16_t)-1)
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
+ else
+ CopyField(TIFFTAG_PREDICTOR, predictor);
+ break;
+ case COMPRESSION_CCITTFAX3:
+ case COMPRESSION_CCITTFAX4:
+ if (bps != 1)
+ {
+ TIFFError("writeCroppedImage",
+ "Group 3/4 compression is not usable with bps > 1");
+ return (-1);
+ }
+ if (compression == COMPRESSION_CCITTFAX3)
+ {
+ if (g3opts != (uint32_t)-1)
+ TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
+ else
+ CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
+ }
+ else
+ {
+ CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
+ }
+ CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
+ CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
+ break;
+ case COMPRESSION_NONE:
+ break;
+ default:
+ break;
+ }
+ {
+ uint32_t len32;
+ void **data;
+ if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
+ TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
+ }
+ {
+ uint16_t ninks;
+ const char *inknames;
+ if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks))
{
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
+ TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
+ if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames))
+ {
+ int inknameslen = (int)strlen(inknames) + 1;
+ const char *cp = inknames;
+ while (ninks > 1)
+ {
+ cp = strchr(cp, '\0');
+ if (cp)
+ {
+ cp++;
+ inknameslen += ((int)strlen(cp) + 1);
+ }
+ ninks--;
+ }
+ TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
+ }
}
- else
+ }
+ {
+ unsigned short pg0, pg1;
+ if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1))
{
- src_byte = (bit_offset + (sample * bps)) / 8;
- src_bit = (bit_offset + (sample * bps)) % 8;
+ TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages);
}
+ }
- switch (rotation)
- {
- case 90: next = src + src_byte - (row * rowsize);
- break;
- case 270: next = src + src_byte + (row * rowsize);
- break;
- default: TIFFError("rotateContigSamples8bits", "Invalid rotation %"PRIu16, rotation);
- return (1);
- }
- matchbits = maskbits << (8 - src_bit - bps);
- buff1 = ((*next) & matchbits) << (src_bit);
+ for (p = tags; p < &tags[NTAGS]; p++)
+ CopyTag(p->tag, p->count, p->type);
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 8)
+ /* Compute the tile or strip dimensions and write to disk */
+ if (outtiled)
+ {
+ if (config == PLANARCONFIG_CONTIG)
{
- *dst++ = buff2;
- buff2 = buff1;
- ready_bits -= 8;
+ if (writeBufferToContigTiles(out, crop_buff, length, width, spp,
+ dump))
+ TIFFError("",
+ "Unable to write contiguous tile data for page %d",
+ pagenum);
}
- else
+ else
{
- buff2 = (buff2 | (buff1 >> ready_bits));
+ if (writeBufferToSeparateTiles(out, crop_buff, length, width, spp,
+ dump))
+ TIFFError("", "Unable to write separate tile data for page %d",
+ pagenum);
}
- ready_bits += bps;
- }
}
-
- if (ready_bits > 0)
+ else
{
- buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
- *dst++ = buff1;
+ if (config == PLANARCONFIG_CONTIG)
+ {
+ if (writeBufferToContigStrips(out, crop_buff, length))
+ TIFFError("",
+ "Unable to write contiguous strip data for page %d",
+ pagenum);
+ }
+ else
+ {
+ if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp,
+ dump))
+ TIFFError("", "Unable to write separate strip data for page %d",
+ pagenum);
+ }
}
- return (0);
- } /* end rotateContigSamples8bits */
+ if (!TIFFWriteDirectory(out))
+ {
+ TIFFError("", "Failed to write IFD for page number %d", pagenum);
+ return (-1);
+ }
+ return (0);
+} /* end writeCroppedImage */
-static int
-rotateContigSamples16bits(uint16_t rotation, uint16_t spp, uint16_t bps, uint32_t width,
- uint32_t length, uint32_t col, uint8_t *src, uint8_t *dst)
- {
- int ready_bits = 0;
- uint32_t row, rowsize, bit_offset;
- uint32_t src_byte = 0, src_bit = 0;
- uint16_t matchbits = 0, maskbits = 0;
- uint16_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff = 0;
- uint8_t *next;
- tsample_t sample;
+static int rotateContigSamples8bits(uint16_t rotation, uint16_t spp,
+ uint16_t bps, uint32_t width,
+ uint32_t length, uint32_t col, uint8_t *src,
+ uint8_t *dst)
+{
+ int ready_bits = 0;
+ uint32_t src_byte = 0, src_bit = 0;
+ uint32_t row, rowsize = 0, bit_offset = 0;
+ uint8_t matchbits = 0, maskbits = 0;
+ uint8_t buff1 = 0, buff2 = 0;
+ uint8_t *next;
+ tsample_t sample;
- if ((src == NULL) || (dst == NULL))
+ if ((src == NULL) || (dst == NULL))
{
- TIFFError("rotateContigSamples16bits","Invalid src or destination buffer");
- return (1);
+ TIFFError("rotateContigSamples8bits",
+ "Invalid src or destination buffer");
+ return (1);
}
- rowsize = ((bps * spp * width) + 7) / 8;
- ready_bits = 0;
- maskbits = (uint16_t)-1 >> (16 - bps);
- buff1 = buff2 = 0;
- for (row = 0; row < length; row++)
+ rowsize = ((bps * spp * width) + 7) / 8;
+ ready_bits = 0;
+ maskbits = (uint8_t)-1 >> (8 - bps);
+ buff1 = buff2 = 0;
+
+ for (row = 0; row < length; row++)
{
- bit_offset = col * bps * spp;
- for (sample = 0; sample < spp; sample++)
- {
- if (sample == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ bit_offset = col * bps * spp;
+ for (sample = 0; sample < spp; sample++)
{
- src_byte = (bit_offset + (sample * bps)) / 8;
- src_bit = (bit_offset + (sample * bps)) % 8;
- }
-
- switch (rotation)
- {
- case 90: next = src + src_byte - (row * rowsize);
- break;
- case 270: next = src + src_byte + (row * rowsize);
- break;
- default: TIFFError("rotateContigSamples8bits", "Invalid rotation %"PRIu16, rotation);
- return (1);
- }
- matchbits = maskbits << (16 - src_bit - bps);
- if (little_endian)
- buff1 = (next[0] << 8) | next[1];
- else
- buff1 = (next[1] << 8) | next[0];
+ if (sample == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sample * bps)) / 8;
+ src_bit = (bit_offset + (sample * bps)) % 8;
+ }
- buff1 = (buff1 & matchbits) << (src_bit);
+ switch (rotation)
+ {
+ case 90:
+ next = src + src_byte - (row * rowsize);
+ break;
+ case 270:
+ next = src + src_byte + (row * rowsize);
+ break;
+ default:
+ TIFFError("rotateContigSamples8bits",
+ "Invalid rotation %" PRIu16, rotation);
+ return (1);
+ }
+ matchbits = maskbits << (8 - src_bit - bps);
+ buff1 = ((*next) & matchbits) << (src_bit);
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 8)
- {
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
- ready_bits -= 8;
- /* shift in new bits */
- buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
- }
- else
- { /* add another bps bits to the buffer */
- bytebuff = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 8)
+ {
+ *dst++ = buff2;
+ buff2 = buff1;
+ ready_bits -= 8;
+ }
+ else
+ {
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- ready_bits += bps;
- }
}
- if (ready_bits > 0)
+ if (ready_bits > 0)
{
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
+ buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
+ *dst++ = buff1;
}
- return (0);
- } /* end rotateContigSamples16bits */
-
-static int
-rotateContigSamples24bits(uint16_t rotation, uint16_t spp, uint16_t bps, uint32_t width,
- uint32_t length, uint32_t col, uint8_t *src, uint8_t *dst)
- {
- int ready_bits = 0;
- uint32_t row, rowsize, bit_offset;
- uint32_t src_byte = 0, src_bit = 0;
- uint32_t matchbits = 0, maskbits = 0;
- uint32_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0;
- uint8_t *next;
- tsample_t sample;
+ return (0);
+} /* end rotateContigSamples8bits */
+static int rotateContigSamples16bits(uint16_t rotation, uint16_t spp,
+ uint16_t bps, uint32_t width,
+ uint32_t length, uint32_t col,
+ uint8_t *src, uint8_t *dst)
+{
+ int ready_bits = 0;
+ uint32_t row, rowsize, bit_offset;
+ uint32_t src_byte = 0, src_bit = 0;
+ uint16_t matchbits = 0, maskbits = 0;
+ uint16_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff = 0;
+ uint8_t *next;
+ tsample_t sample;
- if ((src == NULL) || (dst == NULL))
+ if ((src == NULL) || (dst == NULL))
{
- TIFFError("rotateContigSamples24bits","Invalid src or destination buffer");
- return (1);
+ TIFFError("rotateContigSamples16bits",
+ "Invalid src or destination buffer");
+ return (1);
}
- rowsize = ((bps * spp * width) + 7) / 8;
- ready_bits = 0;
- maskbits = (uint32_t)-1 >> (32 - bps);
- buff1 = buff2 = 0;
- for (row = 0; row < length; row++)
+ rowsize = ((bps * spp * width) + 7) / 8;
+ ready_bits = 0;
+ maskbits = (uint16_t)-1 >> (16 - bps);
+ buff1 = buff2 = 0;
+ for (row = 0; row < length; row++)
{
- bit_offset = col * bps * spp;
- for (sample = 0; sample < spp; sample++)
- {
- if (sample == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ bit_offset = col * bps * spp;
+ for (sample = 0; sample < spp; sample++)
{
- src_byte = (bit_offset + (sample * bps)) / 8;
- src_bit = (bit_offset + (sample * bps)) % 8;
- }
+ if (sample == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sample * bps)) / 8;
+ src_bit = (bit_offset + (sample * bps)) % 8;
+ }
- switch (rotation)
- {
- case 90: next = src + src_byte - (row * rowsize);
- break;
- case 270: next = src + src_byte + (row * rowsize);
- break;
- default: TIFFError("rotateContigSamples8bits", "Invalid rotation %"PRIu16, rotation);
- return (1);
- }
- matchbits = maskbits << (32 - src_bit - bps);
- if (little_endian)
- buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3];
- else
- buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0];
- buff1 = (buff1 & matchbits) << (src_bit);
+ switch (rotation)
+ {
+ case 90:
+ next = src + src_byte - (row * rowsize);
+ break;
+ case 270:
+ next = src + src_byte + (row * rowsize);
+ break;
+ default:
+ TIFFError("rotateContigSamples8bits",
+ "Invalid rotation %" PRIu16, rotation);
+ return (1);
+ }
+ matchbits = maskbits << (16 - src_bit - bps);
+ if (little_endian)
+ buff1 = (next[0] << 8) | next[1];
+ else
+ buff1 = (next[1] << 8) | next[0];
- /* If we have a full buffer's worth, write it out */
- if (ready_bits >= 16)
- {
- bytebuff1 = (buff2 >> 24);
- *dst++ = bytebuff1;
- bytebuff2 = (buff2 >> 16);
- *dst++ = bytebuff2;
- ready_bits -= 16;
+ buff1 = (buff1 & matchbits) << (src_bit);
- /* shift in new bits */
- buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
- }
- else
- { /* add another bps bits to the buffer */
- bytebuff1 = bytebuff2 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 8)
+ {
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
+ ready_bits -= 8;
+ /* shift in new bits */
+ buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
+ }
+ else
+ { /* add another bps bits to the buffer */
+ bytebuff = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- ready_bits += bps;
- }
}
- /* catch any trailing bits at the end of the line */
- while (ready_bits > 0)
+ if (ready_bits > 0)
{
- bytebuff1 = (buff2 >> 24);
- *dst++ = bytebuff1;
-
- buff2 = (buff2 << 8);
- bytebuff2 = bytebuff1;
- ready_bits -= 8;
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
}
-
- return (0);
- } /* end rotateContigSamples24bits */
-static int
-rotateContigSamples32bits(uint16_t rotation, uint16_t spp, uint16_t bps, uint32_t width,
- uint32_t length, uint32_t col, uint8_t *src, uint8_t *dst)
- {
- int ready_bits = 0 /*, shift_width = 0 */;
- /* int bytes_per_sample, bytes_per_pixel; */
- uint32_t row, rowsize, bit_offset;
- uint32_t src_byte, src_bit;
- uint32_t longbuff1 = 0, longbuff2 = 0;
- uint64_t maskbits = 0, matchbits = 0;
- uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
- uint8_t *next;
- tsample_t sample;
+ return (0);
+} /* end rotateContigSamples16bits */
+static int rotateContigSamples24bits(uint16_t rotation, uint16_t spp,
+ uint16_t bps, uint32_t width,
+ uint32_t length, uint32_t col,
+ uint8_t *src, uint8_t *dst)
+{
+ int ready_bits = 0;
+ uint32_t row, rowsize, bit_offset;
+ uint32_t src_byte = 0, src_bit = 0;
+ uint32_t matchbits = 0, maskbits = 0;
+ uint32_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0;
+ uint8_t *next;
+ tsample_t sample;
- if ((src == NULL) || (dst == NULL))
+ if ((src == NULL) || (dst == NULL))
{
- TIFFError("rotateContigSamples24bits","Invalid src or destination buffer");
- return (1);
+ TIFFError("rotateContigSamples24bits",
+ "Invalid src or destination buffer");
+ return (1);
}
- /* bytes_per_sample = (bps + 7) / 8; */
- /* bytes_per_pixel = ((bps * spp) + 7) / 8; */
- /* if (bytes_per_pixel < (bytes_per_sample + 1)) */
- /* shift_width = bytes_per_pixel; */
- /* else */
- /* shift_width = bytes_per_sample + 1; */
-
- rowsize = ((bps * spp * width) + 7) / 8;
- ready_bits = 0;
- maskbits = (uint64_t)-1 >> (64 - bps);
- buff1 = buff2 = 0;
- for (row = 0; row < length; row++)
+ rowsize = ((bps * spp * width) + 7) / 8;
+ ready_bits = 0;
+ maskbits = (uint32_t)-1 >> (32 - bps);
+ buff1 = buff2 = 0;
+ for (row = 0; row < length; row++)
{
- bit_offset = col * bps * spp;
- for (sample = 0; sample < spp; sample++)
- {
- if (sample == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ bit_offset = col * bps * spp;
+ for (sample = 0; sample < spp; sample++)
{
- src_byte = (bit_offset + (sample * bps)) / 8;
- src_bit = (bit_offset + (sample * bps)) % 8;
- }
+ if (sample == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sample * bps)) / 8;
+ src_bit = (bit_offset + (sample * bps)) % 8;
+ }
- switch (rotation)
- {
- case 90: next = src + src_byte - (row * rowsize);
- break;
- case 270: next = src + src_byte + (row * rowsize);
- break;
- default: TIFFError("rotateContigSamples8bits", "Invalid rotation %"PRIu16, rotation);
- return (1);
- }
- matchbits = maskbits << (64 - src_bit - bps);
- if (little_endian)
- {
- longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3];
- longbuff2 = longbuff1;
+ switch (rotation)
+ {
+ case 90:
+ next = src + src_byte - (row * rowsize);
+ break;
+ case 270:
+ next = src + src_byte + (row * rowsize);
+ break;
+ default:
+ TIFFError("rotateContigSamples8bits",
+ "Invalid rotation %" PRIu16, rotation);
+ return (1);
+ }
+ matchbits = maskbits << (32 - src_bit - bps);
+ if (little_endian)
+ buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) |
+ next[3];
+ else
+ buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) |
+ next[0];
+ buff1 = (buff1 & matchbits) << (src_bit);
+
+ /* If we have a full buffer's worth, write it out */
+ if (ready_bits >= 16)
+ {
+ bytebuff1 = (buff2 >> 24);
+ *dst++ = bytebuff1;
+ bytebuff2 = (buff2 >> 16);
+ *dst++ = bytebuff2;
+ ready_bits -= 16;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
+ }
+ else
+ { /* add another bps bits to the buffer */
+ bytebuff1 = bytebuff2 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- else
- {
- longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0];
- longbuff2 = longbuff1;
- }
+ }
- buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
- buff1 = (buff3 & matchbits) << (src_bit);
+ /* catch any trailing bits at the end of the line */
+ while (ready_bits > 0)
+ {
+ bytebuff1 = (buff2 >> 24);
+ *dst++ = bytebuff1;
- if (ready_bits < 32)
- { /* add another bps bits to the buffer */
- bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- }
- else /* If we have a full buffer's worth, write it out */
+ buff2 = (buff2 << 8);
+ bytebuff2 = bytebuff1;
+ ready_bits -= 8;
+ }
+
+ return (0);
+} /* end rotateContigSamples24bits */
+
+static int rotateContigSamples32bits(uint16_t rotation, uint16_t spp,
+ uint16_t bps, uint32_t width,
+ uint32_t length, uint32_t col,
+ uint8_t *src, uint8_t *dst)
+{
+ int ready_bits = 0 /*, shift_width = 0 */;
+ /* int bytes_per_sample, bytes_per_pixel; */
+ uint32_t row, rowsize, bit_offset;
+ uint32_t src_byte, src_bit;
+ uint32_t longbuff1 = 0, longbuff2 = 0;
+ uint64_t maskbits = 0, matchbits = 0;
+ uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
+ uint8_t *next;
+ tsample_t sample;
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("rotateContigSamples24bits",
+ "Invalid src or destination buffer");
+ return (1);
+ }
+
+ /* bytes_per_sample = (bps + 7) / 8; */
+ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */
+ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */
+ /* shift_width = bytes_per_pixel; */
+ /* else */
+ /* shift_width = bytes_per_sample + 1; */
+
+ rowsize = ((bps * spp * width) + 7) / 8;
+ ready_bits = 0;
+ maskbits = (uint64_t)-1 >> (64 - bps);
+ buff1 = buff2 = 0;
+ for (row = 0; row < length; row++)
+ {
+ bit_offset = col * bps * spp;
+ for (sample = 0; sample < spp; sample++)
{
- bytebuff1 = (uint8_t)(buff2 >> 56);
- *dst++ = bytebuff1;
- bytebuff2 = (uint8_t)(buff2 >> 48);
- *dst++ = bytebuff2;
- bytebuff3 = (uint8_t)(buff2 >> 40);
- *dst++ = bytebuff3;
- bytebuff4 = (uint8_t)(buff2 >> 32);
- *dst++ = bytebuff4;
- ready_bits -= 32;
-
- /* shift in new bits */
- buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
+ if (sample == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sample * bps)) / 8;
+ src_bit = (bit_offset + (sample * bps)) % 8;
+ }
+
+ switch (rotation)
+ {
+ case 90:
+ next = src + src_byte - (row * rowsize);
+ break;
+ case 270:
+ next = src + src_byte + (row * rowsize);
+ break;
+ default:
+ TIFFError("rotateContigSamples8bits",
+ "Invalid rotation %" PRIu16, rotation);
+ return (1);
+ }
+ matchbits = maskbits << (64 - src_bit - bps);
+ if (little_endian)
+ {
+ longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) |
+ next[3];
+ longbuff2 = longbuff1;
+ }
+ else
+ {
+ longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) |
+ next[0];
+ longbuff2 = longbuff1;
+ }
+
+ buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
+ buff1 = (buff3 & matchbits) << (src_bit);
+
+ if (ready_bits < 32)
+ { /* add another bps bits to the buffer */
+ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ else /* If we have a full buffer's worth, write it out */
+ {
+ bytebuff1 = (uint8_t)(buff2 >> 56);
+ *dst++ = bytebuff1;
+ bytebuff2 = (uint8_t)(buff2 >> 48);
+ *dst++ = bytebuff2;
+ bytebuff3 = (uint8_t)(buff2 >> 40);
+ *dst++ = bytebuff3;
+ bytebuff4 = (uint8_t)(buff2 >> 32);
+ *dst++ = bytebuff4;
+ ready_bits -= 32;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- ready_bits += bps;
- }
}
- while (ready_bits > 0)
+ while (ready_bits > 0)
{
- bytebuff1 = (buff2 >> 56);
- *dst++ = bytebuff1;
- buff2 = (buff2 << 8);
- ready_bits -= 8;
+ bytebuff1 = (buff2 >> 56);
+ *dst++ = bytebuff1;
+ buff2 = (buff2 << 8);
+ ready_bits -= 8;
}
- return (0);
- } /* end rotateContigSamples32bits */
-
+ return (0);
+} /* end rotateContigSamples32bits */
/* Rotate an image by a multiple of 90 degrees clockwise */
-static int
-rotateImage(uint16_t rotation, struct image_data *image, uint32_t *img_width,
- uint32_t *img_length, unsigned char **ibuff_ptr)
- {
- int shift_width;
- uint32_t bytes_per_pixel, bytes_per_sample;
- uint32_t row, rowsize, src_offset, dst_offset;
- uint32_t i, col, width, length;
- uint32_t colsize, buffsize, col_offset, pix_offset;
- unsigned char *ibuff;
- unsigned char *src;
- unsigned char *dst;
- uint16_t spp, bps;
- float res_temp;
- unsigned char *rbuff = NULL;
-
- width = *img_width;
- length = *img_length;
- spp = image->spp;
- bps = image->bps;
-
- rowsize = ((bps * spp * width) + 7) / 8;
- colsize = ((bps * spp * length) + 7) / 8;
- if ((colsize * width) > (rowsize * length))
- buffsize = (colsize + 1) * width;
- else
- buffsize = (rowsize + 1) * length;
-
- bytes_per_sample = (bps + 7) / 8;
- bytes_per_pixel = ((bps * spp) + 7) / 8;
- if (bytes_per_pixel < (bytes_per_sample + 1))
- shift_width = bytes_per_pixel;
- else
- shift_width = bytes_per_sample + 1;
-
- switch (rotation)
- {
- case 0:
- case 360: return (0);
- case 90:
- case 180:
- case 270: break;
- default: TIFFError("rotateImage", "Invalid rotation angle %"PRIu16, rotation);
- return (-1);
- }
-
- /* Add 3 padding bytes for extractContigSamplesShifted32bits */
- if (!(rbuff = (unsigned char *)limitMalloc(buffsize + NUM_BUFF_OVERSIZE_BYTES)))
- {
- TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize + NUM_BUFF_OVERSIZE_BYTES);
- return (-1);
- }
- _TIFFmemset(rbuff, '\0', buffsize + NUM_BUFF_OVERSIZE_BYTES);
-
- ibuff = *ibuff_ptr;
- switch (rotation)
- {
- case 180: if ((bps % 8) == 0) /* byte aligned data */
- {
+static int rotateImage(uint16_t rotation, struct image_data *image,
+ uint32_t *img_width, uint32_t *img_length,
+ unsigned char **ibuff_ptr)
+{
+ int shift_width;
+ uint32_t bytes_per_pixel, bytes_per_sample;
+ uint32_t row, rowsize, src_offset, dst_offset;
+ uint32_t i, col, width, length;
+ uint32_t colsize, buffsize, col_offset, pix_offset;
+ unsigned char *ibuff;
+ unsigned char *src;
+ unsigned char *dst;
+ uint16_t spp, bps;
+ float res_temp;
+ unsigned char *rbuff = NULL;
+
+ width = *img_width;
+ length = *img_length;
+ spp = image->spp;
+ bps = image->bps;
+
+ rowsize = ((bps * spp * width) + 7) / 8;
+ colsize = ((bps * spp * length) + 7) / 8;
+ if ((colsize * width) > (rowsize * length))
+ buffsize = (colsize + 1) * width;
+ else
+ buffsize = (rowsize + 1) * length;
+
+ bytes_per_sample = (bps + 7) / 8;
+ bytes_per_pixel = ((bps * spp) + 7) / 8;
+ if (bytes_per_pixel < (bytes_per_sample + 1))
+ shift_width = bytes_per_pixel;
+ else
+ shift_width = bytes_per_sample + 1;
+
+ switch (rotation)
+ {
+ case 0:
+ case 360:
+ return (0);
+ case 90:
+ case 180:
+ case 270:
+ break;
+ default:
+ TIFFError("rotateImage", "Invalid rotation angle %" PRIu16,
+ rotation);
+ return (-1);
+ }
+
+ /* Add 3 padding bytes for extractContigSamplesShifted32bits */
+ if (!(rbuff =
+ (unsigned char *)limitMalloc(buffsize + NUM_BUFF_OVERSIZE_BYTES)))
+ {
+ TIFFError("rotateImage",
+ "Unable to allocate rotation buffer of %1u bytes",
+ buffsize + NUM_BUFF_OVERSIZE_BYTES);
+ return (-1);
+ }
+ _TIFFmemset(rbuff, '\0', buffsize + NUM_BUFF_OVERSIZE_BYTES);
+
+ ibuff = *ibuff_ptr;
+ switch (rotation)
+ {
+ case 180:
+ if ((bps % 8) == 0) /* byte aligned data */
+ {
src = ibuff;
pix_offset = (spp * bps) / 8;
for (row = 0; row < length; row++)
- {
- dst_offset = (length - row - 1) * rowsize;
- for (col = 0; col < width; col++)
- {
- col_offset = (width - col - 1) * pix_offset;
- dst = rbuff + dst_offset + col_offset;
-
- for (i = 0; i < bytes_per_pixel; i++)
- *dst++ = *src++;
- }
- }
- }
- else
- { /* non 8 bit per sample data */
+ {
+ dst_offset = (length - row - 1) * rowsize;
+ for (col = 0; col < width; col++)
+ {
+ col_offset = (width - col - 1) * pix_offset;
+ dst = rbuff + dst_offset + col_offset;
+
+ for (i = 0; i < bytes_per_pixel; i++)
+ *dst++ = *src++;
+ }
+ }
+ }
+ else
+ { /* non 8 bit per sample data */
for (row = 0; row < length; row++)
- {
- src_offset = row * rowsize;
- dst_offset = (length - row - 1) * rowsize;
- src = ibuff + src_offset;
- dst = rbuff + dst_offset;
- switch (shift_width)
+ {
+ src_offset = row * rowsize;
+ dst_offset = (length - row - 1) * rowsize;
+ src = ibuff + src_offset;
+ dst = rbuff + dst_offset;
+ switch (shift_width)
{
- case 1: if (bps == 1)
- {
- if (reverseSamples8bits(spp, bps, width, src, dst))
+ case 1:
+ if (bps == 1)
+ {
+ if (reverseSamples8bits(spp, bps, width, src,
+ dst))
{
- _TIFFfree(rbuff);
- return (-1);
+ _TIFFfree(rbuff);
+ return (-1);
}
- break;
- }
+ break;
+ }
if (reverseSamples16bits(spp, bps, width, src, dst))
- {
- _TIFFfree(rbuff);
- return (-1);
- }
- break;
- case 2: if (reverseSamples24bits(spp, bps, width, src, dst))
- {
- _TIFFfree(rbuff);
- return (-1);
- }
- break;
- case 3:
- case 4:
- case 5: if (reverseSamples32bits(spp, bps, width, src, dst))
- {
- _TIFFfree(rbuff);
- return (-1);
- }
- break;
- default: TIFFError("rotateImage","Unsupported bit depth %"PRIu16, bps);
- _TIFFfree(rbuff);
- return (-1);
+ {
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ break;
+ case 2:
+ if (reverseSamples24bits(spp, bps, width, src, dst))
+ {
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ break;
+ case 3:
+ case 4:
+ case 5:
+ if (reverseSamples32bits(spp, bps, width, src, dst))
+ {
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ break;
+ default:
+ TIFFError("rotateImage",
+ "Unsupported bit depth %" PRIu16, bps);
+ _TIFFfree(rbuff);
+ return (-1);
}
- }
- }
- _TIFFfree(ibuff);
- *(ibuff_ptr) = rbuff;
- break;
+ }
+ }
+ _TIFFfree(ibuff);
+ *(ibuff_ptr) = rbuff;
+ break;
- case 90: if ((bps % 8) == 0) /* byte aligned data */
- {
+ case 90:
+ if ((bps % 8) == 0) /* byte aligned data */
+ {
for (col = 0; col < width; col++)
- {
- src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel);
- dst_offset = col * colsize;
- src = ibuff + src_offset;
- dst = rbuff + dst_offset;
- for (row = length; row > 0; row--)
+ {
+ src_offset =
+ ((length - 1) * rowsize) + (col * bytes_per_pixel);
+ dst_offset = col * colsize;
+ src = ibuff + src_offset;
+ dst = rbuff + dst_offset;
+ for (row = length; row > 0; row--)
{
- for (i = 0; i < bytes_per_pixel; i++)
- *dst++ = *(src + i);
- src -= rowsize;
+ for (i = 0; i < bytes_per_pixel; i++)
+ *dst++ = *(src + i);
+ src -= rowsize;
}
- }
- }
- else
- { /* non 8 bit per sample data */
+ }
+ }
+ else
+ { /* non 8 bit per sample data */
for (col = 0; col < width; col++)
- {
- src_offset = (length - 1) * rowsize;
- dst_offset = col * colsize;
- src = ibuff + src_offset;
- dst = rbuff + dst_offset;
- switch (shift_width)
+ {
+ src_offset = (length - 1) * rowsize;
+ dst_offset = col * colsize;
+ src = ibuff + src_offset;
+ dst = rbuff + dst_offset;
+ switch (shift_width)
{
- case 1: if (bps == 1)
- {
- if (rotateContigSamples8bits(rotation, spp, bps, width,
- length, col, src, dst))
+ case 1:
+ if (bps == 1)
+ {
+ if (rotateContigSamples8bits(rotation, spp, bps,
+ width, length, col,
+ src, dst))
{
- _TIFFfree(rbuff);
- return (-1);
+ _TIFFfree(rbuff);
+ return (-1);
}
- break;
- }
- if (rotateContigSamples16bits(rotation, spp, bps, width,
- length, col, src, dst))
- {
- _TIFFfree(rbuff);
- return (-1);
- }
- break;
- case 2: if (rotateContigSamples24bits(rotation, spp, bps, width,
- length, col, src, dst))
- {
- _TIFFfree(rbuff);
- return (-1);
- }
- break;
- case 3:
- case 4:
- case 5: if (rotateContigSamples32bits(rotation, spp, bps, width,
- length, col, src, dst))
- {
- _TIFFfree(rbuff);
- return (-1);
- }
- break;
- default: TIFFError("rotateImage","Unsupported bit depth %"PRIu16, bps);
- _TIFFfree(rbuff);
- return (-1);
- }
- }
- }
- _TIFFfree(ibuff);
- *(ibuff_ptr) = rbuff;
-
- *img_width = length;
- *img_length = width;
- image->width = length;
- image->length = width;
- res_temp = image->xres;
- image->xres = image->yres;
- image->yres = res_temp;
- break;
-
- case 270: if ((bps % 8) == 0) /* byte aligned data */
- {
+ break;
+ }
+ if (rotateContigSamples16bits(rotation, spp, bps,
+ width, length, col,
+ src, dst))
+ {
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ break;
+ case 2:
+ if (rotateContigSamples24bits(rotation, spp, bps,
+ width, length, col,
+ src, dst))
+ {
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ break;
+ case 3:
+ case 4:
+ case 5:
+ if (rotateContigSamples32bits(rotation, spp, bps,
+ width, length, col,
+ src, dst))
+ {
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ break;
+ default:
+ TIFFError("rotateImage",
+ "Unsupported bit depth %" PRIu16, bps);
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ }
+ }
+ _TIFFfree(ibuff);
+ *(ibuff_ptr) = rbuff;
+
+ *img_width = length;
+ *img_length = width;
+ image->width = length;
+ image->length = width;
+ res_temp = image->xres;
+ image->xres = image->yres;
+ image->yres = res_temp;
+ break;
+
+ case 270:
+ if ((bps % 8) == 0) /* byte aligned data */
+ {
for (col = 0; col < width; col++)
- {
- src_offset = col * bytes_per_pixel;
- dst_offset = (width - col - 1) * colsize;
- src = ibuff + src_offset;
- dst = rbuff + dst_offset;
- for (row = length; row > 0; row--)
+ {
+ src_offset = col * bytes_per_pixel;
+ dst_offset = (width - col - 1) * colsize;
+ src = ibuff + src_offset;
+ dst = rbuff + dst_offset;
+ for (row = length; row > 0; row--)
{
- for (i = 0; i < bytes_per_pixel; i++)
- *dst++ = *(src + i);
- src += rowsize;
+ for (i = 0; i < bytes_per_pixel; i++)
+ *dst++ = *(src + i);
+ src += rowsize;
}
- }
- }
- else
- { /* non 8 bit per sample data */
+ }
+ }
+ else
+ { /* non 8 bit per sample data */
for (col = 0; col < width; col++)
- {
- src_offset = 0;
- dst_offset = (width - col - 1) * colsize;
- src = ibuff + src_offset;
- dst = rbuff + dst_offset;
- switch (shift_width)
+ {
+ src_offset = 0;
+ dst_offset = (width - col - 1) * colsize;
+ src = ibuff + src_offset;
+ dst = rbuff + dst_offset;
+ switch (shift_width)
{
- case 1: if (bps == 1)
- {
- if (rotateContigSamples8bits(rotation, spp, bps, width,
- length, col, src, dst))
+ case 1:
+ if (bps == 1)
+ {
+ if (rotateContigSamples8bits(rotation, spp, bps,
+ width, length, col,
+ src, dst))
{
- _TIFFfree(rbuff);
- return (-1);
+ _TIFFfree(rbuff);
+ return (-1);
}
- break;
- }
- if (rotateContigSamples16bits(rotation, spp, bps, width,
- length, col, src, dst))
- {
- _TIFFfree(rbuff);
- return (-1);
- }
- break;
- case 2: if (rotateContigSamples24bits(rotation, spp, bps, width,
- length, col, src, dst))
- {
- _TIFFfree(rbuff);
- return (-1);
- }
- break;
- case 3:
- case 4:
- case 5: if (rotateContigSamples32bits(rotation, spp, bps, width,
- length, col, src, dst))
- {
- _TIFFfree(rbuff);
- return (-1);
- }
- break;
- default: TIFFError("rotateImage","Unsupported bit depth %"PRIu16, bps);
- _TIFFfree(rbuff);
- return (-1);
- }
- }
- }
- _TIFFfree(ibuff);
- *(ibuff_ptr) = rbuff;
-
- *img_width = length;
- *img_length = width;
- image->width = length;
- image->length = width;
- res_temp = image->xres;
- image->xres = image->yres;
- image->yres = res_temp;
- break;
- default:
- break;
- }
-
- return (0);
- } /* end rotateImage */
-
-static int
-reverseSamples8bits (uint16_t spp, uint16_t bps, uint32_t width,
- uint8_t *ibuff, uint8_t *obuff)
- {
- int ready_bits = 0;
- uint32_t col;
- uint32_t src_byte, src_bit;
- uint32_t bit_offset = 0;
- uint8_t match_bits = 0, mask_bits = 0;
- uint8_t buff1 = 0, buff2 = 0;
- unsigned char *src;
- unsigned char *dst;
- tsample_t sample;
-
- if ((ibuff == NULL) || (obuff == NULL))
- {
- TIFFError("reverseSamples8bits","Invalid image or work buffer");
- return (1);
+ break;
+ }
+ if (rotateContigSamples16bits(rotation, spp, bps,
+ width, length, col,
+ src, dst))
+ {
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ break;
+ case 2:
+ if (rotateContigSamples24bits(rotation, spp, bps,
+ width, length, col,
+ src, dst))
+ {
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ break;
+ case 3:
+ case 4:
+ case 5:
+ if (rotateContigSamples32bits(rotation, spp, bps,
+ width, length, col,
+ src, dst))
+ {
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ break;
+ default:
+ TIFFError("rotateImage",
+ "Unsupported bit depth %" PRIu16, bps);
+ _TIFFfree(rbuff);
+ return (-1);
+ }
+ }
+ }
+ _TIFFfree(ibuff);
+ *(ibuff_ptr) = rbuff;
+
+ *img_width = length;
+ *img_length = width;
+ image->width = length;
+ image->length = width;
+ res_temp = image->xres;
+ image->xres = image->yres;
+ image->yres = res_temp;
+ break;
+ default:
+ break;
}
- ready_bits = 0;
- mask_bits = (uint8_t)-1 >> (8 - bps);
- dst = obuff;
- for (col = width; col > 0; col--)
+ return (0);
+} /* end rotateImage */
+
+static int reverseSamples8bits(uint16_t spp, uint16_t bps, uint32_t width,
+ uint8_t *ibuff, uint8_t *obuff)
+{
+ int ready_bits = 0;
+ uint32_t col;
+ uint32_t src_byte, src_bit;
+ uint32_t bit_offset = 0;
+ uint8_t match_bits = 0, mask_bits = 0;
+ uint8_t buff1 = 0, buff2 = 0;
+ unsigned char *src;
+ unsigned char *dst;
+ tsample_t sample;
+
+ if ((ibuff == NULL) || (obuff == NULL))
{
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = (col - 1) * bps * spp;
- for (sample = 0; sample < spp; sample++)
- {
- if (sample == 0)
- {
- src_byte = bit_offset / 8;
- src_bit = bit_offset % 8;
- }
- else
+ TIFFError("reverseSamples8bits", "Invalid image or work buffer");
+ return (1);
+ }
+
+ ready_bits = 0;
+ mask_bits = (uint8_t)-1 >> (8 - bps);
+ dst = obuff;
+ for (col = width; col > 0; col--)
+ {
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = (col - 1) * bps * spp;
+ for (sample = 0; sample < spp; sample++)
{
- src_byte = (bit_offset + (sample * bps)) / 8;
- src_bit = (bit_offset + (sample * bps)) % 8;
- }
+ if (sample == 0)
+ {
+ src_byte = bit_offset / 8;
+ src_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sample * bps)) / 8;
+ src_bit = (bit_offset + (sample * bps)) % 8;
+ }
- src = ibuff + src_byte;
- match_bits = mask_bits << (8 - src_bit - bps);
- buff1 = ((*src) & match_bits) << (src_bit);
+ src = ibuff + src_byte;
+ match_bits = mask_bits << (8 - src_bit - bps);
+ buff1 = ((*src) & match_bits) << (src_bit);
- if (ready_bits < 8)
- buff2 = (buff2 | (buff1 >> ready_bits));
- else /* If we have a full buffer's worth, write it out */
- {
- *dst++ = buff2;
- buff2 = buff1;
- ready_bits -= 8;
+ if (ready_bits < 8)
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ else /* If we have a full buffer's worth, write it out */
+ {
+ *dst++ = buff2;
+ buff2 = buff1;
+ ready_bits -= 8;
+ }
+ ready_bits += bps;
}
- ready_bits += bps;
- }
}
- if (ready_bits > 0)
+ if (ready_bits > 0)
{
- buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
- *dst++ = buff1;
+ buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
+ *dst++ = buff1;
}
- return (0);
- } /* end reverseSamples8bits */
-
+ return (0);
+} /* end reverseSamples8bits */
-static int
-reverseSamples16bits (uint16_t spp, uint16_t bps, uint32_t width,
- uint8_t *ibuff, uint8_t *obuff)
- {
- int ready_bits = 0;
- uint32_t col;
- uint32_t src_byte = 0, high_bit = 0;
- uint32_t bit_offset = 0;
- uint16_t match_bits = 0, mask_bits = 0;
- uint16_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff = 0;
- unsigned char *src;
- unsigned char *dst;
- tsample_t sample;
+static int reverseSamples16bits(uint16_t spp, uint16_t bps, uint32_t width,
+ uint8_t *ibuff, uint8_t *obuff)
+{
+ int ready_bits = 0;
+ uint32_t col;
+ uint32_t src_byte = 0, high_bit = 0;
+ uint32_t bit_offset = 0;
+ uint16_t match_bits = 0, mask_bits = 0;
+ uint16_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff = 0;
+ unsigned char *src;
+ unsigned char *dst;
+ tsample_t sample;
- if ((ibuff == NULL) || (obuff == NULL))
+ if ((ibuff == NULL) || (obuff == NULL))
{
- TIFFError("reverseSample16bits","Invalid image or work buffer");
- return (1);
+ TIFFError("reverseSample16bits", "Invalid image or work buffer");
+ return (1);
}
- ready_bits = 0;
- mask_bits = (uint16_t)-1 >> (16 - bps);
- dst = obuff;
- for (col = width; col > 0; col--)
+ ready_bits = 0;
+ mask_bits = (uint16_t)-1 >> (16 - bps);
+ dst = obuff;
+ for (col = width; col > 0; col--)
{
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = (col - 1) * bps * spp;
- for (sample = 0; sample < spp; sample++)
- {
- if (sample == 0)
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = (col - 1) * bps * spp;
+ for (sample = 0; sample < spp; sample++)
{
- src_byte = bit_offset / 8;
- high_bit = bit_offset % 8;
- }
- else
- {
- src_byte = (bit_offset + (sample * bps)) / 8;
- high_bit = (bit_offset + (sample * bps)) % 8;
- }
+ if (sample == 0)
+ {
+ src_byte = bit_offset / 8;
+ high_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sample * bps)) / 8;
+ high_bit = (bit_offset + (sample * bps)) % 8;
+ }
- src = ibuff + src_byte;
- match_bits = mask_bits << (16 - high_bit - bps);
- if (little_endian)
- buff1 = (src[0] << 8) | src[1];
- else
- buff1 = (src[1] << 8) | src[0];
- buff1 = (buff1 & match_bits) << (high_bit);
-
- if (ready_bits < 8)
- { /* add another bps bits to the buffer */
- bytebuff = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- }
- else /* If we have a full buffer's worth, write it out */
- {
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
- ready_bits -= 8;
- /* shift in new bits */
- buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
+ src = ibuff + src_byte;
+ match_bits = mask_bits << (16 - high_bit - bps);
+ if (little_endian)
+ buff1 = (src[0] << 8) | src[1];
+ else
+ buff1 = (src[1] << 8) | src[0];
+ buff1 = (buff1 & match_bits) << (high_bit);
+
+ if (ready_bits < 8)
+ { /* add another bps bits to the buffer */
+ bytebuff = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ else /* If we have a full buffer's worth, write it out */
+ {
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
+ ready_bits -= 8;
+ /* shift in new bits */
+ buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- ready_bits += bps;
- }
}
- if (ready_bits > 0)
+ if (ready_bits > 0)
{
- bytebuff = (buff2 >> 8);
- *dst++ = bytebuff;
+ bytebuff = (buff2 >> 8);
+ *dst++ = bytebuff;
}
- return (0);
- } /* end reverseSamples16bits */
+ return (0);
+} /* end reverseSamples16bits */
-static int
-reverseSamples24bits (uint16_t spp, uint16_t bps, uint32_t width,
- uint8_t *ibuff, uint8_t *obuff)
- {
- int ready_bits = 0;
- uint32_t col;
- uint32_t src_byte = 0, high_bit = 0;
- uint32_t bit_offset = 0;
- uint32_t match_bits = 0, mask_bits = 0;
- uint32_t buff1 = 0, buff2 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0;
- unsigned char *src;
- unsigned char *dst;
- tsample_t sample;
+static int reverseSamples24bits(uint16_t spp, uint16_t bps, uint32_t width,
+ uint8_t *ibuff, uint8_t *obuff)
+{
+ int ready_bits = 0;
+ uint32_t col;
+ uint32_t src_byte = 0, high_bit = 0;
+ uint32_t bit_offset = 0;
+ uint32_t match_bits = 0, mask_bits = 0;
+ uint32_t buff1 = 0, buff2 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0;
+ unsigned char *src;
+ unsigned char *dst;
+ tsample_t sample;
- if ((ibuff == NULL) || (obuff == NULL))
+ if ((ibuff == NULL) || (obuff == NULL))
{
- TIFFError("reverseSamples24bits","Invalid image or work buffer");
- return (1);
+ TIFFError("reverseSamples24bits", "Invalid image or work buffer");
+ return (1);
}
- ready_bits = 0;
- mask_bits = (uint32_t)-1 >> (32 - bps);
- dst = obuff;
- for (col = width; col > 0; col--)
+ ready_bits = 0;
+ mask_bits = (uint32_t)-1 >> (32 - bps);
+ dst = obuff;
+ for (col = width; col > 0; col--)
{
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = (col - 1) * bps * spp;
- for (sample = 0; sample < spp; sample++)
- {
- if (sample == 0)
- {
- src_byte = bit_offset / 8;
- high_bit = bit_offset % 8;
- }
- else
- {
- src_byte = (bit_offset + (sample * bps)) / 8;
- high_bit = (bit_offset + (sample * bps)) % 8;
- }
-
- src = ibuff + src_byte;
- match_bits = mask_bits << (32 - high_bit - bps);
- if (little_endian)
- buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
- else
- buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
- buff1 = (buff1 & match_bits) << (high_bit);
-
- if (ready_bits < 16)
- { /* add another bps bits to the buffer */
- bytebuff1 = bytebuff2 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
- }
- else /* If we have a full buffer's worth, write it out */
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = (col - 1) * bps * spp;
+ for (sample = 0; sample < spp; sample++)
{
- bytebuff1 = (buff2 >> 24);
- *dst++ = bytebuff1;
- bytebuff2 = (buff2 >> 16);
- *dst++ = bytebuff2;
- ready_bits -= 16;
+ if (sample == 0)
+ {
+ src_byte = bit_offset / 8;
+ high_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sample * bps)) / 8;
+ high_bit = (bit_offset + (sample * bps)) % 8;
+ }
- /* shift in new bits */
- buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
+ src = ibuff + src_byte;
+ match_bits = mask_bits << (32 - high_bit - bps);
+ if (little_endian)
+ buff1 =
+ (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
+ else
+ buff1 =
+ (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
+ buff1 = (buff1 & match_bits) << (high_bit);
+
+ if (ready_bits < 16)
+ { /* add another bps bits to the buffer */
+ bytebuff1 = bytebuff2 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ else /* If we have a full buffer's worth, write it out */
+ {
+ bytebuff1 = (buff2 >> 24);
+ *dst++ = bytebuff1;
+ bytebuff2 = (buff2 >> 16);
+ *dst++ = bytebuff2;
+ ready_bits -= 16;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- ready_bits += bps;
- }
}
- /* catch any trailing bits at the end of the line */
- while (ready_bits > 0)
+ /* catch any trailing bits at the end of the line */
+ while (ready_bits > 0)
{
- bytebuff1 = (buff2 >> 24);
- *dst++ = bytebuff1;
+ bytebuff1 = (buff2 >> 24);
+ *dst++ = bytebuff1;
- buff2 = (buff2 << 8);
- bytebuff2 = bytebuff1;
- ready_bits -= 8;
+ buff2 = (buff2 << 8);
+ bytebuff2 = bytebuff1;
+ ready_bits -= 8;
}
-
- return (0);
- } /* end reverseSamples24bits */
+ return (0);
+} /* end reverseSamples24bits */
-static int
-reverseSamples32bits (uint16_t spp, uint16_t bps, uint32_t width,
- uint8_t *ibuff, uint8_t *obuff)
- {
- int ready_bits = 0 /*, shift_width = 0 */;
- /* int bytes_per_sample, bytes_per_pixel; */
- uint32_t bit_offset;
- uint32_t src_byte = 0, high_bit = 0;
- uint32_t col;
- uint32_t longbuff1 = 0, longbuff2 = 0;
- uint64_t mask_bits = 0, match_bits = 0;
- uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
- uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
- unsigned char *src;
- unsigned char *dst;
- tsample_t sample;
+static int reverseSamples32bits(uint16_t spp, uint16_t bps, uint32_t width,
+ uint8_t *ibuff, uint8_t *obuff)
+{
+ int ready_bits = 0 /*, shift_width = 0 */;
+ /* int bytes_per_sample, bytes_per_pixel; */
+ uint32_t bit_offset;
+ uint32_t src_byte = 0, high_bit = 0;
+ uint32_t col;
+ uint32_t longbuff1 = 0, longbuff2 = 0;
+ uint64_t mask_bits = 0, match_bits = 0;
+ uint64_t buff1 = 0, buff2 = 0, buff3 = 0;
+ uint8_t bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
+ unsigned char *src;
+ unsigned char *dst;
+ tsample_t sample;
- if ((ibuff == NULL) || (obuff == NULL))
+ if ((ibuff == NULL) || (obuff == NULL))
{
- TIFFError("reverseSamples32bits","Invalid image or work buffer");
- return (1);
+ TIFFError("reverseSamples32bits", "Invalid image or work buffer");
+ return (1);
}
- ready_bits = 0;
- mask_bits = (uint64_t)-1 >> (64 - bps);
- dst = obuff;
+ ready_bits = 0;
+ mask_bits = (uint64_t)-1 >> (64 - bps);
+ dst = obuff;
- /* bytes_per_sample = (bps + 7) / 8; */
- /* bytes_per_pixel = ((bps * spp) + 7) / 8; */
- /* if (bytes_per_pixel < (bytes_per_sample + 1)) */
- /* shift_width = bytes_per_pixel; */
- /* else */
- /* shift_width = bytes_per_sample + 1; */
+ /* bytes_per_sample = (bps + 7) / 8; */
+ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */
+ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */
+ /* shift_width = bytes_per_pixel; */
+ /* else */
+ /* shift_width = bytes_per_sample + 1; */
- for (col = width; col > 0; col--)
+ for (col = width; col > 0; col--)
{
- /* Compute src byte(s) and bits within byte(s) */
- bit_offset = (col - 1) * bps * spp;
- for (sample = 0; sample < spp; sample++)
- {
- if (sample == 0)
- {
- src_byte = bit_offset / 8;
- high_bit = bit_offset % 8;
- }
- else
+ /* Compute src byte(s) and bits within byte(s) */
+ bit_offset = (col - 1) * bps * spp;
+ for (sample = 0; sample < spp; sample++)
{
- src_byte = (bit_offset + (sample * bps)) / 8;
- high_bit = (bit_offset + (sample * bps)) % 8;
- }
+ if (sample == 0)
+ {
+ src_byte = bit_offset / 8;
+ high_bit = bit_offset % 8;
+ }
+ else
+ {
+ src_byte = (bit_offset + (sample * bps)) / 8;
+ high_bit = (bit_offset + (sample * bps)) % 8;
+ }
- src = ibuff + src_byte;
- match_bits = mask_bits << (64 - high_bit - bps);
- if (little_endian)
- {
- longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
- longbuff2 = longbuff1;
- }
- else
- {
- longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
- longbuff2 = longbuff1;
- }
- buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
- buff1 = (buff3 & match_bits) << (high_bit);
+ src = ibuff + src_byte;
+ match_bits = mask_bits << (64 - high_bit - bps);
+ if (little_endian)
+ {
+ longbuff1 =
+ (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
+ longbuff2 = longbuff1;
+ }
+ else
+ {
+ longbuff1 =
+ (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
+ longbuff2 = longbuff1;
+ }
+ buff3 = ((uint64_t)longbuff1 << 32) | longbuff2;
+ buff1 = (buff3 & match_bits) << (high_bit);
- if (ready_bits < 32)
- { /* add another bps bits to the buffer */
- bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
- buff2 = (buff2 | (buff1 >> ready_bits));
+ if (ready_bits < 32)
+ { /* add another bps bits to the buffer */
+ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
+ buff2 = (buff2 | (buff1 >> ready_bits));
+ }
+ else /* If we have a full buffer's worth, write it out */
+ {
+ bytebuff1 = (uint8_t)(buff2 >> 56);
+ *dst++ = bytebuff1;
+ bytebuff2 = (uint8_t)(buff2 >> 48);
+ *dst++ = bytebuff2;
+ bytebuff3 = (uint8_t)(buff2 >> 40);
+ *dst++ = bytebuff3;
+ bytebuff4 = (uint8_t)(buff2 >> 32);
+ *dst++ = bytebuff4;
+ ready_bits -= 32;
+
+ /* shift in new bits */
+ buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
+ }
+ ready_bits += bps;
}
- else /* If we have a full buffer's worth, write it out */
- {
- bytebuff1 = (uint8_t)(buff2 >> 56);
+ }
+ while (ready_bits > 0)
+ {
+ bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
- bytebuff2 = (uint8_t)(buff2 >> 48);
- *dst++ = bytebuff2;
- bytebuff3 = (uint8_t)(buff2 >> 40);
- *dst++ = bytebuff3;
- bytebuff4 = (uint8_t)(buff2 >> 32);
- *dst++ = bytebuff4;
- ready_bits -= 32;
-
- /* shift in new bits */
- buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
- }
- ready_bits += bps;
- }
- }
- while (ready_bits > 0)
- {
- bytebuff1 = (buff2 >> 56);
- *dst++ = bytebuff1;
- buff2 = (buff2 << 8);
- ready_bits -= 8;
- }
-
- return (0);
- } /* end reverseSamples32bits */
-
-static int
-reverseSamplesBytes (uint16_t spp, uint16_t bps, uint32_t width,
- uint8_t *src, uint8_t *dst)
- {
- int i;
- uint32_t col, bytes_per_pixel, col_offset;
- uint8_t bytebuff1;
- unsigned char swapbuff[32];
-
- if ((src == NULL) || (dst == NULL))
- {
- TIFFError("reverseSamplesBytes","Invalid input or output buffer");
- return (1);
+ buff2 = (buff2 << 8);
+ ready_bits -= 8;
}
- bytes_per_pixel = ((bps * spp) + 7) / 8;
- if( bytes_per_pixel > sizeof(swapbuff) )
- {
- TIFFError("reverseSamplesBytes","bytes_per_pixel too large");
- return (1);
- }
- switch (bps / 8)
- {
- case 8: /* Use memcpy for multiple bytes per sample data */
- case 4:
- case 3:
- case 2: for (col = 0; col < (width / 2); col++)
- {
- col_offset = col * bytes_per_pixel;
- _TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel);
- _TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel);
- _TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel);
- }
- break;
- case 1: /* Use byte copy only for single byte per sample data */
- for (col = 0; col < (width / 2); col++)
- {
- for (i = 0; i < spp; i++)
- {
- bytebuff1 = *src;
- *src++ = *(dst - spp + i);
- *(dst - spp + i) = bytebuff1;
- }
- dst -= spp;
- }
- break;
- default: TIFFError("reverseSamplesBytes","Unsupported bit depth %"PRIu16, bps);
- return (1);
- }
- return (0);
- } /* end reverseSamplesBytes */
+ return (0);
+} /* end reverseSamples32bits */
+static int reverseSamplesBytes(uint16_t spp, uint16_t bps, uint32_t width,
+ uint8_t *src, uint8_t *dst)
+{
+ int i;
+ uint32_t col, bytes_per_pixel, col_offset;
+ uint8_t bytebuff1;
+ unsigned char swapbuff[32];
+
+ if ((src == NULL) || (dst == NULL))
+ {
+ TIFFError("reverseSamplesBytes", "Invalid input or output buffer");
+ return (1);
+ }
+
+ bytes_per_pixel = ((bps * spp) + 7) / 8;
+ if (bytes_per_pixel > sizeof(swapbuff))
+ {
+ TIFFError("reverseSamplesBytes", "bytes_per_pixel too large");
+ return (1);
+ }
+ switch (bps / 8)
+ {
+ case 8: /* Use memcpy for multiple bytes per sample data */
+ case 4:
+ case 3:
+ case 2:
+ for (col = 0; col < (width / 2); col++)
+ {
+ col_offset = col * bytes_per_pixel;
+ _TIFFmemcpy(swapbuff, src + col_offset, bytes_per_pixel);
+ _TIFFmemcpy(src + col_offset,
+ dst - col_offset - bytes_per_pixel,
+ bytes_per_pixel);
+ _TIFFmemcpy(dst - col_offset - bytes_per_pixel, swapbuff,
+ bytes_per_pixel);
+ }
+ break;
+ case 1: /* Use byte copy only for single byte per sample data */
+ for (col = 0; col < (width / 2); col++)
+ {
+ for (i = 0; i < spp; i++)
+ {
+ bytebuff1 = *src;
+ *src++ = *(dst - spp + i);
+ *(dst - spp + i) = bytebuff1;
+ }
+ dst -= spp;
+ }
+ break;
+ default:
+ TIFFError("reverseSamplesBytes", "Unsupported bit depth %" PRIu16,
+ bps);
+ return (1);
+ }
+ return (0);
+} /* end reverseSamplesBytes */
/* Mirror an image horizontally or vertically */
-static int
-mirrorImage(uint16_t spp, uint16_t bps, uint16_t mirror, uint32_t width, uint32_t length, unsigned char *ibuff)
- {
- int shift_width;
- uint32_t bytes_per_pixel, bytes_per_sample;
- uint32_t row, rowsize, row_offset;
- unsigned char *line_buff = NULL;
- unsigned char *src;
- unsigned char *dst;
-
- src = ibuff;
- rowsize = ((width * bps * spp) + 7) / 8;
- switch (mirror)
- {
- case MIRROR_BOTH:
- case MIRROR_VERT:
- line_buff = (unsigned char *)limitMalloc(rowsize + NUM_BUFF_OVERSIZE_BYTES);
- if (line_buff == NULL)
- {
- TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize + NUM_BUFF_OVERSIZE_BYTES);
- return (-1);
- }
- _TIFFmemset(line_buff, '\0', rowsize + NUM_BUFF_OVERSIZE_BYTES);
-
- dst = ibuff + (rowsize * (length - 1));
- for (row = 0; row < length / 2; row++)
- {
- _TIFFmemcpy(line_buff, src, rowsize);
- _TIFFmemcpy(src, dst, rowsize);
- _TIFFmemcpy(dst, line_buff, rowsize);
- src += (rowsize);
- dst -= (rowsize);
- }
- if (line_buff)
- _TIFFfree(line_buff);
- if (mirror == MIRROR_VERT)
- break;
- /* Fall through */
- case MIRROR_HORIZ :
- if ((bps % 8) == 0) /* byte aligned data */
- {
+static int mirrorImage(uint16_t spp, uint16_t bps, uint16_t mirror,
+ uint32_t width, uint32_t length, unsigned char *ibuff)
+{
+ int shift_width;
+ uint32_t bytes_per_pixel, bytes_per_sample;
+ uint32_t row, rowsize, row_offset;
+ unsigned char *line_buff = NULL;
+ unsigned char *src;
+ unsigned char *dst;
+
+ src = ibuff;
+ rowsize = ((width * bps * spp) + 7) / 8;
+ switch (mirror)
+ {
+ case MIRROR_BOTH:
+ case MIRROR_VERT:
+ line_buff =
+ (unsigned char *)limitMalloc(rowsize + NUM_BUFF_OVERSIZE_BYTES);
+ if (line_buff == NULL)
+ {
+ TIFFError("mirrorImage",
+ "Unable to allocate mirror line buffer of %1u bytes",
+ rowsize + NUM_BUFF_OVERSIZE_BYTES);
+ return (-1);
+ }
+ _TIFFmemset(line_buff, '\0', rowsize + NUM_BUFF_OVERSIZE_BYTES);
+
+ dst = ibuff + (rowsize * (length - 1));
+ for (row = 0; row < length / 2; row++)
+ {
+ _TIFFmemcpy(line_buff, src, rowsize);
+ _TIFFmemcpy(src, dst, rowsize);
+ _TIFFmemcpy(dst, line_buff, rowsize);
+ src += (rowsize);
+ dst -= (rowsize);
+ }
+ if (line_buff)
+ _TIFFfree(line_buff);
+ if (mirror == MIRROR_VERT)
+ break;
+ /* Fall through */
+ case MIRROR_HORIZ:
+ if ((bps % 8) == 0) /* byte aligned data */
+ {
for (row = 0; row < length; row++)
- {
- row_offset = row * rowsize;
- src = ibuff + row_offset;
- dst = ibuff + row_offset + rowsize;
- if (reverseSamplesBytes(spp, bps, width, src, dst))
+ {
+ row_offset = row * rowsize;
+ src = ibuff + row_offset;
+ dst = ibuff + row_offset + rowsize;
+ if (reverseSamplesBytes(spp, bps, width, src, dst))
{
- return (-1);
+ return (-1);
}
- }
- }
- else
- { /* non 8 bit per sample data */
- if (!(line_buff = (unsigned char *)limitMalloc(rowsize + NUM_BUFF_OVERSIZE_BYTES)))
- {
- TIFFError("mirrorImage", "Unable to allocate mirror line buffer");
- return (-1);
- }
+ }
+ }
+ else
+ { /* non 8 bit per sample data */
+ if (!(line_buff = (unsigned char *)limitMalloc(
+ rowsize + NUM_BUFF_OVERSIZE_BYTES)))
+ {
+ TIFFError("mirrorImage",
+ "Unable to allocate mirror line buffer");
+ return (-1);
+ }
_TIFFmemset(line_buff, '\0', rowsize + NUM_BUFF_OVERSIZE_BYTES);
bytes_per_sample = (bps + 7) / 8;
- bytes_per_pixel = ((bps * spp) + 7) / 8;
+ bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
- shift_width = bytes_per_pixel;
+ shift_width = bytes_per_pixel;
else
- shift_width = bytes_per_sample + 1;
+ shift_width = bytes_per_sample + 1;
for (row = 0; row < length; row++)
- {
- row_offset = row * rowsize;
- src = ibuff + row_offset;
- _TIFFmemset (line_buff, '\0', rowsize + NUM_BUFF_OVERSIZE_BYTES);
- switch (shift_width)
+ {
+ row_offset = row * rowsize;
+ src = ibuff + row_offset;
+ _TIFFmemset(line_buff, '\0',
+ rowsize + NUM_BUFF_OVERSIZE_BYTES);
+ switch (shift_width)
{
- case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff))
- {
- _TIFFfree(line_buff);
- return (-1);
- }
- _TIFFmemcpy (src, line_buff, rowsize);
- break;
- case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff))
- {
- _TIFFfree(line_buff);
- return (-1);
- }
- _TIFFmemcpy (src, line_buff, rowsize);
- break;
- case 3:
- case 4:
- case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff))
- {
- _TIFFfree(line_buff);
- return (-1);
- }
- _TIFFmemcpy (src, line_buff, rowsize);
- break;
- default: TIFFError("mirrorImage","Unsupported bit depth %"PRIu16, bps);
- _TIFFfree(line_buff);
- return (-1);
+ case 1:
+ if (reverseSamples16bits(spp, bps, width, src,
+ line_buff))
+ {
+ _TIFFfree(line_buff);
+ return (-1);
+ }
+ _TIFFmemcpy(src, line_buff, rowsize);
+ break;
+ case 2:
+ if (reverseSamples24bits(spp, bps, width, src,
+ line_buff))
+ {
+ _TIFFfree(line_buff);
+ return (-1);
+ }
+ _TIFFmemcpy(src, line_buff, rowsize);
+ break;
+ case 3:
+ case 4:
+ case 5:
+ if (reverseSamples32bits(spp, bps, width, src,
+ line_buff))
+ {
+ _TIFFfree(line_buff);
+ return (-1);
+ }
+ _TIFFmemcpy(src, line_buff, rowsize);
+ break;
+ default:
+ TIFFError("mirrorImage",
+ "Unsupported bit depth %" PRIu16, bps);
+ _TIFFfree(line_buff);
+ return (-1);
}
- }
+ }
if (line_buff)
- _TIFFfree(line_buff);
- }
- break;
+ _TIFFfree(line_buff);
+ }
+ break;
- default: TIFFError ("mirrorImage", "Invalid mirror axis %"PRIu16, mirror);
- return (-1);
- break;
+ default:
+ TIFFError("mirrorImage", "Invalid mirror axis %" PRIu16, mirror);
+ return (-1);
+ break;
}
- return (0);
- }
+ return (0);
+}
/* Invert the light and dark values for a bilevel or grayscale image */
-static int
-invertImage(uint16_t photometric, uint16_t spp, uint16_t bps, uint32_t width, uint32_t length, unsigned char *work_buff)
- {
- uint32_t row, col;
- unsigned char *src;
- uint16_t *src_uint16;
- uint32_t *src_uint32;
+static int invertImage(uint16_t photometric, uint16_t spp, uint16_t bps,
+ uint32_t width, uint32_t length,
+ unsigned char *work_buff)
+{
+ uint32_t row, col;
+ unsigned char *src;
+ uint16_t *src_uint16;
+ uint32_t *src_uint32;
- if (spp != 1)
+ if (spp != 1)
{
- TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel");
- return (-1);
+ TIFFError(
+ "invertImage",
+ "Image inversion not supported for more than one sample per pixel");
+ return (-1);
}
- if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK)
+ if (photometric != PHOTOMETRIC_MINISWHITE &&
+ photometric != PHOTOMETRIC_MINISBLACK)
{
- TIFFError("invertImage", "Only black and white and grayscale images can be inverted");
- return (-1);
+ TIFFError("invertImage",
+ "Only black and white and grayscale images can be inverted");
+ return (-1);
}
- src = work_buff;
- if (src == NULL)
+ src = work_buff;
+ if (src == NULL)
{
- TIFFError ("invertImage", "Invalid crop buffer passed to invertImage");
- return (-1);
+ TIFFError("invertImage", "Invalid crop buffer passed to invertImage");
+ return (-1);
}
- switch (bps)
+ switch (bps)
{
- case 32: src_uint32 = (uint32_t *)src;
- for (row = 0; row < length; row++)
- for (col = 0; col < width; col++)
- {
- *src_uint32 = ~(*src_uint32);
- src_uint32++;
- }
+ case 32:
+ src_uint32 = (uint32_t *)src;
+ for (row = 0; row < length; row++)
+ for (col = 0; col < width; col++)
+ {
+ *src_uint32 = ~(*src_uint32);
+ src_uint32++;
+ }
break;
- case 16: src_uint16 = (uint16_t *)src;
- for (row = 0; row < length; row++)
- for (col = 0; col < width; col++)
- {
- *src_uint16 = ~(*src_uint16);
- src_uint16++;
- }
+ case 16:
+ src_uint16 = (uint16_t *)src;
+ for (row = 0; row < length; row++)
+ for (col = 0; col < width; col++)
+ {
+ *src_uint16 = ~(*src_uint16);
+ src_uint16++;
+ }
break;
- case 8:
- case 4:
- case 2:
- case 1: for (row = 0; row < length; row++)
- for (col = 0; col < width; col += 8 / bps)
+ case 8:
+ case 4:
+ case 2:
+ case 1:
+ for (row = 0; row < length; row++)
+ for (col = 0; col < width; col += 8 / bps)
{
- *src = ~(*src);
- src++;
+ *src = ~(*src);
+ src++;
}
break;
- default: TIFFError("invertImage", "Unsupported bit depth %"PRIu16, bps);
- return (-1);
+ default:
+ TIFFError("invertImage", "Unsupported bit depth %" PRIu16, bps);
+ return (-1);
}
- return (0);
- }
+ return (0);
+}
diff --git a/tools/tiffdither.c b/tools/tiffdither.c
index f2503cdd..187a61a2 100644
--- a/tools/tiffdither.c
+++ b/tools/tiffdither.c
@@ -2,35 +2,35 @@
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#include "tiffio.h"
@@ -43,311 +43,328 @@
#define EXIT_FAILURE 1
#endif
-#define streq(a,b) (strcmp(a,b) == 0)
-#define strneq(a,b,n) (strncmp(a,b,n) == 0)
+#define streq(a, b) (strcmp(a, b) == 0)
+#define strneq(a, b, n) (strncmp(a, b, n) == 0)
-#define CopyField(tag, v) \
- if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
+#define CopyField(tag, v) \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v)
-uint32_t imagewidth;
-uint32_t imagelength;
-int threshold = 128;
+uint32_t imagewidth;
+uint32_t imagelength;
+int threshold = 128;
-static void usage(int code);
+static void usage(int code);
-/*
+/*
* Floyd-Steinberg error propragation with threshold.
* This code is stolen from tiffmedian.
*/
-static int
-fsdither(TIFF* in, TIFF* out)
+static int fsdither(TIFF *in, TIFF *out)
{
- unsigned char *outline, *inputline, *inptr;
- short *thisline, *nextline, *tmpptr;
- register unsigned char *outptr;
- register short *thisptr, *nextptr;
- register uint32_t i, j;
- uint32_t imax, jmax;
- int lastline, lastpixel;
- int bit;
- tsize_t outlinesize;
- int errcode = 0;
+ unsigned char *outline, *inputline, *inptr;
+ short *thisline, *nextline, *tmpptr;
+ register unsigned char *outptr;
+ register short *thisptr, *nextptr;
+ register uint32_t i, j;
+ uint32_t imax, jmax;
+ int lastline, lastpixel;
+ int bit;
+ tsize_t outlinesize;
+ int errcode = 0;
- imax = imagelength - 1;
- jmax = imagewidth - 1;
- inputline = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
- thisline = (short *)_TIFFmalloc(TIFFSafeMultiply(tmsize_t, imagewidth, sizeof (short)));
- nextline = (short *)_TIFFmalloc(TIFFSafeMultiply(tmsize_t, imagewidth, sizeof (short)));
- outlinesize = TIFFScanlineSize(out);
- outline = (unsigned char *) _TIFFmalloc(outlinesize);
- if (! (inputline && thisline && nextline && outline)) {
- fprintf(stderr, "Out of memory.\n");
- goto skip_on_error;
- }
+ imax = imagelength - 1;
+ jmax = imagewidth - 1;
+ inputline = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
+ thisline = (short *)_TIFFmalloc(
+ TIFFSafeMultiply(tmsize_t, imagewidth, sizeof(short)));
+ nextline = (short *)_TIFFmalloc(
+ TIFFSafeMultiply(tmsize_t, imagewidth, sizeof(short)));
+ outlinesize = TIFFScanlineSize(out);
+ outline = (unsigned char *)_TIFFmalloc(outlinesize);
+ if (!(inputline && thisline && nextline && outline))
+ {
+ fprintf(stderr, "Out of memory.\n");
+ goto skip_on_error;
+ }
- /*
- * Get first line
- */
- if (TIFFReadScanline(in, inputline, 0, 0) <= 0)
- goto skip_on_error;
+ /*
+ * Get first line
+ */
+ if (TIFFReadScanline(in, inputline, 0, 0) <= 0)
+ goto skip_on_error;
- inptr = inputline;
- nextptr = nextline;
- for (j = 0; j < imagewidth; ++j)
- *nextptr++ = *inptr++;
- for (i = 1; i < imagelength; ++i) {
- tmpptr = thisline;
- thisline = nextline;
- nextline = tmpptr;
- lastline = (i == imax);
- if (TIFFReadScanline(in, inputline, i, 0) <= 0)
- goto skip_on_error;
- inptr = inputline;
- nextptr = nextline;
- for (j = 0; j < imagewidth; ++j)
- *nextptr++ = *inptr++;
- thisptr = thisline;
- nextptr = nextline;
- _TIFFmemset(outptr = outline, 0, outlinesize);
- bit = 0x80;
- for (j = 0; j < imagewidth; ++j) {
- register int v;
+ inptr = inputline;
+ nextptr = nextline;
+ for (j = 0; j < imagewidth; ++j)
+ *nextptr++ = *inptr++;
+ for (i = 1; i < imagelength; ++i)
+ {
+ tmpptr = thisline;
+ thisline = nextline;
+ nextline = tmpptr;
+ lastline = (i == imax);
+ if (TIFFReadScanline(in, inputline, i, 0) <= 0)
+ goto skip_on_error;
+ inptr = inputline;
+ nextptr = nextline;
+ for (j = 0; j < imagewidth; ++j)
+ *nextptr++ = *inptr++;
+ thisptr = thisline;
+ nextptr = nextline;
+ _TIFFmemset(outptr = outline, 0, outlinesize);
+ bit = 0x80;
+ for (j = 0; j < imagewidth; ++j)
+ {
+ register int v;
- lastpixel = (j == jmax);
- v = *thisptr++;
- if (v < 0)
- v = 0;
- else if (v > 255)
- v = 255;
- if (v > threshold) {
- *outptr |= bit;
- v -= 255;
- }
- bit >>= 1;
- if (bit == 0) {
- outptr++;
- bit = 0x80;
- }
- if (!lastpixel)
- thisptr[0] += v * 7 / 16;
- if (!lastline) {
- if (j != 0)
- nextptr[-1] += v * 3 / 16;
- *nextptr++ += v * 5 / 16;
- if (!lastpixel)
- nextptr[0] += v / 16;
- }
- }
- if (TIFFWriteScanline(out, outline, i-1, 0) < 0)
- goto skip_on_error;
- }
- goto exit_label;
+ lastpixel = (j == jmax);
+ v = *thisptr++;
+ if (v < 0)
+ v = 0;
+ else if (v > 255)
+ v = 255;
+ if (v > threshold)
+ {
+ *outptr |= bit;
+ v -= 255;
+ }
+ bit >>= 1;
+ if (bit == 0)
+ {
+ outptr++;
+ bit = 0x80;
+ }
+ if (!lastpixel)
+ thisptr[0] += v * 7 / 16;
+ if (!lastline)
+ {
+ if (j != 0)
+ nextptr[-1] += v * 3 / 16;
+ *nextptr++ += v * 5 / 16;
+ if (!lastpixel)
+ nextptr[0] += v / 16;
+ }
+ }
+ if (TIFFWriteScanline(out, outline, i - 1, 0) < 0)
+ goto skip_on_error;
+ }
+ goto exit_label;
- skip_on_error:
- errcode = 1;
- exit_label:
- _TIFFfree(inputline);
- _TIFFfree(thisline);
- _TIFFfree(nextline);
- _TIFFfree(outline);
- return errcode;
+skip_on_error:
+ errcode = 1;
+exit_label:
+ _TIFFfree(inputline);
+ _TIFFfree(thisline);
+ _TIFFfree(nextline);
+ _TIFFfree(outline);
+ return errcode;
}
-static uint16_t compression = COMPRESSION_PACKBITS;
-static uint16_t predictor = 0;
-static uint32_t group3options = 0;
+static uint16_t compression = COMPRESSION_PACKBITS;
+static uint16_t predictor = 0;
+static uint32_t group3options = 0;
-static void
-processG3Options(char* cp)
+static void processG3Options(char *cp)
{
- if ((cp = strchr(cp, ':'))) {
- do {
- cp++;
- if (strneq(cp, "1d", 2))
- group3options &= ~GROUP3OPT_2DENCODING;
- else if (strneq(cp, "2d", 2))
- group3options |= GROUP3OPT_2DENCODING;
- else if (strneq(cp, "fill", 4))
- group3options |= GROUP3OPT_FILLBITS;
- else
- usage(EXIT_FAILURE);
- } while ((cp = strchr(cp, ':')));
- }
+ if ((cp = strchr(cp, ':')))
+ {
+ do
+ {
+ cp++;
+ if (strneq(cp, "1d", 2))
+ group3options &= ~GROUP3OPT_2DENCODING;
+ else if (strneq(cp, "2d", 2))
+ group3options |= GROUP3OPT_2DENCODING;
+ else if (strneq(cp, "fill", 4))
+ group3options |= GROUP3OPT_FILLBITS;
+ else
+ usage(EXIT_FAILURE);
+ } while ((cp = strchr(cp, ':')));
+ }
}
-static int
-processCompressOptions(char* opt)
+static int processCompressOptions(char *opt)
{
- if (streq(opt, "none"))
- compression = COMPRESSION_NONE;
- else if (streq(opt, "packbits"))
- compression = COMPRESSION_PACKBITS;
- else if (strneq(opt, "g3", 2)) {
- processG3Options(opt);
- compression = COMPRESSION_CCITTFAX3;
- } else if (streq(opt, "g4"))
- compression = COMPRESSION_CCITTFAX4;
- else if (strneq(opt, "lzw", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_LZW;
- } else if (strneq(opt, "zip", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_ADOBE_DEFLATE;
- } else
- return (0);
- return (1);
+ if (streq(opt, "none"))
+ compression = COMPRESSION_NONE;
+ else if (streq(opt, "packbits"))
+ compression = COMPRESSION_PACKBITS;
+ else if (strneq(opt, "g3", 2))
+ {
+ processG3Options(opt);
+ compression = COMPRESSION_CCITTFAX3;
+ }
+ else if (streq(opt, "g4"))
+ compression = COMPRESSION_CCITTFAX4;
+ else if (strneq(opt, "lzw", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_LZW;
+ }
+ else if (strneq(opt, "zip", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_ADOBE_DEFLATE;
+ }
+ else
+ return (0);
+ return (1);
}
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- TIFF *in, *out;
- uint16_t samplesperpixel, bitspersample = 1, shortv;
- float floatv;
- char thing[1024];
- uint32_t rowsperstrip = (uint32_t) -1;
- uint16_t fillorder = 0;
- int c;
+ TIFF *in, *out;
+ uint16_t samplesperpixel, bitspersample = 1, shortv;
+ float floatv;
+ char thing[1024];
+ uint32_t rowsperstrip = (uint32_t)-1;
+ uint16_t fillorder = 0;
+ int c;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char *optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- while ((c = getopt(argc, argv, "c:f:r:t:h")) != -1)
- switch (c) {
- case 'c': /* compression scheme */
- if (!processCompressOptions(optarg))
- usage(EXIT_FAILURE);
- break;
- case 'f': /* fill order */
- if (streq(optarg, "lsb2msb"))
- fillorder = FILLORDER_LSB2MSB;
- else if (streq(optarg, "msb2lsb"))
- fillorder = FILLORDER_MSB2LSB;
- else
- usage(EXIT_FAILURE);
- break;
- case 'r': /* rows/strip */
- rowsperstrip = atoi(optarg);
- break;
- case 't':
- threshold = atoi(optarg);
- if (threshold < 0)
- threshold = 0;
- else if (threshold > 255)
- threshold = 255;
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- /*NOTREACHED*/
- break;
- case '?':
- usage(EXIT_FAILURE);
- /*NOTREACHED*/
- break;
- }
- if (argc - optind < 2)
- usage(EXIT_FAILURE);
- in = TIFFOpen(argv[optind], "r");
- if (in == NULL)
- return (EXIT_FAILURE);
- TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
- if (samplesperpixel != 1) {
- fprintf(stderr, "%s: Not a b&w image.\n", argv[0]);
- return (EXIT_FAILURE);
- }
- TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
- if (bitspersample != 8) {
- fprintf(stderr,
- " %s: Sorry, only handle 8-bit samples.\n", argv[0]);
- return (EXIT_FAILURE);
- }
- out = TIFFOpen(argv[optind+1], "w");
- if (out == NULL)
- return (EXIT_FAILURE);
- CopyField(TIFFTAG_IMAGEWIDTH, imagewidth);
- TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength);
- TIFFSetField(out, TIFFTAG_IMAGELENGTH, imagelength-1);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 1);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 1);
- TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- if (fillorder)
- TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
- else
- CopyField(TIFFTAG_FILLORDER, shortv);
- snprintf(thing, sizeof(thing), "Dithered B&W version of %s", argv[optind]);
- TIFFSetField(out, TIFFTAG_IMAGEDESCRIPTION, thing);
- CopyField(TIFFTAG_PHOTOMETRIC, shortv);
- CopyField(TIFFTAG_ORIENTATION, shortv);
- CopyField(TIFFTAG_XRESOLUTION, floatv);
- CopyField(TIFFTAG_YRESOLUTION, floatv);
- CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
- rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
- switch (compression) {
- case COMPRESSION_CCITTFAX3:
- TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, group3options);
- break;
- case COMPRESSION_LZW:
- case COMPRESSION_ADOBE_DEFLATE:
- case COMPRESSION_DEFLATE:
- if (predictor)
- TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
- break;
- }
- fsdither(in, out);
- TIFFClose(in);
- TIFFClose(out);
- return (EXIT_SUCCESS);
+ while ((c = getopt(argc, argv, "c:f:r:t:h")) != -1)
+ switch (c)
+ {
+ case 'c': /* compression scheme */
+ if (!processCompressOptions(optarg))
+ usage(EXIT_FAILURE);
+ break;
+ case 'f': /* fill order */
+ if (streq(optarg, "lsb2msb"))
+ fillorder = FILLORDER_LSB2MSB;
+ else if (streq(optarg, "msb2lsb"))
+ fillorder = FILLORDER_MSB2LSB;
+ else
+ usage(EXIT_FAILURE);
+ break;
+ case 'r': /* rows/strip */
+ rowsperstrip = atoi(optarg);
+ break;
+ case 't':
+ threshold = atoi(optarg);
+ if (threshold < 0)
+ threshold = 0;
+ else if (threshold > 255)
+ threshold = 255;
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ /*NOTREACHED*/
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ /*NOTREACHED*/
+ break;
+ }
+ if (argc - optind < 2)
+ usage(EXIT_FAILURE);
+ in = TIFFOpen(argv[optind], "r");
+ if (in == NULL)
+ return (EXIT_FAILURE);
+ TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
+ if (samplesperpixel != 1)
+ {
+ fprintf(stderr, "%s: Not a b&w image.\n", argv[0]);
+ return (EXIT_FAILURE);
+ }
+ TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
+ if (bitspersample != 8)
+ {
+ fprintf(stderr, " %s: Sorry, only handle 8-bit samples.\n", argv[0]);
+ return (EXIT_FAILURE);
+ }
+ out = TIFFOpen(argv[optind + 1], "w");
+ if (out == NULL)
+ return (EXIT_FAILURE);
+ CopyField(TIFFTAG_IMAGEWIDTH, imagewidth);
+ TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength);
+ TIFFSetField(out, TIFFTAG_IMAGELENGTH, imagelength - 1);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 1);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 1);
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
+ if (fillorder)
+ TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
+ else
+ CopyField(TIFFTAG_FILLORDER, shortv);
+ snprintf(thing, sizeof(thing), "Dithered B&W version of %s", argv[optind]);
+ TIFFSetField(out, TIFFTAG_IMAGEDESCRIPTION, thing);
+ CopyField(TIFFTAG_PHOTOMETRIC, shortv);
+ CopyField(TIFFTAG_ORIENTATION, shortv);
+ CopyField(TIFFTAG_XRESOLUTION, floatv);
+ CopyField(TIFFTAG_YRESOLUTION, floatv);
+ CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
+ rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
+ switch (compression)
+ {
+ case COMPRESSION_CCITTFAX3:
+ TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, group3options);
+ break;
+ case COMPRESSION_LZW:
+ case COMPRESSION_ADOBE_DEFLATE:
+ case COMPRESSION_DEFLATE:
+ if (predictor)
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
+ break;
+ }
+ fsdither(in, out);
+ TIFFClose(in);
+ TIFFClose(out);
+ return (EXIT_SUCCESS);
}
static const char usage_info[] =
-"Convert a greyscale image to bilevel using dithering\n\n"
-"usage: tiffdither [options] input.tif output.tif\n"
-"where options are:\n"
-" -r # make each strip have no more than # rows\n"
-" -t # set the threshold value for dithering (default 128)\n"
-" -f lsb2msb force lsb-to-msb FillOrder for output\n"
-" -f msb2lsb force msb-to-lsb FillOrder for output\n"
-"\n"
+ "Convert a greyscale image to bilevel using dithering\n\n"
+ "usage: tiffdither [options] input.tif output.tif\n"
+ "where options are:\n"
+ " -r # make each strip have no more than # rows\n"
+ " -t # set the threshold value for dithering (default 128)\n"
+ " -f lsb2msb force lsb-to-msb FillOrder for output\n"
+ " -f msb2lsb force msb-to-lsb FillOrder for output\n"
+ "\n"
#ifdef LZW_SUPPORT
-" -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
-" # set predictor value\n"
-" For example, -c lzw:2 for LZW-encoded data with horizontal differencing\n"
+ " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
+ " # set predictor value\n"
+ " For example, -c lzw:2 for LZW-encoded data with horizontal "
+ "differencing\n"
#endif
#ifdef ZIP_SUPPORT
-" -c zip[:opts] compress output with deflate encoding\n"
-" # set predictor value\n"
+ " -c zip[:opts] compress output with deflate encoding\n"
+ " # set predictor value\n"
#endif
#ifdef PACKBITS_SUPPORT
-" -c packbits compress output with packbits encoding\n"
+ " -c packbits compress output with packbits encoding\n"
#endif
#ifdef CCITT_SUPPORT
-" -c g3[:opts] compress output with CCITT Group 3 encoding\n"
-" Group 3 options:\n"
-" 1d use default CCITT Group 3 1D-encoding\n"
-" 2d use optional CCITT Group 3 2D-encoding\n"
-" fill byte-align EOL codes\n"
-" For example, -c g3:2d:fill for G3-2D-encoded data with byte-aligned EOLs\n"
-" -c g4 compress output with CCITT Group 4 encoding\n"
+ " -c g3[:opts] compress output with CCITT Group 3 encoding\n"
+ " Group 3 options:\n"
+ " 1d use default CCITT Group 3 1D-encoding\n"
+ " 2d use optional CCITT Group 3 2D-encoding\n"
+ " fill byte-align EOL codes\n"
+ " For example, -c g3:2d:fill for G3-2D-encoded data with byte-aligned "
+ "EOLs\n"
+ " -c g4 compress output with CCITT Group 4 encoding\n"
#endif
-#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(PACKBITS_SUPPORT) || defined(CCITT_SUPPORT)
-" -c none use no compression algorithm on output\n"
+#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || \
+ defined(PACKBITS_SUPPORT) || defined(CCITT_SUPPORT)
+ " -c none use no compression algorithm on output\n"
#endif
-"\n"
-;
+ "\n";
-static void
-usage(int code)
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
diff --git a/tools/tiffdump.c b/tools/tiffdump.c
index 06423343..df1f9358 100644
--- a/tools/tiffdump.c
+++ b/tools/tiffdump.c
@@ -2,49 +2,49 @@
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#include "tiffiop.h"
#ifdef HAVE_FCNTL_H
-# include <fcntl.h>
+#include <fcntl.h>
#endif
#ifdef HAVE_SYS_TYPES_H
-# include <sys/types.h>
+#include <sys/types.h>
#endif
#ifdef HAVE_IO_H
-# include <io.h>
+#include <io.h>
#endif
#include "tiffio.h"
@@ -57,40 +57,40 @@
#endif
#ifndef O_BINARY
-# define O_BINARY 0
+#define O_BINARY 0
#endif
static union
{
- TIFFHeaderClassic classic;
- TIFFHeaderBig big;
- TIFFHeaderCommon common;
+ TIFFHeaderClassic classic;
+ TIFFHeaderBig big;
+ TIFFHeaderCommon common;
} hdr;
-static char* appname;
-static char* curfile;
+static char *appname;
+static char *curfile;
static int swabflag;
static int bigendian;
static int bigtiff;
-static uint32_t maxitems = 24; /* maximum indirect data items to print */
+static uint32_t maxitems = 24; /* maximum indirect data items to print */
-static const char bytefmt[] = "%s%#02" PRIx8; /* BYTE */
-static const char sbytefmt[] = "%s%" PRId8; /* SBYTE */
-static const char shortfmtd[] = "%s%" PRIu16; /* SHORT */
+static const char bytefmt[] = "%s%#02" PRIx8; /* BYTE */
+static const char sbytefmt[] = "%s%" PRId8; /* SBYTE */
+static const char shortfmtd[] = "%s%" PRIu16; /* SHORT */
static const char shortfmth[] = "%s%#" PRIx16;
-static const char sshortfmtd[] = "%s%" PRId16; /* SSHORT */
+static const char sshortfmtd[] = "%s%" PRId16; /* SSHORT */
static const char sshortfmth[] = "%s%#" PRIx16;
-static const char longfmtd[] = "%s%" PRIu32; /* LONG */
+static const char longfmtd[] = "%s%" PRIu32; /* LONG */
static const char longfmth[] = "%s%#" PRIx32;
-static const char slongfmtd[] = "%s%" PRId32; /* SLONG */
+static const char slongfmtd[] = "%s%" PRId32; /* SLONG */
static const char slongfmth[] = "%s%#" PRIx32;
-static const char ifdfmt[] = "%s%#04" PRIx32; /* IFD offset */
-static const char long8fmt[] = "%s%" PRIu64; /* LONG8 */
-static const char slong8fmt[] = "%s%" PRId64; /* SLONG8 */
-static const char ifd8fmt[] = "%s%#08" PRIx64; /* IFD offset8 */
-static const char rationalfmt[] = "%s%g"; /* RATIONAL */
-static const char srationalfmt[] = "%s%g"; /* SRATIONAL */
-static const char floatfmt[] = "%s%g"; /* FLOAT */
-static const char doublefmt[] = "%s%g"; /* DOUBLE */
+static const char ifdfmt[] = "%s%#04" PRIx32; /* IFD offset */
+static const char long8fmt[] = "%s%" PRIu64; /* LONG8 */
+static const char slong8fmt[] = "%s%" PRId64; /* SLONG8 */
+static const char ifd8fmt[] = "%s%#08" PRIx64; /* IFD offset8 */
+static const char rationalfmt[] = "%s%g"; /* RATIONAL */
+static const char srationalfmt[] = "%s%g"; /* SRATIONAL */
+static const char floatfmt[] = "%s%g"; /* FLOAT */
+static const char doublefmt[] = "%s%g"; /* DOUBLE */
unsigned int hex_mode;
@@ -98,762 +98,795 @@ static void dump(int, uint64_t);
#if !HAVE_DECL_OPTARG
extern int optind;
-extern char* optarg;
+extern char *optarg;
#endif
-void
-usage()
+void usage()
{
- fprintf(stderr, "\nDisplay directory information from TIFF files\n\n");
- fprintf(stderr, "usage: %s [-h] [-o offset] [-m maxitems] file.tif ...\n", appname);
- exit(EXIT_FAILURE);
+ fprintf(stderr, "\nDisplay directory information from TIFF files\n\n");
+ fprintf(stderr, "usage: %s [-h] [-o offset] [-m maxitems] file.tif ...\n",
+ appname);
+ exit(EXIT_FAILURE);
}
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- int one = 1, fd;
- int multiplefiles = (argc > 1);
- int c;
- uint64_t diroff = 0;
- hex_mode=0;
- bigendian = (*(char *)&one == 0);
-
- appname = argv[0];
- while ((c = getopt(argc, argv, "m:o:h")) != -1) {
- switch (c) {
- case 'h': /* print values in hex */
- hex_mode=1;
- break;
- case 'o':
- diroff = (uint64_t) strtoul(optarg, NULL, 0);
- break;
- case 'm':
- maxitems = strtoul(optarg, NULL, 0);
- break;
- default:
- usage();
- }
- }
- if (optind >= argc)
- usage();
- for (; optind < argc; optind++) {
- fd = open(argv[optind], O_RDONLY|O_BINARY, 0);
- if (fd < 0) {
- perror(argv[0]);
- return (EXIT_FAILURE);
- }
- if (multiplefiles)
- printf("%s:\n", argv[optind]);
- curfile = argv[optind];
- swabflag = 0;
- bigtiff = 0;
- dump(fd, diroff);
- close(fd);
- }
- return (EXIT_SUCCESS);
+ int one = 1, fd;
+ int multiplefiles = (argc > 1);
+ int c;
+ uint64_t diroff = 0;
+ hex_mode = 0;
+ bigendian = (*(char *)&one == 0);
+
+ appname = argv[0];
+ while ((c = getopt(argc, argv, "m:o:h")) != -1)
+ {
+ switch (c)
+ {
+ case 'h': /* print values in hex */
+ hex_mode = 1;
+ break;
+ case 'o':
+ diroff = (uint64_t)strtoul(optarg, NULL, 0);
+ break;
+ case 'm':
+ maxitems = strtoul(optarg, NULL, 0);
+ break;
+ default:
+ usage();
+ }
+ }
+ if (optind >= argc)
+ usage();
+ for (; optind < argc; optind++)
+ {
+ fd = open(argv[optind], O_RDONLY | O_BINARY, 0);
+ if (fd < 0)
+ {
+ perror(argv[0]);
+ return (EXIT_FAILURE);
+ }
+ if (multiplefiles)
+ printf("%s:\n", argv[optind]);
+ curfile = argv[optind];
+ swabflag = 0;
+ bigtiff = 0;
+ dump(fd, diroff);
+ close(fd);
+ }
+ return (EXIT_SUCCESS);
}
#define ord(e) ((int)e)
static uint64_t ReadDirectory(int, unsigned, uint64_t);
-static void ReadError(char*);
-static void Error(const char*, ...);
-static void Fatal(const char*, ...);
+static void ReadError(char *);
+static void Error(const char *, ...);
+static void Fatal(const char *, ...);
-static void
-dump(int fd, uint64_t diroff)
+static void dump(int fd, uint64_t diroff)
{
- unsigned i, j;
- uint64_t* visited_diroff = NULL;
- unsigned int count_visited_dir = 0;
-
- _TIFF_lseek_f(fd, (_TIFF_off_t) 0, 0);
- if (read(fd, (char*) &hdr, sizeof (TIFFHeaderCommon)) != sizeof (TIFFHeaderCommon))
- ReadError("TIFF header");
- if (hdr.common.tiff_magic != TIFF_BIGENDIAN
- && hdr.common.tiff_magic != TIFF_LITTLEENDIAN &&
+ unsigned i, j;
+ uint64_t *visited_diroff = NULL;
+ unsigned int count_visited_dir = 0;
+
+ _TIFF_lseek_f(fd, (_TIFF_off_t)0, 0);
+ if (read(fd, (char *)&hdr, sizeof(TIFFHeaderCommon)) !=
+ sizeof(TIFFHeaderCommon))
+ ReadError("TIFF header");
+ if (hdr.common.tiff_magic != TIFF_BIGENDIAN &&
+ hdr.common.tiff_magic != TIFF_LITTLEENDIAN &&
#if HOST_BIGENDIAN
- /* MDI is sensitive to the host byte order, unlike TIFF */
- MDI_BIGENDIAN != hdr.common.tiff_magic
+ /* MDI is sensitive to the host byte order, unlike TIFF */
+ MDI_BIGENDIAN != hdr.common.tiff_magic
#else
- MDI_LITTLEENDIAN != hdr.common.tiff_magic
+ MDI_LITTLEENDIAN != hdr.common.tiff_magic
#endif
- ) {
- Fatal("Not a TIFF or MDI file, bad magic number %u (%#x)",
- hdr.common.tiff_magic, hdr.common.tiff_magic);
- }
- if (hdr.common.tiff_magic == TIFF_BIGENDIAN
- || hdr.common.tiff_magic == MDI_BIGENDIAN)
- swabflag = !bigendian;
- else
- swabflag = bigendian;
- if (swabflag)
- TIFFSwabShort(&hdr.common.tiff_version);
- if (hdr.common.tiff_version==42)
- {
- if (read(fd, ((char*) &hdr.classic) + offsetof(TIFFHeaderClassic, tiff_diroff), 4) != 4)
- ReadError("TIFF header");
- if (swabflag)
- TIFFSwabLong(&hdr.classic.tiff_diroff);
- printf("Magic: %#x <%s-endian> Version: %#x <%s>\n",
- hdr.classic.tiff_magic,
- hdr.classic.tiff_magic == TIFF_BIGENDIAN ? "big" : "little",
- 42,"ClassicTIFF");
- if (diroff == 0)
- diroff = hdr.classic.tiff_diroff;
- }
- else if (hdr.common.tiff_version==43)
- {
- if (read(fd, ((char*) &hdr.big) + offsetof(TIFFHeaderBig, tiff_offsetsize), 12) != 12)
- ReadError("TIFF header");
- if (swabflag)
- {
- TIFFSwabShort(&hdr.big.tiff_offsetsize);
- TIFFSwabShort(&hdr.big.tiff_unused);
- TIFFSwabLong8(&hdr.big.tiff_diroff);
- }
- printf("Magic: %#x <%s-endian> Version: %#x <%s>\n",
- hdr.big.tiff_magic,
- hdr.big.tiff_magic == TIFF_BIGENDIAN ? "big" : "little",
- 43,"BigTIFF");
- printf("OffsetSize: %#x Unused: %#x\n",
- hdr.big.tiff_offsetsize,hdr.big.tiff_unused);
- if (diroff == 0)
- diroff = hdr.big.tiff_diroff;
- bigtiff = 1;
- }
- else
- Fatal("Not a TIFF file, bad version number %u (%#x)",
- hdr.common.tiff_version, hdr.common.tiff_version);
- for (i = 0; diroff != 0; i++) {
- for(j=0; j<count_visited_dir; j++)
- {
- if( visited_diroff[j] == diroff )
- {
- free(visited_diroff);
- Fatal("Cycle detected in chaining of TIFF directories!");
- }
- }
- {
- size_t alloc_size;
- alloc_size=TIFFSafeMultiply(tmsize_t,(count_visited_dir + 1),
- sizeof(uint64_t));
- if (alloc_size == 0)
- {
- if (visited_diroff)
- free(visited_diroff);
- visited_diroff = 0;
- }
- else
- {
- visited_diroff = (uint64_t*) realloc(visited_diroff, alloc_size);
- }
- }
- if( !visited_diroff )
- Fatal("Out of memory");
- visited_diroff[count_visited_dir] = diroff;
- count_visited_dir ++;
-
- if (i > 0)
- putchar('\n');
- diroff = ReadDirectory(fd, i, diroff);
- }
- if( visited_diroff )
- free(visited_diroff);
+ )
+ {
+ Fatal("Not a TIFF or MDI file, bad magic number %u (%#x)",
+ hdr.common.tiff_magic, hdr.common.tiff_magic);
+ }
+ if (hdr.common.tiff_magic == TIFF_BIGENDIAN ||
+ hdr.common.tiff_magic == MDI_BIGENDIAN)
+ swabflag = !bigendian;
+ else
+ swabflag = bigendian;
+ if (swabflag)
+ TIFFSwabShort(&hdr.common.tiff_version);
+ if (hdr.common.tiff_version == 42)
+ {
+ if (read(fd,
+ ((char *)&hdr.classic) +
+ offsetof(TIFFHeaderClassic, tiff_diroff),
+ 4) != 4)
+ ReadError("TIFF header");
+ if (swabflag)
+ TIFFSwabLong(&hdr.classic.tiff_diroff);
+ printf("Magic: %#x <%s-endian> Version: %#x <%s>\n",
+ hdr.classic.tiff_magic,
+ hdr.classic.tiff_magic == TIFF_BIGENDIAN ? "big" : "little", 42,
+ "ClassicTIFF");
+ if (diroff == 0)
+ diroff = hdr.classic.tiff_diroff;
+ }
+ else if (hdr.common.tiff_version == 43)
+ {
+ if (read(fd,
+ ((char *)&hdr.big) + offsetof(TIFFHeaderBig, tiff_offsetsize),
+ 12) != 12)
+ ReadError("TIFF header");
+ if (swabflag)
+ {
+ TIFFSwabShort(&hdr.big.tiff_offsetsize);
+ TIFFSwabShort(&hdr.big.tiff_unused);
+ TIFFSwabLong8(&hdr.big.tiff_diroff);
+ }
+ printf("Magic: %#x <%s-endian> Version: %#x <%s>\n", hdr.big.tiff_magic,
+ hdr.big.tiff_magic == TIFF_BIGENDIAN ? "big" : "little", 43,
+ "BigTIFF");
+ printf("OffsetSize: %#x Unused: %#x\n", hdr.big.tiff_offsetsize,
+ hdr.big.tiff_unused);
+ if (diroff == 0)
+ diroff = hdr.big.tiff_diroff;
+ bigtiff = 1;
+ }
+ else
+ Fatal("Not a TIFF file, bad version number %u (%#x)",
+ hdr.common.tiff_version, hdr.common.tiff_version);
+ for (i = 0; diroff != 0; i++)
+ {
+ for (j = 0; j < count_visited_dir; j++)
+ {
+ if (visited_diroff[j] == diroff)
+ {
+ free(visited_diroff);
+ Fatal("Cycle detected in chaining of TIFF directories!");
+ }
+ }
+ {
+ size_t alloc_size;
+ alloc_size = TIFFSafeMultiply(tmsize_t, (count_visited_dir + 1),
+ sizeof(uint64_t));
+ if (alloc_size == 0)
+ {
+ if (visited_diroff)
+ free(visited_diroff);
+ visited_diroff = 0;
+ }
+ else
+ {
+ visited_diroff =
+ (uint64_t *)realloc(visited_diroff, alloc_size);
+ }
+ }
+ if (!visited_diroff)
+ Fatal("Out of memory");
+ visited_diroff[count_visited_dir] = diroff;
+ count_visited_dir++;
+
+ if (i > 0)
+ putchar('\n');
+ diroff = ReadDirectory(fd, i, diroff);
+ }
+ if (visited_diroff)
+ free(visited_diroff);
}
static const int datawidth[] = {
- 0, /* 00 = undefined */
- 1, /* 01 = TIFF_BYTE */
- 1, /* 02 = TIFF_ASCII */
- 2, /* 03 = TIFF_SHORT */
- 4, /* 04 = TIFF_LONG */
- 8, /* 05 = TIFF_RATIONAL */
- 1, /* 06 = TIFF_SBYTE */
- 1, /* 07 = TIFF_UNDEFINED */
- 2, /* 08 = TIFF_SSHORT */
- 4, /* 09 = TIFF_SLONG */
- 8, /* 10 = TIFF_SRATIONAL */
- 4, /* 11 = TIFF_FLOAT */
- 8, /* 12 = TIFF_DOUBLE */
- 4, /* 13 = TIFF_IFD */
- 0, /* 14 = undefined */
- 0, /* 15 = undefined */
- 8, /* 16 = TIFF_LONG8 */
- 8, /* 17 = TIFF_SLONG8 */
- 8, /* 18 = TIFF_IFD8 */
+ 0, /* 00 = undefined */
+ 1, /* 01 = TIFF_BYTE */
+ 1, /* 02 = TIFF_ASCII */
+ 2, /* 03 = TIFF_SHORT */
+ 4, /* 04 = TIFF_LONG */
+ 8, /* 05 = TIFF_RATIONAL */
+ 1, /* 06 = TIFF_SBYTE */
+ 1, /* 07 = TIFF_UNDEFINED */
+ 2, /* 08 = TIFF_SSHORT */
+ 4, /* 09 = TIFF_SLONG */
+ 8, /* 10 = TIFF_SRATIONAL */
+ 4, /* 11 = TIFF_FLOAT */
+ 8, /* 12 = TIFF_DOUBLE */
+ 4, /* 13 = TIFF_IFD */
+ 0, /* 14 = undefined */
+ 0, /* 15 = undefined */
+ 8, /* 16 = TIFF_LONG8 */
+ 8, /* 17 = TIFF_SLONG8 */
+ 8, /* 18 = TIFF_IFD8 */
};
-#define NWIDTHS (sizeof (datawidth) / sizeof (datawidth[0]))
-static void PrintTag(FILE*, uint16_t);
-static void PrintType(FILE*, uint16_t);
-static void PrintData(FILE*, uint16_t, uint32_t, unsigned char*);
+#define NWIDTHS (sizeof(datawidth) / sizeof(datawidth[0]))
+static void PrintTag(FILE *, uint16_t);
+static void PrintType(FILE *, uint16_t);
+static void PrintData(FILE *, uint16_t, uint32_t, unsigned char *);
/*
* Read the next TIFF directory from a file
* and convert it to the internal format.
* We read directories sequentially.
*/
-static uint64_t
-ReadDirectory(int fd, unsigned int ix, uint64_t off)
+static uint64_t ReadDirectory(int fd, unsigned int ix, uint64_t off)
{
- uint16_t dircount;
- uint32_t direntrysize;
- void* dirmem = NULL;
- uint64_t nextdiroff = 0;
- uint32_t n;
- uint8_t* dp;
-
- if (off == 0) /* no more directories */
- goto done;
- if (_TIFF_lseek_f(fd, (_TIFF_off_t)off, SEEK_SET) != (_TIFF_off_t)off) {
- Fatal("Seek error accessing TIFF directory");
- goto done;
- }
- if (!bigtiff) {
- if (read(fd, (char*) &dircount, sizeof (uint16_t)) != sizeof (uint16_t)) {
- ReadError("directory count");
- goto done;
- }
- if (swabflag)
- TIFFSwabShort(&dircount);
- direntrysize = 12;
- } else {
- uint64_t dircount64 = 0;
- if (read(fd, (char*) &dircount64, sizeof (uint64_t)) != sizeof (uint64_t)) {
- ReadError("directory count");
- goto done;
- }
- if (swabflag)
- TIFFSwabLong8(&dircount64);
- if (dircount64>0xFFFF) {
- Error("Sanity check on directory count failed");
- goto done;
- }
- dircount = (uint16_t)dircount64;
- direntrysize = 20;
- }
- dirmem = _TIFFmalloc(TIFFSafeMultiply(tmsize_t,dircount,direntrysize));
- if (dirmem == NULL) {
- Fatal("No space for TIFF directory");
- goto done;
- }
- n = read(fd, (char*) dirmem, dircount*direntrysize);
- if (n != dircount*direntrysize) {
- n /= direntrysize;
- Error(
- "Could only read %" PRIu32 " of %" PRIu16 " entries in directory at offset %#" PRIu64,
- n, dircount, off);
- dircount = n;
- nextdiroff = 0;
- } else {
- if (!bigtiff) {
- uint32_t nextdiroff32;
- if (read(fd, (char*) &nextdiroff32, sizeof (uint32_t)) != sizeof (uint32_t))
- nextdiroff32 = 0;
- if (swabflag)
- TIFFSwabLong(&nextdiroff32);
- nextdiroff = nextdiroff32;
- } else {
- if (read(fd, (char*) &nextdiroff, sizeof (uint64_t)) != sizeof (uint64_t))
- nextdiroff = 0;
- if (swabflag)
- TIFFSwabLong8(&nextdiroff);
- }
- }
- printf("Directory %u: offset %" PRIu64 " (%#" PRIx64 ") next %" PRIu64 " (%#" PRIx64 ")\n",
- ix, off, off, nextdiroff, nextdiroff);
- for (dp = (uint8_t*)dirmem, n = dircount; n > 0; n--) {
- uint16_t tag;
- uint16_t type;
- uint16_t typewidth;
- uint64_t count;
- uint64_t datasize;
- int datafits;
- void* datamem;
- uint64_t dataoffset;
- int datatruncated;
- int datasizeoverflow;
-
- tag = *(uint16_t*)dp;
- if (swabflag)
- TIFFSwabShort(&tag);
- dp += sizeof(uint16_t);
- type = *(uint16_t*)dp;
- dp += sizeof(uint16_t);
- if (swabflag)
- TIFFSwabShort(&type);
- PrintTag(stdout, tag);
- putchar(' ');
- PrintType(stdout, type);
- putchar(' ');
- if (!bigtiff)
- {
- uint32_t count32;
- count32 = *(uint32_t*)dp;
- if (swabflag)
- TIFFSwabLong(&count32);
- dp += sizeof(uint32_t);
- count = count32;
- }
- else
- {
- memcpy(&count, dp, sizeof(uint64_t));
- if (swabflag)
- TIFFSwabLong8(&count);
- dp += sizeof(uint64_t);
- }
- printf("%" PRIu64 "<", count);
- if (type >= NWIDTHS)
- typewidth = 0;
- else
- typewidth = datawidth[type];
- datasize = TIFFSafeMultiply(tmsize_t,count,typewidth);
- datasizeoverflow = (typewidth > 0 && datasize / typewidth != count);
- datafits = 1;
- datamem = dp;
- dataoffset = 0;
- datatruncated = 0;
- if (!bigtiff)
- {
- if (datasizeoverflow || datasize>4)
- {
- uint32_t dataoffset32;
- datafits = 0;
- datamem = NULL;
- dataoffset32 = *(uint32_t*)dp;
- if (swabflag)
- TIFFSwabLong(&dataoffset32);
- dataoffset = dataoffset32;
- }
- dp += sizeof(uint32_t);
- }
- else
- {
- if (datasizeoverflow || datasize>8)
- {
- datafits = 0;
- datamem = NULL;
- memcpy(&dataoffset, dp, sizeof(uint64_t));
- if (swabflag)
- TIFFSwabLong8(&dataoffset);
- }
- dp += sizeof(uint64_t);
- }
- if (datasizeoverflow || datasize>0x10000)
- {
- datatruncated = 1;
- count = 0x10000/typewidth;
- datasize = TIFFSafeMultiply(tmsize_t,count,typewidth);
- }
- if (count>maxitems)
- {
- datatruncated = 1;
- count = maxitems;
- datasize = TIFFSafeMultiply(tmsize_t,count,typewidth);
- }
- if (!datafits)
- {
- datamem = _TIFFmalloc(datasize);
- if (datamem) {
- if (_TIFF_lseek_f(fd, (_TIFF_off_t)dataoffset, 0) !=
- (_TIFF_off_t)dataoffset)
- {
- Error(
- "Seek error accessing tag %u value", tag);
- _TIFFfree(datamem);
- datamem = NULL;
- }
- else if (read(fd, datamem, (size_t)datasize) != (tmsize_t)datasize)
- {
- Error(
- "Read error accessing tag %u value", tag);
- _TIFFfree(datamem);
- datamem = NULL;
- }
- } else
- Error("No space for data for tag %u",tag);
- }
- if (datamem)
- {
- if (swabflag)
- {
- switch (type)
- {
- case TIFF_BYTE:
- case TIFF_ASCII:
- case TIFF_SBYTE:
- case TIFF_UNDEFINED:
- break;
- case TIFF_SHORT:
- case TIFF_SSHORT:
- TIFFSwabArrayOfShort((uint16_t*)datamem, (tmsize_t)count);
- break;
- case TIFF_LONG:
- case TIFF_SLONG:
- case TIFF_FLOAT:
- case TIFF_IFD:
- TIFFSwabArrayOfLong((uint32_t*)datamem, (tmsize_t)count);
- break;
- case TIFF_RATIONAL:
- case TIFF_SRATIONAL:
- TIFFSwabArrayOfLong((uint32_t*)datamem, (tmsize_t)count * 2);
- break;
- case TIFF_DOUBLE:
- case TIFF_LONG8:
- case TIFF_SLONG8:
- case TIFF_IFD8:
- TIFFSwabArrayOfLong8((uint64_t*)datamem, (tmsize_t)count);
- break;
- }
- }
- PrintData(stdout, type, (uint32_t)count, datamem);
- if (datatruncated)
- printf(" ...");
- if (!datafits)
- {
- _TIFFfree(datamem);
- datamem = NULL;
- }
- }
- printf(">\n");
- }
+ uint16_t dircount;
+ uint32_t direntrysize;
+ void *dirmem = NULL;
+ uint64_t nextdiroff = 0;
+ uint32_t n;
+ uint8_t *dp;
+
+ if (off == 0) /* no more directories */
+ goto done;
+ if (_TIFF_lseek_f(fd, (_TIFF_off_t)off, SEEK_SET) != (_TIFF_off_t)off)
+ {
+ Fatal("Seek error accessing TIFF directory");
+ goto done;
+ }
+ if (!bigtiff)
+ {
+ if (read(fd, (char *)&dircount, sizeof(uint16_t)) != sizeof(uint16_t))
+ {
+ ReadError("directory count");
+ goto done;
+ }
+ if (swabflag)
+ TIFFSwabShort(&dircount);
+ direntrysize = 12;
+ }
+ else
+ {
+ uint64_t dircount64 = 0;
+ if (read(fd, (char *)&dircount64, sizeof(uint64_t)) != sizeof(uint64_t))
+ {
+ ReadError("directory count");
+ goto done;
+ }
+ if (swabflag)
+ TIFFSwabLong8(&dircount64);
+ if (dircount64 > 0xFFFF)
+ {
+ Error("Sanity check on directory count failed");
+ goto done;
+ }
+ dircount = (uint16_t)dircount64;
+ direntrysize = 20;
+ }
+ dirmem = _TIFFmalloc(TIFFSafeMultiply(tmsize_t, dircount, direntrysize));
+ if (dirmem == NULL)
+ {
+ Fatal("No space for TIFF directory");
+ goto done;
+ }
+ n = read(fd, (char *)dirmem, dircount * direntrysize);
+ if (n != dircount * direntrysize)
+ {
+ n /= direntrysize;
+ Error("Could only read %" PRIu32 " of %" PRIu16
+ " entries in directory at offset %#" PRIu64,
+ n, dircount, off);
+ dircount = n;
+ nextdiroff = 0;
+ }
+ else
+ {
+ if (!bigtiff)
+ {
+ uint32_t nextdiroff32;
+ if (read(fd, (char *)&nextdiroff32, sizeof(uint32_t)) !=
+ sizeof(uint32_t))
+ nextdiroff32 = 0;
+ if (swabflag)
+ TIFFSwabLong(&nextdiroff32);
+ nextdiroff = nextdiroff32;
+ }
+ else
+ {
+ if (read(fd, (char *)&nextdiroff, sizeof(uint64_t)) !=
+ sizeof(uint64_t))
+ nextdiroff = 0;
+ if (swabflag)
+ TIFFSwabLong8(&nextdiroff);
+ }
+ }
+ printf("Directory %u: offset %" PRIu64 " (%#" PRIx64 ") next %" PRIu64
+ " (%#" PRIx64 ")\n",
+ ix, off, off, nextdiroff, nextdiroff);
+ for (dp = (uint8_t *)dirmem, n = dircount; n > 0; n--)
+ {
+ uint16_t tag;
+ uint16_t type;
+ uint16_t typewidth;
+ uint64_t count;
+ uint64_t datasize;
+ int datafits;
+ void *datamem;
+ uint64_t dataoffset;
+ int datatruncated;
+ int datasizeoverflow;
+
+ tag = *(uint16_t *)dp;
+ if (swabflag)
+ TIFFSwabShort(&tag);
+ dp += sizeof(uint16_t);
+ type = *(uint16_t *)dp;
+ dp += sizeof(uint16_t);
+ if (swabflag)
+ TIFFSwabShort(&type);
+ PrintTag(stdout, tag);
+ putchar(' ');
+ PrintType(stdout, type);
+ putchar(' ');
+ if (!bigtiff)
+ {
+ uint32_t count32;
+ count32 = *(uint32_t *)dp;
+ if (swabflag)
+ TIFFSwabLong(&count32);
+ dp += sizeof(uint32_t);
+ count = count32;
+ }
+ else
+ {
+ memcpy(&count, dp, sizeof(uint64_t));
+ if (swabflag)
+ TIFFSwabLong8(&count);
+ dp += sizeof(uint64_t);
+ }
+ printf("%" PRIu64 "<", count);
+ if (type >= NWIDTHS)
+ typewidth = 0;
+ else
+ typewidth = datawidth[type];
+ datasize = TIFFSafeMultiply(tmsize_t, count, typewidth);
+ datasizeoverflow = (typewidth > 0 && datasize / typewidth != count);
+ datafits = 1;
+ datamem = dp;
+ dataoffset = 0;
+ datatruncated = 0;
+ if (!bigtiff)
+ {
+ if (datasizeoverflow || datasize > 4)
+ {
+ uint32_t dataoffset32;
+ datafits = 0;
+ datamem = NULL;
+ dataoffset32 = *(uint32_t *)dp;
+ if (swabflag)
+ TIFFSwabLong(&dataoffset32);
+ dataoffset = dataoffset32;
+ }
+ dp += sizeof(uint32_t);
+ }
+ else
+ {
+ if (datasizeoverflow || datasize > 8)
+ {
+ datafits = 0;
+ datamem = NULL;
+ memcpy(&dataoffset, dp, sizeof(uint64_t));
+ if (swabflag)
+ TIFFSwabLong8(&dataoffset);
+ }
+ dp += sizeof(uint64_t);
+ }
+ if (datasizeoverflow || datasize > 0x10000)
+ {
+ datatruncated = 1;
+ count = 0x10000 / typewidth;
+ datasize = TIFFSafeMultiply(tmsize_t, count, typewidth);
+ }
+ if (count > maxitems)
+ {
+ datatruncated = 1;
+ count = maxitems;
+ datasize = TIFFSafeMultiply(tmsize_t, count, typewidth);
+ }
+ if (!datafits)
+ {
+ datamem = _TIFFmalloc(datasize);
+ if (datamem)
+ {
+ if (_TIFF_lseek_f(fd, (_TIFF_off_t)dataoffset, 0) !=
+ (_TIFF_off_t)dataoffset)
+ {
+ Error("Seek error accessing tag %u value", tag);
+ _TIFFfree(datamem);
+ datamem = NULL;
+ }
+ else if (read(fd, datamem, (size_t)datasize) !=
+ (tmsize_t)datasize)
+ {
+ Error("Read error accessing tag %u value", tag);
+ _TIFFfree(datamem);
+ datamem = NULL;
+ }
+ }
+ else
+ Error("No space for data for tag %u", tag);
+ }
+ if (datamem)
+ {
+ if (swabflag)
+ {
+ switch (type)
+ {
+ case TIFF_BYTE:
+ case TIFF_ASCII:
+ case TIFF_SBYTE:
+ case TIFF_UNDEFINED:
+ break;
+ case TIFF_SHORT:
+ case TIFF_SSHORT:
+ TIFFSwabArrayOfShort((uint16_t *)datamem,
+ (tmsize_t)count);
+ break;
+ case TIFF_LONG:
+ case TIFF_SLONG:
+ case TIFF_FLOAT:
+ case TIFF_IFD:
+ TIFFSwabArrayOfLong((uint32_t *)datamem,
+ (tmsize_t)count);
+ break;
+ case TIFF_RATIONAL:
+ case TIFF_SRATIONAL:
+ TIFFSwabArrayOfLong((uint32_t *)datamem,
+ (tmsize_t)count * 2);
+ break;
+ case TIFF_DOUBLE:
+ case TIFF_LONG8:
+ case TIFF_SLONG8:
+ case TIFF_IFD8:
+ TIFFSwabArrayOfLong8((uint64_t *)datamem,
+ (tmsize_t)count);
+ break;
+ }
+ }
+ PrintData(stdout, type, (uint32_t)count, datamem);
+ if (datatruncated)
+ printf(" ...");
+ if (!datafits)
+ {
+ _TIFFfree(datamem);
+ datamem = NULL;
+ }
+ }
+ printf(">\n");
+ }
done:
- if (dirmem)
- _TIFFfree((char *)dirmem);
- return (nextdiroff);
+ if (dirmem)
+ _TIFFfree((char *)dirmem);
+ return (nextdiroff);
}
-static const struct tagname {
- uint16_t tag;
- const char* name;
+static const struct tagname
+{
+ uint16_t tag;
+ const char *name;
} tagnames[] = {
- { TIFFTAG_SUBFILETYPE, "SubFileType" },
- { TIFFTAG_OSUBFILETYPE, "OldSubFileType" },
- { TIFFTAG_IMAGEWIDTH, "ImageWidth" },
- { TIFFTAG_IMAGELENGTH, "ImageLength" },
- { TIFFTAG_BITSPERSAMPLE, "BitsPerSample" },
- { TIFFTAG_COMPRESSION, "Compression" },
- { TIFFTAG_PHOTOMETRIC, "Photometric" },
- { TIFFTAG_THRESHHOLDING, "Threshholding" },
- { TIFFTAG_CELLWIDTH, "CellWidth" },
- { TIFFTAG_CELLLENGTH, "CellLength" },
- { TIFFTAG_FILLORDER, "FillOrder" },
- { TIFFTAG_DOCUMENTNAME, "DocumentName" },
- { TIFFTAG_IMAGEDESCRIPTION, "ImageDescription" },
- { TIFFTAG_MAKE, "Make" },
- { TIFFTAG_MODEL, "Model" },
- { TIFFTAG_STRIPOFFSETS, "StripOffsets" },
- { TIFFTAG_ORIENTATION, "Orientation" },
- { TIFFTAG_SAMPLESPERPIXEL, "SamplesPerPixel" },
- { TIFFTAG_ROWSPERSTRIP, "RowsPerStrip" },
- { TIFFTAG_STRIPBYTECOUNTS, "StripByteCounts" },
- { TIFFTAG_MINSAMPLEVALUE, "MinSampleValue" },
- { TIFFTAG_MAXSAMPLEVALUE, "MaxSampleValue" },
- { TIFFTAG_XRESOLUTION, "XResolution" },
- { TIFFTAG_YRESOLUTION, "YResolution" },
- { TIFFTAG_PLANARCONFIG, "PlanarConfig" },
- { TIFFTAG_PAGENAME, "PageName" },
- { TIFFTAG_XPOSITION, "XPosition" },
- { TIFFTAG_YPOSITION, "YPosition" },
- { TIFFTAG_FREEOFFSETS, "FreeOffsets" },
- { TIFFTAG_FREEBYTECOUNTS, "FreeByteCounts" },
- { TIFFTAG_GRAYRESPONSEUNIT, "GrayResponseUnit" },
- { TIFFTAG_GRAYRESPONSECURVE,"GrayResponseCurve" },
- { TIFFTAG_GROUP3OPTIONS, "Group3Options" },
- { TIFFTAG_GROUP4OPTIONS, "Group4Options" },
- { TIFFTAG_RESOLUTIONUNIT, "ResolutionUnit" },
- { TIFFTAG_PAGENUMBER, "PageNumber" },
- { TIFFTAG_COLORRESPONSEUNIT,"ColorResponseUnit" },
- { TIFFTAG_TRANSFERFUNCTION, "TransferFunction" },
- { TIFFTAG_SOFTWARE, "Software" },
- { TIFFTAG_DATETIME, "DateTime" },
- { TIFFTAG_ARTIST, "Artist" },
- { TIFFTAG_HOSTCOMPUTER, "HostComputer" },
- { TIFFTAG_PREDICTOR, "Predictor" },
- { TIFFTAG_WHITEPOINT, "Whitepoint" },
- { TIFFTAG_PRIMARYCHROMATICITIES,"PrimaryChromaticities" },
- { TIFFTAG_COLORMAP, "Colormap" },
- { TIFFTAG_HALFTONEHINTS, "HalftoneHints" },
- { TIFFTAG_TILEWIDTH, "TileWidth" },
- { TIFFTAG_TILELENGTH, "TileLength" },
- { TIFFTAG_TILEOFFSETS, "TileOffsets" },
- { TIFFTAG_TILEBYTECOUNTS, "TileByteCounts" },
- { TIFFTAG_BADFAXLINES, "BadFaxLines" },
- { TIFFTAG_CLEANFAXDATA, "CleanFaxData" },
- { TIFFTAG_CONSECUTIVEBADFAXLINES, "ConsecutiveBadFaxLines" },
- { TIFFTAG_SUBIFD, "SubIFD" },
- { TIFFTAG_INKSET, "InkSet" },
- { TIFFTAG_INKNAMES, "InkNames" },
- { TIFFTAG_NUMBEROFINKS, "NumberOfInks" },
- { TIFFTAG_DOTRANGE, "DotRange" },
- { TIFFTAG_TARGETPRINTER, "TargetPrinter" },
- { TIFFTAG_EXTRASAMPLES, "ExtraSamples" },
- { TIFFTAG_SAMPLEFORMAT, "SampleFormat" },
- { TIFFTAG_SMINSAMPLEVALUE, "SMinSampleValue" },
- { TIFFTAG_SMAXSAMPLEVALUE, "SMaxSampleValue" },
- { TIFFTAG_JPEGPROC, "JPEGProcessingMode" },
- { TIFFTAG_JPEGIFOFFSET, "JPEGInterchangeFormat" },
- { TIFFTAG_JPEGIFBYTECOUNT, "JPEGInterchangeFormatLength" },
- { TIFFTAG_JPEGRESTARTINTERVAL,"JPEGRestartInterval" },
- { TIFFTAG_JPEGLOSSLESSPREDICTORS,"JPEGLosslessPredictors" },
- { TIFFTAG_JPEGPOINTTRANSFORM,"JPEGPointTransform" },
- { TIFFTAG_JPEGTABLES, "JPEGTables" },
- { TIFFTAG_JPEGQTABLES, "JPEGQTables" },
- { TIFFTAG_JPEGDCTABLES, "JPEGDCTables" },
- { TIFFTAG_JPEGACTABLES, "JPEGACTables" },
- { TIFFTAG_YCBCRCOEFFICIENTS,"YCbCrCoefficients" },
- { TIFFTAG_YCBCRSUBSAMPLING, "YCbCrSubsampling" },
- { TIFFTAG_YCBCRPOSITIONING, "YCbCrPositioning" },
- { TIFFTAG_REFERENCEBLACKWHITE, "ReferenceBlackWhite" },
- { TIFFTAG_REFPTS, "IgReferencePoints (Island Graphics)" },
- { TIFFTAG_REGIONTACKPOINT, "IgRegionTackPoint (Island Graphics)" },
- { TIFFTAG_REGIONWARPCORNERS,"IgRegionWarpCorners (Island Graphics)" },
- { TIFFTAG_REGIONAFFINE, "IgRegionAffine (Island Graphics)" },
- { TIFFTAG_MATTEING, "OBSOLETE Matteing (Silicon Graphics)" },
- { TIFFTAG_DATATYPE, "OBSOLETE DataType (Silicon Graphics)" },
- { TIFFTAG_IMAGEDEPTH, "ImageDepth (Silicon Graphics)" },
- { TIFFTAG_TILEDEPTH, "TileDepth (Silicon Graphics)" },
- { 32768, "OLD BOGUS Matteing tag" },
- { TIFFTAG_COPYRIGHT, "Copyright" },
- { TIFFTAG_ICCPROFILE, "ICC Profile" },
- { TIFFTAG_JBIGOPTIONS, "JBIG Options" },
- { TIFFTAG_STONITS, "StoNits" },
- { TIFFTAG_GDAL_METADATA, "GDALMetadata" },
- { TIFFTAG_GDAL_NODATA, "GDALNoDataValue" },
+ {TIFFTAG_SUBFILETYPE, "SubFileType"},
+ {TIFFTAG_OSUBFILETYPE, "OldSubFileType"},
+ {TIFFTAG_IMAGEWIDTH, "ImageWidth"},
+ {TIFFTAG_IMAGELENGTH, "ImageLength"},
+ {TIFFTAG_BITSPERSAMPLE, "BitsPerSample"},
+ {TIFFTAG_COMPRESSION, "Compression"},
+ {TIFFTAG_PHOTOMETRIC, "Photometric"},
+ {TIFFTAG_THRESHHOLDING, "Threshholding"},
+ {TIFFTAG_CELLWIDTH, "CellWidth"},
+ {TIFFTAG_CELLLENGTH, "CellLength"},
+ {TIFFTAG_FILLORDER, "FillOrder"},
+ {TIFFTAG_DOCUMENTNAME, "DocumentName"},
+ {TIFFTAG_IMAGEDESCRIPTION, "ImageDescription"},
+ {TIFFTAG_MAKE, "Make"},
+ {TIFFTAG_MODEL, "Model"},
+ {TIFFTAG_STRIPOFFSETS, "StripOffsets"},
+ {TIFFTAG_ORIENTATION, "Orientation"},
+ {TIFFTAG_SAMPLESPERPIXEL, "SamplesPerPixel"},
+ {TIFFTAG_ROWSPERSTRIP, "RowsPerStrip"},
+ {TIFFTAG_STRIPBYTECOUNTS, "StripByteCounts"},
+ {TIFFTAG_MINSAMPLEVALUE, "MinSampleValue"},
+ {TIFFTAG_MAXSAMPLEVALUE, "MaxSampleValue"},
+ {TIFFTAG_XRESOLUTION, "XResolution"},
+ {TIFFTAG_YRESOLUTION, "YResolution"},
+ {TIFFTAG_PLANARCONFIG, "PlanarConfig"},
+ {TIFFTAG_PAGENAME, "PageName"},
+ {TIFFTAG_XPOSITION, "XPosition"},
+ {TIFFTAG_YPOSITION, "YPosition"},
+ {TIFFTAG_FREEOFFSETS, "FreeOffsets"},
+ {TIFFTAG_FREEBYTECOUNTS, "FreeByteCounts"},
+ {TIFFTAG_GRAYRESPONSEUNIT, "GrayResponseUnit"},
+ {TIFFTAG_GRAYRESPONSECURVE, "GrayResponseCurve"},
+ {TIFFTAG_GROUP3OPTIONS, "Group3Options"},
+ {TIFFTAG_GROUP4OPTIONS, "Group4Options"},
+ {TIFFTAG_RESOLUTIONUNIT, "ResolutionUnit"},
+ {TIFFTAG_PAGENUMBER, "PageNumber"},
+ {TIFFTAG_COLORRESPONSEUNIT, "ColorResponseUnit"},
+ {TIFFTAG_TRANSFERFUNCTION, "TransferFunction"},
+ {TIFFTAG_SOFTWARE, "Software"},
+ {TIFFTAG_DATETIME, "DateTime"},
+ {TIFFTAG_ARTIST, "Artist"},
+ {TIFFTAG_HOSTCOMPUTER, "HostComputer"},
+ {TIFFTAG_PREDICTOR, "Predictor"},
+ {TIFFTAG_WHITEPOINT, "Whitepoint"},
+ {TIFFTAG_PRIMARYCHROMATICITIES, "PrimaryChromaticities"},
+ {TIFFTAG_COLORMAP, "Colormap"},
+ {TIFFTAG_HALFTONEHINTS, "HalftoneHints"},
+ {TIFFTAG_TILEWIDTH, "TileWidth"},
+ {TIFFTAG_TILELENGTH, "TileLength"},
+ {TIFFTAG_TILEOFFSETS, "TileOffsets"},
+ {TIFFTAG_TILEBYTECOUNTS, "TileByteCounts"},
+ {TIFFTAG_BADFAXLINES, "BadFaxLines"},
+ {TIFFTAG_CLEANFAXDATA, "CleanFaxData"},
+ {TIFFTAG_CONSECUTIVEBADFAXLINES, "ConsecutiveBadFaxLines"},
+ {TIFFTAG_SUBIFD, "SubIFD"},
+ {TIFFTAG_INKSET, "InkSet"},
+ {TIFFTAG_INKNAMES, "InkNames"},
+ {TIFFTAG_NUMBEROFINKS, "NumberOfInks"},
+ {TIFFTAG_DOTRANGE, "DotRange"},
+ {TIFFTAG_TARGETPRINTER, "TargetPrinter"},
+ {TIFFTAG_EXTRASAMPLES, "ExtraSamples"},
+ {TIFFTAG_SAMPLEFORMAT, "SampleFormat"},
+ {TIFFTAG_SMINSAMPLEVALUE, "SMinSampleValue"},
+ {TIFFTAG_SMAXSAMPLEVALUE, "SMaxSampleValue"},
+ {TIFFTAG_JPEGPROC, "JPEGProcessingMode"},
+ {TIFFTAG_JPEGIFOFFSET, "JPEGInterchangeFormat"},
+ {TIFFTAG_JPEGIFBYTECOUNT, "JPEGInterchangeFormatLength"},
+ {TIFFTAG_JPEGRESTARTINTERVAL, "JPEGRestartInterval"},
+ {TIFFTAG_JPEGLOSSLESSPREDICTORS, "JPEGLosslessPredictors"},
+ {TIFFTAG_JPEGPOINTTRANSFORM, "JPEGPointTransform"},
+ {TIFFTAG_JPEGTABLES, "JPEGTables"},
+ {TIFFTAG_JPEGQTABLES, "JPEGQTables"},
+ {TIFFTAG_JPEGDCTABLES, "JPEGDCTables"},
+ {TIFFTAG_JPEGACTABLES, "JPEGACTables"},
+ {TIFFTAG_YCBCRCOEFFICIENTS, "YCbCrCoefficients"},
+ {TIFFTAG_YCBCRSUBSAMPLING, "YCbCrSubsampling"},
+ {TIFFTAG_YCBCRPOSITIONING, "YCbCrPositioning"},
+ {TIFFTAG_REFERENCEBLACKWHITE, "ReferenceBlackWhite"},
+ {TIFFTAG_REFPTS, "IgReferencePoints (Island Graphics)"},
+ {TIFFTAG_REGIONTACKPOINT, "IgRegionTackPoint (Island Graphics)"},
+ {TIFFTAG_REGIONWARPCORNERS, "IgRegionWarpCorners (Island Graphics)"},
+ {TIFFTAG_REGIONAFFINE, "IgRegionAffine (Island Graphics)"},
+ {TIFFTAG_MATTEING, "OBSOLETE Matteing (Silicon Graphics)"},
+ {TIFFTAG_DATATYPE, "OBSOLETE DataType (Silicon Graphics)"},
+ {TIFFTAG_IMAGEDEPTH, "ImageDepth (Silicon Graphics)"},
+ {TIFFTAG_TILEDEPTH, "TileDepth (Silicon Graphics)"},
+ {32768, "OLD BOGUS Matteing tag"},
+ {TIFFTAG_COPYRIGHT, "Copyright"},
+ {TIFFTAG_ICCPROFILE, "ICC Profile"},
+ {TIFFTAG_JBIGOPTIONS, "JBIG Options"},
+ {TIFFTAG_STONITS, "StoNits"},
+ {TIFFTAG_GDAL_METADATA, "GDALMetadata"},
+ {TIFFTAG_GDAL_NODATA, "GDALNoDataValue"},
};
-#define NTAGS (sizeof (tagnames) / sizeof (tagnames[0]))
+#define NTAGS (sizeof(tagnames) / sizeof(tagnames[0]))
-static void
-PrintTag(FILE* fd, uint16_t tag)
+static void PrintTag(FILE *fd, uint16_t tag)
{
- const struct tagname *tp;
-
- for (tp = tagnames; tp < &tagnames[NTAGS]; tp++)
- if (tp->tag == tag) {
- fprintf(fd, "%s (%u)", tp->name, tag);
- return;
- }
- fprintf(fd, "%u (%#x)", tag, tag);
+ const struct tagname *tp;
+
+ for (tp = tagnames; tp < &tagnames[NTAGS]; tp++)
+ if (tp->tag == tag)
+ {
+ fprintf(fd, "%s (%u)", tp->name, tag);
+ return;
+ }
+ fprintf(fd, "%u (%#x)", tag, tag);
}
-static void
-PrintType(FILE* fd, uint16_t type)
+static void PrintType(FILE *fd, uint16_t type)
{
- static const char *typenames[] = {
- "0",
- "BYTE",
- "ASCII",
- "SHORT",
- "LONG",
- "RATIONAL",
- "SBYTE",
- "UNDEFINED",
- "SSHORT",
- "SLONG",
- "SRATIONAL",
- "FLOAT",
- "DOUBLE",
- "IFD",
- "14",
- "15",
- "LONG8",
- "SLONG8",
- "IFD8"
- };
-#define NTYPES (sizeof (typenames) / sizeof (typenames[0]))
-
- if (type < NTYPES)
- fprintf(fd, "%s (%u)", typenames[type], type);
- else
- fprintf(fd, "%u (%#x)", type, type);
+ static const char *typenames[] = {
+ "0", "BYTE", "ASCII", "SHORT", "LONG",
+ "RATIONAL", "SBYTE", "UNDEFINED", "SSHORT", "SLONG",
+ "SRATIONAL", "FLOAT", "DOUBLE", "IFD", "14",
+ "15", "LONG8", "SLONG8", "IFD8"};
+#define NTYPES (sizeof(typenames) / sizeof(typenames[0]))
+
+ if (type < NTYPES)
+ fprintf(fd, "%s (%u)", typenames[type], type);
+ else
+ fprintf(fd, "%u (%#x)", type, type);
}
-#undef NTYPES
+#undef NTYPES
#include <ctype.h>
-static void
-PrintASCII(FILE* fd, uint32_t cc, const unsigned char* cp)
+static void PrintASCII(FILE *fd, uint32_t cc, const unsigned char *cp)
{
- for (; cc > 0; cc--, cp++) {
- const char* tp;
-
- if (isprint(*cp)) {
- fputc(*cp, fd);
- continue;
- }
- for (tp = "\tt\bb\rr\nn\vv"; *tp; tp++)
- if (*tp++ == *cp)
- break;
- if (*tp)
- fprintf(fd, "\\%c", *tp);
- else if (*cp)
- fprintf(fd, "\\%03o", *cp);
- else
- fprintf(fd, "\\0");
- }
+ for (; cc > 0; cc--, cp++)
+ {
+ const char *tp;
+
+ if (isprint(*cp))
+ {
+ fputc(*cp, fd);
+ continue;
+ }
+ for (tp = "\tt\bb\rr\nn\vv"; *tp; tp++)
+ if (*tp++ == *cp)
+ break;
+ if (*tp)
+ fprintf(fd, "\\%c", *tp);
+ else if (*cp)
+ fprintf(fd, "\\%03o", *cp);
+ else
+ fprintf(fd, "\\0");
+ }
}
-static void
-PrintData(FILE* fd, uint16_t type, uint32_t count, unsigned char* data)
+static void PrintData(FILE *fd, uint16_t type, uint32_t count,
+ unsigned char *data)
{
- char* sep = "";
-
- switch (type) {
- case TIFF_BYTE:
- while (count-- > 0)
- fprintf(fd, bytefmt, sep, *data++), sep = " ";
- break;
- case TIFF_SBYTE:
- while (count-- > 0)
- fprintf(fd, sbytefmt, sep, *(char *)data++), sep = " ";
- break;
- case TIFF_UNDEFINED:
- while (count-- > 0)
- fprintf(fd, bytefmt, sep, *data++), sep = " ";
- break;
- case TIFF_ASCII:
- PrintASCII(fd, count, data);
- break;
- case TIFF_SHORT: {
- uint16_t *wp = (uint16_t*)data;
- while (count-- > 0)
- fprintf(fd, hex_mode ? shortfmth : shortfmtd, sep, *wp++), sep = " ";
- break;
- }
- case TIFF_SSHORT: {
- int16_t *wp = (int16_t*)data;
- while (count-- > 0)
- fprintf(fd, hex_mode ? sshortfmth : sshortfmtd, sep, *wp++), sep = " ";
- break;
- }
- case TIFF_LONG: {
- uint32_t *lp = (uint32_t*)data;
- while (count-- > 0) {
- fprintf(fd, hex_mode ? longfmth : longfmtd, sep, *lp++);
- sep = " ";
- }
- break;
- }
- case TIFF_SLONG: {
- int32_t *lp = (int32_t*)data;
- while (count-- > 0)
- fprintf(fd, hex_mode ? slongfmth : slongfmtd, sep, *lp++), sep = " ";
- break;
- }
- case TIFF_LONG8: {
- uint64_t *llp = (uint64_t*)data;
- while (count-- > 0) {
- uint64_t val;
- memcpy(&val, llp, sizeof(uint64_t));
- llp ++;
- fprintf(fd, long8fmt, sep, val);
- sep = " ";
- }
- break;
- }
- case TIFF_SLONG8: {
- int64_t *llp = (int64_t*)data;
- while (count-- > 0) {
- int64_t val;
- memcpy(&val, llp, sizeof(int64_t));
- llp ++;
- fprintf(fd, slong8fmt, sep, val);
- sep = " ";
- }
- break;
- }
- case TIFF_RATIONAL: {
- uint32_t *lp = (uint32_t*)data;
- while (count-- > 0) {
- if (lp[1] == 0)
- fprintf(fd, "%sNan (%"PRIu32"/%"PRIu32")", sep,
- lp[0], lp[1]);
- else
- fprintf(fd, rationalfmt, sep,
- (double)lp[0] / (double)lp[1]);
- sep = " ";
- lp += 2;
- }
- break;
- }
- case TIFF_SRATIONAL: {
- int32_t *lp = (int32_t*)data;
- while (count-- > 0) {
- if (lp[1] == 0)
- fprintf(fd, "%sNan (%"PRId32"/%"PRId32")", sep,
- lp[0], lp[1]);
- else
- fprintf(fd, srationalfmt, sep,
- (double)lp[0] / (double)lp[1]);
- sep = " ";
- lp += 2;
- }
- break;
- }
- case TIFF_FLOAT: {
- float *fp = (float *)data;
- while (count-- > 0)
- fprintf(fd, floatfmt, sep, *fp++), sep = " ";
- break;
- }
- case TIFF_DOUBLE: {
- double *dp = (double *)data;
- while (count-- > 0)
- fprintf(fd, doublefmt, sep, *dp++), sep = " ";
- break;
- }
- case TIFF_IFD: {
- uint32_t *lp = (uint32_t*)data;
- while (count-- > 0) {
- fprintf(fd, ifdfmt, sep, *lp++);
- sep = " ";
- }
- break;
- }
- case TIFF_IFD8: {
- uint64_t *llp = (uint64_t*)data;
- while (count-- > 0) {
- fprintf(fd, ifd8fmt, sep, *llp++);
- sep = " ";
- sep = " ";
- }
- break;
- }
- }
+ char *sep = "";
+
+ switch (type)
+ {
+ case TIFF_BYTE:
+ while (count-- > 0)
+ fprintf(fd, bytefmt, sep, *data++), sep = " ";
+ break;
+ case TIFF_SBYTE:
+ while (count-- > 0)
+ fprintf(fd, sbytefmt, sep, *(char *)data++), sep = " ";
+ break;
+ case TIFF_UNDEFINED:
+ while (count-- > 0)
+ fprintf(fd, bytefmt, sep, *data++), sep = " ";
+ break;
+ case TIFF_ASCII:
+ PrintASCII(fd, count, data);
+ break;
+ case TIFF_SHORT:
+ {
+ uint16_t *wp = (uint16_t *)data;
+ while (count-- > 0)
+ fprintf(fd, hex_mode ? shortfmth : shortfmtd, sep, *wp++),
+ sep = " ";
+ break;
+ }
+ case TIFF_SSHORT:
+ {
+ int16_t *wp = (int16_t *)data;
+ while (count-- > 0)
+ fprintf(fd, hex_mode ? sshortfmth : sshortfmtd, sep, *wp++),
+ sep = " ";
+ break;
+ }
+ case TIFF_LONG:
+ {
+ uint32_t *lp = (uint32_t *)data;
+ while (count-- > 0)
+ {
+ fprintf(fd, hex_mode ? longfmth : longfmtd, sep, *lp++);
+ sep = " ";
+ }
+ break;
+ }
+ case TIFF_SLONG:
+ {
+ int32_t *lp = (int32_t *)data;
+ while (count-- > 0)
+ fprintf(fd, hex_mode ? slongfmth : slongfmtd, sep, *lp++),
+ sep = " ";
+ break;
+ }
+ case TIFF_LONG8:
+ {
+ uint64_t *llp = (uint64_t *)data;
+ while (count-- > 0)
+ {
+ uint64_t val;
+ memcpy(&val, llp, sizeof(uint64_t));
+ llp++;
+ fprintf(fd, long8fmt, sep, val);
+ sep = " ";
+ }
+ break;
+ }
+ case TIFF_SLONG8:
+ {
+ int64_t *llp = (int64_t *)data;
+ while (count-- > 0)
+ {
+ int64_t val;
+ memcpy(&val, llp, sizeof(int64_t));
+ llp++;
+ fprintf(fd, slong8fmt, sep, val);
+ sep = " ";
+ }
+ break;
+ }
+ case TIFF_RATIONAL:
+ {
+ uint32_t *lp = (uint32_t *)data;
+ while (count-- > 0)
+ {
+ if (lp[1] == 0)
+ fprintf(fd, "%sNan (%" PRIu32 "/%" PRIu32 ")", sep, lp[0],
+ lp[1]);
+ else
+ fprintf(fd, rationalfmt, sep,
+ (double)lp[0] / (double)lp[1]);
+ sep = " ";
+ lp += 2;
+ }
+ break;
+ }
+ case TIFF_SRATIONAL:
+ {
+ int32_t *lp = (int32_t *)data;
+ while (count-- > 0)
+ {
+ if (lp[1] == 0)
+ fprintf(fd, "%sNan (%" PRId32 "/%" PRId32 ")", sep, lp[0],
+ lp[1]);
+ else
+ fprintf(fd, srationalfmt, sep,
+ (double)lp[0] / (double)lp[1]);
+ sep = " ";
+ lp += 2;
+ }
+ break;
+ }
+ case TIFF_FLOAT:
+ {
+ float *fp = (float *)data;
+ while (count-- > 0)
+ fprintf(fd, floatfmt, sep, *fp++), sep = " ";
+ break;
+ }
+ case TIFF_DOUBLE:
+ {
+ double *dp = (double *)data;
+ while (count-- > 0)
+ fprintf(fd, doublefmt, sep, *dp++), sep = " ";
+ break;
+ }
+ case TIFF_IFD:
+ {
+ uint32_t *lp = (uint32_t *)data;
+ while (count-- > 0)
+ {
+ fprintf(fd, ifdfmt, sep, *lp++);
+ sep = " ";
+ }
+ break;
+ }
+ case TIFF_IFD8:
+ {
+ uint64_t *llp = (uint64_t *)data;
+ while (count-- > 0)
+ {
+ fprintf(fd, ifd8fmt, sep, *llp++);
+ sep = " ";
+ sep = " ";
+ }
+ break;
+ }
+ }
}
-static void
-ReadError(char* what)
-{
- Fatal("Error while reading %s", what);
-}
+static void ReadError(char *what) { Fatal("Error while reading %s", what); }
#include <stdarg.h>
-static void
-vError(FILE* fd, const char* fmt, va_list ap)
+static void vError(FILE *fd, const char *fmt, va_list ap)
{
- fprintf(fd, "%s: ", curfile);
- vfprintf(fd, fmt, ap);
- fprintf(fd, ".\n");
+ fprintf(fd, "%s: ", curfile);
+ vfprintf(fd, fmt, ap);
+ fprintf(fd, ".\n");
}
-static void
-Error(const char* fmt, ...)
+static void Error(const char *fmt, ...)
{
- va_list ap;
- va_start(ap, fmt);
- vError(stderr, fmt, ap);
- va_end(ap);
+ va_list ap;
+ va_start(ap, fmt);
+ vError(stderr, fmt, ap);
+ va_end(ap);
}
-static void
-Fatal(const char* fmt, ...)
+static void Fatal(const char *fmt, ...)
{
- va_list ap;
- va_start(ap, fmt);
- vError(stderr, fmt, ap);
- va_end(ap);
- exit(EXIT_FAILURE);
+ va_list ap;
+ va_start(ap, fmt);
+ vError(stderr, fmt, ap);
+ va_end(ap);
+ exit(EXIT_FAILURE);
}
diff --git a/tools/tiffgt.c b/tools/tiffgt.c
index 28784817..96c692b2 100644
--- a/tools/tiffgt.c
+++ b/tools/tiffgt.c
@@ -3,28 +3,28 @@
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
* Copyright (c) 2003, Andrey Kiselev <dron@ak4719.spb.edu>
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
#include <stdio.h>
#include <stdlib.h>
@@ -34,17 +34,17 @@
#endif
#ifdef HAVE_OPENGL_GL_H
-# include <OpenGL/gl.h>
+#include <OpenGL/gl.h>
#else
-# ifdef _WIN32
-# include <windows.h>
-# endif
-# include <GL/gl.h>
+#ifdef _WIN32
+#include <windows.h>
+#endif
+#include <GL/gl.h>
#endif
#ifdef HAVE_GLUT_GLUT_H
-# include <GLUT/glut.h>
+#include <GLUT/glut.h>
#else
-# include <GL/glut.h>
+#include <GL/glut.h>
#endif
#include "tiffio.h"
@@ -57,58 +57,58 @@
#define EXIT_FAILURE 1
#endif
-static uint32_t width = 0, height = 0; /* window width & height */
-static uint32_t* raster = NULL; /* displayable image */
+static uint32_t width = 0, height = 0; /* window width & height */
+static uint32_t *raster = NULL; /* displayable image */
static TIFFRGBAImage img;
-static int order0 = 0, order;
-static uint16_t photo0 = (uint16_t) -1, photo;
-static int stoponerr = 0; /* stop on read error */
-static int verbose = 0;
-#define TITLE_LENGTH 1024
-static char title[TITLE_LENGTH]; /* window title line */
-static uint32_t xmax, ymax;
-static char** filelist = NULL;
-static int fileindex;
-static int filenum;
+static int order0 = 0, order;
+static uint16_t photo0 = (uint16_t)-1, photo;
+static int stoponerr = 0; /* stop on read error */
+static int verbose = 0;
+#define TITLE_LENGTH 1024
+static char title[TITLE_LENGTH]; /* window title line */
+static uint32_t xmax, ymax;
+static char **filelist = NULL;
+static int fileindex;
+static int filenum;
static TIFFErrorHandler oerror;
static TIFFErrorHandler owarning;
-static void cleanup_and_exit(int);
-static int initImage(void);
-static int prevImage(void);
-static int nextImage(void);
-static void setWindowSize(void);
-static void usage(int);
-static uint16_t photoArg(const char*);
-static void raster_draw(void);
-static void raster_reshape(int, int);
-static void raster_keys(unsigned char, int, int);
-static void raster_special(int, int, int);
+static void cleanup_and_exit(int);
+static int initImage(void);
+static int prevImage(void);
+static int nextImage(void);
+static void setWindowSize(void);
+static void usage(int);
+static uint16_t photoArg(const char *);
+static void raster_draw(void);
+static void raster_reshape(int, int);
+static void raster_keys(unsigned char, int, int);
+static void raster_special(int, int, int);
#if !HAVE_DECL_OPTARG
-extern char* optarg;
-extern int optind;
+extern char *optarg;
+extern int optind;
#endif
/* GLUT framework on MacOS X produces deprecation warnings */
-# if defined(__GNUC__) && defined(__APPLE__)
-# pragma GCC diagnostic push
-# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
-# endif
+#if defined(__GNUC__) && defined(__APPLE__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
-static TIFF* tif = NULL;
+static TIFF *tif = NULL;
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- int c;
- int dirnum = -1;
- uint32_t diroff = 0;
-
- oerror = TIFFSetErrorHandler(NULL);
- owarning = TIFFSetWarningHandler(NULL);
- while ((c = getopt(argc, argv, "d:o:p:eflmsvwh")) != -1)
- switch (c) {
+ int c;
+ int dirnum = -1;
+ uint32_t diroff = 0;
+
+ oerror = TIFFSetErrorHandler(NULL);
+ owarning = TIFFSetWarningHandler(NULL);
+ while ((c = getopt(argc, argv, "d:o:p:eflmsvwh")) != -1)
+ switch (c)
+ {
case 'd':
dirnum = atoi(optarg);
break;
@@ -142,346 +142,350 @@ main(int argc, char* argv[])
case '?':
usage(EXIT_FAILURE);
/*NOTREACHED*/
- }
- filenum = argc - optind;
- if ( filenum < 1)
- usage(EXIT_FAILURE);
-
- glutInit(&argc, argv);
- glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
-
- /*
- * Get the screen size
- */
- xmax = glutGet(GLUT_SCREEN_WIDTH);
- ymax = glutGet(GLUT_SCREEN_HEIGHT);
-
- /*
- * Use 90% of the screen size
- */
- xmax = xmax - xmax / 10.0;
- ymax = ymax - ymax / 10.0;
-
- filelist = (char **) _TIFFmalloc(filenum * sizeof(char*));
- if (!filelist) {
- TIFFError(argv[0], "Can not allocate space for the file list.");
- return EXIT_FAILURE;
- }
- _TIFFmemcpy(filelist, argv + optind, filenum * sizeof(char*));
- fileindex = -1;
- if (nextImage() < 0) {
- _TIFFfree(filelist);
- return EXIT_FAILURE;
- }
- /*
- * Set initial directory if user-specified
- * file was opened successfully.
- */
- if (dirnum != -1 && !TIFFSetDirectory(tif, dirnum))
- TIFFError(argv[0], "Error, seeking to directory %d", dirnum);
- if (diroff != 0 && !TIFFSetSubDirectory(tif, diroff))
- TIFFError(argv[0], "Error, setting subdirectory at %#x", diroff);
- order = order0;
- photo = photo0;
- if (initImage() < 0){
- _TIFFfree(filelist);
- return EXIT_FAILURE;
}
- /*
- * Create a new window or reconfigure an existing
- * one to suit the image to be displayed.
- */
- glutInitWindowSize(width, height);
- snprintf(title, TITLE_LENGTH - 1, "%s [%u]", filelist[fileindex],
- (unsigned int) TIFFCurrentDirectory(tif));
- glutCreateWindow(title);
- glutDisplayFunc(raster_draw);
- glutReshapeFunc(raster_reshape);
- glutKeyboardFunc(raster_keys);
- glutSpecialFunc(raster_special);
- glutMainLoop();
-
- cleanup_and_exit(EXIT_SUCCESS);
- return EXIT_SUCCESS;
+ filenum = argc - optind;
+ if (filenum < 1)
+ usage(EXIT_FAILURE);
+
+ glutInit(&argc, argv);
+ glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
+
+ /*
+ * Get the screen size
+ */
+ xmax = glutGet(GLUT_SCREEN_WIDTH);
+ ymax = glutGet(GLUT_SCREEN_HEIGHT);
+
+ /*
+ * Use 90% of the screen size
+ */
+ xmax = xmax - xmax / 10.0;
+ ymax = ymax - ymax / 10.0;
+
+ filelist = (char **)_TIFFmalloc(filenum * sizeof(char *));
+ if (!filelist)
+ {
+ TIFFError(argv[0], "Can not allocate space for the file list.");
+ return EXIT_FAILURE;
+ }
+ _TIFFmemcpy(filelist, argv + optind, filenum * sizeof(char *));
+ fileindex = -1;
+ if (nextImage() < 0)
+ {
+ _TIFFfree(filelist);
+ return EXIT_FAILURE;
+ }
+ /*
+ * Set initial directory if user-specified
+ * file was opened successfully.
+ */
+ if (dirnum != -1 && !TIFFSetDirectory(tif, dirnum))
+ TIFFError(argv[0], "Error, seeking to directory %d", dirnum);
+ if (diroff != 0 && !TIFFSetSubDirectory(tif, diroff))
+ TIFFError(argv[0], "Error, setting subdirectory at %#x", diroff);
+ order = order0;
+ photo = photo0;
+ if (initImage() < 0)
+ {
+ _TIFFfree(filelist);
+ return EXIT_FAILURE;
+ }
+ /*
+ * Create a new window or reconfigure an existing
+ * one to suit the image to be displayed.
+ */
+ glutInitWindowSize(width, height);
+ snprintf(title, TITLE_LENGTH - 1, "%s [%u]", filelist[fileindex],
+ (unsigned int)TIFFCurrentDirectory(tif));
+ glutCreateWindow(title);
+ glutDisplayFunc(raster_draw);
+ glutReshapeFunc(raster_reshape);
+ glutKeyboardFunc(raster_keys);
+ glutSpecialFunc(raster_special);
+ glutMainLoop();
+
+ cleanup_and_exit(EXIT_SUCCESS);
+ return EXIT_SUCCESS;
}
-static void
-cleanup_and_exit(int code)
+static void cleanup_and_exit(int code)
{
- TIFFRGBAImageEnd(&img);
- if (filelist != NULL)
- _TIFFfree(filelist);
- if (raster != NULL)
- _TIFFfree(raster);
- if (tif != NULL)
- TIFFClose(tif);
- exit(code);
+ TIFFRGBAImageEnd(&img);
+ if (filelist != NULL)
+ _TIFFfree(filelist);
+ if (raster != NULL)
+ _TIFFfree(raster);
+ if (tif != NULL)
+ TIFFClose(tif);
+ exit(code);
}
-static int
-initImage(void)
+static int initImage(void)
{
- uint32_t w, h;
-
- if (order)
- TIFFSetField(tif, TIFFTAG_FILLORDER, order);
- if (photo != (uint16_t) -1)
- TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, photo);
- if (!TIFFRGBAImageBegin(&img, tif, stoponerr, title)) {
- TIFFError(filelist[fileindex], "%s", title);
- TIFFClose(tif);
- tif = NULL;
- return -1;
- }
-
- /*
- * Setup the image raster as required.
- */
- h = img.height;
- w = img.width;
- if (h > ymax) {
- w = (int)(w * ((float)ymax / h));
- h = ymax;
- }
- if (w > xmax) {
- h = (int)(h * ((float)xmax / w));
- w = xmax;
- }
-
- if (w != width || h != height) {
- uint32_t rastersize =
- _TIFFMultiply32(tif, img.width, img.height, "allocating raster buffer");
- if (raster != NULL)
- _TIFFfree(raster), raster = NULL;
- raster = (uint32_t*) _TIFFCheckMalloc(tif, rastersize, sizeof (uint32_t),
+ uint32_t w, h;
+
+ if (order)
+ TIFFSetField(tif, TIFFTAG_FILLORDER, order);
+ if (photo != (uint16_t)-1)
+ TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, photo);
+ if (!TIFFRGBAImageBegin(&img, tif, stoponerr, title))
+ {
+ TIFFError(filelist[fileindex], "%s", title);
+ TIFFClose(tif);
+ tif = NULL;
+ return -1;
+ }
+
+ /*
+ * Setup the image raster as required.
+ */
+ h = img.height;
+ w = img.width;
+ if (h > ymax)
+ {
+ w = (int)(w * ((float)ymax / h));
+ h = ymax;
+ }
+ if (w > xmax)
+ {
+ h = (int)(h * ((float)xmax / w));
+ w = xmax;
+ }
+
+ if (w != width || h != height)
+ {
+ uint32_t rastersize = _TIFFMultiply32(tif, img.width, img.height,
+ "allocating raster buffer");
+ if (raster != NULL)
+ _TIFFfree(raster), raster = NULL;
+ raster = (uint32_t *)_TIFFCheckMalloc(tif, rastersize, sizeof(uint32_t),
"allocating raster buffer");
- if (raster == NULL) {
- width = height = 0;
- TIFFError(filelist[fileindex], "No space for raster buffer");
- cleanup_and_exit(EXIT_FAILURE);
- }
- width = w;
- height = h;
- }
- TIFFRGBAImageGet(&img, raster, img.width, img.height);
+ if (raster == NULL)
+ {
+ width = height = 0;
+ TIFFError(filelist[fileindex], "No space for raster buffer");
+ cleanup_and_exit(EXIT_FAILURE);
+ }
+ width = w;
+ height = h;
+ }
+ TIFFRGBAImageGet(&img, raster, img.width, img.height);
#if HOST_BIGENDIAN
- TIFFSwabArrayOfLong(raster,img.width*img.height);
+ TIFFSwabArrayOfLong(raster, img.width * img.height);
#endif
- return 0;
+ return 0;
}
-static int
-prevImage(void)
+static int prevImage(void)
{
- if (fileindex > 0)
- fileindex--;
- else if (tif)
- return fileindex;
- if (tif)
- TIFFClose(tif);
- tif = TIFFOpen(filelist[fileindex], "r");
- if (tif == NULL)
- return -1;
+ if (fileindex > 0)
+ fileindex--;
+ else if (tif)
return fileindex;
+ if (tif)
+ TIFFClose(tif);
+ tif = TIFFOpen(filelist[fileindex], "r");
+ if (tif == NULL)
+ return -1;
+ return fileindex;
}
-static int
-nextImage(void)
+static int nextImage(void)
{
- if (fileindex < filenum - 1)
- fileindex++;
- else if (tif)
- return fileindex;
- if (tif)
- TIFFClose(tif);
- tif = TIFFOpen(filelist[fileindex], "r");
- if (tif == NULL)
- return -1;
+ if (fileindex < filenum - 1)
+ fileindex++;
+ else if (tif)
return fileindex;
+ if (tif)
+ TIFFClose(tif);
+ tif = TIFFOpen(filelist[fileindex], "r");
+ if (tif == NULL)
+ return -1;
+ return fileindex;
}
-static void
-setWindowSize(void)
+static void setWindowSize(void) { glutReshapeWindow(width, height); }
+
+static void raster_draw(void)
{
- glutReshapeWindow(width, height);
+ glDrawPixels(img.width, img.height, GL_RGBA, GL_UNSIGNED_BYTE,
+ (const GLvoid *)raster);
+ glFlush();
}
-static void
-raster_draw(void)
+static void raster_reshape(int win_w, int win_h)
{
- glDrawPixels(img.width, img.height, GL_RGBA, GL_UNSIGNED_BYTE, (const GLvoid *) raster);
- glFlush();
+ GLfloat xratio = (GLfloat)win_w / img.width;
+ GLfloat yratio = (GLfloat)win_h / img.height;
+ int ratio = (int)(((xratio > yratio) ? xratio : yratio) * 100);
+
+ glPixelZoom(xratio, yratio);
+ glViewport(0, 0, win_w, win_h);
+ snprintf(title, 1024, "%s [%u] %d%%", filelist[fileindex],
+ (unsigned int)TIFFCurrentDirectory(tif), ratio);
+ glutSetWindowTitle(title);
}
-static void
-raster_reshape(int win_w, int win_h)
+static void raster_keys(unsigned char key, int x, int y)
{
- GLfloat xratio = (GLfloat)win_w/img.width;
- GLfloat yratio = (GLfloat)win_h/img.height;
- int ratio = (int)(((xratio > yratio)?xratio:yratio) * 100);
-
- glPixelZoom(xratio, yratio);
- glViewport(0, 0, win_w, win_h);
- snprintf(title, 1024, "%s [%u] %d%%", filelist[fileindex],
- (unsigned int) TIFFCurrentDirectory(tif), ratio);
- glutSetWindowTitle(title);
+ (void)x;
+ (void)y;
+ switch (key)
+ {
+ case 'b': /* photometric MinIsBlack */
+ photo = PHOTOMETRIC_MINISBLACK;
+ initImage();
+ break;
+ case 'l': /* lsb-to-msb FillOrder */
+ order = FILLORDER_LSB2MSB;
+ initImage();
+ break;
+ case 'm': /* msb-to-lsb FillOrder */
+ order = FILLORDER_MSB2LSB;
+ initImage();
+ break;
+ case 'w': /* photometric MinIsWhite */
+ photo = PHOTOMETRIC_MINISWHITE;
+ initImage();
+ break;
+ case 'W': /* toggle warnings */
+ owarning = TIFFSetWarningHandler(owarning);
+ initImage();
+ break;
+ case 'E': /* toggle errors */
+ oerror = TIFFSetErrorHandler(oerror);
+ initImage();
+ break;
+ case 'z': /* reset to defaults */
+ case 'Z':
+ order = order0;
+ photo = photo0;
+ if (owarning == NULL)
+ owarning = TIFFSetWarningHandler(NULL);
+ if (oerror == NULL)
+ oerror = TIFFSetErrorHandler(NULL);
+ initImage();
+ break;
+ case 'q': /* exit */
+ case '\033':
+ cleanup_and_exit(EXIT_SUCCESS);
+ }
+ glutPostRedisplay();
}
-static void
-raster_keys(unsigned char key, int x, int y)
+static void raster_special(int key, int x, int y)
{
- (void) x;
- (void) y;
- switch (key) {
- case 'b': /* photometric MinIsBlack */
- photo = PHOTOMETRIC_MINISBLACK;
+ (void)x;
+ (void)y;
+ switch (key)
+ {
+ case GLUT_KEY_PAGE_UP: /* previous logical image */
+ if (TIFFCurrentDirectory(tif) > 0)
+ {
+ if (TIFFSetDirectory(tif, TIFFCurrentDirectory(tif) - 1))
+ {
initImage();
- break;
- case 'l': /* lsb-to-msb FillOrder */
- order = FILLORDER_LSB2MSB;
- initImage();
- break;
- case 'm': /* msb-to-lsb FillOrder */
- order = FILLORDER_MSB2LSB;
- initImage();
- break;
- case 'w': /* photometric MinIsWhite */
- photo = PHOTOMETRIC_MINISWHITE;
- initImage();
- break;
- case 'W': /* toggle warnings */
- owarning = TIFFSetWarningHandler(owarning);
- initImage();
- break;
- case 'E': /* toggle errors */
- oerror = TIFFSetErrorHandler(oerror);
- initImage();
- break;
- case 'z': /* reset to defaults */
- case 'Z':
- order = order0;
- photo = photo0;
- if (owarning == NULL)
- owarning = TIFFSetWarningHandler(NULL);
- if (oerror == NULL)
- oerror = TIFFSetErrorHandler(NULL);
+ setWindowSize();
+ }
+ }
+ else
+ {
+ TIFFRGBAImageEnd(&img);
+ prevImage();
+ initImage();
+ setWindowSize();
+ }
+ break;
+ case GLUT_KEY_PAGE_DOWN: /* next logical image */
+ if (!TIFFLastDirectory(tif))
+ {
+ if (TIFFReadDirectory(tif))
+ {
initImage();
- break;
- case 'q': /* exit */
- case '\033':
- cleanup_and_exit(EXIT_SUCCESS);
- }
- glutPostRedisplay();
-}
-
-static void
-raster_special(int key, int x, int y)
-{
- (void) x;
- (void) y;
- switch (key) {
- case GLUT_KEY_PAGE_UP: /* previous logical image */
- if (TIFFCurrentDirectory(tif) > 0) {
- if (TIFFSetDirectory(tif,
- TIFFCurrentDirectory(tif)-1)) {
- initImage();
- setWindowSize();
- }
- } else {
- TIFFRGBAImageEnd(&img);
- prevImage();
- initImage();
- setWindowSize();
- }
- break;
- case GLUT_KEY_PAGE_DOWN: /* next logical image */
- if (!TIFFLastDirectory(tif)) {
- if (TIFFReadDirectory(tif)) {
- initImage();
- setWindowSize();
- }
- } else {
- TIFFRGBAImageEnd(&img);
- nextImage();
- initImage();
- setWindowSize();
- }
- break;
- case GLUT_KEY_HOME: /* 1st image in current file */
- if (TIFFSetDirectory(tif, 0)) {
- TIFFRGBAImageEnd(&img);
- initImage();
- setWindowSize();
- }
- break;
- case GLUT_KEY_END: /* last image in current file */
- TIFFRGBAImageEnd(&img);
- while (!TIFFLastDirectory(tif))
- TIFFReadDirectory(tif);
- initImage();
- setWindowSize();
- break;
- }
- glutPostRedisplay();
+ setWindowSize();
+ }
+ }
+ else
+ {
+ TIFFRGBAImageEnd(&img);
+ nextImage();
+ initImage();
+ setWindowSize();
+ }
+ break;
+ case GLUT_KEY_HOME: /* 1st image in current file */
+ if (TIFFSetDirectory(tif, 0))
+ {
+ TIFFRGBAImageEnd(&img);
+ initImage();
+ setWindowSize();
+ }
+ break;
+ case GLUT_KEY_END: /* last image in current file */
+ TIFFRGBAImageEnd(&img);
+ while (!TIFFLastDirectory(tif))
+ TIFFReadDirectory(tif);
+ initImage();
+ setWindowSize();
+ break;
+ }
+ glutPostRedisplay();
}
/* GLUT framework on MacOS X produces deprecation warnings */
-# if defined(__GNUC__) && defined(__APPLE__)
-# pragma GCC diagnostic pop
-# endif
-
-static const char* stuff[] = {
-"usage: tiffgt [options] file.tif",
-"where options are:",
-" -c use colormap visual",
-" -d dirnum set initial directory (default is 0)",
-" -e enable display of TIFF error messages",
-" -l force lsb-to-msb FillOrder",
-" -m force msb-to-lsb FillOrder",
-" -o offset set initial directory offset",
-" -p photo override photometric interpretation",
-" -r use fullcolor visual",
-" -s stop decoding on first error (default is ignore errors)",
-" -v enable verbose mode",
-" -w enable display of TIFF warning messages",
-NULL
-};
-
-static void
-usage(int code)
+#if defined(__GNUC__) && defined(__APPLE__)
+#pragma GCC diagnostic pop
+#endif
+
+static const char *stuff[] = {
+ "usage: tiffgt [options] file.tif",
+ "where options are:",
+ " -c use colormap visual",
+ " -d dirnum set initial directory (default is 0)",
+ " -e enable display of TIFF error messages",
+ " -l force lsb-to-msb FillOrder",
+ " -m force msb-to-lsb FillOrder",
+ " -o offset set initial directory offset",
+ " -p photo override photometric interpretation",
+ " -r use fullcolor visual",
+ " -s stop decoding on first error (default is ignore errors)",
+ " -v enable verbose mode",
+ " -w enable display of TIFF warning messages",
+ NULL};
+
+static void usage(int code)
{
- int i;
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ int i;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- for (i = 0; stuff[i] != NULL; i++)
- fprintf(out, "%s\n", stuff[i]);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ for (i = 0; stuff[i] != NULL; i++)
+ fprintf(out, "%s\n", stuff[i]);
+ exit(code);
}
-static uint16_t
-photoArg(const char* arg)
+static uint16_t photoArg(const char *arg)
{
- if (strcmp(arg, "miniswhite") == 0)
- return (PHOTOMETRIC_MINISWHITE);
- else if (strcmp(arg, "minisblack") == 0)
- return (PHOTOMETRIC_MINISBLACK);
- else if (strcmp(arg, "rgb") == 0)
- return (PHOTOMETRIC_RGB);
- else if (strcmp(arg, "palette") == 0)
- return (PHOTOMETRIC_PALETTE);
- else if (strcmp(arg, "mask") == 0)
- return (PHOTOMETRIC_MASK);
- else if (strcmp(arg, "separated") == 0)
- return (PHOTOMETRIC_SEPARATED);
- else if (strcmp(arg, "ycbcr") == 0)
- return (PHOTOMETRIC_YCBCR);
- else if (strcmp(arg, "cielab") == 0)
- return (PHOTOMETRIC_CIELAB);
- else if (strcmp(arg, "logl") == 0)
- return (PHOTOMETRIC_LOGL);
- else if (strcmp(arg, "logluv") == 0)
- return (PHOTOMETRIC_LOGLUV);
- else
- return ((uint16_t) -1);
+ if (strcmp(arg, "miniswhite") == 0)
+ return (PHOTOMETRIC_MINISWHITE);
+ else if (strcmp(arg, "minisblack") == 0)
+ return (PHOTOMETRIC_MINISBLACK);
+ else if (strcmp(arg, "rgb") == 0)
+ return (PHOTOMETRIC_RGB);
+ else if (strcmp(arg, "palette") == 0)
+ return (PHOTOMETRIC_PALETTE);
+ else if (strcmp(arg, "mask") == 0)
+ return (PHOTOMETRIC_MASK);
+ else if (strcmp(arg, "separated") == 0)
+ return (PHOTOMETRIC_SEPARATED);
+ else if (strcmp(arg, "ycbcr") == 0)
+ return (PHOTOMETRIC_YCBCR);
+ else if (strcmp(arg, "cielab") == 0)
+ return (PHOTOMETRIC_CIELAB);
+ else if (strcmp(arg, "logl") == 0)
+ return (PHOTOMETRIC_LOGL);
+ else if (strcmp(arg, "logluv") == 0)
+ return (PHOTOMETRIC_LOGLUV);
+ else
+ return ((uint16_t)-1);
}
diff --git a/tools/tiffinfo.c b/tools/tiffinfo.c
index a43c30b1..7ec7f952 100644
--- a/tools/tiffinfo.c
+++ b/tools/tiffinfo.c
@@ -2,39 +2,39 @@
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_STRINGS_H
-# include <strings.h>
+#include <strings.h>
#endif
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#include "tiffiop.h"
@@ -47,618 +47,706 @@
#endif
static TIFFErrorHandler old_error_handler = 0;
-static int status = EXIT_SUCCESS; /* exit status */
-static int showdata = 0; /* show data */
-static int rawdata = 0; /* show raw/decoded data */
-static int showwords = 0; /* show data as bytes/words */
-static int readdata = 0; /* read data in file */
-static int stoponerr = 1; /* stop on first read error */
+static int status = EXIT_SUCCESS; /* exit status */
+static int showdata = 0; /* show data */
+static int rawdata = 0; /* show raw/decoded data */
+static int showwords = 0; /* show data as bytes/words */
+static int readdata = 0; /* read data in file */
+static int stoponerr = 1; /* stop on first read error */
-static void usage(int);
-static void tiffinfo(TIFF*, uint16_t, long, int);
+static void usage(int);
+static void tiffinfo(TIFF *, uint16_t, long, int);
#define DEFAULT_MAX_MALLOC (256 * 1024 * 1024)
/* malloc size limit (in bytes)
* disabled when set to 0 */
static tmsize_t maxMalloc = DEFAULT_MAX_MALLOC;
-static void
-PrivateErrorHandler(const char* module, const char* fmt, va_list ap)
+static void PrivateErrorHandler(const char *module, const char *fmt, va_list ap)
{
- if (old_error_handler)
- (*old_error_handler)(module,fmt,ap);
- status = EXIT_FAILURE;
+ if (old_error_handler)
+ (*old_error_handler)(module, fmt, ap);
+ status = EXIT_FAILURE;
}
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- int dirnum = -1, multiplefiles, c;
- uint16_t order = 0;
- TIFF* tif;
+ int dirnum = -1, multiplefiles, c;
+ uint16_t order = 0;
+ TIFF *tif;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char* optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- long flags = 0;
- uint64_t diroff = 0;
- int chopstrips = 0; /* disable strip chopping */
-
- while ((c = getopt(argc, argv, "f:o:M:cdDSjilmrsvwz0123456789h")) != -1)
- switch (c) {
- case '0': case '1': case '2': case '3':
- case '4': case '5': case '6': case '7':
- case '8': case '9':
- dirnum = atoi(&argv[optind-1][1]);
- break;
- case 'd':
- showdata++;
- /* fall through... */
- case 'D':
- readdata++;
- break;
- case 'c':
- flags |= TIFFPRINT_COLORMAP | TIFFPRINT_CURVES;
- break;
- case 'f': /* fill order */
- if (streq(optarg, "lsb2msb"))
- order = FILLORDER_LSB2MSB;
- else if (streq(optarg, "msb2lsb"))
- order = FILLORDER_MSB2LSB;
- else
- usage(EXIT_FAILURE);
- break;
- case 'i':
- stoponerr = 0;
- break;
- case 'M':
- maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
- break;
- case 'o':
- diroff = strtoul(optarg, NULL, 0);
- break;
- case 'j':
- flags |= TIFFPRINT_JPEGQTABLES |
- TIFFPRINT_JPEGACTABLES |
- TIFFPRINT_JPEGDCTABLES;
- break;
- case 'r':
- rawdata = 1;
- break;
- case 's':
- flags |= TIFFPRINT_STRIPS;
- break;
- case 'w':
- showwords = 1;
- break;
- case 'z':
- chopstrips = 1;
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- /*NOTREACHED*/
- break;
- case '?':
- usage(EXIT_FAILURE);
- /*NOTREACHED*/
- break;
- }
- if (optind >= argc)
- usage(EXIT_FAILURE);
-
- old_error_handler = TIFFSetErrorHandler(PrivateErrorHandler);
-
- multiplefiles = (argc - optind > 1);
- for (; optind < argc; optind++) {
- if (multiplefiles)
- printf("File %s:\n", argv[optind]);
- TIFFOpenOptions* opts = TIFFOpenOptionsAlloc();
- if (opts == NULL) {
- status = EXIT_FAILURE;
- break;
- }
- TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
- tif = TIFFOpenExt(argv[optind], chopstrips ? "rC" : "rc", opts);
- TIFFOpenOptionsFree(opts);
- if (tif != NULL) {
- if (dirnum != -1) {
- if (TIFFSetDirectory(tif, (tdir_t) dirnum))
- tiffinfo(tif, order, flags, 1);
- } else if (diroff != 0) {
- if (TIFFSetSubDirectory(tif, diroff))
- tiffinfo(tif, order, flags, 1);
- } else {
- do {
- toff_t offset=0;
- uint16_t curdir = TIFFCurrentDirectory(tif);
- printf("=== TIFF directory %d ===\n", curdir);
- tiffinfo(tif, order, flags, 1);
- if (TIFFGetField(tif, TIFFTAG_EXIFIFD,
- &offset)) {
- printf("--- EXIF directory within directory %d \n", curdir);
- if (TIFFReadEXIFDirectory(tif, offset)) {
- tiffinfo(tif, order, flags, 0);
- /*-- Go back to previous directory, (directory is reloaded from file!) */
- TIFFSetDirectory(tif, curdir);
- }
- }
- if (TIFFGetField(tif, TIFFTAG_GPSIFD,
- &offset)) {
- printf("--- GPS directory within directory %d \n", curdir);
- if (TIFFReadGPSDirectory(tif, offset)) {
- tiffinfo(tif, order, flags, 0);
- TIFFSetDirectory(tif, curdir);
- }
- }
- /*-- Check for SubIFDs --*/
- uint16_t nCount;
- void *vPtr;
- uint64_t *subIFDoffsets = NULL;
- if (TIFFGetField(tif, TIFFTAG_SUBIFD, &nCount, &vPtr)) {
- if (nCount > 0) {
- subIFDoffsets = malloc(nCount * sizeof(uint64_t));
- if (subIFDoffsets != NULL) {
- memcpy(subIFDoffsets, vPtr, nCount * sizeof(subIFDoffsets[0]));
- printf("--- SubIFD image descriptor tag within TIFF directory %d with array of %d SubIFD chains ---\n", curdir, nCount);
- for (int i = 0; i < nCount; i++) {
- offset = subIFDoffsets[i];
- int s = 0;
- if (TIFFSetSubDirectory(tif, offset)) {
- /* print info and check for SubIFD chain */
- do {
- printf("--- SubIFD %d of chain %d at offset 0x%"PRIx64" (%"PRIu64"):\n", s, i, offset, offset);
- tiffinfo(tif, order, flags, 0);
- s++;
- } while (TIFFReadDirectory(tif));
- }
- }
- TIFFSetDirectory(tif, curdir);
- free(subIFDoffsets);
- subIFDoffsets = NULL;
- } else {
- fprintf(stderr, "Error: Could not allocate memory for SubIFDs list. SubIFDs not parsed.\n");
- }
- }
- }
- printf("\n");
- } while (TIFFReadDirectory(tif));
- }
- TIFFClose(tif);
- }
- }
- return (status);
+ long flags = 0;
+ uint64_t diroff = 0;
+ int chopstrips = 0; /* disable strip chopping */
+
+ while ((c = getopt(argc, argv, "f:o:M:cdDSjilmrsvwz0123456789h")) != -1)
+ switch (c)
+ {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ dirnum = atoi(&argv[optind - 1][1]);
+ break;
+ case 'd':
+ showdata++;
+ /* fall through... */
+ case 'D':
+ readdata++;
+ break;
+ case 'c':
+ flags |= TIFFPRINT_COLORMAP | TIFFPRINT_CURVES;
+ break;
+ case 'f': /* fill order */
+ if (streq(optarg, "lsb2msb"))
+ order = FILLORDER_LSB2MSB;
+ else if (streq(optarg, "msb2lsb"))
+ order = FILLORDER_MSB2LSB;
+ else
+ usage(EXIT_FAILURE);
+ break;
+ case 'i':
+ stoponerr = 0;
+ break;
+ case 'M':
+ maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
+ break;
+ case 'o':
+ diroff = strtoul(optarg, NULL, 0);
+ break;
+ case 'j':
+ flags |= TIFFPRINT_JPEGQTABLES | TIFFPRINT_JPEGACTABLES |
+ TIFFPRINT_JPEGDCTABLES;
+ break;
+ case 'r':
+ rawdata = 1;
+ break;
+ case 's':
+ flags |= TIFFPRINT_STRIPS;
+ break;
+ case 'w':
+ showwords = 1;
+ break;
+ case 'z':
+ chopstrips = 1;
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ /*NOTREACHED*/
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ /*NOTREACHED*/
+ break;
+ }
+ if (optind >= argc)
+ usage(EXIT_FAILURE);
+
+ old_error_handler = TIFFSetErrorHandler(PrivateErrorHandler);
+
+ multiplefiles = (argc - optind > 1);
+ for (; optind < argc; optind++)
+ {
+ if (multiplefiles)
+ printf("File %s:\n", argv[optind]);
+ TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
+ if (opts == NULL)
+ {
+ status = EXIT_FAILURE;
+ break;
+ }
+ TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
+ tif = TIFFOpenExt(argv[optind], chopstrips ? "rC" : "rc", opts);
+ TIFFOpenOptionsFree(opts);
+ if (tif != NULL)
+ {
+ if (dirnum != -1)
+ {
+ if (TIFFSetDirectory(tif, (tdir_t)dirnum))
+ tiffinfo(tif, order, flags, 1);
+ }
+ else if (diroff != 0)
+ {
+ if (TIFFSetSubDirectory(tif, diroff))
+ tiffinfo(tif, order, flags, 1);
+ }
+ else
+ {
+ do
+ {
+ toff_t offset = 0;
+ uint16_t curdir = TIFFCurrentDirectory(tif);
+ printf("=== TIFF directory %d ===\n", curdir);
+ tiffinfo(tif, order, flags, 1);
+ if (TIFFGetField(tif, TIFFTAG_EXIFIFD, &offset))
+ {
+ printf("--- EXIF directory within directory %d \n",
+ curdir);
+ if (TIFFReadEXIFDirectory(tif, offset))
+ {
+ tiffinfo(tif, order, flags, 0);
+ /*-- Go back to previous directory, (directory is
+ * reloaded from file!) */
+ TIFFSetDirectory(tif, curdir);
+ }
+ }
+ if (TIFFGetField(tif, TIFFTAG_GPSIFD, &offset))
+ {
+ printf("--- GPS directory within directory %d \n",
+ curdir);
+ if (TIFFReadGPSDirectory(tif, offset))
+ {
+ tiffinfo(tif, order, flags, 0);
+ TIFFSetDirectory(tif, curdir);
+ }
+ }
+ /*-- Check for SubIFDs --*/
+ uint16_t nCount;
+ void *vPtr;
+ uint64_t *subIFDoffsets = NULL;
+ if (TIFFGetField(tif, TIFFTAG_SUBIFD, &nCount, &vPtr))
+ {
+ if (nCount > 0)
+ {
+ subIFDoffsets = malloc(nCount * sizeof(uint64_t));
+ if (subIFDoffsets != NULL)
+ {
+ memcpy(subIFDoffsets, vPtr,
+ nCount * sizeof(subIFDoffsets[0]));
+ printf("--- SubIFD image descriptor tag within "
+ "TIFF directory %d with array of %d "
+ "SubIFD chains ---\n",
+ curdir, nCount);
+ for (int i = 0; i < nCount; i++)
+ {
+ offset = subIFDoffsets[i];
+ int s = 0;
+ if (TIFFSetSubDirectory(tif, offset))
+ {
+ /* print info and check for SubIFD chain
+ */
+ do
+ {
+ printf("--- SubIFD %d of chain %d "
+ "at offset 0x%" PRIx64
+ " (%" PRIu64 "):\n",
+ s, i, offset, offset);
+ tiffinfo(tif, order, flags, 0);
+ s++;
+ } while (TIFFReadDirectory(tif));
+ }
+ }
+ TIFFSetDirectory(tif, curdir);
+ free(subIFDoffsets);
+ subIFDoffsets = NULL;
+ }
+ else
+ {
+ fprintf(stderr,
+ "Error: Could not allocate memory for "
+ "SubIFDs list. SubIFDs not parsed.\n");
+ }
+ }
+ }
+ printf("\n");
+ } while (TIFFReadDirectory(tif));
+ }
+ TIFFClose(tif);
+ }
+ }
+ return (status);
}
static const char usage_info[] =
-"Display information about TIFF files\n\n"
-"usage: tiffinfo [options] input...\n"
-"where options are:\n"
-" -D read data\n"
-" -i ignore read errors\n"
-" -c display data for grey/color response curve or colormap\n"
-" -d display raw/decoded image data\n"
-" -f lsb2msb force lsb-to-msb FillOrder for input\n"
-" -f msb2lsb force msb-to-lsb FillOrder for input\n"
-" -j show JPEG tables\n"
-" -o offset set initial directory offset\n"
-" -r read/display raw image data instead of decoded data\n"
-" -s display strip offsets and byte counts\n"
-" -w display raw data in words rather than bytes\n"
-" -z enable strip chopping\n"
-" -M size set the memory allocation limit in MiB. 0 to disable limit\n"
-" -# set initial directory (first directory is # 0)\n"
-;
-
-static void
-usage(int code)
+ "Display information about TIFF files\n\n"
+ "usage: tiffinfo [options] input...\n"
+ "where options are:\n"
+ " -D read data\n"
+ " -i ignore read errors\n"
+ " -c display data for grey/color response curve or "
+ "colormap\n"
+ " -d display raw/decoded image data\n"
+ " -f lsb2msb force lsb-to-msb FillOrder for input\n"
+ " -f msb2lsb force msb-to-lsb FillOrder for input\n"
+ " -j show JPEG tables\n"
+ " -o offset set initial directory offset\n"
+ " -r read/display raw image data instead of decoded data\n"
+ " -s display strip offsets and byte counts\n"
+ " -w display raw data in words rather than bytes\n"
+ " -z enable strip chopping\n"
+ " -M size set the memory allocation limit in MiB. 0 to disable limit\n"
+ " -# set initial directory (first directory is # 0)\n";
+
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
-static void
-ShowStrip(tstrip_t strip, unsigned char* pp, uint32_t nrow, tsize_t scanline)
+static void ShowStrip(tstrip_t strip, unsigned char *pp, uint32_t nrow,
+ tsize_t scanline)
{
- register tsize_t cc;
-
- printf("Strip %"PRIu32":\n", strip);
- while (nrow-- > 0) {
- for (cc = 0; cc < scanline; cc++) {
- printf(" %02x", *pp++);
- if (((cc+1) % 24) == 0)
- putchar('\n');
- }
- putchar('\n');
- }
+ register tsize_t cc;
+
+ printf("Strip %" PRIu32 ":\n", strip);
+ while (nrow-- > 0)
+ {
+ for (cc = 0; cc < scanline; cc++)
+ {
+ printf(" %02x", *pp++);
+ if (((cc + 1) % 24) == 0)
+ putchar('\n');
+ }
+ putchar('\n');
+ }
}
-void
-TIFFReadContigStripData(TIFF* tif)
+void TIFFReadContigStripData(TIFF *tif)
{
- unsigned char *buf;
- tsize_t scanline = TIFFScanlineSize(tif);
- tmsize_t stripsize = TIFFStripSize(tif);
-
- if (maxMalloc != 0 && stripsize > maxMalloc)
- {
- fprintf(stderr,
- "Memory allocation attempt %" TIFF_SSIZE_FORMAT " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
- stripsize, maxMalloc);
- return;
+ unsigned char *buf;
+ tsize_t scanline = TIFFScanlineSize(tif);
+ tmsize_t stripsize = TIFFStripSize(tif);
+
+ if (maxMalloc != 0 && stripsize > maxMalloc)
+ {
+ fprintf(stderr,
+ "Memory allocation attempt %" TIFF_SSIZE_FORMAT
+ " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
+ stripsize, maxMalloc);
+ return;
+ }
+ buf = (unsigned char *)_TIFFmalloc(stripsize);
+ if (buf)
+ {
+ uint32_t row, h = 0;
+ uint32_t rowsperstrip = (uint32_t)-1;
+
+ TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
+ TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
+ for (row = 0; row < h; row += rowsperstrip)
+ {
+ uint32_t nrow = (row + rowsperstrip > h ? h - row : rowsperstrip);
+ tstrip_t strip = TIFFComputeStrip(tif, row, 0);
+ if (TIFFReadEncodedStrip(tif, strip, buf, nrow * scanline) < 0)
+ {
+ if (stoponerr)
+ break;
+ }
+ else if (showdata)
+ ShowStrip(strip, buf, nrow, scanline);
+ }
+ _TIFFfree(buf);
+ }
+ else
+ {
+ fprintf(stderr, "Cannot allocate %" TIFF_SSIZE_FORMAT " bytes.\n",
+ stripsize);
}
- buf = (unsigned char *)_TIFFmalloc(stripsize);
- if (buf) {
- uint32_t row, h=0;
- uint32_t rowsperstrip = (uint32_t)-1;
-
- TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
- TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
- for (row = 0; row < h; row += rowsperstrip) {
- uint32_t nrow = (row + rowsperstrip > h ?
- h-row : rowsperstrip);
- tstrip_t strip = TIFFComputeStrip(tif, row, 0);
- if (TIFFReadEncodedStrip(tif, strip, buf, nrow*scanline) < 0) {
- if (stoponerr)
- break;
- } else if (showdata)
- ShowStrip(strip, buf, nrow, scanline);
- }
- _TIFFfree(buf);
- }
- else {
- fprintf(stderr, "Cannot allocate %" TIFF_SSIZE_FORMAT " bytes.\n", stripsize);
- }
}
-void
-TIFFReadSeparateStripData(TIFF* tif)
+void TIFFReadSeparateStripData(TIFF *tif)
{
- unsigned char *buf;
- tsize_t scanline = TIFFScanlineSize(tif);
- tmsize_t stripsize = TIFFStripSize(tif);
-
- if (maxMalloc != 0 && stripsize > maxMalloc)
- {
- fprintf(stderr,
- "Memory allocation attempt %" TIFF_SSIZE_FORMAT " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
- stripsize, maxMalloc);
- return;
+ unsigned char *buf;
+ tsize_t scanline = TIFFScanlineSize(tif);
+ tmsize_t stripsize = TIFFStripSize(tif);
+
+ if (maxMalloc != 0 && stripsize > maxMalloc)
+ {
+ fprintf(stderr,
+ "Memory allocation attempt %" TIFF_SSIZE_FORMAT
+ " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
+ stripsize, maxMalloc);
+ return;
+ }
+ buf = (unsigned char *)_TIFFmalloc(stripsize);
+ if (buf)
+ {
+ uint32_t row, h = 0;
+ uint32_t rowsperstrip = (uint32_t)-1;
+ tsample_t s, samplesperpixel = 0;
+
+ TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
+ TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
+ TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
+ for (row = 0; row < h; row += rowsperstrip)
+ {
+ for (s = 0; s < samplesperpixel; s++)
+ {
+ uint32_t nrow =
+ (row + rowsperstrip > h ? h - row : rowsperstrip);
+ tstrip_t strip = TIFFComputeStrip(tif, row, s);
+ if (TIFFReadEncodedStrip(tif, strip, buf, nrow * scanline) < 0)
+ {
+ if (stoponerr)
+ break;
+ }
+ else if (showdata)
+ ShowStrip(strip, buf, nrow, scanline);
+ }
+ }
+ _TIFFfree(buf);
+ }
+ else
+ {
+ fprintf(stderr, "Cannot allocate %" TIFF_SSIZE_FORMAT " bytes.\n",
+ stripsize);
}
- buf = (unsigned char *)_TIFFmalloc(stripsize);
- if (buf) {
- uint32_t row, h=0;
- uint32_t rowsperstrip = (uint32_t)-1;
- tsample_t s, samplesperpixel=0;
-
- TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
- TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
- TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
- for (row = 0; row < h; row += rowsperstrip) {
- for (s = 0; s < samplesperpixel; s++) {
- uint32_t nrow = (row + rowsperstrip > h ?
- h-row : rowsperstrip);
- tstrip_t strip = TIFFComputeStrip(tif, row, s);
- if (TIFFReadEncodedStrip(tif, strip, buf, nrow*scanline) < 0) {
- if (stoponerr)
- break;
- } else if (showdata)
- ShowStrip(strip, buf, nrow, scanline);
- }
- }
- _TIFFfree(buf);
- }
- else {
- fprintf(stderr, "Cannot allocate %" TIFF_SSIZE_FORMAT " bytes.\n", stripsize);
- }
}
-static void
-ShowTile(uint32_t row, uint32_t col, tsample_t sample,
- unsigned char* pp, uint32_t nrow, tsize_t rowsize)
+static void ShowTile(uint32_t row, uint32_t col, tsample_t sample,
+ unsigned char *pp, uint32_t nrow, tsize_t rowsize)
{
- uint32_t cc;
-
- printf("Tile (%" PRIu32 ",%" PRIu32 "", row, col);
- if (sample != (tsample_t) -1)
- printf(",%" PRIu16, sample);
- printf("):\n");
- while (nrow-- > 0) {
- for (cc = 0; cc < (uint32_t) rowsize; cc++) {
- printf(" %02x", *pp++);
- if (((cc+1) % 24) == 0)
- putchar('\n');
- }
- putchar('\n');
- }
+ uint32_t cc;
+
+ printf("Tile (%" PRIu32 ",%" PRIu32 "", row, col);
+ if (sample != (tsample_t)-1)
+ printf(",%" PRIu16, sample);
+ printf("):\n");
+ while (nrow-- > 0)
+ {
+ for (cc = 0; cc < (uint32_t)rowsize; cc++)
+ {
+ printf(" %02x", *pp++);
+ if (((cc + 1) % 24) == 0)
+ putchar('\n');
+ }
+ putchar('\n');
+ }
}
-void
-TIFFReadContigTileData(TIFF* tif)
+void TIFFReadContigTileData(TIFF *tif)
{
- unsigned char *buf;
- tmsize_t rowsize = TIFFTileRowSize(tif);
- tmsize_t tilesize = TIFFTileSize(tif);
-
- if (maxMalloc != 0 && tilesize > maxMalloc)
- {
- fprintf(stderr,
- "Memory allocation attempt %" TIFF_SSIZE_FORMAT " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
- tilesize, maxMalloc);
- return;
+ unsigned char *buf;
+ tmsize_t rowsize = TIFFTileRowSize(tif);
+ tmsize_t tilesize = TIFFTileSize(tif);
+
+ if (maxMalloc != 0 && tilesize > maxMalloc)
+ {
+ fprintf(stderr,
+ "Memory allocation attempt %" TIFF_SSIZE_FORMAT
+ " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
+ tilesize, maxMalloc);
+ return;
}
- buf = (unsigned char *)_TIFFmalloc(tilesize);
- if (buf) {
- uint32_t tw=0, th=0, w=0, h=0;
- uint32_t row, col;
-
- TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
- TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
- TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);
- TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);
- if ( rowsize == 0 || th > (size_t) (tilesize / rowsize) )
+ buf = (unsigned char *)_TIFFmalloc(tilesize);
+ if (buf)
+ {
+ uint32_t tw = 0, th = 0, w = 0, h = 0;
+ uint32_t row, col;
+
+ TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
+ TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
+ TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);
+ TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);
+ if (rowsize == 0 || th > (size_t)(tilesize / rowsize))
{
fprintf(stderr, "Cannot display data: th * rowsize > tilesize\n");
_TIFFfree(buf);
return;
}
- for (row = 0; row < h; row += th) {
- for (col = 0; col < w; col += tw) {
- if (TIFFReadTile(tif, buf, col, row, 0, 0) < 0) {
- if (stoponerr)
- break;
- } else if (showdata)
- ShowTile(row, col, (tsample_t) -1, buf, th, rowsize);
- }
- }
- _TIFFfree(buf);
- }
- else {
- fprintf(stderr, "Cannot allocate %" TIFF_SSIZE_FORMAT " bytes.\n",
+ for (row = 0; row < h; row += th)
+ {
+ for (col = 0; col < w; col += tw)
+ {
+ if (TIFFReadTile(tif, buf, col, row, 0, 0) < 0)
+ {
+ if (stoponerr)
+ break;
+ }
+ else if (showdata)
+ ShowTile(row, col, (tsample_t)-1, buf, th, rowsize);
+ }
+ }
+ _TIFFfree(buf);
+ }
+ else
+ {
+ fprintf(stderr, "Cannot allocate %" TIFF_SSIZE_FORMAT " bytes.\n",
tilesize);
- }
+ }
}
-void
-TIFFReadSeparateTileData(TIFF* tif)
+void TIFFReadSeparateTileData(TIFF *tif)
{
- unsigned char *buf;
- tmsize_t rowsize = TIFFTileRowSize(tif);
- tmsize_t tilesize = TIFFTileSize(tif);
-
- if (maxMalloc != 0 && tilesize > maxMalloc)
- {
- fprintf(stderr,
- "Memory allocation attempt %" TIFF_SSIZE_FORMAT " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
- tilesize, maxMalloc);
- return;
+ unsigned char *buf;
+ tmsize_t rowsize = TIFFTileRowSize(tif);
+ tmsize_t tilesize = TIFFTileSize(tif);
+
+ if (maxMalloc != 0 && tilesize > maxMalloc)
+ {
+ fprintf(stderr,
+ "Memory allocation attempt %" TIFF_SSIZE_FORMAT
+ " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
+ tilesize, maxMalloc);
+ return;
}
- buf = (unsigned char *)_TIFFmalloc(tilesize);
- if (buf) {
- uint32_t tw=0, th=0, w=0, h=0;
- uint32_t row, col;
- tsample_t s, samplesperpixel=0;
-
- TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
- TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
- TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);
- TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);
- TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
- if ( rowsize == 0 || th > (size_t) (tilesize / rowsize) )
+ buf = (unsigned char *)_TIFFmalloc(tilesize);
+ if (buf)
+ {
+ uint32_t tw = 0, th = 0, w = 0, h = 0;
+ uint32_t row, col;
+ tsample_t s, samplesperpixel = 0;
+
+ TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
+ TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
+ TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);
+ TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);
+ TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
+ if (rowsize == 0 || th > (size_t)(tilesize / rowsize))
{
fprintf(stderr, "Cannot display data: th * rowsize > tilesize\n");
_TIFFfree(buf);
return;
}
- for (row = 0; row < h; row += th) {
- for (col = 0; col < w; col += tw) {
- for (s = 0; s < samplesperpixel; s++) {
- if (TIFFReadTile(tif, buf, col, row, 0, s) < 0) {
- if (stoponerr)
- break;
- } else if (showdata)
- ShowTile(row, col, s, buf, th, rowsize);
- }
- }
- }
- _TIFFfree(buf);
- }
- else {
- fprintf(stderr, "Cannot allocate %" TIFF_SSIZE_FORMAT " bytes.\n",
+ for (row = 0; row < h; row += th)
+ {
+ for (col = 0; col < w; col += tw)
+ {
+ for (s = 0; s < samplesperpixel; s++)
+ {
+ if (TIFFReadTile(tif, buf, col, row, 0, s) < 0)
+ {
+ if (stoponerr)
+ break;
+ }
+ else if (showdata)
+ ShowTile(row, col, s, buf, th, rowsize);
+ }
+ }
+ }
+ _TIFFfree(buf);
+ }
+ else
+ {
+ fprintf(stderr, "Cannot allocate %" TIFF_SSIZE_FORMAT " bytes.\n",
tilesize);
- }
+ }
}
-void
-TIFFReadData(TIFF* tif)
+void TIFFReadData(TIFF *tif)
{
- uint16_t config = PLANARCONFIG_CONTIG;
-
- TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &config);
- if (TIFFIsTiled(tif)) {
- if (config == PLANARCONFIG_CONTIG)
- TIFFReadContigTileData(tif);
- else
- TIFFReadSeparateTileData(tif);
- } else {
- if (config == PLANARCONFIG_CONTIG)
- TIFFReadContigStripData(tif);
- else
- TIFFReadSeparateStripData(tif);
- }
+ uint16_t config = PLANARCONFIG_CONTIG;
+
+ TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &config);
+ if (TIFFIsTiled(tif))
+ {
+ if (config == PLANARCONFIG_CONTIG)
+ TIFFReadContigTileData(tif);
+ else
+ TIFFReadSeparateTileData(tif);
+ }
+ else
+ {
+ if (config == PLANARCONFIG_CONTIG)
+ TIFFReadContigStripData(tif);
+ else
+ TIFFReadSeparateStripData(tif);
+ }
}
-static void
-ShowRawBytes(unsigned char* pp, uint32_t n)
+static void ShowRawBytes(unsigned char *pp, uint32_t n)
{
- uint32_t i;
-
- for (i = 0; i < n; i++) {
- printf(" %02x", *pp++);
- if (((i+1) % 24) == 0)
- printf("\n ");
- }
- putchar('\n');
+ uint32_t i;
+
+ for (i = 0; i < n; i++)
+ {
+ printf(" %02x", *pp++);
+ if (((i + 1) % 24) == 0)
+ printf("\n ");
+ }
+ putchar('\n');
}
-static void
-ShowRawWords(uint16_t* pp, uint32_t n)
+static void ShowRawWords(uint16_t *pp, uint32_t n)
{
- uint32_t i;
-
- for (i = 0; i < n; i++) {
- printf(" %04" PRIx16, *pp++);
- if (((i+1) % 15) == 0)
- printf("\n ");
- }
- putchar('\n');
+ uint32_t i;
+
+ for (i = 0; i < n; i++)
+ {
+ printf(" %04" PRIx16, *pp++);
+ if (((i + 1) % 15) == 0)
+ printf("\n ");
+ }
+ putchar('\n');
}
-static void
-TIFFReadRawDataStriped(TIFF* tif, int bitrev)
+static void TIFFReadRawDataStriped(TIFF *tif, int bitrev)
{
- tstrip_t nstrips = TIFFNumberOfStrips(tif);
- const char* what = "Strip";
- uint64_t* stripbc=NULL;
-
- TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &stripbc);
- if (stripbc != NULL && nstrips > 0) {
- uint32_t bufsize = 0;
- tdata_t buf = NULL;
- tstrip_t s;
-
- for (s = 0; s < nstrips; s++) {
- if (stripbc[s] > bufsize || buf == NULL) {
- tdata_t newbuf;
- if (maxMalloc != 0 && stripbc[s] > (uint64_t)maxMalloc)
- {
- fprintf(stderr,
- "Memory allocation attempt %" TIFF_SSIZE_FORMAT " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
- (tmsize_t)stripbc[s], maxMalloc);
- break;
- }
- newbuf = _TIFFrealloc(buf, (tmsize_t)stripbc[s]);
- if (newbuf == NULL) {
- fprintf(stderr,
- "Cannot allocate buffer to read strip %"PRIu32"\n",
- s);
- break;
- }
- bufsize = (uint32_t) stripbc[s];
- buf = newbuf;
- }
- if (TIFFReadRawStrip(tif, s, buf, (tmsize_t) stripbc[s]) < 0) {
- fprintf(stderr, "Error reading strip %"PRIu32"\n",
- s);
- if (stoponerr)
- break;
- } else if (showdata) {
- if (bitrev) {
- TIFFReverseBits(buf, (tmsize_t)stripbc[s]);
- printf("%s %"PRIu32": (bit reversed)\n ",
- what, s);
- } else
- printf("%s %"PRIu32":\n ", what,
- s);
- if (showwords)
- ShowRawWords((uint16_t*) buf, (uint32_t) stripbc[s] >> 1);
- else
- ShowRawBytes((unsigned char*) buf, (uint32_t) stripbc[s]);
- }
- }
- if (buf != NULL)
- _TIFFfree(buf);
- }
+ tstrip_t nstrips = TIFFNumberOfStrips(tif);
+ const char *what = "Strip";
+ uint64_t *stripbc = NULL;
+
+ TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &stripbc);
+ if (stripbc != NULL && nstrips > 0)
+ {
+ uint32_t bufsize = 0;
+ tdata_t buf = NULL;
+ tstrip_t s;
+
+ for (s = 0; s < nstrips; s++)
+ {
+ if (stripbc[s] > bufsize || buf == NULL)
+ {
+ tdata_t newbuf;
+ if (maxMalloc != 0 && stripbc[s] > (uint64_t)maxMalloc)
+ {
+ fprintf(stderr,
+ "Memory allocation attempt %" TIFF_SSIZE_FORMAT
+ " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
+ (tmsize_t)stripbc[s], maxMalloc);
+ break;
+ }
+ newbuf = _TIFFrealloc(buf, (tmsize_t)stripbc[s]);
+ if (newbuf == NULL)
+ {
+ fprintf(stderr,
+ "Cannot allocate buffer to read strip %" PRIu32
+ "\n",
+ s);
+ break;
+ }
+ bufsize = (uint32_t)stripbc[s];
+ buf = newbuf;
+ }
+ if (TIFFReadRawStrip(tif, s, buf, (tmsize_t)stripbc[s]) < 0)
+ {
+ fprintf(stderr, "Error reading strip %" PRIu32 "\n", s);
+ if (stoponerr)
+ break;
+ }
+ else if (showdata)
+ {
+ if (bitrev)
+ {
+ TIFFReverseBits(buf, (tmsize_t)stripbc[s]);
+ printf("%s %" PRIu32 ": (bit reversed)\n ", what, s);
+ }
+ else
+ printf("%s %" PRIu32 ":\n ", what, s);
+ if (showwords)
+ ShowRawWords((uint16_t *)buf, (uint32_t)stripbc[s] >> 1);
+ else
+ ShowRawBytes((unsigned char *)buf, (uint32_t)stripbc[s]);
+ }
+ }
+ if (buf != NULL)
+ _TIFFfree(buf);
+ }
}
-static void
-TIFFReadRawDataTiled(TIFF* tif, int bitrev)
+static void TIFFReadRawDataTiled(TIFF *tif, int bitrev)
{
- const char* what = "Tile";
- uint32_t ntiles = TIFFNumberOfTiles(tif);
- uint64_t *tilebc = NULL;
-
- TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &tilebc);
- if (tilebc != NULL && ntiles > 0) {
- uint64_t bufsize = 0;
- tdata_t buf = NULL;
- uint32_t t;
-
- for (t = 0; t < ntiles; t++) {
- if (tilebc[t] > bufsize || buf == NULL) {
- tdata_t newbuf;
- if (maxMalloc != 0 && tilebc[t] > (uint64_t)maxMalloc)
- {
- fprintf(stderr,
- "Memory allocation attempt %" TIFF_SSIZE_FORMAT " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
- (tmsize_t)tilebc[t], maxMalloc);
- break;
- }
- newbuf = _TIFFrealloc(buf, (tmsize_t)tilebc[t]);
- if (newbuf == NULL) {
- fprintf(stderr,
- "Cannot allocate buffer to read tile %"PRIu32"\n",
- t);
- break;
- }
- bufsize = (uint32_t) tilebc[t];
- buf = newbuf;
- }
- if (TIFFReadRawTile(tif, t, buf, (tmsize_t)tilebc[t]) < 0) {
- fprintf(stderr, "Error reading tile %"PRIu32"\n",
- t);
- if (stoponerr)
- break;
- } else if (showdata) {
- if (bitrev) {
- TIFFReverseBits(buf, (tmsize_t)tilebc[t]);
- printf("%s %"PRIu32": (bit reversed)\n ",
- what, t);
- } else {
- printf("%s %"PRIu32":\n ", what,
- t);
- }
- if (showwords) {
- ShowRawWords((uint16_t*) buf, (uint32_t)(tilebc[t] >> 1));
- } else {
- ShowRawBytes((unsigned char*) buf, (uint32_t) tilebc[t]);
- }
- }
- }
- if (buf != NULL)
- _TIFFfree(buf);
- }
+ const char *what = "Tile";
+ uint32_t ntiles = TIFFNumberOfTiles(tif);
+ uint64_t *tilebc = NULL;
+
+ TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &tilebc);
+ if (tilebc != NULL && ntiles > 0)
+ {
+ uint64_t bufsize = 0;
+ tdata_t buf = NULL;
+ uint32_t t;
+
+ for (t = 0; t < ntiles; t++)
+ {
+ if (tilebc[t] > bufsize || buf == NULL)
+ {
+ tdata_t newbuf;
+ if (maxMalloc != 0 && tilebc[t] > (uint64_t)maxMalloc)
+ {
+ fprintf(stderr,
+ "Memory allocation attempt %" TIFF_SSIZE_FORMAT
+ " over memory limit (%" TIFF_SSIZE_FORMAT ")\n",
+ (tmsize_t)tilebc[t], maxMalloc);
+ break;
+ }
+ newbuf = _TIFFrealloc(buf, (tmsize_t)tilebc[t]);
+ if (newbuf == NULL)
+ {
+ fprintf(stderr,
+ "Cannot allocate buffer to read tile %" PRIu32 "\n",
+ t);
+ break;
+ }
+ bufsize = (uint32_t)tilebc[t];
+ buf = newbuf;
+ }
+ if (TIFFReadRawTile(tif, t, buf, (tmsize_t)tilebc[t]) < 0)
+ {
+ fprintf(stderr, "Error reading tile %" PRIu32 "\n", t);
+ if (stoponerr)
+ break;
+ }
+ else if (showdata)
+ {
+ if (bitrev)
+ {
+ TIFFReverseBits(buf, (tmsize_t)tilebc[t]);
+ printf("%s %" PRIu32 ": (bit reversed)\n ", what, t);
+ }
+ else
+ {
+ printf("%s %" PRIu32 ":\n ", what, t);
+ }
+ if (showwords)
+ {
+ ShowRawWords((uint16_t *)buf, (uint32_t)(tilebc[t] >> 1));
+ }
+ else
+ {
+ ShowRawBytes((unsigned char *)buf, (uint32_t)tilebc[t]);
+ }
+ }
+ }
+ if (buf != NULL)
+ _TIFFfree(buf);
+ }
}
-void
-TIFFReadRawData(TIFF* tif, int bitrev)
+void TIFFReadRawData(TIFF *tif, int bitrev)
{
- if (TIFFIsTiled(tif)) {
- TIFFReadRawDataTiled(tif, bitrev);
- } else {
- TIFFReadRawDataStriped(tif, bitrev);
- }
+ if (TIFFIsTiled(tif))
+ {
+ TIFFReadRawDataTiled(tif, bitrev);
+ }
+ else
+ {
+ TIFFReadRawDataStriped(tif, bitrev);
+ }
}
-static void
-tiffinfo(TIFF* tif, uint16_t order, long flags, int is_image)
+static void tiffinfo(TIFF *tif, uint16_t order, long flags, int is_image)
{
- TIFFPrintDirectory(tif, stdout, flags);
- if (!readdata || !is_image)
- return;
- if (rawdata) {
- if (order) {
- uint16_t o;
- TIFFGetFieldDefaulted(tif,
- TIFFTAG_FILLORDER, &o);
- TIFFReadRawData(tif, o != order);
- } else
- TIFFReadRawData(tif, 0);
- } else {
- if (order)
- TIFFSetField(tif, TIFFTAG_FILLORDER, order);
- TIFFReadData(tif);
- }
+ TIFFPrintDirectory(tif, stdout, flags);
+ if (!readdata || !is_image)
+ return;
+ if (rawdata)
+ {
+ if (order)
+ {
+ uint16_t o;
+ TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &o);
+ TIFFReadRawData(tif, o != order);
+ }
+ else
+ TIFFReadRawData(tif, 0);
+ }
+ else
+ {
+ if (order)
+ TIFFSetField(tif, TIFFTAG_FILLORDER, order);
+ TIFFReadData(tif);
+ }
}
diff --git a/tools/tiffmedian.c b/tools/tiffmedian.c
index 259525dd..8225970c 100644
--- a/tools/tiffmedian.c
+++ b/tools/tiffmedian.c
@@ -4,7 +4,7 @@
* tiffmedian [-c n] [-f] input output
* -C n - set colortable size. Default is 256.
* -f - use Floyd-Steinberg dithering.
- * -c lzw - compress output with LZW
+ * -c lzw - compress output with LZW
* -c none - use no compression on output
* -c packbits - use packbits compression on output
* -r n - create output with n rows/strip of data
@@ -18,7 +18,7 @@
* you are at X, moving left to right:
*
* X 7/16
- * 3/16 5/16 1/16
+ * 3/16 5/16 1/16
*
* Note that the error goes to four neighbors, not three. I think this
* will probably do better (at least for black and white) than the
@@ -31,22 +31,22 @@
* half the error one pixel ahead (e.g. to the right on lines you scan
* left to right), and half one pixel straight down. Again, this is for
* black and white; I've not tried it with color.
- * --
+ * --
* Lou Steinberg
*
* [2] Color Image Quantization for Frame Buffer Display, Paul Heckbert,
* Siggraph '82 proceedings, pp. 297-307
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
#endif
#include "tiffio.h"
@@ -58,714 +58,767 @@
#define EXIT_FAILURE 1
#endif
-#define MAX_CMAP_SIZE 256
+#define MAX_CMAP_SIZE 256
-#define streq(a,b) (strcmp(a,b) == 0)
-#define strneq(a,b,n) (strncmp(a,b,n) == 0)
+#define streq(a, b) (strcmp(a, b) == 0)
+#define strneq(a, b, n) (strncmp(a, b, n) == 0)
-#define COLOR_DEPTH 8
-#define MAX_COLOR 256
+#define COLOR_DEPTH 8
+#define MAX_COLOR 256
-#define B_DEPTH 5 /* # bits/pixel to use */
-#define B_LEN (1L<<B_DEPTH)
+#define B_DEPTH 5 /* # bits/pixel to use */
+#define B_LEN (1L << B_DEPTH)
-#define C_DEPTH 2
-#define C_LEN (1L<<C_DEPTH) /* # cells/color to use */
+#define C_DEPTH 2
+#define C_LEN (1L << C_DEPTH) /* # cells/color to use */
-#define COLOR_SHIFT (COLOR_DEPTH-B_DEPTH)
+#define COLOR_SHIFT (COLOR_DEPTH - B_DEPTH)
-typedef struct colorbox {
- struct colorbox *next, *prev;
- int rmin, rmax;
- int gmin, gmax;
- int bmin, bmax;
- uint32_t total;
+typedef struct colorbox
+{
+ struct colorbox *next, *prev;
+ int rmin, rmax;
+ int gmin, gmax;
+ int bmin, bmax;
+ uint32_t total;
} Colorbox;
-typedef struct {
- int num_ents;
- int entries[MAX_CMAP_SIZE][2];
+typedef struct
+{
+ int num_ents;
+ int entries[MAX_CMAP_SIZE][2];
} C_cell;
-static uint16_t rm[MAX_CMAP_SIZE], gm[MAX_CMAP_SIZE], bm[MAX_CMAP_SIZE];
-static int num_colors;
-static uint32_t histogram[B_LEN][B_LEN][B_LEN];
+static uint16_t rm[MAX_CMAP_SIZE], gm[MAX_CMAP_SIZE], bm[MAX_CMAP_SIZE];
+static int num_colors;
+static uint32_t histogram[B_LEN][B_LEN][B_LEN];
static Colorbox *freeboxes;
static Colorbox *usedboxes;
-static C_cell **ColorCells;
-static TIFF *in, *out;
-static uint32_t rowsperstrip = (uint32_t) -1;
-static uint16_t compression = (uint16_t) -1;
-static uint16_t bitspersample = 1;
-static uint16_t samplesperpixel;
-static uint32_t imagewidth;
-static uint32_t imagelength;
-static uint16_t predictor = 0;
-
-static void get_histogram(TIFF*, Colorbox*);
-static void splitbox(Colorbox*);
-static void shrinkbox(Colorbox*);
-static void map_colortable(void);
-static void quant(TIFF*, TIFF*);
-static void quant_fsdither(TIFF*, TIFF*);
-static Colorbox* largest_box(void);
-
-static void usage(int);
-static int processCompressOptions(char*);
-
-#define CopyField(tag, v) \
- if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
-
-int
-main(int argc, char* argv[])
+static C_cell **ColorCells;
+static TIFF *in, *out;
+static uint32_t rowsperstrip = (uint32_t)-1;
+static uint16_t compression = (uint16_t)-1;
+static uint16_t bitspersample = 1;
+static uint16_t samplesperpixel;
+static uint32_t imagewidth;
+static uint32_t imagelength;
+static uint16_t predictor = 0;
+
+static void get_histogram(TIFF *, Colorbox *);
+static void splitbox(Colorbox *);
+static void shrinkbox(Colorbox *);
+static void map_colortable(void);
+static void quant(TIFF *, TIFF *);
+static void quant_fsdither(TIFF *, TIFF *);
+static Colorbox *largest_box(void);
+
+static void usage(int);
+static int processCompressOptions(char *);
+
+#define CopyField(tag, v) \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v)
+
+int main(int argc, char *argv[])
{
- int i, dither = 0;
- uint16_t shortv, config, photometric;
- Colorbox *box_list, *ptr;
- float floatv;
- uint32_t longv;
- int c;
+ int i, dither = 0;
+ uint16_t shortv, config, photometric;
+ Colorbox *box_list, *ptr;
+ float floatv;
+ uint32_t longv;
+ int c;
#if !HAVE_DECL_OPTARG
- extern int optind;
- extern char* optarg;
+ extern int optind;
+ extern char *optarg;
#endif
- num_colors = MAX_CMAP_SIZE;
- while ((c = getopt(argc, argv, "c:C:r:fh")) != -1)
- switch (c) {
- case 'c': /* compression scheme */
- if (!processCompressOptions(optarg))
- usage(EXIT_FAILURE);
- break;
- case 'C': /* set colormap size */
- num_colors = atoi(optarg);
- if (num_colors > MAX_CMAP_SIZE) {
- fprintf(stderr,
- "-c: colormap too big, max %d\n",
- MAX_CMAP_SIZE);
- usage(EXIT_FAILURE);
- }
- break;
- case 'f': /* dither */
- dither = 1;
- break;
- case 'r': /* rows/strip */
- rowsperstrip = atoi(optarg);
- break;
- case 'h':
- usage(EXIT_SUCCESS);
- /*NOTREACHED*/
- break;
- case '?':
- usage(EXIT_FAILURE);
- /*NOTREACHED*/
- break;
- }
- if (argc - optind != 2)
- usage(EXIT_FAILURE);
- in = TIFFOpen(argv[optind], "r");
- if (in == NULL)
- return (EXIT_FAILURE);
- TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &imagewidth);
- TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength);
- TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
- TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
- if (bitspersample != 8 && bitspersample != 16) {
- fprintf(stderr, "%s: Image must have at least 8-bits/sample\n",
- argv[optind]);
- return (EXIT_FAILURE);
- }
- if (!TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric) ||
- photometric != PHOTOMETRIC_RGB || samplesperpixel < 3) {
- fprintf(stderr, "%s: Image must have RGB data\n", argv[optind]);
- return (EXIT_FAILURE);
- }
- TIFFGetField(in, TIFFTAG_PLANARCONFIG, &config);
- if (config != PLANARCONFIG_CONTIG) {
- fprintf(stderr, "%s: Can only handle contiguous data packing\n",
- argv[optind]);
- return (EXIT_FAILURE);
- }
-
- /*
- * STEP 1: create empty boxes
- */
- usedboxes = NULL;
- box_list = freeboxes = (Colorbox *)_TIFFmalloc(num_colors*sizeof (Colorbox));
- freeboxes[0].next = &freeboxes[1];
- freeboxes[0].prev = NULL;
- for (i = 1; i < num_colors-1; ++i) {
- freeboxes[i].next = &freeboxes[i+1];
- freeboxes[i].prev = &freeboxes[i-1];
- }
- freeboxes[num_colors-1].next = NULL;
- freeboxes[num_colors-1].prev = &freeboxes[num_colors-2];
-
- /*
- * STEP 2: get histogram, initialize first box
- */
- ptr = freeboxes;
- freeboxes = ptr->next;
- if (freeboxes)
- freeboxes->prev = NULL;
- ptr->next = usedboxes;
- usedboxes = ptr;
- if (ptr->next)
- ptr->next->prev = ptr;
- get_histogram(in, ptr);
-
- /*
- * STEP 3: continually subdivide boxes until no more free
- * boxes remain or until all colors assigned.
- */
- while (freeboxes != NULL) {
- ptr = largest_box();
- if (ptr != NULL)
- splitbox(ptr);
- else
- freeboxes = NULL;
- }
-
- /*
- * STEP 4: assign colors to all boxes
- */
- for (i = 0, ptr = usedboxes; ptr != NULL; ++i, ptr = ptr->next) {
- rm[i] = ((ptr->rmin + ptr->rmax) << COLOR_SHIFT) / 2;
- gm[i] = ((ptr->gmin + ptr->gmax) << COLOR_SHIFT) / 2;
- bm[i] = ((ptr->bmin + ptr->bmax) << COLOR_SHIFT) / 2;
- }
-
- /* We're done with the boxes now */
- _TIFFfree(box_list);
- freeboxes = usedboxes = NULL;
-
- /*
- * STEP 5: scan histogram and map all values to closest color
- */
- /* 5a: create cell list as described in Heckbert[2] */
- ColorCells = (C_cell **)_TIFFmalloc(C_LEN*C_LEN*C_LEN*sizeof (C_cell*));
- _TIFFmemset(ColorCells, 0, C_LEN*C_LEN*C_LEN*sizeof (C_cell*));
- /* 5b: create mapping from truncated pixel space to color
- table entries */
- map_colortable();
-
- /*
- * STEP 6: scan image, match input values to table entries
- */
- out = TIFFOpen(argv[optind+1], "w");
- if (out == NULL)
- return (EXIT_FAILURE);
-
- CopyField(TIFFTAG_SUBFILETYPE, longv);
- CopyField(TIFFTAG_IMAGEWIDTH, longv);
- TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, (short)COLOR_DEPTH);
- if (compression != (uint16_t)-1) {
- TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
- switch (compression) {
- case COMPRESSION_LZW:
- case COMPRESSION_ADOBE_DEFLATE:
- case COMPRESSION_DEFLATE:
- if (predictor != 0)
- TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
- break;
- }
- } else
- CopyField(TIFFTAG_COMPRESSION, compression);
- TIFFSetField(out, TIFFTAG_PHOTOMETRIC, (short)PHOTOMETRIC_PALETTE);
- CopyField(TIFFTAG_ORIENTATION, shortv);
- TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, (short)1);
- CopyField(TIFFTAG_PLANARCONFIG, shortv);
- TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
- TIFFDefaultStripSize(out, rowsperstrip));
- CopyField(TIFFTAG_MINSAMPLEVALUE, shortv);
- CopyField(TIFFTAG_MAXSAMPLEVALUE, shortv);
- CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
- CopyField(TIFFTAG_XRESOLUTION, floatv);
- CopyField(TIFFTAG_YRESOLUTION, floatv);
- CopyField(TIFFTAG_XPOSITION, floatv);
- CopyField(TIFFTAG_YPOSITION, floatv);
-
- if (dither)
- quant_fsdither(in, out);
- else
- quant(in, out);
- /*
- * Scale colormap to TIFF-required 16-bit values.
- */
-#define SCALE(x) (((x)*((1L<<16)-1))/255)
- for (i = 0; i < MAX_CMAP_SIZE; ++i) {
- rm[i] = SCALE(rm[i]);
- gm[i] = SCALE(gm[i]);
- bm[i] = SCALE(bm[i]);
- }
- TIFFSetField(out, TIFFTAG_COLORMAP, rm, gm, bm);
- (void) TIFFClose(out);
- return (EXIT_SUCCESS);
+ num_colors = MAX_CMAP_SIZE;
+ while ((c = getopt(argc, argv, "c:C:r:fh")) != -1)
+ switch (c)
+ {
+ case 'c': /* compression scheme */
+ if (!processCompressOptions(optarg))
+ usage(EXIT_FAILURE);
+ break;
+ case 'C': /* set colormap size */
+ num_colors = atoi(optarg);
+ if (num_colors > MAX_CMAP_SIZE)
+ {
+ fprintf(stderr, "-c: colormap too big, max %d\n",
+ MAX_CMAP_SIZE);
+ usage(EXIT_FAILURE);
+ }
+ break;
+ case 'f': /* dither */
+ dither = 1;
+ break;
+ case 'r': /* rows/strip */
+ rowsperstrip = atoi(optarg);
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ /*NOTREACHED*/
+ break;
+ case '?':
+ usage(EXIT_FAILURE);
+ /*NOTREACHED*/
+ break;
+ }
+ if (argc - optind != 2)
+ usage(EXIT_FAILURE);
+ in = TIFFOpen(argv[optind], "r");
+ if (in == NULL)
+ return (EXIT_FAILURE);
+ TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &imagewidth);
+ TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength);
+ TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
+ TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
+ if (bitspersample != 8 && bitspersample != 16)
+ {
+ fprintf(stderr, "%s: Image must have at least 8-bits/sample\n",
+ argv[optind]);
+ return (EXIT_FAILURE);
+ }
+ if (!TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric) ||
+ photometric != PHOTOMETRIC_RGB || samplesperpixel < 3)
+ {
+ fprintf(stderr, "%s: Image must have RGB data\n", argv[optind]);
+ return (EXIT_FAILURE);
+ }
+ TIFFGetField(in, TIFFTAG_PLANARCONFIG, &config);
+ if (config != PLANARCONFIG_CONTIG)
+ {
+ fprintf(stderr, "%s: Can only handle contiguous data packing\n",
+ argv[optind]);
+ return (EXIT_FAILURE);
+ }
+
+ /*
+ * STEP 1: create empty boxes
+ */
+ usedboxes = NULL;
+ box_list = freeboxes =
+ (Colorbox *)_TIFFmalloc(num_colors * sizeof(Colorbox));
+ freeboxes[0].next = &freeboxes[1];
+ freeboxes[0].prev = NULL;
+ for (i = 1; i < num_colors - 1; ++i)
+ {
+ freeboxes[i].next = &freeboxes[i + 1];
+ freeboxes[i].prev = &freeboxes[i - 1];
+ }
+ freeboxes[num_colors - 1].next = NULL;
+ freeboxes[num_colors - 1].prev = &freeboxes[num_colors - 2];
+
+ /*
+ * STEP 2: get histogram, initialize first box
+ */
+ ptr = freeboxes;
+ freeboxes = ptr->next;
+ if (freeboxes)
+ freeboxes->prev = NULL;
+ ptr->next = usedboxes;
+ usedboxes = ptr;
+ if (ptr->next)
+ ptr->next->prev = ptr;
+ get_histogram(in, ptr);
+
+ /*
+ * STEP 3: continually subdivide boxes until no more free
+ * boxes remain or until all colors assigned.
+ */
+ while (freeboxes != NULL)
+ {
+ ptr = largest_box();
+ if (ptr != NULL)
+ splitbox(ptr);
+ else
+ freeboxes = NULL;
+ }
+
+ /*
+ * STEP 4: assign colors to all boxes
+ */
+ for (i = 0, ptr = usedboxes; ptr != NULL; ++i, ptr = ptr->next)
+ {
+ rm[i] = ((ptr->rmin + ptr->rmax) << COLOR_SHIFT) / 2;
+ gm[i] = ((ptr->gmin + ptr->gmax) << COLOR_SHIFT) / 2;
+ bm[i] = ((ptr->bmin + ptr->bmax) << COLOR_SHIFT) / 2;
+ }
+
+ /* We're done with the boxes now */
+ _TIFFfree(box_list);
+ freeboxes = usedboxes = NULL;
+
+ /*
+ * STEP 5: scan histogram and map all values to closest color
+ */
+ /* 5a: create cell list as described in Heckbert[2] */
+ ColorCells =
+ (C_cell **)_TIFFmalloc(C_LEN * C_LEN * C_LEN * sizeof(C_cell *));
+ _TIFFmemset(ColorCells, 0, C_LEN * C_LEN * C_LEN * sizeof(C_cell *));
+ /* 5b: create mapping from truncated pixel space to color
+ table entries */
+ map_colortable();
+
+ /*
+ * STEP 6: scan image, match input values to table entries
+ */
+ out = TIFFOpen(argv[optind + 1], "w");
+ if (out == NULL)
+ return (EXIT_FAILURE);
+
+ CopyField(TIFFTAG_SUBFILETYPE, longv);
+ CopyField(TIFFTAG_IMAGEWIDTH, longv);
+ TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, (short)COLOR_DEPTH);
+ if (compression != (uint16_t)-1)
+ {
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
+ switch (compression)
+ {
+ case COMPRESSION_LZW:
+ case COMPRESSION_ADOBE_DEFLATE:
+ case COMPRESSION_DEFLATE:
+ if (predictor != 0)
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
+ break;
+ }
+ }
+ else
+ CopyField(TIFFTAG_COMPRESSION, compression);
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, (short)PHOTOMETRIC_PALETTE);
+ CopyField(TIFFTAG_ORIENTATION, shortv);
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, (short)1);
+ CopyField(TIFFTAG_PLANARCONFIG, shortv);
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
+ TIFFDefaultStripSize(out, rowsperstrip));
+ CopyField(TIFFTAG_MINSAMPLEVALUE, shortv);
+ CopyField(TIFFTAG_MAXSAMPLEVALUE, shortv);
+ CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
+ CopyField(TIFFTAG_XRESOLUTION, floatv);
+ CopyField(TIFFTAG_YRESOLUTION, floatv);
+ CopyField(TIFFTAG_XPOSITION, floatv);
+ CopyField(TIFFTAG_YPOSITION, floatv);
+
+ if (dither)
+ quant_fsdither(in, out);
+ else
+ quant(in, out);
+ /*
+ * Scale colormap to TIFF-required 16-bit values.
+ */
+#define SCALE(x) (((x) * ((1L << 16) - 1)) / 255)
+ for (i = 0; i < MAX_CMAP_SIZE; ++i)
+ {
+ rm[i] = SCALE(rm[i]);
+ gm[i] = SCALE(gm[i]);
+ bm[i] = SCALE(bm[i]);
+ }
+ TIFFSetField(out, TIFFTAG_COLORMAP, rm, gm, bm);
+ (void)TIFFClose(out);
+ return (EXIT_SUCCESS);
}
-static int
-processCompressOptions(char* opt)
+static int processCompressOptions(char *opt)
{
- if (streq(opt, "none"))
- compression = COMPRESSION_NONE;
- else if (streq(opt, "packbits"))
- compression = COMPRESSION_PACKBITS;
- else if (strneq(opt, "lzw", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_LZW;
- } else if (strneq(opt, "zip", 3)) {
- char* cp = strchr(opt, ':');
- if (cp)
- predictor = atoi(cp+1);
- compression = COMPRESSION_ADOBE_DEFLATE;
- } else
- return (0);
- return (1);
+ if (streq(opt, "none"))
+ compression = COMPRESSION_NONE;
+ else if (streq(opt, "packbits"))
+ compression = COMPRESSION_PACKBITS;
+ else if (strneq(opt, "lzw", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_LZW;
+ }
+ else if (strneq(opt, "zip", 3))
+ {
+ char *cp = strchr(opt, ':');
+ if (cp)
+ predictor = atoi(cp + 1);
+ compression = COMPRESSION_ADOBE_DEFLATE;
+ }
+ else
+ return (0);
+ return (1);
}
static const char usage_info[] =
-"Apply the median cut algorithm to an RGB TIFF file\n\n"
-"usage: tiffmedian [options] input.tif output.tif\n"
-"where options are:\n"
-" -r # make each strip have no more than # rows\n"
-" -C # create a colormap with # entries\n"
-" -f use Floyd-Steinberg dithering\n"
-"\n"
+ "Apply the median cut algorithm to an RGB TIFF file\n\n"
+ "usage: tiffmedian [options] input.tif output.tif\n"
+ "where options are:\n"
+ " -r # make each strip have no more than # rows\n"
+ " -C # create a colormap with # entries\n"
+ " -f use Floyd-Steinberg dithering\n"
+ "\n"
#ifdef LZW_SUPPORT
-" -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
-/* " LZW options:" */
-" # set predictor value\n"
-" For example, -c lzw:2 to get LZW-encoded data with horizontal differencing\n"
+ " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding\n"
+ /* " LZW options:" */
+ " # set predictor value\n"
+ " For example, -c lzw:2 to get LZW-encoded data with horizontal "
+ "differencing\n"
#endif
#ifdef ZIP_SUPPORT
-" -c zip[:opts] compress output with deflate encoding\n"
-/* " Deflate (ZIP) options:" */
-" # set predictor value\n"
+ " -c zip[:opts] compress output with deflate encoding\n"
+ /* " Deflate (ZIP) options:" */
+ " # set predictor value\n"
#endif
#ifdef PACKBITS_SUPPORT
-" -c packbits compress output with packbits encoding\n"
+ " -c packbits compress output with packbits encoding\n"
#endif
#if defined(LZW_SUPPORT) || defined(ZIP_SUPPORT) || defined(PACKBITS_SUPPORT)
-" -c none use no compression algorithm on output\n"
+ " -c none use no compression algorithm on output\n"
#endif
-"\n"
-;
+ "\n";
-static void
-usage(int code)
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usage_info);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usage_info);
+ exit(code);
}
-static void
-get_histogram(TIFF* in, Colorbox* box)
+static void get_histogram(TIFF *in, Colorbox *box)
{
- register unsigned char *inptr;
- register int red, green, blue;
- register uint32_t j, i;
- unsigned char *inputline;
-
- inputline = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
- if (inputline == NULL) {
- fprintf(stderr, "No space for scanline buffer\n");
- exit(EXIT_FAILURE);
- }
- box->rmin = box->gmin = box->bmin = 999;
- box->rmax = box->gmax = box->bmax = -1;
- box->total = imagewidth * imagelength;
-
- { register uint32_t *ptr = &histogram[0][0][0];
- for (i = B_LEN*B_LEN*B_LEN; i-- > 0;)
- *ptr++ = 0;
- }
- for (i = 0; i < imagelength; i++) {
- if (TIFFReadScanline(in, inputline, i, 0) <= 0)
- break;
- inptr = inputline;
- for (j = imagewidth; j-- > 0;) {
- red = (*inptr++) & 0xff >> COLOR_SHIFT;
- green = (*inptr++) & 0xff >> COLOR_SHIFT;
- blue = (*inptr++) & 0xff >> COLOR_SHIFT;
- if ((red | green | blue) >= B_LEN) {
- fprintf(stderr,
- "Logic error. "
- "Histogram array overflow!\n");
- exit(EXIT_FAILURE);
- }
- if (red < box->rmin)
- box->rmin = red;
- if (red > box->rmax)
- box->rmax = red;
- if (green < box->gmin)
- box->gmin = green;
- if (green > box->gmax)
- box->gmax = green;
- if (blue < box->bmin)
- box->bmin = blue;
- if (blue > box->bmax)
- box->bmax = blue;
- histogram[red][green][blue]++;
- }
- }
- _TIFFfree(inputline);
+ register unsigned char *inptr;
+ register int red, green, blue;
+ register uint32_t j, i;
+ unsigned char *inputline;
+
+ inputline = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
+ if (inputline == NULL)
+ {
+ fprintf(stderr, "No space for scanline buffer\n");
+ exit(EXIT_FAILURE);
+ }
+ box->rmin = box->gmin = box->bmin = 999;
+ box->rmax = box->gmax = box->bmax = -1;
+ box->total = imagewidth * imagelength;
+
+ {
+ register uint32_t *ptr = &histogram[0][0][0];
+ for (i = B_LEN * B_LEN * B_LEN; i-- > 0;)
+ *ptr++ = 0;
+ }
+ for (i = 0; i < imagelength; i++)
+ {
+ if (TIFFReadScanline(in, inputline, i, 0) <= 0)
+ break;
+ inptr = inputline;
+ for (j = imagewidth; j-- > 0;)
+ {
+ red = (*inptr++) & 0xff >> COLOR_SHIFT;
+ green = (*inptr++) & 0xff >> COLOR_SHIFT;
+ blue = (*inptr++) & 0xff >> COLOR_SHIFT;
+ if ((red | green | blue) >= B_LEN)
+ {
+ fprintf(stderr, "Logic error. "
+ "Histogram array overflow!\n");
+ exit(EXIT_FAILURE);
+ }
+ if (red < box->rmin)
+ box->rmin = red;
+ if (red > box->rmax)
+ box->rmax = red;
+ if (green < box->gmin)
+ box->gmin = green;
+ if (green > box->gmax)
+ box->gmax = green;
+ if (blue < box->bmin)
+ box->bmin = blue;
+ if (blue > box->bmax)
+ box->bmax = blue;
+ histogram[red][green][blue]++;
+ }
+ }
+ _TIFFfree(inputline);
}
-static Colorbox *
-largest_box(void)
+static Colorbox *largest_box(void)
{
- register Colorbox *p, *b;
- register uint32_t size;
-
- b = NULL;
- size = 0;
- for (p = usedboxes; p != NULL; p = p->next)
- if ((p->rmax > p->rmin || p->gmax > p->gmin ||
- p->bmax > p->bmin) && p->total > size)
- size = (b = p)->total;
- return (b);
+ register Colorbox *p, *b;
+ register uint32_t size;
+
+ b = NULL;
+ size = 0;
+ for (p = usedboxes; p != NULL; p = p->next)
+ if ((p->rmax > p->rmin || p->gmax > p->gmin || p->bmax > p->bmin) &&
+ p->total > size)
+ size = (b = p)->total;
+ return (b);
}
-static void
-splitbox(Colorbox* ptr)
+static void splitbox(Colorbox *ptr)
{
- uint32_t hist2[B_LEN];
- int first=0, last=0;
- register Colorbox *new;
- register uint32_t *iptr, *histp;
- register int i, j;
- register int ir,ig,ib;
- register uint32_t sum, sum1, sum2;
- enum { RED, GREEN, BLUE } axis;
-
- /*
- * See which axis is the largest, do a histogram along that
- * axis. Split at median point. Contract both new boxes to
- * fit points and return
- */
- i = ptr->rmax - ptr->rmin;
- if (i >= ptr->gmax - ptr->gmin && i >= ptr->bmax - ptr->bmin)
- axis = RED;
- else if (ptr->gmax - ptr->gmin >= ptr->bmax - ptr->bmin)
- axis = GREEN;
- else
- axis = BLUE;
- /* get histogram along longest axis */
- switch (axis) {
- case RED:
- histp = &hist2[ptr->rmin];
- for (ir = ptr->rmin; ir <= ptr->rmax; ++ir) {
- *histp = 0;
- for (ig = ptr->gmin; ig <= ptr->gmax; ++ig) {
- iptr = &histogram[ir][ig][ptr->bmin];
- for (ib = ptr->bmin; ib <= ptr->bmax; ++ib)
- *histp += *iptr++;
- }
- histp++;
- }
- first = ptr->rmin;
- last = ptr->rmax;
- break;
- case GREEN:
- histp = &hist2[ptr->gmin];
- for (ig = ptr->gmin; ig <= ptr->gmax; ++ig) {
- *histp = 0;
- for (ir = ptr->rmin; ir <= ptr->rmax; ++ir) {
- iptr = &histogram[ir][ig][ptr->bmin];
- for (ib = ptr->bmin; ib <= ptr->bmax; ++ib)
- *histp += *iptr++;
- }
- histp++;
- }
- first = ptr->gmin;
- last = ptr->gmax;
- break;
- case BLUE:
- histp = &hist2[ptr->bmin];
- for (ib = ptr->bmin; ib <= ptr->bmax; ++ib) {
- *histp = 0;
- for (ir = ptr->rmin; ir <= ptr->rmax; ++ir) {
- iptr = &histogram[ir][ptr->gmin][ib];
- for (ig = ptr->gmin; ig <= ptr->gmax; ++ig) {
- *histp += *iptr;
- iptr += B_LEN;
- }
- }
- histp++;
- }
- first = ptr->bmin;
- last = ptr->bmax;
- break;
- }
- /* find median point */
- sum2 = ptr->total / 2;
- histp = &hist2[first];
- sum = 0;
- for (i = first; i <= last && (sum += *histp++) < sum2; ++i)
- ;
- if (i == first)
- i++;
-
- /* Create new box, re-allocate points */
- new = freeboxes;
- freeboxes = new->next;
- if (freeboxes)
- freeboxes->prev = NULL;
- if (usedboxes)
- usedboxes->prev = new;
- new->next = usedboxes;
- usedboxes = new;
-
- histp = &hist2[first];
- for (sum1 = 0, j = first; j < i; j++)
- sum1 += *histp++;
- for (sum2 = 0, j = i; j <= last; j++)
- sum2 += *histp++;
- new->total = sum1;
- ptr->total = sum2;
-
- new->rmin = ptr->rmin;
- new->rmax = ptr->rmax;
- new->gmin = ptr->gmin;
- new->gmax = ptr->gmax;
- new->bmin = ptr->bmin;
- new->bmax = ptr->bmax;
- switch (axis) {
- case RED:
- new->rmax = i-1;
- ptr->rmin = i;
- break;
- case GREEN:
- new->gmax = i-1;
- ptr->gmin = i;
- break;
- case BLUE:
- new->bmax = i-1;
- ptr->bmin = i;
- break;
- }
- shrinkbox(new);
- shrinkbox(ptr);
+ uint32_t hist2[B_LEN];
+ int first = 0, last = 0;
+ register Colorbox *new;
+ register uint32_t *iptr, *histp;
+ register int i, j;
+ register int ir, ig, ib;
+ register uint32_t sum, sum1, sum2;
+ enum
+ {
+ RED,
+ GREEN,
+ BLUE
+ } axis;
+
+ /*
+ * See which axis is the largest, do a histogram along that
+ * axis. Split at median point. Contract both new boxes to
+ * fit points and return
+ */
+ i = ptr->rmax - ptr->rmin;
+ if (i >= ptr->gmax - ptr->gmin && i >= ptr->bmax - ptr->bmin)
+ axis = RED;
+ else if (ptr->gmax - ptr->gmin >= ptr->bmax - ptr->bmin)
+ axis = GREEN;
+ else
+ axis = BLUE;
+ /* get histogram along longest axis */
+ switch (axis)
+ {
+ case RED:
+ histp = &hist2[ptr->rmin];
+ for (ir = ptr->rmin; ir <= ptr->rmax; ++ir)
+ {
+ *histp = 0;
+ for (ig = ptr->gmin; ig <= ptr->gmax; ++ig)
+ {
+ iptr = &histogram[ir][ig][ptr->bmin];
+ for (ib = ptr->bmin; ib <= ptr->bmax; ++ib)
+ *histp += *iptr++;
+ }
+ histp++;
+ }
+ first = ptr->rmin;
+ last = ptr->rmax;
+ break;
+ case GREEN:
+ histp = &hist2[ptr->gmin];
+ for (ig = ptr->gmin; ig <= ptr->gmax; ++ig)
+ {
+ *histp = 0;
+ for (ir = ptr->rmin; ir <= ptr->rmax; ++ir)
+ {
+ iptr = &histogram[ir][ig][ptr->bmin];
+ for (ib = ptr->bmin; ib <= ptr->bmax; ++ib)
+ *histp += *iptr++;
+ }
+ histp++;
+ }
+ first = ptr->gmin;
+ last = ptr->gmax;
+ break;
+ case BLUE:
+ histp = &hist2[ptr->bmin];
+ for (ib = ptr->bmin; ib <= ptr->bmax; ++ib)
+ {
+ *histp = 0;
+ for (ir = ptr->rmin; ir <= ptr->rmax; ++ir)
+ {
+ iptr = &histogram[ir][ptr->gmin][ib];
+ for (ig = ptr->gmin; ig <= ptr->gmax; ++ig)
+ {
+ *histp += *iptr;
+ iptr += B_LEN;
+ }
+ }
+ histp++;
+ }
+ first = ptr->bmin;
+ last = ptr->bmax;
+ break;
+ }
+ /* find median point */
+ sum2 = ptr->total / 2;
+ histp = &hist2[first];
+ sum = 0;
+ for (i = first; i <= last && (sum += *histp++) < sum2; ++i)
+ ;
+ if (i == first)
+ i++;
+
+ /* Create new box, re-allocate points */
+ new = freeboxes;
+ freeboxes = new->next;
+ if (freeboxes)
+ freeboxes->prev = NULL;
+ if (usedboxes)
+ usedboxes->prev = new;
+ new->next = usedboxes;
+ usedboxes = new;
+
+ histp = &hist2[first];
+ for (sum1 = 0, j = first; j < i; j++)
+ sum1 += *histp++;
+ for (sum2 = 0, j = i; j <= last; j++)
+ sum2 += *histp++;
+ new->total = sum1;
+ ptr->total = sum2;
+
+ new->rmin = ptr->rmin;
+ new->rmax = ptr->rmax;
+ new->gmin = ptr->gmin;
+ new->gmax = ptr->gmax;
+ new->bmin = ptr->bmin;
+ new->bmax = ptr->bmax;
+ switch (axis)
+ {
+ case RED:
+ new->rmax = i - 1;
+ ptr->rmin = i;
+ break;
+ case GREEN:
+ new->gmax = i - 1;
+ ptr->gmin = i;
+ break;
+ case BLUE:
+ new->bmax = i - 1;
+ ptr->bmin = i;
+ break;
+ }
+ shrinkbox(new);
+ shrinkbox(ptr);
}
-static void
-shrinkbox(Colorbox* box)
+static void shrinkbox(Colorbox *box)
{
- register uint32_t *histp;
- register int ir, ig, ib;
-
- if (box->rmax > box->rmin) {
- for (ir = box->rmin; ir <= box->rmax; ++ir)
- for (ig = box->gmin; ig <= box->gmax; ++ig) {
- histp = &histogram[ir][ig][box->bmin];
- for (ib = box->bmin; ib <= box->bmax; ++ib)
- if (*histp++ != 0) {
- box->rmin = ir;
- goto have_rmin;
- }
- }
- have_rmin:
- if (box->rmax > box->rmin)
- for (ir = box->rmax; ir >= box->rmin; --ir)
- for (ig = box->gmin; ig <= box->gmax; ++ig) {
- histp = &histogram[ir][ig][box->bmin];
- ib = box->bmin;
- for (; ib <= box->bmax; ++ib)
- if (*histp++ != 0) {
- box->rmax = ir;
- goto have_rmax;
- }
- }
- }
+ register uint32_t *histp;
+ register int ir, ig, ib;
+
+ if (box->rmax > box->rmin)
+ {
+ for (ir = box->rmin; ir <= box->rmax; ++ir)
+ for (ig = box->gmin; ig <= box->gmax; ++ig)
+ {
+ histp = &histogram[ir][ig][box->bmin];
+ for (ib = box->bmin; ib <= box->bmax; ++ib)
+ if (*histp++ != 0)
+ {
+ box->rmin = ir;
+ goto have_rmin;
+ }
+ }
+ have_rmin:
+ if (box->rmax > box->rmin)
+ for (ir = box->rmax; ir >= box->rmin; --ir)
+ for (ig = box->gmin; ig <= box->gmax; ++ig)
+ {
+ histp = &histogram[ir][ig][box->bmin];
+ ib = box->bmin;
+ for (; ib <= box->bmax; ++ib)
+ if (*histp++ != 0)
+ {
+ box->rmax = ir;
+ goto have_rmax;
+ }
+ }
+ }
have_rmax:
- if (box->gmax > box->gmin) {
- for (ig = box->gmin; ig <= box->gmax; ++ig)
- for (ir = box->rmin; ir <= box->rmax; ++ir) {
- histp = &histogram[ir][ig][box->bmin];
- for (ib = box->bmin; ib <= box->bmax; ++ib)
- if (*histp++ != 0) {
- box->gmin = ig;
- goto have_gmin;
- }
- }
- have_gmin:
- if (box->gmax > box->gmin)
- for (ig = box->gmax; ig >= box->gmin; --ig)
- for (ir = box->rmin; ir <= box->rmax; ++ir) {
- histp = &histogram[ir][ig][box->bmin];
- ib = box->bmin;
- for (; ib <= box->bmax; ++ib)
- if (*histp++ != 0) {
- box->gmax = ig;
- goto have_gmax;
- }
- }
- }
+ if (box->gmax > box->gmin)
+ {
+ for (ig = box->gmin; ig <= box->gmax; ++ig)
+ for (ir = box->rmin; ir <= box->rmax; ++ir)
+ {
+ histp = &histogram[ir][ig][box->bmin];
+ for (ib = box->bmin; ib <= box->bmax; ++ib)
+ if (*histp++ != 0)
+ {
+ box->gmin = ig;
+ goto have_gmin;
+ }
+ }
+ have_gmin:
+ if (box->gmax > box->gmin)
+ for (ig = box->gmax; ig >= box->gmin; --ig)
+ for (ir = box->rmin; ir <= box->rmax; ++ir)
+ {
+ histp = &histogram[ir][ig][box->bmin];
+ ib = box->bmin;
+ for (; ib <= box->bmax; ++ib)
+ if (*histp++ != 0)
+ {
+ box->gmax = ig;
+ goto have_gmax;
+ }
+ }
+ }
have_gmax:
- if (box->bmax > box->bmin) {
- for (ib = box->bmin; ib <= box->bmax; ++ib)
- for (ir = box->rmin; ir <= box->rmax; ++ir) {
- histp = &histogram[ir][box->gmin][ib];
- for (ig = box->gmin; ig <= box->gmax; ++ig) {
- if (*histp != 0) {
- box->bmin = ib;
- goto have_bmin;
- }
- histp += B_LEN;
- }
- }
- have_bmin:
- if (box->bmax > box->bmin)
- for (ib = box->bmax; ib >= box->bmin; --ib)
- for (ir = box->rmin; ir <= box->rmax; ++ir) {
- histp = &histogram[ir][box->gmin][ib];
- ig = box->gmin;
- for (; ig <= box->gmax; ++ig) {
- if (*histp != 0) {
- box->bmax = ib;
- goto have_bmax;
- }
- histp += B_LEN;
- }
- }
- }
-have_bmax:
- ;
+ if (box->bmax > box->bmin)
+ {
+ for (ib = box->bmin; ib <= box->bmax; ++ib)
+ for (ir = box->rmin; ir <= box->rmax; ++ir)
+ {
+ histp = &histogram[ir][box->gmin][ib];
+ for (ig = box->gmin; ig <= box->gmax; ++ig)
+ {
+ if (*histp != 0)
+ {
+ box->bmin = ib;
+ goto have_bmin;
+ }
+ histp += B_LEN;
+ }
+ }
+ have_bmin:
+ if (box->bmax > box->bmin)
+ for (ib = box->bmax; ib >= box->bmin; --ib)
+ for (ir = box->rmin; ir <= box->rmax; ++ir)
+ {
+ histp = &histogram[ir][box->gmin][ib];
+ ig = box->gmin;
+ for (; ig <= box->gmax; ++ig)
+ {
+ if (*histp != 0)
+ {
+ box->bmax = ib;
+ goto have_bmax;
+ }
+ histp += B_LEN;
+ }
+ }
+ }
+have_bmax:;
}
-static C_cell *
-create_colorcell(int red, int green, int blue)
+static C_cell *create_colorcell(int red, int green, int blue)
{
- register int ir, ig, ib, i;
- register C_cell *ptr;
- int mindist, next_n;
- register int tmp, dist, n;
-
- ir = red >> (COLOR_DEPTH-C_DEPTH);
- ig = green >> (COLOR_DEPTH-C_DEPTH);
- ib = blue >> (COLOR_DEPTH-C_DEPTH);
- ptr = (C_cell *)_TIFFmalloc(sizeof (C_cell));
- *(ColorCells + ir*C_LEN*C_LEN + ig*C_LEN + ib) = ptr;
- ptr->num_ents = 0;
-
- /*
- * Step 1: find all colors inside this cell, while we're at
- * it, find distance of centermost point to furthest corner
- */
- mindist = 99999999;
- for (i = 0; i < num_colors; ++i) {
- if (rm[i]>>(COLOR_DEPTH-C_DEPTH) != ir ||
- gm[i]>>(COLOR_DEPTH-C_DEPTH) != ig ||
- bm[i]>>(COLOR_DEPTH-C_DEPTH) != ib)
- continue;
- ptr->entries[ptr->num_ents][0] = i;
- ptr->entries[ptr->num_ents][1] = 0;
- ++ptr->num_ents;
- tmp = rm[i] - red;
- if (tmp < (MAX_COLOR/C_LEN/2))
- tmp = MAX_COLOR/C_LEN-1 - tmp;
- dist = tmp*tmp;
- tmp = gm[i] - green;
- if (tmp < (MAX_COLOR/C_LEN/2))
- tmp = MAX_COLOR/C_LEN-1 - tmp;
- dist += tmp*tmp;
- tmp = bm[i] - blue;
- if (tmp < (MAX_COLOR/C_LEN/2))
- tmp = MAX_COLOR/C_LEN-1 - tmp;
- dist += tmp*tmp;
- if (dist < mindist)
- mindist = dist;
- }
-
- /*
- * Step 3: find all points within that distance to cell.
- */
- for (i = 0; i < num_colors; ++i) {
- if (rm[i] >> (COLOR_DEPTH-C_DEPTH) == ir &&
- gm[i] >> (COLOR_DEPTH-C_DEPTH) == ig &&
- bm[i] >> (COLOR_DEPTH-C_DEPTH) == ib)
- continue;
- dist = 0;
- if ((tmp = red - rm[i]) > 0 ||
- (tmp = rm[i] - (red + MAX_COLOR/C_LEN-1)) > 0 )
- dist += tmp*tmp;
- if ((tmp = green - gm[i]) > 0 ||
- (tmp = gm[i] - (green + MAX_COLOR/C_LEN-1)) > 0 )
- dist += tmp*tmp;
- if ((tmp = blue - bm[i]) > 0 ||
- (tmp = bm[i] - (blue + MAX_COLOR/C_LEN-1)) > 0 )
- dist += tmp*tmp;
- if (dist < mindist) {
- ptr->entries[ptr->num_ents][0] = i;
- ptr->entries[ptr->num_ents][1] = dist;
- ++ptr->num_ents;
- }
- }
-
- /*
- * Sort color cells by distance, use cheap exchange sort
- */
- for (n = ptr->num_ents - 1; n > 0; n = next_n) {
- next_n = 0;
- for (i = 0; i < n; ++i)
- if (ptr->entries[i][1] > ptr->entries[i+1][1]) {
- tmp = ptr->entries[i][0];
- ptr->entries[i][0] = ptr->entries[i+1][0];
- ptr->entries[i+1][0] = tmp;
- tmp = ptr->entries[i][1];
- ptr->entries[i][1] = ptr->entries[i+1][1];
- ptr->entries[i+1][1] = tmp;
- next_n = i;
- }
- }
- return (ptr);
+ register int ir, ig, ib, i;
+ register C_cell *ptr;
+ int mindist, next_n;
+ register int tmp, dist, n;
+
+ ir = red >> (COLOR_DEPTH - C_DEPTH);
+ ig = green >> (COLOR_DEPTH - C_DEPTH);
+ ib = blue >> (COLOR_DEPTH - C_DEPTH);
+ ptr = (C_cell *)_TIFFmalloc(sizeof(C_cell));
+ *(ColorCells + ir * C_LEN * C_LEN + ig * C_LEN + ib) = ptr;
+ ptr->num_ents = 0;
+
+ /*
+ * Step 1: find all colors inside this cell, while we're at
+ * it, find distance of centermost point to furthest corner
+ */
+ mindist = 99999999;
+ for (i = 0; i < num_colors; ++i)
+ {
+ if (rm[i] >> (COLOR_DEPTH - C_DEPTH) != ir ||
+ gm[i] >> (COLOR_DEPTH - C_DEPTH) != ig ||
+ bm[i] >> (COLOR_DEPTH - C_DEPTH) != ib)
+ continue;
+ ptr->entries[ptr->num_ents][0] = i;
+ ptr->entries[ptr->num_ents][1] = 0;
+ ++ptr->num_ents;
+ tmp = rm[i] - red;
+ if (tmp < (MAX_COLOR / C_LEN / 2))
+ tmp = MAX_COLOR / C_LEN - 1 - tmp;
+ dist = tmp * tmp;
+ tmp = gm[i] - green;
+ if (tmp < (MAX_COLOR / C_LEN / 2))
+ tmp = MAX_COLOR / C_LEN - 1 - tmp;
+ dist += tmp * tmp;
+ tmp = bm[i] - blue;
+ if (tmp < (MAX_COLOR / C_LEN / 2))
+ tmp = MAX_COLOR / C_LEN - 1 - tmp;
+ dist += tmp * tmp;
+ if (dist < mindist)
+ mindist = dist;
+ }
+
+ /*
+ * Step 3: find all points within that distance to cell.
+ */
+ for (i = 0; i < num_colors; ++i)
+ {
+ if (rm[i] >> (COLOR_DEPTH - C_DEPTH) == ir &&
+ gm[i] >> (COLOR_DEPTH - C_DEPTH) == ig &&
+ bm[i] >> (COLOR_DEPTH - C_DEPTH) == ib)
+ continue;
+ dist = 0;
+ if ((tmp = red - rm[i]) > 0 ||
+ (tmp = rm[i] - (red + MAX_COLOR / C_LEN - 1)) > 0)
+ dist += tmp * tmp;
+ if ((tmp = green - gm[i]) > 0 ||
+ (tmp = gm[i] - (green + MAX_COLOR / C_LEN - 1)) > 0)
+ dist += tmp * tmp;
+ if ((tmp = blue - bm[i]) > 0 ||
+ (tmp = bm[i] - (blue + MAX_COLOR / C_LEN - 1)) > 0)
+ dist += tmp * tmp;
+ if (dist < mindist)
+ {
+ ptr->entries[ptr->num_ents][0] = i;
+ ptr->entries[ptr->num_ents][1] = dist;
+ ++ptr->num_ents;
+ }
+ }
+
+ /*
+ * Sort color cells by distance, use cheap exchange sort
+ */
+ for (n = ptr->num_ents - 1; n > 0; n = next_n)
+ {
+ next_n = 0;
+ for (i = 0; i < n; ++i)
+ if (ptr->entries[i][1] > ptr->entries[i + 1][1])
+ {
+ tmp = ptr->entries[i][0];
+ ptr->entries[i][0] = ptr->entries[i + 1][0];
+ ptr->entries[i + 1][0] = tmp;
+ tmp = ptr->entries[i][1];
+ ptr->entries[i][1] = ptr->entries[i + 1][1];
+ ptr->entries[i + 1][1] = tmp;
+ next_n = i;
+ }
+ }
+ return (ptr);
}
-static void
-map_colortable(void)
+static void map_colortable(void)
{
- register uint32_t *histp = &histogram[0][0][0];
- register C_cell *cell;
- register int j, tmp, d2, dist;
- int ir, ig, ib, i;
-
- for (ir = 0; ir < B_LEN; ++ir)
- for (ig = 0; ig < B_LEN; ++ig)
- for (ib = 0; ib < B_LEN; ++ib, histp++) {
- if (*histp == 0) {
- *histp = -1;
- continue;
- }
- cell = *(ColorCells +
- (((ir>>(B_DEPTH-C_DEPTH)) << C_DEPTH*2) +
- ((ig>>(B_DEPTH-C_DEPTH)) << C_DEPTH) +
- (ib>>(B_DEPTH-C_DEPTH))));
- if (cell == NULL )
- cell = create_colorcell(
- ir << COLOR_SHIFT,
- ig << COLOR_SHIFT,
- ib << COLOR_SHIFT);
- dist = 9999999;
- for (i = 0; i < cell->num_ents &&
- dist > cell->entries[i][1]; ++i) {
- j = cell->entries[i][0];
- d2 = rm[j] - (ir << COLOR_SHIFT);
- d2 *= d2;
- tmp = gm[j] - (ig << COLOR_SHIFT);
- d2 += tmp*tmp;
- tmp = bm[j] - (ib << COLOR_SHIFT);
- d2 += tmp*tmp;
- if (d2 < dist) {
- dist = d2;
- *histp = j;
- }
- }
- }
+ register uint32_t *histp = &histogram[0][0][0];
+ register C_cell *cell;
+ register int j, tmp, d2, dist;
+ int ir, ig, ib, i;
+
+ for (ir = 0; ir < B_LEN; ++ir)
+ for (ig = 0; ig < B_LEN; ++ig)
+ for (ib = 0; ib < B_LEN; ++ib, histp++)
+ {
+ if (*histp == 0)
+ {
+ *histp = -1;
+ continue;
+ }
+ cell = *(ColorCells +
+ (((ir >> (B_DEPTH - C_DEPTH)) << C_DEPTH * 2) +
+ ((ig >> (B_DEPTH - C_DEPTH)) << C_DEPTH) +
+ (ib >> (B_DEPTH - C_DEPTH))));
+ if (cell == NULL)
+ cell =
+ create_colorcell(ir << COLOR_SHIFT, ig << COLOR_SHIFT,
+ ib << COLOR_SHIFT);
+ dist = 9999999;
+ for (i = 0; i < cell->num_ents && dist > cell->entries[i][1];
+ ++i)
+ {
+ j = cell->entries[i][0];
+ d2 = rm[j] - (ir << COLOR_SHIFT);
+ d2 *= d2;
+ tmp = gm[j] - (ig << COLOR_SHIFT);
+ d2 += tmp * tmp;
+ tmp = bm[j] - (ib << COLOR_SHIFT);
+ d2 += tmp * tmp;
+ if (d2 < dist)
+ {
+ dist = d2;
+ *histp = j;
+ }
+ }
+ }
}
/*
@@ -773,155 +826,173 @@ map_colortable(void)
* closest to it. Color values are rounded to the nearest color
* table entry.
*/
-static void
-quant(TIFF* in, TIFF* out)
+static void quant(TIFF *in, TIFF *out)
{
- unsigned char *outline, *inputline;
- register unsigned char *outptr, *inptr;
- register uint32_t i, j;
- register int red, green, blue;
-
- inputline = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
- outline = (unsigned char *)_TIFFmalloc(imagewidth);
- for (i = 0; i < imagelength; i++) {
- if (TIFFReadScanline(in, inputline, i, 0) <= 0)
- break;
- inptr = inputline;
- outptr = outline;
- for (j = 0; j < imagewidth; j++) {
- red = *inptr++ >> COLOR_SHIFT;
- green = *inptr++ >> COLOR_SHIFT;
- blue = *inptr++ >> COLOR_SHIFT;
- *outptr++ = (unsigned char)histogram[red][green][blue];
- }
- if (TIFFWriteScanline(out, outline, i, 0) < 0)
- break;
- }
- _TIFFfree(inputline);
- _TIFFfree(outline);
+ unsigned char *outline, *inputline;
+ register unsigned char *outptr, *inptr;
+ register uint32_t i, j;
+ register int red, green, blue;
+
+ inputline = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
+ outline = (unsigned char *)_TIFFmalloc(imagewidth);
+ for (i = 0; i < imagelength; i++)
+ {
+ if (TIFFReadScanline(in, inputline, i, 0) <= 0)
+ break;
+ inptr = inputline;
+ outptr = outline;
+ for (j = 0; j < imagewidth; j++)
+ {
+ red = *inptr++ >> COLOR_SHIFT;
+ green = *inptr++ >> COLOR_SHIFT;
+ blue = *inptr++ >> COLOR_SHIFT;
+ *outptr++ = (unsigned char)histogram[red][green][blue];
+ }
+ if (TIFFWriteScanline(out, outline, i, 0) < 0)
+ break;
+ }
+ _TIFFfree(inputline);
+ _TIFFfree(outline);
}
-#define SWAP(type,a,b) { type p; p = a; a = b; b = p; }
-
-#define GetInputLine(tif, row, bad) \
- do { \
- if (TIFFReadScanline(tif, inputline, row, 0) <= 0) \
- bad; \
- inptr = inputline; \
- nextptr = nextline; \
- for (j = 0; j < imagewidth; ++j) { \
- *nextptr++ = *inptr++; \
- *nextptr++ = *inptr++; \
- *nextptr++ = *inptr++; \
- } \
- } while (0);
-#define GetComponent(raw, cshift, c) \
- do { \
- cshift = raw; \
- if (cshift < 0) \
- cshift = 0; \
- else if (cshift >= MAX_COLOR) \
- cshift = MAX_COLOR-1; \
- c = cshift; \
- cshift >>= COLOR_SHIFT; \
- } while (0);
-
-static void
-quant_fsdither(TIFF* in, TIFF* out)
+#define SWAP(type, a, b) \
+ { \
+ type p; \
+ p = a; \
+ a = b; \
+ b = p; \
+ }
+
+#define GetInputLine(tif, row, bad) \
+ do \
+ { \
+ if (TIFFReadScanline(tif, inputline, row, 0) <= 0) \
+ bad; \
+ inptr = inputline; \
+ nextptr = nextline; \
+ for (j = 0; j < imagewidth; ++j) \
+ { \
+ *nextptr++ = *inptr++; \
+ *nextptr++ = *inptr++; \
+ *nextptr++ = *inptr++; \
+ } \
+ } while (0);
+#define GetComponent(raw, cshift, c) \
+ do \
+ { \
+ cshift = raw; \
+ if (cshift < 0) \
+ cshift = 0; \
+ else if (cshift >= MAX_COLOR) \
+ cshift = MAX_COLOR - 1; \
+ c = cshift; \
+ cshift >>= COLOR_SHIFT; \
+ } while (0);
+
+static void quant_fsdither(TIFF *in, TIFF *out)
{
- unsigned char *outline, *inputline, *inptr;
- short *thisline, *nextline;
- register unsigned char *outptr;
- register short *thisptr, *nextptr;
- register uint32_t i, j;
- uint32_t imax, jmax;
- int lastline, lastpixel;
-
- imax = imagelength - 1;
- jmax = imagewidth - 1;
- inputline = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
- thisline = (short *)_TIFFmalloc(imagewidth * 3 * sizeof (short));
- nextline = (short *)_TIFFmalloc(imagewidth * 3 * sizeof (short));
- outline = (unsigned char *) _TIFFmalloc(TIFFScanlineSize(out));
-
- GetInputLine(in, 0, goto bad); /* get first line */
- for (i = 1; i <= imagelength; ++i) {
- SWAP(short *, thisline, nextline);
- lastline = (i >= imax);
- if (i <= imax)
- GetInputLine(in, i, break);
- thisptr = thisline;
- nextptr = nextline;
- outptr = outline;
- for (j = 0; j < imagewidth; ++j) {
- int red, green, blue;
- register int oval, r2, g2, b2;
-
- lastpixel = (j == jmax);
- GetComponent(*thisptr++, r2, red);
- GetComponent(*thisptr++, g2, green);
- GetComponent(*thisptr++, b2, blue);
- oval = histogram[r2][g2][b2];
- if (oval == -1) {
- int ci;
- register int cj, tmp, d2, dist;
- register C_cell *cell;
-
- cell = *(ColorCells +
- (((r2>>(B_DEPTH-C_DEPTH)) << C_DEPTH*2) +
- ((g2>>(B_DEPTH-C_DEPTH)) << C_DEPTH ) +
- (b2>>(B_DEPTH-C_DEPTH))));
- if (cell == NULL)
- cell = create_colorcell(red,
- green, blue);
- dist = 9999999;
- for (ci = 0; ci < cell->num_ents && dist > cell->entries[ci][1]; ++ci) {
- cj = cell->entries[ci][0];
- d2 = (rm[cj] >> COLOR_SHIFT) - r2;
- d2 *= d2;
- tmp = (gm[cj] >> COLOR_SHIFT) - g2;
- d2 += tmp*tmp;
- tmp = (bm[cj] >> COLOR_SHIFT) - b2;
- d2 += tmp*tmp;
- if (d2 < dist) {
- dist = d2;
- oval = cj;
- }
- }
- histogram[r2][g2][b2] = oval;
- }
- *outptr++ = oval;
- red -= rm[oval];
- green -= gm[oval];
- blue -= bm[oval];
- if (!lastpixel) {
- thisptr[0] += blue * 7 / 16;
- thisptr[1] += green * 7 / 16;
- thisptr[2] += red * 7 / 16;
- }
- if (!lastline) {
- if (j != 0) {
- nextptr[-3] += blue * 3 / 16;
- nextptr[-2] += green * 3 / 16;
- nextptr[-1] += red * 3 / 16;
- }
- nextptr[0] += blue * 5 / 16;
- nextptr[1] += green * 5 / 16;
- nextptr[2] += red * 5 / 16;
- if (!lastpixel) {
- nextptr[3] += blue / 16;
- nextptr[4] += green / 16;
- nextptr[5] += red / 16;
- }
- nextptr += 3;
- }
- }
- if (TIFFWriteScanline(out, outline, i-1, 0) < 0)
- break;
- }
+ unsigned char *outline, *inputline, *inptr;
+ short *thisline, *nextline;
+ register unsigned char *outptr;
+ register short *thisptr, *nextptr;
+ register uint32_t i, j;
+ uint32_t imax, jmax;
+ int lastline, lastpixel;
+
+ imax = imagelength - 1;
+ jmax = imagewidth - 1;
+ inputline = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
+ thisline = (short *)_TIFFmalloc(imagewidth * 3 * sizeof(short));
+ nextline = (short *)_TIFFmalloc(imagewidth * 3 * sizeof(short));
+ outline = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(out));
+
+ GetInputLine(in, 0, goto bad); /* get first line */
+ for (i = 1; i <= imagelength; ++i)
+ {
+ SWAP(short *, thisline, nextline);
+ lastline = (i >= imax);
+ if (i <= imax)
+ GetInputLine(in, i, break);
+ thisptr = thisline;
+ nextptr = nextline;
+ outptr = outline;
+ for (j = 0; j < imagewidth; ++j)
+ {
+ int red, green, blue;
+ register int oval, r2, g2, b2;
+
+ lastpixel = (j == jmax);
+ GetComponent(*thisptr++, r2, red);
+ GetComponent(*thisptr++, g2, green);
+ GetComponent(*thisptr++, b2, blue);
+ oval = histogram[r2][g2][b2];
+ if (oval == -1)
+ {
+ int ci;
+ register int cj, tmp, d2, dist;
+ register C_cell *cell;
+
+ cell = *(ColorCells +
+ (((r2 >> (B_DEPTH - C_DEPTH)) << C_DEPTH * 2) +
+ ((g2 >> (B_DEPTH - C_DEPTH)) << C_DEPTH) +
+ (b2 >> (B_DEPTH - C_DEPTH))));
+ if (cell == NULL)
+ cell = create_colorcell(red, green, blue);
+ dist = 9999999;
+ for (ci = 0; ci < cell->num_ents && dist > cell->entries[ci][1];
+ ++ci)
+ {
+ cj = cell->entries[ci][0];
+ d2 = (rm[cj] >> COLOR_SHIFT) - r2;
+ d2 *= d2;
+ tmp = (gm[cj] >> COLOR_SHIFT) - g2;
+ d2 += tmp * tmp;
+ tmp = (bm[cj] >> COLOR_SHIFT) - b2;
+ d2 += tmp * tmp;
+ if (d2 < dist)
+ {
+ dist = d2;
+ oval = cj;
+ }
+ }
+ histogram[r2][g2][b2] = oval;
+ }
+ *outptr++ = oval;
+ red -= rm[oval];
+ green -= gm[oval];
+ blue -= bm[oval];
+ if (!lastpixel)
+ {
+ thisptr[0] += blue * 7 / 16;
+ thisptr[1] += green * 7 / 16;
+ thisptr[2] += red * 7 / 16;
+ }
+ if (!lastline)
+ {
+ if (j != 0)
+ {
+ nextptr[-3] += blue * 3 / 16;
+ nextptr[-2] += green * 3 / 16;
+ nextptr[-1] += red * 3 / 16;
+ }
+ nextptr[0] += blue * 5 / 16;
+ nextptr[1] += green * 5 / 16;
+ nextptr[2] += red * 5 / 16;
+ if (!lastpixel)
+ {
+ nextptr[3] += blue / 16;
+ nextptr[4] += green / 16;
+ nextptr[5] += red / 16;
+ }
+ nextptr += 3;
+ }
+ }
+ if (TIFFWriteScanline(out, outline, i - 1, 0) < 0)
+ break;
+ }
bad:
- _TIFFfree(inputline);
- _TIFFfree(thisline);
- _TIFFfree(nextline);
- _TIFFfree(outline);
+ _TIFFfree(inputline);
+ _TIFFfree(thisline);
+ _TIFFfree(nextline);
+ _TIFFfree(outline);
}
diff --git a/tools/tiffset.c b/tools/tiffset.c
index 770336c9..5dff54f4 100644
--- a/tools/tiffset.c
+++ b/tools/tiffset.c
@@ -6,23 +6,23 @@
******************************************************************************
* Copyright (c) 2000, Frank Warmerdam
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
******************************************************************************
*/
@@ -30,13 +30,13 @@
#include "tif_config.h"
#include <stdio.h>
-#include <string.h>
#include <stdlib.h>
+#include <string.h>
#include "tiffio.h"
#ifdef NEED_LIBPORT
-# include "libport.h"
+#include "libport.h"
#endif
#ifndef EXIT_SUCCESS
@@ -47,93 +47,100 @@
#endif
static const char usageMsg[] =
-"Set the value of a TIFF header to a specified value\n\n"
-"usage: tiffset [options] filename\n"
-"where options are:\n"
-" -s <tagname> [count] <value>... set the tag value\n"
-" -u <tagname> to unset the tag\n"
-" -d <dirno> set the directory\n"
-" -sd <diroff> set the subdirectory\n"
-" -sf <tagname> <filename> read the tag value from file (for ASCII tags only)\n"
-" -h this help screen\n"
-;
-
-static void
-usage(int code)
+ "Set the value of a TIFF header to a specified value\n\n"
+ "usage: tiffset [options] filename\n"
+ "where options are:\n"
+ " -s <tagname> [count] <value>... set the tag value\n"
+ " -u <tagname> to unset the tag\n"
+ " -d <dirno> set the directory\n"
+ " -sd <diroff> set the subdirectory\n"
+ " -sf <tagname> <filename> read the tag value from file (for ASCII tags "
+ "only)\n"
+ " -h this help screen\n";
+
+static void usage(int code)
{
- FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
- fprintf(out, "%s\n\n", TIFFGetVersion());
- fprintf(out, "%s", usageMsg);
- exit(code);
+ fprintf(out, "%s\n\n", TIFFGetVersion());
+ fprintf(out, "%s", usageMsg);
+ exit(code);
}
-static const TIFFField *
-GetField(TIFF *tiff, const char *tagname)
+static const TIFFField *GetField(TIFF *tiff, const char *tagname)
{
const TIFFField *fip;
- if( atoi(tagname) > 0 )
+ if (atoi(tagname) > 0)
fip = TIFFFieldWithTag(tiff, (ttag_t)atoi(tagname));
else
fip = TIFFFieldWithName(tiff, tagname);
- if (!fip) {
- fprintf( stderr, "Field name \"%s\" is not recognised.\n", tagname );
+ if (!fip)
+ {
+ fprintf(stderr, "Field name \"%s\" is not recognised.\n", tagname);
return (TIFFField *)NULL;
}
return fip;
}
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
TIFF *tiff;
- int arg_index;
+ int arg_index;
if (argc < 2)
usage(EXIT_FAILURE);
- tiff = TIFFOpen(argv[argc-1], "r+");
+ tiff = TIFFOpen(argv[argc - 1], "r+");
if (tiff == NULL)
return EXIT_FAILURE;
- for( arg_index = 1; arg_index < argc-1; arg_index++ ) {
- if (strcmp(argv[arg_index],"-d") == 0 && arg_index < argc-2) {
- arg_index++;
- if( TIFFSetDirectory(tiff, atoi(argv[arg_index]) ) != 1 )
+ for (arg_index = 1; arg_index < argc - 1; arg_index++)
+ {
+ if (strcmp(argv[arg_index], "-d") == 0 && arg_index < argc - 2)
+ {
+ arg_index++;
+ if (TIFFSetDirectory(tiff, atoi(argv[arg_index])) != 1)
{
- fprintf( stderr, "Failed to set directory=%s\n", argv[arg_index] );
- return EXIT_FAILURE;
+ fprintf(stderr, "Failed to set directory=%s\n",
+ argv[arg_index]);
+ return EXIT_FAILURE;
}
- arg_index++;
- }
- if (strcmp(argv[arg_index],"-sd") == 0 && arg_index < argc-2) {
- arg_index++;
- if( TIFFSetSubDirectory(tiff, atoi(argv[arg_index]) ) != 1 )
+ arg_index++;
+ }
+ if (strcmp(argv[arg_index], "-sd") == 0 && arg_index < argc - 2)
+ {
+ arg_index++;
+ if (TIFFSetSubDirectory(tiff, atoi(argv[arg_index])) != 1)
{
- fprintf( stderr, "Failed to set sub directory=%s\n", argv[arg_index] );
- return EXIT_FAILURE;
+ fprintf(stderr, "Failed to set sub directory=%s\n",
+ argv[arg_index]);
+ return EXIT_FAILURE;
}
- arg_index++;
- }
- /* Add unset option to tiffset -- Zach Baker (niquil@niquil.net) 11/14/2012 */
- if (strcmp(argv[arg_index],"-u") == 0 && arg_index < argc-2) {
+ arg_index++;
+ }
+ /* Add unset option to tiffset -- Zach Baker (niquil@niquil.net)
+ * 11/14/2012 */
+ if (strcmp(argv[arg_index], "-u") == 0 && arg_index < argc - 2)
+ {
const TIFFField *fip;
const char *tagname;
arg_index++;
tagname = argv[arg_index];
fip = GetField(tiff, tagname);
if (!fip)
- return EXIT_FAILURE;
+ return EXIT_FAILURE;
if (TIFFUnsetField(tiff, TIFFFieldTag(fip)) != 1)
{
- fprintf(stderr, "Failed to unset %s\n", TIFFFieldName(fip));
+ fprintf(stderr, "Failed to unset %s\n", TIFFFieldName(fip));
}
arg_index++;
- } else if (strcmp(argv[arg_index],"-s") == 0 && arg_index < argc-3) {
+ }
+ else if (strcmp(argv[arg_index], "-s") == 0 && arg_index < argc - 3)
+ {
const TIFFField *fip;
const char *tagname;
@@ -145,201 +152,236 @@ main(int argc, char* argv[])
return 3;
arg_index++;
- if (TIFFFieldDataType(fip) == TIFF_ASCII) {
- if(TIFFFieldPassCount( fip )) {
+ if (TIFFFieldDataType(fip) == TIFF_ASCII)
+ {
+ if (TIFFFieldPassCount(fip))
+ {
size_t len;
len = strlen(argv[arg_index]) + 1;
- if (len > UINT16_MAX || TIFFSetField(tiff, TIFFFieldTag(fip),
- (uint16_t)len, argv[arg_index]) != 1)
- fprintf( stderr, "Failed to set %s=%s\n",
- TIFFFieldName(fip), argv[arg_index] );
- } else {
+ if (len > UINT16_MAX ||
+ TIFFSetField(tiff, TIFFFieldTag(fip), (uint16_t)len,
+ argv[arg_index]) != 1)
+ fprintf(stderr, "Failed to set %s=%s\n",
+ TIFFFieldName(fip), argv[arg_index]);
+ }
+ else
+ {
if (TIFFSetField(tiff, TIFFFieldTag(fip),
- argv[arg_index]) != 1)
- fprintf( stderr, "Failed to set %s=%s\n",
- TIFFFieldName(fip), argv[arg_index] );
+ argv[arg_index]) != 1)
+ fprintf(stderr, "Failed to set %s=%s\n",
+ TIFFFieldName(fip), argv[arg_index]);
}
- } else if (TIFFFieldWriteCount(fip) > 0
- || TIFFFieldWriteCount(fip) == TIFF_VARIABLE) {
- int ret = 1;
- short wc;
+ }
+ else if (TIFFFieldWriteCount(fip) > 0 ||
+ TIFFFieldWriteCount(fip) == TIFF_VARIABLE)
+ {
+ int ret = 1;
+ short wc;
if (TIFFFieldWriteCount(fip) == TIFF_VARIABLE)
- wc = atoi(argv[arg_index++]);
+ wc = atoi(argv[arg_index++]);
else
- wc = TIFFFieldWriteCount(fip);
-
- if (argc - arg_index < wc) {
- fprintf( stderr,
- "Number of tag values is not enough. "
- "Expected %d values for %s tag, got %d\n",
- wc, TIFFFieldName(fip), argc - arg_index);
+ wc = TIFFFieldWriteCount(fip);
+
+ if (argc - arg_index < wc)
+ {
+ fprintf(stderr,
+ "Number of tag values is not enough. "
+ "Expected %d values for %s tag, got %d\n",
+ wc, TIFFFieldName(fip), argc - arg_index);
return EXIT_FAILURE;
}
-
- if (wc > 1 || TIFFFieldWriteCount(fip) == TIFF_VARIABLE) {
- int i, size;
- void *array;
-
- switch (TIFFFieldDataType(fip)) {
- /*
- * XXX: We can't use TIFFDataWidth()
- * to determine the space needed to store
- * the value. For TIFF_RATIONAL values
- * TIFFDataWidth() returns 8, but we use 4-byte
- * float to represent rationals.
- */
- case TIFF_BYTE:
- case TIFF_ASCII:
- case TIFF_SBYTE:
- case TIFF_UNDEFINED:
- default:
- size = 1;
- break;
-
- case TIFF_SHORT:
- case TIFF_SSHORT:
- size = 2;
- break;
-
- case TIFF_LONG:
- case TIFF_SLONG:
- case TIFF_FLOAT:
- case TIFF_IFD:
- case TIFF_RATIONAL:
- case TIFF_SRATIONAL:
- size = 4;
- break;
-
- case TIFF_LONG8:
- case TIFF_SLONG8:
- case TIFF_IFD8:
- case TIFF_DOUBLE:
- size = 8;
- break;
- }
-
- array = _TIFFmalloc(wc * size);
- if (!array) {
- fprintf(stderr, "No space for %s tag\n",
- tagname);
- return EXIT_FAILURE;
- }
- switch (TIFFFieldDataType(fip)) {
- case TIFF_BYTE:
- for (i = 0; i < wc; i++)
- ((uint8_t *)array)[i] = atoi(argv[arg_index + i]);
- break;
- case TIFF_SHORT:
- for (i = 0; i < wc; i++)
- ((uint16_t *)array)[i] = atoi(argv[arg_index + i]);
- break;
- case TIFF_SBYTE:
- for (i = 0; i < wc; i++)
- ((int8_t *)array)[i] = atoi(argv[arg_index + i]);
- break;
- case TIFF_SSHORT:
- for (i = 0; i < wc; i++)
- ((int16_t *)array)[i] = atoi(argv[arg_index + i]);
- break;
- case TIFF_LONG:
- for (i = 0; i < wc; i++)
- ((uint32_t *)array)[i] = atol(argv[arg_index + i]);
- break;
- case TIFF_SLONG:
- case TIFF_IFD:
- for (i = 0; i < wc; i++)
- ((int32_t *)array)[i] = atol(argv[arg_index + i]);
- break;
- case TIFF_LONG8:
- for (i = 0; i < wc; i++)
- ((uint64_t *)array)[i] = strtoll(argv[arg_index + i], (char **)NULL, 10);
- break;
- case TIFF_SLONG8:
- case TIFF_IFD8:
- for (i = 0; i < wc; i++)
- ((int64_t *)array)[i] = strtoll(argv[arg_index + i], (char **)NULL, 10);
- break;
- case TIFF_DOUBLE:
- for (i = 0; i < wc; i++)
- ((double *)array)[i] = atof(argv[arg_index+i]);
- break;
- case TIFF_RATIONAL:
- case TIFF_SRATIONAL:
- case TIFF_FLOAT:
- for (i = 0; i < wc; i++)
- ((float *)array)[i] = (float)atof(argv[arg_index+i]);
- break;
- default:
- break;
+ if (wc > 1 || TIFFFieldWriteCount(fip) == TIFF_VARIABLE)
+ {
+ int i, size;
+ void *array;
+
+ switch (TIFFFieldDataType(fip))
+ {
+ /*
+ * XXX: We can't use TIFFDataWidth()
+ * to determine the space needed to store
+ * the value. For TIFF_RATIONAL values
+ * TIFFDataWidth() returns 8, but we use 4-byte
+ * float to represent rationals.
+ */
+ case TIFF_BYTE:
+ case TIFF_ASCII:
+ case TIFF_SBYTE:
+ case TIFF_UNDEFINED:
+ default:
+ size = 1;
+ break;
+
+ case TIFF_SHORT:
+ case TIFF_SSHORT:
+ size = 2;
+ break;
+
+ case TIFF_LONG:
+ case TIFF_SLONG:
+ case TIFF_FLOAT:
+ case TIFF_IFD:
+ case TIFF_RATIONAL:
+ case TIFF_SRATIONAL:
+ size = 4;
+ break;
+
+ case TIFF_LONG8:
+ case TIFF_SLONG8:
+ case TIFF_IFD8:
+ case TIFF_DOUBLE:
+ size = 8;
+ break;
+ }
+
+ array = _TIFFmalloc(wc * size);
+ if (!array)
+ {
+ fprintf(stderr, "No space for %s tag\n", tagname);
+ return EXIT_FAILURE;
+ }
+
+ switch (TIFFFieldDataType(fip))
+ {
+ case TIFF_BYTE:
+ for (i = 0; i < wc; i++)
+ ((uint8_t *)array)[i] =
+ atoi(argv[arg_index + i]);
+ break;
+ case TIFF_SHORT:
+ for (i = 0; i < wc; i++)
+ ((uint16_t *)array)[i] =
+ atoi(argv[arg_index + i]);
+ break;
+ case TIFF_SBYTE:
+ for (i = 0; i < wc; i++)
+ ((int8_t *)array)[i] =
+ atoi(argv[arg_index + i]);
+ break;
+ case TIFF_SSHORT:
+ for (i = 0; i < wc; i++)
+ ((int16_t *)array)[i] =
+ atoi(argv[arg_index + i]);
+ break;
+ case TIFF_LONG:
+ for (i = 0; i < wc; i++)
+ ((uint32_t *)array)[i] =
+ atol(argv[arg_index + i]);
+ break;
+ case TIFF_SLONG:
+ case TIFF_IFD:
+ for (i = 0; i < wc; i++)
+ ((int32_t *)array)[i] =
+ atol(argv[arg_index + i]);
+ break;
+ case TIFF_LONG8:
+ for (i = 0; i < wc; i++)
+ ((uint64_t *)array)[i] = strtoll(
+ argv[arg_index + i], (char **)NULL, 10);
+ break;
+ case TIFF_SLONG8:
+ case TIFF_IFD8:
+ for (i = 0; i < wc; i++)
+ ((int64_t *)array)[i] = strtoll(
+ argv[arg_index + i], (char **)NULL, 10);
+ break;
+ case TIFF_DOUBLE:
+ for (i = 0; i < wc; i++)
+ ((double *)array)[i] =
+ atof(argv[arg_index + i]);
+ break;
+ case TIFF_RATIONAL:
+ case TIFF_SRATIONAL:
+ case TIFF_FLOAT:
+ for (i = 0; i < wc; i++)
+ ((float *)array)[i] =
+ (float)atof(argv[arg_index + i]);
+ break;
+ default:
+ break;
+ }
+
+ if (TIFFFieldPassCount(fip))
+ {
+ ret = TIFFSetField(tiff, TIFFFieldTag(fip), wc, array);
+ }
+ else if (TIFFFieldTag(fip) == TIFFTAG_PAGENUMBER ||
+ TIFFFieldTag(fip) == TIFFTAG_HALFTONEHINTS ||
+ TIFFFieldTag(fip) == TIFFTAG_YCBCRSUBSAMPLING ||
+ TIFFFieldTag(fip) == TIFFTAG_DOTRANGE)
+ {
+ if (TIFFFieldDataType(fip) == TIFF_BYTE)
+ {
+ ret = TIFFSetField(tiff, TIFFFieldTag(fip),
+ ((uint8_t *)array)[0],
+ ((uint8_t *)array)[1]);
}
-
- if (TIFFFieldPassCount(fip)) {
- ret = TIFFSetField(tiff, TIFFFieldTag(fip),
- wc, array);
- } else if (TIFFFieldTag(fip) == TIFFTAG_PAGENUMBER
- || TIFFFieldTag(fip) == TIFFTAG_HALFTONEHINTS
- || TIFFFieldTag(fip) == TIFFTAG_YCBCRSUBSAMPLING
- || TIFFFieldTag(fip) == TIFFTAG_DOTRANGE) {
- if (TIFFFieldDataType(fip) == TIFF_BYTE) {
- ret = TIFFSetField(tiff, TIFFFieldTag(fip),
- ((uint8_t *)array)[0], ((uint8_t *)array)[1]);
- } else if (TIFFFieldDataType(fip) == TIFF_SHORT) {
- ret = TIFFSetField(tiff, TIFFFieldTag(fip),
- ((uint16_t *)array)[0], ((uint16_t *)array)[1]);
- }
- } else {
- ret = TIFFSetField(tiff, TIFFFieldTag(fip),
- array);
+ else if (TIFFFieldDataType(fip) == TIFF_SHORT)
+ {
+ ret = TIFFSetField(tiff, TIFFFieldTag(fip),
+ ((uint16_t *)array)[0],
+ ((uint16_t *)array)[1]);
}
+ }
+ else
+ {
+ ret = TIFFSetField(tiff, TIFFFieldTag(fip), array);
+ }
- _TIFFfree(array);
- } else {
- switch (TIFFFieldDataType(fip)) {
- case TIFF_BYTE:
- case TIFF_SHORT:
- case TIFF_SBYTE:
- case TIFF_SSHORT:
- ret = TIFFSetField(tiff, TIFFFieldTag(fip),
- atoi(argv[arg_index++]));
- break;
- case TIFF_LONG:
- case TIFF_SLONG:
- case TIFF_IFD:
- ret = TIFFSetField(tiff, TIFFFieldTag(fip),
- atol(argv[arg_index++]));
- break;
- case TIFF_LONG8:
- case TIFF_SLONG8:
- case TIFF_IFD8:
- ret = TIFFSetField(tiff, TIFFFieldTag(fip),
- strtoll(argv[arg_index++], (char **)NULL, 10));
- break;
- case TIFF_DOUBLE:
- ret = TIFFSetField(tiff, TIFFFieldTag(fip),
- atof(argv[arg_index++]));
- break;
- case TIFF_RATIONAL:
- case TIFF_SRATIONAL:
- case TIFF_FLOAT:
- ret = TIFFSetField(tiff, TIFFFieldTag(fip),
- (float)atof(argv[arg_index++]));
- break;
- default:
- break;
- }
+ _TIFFfree(array);
+ }
+ else
+ {
+ switch (TIFFFieldDataType(fip))
+ {
+ case TIFF_BYTE:
+ case TIFF_SHORT:
+ case TIFF_SBYTE:
+ case TIFF_SSHORT:
+ ret = TIFFSetField(tiff, TIFFFieldTag(fip),
+ atoi(argv[arg_index++]));
+ break;
+ case TIFF_LONG:
+ case TIFF_SLONG:
+ case TIFF_IFD:
+ ret = TIFFSetField(tiff, TIFFFieldTag(fip),
+ atol(argv[arg_index++]));
+ break;
+ case TIFF_LONG8:
+ case TIFF_SLONG8:
+ case TIFF_IFD8:
+ ret = TIFFSetField(
+ tiff, TIFFFieldTag(fip),
+ strtoll(argv[arg_index++], (char **)NULL, 10));
+ break;
+ case TIFF_DOUBLE:
+ ret = TIFFSetField(tiff, TIFFFieldTag(fip),
+ atof(argv[arg_index++]));
+ break;
+ case TIFF_RATIONAL:
+ case TIFF_SRATIONAL:
+ case TIFF_FLOAT:
+ ret = TIFFSetField(tiff, TIFFFieldTag(fip),
+ (float)atof(argv[arg_index++]));
+ break;
+ default:
+ break;
+ }
}
if (ret != 1)
fprintf(stderr, "Failed to set %s\n", TIFFFieldName(fip));
arg_index += wc;
}
- } else if (strcmp(argv[arg_index],"-sf") == 0 && arg_index < argc-3) {
- FILE *fp;
+ }
+ else if (strcmp(argv[arg_index], "-sf") == 0 && arg_index < argc - 3)
+ {
+ FILE *fp;
const TIFFField *fip;
- char *text;
- size_t len;
+ char *text;
+ size_t len;
int ret;
arg_index++;
@@ -348,49 +390,61 @@ main(int argc, char* argv[])
if (!fip)
return EXIT_FAILURE;
- if (TIFFFieldDataType(fip) != TIFF_ASCII) {
- fprintf( stderr,
- "Only ASCII tags can be set from file. "
- "%s is not ASCII tag.\n", TIFFFieldName(fip) );
+ if (TIFFFieldDataType(fip) != TIFF_ASCII)
+ {
+ fprintf(stderr,
+ "Only ASCII tags can be set from file. "
+ "%s is not ASCII tag.\n",
+ TIFFFieldName(fip));
return EXIT_FAILURE;
}
arg_index++;
- fp = fopen( argv[arg_index], "rt" );
- if(fp == NULL) {
- perror( argv[arg_index] );
+ fp = fopen(argv[arg_index], "rt");
+ if (fp == NULL)
+ {
+ perror(argv[arg_index]);
continue;
}
- text = (char *) malloc(1000000);
- if(text == NULL) {
- fprintf( stderr,
- "Memory allocation error\n");
- fclose( fp );
+ text = (char *)malloc(1000000);
+ if (text == NULL)
+ {
+ fprintf(stderr, "Memory allocation error\n");
+ fclose(fp);
continue;
}
- len = fread( text, 1, 999999, fp );
+ len = fread(text, 1, 999999, fp);
text[len] = '\0';
- fclose( fp );
+ fclose(fp);
- if(TIFFFieldPassCount( fip )) {
- ret = TIFFSetField(tiff, TIFFFieldTag(fip), (uint16_t)len, text );
- } else {
- ret = TIFFSetField( tiff, TIFFFieldTag(fip), text );
+ if (TIFFFieldPassCount(fip))
+ {
+ ret =
+ TIFFSetField(tiff, TIFFFieldTag(fip), (uint16_t)len, text);
}
- if(!ret) {
- fprintf(stderr, "Failed to set %s from file %s\n",
+ else
+ {
+ ret = TIFFSetField(tiff, TIFFFieldTag(fip), text);
+ }
+ if (!ret)
+ {
+ fprintf(stderr, "Failed to set %s from file %s\n",
TIFFFieldName(fip), argv[arg_index]);
}
- _TIFFfree( text );
+ _TIFFfree(text);
arg_index++;
- } else if (strcmp(argv[arg_index],"-h") == 0 || strcmp(argv[arg_index],"--help") == 0) {
+ }
+ else if (strcmp(argv[arg_index], "-h") == 0 ||
+ strcmp(argv[arg_index], "--help") == 0)
+ {
usage(EXIT_SUCCESS);
- } else {
- fprintf(stderr, "Unrecognised option: %s\n",
- argv[arg_index]);
+ }
+ else
+ {
+ fprintf(stderr, "Unrecognised option: %s\n", argv[arg_index]);
usage(EXIT_FAILURE);
}
}
diff --git a/tools/tiffsplit.c b/tools/tiffsplit.c
index 2b968ff8..fcbec1d1 100644
--- a/tools/tiffsplit.c
+++ b/tools/tiffsplit.c
@@ -2,28 +2,28 @@
* Copyright (c) 1992-1997 Sam Leffler
* Copyright (c) 1992-1997 Silicon Graphics, Inc.
*
- * Permission to use, copy, modify, distribute, and sell this software and
+ * Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
- *
- * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
- * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- *
+ *
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ *
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
- * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
-#include "tif_config.h"
#include "libport.h"
+#include "tif_config.h"
#include <stdio.h>
#include <stdlib.h>
@@ -38,369 +38,433 @@
#define EXIT_FAILURE 1
#endif
-#define CopyField(tag, v) \
- if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
-#define CopyField2(tag, v1, v2) \
- if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
-#define CopyField3(tag, v1, v2, v3) \
- if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
+#define CopyField(tag, v) \
+ if (TIFFGetField(in, tag, &v)) \
+ TIFFSetField(out, tag, v)
+#define CopyField2(tag, v1, v2) \
+ if (TIFFGetField(in, tag, &v1, &v2)) \
+ TIFFSetField(out, tag, v1, v2)
+#define CopyField3(tag, v1, v2, v3) \
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) \
+ TIFFSetField(out, tag, v1, v2, v3)
#define PATH_LENGTH 8192
#define DEFAULT_MAX_MALLOC (256 * 1024 * 1024)
- /* malloc size limit (in bytes)
- * disabled when set to 0 */
+/* malloc size limit (in bytes)
+ * disabled when set to 0 */
static tmsize_t maxMalloc = DEFAULT_MAX_MALLOC;
static const char TIFF_SUFFIX[] = ".tif";
-static char fname[PATH_LENGTH];
+static char fname[PATH_LENGTH];
-static int tiffcp(TIFF*, TIFF*);
-static void newfilename(void);
-static int cpStrips(TIFF*, TIFF*);
-static int cpTiles(TIFF*, TIFF*);
+static int tiffcp(TIFF *, TIFF *);
+static void newfilename(void);
+static int cpStrips(TIFF *, TIFF *);
+static int cpTiles(TIFF *, TIFF *);
-static void usage(int);
+static void usage(int);
/**
* This custom malloc function enforce a maximum allocation size
*/
-static void* limitMalloc(tmsize_t s)
+static void *limitMalloc(tmsize_t s)
{
- /* tmsize_t is signed and _TIFFmalloc() converts s to size_t. Therefore check for negative s. */
- if (maxMalloc && ((s > maxMalloc) || (s < 0))) {
- fprintf(stderr, "MemoryLimitError: allocation of %" TIFF_SSIZE_FORMAT " bytes is forbidden. Limit is %" TIFF_SSIZE_FORMAT ".\n",
- s, maxMalloc);
- fprintf(stderr, " use -M option to change limit.\n");
- return NULL;
- }
- return _TIFFmalloc(s);
+ /* tmsize_t is signed and _TIFFmalloc() converts s to size_t. Therefore
+ * check for negative s. */
+ if (maxMalloc && ((s > maxMalloc) || (s < 0)))
+ {
+ fprintf(stderr,
+ "MemoryLimitError: allocation of %" TIFF_SSIZE_FORMAT
+ " bytes is forbidden. Limit is %" TIFF_SSIZE_FORMAT ".\n",
+ s, maxMalloc);
+ fprintf(stderr, " use -M option to change limit.\n");
+ return NULL;
+ }
+ return _TIFFmalloc(s);
}
-static void* limitRealloc(void* buf, tmsize_t s)
+static void *limitRealloc(void *buf, tmsize_t s)
{
- if (maxMalloc && ((s > maxMalloc) || (s < 0))) {
- fprintf(stderr, "MemoryLimitError: re-allocation of %" TIFF_SSIZE_FORMAT " bytes is forbidden. Limit is %" TIFF_SSIZE_FORMAT ".\n",
- s, maxMalloc);
- fprintf(stderr, " use -M option to change limit.\n");
- if (buf != NULL) _TIFFfree(buf);
- return NULL;
- }
- return _TIFFrealloc(buf, s);
+ if (maxMalloc && ((s > maxMalloc) || (s < 0)))
+ {
+ fprintf(stderr,
+ "MemoryLimitError: re-allocation of %" TIFF_SSIZE_FORMAT
+ " bytes is forbidden. Limit is %" TIFF_SSIZE_FORMAT ".\n",
+ s, maxMalloc);
+ fprintf(stderr, " use -M option to change limit.\n");
+ if (buf != NULL)
+ _TIFFfree(buf);
+ return NULL;
+ }
+ return _TIFFrealloc(buf, s);
}
-
-int
-main(int argc, char* argv[])
+int main(int argc, char *argv[])
{
- TIFF *in, *out;
+ TIFF *in, *out;
#if !HAVE_DECL_OPTARG
- extern char* optarg;
- extern int optind;
+ extern char *optarg;
+ extern int optind;
#endif
- int c;
-
- while ((c = getopt(argc, argv, "M:")) != -1) {
- switch (c) {
- case 'M':
- maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
- if ((maxMalloc == 0) && (optarg[0] != '0')) {
- fprintf(stderr, "tiffsplit: Error: Option -M was not followed by a number but <%s>\n", optarg);
- usage(EXIT_FAILURE);
- }
- break;
- case '?':
- usage(EXIT_SUCCESS);
- break;
- default:
- break;
- }
- }
-
- c = argc - optind;
- if (c < 1 || c > 2) usage(EXIT_FAILURE);
- if (c > 1) {
- strncpy(fname, argv[optind + 1], sizeof(fname));
- fname[sizeof(fname) - 1] = '\0';
- }
-
- TIFFOpenOptions* opts = TIFFOpenOptionsAlloc();
- if (opts == NULL) {
- return EXIT_FAILURE;
- }
- TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
- in = TIFFOpenExt(argv[optind], "r", opts);
- if (in == NULL) {
- fprintf(stderr, "tiffsplit: Error: Could not open %s \n", argv[optind]);
+ int c;
+
+ while ((c = getopt(argc, argv, "M:")) != -1)
+ {
+ switch (c)
+ {
+ case 'M':
+ maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
+ if ((maxMalloc == 0) && (optarg[0] != '0'))
+ {
+ fprintf(stderr,
+ "tiffsplit: Error: Option -M was not followed by a "
+ "number but <%s>\n",
+ optarg);
+ usage(EXIT_FAILURE);
+ }
+ break;
+ case '?':
+ usage(EXIT_SUCCESS);
+ break;
+ default:
+ break;
+ }
+ }
+
+ c = argc - optind;
+ if (c < 1 || c > 2)
+ usage(EXIT_FAILURE);
+ if (c > 1)
+ {
+ strncpy(fname, argv[optind + 1], sizeof(fname));
+ fname[sizeof(fname) - 1] = '\0';
+ }
+
+ TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
+ if (opts == NULL)
+ {
+ return EXIT_FAILURE;
+ }
+ TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
+ in = TIFFOpenExt(argv[optind], "r", opts);
+ if (in == NULL)
+ {
+ fprintf(stderr, "tiffsplit: Error: Could not open %s \n", argv[optind]);
TIFFOpenOptionsFree(opts);
- usage(EXIT_FAILURE);
- }
-
- do {
- size_t path_len;
- char* path = NULL;
-
- newfilename();
-
- path_len = strlen(fname) + sizeof(TIFF_SUFFIX);
- path = (char*)limitMalloc(path_len);
- if (!path) {
- fprintf(stderr, "tiffsplit: Error: Can't allocate %"TIFF_SSIZE_FORMAT" bytes for path-variable.\n", path_len);
- TIFFClose(in);
- TIFFOpenOptionsFree(opts);
- return (EXIT_FAILURE);
- }
- strncpy(path, fname, path_len);
- path[path_len - 1] = '\0';
- strncat(path, TIFF_SUFFIX, path_len - strlen(path) - 1);
- out = TIFFOpenExt(path, TIFFIsBigEndian(in) ? "wb" : "wl", opts);
-
- if (out == NULL) {
- TIFFClose(in);
- fprintf(stderr, "tiffsplit: Error: Could not open output file %s \n", path);
- _TIFFfree(path);
- TIFFOpenOptionsFree(opts);
- return (EXIT_FAILURE);
- }
- _TIFFfree(path);
- if (!tiffcp(in, out)) {
- TIFFClose(in);
- TIFFClose(out);
- TIFFOpenOptionsFree(opts);
- fprintf(stderr, "tiffsplit: Error: Could not copy data from input to output.\n");
- return (EXIT_FAILURE);
-
- }
- TIFFClose(out);
- } while (TIFFReadDirectory(in));
-
- TIFFOpenOptionsFree(opts);
- (void)TIFFClose(in);
-
- return (EXIT_SUCCESS);
+ usage(EXIT_FAILURE);
+ }
+
+ do
+ {
+ size_t path_len;
+ char *path = NULL;
+
+ newfilename();
+
+ path_len = strlen(fname) + sizeof(TIFF_SUFFIX);
+ path = (char *)limitMalloc(path_len);
+ if (!path)
+ {
+ fprintf(stderr,
+ "tiffsplit: Error: Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes for path-variable.\n",
+ path_len);
+ TIFFClose(in);
+ TIFFOpenOptionsFree(opts);
+ return (EXIT_FAILURE);
+ }
+ strncpy(path, fname, path_len);
+ path[path_len - 1] = '\0';
+ strncat(path, TIFF_SUFFIX, path_len - strlen(path) - 1);
+ out = TIFFOpenExt(path, TIFFIsBigEndian(in) ? "wb" : "wl", opts);
+
+ if (out == NULL)
+ {
+ TIFFClose(in);
+ fprintf(stderr,
+ "tiffsplit: Error: Could not open output file %s \n", path);
+ _TIFFfree(path);
+ TIFFOpenOptionsFree(opts);
+ return (EXIT_FAILURE);
+ }
+ _TIFFfree(path);
+ if (!tiffcp(in, out))
+ {
+ TIFFClose(in);
+ TIFFClose(out);
+ TIFFOpenOptionsFree(opts);
+ fprintf(stderr, "tiffsplit: Error: Could not copy data from input "
+ "to output.\n");
+ return (EXIT_FAILURE);
+ }
+ TIFFClose(out);
+ } while (TIFFReadDirectory(in));
+
+ TIFFOpenOptionsFree(opts);
+ (void)TIFFClose(in);
+
+ return (EXIT_SUCCESS);
}
-static void
-newfilename(void)
+static void newfilename(void)
{
- static int first = 1;
- static long lastTurn;
- static long fnum;
- static short defname;
- static char *fpnt;
-
- if (first) {
- if (fname[0]) {
- fpnt = fname + strlen(fname);
- defname = 0;
- } else {
- fname[0] = 'x';
- fpnt = fname + 1;
- defname = 1;
- }
- first = 0;
- }
-#define MAXFILES 17576
- if (fnum == MAXFILES) {
- if (!defname || fname[0] == 'z') {
- fprintf(stderr, "tiffsplit: too many files.\n");
- exit(EXIT_FAILURE);
- }
- fname[0]++;
- fnum = 0;
- }
- if (fnum % 676 == 0) {
- if (fnum != 0) {
- /*
- * advance to next letter every 676 pages
- * condition for 'z'++ will be covered above
- */
- fpnt[0]++;
- } else {
- /*
- * set to 'a' if we are on the very first file
- */
- fpnt[0] = 'a';
- }
- /*
- * set the value of the last turning point
- */
- lastTurn = fnum;
- }
- /*
- * start from 0 every 676 times (provided by lastTurn)
- * this keeps us within a-z boundaries
- */
- fpnt[1] = (char)((fnum - lastTurn) / 26) + 'a';
- /*
- * cycle last letter every file, from a-z, then repeat
- */
- fpnt[2] = (char)(fnum % 26) + 'a';
- fnum++;
+ static int first = 1;
+ static long lastTurn;
+ static long fnum;
+ static short defname;
+ static char *fpnt;
+
+ if (first)
+ {
+ if (fname[0])
+ {
+ fpnt = fname + strlen(fname);
+ defname = 0;
+ }
+ else
+ {
+ fname[0] = 'x';
+ fpnt = fname + 1;
+ defname = 1;
+ }
+ first = 0;
+ }
+#define MAXFILES 17576
+ if (fnum == MAXFILES)
+ {
+ if (!defname || fname[0] == 'z')
+ {
+ fprintf(stderr, "tiffsplit: too many files.\n");
+ exit(EXIT_FAILURE);
+ }
+ fname[0]++;
+ fnum = 0;
+ }
+ if (fnum % 676 == 0)
+ {
+ if (fnum != 0)
+ {
+ /*
+ * advance to next letter every 676 pages
+ * condition for 'z'++ will be covered above
+ */
+ fpnt[0]++;
+ }
+ else
+ {
+ /*
+ * set to 'a' if we are on the very first file
+ */
+ fpnt[0] = 'a';
+ }
+ /*
+ * set the value of the last turning point
+ */
+ lastTurn = fnum;
+ }
+ /*
+ * start from 0 every 676 times (provided by lastTurn)
+ * this keeps us within a-z boundaries
+ */
+ fpnt[1] = (char)((fnum - lastTurn) / 26) + 'a';
+ /*
+ * cycle last letter every file, from a-z, then repeat
+ */
+ fpnt[2] = (char)(fnum % 26) + 'a';
+ fnum++;
}
-static int
-tiffcp(TIFF* in, TIFF* out)
+static int tiffcp(TIFF *in, TIFF *out)
{
- uint16_t bitspersample, samplesperpixel, compression, shortv, *shortav;
- uint32_t w, l;
- float floatv;
- char *stringv;
- uint32_t longv;
-
- CopyField(TIFFTAG_SUBFILETYPE, longv);
- CopyField(TIFFTAG_TILEWIDTH, w);
- CopyField(TIFFTAG_TILELENGTH, l);
- CopyField(TIFFTAG_IMAGEWIDTH, w);
- CopyField(TIFFTAG_IMAGELENGTH, l);
- CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample);
- CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
- CopyField(TIFFTAG_COMPRESSION, compression);
- if (compression == COMPRESSION_JPEG) {
- uint32_t count = 0;
- void *table = NULL;
- if (TIFFGetField(in, TIFFTAG_JPEGTABLES, &count, &table)
- && count > 0 && table) {
- TIFFSetField(out, TIFFTAG_JPEGTABLES, count, table);
- }
- }
- CopyField(TIFFTAG_PHOTOMETRIC, shortv);
- CopyField(TIFFTAG_PREDICTOR, shortv);
- CopyField(TIFFTAG_THRESHHOLDING, shortv);
- CopyField(TIFFTAG_FILLORDER, shortv);
- CopyField(TIFFTAG_ORIENTATION, shortv);
- CopyField(TIFFTAG_MINSAMPLEVALUE, shortv);
- CopyField(TIFFTAG_MAXSAMPLEVALUE, shortv);
- CopyField(TIFFTAG_XRESOLUTION, floatv);
- CopyField(TIFFTAG_YRESOLUTION, floatv);
- CopyField(TIFFTAG_GROUP3OPTIONS, longv);
- CopyField(TIFFTAG_GROUP4OPTIONS, longv);
- CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
- CopyField(TIFFTAG_PLANARCONFIG, shortv);
- CopyField(TIFFTAG_ROWSPERSTRIP, longv);
- CopyField(TIFFTAG_XPOSITION, floatv);
- CopyField(TIFFTAG_YPOSITION, floatv);
- CopyField(TIFFTAG_IMAGEDEPTH, longv);
- CopyField(TIFFTAG_TILEDEPTH, longv);
- CopyField(TIFFTAG_SAMPLEFORMAT, shortv);
- CopyField2(TIFFTAG_EXTRASAMPLES, shortv, shortav);
- {
- uint16_t *red, *green, *blue;
- CopyField3(TIFFTAG_COLORMAP, red, green, blue);
- }
- {
- uint16_t shortv2;
- CopyField2(TIFFTAG_PAGENUMBER, shortv, shortv2);
- }
- CopyField(TIFFTAG_ARTIST, stringv);
- CopyField(TIFFTAG_IMAGEDESCRIPTION, stringv);
- CopyField(TIFFTAG_MAKE, stringv);
- CopyField(TIFFTAG_MODEL, stringv);
- CopyField(TIFFTAG_SOFTWARE, stringv);
- CopyField(TIFFTAG_DATETIME, stringv);
- CopyField(TIFFTAG_HOSTCOMPUTER, stringv);
- CopyField(TIFFTAG_PAGENAME, stringv);
- CopyField(TIFFTAG_DOCUMENTNAME, stringv);
- CopyField(TIFFTAG_BADFAXLINES, longv);
- CopyField(TIFFTAG_CLEANFAXDATA, longv);
- CopyField(TIFFTAG_CONSECUTIVEBADFAXLINES, longv);
- CopyField(TIFFTAG_FAXRECVPARAMS, longv);
- CopyField(TIFFTAG_FAXRECVTIME, longv);
- CopyField(TIFFTAG_FAXSUBADDRESS, stringv);
- CopyField(TIFFTAG_FAXDCS, stringv);
- if (TIFFIsTiled(in))
- return (cpTiles(in, out));
- else
- return (cpStrips(in, out));
+ uint16_t bitspersample, samplesperpixel, compression, shortv, *shortav;
+ uint32_t w, l;
+ float floatv;
+ char *stringv;
+ uint32_t longv;
+
+ CopyField(TIFFTAG_SUBFILETYPE, longv);
+ CopyField(TIFFTAG_TILEWIDTH, w);
+ CopyField(TIFFTAG_TILELENGTH, l);
+ CopyField(TIFFTAG_IMAGEWIDTH, w);
+ CopyField(TIFFTAG_IMAGELENGTH, l);
+ CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample);
+ CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
+ CopyField(TIFFTAG_COMPRESSION, compression);
+ if (compression == COMPRESSION_JPEG)
+ {
+ uint32_t count = 0;
+ void *table = NULL;
+ if (TIFFGetField(in, TIFFTAG_JPEGTABLES, &count, &table) && count > 0 &&
+ table)
+ {
+ TIFFSetField(out, TIFFTAG_JPEGTABLES, count, table);
+ }
+ }
+ CopyField(TIFFTAG_PHOTOMETRIC, shortv);
+ CopyField(TIFFTAG_PREDICTOR, shortv);
+ CopyField(TIFFTAG_THRESHHOLDING, shortv);
+ CopyField(TIFFTAG_FILLORDER, shortv);
+ CopyField(TIFFTAG_ORIENTATION, shortv);
+ CopyField(TIFFTAG_MINSAMPLEVALUE, shortv);
+ CopyField(TIFFTAG_MAXSAMPLEVALUE, shortv);
+ CopyField(TIFFTAG_XRESOLUTION, floatv);
+ CopyField(TIFFTAG_YRESOLUTION, floatv);
+ CopyField(TIFFTAG_GROUP3OPTIONS, longv);
+ CopyField(TIFFTAG_GROUP4OPTIONS, longv);
+ CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
+ CopyField(TIFFTAG_PLANARCONFIG, shortv);
+ CopyField(TIFFTAG_ROWSPERSTRIP, longv);
+ CopyField(TIFFTAG_XPOSITION, floatv);
+ CopyField(TIFFTAG_YPOSITION, floatv);
+ CopyField(TIFFTAG_IMAGEDEPTH, longv);
+ CopyField(TIFFTAG_TILEDEPTH, longv);
+ CopyField(TIFFTAG_SAMPLEFORMAT, shortv);
+ CopyField2(TIFFTAG_EXTRASAMPLES, shortv, shortav);
+ {
+ uint16_t *red, *green, *blue;
+ CopyField3(TIFFTAG_COLORMAP, red, green, blue);
+ }
+ {
+ uint16_t shortv2;
+ CopyField2(TIFFTAG_PAGENUMBER, shortv, shortv2);
+ }
+ CopyField(TIFFTAG_ARTIST, stringv);
+ CopyField(TIFFTAG_IMAGEDESCRIPTION, stringv);
+ CopyField(TIFFTAG_MAKE, stringv);
+ CopyField(TIFFTAG_MODEL, stringv);
+ CopyField(TIFFTAG_SOFTWARE, stringv);
+ CopyField(TIFFTAG_DATETIME, stringv);
+ CopyField(TIFFTAG_HOSTCOMPUTER, stringv);
+ CopyField(TIFFTAG_PAGENAME, stringv);
+ CopyField(TIFFTAG_DOCUMENTNAME, stringv);
+ CopyField(TIFFTAG_BADFAXLINES, longv);
+ CopyField(TIFFTAG_CLEANFAXDATA, longv);
+ CopyField(TIFFTAG_CONSECUTIVEBADFAXLINES, longv);
+ CopyField(TIFFTAG_FAXRECVPARAMS, longv);
+ CopyField(TIFFTAG_FAXRECVTIME, longv);
+ CopyField(TIFFTAG_FAXSUBADDRESS, stringv);
+ CopyField(TIFFTAG_FAXDCS, stringv);
+ if (TIFFIsTiled(in))
+ return (cpTiles(in, out));
+ else
+ return (cpStrips(in, out));
}
-static int
-cpStrips(TIFF* in, TIFF* out)
+static int cpStrips(TIFF *in, TIFF *out)
{
- tmsize_t bufsize = TIFFStripSize(in);
- unsigned char* buf = (unsigned char*)limitMalloc(bufsize);
- if (buf) {
- tstrip_t s, ns = TIFFNumberOfStrips(in);
- uint64_t* bytecounts;
-
- if (!TIFFGetField(in, TIFFTAG_STRIPBYTECOUNTS, &bytecounts)) {
- fprintf(stderr, "tiffsplit: strip byte counts are missing\n");
- _TIFFfree(buf);
- return (0);
- }
- for (s = 0; s < ns; s++) {
- if (bytecounts[s] > (uint64_t)bufsize) {
- buf = (unsigned char*)limitRealloc(buf, (tmsize_t)bytecounts[s]);
- if (!buf) {
- fprintf(stderr, "tiffsplit: Error: Can't re-allocate %"TIFF_SSIZE_FORMAT" bytes for strip-size.\n", (tmsize_t)bytecounts[s]);
- return (0);
- }
- bufsize = (tmsize_t)bytecounts[s];
- }
- if (TIFFReadRawStrip(in, s, buf, (tmsize_t)bytecounts[s]) < 0 ||
- TIFFWriteRawStrip(out, s, buf, (tmsize_t)bytecounts[s]) < 0) {
- _TIFFfree(buf);
- return (0);
- }
- }
- _TIFFfree(buf);
- return (1);
- } else {
- fprintf(stderr, "tiffsplit: Error: Can't allocate %"TIFF_SSIZE_FORMAT" bytes for strip-size.\n", bufsize);
- }
- return (0);
+ tmsize_t bufsize = TIFFStripSize(in);
+ unsigned char *buf = (unsigned char *)limitMalloc(bufsize);
+ if (buf)
+ {
+ tstrip_t s, ns = TIFFNumberOfStrips(in);
+ uint64_t *bytecounts;
+
+ if (!TIFFGetField(in, TIFFTAG_STRIPBYTECOUNTS, &bytecounts))
+ {
+ fprintf(stderr, "tiffsplit: strip byte counts are missing\n");
+ _TIFFfree(buf);
+ return (0);
+ }
+ for (s = 0; s < ns; s++)
+ {
+ if (bytecounts[s] > (uint64_t)bufsize)
+ {
+ buf =
+ (unsigned char *)limitRealloc(buf, (tmsize_t)bytecounts[s]);
+ if (!buf)
+ {
+ fprintf(stderr,
+ "tiffsplit: Error: Can't re-allocate "
+ "%" TIFF_SSIZE_FORMAT " bytes for strip-size.\n",
+ (tmsize_t)bytecounts[s]);
+ return (0);
+ }
+ bufsize = (tmsize_t)bytecounts[s];
+ }
+ if (TIFFReadRawStrip(in, s, buf, (tmsize_t)bytecounts[s]) < 0 ||
+ TIFFWriteRawStrip(out, s, buf, (tmsize_t)bytecounts[s]) < 0)
+ {
+ _TIFFfree(buf);
+ return (0);
+ }
+ }
+ _TIFFfree(buf);
+ return (1);
+ }
+ else
+ {
+ fprintf(stderr,
+ "tiffsplit: Error: Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes for strip-size.\n",
+ bufsize);
+ }
+ return (0);
}
-static int
-cpTiles(TIFF* in, TIFF* out)
+static int cpTiles(TIFF *in, TIFF *out)
{
- tmsize_t bufsize = TIFFTileSize(in);
- unsigned char* buf = (unsigned char*)limitMalloc(bufsize);
-
- if (buf) {
- ttile_t t, nt = TIFFNumberOfTiles(in);
- uint64_t* bytecounts;
-
- if (!TIFFGetField(in, TIFFTAG_TILEBYTECOUNTS, &bytecounts)) {
- fprintf(stderr, "tiffsplit: tile byte counts are missing\n");
- _TIFFfree(buf);
- return (0);
- }
- for (t = 0; t < nt; t++) {
- if (bytecounts[t] > (uint64_t) bufsize) {
- buf = (unsigned char*)limitRealloc(buf, (tmsize_t)bytecounts[t]);
- if (!buf) {
- fprintf(stderr, "tiffsplit: Error: Can't re-allocate %"TIFF_SSIZE_FORMAT" bytes for tile-size.\n", (tmsize_t)bytecounts[t]);
- return (0);
- }
- bufsize = (tmsize_t)bytecounts[t];
- }
- if (TIFFReadRawTile(in, t, buf, (tmsize_t)bytecounts[t]) < 0 ||
- TIFFWriteRawTile(out, t, buf, (tmsize_t)bytecounts[t]) < 0) {
- _TIFFfree(buf);
- return (0);
- }
- }
- _TIFFfree(buf);
- return (1);
- } else {
- fprintf(stderr, "tiffsplit: Error: Can't allocate %"TIFF_SSIZE_FORMAT" bytes for tile-size.\n", bufsize);
- }
- return (0);
+ tmsize_t bufsize = TIFFTileSize(in);
+ unsigned char *buf = (unsigned char *)limitMalloc(bufsize);
+
+ if (buf)
+ {
+ ttile_t t, nt = TIFFNumberOfTiles(in);
+ uint64_t *bytecounts;
+
+ if (!TIFFGetField(in, TIFFTAG_TILEBYTECOUNTS, &bytecounts))
+ {
+ fprintf(stderr, "tiffsplit: tile byte counts are missing\n");
+ _TIFFfree(buf);
+ return (0);
+ }
+ for (t = 0; t < nt; t++)
+ {
+ if (bytecounts[t] > (uint64_t)bufsize)
+ {
+ buf =
+ (unsigned char *)limitRealloc(buf, (tmsize_t)bytecounts[t]);
+ if (!buf)
+ {
+ fprintf(stderr,
+ "tiffsplit: Error: Can't re-allocate "
+ "%" TIFF_SSIZE_FORMAT " bytes for tile-size.\n",
+ (tmsize_t)bytecounts[t]);
+ return (0);
+ }
+ bufsize = (tmsize_t)bytecounts[t];
+ }
+ if (TIFFReadRawTile(in, t, buf, (tmsize_t)bytecounts[t]) < 0 ||
+ TIFFWriteRawTile(out, t, buf, (tmsize_t)bytecounts[t]) < 0)
+ {
+ _TIFFfree(buf);
+ return (0);
+ }
+ }
+ _TIFFfree(buf);
+ return (1);
+ }
+ else
+ {
+ fprintf(stderr,
+ "tiffsplit: Error: Can't allocate %" TIFF_SSIZE_FORMAT
+ " bytes for tile-size.\n",
+ bufsize);
+ }
+ return (0);
}
-static void
-usage(int code)
+static void usage(int code)
{
- FILE* out = (code == EXIT_SUCCESS) ? stdout : stderr;
-
-
- fprintf(out, "\n\n%s\n\n", TIFFGetVersion());
- fprintf(out, "Split a multi-image TIFF into single-image TIFF files\n\n");
- fprintf(out, "usage: tiffsplit [option] input.tif [prefix]\n");
- fprintf(out, "where option is:\n");
- fprintf(out, " -M size set the memory allocation limit in MiB. 0 to disable limit.\n");
- exit(code);
+ FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
+
+ fprintf(out, "\n\n%s\n\n", TIFFGetVersion());
+ fprintf(out, "Split a multi-image TIFF into single-image TIFF files\n\n");
+ fprintf(out, "usage: tiffsplit [option] input.tif [prefix]\n");
+ fprintf(out, "where option is:\n");
+ fprintf(out, " -M size set the memory allocation limit in MiB. 0 to "
+ "disable limit.\n");
+ exit(code);
}