-
Notifications
You must be signed in to change notification settings - Fork 11
/
bmp.c
6978 lines (6103 loc) · 190 KB
/
bmp.c
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
/*
* Bitmap manipulation functions. See `bmp.h` for details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdarg.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <ctype.h>
#include <float.h>
#include <assert.h>
#ifdef USESDL
# ifdef ANDROID
# include <SDL.h>
# else
# include <SDL2/SDL.h>
# endif
#endif
/*
Use the -DUSEPNG compiler option to enable PNG support via libpng.
If you use it, you need to link against the libpng (-lpng)
and zlib (-lz) libraries.
Use the -DUSEJPG compiler option to enable JPG support via libjpg.
I've decided to keep both optional, for situations where
you may not want to import a bunch of third party libraries.
*/
#ifdef USEPNG
# include <png.h>
#endif
#ifdef USEJPG
# include <jpeglib.h>
# include <setjmp.h>
#endif
#ifndef BMP_H
# include "bmp.h"
#endif
/* Ignore the alpha byte when comparing colors?
FIXME: Not all functions that should respect IGNORE_ALPHA does so.
*/
#ifndef IGNORE_ALPHA
# define IGNORE_ALPHA 1
#endif
/* Experimental ABGR color mode.
* Normally colors are stored as 0xARGB, but Emscripten uses an
* 0xABGR format on the canvas, so use -DABGR=1 in your compiler
* flags if you need to use this mode. */
#ifndef ABGR
# define ABGR 0
#endif
/* Use RLE when saving TGA files? */
#define TGA_SAVE_RLE 1
/* Save NetPBM in binary format (P4,P5,P6)? */
#ifndef PPM_BINARY
# define PPM_BINARY 0
#endif
/* Save transparent backgrounds when saving GIF?
It used to be on by default, but it turned out to be less useful
than I expected, and caused some confusion.
Still, it is here if you need it
*/
#ifndef SAVE_GIF_TRANSPARENT
# define SAVE_GIF_TRANSPARENT 0
#endif
#ifndef SIZE_LIMITS
# define SIZE_LIMITS 1
#endif
#if BM_LAST_ERROR
static const char *bm_last_error = "no error";
# define SET_ERROR(e) bm_last_error = e
#else
# define SET_ERROR(e) (void)e
#endif
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#define SWAPINT(a, b) do {int t = a; a = b; b = t;} while(0)
/* https://eli.thegreenplace.net/2009/11/16/void-and-casts-in-c-and-c */
#if defined(__cplusplus)
# define CAST(T) static_cast<T>
#else
# define CAST(T)
#endif
#if !defined(WIN32) && 0
/* TODO: Use `alloca()` if it is available */
#define ALLOCA(x) alloca(x)
#define FREEA(x)
#else
#define ALLOCA(x) malloc(x)
#define FREEA(x) free(x)
#endif
/* TODO: C11 defines fopen_s(), strncpy_s(), etc.
At the moment, I only use them if WIN32 is defined.
See __STDC_LIB_EXT1__
*/
#if defined(WIN32) && defined(_MSC_VER)
# define SAFE_C11
# define strdup _strdup
#endif
/* Definitions for Bitmap::flags */
/* FLAG_OWNS_DATA - set if the Bitmap owns the memory allocated to Bitmap::data.
If it is set, then bm_free() will free it.
*/
#define FLAG_OWNS_DATA 1
/* TODO: I want to add flags to check if the bitmap had a palette and an alpha channel
and so on in the file it was loaded from, etc.
*/
/*
* Structure containing a bitmap image.
*
* The internal format is `0xAARRGGBB` little endian.
* Meaning that `p[0]` contains B, `p[1]` contains G,
* `p[2]` contains R and `p[3]` contains A
* and the data buffer is an array of bytes BGRABGRABGRABGRABGRA...
*
* The member `color` contains the color that will be used for drawing
* primitives, and for transparency while blitting.
*
* The member `font` is a pointer to a `BmFont` structure that is used
* to render text. See the [Font Routines][] section for more details.
* Don't modify this directly, since fonts are reference counted;
* use `bm_set_font()` instead.
*
* The member `clip` is a `BmRect` that defines the clipping rectangle
* when drawing primitives and text.
*/
struct bitmap {
/* Dimesions of the bitmap */
int w, h;
/* The actual pixel data in RGBA format */
unsigned char *data;
/* Color for the pen of the canvas */
unsigned int color;
/* Font object for rendering text */
struct bitmap_font *font;
/* Reference count of the bitmap object */
unsigned int ref_count;
/* Some flags for the bitmap */
unsigned int flags;
/* Clipping rectangle */
BmRect clip;
};
#pragma pack(push, 1) /* Don't use any padding (Windows compilers) */
/* Data structures for the header of BMP files. */
struct bmpfile_magic {
unsigned char magic[2];
};
struct bmpfile_header {
uint32_t filesz;
uint16_t creator1;
uint16_t creator2;
uint32_t bmp_offset;
};
struct bmpfile_dibinfo {
uint32_t header_sz;
int32_t width;
int32_t height;
uint16_t nplanes;
uint16_t bitspp;
uint32_t compress_type;
uint32_t bmp_bytesz;
int32_t hres;
int32_t vres;
uint32_t ncolors;
uint32_t nimpcolors;
};
struct bmpfile_colinfo {
uint8_t b, g, r, a;
};
/* RGB triplet used for palettes in PCX and GIF support */
struct rgb_triplet {
unsigned char r, g, b;
};
#pragma pack(pop)
#define BM_BPP 4 /* Bytes per Pixel */
#define BM_BLOB_SIZE(B) (B->w * B->h * BM_BPP)
#define BM_ROW_SIZE(B) (B->w * BM_BPP)
#define BM_GET(b, x, y) (*((unsigned int*)(b->data + (y) * BM_ROW_SIZE(b) + (x) * BM_BPP)))
#define BM_SET(b, x, y, c) *((unsigned int*)(b->data + (y) * BM_ROW_SIZE(b) + (x) * BM_BPP)) = (c)
#if !ABGR
# define BM_SET_RGBA(BMP, X, Y, R, G, B, A) do { \
int _p = ((Y) * BM_ROW_SIZE(BMP) + (X)*BM_BPP); \
BMP->data[_p++] = B;\
BMP->data[_p++] = G;\
BMP->data[_p++] = R;\
BMP->data[_p++] = A;\
} while(0)
# define BM_GETB(B,X,Y) (B->data[((Y) * BM_ROW_SIZE(B) + (X) * BM_BPP) + 0])
# define BM_GETG(B,X,Y) (B->data[((Y) * BM_ROW_SIZE(B) + (X) * BM_BPP) + 1])
# define BM_GETR(B,X,Y) (B->data[((Y) * BM_ROW_SIZE(B) + (X) * BM_BPP) + 2])
# define BM_GETA(B,X,Y) (B->data[((Y) * BM_ROW_SIZE(B) + (X) * BM_BPP) + 3])
# define SET_COLOR_RGB(bm, r, g, b) bm->color = 0xFF000000 | ((r) << 16) | ((g) << 8) | (b)
#else
# define BM_SET_RGBA(BMP, X, Y, R, G, B, A) do { \
int _p = ((Y) * BM_ROW_SIZE(BMP) + (X)*BM_BPP); \
BMP->data[_p++] = R;\
BMP->data[_p++] = G;\
BMP->data[_p++] = B;\
BMP->data[_p++] = A;\
} while(0)
# define BM_GETR(B,X,Y) (B->data[((Y) * BM_ROW_SIZE(B) + (X) * BM_BPP) + 0])
# define BM_GETG(B,X,Y) (B->data[((Y) * BM_ROW_SIZE(B) + (X) * BM_BPP) + 1])
# define BM_GETB(B,X,Y) (B->data[((Y) * BM_ROW_SIZE(B) + (X) * BM_BPP) + 2])
# define BM_GETA(B,X,Y) (B->data[((Y) * BM_ROW_SIZE(B) + (X) * BM_BPP) + 3])
# define SET_COLOR_RGB(bm, r, g, b) bm->color = 0xFF000000 | ((b) << 16) | ((g) << 8) | (r)
#endif
/* N=0 -> B, N=1 -> G, N=2 -> R, N=3 -> A */
#define BM_GETN(B,N,X,Y) (B->data[((Y) * BM_ROW_SIZE(B) + (X) * BM_BPP) + (N)])
static Bitmap *bm_create_internal(int w, int h) {
SET_ERROR("no error");
if(w <= 0 || h <= 0) {
SET_ERROR("invalid dimensions");
return NULL;
}
#if SIZE_LIMITS
if(w > 23000 || h > 23000 || w*h > 0x1FFFFFFF) {
SET_ERROR("dimensions too large");
return NULL;
}
#endif
Bitmap *b = CAST(Bitmap *)(malloc(sizeof *b));
if(!b) {
SET_ERROR("out of memory");
return NULL;
}
b->w = w;
b->h = h;
b->clip.x0 = 0;
b->clip.y0 = 0;
b->clip.x1 = w;
b->clip.y1 = h;
b->data = NULL;
b->flags = 0;
b->font = NULL;
bm_reset_font(b);
bm_set_color(b, 0xFFFFFFFF);
b->ref_count = 0;
return b;
}
Bitmap *bm_create(int w, int h) {
Bitmap *b = bm_create_internal(w, h);
if(!b)
return NULL;
b->data = CAST(unsigned char *)(malloc(BM_BLOB_SIZE(b)));
if(!b->data) {
SET_ERROR("out of memory");
bm_free(b);
return NULL;
}
memset(b->data, 0x00, BM_BLOB_SIZE(b));
b->flags = FLAG_OWNS_DATA;
return b;
}
#if defined(USESTB)
# define STB_IMAGE_IMPLEMENTATION
# ifdef __TINYC__
/* Yes, it compiles with the Tiny C Compiler, but without SIMD */
# define STBI_NO_SIMD
# endif
# ifndef STBI_INCLUDE_STB_IMAGE_H
# include "stb_image.h"
# undef STB_IMAGE_IMPLEMENTATION
# endif
#endif
/* Wraps around the stdio functions, so I don't have to duplicate my code
for SDL2's RWops support.
It is unfortunately an abstraction over an abstraction in the case of
SDL_RWops, but such is life. */
typedef struct {
void *data;
size_t (*fread)(void* ptr, size_t size, size_t nobj, void* stream);
long (*ftell)(void* stream);
int (*fseek)(void* stream, long offset, int origin);
} BmReader;
static BmReader make_file_reader(FILE *fp) {
BmReader rd;
rd.data = fp;
rd.fread = (size_t(*)(void*,size_t,size_t,void*))fread;
rd.ftell = (long(*)(void* ))ftell;
rd.fseek = (int(*)(void*,long,int))fseek;
return rd;
}
typedef struct {
const unsigned char *buffer;
unsigned int len;
unsigned int pos;
} BmMemReader;
static size_t memread(void *ptr, size_t size, size_t nobj, BmMemReader *mem) {
size = size * nobj;
if(mem->pos + size > mem->len) {
return 0;
}
memcpy(ptr, mem->buffer + mem->pos, size);
mem->pos += size;
return nobj;
}
static long memtell(BmMemReader *mem) {
return mem->pos;
}
static int memseek(BmMemReader *mem, long offset, int origin) {
switch(origin) {
case SEEK_SET: mem->pos = offset; break;
case SEEK_CUR: mem->pos += offset; break;
case SEEK_END: mem->pos = mem->len - offset; break;
}
if(mem->pos >= mem->len) {
mem->pos = 0;
return -1;
}
return 0;
}
static BmReader make_mem_reader(BmMemReader *mem) {
BmReader rd;
rd.data = mem;
mem->pos = 0;
rd.fread = (size_t(*)(void*,size_t,size_t,void*))memread;
rd.ftell = (long(*)(void* ))memtell;
rd.fseek = (int(*)(void*,long,int))memseek;
return rd;
}
#ifdef USESDL
static size_t rw_fread(void *ptr, size_t size, size_t nobj, SDL_RWops *stream) {
return SDL_RWread(stream, ptr, size, nobj);
}
static long rw_ftell(SDL_RWops *stream) {
return SDL_RWtell(stream);
}
static int rw_fseek(SDL_RWops *stream, long offset, int origin) {
switch (origin) {
case SEEK_SET: origin = RW_SEEK_SET; break;
case SEEK_CUR: origin = RW_SEEK_CUR; break;
case SEEK_END: origin = RW_SEEK_END; break;
}
if(SDL_RWseek(stream, offset, origin) < 0)
return 1;
return 0;
}
static BmReader make_rwops_reader(SDL_RWops *rw) {
BmReader rd;
rd.data = rw;
rd.fread = (size_t(*)(void*,size_t,size_t,void*))rw_fread;
rd.ftell = (long(*)(void* ))rw_ftell;
rd.fseek = (int(*)(void*,long,int))rw_fseek;
return rd;
}
#endif
Bitmap *bm_load(const char *filename) {
SET_ERROR("no error");
Bitmap *bmp;
#ifdef SAFE_C11
FILE *f;
errno_t err = fopen_s(&f, filename, "rb");
if (err != 0) f = 0;
#else
FILE *f = fopen(filename, "rb");
#endif
if(!f) {
SET_ERROR("unable to open file");
return NULL;
}
bmp = bm_load_fp(f);
fclose(f);
return bmp;
}
Bitmap *bm_loadf(const char *fmt, ...) {
char fname[256];
va_list arg;
va_start(arg, fmt);
vsnprintf(fname, sizeof fname, fmt, arg);
va_end(arg);
return bm_load(fname);
}
static int is_tga_file(BmReader rd);
static uint32_t count_trailing_zeroes(uint32_t v);
static Bitmap *bm_load_bmp_rd(BmReader rd);
static Bitmap *bm_load_gif_rd(BmReader rd);
static Bitmap *bm_load_pcx_rd(BmReader rd);
static Bitmap *bm_load_tga_rd(BmReader rd);
static Bitmap *bm_load_ppm_rd(BmReader rd);
#ifdef USEPNG
static Bitmap *bm_load_png_fp(FILE *f);
#endif
#ifdef USEJPG
static Bitmap *bm_load_jpg_fp(FILE *f);
#endif
Bitmap *bm_load_fp(FILE *f) {
SET_ERROR("no error");
unsigned char magic[4];
long start, isbmp = 0, ispng = 0, isjpg = 0, ispcx = 0, isgif = 0, istga = 0, ispbm = 0;
BmReader rd = make_file_reader(f);
start = rd.ftell(rd.data);
/* Tries to detect the type of file by looking at the first bytes.
http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html
*/
if(rd.fread(magic, sizeof magic, 1, rd.data) == 1) {
if(!memcmp(magic, "BM", 2))
isbmp = 1;
else if(!memcmp(magic, "GIF", 3))
isgif = 1;
else if(magic[0] == 0xFF && magic[1] == 0xD8)
isjpg = 1;
else if(magic[0] == 0x0A)
ispcx = 1;
else if(magic[0] == 0x89 && !memcmp(magic+1, "PNG", 3))
ispng = 1;
if(magic[0] == 'P' && strchr("123456", magic[1]))
ispbm = 1;
else {
/* Might be a TGA. TGA does not have a magic number :( */
rd.fseek(rd.data, start, SEEK_SET);
istga = is_tga_file(rd);
}
} else {
SET_ERROR("couldn't determine filetype");
return NULL;
}
rd.fseek(rd.data, start, SEEK_SET);
if(isjpg) {
#ifdef USEJPG
return bm_load_jpg_fp(f);
#elif defined(USESTB)
int x, y, n;
stbi_uc *data = stbi_load_from_file(f, &x, &y, &n, 4);
if(!data) {
SET_ERROR(stbi_failure_reason());
return NULL;
}
return bm_from_stb(x, y, data);
#else
(void)isjpg;
SET_ERROR("JPEG support is not enabled");
return NULL;
#endif
}
if(ispng) {
#ifdef USEPNG
return bm_load_png_fp(f);
#elif defined(USESTB)
int x, y, n;
stbi_uc *data = stbi_load_from_file(f, &x, &y, &n, 4);
if(!data) {
SET_ERROR(stbi_failure_reason());
return NULL;
}
return bm_from_stb(x, y, data);
#else
(void)ispng;
SET_ERROR("PNG support is not enabled");
return NULL;
#endif
}
if(isgif) {
return bm_load_gif_rd(rd);
}
if(ispcx) {
return bm_load_pcx_rd(rd);
}
if(isbmp) {
return bm_load_bmp_rd(rd);
}
if(istga) {
return bm_load_tga_rd(rd);
}
if(ispbm) {
return bm_load_ppm_rd(rd);
}
SET_ERROR("unsupported file type");
return NULL;
}
Bitmap *bm_load_mem(const unsigned char *buffer, long len) {
SET_ERROR("no error");
unsigned char magic[4];
long isbmp = 0, ispng = 0, isjpg = 0, ispcx = 0, isgif = 0, istga = 0, ispbm = 0;
BmMemReader memr;
memr.buffer = buffer;
memr.len = len;
BmReader rd = make_mem_reader(&memr);
/* Tries to detect the type of file by looking at the first bytes.
http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html
*/
if(rd.fread(magic, sizeof magic, 1, rd.data) == 1) {
if(!memcmp(magic, "BM", 2))
isbmp = 1;
else if(!memcmp(magic, "GIF", 3))
isgif = 1;
else if(magic[0] == 0xFF && magic[1] == 0xD8)
isjpg = 1;
else if(magic[0] == 0x0A)
ispcx = 1;
else if(magic[0] == 0x89 && !memcmp(magic+1, "PNG", 3))
ispng = 1;
if(magic[0] == 'P' && strchr("123456", magic[1]))
ispbm = 1;
else {
/* Might be a TGA. TGA does not have a magic number :( */
rd.fseek(rd.data, 0, SEEK_SET);
istga = is_tga_file(rd);
}
} else {
SET_ERROR("couldn't determine filetype");
return NULL;
}
rd.fseek(rd.data, 0, SEEK_SET);
if(isjpg) {
#ifdef USEJPG
/* FIXME: JPG support */
SET_ERROR("JPEG not supported by bm_load_mem()");
return NULL;
#elif defined(USESTB)
int x, y, n;
stbi_uc *data = stbi_load_from_memory(buffer, len, &x, &y, &n, 4);
if(!data) {
SET_ERROR(stbi_failure_reason());
return NULL;
}
return bm_from_stb(x, y, data);
#else
(void)isjpg;
SET_ERROR("JPEG support is not enabled");
return NULL;
#endif
}
if(ispng) {
#ifdef USEPNG
/* FIXME: PNG support */
SET_ERROR("PNG not supported by bm_load_mem()");
return NULL;
#elif defined(USESTB)
int x, y, n;
stbi_uc *data = stbi_load_from_memory(buffer, len, &x, &y, &n, 4);
if(!data) {
SET_ERROR(stbi_failure_reason());
return NULL;
}
return bm_from_stb(x, y, data);
#else
(void)ispng;
SET_ERROR("PNG support is not enabled");
return NULL;
#endif
}
if(isgif) {
return bm_load_gif_rd(rd);
}
if(ispcx) {
return bm_load_pcx_rd(rd);
}
if(isbmp) {
return bm_load_bmp_rd(rd);
}
if(istga) {
return bm_load_tga_rd(rd);
}
if(ispbm) {
return bm_load_ppm_rd(rd);
}
SET_ERROR("unsupported file type"); /* should not happen */
return NULL;
}
Bitmap *bm_load_base64(const char *base64) {
SET_ERROR("no error");
/* It would've been cool to read the Base64 data
in place with a custom BmReader object, but I
found that decoding first makes it easier to deal with
whitespace in the input data */
if(!base64)
return NULL;
if(!memcmp(base64, "data:", 5)) {
/* https://en.wikipedia.org/wiki/Data_URI_scheme
I can ignore the parameters because we deduce the file type from the data,
and assume the Base64 is in ASCII
*/
base64 = strchr(base64, ',');
if(!base64) {
SET_ERROR("invalid data URI");
return NULL;
}
base64++;
}
long len = strlen(base64);
unsigned char *p, *buffer;
const char *q;
unsigned octet = 0, sextet, bits = 0;
buffer = CAST(unsigned char*)(malloc(len + 1));
if(!buffer) {
SET_ERROR("out of memory");
return NULL;
}
for(p = buffer, q = base64; *q; q++) {
if(isspace(*q))
continue;
else if(isupper(*q))
sextet = *q - 'A';
else if(islower(*q))
sextet = *q - 'a' + 26;
else if(isdigit(*q))
sextet = *q - '0' + 52;
else if(*q == '+')
sextet = 62;
else if(*q == '/')
sextet = 63;
else if(*q == '=')
break;
else {
SET_ERROR("invalid character in Base64 data");
free(buffer);
return NULL;
}
octet = (octet << 6) | sextet;
bits += 6;
if(bits > 8) {
*p++ = (octet >> (bits - 8)) & 0xFF;
bits -= 8;
}
}
if(bits == 8)
*p++ = octet & 0xFF;
assert((p - buffer) < len);
Bitmap *b = bm_load_mem(buffer, p - buffer);
free(buffer);
return b;
}
static Bitmap *bm_load_bmp_rd(BmReader rd) {
struct bmpfile_magic magic;
struct bmpfile_header hdr;
struct bmpfile_dibinfo dib;
struct bmpfile_colinfo *palette = NULL;
Bitmap *b = NULL;
int i, j;
unsigned rs;
unsigned char *data = NULL;
uint32_t rgbmask[3] = { 0, 0, 0 };
uint32_t rgbshift[3] = { 0, 0, 0 };
float rgbcorr[3] = { 0.0f, 0.0f, 0.0f };
long start_offset = rd.ftell(rd.data);
if(rd.fread(&magic, sizeof magic, 1, rd.data) != 1) {
SET_ERROR("fread on magic");
return NULL;
}
if(memcmp(magic.magic, "BM", 2)) {
SET_ERROR("bad magic");
return NULL;
}
if(rd.fread(&hdr, sizeof hdr, 1, rd.data) != 1 ||
rd.fread(&dib, sizeof dib, 1, rd.data) != 1) {
SET_ERROR("fread on header");
return NULL;
}
if (dib.bitspp != 1 &&
dib.bitspp != 4 &&
dib.bitspp != 8 &&
dib.bitspp != 24 &&
dib.bitspp != 32) {
/* Unsupported BMP type. Only 16bpp is missing now */
SET_ERROR("unsupported BMP type");
return NULL;
}
if(dib.compress_type != 0 && dib.compress_type != 3) {
/* Unsupported compression type. Only uncompressed BI_RGB & BI_BITFIELDS are ok */
SET_ERROR("unsupported compression type");
return NULL;
}
b = bm_create(dib.width, dib.height);
if(!b) {
return NULL;
}
if(dib.bitspp <= 8) {
if(!dib.ncolors) {
dib.ncolors = 1 << dib.bitspp;
}
palette = CAST(struct bmpfile_colinfo*)(calloc(dib.ncolors, sizeof *palette));
if(!palette) {
SET_ERROR("out of memory");
goto error;
}
if(rd.fread(palette, sizeof *palette, dib.ncolors, rd.data) != dib.ncolors) {
SET_ERROR("fread on palette");
goto error;
}
}
/* standard bitmasks for 16 & 32 bpp, required when biCompression = BI_RGB */
if (dib.bitspp == 32) {
rgbmask[0] = 0x00FF0000;
rgbmask[1] = 0x0000FF00;
rgbmask[2] = 0x000000FF;
} else if (dib.bitspp == 16) {
rgbmask[0] = 0x00007C00;
rgbmask[1] = 0x000003E0;
rgbmask[2] = 0x0000001F;
}
/* biCompression = BI_BITFIELDS, so read the bitmask */
if (dib.compress_type == 3) {
if (rd.fread(rgbmask, 1, 12, rd.data) != 12) {
SET_ERROR("fread on bitfields");
goto error;
}
}
/* 1. calculate how many bits we have to shift after masking */
/* 2. calculate the bit depth of the input channels */
/* 3. calculate the factor that maps the channel to 0-255 */
for (int i = 0; i < 3; ++i) {
rgbshift[i] = count_trailing_zeroes(rgbmask[i]);
uint32_t chdepth = rgbmask[i] >> rgbshift[i];
rgbcorr[i] = chdepth ? 255.0f / chdepth : 0.0f;
}
if(rd.fseek(rd.data, hdr.bmp_offset + start_offset, SEEK_SET) != 0) {
SET_ERROR("out of memory");
goto error;
}
rs = ((dib.width * dib.bitspp / 8) + 3) & ~3;
assert(rs % 4 == 0);
if(dib.bmp_bytesz == 0) {
data = CAST(unsigned char *)(malloc(rs * b->h));
if(!data) {
SET_ERROR("out of memory");
goto error;
}
if(rd.fread(data, 1, rs * b->h, rd.data) != rs * b->h) {
SET_ERROR("fread on data");
goto error;
}
} else {
data = CAST(unsigned char *)(malloc(dib.bmp_bytesz));
if(!data) {
SET_ERROR("out of memory");
goto error;
}
if(rd.fread(data, 1, dib.bmp_bytesz, rd.data) != dib.bmp_bytesz) {
SET_ERROR("fread on data");
goto error;
}
}
if(dib.bitspp == 8) {
for(j = 0; j < b->h; j++) {
int y = b->h - j - 1;
for(i = 0; i < b->w; i++) {
int byt = y * rs + i;
uint8_t p = data[byt];
assert(p < dib.ncolors);
BM_SET_RGBA(b, i, j, palette[p].r, palette[p].g, palette[p].b, palette[p].a);
}
}
} else if(dib.bitspp == 4) {
for(j = 0; j < b->h; j++) {
int y = b->h - j - 1;
for(i = 0; i < b->w; i++) {
int byt = y * rs + (i >> 1);
uint8_t p = ( (i & 0x01) ? data[byt] : (data[byt] >> 4) ) & 0x0F;
assert(p < dib.ncolors);
BM_SET_RGBA(b, i, j, palette[p].r, palette[p].g, palette[p].b, palette[p].a);
}
}
} else if (dib.bitspp == 1) {
for(j = 0; j < b->h; j++) {
int y = b->h - j - 1;
for(i = 0; i < b->w; i++) {
int byt = y * rs + (i >> 3);
int bit = 7 - (i % 8);
uint8_t p = (data[byt] & (1 << bit)) >> bit;
assert(p < dib.ncolors);
BM_SET_RGBA(b, i, j, palette[p].r, palette[p].g, palette[p].b, palette[p].a);
}
}
} else if (dib.bitspp == 32) {
for(j = 0; j < b->h; j++) {
uint32_t y = b->h - j - 1;
for(i = 0; i < b->w; i++) {
uint32_t p = y * rs + i * 4;
uint32_t* pixel = (uint32_t*)(data + p);
uint32_t r_unc = (*pixel & rgbmask[0]) >> rgbshift[0];
uint32_t g_unc = (*pixel & rgbmask[1]) >> rgbshift[1];
uint32_t b_unc = (*pixel & rgbmask[2]) >> rgbshift[2];
BM_SET_RGBA(b, i, j,
(unsigned char)(r_unc * rgbcorr[0]),
(unsigned char)(g_unc * rgbcorr[1]),
(unsigned char)(b_unc * rgbcorr[2]), 0xFF);
}
}
} else {
for(j = 0; j < b->h; j++) {
uint32_t y = b->h - j - 1;
for(i = 0; i < b->w; i++) {
uint32_t p = y * rs + i * 3;
BM_SET_RGBA(b, i, j, data[p+2], data[p+1], data[p+0], 0xFF);
}
}
}
end:
if(data) free(data);
if(palette != NULL) free(palette);
return b;
error:
if(b)
bm_free(b);
b = NULL;
goto end;
}
static int bm_save_bmp(Bitmap *b, const char *fname);
static int bm_save_gif(Bitmap *b, const char *fname);
static int bm_save_pcx(Bitmap *b, const char *fname);
static int bm_save_tga(Bitmap *b, const char *fname);
static int bm_save_ppm(Bitmap *b, const char *fname);
#ifdef USEPNG
static int bm_save_png(Bitmap *b, const char *fname);
#endif
#ifdef USEJPG
static int bm_save_jpg(Bitmap *b, const char *fname);
#endif
int bm_save(Bitmap *b, const char *fname) {
SET_ERROR("no error");
/* Chooses the file type to save as based on the
extension in the filename */
char *lname = strdup(fname), *c,
jpg = 0, png = 0, pcx = 0, gif = 0, tga = 0, ppm = 0;
for(c = lname; *c; c++)
*c = tolower(*c);
png = !!strstr(lname, ".png");
pcx = !!strstr(lname, ".pcx");
gif = !!strstr(lname, ".gif");
tga = !!strstr(lname, ".tga");
jpg = !!strstr(lname, ".jpg") || !!strstr(lname, ".jpeg");
ppm = !!strstr(lname, ".pbm") || !!strstr(lname, ".pgm") || !!strstr(lname, ".ppm");
free(lname);
#ifdef USEPNG
if(png)
return bm_save_png(b, fname);
#else
(void)png;
#endif
#ifdef USEJPG
if(jpg)
return bm_save_jpg(b, fname);
#else
(void)jpg;
#endif
if(gif)
return bm_save_gif(b, fname);
if(pcx)
return bm_save_pcx(b, fname);
if(tga)
return bm_save_tga(b, fname);
if(ppm)
return bm_save_ppm(b, fname);
return bm_save_bmp(b, fname);
}
int bm_savef(Bitmap *b, const char *fmt, ...) {
char fname[256];
va_list arg;
assert(b);
va_start(arg, fmt);
vsnprintf(fname, sizeof fname, fmt, arg);
va_end(arg);
return bm_save(b, fname);
}
static int bm_save_bmp(Bitmap *b, const char *fname) {
SET_ERROR("no error");
/* TODO: Now that I have a function to count colors, maybe
I should choose to save a bitmap as 8-bit if there
are <= 256 colors in the image? */
struct bmpfile_magic magic = {{'B','M'}};
struct bmpfile_header hdr;
struct bmpfile_dibinfo dib;
FILE *f;
int rs, padding, i, j;
unsigned char *data;
padding = 4 - ((b->w * 3) % 4);
if(padding > 3) padding = 0;
rs = b->w * 3 + padding;
assert(rs % 4 == 0);
#ifdef SAFE_C11
errno_t err = fopen_s(&f, fname, "wb");
if(err != 0) {
SET_ERROR("unable to open file for output");
return 0;
}
#else
f = fopen(fname, "wb");
if(!f) {