-
-
Notifications
You must be signed in to change notification settings - Fork 21.1k
/
jpgd.cpp
3283 lines (2624 loc) · 80.1 KB
/
jpgd.cpp
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
// jpgd.cpp - C++ class for JPEG decompression. Written by Richard Geldreich <richgel99@gmail.com> between 1994-2020.
// Supports progressive and baseline sequential JPEG image files, and the most common chroma subsampling factors: Y, H1V1, H2V1, H1V2, and H2V2.
// Supports box and linear chroma upsampling.
//
// Released under two licenses. You are free to choose which license you want:
// License 1:
// Public Domain
//
// License 2:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Alex Evans: Linear memory allocator (taken from jpge.h).
// v1.04, May. 19, 2012: Code tweaks to fix VS2008 static code analysis warnings
// v2.00, March 20, 2020: Fuzzed with zzuf and afl. Fixed several issues, converted most assert()'s to run-time checks. Added chroma upsampling. Removed freq. domain upsampling. gcc/clang warnings.
//
// Important:
// #define JPGD_USE_SSE2 to 0 to completely disable SSE2 usage.
//
#include "jpgd.h"
#include <string.h>
#include <algorithm>
#include <assert.h>
#ifdef _MSC_VER
#pragma warning (disable : 4611) // warning C4611: interaction between '_setjmp' and C++ object destruction is non-portable
#endif
#ifndef JPGD_USE_SSE2
#if defined(__GNUC__)
#if defined(__SSE2__)
#define JPGD_USE_SSE2 (1)
#endif
#elif defined(_MSC_VER)
#if defined(_M_X64)
#define JPGD_USE_SSE2 (1)
#endif
#endif
#endif
#define JPGD_TRUE (1)
#define JPGD_FALSE (0)
#define JPGD_MAX(a,b) (((a)>(b)) ? (a) : (b))
#define JPGD_MIN(a,b) (((a)<(b)) ? (a) : (b))
namespace jpgd {
static inline void* jpgd_malloc(size_t nSize) { return malloc(nSize); }
static inline void jpgd_free(void* p) { free(p); }
// DCT coefficients are stored in this sequence.
static int g_ZAG[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 };
enum JPEG_MARKER
{
M_SOF0 = 0xC0, M_SOF1 = 0xC1, M_SOF2 = 0xC2, M_SOF3 = 0xC3, M_SOF5 = 0xC5, M_SOF6 = 0xC6, M_SOF7 = 0xC7, M_JPG = 0xC8,
M_SOF9 = 0xC9, M_SOF10 = 0xCA, M_SOF11 = 0xCB, M_SOF13 = 0xCD, M_SOF14 = 0xCE, M_SOF15 = 0xCF, M_DHT = 0xC4, M_DAC = 0xCC,
M_RST0 = 0xD0, M_RST1 = 0xD1, M_RST2 = 0xD2, M_RST3 = 0xD3, M_RST4 = 0xD4, M_RST5 = 0xD5, M_RST6 = 0xD6, M_RST7 = 0xD7,
M_SOI = 0xD8, M_EOI = 0xD9, M_SOS = 0xDA, M_DQT = 0xDB, M_DNL = 0xDC, M_DRI = 0xDD, M_DHP = 0xDE, M_EXP = 0xDF,
M_APP0 = 0xE0, M_APP15 = 0xEF, M_JPG0 = 0xF0, M_JPG13 = 0xFD, M_COM = 0xFE, M_TEM = 0x01, M_ERROR = 0x100, RST0 = 0xD0
};
enum JPEG_SUBSAMPLING { JPGD_GRAYSCALE = 0, JPGD_YH1V1, JPGD_YH2V1, JPGD_YH1V2, JPGD_YH2V2 };
#if JPGD_USE_SSE2
#include "jpgd_idct.h"
#endif
#define CONST_BITS 13
#define PASS1_BITS 2
#define SCALEDONE ((int32)1)
#define FIX_0_298631336 ((int32)2446) /* FIX(0.298631336) */
#define FIX_0_390180644 ((int32)3196) /* FIX(0.390180644) */
#define FIX_0_541196100 ((int32)4433) /* FIX(0.541196100) */
#define FIX_0_765366865 ((int32)6270) /* FIX(0.765366865) */
#define FIX_0_899976223 ((int32)7373) /* FIX(0.899976223) */
#define FIX_1_175875602 ((int32)9633) /* FIX(1.175875602) */
#define FIX_1_501321110 ((int32)12299) /* FIX(1.501321110) */
#define FIX_1_847759065 ((int32)15137) /* FIX(1.847759065) */
#define FIX_1_961570560 ((int32)16069) /* FIX(1.961570560) */
#define FIX_2_053119869 ((int32)16819) /* FIX(2.053119869) */
#define FIX_2_562915447 ((int32)20995) /* FIX(2.562915447) */
#define FIX_3_072711026 ((int32)25172) /* FIX(3.072711026) */
#define DESCALE(x,n) (((x) + (SCALEDONE << ((n)-1))) >> (n))
#define DESCALE_ZEROSHIFT(x,n) (((x) + (128 << (n)) + (SCALEDONE << ((n)-1))) >> (n))
#define MULTIPLY(var, cnst) ((var) * (cnst))
#define CLAMP(i) ((static_cast<uint>(i) > 255) ? (((~i) >> 31) & 0xFF) : (i))
static inline int left_shifti(int val, uint32_t bits)
{
return static_cast<int>(static_cast<uint32_t>(val) << bits);
}
// Compiler creates a fast path 1D IDCT for X non-zero columns
template <int NONZERO_COLS>
struct Row
{
static void idct(int* pTemp, const jpgd_block_coeff_t* pSrc)
{
// ACCESS_COL() will be optimized at compile time to either an array access, or 0. Good compilers will then optimize out muls against 0.
#define ACCESS_COL(x) (((x) < NONZERO_COLS) ? (int)pSrc[x] : 0)
const int z2 = ACCESS_COL(2), z3 = ACCESS_COL(6);
const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
const int tmp2 = z1 + MULTIPLY(z3, -FIX_1_847759065);
const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
const int tmp0 = left_shifti(ACCESS_COL(0) + ACCESS_COL(4), CONST_BITS);
const int tmp1 = left_shifti(ACCESS_COL(0) - ACCESS_COL(4), CONST_BITS);
const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
const int atmp0 = ACCESS_COL(7), atmp1 = ACCESS_COL(5), atmp2 = ACCESS_COL(3), atmp3 = ACCESS_COL(1);
const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3;
const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602);
const int az1 = MULTIPLY(bz1, -FIX_0_899976223);
const int az2 = MULTIPLY(bz2, -FIX_2_562915447);
const int az3 = MULTIPLY(bz3, -FIX_1_961570560) + bz5;
const int az4 = MULTIPLY(bz4, -FIX_0_390180644) + bz5;
const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3;
const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4;
const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3;
const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4;
pTemp[0] = DESCALE(tmp10 + btmp3, CONST_BITS - PASS1_BITS);
pTemp[7] = DESCALE(tmp10 - btmp3, CONST_BITS - PASS1_BITS);
pTemp[1] = DESCALE(tmp11 + btmp2, CONST_BITS - PASS1_BITS);
pTemp[6] = DESCALE(tmp11 - btmp2, CONST_BITS - PASS1_BITS);
pTemp[2] = DESCALE(tmp12 + btmp1, CONST_BITS - PASS1_BITS);
pTemp[5] = DESCALE(tmp12 - btmp1, CONST_BITS - PASS1_BITS);
pTemp[3] = DESCALE(tmp13 + btmp0, CONST_BITS - PASS1_BITS);
pTemp[4] = DESCALE(tmp13 - btmp0, CONST_BITS - PASS1_BITS);
}
};
template <>
struct Row<0>
{
static void idct(int* pTemp, const jpgd_block_coeff_t* pSrc)
{
(void)pTemp;
(void)pSrc;
}
};
template <>
struct Row<1>
{
static void idct(int* pTemp, const jpgd_block_coeff_t* pSrc)
{
const int dcval = left_shifti(pSrc[0], PASS1_BITS);
pTemp[0] = dcval;
pTemp[1] = dcval;
pTemp[2] = dcval;
pTemp[3] = dcval;
pTemp[4] = dcval;
pTemp[5] = dcval;
pTemp[6] = dcval;
pTemp[7] = dcval;
}
};
// Compiler creates a fast path 1D IDCT for X non-zero rows
template <int NONZERO_ROWS>
struct Col
{
static void idct(uint8* pDst_ptr, const int* pTemp)
{
// ACCESS_ROW() will be optimized at compile time to either an array access, or 0.
#define ACCESS_ROW(x) (((x) < NONZERO_ROWS) ? pTemp[x * 8] : 0)
const int z2 = ACCESS_ROW(2);
const int z3 = ACCESS_ROW(6);
const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
const int tmp2 = z1 + MULTIPLY(z3, -FIX_1_847759065);
const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
const int tmp0 = left_shifti(ACCESS_ROW(0) + ACCESS_ROW(4), CONST_BITS);
const int tmp1 = left_shifti(ACCESS_ROW(0) - ACCESS_ROW(4), CONST_BITS);
const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
const int atmp0 = ACCESS_ROW(7), atmp1 = ACCESS_ROW(5), atmp2 = ACCESS_ROW(3), atmp3 = ACCESS_ROW(1);
const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3;
const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602);
const int az1 = MULTIPLY(bz1, -FIX_0_899976223);
const int az2 = MULTIPLY(bz2, -FIX_2_562915447);
const int az3 = MULTIPLY(bz3, -FIX_1_961570560) + bz5;
const int az4 = MULTIPLY(bz4, -FIX_0_390180644) + bz5;
const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3;
const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4;
const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3;
const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4;
int i = DESCALE_ZEROSHIFT(tmp10 + btmp3, CONST_BITS + PASS1_BITS + 3);
pDst_ptr[8 * 0] = (uint8)CLAMP(i);
i = DESCALE_ZEROSHIFT(tmp10 - btmp3, CONST_BITS + PASS1_BITS + 3);
pDst_ptr[8 * 7] = (uint8)CLAMP(i);
i = DESCALE_ZEROSHIFT(tmp11 + btmp2, CONST_BITS + PASS1_BITS + 3);
pDst_ptr[8 * 1] = (uint8)CLAMP(i);
i = DESCALE_ZEROSHIFT(tmp11 - btmp2, CONST_BITS + PASS1_BITS + 3);
pDst_ptr[8 * 6] = (uint8)CLAMP(i);
i = DESCALE_ZEROSHIFT(tmp12 + btmp1, CONST_BITS + PASS1_BITS + 3);
pDst_ptr[8 * 2] = (uint8)CLAMP(i);
i = DESCALE_ZEROSHIFT(tmp12 - btmp1, CONST_BITS + PASS1_BITS + 3);
pDst_ptr[8 * 5] = (uint8)CLAMP(i);
i = DESCALE_ZEROSHIFT(tmp13 + btmp0, CONST_BITS + PASS1_BITS + 3);
pDst_ptr[8 * 3] = (uint8)CLAMP(i);
i = DESCALE_ZEROSHIFT(tmp13 - btmp0, CONST_BITS + PASS1_BITS + 3);
pDst_ptr[8 * 4] = (uint8)CLAMP(i);
}
};
template <>
struct Col<1>
{
static void idct(uint8* pDst_ptr, const int* pTemp)
{
int dcval = DESCALE_ZEROSHIFT(pTemp[0], PASS1_BITS + 3);
const uint8 dcval_clamped = (uint8)CLAMP(dcval);
pDst_ptr[0 * 8] = dcval_clamped;
pDst_ptr[1 * 8] = dcval_clamped;
pDst_ptr[2 * 8] = dcval_clamped;
pDst_ptr[3 * 8] = dcval_clamped;
pDst_ptr[4 * 8] = dcval_clamped;
pDst_ptr[5 * 8] = dcval_clamped;
pDst_ptr[6 * 8] = dcval_clamped;
pDst_ptr[7 * 8] = dcval_clamped;
}
};
static const uint8 s_idct_row_table[] =
{
1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0, 2,1,0,0,0,0,0,0, 2,1,1,0,0,0,0,0, 2,2,1,0,0,0,0,0, 3,2,1,0,0,0,0,0, 4,2,1,0,0,0,0,0, 4,3,1,0,0,0,0,0,
4,3,2,0,0,0,0,0, 4,3,2,1,0,0,0,0, 4,3,2,1,1,0,0,0, 4,3,2,2,1,0,0,0, 4,3,3,2,1,0,0,0, 4,4,3,2,1,0,0,0, 5,4,3,2,1,0,0,0, 6,4,3,2,1,0,0,0,
6,5,3,2,1,0,0,0, 6,5,4,2,1,0,0,0, 6,5,4,3,1,0,0,0, 6,5,4,3,2,0,0,0, 6,5,4,3,2,1,0,0, 6,5,4,3,2,1,1,0, 6,5,4,3,2,2,1,0, 6,5,4,3,3,2,1,0,
6,5,4,4,3,2,1,0, 6,5,5,4,3,2,1,0, 6,6,5,4,3,2,1,0, 7,6,5,4,3,2,1,0, 8,6,5,4,3,2,1,0, 8,7,5,4,3,2,1,0, 8,7,6,4,3,2,1,0, 8,7,6,5,3,2,1,0,
8,7,6,5,4,2,1,0, 8,7,6,5,4,3,1,0, 8,7,6,5,4,3,2,0, 8,7,6,5,4,3,2,1, 8,7,6,5,4,3,2,2, 8,7,6,5,4,3,3,2, 8,7,6,5,4,4,3,2, 8,7,6,5,5,4,3,2,
8,7,6,6,5,4,3,2, 8,7,7,6,5,4,3,2, 8,8,7,6,5,4,3,2, 8,8,8,6,5,4,3,2, 8,8,8,7,5,4,3,2, 8,8,8,7,6,4,3,2, 8,8,8,7,6,5,3,2, 8,8,8,7,6,5,4,2,
8,8,8,7,6,5,4,3, 8,8,8,7,6,5,4,4, 8,8,8,7,6,5,5,4, 8,8,8,7,6,6,5,4, 8,8,8,7,7,6,5,4, 8,8,8,8,7,6,5,4, 8,8,8,8,8,6,5,4, 8,8,8,8,8,7,5,4,
8,8,8,8,8,7,6,4, 8,8,8,8,8,7,6,5, 8,8,8,8,8,7,6,6, 8,8,8,8,8,7,7,6, 8,8,8,8,8,8,7,6, 8,8,8,8,8,8,8,6, 8,8,8,8,8,8,8,7, 8,8,8,8,8,8,8,8,
};
static const uint8 s_idct_col_table[] =
{
1, 1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
};
// Scalar "fast pathing" IDCT.
static void idct(const jpgd_block_coeff_t* pSrc_ptr, uint8* pDst_ptr, int block_max_zag, bool use_simd)
{
(void)use_simd;
assert(block_max_zag >= 1);
assert(block_max_zag <= 64);
if (block_max_zag <= 1)
{
int k = ((pSrc_ptr[0] + 4) >> 3) + 128;
k = CLAMP(k);
k = k | (k << 8);
k = k | (k << 16);
for (int i = 8; i > 0; i--)
{
*(int*)&pDst_ptr[0] = k;
*(int*)&pDst_ptr[4] = k;
pDst_ptr += 8;
}
return;
}
#if JPGD_USE_SSE2
if (use_simd)
{
assert((((uintptr_t)pSrc_ptr) & 15) == 0);
assert((((uintptr_t)pDst_ptr) & 15) == 0);
idctSSEShortU8(pSrc_ptr, pDst_ptr);
return;
}
#endif
int temp[64];
const jpgd_block_coeff_t* pSrc = pSrc_ptr;
int* pTemp = temp;
const uint8* pRow_tab = &s_idct_row_table[(block_max_zag - 1) * 8];
int i;
for (i = 8; i > 0; i--, pRow_tab++)
{
switch (*pRow_tab)
{
case 0: Row<0>::idct(pTemp, pSrc); break;
case 1: Row<1>::idct(pTemp, pSrc); break;
case 2: Row<2>::idct(pTemp, pSrc); break;
case 3: Row<3>::idct(pTemp, pSrc); break;
case 4: Row<4>::idct(pTemp, pSrc); break;
case 5: Row<5>::idct(pTemp, pSrc); break;
case 6: Row<6>::idct(pTemp, pSrc); break;
case 7: Row<7>::idct(pTemp, pSrc); break;
case 8: Row<8>::idct(pTemp, pSrc); break;
}
pSrc += 8;
pTemp += 8;
}
pTemp = temp;
const int nonzero_rows = s_idct_col_table[block_max_zag - 1];
for (i = 8; i > 0; i--)
{
switch (nonzero_rows)
{
case 1: Col<1>::idct(pDst_ptr, pTemp); break;
case 2: Col<2>::idct(pDst_ptr, pTemp); break;
case 3: Col<3>::idct(pDst_ptr, pTemp); break;
case 4: Col<4>::idct(pDst_ptr, pTemp); break;
case 5: Col<5>::idct(pDst_ptr, pTemp); break;
case 6: Col<6>::idct(pDst_ptr, pTemp); break;
case 7: Col<7>::idct(pDst_ptr, pTemp); break;
case 8: Col<8>::idct(pDst_ptr, pTemp); break;
}
pTemp++;
pDst_ptr++;
}
}
// Retrieve one character from the input stream.
inline uint jpeg_decoder::get_char()
{
// Any bytes remaining in buffer?
if (!m_in_buf_left)
{
// Try to get more bytes.
prep_in_buffer();
// Still nothing to get?
if (!m_in_buf_left)
{
// Pad the end of the stream with 0xFF 0xD9 (EOI marker)
int t = m_tem_flag;
m_tem_flag ^= 1;
if (t)
return 0xD9;
else
return 0xFF;
}
}
uint c = *m_pIn_buf_ofs++;
m_in_buf_left--;
return c;
}
// Same as previous method, except can indicate if the character is a pad character or not.
inline uint jpeg_decoder::get_char(bool* pPadding_flag)
{
if (!m_in_buf_left)
{
prep_in_buffer();
if (!m_in_buf_left)
{
*pPadding_flag = true;
int t = m_tem_flag;
m_tem_flag ^= 1;
if (t)
return 0xD9;
else
return 0xFF;
}
}
*pPadding_flag = false;
uint c = *m_pIn_buf_ofs++;
m_in_buf_left--;
return c;
}
// Inserts a previously retrieved character back into the input buffer.
inline void jpeg_decoder::stuff_char(uint8 q)
{
// This could write before the input buffer, but we've placed another array there.
*(--m_pIn_buf_ofs) = q;
m_in_buf_left++;
}
// Retrieves one character from the input stream, but does not read past markers. Will continue to return 0xFF when a marker is encountered.
inline uint8 jpeg_decoder::get_octet()
{
bool padding_flag;
int c = get_char(&padding_flag);
if (c == 0xFF)
{
if (padding_flag)
return 0xFF;
c = get_char(&padding_flag);
if (padding_flag)
{
stuff_char(0xFF);
return 0xFF;
}
if (c == 0x00)
return 0xFF;
else
{
stuff_char(static_cast<uint8>(c));
stuff_char(0xFF);
return 0xFF;
}
}
return static_cast<uint8>(c);
}
// Retrieves a variable number of bits from the input stream. Does not recognize markers.
inline uint jpeg_decoder::get_bits(int num_bits)
{
if (!num_bits)
return 0;
uint i = m_bit_buf >> (32 - num_bits);
if ((m_bits_left -= num_bits) <= 0)
{
m_bit_buf <<= (num_bits += m_bits_left);
uint c1 = get_char();
uint c2 = get_char();
m_bit_buf = (m_bit_buf & 0xFFFF0000) | (c1 << 8) | c2;
m_bit_buf <<= -m_bits_left;
m_bits_left += 16;
assert(m_bits_left >= 0);
}
else
m_bit_buf <<= num_bits;
return i;
}
// Retrieves a variable number of bits from the input stream. Markers will not be read into the input bit buffer. Instead, an infinite number of all 1's will be returned when a marker is encountered.
inline uint jpeg_decoder::get_bits_no_markers(int num_bits)
{
if (!num_bits)
return 0;
assert(num_bits <= 16);
uint i = m_bit_buf >> (32 - num_bits);
if ((m_bits_left -= num_bits) <= 0)
{
m_bit_buf <<= (num_bits += m_bits_left);
if ((m_in_buf_left < 2) || (m_pIn_buf_ofs[0] == 0xFF) || (m_pIn_buf_ofs[1] == 0xFF))
{
uint c1 = get_octet();
uint c2 = get_octet();
m_bit_buf |= (c1 << 8) | c2;
}
else
{
m_bit_buf |= ((uint)m_pIn_buf_ofs[0] << 8) | m_pIn_buf_ofs[1];
m_in_buf_left -= 2;
m_pIn_buf_ofs += 2;
}
m_bit_buf <<= -m_bits_left;
m_bits_left += 16;
assert(m_bits_left >= 0);
}
else
m_bit_buf <<= num_bits;
return i;
}
// Decodes a Huffman encoded symbol.
inline int jpeg_decoder::huff_decode(huff_tables* pH)
{
if (!pH)
stop_decoding(JPGD_DECODE_ERROR);
int symbol;
// Check first 8-bits: do we have a complete symbol?
if ((symbol = pH->look_up[m_bit_buf >> 24]) < 0)
{
// Decode more bits, use a tree traversal to find symbol.
int ofs = 23;
do
{
unsigned int idx = -(int)(symbol + ((m_bit_buf >> ofs) & 1));
// This should never happen, but to be safe I'm turning these asserts into a run-time check.
if ((idx >= JPGD_HUFF_TREE_MAX_LENGTH) || (ofs < 0))
stop_decoding(JPGD_DECODE_ERROR);
symbol = pH->tree[idx];
ofs--;
} while (symbol < 0);
get_bits_no_markers(8 + (23 - ofs));
}
else
{
assert(symbol < JPGD_HUFF_CODE_SIZE_MAX_LENGTH);
get_bits_no_markers(pH->code_size[symbol]);
}
return symbol;
}
// Decodes a Huffman encoded symbol.
inline int jpeg_decoder::huff_decode(huff_tables* pH, int& extra_bits)
{
int symbol;
if (!pH)
stop_decoding(JPGD_DECODE_ERROR);
// Check first 8-bits: do we have a complete symbol?
if ((symbol = pH->look_up2[m_bit_buf >> 24]) < 0)
{
// Use a tree traversal to find symbol.
int ofs = 23;
do
{
unsigned int idx = -(int)(symbol + ((m_bit_buf >> ofs) & 1));
// This should never happen, but to be safe I'm turning these asserts into a run-time check.
if ((idx >= JPGD_HUFF_TREE_MAX_LENGTH) || (ofs < 0))
stop_decoding(JPGD_DECODE_ERROR);
symbol = pH->tree[idx];
ofs--;
} while (symbol < 0);
get_bits_no_markers(8 + (23 - ofs));
extra_bits = get_bits_no_markers(symbol & 0xF);
}
else
{
if (symbol & 0x8000)
{
//get_bits_no_markers((symbol >> 8) & 31);
assert(((symbol >> 8) & 31) <= 15);
get_bits_no_markers((symbol >> 8) & 15);
extra_bits = symbol >> 16;
}
else
{
int code_size = (symbol >> 8) & 31;
int num_extra_bits = symbol & 0xF;
int bits = code_size + num_extra_bits;
if (bits <= 16)
extra_bits = get_bits_no_markers(bits) & ((1 << num_extra_bits) - 1);
else
{
get_bits_no_markers(code_size);
extra_bits = get_bits_no_markers(num_extra_bits);
}
}
symbol &= 0xFF;
}
return symbol;
}
// Tables and macro used to fully decode the DPCM differences.
static const int s_extend_test[16] = { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
static const int s_extend_offset[16] = { 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047, -4095, -8191, -16383, -32767 };
//static const int s_extend_mask[] = { 0, (1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4), (1 << 5), (1 << 6), (1 << 7), (1 << 8), (1 << 9), (1 << 10), (1 << 11), (1 << 12), (1 << 13), (1 << 14), (1 << 15), (1 << 16) };
#define JPGD_HUFF_EXTEND(x, s) (((x) < s_extend_test[s & 15]) ? ((x) + s_extend_offset[s & 15]) : (x))
// Unconditionally frees all allocated m_blocks.
void jpeg_decoder::free_all_blocks()
{
m_pStream = nullptr;
for (mem_block* b = m_pMem_blocks; b; )
{
mem_block* n = b->m_pNext;
jpgd_free(b);
b = n;
}
m_pMem_blocks = nullptr;
}
// This method handles all errors. It will never return.
// It could easily be changed to use C++ exceptions.
JPGD_NORETURN void jpeg_decoder::stop_decoding(jpgd_status status)
{
m_error_code = status;
free_all_blocks();
longjmp(m_jmp_state, status);
}
void* jpeg_decoder::alloc(size_t nSize, bool zero)
{
nSize = (JPGD_MAX(nSize, 1) + 3) & ~3;
char* rv = nullptr;
for (mem_block* b = m_pMem_blocks; b; b = b->m_pNext)
{
if ((b->m_used_count + nSize) <= b->m_size)
{
rv = b->m_data + b->m_used_count;
b->m_used_count += nSize;
break;
}
}
if (!rv)
{
int capacity = JPGD_MAX(32768 - 256, (nSize + 2047) & ~2047);
mem_block* b = (mem_block*)jpgd_malloc(sizeof(mem_block) + capacity);
if (!b)
{
stop_decoding(JPGD_NOTENOUGHMEM);
}
b->m_pNext = m_pMem_blocks;
m_pMem_blocks = b;
b->m_used_count = nSize;
b->m_size = capacity;
rv = b->m_data;
}
if (zero) memset(rv, 0, nSize);
return rv;
}
void* jpeg_decoder::alloc_aligned(size_t nSize, uint32_t align, bool zero)
{
assert((align >= 1U) && ((align & (align - 1U)) == 0U));
void *p = alloc(nSize + align - 1U, zero);
p = (void *)( ((uintptr_t)p + (align - 1U)) & ~((uintptr_t)(align - 1U)) );
return p;
}
void jpeg_decoder::word_clear(void* p, uint16 c, uint n)
{
uint8* pD = (uint8*)p;
const uint8 l = c & 0xFF, h = (c >> 8) & 0xFF;
while (n)
{
pD[0] = l;
pD[1] = h;
pD += 2;
n--;
}
}
// Refill the input buffer.
// This method will sit in a loop until (A) the buffer is full or (B)
// the stream's read() method reports and end of file condition.
void jpeg_decoder::prep_in_buffer()
{
m_in_buf_left = 0;
m_pIn_buf_ofs = m_in_buf;
if (m_eof_flag)
return;
do
{
int bytes_read = m_pStream->read(m_in_buf + m_in_buf_left, JPGD_IN_BUF_SIZE - m_in_buf_left, &m_eof_flag);
if (bytes_read == -1)
stop_decoding(JPGD_STREAM_READ);
m_in_buf_left += bytes_read;
} while ((m_in_buf_left < JPGD_IN_BUF_SIZE) && (!m_eof_flag));
m_total_bytes_read += m_in_buf_left;
// Pad the end of the block with M_EOI (prevents the decompressor from going off the rails if the stream is invalid).
// (This dates way back to when this decompressor was written in C/asm, and the all-asm Huffman decoder did some fancy things to increase perf.)
word_clear(m_pIn_buf_ofs + m_in_buf_left, 0xD9FF, 64);
}
// Read a Huffman code table.
void jpeg_decoder::read_dht_marker()
{
int i, index, count;
uint8 huff_num[17];
uint8 huff_val[256];
uint num_left = get_bits(16);
if (num_left < 2)
stop_decoding(JPGD_BAD_DHT_MARKER);
num_left -= 2;
while (num_left)
{
index = get_bits(8);
huff_num[0] = 0;
count = 0;
for (i = 1; i <= 16; i++)
{
huff_num[i] = static_cast<uint8>(get_bits(8));
count += huff_num[i];
}
if (count > 255)
stop_decoding(JPGD_BAD_DHT_COUNTS);
bool symbol_present[256];
memset(symbol_present, 0, sizeof(symbol_present));
for (i = 0; i < count; i++)
{
const int s = get_bits(8);
// Check for obviously bogus tables.
if (symbol_present[s])
stop_decoding(JPGD_BAD_DHT_COUNTS);
huff_val[i] = static_cast<uint8_t>(s);
symbol_present[s] = true;
}
i = 1 + 16 + count;
if (num_left < (uint)i)
stop_decoding(JPGD_BAD_DHT_MARKER);
num_left -= i;
if ((index & 0x10) > 0x10)
stop_decoding(JPGD_BAD_DHT_INDEX);
index = (index & 0x0F) + ((index & 0x10) >> 4) * (JPGD_MAX_HUFF_TABLES >> 1);
if (index >= JPGD_MAX_HUFF_TABLES)
stop_decoding(JPGD_BAD_DHT_INDEX);
if (!m_huff_num[index])
m_huff_num[index] = (uint8*)alloc(17);
if (!m_huff_val[index])
m_huff_val[index] = (uint8*)alloc(256);
m_huff_ac[index] = (index & 0x10) != 0;
memcpy(m_huff_num[index], huff_num, 17);
memcpy(m_huff_val[index], huff_val, 256);
}
}
// Read a quantization table.
void jpeg_decoder::read_dqt_marker()
{
int n, i, prec;
uint num_left;
uint temp;
num_left = get_bits(16);
if (num_left < 2)
stop_decoding(JPGD_BAD_DQT_MARKER);
num_left -= 2;
while (num_left)
{
n = get_bits(8);
prec = n >> 4;
n &= 0x0F;
if (n >= JPGD_MAX_QUANT_TABLES)
stop_decoding(JPGD_BAD_DQT_TABLE);
if (!m_quant[n])
m_quant[n] = (jpgd_quant_t*)alloc(64 * sizeof(jpgd_quant_t));
// read quantization entries, in zag order
for (i = 0; i < 64; i++)
{
temp = get_bits(8);
if (prec)
temp = (temp << 8) + get_bits(8);
m_quant[n][i] = static_cast<jpgd_quant_t>(temp);
}
i = 64 + 1;
if (prec)
i += 64;
if (num_left < (uint)i)
stop_decoding(JPGD_BAD_DQT_LENGTH);
num_left -= i;
}
}
// Read the start of frame (SOF) marker.
void jpeg_decoder::read_sof_marker()
{
int i;
uint num_left;
num_left = get_bits(16);
/* precision: sorry, only 8-bit precision is supported */
if (get_bits(8) != 8)
stop_decoding(JPGD_BAD_PRECISION);
m_image_y_size = get_bits(16);
if ((m_image_y_size < 1) || (m_image_y_size > JPGD_MAX_HEIGHT))
stop_decoding(JPGD_BAD_HEIGHT);
m_image_x_size = get_bits(16);
if ((m_image_x_size < 1) || (m_image_x_size > JPGD_MAX_WIDTH))
stop_decoding(JPGD_BAD_WIDTH);
m_comps_in_frame = get_bits(8);
if (m_comps_in_frame > JPGD_MAX_COMPONENTS)
stop_decoding(JPGD_TOO_MANY_COMPONENTS);
if (num_left != (uint)(m_comps_in_frame * 3 + 8))
stop_decoding(JPGD_BAD_SOF_LENGTH);
for (i = 0; i < m_comps_in_frame; i++)
{
m_comp_ident[i] = get_bits(8);
m_comp_h_samp[i] = get_bits(4);
m_comp_v_samp[i] = get_bits(4);
if (!m_comp_h_samp[i] || !m_comp_v_samp[i] || (m_comp_h_samp[i] > 2) || (m_comp_v_samp[i] > 2))
stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
m_comp_quant[i] = get_bits(8);
if (m_comp_quant[i] >= JPGD_MAX_QUANT_TABLES)
stop_decoding(JPGD_DECODE_ERROR);
}
}
// Used to skip unrecognized markers.
void jpeg_decoder::skip_variable_marker()
{
uint num_left;
num_left = get_bits(16);
if (num_left < 2)
stop_decoding(JPGD_BAD_VARIABLE_MARKER);
num_left -= 2;
while (num_left)
{
get_bits(8);
num_left--;
}
}
// Read a define restart interval (DRI) marker.
void jpeg_decoder::read_dri_marker()
{
if (get_bits(16) != 4)
stop_decoding(JPGD_BAD_DRI_LENGTH);
m_restart_interval = get_bits(16);
}
// Read a start of scan (SOS) marker.
void jpeg_decoder::read_sos_marker()
{
uint num_left;
int i, ci, n, c, cc;
num_left = get_bits(16);
n = get_bits(8);
m_comps_in_scan = n;
num_left -= 3;
if ((num_left != (uint)(n * 2 + 3)) || (n < 1) || (n > JPGD_MAX_COMPS_IN_SCAN))
stop_decoding(JPGD_BAD_SOS_LENGTH);
for (i = 0; i < n; i++)
{
cc = get_bits(8);
c = get_bits(8);
num_left -= 2;
for (ci = 0; ci < m_comps_in_frame; ci++)
if (cc == m_comp_ident[ci])
break;
if (ci >= m_comps_in_frame)
stop_decoding(JPGD_BAD_SOS_COMP_ID);
if (ci >= JPGD_MAX_COMPONENTS)
stop_decoding(JPGD_DECODE_ERROR);
m_comp_list[i] = ci;
m_comp_dc_tab[ci] = (c >> 4) & 15;
m_comp_ac_tab[ci] = (c & 15) + (JPGD_MAX_HUFF_TABLES >> 1);
if (m_comp_dc_tab[ci] >= JPGD_MAX_HUFF_TABLES)
stop_decoding(JPGD_DECODE_ERROR);
if (m_comp_ac_tab[ci] >= JPGD_MAX_HUFF_TABLES)
stop_decoding(JPGD_DECODE_ERROR);
}
m_spectral_start = get_bits(8);
m_spectral_end = get_bits(8);
m_successive_high = get_bits(4);
m_successive_low = get_bits(4);
if (!m_progressive_flag)
{
m_spectral_start = 0;
m_spectral_end = 63;
}
num_left -= 3;
/* read past whatever is num_left */
while (num_left)
{
get_bits(8);
num_left--;
}
}
// Finds the next marker.
int jpeg_decoder::next_marker()
{
uint c, bytes;
bytes = 0;
do
{
do
{
bytes++;
c = get_bits(8);
} while (c != 0xFF);