-
Notifications
You must be signed in to change notification settings - Fork 0
/
stb_image_aug.c
3631 lines (3286 loc) · 112 KB
/
stb_image_aug.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
/* stbi-1.16 - public domain JPEG/PNG reader
QUICK NOTES:
JPEG baseline (no JPEG progressive, no oddball channel decimations)
PNG non-interlaced
BMP non-1bpp, non-RLE
TGA (not sure what subset, if a subset)
PSD (composited view only, no extra channels)
HDR (radiance rgbE format)
writes BMP,TGA (define STBI_NO_WRITE to remove code)
decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code)
supports installable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
*/
#include "stb_image_aug.h"
#ifndef STBI_NO_HDR
#include <math.h> // ldexp
#include <string.h> // strcmp
#endif
#ifndef STBI_NO_STDIO
#include <stdio.h>
#endif
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
#include <stdarg.h>
#ifndef _MSC_VER
#ifdef __cplusplus
#define __forceinline inline
#else
#define __forceinline
#endif
#endif
// implementation:
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned int uint32;
typedef signed int int32;
typedef unsigned int uint;
// should produce compiler error if size is wrong
typedef unsigned char validate_uint32[sizeof(uint32)==4];
#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)
#define STBI_NO_WRITE
#endif
#ifndef STBI_NO_DDS
#include "stbi_dds_aug.h"
#endif
// I (JLD) want full messages for SOIL
#define STBI_FAILURE_USERMSG 1
//////////////////////////////////////////////////////////////////////////////
//
// Generic API that works on all image types
//
// this is not threadsafe
static char *failure_reason;
char *stbi_failure_reason(void)
{
return failure_reason;
}
static int e(char *str)
{
failure_reason = str;
return 0;
}
#ifdef STBI_NO_FAILURE_STRINGS
#define e(x,y) 0
#elif defined(STBI_FAILURE_USERMSG)
#define e(x,y) e(y)
#else
#define e(x,y) e(x)
#endif
#define epf(x,y) ((float *) (e(x,y)?NULL:NULL))
#define epuc(x,y) ((unsigned char *) (e(x,y)?NULL:NULL))
void stbi_image_free(void *retval_from_stbi_load)
{
free(retval_from_stbi_load);
}
#define MAX_LOADERS 32
stbi_loader *loaders[MAX_LOADERS];
static int max_loaders = 0;
int stbi_register_loader(stbi_loader *loader)
{
int i;
for (i=0; i < MAX_LOADERS; ++i) {
// already present?
if (loaders[i] == loader)
return 1;
// end of the list?
if (loaders[i] == NULL) {
loaders[i] = loader;
max_loaders = i+1;
return 1;
}
}
// no room for it
return 0;
}
#ifndef STBI_NO_HDR
static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp);
#endif
#ifndef STBI_NO_STDIO
unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
{
FILE *f = fopen(filename, "rb");
unsigned char *result;
if (!f) return epuc("can't fopen", "Unable to open file");
result = stbi_load_from_file(f,x,y,comp,req_comp);
fclose(f);
return result;
}
unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
int i;
if (stbi_jpeg_test_file(f))
return stbi_jpeg_load_from_file(f,x,y,comp,req_comp);
if (stbi_png_test_file(f))
return stbi_png_load_from_file(f,x,y,comp,req_comp);
if (stbi_bmp_test_file(f))
return stbi_bmp_load_from_file(f,x,y,comp,req_comp);
if (stbi_psd_test_file(f))
return stbi_psd_load_from_file(f,x,y,comp,req_comp);
#ifndef STBI_NO_DDS
if (stbi_dds_test_file(f))
return stbi_dds_load_from_file(f,x,y,comp,req_comp);
#endif
#ifndef STBI_NO_HDR
if (stbi_hdr_test_file(f)) {
float *hdr = stbi_hdr_load_from_file(f, x,y,comp,req_comp);
return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
}
#endif
for (i=0; i < max_loaders; ++i)
if (loaders[i]->test_file(f))
return loaders[i]->load_from_file(f,x,y,comp,req_comp);
// test tga last because it's a crappy test!
if (stbi_tga_test_file(f))
return stbi_tga_load_from_file(f,x,y,comp,req_comp);
return epuc("unknown image type", "Image not of any known type, or corrupt");
}
#endif
unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
int i;
if (stbi_jpeg_test_memory(buffer,len))
return stbi_jpeg_load_from_memory(buffer,len,x,y,comp,req_comp);
if (stbi_png_test_memory(buffer,len))
return stbi_png_load_from_memory(buffer,len,x,y,comp,req_comp);
if (stbi_bmp_test_memory(buffer,len))
return stbi_bmp_load_from_memory(buffer,len,x,y,comp,req_comp);
if (stbi_psd_test_memory(buffer,len))
return stbi_psd_load_from_memory(buffer,len,x,y,comp,req_comp);
#ifndef STBI_NO_DDS
if (stbi_dds_test_memory(buffer,len))
return stbi_dds_load_from_memory(buffer,len,x,y,comp,req_comp);
#endif
#ifndef STBI_NO_HDR
if (stbi_hdr_test_memory(buffer, len)) {
float *hdr = stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);
return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
}
#endif
for (i=0; i < max_loaders; ++i)
if (loaders[i]->test_memory(buffer,len))
return loaders[i]->load_from_memory(buffer,len,x,y,comp,req_comp);
// test tga last because it's a crappy test!
if (stbi_tga_test_memory(buffer,len))
return stbi_tga_load_from_memory(buffer,len,x,y,comp,req_comp);
return epuc("unknown image type", "Image not of any known type, or corrupt");
}
#ifndef STBI_NO_HDR
#ifndef STBI_NO_STDIO
float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
{
FILE *f = fopen(filename, "rb");
float *result;
if (!f) return epf("can't fopen", "Unable to open file");
result = stbi_loadf_from_file(f,x,y,comp,req_comp);
fclose(f);
return result;
}
float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
unsigned char *data;
#ifndef STBI_NO_HDR
if (stbi_hdr_test_file(f))
return stbi_hdr_load_from_file(f,x,y,comp,req_comp);
#endif
data = stbi_load_from_file(f, x, y, comp, req_comp);
if (data)
return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
return epf("unknown image type", "Image not of any known type, or corrupt");
}
#endif
float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
stbi_uc *data;
#ifndef STBI_NO_HDR
if (stbi_hdr_test_memory(buffer, len))
return stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);
#endif
data = stbi_load_from_memory(buffer, len, x, y, comp, req_comp);
if (data)
return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
return epf("unknown image type", "Image not of any known type, or corrupt");
}
#endif
// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
// defined, for API simplicity; if STBI_NO_HDR is defined, it always
// reports false!
int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
{
#ifndef STBI_NO_HDR
return stbi_hdr_test_memory(buffer, len);
#else
return 0;
#endif
}
#ifndef STBI_NO_STDIO
extern int stbi_is_hdr (char const *filename)
{
FILE *f = fopen(filename, "rb");
int result=0;
if (f) {
result = stbi_is_hdr_from_file(f);
fclose(f);
}
return result;
}
extern int stbi_is_hdr_from_file(FILE *f)
{
#ifndef STBI_NO_HDR
return stbi_hdr_test_file(f);
#else
return 0;
#endif
}
#endif
// @TODO: get image dimensions & components without fully decoding
#ifndef STBI_NO_STDIO
extern int stbi_info (char const *filename, int *x, int *y, int *comp);
extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
#ifndef STBI_NO_HDR
static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;
static float l2h_gamma=2.2f, l2h_scale=1.0f;
void stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
void stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
void stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
void stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
#endif
//////////////////////////////////////////////////////////////////////////////
//
// Common code used by all image loaders
//
enum
{
SCAN_load=0,
SCAN_type,
SCAN_header,
};
typedef struct
{
uint32 img_x, img_y;
int img_n, img_out_n;
#ifndef STBI_NO_STDIO
FILE *img_file;
#endif
uint8 *img_buffer, *img_buffer_end;
} stbi;
#ifndef STBI_NO_STDIO
static void start_file(stbi *s, FILE *f)
{
s->img_file = f;
}
#endif
static void start_mem(stbi *s, uint8 const *buffer, int len)
{
#ifndef STBI_NO_STDIO
s->img_file = NULL;
#endif
s->img_buffer = (uint8 *) buffer;
s->img_buffer_end = (uint8 *) buffer+len;
}
__forceinline static int get8(stbi *s)
{
#ifndef STBI_NO_STDIO
if (s->img_file) {
int c = fgetc(s->img_file);
return c == EOF ? 0 : c;
}
#endif
if (s->img_buffer < s->img_buffer_end)
return *s->img_buffer++;
return 0;
}
__forceinline static int at_eof(stbi *s)
{
#ifndef STBI_NO_STDIO
if (s->img_file)
return feof(s->img_file);
#endif
return s->img_buffer >= s->img_buffer_end;
}
__forceinline static uint8 get8u(stbi *s)
{
return (uint8) get8(s);
}
static void skip(stbi *s, int n)
{
#ifndef STBI_NO_STDIO
if (s->img_file)
fseek(s->img_file, n, SEEK_CUR);
else
#endif
s->img_buffer += n;
}
static int get16(stbi *s)
{
int z = get8(s);
return (z << 8) + get8(s);
}
static uint32 get32(stbi *s)
{
uint32 z = get16(s);
return (z << 16) + get16(s);
}
static int get16le(stbi *s)
{
int z = get8(s);
return z + (get8(s) << 8);
}
static uint32 get32le(stbi *s)
{
uint32 z = get16le(s);
return z + (get16le(s) << 16);
}
static void getn(stbi *s, stbi_uc *buffer, int n)
{
#ifndef STBI_NO_STDIO
if (s->img_file) {
fread(buffer, 1, n, s->img_file);
return;
}
#endif
memcpy(buffer, s->img_buffer, n);
s->img_buffer += n;
}
//////////////////////////////////////////////////////////////////////////////
//
// generic converter from built-in img_n to req_comp
// individual types do this automatically as much as possible (e.g. jpeg
// does all cases internally since it needs to colorspace convert anyway,
// and it never has alpha, so very few cases ). png can automatically
// interleave an alpha=255 channel, but falls back to this for other cases
//
// assume data buffer is malloced, so malloc a new one and free that one
// only failure mode is malloc failing
static uint8 compute_y(int r, int g, int b)
{
return (uint8) (((r*77) + (g*150) + (29*b)) >> 8);
}
static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)
{
int i,j;
unsigned char *good;
if (req_comp == img_n) return data;
assert(req_comp >= 1 && req_comp <= 4);
good = (unsigned char *) malloc(req_comp * x * y);
if (good == NULL) {
free(data);
return epuc("outofmem", "Out of memory");
}
for (j=0; j < (int) y; ++j) {
unsigned char *src = data + j * x * img_n ;
unsigned char *dest = good + j * x * req_comp;
#define COMBO(a,b) ((a)*8+(b))
#define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
// convert source image with img_n components to one with req_comp components;
// avoid switch per pixel, so use switch per scanline and massive macros
switch(COMBO(img_n, req_comp)) {
CASE(1,2) dest[0]=src[0], dest[1]=255; break;
CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
CASE(2,1) dest[0]=src[0]; break;
CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
default: assert(0);
}
#undef CASE
}
free(data);
return good;
}
#ifndef STBI_NO_HDR
static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
{
int i,k,n;
float *output = (float *) malloc(x * y * comp * sizeof(float));
if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }
// compute number of non-alpha components
if (comp & 1) n = comp; else n = comp-1;
for (i=0; i < x*y; ++i) {
for (k=0; k < n; ++k) {
output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;
}
if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
}
free(data);
return output;
}
#define float2int(x) ((int) (x))
static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp)
{
int i,k,n;
stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }
// compute number of non-alpha components
if (comp & 1) n = comp; else n = comp-1;
for (i=0; i < x*y; ++i) {
for (k=0; k < n; ++k) {
float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;
if (z < 0) z = 0;
if (z > 255) z = 255;
output[i*comp + k] = float2int(z);
}
if (k < comp) {
float z = data[i*comp+k] * 255 + 0.5f;
if (z < 0) z = 0;
if (z > 255) z = 255;
output[i*comp + k] = float2int(z);
}
}
free(data);
return output;
}
#endif
//////////////////////////////////////////////////////////////////////////////
//
// "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
//
// simple implementation
// - channel subsampling of at most 2 in each dimension
// - doesn't support delayed output of y-dimension
// - simple interface (only one output format: 8-bit interleaved RGB)
// - doesn't try to recover corrupt jpegs
// - doesn't allow partial loading, loading multiple at once
// - still fast on x86 (copying globals into locals doesn't help x86)
// - allocates lots of intermediate memory (full size of all components)
// - non-interleaved case requires this anyway
// - allows good upsampling (see next)
// high-quality
// - upsampled channels are bilinearly interpolated, even across blocks
// - quality integer IDCT derived from IJG's 'slow'
// performance
// - fast huffman; reasonable integer IDCT
// - uses a lot of intermediate memory, could cache poorly
// - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
// stb_jpeg: 1.34 seconds (MSVC6, default release build)
// stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro)
// IJL11.dll: 1.08 seconds (compiled by intel)
// IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG)
// IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro)
// huffman decoding acceleration
#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
typedef struct
{
uint8 fast[1 << FAST_BITS];
// weirdly, repacking this into AoS is a 10% speed loss, instead of a win
uint16 code[256];
uint8 values[256];
uint8 size[257];
unsigned int maxcode[18];
int delta[17]; // old 'firstsymbol' - old 'firstcode'
} huffman;
typedef struct
{
#if STBI_SIMD
unsigned short dequant2[4][64];
#endif
stbi s;
huffman huff_dc[4];
huffman huff_ac[4];
uint8 dequant[4][64];
// sizes for components, interleaved MCUs
int img_h_max, img_v_max;
int img_mcu_x, img_mcu_y;
int img_mcu_w, img_mcu_h;
// definition of jpeg image component
struct
{
int id;
int h,v;
int tq;
int hd,ha;
int dc_pred;
int x,y,w2,h2;
uint8 *data;
void *raw_data;
uint8 *linebuf;
} img_comp[4];
uint32 code_buffer; // jpeg entropy-coded buffer
int code_bits; // number of valid bits
unsigned char marker; // marker seen while filling entropy buffer
int nomore; // flag if we saw a marker so must stop
int scan_n, order[4];
int restart_interval, todo;
} jpeg;
static int build_huffman(huffman *h, int *count)
{
int i,j,k=0,code;
// build size list for each symbol (from JPEG spec)
for (i=0; i < 16; ++i)
for (j=0; j < count[i]; ++j)
h->size[k++] = (uint8) (i+1);
h->size[k] = 0;
// compute actual symbols (from jpeg spec)
code = 0;
k = 0;
for(j=1; j <= 16; ++j) {
// compute delta to add to code to compute symbol id
h->delta[j] = k - code;
if (h->size[k] == j) {
while (h->size[k] == j)
h->code[k++] = (uint16) (code++);
if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");
}
// compute largest code + 1 for this size, preshifted as needed later
h->maxcode[j] = code << (16-j);
code <<= 1;
}
h->maxcode[j] = 0xffffffff;
// build non-spec acceleration table; 255 is flag for not-accelerated
memset(h->fast, 255, 1 << FAST_BITS);
for (i=0; i < k; ++i) {
int s = h->size[i];
if (s <= FAST_BITS) {
int c = h->code[i] << (FAST_BITS-s);
int m = 1 << (FAST_BITS-s);
for (j=0; j < m; ++j) {
h->fast[c+j] = (uint8) i;
}
}
}
return 1;
}
static void grow_buffer_unsafe(jpeg *j)
{
do {
int b = j->nomore ? 0 : get8(&j->s);
if (b == 0xff) {
int c = get8(&j->s);
if (c != 0) {
j->marker = (unsigned char) c;
j->nomore = 1;
return;
}
}
j->code_buffer = (j->code_buffer << 8) | b;
j->code_bits += 8;
} while (j->code_bits <= 24);
}
// (1 << n) - 1
static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
// decode a jpeg huffman value from the bitstream
__forceinline static int decode(jpeg *j, huffman *h)
{
unsigned int temp;
int c,k;
if (j->code_bits < 16) grow_buffer_unsafe(j);
// look at the top FAST_BITS and determine what symbol ID it is,
// if the code is <= FAST_BITS
c = (j->code_buffer >> (j->code_bits - FAST_BITS)) & ((1 << FAST_BITS)-1);
k = h->fast[c];
if (k < 255) {
if (h->size[k] > j->code_bits)
return -1;
j->code_bits -= h->size[k];
return h->values[k];
}
// naive test is to shift the code_buffer down so k bits are
// valid, then test against maxcode. To speed this up, we've
// preshifted maxcode left so that it has (16-k) 0s at the
// end; in other words, regardless of the number of bits, it
// wants to be compared against something shifted to have 16;
// that way we don't need to shift inside the loop.
if (j->code_bits < 16)
temp = (j->code_buffer << (16 - j->code_bits)) & 0xffff;
else
temp = (j->code_buffer >> (j->code_bits - 16)) & 0xffff;
for (k=FAST_BITS+1 ; ; ++k)
if (temp < h->maxcode[k])
break;
if (k == 17) {
// error! code not found
j->code_bits -= 16;
return -1;
}
if (k > j->code_bits)
return -1;
// convert the huffman code to the symbol id
c = ((j->code_buffer >> (j->code_bits - k)) & bmask[k]) + h->delta[k];
assert((((j->code_buffer) >> (j->code_bits - h->size[c])) & bmask[h->size[c]]) == h->code[c]);
// convert the id to a symbol
j->code_bits -= k;
return h->values[c];
}
// combined JPEG 'receive' and JPEG 'extend', since baseline
// always extends everything it receives.
__forceinline static int extend_receive(jpeg *j, int n)
{
unsigned int m = 1 << (n-1);
unsigned int k;
if (j->code_bits < n) grow_buffer_unsafe(j);
k = (j->code_buffer >> (j->code_bits - n)) & bmask[n];
j->code_bits -= n;
// the following test is probably a random branch that won't
// predict well. I tried to table accelerate it but failed.
// maybe it's compiling as a conditional move?
if (k < m)
return (-1 << n) + k + 1;
else
return k;
}
// given a value that's at position X in the zigzag stream,
// where does it appear in the 8x8 matrix coded as row-major?
static uint8 dezigzag[64+15] =
{
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,
// let corrupt input sample past end
63, 63, 63, 63, 63, 63, 63, 63,
63, 63, 63, 63, 63, 63, 63
};
// decode one 64-entry block--
static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)
{
int diff,dc,k;
int t = decode(j, hdc);
if (t < 0) return e("bad huffman code","Corrupt JPEG");
// 0 all the ac values now so we can do it 32-bits at a time
memset(data,0,64*sizeof(data[0]));
diff = t ? extend_receive(j, t) : 0;
dc = j->img_comp[b].dc_pred + diff;
j->img_comp[b].dc_pred = dc;
data[0] = (short) dc;
// decode AC components, see JPEG spec
k = 1;
do {
int r,s;
int rs = decode(j, hac);
if (rs < 0) return e("bad huffman code","Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0) {
if (rs != 0xf0) break; // end block
k += 16;
} else {
k += r;
// decode into unzigzag'd location
data[dezigzag[k++]] = (short) extend_receive(j,s);
}
} while (k < 64);
return 1;
}
// take a -128..127 value and clamp it and convert to 0..255
__forceinline static uint8 clamp(int x)
{
x += 128;
// trick to use a single test to catch both cases
if ((unsigned int) x > 255) {
if (x < 0) return 0;
if (x > 255) return 255;
}
return (uint8) x;
}
#define f2f(x) (int) (((x) * 4096 + 0.5))
#define fsh(x) ((x) << 12)
// derived from jidctint -- DCT_ISLOW
#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
p2 = s2; \
p3 = s6; \
p1 = (p2+p3) * f2f(0.5411961f); \
t2 = p1 + p3*f2f(-1.847759065f); \
t3 = p1 + p2*f2f( 0.765366865f); \
p2 = s0; \
p3 = s4; \
t0 = fsh(p2+p3); \
t1 = fsh(p2-p3); \
x0 = t0+t3; \
x3 = t0-t3; \
x1 = t1+t2; \
x2 = t1-t2; \
t0 = s7; \
t1 = s5; \
t2 = s3; \
t3 = s1; \
p3 = t0+t2; \
p4 = t1+t3; \
p1 = t0+t3; \
p2 = t1+t2; \
p5 = (p3+p4)*f2f( 1.175875602f); \
t0 = t0*f2f( 0.298631336f); \
t1 = t1*f2f( 2.053119869f); \
t2 = t2*f2f( 3.072711026f); \
t3 = t3*f2f( 1.501321110f); \
p1 = p5 + p1*f2f(-0.899976223f); \
p2 = p5 + p2*f2f(-2.562915447f); \
p3 = p3*f2f(-1.961570560f); \
p4 = p4*f2f(-0.390180644f); \
t3 += p1+p4; \
t2 += p2+p3; \
t1 += p2+p4; \
t0 += p1+p3;
#if !STBI_SIMD
// .344 seconds on 3*anemones.jpg
static void idct_block(uint8 *out, int out_stride, short data[64], uint8 *dequantize)
{
int i,val[64],*v=val;
uint8 *o,*dq = dequantize;
short *d = data;
// columns
for (i=0; i < 8; ++i,++d,++dq, ++v) {
// if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
&& d[40]==0 && d[48]==0 && d[56]==0) {
// no shortcut 0 seconds
// (1|2|3|4|5|6|7)==0 0 seconds
// all separate -0.047 seconds
// 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
int dcterm = d[0] * dq[0] << 2;
v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
} else {
IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
// constants scaled things up by 1<<12; let's bring them back
// down, but keep 2 extra bits of precision
x0 += 512; x1 += 512; x2 += 512; x3 += 512;
v[ 0] = (x0+t3) >> 10;
v[56] = (x0-t3) >> 10;
v[ 8] = (x1+t2) >> 10;
v[48] = (x1-t2) >> 10;
v[16] = (x2+t1) >> 10;
v[40] = (x2-t1) >> 10;
v[24] = (x3+t0) >> 10;
v[32] = (x3-t0) >> 10;
}
}
for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
// no fast case since the first 1D IDCT spread components out
IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
// constants scaled things up by 1<<12, plus we had 1<<2 from first
// loop, plus horizontal and vertical each scale by sqrt(8) so together
// we've got an extra 1<<3, so 1<<17 total we need to remove.
x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;
o[0] = clamp((x0+t3) >> 17);
o[7] = clamp((x0-t3) >> 17);
o[1] = clamp((x1+t2) >> 17);
o[6] = clamp((x1-t2) >> 17);
o[2] = clamp((x2+t1) >> 17);
o[5] = clamp((x2-t1) >> 17);
o[3] = clamp((x3+t0) >> 17);
o[4] = clamp((x3-t0) >> 17);
}
}
#else
static void idct_block(uint8 *out, int out_stride, short data[64], unsigned short *dequantize)
{
int i,val[64],*v=val;
uint8 *o;
unsigned short *dq = dequantize;
short *d = data;
// columns
for (i=0; i < 8; ++i,++d,++dq, ++v) {
// if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
&& d[40]==0 && d[48]==0 && d[56]==0) {
// no shortcut 0 seconds
// (1|2|3|4|5|6|7)==0 0 seconds
// all separate -0.047 seconds
// 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
int dcterm = d[0] * dq[0] << 2;
v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
} else {
IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
// constants scaled things up by 1<<12; let's bring them back
// down, but keep 2 extra bits of precision
x0 += 512; x1 += 512; x2 += 512; x3 += 512;
v[ 0] = (x0+t3) >> 10;
v[56] = (x0-t3) >> 10;
v[ 8] = (x1+t2) >> 10;
v[48] = (x1-t2) >> 10;
v[16] = (x2+t1) >> 10;
v[40] = (x2-t1) >> 10;
v[24] = (x3+t0) >> 10;
v[32] = (x3-t0) >> 10;
}
}
for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
// no fast case since the first 1D IDCT spread components out
IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
// constants scaled things up by 1<<12, plus we had 1<<2 from first
// loop, plus horizontal and vertical each scale by sqrt(8) so together
// we've got an extra 1<<3, so 1<<17 total we need to remove.
x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;
o[0] = clamp((x0+t3) >> 17);
o[7] = clamp((x0-t3) >> 17);
o[1] = clamp((x1+t2) >> 17);
o[6] = clamp((x1-t2) >> 17);
o[2] = clamp((x2+t1) >> 17);
o[5] = clamp((x2-t1) >> 17);
o[3] = clamp((x3+t0) >> 17);
o[4] = clamp((x3-t0) >> 17);
}
}
static stbi_idct_8x8 stbi_idct_installed = idct_block;
extern void stbi_install_idct(stbi_idct_8x8 func)
{
stbi_idct_installed = func;
}
#endif
#define MARKER_none 0xff
// if there's a pending marker from the entropy stream, return that
// otherwise, fetch from the stream and get a marker. if there's no
// marker, return 0xff, which is never a valid marker value
static uint8 get_marker(jpeg *j)
{
uint8 x;
if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }
x = get8u(&j->s);
if (x != 0xff) return MARKER_none;
while (x == 0xff)
x = get8u(&j->s);
return x;
}
// in each scan, we'll have scan_n components, and the order
// of the components is specified by order[]
#define RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
// after a restart interval, reset the entropy decoder and
// the dc prediction
static void reset(jpeg *j)
{
j->code_bits = 0;
j->code_buffer = 0;
j->nomore = 0;
j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
j->marker = MARKER_none;
j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
// no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
// since we don't even allow 1<<30 pixels
}
static int parse_entropy_coded_data(jpeg *z)
{
reset(z);
if (z->scan_n == 1) {
int i,j;
#if STBI_SIMD
__declspec(align(16))
#endif
short data[64];
int n = z->order[0];
// non-interleaved data, we just need to process one block at a time,
// in trivial scanline order
// number of blocks to do just depends on how many actual "pixels" this
// component has, independent of interleaved MCU blocking and such
int w = (z->img_comp[n].x+7) >> 3;
int h = (z->img_comp[n].y+7) >> 3;
for (j=0; j < h; ++j) {
for (i=0; i < w; ++i) {
if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
#if STBI_SIMD
stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
#else
idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
#endif
// every data block is an MCU, so countdown the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) grow_buffer_unsafe(z);
// if it's NOT a restart, then just bail, so we get corrupt data
// rather than no data
if (!RESTART(z->marker)) return 1;
reset(z);
}