-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathBmpDecoder.c
More file actions
1553 lines (1390 loc) · 64.1 KB
/
BmpDecoder.c
File metadata and controls
1553 lines (1390 loc) · 64.1 KB
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
/*
* @cond
* The following section will be excluded from the documentation.
*/
#define __BMPDECODER_C__
/***********************************************************************************************************************
PicoMite MMBasic
BmpDecoder.c
<COPYRIGHT HOLDERS> Geoff Graham, Peter Mather
Copyright (c) 2021, <COPYRIGHT HOLDERS> All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
3. The name MMBasic be used when referring to the interpreter in any documentation and promotional material and the original copyright message be displayed
on the console at startup (additional copyright messages may be added).
4. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed
by the <copyright holder>.
5. Neither the name of the <copyright holder> nor the names of its contributors may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDERS> AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDERS> BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
************************************************************************************************************************/
// #include "GenericTypeDefs.h"
#include "MMBasic_Includes.h"
#include "Hardware_Includes.h"
//** SD CARD INCLUDES ***********************************************************
#include "ff.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// BMP file header structures
#pragma pack(push, 1)
typedef struct
{
uint16_t bfType; // Must be 'BM' (0x4D42)
uint32_t bfSize; // File size in bytes
uint16_t bfReserved1; // Reserved, must be 0
uint16_t bfReserved2; // Reserved, must be 0
uint32_t bfOffBits; // Offset to bitmap data
} BITMAPFILEHEADER;
typedef struct
{
uint32_t biSize; // Size of this header (40 bytes)
int32_t biWidth; // Width in pixels
int32_t biHeight; // Height in pixels (positive = bottom-up)
uint16_t biPlanes; // Must be 1
uint16_t biBitCount; // Bits per pixel (1, 4, 8, 16, 24, 32)
uint32_t biCompression; // Compression type (0 = uncompressed)
uint32_t biSizeImage; // Image size (may be 0 for uncompressed)
int32_t biXPelsPerMeter; // Horizontal resolution
int32_t biYPelsPerMeter; // Vertical resolution
uint32_t biClrUsed; // Number of colors in palette
uint32_t biClrImportant; // Important colors (0 = all)
} BITMAPINFOHEADER;
typedef struct
{
uint8_t rgbBlue;
uint8_t rgbGreen;
uint8_t rgbRed;
uint8_t rgbReserved;
} RGBQUAD;
#pragma pack(pop)
// Compression types
#define BI_RGB 0
#define BI_RLE8 1
#define BI_RLE4 2
#define BI_BITFIELDS 3
// Seek origins
#define SEEK_SET 0
#define SEEK_CUR 1
// Return structure
// Structure to hold line start positions for compressed formats
typedef struct
{
long *positions; // Array of file positions for each line
int count; // Number of lines
} LineStartTable;
// External read function
size_t onBMPRead(char *pBufferOut, size_t bytesToRead)
{
unsigned int nbr;
FileGetData(BMPfnbr, pBufferOut, bytesToRead, &nbr);
return nbr;
}
bool onBMPSeek(int offset, bool origin)
{
if (filesource[BMPfnbr] == FATFSFILE)
{
if (origin == 0)
FSerror = f_lseek(FileTable[BMPfnbr].fptr, offset);
else
FSerror = f_lseek(FileTable[BMPfnbr].fptr, FileTable[BMPfnbr].fptr->fptr + offset);
}
else
{
if (origin == 0)
FSerror = lfs_file_seek(&lfs, FileTable[BMPfnbr].lfsptr, offset, LFS_SEEK_SET);
else
FSerror = lfs_file_seek(&lfs, FileTable[BMPfnbr].lfsptr, offset, LFS_SEEK_CUR);
}
return 1;
}
// Cleanup and error function
static void cleanupAndError(char *message, RGBQUAD **palette, uint8_t **rowBuffer,
uint32_t **lineData, LineStartTable **lineTable)
{
if (palette)
FreeMemorySafe((void **)palette);
if (rowBuffer)
FreeMemorySafe((void **)rowBuffer);
if (lineData)
FreeMemorySafe((void **)lineData);
if (lineTable && *lineTable)
{
if ((*lineTable)->positions)
{
FreeMemorySafe((void **)&((*lineTable)->positions));
}
FreeMemorySafe((void **)lineTable);
}
error(message);
// This function never returns
}
// Helper function to build line start table for RLE compressed images
static LineStartTable *buildLineStartTable(int height, long dataStart)
{
LineStartTable *table = (LineStartTable *)GetMemory(sizeof(LineStartTable));
if (!table)
return NULL;
table->positions = (long *)GetMemory(height * sizeof(long));
if (!table->positions)
{
FreeMemorySafe((void **)&table);
return NULL;
}
table->count = height;
// Seek to start of pixel data
onBMPSeek(dataStart, SEEK_SET);
int currentLine = 0;
bool done = false;
// Scan through RLE data and record line start positions
while (!done && currentLine < height)
{
// Record current file position as start of this line
table->positions[currentLine] = dataStart;
// Scan through this line to find its end
while (1)
{
uint8_t count, value;
// long currentPos;
// Remember position before reading
if (onBMPRead((char *)&count, 1) != 1)
{
FreeMemorySafe((void **)&(table->positions));
FreeMemorySafe((void **)&table);
return NULL;
}
dataStart += 1;
if (count == 0)
{
// Escape code
if (onBMPRead((char *)&value, 1) != 1)
{
FreeMemorySafe((void **)&(table->positions));
FreeMemorySafe((void **)&table);
return NULL;
}
dataStart += 1;
if (value == 0)
{
// End of line
currentLine++;
break;
}
else if (value == 1)
{
// End of bitmap
done = true;
break;
}
else if (value == 2)
{
// Delta
uint8_t dx, dy;
if (onBMPRead((char *)&dx, 1) != 1 || onBMPRead((char *)&dy, 1) != 1)
{
FreeMemorySafe((void **)&(table->positions));
FreeMemorySafe((void **)&table);
return NULL;
}
dataStart += 2;
if (dy > 0)
{
currentLine += dy;
break;
}
}
else
{
// Absolute mode
int bytesToRead = value;
int padding = bytesToRead & 1; // Pad to word boundary
// Skip the data
for (int i = 0; i < bytesToRead + padding; i++)
{
uint8_t dummy;
if (onBMPRead((char *)&dummy, 1) != 1)
{
FreeMemorySafe((void **)&(table->positions));
FreeMemorySafe((void **)&table);
return NULL;
}
dataStart += 1;
}
}
}
else
{
// Encoded mode - skip value byte
if (onBMPRead((char *)&value, 1) != 1)
{
FreeMemorySafe((void **)&(table->positions));
FreeMemorySafe((void **)&table);
return NULL;
}
dataStart += 1;
}
}
}
return table;
}
// Helper function to build line start table for RLE4
static LineStartTable *buildLineStartTableRLE4(int height, long dataStart)
{
LineStartTable *table = (LineStartTable *)GetMemory(sizeof(LineStartTable));
if (!table)
return NULL;
table->positions = (long *)GetMemory(height * sizeof(long));
if (!table->positions)
{
FreeMemorySafe((void **)&table);
return NULL;
}
table->count = height;
// Seek to start of pixel data
onBMPSeek(dataStart, SEEK_SET);
int currentLine = 0;
bool done = false;
// Scan through RLE data and record line start positions
while (!done && currentLine < height)
{
// Record current file position as start of this line
table->positions[currentLine] = dataStart;
// Scan through this line to find its end
while (1)
{
uint8_t count, value;
if (onBMPRead((char *)&count, 1) != 1)
{
FreeMemorySafe((void **)&(table->positions));
FreeMemorySafe((void **)&table);
return NULL;
}
dataStart += 1;
if (count == 0)
{
// Escape code
if (onBMPRead((char *)&value, 1) != 1)
{
FreeMemorySafe((void **)&(table->positions));
FreeMemorySafe((void **)&table);
return NULL;
}
dataStart += 1;
if (value == 0)
{
// End of line
currentLine++;
break;
}
else if (value == 1)
{
// End of bitmap
done = true;
break;
}
else if (value == 2)
{
// Delta
uint8_t dx, dy;
if (onBMPRead((char *)&dx, 1) != 1 || onBMPRead((char *)&dy, 1) != 1)
{
FreeMemorySafe((void **)&(table->positions));
FreeMemorySafe((void **)&table);
return NULL;
}
dataStart += 2;
if (dy > 0)
{
currentLine += dy;
break;
}
}
else
{
// Absolute mode - pixels packed 2 per byte
int bytesToRead = (value + 1) / 2;
int padding = bytesToRead & 1; // Pad to word boundary
// Skip the data
for (int i = 0; i < bytesToRead + padding; i++)
{
uint8_t dummy;
if (onBMPRead((char *)&dummy, 1) != 1)
{
FreeMemorySafe((void **)&(table->positions));
FreeMemorySafe((void **)&table);
return NULL;
}
dataStart += 1;
}
}
}
else
{
// Encoded mode - skip value byte
if (onBMPRead((char *)&value, 1) != 1)
{
FreeMemorySafe((void **)&(table->positions));
FreeMemorySafe((void **)&table);
return NULL;
}
dataStart += 1;
}
}
}
return table;
}
// Helper function to decode a single RLE8 line
static bool decodeRLE8Line(RGBQUAD *palette, int paletteSize, int width,
uint32_t *lineData, uint8_t *rowBuffer)
{
memset(rowBuffer, 0, width);
int x = 0;
bool lineComplete = false;
while (!lineComplete)
{
uint8_t count, value;
if (onBMPRead((char *)&count, 1) != 1)
return false;
if (count == 0)
{
// Escape code
if (onBMPRead((char *)&value, 1) != 1)
return false;
if (value == 0)
{
// End of line
lineComplete = true;
}
else if (value == 1)
{
// End of bitmap
lineComplete = true;
}
else if (value == 2)
{
// Delta - skip
uint8_t dx, dy;
if (onBMPRead((char *)&dx, 1) != 1 || onBMPRead((char *)&dy, 1) != 1)
return false;
x += dx;
}
else
{
// Absolute mode
for (int i = 0; i < value && x < width; i++, x++)
{
uint8_t pixel;
if (onBMPRead((char *)&pixel, 1) != 1)
return false;
rowBuffer[x] = pixel;
}
// Pad to word boundary
if (value & 1)
{
uint8_t dummy;
onBMPRead((char *)&dummy, 1);
}
}
}
else
{
// Encoded mode
if (onBMPRead((char *)&value, 1) != 1)
return false;
for (int i = 0; i < count && x < width; i++, x++)
{
rowBuffer[x] = value;
}
}
}
// Convert to RGB888
for (int col = 0; col < width; col++)
{
uint8_t index = rowBuffer[col];
if (index < paletteSize)
{
lineData[col] = (palette[index].rgbRed << 16) |
(palette[index].rgbGreen << 8) |
palette[index].rgbBlue;
}
else
{
lineData[col] = 0;
}
}
return true;
}
// Helper function to decode a single RLE4 line
static bool decodeRLE4Line(RGBQUAD *palette, int paletteSize, int width,
uint32_t *lineData, uint8_t *rowBuffer)
{
memset(rowBuffer, 0, width);
int x = 0;
bool lineComplete = false;
while (!lineComplete)
{
uint8_t count, value;
if (onBMPRead((char *)&count, 1) != 1)
return false;
if (count == 0)
{
// Escape code
if (onBMPRead((char *)&value, 1) != 1)
return false;
if (value == 0)
{
// End of line
lineComplete = true;
}
else if (value == 1)
{
// End of bitmap
lineComplete = true;
}
else if (value == 2)
{
// Delta
uint8_t dx, dy;
if (onBMPRead((char *)&dx, 1) != 1 || onBMPRead((char *)&dy, 1) != 1)
return false;
x += dx;
}
else
{
// Absolute mode
int pixelsToRead = value;
int bytesToRead = (pixelsToRead + 1) / 2;
for (int i = 0; i < bytesToRead; i++)
{
uint8_t byte;
if (onBMPRead((char *)&byte, 1) != 1)
return false;
if (x < width)
{
rowBuffer[x++] = (byte >> 4) & 0x0F;
}
if (pixelsToRead > 1 && x < width)
{
rowBuffer[x++] = byte & 0x0F;
}
pixelsToRead -= 2;
}
// Pad to word boundary
if (((value + 1) / 2) & 1)
{
uint8_t dummy;
onBMPRead((char *)&dummy, 1);
}
}
}
else
{
// Encoded mode
if (onBMPRead((char *)&value, 1) != 1)
return false;
uint8_t pixel1 = (value >> 4) & 0x0F;
uint8_t pixel2 = value & 0x0F;
for (int i = 0; i < count && x < width; i++)
{
rowBuffer[x++] = (i & 1) ? pixel2 : pixel1;
}
}
}
// Convert to RGB888
for (int col = 0; col < width; col++)
{
uint8_t index = rowBuffer[col];
if (index < paletteSize)
{
lineData[col] = (palette[index].rgbRed << 16) |
(palette[index].rgbGreen << 8) |
palette[index].rgbBlue;
}
else
{
lineData[col] = 0;
}
}
return true;
}
void decodeBMPheader(int *width, int *height)
{
BITMAPFILEHEADER fileHeader;
BITMAPINFOHEADER infoHeader;
// Set defaults in case of error
*width = 0;
*height = 0;
// Read file header
if (onBMPRead((char *)&fileHeader, sizeof(BITMAPFILEHEADER)) != sizeof(BITMAPFILEHEADER))
{
return;
}
// Check BMP signature
if (fileHeader.bfType != 0x4D42)
{ // 'BM'
return;
}
// Read info header
if (onBMPRead((char *)&infoHeader, sizeof(BITMAPINFOHEADER)) != sizeof(BITMAPINFOHEADER))
{
return;
}
// Return dimensions
*width = infoHeader.biWidth;
*height = abs(infoHeader.biHeight);
// Seek back to start of file for decodeBMP
onBMPSeek(0, 0);
}
BMP_Result decodeBMP(bool topdown)
{
BMP_Result result = {0};
BITMAPFILEHEADER fileHeader;
BITMAPINFOHEADER infoHeader;
RGBQUAD *palette = NULL;
uint8_t *rowBuffer = NULL;
uint32_t *lineData = NULL;
LineStartTable *lineTable = NULL;
int col;
int bottomUp;
int rowSize;
int paletteSize = 0;
long pixelDataStart;
// Read file header
if (onBMPRead((char *)&fileHeader, sizeof(BITMAPFILEHEADER)) != sizeof(BITMAPFILEHEADER))
{
cleanupAndError("Failed to read file header", &palette, &rowBuffer, &lineData, &lineTable);
}
// Check BMP signature
if (fileHeader.bfType != 0x4D42)
{ // 'BM'
cleanupAndError("Not a valid BMP file (missing BM signature)", &palette, &rowBuffer, &lineData, &lineTable);
}
// Read info header
if (onBMPRead((char *)&infoHeader, sizeof(BITMAPINFOHEADER)) != sizeof(BITMAPINFOHEADER))
{
cleanupAndError("Failed to read info header", &palette, &rowBuffer, &lineData, &lineTable);
}
// Validate header - accept BITMAPINFOHEADER (40), BITMAPV4HEADER (108), and BITMAPV5HEADER (124)
if (infoHeader.biSize != 40 && infoHeader.biSize != 108 && infoHeader.biSize != 124)
{
cleanupAndError("Unsupported BMP header format", &palette, &rowBuffer, &lineData, &lineTable);
}
// Skip any extra header bytes for V4/V5 headers (we already read 40 bytes)
if (infoHeader.biSize > 40)
{
int extraBytes = infoHeader.biSize - 40;
onBMPSeek(extraBytes, SEEK_CUR);
}
// Check compression and bit depth combinations
if (infoHeader.biCompression == BI_RLE8 && infoHeader.biBitCount != 8)
{
cleanupAndError("RLE8 compression requires 8-bit color", &palette, &rowBuffer, &lineData, &lineTable);
}
if (infoHeader.biCompression == BI_RLE4 && infoHeader.biBitCount != 4)
{
cleanupAndError("RLE4 compression requires 4-bit color", &palette, &rowBuffer, &lineData, &lineTable);
}
if (infoHeader.biCompression != BI_RGB &&
infoHeader.biCompression != BI_RLE8 &&
infoHeader.biCompression != BI_RLE4)
{
cleanupAndError("Unsupported compression format", &palette, &rowBuffer, &lineData, &lineTable);
}
if (infoHeader.biBitCount != 1 && infoHeader.biBitCount != 4 &&
infoHeader.biBitCount != 8 && infoHeader.biBitCount != 16 &&
infoHeader.biBitCount != 24)
{
cleanupAndError("Unsupported bit depth", &palette, &rowBuffer, &lineData, &lineTable);
}
// Set result dimensions
result.width = infoHeader.biWidth;
result.height = abs(infoHeader.biHeight);
result.bitsPerPixel = infoHeader.biBitCount;
bottomUp = (infoHeader.biHeight > 0);
// Read palette if needed (1-bit, 4-bit and 8-bit)
if (infoHeader.biBitCount <= 8)
{
paletteSize = infoHeader.biClrUsed;
if (paletteSize == 0)
{
paletteSize = 1 << infoHeader.biBitCount; // 2 for 1-bit, 16 for 4-bit, 256 for 8-bit
}
palette = (RGBQUAD *)GetMemory(paletteSize * sizeof(RGBQUAD));
if (!palette)
{
cleanupAndError("Failed to allocate palette", &palette, &rowBuffer, &lineData, &lineTable);
}
if (onBMPRead((char *)palette, paletteSize * sizeof(RGBQUAD)) !=
paletteSize * sizeof(RGBQUAD))
{
cleanupAndError("Failed to read palette", &palette, &rowBuffer, &lineData, &lineTable);
}
}
// Allocate line data buffer for callback (RGB888 packed into uint32_t)
lineData = (uint32_t *)GetMemory(result.width * sizeof(uint32_t));
if (!lineData)
{
cleanupAndError("Failed to allocate line data buffer", &palette, &rowBuffer, &lineData, &lineTable);
}
// Calculate pixel data start position
pixelDataStart = fileHeader.bfOffBits;
// Seek to pixel data (skip any additional headers/data)
size_t bytesRead = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
if (palette)
bytesRead += paletteSize * sizeof(RGBQUAD);
while (bytesRead < fileHeader.bfOffBits)
{
uint8_t dummy;
onBMPRead((char *)&dummy, 1);
bytesRead++;
}
// Handle RLE compressed formats
if (infoHeader.biCompression == BI_RLE8 || infoHeader.biCompression == BI_RLE4)
{
// Build line start table for random access
if (infoHeader.biCompression == BI_RLE8)
{
lineTable = buildLineStartTable(result.height, pixelDataStart);
}
else
{
lineTable = buildLineStartTableRLE4(result.height, pixelDataStart);
}
if (!lineTable)
{
cleanupAndError("Failed to build line start table", &palette, &rowBuffer, &lineData, &lineTable);
}
// Allocate row buffer for RLE decoding
rowBuffer = (uint8_t *)GetMemory(result.width);
if (!rowBuffer)
{
cleanupAndError("Failed to allocate row buffer", &palette, &rowBuffer, &lineData, &lineTable);
}
// Process lines
for (int i = 0; i < result.height; i++)
{
// Determine which file line to read and which screen row to report
int fileRow;
int screenRow;
if (topdown)
{
// topdown=true: read backwards through file
fileRow = result.height - 1 - i;
screenRow = i; // Report screen rows 0, 1, 2, ...
}
else
{
// topdown=false: read sequentially (efficient)
fileRow = i;
// RLE is bottom-up: file line 0 = image bottom → screen row 479
screenRow = result.height - 1 - i;
}
// Seek to start of this line
if (fileRow < lineTable->count && fileRow >= 0)
{
onBMPSeek(lineTable->positions[fileRow], SEEK_SET);
// Decode the line
bool success;
if (infoHeader.biCompression == BI_RLE8)
{
success = decodeRLE8Line(palette, paletteSize, result.width, lineData, rowBuffer);
}
else
{
success = decodeRLE4Line(palette, paletteSize, result.width, lineData, rowBuffer);
}
if (!success)
{
cleanupAndError("Failed to decode RLE line", &palette, &rowBuffer, &lineData, &lineTable);
}
// Call callback with screen row position
if (!linecallback(&result.width, &result.height, lineData, &screenRow))
{
result.linesProcessed = i;
FreeMemorySafe((void **)&rowBuffer);
FreeMemorySafe((void **)&lineData);
FreeMemorySafe((void **)&(lineTable->positions));
FreeMemorySafe((void **)&lineTable);
FreeMemorySafe((void **)&palette);
result.success = true;
return result;
}
}
result.linesProcessed = i + 1;
}
// Cleanup
FreeMemorySafe((void **)&rowBuffer);
FreeMemorySafe((void **)&lineData);
FreeMemorySafe((void **)&(lineTable->positions));
FreeMemorySafe((void **)&lineTable);
FreeMemorySafe((void **)&palette);
result.success = true;
return result;
}
// Handle uncompressed formats (BI_RGB)
// Calculate row size with padding (rows are padded to 4-byte boundaries)
rowSize = ((infoHeader.biBitCount * result.width + 31) / 32) * 4;
// Allocate row buffer for reading from file
rowBuffer = (uint8_t *)GetMemory(rowSize);
if (!rowBuffer)
{
cleanupAndError("Failed to allocate row buffer", &palette, &rowBuffer, &lineData, &lineTable);
}
// Read and decode pixel data
for (int i = 0; i < result.height; i++)
{
// Determine which file line to read and which screen row to report
int fileRow;
int screenRow;
if (topdown)
{
// topdown=true: read backwards through file
if (bottomUp)
{
fileRow = result.height - 1 - i;
}
else
{
fileRow = i;
}
screenRow = i; // Report screen rows 0, 1, 2, ...
}
else
{
// topdown=false: read sequentially (efficient)
fileRow = i;
if (bottomUp)
{
// File line 0 = image bottom → screen row 479
screenRow = result.height - 1 - i;
}
else
{
// File line 0 = image top → screen row 479 (upside down)
screenRow = result.height - 1 - i;
}
}
// Seek to the correct line in the file
long linePosition = pixelDataStart + ((long)fileRow * rowSize);
onBMPSeek(linePosition, SEEK_SET);
// Read row from file
if (onBMPRead((char *)rowBuffer, rowSize) != rowSize)
{
cleanupAndError("Failed to read pixel data", &palette, &rowBuffer, &lineData, &lineTable);
}
// Decode based on bit depth into lineData buffer
switch (infoHeader.biBitCount)
{
case 1: // 1-bit monochrome
for (col = 0; col < result.width; col++)
{
int byteIndex = col / 8;
int bitIndex = 7 - (col % 8);
int bit = (rowBuffer[byteIndex] >> bitIndex) & 1;
if (bit < paletteSize)
{
lineData[col] = (palette[bit].rgbRed << 16) |
(palette[bit].rgbGreen << 8) |
palette[bit].rgbBlue;
}
else
{
lineData[col] = bit ? 0xFFFFFF : 0x000000; // White or black
}
}
break;
case 4: // 4-bit indexed
for (col = 0; col < result.width; col++)
{
int byteIndex = col / 2;
int nibble = (col & 1) ? (rowBuffer[byteIndex] & 0x0F) : (rowBuffer[byteIndex] >> 4);
if (nibble < paletteSize)
{
lineData[col] = (palette[nibble].rgbRed << 16) |
(palette[nibble].rgbGreen << 8) |
palette[nibble].rgbBlue;
}
else
{
lineData[col] = 0; // Black for invalid index
}
}
break;
case 8: // 8-bit indexed
for (col = 0; col < result.width; col++)
{
uint8_t index = rowBuffer[col];
if (index < paletteSize)
{
lineData[col] = (palette[index].rgbRed << 16) |
(palette[index].rgbGreen << 8) |
palette[index].rgbBlue;
}
else
{
lineData[col] = 0; // Black for invalid index
}
}
break;
case 16: // 16-bit RGB (assume 5-5-5)
for (col = 0; col < result.width; col++)
{
uint16_t pixel = *(uint16_t *)(rowBuffer + col * 2);
// Extract RGB components (5-5-5 format) and expand to 8-bit
uint8_t r = ((pixel >> 10) & 0x1F) << 3;
uint8_t g = ((pixel >> 5) & 0x1F) << 3;
uint8_t b = (pixel & 0x1F) << 3;
lineData[col] = (r << 16) | (g << 8) | b;
}
break;
case 24: // 24-bit BGR
for (col = 0; col < result.width; col++)
{
uint8_t b = rowBuffer[col * 3 + 0];
uint8_t g = rowBuffer[col * 3 + 1];
uint8_t r = rowBuffer[col * 3 + 2];
lineData[col] = (r << 16) | (g << 8) | b;
}
break;
}
// Call the callback with screen row position
if (!linecallback(&result.width, &result.height, lineData, &screenRow))
{
// Callback requested abort - clean up and return successfully
result.linesProcessed = i;
FreeMemorySafe((void **)&rowBuffer);
FreeMemorySafe((void **)&lineData);
FreeMemorySafe((void **)&palette);
result.success = true;
return result;
}
result.linesProcessed = i + 1;
}
// Cleanup
FreeMemorySafe((void **)&rowBuffer);
FreeMemorySafe((void **)&lineData);
FreeMemorySafe((void **)&palette);
result.success = true;
return result;
}
BYTE BMP_bDecode_memory(int x, int y, int xlen, int ylen, int fnbr, char *p)
{
return 0;
}
/* BMPDECODER BmpDec;
WORD wX, wY;
BYTE bPadding;
unsigned int nbr;
BDEC_vResetData(&BmpDec);
BDEC_bReadHeader(&BmpDec, fnbr);
if (BmpDec.blBmMarkerFlag == 0 || BmpDec.bHeaderType < 40 || (BmpDec.blCompressionType != 0 && BmpDec.blCompressionType != 3))
{
return 100;
}
IMG_wImageWidth = (WORD)BmpDec.lWidth;
IMG_wImageHeight = (WORD)BmpDec.lHeight;
IMG_vSetboundaries();
char *linebuff = GetMemory(IMG_wImageWidth * 3); // get a line buffer
// IMG_FSEEK(pFile, BmpDec.lImageOffset, 0);
if (BmpDec.bBitsPerPixel == 24) // True color Image