File: bmp.c

package info (click to toggle)
allegro5 2%3A5.0.10-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 14,856 kB
  • ctags: 15,948
  • sloc: ansic: 87,540; cpp: 9,693; objc: 3,491; python: 2,057; sh: 829; makefile: 93; perl: 37; pascal: 24
file content (1157 lines) | stat: -rw-r--r-- 30,120 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
/*         ______   ___    ___
 *        /\  _  \ /\_ \  /\_ \
 *        \ \ \L\ \\//\ \ \//\ \      __     __   _ __   ___
 *         \ \  __ \ \ \ \  \ \ \   /'__`\ /'_ `\/\`'__\/ __`\
 *          \ \ \/\ \ \_\ \_ \_\ \_/\  __//\ \L\ \ \ \//\ \L\ \
 *           \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
 *            \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
 *                                           /\____/
 *                                           \_/__/
 *
 *      BMP reader.
 *
 *      By Seymour Shlien.
 *
 *      OS/2 BMP support and BMP save function by Jonas Petersen.
 *
 *      See readme.txt for copyright information.
 */


#include <string.h>

#include "allegro5/allegro.h"
#include "allegro5/allegro_image.h"
#include "allegro5/internal/aintern_convert.h"
#include "allegro5/internal/aintern_image.h"

#include "iio.h"

ALLEGRO_DEBUG_CHANNEL("image")

#define BIT_RGB          0
#define BIT_RLE8         1
#define BIT_RLE4         2
#define BIT_BITFIELDS    3

#define OS2INFOHEADERSIZE     12
#define WININFOHEADERSIZE     40
#define WININFOHEADERSIZEV2   52
#define WININFOHEADERSIZEV3   56
#define WININFOHEADERSIZEV4   108
#define WININFOHEADERSIZEV5   124


typedef struct BMPFILEHEADER
{
   unsigned long bfType;
   unsigned long bfSize;
   unsigned short bfReserved1;
   unsigned short bfReserved2;
   unsigned long bfOffBits;
} BMPFILEHEADER;


/* Used for both OS/2 and Windows BMP. 
 * Contains only the parameters needed to load the image 
 */
typedef struct BMPINFOHEADER
{
   unsigned long biWidth;
   signed long biHeight;
   unsigned short biBitCount;
   unsigned long biCompression;
   unsigned long biClrUsed;
   bool biHaveAlphaMask;
   uint32_t biAlphaMask;
} BMPINFOHEADER;


typedef struct WINBMPINFOHEADER
{                               /* size: 40 */
   unsigned long biWidth;
   signed long biHeight;
   unsigned short biPlanes;
   unsigned short biBitCount;
   unsigned long biCompression;
   unsigned long biSizeImage;
   unsigned long biXPelsPerMeter;
   unsigned long biYPelsPerMeter;
   unsigned long biClrUsed;
   unsigned long biClrImportant;
} WINBMPINFOHEADER;


typedef struct OS2BMPINFOHEADER
{                               /* size: 12 */
   unsigned short biWidth;
   unsigned short biHeight;
   unsigned short biPlanes;
   unsigned short biBitCount;
} OS2BMPINFOHEADER;



/* read_bmfileheader:
 *  Reads a BMP file header and check that it has the BMP magic number.
 */
static int read_bmfileheader(ALLEGRO_FILE *f, BMPFILEHEADER *fileheader)
{
   fileheader->bfType = al_fread16le(f);
   fileheader->bfSize = al_fread32le(f);
   fileheader->bfReserved1 = al_fread16le(f);
   fileheader->bfReserved2 = al_fread16le(f);
   fileheader->bfOffBits = al_fread32le(f);

   if (fileheader->bfType != 19778) {
      ALLEGRO_ERROR("Not BMP format\n");
      return -1;
   }

   if (al_feof(f) || al_ferror(f)) {
      ALLEGRO_ERROR("Failed to read file header\n");
      return -1;
   }

   return 0;
}



/* read_win_bminfoheader:
 *  Reads information from a BMP file header.
 */
