1 /*
2  * wrbmp.c
3  *
4  * This file was part of the Independent JPEG Group's software:
5  * Copyright (C) 1994-1996, Thomas G. Lane.
6  * libjpeg-turbo Modifications:
7  * Copyright (C) 2013, Linaro Limited.
8  * Copyright (C) 2014, D. R. Commander.
9  * For conditions of distribution and use, see the accompanying README file.
10  *
11  * This file contains routines to write output images in Microsoft "BMP"
12  * format (MS Windows 3.x and OS/2 1.x flavors).
13  * Either 8-bit colormapped or 24-bit full-color format can be written.
14  * No compression is supported.
15  *
16  * These routines may need modification for non-Unix environments or
17  * specialized applications.  As they stand, they assume output to
18  * an ordinary stdio stream.
19  *
20  * This code contributed by James Arthur Boucher.
21  */
22 
23 #include "cdjpeg.h"             /* Common decls for cjpeg/djpeg applications */
24 #include "jconfigint.h"
25 
26 #ifdef BMP_SUPPORTED
27 
28 
29 /*
30  * To support 12-bit JPEG data, we'd have to scale output down to 8 bits.
31  * This is not yet implemented.
32  */
33 
34 #if BITS_IN_JSAMPLE != 8
35   Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
36 #endif
37 
38 /*
39  * Since BMP stores scanlines bottom-to-top, we have to invert the image
40  * from JPEG's top-to-bottom order.  To do this, we save the outgoing data
41  * in a virtual array during put_pixel_row calls, then actually emit the
42  * BMP file during finish_output.  The virtual array contains one JSAMPLE per
43  * pixel if the output is grayscale or colormapped, three if it is full color.
44  */
45 
46 /* Private version of data destination object */
47 
48 typedef struct {
49   struct djpeg_dest_struct pub; /* public fields */
50 
51   boolean is_os2;               /* saves the OS2 format request flag */
52 
53   jvirt_sarray_ptr whole_image; /* needed to reverse row order */
54   JDIMENSION data_width;        /* JSAMPLEs per row */
55   JDIMENSION row_width;         /* physical width of one row in the BMP file */
56   int pad_bytes;                /* number of padding bytes needed per row */
57   JDIMENSION cur_output_row;    /* next row# to write to virtual array */
58 } bmp_dest_struct;
59 
60 typedef bmp_dest_struct * bmp_dest_ptr;
61 
62 
63 /* Forward declarations */
64 LOCAL(void) write_colormap
65         (j_decompress_ptr cinfo, bmp_dest_ptr dest, int map_colors,
66          int map_entry_size);
67 
68 
is_big_endian(void)69 static INLINE boolean is_big_endian(void)
70 {
71   int test_value = 1;
72   if(*(char *)&test_value != 1)
73     return TRUE;
74   return FALSE;
75 }
76 
77 
78 /*
79  * Write some pixel data.
80  * In this module rows_supplied will always be 1.
81  */
82 
83 METHODDEF(void)
put_pixel_rows(j_decompress_ptr cinfo,djpeg_dest_ptr dinfo,JDIMENSION rows_supplied)84 put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
85                 JDIMENSION rows_supplied)
86 /* This version is for writing 24-bit pixels */
87 {
88   bmp_dest_ptr dest = (bmp_dest_ptr) dinfo;
89   JSAMPARRAY image_ptr;
90   register JSAMPROW inptr, outptr;
91   register JDIMENSION col;
92   int pad;
93 
94   /* Access next row in virtual array */
95   image_ptr = (*cinfo->mem->access_virt_sarray)
96     ((j_common_ptr) cinfo, dest->whole_image,
97      dest->cur_output_row, (JDIMENSION) 1, TRUE);
98   dest->cur_output_row++;
99 
100   /* Transfer data.  Note destination values must be in BGR order
101    * (even though Microsoft's own documents say the opposite).
102    */
103   inptr = dest->pub.buffer[0];
104   outptr = image_ptr[0];
105 
106   if(cinfo->out_color_space == JCS_RGB565) {
107     boolean big_endian = is_big_endian();
108     unsigned short *inptr2 = (unsigned short *)inptr;
109     for (col = cinfo->output_width; col > 0; col--) {
110       if (big_endian) {
111         outptr[0] = (*inptr2 >> 5) & 0xF8;
112         outptr[1] = ((*inptr2 << 5) & 0xE0) | ((*inptr2 >> 11) & 0x1C);
113         outptr[2] = *inptr2 & 0xF8;
114       } else {
115         outptr[0] = (*inptr2 << 3) & 0xF8;
116         outptr[1] = (*inptr2 >> 3) & 0xFC;
117         outptr[2] = (*inptr2 >> 8) & 0xF8;
118       }
119       outptr += 3;
120       inptr2++;
121     }
122   } else {
123     for (col = cinfo->output_width; col > 0; col--) {
124       outptr[2] = *inptr++;       /* can omit GETJSAMPLE() safely */
125       outptr[1] = *inptr++;
126       outptr[0] = *inptr++;
127       outptr += 3;
128     }
129   }
130 
131   /* Zero out the pad bytes. */
132   pad = dest->pad_bytes;
133   while (--pad >= 0)
134     *outptr++ = 0;
135 }
136 
137 METHODDEF(void)
put_gray_rows(j_decompress_ptr cinfo,djpeg_dest_ptr dinfo,JDIMENSION rows_supplied)138 put_gray_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
139                JDIMENSION rows_supplied)
140 /* This version is for grayscale OR quantized color output */
141 {
142   bmp_dest_ptr dest = (bmp_dest_ptr) dinfo;
143   JSAMPARRAY image_ptr;
144   register JSAMPROW inptr, outptr;
145   register JDIMENSION col;
146   int pad;
147 
148   /* Access next row in virtual array */
149   image_ptr = (*cinfo->mem->access_virt_sarray)
150     ((j_common_ptr) cinfo, dest->whole_image,
151      dest->cur_output_row, (JDIMENSION) 1, TRUE);
152   dest->cur_output_row++;
153 
154   /* Transfer data. */
155   inptr = dest->pub.buffer[0];
156   outptr = image_ptr[0];
157   for (col = cinfo->output_width; col > 0; col--) {
158     *outptr++ = *inptr++;       /* can omit GETJSAMPLE() safely */
159   }
160 
161   /* Zero out the pad bytes. */
162   pad = dest->pad_bytes;
163   while (--pad >= 0)
164     *outptr++ = 0;
165 }
166 
167 
168 /*
169  * Startup: normally writes the file header.
170  * In this module we may as well postpone everything until finish_output.
171  */
172 
173 METHODDEF(void)
start_output_bmp(j_decompress_ptr cinfo,djpeg_dest_ptr dinfo)174 start_output_bmp (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
175 {
176   /* no work here */
177 }
178 
179 
180 /*
181  * Finish up at the end of the file.
182  *
183  * Here is where we really output the BMP file.
184  *
185  * First, routines to write the Windows and OS/2 variants of the file header.
186  */
187 
188 LOCAL(void)
write_bmp_header(j_decompress_ptr cinfo,bmp_dest_ptr dest)189 write_bmp_header (j_decompress_ptr cinfo, bmp_dest_ptr dest)
190 /* Write a Windows-style BMP file header, including colormap if needed */
191 {
192   char bmpfileheader[14];
193   char bmpinfoheader[40];
194 #define PUT_2B(array,offset,value)  \
195         (array[offset] = (char) ((value) & 0xFF), \
196          array[offset+1] = (char) (((value) >> 8) & 0xFF))
197 #define PUT_4B(array,offset,value)  \
198         (array[offset] = (char) ((value) & 0xFF), \
199          array[offset+1] = (char) (((value) >> 8) & 0xFF), \
200          array[offset+2] = (char) (((value) >> 16) & 0xFF), \
201          array[offset+3] = (char) (((value) >> 24) & 0xFF))
202   INT32 headersize, bfSize;
203   int bits_per_pixel, cmap_entries;
204 
205   /* Compute colormap size and total file size */
206   if (cinfo->out_color_space == JCS_RGB) {
207     if (cinfo->quantize_colors) {
208       /* Colormapped RGB */
209       bits_per_pixel = 8;
210       cmap_entries = 256;
211     } else {
212       /* Unquantized, full color RGB */
213       bits_per_pixel = 24;
214       cmap_entries = 0;
215     }
216   } else if (cinfo->out_color_space == JCS_RGB565) {
217     bits_per_pixel = 24;
218     cmap_entries   = 0;
219   } else {
220     /* Grayscale output.  We need to fake a 256-entry colormap. */
221     bits_per_pixel = 8;
222     cmap_entries = 256;
223   }
224   /* File size */
225   headersize = 14 + 40 + cmap_entries * 4; /* Header and colormap */
226   bfSize = headersize + (INT32) dest->row_width * (INT32) cinfo->output_height;
227 
228   /* Set unused fields of header to 0 */
229   MEMZERO(bmpfileheader, sizeof(bmpfileheader));
230   MEMZERO(bmpinfoheader, sizeof(bmpinfoheader));
231 
232   /* Fill the file header */
233   bmpfileheader[0] = 0x42;      /* first 2 bytes are ASCII 'B', 'M' */
234   bmpfileheader[1] = 0x4D;
235   PUT_4B(bmpfileheader, 2, bfSize); /* bfSize */
236   /* we leave bfReserved1 & bfReserved2 = 0 */
237   PUT_4B(bmpfileheader, 10, headersize); /* bfOffBits */
238 
239   /* Fill the info header (Microsoft calls this a BITMAPINFOHEADER) */
240   PUT_2B(bmpinfoheader, 0, 40); /* biSize */
241   PUT_4B(bmpinfoheader, 4, cinfo->output_width); /* biWidth */
242   PUT_4B(bmpinfoheader, 8, cinfo->output_height); /* biHeight */
243   PUT_2B(bmpinfoheader, 12, 1); /* biPlanes - must be 1 */
244   PUT_2B(bmpinfoheader, 14, bits_per_pixel); /* biBitCount */
245   /* we leave biCompression = 0, for none */
246   /* we leave biSizeImage = 0; this is correct for uncompressed data */
247   if (cinfo->density_unit == 2) { /* if have density in dots/cm, then */
248     PUT_4B(bmpinfoheader, 24, (INT32) (cinfo->X_density*100)); /* XPels/M */
249     PUT_4B(bmpinfoheader, 28, (INT32) (cinfo->Y_density*100)); /* XPels/M */
250   }
251   PUT_2B(bmpinfoheader, 32, cmap_entries); /* biClrUsed */
252   /* we leave biClrImportant = 0 */
253 
254   if (JFWRITE(dest->pub.output_file, bmpfileheader, 14) != (size_t) 14)
255     ERREXIT(cinfo, JERR_FILE_WRITE);
256   if (JFWRITE(dest->pub.output_file, bmpinfoheader, 40) != (size_t) 40)
257     ERREXIT(cinfo, JERR_FILE_WRITE);
258 
259   if (cmap_entries > 0)
260     write_colormap(cinfo, dest, cmap_entries, 4);
261 }
262 
263 
264 LOCAL(void)
write_os2_header(j_decompress_ptr cinfo,bmp_dest_ptr dest)265 write_os2_header (j_decompress_ptr cinfo, bmp_dest_ptr dest)
266 /* Write an OS2-style BMP file header, including colormap if needed */
267 {
268   char bmpfileheader[14];
269   char bmpcoreheader[12];
270   INT32 headersize, bfSize;
271   int bits_per_pixel, cmap_entries;
272 
273   /* Compute colormap size and total file size */
274   if (cinfo->out_color_space == JCS_RGB) {
275     if (cinfo->quantize_colors) {
276       /* Colormapped RGB */
277       bits_per_pixel = 8;
278       cmap_entries = 256;
279     } else {
280       /* Unquantized, full color RGB */
281       bits_per_pixel = 24;
282       cmap_entries = 0;
283     }
284   } else if (cinfo->out_color_space == JCS_RGB565) {
285     bits_per_pixel = 24;
286     cmap_entries   = 0;
287   } else {
288     /* Grayscale output.  We need to fake a 256-entry colormap. */
289     bits_per_pixel = 8;
290     cmap_entries = 256;
291   }
292   /* File size */
293   headersize = 14 + 12 + cmap_entries * 3; /* Header and colormap */
294   bfSize = headersize + (INT32) dest->row_width * (INT32) cinfo->output_height;
295 
296   /* Set unused fields of header to 0 */
297   MEMZERO(bmpfileheader, sizeof(bmpfileheader));
298   MEMZERO(bmpcoreheader, sizeof(bmpcoreheader));
299 
300   /* Fill the file header */
301   bmpfileheader[0] = 0x42;      /* first 2 bytes are ASCII 'B', 'M' */
302   bmpfileheader[1] = 0x4D;
303   PUT_4B(bmpfileheader, 2, bfSize); /* bfSize */
304   /* we leave bfReserved1 & bfReserved2 = 0 */
305   PUT_4B(bmpfileheader, 10, headersize); /* bfOffBits */
306 
307   /* Fill the info header (Microsoft calls this a BITMAPCOREHEADER) */
308   PUT_2B(bmpcoreheader, 0, 12); /* bcSize */
309   PUT_2B(bmpcoreheader, 4, cinfo->output_width); /* bcWidth */
310   PUT_2B(bmpcoreheader, 6, cinfo->output_height); /* bcHeight */
311   PUT_2B(bmpcoreheader, 8, 1);  /* bcPlanes - must be 1 */
312   PUT_2B(bmpcoreheader, 10, bits_per_pixel); /* bcBitCount */
313 
314   if (JFWRITE(dest->pub.output_file, bmpfileheader, 14) != (size_t) 14)
315     ERREXIT(cinfo, JERR_FILE_WRITE);
316   if (JFWRITE(dest->pub.output_file, bmpcoreheader, 12) != (size_t) 12)
317     ERREXIT(cinfo, JERR_FILE_WRITE);
318 
319   if (cmap_entries > 0)
320     write_colormap(cinfo, dest, cmap_entries, 3);
321 }
322 
323 
324 /*
325  * Write the colormap.
326  * Windows uses BGR0 map entries; OS/2 uses BGR entries.
327  */
328 
329 LOCAL(void)
write_colormap(j_decompress_ptr cinfo,bmp_dest_ptr dest,int map_colors,int map_entry_size)330 write_colormap (j_decompress_ptr cinfo, bmp_dest_ptr dest,
331                 int map_colors, int map_entry_size)
332 {
333   JSAMPARRAY colormap = cinfo->colormap;
334   int num_colors = cinfo->actual_number_of_colors;
335   FILE * outfile = dest->pub.output_file;
336   int i;
337 
338   if (colormap != NULL) {
339     if (cinfo->out_color_components == 3) {
340       /* Normal case with RGB colormap */
341       for (i = 0; i < num_colors; i++) {
342         putc(GETJSAMPLE(colormap[2][i]), outfile);
343         putc(GETJSAMPLE(colormap[1][i]), outfile);
344         putc(GETJSAMPLE(colormap[0][i]), outfile);
345         if (map_entry_size == 4)
346           putc(0, outfile);
347       }
348     } else {
349       /* Grayscale colormap (only happens with grayscale quantization) */
350       for (i = 0; i < num_colors; i++) {
351         putc(GETJSAMPLE(colormap[0][i]), outfile);
352         putc(GETJSAMPLE(colormap[0][i]), outfile);
353         putc(GETJSAMPLE(colormap[0][i]), outfile);
354         if (map_entry_size == 4)
355           putc(0, outfile);
356       }
357     }
358   } else {
359     /* If no colormap, must be grayscale data.  Generate a linear "map". */
360     for (i = 0; i < 256; i++) {
361       putc(i, outfile);
362       putc(i, outfile);
363       putc(i, outfile);
364       if (map_entry_size == 4)
365         putc(0, outfile);
366     }
367   }
368   /* Pad colormap with zeros to ensure specified number of colormap entries */
369   if (i > map_colors)
370     ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, i);
371   for (; i < map_colors; i++) {
372     putc(0, outfile);
373     putc(0, outfile);
374     putc(0, outfile);
375     if (map_entry_size == 4)
376       putc(0, outfile);
377   }
378 }
379 
380 
381 METHODDEF(void)
finish_output_bmp(j_decompress_ptr cinfo,djpeg_dest_ptr dinfo)382 finish_output_bmp (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
383 {
384   bmp_dest_ptr dest = (bmp_dest_ptr) dinfo;
385   register FILE * outfile = dest->pub.output_file;
386   JSAMPARRAY image_ptr;
387   register JSAMPROW data_ptr;
388   JDIMENSION row;
389   register JDIMENSION col;
390   cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
391 
392   /* Write the header and colormap */
393   if (dest->is_os2)
394     write_os2_header(cinfo, dest);
395   else
396     write_bmp_header(cinfo, dest);
397 
398   /* Write the file body from our virtual array */
399   for (row = cinfo->output_height; row > 0; row--) {
400     if (progress != NULL) {
401       progress->pub.pass_counter = (long) (cinfo->output_height - row);
402       progress->pub.pass_limit = (long) cinfo->output_height;
403       (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
404     }
405     image_ptr = (*cinfo->mem->access_virt_sarray)
406       ((j_common_ptr) cinfo, dest->whole_image, row-1, (JDIMENSION) 1, FALSE);
407     data_ptr = image_ptr[0];
408     for (col = dest->row_width; col > 0; col--) {
409       putc(GETJSAMPLE(*data_ptr), outfile);
410       data_ptr++;
411     }
412   }
413   if (progress != NULL)
414     progress->completed_extra_passes++;
415 
416   /* Make sure we wrote the output file OK */
417   fflush(outfile);
418   if (ferror(outfile))
419     ERREXIT(cinfo, JERR_FILE_WRITE);
420 }
421 
422 
423 /*
424  * The module selection routine for BMP format output.
425  */
426 
427 GLOBAL(djpeg_dest_ptr)
jinit_write_bmp(j_decompress_ptr cinfo,boolean is_os2)428 jinit_write_bmp (j_decompress_ptr cinfo, boolean is_os2)
429 {
430   bmp_dest_ptr dest;
431   JDIMENSION row_width;
432 
433   /* Create module interface object, fill in method pointers */
434   dest = (bmp_dest_ptr)
435       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
436                                   sizeof(bmp_dest_struct));
437   dest->pub.start_output = start_output_bmp;
438   dest->pub.finish_output = finish_output_bmp;
439   dest->is_os2 = is_os2;
440 
441   if (cinfo->out_color_space == JCS_GRAYSCALE) {
442     dest->pub.put_pixel_rows = put_gray_rows;
443   } else if (cinfo->out_color_space == JCS_RGB) {
444     if (cinfo->quantize_colors)
445       dest->pub.put_pixel_rows = put_gray_rows;
446     else
447       dest->pub.put_pixel_rows = put_pixel_rows;
448   } else if(cinfo->out_color_space == JCS_RGB565 ) {
449       dest->pub.put_pixel_rows = put_pixel_rows;
450   } else {
451     ERREXIT(cinfo, JERR_BMP_COLORSPACE);
452   }
453 
454   /* Calculate output image dimensions so we can allocate space */
455   jpeg_calc_output_dimensions(cinfo);
456 
457   /* Determine width of rows in the BMP file (padded to 4-byte boundary). */
458   if (cinfo->out_color_space == JCS_RGB565) {
459     row_width = cinfo->output_width * 2;
460     dest->row_width = dest->data_width = cinfo->output_width * 3;
461   } else {
462     row_width = cinfo->output_width * cinfo->output_components;
463     dest->row_width = dest->data_width = row_width;
464   }
465   while ((dest->row_width & 3) != 0) dest->row_width++;
466   dest->pad_bytes = (int) (dest->row_width - dest->data_width);
467   if (cinfo->out_color_space == JCS_RGB565) {
468     while ((row_width & 3) != 0) row_width++;
469   } else {
470     row_width = dest->row_width;
471   }
472 
473 
474   /* Allocate space for inversion array, prepare for write pass */
475   dest->whole_image = (*cinfo->mem->request_virt_sarray)
476     ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
477      dest->row_width, cinfo->output_height, (JDIMENSION) 1);
478   dest->cur_output_row = 0;
479   if (cinfo->progress != NULL) {
480     cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
481     progress->total_extra_passes++; /* count file input as separate pass */
482   }
483 
484   /* Create decompressor output buffer. */
485   dest->pub.buffer = (*cinfo->mem->alloc_sarray)
486     ((j_common_ptr) cinfo, JPOOL_IMAGE, row_width, (JDIMENSION) 1);
487   dest->pub.buffer_height = 1;
488 
489   return (djpeg_dest_ptr) dest;
490 }
491 
492 #endif /* BMP_SUPPORTED */
493