New comit of SDL2
[supertux.git] / src / SDL2 / external / tiff-4.0.3 / tools / bmp2tiff.c
1 /* $Id: bmp2tiff.c,v 1.23 2010-03-10 18:56:49 bfriesen Exp $
2  *
3  * Project:  libtiff tools
4  * Purpose:  Convert Windows BMP files in TIFF.
5  * Author:   Andrey Kiselev, dron@ak4719.spb.edu
6  *
7  ******************************************************************************
8  * Copyright (c) 2004, Andrey Kiselev <dron@ak4719.spb.edu>
9  *
10  * Permission to use, copy, modify, distribute, and sell this software and 
11  * its documentation for any purpose is hereby granted without fee, provided
12  * that (i) the above copyright notices and this permission notice appear in
13  * all copies of the software and related documentation, and (ii) the names of
14  * Sam Leffler and Silicon Graphics may not be used in any advertising or
15  * publicity relating to the software without the specific, prior written
16  * permission of Sam Leffler and Silicon Graphics.
17  * 
18  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
19  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
20  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
21  * 
22  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
23  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
24  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
25  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
26  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
27  * OF THIS SOFTWARE.
28  */
29
30 #include "tif_config.h"
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <ctype.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38
39 #ifdef HAVE_UNISTD_H
40 # include <unistd.h>
41 #endif
42
43 #if HAVE_FCNTL_H
44 # include <fcntl.h>
45 #endif
46
47 #if HAVE_SYS_TYPES_H
48 # include <sys/types.h>
49 #endif
50
51 #if HAVE_IO_H
52 # include <io.h>
53 #endif
54
55 #ifdef NEED_LIBPORT
56 # include "libport.h"
57 #endif
58
59 #include "tiffio.h"
60
61 #ifndef O_BINARY
62 # define O_BINARY 0
63 #endif
64
65 enum BMPType
66 {
67     BMPT_WIN4,      /* BMP used in Windows 3.0/NT 3.51/95 */
68     BMPT_WIN5,      /* BMP used in Windows NT 4.0/98/Me/2000/XP */
69     BMPT_OS21,      /* BMP used in OS/2 PM 1.x */
70     BMPT_OS22       /* BMP used in OS/2 PM 2.x */
71 };
72
73 /*
74  * Bitmap file consists of a BMPFileHeader structure followed by a
75  * BMPInfoHeader structure. An array of BMPColorEntry structures (also called
76  * a colour table) follows the bitmap information header structure. The colour
77  * table is followed by a second array of indexes into the colour table (the
78  * actual bitmap data). Data may be comressed, for 4-bpp and 8-bpp used RLE
79  * compression.
80  *
81  * +---------------------+
82  * | BMPFileHeader       |
83  * +---------------------+
84  * | BMPInfoHeader       |
85  * +---------------------+
86  * | BMPColorEntry array |
87  * +---------------------+
88  * | Colour-index array  |
89  * +---------------------+
90  *
91  * All numbers stored in Intel order with least significant byte first.
92  */
93
94 enum BMPComprMethod
95 {
96     BMPC_RGB = 0L,          /* Uncompressed */
97     BMPC_RLE8 = 1L,         /* RLE for 8 bpp images */
98     BMPC_RLE4 = 2L,         /* RLE for 4 bpp images */
99     BMPC_BITFIELDS = 3L,    /* Bitmap is not compressed and the colour table
100                              * consists of three DWORD color masks that specify
101                              * the red, green, and blue components of each
102                              * pixel. This is valid when used with
103                              * 16- and 32-bpp bitmaps. */
104     BMPC_JPEG = 4L,         /* Indicates that the image is a JPEG image. */
105     BMPC_PNG = 5L           /* Indicates that the image is a PNG image. */
106 };
107
108 enum BMPLCSType                 /* Type of logical color space. */
109 {
110     BMPLT_CALIBRATED_RGB = 0,   /* This value indicates that endpoints and
111                                  * gamma values are given in the appropriate
112                                  * fields. */
113     BMPLT_DEVICE_RGB = 1,
114     BMPLT_DEVICE_CMYK = 2
115 };
116
117 typedef struct
118 {
119     int32   iCIEX;
120     int32   iCIEY;
121     int32   iCIEZ;
122 } BMPCIEXYZ;
123
124 typedef struct                  /* This structure contains the x, y, and z */
125 {                               /* coordinates of the three colors that */
126                                 /* correspond */
127     BMPCIEXYZ   iCIERed;        /* to the red, green, and blue endpoints for */
128     BMPCIEXYZ   iCIEGreen;      /* a specified logical color space. */
129     BMPCIEXYZ   iCIEBlue;
130 } BMPCIEXYZTriple;
131
132 typedef struct
133 {
134     char        bType[2];       /* Signature "BM" */
135     uint32      iSize;          /* Size in bytes of the bitmap file. Should
136                                  * always be ignored while reading because
137                                  * of error in Windows 3.0 SDK's description
138                                  * of this field */
139     uint16      iReserved1;     /* Reserved, set as 0 */
140     uint16      iReserved2;     /* Reserved, set as 0 */
141     uint32      iOffBits;       /* Offset of the image from file start in bytes */
142 } BMPFileHeader;
143
144 /* File header size in bytes: */
145 const int       BFH_SIZE = 14;
146
147 typedef struct
148 {
149     uint32      iSize;          /* Size of BMPInfoHeader structure in bytes.
150                                  * Should be used to determine start of the
151                                  * colour table */
152     int32       iWidth;         /* Image width */
153     int32       iHeight;        /* Image height. If positive, image has bottom
154                                  * left origin, if negative --- top left. */
155     int16       iPlanes;        /* Number of image planes (must be set to 1) */
156     int16       iBitCount;      /* Number of bits per pixel (1, 4, 8, 16, 24
157                                  * or 32). If 0 then the number of bits per
158                                  * pixel is specified or is implied by the
159                                  * JPEG or PNG format. */
160     uint32      iCompression;   /* Compression method */
161     uint32      iSizeImage;     /* Size of uncomressed image in bytes. May
162                                  * be 0 for BMPC_RGB bitmaps. If iCompression
163                                  * is BI_JPEG or BI_PNG, iSizeImage indicates
164                                  * the size of the JPEG or PNG image buffer. */
165     int32       iXPelsPerMeter; /* X resolution, pixels per meter (0 if not used) */
166     int32       iYPelsPerMeter; /* Y resolution, pixels per meter (0 if not used) */
167     uint32      iClrUsed;       /* Size of colour table. If 0, iBitCount should
168                                  * be used to calculate this value
169                                  * (1<<iBitCount). This value should be
170                                  * unsigned for proper shifting. */
171     int32       iClrImportant;  /* Number of important colours. If 0, all
172                                  * colours are required */
173
174     /*
175      * Fields above should be used for bitmaps, compatible with Windows NT 3.51
176      * and earlier. Windows 98/Me, Windows 2000/XP introduces additional fields:
177      */
178
179     int32       iRedMask;       /* Colour mask that specifies the red component
180                                  * of each pixel, valid only if iCompression
181                                  * is set to BI_BITFIELDS. */
182     int32       iGreenMask;     /* The same for green component */
183     int32       iBlueMask;      /* The same for blue component */
184     int32       iAlphaMask;     /* Colour mask that specifies the alpha
185                                  * component of each pixel. */
186     uint32      iCSType;        /* Colour space of the DIB. */
187     BMPCIEXYZTriple sEndpoints; /* This member is ignored unless the iCSType
188                                  * member specifies BMPLT_CALIBRATED_RGB. */
189     int32       iGammaRed;      /* Toned response curve for red. This member
190                                  * is ignored unless color values are
191                                  * calibrated RGB values and iCSType is set to
192                                  * BMPLT_CALIBRATED_RGB. Specified
193                                  * in 16^16 format. */
194     int32       iGammaGreen;    /* Toned response curve for green. */
195     int32       iGammaBlue;     /* Toned response curve for blue. */
196 } BMPInfoHeader;
197
198 /*
199  * Info header size in bytes:
200  */
201 const unsigned int  BIH_WIN4SIZE = 40; /* for BMPT_WIN4 */
202 const unsigned int  BIH_WIN5SIZE = 57; /* for BMPT_WIN5 */
203 const unsigned int  BIH_OS21SIZE = 12; /* for BMPT_OS21 */
204 const unsigned int  BIH_OS22SIZE = 64; /* for BMPT_OS22 */
205
206 /*
207  * We will use plain byte array instead of this structure, but declaration
208  * provided for reference
209  */
210 typedef struct
211 {
212     char       bBlue;
213     char       bGreen;
214     char       bRed;
215     char       bReserved;      /* Must be 0 */
216 } BMPColorEntry;
217
218 static  uint16 compression = (uint16) -1;
219 static  int jpegcolormode = JPEGCOLORMODE_RGB;
220 static  int quality = 75;               /* JPEG quality */
221 static  uint16 predictor = 0;
222
223 static void usage(void);
224 static int processCompressOptions(char*);
225 static void rearrangePixels(char *, uint32, uint32);
226
227 int
228 main(int argc, char* argv[])
229 {
230         uint32  width, length;
231         uint16  nbands = 1;             /* number of bands in input image */
232         uint16  depth = 8;              /* bits per pixel in input image */
233         uint32  rowsperstrip = (uint32) -1;
234         uint16  photometric = PHOTOMETRIC_MINISBLACK;
235         int     fd = 0;
236         struct stat instat;
237         char    *outfilename = NULL, *infilename = NULL;
238         TIFF    *out = NULL;
239
240         BMPFileHeader file_hdr;
241         BMPInfoHeader info_hdr;
242         int     bmp_type;
243         uint32  clr_tbl_size, n_clr_elems = 3;
244         unsigned char *clr_tbl;
245         unsigned short *red_tbl = NULL, *green_tbl = NULL, *blue_tbl = NULL;
246         uint32  row, clr;
247
248         int     c;
249         extern int optind;
250         extern char* optarg;
251
252         while ((c = getopt(argc, argv, "c:r:o:h")) != -1) {
253                 switch (c) {
254                 case 'c':               /* compression scheme */
255                         if (!processCompressOptions(optarg))
256                                 usage();
257                         break;
258                 case 'r':               /* rows/strip */
259                         rowsperstrip = atoi(optarg);
260                         break;
261                 case 'o':
262                         outfilename = optarg;
263                         break;
264                 case 'h':
265                         usage();
266                 default:
267                         break;
268                 }
269         }
270
271         if (argc - optind < 2)
272                 usage();
273
274         if (outfilename == NULL)
275                 outfilename = argv[argc-1];
276         out = TIFFOpen(outfilename, "w");
277         if (out == NULL) {
278                 TIFFError(infilename, "Cannot open file %s for output",
279                           outfilename);
280                 goto bad3;
281         }
282         
283
284         while (optind < argc-1) {
285                 infilename = argv[optind];
286                 optind++;
287             
288                 fd = open(infilename, O_RDONLY|O_BINARY, 0);
289                 if (fd < 0) {
290                         TIFFError(infilename, "Cannot open input file");
291                         return -1;
292                 }
293
294                 read(fd, file_hdr.bType, 2);
295                 if(file_hdr.bType[0] != 'B' || file_hdr.bType[1] != 'M') {
296                         TIFFError(infilename, "File is not BMP");
297                         goto bad;
298                 }
299
300 /* -------------------------------------------------------------------- */
301 /*      Read the BMPFileHeader. We need iOffBits value only             */
302 /* -------------------------------------------------------------------- */
303                 lseek(fd, 10, SEEK_SET);
304                 read(fd, &file_hdr.iOffBits, 4);
305 #ifdef WORDS_BIGENDIAN
306                 TIFFSwabLong(&file_hdr.iOffBits);
307 #endif
308                 fstat(fd, &instat);
309                 file_hdr.iSize = instat.st_size;
310
311 /* -------------------------------------------------------------------- */
312 /*      Read the BMPInfoHeader.                                         */
313 /* -------------------------------------------------------------------- */
314
315                 lseek(fd, BFH_SIZE, SEEK_SET);
316                 read(fd, &info_hdr.iSize, 4);
317 #ifdef WORDS_BIGENDIAN
318                 TIFFSwabLong(&info_hdr.iSize);
319 #endif
320
321                 if (info_hdr.iSize == BIH_WIN4SIZE)
322                         bmp_type = BMPT_WIN4;
323                 else if (info_hdr.iSize == BIH_OS21SIZE)
324                         bmp_type = BMPT_OS21;
325                 else if (info_hdr.iSize == BIH_OS22SIZE
326                          || info_hdr.iSize == 16)
327                         bmp_type = BMPT_OS22;
328                 else
329                         bmp_type = BMPT_WIN5;
330
331                 if (bmp_type == BMPT_WIN4
332                     || bmp_type == BMPT_WIN5
333                     || bmp_type == BMPT_OS22) {
334                         read(fd, &info_hdr.iWidth, 4);
335                         read(fd, &info_hdr.iHeight, 4);
336                         read(fd, &info_hdr.iPlanes, 2);
337                         read(fd, &info_hdr.iBitCount, 2);
338                         read(fd, &info_hdr.iCompression, 4);
339                         read(fd, &info_hdr.iSizeImage, 4);
340                         read(fd, &info_hdr.iXPelsPerMeter, 4);
341                         read(fd, &info_hdr.iYPelsPerMeter, 4);
342                         read(fd, &info_hdr.iClrUsed, 4);
343                         read(fd, &info_hdr.iClrImportant, 4);
344 #ifdef WORDS_BIGENDIAN
345                         TIFFSwabLong((uint32*) &info_hdr.iWidth);
346                         TIFFSwabLong((uint32*) &info_hdr.iHeight);
347                         TIFFSwabShort((uint16*) &info_hdr.iPlanes);
348                         TIFFSwabShort((uint16*) &info_hdr.iBitCount);
349                         TIFFSwabLong((uint32*) &info_hdr.iCompression);
350                         TIFFSwabLong((uint32*) &info_hdr.iSizeImage);
351                         TIFFSwabLong((uint32*) &info_hdr.iXPelsPerMeter);
352                         TIFFSwabLong((uint32*) &info_hdr.iYPelsPerMeter);
353                         TIFFSwabLong((uint32*) &info_hdr.iClrUsed);
354                         TIFFSwabLong((uint32*) &info_hdr.iClrImportant);
355 #endif
356                         n_clr_elems = 4;
357                 }
358
359                 if (bmp_type == BMPT_OS22) {
360                         /* 
361                          * FIXME: different info in different documents
362                          * regarding this!
363                          */
364                          n_clr_elems = 3;
365                 }
366
367                 if (bmp_type == BMPT_OS21) {
368                         int16  iShort;
369
370                         read(fd, &iShort, 2);
371 #ifdef WORDS_BIGENDIAN
372                         TIFFSwabShort((uint16*) &iShort);
373 #endif
374                         info_hdr.iWidth = iShort;
375                         read(fd, &iShort, 2);
376 #ifdef WORDS_BIGENDIAN
377                         TIFFSwabShort((uint16*) &iShort);
378 #endif
379                         info_hdr.iHeight = iShort;
380                         read(fd, &iShort, 2);
381 #ifdef WORDS_BIGENDIAN
382                         TIFFSwabShort((uint16*) &iShort);
383 #endif
384                         info_hdr.iPlanes = iShort;
385                         read(fd, &iShort, 2);
386 #ifdef WORDS_BIGENDIAN
387                         TIFFSwabShort((uint16*) &iShort);
388 #endif
389                         info_hdr.iBitCount = iShort;
390                         info_hdr.iCompression = BMPC_RGB;
391                         n_clr_elems = 3;
392                 }
393
394                 if (info_hdr.iBitCount != 1  && info_hdr.iBitCount != 4  &&
395                     info_hdr.iBitCount != 8  && info_hdr.iBitCount != 16 &&
396                     info_hdr.iBitCount != 24 && info_hdr.iBitCount != 32) {
397                     TIFFError(infilename,
398                               "Cannot process BMP file with bit count %d",
399                               info_hdr.iBitCount);
400                     close(fd);
401                     return 0;
402                 }
403
404                 width = info_hdr.iWidth;
405                 length = (info_hdr.iHeight > 0) ? info_hdr.iHeight : -info_hdr.iHeight;
406
407                 switch (info_hdr.iBitCount)
408                 {
409                         case 1:
410                         case 4:
411                         case 8:
412                                 nbands = 1;
413                                 depth = info_hdr.iBitCount;
414                                 photometric = PHOTOMETRIC_PALETTE;
415                                 /* Allocate memory for colour table and read it. */
416                                 if (info_hdr.iClrUsed)
417                                     clr_tbl_size =
418                                             ((uint32)(1<<depth)<info_hdr.iClrUsed)
419                                             ? (uint32) (1 << depth)
420                                             : info_hdr.iClrUsed;
421                                 else
422                                     clr_tbl_size = 1 << depth;
423                                 clr_tbl = (unsigned char *)
424                                         _TIFFmalloc(n_clr_elems * clr_tbl_size);
425                                 if (!clr_tbl) {
426                                         TIFFError(infilename,
427                                         "Can't allocate space for color table");
428                                         goto bad;
429                                 }
430
431                                 lseek(fd, BFH_SIZE + info_hdr.iSize, SEEK_SET);
432                                 read(fd, clr_tbl, n_clr_elems * clr_tbl_size);
433
434                                 red_tbl = (unsigned short*)
435                                         _TIFFmalloc(((tmsize_t)1)<<depth * sizeof(unsigned short));
436                                 if (!red_tbl) {
437                                         TIFFError(infilename,
438                                 "Can't allocate space for red component table");
439                                         _TIFFfree(clr_tbl);
440                                         goto bad1;
441                                 }
442                                 green_tbl = (unsigned short*)
443                                         _TIFFmalloc(((tmsize_t)1)<<depth * sizeof(unsigned short));
444                                 if (!green_tbl) {
445                                         TIFFError(infilename,
446                                 "Can't allocate space for green component table");
447                                         _TIFFfree(clr_tbl);
448                                         goto bad2;
449                                 }
450                                 blue_tbl = (unsigned short*)
451                                         _TIFFmalloc(((tmsize_t)1)<<depth * sizeof(unsigned short));
452                                 if (!blue_tbl) {
453                                         TIFFError(infilename,
454                                 "Can't allocate space for blue component table");
455                                         _TIFFfree(clr_tbl);
456                                         goto bad3;
457                                 }
458
459                                 for(clr = 0; clr < clr_tbl_size; clr++) {
460                                     red_tbl[clr] = 257*clr_tbl[clr*n_clr_elems+2];
461                                     green_tbl[clr] = 257*clr_tbl[clr*n_clr_elems+1];
462                                     blue_tbl[clr] = 257*clr_tbl[clr*n_clr_elems];
463                                 }
464
465                                 _TIFFfree(clr_tbl);
466                                 break;
467                         case 16:
468                         case 24:
469                                 nbands = 3;
470                                 depth = info_hdr.iBitCount / nbands;
471                                 photometric = PHOTOMETRIC_RGB;
472                                 break;
473                         case 32:
474                                 nbands = 3;
475                                 depth = 8;
476                                 photometric = PHOTOMETRIC_RGB;
477                                 break;
478                         default:
479                                 break;
480                 }
481
482 /* -------------------------------------------------------------------- */
483 /*  Create output file.                                                 */
484 /* -------------------------------------------------------------------- */
485
486                 TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
487                 TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
488                 TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
489                 TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nbands);
490                 TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, depth);
491                 TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
492                 TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
493                 TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
494                              TIFFDefaultStripSize(out, rowsperstrip));
495                 
496                 if (red_tbl && green_tbl && blue_tbl) {
497                         TIFFSetField(out, TIFFTAG_COLORMAP,
498                                      red_tbl, green_tbl, blue_tbl);
499                 }
500                 
501                 if (compression == (uint16) -1)
502                         compression = COMPRESSION_PACKBITS;
503                 TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
504                 switch (compression) {
505                 case COMPRESSION_JPEG:
506                         if (photometric == PHOTOMETRIC_RGB
507                             && jpegcolormode == JPEGCOLORMODE_RGB)
508                                 photometric = PHOTOMETRIC_YCBCR;
509                         TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
510                         TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
511                         break;
512                 case COMPRESSION_LZW:
513                 case COMPRESSION_DEFLATE:
514                         if (predictor != 0)
515                                 TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
516                         break;
517                 }
518
519 /* -------------------------------------------------------------------- */
520 /*  Read uncompressed image data.                                       */
521 /* -------------------------------------------------------------------- */
522
523                 if (info_hdr.iCompression == BMPC_RGB) {
524                         uint32 offset, size;
525                         char *scanbuf;
526
527                         /* XXX: Avoid integer overflow. We can calculate size
528                          * in one step using
529                          *
530                          *  size = ((width * info_hdr.iBitCount + 31) & ~31) / 8
531                          *
532                          * formulae, but we should check for overflow
533                          * conditions during calculation.
534                          */
535                         size = width * info_hdr.iBitCount + 31;
536                         if (!width || !info_hdr.iBitCount
537                             || (size - 31) / info_hdr.iBitCount != width ) {
538                                 TIFFError(infilename,
539                                           "Wrong image parameters; can't "
540                                           "allocate space for scanline buffer");
541                                 goto bad3;
542                         }
543                         size = (size & ~31) / 8;
544
545                         scanbuf = (char *) _TIFFmalloc(size);
546                         if (!scanbuf) {
547                                 TIFFError(infilename,
548                                 "Can't allocate space for scanline buffer");
549                                 goto bad3;
550                         }
551
552                         for (row = 0; row < length; row++) {
553                                 if (info_hdr.iHeight > 0)
554                                         offset = file_hdr.iOffBits+(length-row-1)*size;
555                                 else
556                                         offset = file_hdr.iOffBits + row * size;
557                                 if (lseek(fd, offset, SEEK_SET) == (off_t)-1) {
558                                         TIFFError(infilename,
559                                                   "scanline %lu: Seek error",
560                                                   (unsigned long) row);
561                                         break;
562                                 }
563
564                                 if (read(fd, scanbuf, size) < 0) {
565                                         TIFFError(infilename,
566                                                   "scanline %lu: Read error",
567                                                   (unsigned long) row);
568                                         break;
569                                 }
570
571                                 rearrangePixels(scanbuf, width, info_hdr.iBitCount);
572
573                                 if (TIFFWriteScanline(out, scanbuf, row, 0)<0) {
574                                         TIFFError(infilename,
575                                                   "scanline %lu: Write error",
576                                                   (unsigned long) row);
577                                         break;
578                                 }
579                         }
580
581                         _TIFFfree(scanbuf);
582
583 /* -------------------------------------------------------------------- */
584 /*  Read compressed image data.                                         */
585 /* -------------------------------------------------------------------- */
586
587                 } else if ( info_hdr.iCompression == BMPC_RLE8
588                             || info_hdr.iCompression == BMPC_RLE4 ) {
589                         uint32          i, j, k, runlength;
590                         uint32          compr_size, uncompr_size;
591                         unsigned char   *comprbuf;
592                         unsigned char   *uncomprbuf;
593
594                         compr_size = file_hdr.iSize - file_hdr.iOffBits;
595                         uncompr_size = width * length;
596                         comprbuf = (unsigned char *) _TIFFmalloc( compr_size );
597                         if (!comprbuf) {
598                                 TIFFError(infilename,
599                         "Can't allocate space for compressed scanline buffer");
600                                 goto bad3;
601                         }
602                         uncomprbuf = (unsigned char *)_TIFFmalloc(uncompr_size);
603                         if (!uncomprbuf) {
604                                 TIFFError(infilename,
605                         "Can't allocate space for uncompressed scanline buffer");
606                                 goto bad3;
607                         }
608
609                         lseek(fd, file_hdr.iOffBits, SEEK_SET);
610                         read(fd, comprbuf, compr_size);
611                         i = 0;
612                         j = 0;
613                         if (info_hdr.iBitCount == 8) {          /* RLE8 */
614                             while(j < uncompr_size && i < compr_size) {
615                                 if ( comprbuf[i] ) {
616                                     runlength = comprbuf[i++];
617                                     while( runlength > 0
618                                            && j < uncompr_size
619                                            && i < compr_size ) {
620                                         uncomprbuf[j++] = comprbuf[i];
621                                         runlength--;
622                                     }
623                                     i++;
624                                 } else {
625                                     i++;
626                                     if (comprbuf[i] == 0) /* Next scanline */
627                                         i++;
628                                     else if (comprbuf[i] == 1) /* End of image */
629                                         break;
630                                     else if (comprbuf[i] == 2) { /* Move to... */
631                                         i++;
632                                         if (i < compr_size - 1) {
633                                             j+=comprbuf[i]+comprbuf[i+1]*width;
634                                             i += 2;
635                                         }
636                                         else
637                                             break;
638                                     } else {            /* Absolute mode */
639                                         runlength = comprbuf[i++];
640                                         for (k = 0; k < runlength && j < uncompr_size && i < compr_size; k++)
641                                             uncomprbuf[j++] = comprbuf[i++];
642                                         if ( k & 0x01 )
643                                             i++;
644                                     }
645                                 }
646                             }
647                         }
648                         else {                              /* RLE4 */
649                             while( j < uncompr_size && i < compr_size ) {
650                                 if ( comprbuf[i] ) {
651                                     runlength = comprbuf[i++];
652                                     while( runlength > 0 && j < uncompr_size && i < compr_size ) {
653                                         if ( runlength & 0x01 )
654                                             uncomprbuf[j++] = (comprbuf[i] & 0xF0) >> 4;
655                                         else
656                                             uncomprbuf[j++] = comprbuf[i] & 0x0F;
657                                         runlength--;
658                                     }
659                                     i++;
660                                 } else {
661                                     i++;
662                                     if (comprbuf[i] == 0) /* Next scanline */
663                                         i++;
664                                     else if (comprbuf[i] == 1) /* End of image */
665                                         break;
666                                     else if (comprbuf[i] == 2) { /* Move to... */
667                                         i++;
668                                         if (i < compr_size - 1) {
669                                             j+=comprbuf[i]+comprbuf[i+1]*width;
670                                             i += 2;
671                                         }
672                                         else
673                                             break;
674                                     } else {            /* Absolute mode */
675                                         runlength = comprbuf[i++];
676                                         for (k = 0; k < runlength && j < uncompr_size && i < compr_size; k++) {
677                                             if (k & 0x01)
678                                                 uncomprbuf[j++] = comprbuf[i++] & 0x0F;
679                                             else
680                                                 uncomprbuf[j++] = (comprbuf[i] & 0xF0) >> 4;
681                                         }
682                                         if (k & 0x01)
683                                             i++;
684                                     }
685                                 }
686                             }
687                         }
688
689                         _TIFFfree(comprbuf);
690
691                         for (row = 0; row < length; row++) {
692                                 if (TIFFWriteScanline(out,
693                                         uncomprbuf + (length - row - 1) * width,
694                                         row, 0) < 0) {
695                                         TIFFError(infilename,
696                                                 "scanline %lu: Write error.\n",
697                                                   (unsigned long) row);
698                                 }
699                         }
700
701                         _TIFFfree(uncomprbuf);
702                 }
703                 TIFFWriteDirectory(out);
704                 if (blue_tbl) {
705                   _TIFFfree(blue_tbl);
706                   blue_tbl=NULL;
707                 }
708                 if (green_tbl) {
709                   _TIFFfree(green_tbl);
710                   green_tbl=NULL;
711                 }
712                 if (red_tbl) {
713                   _TIFFfree(red_tbl);
714                   red_tbl=NULL;
715                 }
716         }
717
718 bad3:
719         if (blue_tbl)
720                 _TIFFfree(blue_tbl);
721 bad2:
722         if (green_tbl)
723                 _TIFFfree(green_tbl);
724 bad1:
725         if (red_tbl)
726                 _TIFFfree(red_tbl);
727 bad:
728         close(fd);
729
730         if (out)
731                 TIFFClose(out);
732         return 0;
733 }
734
735 /*
736  * Image data in BMP file stored in BGR (or ABGR) format. We should rearrange
737  * pixels to RGB (RGBA) format.
738  */
739 static void
740 rearrangePixels(char *buf, uint32 width, uint32 bit_count)
741 {
742         char tmp;
743         uint32 i;
744
745         switch(bit_count) {
746                 case 16:    /* FIXME: need a sample file */
747                         break;
748                 case 24:
749                         for (i = 0; i < width; i++, buf += 3) {
750                                 tmp = *buf;
751                                 *buf = *(buf + 2);
752                                 *(buf + 2) = tmp;
753                         }
754                         break;
755                 case 32:
756                         {
757                                 char    *buf1 = buf;
758
759                                 for (i = 0; i < width; i++, buf += 4) {
760                                         tmp = *buf;
761                                         *buf1++ = *(buf + 2);
762                                         *buf1++ = *(buf + 1);
763                                         *buf1++ = tmp;
764                                 }
765                         }
766                         break;
767                 default:
768                         break;
769         }
770 }
771
772 static int
773 processCompressOptions(char* opt)
774 {
775         if (strcmp(opt, "none") == 0)
776                 compression = COMPRESSION_NONE;
777         else if (strcmp(opt, "packbits") == 0)
778                 compression = COMPRESSION_PACKBITS;
779         else if (strncmp(opt, "jpeg", 4) == 0) {
780                 char* cp = strchr(opt, ':');
781
782                 compression = COMPRESSION_JPEG;
783                 while( cp )
784                 {
785                     if (isdigit((int)cp[1]))
786                         quality = atoi(cp+1);
787                     else if (cp[1] == 'r' )
788                         jpegcolormode = JPEGCOLORMODE_RAW;
789                     else
790                         usage();
791
792                     cp = strchr(cp+1,':');
793                 }
794         } else if (strncmp(opt, "lzw", 3) == 0) {
795                 char* cp = strchr(opt, ':');
796                 if (cp)
797                         predictor = atoi(cp+1);
798                 compression = COMPRESSION_LZW;
799         } else if (strncmp(opt, "zip", 3) == 0) {
800                 char* cp = strchr(opt, ':');
801                 if (cp)
802                         predictor = atoi(cp+1);
803                 compression = COMPRESSION_DEFLATE;
804         } else
805                 return (0);
806         return (1);
807 }
808
809 static char* stuff[] = {
810 "bmp2tiff --- convert Windows BMP files to TIFF",
811 "usage: bmp2tiff [options] input.bmp [input2.bmp ...] output.tif",
812 "where options are:",
813 " -r #          make each strip have no more than # rows",
814 "",
815 " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding",
816 " -c zip[:opts] compress output with deflate encoding",
817 " -c jpeg[:opts]compress output with JPEG encoding",
818 " -c packbits   compress output with packbits encoding",
819 " -c none       use no compression algorithm on output",
820 "",
821 "JPEG options:",
822 " #             set compression quality level (0-100, default 75)",
823 " r             output color image as RGB rather than YCbCr",
824 "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality",
825 "",
826 "LZW and deflate options:",
827 " #             set predictor value",
828 "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
829 " -o out.tif    write output to out.tif",
830 " -h            this help message",
831 NULL
832 };
833
834 static void
835 usage(void)
836 {
837         char buf[BUFSIZ];
838         int i;
839
840         setbuf(stderr, buf);
841         fprintf(stderr, "%s\n\n", TIFFGetVersion());
842         for (i = 0; stuff[i] != NULL; i++)
843                 fprintf(stderr, "%s\n", stuff[i]);
844         exit(-1);
845 }
846
847 /* vim: set ts=8 sts=8 sw=8 noet: */
848 /*
849  * Local Variables:
850  * mode: c
851  * c-basic-offset: 8
852  * fill-column: 78
853  * End:
854  */