static int read_win_bminfoheader(ALLEGRO_FILE *f, BMPINFOHEADER *infoheader)
{
   WINBMPINFOHEADER win_infoheader;

   win_infoheader.biWidth = al_fread32le(f);
   win_infoheader.biHeight = al_fread32le(f);
   win_infoheader.biPlanes = al_fread16le(f);
   win_infoheader.biBitCount = al_fread16le(f);
   win_infoheader.biCompression = al_fread32le(f);
   win_infoheader.biSizeImage = al_fread32le(f);
   win_infoheader.biXPelsPerMeter = al_fread32le(f);
   win_infoheader.biYPelsPerMeter = al_fread32le(f);
   win_infoheader.biClrUsed = al_fread32le(f);
   win_infoheader.biClrImportant = al_fread32le(f);

   infoheader->biWidth = win_infoheader.biWidth;
   infoheader->biHeight = win_infoheader.biHeight;
   infoheader->biBitCount = win_infoheader.biBitCount;
   infoheader->biCompression = win_infoheader.biCompression;
   infoheader->biClrUsed = win_infoheader.biClrUsed;

   if (al_feof(f) || al_ferror(f)) {
      ALLEGRO_ERROR("Failed to read file header\n");
      return -1;
   }

   return 0;
}



/* read_os2_bminfoheader:
 *  Reads information from an OS/2 format BMP file header.
 */
static int read_os2_bminfoheader(ALLEGRO_FILE *f, BMPINFOHEADER *infoheader)
{
   OS2BMPINFOHEADER os2_infoheader;

   os2_infoheader.biWidth = al_fread16le(f);
   os2_infoheader.biHeight = al_fread16le(f);
   os2_infoheader.biPlanes = al_fread16le(f);
   os2_infoheader.biBitCount = al_fread16le(f);

   infoheader->biWidth = os2_infoheader.biWidth;
   infoheader->biHeight = os2_infoheader.biHeight;
   infoheader->biBitCount = os2_infoheader.biBitCount;
   infoheader->biCompression = BIT_RGB;
   infoheader->biClrUsed = 0; /* default */

   if (al_feof(f) || al_ferror(f)) {
      ALLEGRO_ERROR("Failed to read file header\n");
      return -1;
   }

   return 0;
}



/* read_palette:
 *  Loads the color palette for 1,4,8 bit formats.
 *  OS/2 bitmaps take 3 bytes per color.
 *  Windows bitmaps take 4 bytes per color.
 */
static void read_palette(int ncolors, PalEntry *pal, ALLEGRO_FILE *f,
   int win_flag)
{
   int i;

   for (i = 0; i < ncolors; i++) {
      pal[i].b = al_fgetc(f);
      pal[i].g = al_fgetc(f);
      pal[i].r = al_fgetc(f);

      if (win_flag) {
         al_fgetc(f);
      }
   }
}



/* read_1bit_line:
 *  Support function for reading the 1 bit bitmap file format.
 */
static void read_1bit_line(int length, ALLEGRO_FILE *f, unsigned char *buf)
{
   unsigned char b[32];
   unsigned long n;
   int i, j, k;

   for (i = 0; i < length; i++) {
      j = i % 32;
      if (j == 0) {
         n = al_fread32be(f);
         for (k = 0; k < 32; k++) {
            b[31 - k] = (char)(n & 1);
            n = n >> 1;
         }
      }
      buf[i] = b[j];
   }
}



/* read_4bit_line:
 *  Support function for reading the 4 bit bitmap file format.
 */
static void read_4bit_line(int length, ALLEGRO_FILE *f, unsigned char *buf)
{
   unsigned char b[8];
   unsigned long n;
   int i, j, k;
   int temp;

   for (i = 0; i < length; i++) {
      j = i % 8;
      if (j == 0) {
         n = al_fread32le(f);
         for (k = 0; k < 4; k++) {
            temp = n & 255;
            b[k * 2 + 1] = temp & 15;
            temp = temp >> 4;
            b[k * 2] = temp & 15;
            n = n >> 8;
         }
      }
      buf[i] = b[j];
   }
}



/* read_8bit_line:
 *  Support function for reading the 8 bit bitmap file format.
 */
static void read_8bit_line(int length, ALLEGRO_FILE *f, unsigned char *buf)
{
   unsigned char b[4];
   unsigned long n;
   int i, j, k;

   for (i = 0; i < length; i++) {
      j = i % 4;
      if (j == 0) {
         n = al_fread32le(f);
         for (k = 0; k < 4; k++) {
            b[k] = (char)(n & 255);
            n = n >> 8;
         }
      }
      buf[i] = b[j];
   }
}



