]> git.cworth.org Git - vogl/blob - src/voglcore/vogl_jpgd.cpp
Initial vogl checkin
[vogl] / src / voglcore / vogl_jpgd.cpp
1 /**************************************************************************
2  *
3  * Copyright 2013-2014 RAD Game Tools and Valve Software
4  * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  *
25  **************************************************************************/
26
27 // jpgd.cpp - C++ class for JPEG decompression.
28 // Public domain, Rich Geldreich <richgel99@gmail.com>
29 // Alex Evans: Linear memory allocator (taken from jpge.h).
30 // v1.04, May. 19, 2012: Code tweaks to fix VS2008 static code analysis warnings (all looked harmless)
31 //
32 // Supports progressive and baseline sequential JPEG image files, and the most common chroma subsampling factors: Y, H1V1, H2V1, H1V2, and H2V2.
33 //
34 // Chroma upsampling quality: H2V2 is upsampled in the frequency domain, H2V1 and H1V2 are upsampled using point sampling.
35 // Chroma upsampling reference: "Fast Scheme for Image Size Change in the Compressed Domain"
36 // http://vision.ai.uiuc.edu/~dugad/research/dct/index.html
37
38 #include "vogl_jpgd.h"
39 #include <string.h>
40
41 #include <assert.h>
42 #define JPGD_ASSERT(x) assert(x)
43
44 #ifdef _MSC_VER
45 #pragma warning(disable : 4611) // warning C4611: interaction between '_setjmp' and C++ object destruction is non-portable
46 #endif
47
48 // Set to 1 to enable freq. domain chroma upsampling on images using H2V2 subsampling (0=faster nearest neighbor sampling).
49 // This is slower, but results in higher quality on images with highly saturated colors.
50 #define JPGD_SUPPORT_FREQ_DOMAIN_UPSAMPLING 1
51
52 #define JPGD_TRUE (1)
53 #define JPGD_FALSE (0)
54
55 #define JPGD_MAX(a, b) (((a) > (b)) ? (a) : (b))
56 #define JPGD_MIN(a, b) (((a) < (b)) ? (a) : (b))
57
58 namespace jpgd
59 {
60
61     static inline void *jpgd_malloc(size_t nSize)
62     {
63         return vogl_malloc(nSize);
64     }
65     static inline void jpgd_free(void *p)
66     {
67         vogl_free(p);
68     }
69
70     // DCT coefficients are stored in this sequence.
71     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 };
72
73     enum JPEG_MARKER
74     {
75         M_SOF0 = 0xC0,
76         M_SOF1 = 0xC1,
77         M_SOF2 = 0xC2,
78         M_SOF3 = 0xC3,
79         M_SOF5 = 0xC5,
80         M_SOF6 = 0xC6,
81         M_SOF7 = 0xC7,
82         M_JPG = 0xC8,
83         M_SOF9 = 0xC9,
84         M_SOF10 = 0xCA,
85         M_SOF11 = 0xCB,
86         M_SOF13 = 0xCD,
87         M_SOF14 = 0xCE,
88         M_SOF15 = 0xCF,
89         M_DHT = 0xC4,
90         M_DAC = 0xCC,
91         M_RST0 = 0xD0,
92         M_RST1 = 0xD1,
93         M_RST2 = 0xD2,
94         M_RST3 = 0xD3,
95         M_RST4 = 0xD4,
96         M_RST5 = 0xD5,
97         M_RST6 = 0xD6,
98         M_RST7 = 0xD7,
99         M_SOI = 0xD8,
100         M_EOI = 0xD9,
101         M_SOS = 0xDA,
102         M_DQT = 0xDB,
103         M_DNL = 0xDC,
104         M_DRI = 0xDD,
105         M_DHP = 0xDE,
106         M_EXP = 0xDF,
107         M_APP0 = 0xE0,
108         M_APP15 = 0xEF,
109         M_JPG0 = 0xF0,
110         M_JPG13 = 0xFD,
111         M_COM = 0xFE,
112         M_TEM = 0x01,
113         M_ERROR = 0x100,
114         RST0 = 0xD0
115     };
116
117     enum JPEG_SUBSAMPLING
118     {
119         JPGD_GRAYSCALE = 0,
120         JPGD_YH1V1,
121         JPGD_YH2V1,
122         JPGD_YH1V2,
123         JPGD_YH2V2
124     };
125
126 #define CONST_BITS 13
127 #define PASS1_BITS 2
128 #define SCALEDONE ((int32)1)
129
130 #define FIX_0_298631336 ((int32)2446)  /* FIX(0.298631336) */
131 #define FIX_0_390180644 ((int32)3196)  /* FIX(0.390180644) */
132 #define FIX_0_541196100 ((int32)4433)  /* FIX(0.541196100) */
133 #define FIX_0_765366865 ((int32)6270)  /* FIX(0.765366865) */
134 #define FIX_0_899976223 ((int32)7373)  /* FIX(0.899976223) */
135 #define FIX_1_175875602 ((int32)9633)  /* FIX(1.175875602) */
136 #define FIX_1_501321110 ((int32)12299) /* FIX(1.501321110) */
137 #define FIX_1_847759065 ((int32)15137) /* FIX(1.847759065) */
138 #define FIX_1_961570560 ((int32)16069) /* FIX(1.961570560) */
139 #define FIX_2_053119869 ((int32)16819) /* FIX(2.053119869) */
140 #define FIX_2_562915447 ((int32)20995) /* FIX(2.562915447) */
141 #define FIX_3_072711026 ((int32)25172) /* FIX(3.072711026) */
142
143 #define DESCALE(x, n) (((x) + (SCALEDONE << ((n) - 1))) >> (n))
144 #define DESCALE_ZEROSHIFT(x, n) (((x) + (128 << (n)) + (SCALEDONE << ((n) - 1))) >> (n))
145
146 #define MULTIPLY(var, cnst) ((var) * (cnst))
147
148 #define CLAMP(i) ((static_cast<uint>(i) > 255) ? (((~i) >> 31) & 0xFF) : (i))
149
150     // Compiler creates a fast path 1D IDCT for X non-zero columns
151     template <int NONZERO_COLS>
152     struct Row
153     {
154         static void idct(int *pTemp, const jpgd_block_t *pSrc)
155         {
156 // ACCESS_COL() will be optimized at compile time to either an array access, or 0.
157 #define ACCESS_COL(x) (((x) < NONZERO_COLS) ? (int)pSrc[x] : 0)
158
159             const int z2 = ACCESS_COL(2), z3 = ACCESS_COL(6);
160
161             const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
162             const int tmp2 = z1 + MULTIPLY(z3, -FIX_1_847759065);
163             const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
164
165             const int tmp0 = (ACCESS_COL(0) + ACCESS_COL(4)) << CONST_BITS;
166             const int tmp1 = (ACCESS_COL(0) - ACCESS_COL(4)) << CONST_BITS;
167
168             const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
169
170             const int atmp0 = ACCESS_COL(7), atmp1 = ACCESS_COL(5), atmp2 = ACCESS_COL(3), atmp3 = ACCESS_COL(1);
171
172             const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3;
173             const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602);
174
175             const int az1 = MULTIPLY(bz1, -FIX_0_899976223);
176             const int az2 = MULTIPLY(bz2, -FIX_2_562915447);
177             const int az3 = MULTIPLY(bz3, -FIX_1_961570560) + bz5;
178             const int az4 = MULTIPLY(bz4, -FIX_0_390180644) + bz5;
179
180             const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3;
181             const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4;
182             const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3;
183             const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4;
184
185             pTemp[0] = DESCALE(tmp10 + btmp3, CONST_BITS - PASS1_BITS);
186             pTemp[7] = DESCALE(tmp10 - btmp3, CONST_BITS - PASS1_BITS);
187             pTemp[1] = DESCALE(tmp11 + btmp2, CONST_BITS - PASS1_BITS);
188             pTemp[6] = DESCALE(tmp11 - btmp2, CONST_BITS - PASS1_BITS);
189             pTemp[2] = DESCALE(tmp12 + btmp1, CONST_BITS - PASS1_BITS);
190             pTemp[5] = DESCALE(tmp12 - btmp1, CONST_BITS - PASS1_BITS);
191             pTemp[3] = DESCALE(tmp13 + btmp0, CONST_BITS - PASS1_BITS);
192             pTemp[4] = DESCALE(tmp13 - btmp0, CONST_BITS - PASS1_BITS);
193         }
194     };
195
196     template <>
197     struct Row<0>
198     {
199         static void idct(int *pTemp, const jpgd_block_t *pSrc)
200         {
201             (void)pTemp;
202             (void)pSrc;
203         }
204     };
205
206     template <>
207     struct Row<1>
208     {
209         static void idct(int *pTemp, const jpgd_block_t *pSrc)
210         {
211             const int dcval = (pSrc[0] << PASS1_BITS);
212
213             pTemp[0] = dcval;
214             pTemp[1] = dcval;
215             pTemp[2] = dcval;
216             pTemp[3] = dcval;
217             pTemp[4] = dcval;
218             pTemp[5] = dcval;
219             pTemp[6] = dcval;
220             pTemp[7] = dcval;
221         }
222     };
223
224     // Compiler creates a fast path 1D IDCT for X non-zero rows
225     template <int NONZERO_ROWS>
226     struct Col
227     {
228         static void idct(uint8 *pDst_ptr, const int *pTemp)
229         {
230 // ACCESS_ROW() will be optimized at compile time to either an array access, or 0.
231 #define ACCESS_ROW(x) (((x) < NONZERO_ROWS) ? pTemp[x * 8] : 0)
232
233             const int z2 = ACCESS_ROW(2);
234             const int z3 = ACCESS_ROW(6);
235
236             const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
237             const int tmp2 = z1 + MULTIPLY(z3, -FIX_1_847759065);
238             const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
239
240             const int tmp0 = (ACCESS_ROW(0) + ACCESS_ROW(4)) << CONST_BITS;
241             const int tmp1 = (ACCESS_ROW(0) - ACCESS_ROW(4)) << CONST_BITS;
242
243             const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
244
245             const int atmp0 = ACCESS_ROW(7), atmp1 = ACCESS_ROW(5), atmp2 = ACCESS_ROW(3), atmp3 = ACCESS_ROW(1);
246
247             const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3;
248             const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602);
249
250             const int az1 = MULTIPLY(bz1, -FIX_0_899976223);
251             const int az2 = MULTIPLY(bz2, -FIX_2_562915447);
252             const int az3 = MULTIPLY(bz3, -FIX_1_961570560) + bz5;
253             const int az4 = MULTIPLY(bz4, -FIX_0_390180644) + bz5;
254
255             const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3;
256             const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4;
257             const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3;
258             const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4;
259
260             int i = DESCALE_ZEROSHIFT(tmp10 + btmp3, CONST_BITS + PASS1_BITS + 3);
261             pDst_ptr[8 * 0] = (uint8)CLAMP(i);
262
263             i = DESCALE_ZEROSHIFT(tmp10 - btmp3, CONST_BITS + PASS1_BITS + 3);
264             pDst_ptr[8 * 7] = (uint8)CLAMP(i);
265
266             i = DESCALE_ZEROSHIFT(tmp11 + btmp2, CONST_BITS + PASS1_BITS + 3);
267             pDst_ptr[8 * 1] = (uint8)CLAMP(i);
268
269             i = DESCALE_ZEROSHIFT(tmp11 - btmp2, CONST_BITS + PASS1_BITS + 3);
270             pDst_ptr[8 * 6] = (uint8)CLAMP(i);
271
272             i = DESCALE_ZEROSHIFT(tmp12 + btmp1, CONST_BITS + PASS1_BITS + 3);
273             pDst_ptr[8 * 2] = (uint8)CLAMP(i);
274
275             i = DESCALE_ZEROSHIFT(tmp12 - btmp1, CONST_BITS + PASS1_BITS + 3);
276             pDst_ptr[8 * 5] = (uint8)CLAMP(i);
277
278             i = DESCALE_ZEROSHIFT(tmp13 + btmp0, CONST_BITS + PASS1_BITS + 3);
279             pDst_ptr[8 * 3] = (uint8)CLAMP(i);
280
281             i = DESCALE_ZEROSHIFT(tmp13 - btmp0, CONST_BITS + PASS1_BITS + 3);
282             pDst_ptr[8 * 4] = (uint8)CLAMP(i);
283         }
284     };
285
286     template <>
287     struct Col<1>
288     {
289         static void idct(uint8 *pDst_ptr, const int *pTemp)
290         {
291             int dcval = DESCALE_ZEROSHIFT(pTemp[0], PASS1_BITS + 3);
292             const uint8 dcval_clamped = (uint8)CLAMP(dcval);
293             pDst_ptr[0 * 8] = dcval_clamped;
294             pDst_ptr[1 * 8] = dcval_clamped;
295             pDst_ptr[2 * 8] = dcval_clamped;
296             pDst_ptr[3 * 8] = dcval_clamped;
297             pDst_ptr[4 * 8] = dcval_clamped;
298             pDst_ptr[5 * 8] = dcval_clamped;
299             pDst_ptr[6 * 8] = dcval_clamped;
300             pDst_ptr[7 * 8] = dcval_clamped;
301         }
302     };
303
304     static const uint8 s_idct_row_table[] =
305         {
306             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,
307             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,
308             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,
309             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,
310             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,
311             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,
312             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,
313             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,
314         };
315
316     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 };
317
318     void idct(const jpgd_block_t *pSrc_ptr, uint8 *pDst_ptr, int block_max_zag)
319     {
320         JPGD_ASSERT(block_max_zag >= 1);
321         JPGD_ASSERT(block_max_zag <= 64);
322
323         if (block_max_zag <= 1)
324         {
325             int k = ((pSrc_ptr[0] + 4) >> 3) + 128;
326             k = CLAMP(k);
327             k = k | (k << 8);
328             k = k | (k << 16);
329
330             for (int i = 8; i > 0; i--)
331             {
332                 *(int *)&pDst_ptr[0] = k;
333                 *(int *)&pDst_ptr[4] = k;
334                 pDst_ptr += 8;
335             }
336             return;
337         }
338
339         int temp[64];
340
341         const jpgd_block_t *pSrc = pSrc_ptr;
342         int *pTemp = temp;
343
344         const uint8 *pRow_tab = &s_idct_row_table[(block_max_zag - 1) * 8];
345         int i;
346         for (i = 8; i > 0; i--, pRow_tab++)
347         {
348             switch (*pRow_tab)
349             {
350                 case 0:
351                     Row<0>::idct(pTemp, pSrc);
352                     break;
353                 case 1:
354                     Row<1>::idct(pTemp, pSrc);
355                     break;
356                 case 2:
357                     Row<2>::idct(pTemp, pSrc);
358                     break;
359                 case 3:
360                     Row<3>::idct(pTemp, pSrc);
361                     break;
362                 case 4:
363                     Row<4>::idct(pTemp, pSrc);
364                     break;
365                 case 5:
366                     Row<5>::idct(pTemp, pSrc);
367                     break;
368                 case 6:
369                     Row<6>::idct(pTemp, pSrc);
370                     break;
371                 case 7:
372                     Row<7>::idct(pTemp, pSrc);
373                     break;
374                 case 8:
375                     Row<8>::idct(pTemp, pSrc);
376                     break;
377             }
378
379             pSrc += 8;
380             pTemp += 8;
381         }
382
383         pTemp = temp;
384
385         const int nonzero_rows = s_idct_col_table[block_max_zag - 1];
386         for (i = 8; i > 0; i--)
387         {
388             switch (nonzero_rows)
389             {
390                 case 1:
391                     Col<1>::idct(pDst_ptr, pTemp);
392                     break;
393                 case 2:
394                     Col<2>::idct(pDst_ptr, pTemp);
395                     break;
396                 case 3:
397                     Col<3>::idct(pDst_ptr, pTemp);
398                     break;
399                 case 4:
400                     Col<4>::idct(pDst_ptr, pTemp);
401                     break;
402                 case 5:
403                     Col<5>::idct(pDst_ptr, pTemp);
404                     break;
405                 case 6:
406                     Col<6>::idct(pDst_ptr, pTemp);
407                     break;
408                 case 7:
409                     Col<7>::idct(pDst_ptr, pTemp);
410                     break;
411                 case 8:
412                     Col<8>::idct(pDst_ptr, pTemp);
413                     break;
414             }
415
416             pTemp++;
417             pDst_ptr++;
418         }
419     }
420
421     void idct_4x4(const jpgd_block_t *pSrc_ptr, uint8 *pDst_ptr)
422     {
423         int temp[64];
424         int *pTemp = temp;
425         const jpgd_block_t *pSrc = pSrc_ptr;
426
427         for (int i = 4; i > 0; i--)
428         {
429             Row<4>::idct(pTemp, pSrc);
430             pSrc += 8;
431             pTemp += 8;
432         }
433
434         pTemp = temp;
435         for (int i = 8; i > 0; i--)
436         {
437             Col<4>::idct(pDst_ptr, pTemp);
438             pTemp++;
439             pDst_ptr++;
440         }
441     }
442
443     // Retrieve one character from the input stream.
444     inline uint jpeg_decoder::get_char()
445     {
446         // Any bytes remaining in buffer?
447         if (!m_in_buf_left)
448         {
449             // Try to get more bytes.
450             prep_in_buffer();
451             // Still nothing to get?
452             if (!m_in_buf_left)
453             {
454                 // Pad the end of the stream with 0xFF 0xD9 (EOI marker)
455                 int t = m_tem_flag;
456                 m_tem_flag ^= 1;
457                 if (t)
458                     return 0xD9;
459                 else
460                     return 0xFF;
461             }
462         }
463
464         uint c = *m_pIn_buf_ofs++;
465         m_in_buf_left--;
466
467         return c;
468     }
469
470     // Same as previous method, except can indicate if the character is a pad character or not.
471     inline uint jpeg_decoder::get_char(bool *pPadding_flag)
472     {
473         if (!m_in_buf_left)
474         {
475             prep_in_buffer();
476             if (!m_in_buf_left)
477             {
478                 *pPadding_flag = true;
479                 int t = m_tem_flag;
480                 m_tem_flag ^= 1;
481                 if (t)
482                     return 0xD9;
483                 else
484                     return 0xFF;
485             }
486         }
487
488         *pPadding_flag = false;
489
490         uint c = *m_pIn_buf_ofs++;
491         m_in_buf_left--;
492
493         return c;
494     }
495
496     // Inserts a previously retrieved character back into the input buffer.
497     inline void jpeg_decoder::stuff_char(uint8 q)
498     {
499         *(--m_pIn_buf_ofs) = q;
500         m_in_buf_left++;
501     }
502
503     // Retrieves one character from the input stream, but does not read past markers. Will continue to return 0xFF when a marker is encountered.
504     inline uint8 jpeg_decoder::get_octet()
505     {
506         bool padding_flag;
507         int c = get_char(&padding_flag);
508
509         if (c == 0xFF)
510         {
511             if (padding_flag)
512                 return 0xFF;
513
514             c = get_char(&padding_flag);
515             if (padding_flag)
516             {
517                 stuff_char(0xFF);
518                 return 0xFF;
519             }
520
521             if (c == 0x00)
522                 return 0xFF;
523             else
524             {
525                 stuff_char(static_cast<uint8>(c));
526                 stuff_char(0xFF);
527                 return 0xFF;
528             }
529         }
530
531         return static_cast<uint8>(c);
532     }
533
534     // Retrieves a variable number of bits from the input stream. Does not recognize markers.
535     inline uint jpeg_decoder::get_bits(int num_bits)
536     {
537         if (!num_bits)
538             return 0;
539
540         uint i = m_bit_buf >> (32 - num_bits);
541
542         if ((m_bits_left -= num_bits) <= 0)
543         {
544             m_bit_buf <<= (num_bits += m_bits_left);
545
546             uint c1 = get_char();
547             uint c2 = get_char();
548             m_bit_buf = (m_bit_buf & 0xFFFF0000) | (c1 << 8) | c2;
549
550             m_bit_buf <<= -m_bits_left;
551
552             m_bits_left += 16;
553
554             JPGD_ASSERT(m_bits_left >= 0);
555         }
556         else
557             m_bit_buf <<= num_bits;
558
559         return i;
560     }
561
562     // 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.
563     inline uint jpeg_decoder::get_bits_no_markers(int num_bits)
564     {
565         if (!num_bits)
566             return 0;
567
568         uint i = m_bit_buf >> (32 - num_bits);
569
570         if ((m_bits_left -= num_bits) <= 0)
571         {
572             m_bit_buf <<= (num_bits += m_bits_left);
573
574             if ((m_in_buf_left < 2) || (m_pIn_buf_ofs[0] == 0xFF) || (m_pIn_buf_ofs[1] == 0xFF))
575             {
576                 uint c1 = get_octet();
577                 uint c2 = get_octet();
578                 m_bit_buf |= (c1 << 8) | c2;
579             }
580             else
581             {
582                 m_bit_buf |= ((uint)m_pIn_buf_ofs[0] << 8) | m_pIn_buf_ofs[1];
583                 m_in_buf_left -= 2;
584                 m_pIn_buf_ofs += 2;
585             }
586
587             m_bit_buf <<= -m_bits_left;
588
589             m_bits_left += 16;
590
591             JPGD_ASSERT(m_bits_left >= 0);
592         }
593         else
594             m_bit_buf <<= num_bits;
595
596         return i;
597     }
598
599     // Decodes a Huffman encoded symbol.
600     inline int jpeg_decoder::huff_decode(huff_tables *pH)
601     {
602         int symbol;
603
604         // Check first 8-bits: do we have a complete symbol?
605         if ((symbol = pH->look_up[m_bit_buf >> 24]) < 0)
606         {
607             // Decode more bits, use a tree traversal to find symbol.
608             int ofs = 23;
609             do
610             {
611                 symbol = pH->tree[-(int)(symbol + ((m_bit_buf >> ofs) & 1))];
612                 ofs--;
613             } while (symbol < 0);
614
615             get_bits_no_markers(8 + (23 - ofs));
616         }
617         else
618             get_bits_no_markers(pH->code_size[symbol]);
619
620         return symbol;
621     }
622
623     // Decodes a Huffman encoded symbol.
624     inline int jpeg_decoder::huff_decode(huff_tables *pH, int &extra_bits)
625     {
626         int symbol;
627
628         // Check first 8-bits: do we have a complete symbol?
629         if ((symbol = pH->look_up2[m_bit_buf >> 24]) < 0)
630         {
631             // Use a tree traversal to find symbol.
632             int ofs = 23;
633             do
634             {
635                 symbol = pH->tree[-(int)(symbol + ((m_bit_buf >> ofs) & 1))];
636                 ofs--;
637             } while (symbol < 0);
638
639             get_bits_no_markers(8 + (23 - ofs));
640
641             extra_bits = get_bits_no_markers(symbol & 0xF);
642         }
643         else
644         {
645             JPGD_ASSERT(((symbol >> 8) & 31) == pH->code_size[symbol & 255] + ((symbol & 0x8000) ? (symbol & 15) : 0));
646
647             if (symbol & 0x8000)
648             {
649                 get_bits_no_markers((symbol >> 8) & 31);
650                 extra_bits = symbol >> 16;
651             }
652             else
653             {
654                 int code_size = (symbol >> 8) & 31;
655                 int num_extra_bits = symbol & 0xF;
656                 int bits = code_size + num_extra_bits;
657                 if (bits <= (m_bits_left + 16))
658                     extra_bits = get_bits_no_markers(bits) & ((1 << num_extra_bits) - 1);
659                 else
660                 {
661                     get_bits_no_markers(code_size);
662                     extra_bits = get_bits_no_markers(num_extra_bits);
663                 }
664             }
665
666             symbol &= 0xFF;
667         }
668
669         return symbol;
670     }
671
672     // Tables and macro used to fully decode the DPCM differences.
673     static const int s_extend_test[16] = { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
674     static const int s_extend_offset[16] = { 0, ((-1) << 1) + 1, ((-1) << 2) + 1, ((-1) << 3) + 1, ((-1) << 4) + 1, ((-1) << 5) + 1, ((-1) << 6) + 1, ((-1) << 7) + 1, ((-1) << 8) + 1, ((-1) << 9) + 1, ((-1) << 10) + 1, ((-1) << 11) + 1, ((-1) << 12) + 1, ((-1) << 13) + 1, ((-1) << 14) + 1, ((-1) << 15) + 1 };
675     // 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) };
676 // The logical AND's in this macro are to shut up static code analysis (aren't really necessary - couldn't find another way to do this)
677 #define JPGD_HUFF_EXTEND(x, s) (((x) < s_extend_test[s & 15]) ? ((x) + s_extend_offset[s & 15]) : (x))
678
679     // Clamps a value between 0-255.
680     inline uint8 jpeg_decoder::clamp(int i)
681     {
682         if (static_cast<uint>(i) > 255)
683             i = (((~i) >> 31) & 0xFF);
684
685         return static_cast<uint8>(i);
686     }
687
688     namespace DCT_Upsample
689     {
690         struct Matrix44
691         {
692             typedef int Element_Type;
693             enum
694             {
695                 NUM_ROWS = 4,
696                 NUM_COLS = 4
697             };
698
699             Element_Type v[NUM_ROWS][NUM_COLS];
700
701             inline int rows() const
702             {
703                 return NUM_ROWS;
704             }
705             inline int cols() const
706             {
707                 return NUM_COLS;
708             }
709
710             inline const Element_Type &at(int r, int c) const
711             {
712                 return v[r][c];
713             }
714             inline Element_Type &at(int r, int c)
715             {
716                 return v[r][c];
717             }
718
719             inline Matrix44()
720             {
721             }
722
723             inline Matrix44 &operator+=(const Matrix44 &a)
724             {
725                 for (int r = 0; r < NUM_ROWS; r++)
726                 {
727                     at(r, 0) += a.at(r, 0);
728                     at(r, 1) += a.at(r, 1);
729                     at(r, 2) += a.at(r, 2);
730                     at(r, 3) += a.at(r, 3);
731                 }
732                 return *this;
733             }
734
735             inline Matrix44 &operator-=(const Matrix44 &a)
736             {
737                 for (int r = 0; r < NUM_ROWS; r++)
738                 {
739                     at(r, 0) -= a.at(r, 0);
740                     at(r, 1) -= a.at(r, 1);
741                     at(r, 2) -= a.at(r, 2);
742                     at(r, 3) -= a.at(r, 3);
743                 }
744                 return *this;
745             }
746
747             friend inline Matrix44 operator+(const Matrix44 &a, const Matrix44 &b)
748             {
749                 Matrix44 ret;
750                 for (int r = 0; r < NUM_ROWS; r++)
751                 {
752                     ret.at(r, 0) = a.at(r, 0) + b.at(r, 0);
753                     ret.at(r, 1) = a.at(r, 1) + b.at(r, 1);
754                     ret.at(r, 2) = a.at(r, 2) + b.at(r, 2);
755                     ret.at(r, 3) = a.at(r, 3) + b.at(r, 3);
756                 }
757                 return ret;
758             }
759
760             friend inline Matrix44 operator-(const Matrix44 &a, const Matrix44 &b)
761             {
762                 Matrix44 ret;
763                 for (int r = 0; r < NUM_ROWS; r++)
764                 {
765                     ret.at(r, 0) = a.at(r, 0) - b.at(r, 0);
766                     ret.at(r, 1) = a.at(r, 1) - b.at(r, 1);
767                     ret.at(r, 2) = a.at(r, 2) - b.at(r, 2);
768                     ret.at(r, 3) = a.at(r, 3) - b.at(r, 3);
769                 }
770                 return ret;
771             }
772
773             static inline void add_and_store(jpgd_block_t *pDst, const Matrix44 &a, const Matrix44 &b)
774             {
775                 for (int r = 0; r < 4; r++)
776                 {
777                     pDst[0 * 8 + r] = static_cast<jpgd_block_t>(a.at(r, 0) + b.at(r, 0));
778                     pDst[1 * 8 + r] = static_cast<jpgd_block_t>(a.at(r, 1) + b.at(r, 1));
779                     pDst[2 * 8 + r] = static_cast<jpgd_block_t>(a.at(r, 2) + b.at(r, 2));
780                     pDst[3 * 8 + r] = static_cast<jpgd_block_t>(a.at(r, 3) + b.at(r, 3));
781                 }
782             }
783
784             static inline void sub_and_store(jpgd_block_t *pDst, const Matrix44 &a, const Matrix44 &b)
785             {
786                 for (int r = 0; r < 4; r++)
787                 {
788                     pDst[0 * 8 + r] = static_cast<jpgd_block_t>(a.at(r, 0) - b.at(r, 0));
789                     pDst[1 * 8 + r] = static_cast<jpgd_block_t>(a.at(r, 1) - b.at(r, 1));
790                     pDst[2 * 8 + r] = static_cast<jpgd_block_t>(a.at(r, 2) - b.at(r, 2));
791                     pDst[3 * 8 + r] = static_cast<jpgd_block_t>(a.at(r, 3) - b.at(r, 3));
792                 }
793             }
794         };
795
796         const int FRACT_BITS = 10;
797         const int SCALE = 1 << FRACT_BITS;
798
799         typedef int Temp_Type;
800 #define D(i) (((i) + (SCALE >> 1)) >> FRACT_BITS)
801 #define F(i) ((int)((i) * SCALE + .5f))
802
803 // Any decent C++ compiler will optimize this at compile time to a 0, or an array access.
804 #define AT(c, r) ((((c) >= NUM_COLS) || ((r) >= NUM_ROWS)) ? 0 : pSrc[(c) + (r) * 8])
805
806         // NUM_ROWS/NUM_COLS = # of non-zero rows/cols in input matrix
807         template <int NUM_ROWS, int NUM_COLS>
808         struct P_Q
809         {
810             static void calc(Matrix44 &P, Matrix44 &Q, const jpgd_block_t *pSrc)
811             {
812                 // 4x8 = 4x8 times 8x8, matrix 0 is constant
813                 const Temp_Type X000 = AT(0, 0);
814                 const Temp_Type X001 = AT(0, 1);
815                 const Temp_Type X002 = AT(0, 2);
816                 const Temp_Type X003 = AT(0, 3);
817                 const Temp_Type X004 = AT(0, 4);
818                 const Temp_Type X005 = AT(0, 5);
819                 const Temp_Type X006 = AT(0, 6);
820                 const Temp_Type X007 = AT(0, 7);
821                 const Temp_Type X010 = D(F(0.415735f) * AT(1, 0) + F(0.791065f) * AT(3, 0) + F(-0.352443f) * AT(5, 0) + F(0.277785f) * AT(7, 0));
822                 const Temp_Type X011 = D(F(0.415735f) * AT(1, 1) + F(0.791065f) * AT(3, 1) + F(-0.352443f) * AT(5, 1) + F(0.277785f) * AT(7, 1));
823                 const Temp_Type X012 = D(F(0.415735f) * AT(1, 2) + F(0.791065f) * AT(3, 2) + F(-0.352443f) * AT(5, 2) + F(0.277785f) * AT(7, 2));
824                 const Temp_Type X013 = D(F(0.415735f) * AT(1, 3) + F(0.791065f) * AT(3, 3) + F(-0.352443f) * AT(5, 3) + F(0.277785f) * AT(7, 3));
825                 const Temp_Type X014 = D(F(0.415735f) * AT(1, 4) + F(0.791065f) * AT(3, 4) + F(-0.352443f) * AT(5, 4) + F(0.277785f) * AT(7, 4));
826                 const Temp_Type X015 = D(F(0.415735f) * AT(1, 5) + F(0.791065f) * AT(3, 5) + F(-0.352443f) * AT(5, 5) + F(0.277785f) * AT(7, 5));
827                 const Temp_Type X016 = D(F(0.415735f) * AT(1, 6) + F(0.791065f) * AT(3, 6) + F(-0.352443f) * AT(5, 6) + F(0.277785f) * AT(7, 6));
828                 const Temp_Type X017 = D(F(0.415735f) * AT(1, 7) + F(0.791065f) * AT(3, 7) + F(-0.352443f) * AT(5, 7) + F(0.277785f) * AT(7, 7));
829                 const Temp_Type X020 = AT(4, 0);
830                 const Temp_Type X021 = AT(4, 1);
831                 const Temp_Type X022 = AT(4, 2);
832                 const Temp_Type X023 = AT(4, 3);
833                 const Temp_Type X024 = AT(4, 4);
834                 const Temp_Type X025 = AT(4, 5);
835                 const Temp_Type X026 = AT(4, 6);
836                 const Temp_Type X027 = AT(4, 7);
837                 const Temp_Type X030 = D(F(0.022887f) * AT(1, 0) + F(-0.097545f) * AT(3, 0) + F(0.490393f) * AT(5, 0) + F(0.865723f) * AT(7, 0));
838                 const Temp_Type X031 = D(F(0.022887f) * AT(1, 1) + F(-0.097545f) * AT(3, 1) + F(0.490393f) * AT(5, 1) + F(0.865723f) * AT(7, 1));
839                 const Temp_Type X032 = D(F(0.022887f) * AT(1, 2) + F(-0.097545f) * AT(3, 2) + F(0.490393f) * AT(5, 2) + F(0.865723f) * AT(7, 2));
840                 const Temp_Type X033 = D(F(0.022887f) * AT(1, 3) + F(-0.097545f) * AT(3, 3) + F(0.490393f) * AT(5, 3) + F(0.865723f) * AT(7, 3));
841                 const Temp_Type X034 = D(F(0.022887f) * AT(1, 4) + F(-0.097545f) * AT(3, 4) + F(0.490393f) * AT(5, 4) + F(0.865723f) * AT(7, 4));
842                 const Temp_Type X035 = D(F(0.022887f) * AT(1, 5) + F(-0.097545f) * AT(3, 5) + F(0.490393f) * AT(5, 5) + F(0.865723f) * AT(7, 5));
843                 const Temp_Type X036 = D(F(0.022887f) * AT(1, 6) + F(-0.097545f) * AT(3, 6) + F(0.490393f) * AT(5, 6) + F(0.865723f) * AT(7, 6));
844                 const Temp_Type X037 = D(F(0.022887f) * AT(1, 7) + F(-0.097545f) * AT(3, 7) + F(0.490393f) * AT(5, 7) + F(0.865723f) * AT(7, 7));
845
846                 // 4x4 = 4x8 times 8x4, matrix 1 is constant
847                 P.at(0, 0) = X000;
848                 P.at(0, 1) = D(X001 * F(0.415735f) + X003 * F(0.791065f) + X005 * F(-0.352443f) + X007 * F(0.277785f));
849                 P.at(0, 2) = X004;
850                 P.at(0, 3) = D(X001 * F(0.022887f) + X003 * F(-0.097545f) + X005 * F(0.490393f) + X007 * F(0.865723f));
851                 P.at(1, 0) = X010;
852                 P.at(1, 1) = D(X011 * F(0.415735f) + X013 * F(0.791065f) + X015 * F(-0.352443f) + X017 * F(0.277785f));
853                 P.at(1, 2) = X014;
854                 P.at(1, 3) = D(X011 * F(0.022887f) + X013 * F(-0.097545f) + X015 * F(0.490393f) + X017 * F(0.865723f));
855                 P.at(2, 0) = X020;
856                 P.at(2, 1) = D(X021 * F(0.415735f) + X023 * F(0.791065f) + X025 * F(-0.352443f) + X027 * F(0.277785f));
857                 P.at(2, 2) = X024;
858                 P.at(2, 3) = D(X021 * F(0.022887f) + X023 * F(-0.097545f) + X025 * F(0.490393f) + X027 * F(0.865723f));
859                 P.at(3, 0) = X030;
860                 P.at(3, 1) = D(X031 * F(0.415735f) + X033 * F(0.791065f) + X035 * F(-0.352443f) + X037 * F(0.277785f));
861                 P.at(3, 2) = X034;
862                 P.at(3, 3) = D(X031 * F(0.022887f) + X033 * F(-0.097545f) + X035 * F(0.490393f) + X037 * F(0.865723f));
863                 // 40 muls 24 adds
864
865                 // 4x4 = 4x8 times 8x4, matrix 1 is constant
866                 Q.at(0, 0) = D(X001 * F(0.906127f) + X003 * F(-0.318190f) + X005 * F(0.212608f) + X007 * F(-0.180240f));
867                 Q.at(0, 1) = X002;
868                 Q.at(0, 2) = D(X001 * F(-0.074658f) + X003 * F(0.513280f) + X005 * F(0.768178f) + X007 * F(-0.375330f));
869                 Q.at(0, 3) = X006;
870                 Q.at(1, 0) = D(X011 * F(0.906127f) + X013 * F(-0.318190f) + X015 * F(0.212608f) + X017 * F(-0.180240f));
871                 Q.at(1, 1) = X012;
872                 Q.at(1, 2) = D(X011 * F(-0.074658f) + X013 * F(0.513280f) + X015 * F(0.768178f) + X017 * F(-0.375330f));
873                 Q.at(1, 3) = X016;
874                 Q.at(2, 0) = D(X021 * F(0.906127f) + X023 * F(-0.318190f) + X025 * F(0.212608f) + X027 * F(-0.180240f));
875                 Q.at(2, 1) = X022;
876                 Q.at(2, 2) = D(X021 * F(-0.074658f) + X023 * F(0.513280f) + X025 * F(0.768178f) + X027 * F(-0.375330f));
877                 Q.at(2, 3) = X026;
878                 Q.at(3, 0) = D(X031 * F(0.906127f) + X033 * F(-0.318190f) + X035 * F(0.212608f) + X037 * F(-0.180240f));
879                 Q.at(3, 1) = X032;
880                 Q.at(3, 2) = D(X031 * F(-0.074658f) + X033 * F(0.513280f) + X035 * F(0.768178f) + X037 * F(-0.375330f));
881                 Q.at(3, 3) = X036;
882                 // 40 muls 24 adds
883             }
884         };
885
886         template <int NUM_ROWS, int NUM_COLS>
887         struct R_S
888         {
889             static void calc(Matrix44 &R, Matrix44 &S, const jpgd_block_t *pSrc)
890             {
891                 // 4x8 = 4x8 times 8x8, matrix 0 is constant
892                 const Temp_Type X100 = D(F(0.906127f) * AT(1, 0) + F(-0.318190f) * AT(3, 0) + F(0.212608f) * AT(5, 0) + F(-0.180240f) * AT(7, 0));
893                 const Temp_Type X101 = D(F(0.906127f) * AT(1, 1) + F(-0.318190f) * AT(3, 1) + F(0.212608f) * AT(5, 1) + F(-0.180240f) * AT(7, 1));
894                 const Temp_Type X102 = D(F(0.906127f) * AT(1, 2) + F(-0.318190f) * AT(3, 2) + F(0.212608f) * AT(5, 2) + F(-0.180240f) * AT(7, 2));
895                 const Temp_Type X103 = D(F(0.906127f) * AT(1, 3) + F(-0.318190f) * AT(3, 3) + F(0.212608f) * AT(5, 3) + F(-0.180240f) * AT(7, 3));
896                 const Temp_Type X104 = D(F(0.906127f) * AT(1, 4) + F(-0.318190f) * AT(3, 4) + F(0.212608f) * AT(5, 4) + F(-0.180240f) * AT(7, 4));
897                 const Temp_Type X105 = D(F(0.906127f) * AT(1, 5) + F(-0.318190f) * AT(3, 5) + F(0.212608f) * AT(5, 5) + F(-0.180240f) * AT(7, 5));
898                 const Temp_Type X106 = D(F(0.906127f) * AT(1, 6) + F(-0.318190f) * AT(3, 6) + F(0.212608f) * AT(5, 6) + F(-0.180240f) * AT(7, 6));
899                 const Temp_Type X107 = D(F(0.906127f) * AT(1, 7) + F(-0.318190f) * AT(3, 7) + F(0.212608f) * AT(5, 7) + F(-0.180240f) * AT(7, 7));
900                 const Temp_Type X110 = AT(2, 0);
901                 const Temp_Type X111 = AT(2, 1);
902                 const Temp_Type X112 = AT(2, 2);
903                 const Temp_Type X113 = AT(2, 3);
904                 const Temp_Type X114 = AT(2, 4);
905                 const Temp_Type X115 = AT(2, 5);
906                 const Temp_Type X116 = AT(2, 6);
907                 const Temp_Type X117 = AT(2, 7);
908                 const Temp_Type X120 = D(F(-0.074658f) * AT(1, 0) + F(0.513280f) * AT(3, 0) + F(0.768178f) * AT(5, 0) + F(-0.375330f) * AT(7, 0));
909                 const Temp_Type X121 = D(F(-0.074658f) * AT(1, 1) + F(0.513280f) * AT(3, 1) + F(0.768178f) * AT(5, 1) + F(-0.375330f) * AT(7, 1));
910                 const Temp_Type X122 = D(F(-0.074658f) * AT(1, 2) + F(0.513280f) * AT(3, 2) + F(0.768178f) * AT(5, 2) + F(-0.375330f) * AT(7, 2));
911                 const Temp_Type X123 = D(F(-0.074658f) * AT(1, 3) + F(0.513280f) * AT(3, 3) + F(0.768178f) * AT(5, 3) + F(-0.375330f) * AT(7, 3));
912                 const Temp_Type X124 = D(F(-0.074658f) * AT(1, 4) + F(0.513280f) * AT(3, 4) + F(0.768178f) * AT(5, 4) + F(-0.375330f) * AT(7, 4));
913                 const Temp_Type X125 = D(F(-0.074658f) * AT(1, 5) + F(0.513280f) * AT(3, 5) + F(0.768178f) * AT(5, 5) + F(-0.375330f) * AT(7, 5));
914                 const Temp_Type X126 = D(F(-0.074658f) * AT(1, 6) + F(0.513280f) * AT(3, 6) + F(0.768178f) * AT(5, 6) + F(-0.375330f) * AT(7, 6));
915                 const Temp_Type X127 = D(F(-0.074658f) * AT(1, 7) + F(0.513280f) * AT(3, 7) + F(0.768178f) * AT(5, 7) + F(-0.375330f) * AT(7, 7));
916                 const Temp_Type X130 = AT(6, 0);
917                 const Temp_Type X131 = AT(6, 1);
918                 const Temp_Type X132 = AT(6, 2);
919                 const Temp_Type X133 = AT(6, 3);
920                 const Temp_Type X134 = AT(6, 4);
921                 const Temp_Type X135 = AT(6, 5);
922                 const Temp_Type X136 = AT(6, 6);
923                 const Temp_Type X137 = AT(6, 7);
924                 // 80 muls 48 adds
925
926                 // 4x4 = 4x8 times 8x4, matrix 1 is constant
927                 R.at(0, 0) = X100;
928                 R.at(0, 1) = D(X101 * F(0.415735f) + X103 * F(0.791065f) + X105 * F(-0.352443f) + X107 * F(0.277785f));
929                 R.at(0, 2) = X104;
930                 R.at(0, 3) = D(X101 * F(0.022887f) + X103 * F(-0.097545f) + X105 * F(0.490393f) + X107 * F(0.865723f));
931                 R.at(1, 0) = X110;
932                 R.at(1, 1) = D(X111 * F(0.415735f) + X113 * F(0.791065f) + X115 * F(-0.352443f) + X117 * F(0.277785f));
933                 R.at(1, 2) = X114;
934                 R.at(1, 3) = D(X111 * F(0.022887f) + X113 * F(-0.097545f) + X115 * F(0.490393f) + X117 * F(0.865723f));
935                 R.at(2, 0) = X120;
936                 R.at(2, 1) = D(X121 * F(0.415735f) + X123 * F(0.791065f) + X125 * F(-0.352443f) + X127 * F(0.277785f));
937                 R.at(2, 2) = X124;
938                 R.at(2, 3) = D(X121 * F(0.022887f) + X123 * F(-0.097545f) + X125 * F(0.490393f) + X127 * F(0.865723f));
939                 R.at(3, 0) = X130;
940                 R.at(3, 1) = D(X131 * F(0.415735f) + X133 * F(0.791065f) + X135 * F(-0.352443f) + X137 * F(0.277785f));
941                 R.at(3, 2) = X134;
942                 R.at(3, 3) = D(X131 * F(0.022887f) + X133 * F(-0.097545f) + X135 * F(0.490393f) + X137 * F(0.865723f));
943                 // 40 muls 24 adds
944                 // 4x4 = 4x8 times 8x4, matrix 1 is constant
945                 S.at(0, 0) = D(X101 * F(0.906127f) + X103 * F(-0.318190f) + X105 * F(0.212608f) + X107 * F(-0.180240f));
946                 S.at(0, 1) = X102;
947                 S.at(0, 2) = D(X101 * F(-0.074658f) + X103 * F(0.513280f) + X105 * F(0.768178f) + X107 * F(-0.375330f));
948                 S.at(0, 3) = X106;
949                 S.at(1, 0) = D(X111 * F(0.906127f) + X113 * F(-0.318190f) + X115 * F(0.212608f) + X117 * F(-0.180240f));
950                 S.at(1, 1) = X112;
951                 S.at(1, 2) = D(X111 * F(-0.074658f) + X113 * F(0.513280f) + X115 * F(0.768178f) + X117 * F(-0.375330f));
952                 S.at(1, 3) = X116;
953                 S.at(2, 0) = D(X121 * F(0.906127f) + X123 * F(-0.318190f) + X125 * F(0.212608f) + X127 * F(-0.180240f));
954                 S.at(2, 1) = X122;
955                 S.at(2, 2) = D(X121 * F(-0.074658f) + X123 * F(0.513280f) + X125 * F(0.768178f) + X127 * F(-0.375330f));
956                 S.at(2, 3) = X126;
957                 S.at(3, 0) = D(X131 * F(0.906127f) + X133 * F(-0.318190f) + X135 * F(0.212608f) + X137 * F(-0.180240f));
958                 S.at(3, 1) = X132;
959                 S.at(3, 2) = D(X131 * F(-0.074658f) + X133 * F(0.513280f) + X135 * F(0.768178f) + X137 * F(-0.375330f));
960                 S.at(3, 3) = X136;
961                 // 40 muls 24 adds
962             }
963         };
964     } // end namespace DCT_Upsample
965
966     // Unconditionally frees all allocated m_blocks.
967     void jpeg_decoder::free_all_blocks()
968     {
969         m_pStream = NULL;
970         for (mem_block *b = m_pMem_blocks; b;)
971         {
972             mem_block *n = b->m_pNext;
973             jpgd_free(b);
974             b = n;
975         }
976         m_pMem_blocks = NULL;
977     }
978
979     // This method handles all errors. It will never return.
980     // It could easily be changed to use C++ exceptions.
981     JPGD_NORETURN void jpeg_decoder::stop_decoding(jpgd_status status)
982     {
983         m_error_code = status;
984         free_all_blocks();
985         longjmp(m_jmp_state, status);
986     }
987
988     void *jpeg_decoder::alloc(size_t nSize, bool zero)
989     {
990         nSize = (JPGD_MAX(nSize, 1) + 3) & ~3;
991         char *rv = NULL;
992         for (mem_block *b = m_pMem_blocks; b; b = b->m_pNext)
993         {
994             if ((b->m_used_count + nSize) <= b->m_size)
995             {
996                 rv = b->m_data + b->m_used_count;
997                 b->m_used_count += nSize;
998                 break;
999             }
1000         }
1001         if (!rv)
1002         {
1003             int capacity = JPGD_MAX(32768 - 256, (static_cast<int>(nSize) + 2047) & ~2047);
1004             mem_block *b = (mem_block *)jpgd_malloc(sizeof(mem_block) + capacity);
1005             if (!b)
1006             {
1007                 stop_decoding(JPGD_NOTENOUGHMEM);
1008             }
1009             b->m_pNext = m_pMem_blocks;
1010             m_pMem_blocks = b;
1011             b->m_used_count = nSize;
1012             b->m_size = capacity;
1013             rv = b->m_data;
1014         }
1015         if (zero)
1016             memset(rv, 0, nSize);
1017         return rv;
1018     }
1019
1020     void jpeg_decoder::word_clear(void *p, uint16 c, uint n)
1021     {
1022         uint8 *pD = (uint8 *)p;
1023         const uint8 l = c & 0xFF, h = (c >> 8) & 0xFF;
1024         while (n)
1025         {
1026             pD[0] = l;
1027             pD[1] = h;
1028             pD += 2;
1029             n--;
1030         }
1031     }
1032
1033     // Refill the input buffer.
1034     // This method will sit in a loop until (A) the buffer is full or (B)
1035     // the stream's read() method reports and end of file condition.
1036     void jpeg_decoder::prep_in_buffer()
1037     {
1038         m_in_buf_left = 0;
1039         m_pIn_buf_ofs = m_in_buf;
1040
1041         if (m_eof_flag)
1042             return;
1043
1044         do
1045         {
1046             int bytes_read = m_pStream->read(m_in_buf + m_in_buf_left, JPGD_IN_BUF_SIZE - m_in_buf_left, &m_eof_flag);
1047             if (bytes_read == -1)
1048                 stop_decoding(JPGD_STREAM_READ);
1049
1050             m_in_buf_left += bytes_read;
1051         } while ((m_in_buf_left < JPGD_IN_BUF_SIZE) && (!m_eof_flag));
1052
1053         m_total_bytes_read += m_in_buf_left;
1054
1055         // Pad the end of the block with M_EOI (prevents the decompressor from going off the rails if the stream is invalid).
1056         // (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.)
1057         word_clear(m_pIn_buf_ofs + m_in_buf_left, 0xD9FF, 64);
1058     }
1059
1060     // Read a Huffman code table.
1061     void jpeg_decoder::read_dht_marker()
1062     {
1063         int i, index, count;
1064         uint8 huff_num[17];
1065         uint8 huff_val[256];
1066
1067         uint num_left = get_bits(16);
1068
1069         if (num_left < 2)
1070             stop_decoding(JPGD_BAD_DHT_MARKER);
1071
1072         num_left -= 2;
1073
1074         while (num_left)
1075         {
1076             index = get_bits(8);
1077
1078             huff_num[0] = 0;
1079
1080             count = 0;
1081
1082             for (i = 1; i <= 16; i++)
1083             {
1084                 huff_num[i] = static_cast<uint8>(get_bits(8));
1085                 count += huff_num[i];
1086             }
1087
1088             if (count > 255)
1089                 stop_decoding(JPGD_BAD_DHT_COUNTS);
1090
1091             for (i = 0; i < count; i++)
1092                 huff_val[i] = static_cast<uint8>(get_bits(8));
1093
1094             i = 1 + 16 + count;
1095
1096             if (num_left < (uint)i)
1097                 stop_decoding(JPGD_BAD_DHT_MARKER);
1098
1099             num_left -= i;
1100
1101             if ((index & 0x10) > 0x10)
1102                 stop_decoding(JPGD_BAD_DHT_INDEX);
1103
1104             index = (index & 0x0F) + ((index & 0x10) >> 4) * (JPGD_MAX_HUFF_TABLES >> 1);
1105
1106             if (index >= JPGD_MAX_HUFF_TABLES)
1107                 stop_decoding(JPGD_BAD_DHT_INDEX);
1108
1109             if (!m_huff_num[index])
1110                 m_huff_num[index] = (uint8 *)alloc(17);
1111
1112             if (!m_huff_val[index])
1113                 m_huff_val[index] = (uint8 *)alloc(256);
1114
1115             m_huff_ac[index] = (index & 0x10) != 0;
1116             memcpy(m_huff_num[index], huff_num, 17);
1117             memcpy(m_huff_val[index], huff_val, 256);
1118         }
1119     }
1120
1121     // Read a quantization table.
1122     void jpeg_decoder::read_dqt_marker()
1123     {
1124         int n, i, prec;
1125         uint num_left;
1126         uint temp;
1127
1128         num_left = get_bits(16);
1129
1130         if (num_left < 2)
1131             stop_decoding(JPGD_BAD_DQT_MARKER);
1132
1133         num_left -= 2;
1134
1135         while (num_left)
1136         {
1137             n = get_bits(8);
1138             prec = n >> 4;
1139             n &= 0x0F;
1140
1141             if (n >= JPGD_MAX_QUANT_TABLES)
1142                 stop_decoding(JPGD_BAD_DQT_TABLE);
1143
1144             if (!m_quant[n])
1145                 m_quant[n] = (jpgd_quant_t *)alloc(64 * sizeof(jpgd_quant_t));
1146
1147             // read quantization entries, in zag order
1148             for (i = 0; i < 64; i++)
1149             {
1150                 temp = get_bits(8);
1151
1152                 if (prec)
1153                     temp = (temp << 8) + get_bits(8);
1154
1155                 m_quant[n][i] = static_cast<jpgd_quant_t>(temp);
1156             }
1157
1158             i = 64 + 1;
1159
1160             if (prec)
1161                 i += 64;
1162
1163             if (num_left < (uint)i)
1164                 stop_decoding(JPGD_BAD_DQT_LENGTH);
1165
1166             num_left -= i;
1167         }
1168     }
1169
1170     // Read the start of frame (SOF) marker.
1171     void jpeg_decoder::read_sof_marker()
1172     {
1173         int i;
1174         uint num_left;
1175
1176         num_left = get_bits(16);
1177
1178         if (get_bits(8) != 8) /* precision: sorry, only 8-bit precision is supported right now */
1179             stop_decoding(JPGD_BAD_PRECISION);
1180
1181         m_image_y_size = get_bits(16);
1182
1183         if ((m_image_y_size < 1) || (m_image_y_size > JPGD_MAX_HEIGHT))
1184             stop_decoding(JPGD_BAD_HEIGHT);
1185
1186         m_image_x_size = get_bits(16);
1187
1188         if ((m_image_x_size < 1) || (m_image_x_size > JPGD_MAX_WIDTH))
1189             stop_decoding(JPGD_BAD_WIDTH);
1190
1191         m_comps_in_frame = get_bits(8);
1192
1193         if (m_comps_in_frame > JPGD_MAX_COMPONENTS)
1194             stop_decoding(JPGD_TOO_MANY_COMPONENTS);
1195
1196         if (num_left != (uint)(m_comps_in_frame * 3 + 8))
1197             stop_decoding(JPGD_BAD_SOF_LENGTH);
1198
1199         for (i = 0; i < m_comps_in_frame; i++)
1200         {
1201             m_comp_ident[i] = get_bits(8);
1202             m_comp_h_samp[i] = get_bits(4);
1203             m_comp_v_samp[i] = get_bits(4);
1204             m_comp_quant[i] = get_bits(8);
1205         }
1206     }
1207
1208     // Used to skip unrecognized markers.
1209     void jpeg_decoder::skip_variable_marker()
1210     {
1211         uint num_left;
1212
1213         num_left = get_bits(16);
1214
1215         if (num_left < 2)
1216             stop_decoding(JPGD_BAD_VARIABLE_MARKER);
1217
1218         num_left -= 2;
1219
1220         while (num_left)
1221         {
1222             get_bits(8);
1223             num_left--;
1224         }
1225     }
1226
1227     // Read a define restart interval (DRI) marker.
1228     void jpeg_decoder::read_dri_marker()
1229     {
1230         if (get_bits(16) != 4)
1231             stop_decoding(JPGD_BAD_DRI_LENGTH);
1232
1233         m_restart_interval = get_bits(16);
1234     }
1235
1236     // Read a start of scan (SOS) marker.
1237     void jpeg_decoder::read_sos_marker()
1238     {
1239         uint num_left;
1240         int i, ci, n, c, cc;
1241
1242         num_left = get_bits(16);
1243
1244         n = get_bits(8);
1245
1246         m_comps_in_scan = n;
1247
1248         num_left -= 3;
1249
1250         if ((num_left != (uint)(n * 2 + 3)) || (n < 1) || (n > JPGD_MAX_COMPS_IN_SCAN))
1251             stop_decoding(JPGD_BAD_SOS_LENGTH);
1252
1253         for (i = 0; i < n; i++)
1254         {
1255             cc = get_bits(8);
1256             c = get_bits(8);
1257             num_left -= 2;
1258
1259             for (ci = 0; ci < m_comps_in_frame; ci++)
1260                 if (cc == m_comp_ident[ci])
1261                     break;
1262
1263             if (ci >= m_comps_in_frame)
1264                 stop_decoding(JPGD_BAD_SOS_COMP_ID);
1265
1266             m_comp_list[i] = ci;
1267             m_comp_dc_tab[ci] = (c >> 4) & 15;
1268             m_comp_ac_tab[ci] = (c & 15) + (JPGD_MAX_HUFF_TABLES >> 1);
1269         }
1270
1271         m_spectral_start = get_bits(8);
1272         m_spectral_end = get_bits(8);
1273         m_successive_high = get_bits(4);
1274         m_successive_low = get_bits(4);
1275
1276         if (!m_progressive_flag)
1277         {
1278             m_spectral_start = 0;
1279             m_spectral_end = 63;
1280         }
1281
1282         num_left -= 3;
1283
1284         while (num_left) /* read past whatever is num_left */
1285         {
1286             get_bits(8);
1287             num_left--;
1288         }
1289     }
1290
1291     // Finds the next marker.
1292     int jpeg_decoder::next_marker()
1293     {
1294         uint c, bytes;
1295
1296         bytes = 0;
1297
1298         do
1299         {
1300             do
1301             {
1302                 bytes++;
1303                 c = get_bits(8);
1304             } while (c != 0xFF);
1305
1306             do
1307             {
1308                 c = get_bits(8);
1309             } while (c == 0xFF);
1310
1311         } while (c == 0);
1312
1313         // If bytes > 0 here, there where extra bytes before the marker (not good).
1314
1315         return c;
1316     }
1317
1318     // Process markers. Returns when an SOFx, SOI, EOI, or SOS marker is
1319     // encountered.
1320     int jpeg_decoder::process_markers()
1321     {
1322         int c;
1323
1324         for (;;)
1325         {
1326             c = next_marker();
1327
1328             switch (c)
1329             {
1330                 case M_SOF0:
1331                 case M_SOF1:
1332                 case M_SOF2:
1333                 case M_SOF3:
1334                 case M_SOF5:
1335                 case M_SOF6:
1336                 case M_SOF7:
1337                 //      case M_JPG:
1338                 case M_SOF9:
1339                 case M_SOF10:
1340                 case M_SOF11:
1341                 case M_SOF13:
1342                 case M_SOF14:
1343                 case M_SOF15:
1344                 case M_SOI:
1345                 case M_EOI:
1346                 case M_SOS:
1347                 {
1348                     return c;
1349                 }
1350                 case M_DHT:
1351                 {
1352                     read_dht_marker();
1353                     break;
1354                 }
1355                 // No arithmitic support - dumb patents!
1356                 case M_DAC:
1357                 {
1358                     stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT);
1359                     break;
1360                 }
1361                 case M_DQT:
1362                 {
1363                     read_dqt_marker();
1364                     break;
1365                 }
1366                 case M_DRI:
1367                 {
1368                     read_dri_marker();
1369                     break;
1370                 }
1371                 //case M_APP0:  /* no need to read the JFIF marker */
1372
1373                 case M_JPG:
1374                 case M_RST0: /* no parameters */
1375                 case M_RST1:
1376                 case M_RST2:
1377                 case M_RST3:
1378                 case M_RST4:
1379                 case M_RST5:
1380                 case M_RST6:
1381                 case M_RST7:
1382                 case M_TEM:
1383                 {
1384                     stop_decoding(JPGD_UNEXPECTED_MARKER);
1385                     break;
1386                 }
1387                 default: /* must be DNL, DHP, EXP, APPn, JPGn, COM, or RESn or APP0 */
1388                 {
1389                     skip_variable_marker();
1390                     break;
1391                 }
1392             }
1393         }
1394     }
1395
1396     // Finds the start of image (SOI) marker.
1397     // This code is rather defensive: it only checks the first 512 bytes to avoid
1398     // false positives.
1399     void jpeg_decoder::locate_soi_marker()
1400     {
1401         uint lastchar, thischar;
1402         uint bytesleft;
1403
1404         lastchar = get_bits(8);
1405
1406         thischar = get_bits(8);
1407
1408         /* ok if it's a normal JPEG file without a special header */
1409
1410         if ((lastchar == 0xFF) && (thischar == M_SOI))
1411             return;
1412
1413         bytesleft = 4096; //512;
1414
1415         for (;;)
1416         {
1417             if (--bytesleft == 0)
1418                 stop_decoding(JPGD_NOT_JPEG);
1419
1420             lastchar = thischar;
1421
1422             thischar = get_bits(8);
1423
1424             if (lastchar == 0xFF)
1425             {
1426                 if (thischar == M_SOI)
1427                     break;
1428                 else if (thischar == M_EOI) // get_bits will keep returning M_EOI if we read past the end
1429                     stop_decoding(JPGD_NOT_JPEG);
1430             }
1431         }
1432
1433         // Check the next character after marker: if it's not 0xFF, it can't be the start of the next marker, so the file is bad.
1434         thischar = (m_bit_buf >> 24) & 0xFF;
1435
1436         if (thischar != 0xFF)
1437             stop_decoding(JPGD_NOT_JPEG);
1438     }
1439
1440     // Find a start of frame (SOF) marker.
1441     void jpeg_decoder::locate_sof_marker()
1442     {
1443         locate_soi_marker();
1444
1445         int c = process_markers();
1446
1447         switch (c)
1448         {
1449             case M_SOF2:
1450                 m_progressive_flag = JPGD_TRUE;
1451             case M_SOF0: /* baseline DCT */
1452             case M_SOF1: /* extended sequential DCT */
1453             {
1454                 read_sof_marker();
1455                 break;
1456             }
1457             case M_SOF9: /* Arithmitic coding */
1458             {
1459                 stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT);
1460                 break;
1461             }
1462             default:
1463             {
1464                 stop_decoding(JPGD_UNSUPPORTED_MARKER);
1465                 break;
1466             }
1467         }
1468     }
1469
1470     // Find a start of scan (SOS) marker.
1471     int jpeg_decoder::locate_sos_marker()
1472     {
1473         int c;
1474
1475         c = process_markers();
1476
1477         if (c == M_EOI)
1478             return JPGD_FALSE;
1479         else if (c != M_SOS)
1480             stop_decoding(JPGD_UNEXPECTED_MARKER);
1481
1482         read_sos_marker();
1483
1484         return JPGD_TRUE;
1485     }
1486
1487     // Reset everything to default/uninitialized state.
1488     void jpeg_decoder::init(jpeg_decoder_stream *pStream)
1489     {
1490         m_pMem_blocks = NULL;
1491         m_error_code = JPGD_SUCCESS;
1492         m_ready_flag = false;
1493         m_image_x_size = m_image_y_size = 0;
1494         m_pStream = pStream;
1495         m_progressive_flag = JPGD_FALSE;
1496
1497         memset(m_huff_ac, 0, sizeof(m_huff_ac));
1498         memset(m_huff_num, 0, sizeof(m_huff_num));
1499         memset(m_huff_val, 0, sizeof(m_huff_val));
1500         memset(m_quant, 0, sizeof(m_quant));
1501
1502         m_scan_type = 0;
1503         m_comps_in_frame = 0;
1504
1505         memset(m_comp_h_samp, 0, sizeof(m_comp_h_samp));
1506         memset(m_comp_v_samp, 0, sizeof(m_comp_v_samp));
1507         memset(m_comp_quant, 0, sizeof(m_comp_quant));
1508         memset(m_comp_ident, 0, sizeof(m_comp_ident));
1509         memset(m_comp_h_blocks, 0, sizeof(m_comp_h_blocks));
1510         memset(m_comp_v_blocks, 0, sizeof(m_comp_v_blocks));
1511
1512         m_comps_in_scan = 0;
1513         memset(m_comp_list, 0, sizeof(m_comp_list));
1514         memset(m_comp_dc_tab, 0, sizeof(m_comp_dc_tab));
1515         memset(m_comp_ac_tab, 0, sizeof(m_comp_ac_tab));
1516
1517         m_spectral_start = 0;
1518         m_spectral_end = 0;
1519         m_successive_low = 0;
1520         m_successive_high = 0;
1521         m_max_mcu_x_size = 0;
1522         m_max_mcu_y_size = 0;
1523         m_blocks_per_mcu = 0;
1524         m_max_blocks_per_row = 0;
1525         m_mcus_per_row = 0;
1526         m_mcus_per_col = 0;
1527         m_expanded_blocks_per_component = 0;
1528         m_expanded_blocks_per_mcu = 0;
1529         m_expanded_blocks_per_row = 0;
1530         m_freq_domain_chroma_upsample = false;
1531
1532         memset(m_mcu_org, 0, sizeof(m_mcu_org));
1533
1534         m_total_lines_left = 0;
1535         m_mcu_lines_left = 0;
1536         m_real_dest_bytes_per_scan_line = 0;
1537         m_dest_bytes_per_scan_line = 0;
1538         m_dest_bytes_per_pixel = 0;
1539
1540         memset(m_pHuff_tabs, 0, sizeof(m_pHuff_tabs));
1541
1542         memset(m_dc_coeffs, 0, sizeof(m_dc_coeffs));
1543         memset(m_ac_coeffs, 0, sizeof(m_ac_coeffs));
1544         memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu));
1545
1546         m_eob_run = 0;
1547
1548         memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu));
1549
1550         m_pIn_buf_ofs = m_in_buf;
1551         m_in_buf_left = 0;
1552         m_eof_flag = false;
1553         m_tem_flag = 0;
1554
1555         memset(m_in_buf_pad_start, 0, sizeof(m_in_buf_pad_start));
1556         memset(m_in_buf, 0, sizeof(m_in_buf));
1557         memset(m_in_buf_pad_end, 0, sizeof(m_in_buf_pad_end));
1558
1559         m_restart_interval = 0;
1560         m_restarts_left = 0;
1561         m_next_restart_num = 0;
1562
1563         m_max_mcus_per_row = 0;
1564         m_max_blocks_per_mcu = 0;
1565         m_max_mcus_per_col = 0;
1566
1567         memset(m_last_dc_val, 0, sizeof(m_last_dc_val));
1568         m_pMCU_coefficients = NULL;
1569         m_pSample_buf = NULL;
1570
1571         m_total_bytes_read = 0;
1572
1573         m_pScan_line_0 = NULL;
1574         m_pScan_line_1 = NULL;
1575
1576         // Ready the input buffer.
1577         prep_in_buffer();
1578
1579         // Prime the bit buffer.
1580         m_bits_left = 16;
1581         m_bit_buf = 0;
1582
1583         get_bits(16);
1584         get_bits(16);
1585
1586         for (int i = 0; i < JPGD_MAX_BLOCKS_PER_MCU; i++)
1587             m_mcu_block_max_zag[i] = 64;
1588     }
1589
1590 #define SCALEBITS 16
1591 #define ONE_HALF ((int)1 << (SCALEBITS - 1))
1592 #define FIX(x) ((int)((x) * (1L << SCALEBITS) + 0.5f))
1593
1594     // Create a few tables that allow us to quickly convert YCbCr to RGB.
1595     void jpeg_decoder::create_look_ups()
1596     {
1597         for (int i = 0; i <= 255; i++)
1598         {
1599             int k = i - 128;
1600             m_crr[i] = (FIX(1.40200f) * k + ONE_HALF) >> SCALEBITS;
1601             m_cbb[i] = (FIX(1.77200f) * k + ONE_HALF) >> SCALEBITS;
1602             m_crg[i] = (-FIX(0.71414f)) * k;
1603             m_cbg[i] = (-FIX(0.34414f)) * k + ONE_HALF;
1604         }
1605     }
1606
1607     // This method throws back into the stream any bytes that where read
1608     // into the bit buffer during initial marker scanning.
1609     void jpeg_decoder::fix_in_buffer()
1610     {
1611         // In case any 0xFF's where pulled into the buffer during marker scanning.
1612         JPGD_ASSERT((m_bits_left & 7) == 0);
1613
1614         if (m_bits_left == 16)
1615             stuff_char((uint8)(m_bit_buf & 0xFF));
1616
1617         if (m_bits_left >= 8)
1618             stuff_char((uint8)((m_bit_buf >> 8) & 0xFF));
1619
1620         stuff_char((uint8)((m_bit_buf >> 16) & 0xFF));
1621         stuff_char((uint8)((m_bit_buf >> 24) & 0xFF));
1622
1623         m_bits_left = 16;
1624         get_bits_no_markers(16);
1625         get_bits_no_markers(16);
1626     }
1627
1628     void jpeg_decoder::transform_mcu(int mcu_row)
1629     {
1630         jpgd_block_t *pSrc_ptr = m_pMCU_coefficients;
1631         uint8 *pDst_ptr = m_pSample_buf + mcu_row * m_blocks_per_mcu * 64;
1632
1633         for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
1634         {
1635             idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]);
1636             pSrc_ptr += 64;
1637             pDst_ptr += 64;
1638         }
1639     }
1640
1641     static const uint8 s_max_rc[64] =
1642         {
1643             17, 18, 34, 50, 50, 51, 52, 52, 52, 68, 84, 84, 84, 84, 85, 86, 86, 86, 86, 86,
1644             102, 118, 118, 118, 118, 118, 118, 119, 120, 120, 120, 120, 120, 120, 120, 136,
1645             136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136,
1646             136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136
1647         };
1648
1649     void jpeg_decoder::transform_mcu_expand(int mcu_row)
1650     {
1651         jpgd_block_t *pSrc_ptr = m_pMCU_coefficients;
1652         uint8 *pDst_ptr = m_pSample_buf + mcu_row * m_expanded_blocks_per_mcu * 64;
1653
1654         // Y IDCT
1655         int mcu_block;
1656         for (mcu_block = 0; mcu_block < m_expanded_blocks_per_component; mcu_block++)
1657         {
1658             idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]);
1659             pSrc_ptr += 64;
1660             pDst_ptr += 64;
1661         }
1662
1663         // Chroma IDCT, with upsampling
1664         jpgd_block_t temp_block[64];
1665
1666         for (int i = 0; i < 2; i++)
1667         {
1668             DCT_Upsample::Matrix44 P, Q, R, S;
1669
1670             JPGD_ASSERT(m_mcu_block_max_zag[mcu_block] >= 1);
1671             JPGD_ASSERT(m_mcu_block_max_zag[mcu_block] <= 64);
1672
1673             int max_zag = m_mcu_block_max_zag[mcu_block++] - 1;
1674             if (max_zag <= 0)
1675                 max_zag = 0; // should never happen, only here to shut up static analysis
1676             switch (s_max_rc[max_zag])
1677             {
1678                 case 1 * 16 + 1:
1679                     DCT_Upsample::P_Q<1, 1>::calc(P, Q, pSrc_ptr);
1680                     DCT_Upsample::R_S<1, 1>::calc(R, S, pSrc_ptr);
1681                     break;
1682                 case 1 * 16 + 2:
1683                     DCT_Upsample::P_Q<1, 2>::calc(P, Q, pSrc_ptr);
1684                     DCT_Upsample::R_S<1, 2>::calc(R, S, pSrc_ptr);
1685                     break;
1686                 case 2 * 16 + 2:
1687                     DCT_Upsample::P_Q<2, 2>::calc(P, Q, pSrc_ptr);
1688                     DCT_Upsample::R_S<2, 2>::calc(R, S, pSrc_ptr);
1689                     break;
1690                 case 3 * 16 + 2:
1691                     DCT_Upsample::P_Q<3, 2>::calc(P, Q, pSrc_ptr);
1692                     DCT_Upsample::R_S<3, 2>::calc(R, S, pSrc_ptr);
1693                     break;
1694                 case 3 * 16 + 3:
1695                     DCT_Upsample::P_Q<3, 3>::calc(P, Q, pSrc_ptr);
1696                     DCT_Upsample::R_S<3, 3>::calc(R, S, pSrc_ptr);
1697                     break;
1698                 case 3 * 16 + 4:
1699                     DCT_Upsample::P_Q<3, 4>::calc(P, Q, pSrc_ptr);
1700                     DCT_Upsample::R_S<3, 4>::calc(R, S, pSrc_ptr);
1701                     break;
1702                 case 4 * 16 + 4:
1703                     DCT_Upsample::P_Q<4, 4>::calc(P, Q, pSrc_ptr);
1704                     DCT_Upsample::R_S<4, 4>::calc(R, S, pSrc_ptr);
1705                     break;
1706                 case 5 * 16 + 4:
1707                     DCT_Upsample::P_Q<5, 4>::calc(P, Q, pSrc_ptr);
1708                     DCT_Upsample::R_S<5, 4>::calc(R, S, pSrc_ptr);
1709                     break;
1710                 case 5 * 16 + 5:
1711                     DCT_Upsample::P_Q<5, 5>::calc(P, Q, pSrc_ptr);
1712                     DCT_Upsample::R_S<5, 5>::calc(R, S, pSrc_ptr);
1713                     break;
1714                 case 5 * 16 + 6:
1715                     DCT_Upsample::P_Q<5, 6>::calc(P, Q, pSrc_ptr);
1716                     DCT_Upsample::R_S<5, 6>::calc(R, S, pSrc_ptr);
1717                     break;
1718                 case 6 * 16 + 6:
1719                     DCT_Upsample::P_Q<6, 6>::calc(P, Q, pSrc_ptr);
1720                     DCT_Upsample::R_S<6, 6>::calc(R, S, pSrc_ptr);
1721                     break;
1722                 case 7 * 16 + 6:
1723                     DCT_Upsample::P_Q<7, 6>::calc(P, Q, pSrc_ptr);
1724                     DCT_Upsample::R_S<7, 6>::calc(R, S, pSrc_ptr);
1725                     break;
1726                 case 7 * 16 + 7:
1727                     DCT_Upsample::P_Q<7, 7>::calc(P, Q, pSrc_ptr);
1728                     DCT_Upsample::R_S<7, 7>::calc(R, S, pSrc_ptr);
1729                     break;
1730                 case 7 * 16 + 8:
1731                     DCT_Upsample::P_Q<7, 8>::calc(P, Q, pSrc_ptr);
1732                     DCT_Upsample::R_S<7, 8>::calc(R, S, pSrc_ptr);
1733                     break;
1734                 case 8 * 16 + 8:
1735                     DCT_Upsample::P_Q<8, 8>::calc(P, Q, pSrc_ptr);
1736                     DCT_Upsample::R_S<8, 8>::calc(R, S, pSrc_ptr);
1737                     break;
1738                 default:
1739                     JPGD_ASSERT(false);
1740             }
1741
1742             DCT_Upsample::Matrix44 a(P + Q);
1743             P -= Q;
1744             DCT_Upsample::Matrix44 &b = P;
1745             DCT_Upsample::Matrix44 c(R + S);
1746             R -= S;
1747             DCT_Upsample::Matrix44 &d = R;
1748
1749             DCT_Upsample::Matrix44::add_and_store(temp_block, a, c);
1750             idct_4x4(temp_block, pDst_ptr);
1751             pDst_ptr += 64;
1752
1753             DCT_Upsample::Matrix44::sub_and_store(temp_block, a, c);
1754             idct_4x4(temp_block, pDst_ptr);
1755             pDst_ptr += 64;
1756
1757             DCT_Upsample::Matrix44::add_and_store(temp_block, b, d);
1758             idct_4x4(temp_block, pDst_ptr);
1759             pDst_ptr += 64;
1760
1761             DCT_Upsample::Matrix44::sub_and_store(temp_block, b, d);
1762             idct_4x4(temp_block, pDst_ptr);
1763             pDst_ptr += 64;
1764
1765             pSrc_ptr += 64;
1766         }
1767     }
1768
1769     // Loads and dequantizes the next row of (already decoded) coefficients.
1770     // Progressive images only.
1771     void jpeg_decoder::load_next_row()
1772     {
1773         int i;
1774         jpgd_block_t *p;
1775         jpgd_quant_t *q;
1776         int mcu_row, mcu_block, row_block = 0;
1777         int component_num, component_id;
1778         int block_x_mcu[JPGD_MAX_COMPONENTS];
1779
1780         memset(block_x_mcu, 0, JPGD_MAX_COMPONENTS * sizeof(int));
1781
1782         for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
1783         {
1784             int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0;
1785
1786             for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
1787             {
1788                 component_id = m_mcu_org[mcu_block];
1789                 q = m_quant[m_comp_quant[component_id]];
1790
1791                 p = m_pMCU_coefficients + 64 * mcu_block;
1792
1793                 jpgd_block_t *pAC = coeff_buf_getp(m_ac_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
1794                 jpgd_block_t *pDC = coeff_buf_getp(m_dc_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
1795                 p[0] = pDC[0];
1796                 memcpy(&p[1], &pAC[1], 63 * sizeof(jpgd_block_t));
1797
1798                 for (i = 63; i > 0; i--)
1799                     if (p[g_ZAG[i]])
1800                         break;
1801
1802                 m_mcu_block_max_zag[mcu_block] = i + 1;
1803
1804                 for (; i >= 0; i--)
1805                     if (p[g_ZAG[i]])
1806                         p[g_ZAG[i]] = static_cast<jpgd_block_t>(p[g_ZAG[i]] * q[i]);
1807
1808                 row_block++;
1809
1810                 if (m_comps_in_scan == 1)
1811                     block_x_mcu[component_id]++;
1812                 else
1813                 {
1814                     if (++block_x_mcu_ofs == m_comp_h_samp[component_id])
1815                     {
1816                         block_x_mcu_ofs = 0;
1817
1818                         if (++block_y_mcu_ofs == m_comp_v_samp[component_id])
1819                         {
1820                             block_y_mcu_ofs = 0;
1821
1822                             block_x_mcu[component_id] += m_comp_h_samp[component_id];
1823                         }
1824                     }
1825                 }
1826             }
1827
1828             if (m_freq_domain_chroma_upsample)
1829                 transform_mcu_expand(mcu_row);
1830             else
1831                 transform_mcu(mcu_row);
1832         }
1833
1834         if (m_comps_in_scan == 1)
1835             m_block_y_mcu[m_comp_list[0]]++;
1836         else
1837         {
1838             for (component_num = 0; component_num < m_comps_in_scan; component_num++)
1839             {
1840                 component_id = m_comp_list[component_num];
1841
1842                 m_block_y_mcu[component_id] += m_comp_v_samp[component_id];
1843             }
1844         }
1845     }
1846
1847     // Restart interval processing.
1848     void jpeg_decoder::process_restart()
1849     {
1850         int i;
1851         int c = 0;
1852
1853         // Align to a byte boundry
1854         // FIXME: Is this really necessary? get_bits_no_markers() never reads in markers!
1855         //get_bits_no_markers(m_bits_left & 7);
1856
1857         // Let's scan a little bit to find the marker, but not _too_ far.
1858         // 1536 is a "fudge factor" that determines how much to scan.
1859         for (i = 1536; i > 0; i--)
1860             if (get_char() == 0xFF)
1861                 break;
1862
1863         if (i == 0)
1864             stop_decoding(JPGD_BAD_RESTART_MARKER);
1865
1866         for (; i > 0; i--)
1867             if ((c = get_char()) != 0xFF)
1868                 break;
1869
1870         if (i == 0)
1871             stop_decoding(JPGD_BAD_RESTART_MARKER);
1872
1873         // Is it the expected marker? If not, something bad happened.
1874         if (c != (m_next_restart_num + M_RST0))
1875             stop_decoding(JPGD_BAD_RESTART_MARKER);
1876
1877         // Reset each component's DC prediction values.
1878         memset(&m_last_dc_val, 0, m_comps_in_frame * sizeof(uint));
1879
1880         m_eob_run = 0;
1881
1882         m_restarts_left = m_restart_interval;
1883
1884         m_next_restart_num = (m_next_restart_num + 1) & 7;
1885
1886         // Get the bit buffer going again...
1887
1888         m_bits_left = 16;
1889         get_bits_no_markers(16);
1890         get_bits_no_markers(16);
1891     }
1892
1893     static inline int dequantize_ac(int c, int q)
1894     {
1895         c *= q;
1896         return c;
1897     }
1898
1899     // Decodes and dequantizes the next row of coefficients.
1900     void jpeg_decoder::decode_next_row()
1901     {
1902         int row_block = 0;
1903
1904         for (int mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
1905         {
1906             if ((m_restart_interval) && (m_restarts_left == 0))
1907                 process_restart();
1908
1909             jpgd_block_t *p = m_pMCU_coefficients;
1910             for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++, p += 64)
1911             {
1912                 int component_id = m_mcu_org[mcu_block];
1913                 jpgd_quant_t *q = m_quant[m_comp_quant[component_id]];
1914
1915                 int r, s;
1916                 s = huff_decode(m_pHuff_tabs[m_comp_dc_tab[component_id]], r);
1917                 s = JPGD_HUFF_EXTEND(r, s);
1918
1919                 m_last_dc_val[component_id] = (s += m_last_dc_val[component_id]);
1920
1921                 p[0] = static_cast<jpgd_block_t>(s * q[0]);
1922
1923                 int prev_num_set = m_mcu_block_max_zag[mcu_block];
1924
1925                 huff_tables *pH = m_pHuff_tabs[m_comp_ac_tab[component_id]];
1926
1927                 int k;
1928                 for (k = 1; k < 64; k++)
1929                 {
1930                     int extra_bits;
1931                     s = huff_decode(pH, extra_bits);
1932
1933                     r = s >> 4;
1934                     s &= 15;
1935
1936                     if (s)
1937                     {
1938                         if (r)
1939                         {
1940                             if ((k + r) > 63)
1941                                 stop_decoding(JPGD_DECODE_ERROR);
1942
1943                             if (k < prev_num_set)
1944                             {
1945                                 int n = JPGD_MIN(r, prev_num_set - k);
1946                                 int kt = k;
1947                                 while (n--)
1948                                     p[g_ZAG[kt++]] = 0;
1949                             }
1950
1951                             k += r;
1952                         }
1953
1954                         s = JPGD_HUFF_EXTEND(extra_bits, s);
1955
1956                         JPGD_ASSERT(k < 64);
1957
1958                         p[g_ZAG[k]] = static_cast<jpgd_block_t>(dequantize_ac(s, q[k])); //s * q[k];
1959                     }
1960                     else
1961                     {
1962                         if (r == 15)
1963                         {
1964                             if ((k + 16) > 64)
1965                                 stop_decoding(JPGD_DECODE_ERROR);
1966
1967                             if (k < prev_num_set)
1968                             {
1969                                 int n = JPGD_MIN(16, prev_num_set - k);
1970                                 int kt = k;
1971                                 while (n--)
1972                                 {
1973                                     JPGD_ASSERT(kt <= 63);
1974                                     p[g_ZAG[kt++]] = 0;
1975                                 }
1976                             }
1977
1978                             k += 16 - 1; // - 1 because the loop counter is k
1979                             JPGD_ASSERT(p[g_ZAG[k]] == 0);
1980                         }
1981                         else
1982                             break;
1983                     }
1984                 }
1985
1986                 if (k < prev_num_set)
1987                 {
1988                     int kt = k;
1989                     while (kt < prev_num_set)
1990                         p[g_ZAG[kt++]] = 0;
1991                 }
1992
1993                 m_mcu_block_max_zag[mcu_block] = k;
1994
1995                 row_block++;
1996             }
1997
1998             if (m_freq_domain_chroma_upsample)
1999                 transform_mcu_expand(mcu_row);
2000             else
2001                 transform_mcu(mcu_row);
2002
2003             m_restarts_left--;
2004         }
2005     }
2006
2007     // YCbCr H1V1 (1x1:1:1, 3 m_blocks per MCU) to RGB
2008     void jpeg_decoder::H1V1Convert()
2009     {
2010         int row = m_max_mcu_y_size - m_mcu_lines_left;
2011         uint8 *d = m_pScan_line_0;
2012         uint8 *s = m_pSample_buf + row * 8;
2013
2014         for (int i = m_max_mcus_per_row; i > 0; i--)
2015         {
2016             for (int j = 0; j < 8; j++)
2017             {
2018                 int y = s[j];
2019                 int cb = s[64 + j];
2020                 int cr = s[128 + j];
2021
2022                 d[0] = clamp(y + m_crr[cr]);
2023                 d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
2024                 d[2] = clamp(y + m_cbb[cb]);
2025                 d[3] = 255;
2026
2027                 d += 4;
2028             }
2029
2030             s += 64 * 3;
2031         }
2032     }
2033
2034     // YCbCr H2V1 (2x1:1:1, 4 m_blocks per MCU) to RGB
2035     void jpeg_decoder::H2V1Convert()
2036     {
2037         int row = m_max_mcu_y_size - m_mcu_lines_left;
2038         uint8 *d0 = m_pScan_line_0;
2039         uint8 *y = m_pSample_buf + row * 8;
2040         uint8 *c = m_pSample_buf + 2 * 64 + row * 8;
2041
2042         for (int i = m_max_mcus_per_row; i > 0; i--)
2043         {
2044             for (int l = 0; l < 2; l++)
2045             {
2046                 for (int j = 0; j < 4; j++)
2047                 {
2048                     int cb = c[0];
2049                     int cr = c[64];
2050
2051                     int rc = m_crr[cr];
2052                     int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
2053                     int bc = m_cbb[cb];
2054
2055                     int yy = y[j << 1];
2056                     d0[0] = clamp(yy + rc);
2057                     d0[1] = clamp(yy + gc);
2058                     d0[2] = clamp(yy + bc);
2059                     d0[3] = 255;
2060
2061                     yy = y[(j << 1) + 1];
2062                     d0[4] = clamp(yy + rc);
2063                     d0[5] = clamp(yy + gc);
2064                     d0[6] = clamp(yy + bc);
2065                     d0[7] = 255;
2066
2067                     d0 += 8;
2068
2069                     c++;
2070                 }
2071                 y += 64;
2072             }
2073
2074             y += 64 * 4 - 64 * 2;
2075             c += 64 * 4 - 8;
2076         }
2077     }
2078
2079     // YCbCr H2V1 (1x2:1:1, 4 m_blocks per MCU) to RGB
2080     void jpeg_decoder::H1V2Convert()
2081     {
2082         int row = m_max_mcu_y_size - m_mcu_lines_left;
2083         uint8 *d0 = m_pScan_line_0;
2084         uint8 *d1 = m_pScan_line_1;
2085         uint8 *y;
2086         uint8 *c;
2087
2088         if (row < 8)
2089             y = m_pSample_buf + row * 8;
2090         else
2091             y = m_pSample_buf + 64 * 1 + (row & 7) * 8;
2092
2093         c = m_pSample_buf + 64 * 2 + (row >> 1) * 8;
2094
2095         for (int i = m_max_mcus_per_row; i > 0; i--)
2096         {
2097             for (int j = 0; j < 8; j++)
2098             {
2099                 int cb = c[0 + j];
2100                 int cr = c[64 + j];
2101
2102                 int rc = m_crr[cr];
2103                 int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
2104                 int bc = m_cbb[cb];
2105
2106                 int yy = y[j];
2107                 d0[0] = clamp(yy + rc);
2108                 d0[1] = clamp(yy + gc);
2109                 d0[2] = clamp(yy + bc);
2110                 d0[3] = 255;
2111
2112                 yy = y[8 + j];
2113                 d1[0] = clamp(yy + rc);
2114                 d1[1] = clamp(yy + gc);
2115                 d1[2] = clamp(yy + bc);
2116                 d1[3] = 255;
2117
2118                 d0 += 4;
2119                 d1 += 4;
2120             }
2121
2122             y += 64 * 4;
2123             c += 64 * 4;
2124         }
2125     }
2126
2127     // YCbCr H2V2 (2x2:1:1, 6 m_blocks per MCU) to RGB
2128     void jpeg_decoder::H2V2Convert()
2129     {
2130         int row = m_max_mcu_y_size - m_mcu_lines_left;
2131         uint8 *d0 = m_pScan_line_0;
2132         uint8 *d1 = m_pScan_line_1;
2133         uint8 *y;
2134         uint8 *c;
2135
2136         if (row < 8)
2137             y = m_pSample_buf + row * 8;
2138         else
2139             y = m_pSample_buf + 64 * 2 + (row & 7) * 8;
2140
2141         c = m_pSample_buf + 64 * 4 + (row >> 1) * 8;
2142
2143         for (int i = m_max_mcus_per_row; i > 0; i--)
2144         {
2145             for (int l = 0; l < 2; l++)
2146             {
2147                 for (int j = 0; j < 8; j += 2)
2148                 {
2149                     int cb = c[0];
2150                     int cr = c[64];
2151
2152                     int rc = m_crr[cr];
2153                     int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
2154                     int bc = m_cbb[cb];
2155
2156                     int yy = y[j];
2157                     d0[0] = clamp(yy + rc);
2158                     d0[1] = clamp(yy + gc);
2159                     d0[2] = clamp(yy + bc);
2160                     d0[3] = 255;
2161
2162                     yy = y[j + 1];
2163                     d0[4] = clamp(yy + rc);
2164                     d0[5] = clamp(yy + gc);
2165                     d0[6] = clamp(yy + bc);
2166                     d0[7] = 255;
2167
2168                     yy = y[j + 8];
2169                     d1[0] = clamp(yy + rc);
2170                     d1[1] = clamp(yy + gc);
2171                     d1[2] = clamp(yy + bc);
2172                     d1[3] = 255;
2173
2174                     yy = y[j + 8 + 1];
2175                     d1[4] = clamp(yy + rc);
2176                     d1[5] = clamp(yy + gc);
2177                     d1[6] = clamp(yy + bc);
2178                     d1[7] = 255;
2179
2180                     d0 += 8;
2181                     d1 += 8;
2182
2183                     c++;
2184                 }
2185                 y += 64;
2186             }
2187
2188             y += 64 * 6 - 64 * 2;
2189             c += 64 * 6 - 8;
2190         }
2191     }
2192
2193     // Y (1 block per MCU) to 8-bit grayscale
2194     void jpeg_decoder::gray_convert()
2195     {
2196         int row = m_max_mcu_y_size - m_mcu_lines_left;
2197         uint8 *d = m_pScan_line_0;
2198         uint8 *s = m_pSample_buf + row * 8;
2199
2200         for (int i = m_max_mcus_per_row; i > 0; i--)
2201         {
2202             *(uint *)d = *(uint *)s;
2203             *(uint *)(&d[4]) = *(uint *)(&s[4]);
2204
2205             s += 64;
2206             d += 8;
2207         }
2208     }
2209
2210     void jpeg_decoder::expanded_convert()
2211     {
2212         int row = m_max_mcu_y_size - m_mcu_lines_left;
2213
2214         uint8 *Py = m_pSample_buf + (row / 8) * 64 * m_comp_h_samp[0] + (row & 7) * 8;
2215
2216         uint8 *d = m_pScan_line_0;
2217
2218         for (int i = m_max_mcus_per_row; i > 0; i--)
2219         {
2220             for (int k = 0; k < m_max_mcu_x_size; k += 8)
2221             {
2222                 const int Y_ofs = k * 8;
2223                 const int Cb_ofs = Y_ofs + 64 * m_expanded_blocks_per_component;
2224                 const int Cr_ofs = Y_ofs + 64 * m_expanded_blocks_per_component * 2;
2225                 for (int j = 0; j < 8; j++)
2226                 {
2227                     int y = Py[Y_ofs + j];
2228                     int cb = Py[Cb_ofs + j];
2229                     int cr = Py[Cr_ofs + j];
2230
2231                     d[0] = clamp(y + m_crr[cr]);
2232                     d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
2233                     d[2] = clamp(y + m_cbb[cb]);
2234                     d[3] = 255;
2235
2236                     d += 4;
2237                 }
2238             }
2239
2240             Py += 64 * m_expanded_blocks_per_mcu;
2241         }
2242     }
2243
2244     // Find end of image (EOI) marker, so we can return to the user the exact size of the input stream.
2245     void jpeg_decoder::find_eoi()
2246     {
2247         if (!m_progressive_flag)
2248         {
2249             // Attempt to read the EOI marker.
2250             //get_bits_no_markers(m_bits_left & 7);
2251
2252             // Prime the bit buffer
2253             m_bits_left = 16;
2254             get_bits(16);
2255             get_bits(16);
2256
2257             // The next marker _should_ be EOI
2258             process_markers();
2259         }
2260
2261         m_total_bytes_read -= m_in_buf_left;
2262     }
2263
2264     int jpeg_decoder::decode(const void **pScan_line, uint *pScan_line_len)
2265     {
2266         if ((m_error_code) || (!m_ready_flag))
2267             return JPGD_FAILED;
2268
2269         if (m_total_lines_left == 0)
2270             return JPGD_DONE;
2271
2272         if (m_mcu_lines_left == 0)
2273         {
2274             if (setjmp(m_jmp_state))
2275                 return JPGD_FAILED;
2276
2277             if (m_progressive_flag)
2278                 load_next_row();
2279             else
2280                 decode_next_row();
2281
2282             // Find the EOI marker if that was the last row.
2283             if (m_total_lines_left <= m_max_mcu_y_size)
2284                 find_eoi();
2285
2286             m_mcu_lines_left = m_max_mcu_y_size;
2287         }
2288
2289         if (m_freq_domain_chroma_upsample)
2290         {
2291             expanded_convert();
2292             *pScan_line = m_pScan_line_0;
2293         }
2294         else
2295         {
2296             switch (m_scan_type)
2297             {
2298                 case JPGD_YH2V2:
2299                 {
2300                     if ((m_mcu_lines_left & 1) == 0)
2301                     {
2302                         H2V2Convert();
2303                         *pScan_line = m_pScan_line_0;
2304                     }
2305                     else
2306                         *pScan_line = m_pScan_line_1;
2307
2308                     break;
2309                 }
2310                 case JPGD_YH2V1:
2311                 {
2312                     H2V1Convert();
2313                     *pScan_line = m_pScan_line_0;
2314                     break;
2315                 }
2316                 case JPGD_YH1V2:
2317                 {
2318                     if ((m_mcu_lines_left & 1) == 0)
2319                     {
2320                         H1V2Convert();
2321                         *pScan_line = m_pScan_line_0;
2322                     }
2323                     else
2324                         *pScan_line = m_pScan_line_1;
2325
2326                     break;
2327                 }
2328                 case JPGD_YH1V1:
2329                 {
2330                     H1V1Convert();
2331                     *pScan_line = m_pScan_line_0;
2332                     break;
2333                 }
2334                 case JPGD_GRAYSCALE:
2335                 {
2336                     gray_convert();
2337                     *pScan_line = m_pScan_line_0;
2338
2339                     break;
2340                 }
2341             }
2342         }
2343
2344         *pScan_line_len = m_real_dest_bytes_per_scan_line;
2345
2346         m_mcu_lines_left--;
2347         m_total_lines_left--;
2348
2349         return JPGD_SUCCESS;
2350     }
2351
2352     // Creates the tables needed for efficient Huffman decoding.
2353     void jpeg_decoder::make_huff_table(int index, huff_tables *pH)
2354     {
2355         int p, i, l, si;
2356         uint8 huffsize[257];
2357         uint huffcode[257];
2358         uint code;
2359         uint subtree;
2360         int code_size;
2361         int lastp;
2362         int nextfreeentry;
2363         int currententry;
2364
2365         pH->ac_table = m_huff_ac[index] != 0;
2366
2367         p = 0;
2368
2369         for (l = 1; l <= 16; l++)
2370         {
2371             for (i = 1; i <= m_huff_num[index][l]; i++)
2372                 huffsize[p++] = static_cast<uint8>(l);
2373         }
2374
2375         huffsize[p] = 0;
2376
2377         lastp = p;
2378
2379         code = 0;
2380         si = huffsize[0];
2381         p = 0;
2382
2383         while (huffsize[p])
2384         {
2385             while (huffsize[p] == si)
2386             {
2387                 huffcode[p++] = code;
2388                 code++;
2389             }
2390
2391             code <<= 1;
2392             si++;
2393         }
2394
2395         memset(pH->look_up, 0, sizeof(pH->look_up));
2396         memset(pH->look_up2, 0, sizeof(pH->look_up2));
2397         memset(pH->tree, 0, sizeof(pH->tree));
2398         memset(pH->code_size, 0, sizeof(pH->code_size));
2399
2400         nextfreeentry = -1;
2401
2402         p = 0;
2403
2404         while (p < lastp)
2405         {
2406             i = m_huff_val[index][p];
2407             code = huffcode[p];
2408             code_size = huffsize[p];
2409
2410             pH->code_size[i] = static_cast<uint8>(code_size);
2411
2412             if (code_size <= 8)
2413             {
2414                 code <<= (8 - code_size);
2415
2416                 for (l = 1 << (8 - code_size); l > 0; l--)
2417                 {
2418                     JPGD_ASSERT(i < 256);
2419
2420                     pH->look_up[code] = i;
2421
2422                     bool has_extrabits = false;
2423                     int extra_bits = 0;
2424                     int num_extra_bits = i & 15;
2425
2426                     int bits_to_fetch = code_size;
2427                     if (num_extra_bits)
2428                     {
2429                         int total_codesize = code_size + num_extra_bits;
2430                         if (total_codesize <= 8)
2431                         {
2432                             has_extrabits = true;
2433                             extra_bits = ((1 << num_extra_bits) - 1) & (code >> (8 - total_codesize));
2434                             JPGD_ASSERT(extra_bits <= 0x7FFF);
2435                             bits_to_fetch += num_extra_bits;
2436                         }
2437                     }
2438
2439                     if (!has_extrabits)
2440                         pH->look_up2[code] = i | (bits_to_fetch << 8);
2441                     else
2442                         pH->look_up2[code] = i | 0x8000 | (extra_bits << 16) | (bits_to_fetch << 8);
2443
2444                     code++;
2445                 }
2446             }
2447             else
2448             {
2449                 subtree = (code >> (code_size - 8)) & 0xFF;
2450
2451                 currententry = pH->look_up[subtree];
2452
2453                 if (currententry == 0)
2454                 {
2455                     pH->look_up[subtree] = currententry = nextfreeentry;
2456                     pH->look_up2[subtree] = currententry = nextfreeentry;
2457
2458                     nextfreeentry -= 2;
2459                 }
2460
2461                 code <<= (16 - (code_size - 8));
2462
2463                 for (l = code_size; l > 9; l--)
2464                 {
2465                     if ((code & 0x8000) == 0)
2466                         currententry--;
2467
2468                     if (pH->tree[-currententry - 1] == 0)
2469                     {
2470                         pH->tree[-currententry - 1] = nextfreeentry;
2471
2472                         currententry = nextfreeentry;
2473
2474                         nextfreeentry -= 2;
2475                     }
2476                     else
2477                         currententry = pH->tree[-currententry - 1];
2478
2479                     code <<= 1;
2480                 }
2481
2482                 if ((code & 0x8000) == 0)
2483                     currententry--;
2484
2485                 pH->tree[-currententry - 1] = i;
2486             }
2487
2488             p++;
2489         }
2490     }
2491
2492     // Verifies the quantization tables needed for this scan are available.
2493     void jpeg_decoder::check_quant_tables()
2494     {
2495         for (int i = 0; i < m_comps_in_scan; i++)
2496             if (m_quant[m_comp_quant[m_comp_list[i]]] == NULL)
2497                 stop_decoding(JPGD_UNDEFINED_QUANT_TABLE);
2498     }
2499
2500     // Verifies that all the Huffman tables needed for this scan are available.
2501     void jpeg_decoder::check_huff_tables()
2502     {
2503         for (int i = 0; i < m_comps_in_scan; i++)
2504         {
2505             if ((m_spectral_start == 0) && (m_huff_num[m_comp_dc_tab[m_comp_list[i]]] == NULL))
2506                 stop_decoding(JPGD_UNDEFINED_HUFF_TABLE);
2507
2508             if ((m_spectral_end > 0) && (m_huff_num[m_comp_ac_tab[m_comp_list[i]]] == NULL))
2509                 stop_decoding(JPGD_UNDEFINED_HUFF_TABLE);
2510         }
2511
2512         for (int i = 0; i < JPGD_MAX_HUFF_TABLES; i++)
2513             if (m_huff_num[i])
2514             {
2515                 if (!m_pHuff_tabs[i])
2516                     m_pHuff_tabs[i] = (huff_tables *)alloc(sizeof(huff_tables));
2517
2518                 make_huff_table(i, m_pHuff_tabs[i]);
2519             }
2520     }
2521
2522     // Determines the component order inside each MCU.
2523     // Also calcs how many MCU's are on each row, etc.
2524     void jpeg_decoder::calc_mcu_block_order()
2525     {
2526         int component_num, component_id;
2527         int max_h_samp = 0, max_v_samp = 0;
2528
2529         for (component_id = 0; component_id < m_comps_in_frame; component_id++)
2530         {
2531             if (m_comp_h_samp[component_id] > max_h_samp)
2532                 max_h_samp = m_comp_h_samp[component_id];
2533
2534             if (m_comp_v_samp[component_id] > max_v_samp)
2535                 max_v_samp = m_comp_v_samp[component_id];
2536         }
2537
2538         for (component_id = 0; component_id < m_comps_in_frame; component_id++)
2539         {
2540             m_comp_h_blocks[component_id] = ((((m_image_x_size * m_comp_h_samp[component_id]) + (max_h_samp - 1)) / max_h_samp) + 7) / 8;
2541             m_comp_v_blocks[component_id] = ((((m_image_y_size * m_comp_v_samp[component_id]) + (max_v_samp - 1)) / max_v_samp) + 7) / 8;
2542         }
2543
2544         if (m_comps_in_scan == 1)
2545         {
2546             m_mcus_per_row = m_comp_h_blocks[m_comp_list[0]];
2547             m_mcus_per_col = m_comp_v_blocks[m_comp_list[0]];
2548         }
2549         else
2550         {
2551             m_mcus_per_row = (((m_image_x_size + 7) / 8) + (max_h_samp - 1)) / max_h_samp;
2552             m_mcus_per_col = (((m_image_y_size + 7) / 8) + (max_v_samp - 1)) / max_v_samp;
2553         }
2554
2555         if (m_comps_in_scan == 1)
2556         {
2557             m_mcu_org[0] = m_comp_list[0];
2558
2559             m_blocks_per_mcu = 1;
2560         }
2561         else
2562         {
2563             m_blocks_per_mcu = 0;
2564
2565             for (component_num = 0; component_num < m_comps_in_scan; component_num++)
2566             {
2567                 int num_blocks;
2568
2569                 component_id = m_comp_list[component_num];
2570
2571                 num_blocks = m_comp_h_samp[component_id] * m_comp_v_samp[component_id];
2572
2573                 while (num_blocks--)
2574                     m_mcu_org[m_blocks_per_mcu++] = component_id;
2575             }
2576         }
2577     }
2578
2579     // Starts a new scan.
2580     int jpeg_decoder::init_scan()
2581     {
2582         if (!locate_sos_marker())
2583             return JPGD_FALSE;
2584
2585         calc_mcu_block_order();
2586
2587         check_huff_tables();
2588
2589         check_quant_tables();
2590
2591         memset(m_last_dc_val, 0, m_comps_in_frame * sizeof(uint));
2592
2593         m_eob_run = 0;
2594
2595         if (m_restart_interval)
2596         {
2597             m_restarts_left = m_restart_interval;
2598             m_next_restart_num = 0;
2599         }
2600
2601         fix_in_buffer();
2602
2603         return JPGD_TRUE;
2604     }
2605
2606     // Starts a frame. Determines if the number of components or sampling factors
2607     // are supported.
2608     void jpeg_decoder::init_frame()
2609     {
2610         int i;
2611
2612         if (m_comps_in_frame == 1)
2613         {
2614             if ((m_comp_h_samp[0] != 1) || (m_comp_v_samp[0] != 1))
2615                 stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
2616
2617             m_scan_type = JPGD_GRAYSCALE;
2618             m_max_blocks_per_mcu = 1;
2619             m_max_mcu_x_size = 8;
2620             m_max_mcu_y_size = 8;
2621         }
2622         else if (m_comps_in_frame == 3)
2623         {
2624             if (((m_comp_h_samp[1] != 1) || (m_comp_v_samp[1] != 1)) ||
2625                 ((m_comp_h_samp[2] != 1) || (m_comp_v_samp[2] != 1)))
2626                 stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
2627
2628             if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 1))
2629             {
2630                 m_scan_type = JPGD_YH1V1;
2631
2632                 m_max_blocks_per_mcu = 3;
2633                 m_max_mcu_x_size = 8;
2634                 m_max_mcu_y_size = 8;
2635             }
2636             else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 1))
2637             {
2638                 m_scan_type = JPGD_YH2V1;
2639                 m_max_blocks_per_mcu = 4;
2640                 m_max_mcu_x_size = 16;
2641                 m_max_mcu_y_size = 8;
2642             }
2643             else if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 2))
2644             {
2645                 m_scan_type = JPGD_YH1V2;
2646                 m_max_blocks_per_mcu = 4;
2647                 m_max_mcu_x_size = 8;
2648                 m_max_mcu_y_size = 16;
2649             }
2650             else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 2))
2651             {
2652                 m_scan_type = JPGD_YH2V2;
2653                 m_max_blocks_per_mcu = 6;
2654                 m_max_mcu_x_size = 16;
2655                 m_max_mcu_y_size = 16;
2656             }
2657             else
2658                 stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
2659         }
2660         else
2661             stop_decoding(JPGD_UNSUPPORTED_COLORSPACE);
2662
2663         m_max_mcus_per_row = (m_image_x_size + (m_max_mcu_x_size - 1)) / m_max_mcu_x_size;
2664         m_max_mcus_per_col = (m_image_y_size + (m_max_mcu_y_size - 1)) / m_max_mcu_y_size;
2665
2666         // These values are for the *destination* pixels: after conversion.
2667         if (m_scan_type == JPGD_GRAYSCALE)
2668             m_dest_bytes_per_pixel = 1;
2669         else
2670             m_dest_bytes_per_pixel = 4;
2671
2672         m_dest_bytes_per_scan_line = ((m_image_x_size + 15) & 0xFFF0) * m_dest_bytes_per_pixel;
2673
2674         m_real_dest_bytes_per_scan_line = (m_image_x_size * m_dest_bytes_per_pixel);
2675
2676         // Initialize two scan line buffers.
2677         m_pScan_line_0 = (uint8 *)alloc(m_dest_bytes_per_scan_line, true);
2678         if ((m_scan_type == JPGD_YH1V2) || (m_scan_type == JPGD_YH2V2))
2679             m_pScan_line_1 = (uint8 *)alloc(m_dest_bytes_per_scan_line, true);
2680
2681         m_max_blocks_per_row = m_max_mcus_per_row * m_max_blocks_per_mcu;
2682
2683         // Should never happen
2684         if (m_max_blocks_per_row > JPGD_MAX_BLOCKS_PER_ROW)
2685             stop_decoding(JPGD_ASSERTION_ERROR);
2686
2687         // Allocate the coefficient buffer, enough for one MCU
2688         m_pMCU_coefficients = (jpgd_block_t *)alloc(m_max_blocks_per_mcu * 64 * sizeof(jpgd_block_t));
2689
2690         for (i = 0; i < m_max_blocks_per_mcu; i++)
2691             m_mcu_block_max_zag[i] = 64;
2692
2693         m_expanded_blocks_per_component = m_comp_h_samp[0] * m_comp_v_samp[0];
2694         m_expanded_blocks_per_mcu = m_expanded_blocks_per_component * m_comps_in_frame;
2695         m_expanded_blocks_per_row = m_max_mcus_per_row * m_expanded_blocks_per_mcu;
2696         // Freq. domain chroma upsampling is only supported for H2V2 subsampling factor (the most common one I've seen).
2697         m_freq_domain_chroma_upsample = false;
2698 #if JPGD_SUPPORT_FREQ_DOMAIN_UPSAMPLING
2699         m_freq_domain_chroma_upsample = (m_expanded_blocks_per_mcu == 4 * 3);
2700 #endif
2701
2702         if (m_freq_domain_chroma_upsample)
2703             m_pSample_buf = (uint8 *)alloc(m_expanded_blocks_per_row * 64);
2704         else
2705             m_pSample_buf = (uint8 *)alloc(m_max_blocks_per_row * 64);
2706
2707         m_total_lines_left = m_image_y_size;
2708
2709         m_mcu_lines_left = 0;
2710
2711         create_look_ups();
2712     }
2713
2714     // The coeff_buf series of methods originally stored the coefficients
2715     // into a "virtual" file which was located in EMS, XMS, or a disk file. A cache
2716     // was used to make this process more efficient. Now, we can store the entire
2717     // thing in RAM.
2718     jpeg_decoder::coeff_buf *jpeg_decoder::coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y)
2719     {
2720         coeff_buf *cb = (coeff_buf *)alloc(sizeof(coeff_buf));
2721
2722         cb->block_num_x = block_num_x;
2723         cb->block_num_y = block_num_y;
2724         cb->block_len_x = block_len_x;
2725         cb->block_len_y = block_len_y;
2726         cb->block_size = (block_len_x * block_len_y) * sizeof(jpgd_block_t);
2727         cb->pData = (uint8 *)alloc(cb->block_size * block_num_x * block_num_y, true);
2728         return cb;
2729     }
2730
2731     inline jpgd_block_t *jpeg_decoder::coeff_buf_getp(coeff_buf *cb, int block_x, int block_y)
2732     {
2733         JPGD_ASSERT((block_x < cb->block_num_x) && (block_y < cb->block_num_y));
2734         return (jpgd_block_t *)(cb->pData + block_x * cb->block_size + block_y * (cb->block_size * cb->block_num_x));
2735     }
2736
2737     // The following methods decode the various types of m_blocks encountered
2738     // in progressively encoded images.
2739     void jpeg_decoder::decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y)
2740     {
2741         int s, r;
2742         jpgd_block_t *p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y);
2743
2744         if ((s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_dc_tab[component_id]])) != 0)
2745         {
2746             r = pD->get_bits_no_markers(s);
2747             s = JPGD_HUFF_EXTEND(r, s);
2748         }
2749
2750         pD->m_last_dc_val[component_id] = (s += pD->m_last_dc_val[component_id]);
2751
2752         p[0] = static_cast<jpgd_block_t>(s << pD->m_successive_low);
2753     }
2754
2755     void jpeg_decoder::decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y)
2756     {
2757         if (pD->get_bits_no_markers(1))
2758         {
2759             jpgd_block_t *p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y);
2760
2761             p[0] |= (1 << pD->m_successive_low);
2762         }
2763     }
2764
2765     void jpeg_decoder::decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y)
2766     {
2767         int k, s, r;
2768
2769         if (pD->m_eob_run)
2770         {
2771             pD->m_eob_run--;
2772             return;
2773         }
2774
2775         jpgd_block_t *p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y);
2776
2777         for (k = pD->m_spectral_start; k <= pD->m_spectral_end; k++)
2778         {
2779             s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_ac_tab[component_id]]);
2780
2781             r = s >> 4;
2782             s &= 15;
2783
2784             if (s)
2785             {
2786                 if ((k += r) > 63)
2787                     pD->stop_decoding(JPGD_DECODE_ERROR);
2788
2789                 r = pD->get_bits_no_markers(s);
2790                 s = JPGD_HUFF_EXTEND(r, s);
2791
2792                 p[g_ZAG[k]] = static_cast<jpgd_block_t>(s << pD->m_successive_low);
2793             }
2794             else
2795             {
2796                 if (r == 15)
2797                 {
2798                     if ((k += 15) > 63)
2799                         pD->stop_decoding(JPGD_DECODE_ERROR);
2800                 }
2801                 else
2802                 {
2803                     pD->m_eob_run = 1 << r;
2804
2805                     if (r)
2806                         pD->m_eob_run += pD->get_bits_no_markers(r);
2807
2808                     pD->m_eob_run--;
2809
2810                     break;
2811                 }
2812             }
2813         }
2814     }
2815
2816     void jpeg_decoder::decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y)
2817     {
2818         int s, k, r;
2819         int p1 = 1 << pD->m_successive_low;
2820         int m1 = (-1) << pD->m_successive_low;
2821         jpgd_block_t *p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y);
2822
2823         JPGD_ASSERT(pD->m_spectral_end <= 63);
2824
2825         k = pD->m_spectral_start;
2826
2827         if (pD->m_eob_run == 0)
2828         {
2829             for (; k <= pD->m_spectral_end; k++)
2830             {
2831                 s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_ac_tab[component_id]]);
2832
2833                 r = s >> 4;
2834                 s &= 15;
2835
2836                 if (s)
2837                 {
2838                     if (s != 1)
2839                         pD->stop_decoding(JPGD_DECODE_ERROR);
2840
2841                     if (pD->get_bits_no_markers(1))
2842                         s = p1;
2843                     else
2844                         s = m1;
2845                 }
2846                 else
2847                 {
2848                     if (r != 15)
2849                     {
2850                         pD->m_eob_run = 1 << r;
2851
2852                         if (r)
2853                             pD->m_eob_run += pD->get_bits_no_markers(r);
2854
2855                         break;
2856                     }
2857                 }
2858
2859                 do
2860                 {
2861                     jpgd_block_t *this_coef = p + g_ZAG[k & 63];
2862
2863                     if (*this_coef != 0)
2864                     {
2865                         if (pD->get_bits_no_markers(1))
2866                         {
2867                             if ((*this_coef & p1) == 0)
2868                             {
2869                                 if (*this_coef >= 0)
2870                                     *this_coef = static_cast<jpgd_block_t>(*this_coef + p1);
2871                                 else
2872                                     *this_coef = static_cast<jpgd_block_t>(*this_coef + m1);
2873                             }
2874                         }
2875                     }
2876                     else
2877                     {
2878                         if (--r < 0)
2879                             break;
2880                     }
2881
2882                     k++;
2883
2884                 } while (k <= pD->m_spectral_end);
2885
2886                 if ((s) && (k < 64))
2887                 {
2888                     p[g_ZAG[k]] = static_cast<jpgd_block_t>(s);
2889                 }
2890             }
2891         }
2892
2893         if (pD->m_eob_run > 0)
2894         {
2895             for (; k <= pD->m_spectral_end; k++)
2896             {
2897                 jpgd_block_t *this_coef = p + g_ZAG[k & 63]; // logical AND to shut up static code analysis
2898
2899                 if (*this_coef != 0)
2900                 {
2901                     if (pD->get_bits_no_markers(1))
2902                     {
2903                         if ((*this_coef & p1) == 0)
2904                         {
2905                             if (*this_coef >= 0)
2906                                 *this_coef = static_cast<jpgd_block_t>(*this_coef + p1);
2907                             else
2908                                 *this_coef = static_cast<jpgd_block_t>(*this_coef + m1);
2909                         }
2910                     }
2911                 }
2912             }
2913
2914             pD->m_eob_run--;
2915         }
2916     }
2917
2918     // Decode a scan in a progressively encoded image.
2919     void jpeg_decoder::decode_scan(pDecode_block_func decode_block_func)
2920     {
2921         int mcu_row, mcu_col, mcu_block;
2922         int block_x_mcu[JPGD_MAX_COMPONENTS], m_block_y_mcu[JPGD_MAX_COMPONENTS];
2923
2924         memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu));
2925
2926         for (mcu_col = 0; mcu_col < m_mcus_per_col; mcu_col++)
2927         {
2928             int component_num, component_id;
2929
2930             memset(block_x_mcu, 0, sizeof(block_x_mcu));
2931
2932             for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
2933             {
2934                 int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0;
2935
2936                 if ((m_restart_interval) && (m_restarts_left == 0))
2937                     process_restart();
2938
2939                 for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
2940                 {
2941                     component_id = m_mcu_org[mcu_block];
2942
2943                     decode_block_func(this, component_id, block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
2944
2945                     if (m_comps_in_scan == 1)
2946                         block_x_mcu[component_id]++;
2947                     else
2948                     {
2949                         if (++block_x_mcu_ofs == m_comp_h_samp[component_id])
2950                         {
2951                             block_x_mcu_ofs = 0;
2952
2953                             if (++block_y_mcu_ofs == m_comp_v_samp[component_id])
2954                             {
2955                                 block_y_mcu_ofs = 0;
2956                                 block_x_mcu[component_id] += m_comp_h_samp[component_id];
2957                             }
2958                         }
2959                     }
2960                 }
2961
2962                 m_restarts_left--;
2963             }
2964
2965             if (m_comps_in_scan == 1)
2966                 m_block_y_mcu[m_comp_list[0]]++;
2967             else
2968             {
2969                 for (component_num = 0; component_num < m_comps_in_scan; component_num++)
2970                 {
2971                     component_id = m_comp_list[component_num];
2972                     m_block_y_mcu[component_id] += m_comp_v_samp[component_id];
2973                 }
2974             }
2975         }
2976     }
2977
2978     // Decode a progressively encoded image.
2979     void jpeg_decoder::init_progressive()
2980     {
2981         int i;
2982
2983         if (m_comps_in_frame == 4)
2984             stop_decoding(JPGD_UNSUPPORTED_COLORSPACE);
2985
2986         // Allocate the coefficient buffers.
2987         for (i = 0; i < m_comps_in_frame; i++)
2988         {
2989             m_dc_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 1, 1);
2990             m_ac_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 8, 8);
2991         }
2992
2993         for (;;)
2994         {
2995             int dc_only_scan, refinement_scan;
2996             pDecode_block_func decode_block_func;
2997
2998             if (!init_scan())
2999                 break;
3000
3001             dc_only_scan = (m_spectral_start == 0);
3002             refinement_scan = (m_successive_high != 0);
3003
3004             if ((m_spectral_start > m_spectral_end) || (m_spectral_end > 63))
3005                 stop_decoding(JPGD_BAD_SOS_SPECTRAL);
3006
3007             if (dc_only_scan)
3008             {
3009                 if (m_spectral_end)
3010                     stop_decoding(JPGD_BAD_SOS_SPECTRAL);
3011             }
3012             else if (m_comps_in_scan != 1) /* AC scans can only contain one component */
3013                 stop_decoding(JPGD_BAD_SOS_SPECTRAL);
3014
3015             if ((refinement_scan) && (m_successive_low != m_successive_high - 1))
3016                 stop_decoding(JPGD_BAD_SOS_SUCCESSIVE);
3017
3018             if (dc_only_scan)
3019             {
3020                 if (refinement_scan)
3021                     decode_block_func = decode_block_dc_refine;
3022                 else
3023                     decode_block_func = decode_block_dc_first;
3024             }
3025             else
3026             {
3027                 if (refinement_scan)
3028                     decode_block_func = decode_block_ac_refine;
3029                 else
3030                     decode_block_func = decode_block_ac_first;
3031             }
3032
3033             decode_scan(decode_block_func);
3034
3035             m_bits_left = 16;
3036             get_bits(16);
3037             get_bits(16);
3038         }
3039
3040         m_comps_in_scan = m_comps_in_frame;
3041
3042         for (i = 0; i < m_comps_in_frame; i++)
3043             m_comp_list[i] = i;
3044
3045         calc_mcu_block_order();
3046     }
3047
3048     void jpeg_decoder::init_sequential()
3049     {
3050         if (!init_scan())
3051             stop_decoding(JPGD_UNEXPECTED_MARKER);
3052     }
3053
3054     void jpeg_decoder::decode_start()
3055     {
3056         init_frame();
3057
3058         if (m_progressive_flag)
3059             init_progressive();
3060         else
3061             init_sequential();
3062     }
3063
3064     void jpeg_decoder::decode_init(jpeg_decoder_stream *pStream)
3065     {
3066         init(pStream);
3067         locate_sof_marker();
3068     }
3069
3070     jpeg_decoder::jpeg_decoder(jpeg_decoder_stream *pStream)
3071     {
3072         if (setjmp(m_jmp_state))
3073             return;
3074         decode_init(pStream);
3075     }
3076
3077     int jpeg_decoder::begin_decoding()
3078     {
3079         if (m_ready_flag)
3080             return JPGD_SUCCESS;
3081
3082         if (m_error_code)
3083             return JPGD_FAILED;
3084
3085         if (setjmp(m_jmp_state))
3086             return JPGD_FAILED;
3087
3088         decode_start();
3089
3090         m_ready_flag = true;
3091
3092         return JPGD_SUCCESS;
3093     }
3094
3095     jpeg_decoder::~jpeg_decoder()
3096     {
3097         free_all_blocks();
3098     }
3099
3100     jpeg_decoder_file_stream::jpeg_decoder_file_stream()
3101     {
3102         m_pFile = NULL;
3103         m_eof_flag = false;
3104         m_error_flag = false;
3105     }
3106
3107     void jpeg_decoder_file_stream::close()
3108     {
3109         if (m_pFile)
3110         {
3111             fclose(m_pFile);
3112             m_pFile = NULL;
3113         }
3114
3115         m_eof_flag = false;
3116         m_error_flag = false;
3117     }
3118
3119     jpeg_decoder_file_stream::~jpeg_decoder_file_stream()
3120     {
3121         close();
3122     }
3123
3124     bool jpeg_decoder_file_stream::open(const char *Pfilename)
3125     {
3126         close();
3127
3128         m_eof_flag = false;
3129         m_error_flag = false;
3130
3131 #if defined(_MSC_VER)
3132         m_pFile = NULL;
3133         fopen_s(&m_pFile, Pfilename, "rb");
3134 #else
3135         m_pFile = fopen(Pfilename, "rb");
3136 #endif
3137         return m_pFile != NULL;
3138     }
3139
3140     int jpeg_decoder_file_stream::read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag)
3141     {
3142         if (!m_pFile)
3143             return -1;
3144
3145         if (m_eof_flag)
3146         {
3147             *pEOF_flag = true;
3148             return 0;
3149         }
3150
3151         if (m_error_flag)
3152             return -1;
3153
3154         int bytes_read = static_cast<int>(fread(pBuf, 1, max_bytes_to_read, m_pFile));
3155         if (bytes_read < max_bytes_to_read)
3156         {
3157             if (ferror(m_pFile))
3158             {
3159                 m_error_flag = true;
3160                 return -1;
3161             }
3162
3163             m_eof_flag = true;
3164             *pEOF_flag = true;
3165         }
3166
3167         return bytes_read;
3168     }
3169
3170     bool jpeg_decoder_mem_stream::open(const uint8 *pSrc_data, uint size)
3171     {
3172         close();
3173         m_pSrc_data = pSrc_data;
3174         m_ofs = 0;
3175         m_size = size;
3176         return true;
3177     }
3178
3179     int jpeg_decoder_mem_stream::read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag)
3180     {
3181         *pEOF_flag = false;
3182
3183         if (!m_pSrc_data)
3184             return -1;
3185
3186         uint bytes_remaining = m_size - m_ofs;
3187         if ((uint)max_bytes_to_read > bytes_remaining)
3188         {
3189             max_bytes_to_read = bytes_remaining;
3190             *pEOF_flag = true;
3191         }
3192
3193         memcpy(pBuf, m_pSrc_data + m_ofs, max_bytes_to_read);
3194         m_ofs += max_bytes_to_read;
3195
3196         return max_bytes_to_read;
3197     }
3198
3199     unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps)
3200     {
3201         if (!actual_comps)
3202             return NULL;
3203         *actual_comps = 0;
3204
3205         if ((!pStream) || (!width) || (!height) || (!req_comps))
3206             return NULL;
3207
3208         if ((req_comps != 1) && (req_comps != 3) && (req_comps != 4))
3209             return NULL;
3210
3211         jpeg_decoder decoder(pStream);
3212         if (decoder.get_error_code() != JPGD_SUCCESS)
3213             return NULL;
3214
3215         const int image_width = decoder.get_width(), image_height = decoder.get_height();
3216         *width = image_width;
3217         *height = image_height;
3218         *actual_comps = decoder.get_num_components();
3219
3220         if (decoder.begin_decoding() != JPGD_SUCCESS)
3221             return NULL;
3222
3223         const int dst_bpl = image_width * req_comps;
3224
3225         uint8 *pImage_data = (uint8 *)jpgd_malloc(dst_bpl * image_height);
3226         if (!pImage_data)
3227             return NULL;
3228
3229         for (int y = 0; y < image_height; y++)
3230         {
3231             const uint8 *pScan_line;
3232             uint scan_line_len;
3233             if (decoder.decode((const void **)&pScan_line, &scan_line_len) != JPGD_SUCCESS)
3234             {
3235                 jpgd_free(pImage_data);
3236                 return NULL;
3237             }
3238
3239             uint8 *pDst = pImage_data + y * dst_bpl;
3240
3241             if (((req_comps == 1) && (decoder.get_num_components() == 1)) || ((req_comps == 4) && (decoder.get_num_components() == 3)))
3242                 memcpy(pDst, pScan_line, dst_bpl);
3243             else if (decoder.get_num_components() == 1)
3244             {
3245                 if (req_comps == 3)
3246                 {
3247                     for (int x = 0; x < image_width; x++)
3248                     {
3249                         uint8 luma = pScan_line[x];
3250                         pDst[0] = luma;
3251                         pDst[1] = luma;
3252                         pDst[2] = luma;
3253                         pDst += 3;
3254                     }
3255                 }
3256                 else
3257                 {
3258                     for (int x = 0; x < image_width; x++)
3259                     {
3260                         uint8 luma = pScan_line[x];
3261                         pDst[0] = luma;
3262                         pDst[1] = luma;
3263                         pDst[2] = luma;
3264                         pDst[3] = 255;
3265                         pDst += 4;
3266                     }
3267                 }
3268             }
3269             else if (decoder.get_num_components() == 3)
3270             {
3271                 if (req_comps == 1)
3272                 {
3273                     const int YR = 19595, YG = 38470, YB = 7471;
3274                     for (int x = 0; x < image_width; x++)
3275                     {
3276                         int r = pScan_line[x * 4 + 0];
3277                         int g = pScan_line[x * 4 + 1];
3278                         int b = pScan_line[x * 4 + 2];
3279                         *pDst++ = static_cast<uint8>((r * YR + g * YG + b * YB + 32768) >> 16);
3280                     }
3281                 }
3282                 else
3283                 {
3284                     for (int x = 0; x < image_width; x++)
3285                     {
3286                         pDst[0] = pScan_line[x * 4 + 0];
3287                         pDst[1] = pScan_line[x * 4 + 1];
3288                         pDst[2] = pScan_line[x * 4 + 2];
3289                         pDst += 3;
3290                     }
3291                 }
3292             }
3293         }
3294
3295         return pImage_data;
3296     }
3297
3298     unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps)
3299     {
3300         jpgd::jpeg_decoder_mem_stream mem_stream(pSrc_data, src_data_size);
3301         return decompress_jpeg_image_from_stream(&mem_stream, width, height, actual_comps, req_comps);
3302     }
3303
3304     unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps)
3305     {
3306         jpgd::jpeg_decoder_file_stream file_stream;
3307         if (!file_stream.open(pSrc_filename))
3308             return NULL;
3309         return decompress_jpeg_image_from_stream(&file_stream, width, height, actual_comps, req_comps);
3310     }
3311
3312 } // namespace jpgd