]> git.imager.perl.org - imager.git/blob - bmp.c
- writing a 2 or 4 channel image to a BMP file will now write that
[imager.git] / bmp.c
1 #include <stdarg.h>
2 #include "imageri.h"
3
4 /*
5 =head1 NAME
6
7 bmp.c - read and write windows BMP files
8
9 =head1 SYNOPSIS
10
11   i_img *im;
12   io_glue *ig;
13
14   if (!i_writebmp_wiol(im, ig)) {
15     ... error ...
16   }
17   im = i_readbmp(ig);
18
19 =head1 DESCRIPTION
20
21 Reads and writes Windows BMP files.
22
23 =over
24
25 =cut
26 */
27
28 #define FILEHEAD_SIZE 14
29 #define INFOHEAD_SIZE 40
30 #define BI_RGB          0
31 #define BI_RLE8         1
32 #define BI_RLE4         2
33 #define BI_BITFIELDS    3
34 #define BMPRLE_ENDOFLINE 0
35 #define BMPRLE_ENDOFBMP 1
36 #define BMPRLE_DELTA 2
37
38 static int read_packed(io_glue *ig, char *format, ...);
39 static int write_packed(io_glue *ig, char *format, ...);
40 static int write_bmphead(io_glue *ig, i_img *im, int bit_count, 
41                          int data_size);
42 static int write_1bit_data(io_glue *ig, i_img *im);
43 static int write_4bit_data(io_glue *ig, i_img *im);
44 static int write_8bit_data(io_glue *ig, i_img *im);
45 static int write_24bit_data(io_glue *ig, i_img *im);
46 static int read_bmp_pal(io_glue *ig, i_img *im, int count);
47 static i_img *read_1bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
48                             int compression, long offbits, int allow_incomplete);
49 static i_img *read_4bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
50                             int compression, long offbits, int allow_incomplete);
51 static i_img *read_8bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
52                             int compression, long offbits, int allow_incomplete);
53 static i_img *read_direct_bmp(io_glue *ig, int xsize, int ysize, 
54                               int bit_count, int clr_used, int compression,
55                               long offbits, int allow_incomplete);
56
57 /* 
58 =item i_writebmp_wiol(im, io_glue)
59
60 Writes the image as a BMP file.  Uses 1-bit, 4-bit, 8-bit or 24-bit
61 formats depending on the image.
62
63 Never compresses the image.
64
65 =cut
66 */
67 int
68 i_writebmp_wiol(i_img *im, io_glue *ig) {
69   io_glue_commit_types(ig);
70   i_clear_error();
71
72   /* pick a format */
73   if (im->type == i_direct_type) {
74     return write_24bit_data(ig, im);
75   }
76   else {
77     int pal_size;
78
79     /* must be paletted */
80     pal_size = i_colorcount(im);
81     if (pal_size <= 2) {
82       return write_1bit_data(ig, im);
83     }
84     else if (pal_size <= 16) {
85       return write_4bit_data(ig, im);
86     }
87     else {
88       return write_8bit_data(ig, im);
89     }
90   }
91 }
92
93 /*
94 =item i_readbmp_wiol(ig)
95
96 Reads a Windows format bitmap from the given file.
97
98 Handles BI_RLE4 and BI_RLE8 compressed images.  Attempts to handle
99 BI_BITFIELDS images too, but I need a test image.
100
101 =cut
102 */
103
104 i_img *
105 i_readbmp_wiol(io_glue *ig, int allow_incomplete) {
106   int b_magic, m_magic, filesize, res1, res2, infohead_size;
107   int xsize, ysize, planes, bit_count, compression, size_image, xres, yres;
108   int clr_used, clr_important, offbits;
109   i_img *im;
110
111   mm_log((1, "i_readbmp_wiol(ig %p)\n", ig));
112   
113   io_glue_commit_types(ig);
114   i_clear_error();
115
116   if (!read_packed(ig, "CCVvvVVVVvvVVVVVV", &b_magic, &m_magic, &filesize, 
117                    &res1, &res2, &offbits, &infohead_size, 
118                    &xsize, &ysize, &planes,
119                    &bit_count, &compression, &size_image, &xres, &yres, 
120                    &clr_used, &clr_important)) {
121     i_push_error(0, "file too short to be a BMP file");
122     return 0;
123   }
124   if (b_magic != 'B' || m_magic != 'M' || infohead_size != INFOHEAD_SIZE
125       || planes != 1) {
126     i_push_error(0, "not a BMP file");
127     return 0;
128   }
129
130   mm_log((1, " bmp header: filesize %d offbits %d xsize %d ysize %d planes %d "
131           "bit_count %d compression %d size %d xres %d yres %d clr_used %d "
132           "clr_important %d\n", filesize, offbits, xsize, ysize, planes, 
133           bit_count, compression, size_image, xres, yres, clr_used, 
134           clr_important));
135
136   if (!i_int_check_image_file_limits(xsize, abs(ysize), 3, sizeof(i_sample_t))) {
137     mm_log((1, "i_readbmp_wiol: image size exceeds limits\n"));
138     return NULL;
139   }
140   
141   switch (bit_count) {
142   case 1:
143     im = read_1bit_bmp(ig, xsize, ysize, clr_used, compression, offbits, 
144                        allow_incomplete);
145     break;
146
147   case 4:
148     im = read_4bit_bmp(ig, xsize, ysize, clr_used, compression, offbits, 
149                        allow_incomplete);
150     break;
151
152   case 8:
153     im = read_8bit_bmp(ig, xsize, ysize, clr_used, compression, offbits, 
154                        allow_incomplete);
155     break;
156
157   case 32:
158   case 24:
159   case 16:
160     im = read_direct_bmp(ig, xsize, ysize, bit_count, clr_used, compression,
161                          offbits, allow_incomplete);
162     break;
163
164   default:
165     i_push_errorf(0, "unknown bit count for BMP file (%d)", bit_count);
166     return NULL;
167   }
168
169   if (im) {
170     /* store the resolution */
171     if (xres && !yres)
172       yres = xres;
173     else if (yres && !xres)
174       xres = yres;
175     if (xres) {
176       i_tags_set_float2(&im->tags, "i_xres", 0, xres * 0.0254, 4);
177       i_tags_set_float2(&im->tags, "i_yres", 0, yres * 0.0254, 4);
178     }
179     i_tags_addn(&im->tags, "bmp_compression", 0, compression);
180     i_tags_addn(&im->tags, "bmp_important_colors", 0, clr_important);
181     i_tags_addn(&im->tags, "bmp_used_colors", 0, clr_used);
182     i_tags_addn(&im->tags, "bmp_filesize", 0, filesize);
183     i_tags_addn(&im->tags, "bmp_bit_count", 0, bit_count);
184     i_tags_add(&im->tags, "i_format", 0, "bmp", 3, 0);
185   }
186
187   return im;
188 }
189
190 /*
191 =back
192
193 =head1 IMPLEMENTATION FUNCTIONS
194
195 Internal functions used in the implementation.
196
197 =over
198
199 =item read_packed(ig, format, ...)
200
201 Reads from the specified "file" the specified sizes.  The format codes
202 match those used by perl's pack() function, though only a few are
203 implemented.  In all cases the vararg arguement is an int *.
204
205 Returns non-zero if all of the arguments were read.
206
207 =cut
208 */
209 static
210 int read_packed(io_glue *ig, char *format, ...) {
211   unsigned char buf[4];
212   va_list ap;
213   int *p;
214
215   va_start(ap, format);
216
217   while (*format) {
218     p = va_arg(ap, int *);
219
220     switch (*format) {
221     case 'v':
222       if (ig->readcb(ig, buf, 2) != 2)
223         return 0;
224       *p = buf[0] + (buf[1] << 8);
225       break;
226
227     case 'V':
228       if (ig->readcb(ig, buf, 4) != 4)
229         return 0;
230       *p = buf[0] + (buf[1] << 8) + (buf[2] << 16) + (buf[3] << 24);
231       break;
232
233     case 'C':
234       if (ig->readcb(ig, buf, 1) != 1)
235         return 0;
236       *p = buf[0];
237       break;
238
239     case 'c':
240       if (ig->readcb(ig, buf, 1) != 1)
241         return 0;
242       *p = (char)buf[0];
243       break;
244       
245     case '3': /* extension - 24-bit number */
246       if (ig->readcb(ig, buf, 3) != 3)
247         return 0;
248       *p = buf[0] + (buf[1] << 8) + (buf[2] << 16);
249       break;
250       
251     default:
252       i_fatal(1, "Unknown read_packed format code 0x%02x", *format);
253     }
254     ++format;
255   }
256   return 1;
257 }
258
259 /*
260 =item write_packed(ig, format, ...)
261
262 Writes packed data to the specified io_glue.
263
264 Returns non-zero on success.
265
266 =cut
267 */
268
269 static int
270 write_packed(io_glue *ig, char *format, ...) {
271   unsigned char buf[4];
272   va_list ap;
273   int i;
274
275   va_start(ap, format);
276
277   while (*format) {
278     i = va_arg(ap, unsigned int);
279
280     switch (*format) {
281     case 'v':
282       buf[0] = i & 255;
283       buf[1] = i / 256;
284       if (ig->writecb(ig, buf, 2) == -1)
285         return 0;
286       break;
287
288     case 'V':
289       buf[0] = i & 0xFF;
290       buf[1] = (i >> 8) & 0xFF;
291       buf[2] = (i >> 16) & 0xFF;
292       buf[3] = (i >> 24) & 0xFF;
293       if (ig->writecb(ig, buf, 4) == -1)
294         return 0;
295       break;
296
297     case 'C':
298     case 'c':
299       buf[0] = i & 0xFF;
300       if (ig->writecb(ig, buf, 1) == -1)
301         return 0;
302       break;
303
304     default:
305       i_fatal(1, "Unknown write_packed format code 0x%02x", *format);
306     }
307     ++format;
308   }
309   va_end(ap);
310
311   return 1;
312 }
313
314 /*
315 =item write_bmphead(ig, im, bit_count, data_size)
316
317 Writes a Windows BMP header to the file.
318
319 Returns non-zero on success.
320
321 =cut
322 */
323
324 static
325 int write_bmphead(io_glue *ig, i_img *im, int bit_count, int data_size) {
326   double xres, yres;
327   int got_xres, got_yres, aspect_only;
328   int colors_used = 0;
329   int offset = FILEHEAD_SIZE + INFOHEAD_SIZE;
330
331   got_xres = i_tags_get_float(&im->tags, "i_xres", 0, &xres);
332   got_yres = i_tags_get_float(&im->tags, "i_yres", 0, &yres);
333   if (!i_tags_get_int(&im->tags, "i_aspect_only", 0,&aspect_only))
334     aspect_only = 0;
335   if (!got_xres) {
336     if (!got_yres)
337       xres = yres = 72;
338     else
339       xres = yres;
340   }
341   else {
342     if (!got_yres)
343       yres = xres;
344   }
345   if (xres <= 0 || yres <= 0)
346     xres = yres = 72;
347   if (aspect_only) {
348     /* scale so the smaller value is 72 */
349     double ratio;
350     if (xres < yres) {
351       ratio = 72.0 / xres;
352     }
353     else {
354       ratio = 72.0 / yres;
355     }
356     xres *= ratio;
357     yres *= ratio;
358   }
359   /* now to pels/meter */
360   xres *= 100.0/2.54;
361   yres *= 100.0/2.54;
362
363   if (im->type == i_palette_type) {
364     colors_used = i_colorcount(im);
365     offset += 4 * colors_used;
366   }
367
368   if (!write_packed(ig, "CCVvvVVVVvvVVVVVV", 'B', 'M', data_size+offset, 
369                     0, 0, offset, INFOHEAD_SIZE, im->xsize, im->ysize, 1, 
370                     bit_count, BI_RGB, 0, (int)(xres+0.5), (int)(yres+0.5), 
371                     colors_used, colors_used)){
372     i_push_error(0, "cannot write bmp header");
373     return 0;
374   }
375   if (im->type == i_palette_type) {
376     int i;
377     i_color c;
378
379     for (i = 0; i < colors_used; ++i) {
380       i_getcolors(im, i, &c, 1);
381       if (im->channels >= 3) {
382         if (!write_packed(ig, "CCCC", c.channel[2], c.channel[1], 
383                           c.channel[0], 0)) {
384           i_push_error(0, "cannot write palette entry");
385           return 0;
386         }
387       }
388       else {
389         if (!write_packed(ig, "CCCC", c.channel[0], c.channel[0], 
390                           c.channel[0], 0)) {
391           i_push_error(0, "cannot write palette entry");
392           return 0;
393         }
394       }
395     }
396   }
397
398   return 1;
399 }
400
401 /*
402 =item write_1bit_data(ig, im)
403
404 Writes the image data as a 1-bit/pixel image.
405
406 Returns non-zero on success.
407
408 =cut
409 */
410 static int
411 write_1bit_data(io_glue *ig, i_img *im) {
412   i_palidx *line;
413   unsigned char *packed;
414   int byte;
415   int mask;
416   unsigned char *out;
417   int line_size = (im->xsize+7) / 8;
418   int x, y;
419   int unpacked_size;
420
421   /* round up to nearest multiple of four */
422   line_size = (line_size + 3) / 4 * 4;
423
424   if (!write_bmphead(ig, im, 1, line_size * im->ysize))
425     return 0;
426
427   /* this shouldn't be an issue, but let's be careful */
428   unpacked_size = im->xsize + 8;
429   if (unpacked_size < im->xsize) {
430     i_push_error(0, "integer overflow during memory allocation");
431     return 0;
432   }
433   line = mymalloc(unpacked_size); /* checked 29jun05 tonyc */
434   memset(line + im->xsize, 0, 8);
435
436   /* size allocated here is always much smaller than xsize, hence
437      can't overflow int */
438   packed = mymalloc(line_size); /* checked 29jun05 tonyc */
439   memset(packed, 0, line_size);
440   
441   for (y = im->ysize-1; y >= 0; --y) {
442     i_gpal(im, 0, im->xsize, y, line);
443     mask = 0x80;
444     byte = 0;
445     out = packed;
446     for (x = 0; x < im->xsize; ++x) {
447       if (line[x])
448         byte |= mask;
449       if ((mask >>= 1) == 0) {
450         *out++ = byte;
451         byte = 0;
452         mask = 0x80;
453       }
454     }
455     if (mask != 0x80) {
456       *out++ = byte;
457     }
458     if (ig->writecb(ig, packed, line_size) < 0) {
459       myfree(packed);
460       myfree(line);
461       i_push_error(0, "writing 1 bit/pixel packed data");
462       return 0;
463     }
464   }
465   myfree(packed);
466   myfree(line);
467
468   ig->closecb(ig);
469
470   return 1;
471 }
472
473 /*
474 =item write_4bit_data(ig, im)
475
476 Writes the image data as a 4-bit/pixel image.
477
478 Returns non-zero on success.
479
480 =cut
481 */
482 static int
483 write_4bit_data(io_glue *ig, i_img *im) {
484   i_palidx *line;
485   unsigned char *packed;
486   unsigned char *out;
487   int line_size = (im->xsize+1) / 2;
488   int x, y;
489   int unpacked_size;
490
491   /* round up to nearest multiple of four */
492   line_size = (line_size + 3) / 4 * 4;
493
494   if (!write_bmphead(ig, im, 4, line_size * im->ysize))
495     return 0;
496
497   /* this shouldn't be an issue, but let's be careful */
498   unpacked_size = im->xsize + 2;
499   if (unpacked_size < im->xsize) {
500     i_push_error(0, "integer overflow during memory allocation");
501     return 0;
502   }
503   line = mymalloc(unpacked_size); /* checked 29jun05 tonyc */
504   memset(line + im->xsize, 0, 2);
505   
506   /* size allocated here is always much smaller than xsize, hence
507      can't overflow int */
508   packed = mymalloc(line_size); /* checked 29jun05 tonyc */
509   memset(packed, 0, line_size);
510   
511   for (y = im->ysize-1; y >= 0; --y) {
512     i_gpal(im, 0, im->xsize, y, line);
513     out = packed;
514     for (x = 0; x < im->xsize; x += 2) {
515       *out++ = (line[x] << 4) + line[x+1];
516     }
517     if (ig->writecb(ig, packed, line_size) < 0) {
518       myfree(packed);
519       myfree(line);
520       i_push_error(0, "writing 4 bit/pixel packed data");
521       return 0;
522     }
523   }
524   myfree(packed);
525   myfree(line);
526
527   ig->closecb(ig);
528
529   return 1;
530 }
531
532 /*
533 =item write_8bit_data(ig, im)
534
535 Writes the image data as a 8-bit/pixel image.
536
537 Returns non-zero on success.
538
539 =cut
540 */
541 static int
542 write_8bit_data(io_glue *ig, i_img *im) {
543   i_palidx *line;
544   int line_size = im->xsize;
545   int y;
546   int unpacked_size;
547
548   /* round up to nearest multiple of four */
549   line_size = (line_size + 3) / 4 * 4;
550
551   if (!write_bmphead(ig, im, 8, line_size * im->ysize))
552     return 0;
553
554   /* this shouldn't be an issue, but let's be careful */
555   unpacked_size = im->xsize + 4;
556   if (unpacked_size < im->xsize) {
557     i_push_error(0, "integer overflow during memory allocation");
558     return 0;
559   }
560   line = mymalloc(unpacked_size); /* checked 29jun05 tonyc */
561   memset(line + im->xsize, 0, 4);
562   
563   for (y = im->ysize-1; y >= 0; --y) {
564     i_gpal(im, 0, im->xsize, y, line);
565     if (ig->writecb(ig, line, line_size) < 0) {
566       myfree(line);
567       i_push_error(0, "writing 8 bit/pixel packed data");
568       return 0;
569     }
570   }
571   myfree(line);
572
573   ig->closecb(ig);
574
575   return 1;
576 }
577
578 /*
579 =item write_24bit_data(ig, im)
580
581 Writes the image data as a 24-bit/pixel image.
582
583 Returns non-zero on success.
584
585 =cut
586 */
587 static int
588 write_24bit_data(io_glue *ig, i_img *im) {
589   int *chans;
590   unsigned char *samples;
591   int y;
592   int line_size = 3 * im->xsize;
593   i_color bg;
594
595   i_get_file_background(im, &bg);
596
597   /* just in case we implement a direct format with 2bytes/pixel
598      (unlikely though) */
599   if (line_size / 3 != im->xsize) {
600     i_push_error(0, "integer overflow during memory allocation");
601     return 0;
602   }
603   
604   line_size = (line_size + 3) / 4 * 4;
605   
606   if (!write_bmphead(ig, im, 24, line_size * im->ysize))
607     return 0;
608   samples = mymalloc(4 * im->xsize);
609   memset(samples, 0, line_size);
610   for (y = im->ysize-1; y >= 0; --y) {
611     unsigned char *samplep = samples;
612     int x;
613     i_gsamp_bg(im, 0, im->xsize, y, samples, 3, &bg);
614     for (x = 0; x < im->xsize; ++x) {
615       unsigned char tmp = samplep[2];
616       samplep[2] = samplep[0];
617       samplep[0] = tmp;
618       samplep += 3;
619     }
620     if (ig->writecb(ig, samples, line_size) < 0) {
621       i_push_error(0, "writing image data");
622       myfree(samples);
623       return 0;
624     }
625   }
626   myfree(samples);
627
628   ig->closecb(ig);
629
630   return 1;
631 }
632
633 /*
634 =item read_bmp_pal(ig, im, count)
635
636 Reads count palette entries from the file and add them to the image.
637
638 Returns non-zero on success.
639
640 =cut
641 */
642 static int
643 read_bmp_pal(io_glue *ig, i_img *im, int count) {
644   int i;
645   int r, g, b, x;
646   i_color c;
647   
648   for (i = 0; i < count; ++i) {
649     if (!read_packed(ig, "CCCC", &b, &g, &r, &x)) {
650       i_push_error(0, "reading BMP palette");
651       return 0;
652     }
653     c.channel[0] = r;
654     c.channel[1] = g;
655     c.channel[2] = b;
656     if (i_addcolors(im, &c, 1) < 0) {
657       i_push_error(0, "out of space in image palette");
658       return 0;
659     }
660   }
661   
662   return 1;
663 }
664
665 /*
666 =item read_1bit_bmp(ig, xsize, ysize, clr_used, compression, offbits)
667
668 Reads in the palette and image data for a 1-bit/pixel image.
669
670 Returns the image or NULL.
671
672 =cut
673 */
674 static i_img *
675 read_1bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
676               int compression, long offbits, int allow_incomplete) {
677   i_img *im;
678   int x, y, lasty, yinc, start_y;
679   i_palidx *line, *p;
680   unsigned char *packed;
681   int line_size = (xsize + 7)/8;
682   int bit;
683   unsigned char *in;
684   long base_offset;
685
686   if (compression != BI_RGB) {
687     i_push_errorf(0, "unknown 1-bit BMP compression (%d)", compression);
688     return NULL;
689   }
690
691   if (xsize + 8 < xsize) { /* if there was overflow */
692     /* we check with 8 because we allocate that much for the decoded 
693        line buffer */
694     i_push_error(0, "integer overflow during memory allocation");
695     return NULL;
696   }
697
698   /* if xsize+7 is ok then (xsize+7)/8 will be and the minor
699      adjustments below won't make it overflow */
700   line_size = (line_size+3) / 4 * 4;
701
702   if (ysize > 0) {
703     start_y = ysize-1;
704     lasty = -1;
705     yinc = -1;
706   }
707   else {
708     /* when ysize is -ve it's a top-down image */
709     ysize = -ysize;
710     start_y = 0;
711     lasty = ysize;
712     yinc = 1;
713   }
714   y = start_y;
715   if (!clr_used)
716     clr_used = 2;
717   if (clr_used < 0 || clr_used > 2) {
718     i_push_errorf(0, "out of range colors used (%d)", clr_used);
719     return NULL;
720   }
721
722   base_offset = FILEHEAD_SIZE + INFOHEAD_SIZE + clr_used * 4;
723   if (offbits < base_offset) {
724     i_push_errorf(0, "image data offset too small (%ld)", offbits);
725     return NULL;
726   }
727
728   im = i_img_pal_new(xsize, ysize, 3, 256);
729   if (!im)
730     return NULL;
731   if (!read_bmp_pal(ig, im, clr_used)) {
732     i_img_destroy(im);
733     return NULL;
734   }
735
736   if (offbits > base_offset) {
737     /* this will be slow if the offset is large, but that should be
738        rare */
739     char buffer;
740     while (base_offset < offbits) {
741       if (ig->readcb(ig, &buffer, 1) != 1) {
742         i_img_destroy(im);
743         i_push_error(0, "failed skipping to image data offset");
744         return NULL;
745       }
746       ++base_offset;
747     }
748   }
749   
750   i_tags_add(&im->tags, "bmp_compression_name", 0, "BI_RGB", -1, 0);
751
752   packed = mymalloc(line_size); /* checked 29jun05 tonyc */
753   line = mymalloc(xsize+8); /* checked 29jun05 tonyc */
754   while (y != lasty) {
755     if (ig->readcb(ig, packed, line_size) != line_size) {
756       myfree(packed);
757       myfree(line);
758       if (allow_incomplete) {
759         i_tags_setn(&im->tags, "i_incomplete", 1);
760         i_tags_setn(&im->tags, "i_lines_read", abs(start_y - y));
761         return im;
762       }
763       else {
764         i_push_error(0, "failed reading 1-bit bmp data");
765         i_img_destroy(im);
766         return NULL;
767       }
768     }
769     in = packed;
770     bit = 0x80;
771     p = line;
772     for (x = 0; x < xsize; ++x) {
773       *p++ = (*in & bit) ? 1 : 0;
774       bit >>= 1;
775       if (!bit) {
776         ++in;
777         bit = 0x80;
778       }
779     }
780     i_ppal(im, 0, xsize, y, line);
781     y += yinc;
782   }
783
784   myfree(packed);
785   myfree(line);
786   return im;
787 }
788
789 /*
790 =item read_4bit_bmp(ig, xsize, ysize, clr_used, compression)
791
792 Reads in the palette and image data for a 4-bit/pixel image.
793
794 Returns the image or NULL.
795
796 Hopefully this will be combined with the following function at some
797 point.
798
799 =cut
800 */
801 static i_img *
802 read_4bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
803               int compression, long offbits, int allow_incomplete) {
804   i_img *im;
805   int x, y, lasty, yinc;
806   i_palidx *line, *p;
807   unsigned char *packed;
808   int line_size = (xsize + 1)/2;
809   unsigned char *in;
810   int size, i;
811   long base_offset;
812   int starty;
813
814   /* line_size is going to be smaller than xsize in most cases (and
815      when it's not, xsize is itself small), and hence not overflow */
816   line_size = (line_size+3) / 4 * 4;
817
818   if (ysize > 0) {
819     starty = ysize-1;
820     lasty = -1;
821     yinc = -1;
822   }
823   else {
824     /* when ysize is -ve it's a top-down image */
825     ysize = -ysize;
826     starty = 0;
827     lasty = ysize;
828     yinc = 1;
829   }
830   y = starty;
831   if (!clr_used)
832     clr_used = 16;
833
834   if (clr_used > 16 || clr_used < 0) {
835     i_push_errorf(0, "out of range colors used (%d)", clr_used);
836     return NULL;
837   }
838
839   base_offset = FILEHEAD_SIZE + INFOHEAD_SIZE + clr_used * 4;
840   if (offbits < base_offset) {
841     i_push_errorf(0, "image data offset too small (%ld)", offbits);
842     return NULL;
843   }
844
845   im = i_img_pal_new(xsize, ysize, 3, 256);
846   if (!im) /* error should have been pushed already */
847     return NULL;
848   if (!read_bmp_pal(ig, im, clr_used)) {
849     i_img_destroy(im);
850     return NULL;
851   }
852
853   if (offbits > base_offset) {
854     /* this will be slow if the offset is large, but that should be
855        rare */
856     char buffer;
857     while (base_offset < offbits) {
858       if (ig->readcb(ig, &buffer, 1) != 1) {
859         i_img_destroy(im);
860         i_push_error(0, "failed skipping to image data offset");
861         return NULL;
862       }
863       ++base_offset;
864     }
865   }
866   
867   if (line_size < 260)
868     packed = mymalloc(260); /* checked 29jun05 tonyc */
869   else
870     packed = mymalloc(line_size); /* checked 29jun05 tonyc */
871   /* xsize won't approach MAXINT */
872   line = mymalloc(xsize+1); /* checked 29jun05 tonyc */
873   if (compression == BI_RGB) {
874     i_tags_add(&im->tags, "bmp_compression_name", 0, "BI_RGB", -1, 0);
875     while (y != lasty) {
876       if (ig->readcb(ig, packed, line_size) != line_size) {
877         myfree(packed);
878         myfree(line);
879         if (allow_incomplete) {
880           i_tags_setn(&im->tags, "i_incomplete", 1);
881           i_tags_setn(&im->tags, "i_lines_read", abs(y - starty));
882           return im;
883         }
884         else {
885           i_push_error(0, "failed reading 4-bit bmp data");
886           i_img_destroy(im);
887           return NULL;
888         }
889       }
890       in = packed;
891       p = line;
892       for (x = 0; x < xsize; x+=2) {
893         *p++ = *in >> 4;
894         *p++ = *in & 0x0F;
895         ++in;
896       }
897       i_ppal(im, 0, xsize, y, line);
898       y += yinc;
899     }
900     myfree(packed);
901     myfree(line);
902   }
903   else if (compression == BI_RLE4) {
904     int read_size;
905     int count;
906
907     i_tags_add(&im->tags, "bmp_compression_name", 0, "BI_RLE4", -1, 0);
908     x = 0;
909     while (1) {
910       /* there's always at least 2 bytes in a sequence */
911       if (ig->readcb(ig, packed, 2) != 2) {
912         myfree(packed);
913         myfree(line);
914         if (allow_incomplete) {
915           i_tags_setn(&im->tags, "i_incomplete", 1);
916           i_tags_setn(&im->tags, "i_lines_read", abs(y - starty));
917           return im;
918         }
919         else {
920           i_push_error(0, "missing data during decompression");
921           i_img_destroy(im);
922           return NULL;
923         }
924       }
925       else if (packed[0]) {
926         if (x + packed[0] > xsize) {
927           /* this file is corrupt */
928           myfree(packed);
929           myfree(line);
930           i_push_error(0, "invalid data during decompression");
931           i_img_destroy(im);
932           return NULL;
933         }
934         line[0] = packed[1] >> 4;
935         line[1] = packed[1] & 0x0F;
936         for (i = 0; i < packed[0]; i += 2) {
937           if (i < packed[0]-1) 
938             i_ppal(im, x, x+2, y, line);
939           else
940             i_ppal(im, x, x+(packed[0]-i), y, line);
941           x += 2;
942         }
943       } else {
944         switch (packed[1]) {
945         case BMPRLE_ENDOFLINE:
946           x = 0;
947           y += yinc;
948           break;
949
950         case BMPRLE_ENDOFBMP:
951           myfree(packed);
952           myfree(line);
953           return im;
954
955         case BMPRLE_DELTA:
956           if (ig->readcb(ig, packed, 2) != 2) {
957             myfree(packed);
958             myfree(line);
959             if (allow_incomplete) {
960               i_tags_setn(&im->tags, "i_incomplete", 1);
961               i_tags_setn(&im->tags, "i_lines_read", abs(y - starty));
962               return im;
963             }
964             else {
965               i_push_error(0, "missing data during decompression");
966               i_img_destroy(im);
967               return NULL;
968             }
969           }
970           x += packed[0];
971           y += yinc * packed[1];
972           break;
973
974         default:
975           count = packed[1];
976           if (x + count > xsize) {
977             /* this file is corrupt */
978             myfree(packed);
979             myfree(line);
980             i_push_error(0, "invalid data during decompression");
981             i_img_destroy(im);
982             return NULL;
983           }
984           size = (count + 1) / 2;
985           read_size = (size+1) / 2 * 2;
986           if (ig->readcb(ig, packed, read_size) != read_size) {
987             myfree(packed);
988             myfree(line);
989             if (allow_incomplete) {
990               i_tags_setn(&im->tags, "i_incomplete", 1);
991               i_tags_setn(&im->tags, "i_lines_read", abs(y - starty));
992               return im;
993             }
994             else {
995               i_push_error(0, "missing data during decompression");
996               i_img_destroy(im);
997               return NULL;
998             }
999           }
1000           for (i = 0; i < size; ++i) {
1001             line[0] = packed[i] >> 4;
1002             line[1] = packed[i] & 0xF;
1003             i_ppal(im, x, x+2, y, line);
1004             x += 2;
1005           }
1006           break;
1007         }
1008       }
1009     }
1010   }
1011   else { /*if (compression == BI_RLE4) {*/
1012     myfree(packed);
1013     myfree(line);
1014     i_push_errorf(0, "unknown 4-bit BMP compression (%d)", compression);
1015     i_img_destroy(im);
1016     return NULL;
1017   }
1018
1019   return im;
1020 }
1021
1022 /*
1023 =item read_8bit_bmp(ig, xsize, ysize, clr_used, compression, allow_incomplete)
1024
1025 Reads in the palette and image data for a 8-bit/pixel image.
1026
1027 Returns the image or NULL.
1028
1029 =cut
1030 */
1031 static i_img *
1032 read_8bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
1033               int compression, long offbits, int allow_incomplete) {
1034   i_img *im;
1035   int x, y, lasty, yinc, start_y;
1036   i_palidx *line;
1037   int line_size = xsize;
1038   long base_offset;
1039
1040   line_size = (line_size+3) / 4 * 4;
1041   if (line_size < xsize) { /* if it overflowed (unlikely, but check) */
1042     i_push_error(0, "integer overflow during memory allocation");
1043     return NULL;
1044   }
1045
1046   if (ysize > 0) {
1047     start_y = ysize-1;
1048     lasty = -1;
1049     yinc = -1;
1050   }
1051   else {
1052     /* when ysize is -ve it's a top-down image */
1053     ysize = -ysize;
1054     start_y = 0;
1055     lasty = ysize;
1056     yinc = 1;
1057   }
1058   y = start_y;
1059   if (!clr_used)
1060     clr_used = 256;
1061   if (clr_used > 256 || clr_used < 0) {
1062     i_push_errorf(0, "out of range colors used (%d)", clr_used);
1063     return NULL;
1064   }
1065
1066   base_offset = FILEHEAD_SIZE + INFOHEAD_SIZE + clr_used * 4;
1067   if (offbits < base_offset) {
1068     i_push_errorf(0, "image data offset too small (%ld)", offbits);
1069     return NULL;
1070   }
1071
1072   im = i_img_pal_new(xsize, ysize, 3, 256);
1073   if (!im)
1074     return NULL;
1075   if (!read_bmp_pal(ig, im, clr_used)) {
1076     i_img_destroy(im);
1077     return NULL;
1078   }
1079
1080   if (offbits > base_offset) {
1081     /* this will be slow if the offset is large, but that should be
1082        rare */
1083     char buffer;
1084     while (base_offset < offbits) {
1085       if (ig->readcb(ig, &buffer, 1) != 1) {
1086         i_img_destroy(im);
1087         i_push_error(0, "failed skipping to image data offset");
1088         return NULL;
1089       }
1090       ++base_offset;
1091     }
1092   }
1093   
1094   line = mymalloc(line_size); /* checked 29jun05 tonyc */
1095   if (compression == BI_RGB) {
1096     i_tags_add(&im->tags, "bmp_compression_name", 0, "BI_RGB", -1, 0);
1097     while (y != lasty) {
1098       if (ig->readcb(ig, line, line_size) != line_size) {
1099         myfree(line);
1100         if (allow_incomplete) {
1101           i_tags_setn(&im->tags, "i_incomplete", 1);
1102           i_tags_setn(&im->tags, "i_lines_read", abs(start_y - y));
1103           return im;
1104         }
1105         else {
1106           i_push_error(0, "failed reading 8-bit bmp data");
1107           i_img_destroy(im);
1108           return NULL;
1109         }
1110       }
1111       i_ppal(im, 0, xsize, y, line);
1112       y += yinc;
1113     }
1114     myfree(line);
1115   }
1116   else if (compression == BI_RLE8) {
1117     int read_size;
1118     int count;
1119     unsigned char packed[2];
1120
1121     i_tags_add(&im->tags, "bmp_compression_name", 0, "BI_RLE8", -1, 0);
1122     x = 0;
1123     while (1) {
1124       /* there's always at least 2 bytes in a sequence */
1125       if (ig->readcb(ig, packed, 2) != 2) {
1126         myfree(line);
1127         if (allow_incomplete) {
1128           i_tags_setn(&im->tags, "i_incomplete", 1);
1129           i_tags_setn(&im->tags, "i_lines_read", abs(start_y-y));
1130           return im;
1131         }
1132         else {
1133           i_push_error(0, "missing data during decompression");
1134           i_img_destroy(im);
1135           return NULL;
1136         }
1137       }
1138       if (packed[0]) {
1139         if (x + packed[0] > xsize) {
1140           /* this file isn't incomplete, it's corrupt */
1141           myfree(line);
1142           i_push_error(0, "invalid data during decompression");
1143           i_img_destroy(im);
1144           return NULL;
1145         }
1146         memset(line, packed[1], packed[0]);
1147         i_ppal(im, x, x+packed[0], y, line);
1148         x += packed[0];
1149       } else {
1150         switch (packed[1]) {
1151         case BMPRLE_ENDOFLINE:
1152           x = 0;
1153           y += yinc;
1154           break;
1155
1156         case BMPRLE_ENDOFBMP:
1157           myfree(line);
1158           return im;
1159
1160         case BMPRLE_DELTA:
1161           if (ig->readcb(ig, packed, 2) != 2) {
1162             myfree(line);
1163             if (allow_incomplete) {
1164               i_tags_setn(&im->tags, "i_incomplete", 1);
1165               i_tags_setn(&im->tags, "i_lines_read", abs(start_y-y));
1166               return im;
1167             }
1168             else {
1169               i_push_error(0, "missing data during decompression");
1170               i_img_destroy(im);
1171               return NULL;
1172             }
1173           }
1174           x += packed[0];
1175           y += yinc * packed[1];
1176           break;
1177
1178         default:
1179           count = packed[1];
1180           if (x + count > xsize) {
1181             /* runs shouldn't cross a line boundary */
1182             /* this file isn't incomplete, it's corrupt */
1183             myfree(line);
1184             i_push_error(0, "invalid data during decompression");
1185             i_img_destroy(im);
1186             return NULL;
1187           }
1188           read_size = (count+1) / 2 * 2;
1189           if (ig->readcb(ig, line, read_size) != read_size) {
1190             myfree(line);
1191             if (allow_incomplete) {
1192               i_tags_setn(&im->tags, "i_incomplete", 1);
1193               i_tags_setn(&im->tags, "i_lines_read", abs(start_y-y));
1194               return im;
1195             }
1196             else {
1197               i_push_error(0, "missing data during decompression");
1198               i_img_destroy(im);
1199               return NULL;
1200             }
1201           }
1202           i_ppal(im, x, x+count, y, line);
1203           x += count;
1204           break;
1205         }
1206       }
1207     }
1208   }
1209   else { 
1210     myfree(line);
1211     i_push_errorf(0, "unknown 8-bit BMP compression (%d)", compression);
1212     i_img_destroy(im);
1213     return NULL;
1214   }
1215
1216   return im;
1217 }
1218
1219 struct bm_masks {
1220   unsigned masks[3];
1221   int shifts[3];
1222 };
1223 static struct bm_masks std_masks[] =
1224 {
1225   { /* 16-bit */
1226     { 0770000, 00007700, 00000077, },
1227     { 10, 4, -2, },
1228   },
1229   { /* 24-bit */
1230     { 0xFF0000, 0x00FF00, 0x0000FF, },
1231     {       16,        8,        0, },
1232   },
1233   { /* 32-bit */
1234     { 0xFF0000, 0x00FF00, 0x0000FF, },
1235     {       16,        8,        0, },
1236   },
1237 };
1238
1239 /*
1240 =item read_direct_bmp(ig, xsize, ysize, bit_count, clr_used, compression, allow_incomplete)
1241
1242 Skips the palette and reads in the image data for a direct colour image.
1243
1244 Returns the image or NULL.
1245
1246 =cut
1247 */
1248 static i_img *
1249 read_direct_bmp(io_glue *ig, int xsize, int ysize, int bit_count, 
1250                 int clr_used, int compression, long offbits, 
1251                 int allow_incomplete) {
1252   i_img *im;
1253   int x, y, starty, lasty, yinc;
1254   i_color *line, *p;
1255   int pix_size = bit_count / 8;
1256   int line_size = xsize * pix_size;
1257   struct bm_masks masks;
1258   char unpack_code[2] = "";
1259   int i;
1260   int extras;
1261   char junk[4];
1262   const char *compression_name;
1263   int bytes;
1264   long base_offset = FILEHEAD_SIZE + INFOHEAD_SIZE;
1265   
1266   unpack_code[0] = *("v3V"+pix_size-2);
1267   unpack_code[1] = '\0';
1268
1269   line_size = (line_size+3) / 4 * 4;
1270   extras = line_size - xsize * pix_size;
1271
1272   if (ysize > 0) {
1273     starty = ysize-1;
1274     lasty = -1;
1275     yinc = -1;
1276   }
1277   else {
1278     /* when ysize is -ve it's a top-down image */
1279     ysize = -ysize;
1280     starty = 0;
1281     lasty = ysize;
1282     yinc = 1;
1283   }
1284   y = starty;
1285   if (compression == BI_RGB) {
1286     compression_name = "BI_RGB";
1287     masks = std_masks[pix_size-2];
1288     
1289     /* there's a potential "palette" after the header */
1290     for (i = 0; i < clr_used; ++clr_used) {
1291       char buf[4];
1292       if (ig->readcb(ig, buf, 4) != 4) {
1293         i_push_error(0, "skipping colors");
1294         return 0;
1295       }
1296       base_offset += 4;
1297     }
1298   }
1299   else if (compression == BI_BITFIELDS) {
1300     int pos, bit;
1301     compression_name = "BI_BITFIELDS";
1302
1303     for (i = 0; i < 3; ++i) {
1304       if (!read_packed(ig, "V", masks.masks+i)) {
1305         i_push_error(0, "reading pixel masks");
1306         return 0;
1307       }
1308       /* work out a shift for the mask */
1309       pos = 0;
1310       bit = masks.masks[i] & -masks.masks[i];
1311       while (bit) {
1312         ++pos;
1313         bit >>= 1;
1314       }
1315       masks.shifts[i] = pos - 8;
1316     }
1317     base_offset += 4 * 4;
1318   }
1319   else {
1320     i_push_errorf(0, "unknown 24-bit BMP compression (%d)", compression);
1321     return NULL;
1322   }
1323
1324   if (offbits < base_offset) {
1325     i_push_errorf(0, "image data offset too small (%ld)", offbits);
1326     return NULL;
1327   }
1328
1329   if (offbits > base_offset) {
1330     /* this will be slow if the offset is large, but that should be
1331        rare */
1332     char buffer;
1333     while (base_offset < offbits) {
1334       if (ig->readcb(ig, &buffer, 1) != 1) {
1335         i_push_error(0, "failed skipping to image data offset");
1336         return NULL;
1337       }
1338       ++base_offset;
1339     }
1340   }
1341   
1342   im = i_img_empty(NULL, xsize, ysize);
1343   if (!im)
1344     return NULL;
1345
1346   i_tags_add(&im->tags, "bmp_compression_name", 0, compression_name, -1, 0);
1347
1348   /* I wasn't able to make this overflow in testing, but better to be
1349      safe */
1350   bytes = sizeof(i_color) * xsize;
1351   if (bytes / sizeof(i_color) != xsize) {
1352     i_img_destroy(im);
1353     i_push_error(0, "integer overflow calculating buffer size");
1354     return NULL;
1355   }
1356   line = mymalloc(bytes); /* checked 29jun05 tonyc */
1357   while (y != lasty) {
1358     p = line;
1359     for (x = 0; x < xsize; ++x) {
1360       unsigned pixel;
1361       if (!read_packed(ig, unpack_code, &pixel)) {
1362         myfree(line);
1363         if (allow_incomplete) {
1364           i_tags_setn(&im->tags, "i_incomplete", 1);
1365           i_tags_setn(&im->tags, "i_lines_read", abs(starty - y));
1366           return im;
1367         }
1368         else {
1369           i_push_error(0, "failed reading image data");
1370           i_img_destroy(im);
1371           return NULL;
1372         }
1373       }
1374       for (i = 0; i < 3; ++i) {
1375         if (masks.shifts[i] > 0)
1376           p->channel[i] = (pixel & masks.masks[i]) >> masks.shifts[i];
1377         else 
1378           p->channel[i] = (pixel & masks.masks[i]) << -masks.shifts[i];
1379       }
1380       ++p;
1381     }
1382     i_plin(im, 0, xsize, y, line);
1383     if (extras)
1384       ig->readcb(ig, junk, extras);
1385     y += yinc;
1386   }
1387   myfree(line);
1388
1389   return im;
1390 }
1391
1392 /*
1393 =head1 SEE ALSO
1394
1395 Imager(3)
1396
1397 =head1 AUTHOR
1398
1399 Tony Cook <tony@develop-help.com>
1400
1401 =head1 RESTRICTIONS
1402
1403 Cannot save as compressed BMP.
1404
1405 =head1 BUGS
1406
1407 Doesn't handle OS/2 bitmaps.
1408
1409 16-bit/pixel images haven't been tested.  (I need an image).
1410
1411 BI_BITFIELDS compression hasn't been tested (I need an image).
1412
1413 The header handling for paletted images needs to be refactored
1414
1415 =cut
1416 */