/* read_16bit_line:
 *  Support function for reading the 16 bit bitmap file format, doing
 *  our best to convert it down to a 256 color palette.
 */
static void read_16bit_line(int length, ALLEGRO_FILE *f, unsigned char *data)
{
   int i, w;
   unsigned char r, g, b;

   for (i = 0; i < length; i++) {
      w = al_fread16le(f);

      /* the format is like a 15-bpp bitmap, not 16bpp */
      r = _al_rgb_scale_5[(w >> 10) & 0x1f];
      g = _al_rgb_scale_5[(w >> 5) & 0x1f];
      b = _al_rgb_scale_5[w & 0x1f];

      data[0] = r;
      data[1] = g;
      data[2] = b;
      data[3] = 255;
      data += 4;
   }

   /* padding */
   i = (i * 2) % 4;
   if (i != 0) {
      while (i++ < 4)
         al_fgetc(f);
   }
}



/* read_24bit_line:
 *  Support function for reading the 24 bit bitmap file format.
 */
static void read_24bit_line(int length, ALLEGRO_FILE *f, unsigned char *data)
{
   int i;
   unsigned char c[3];
   unsigned char r, g, b;

   for (i = 0; i < length; i++) {
      al_fread(f, c, 3);
      r = c[2];
      g = c[1];
      b = c[0];

      data[0] = r;
      data[1] = g;
      data[2] = b;
      data[3] = 255;
      data += 4;
   }

   /* padding */
   i = (i * 3) % 4;
   if (i != 0) {
      while (i++ < 4)
         al_fgetc(f);
   }
}



/* read_32bit_line:
 *  Support function for reading the 32 bit bitmap file format,
 *  treating fourth byte as alpha.
 */
static void read_32bit_line(int length, ALLEGRO_FILE *f, unsigned char *data)
{
   int i;
   unsigned char c[4];
   unsigned char r, g, b, a;
   bool premul = !(al_get_new_bitmap_flags() & ALLEGRO_NO_PREMULTIPLIED_ALPHA);

   for (i = 0; i < length; i++) {
      al_fread(f, c, 4);
      r = c[2];
      g = c[1];
      b = c[0];
      a = c[3];
      
      if (premul) {
         r = r * a / 255;
         g = g * a / 255;
         b = b * a / 255;
      }

      data[0] = r;
      data[1] = g;
      data[2] = b;
      data[3] = a;
      data += 4;
   }
}



/* read_bitfields_image:
 *  For reading the bitfield compressed BMP image format.
 */
static void read_bitfields_image(ALLEGRO_FILE *f,
   const BMPINFOHEADER *infoheader, int bpp, ALLEGRO_LOCKED_REGION *lr)
{
   int k, i, line, height, dir;
   int bytes_per_pixel;
   unsigned long buffer;
   int pix;

   height = infoheader->biHeight;
   line = height < 0 ? 0 : height - 1;
   dir = height < 0 ? 1 : -1;
   height = abs(height);

   bytes_per_pixel = (bpp + 1) / 8;

   for (i = 0; i < height; i++, line += dir) {
      unsigned char *data = (unsigned char *)lr->data + lr->pitch * line;

      for (k = 0; k < (int)infoheader->biWidth; k++) {

         al_fread(f, &buffer, bytes_per_pixel);

         if (bpp == 15) {
            if (infoheader->biAlphaMask == 0x8000) {
               pix = ALLEGRO_CONVERT_ARGB_1555_TO_ARGB_8888(buffer);
            }
            else {
               pix = ALLEGRO_CONVERT_RGB_555_TO_ARGB_8888(buffer);
            }
         }
         else if (bpp == 16) {
            pix = ALLEGRO_CONVERT_RGB_565_TO_ARGB_8888(buffer);
         }
         else {
            if (infoheader->biAlphaMask == 0xFF000000) {
               pix = buffer;
            }
            else {
               pix = ALLEGRO_CONVERT_XRGB_8888_TO_ARGB_8888(buffer);
            }
         }

         data[2] = pix & 255;
         data[1] = (pix >> 8) & 255;
         data[0] = (pix >> 16) & 255;
         data[3] = (pix >> 24) & 255;
         data += 4;
      }

      /* padding */
      k = (k * bytes_per_pixel) % 4;
      if (k > 0) {
         while (k++ < 4)
            al_fgetc(f);
      }
   }
}



