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