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