/* read_RGB_image:
 *  For reading the non-compressed BMP image format (all except 32-bit with
 *  alpha hack).
 */
static void read_RGB_image(ALLEGRO_FILE *f,
   const BMPINFOHEADER *infoheader, PalEntry *pal, ALLEGRO_LOCKED_REGION *lr)
{
   int i, j, line, height, dir;
   unsigned char *buf;
   unsigned char *data;

   height = infoheader->biHeight;
   line = height < 0 ? 0 : height - 1;
   dir = height < 0 ? 1 : -1;
   height = abs(height);

   buf = al_malloc(infoheader->biWidth);

   for (i = 0; i < height; i++, line += dir) {
      data = (unsigned char *)lr->data + lr->pitch * line;

      switch (infoheader->biBitCount) {

         case 1:
            read_1bit_line(infoheader->biWidth, f, buf);
            break;

         case 4:
            read_4bit_line(infoheader->biWidth, f, buf);
            break;

         case 8:
            read_8bit_line(infoheader->biWidth, f, buf);
            break;

         case 16:
            read_16bit_line(infoheader->biWidth, f, data);
            break;

         case 24:
            read_24bit_line(infoheader->biWidth, f, data);
            break;

         case 32:
            read_32bit_line(infoheader->biWidth, f, data);
            break;
      }
      if (infoheader->biBitCount <= 8) {
         for (j = 0; j < (int)infoheader->biWidth; j++) {
            data[0] = pal[buf[j]].r;
            data[1] = pal[buf[j]].g;
            data[2] = pal[buf[j]].b;
            data[3] = 255;
            data += 4;
         }
      }
   }

   al_free(buf);
}



/* read_RGB_image_32bit_alpha_hack:
 *  For reading the non-compressed BMP image format (32-bit).
 *  These are treatly specially because some programs put alpha information in
 *  the fourth byte of each pixel, which is normally just padding (and zero).
 *  We use a heuristic: if every pixel has zero in that fourth byte then assume
 *  the whole image is opaque (a=255).  Otherwise treat the fourth byte as an
 *  alpha channel.
 *
 *  Note that V3 headers include an alpha bit mask, which can properly indicate
 *  the presence or absence of an alpha channel.
 *  This hack is not required then.
 */
static void read_RGB_image_32bit_alpha_hack(ALLEGRO_FILE *f,
   const BMPINFOHEADER *infoheader, ALLEGRO_LOCKED_REGION *lr)
{
   int i, j, line, height, dir;
   unsigned char *data;
   unsigned char r, g, b, a;
   unsigned char have_alpha = 0;
   const bool premul = !(al_get_new_bitmap_flags() & ALLEGRO_NO_PREMULTIPLIED_ALPHA);

   height = infoheader->biHeight;
   line = height < 0 ? 0 : height - 1;
   dir = height < 0 ? 1 : -1;
   height = abs(height);

   /* Read data. */
   for (i = 0; i < height; i++, line += dir) {
      data = (unsigned char *)lr->data + lr->pitch * line;

      for (j = 0; j < (int)infoheader->biWidth; j++) {
         b = al_fgetc(f);
         g = al_fgetc(f);
         r = al_fgetc(f);
         a = al_fgetc(f);
         have_alpha |= a;

         data[0] = r;
         data[1] = g;
         data[2] = b;
         data[3] = a;
         data += 4;
      }
   }

   /* Fixup pass. */
   if (!have_alpha) {
      for (i = 0; i < height; i++) {
         data = (unsigned char *)lr->data + lr->pitch * i;
         for (j = 0; j < (int)infoheader->biWidth; j++) {
            data[3] = 255; /* a */
            data += 4;
         }
      }
   }
   else if (premul) {
      for (i = 0; i < height; i++) {
         data = (unsigned char *)lr->data + lr->pitch * i;
         for (j = 0; j < (int)infoheader->biWidth; j++) {
            r = data[0];
            g = data[1];
            b = data[2];
            a = data[3];

            r = r * a / 255;
            g = g * a / 255;
            b = b * a / 255;

            data[0] = r;
            data[1] = g;
            data[2] = b;
            data[3] = a;
            data += 4;
         }
      }
   }
}



/* read_RLE8_compressed_image:
 *  For reading the 8 bit RLE compressed BMP image format.
 */
