-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathjpeg.h
More file actions
1550 lines (1310 loc) · 50.1 KB
/
jpeg.h
File metadata and controls
1550 lines (1310 loc) · 50.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
/*
* JPEG Decoder - Single-header implementation
*
* A dependency-free C implementation for reading JPEG images.
* Supports baseline and progressive DCT with various chroma subsampling.
*
* Usage:
* jpeg_image *img = jpeg_load("image.jpg");
* if (!img) { handle error }
*
* // Access pixel data (RGB)
* uint8_t *pixel = img->data + (y * img->width + x) * img->channels;
*
* jpeg_free(img);
*
* To use as header-only, define JPEG_IMPLEMENTATION before including:
* #define JPEG_IMPLEMENTATION
* #include "jpeg.h"
*
* Features:
* - Baseline DCT (SOF0)
* - Progressive DCT (SOF2)
* - 4:4:4, 4:2:2, 4:2:0 chroma subsampling
* - Restart markers
* - Multi-scan progressive images
*/
#ifndef JPEG_H
#define JPEG_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ========================================================================
* Image Structure
* ======================================================================== */
typedef struct {
int width;
int height;
int channels; /* 1=Grayscale, 3=RGB */
uint8_t *data; /* Row-major, channel-interleaved */
} jpeg_image;
/* ========================================================================
* Public API
* ======================================================================== */
/*
* Load JPEG image from file.
* Returns NULL on error.
*/
jpeg_image *jpeg_load(const char *path);
/*
* Load JPEG image from memory buffer.
* Returns NULL on error.
*/
jpeg_image *jpeg_load_mem(const uint8_t *data, size_t len);
/*
* Create a new image with given dimensions.
* Allocates zeroed pixel data.
*/
jpeg_image *jpeg_create(int width, int height, int channels);
/*
* Free image and pixel data.
*/
void jpeg_free(jpeg_image *img);
/*
* Clone an image (deep copy).
*/
jpeg_image *jpeg_clone(const jpeg_image *img);
#ifdef __cplusplus
}
#endif
#endif /* JPEG_H */
/* ========================================================================
* Implementation
* ======================================================================== */
#ifdef JPEG_IMPLEMENTATION
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ========================================================================
* Image Creation and Management
* ======================================================================== */
jpeg_image *jpeg_create(int width, int height, int channels) {
jpeg_image *img = (jpeg_image *)malloc(sizeof(jpeg_image));
if (!img) return NULL;
img->width = width;
img->height = height;
img->channels = channels;
img->data = (uint8_t *)calloc(width * height * channels, sizeof(uint8_t));
if (!img->data) {
free(img);
return NULL;
}
return img;
}
void jpeg_free(jpeg_image *img) {
if (img) {
free(img->data);
free(img);
}
}
jpeg_image *jpeg_clone(const jpeg_image *img) {
if (!img) return NULL;
jpeg_image *clone = jpeg_create(img->width, img->height, img->channels);
if (!clone) return NULL;
memcpy(clone->data, img->data, img->width * img->height * img->channels);
return clone;
}
/* ========================================================================
* JPEG Decoder Internals
* ======================================================================== */
/* JPEG markers */
#define JPEG_SOI 0xD8 /* Start of image */
#define JPEG_EOI 0xD9 /* End of image */
#define JPEG_SOF0 0xC0 /* Baseline DCT */
#define JPEG_SOF2 0xC2 /* Progressive DCT */
#define JPEG_DHT 0xC4 /* Define Huffman table */
#define JPEG_DQT 0xDB /* Define quantization table */
#define JPEG_DRI 0xDD /* Define restart interval */
#define JPEG_SOS 0xDA /* Start of scan */
#define JPEG_RST0 0xD0 /* Restart marker 0 */
/* Clamp value to 0-255 range */
#define JPEG_CLAMP(x) ((x) < 0 ? 0 : ((x) > 255 ? 255 : (x)))
typedef struct {
uint8_t bits[16]; /* Number of codes of each length 1-16 */
uint8_t values[256]; /* Symbol values */
/* Derived lookup tables */
int maxcode[17]; /* Max code for each length, -1 if none */
int valptr[17]; /* Index into values for codes of length i */
int lookup[256]; /* Fast lookup for short codes: (length << 8) | symbol */
} jpeg_huff_table;
typedef struct {
const uint8_t *data;
size_t len;
size_t pos;
uint64_t bitbuf; /* 64-bit to prevent overflow when refilling */
int bitcount;
int eof; /* Set when we've padded past end of data */
} jpeg_bitstream;
typedef struct {
int width, height;
int num_components;
int restart_interval;
int is_progressive;
/* Component info */
struct {
int id;
int h_samp, v_samp; /* Sampling factors */
int qt_idx; /* Quantization table index */
int dc_idx, ac_idx; /* Huffman table indices */
int blocks_x, blocks_y; /* Number of 8x8 blocks */
int16_t *coefs; /* Coefficient buffer for progressive */
} comp[4];
int max_h_samp, max_v_samp;
/* Quantization tables (up to 4) */
uint16_t qt[4][64];
/* Huffman tables (DC: 0-1, AC: 2-3) */
jpeg_huff_table huff[4];
/* DC prediction for each component */
int dc_pred[4];
/* Bitstream */
jpeg_bitstream bs;
/* MCU dimensions */
int mcu_width, mcu_height;
int mcus_x, mcus_y;
/* Progressive scan parameters */
int ss, se; /* Spectral selection: start and end coefficient */
int ah, al; /* Successive approximation: high and low bit */
int eobrun; /* End of block run counter */
} jpeg_decoder;
/* Zigzag order for 8x8 block */
static const uint8_t jpeg_zigzag[64] = {
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63
};
/* Read next byte, handling FF00 stuffing */
static int jpeg_read_byte(jpeg_bitstream *bs) {
if (bs->pos >= bs->len) return -1;
uint8_t b = bs->data[bs->pos++];
if (b == 0xFF) {
/* Skip any fill bytes (extra 0xFF) */
while (bs->pos < bs->len && bs->data[bs->pos] == 0xFF) {
bs->pos++;
}
if (bs->pos >= bs->len) return -1;
uint8_t next = bs->data[bs->pos];
if (next == 0x00) {
/* Stuffed 0x00 means literal 0xFF data byte */
bs->pos++;
return 0xFF;
}
/* Marker found (including restart markers).
*
* IMPORTANT: Don't consume the marker here. If we skip restart markers
* inside the bitreader, the 8-bit Huffman fast path (peek_bits(8))
* can read past a restart boundary and accidentally consume bytes from
* the next interval. Instead, signal the marker and let the scan-level
* logic consume restart markers at the correct MCU boundary.
*/
bs->pos--; /* Back up so bs->data[bs->pos] points at 0xFF */
if (next >= JPEG_RST0 && next <= JPEG_RST0 + 7) return -2; /* Restart marker */
return -1; /* Other marker (end of scan data) */
}
return b;
}
/* Get n bits from bitstream */
static int jpeg_get_bits(jpeg_bitstream *bs, int n) {
while (bs->bitcount < n) {
int b = jpeg_read_byte(bs);
if (b == -2) {
/* Restart marker encountered: treat as fill bits without setting EOF. */
b = 0xFF;
} else if (b < 0) {
/* At EOF - pad with 1s (JPEG convention for fill bits) */
b = 0xFF;
bs->eof = 1;
}
bs->bitbuf = (bs->bitbuf << 8) | b;
bs->bitcount += 8;
}
bs->bitcount -= n;
return (bs->bitbuf >> bs->bitcount) & ((1 << n) - 1);
}
/* Peek at n bits without consuming */
static int jpeg_peek_bits(jpeg_bitstream *bs, int n) {
while (bs->bitcount < n) {
int b = jpeg_read_byte(bs);
if (b == -2) {
/* Restart marker encountered: treat as fill bits without setting EOF. */
b = 0xFF;
} else if (b < 0) {
/* At EOF - pad with 1s (JPEG convention for fill bits) */
b = 0xFF;
bs->eof = 1;
}
bs->bitbuf = (bs->bitbuf << 8) | b;
bs->bitcount += 8;
}
return (bs->bitbuf >> (bs->bitcount - n)) & ((1 << n) - 1);
}
/* Skip n bits */
static void jpeg_skip_bits(jpeg_bitstream *bs, int n) {
bs->bitcount -= n;
}
/* Build Huffman table */
static int jpeg_build_huffman(jpeg_huff_table *h, const uint8_t *bits, const uint8_t *values) {
memcpy(h->bits, bits, 16);
memset(h->lookup, 0, sizeof(h->lookup));
int total = 0;
for (int i = 0; i < 16; i++) {
total += bits[i];
}
if (total > 256) return 0;
memcpy(h->values, values, total);
/* Build maxcode and valptr tables */
int code = 0;
int idx = 0;
for (int len = 1; len <= 16; len++) {
if (bits[len - 1] == 0) {
h->maxcode[len] = -1;
h->valptr[len] = 0;
} else {
h->valptr[len] = idx;
for (int i = 0; i < bits[len - 1]; i++) {
/* Build fast lookup for codes up to 8 bits */
if (len <= 8) {
int pad = 8 - len;
int base_code = code << pad;
/* Validate lookup index is in bounds */
if (base_code + (1 << pad) > 256) return 0;
for (int p = 0; p < (1 << pad); p++) {
h->lookup[base_code + p] = (len << 8) | values[idx + i];
}
}
code++;
}
h->maxcode[len] = code - 1;
idx += bits[len - 1];
}
code <<= 1;
}
return 1;
}
/* Decode one Huffman symbol */
static int jpeg_decode_huffman(jpeg_bitstream *bs, jpeg_huff_table *h) {
/* Try fast lookup first (8 bits) */
int peek = jpeg_peek_bits(bs, 8);
if (peek < 0) return -1;
int lookup = h->lookup[peek];
if (lookup != 0) {
int len = lookup >> 8;
jpeg_skip_bits(bs, len);
return lookup & 0xFF;
}
/* Slow path for longer codes */
int code = jpeg_get_bits(bs, 8);
if (code < 0) return -1;
for (int len = 9; len <= 16; len++) {
int bit = jpeg_get_bits(bs, 1);
if (bit < 0) return -1;
code = (code << 1) | bit;
if (h->maxcode[len] >= 0 && code <= h->maxcode[len]) {
int idx = h->valptr[len] + code - (h->maxcode[len] - h->bits[len - 1] + 1);
return h->values[idx];
}
}
return -1; /* Invalid code */
}
/* Extend sign bit */
static int jpeg_extend(int v, int bits) {
if (bits == 0) return 0;
int vt = 1 << (bits - 1);
if (v < vt) {
v = v + (-1 << bits) + 1;
}
return v;
}
/* ========================================================================
* Inverse DCT
* ======================================================================== */
/* Fast integer IDCT using AAN algorithm (Arai, Agui, Nakajima 1988) */
static void jpeg_idct(int *block, uint8_t *out, int stride) {
int tmp0, tmp1, tmp2, tmp3;
int tmp10, tmp11, tmp12, tmp13;
int z1, z2, z3, z4, z5;
int *blkptr;
uint8_t *outptr;
int workspace[64];
/* Constants for IDCT */
#define FIX_0_298 2446
#define FIX_0_390 3196
#define FIX_0_541 4433
#define FIX_0_765 6270
#define FIX_0_899 7373
#define FIX_1_175 9633
#define FIX_1_501 12299
#define FIX_1_847 15137
#define FIX_1_961 16069
#define FIX_2_053 16819
#define FIX_2_562 20995
#define FIX_3_072 25172
/* Pass 1: process columns */
blkptr = block;
int *wsptr = workspace;
for (int col = 0; col < 8; col++) {
/* Check for all-zero AC terms */
if (blkptr[8] == 0 && blkptr[16] == 0 && blkptr[24] == 0 &&
blkptr[32] == 0 && blkptr[40] == 0 && blkptr[48] == 0 && blkptr[56] == 0) {
int dc = blkptr[0] << 2;
wsptr[0] = wsptr[8] = wsptr[16] = wsptr[24] =
wsptr[32] = wsptr[40] = wsptr[48] = wsptr[56] = dc;
blkptr++;
wsptr++;
continue;
}
z2 = blkptr[16];
z3 = blkptr[48];
z1 = (z2 + z3) * FIX_0_541;
tmp2 = z1 + z3 * (-FIX_1_847);
tmp3 = z1 + z2 * FIX_0_765;
z2 = blkptr[0];
z3 = blkptr[32];
tmp0 = (z2 + z3) << 13;
tmp1 = (z2 - z3) << 13;
tmp10 = tmp0 + tmp3;
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
tmp0 = blkptr[56];
tmp1 = blkptr[40];
tmp2 = blkptr[24];
tmp3 = blkptr[8];
z1 = tmp0 + tmp3;
z2 = tmp1 + tmp2;
z3 = tmp0 + tmp2;
z4 = tmp1 + tmp3;
z5 = (z3 + z4) * FIX_1_175;
tmp0 = tmp0 * FIX_0_298;
tmp1 = tmp1 * FIX_2_053;
tmp2 = tmp2 * FIX_3_072;
tmp3 = tmp3 * FIX_1_501;
z1 = z1 * (-FIX_0_899);
z2 = z2 * (-FIX_2_562);
z3 = z3 * (-FIX_1_961);
z4 = z4 * (-FIX_0_390);
z3 += z5;
z4 += z5;
tmp0 += z1 + z3;
tmp1 += z2 + z4;
tmp2 += z2 + z3;
tmp3 += z1 + z4;
wsptr[0] = (tmp10 + tmp3 + (1 << 10)) >> 11;
wsptr[56] = (tmp10 - tmp3 + (1 << 10)) >> 11;
wsptr[8] = (tmp11 + tmp2 + (1 << 10)) >> 11;
wsptr[48] = (tmp11 - tmp2 + (1 << 10)) >> 11;
wsptr[16] = (tmp12 + tmp1 + (1 << 10)) >> 11;
wsptr[40] = (tmp12 - tmp1 + (1 << 10)) >> 11;
wsptr[24] = (tmp13 + tmp0 + (1 << 10)) >> 11;
wsptr[32] = (tmp13 - tmp0 + (1 << 10)) >> 11;
blkptr++;
wsptr++;
}
/* Pass 2: process rows */
wsptr = workspace;
outptr = out;
for (int row = 0; row < 8; row++) {
z2 = wsptr[2];
z3 = wsptr[6];
z1 = (z2 + z3) * FIX_0_541;
tmp2 = z1 + z3 * (-FIX_1_847);
tmp3 = z1 + z2 * FIX_0_765;
tmp0 = (wsptr[0] + wsptr[4]) << 13;
tmp1 = (wsptr[0] - wsptr[4]) << 13;
tmp10 = tmp0 + tmp3;
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
tmp0 = wsptr[7];
tmp1 = wsptr[5];
tmp2 = wsptr[3];
tmp3 = wsptr[1];
z1 = tmp0 + tmp3;
z2 = tmp1 + tmp2;
z3 = tmp0 + tmp2;
z4 = tmp1 + tmp3;
z5 = (z3 + z4) * FIX_1_175;
tmp0 = tmp0 * FIX_0_298;
tmp1 = tmp1 * FIX_2_053;
tmp2 = tmp2 * FIX_3_072;
tmp3 = tmp3 * FIX_1_501;
z1 = z1 * (-FIX_0_899);
z2 = z2 * (-FIX_2_562);
z3 = z3 * (-FIX_1_961);
z4 = z4 * (-FIX_0_390);
z3 += z5;
z4 += z5;
tmp0 += z1 + z3;
tmp1 += z2 + z4;
tmp2 += z2 + z3;
tmp3 += z1 + z4;
outptr[0] = JPEG_CLAMP(((tmp10 + tmp3 + (1 << 17)) >> 18) + 128);
outptr[7] = JPEG_CLAMP(((tmp10 - tmp3 + (1 << 17)) >> 18) + 128);
outptr[1] = JPEG_CLAMP(((tmp11 + tmp2 + (1 << 17)) >> 18) + 128);
outptr[6] = JPEG_CLAMP(((tmp11 - tmp2 + (1 << 17)) >> 18) + 128);
outptr[2] = JPEG_CLAMP(((tmp12 + tmp1 + (1 << 17)) >> 18) + 128);
outptr[5] = JPEG_CLAMP(((tmp12 - tmp1 + (1 << 17)) >> 18) + 128);
outptr[3] = JPEG_CLAMP(((tmp13 + tmp0 + (1 << 17)) >> 18) + 128);
outptr[4] = JPEG_CLAMP(((tmp13 - tmp0 + (1 << 17)) >> 18) + 128);
wsptr += 8;
outptr += stride;
}
#undef FIX_0_298
#undef FIX_0_390
#undef FIX_0_541
#undef FIX_0_765
#undef FIX_0_899
#undef FIX_1_175
#undef FIX_1_501
#undef FIX_1_847
#undef FIX_1_961
#undef FIX_2_053
#undef FIX_2_562
#undef FIX_3_072
}
/* ========================================================================
* Baseline Decoding
* ======================================================================== */
/* Decode one 8x8 block */
static int jpeg_decode_block(jpeg_decoder *dec, int comp_idx, int *block) {
int dc_idx = dec->comp[comp_idx].dc_idx;
int ac_idx = dec->comp[comp_idx].ac_idx;
jpeg_huff_table *dc_huff = &dec->huff[dc_idx];
jpeg_huff_table *ac_huff = &dec->huff[ac_idx + 2];
uint16_t *qt = dec->qt[dec->comp[comp_idx].qt_idx];
memset(block, 0, 64 * sizeof(int));
/* Decode DC coefficient */
int dc_len = jpeg_decode_huffman(&dec->bs, dc_huff);
if (dc_len < 0) return -1;
int dc_val = 0;
if (dc_len > 0) {
dc_val = jpeg_get_bits(&dec->bs, dc_len);
if (dc_val < 0) return -1;
dc_val = jpeg_extend(dc_val, dc_len);
}
dec->dc_pred[comp_idx] += dc_val;
block[0] = dec->dc_pred[comp_idx] * qt[0];
/* Decode AC coefficients */
int k = 1;
while (k < 64) {
int rs = jpeg_decode_huffman(&dec->bs, ac_huff);
if (rs < 0) return -1;
int run = rs >> 4;
int size = rs & 0x0F;
if (size == 0) {
if (run == 15) {
k += 16; /* ZRL: skip 16 zeros */
} else {
break; /* EOB */
}
} else {
k += run;
if (k >= 64) return -1;
int ac_val = jpeg_get_bits(&dec->bs, size);
if (ac_val < 0) return -1;
ac_val = jpeg_extend(ac_val, size);
block[jpeg_zigzag[k]] = ac_val * qt[k];
k++;
}
}
return 0;
}
/* YCbCr to RGB conversion */
static void jpeg_ycbcr_to_rgb(uint8_t y, uint8_t cb, uint8_t cr, uint8_t *rgb) {
int yy = y;
int cbb = cb - 128;
int crr = cr - 128;
int r = yy + ((crr * 359) >> 8);
int g = yy - ((cbb * 88 + crr * 183) >> 8);
int b = yy + ((cbb * 454) >> 8);
rgb[0] = JPEG_CLAMP(r);
rgb[1] = JPEG_CLAMP(g);
rgb[2] = JPEG_CLAMP(b);
}
/* Consume a restart marker at the current bitstream position.
* Caller must ensure the bitstream is byte-aligned (bitcount == 0). */
static int jpeg_skip_restart_marker(jpeg_decoder *dec) {
jpeg_bitstream *bs = &dec->bs;
/* Skip any fill bytes (extra 0xFF) */
while (bs->pos + 1 < bs->len &&
bs->data[bs->pos] == 0xFF &&
bs->data[bs->pos + 1] == 0xFF) {
bs->pos++;
}
if (bs->pos + 1 >= bs->len) return -1;
if (bs->data[bs->pos] != 0xFF) return -1;
uint8_t marker = bs->data[bs->pos + 1];
if (marker < JPEG_RST0 || marker > JPEG_RST0 + 7) return -1;
bs->pos += 2;
return 0;
}
/* Decode scan data for baseline JPEG */
static int jpeg_decode_scan(jpeg_decoder *dec, uint8_t *y_data, uint8_t *cb_data, uint8_t *cr_data) {
int block[64];
uint8_t block_out[64];
int restart_count = dec->restart_interval;
/* Reset DC predictors */
for (int i = 0; i < 4; i++) {
dec->dc_pred[i] = 0;
}
for (int mcu_y = 0; mcu_y < dec->mcus_y; mcu_y++) {
for (int mcu_x = 0; mcu_x < dec->mcus_x; mcu_x++) {
/* Handle restart interval */
if (dec->restart_interval > 0 && restart_count == 0) {
/* Align to byte boundary */
dec->bs.bitcount = 0;
dec->bs.bitbuf = 0;
/* Reset DC predictors */
for (int i = 0; i < 4; i++) {
dec->dc_pred[i] = 0;
}
if (jpeg_skip_restart_marker(dec) < 0) return -1;
restart_count = dec->restart_interval;
}
/* Decode Y blocks */
for (int v = 0; v < dec->comp[0].v_samp; v++) {
for (int h = 0; h < dec->comp[0].h_samp; h++) {
if (jpeg_decode_block(dec, 0, block) < 0) return -1;
jpeg_idct(block, block_out, 8);
/* Copy to Y plane */
int bx = mcu_x * dec->comp[0].h_samp * 8 + h * 8;
int by = mcu_y * dec->comp[0].v_samp * 8 + v * 8;
int y_stride = dec->mcus_x * dec->comp[0].h_samp * 8;
for (int row = 0; row < 8; row++) {
int dst_y = by + row;
if (dst_y < dec->height) {
for (int col = 0; col < 8; col++) {
int dst_x = bx + col;
if (dst_x < dec->width) {
y_data[dst_y * y_stride + dst_x] = block_out[row * 8 + col];
}
}
}
}
}
}
/* Decode Cb block(s) */
if (dec->num_components >= 3) {
for (int v = 0; v < dec->comp[1].v_samp; v++) {
for (int h = 0; h < dec->comp[1].h_samp; h++) {
if (jpeg_decode_block(dec, 1, block) < 0) return -1;
jpeg_idct(block, block_out, 8);
int bx = mcu_x * dec->comp[1].h_samp * 8 + h * 8;
int by = mcu_y * dec->comp[1].v_samp * 8 + v * 8;
int cb_stride = dec->mcus_x * dec->comp[1].h_samp * 8;
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
int dst_y = by + row;
int dst_x = bx + col;
if (dst_y < (dec->mcus_y * dec->comp[1].v_samp * 8) &&
dst_x < cb_stride) {
cb_data[dst_y * cb_stride + dst_x] = block_out[row * 8 + col];
}
}
}
}
}
/* Decode Cr block(s) */
for (int v = 0; v < dec->comp[2].v_samp; v++) {
for (int h = 0; h < dec->comp[2].h_samp; h++) {
if (jpeg_decode_block(dec, 2, block) < 0) return -1;
jpeg_idct(block, block_out, 8);
int bx = mcu_x * dec->comp[2].h_samp * 8 + h * 8;
int by = mcu_y * dec->comp[2].v_samp * 8 + v * 8;
int cr_stride = dec->mcus_x * dec->comp[2].h_samp * 8;
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
int dst_y = by + row;
int dst_x = bx + col;
if (dst_y < (dec->mcus_y * dec->comp[2].v_samp * 8) &&
dst_x < cr_stride) {
cr_data[dst_y * cr_stride + dst_x] = block_out[row * 8 + col];
}
}
}
}
}
}
if (dec->restart_interval > 0) {
restart_count--;
}
}
}
return 0;
}
/* ========================================================================
* Progressive Decoding
* ======================================================================== */
/* Decode DC coefficient for progressive first scan (Ah == 0) */
static int jpeg_prog_decode_dc_first(jpeg_decoder *dec, int comp_idx, int16_t *coef) {
jpeg_huff_table *dc_huff = &dec->huff[dec->comp[comp_idx].dc_idx];
int dc_len = jpeg_decode_huffman(&dec->bs, dc_huff);
if (dc_len < 0) return -1;
int dc_val = 0;
if (dc_len > 0) {
dc_val = jpeg_get_bits(&dec->bs, dc_len);
if (dc_val < 0) return -1;
dc_val = jpeg_extend(dc_val, dc_len);
}
dec->dc_pred[comp_idx] += dc_val;
coef[0] = (int16_t)(dec->dc_pred[comp_idx] << dec->al);
return 0;
}
/* Decode DC coefficient refinement for progressive (Ah != 0) */
static int jpeg_prog_decode_dc_refine(jpeg_decoder *dec, int16_t *coef) {
int bit = jpeg_get_bits(&dec->bs, 1);
if (bit < 0) return -1;
if (bit) {
coef[0] |= (1 << dec->al);
}
return 0;
}
/* Decode AC coefficients for progressive first scan (Ah == 0) */
static int jpeg_prog_decode_ac_first(jpeg_decoder *dec, int comp_idx, int16_t *coef) {
jpeg_huff_table *ac_huff = &dec->huff[dec->comp[comp_idx].ac_idx + 2];
if (dec->eobrun > 0) {
dec->eobrun--;
return 0;
}
int k = dec->ss;
while (k <= dec->se) {
int rs = jpeg_decode_huffman(&dec->bs, ac_huff);
if (rs < 0) {
/* At EOF, treat as implicit EOB for remaining blocks */
if (dec->bs.eof) return 0;
return -1;
}
int run = rs >> 4;
int size = rs & 0x0F;
if (size == 0) {
if (run == 15) {
k += 16; /* ZRL: skip 16 zeros */
} else {
/* EOBn: end of block run */
dec->eobrun = (1 << run);
if (run > 0) {
int extra = jpeg_get_bits(&dec->bs, run);
if (extra < 0) {
if (dec->bs.eof) break;
return -1;
}
dec->eobrun += extra;
}
dec->eobrun--;
break;
}
} else {
k += run;
if (k > dec->se) {
if (dec->bs.eof) return 0;
return -1;
}
int ac_val = jpeg_get_bits(&dec->bs, size);
if (ac_val < 0) {
if (dec->bs.eof) return 0;
return -1;
}
ac_val = jpeg_extend(ac_val, size);
coef[jpeg_zigzag[k]] = (int16_t)(ac_val << dec->al);
k++;
}
}
return 0;
}
/* Decode AC coefficient refinement for progressive (Ah != 0) */
static int jpeg_prog_decode_ac_refine(jpeg_decoder *dec, int comp_idx, int16_t *coef) {
jpeg_huff_table *ac_huff = &dec->huff[dec->comp[comp_idx].ac_idx + 2];
int p1 = 1 << dec->al; /* Bit to add for positive refinement */
int m1 = -p1; /* Bit to add for negative refinement */
int k = dec->ss;
if (dec->eobrun == 0) {
while (k <= dec->se) {
int rs = jpeg_decode_huffman(&dec->bs, ac_huff);
if (rs < 0) {
/* At EOF, treat as implicit EOB for remaining blocks */
if (dec->bs.eof) break;
return -1;
}
int run = rs >> 4;
int size = rs & 0x0F;
if (size == 0) {
if (run != 15) {
/* EOBn */
dec->eobrun = (1 << run);
if (run > 0) {
int extra = jpeg_get_bits(&dec->bs, run);
if (extra < 0) {
if (dec->bs.eof) break;
return -1;
}
dec->eobrun += extra;
}
break;
}
/* ZRL: skip 16 zeros while refining non-zeros */
run = 16;
} else if (size != 1) {
if (dec->bs.eof) break;
return -1; /* Invalid: size must be 1 for refinement */
}
/* Skip 'run' zero coefficients, refining any non-zero ones along the way */
int new_val = 0;
if (size == 1) {
int bit = jpeg_get_bits(&dec->bs, 1);
if (bit < 0) {
if (dec->bs.eof) break;
return -1;
}
new_val = bit ? p1 : m1;
}
while (k <= dec->se) {
int zk = jpeg_zigzag[k];
if (coef[zk] != 0) {
/* Refine existing non-zero coefficient */
int bit = jpeg_get_bits(&dec->bs, 1);
if (bit < 0) {
if (dec->bs.eof) goto refine_done;
return -1;
}
if (bit && (coef[zk] & p1) == 0) {
if (coef[zk] > 0) {
coef[zk] += p1;
} else {
coef[zk] += m1;
}
}
k++;
} else if (run > 0) {
run--;
k++;
} else {
break;
}
}
if (dec->bs.eof) goto refine_done;
if (size == 1 && k <= dec->se) {
coef[jpeg_zigzag[k]] = (int16_t)new_val;
k++;
}
}
}
refine_done:
/* Process remaining coefficients if in EOBRUN */
if (dec->eobrun > 0) {
while (k <= dec->se) {
int zk = jpeg_zigzag[k];
if (coef[zk] != 0) {
int bit = jpeg_get_bits(&dec->bs, 1);
if (bit < 0) {
if (dec->bs.eof) break;
return -1;
}
if (bit && (coef[zk] & p1) == 0) {
if (coef[zk] > 0) {
coef[zk] += p1;
} else {
coef[zk] += m1;
}
}
}
k++;
}
dec->eobrun--;
}
return 0;
}
/* Decode one progressive scan */
static int jpeg_decode_progressive_scan(jpeg_decoder *dec, int *scan_comps, int num_scan_comps) {
int restart_count = dec->restart_interval;
/* Reset state */
for (int i = 0; i < 4; i++) {
dec->dc_pred[i] = 0;
}
dec->eobrun = 0;
/* DC scans process all components interleaved, AC scans process one component */
if (dec->ss == 0) {
/* DC scan - interleaved MCUs */
for (int mcu_y = 0; mcu_y < dec->mcus_y; mcu_y++) {
for (int mcu_x = 0; mcu_x < dec->mcus_x; mcu_x++) {
/* Handle restart interval */
if (dec->restart_interval > 0 && restart_count == 0) {
dec->bs.bitcount = 0;
dec->bs.bitbuf = 0;
for (int i = 0; i < 4; i++) {
dec->dc_pred[i] = 0;
}
dec->eobrun = 0;
if (jpeg_skip_restart_marker(dec) < 0) return -1;
restart_count = dec->restart_interval;
}
/* Process each component in this MCU */
for (int ci = 0; ci < num_scan_comps; ci++) {
int comp_idx = scan_comps[ci];
int h_samp = dec->comp[comp_idx].h_samp;
int v_samp = dec->comp[comp_idx].v_samp;
int blocks_x = dec->comp[comp_idx].blocks_x;