]> git.imager.perl.org - imager.git/blob - bmp.c
- minor cleanup of Imager::Fill
[imager.git] / bmp.c
1 #include "image.h"
2 #include <stdarg.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);
49 static i_img *read_4bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
50                             int compression, long offbits);
51 static i_img *read_8bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
52                             int compression, long offbits);
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);
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) {
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");
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   switch (bit_count) {
137   case 1:
138     im = read_1bit_bmp(ig, xsize, ysize, clr_used, compression, offbits);
139     break;
140
141   case 4:
142     im = read_4bit_bmp(ig, xsize, ysize, clr_used, compression, offbits);
143     break;
144
145   case 8:
146     im = read_8bit_bmp(ig, xsize, ysize, clr_used, compression, offbits);
147     break;
148
149   case 32:
150   case 24:
151   case 16:
152     im = read_direct_bmp(ig, xsize, ysize, bit_count, clr_used, compression,
153                          offbits);
154     break;
155
156   default:
157     i_push_errorf(0, "unknown bit count for BMP file (%d)", bit_count);
158     return NULL;
159   }
160
161   if (im) {
162     /* store the resolution */
163     if (xres && !yres)
164       yres = xres;
165     else if (yres && !xres)
166       xres = yres;
167     if (xres) {
168       i_tags_set_float2(&im->tags, "i_xres", 0, xres * 0.0254, 4);
169       i_tags_set_float2(&im->tags, "i_yres", 0, yres * 0.0254, 4);
170     }
171     i_tags_addn(&im->tags, "bmp_compression", 0, compression);
172     i_tags_addn(&im->tags, "bmp_important_colors", 0, clr_important);
173     i_tags_addn(&im->tags, "bmp_used_colors", 0, clr_used);
174     i_tags_addn(&im->tags, "bmp_filesize", 0, filesize);
175     i_tags_addn(&im->tags, "bmp_bit_count", 0, bit_count);
176     i_tags_add(&im->tags, "i_format", 0, "bmp", 3, 0);
177   }
178
179   return im;
180 }
181
182 /*
183 =back
184
185 =head1 IMPLEMENTATION FUNCTIONS
186
187 Internal functions used in the implementation.
188
189 =over
190
191 =item read_packed(ig, format, ...)
192
193 Reads from the specified "file" the specified sizes.  The format codes
194 match those used by perl's pack() function, though only a few are
195 implemented.  In all cases the vararg arguement is an int *.
196
197 Returns non-zero if all of the arguments were read.
198
199 =cut
200 */
201 static
202 int read_packed(io_glue *ig, char *format, ...) {
203   unsigned char buf[4];
204   va_list ap;
205   int *p;
206
207   va_start(ap, format);
208
209   while (*format) {
210     p = va_arg(ap, int *);
211
212     switch (*format) {
213     case 'v':
214       if (ig->readcb(ig, buf, 2) != 2)
215         return 0;
216       *p = buf[0] + (buf[1] << 8);
217       break;
218
219     case 'V':
220       if (ig->readcb(ig, buf, 4) != 4)
221         return 0;
222       *p = buf[0] + (buf[1] << 8) + (buf[2] << 16) + (buf[3] << 24);
223       break;
224
225     case 'C':
226       if (ig->readcb(ig, buf, 1) != 1)
227         return 0;
228       *p = buf[0];
229       break;
230
231     case 'c':
232       if (ig->readcb(ig, buf, 1) != 1)
233         return 0;
234       *p = (char)buf[0];
235       break;
236       
237     case '3': /* extension - 24-bit number */
238       if (ig->readcb(ig, buf, 3) != 3)
239         return 0;
240       *p = buf[0] + (buf[1] << 8) + (buf[2] << 16);
241       break;
242       
243     default:
244       m_fatal(1, "Unknown read_packed format code 0x%02x", *format);
245     }
246     ++format;
247   }
248   return 1;
249 }
250
251 /*
252 =item write_packed(ig, format, ...)
253
254 Writes packed data to the specified io_glue.
255
256 Returns non-zero on success.
257
258 =cut
259 */
260
261 static int
262 write_packed(io_glue *ig, char *format, ...) {
263   unsigned char buf[4];
264   va_list ap;
265   int i;
266
267   va_start(ap, format);
268
269   while (*format) {
270     i = va_arg(ap, unsigned int);
271
272     switch (*format) {
273     case 'v':
274       buf[0] = i & 255;
275       buf[1] = i / 256;
276       if (ig->writecb(ig, buf, 2) == -1)
277         return 0;
278       break;
279
280     case 'V':
281       buf[0] = i & 0xFF;
282       buf[1] = (i >> 8) & 0xFF;
283       buf[2] = (i >> 16) & 0xFF;
284       buf[3] = (i >> 24) & 0xFF;
285       if (ig->writecb(ig, buf, 4) == -1)
286         return 0;
287       break;
288
289     case 'C':
290     case 'c':
291       buf[0] = i & 0xFF;
292       if (ig->writecb(ig, buf, 1) == -1)
293         return 0;
294       break;
295
296     default:
297       m_fatal(1, "Unknown write_packed format code 0x%02x", *format);
298     }
299     ++format;
300   }
301   va_end(ap);
302
303   return 1;
304 }
305
306 /*
307 =item write_bmphead(ig, im, bit_count, data_size)
308
309 Writes a Windows BMP header to the file.
310
311 Returns non-zero on success.
312
313 =cut
314 */
315
316 static
317 int write_bmphead(io_glue *ig, i_img *im, int bit_count, int data_size) {
318   double xres, yres;
319   int got_xres, got_yres, aspect_only;
320   int colors_used = 0;
321   int offset = FILEHEAD_SIZE + INFOHEAD_SIZE;
322
323   got_xres = i_tags_get_float(&im->tags, "i_xres", 0, &xres);
324   got_yres = i_tags_get_float(&im->tags, "i_yres", 0, &yres);
325   if (!i_tags_get_int(&im->tags, "i_aspect_only", 0,&aspect_only))
326     aspect_only = 0;
327   if (!got_xres) {
328     if (!got_yres)
329       xres = yres = 72;
330     else
331       xres = yres;
332   }
333   else {
334     if (!got_yres)
335       yres = xres;
336   }
337   if (xres <= 0 || yres <= 0)
338     xres = yres = 72;
339   if (aspect_only) {
340     /* scale so the smaller value is 72 */
341     double ratio;
342     if (xres < yres) {
343       ratio = 72.0 / xres;
344     }
345     else {
346       ratio = 72.0 / yres;
347     }
348     xres *= ratio;
349     yres *= ratio;
350   }
351   /* now to pels/meter */
352   xres *= 100.0/2.54;
353   yres *= 100.0/2.54;
354
355   if (im->type == i_palette_type) {
356     colors_used = i_colorcount(im);
357     offset += 4 * colors_used;
358   }
359
360   if (!write_packed(ig, "CCVvvVVVVvvVVVVVV", 'B', 'M', data_size+offset, 
361                     0, 0, offset, INFOHEAD_SIZE, im->xsize, im->ysize, 1, 
362                     bit_count, BI_RGB, 0, (int)(xres+0.5), (int)(yres+0.5), 
363                     colors_used, colors_used)){
364     i_push_error(0, "cannot write bmp header");
365     return 0;
366   }
367   if (im->type == i_palette_type) {
368     int i;
369     i_color c;
370
371     for (i = 0; i < colors_used; ++i) {
372       i_getcolors(im, i, &c, 1);
373       if (im->channels >= 3) {
374         if (!write_packed(ig, "CCCC", c.channel[2], c.channel[1], 
375                           c.channel[0], 0)) {
376           i_push_error(0, "cannot write palette entry");
377           return 0;
378         }
379       }
380       else {
381         if (!write_packed(ig, "CCCC", c.channel[0], c.channel[0], 
382                           c.channel[0], 0)) {
383           i_push_error(0, "cannot write palette entry");
384           return 0;
385         }
386       }
387     }
388   }
389
390   return 1;
391 }
392
393 /*
394 =item write_1bit_data(ig, im)
395
396 Writes the image data as a 1-bit/pixel image.
397
398 Returns non-zero on success.
399
400 =cut
401 */
402 static int
403 write_1bit_data(io_glue *ig, i_img *im) {
404   i_palidx *line;
405   unsigned char *packed;
406   int byte;
407   int mask;
408   unsigned char *out;
409   int line_size = (im->xsize+7) / 8;
410   int x, y;
411
412   /* round up to nearest multiple of four */
413   line_size = (line_size + 3) / 4 * 4;
414
415   if (!write_bmphead(ig, im, 1, line_size * im->ysize))
416     return 0;
417
418   line = mymalloc(im->xsize + 8);
419   memset(line + im->xsize, 0, 8);
420   
421   packed = mymalloc(line_size);
422   memset(packed, 0, line_size);
423   
424   for (y = im->ysize-1; y >= 0; --y) {
425     i_gpal(im, 0, im->xsize, y, line);
426     mask = 0x80;
427     byte = 0;
428     out = packed;
429     for (x = 0; x < im->xsize; ++x) {
430       if (line[x])
431         byte |= mask;
432       if ((mask >>= 1) == 0) {
433         *out++ = byte;
434         byte = 0;
435         mask = 0x80;
436       }
437     }
438     if (mask != 0x80) {
439       *out++ = byte;
440     }
441     if (ig->writecb(ig, packed, line_size) < 0) {
442       myfree(packed);
443       myfree(line);
444       i_push_error(0, "writing 1 bit/pixel packed data");
445       return 0;
446     }
447   }
448   myfree(packed);
449   myfree(line);
450
451   ig->closecb(ig);
452
453   return 1;
454 }
455
456 /*
457 =item write_4bit_data(ig, im)
458
459 Writes the image data as a 4-bit/pixel image.
460
461 Returns non-zero on success.
462
463 =cut
464 */
465 static int
466 write_4bit_data(io_glue *ig, i_img *im) {
467   i_palidx *line;
468   unsigned char *packed;
469   unsigned char *out;
470   int line_size = (im->xsize+1) / 2;
471   int x, y;
472
473   /* round up to nearest multiple of four */
474   line_size = (line_size + 3) / 4 * 4;
475
476   if (!write_bmphead(ig, im, 4, line_size * im->ysize))
477     return 0;
478
479   line = mymalloc(im->xsize + 2);
480   memset(line + im->xsize, 0, 2);
481   
482   packed = mymalloc(line_size);
483   memset(packed, 0, line_size);
484   
485   for (y = im->ysize-1; y >= 0; --y) {
486     i_gpal(im, 0, im->xsize, y, line);
487     out = packed;
488     for (x = 0; x < im->xsize; x += 2) {
489       *out++ = (line[x] << 4) + line[x+1];
490     }
491     if (ig->writecb(ig, packed, line_size) < 0) {
492       myfree(packed);
493       myfree(line);
494       i_push_error(0, "writing 4 bit/pixel packed data");
495       return 0;
496     }
497   }
498   myfree(packed);
499   myfree(line);
500
501   ig->closecb(ig);
502
503   return 1;
504 }
505
506 /*
507 =item write_8bit_data(ig, im)
508
509 Writes the image data as a 8-bit/pixel image.
510
511 Returns non-zero on success.
512
513 =cut
514 */
515 static int
516 write_8bit_data(io_glue *ig, i_img *im) {
517   i_palidx *line;
518   int line_size = im->xsize;
519   int x, y;
520
521   /* round up to nearest multiple of four */
522   line_size = (line_size + 3) / 4 * 4;
523
524   if (!write_bmphead(ig, im, 8, line_size * im->ysize))
525     return 0;
526
527   line = mymalloc(im->xsize + 4);
528   memset(line + im->xsize, 0, 4);
529   
530   for (y = im->ysize-1; y >= 0; --y) {
531     i_gpal(im, 0, im->xsize, y, line);
532     if (ig->writecb(ig, line, line_size) < 0) {
533       myfree(line);
534       i_push_error(0, "writing 8 bit/pixel packed data");
535       return 0;
536     }
537   }
538   myfree(line);
539
540   ig->closecb(ig);
541
542   return 1;
543 }
544
545 static int bgr_chans[] = { 2, 1, 0, };
546 static int grey_chans[] = { 0, 0, 0, };
547
548 /*
549 =item write_24bit_data(ig, im)
550
551 Writes the image data as a 24-bit/pixel image.
552
553 Returns non-zero on success.
554
555 =cut
556 */
557 static int
558 write_24bit_data(io_glue *ig, i_img *im) {
559   int *chans;
560   unsigned char *samples;
561   int x, y;
562   int line_size = 3 * im->xsize;
563   
564   line_size = (line_size + 3) / 4 * 4;
565   
566   if (!write_bmphead(ig, im, 24, line_size * im->ysize))
567     return 0;
568   chans = im->channels >= 3 ? bgr_chans : grey_chans;
569   samples = mymalloc(line_size);
570   memset(samples, 0, line_size);
571   for (y = im->ysize-1; y >= 0; --y) {
572     i_gsamp(im, 0, im->xsize, y, samples, chans, 3);
573     if (ig->writecb(ig, samples, line_size) < 0) {
574       i_push_error(0, "writing image data");
575       myfree(samples);
576       return 0;
577     }
578   }
579   myfree(samples);
580
581   ig->closecb(ig);
582
583   return 1;
584 }
585
586 /*
587 =item read_bmp_pal(ig, im, count)
588
589 Reads count palette entries from the file and add them to the image.
590
591 Returns non-zero on success.
592
593 =cut
594 */
595 static int
596 read_bmp_pal(io_glue *ig, i_img *im, int count) {
597   int i;
598   int r, g, b, x;
599   i_color c;
600   
601   for (i = 0; i < count; ++i) {
602     if (!read_packed(ig, "CCCC", &b, &g, &r, &x)) {
603       i_push_error(0, "reading BMP palette");
604       return 0;
605     }
606     c.channel[0] = r;
607     c.channel[1] = g;
608     c.channel[2] = b;
609     if (i_addcolors(im, &c, 1) < 0) {
610       i_push_error(0, "out of space in image palette");
611       return 0;
612     }
613   }
614   
615   return 1;
616 }
617
618 /*
619 =item read_1bit_bmp(ig, xsize, ysize, clr_used, compression, offbits)
620
621 Reads in the palette and image data for a 1-bit/pixel image.
622
623 Returns the image or NULL.
624
625 =cut
626 */
627 static i_img *
628 read_1bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
629               int compression, long offbits) {
630   i_img *im;
631   int x, y, lasty, yinc;
632   i_palidx *line, *p;
633   unsigned char *packed;
634   int line_size = (xsize + 7)/8;
635   int byte, bit;
636   unsigned char *in;
637   long base_offset;
638
639   if (compression != BI_RGB) {
640     i_push_errorf(0, "unknown 1-bit BMP compression (%d)", compression);
641     return NULL;
642   }
643
644   line_size = (line_size+3) / 4 * 4;
645
646   if (ysize > 0) {
647     y = ysize-1;
648     lasty = -1;
649     yinc = -1;
650   }
651   else {
652     /* when ysize is -ve it's a top-down image */
653     ysize = -ysize;
654     y = 0;
655     lasty = ysize;
656     yinc = 1;
657   }
658   if (!clr_used)
659     clr_used = 2;
660   if (clr_used < 0 || clr_used > 2) {
661     i_push_errorf(0, "out of range colors used (%d)", clr_used);
662     return NULL;
663   }
664
665   base_offset = FILEHEAD_SIZE + INFOHEAD_SIZE + clr_used * 4;
666   if (offbits < base_offset) {
667     i_push_errorf(0, "image data offset too small (%ld)", offbits);
668     return NULL;
669   }
670
671   im = i_img_pal_new(xsize, ysize, 3, 256);
672   if (!im)
673     return NULL;
674   if (!read_bmp_pal(ig, im, clr_used)) {
675     i_img_destroy(im);
676     return NULL;
677   }
678
679   if (offbits > base_offset) {
680     /* this will be slow if the offset is large, but that should be
681        rare */
682     char buffer;
683     while (base_offset < offbits) {
684       if (ig->readcb(ig, &buffer, 1) != 1) {
685         i_img_destroy(im);
686         i_push_error(0, "failed skipping to image data offset");
687         return NULL;
688       }
689       ++base_offset;
690     }
691   }
692   
693   i_tags_add(&im->tags, "bmp_compression_name", 0, "BI_RGB", -1, 0);
694
695   packed = mymalloc(line_size);
696   line = mymalloc(xsize+8);
697   while (y != lasty) {
698     if (ig->readcb(ig, packed, line_size) != line_size) {
699       myfree(packed);
700       myfree(line);
701       i_push_error(0, "failed reading 1-bit bmp data");
702       i_img_destroy(im);
703       return NULL;
704     }
705     in = packed;
706     bit = 0x80;
707     p = line;
708     for (x = 0; x < xsize; ++x) {
709       *p++ = (*in & bit) ? 1 : 0;
710       bit >>= 1;
711       if (!bit) {
712         ++in;
713         bit = 0x80;
714       }
715     }
716     i_ppal(im, 0, xsize, y, line);
717     y += yinc;
718   }
719
720   myfree(packed);
721   myfree(line);
722   return im;
723 }
724
725 /*
726 =item read_4bit_bmp(ig, xsize, ysize, clr_used, compression)
727
728 Reads in the palette and image data for a 4-bit/pixel image.
729
730 Returns the image or NULL.
731
732 Hopefully this will be combined with the following function at some
733 point.
734
735 =cut
736 */
737 static i_img *
738 read_4bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
739               int compression, long offbits) {
740   i_img *im;
741   int x, y, lasty, yinc;
742   i_palidx *line, *p;
743   unsigned char *packed;
744   int line_size = (xsize + 1)/2;
745   unsigned char *in;
746   int size, i;
747   long base_offset;
748
749   line_size = (line_size+3) / 4 * 4;
750
751   if (ysize > 0) {
752     y = ysize-1;
753     lasty = -1;
754     yinc = -1;
755   }
756   else {
757     /* when ysize is -ve it's a top-down image */
758     ysize = -ysize;
759     y = 0;
760     lasty = ysize;
761     yinc = 1;
762   }
763   if (!clr_used)
764     clr_used = 16;
765
766   if (clr_used > 16 || clr_used < 0) {
767     i_push_errorf(0, "out of range colors used (%d)", clr_used);
768     return NULL;
769   }
770
771   base_offset = FILEHEAD_SIZE + INFOHEAD_SIZE + clr_used * 4;
772   if (offbits < base_offset) {
773     i_push_errorf(0, "image data offset too small (%ld)", offbits);
774     return NULL;
775   }
776
777   im = i_img_pal_new(xsize, ysize, 3, 256);
778   if (!im) /* error should have been pushed already */
779     return NULL;
780   if (!read_bmp_pal(ig, im, clr_used)) {
781     i_img_destroy(im);
782     return NULL;
783   }
784
785   if (offbits > base_offset) {
786     /* this will be slow if the offset is large, but that should be
787        rare */
788     char buffer;
789     while (base_offset < offbits) {
790       if (ig->readcb(ig, &buffer, 1) != 1) {
791         i_img_destroy(im);
792         i_push_error(0, "failed skipping to image data offset");
793         return NULL;
794       }
795       ++base_offset;
796     }
797   }
798   
799   if (line_size < 260)
800     packed = mymalloc(260);
801   else
802     packed = mymalloc(line_size);
803   line = mymalloc(xsize+1);
804   if (compression == BI_RGB) {
805     i_tags_add(&im->tags, "bmp_compression_name", 0, "BI_RGB", -1, 0);
806     while (y != lasty) {
807       if (ig->readcb(ig, packed, line_size) != line_size) {
808         myfree(packed);
809         myfree(line);
810         i_push_error(0, "failed reading 4-bit bmp data");
811         i_img_destroy(im);
812         return NULL;
813       }
814       in = packed;
815       p = line;
816       for (x = 0; x < xsize; x+=2) {
817         *p++ = *in >> 4;
818         *p++ = *in & 0x0F;
819         ++in;
820       }
821       i_ppal(im, 0, xsize, y, line);
822       y += yinc;
823     }
824     myfree(packed);
825     myfree(line);
826   }
827   else if (compression == BI_RLE4) {
828     int read_size;
829     int want_high;
830     int count;
831
832     i_tags_add(&im->tags, "bmp_compression_name", 0, "BI_RLE4", -1, 0);
833     x = 0;
834     while (1) {
835       /* there's always at least 2 bytes in a sequence */
836       if (ig->readcb(ig, packed, 2) != 2) {
837         myfree(packed);
838         myfree(line);
839         i_push_error(0, "missing data during decompression");
840         i_img_destroy(im);
841         return NULL;
842       }
843       else if (packed[0]) {
844         line[0] = packed[1] >> 4;
845         line[1] = packed[1] & 0x0F;
846         for (i = 0; i < packed[0]; i += 2) {
847           if (i < packed[0]-1) 
848             i_ppal(im, x, x+2, y, line);
849           else
850             i_ppal(im, x, x+(packed[0]-i), y, line);
851           x += 2;
852         }
853       } else {
854         switch (packed[1]) {
855         case BMPRLE_ENDOFLINE:
856           x = 0;
857           y += yinc;
858           break;
859
860         case BMPRLE_ENDOFBMP:
861           myfree(packed);
862           myfree(line);
863           return im;
864
865         case BMPRLE_DELTA:
866           if (ig->readcb(ig, packed, 2) != 2) {
867             myfree(packed);
868             myfree(line);
869             i_push_error(0, "missing data during decompression");
870             i_img_destroy(im);
871             return NULL;
872           }
873           x += packed[0];
874           y += yinc * packed[1];
875           break;
876
877         default:
878           count = packed[1];
879           size = (count + 1) / 2;
880           read_size = (size+1) / 2 * 2;
881           if (ig->readcb(ig, packed, read_size) != read_size) {
882             myfree(packed);
883             myfree(line);
884             i_push_error(0, "missing data during decompression");
885             /*i_img_destroy(im);*/
886             return im;
887           }
888           for (i = 0; i < size; ++i) {
889             line[0] = packed[i] >> 4;
890             line[1] = packed[i] & 0xF;
891             i_ppal(im, x, x+2, y, line);
892             x += 2;
893           }
894           break;
895         }
896       }
897     }
898   }
899   else { /*if (compression == BI_RLE4) {*/
900     myfree(packed);
901     myfree(line);
902     i_push_errorf(0, "unknown 4-bit BMP compression (%d)", compression);
903     i_img_destroy(im);
904     return NULL;
905   }
906
907   return im;
908 }
909
910 /*
911 =item read_8bit_bmp(ig, xsize, ysize, clr_used, compression)
912
913 Reads in the palette and image data for a 8-bit/pixel image.
914
915 Returns the image or NULL.
916
917 =cut
918 */
919 static i_img *
920 read_8bit_bmp(io_glue *ig, int xsize, int ysize, int clr_used, 
921               int compression, long offbits) {
922   i_img *im;
923   int x, y, lasty, yinc;
924   i_palidx *line, *p;
925   int line_size = xsize;
926   unsigned char *in;
927   long base_offset;
928
929   line_size = (line_size+3) / 4 * 4;
930
931   if (ysize > 0) {
932     y = ysize-1;
933     lasty = -1;
934     yinc = -1;
935   }
936   else {
937     /* when ysize is -ve it's a top-down image */
938     ysize = -ysize;
939     y = 0;
940     lasty = ysize;
941     yinc = 1;
942   }
943   if (!clr_used)
944     clr_used = 256;
945   if (clr_used > 256 || clr_used < 0) {
946     i_push_errorf(0, "out of range colors used (%d)", clr_used);
947     return NULL;
948   }
949
950   base_offset = FILEHEAD_SIZE + INFOHEAD_SIZE + clr_used * 4;
951   if (offbits < base_offset) {
952     i_push_errorf(0, "image data offset too small (%ld)", offbits);
953     return NULL;
954   }
955
956   im = i_img_pal_new(xsize, ysize, 3, 256);
957   if (!im)
958     return NULL;
959   if (!read_bmp_pal(ig, im, clr_used)) {
960     i_img_destroy(im);
961     return NULL;
962   }
963
964   if (offbits > base_offset) {
965     /* this will be slow if the offset is large, but that should be
966        rare */
967     char buffer;
968     while (base_offset < offbits) {
969       if (ig->readcb(ig, &buffer, 1) != 1) {
970         i_img_destroy(im);
971         i_push_error(0, "failed skipping to image data offset");
972         return NULL;
973       }
974       ++base_offset;
975     }
976   }
977   
978   line = mymalloc(line_size);
979   if (compression == BI_RGB) {
980     i_tags_add(&im->tags, "bmp_compression_name", 0, "BI_RGB", -1, 0);
981     while (y != lasty) {
982       if (ig->readcb(ig, line, line_size) != line_size) {
983         myfree(line);
984         i_push_error(0, "failed reading 8-bit bmp data");
985         i_img_destroy(im);
986         return NULL;
987       }
988       i_ppal(im, 0, xsize, y, line);
989       y += yinc;
990     }
991     myfree(line);
992   }
993   else if (compression == BI_RLE8) {
994     int read_size;
995     int want_high;
996     int count;
997     unsigned char packed[2];
998
999     i_tags_add(&im->tags, "bmp_compression_name", 0, "BI_RLE8", -1, 0);
1000     x = 0;
1001     while (1) {
1002       /* there's always at least 2 bytes in a sequence */
1003       if (ig->readcb(ig, packed, 2) != 2) {
1004         myfree(line);
1005         i_push_error(0, "missing data during decompression");
1006         i_img_destroy(im);
1007         return NULL;
1008       }
1009       if (packed[0]) {
1010         memset(line, packed[1], packed[0]);
1011         i_ppal(im, x, x+packed[0], y, line);
1012         x += packed[0];
1013       } else {
1014         switch (packed[1]) {
1015         case BMPRLE_ENDOFLINE:
1016           x = 0;
1017           y += yinc;
1018           break;
1019
1020         case BMPRLE_ENDOFBMP:
1021           myfree(line);
1022           return im;
1023
1024         case BMPRLE_DELTA:
1025           if (ig->readcb(ig, packed, 2) != 2) {
1026             myfree(line);
1027             i_push_error(0, "missing data during decompression");
1028             i_img_destroy(im);
1029             return NULL;
1030           }
1031           x += packed[0];
1032           y += yinc * packed[1];
1033           break;
1034
1035         default:
1036           count = packed[1];
1037           read_size = (count+1) / 2 * 2;
1038           if (ig->readcb(ig, line, read_size) != read_size) {
1039             myfree(line);
1040             i_push_error(0, "missing data during decompression");
1041             i_img_destroy(im);
1042             return NULL;
1043           }
1044           i_ppal(im, x, x+count, y, line);
1045           x += count;
1046           break;
1047         }
1048       }
1049     }
1050   }
1051   else { 
1052     myfree(line);
1053     i_push_errorf(0, "unknown 8-bit BMP compression (%d)", compression);
1054     i_img_destroy(im);
1055     return NULL;
1056   }
1057
1058   return im;
1059 }
1060
1061 struct bm_masks {
1062   unsigned masks[3];
1063   int shifts[3];
1064 };
1065 static struct bm_masks std_masks[] =
1066 {
1067   { /* 16-bit */
1068     { 0770000, 00007700, 00000077, },
1069     { 10, 4, -2, },
1070   },
1071   { /* 24-bit */
1072     { 0xFF0000, 0x00FF00, 0x0000FF, },
1073     {       16,        8,        0, },
1074   },
1075   { /* 32-bit */
1076     { 0xFF0000, 0x00FF00, 0x0000FF, },
1077     {       16,        8,        0, },
1078   },
1079 };
1080
1081 /*
1082 =item read_direct_bmp(ig, xsize, ysize, bit_count, clr_used, compression)
1083
1084 Skips the palette and reads in the image data for a direct colour image.
1085
1086 Returns the image or NULL.
1087
1088 =cut
1089 */
1090 static i_img *
1091 read_direct_bmp(io_glue *ig, int xsize, int ysize, int bit_count, 
1092                 int clr_used, int compression, long offbits) {
1093   i_img *im;
1094   int x, y, lasty, yinc;
1095   i_color *line, *p;
1096   unsigned char *in;
1097   int pix_size = bit_count / 8;
1098   int line_size = xsize * pix_size;
1099   struct bm_masks masks;
1100   char unpack_code[2] = "";
1101   int i;
1102   int extras;
1103   char junk[4];
1104   const char *compression_name;
1105   int bytes;
1106   long base_offset = FILEHEAD_SIZE + INFOHEAD_SIZE;
1107   
1108   unpack_code[0] = *("v3V"+pix_size-2);
1109   unpack_code[1] = '\0';
1110
1111   line_size = (line_size+3) / 4 * 4;
1112   extras = line_size - xsize * pix_size;
1113
1114   if (ysize > 0) {
1115     y = ysize-1;
1116     lasty = -1;
1117     yinc = -1;
1118   }
1119   else {
1120     /* when ysize is -ve it's a top-down image */
1121     ysize = -ysize;
1122     y = 0;
1123     lasty = ysize;
1124     yinc = 1;
1125   }
1126   if (compression == BI_RGB) {
1127     compression_name = "BI_RGB";
1128     masks = std_masks[pix_size-2];
1129     
1130     /* there's a potential "palette" after the header */
1131     for (i = 0; i < clr_used; ++clr_used) {
1132       char buf[4];
1133       if (ig->readcb(ig, buf, 4) != 4) {
1134         i_push_error(0, "skipping colors");
1135         return 0;
1136       }
1137       base_offset += 4;
1138     }
1139   }
1140   else if (compression == BI_BITFIELDS) {
1141     int pos, bit;
1142     compression_name = "BI_BITFIELDS";
1143
1144     for (i = 0; i < 3; ++i) {
1145       if (!read_packed(ig, "V", masks.masks+i)) {
1146         i_push_error(0, "reading pixel masks");
1147         return 0;
1148       }
1149       /* work out a shift for the mask */
1150       pos = 0;
1151       bit = masks.masks[i] & -masks.masks[i];
1152       while (bit) {
1153         ++pos;
1154         bit >>= 1;
1155       }
1156       masks.shifts[i] = pos - 8;
1157     }
1158     base_offset += 4 * 4;
1159   }
1160   else {
1161     i_push_errorf(0, "unknown 24-bit BMP compression (%d)", compression);
1162     return NULL;
1163   }
1164
1165   if (offbits > base_offset) {
1166     /* this will be slow if the offset is large, but that should be
1167        rare */
1168     char buffer;
1169     while (base_offset < offbits) {
1170       if (ig->readcb(ig, &buffer, 1) != 1) {
1171         i_img_destroy(im);
1172         i_push_error(0, "failed skipping to image data offset");
1173         return NULL;
1174       }
1175       ++base_offset;
1176     }
1177   }
1178   
1179   im = i_img_empty(NULL, xsize, ysize);
1180   if (!im)
1181     return NULL;
1182
1183   i_tags_add(&im->tags, "bmp_compression_name", 0, compression_name, -1, 0);
1184
1185   /* I wasn't able to make this overflow in testing, but better to be
1186      safe */
1187   bytes = sizeof(i_color) * xsize;
1188   if (bytes / sizeof(i_color) != xsize) {
1189     i_img_destroy(im);
1190     i_push_error(0, "integer overflow calculating buffer size");
1191     return NULL;
1192   }
1193   line = mymalloc(bytes);
1194   while (y != lasty) {
1195     p = line;
1196     for (x = 0; x < xsize; ++x) {
1197       unsigned pixel;
1198       if (!read_packed(ig, unpack_code, &pixel)) {
1199         i_push_error(0, "failed reading image data");
1200         myfree(line);
1201         i_img_destroy(im);
1202         return NULL;
1203       }
1204       for (i = 0; i < 3; ++i) {
1205         if (masks.shifts[i] > 0)
1206           p->channel[i] = (pixel & masks.masks[i]) >> masks.shifts[i];
1207         else 
1208           p->channel[i] = (pixel & masks.masks[i]) << -masks.shifts[i];
1209       }
1210       ++p;
1211     }
1212     i_plin(im, 0, xsize, y, line);
1213     if (extras)
1214       ig->readcb(ig, junk, extras);
1215     y += yinc;
1216   }
1217   myfree(line);
1218
1219   return im;
1220 }
1221
1222 /*
1223 =head1 SEE ALSO
1224
1225 Imager(3)
1226
1227 =head1 AUTHOR
1228
1229 Tony Cook <tony@develop-help.com>
1230
1231 =head1 RESTRICTIONS
1232
1233 Cannot save as compressed BMP.
1234
1235 =head1 BUGS
1236
1237 Doesn't handle OS/2 bitmaps.
1238
1239 16-bit/pixel images haven't been tested.  (I need an image).
1240
1241 BI_BITFIELDS compression hasn't been tested (I need an image).
1242
1243 The header handling for paletted images needs to be refactored
1244
1245 =cut
1246 */