static void read_RLE8_compressed_image(ALLEGRO_FILE *f, unsigned char *buf,
                                       const BMPINFOHEADER *infoheader)
{
   int count;
   unsigned char val;
   unsigned char val0;
   int j, pos, line, height, dir;
   int eolflag, eopicflag;

   eopicflag = 0;
   height = abs(infoheader->biHeight);
   line = (infoheader->biHeight < 0) ? 0 : height - 1;
   dir = (infoheader->biHeight < 0) ? 1 : -1;

   while (eopicflag == 0) {
      pos = 0;                  /* x position in bitmap */
      eolflag = 0;              /* end of line flag */

      while ((eolflag == 0) && (eopicflag == 0)) {
         count = al_fgetc(f);
         if (count == EOF)
            return;
         if (pos + count > (int)infoheader->biWidth) {
            ALLEGRO_WARN("overlong compressed line\n");
            count = infoheader->biWidth - pos;
         }

         val = al_fgetc(f);

         if (count > 0) {       /* repeat pixel count times */
            for (j = 0; j < count; j++) {
               buf[line * infoheader->biWidth + pos] = val;
               pos++;
            }
         }
         else {
            switch (val) {

               case 0:         /* end of line flag */
                  eolflag = 1;
                  break;

               case 1:         /* end of picture flag */
                  eopicflag = 1;
                  break;

               case 2:         /* displace picture */
                  count = al_fgetc(f);
                  if (count == EOF)
                     return;
                  val = al_fgetc(f);
                  pos += count;
                  line += dir * val;
                  break;

               default:                      /* read in absolute mode */
                  for (j=0; j<val; j++) {
                     val0 = al_fgetc(f);
                     buf[line * infoheader->biWidth + pos] = val0;
                     pos++;
                  }

                  if (j % 2 == 1)
                     val0 = al_fgetc(f);    /* align on word boundary */

                  break;
            }
         }

         if (pos - 1 > (int)infoheader->biWidth)
            eolflag = 1;
      }

      line += dir;
      if (line < 0 || line >= height)
         eopicflag = 1;
   }
}



/* read_RLE4_compressed_image:
 *  For reading the 4 bit RLE compressed BMP image format.
 */
static void read_RLE4_compressed_image(ALLEGRO_FILE *f, unsigned char *buf,
                                       const BMPINFOHEADER *infoheader)
{
   unsigned char b[8];
   int count;
   unsigned short val0, val;
   int j, k, pos, line, height, dir;
   int eolflag, eopicflag;

   eopicflag = 0;               /* end of picture flag */
   height = abs(infoheader->biHeight);
   line = (infoheader->biHeight < 0) ? 0 : height - 1;
   dir = (infoheader->biHeight < 0) ? 1 : -1;

   while (eopicflag == 0) {
      pos = 0;
      eolflag = 0;              /* end of line flag */

      while ((eolflag == 0) && (eopicflag == 0)) {
         count = al_fgetc(f);
         if (count == EOF)
            return;
         if (pos + count > (int)infoheader->biWidth) {
            ALLEGRO_WARN("overlong compressed line\n");
            count = infoheader->biWidth - pos;
         }

         val = al_fgetc(f);

         if (count > 0) {       /* repeat pixels count times */
            b[1] = val & 15;
            b[0] = (val >> 4) & 15;
            for (j = 0; j < count; j++) {
               buf[line * infoheader->biWidth + pos] = b[j % 2];
               pos++;
            }
         }
         else {
            switch (val) {

               case 0:         /* end of line */
                  eolflag = 1;
                  break;

               case 1:         /* end of picture */
                  eopicflag = 1;
                  break;

               case 2:         /* displace image */
                  count = al_fgetc(f);
                  if (count == EOF)
                     return;
                  val = al_fgetc(f);
                  pos += count;
                  line += dir * val;
                  break;

               default:        /* read in absolute mode */
                  for (j = 0; j < val; j++) {
                     if ((j % 4) == 0) {
                        val0 = al_fread16le(f);
                        for (k = 0; k < 2; k++) {
                           b[2 * k + 1] = val0 & 15;
                           val0 = val0 >> 4;
                           b[2 * k] = val0 & 15;
                           val0 = val0 >> 4;
                        }
                     }
                     buf[line * infoheader->biWidth + pos] = b[j % 4];
                     pos++;
                  }
                  break;
            }
         }

         if (pos - 1 > (int)infoheader->biWidth)
            eolflag = 1;
      }

      line += dir;
      if (line < 0 || line >= height)
         eopicflag = 1;
   }
}



