1 /*
2  * rdbmp.c
3  *
4  * Copyright (C) 1994, Thomas G. Lane.
5  * This file is part of the Independent JPEG Group's software.
6  * For conditions of distribution and use, see the accompanying README file.
7  *
8  * This file contains routines to read input images in Microsoft "BMP"
9  * format (MS Windows 3.x, OS/2 1.x, and OS/2 2.x flavors).
10  * Currently, only 8-bit and 24-bit images are supported, not 1-bit or
11  * 4-bit (feeding such low-depth images into JPEG would be silly anyway).
12  * Also, we don't support RLE-compressed files.
13  *
14  * These routines may need modification for non-Unix environments or
15  * specialized applications.  As they stand, they assume input from
16  * an ordinary stdio stream.  They further assume that reading begins
17  * at the start of the file; start_input may need work if the
18  * user interface has already read some data (e.g., to determine that
19  * the file is indeed BMP format).
20  *
21  * This code contributed by James Arthur Boucher.
22  */
23 
24 #include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
25 
26 #ifdef BMP_SUPPORTED
27 
28 
29 /* Macros to deal with unsigned chars as efficiently as compiler allows */
30 
31 #ifdef HAVE_UNSIGNED_CHAR
32 typedef unsigned char U_CHAR;
33 #define UCH(x)	((int) (x))
34 #else /* !HAVE_UNSIGNED_CHAR */
35 #ifdef CHAR_IS_UNSIGNED
36 typedef char U_CHAR;
37 #define UCH(x)	((int) (x))
38 #else
39 typedef char U_CHAR;
40 #define UCH(x)	((int) (x) & 0xFF)
41 #endif
42 #endif /* HAVE_UNSIGNED_CHAR */
43 
44 
45 #define	ReadOK(file,buffer,len)	(JFREAD(file,buffer,len) == ((size_t) (len)))
46 
47 
48 /* Private version of data source object */
49 
50 typedef struct _bmp_source_struct * bmp_source_ptr;
51 
52 typedef struct _bmp_source_struct {
53   struct cjpeg_source_struct pub; /* public fields */
54 
55   j_compress_ptr cinfo;		/* back link saves passing separate parm */
56 
57   JSAMPARRAY colormap;		/* BMP colormap (converted to my format) */
58 
59   jvirt_sarray_ptr whole_image;	/* Needed to reverse row order */
60   JDIMENSION source_row;	/* Current source row number */
61   JDIMENSION row_width;		/* Physical width of scanlines in file */
62 
63   int bits_per_pixel;		/* remembers 8- or 24-bit format */
64 } bmp_source_struct;
65 
66 
67 LOCAL int
read_byte(bmp_source_ptr sinfo)68 read_byte (bmp_source_ptr sinfo)
69 /* Read next byte from BMP file */
70 {
71   register FILE *infile = sinfo->pub.input_file;
72   register int c;
73 
74   if ((c = getc(infile)) == EOF)
75     ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
76   return c;
77 }
78 
79 
80 LOCAL void
read_colormap(bmp_source_ptr sinfo,int cmaplen,int mapentrysize)81 read_colormap (bmp_source_ptr sinfo, int cmaplen, int mapentrysize)
82 /* Read the colormap from a BMP file */
83 {
84   int i;
85 
86   switch (mapentrysize) {
87   case 3:
88     /* BGR format (occurs in OS/2 files) */
89     for (i = 0; i < cmaplen; i++) {
90       sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo);
91       sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo);
92       sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo);
93     }
94     break;
95   case 4:
96     /* BGR0 format (occurs in MS Windows files) */
97     for (i = 0; i < cmaplen; i++) {
98       sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo);
99       sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo);
100       sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo);
101       (void) read_byte(sinfo);
102     }
103     break;
104   default:
105     ERREXIT(sinfo->cinfo, JERR_BMP_BADCMAP);
106     break;
107   }
108 }
109 
110 
111 /*
112  * Read one row of pixels.
113  * The image has been read into the whole_image array, but is otherwise
114  * unprocessed.  We must read it out in top-to-bottom row order, and if
115  * it is an 8-bit image, we must expand colormapped pixels to 24bit format.
116  */
117 
118 METHODDEF JDIMENSION
get_8bit_row(j_compress_ptr cinfo,cjpeg_source_ptr sinfo)119 get_8bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
120 /* This version is for reading 8-bit colormap indexes */
121 {
122   bmp_source_ptr source = (bmp_source_ptr) sinfo;
123   register JSAMPARRAY colormap = source->colormap;
124   JSAMPARRAY image_ptr;
125   register int t;
126   register JSAMPROW inptr, outptr;
127   register JDIMENSION col;
128 
129   /* Fetch next row from virtual array */
130   source->source_row--;
131   image_ptr = (*cinfo->mem->access_virt_sarray)
132     ((j_common_ptr) cinfo, source->whole_image, source->source_row, FALSE);
133 
134   /* Expand the colormap indexes to real data */
135   inptr = image_ptr[0];
136   outptr = source->pub.buffer[0];
137   for (col = cinfo->image_width; col > 0; col--) {
138     t = GETJSAMPLE(*inptr++);
139     *outptr++ = colormap[0][t];	/* can omit GETJSAMPLE() safely */
140     *outptr++ = colormap[1][t];
141     *outptr++ = colormap[2][t];
142   }
143 
144   return 1;
145 }
146 
147 
148 METHODDEF JDIMENSION
get_24bit_row(j_compress_ptr cinfo,cjpeg_source_ptr sinfo)149 get_24bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
150 /* This version is for reading 24-bit pixels */
151 {
152   bmp_source_ptr source = (bmp_source_ptr) sinfo;
153   JSAMPARRAY image_ptr;
154   register JSAMPROW inptr, outptr;
155   register JDIMENSION col;
156 
157   /* Fetch next row from virtual array */
158   source->source_row--;
159   image_ptr = (*cinfo->mem->access_virt_sarray)
160     ((j_common_ptr) cinfo, source->whole_image, source->source_row, FALSE);
161 
162   /* Transfer data.  Note source values are in BGR order
163    * (even though Microsoft's own documents say the opposite).
164    */
165   inptr = image_ptr[0];
166   outptr = source->pub.buffer[0];
167   for (col = cinfo->image_width; col > 0; col--) {
168     outptr[2] = *inptr++;	/* can omit GETJSAMPLE() safely */
169     outptr[1] = *inptr++;
170     outptr[0] = *inptr++;
171     outptr += 3;
172   }
173 
174   return 1;
175 }
176 
177 
178 /*
179  * This method loads the image into whole_image during the first call on
180  * get_pixel_rows.  The get_pixel_rows pointer is then adjusted to call
181  * get_8bit_row or get_24bit_row on subsequent calls.
182  */
183 
184 METHODDEF JDIMENSION
preload_image(j_compress_ptr cinfo,cjpeg_source_ptr sinfo)185 preload_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
186 {
187   bmp_source_ptr source = (bmp_source_ptr) sinfo;
188   register FILE *infile = source->pub.input_file;
189   register int c;
190   register JSAMPROW out_ptr;
191   JSAMPARRAY image_ptr;
192   JDIMENSION row, col;
193   cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
194 
195   /* Read the data into a virtual array in input-file row order. */
196   for (row = 0; row < cinfo->image_height; row++) {
197     if (progress != NULL) {
198       progress->pub.pass_counter = (long) row;
199       progress->pub.pass_limit = (long) cinfo->image_height;
200       (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
201     }
202     image_ptr = (*cinfo->mem->access_virt_sarray)
203       ((j_common_ptr) cinfo, source->whole_image, row, TRUE);
204     out_ptr = image_ptr[0];
205     for (col = source->row_width; col > 0; col--) {
206       /* inline copy of read_byte() for speed */
207       if ((c = getc(infile)) == EOF)
208 	ERREXIT(cinfo, JERR_INPUT_EOF);
209       *out_ptr++ = (JSAMPLE) c;
210     }
211   }
212   if (progress != NULL)
213     progress->completed_extra_passes++;
214 
215   /* Set up to read from the virtual array in top-to-bottom order */
216   switch (source->bits_per_pixel) {
217   case 8:
218     source->pub.get_pixel_rows = get_8bit_row;
219     break;
220   case 24:
221     source->pub.get_pixel_rows = get_24bit_row;
222     break;
223   default:
224     ERREXIT(cinfo, JERR_BMP_BADDEPTH);
225   }
226   source->source_row = cinfo->image_height;
227 
228   /* And read the first row */
229   return (*source->pub.get_pixel_rows) (cinfo, sinfo);
230 }
231 
232 
233 /*
234  * Read the file header; return image size and component count.
235  */
236 
237 METHODDEF void
start_input_bmp(j_compress_ptr cinfo,cjpeg_source_ptr sinfo)238 start_input_bmp (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
239 {
240   bmp_source_ptr source = (bmp_source_ptr) sinfo;
241   U_CHAR bmpfileheader[14];
242   U_CHAR bmpinfoheader[64];
243 #define GET_2B(array,offset)  ((unsigned int) UCH(array[offset]) + \
244 			       (((unsigned int) UCH(array[offset+1])) << 8))
245 #define GET_4B(array,offset)  ((INT32) UCH(array[offset]) + \
246 			       (((INT32) UCH(array[offset+1])) << 8) + \
247 			       (((INT32) UCH(array[offset+2])) << 16) + \
248 			       (((INT32) UCH(array[offset+3])) << 24))
249   INT32 bfOffBits;
250   INT32 headerSize;
251   INT32 biWidth = 0;		/* initialize to avoid compiler warning */
252   INT32 biHeight = 0;
253   unsigned int biPlanes;
254   INT32 biCompression;
255   INT32 biXPelsPerMeter,biYPelsPerMeter;
256   INT32 biClrUsed = 0;
257   int mapentrysize = 0;		/* 0 indicates no colormap */
258   INT32 bPad;
259   JDIMENSION row_width;
260 
261   /* Read and verify the bitmap file header */
262   if (! ReadOK(source->pub.input_file, bmpfileheader, 14))
263     ERREXIT(cinfo, JERR_INPUT_EOF);
264   if (GET_2B(bmpfileheader,0) != 0x4D42) /* 'BM' */
265     ERREXIT(cinfo, JERR_BMP_NOT);
266   bfOffBits = (INT32) GET_4B(bmpfileheader,10);
267   /* We ignore the remaining fileheader fields */
268 
269   /* The infoheader might be 12 bytes (OS/2 1.x), 40 bytes (Windows),
270    * or 64 bytes (OS/2 2.x).  Check the first 4 bytes to find out which.
271    */
272   if (! ReadOK(source->pub.input_file, bmpinfoheader, 4))
273     ERREXIT(cinfo, JERR_INPUT_EOF);
274   headerSize = (INT32) GET_4B(bmpinfoheader,0);
275   if (headerSize < 12 || headerSize > 64)
276     ERREXIT(cinfo, JERR_BMP_BADHEADER);
277   if (! ReadOK(source->pub.input_file, bmpinfoheader+4, headerSize-4))
278     ERREXIT(cinfo, JERR_INPUT_EOF);
279 
280   switch ((int) headerSize) {
281   case 12:
282     /* Decode OS/2 1.x header (Microsoft calls this a BITMAPCOREHEADER) */
283     biWidth = (INT32) GET_2B(bmpinfoheader,4);
284     biHeight = (INT32) GET_2B(bmpinfoheader,6);
285     biPlanes = GET_2B(bmpinfoheader,8);
286     source->bits_per_pixel = (int) GET_2B(bmpinfoheader,10);
287 
288     switch (source->bits_per_pixel) {
289     case 8:			/* colormapped image */
290       mapentrysize = 3;		/* OS/2 uses RGBTRIPLE colormap */
291       TRACEMS2(cinfo, 1, JTRC_BMP_OS2_MAPPED, (int) biWidth, (int) biHeight);
292       break;
293     case 24:			/* RGB image */
294       TRACEMS2(cinfo, 1, JTRC_BMP_OS2, (int) biWidth, (int) biHeight);
295       break;
296     default:
297       ERREXIT(cinfo, JERR_BMP_BADDEPTH);
298       break;
299     }
300     if (biPlanes != 1)
301       ERREXIT(cinfo, JERR_BMP_BADPLANES);
302     break;
303   case 40:
304   case 64:
305     /* Decode Windows 3.x header (Microsoft calls this a BITMAPINFOHEADER) */
306     /* or OS/2 2.x header, which has additional fields that we ignore */
307     biWidth = GET_4B(bmpinfoheader,4);
308     biHeight = GET_4B(bmpinfoheader,8);
309     biPlanes = GET_2B(bmpinfoheader,12);
310     source->bits_per_pixel = (int) GET_2B(bmpinfoheader,14);
311     biCompression = GET_4B(bmpinfoheader,16);
312     biXPelsPerMeter = GET_4B(bmpinfoheader,24);
313     biYPelsPerMeter = GET_4B(bmpinfoheader,28);
314     biClrUsed = GET_4B(bmpinfoheader,32);
315     /* biSizeImage, biClrImportant fields are ignored */
316 
317     switch (source->bits_per_pixel) {
318     case 8:			/* colormapped image */
319       mapentrysize = 4;		/* Windows uses RGBQUAD colormap */
320       TRACEMS2(cinfo, 1, JTRC_BMP_MAPPED, (int) biWidth, (int) biHeight);
321       break;
322     case 24:			/* RGB image */
323       TRACEMS2(cinfo, 1, JTRC_BMP, (int) biWidth, (int) biHeight);
324       break;
325     default:
326       ERREXIT(cinfo, JERR_BMP_BADDEPTH);
327       break;
328     }
329     if (biPlanes != 1)
330       ERREXIT(cinfo, JERR_BMP_BADPLANES);
331     if (biCompression != 0)
332       ERREXIT(cinfo, JERR_BMP_COMPRESSED);
333 
334     if (biXPelsPerMeter > 0 && biYPelsPerMeter > 0) {
335       /* Set JFIF density parameters from the BMP data */
336       cinfo->X_density = (UINT16) (biXPelsPerMeter/100); /* 100 cm per meter */
337       cinfo->Y_density = (UINT16) (biYPelsPerMeter/100);
338       cinfo->density_unit = 2;	/* dots/cm */
339     }
340     break;
341   default:
342     ERREXIT(cinfo, JERR_BMP_BADHEADER);
343     break;
344   }
345 
346   /* Compute distance to bitmap data --- will adjust for colormap below */
347   bPad = bfOffBits - (headerSize + 14);
348 
349   /* Read the colormap, if any */
350   if (mapentrysize > 0) {
351     if (biClrUsed <= 0)
352       biClrUsed = 256;		/* assume it's 256 */
353     else if (biClrUsed > 256)
354       ERREXIT(cinfo, JERR_BMP_BADCMAP);
355     /* Allocate space to store the colormap */
356     source->colormap = (*cinfo->mem->alloc_sarray)
357       ((j_common_ptr) cinfo, JPOOL_IMAGE,
358        (JDIMENSION) biClrUsed, (JDIMENSION) 3);
359     /* and read it from the file */
360     read_colormap(source, (int) biClrUsed, mapentrysize);
361     /* account for size of colormap */
362     bPad -= biClrUsed * mapentrysize;
363   }
364 
365   /* Skip any remaining pad bytes */
366   if (bPad < 0)			/* incorrect bfOffBits value? */
367     ERREXIT(cinfo, JERR_BMP_BADHEADER);
368   while (--bPad >= 0) {
369     (void) read_byte(source);
370   }
371 
372   /* Compute row width in file, including padding to 4-byte boundary */
373   if (source->bits_per_pixel == 24)
374     row_width = (JDIMENSION) (biWidth * 3);
375   else
376     row_width = (JDIMENSION) biWidth;
377   while ((row_width & 3) != 0) row_width++;
378   source->row_width = row_width;
379 
380   /* Allocate space for inversion array, prepare for preload pass */
381   source->whole_image = (*cinfo->mem->request_virt_sarray)
382     ((j_common_ptr) cinfo, JPOOL_IMAGE,
383      row_width, (JDIMENSION) biHeight, (JDIMENSION) 1);
384   source->pub.get_pixel_rows = preload_image;
385   if (cinfo->progress != NULL) {
386     cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
387     progress->total_extra_passes++; /* count file input as separate pass */
388   }
389 
390   /* Allocate one-row buffer for returned data */
391   source->pub.buffer = (*cinfo->mem->alloc_sarray)
392     ((j_common_ptr) cinfo, JPOOL_IMAGE,
393      (JDIMENSION) (biWidth * 3), (JDIMENSION) 1);
394   source->pub.buffer_height = 1;
395 
396   cinfo->in_color_space = JCS_RGB;
397   cinfo->input_components = 3;
398   cinfo->data_precision = 8;
399   cinfo->image_width = (JDIMENSION) biWidth;
400   cinfo->image_height = (JDIMENSION) biHeight;
401 }
402 
403 
404 /*
405  * Finish up at the end of the file.
406  */
407 
408 METHODDEF void
finish_input_bmp(j_compress_ptr cinfo,cjpeg_source_ptr sinfo)409 finish_input_bmp (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
410 {
411   /* no work */
412 }
413 
414 
415 /*
416  * The module selection routine for BMP format input.
417  */
418 
419 GLOBAL cjpeg_source_ptr
jinit_read_bmp(j_compress_ptr cinfo)420 jinit_read_bmp (j_compress_ptr cinfo)
421 {
422   bmp_source_ptr source;
423 
424   /* Create module interface object */
425   source = (bmp_source_ptr)
426       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
427 				  SIZEOF(bmp_source_struct));
428   source->cinfo = cinfo;	/* make back link for subroutines */
429   /* Fill in method ptrs, except get_pixel_rows which start_input sets */
430   source->pub.start_input = start_input_bmp;
431   source->pub.finish_input = finish_input_bmp;
432 
433   return (cjpeg_source_ptr) source;
434 }
435 
436 #endif /* BMP_SUPPORTED */
437