/* alpha_mask_supported:
 *  Return true if we support the combination of compressed, bit depth
 *  and alpha mask.
 */
static bool alpha_mask_supported(int biCompression, int biBitCount,
   uint32_t biAlphaMask)
{
   if (biAlphaMask == 0) {
      return true;
   }

   if (biCompression == BIT_RGB) {
      return (biBitCount == 24 && biAlphaMask == 0xff000000)
         || (biBitCount == 32 && biAlphaMask == 0xff000000);
   }

   if (biCompression == BIT_BITFIELDS) {
      return (biBitCount == 16 && biAlphaMask == 0x8000)
         || (biBitCount == 24 && biAlphaMask == 0xff000000)
         || (biBitCount == 32 && biAlphaMask == 0xff000000);
   }

   return false;
}



/*  Like load_bmp, but starts loading from the current place in the ALLEGRO_FILE
 *  specified. If successful the offset into the file will be left just after
 *  the image data. If unsuccessful the offset into the file is unspecified,
 *  i.e. you must either reset the offset to some known place or close the
 *  packfile. The packfile is not closed by this function.
 */
ALLEGRO_BITMAP *_al_load_bmp_f(ALLEGRO_FILE *f)
{
   BMPFILEHEADER fileheader;
   BMPINFOHEADER infoheader;
   ALLEGRO_BITMAP *bmp;
   PalEntry pal[256];
   int64_t file_start;
   int64_t header_start;
   unsigned long biSize;
   unsigned char *buf = NULL;
   ALLEGRO_LOCKED_REGION *lr;
   int bpp;
   ASSERT(f);

   file_start = al_ftell(f);

   if (read_bmfileheader(f, &fileheader) != 0) {
      return NULL;
   }

   header_start = al_ftell(f);

   biSize = al_fread32le(f);
   if (al_feof(f) || al_ferror(f)) {
      ALLEGRO_ERROR("EOF or file error\n");
      return NULL;
   }

   switch (biSize) {
      case WININFOHEADERSIZE:
      case WININFOHEADERSIZEV2:
      case WININFOHEADERSIZEV3:
      case WININFOHEADERSIZEV4:
      case WININFOHEADERSIZEV5:
         if (read_win_bminfoheader(f, &infoheader) != 0) {
            return NULL;
         }
         break;

      case OS2INFOHEADERSIZE:
         if (read_os2_bminfoheader(f, &infoheader) != 0) {
            return NULL;
         }
         ASSERT(infoheader.biCompression == BIT_RGB);
         break;

      default:
         ALLEGRO_WARN("Unsupported header size: %ld\n", biSize);
         return NULL;
   }

   /* End of header for OS/2 and BITMAPV2INFOHEADER (V1). */
   if (biSize == OS2INFOHEADERSIZE || biSize == WININFOHEADERSIZE) {
      ASSERT(al_ftell(f) == header_start + (int64_t) biSize);
   }

   if ((int)infoheader.biWidth < 0) {
      ALLEGRO_WARN("negative width: %ld\n", infoheader.biWidth);
      return NULL;
   }

   if (infoheader.biBitCount == 24)
      bpp = 24;
   else if (infoheader.biBitCount == 16)
      bpp = 16;
   else if (infoheader.biBitCount == 32)
      bpp = 32;
   else
      bpp = 8;

   /* In BITMAPINFOHEADER (V1) the RGB bit masks are not part of the header.
    * In BITMAPV2INFOHEADER they form part of the header, but only valid when
    * for BITFIELDS images.
    */
   if (infoheader.biCompression == BIT_BITFIELDS
      || biSize >= WININFOHEADERSIZEV2)
   {
      uint32_t redMask = al_fread32le(f);
      uint32_t grnMask = al_fread32le(f);
      uint32_t bluMask = al_fread32le(f);

      (void)grnMask;

      if (infoheader.biCompression == BIT_BITFIELDS) {
         if ((bluMask == 0x001f) && (redMask == 0x7C00))
            bpp = 15;
         else if ((bluMask == 0x001f) && (redMask == 0xF800))
            bpp = 16;
         else if ((bluMask == 0x0000FF) && (redMask == 0xFF0000))
            bpp = 32;
         else {
            /* Unrecognised bit masks/depth, refuse to load. */
            ALLEGRO_WARN("Unrecognised RGB masks: %x, %x, %x\n",
               redMask, grnMask, bluMask);
            return NULL;
         }
      }
   }

   /* BITMAPV3INFOHEADER and above include an Alpha bit mask. */
   if (biSize < WININFOHEADERSIZEV3) {
      infoheader.biHaveAlphaMask = false;
      infoheader.biAlphaMask = 0x0;
   }
   else {
      infoheader.biHaveAlphaMask = true;
      infoheader.biAlphaMask = al_fread32le(f);

      if (!alpha_mask_supported(infoheader.biCompression,
            infoheader.biBitCount, infoheader.biAlphaMask))
      {
         ALLEGRO_WARN(
            "Unsupported: compression=%ld, bit count=%d, alpha mask=%x\n",
            infoheader.biCompression, infoheader.biBitCount,
            infoheader.biAlphaMask);
         return NULL;
      }
   }

   /* End of header for BITMAPV2INFOHEADER and above. */

   /* Read the palette, if any.  Higher bit depth images _may_ have an optional
    * palette but we don't use it and don't read it.
    */
   if (infoheader.biCompression != BIT_BITFIELDS
      && infoheader.biBitCount <= 8)
   {
      int win_flag = (biSize != OS2INFOHEADERSIZE);
      int ncolors = infoheader.biClrUsed;
      if (ncolors == 0) {
         ncolors = (1 << infoheader.biBitCount);
      }
      if (ncolors > 256) {
         ALLEGRO_ERROR("Too many colors: %d\n", ncolors);
         return NULL;
      }

      read_palette(ncolors, pal, f, win_flag);
      if (al_feof(f) || al_ferror(f)) {
         ALLEGRO_ERROR("EOF or I/O error\n");
         return NULL;
      }
   }

   /* Skip to the pixel storage. */
   if (!al_fseek(f, file_start + fileheader.bfOffBits, ALLEGRO_SEEK_SET)) {
      ALLEGRO_ERROR("Seek error\n");
      return NULL;
   }

   bmp = al_create_bitmap(infoheader.biWidth, abs(infoheader.biHeight));
   if (!bmp) {
      ALLEGRO_ERROR("Failed to create bitmap\n");
      return NULL;
   }

   lr = al_lock_bitmap(bmp, ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE,
      ALLEGRO_LOCK_WRITEONLY);
   if (!lr) {
      ALLEGRO_ERROR("Failed to lock region\n");
      al_destroy_bitmap(bmp);
      return NULL;
   }

   if (infoheader.biCompression == BIT_RLE8
       || infoheader.biCompression == BIT_RLE4)
   {
      /* Questionable but most loaders handle this, so we should. */
      if (infoheader.biHeight < 0) {
         ALLEGRO_WARN("compressed bitmap with negative height\n");
      }

      /* RLE decoding may skip pixels so clear the buffer first. */
      buf = al_calloc(infoheader.biWidth, abs(infoheader.biHeight));
   }

   switch (infoheader.biCompression) {

      case BIT_RGB:
         if (infoheader.biBitCount == 32 && !infoheader.biHaveAlphaMask) {
            read_RGB_image_32bit_alpha_hack(f, &infoheader, lr);
         }
         else {
            read_RGB_image(f, &infoheader, pal, lr);
         }
         break;

      case BIT_RLE8:
         read_RLE8_compressed_image(f, buf, &infoheader);
         break;

      case BIT_RLE4:
         read_RLE4_compressed_image(f, buf, &infoheader);
         break;

      case BIT_BITFIELDS:
         read_bitfields_image(f, &infoheader, bpp, lr);
         break;

      default:
         ALLEGRO_WARN("Unknown compression: %ld\n", infoheader.biCompression);
         al_unlock_bitmap(bmp);
         al_destroy_bitmap(bmp);
         bmp = NULL;
         break;
   }

   if (infoheader.biCompression == BIT_RLE8
       || infoheader.biCompression == BIT_RLE4) {
      int x, y;
      unsigned char *data;

      for (y = 0; y < abs(infoheader.biHeight); y++) {
         data = (unsigned char *)lr->data + lr->pitch * y;
         for (x = 0; x < (int)infoheader.biWidth; x++) {
            data[0] = pal[buf[y * infoheader.biWidth + x]].r;
            data[1] = pal[buf[y * infoheader.biWidth + x]].g;
            data[2] = pal[buf[y * infoheader.biWidth + x]].b;
            data[3] = 255;
            data += 4;
         }
      }
      al_free(buf);
   }

   if (bmp) {
      al_unlock_bitmap(bmp);
   }

   return bmp;
}



/*  Like save_bmp but writes into the ALLEGRO_FILE given instead of a new file.
 *  The packfile is not closed after writing is completed. On success the
 *  offset into the file is left after the TGA file just written. On failure
 *  the offset is left at the end of whatever incomplete data was written.
 */
bool _al_save_bmp_f(ALLEGRO_FILE *f, ALLEGRO_BITMAP *bmp)
{
   int bfSize;
   int biSizeImage;
   int bpp;
   int filler;
   int i, j;
   int w, h;
   ALLEGRO_LOCKED_REGION *lr;
   ASSERT(f);
   ASSERT(bmp);

   w = al_get_bitmap_width(bmp);
   h = al_get_bitmap_height(bmp);

   bpp = 24;
   filler = 3 - ((w * (bpp / 8) - 1) & 3);

   if (bpp == 8) {
      biSizeImage = (w + filler) * h;
      bfSize = (54              /* header */
                + 256 * 4       /* palette */
                + biSizeImage); /* image data */
   }
   else {
      biSizeImage = (w * 3 + filler) * h;
      bfSize = 54 + biSizeImage;        /* header + image data */
   }

   al_set_errno(0);

   /* file_header */
   al_fwrite16le(f, 0x4D42);              /* bfType ("BM") */
   al_fwrite32le(f, bfSize);              /* bfSize */
   al_fwrite16le(f, 0);                   /* bfReserved1 */
   al_fwrite16le(f, 0);                   /* bfReserved2 */

   if (bpp == 8)                /* bfOffBits */
      al_fwrite32le(f, 54 + 256 * 4);
   else
      al_fwrite32le(f, 54);

   /* info_header */
   al_fwrite32le(f, 40);                  /* biSize */
   al_fwrite32le(f, w);                   /* biWidth */
   al_fwrite32le(f, h);                   /* biHeight */
   al_fwrite16le(f, 1);                   /* biPlanes */
   al_fwrite16le(f, bpp);                 /* biBitCount */
   al_fwrite32le(f, 0);                   /* biCompression */
   al_fwrite32le(f, biSizeImage);         /* biSizeImage */
   al_fwrite32le(f, 0xB12);               /* biXPelsPerMeter (0xB12 = 72 dpi) */
   al_fwrite32le(f, 0xB12);               /* biYPelsPerMeter */

   al_fwrite32le(f, 0);                   /* biClrUsed */
   al_fwrite32le(f, 0);                   /* biClrImportant */

   /* Don't really need the alpha channel, just the _LE.
    * Note that there exist 32-bit BMPs now so we could try to save those.
    */
   lr = al_lock_bitmap(bmp, ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE,
      ALLEGRO_LOCK_READONLY);

   /* image data */
   for (i = h - 1; i >= 0; i--) {
      unsigned char *data = (unsigned char *)lr->data + i * lr->pitch;

      for (j = 0; j < w; j++) {
         unsigned char r = data[0];
         unsigned char g = data[1];
         unsigned char b = data[2];
         data += 4;

         al_fputc(f, b);
         al_fputc(f, g);
         al_fputc(f, r);
      }

      for (j = 0; j < filler; j++)
         al_fputc(f, 0);
   }

   al_unlock_bitmap(bmp);

   return al_get_errno() ? false : true;
}



ALLEGRO_BITMAP *_al_load_bmp(const char *filename)
{
   ALLEGRO_FILE *f;
   ALLEGRO_BITMAP *bmp;
   ASSERT(filename);

   f = al_fopen(filename, "rb");
   if (!f)
      return NULL;

   bmp = _al_load_bmp_f(f);

   al_fclose(f);

   return bmp;
}


bool _al_save_bmp(const char *filename, ALLEGRO_BITMAP *bmp)
{
   ALLEGRO_FILE *f;
   bool ret;
   ASSERT(filename);

   f = al_fopen(filename, "wb");
   if (!f)
      return false;

   ret = _al_save_bmp_f(f, bmp);

   al_fclose(f);

   return ret;
}

/* vim: set sts=3 sw=3 et: */