~ppsspp/ppsspp/ppsspp_1.3.0

« back to all changes in this revision

Viewing changes to ext/native/ext/jpge/jpge.cpp

  • Committer: Sérgio Benjamim
  • Date: 2017-01-02 00:12:05 UTC
  • Revision ID: sergio_br2@yahoo.com.br-20170102001205-cxbta9za203nmjwm
1.3.0 source (from ppsspp_1.3.0-r160.p5.l1762.a165.t83~56~ubuntu16.04.1.tar.xz).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// jpge.cpp - C++ class for JPEG compression.
 
2
// Public domain, Rich Geldreich <richgel99@gmail.com>
 
3
// v1.01, Dec. 18, 2010 - Initial release
 
4
// v1.02, Apr. 6, 2011 - Removed 2x2 ordered dither in H2V1 chroma subsampling method load_block_16_8_8(). (The rounding factor was 2, when it should have been 1. Either way, it wasn't helping.)
 
5
// v1.03, Apr. 16, 2011 - Added support for optimized Huffman code tables, optimized dynamic memory allocation down to only 1 alloc.
 
6
//                        Also from Alex Evans: Added RGBA support, linear memory allocator (no longer needed in v1.03).
 
7
// v1.04, May. 19, 2012: Forgot to set m_pFile ptr to NULL in cfile_stream::close(). Thanks to Owen Kaluza for reporting this bug.
 
8
//                       Code tweaks to fix VS2008 static code analysis warnings (all looked harmless).
 
9
//                       Code review revealed method load_block_16_8_8() (used for the non-default H2V1 sampling mode to downsample chroma) somehow didn't get the rounding factor fix from v1.02.
 
10
 
 
11
#include "jpge.h"
 
12
 
 
13
#include <stdlib.h>
 
14
#include <string.h>
 
15
// Higher level wrappers/examples (optional).
 
16
#include <stdio.h>
 
17
 
 
18
#define JPGE_MAX(a,b) (((a)>(b))?(a):(b))
 
19
#define JPGE_MIN(a,b) (((a)<(b))?(a):(b))
 
20
 
 
21
namespace jpge {
 
22
 
 
23
static inline void *jpge_malloc(size_t nSize) { return malloc(nSize); }
 
24
static inline void jpge_free(void *p) { free(p); }
 
25
 
 
26
// Various JPEG enums and tables.
 
27
enum { M_SOF0 = 0xC0, M_DHT = 0xC4, M_SOI = 0xD8, M_EOI = 0xD9, M_SOS = 0xDA, M_DQT = 0xDB, M_APP0 = 0xE0 };
 
28
enum { DC_LUM_CODES = 12, AC_LUM_CODES = 256, DC_CHROMA_CODES = 12, AC_CHROMA_CODES = 256, MAX_HUFF_SYMBOLS = 257, MAX_HUFF_CODESIZE = 32 };
 
29
 
 
30
static uint8 s_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 };
 
31
static int16 s_std_lum_quant[64] = { 16,11,12,14,12,10,16,14,13,14,18,17,16,19,24,40,26,24,22,22,24,49,35,37,29,40,58,51,61,60,57,51,56,55,64,72,92,78,64,68,87,69,55,56,80,109,81,87,95,98,103,104,103,62,77,113,121,112,100,120,92,101,103,99 };
 
32
static int16 s_std_croma_quant[64] = { 17,18,18,24,21,24,47,26,26,47,99,66,56,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99 };
 
33
static uint8 s_dc_lum_bits[17] = { 0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0 };
 
34
static uint8 s_dc_lum_val[DC_LUM_CODES] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
 
35
static uint8 s_ac_lum_bits[17] = { 0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d };
 
36
static uint8 s_ac_lum_val[AC_LUM_CODES]  =
 
37
{
 
38
  0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
 
39
  0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
 
40
  0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
 
41
  0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
 
42
  0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
 
43
  0xf9,0xfa
 
44
};
 
45
static uint8 s_dc_chroma_bits[17] = { 0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0 };
 
46
static uint8 s_dc_chroma_val[DC_CHROMA_CODES]  = { 0,1,2,3,4,5,6,7,8,9,10,11 };
 
47
static uint8 s_ac_chroma_bits[17] = { 0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77 };
 
48
static uint8 s_ac_chroma_val[AC_CHROMA_CODES] =
 
49
{
 
50
  0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
 
51
  0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
 
52
  0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
 
53
  0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
 
54
  0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
 
55
  0xf9,0xfa
 
56
};
 
57
 
 
58
// Low-level helper functions.
 
59
template <class T> inline void clear_obj(T &obj) { memset(&obj, 0, sizeof(obj)); }
 
60
 
 
61
const int YR = 19595, YG = 38470, YB = 7471, CB_R = -11059, CB_G = -21709, CB_B = 32768, CR_R = 32768, CR_G = -27439, CR_B = -5329;
 
62
static inline uint8 clamp(int i) { if (static_cast<uint>(i) > 255U) { if (i < 0) i = 0; else if (i > 255) i = 255; } return static_cast<uint8>(i); }
 
63
 
 
64
static void RGB_to_YCC(uint8* pDst, const uint8 *pSrc, int num_pixels)
 
65
{
 
66
  for ( ; num_pixels; pDst += 3, pSrc += 3, num_pixels--)
 
67
  {
 
68
    const int r = pSrc[0], g = pSrc[1], b = pSrc[2];
 
69
    pDst[0] = static_cast<uint8>((r * YR + g * YG + b * YB + 32768) >> 16);
 
70
    pDst[1] = clamp(128 + ((r * CB_R + g * CB_G + b * CB_B + 32768) >> 16));
 
71
    pDst[2] = clamp(128 + ((r * CR_R + g * CR_G + b * CR_B + 32768) >> 16));
 
72
  }
 
73
}
 
74
 
 
75
static void RGB_to_Y(uint8* pDst, const uint8 *pSrc, int num_pixels)
 
76
{
 
77
  for ( ; num_pixels; pDst++, pSrc += 3, num_pixels--)
 
78
    pDst[0] = static_cast<uint8>((pSrc[0] * YR + pSrc[1] * YG + pSrc[2] * YB + 32768) >> 16);
 
79
}
 
80
 
 
81
static void RGBA_to_YCC(uint8* pDst, const uint8 *pSrc, int num_pixels)
 
82
{
 
83
  for ( ; num_pixels; pDst += 3, pSrc += 4, num_pixels--)
 
84
  {
 
85
    const int r = pSrc[0], g = pSrc[1], b = pSrc[2];
 
86
    pDst[0] = static_cast<uint8>((r * YR + g * YG + b * YB + 32768) >> 16);
 
87
    pDst[1] = clamp(128 + ((r * CB_R + g * CB_G + b * CB_B + 32768) >> 16));
 
88
    pDst[2] = clamp(128 + ((r * CR_R + g * CR_G + b * CR_B + 32768) >> 16));
 
89
  }
 
90
}
 
91
 
 
92
static void RGBA_to_Y(uint8* pDst, const uint8 *pSrc, int num_pixels)
 
93
{
 
94
  for ( ; num_pixels; pDst++, pSrc += 4, num_pixels--)
 
95
    pDst[0] = static_cast<uint8>((pSrc[0] * YR + pSrc[1] * YG + pSrc[2] * YB + 32768) >> 16);
 
96
}
 
97
 
 
98
static void Y_to_YCC(uint8* pDst, const uint8* pSrc, int num_pixels)
 
99
{
 
100
  for( ; num_pixels; pDst += 3, pSrc++, num_pixels--) { pDst[0] = pSrc[0]; pDst[1] = 128; pDst[2] = 128; }
 
101
}
 
102
 
 
103
// Forward DCT - DCT derived from jfdctint.
 
104
enum { CONST_BITS = 13, ROW_BITS = 2 };
 
105
#define DCT_DESCALE(x, n) (((x) + (((int32)1) << ((n) - 1))) >> (n))
 
106
#define DCT_MUL(var, c) (static_cast<int16>(var) * static_cast<int32>(c))
 
107
#define DCT1D(s0, s1, s2, s3, s4, s5, s6, s7) \
 
108
  int32 t0 = s0 + s7, t7 = s0 - s7, t1 = s1 + s6, t6 = s1 - s6, t2 = s2 + s5, t5 = s2 - s5, t3 = s3 + s4, t4 = s3 - s4; \
 
109
  int32 t10 = t0 + t3, t13 = t0 - t3, t11 = t1 + t2, t12 = t1 - t2; \
 
110
  int32 u1 = DCT_MUL(t12 + t13, 4433); \
 
111
  s2 = u1 + DCT_MUL(t13, 6270); \
 
112
  s6 = u1 + DCT_MUL(t12, -15137); \
 
113
  u1 = t4 + t7; \
 
114
  int32 u2 = t5 + t6, u3 = t4 + t6, u4 = t5 + t7; \
 
115
  int32 z5 = DCT_MUL(u3 + u4, 9633); \
 
116
  t4 = DCT_MUL(t4, 2446); t5 = DCT_MUL(t5, 16819); \
 
117
  t6 = DCT_MUL(t6, 25172); t7 = DCT_MUL(t7, 12299); \
 
118
  u1 = DCT_MUL(u1, -7373); u2 = DCT_MUL(u2, -20995); \
 
119
  u3 = DCT_MUL(u3, -16069); u4 = DCT_MUL(u4, -3196); \
 
120
  u3 += z5; u4 += z5; \
 
121
  s0 = t10 + t11; s1 = t7 + u1 + u4; s3 = t6 + u2 + u3; s4 = t10 - t11; s5 = t5 + u2 + u4; s7 = t4 + u1 + u3;
 
122
 
 
123
static void DCT2D(int32 *p)
 
124
{
 
125
  int32 c, *q = p;
 
126
  for (c = 7; c >= 0; c--, q += 8)
 
127
  {
 
128
    int32 s0 = q[0], s1 = q[1], s2 = q[2], s3 = q[3], s4 = q[4], s5 = q[5], s6 = q[6], s7 = q[7];
 
129
    DCT1D(s0, s1, s2, s3, s4, s5, s6, s7);
 
130
    q[0] = s0 << ROW_BITS; q[1] = DCT_DESCALE(s1, CONST_BITS-ROW_BITS); q[2] = DCT_DESCALE(s2, CONST_BITS-ROW_BITS); q[3] = DCT_DESCALE(s3, CONST_BITS-ROW_BITS);
 
131
    q[4] = s4 << ROW_BITS; q[5] = DCT_DESCALE(s5, CONST_BITS-ROW_BITS); q[6] = DCT_DESCALE(s6, CONST_BITS-ROW_BITS); q[7] = DCT_DESCALE(s7, CONST_BITS-ROW_BITS);
 
132
  }
 
133
  for (q = p, c = 7; c >= 0; c--, q++)
 
134
  {
 
135
    int32 s0 = q[0*8], s1 = q[1*8], s2 = q[2*8], s3 = q[3*8], s4 = q[4*8], s5 = q[5*8], s6 = q[6*8], s7 = q[7*8];
 
136
    DCT1D(s0, s1, s2, s3, s4, s5, s6, s7);
 
137
    q[0*8] = DCT_DESCALE(s0, ROW_BITS+3); q[1*8] = DCT_DESCALE(s1, CONST_BITS+ROW_BITS+3); q[2*8] = DCT_DESCALE(s2, CONST_BITS+ROW_BITS+3); q[3*8] = DCT_DESCALE(s3, CONST_BITS+ROW_BITS+3);
 
138
    q[4*8] = DCT_DESCALE(s4, ROW_BITS+3); q[5*8] = DCT_DESCALE(s5, CONST_BITS+ROW_BITS+3); q[6*8] = DCT_DESCALE(s6, CONST_BITS+ROW_BITS+3); q[7*8] = DCT_DESCALE(s7, CONST_BITS+ROW_BITS+3);
 
139
  }
 
140
}
 
141
 
 
142
struct sym_freq { uint m_key, m_sym_index; };
 
143
 
 
144
// Radix sorts sym_freq[] array by 32-bit key m_key. Returns ptr to sorted values.
 
145
static inline sym_freq* radix_sort_syms(uint num_syms, sym_freq* pSyms0, sym_freq* pSyms1)
 
146
{
 
147
  const uint cMaxPasses = 4;
 
148
  uint32 hist[256 * cMaxPasses]; clear_obj(hist);
 
149
  for (uint i = 0; i < num_syms; i++) { uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; hist[256*2 + ((freq >> 16) & 0xFF)]++; hist[256*3 + ((freq >> 24) & 0xFF)]++; }
 
150
  sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1;
 
151
  uint total_passes = cMaxPasses; while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--;
 
152
  for (uint pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
 
153
  {
 
154
    const uint32* pHist = &hist[pass << 8];
 
155
    uint offsets[256], cur_ofs = 0;
 
156
    for (uint i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; }
 
157
    for (uint i = 0; i < num_syms; i++)
 
158
      pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
 
159
    sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t;
 
160
  }
 
161
  return pCur_syms;
 
162
}
 
163
 
 
164
// calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
 
165
static void calculate_minimum_redundancy(sym_freq *A, int n)
 
166
{
 
167
  int root, leaf, next, avbl, used, dpth;
 
168
  if (n==0) return; else if (n==1) { A[0].m_key = 1; return; }
 
169
  A[0].m_key += A[1].m_key; root = 0; leaf = 2;
 
170
  for (next=1; next < n-1; next++)
 
171
  {
 
172
    if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = next; } else A[next].m_key = A[leaf++].m_key;
 
173
    if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key += A[root].m_key; A[root++].m_key = next; } else A[next].m_key += A[leaf++].m_key;
 
174
  }
 
175
  A[n-2].m_key = 0;
 
176
  for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1;
 
177
  avbl = 1; used = dpth = 0; root = n-2; next = n-1;
 
178
  while (avbl>0)
 
179
  {
 
180
    while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; }
 
181
    while (avbl>used) { A[next--].m_key = dpth; avbl--; }
 
182
    avbl = 2*used; dpth++; used = 0;
 
183
  }
 
184
}
 
185
 
 
186
// Limits canonical Huffman code table's max code size to max_code_size.
 
187
static void huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
 
188
{
 
189
  if (code_list_len <= 1) return;
 
190
 
 
191
  for (int i = max_code_size + 1; i <= MAX_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i];
 
192
 
 
193
  uint32 total = 0;
 
194
  for (int i = max_code_size; i > 0; i--)
 
195
    total += (((uint32)pNum_codes[i]) << (max_code_size - i));
 
196
 
 
197
  while (total != (1UL << max_code_size))
 
198
  {
 
199
    pNum_codes[max_code_size]--;
 
200
    for (int i = max_code_size - 1; i > 0; i--)
 
201
    {
 
202
      if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; }
 
203
    }
 
204
    total--;
 
205
  }
 
206
}
 
207
 
 
208
// Generates an optimized offman table.
 
209
void jpeg_encoder::optimize_huffman_table(int table_num, int table_len)
 
210
{
 
211
  sym_freq syms0[MAX_HUFF_SYMBOLS], syms1[MAX_HUFF_SYMBOLS];
 
212
  syms0[0].m_key = 1; syms0[0].m_sym_index = 0;  // dummy symbol, assures that no valid code contains all 1's
 
213
  int num_used_syms = 1;
 
214
  const uint32 *pSym_count = &m_huff_count[table_num][0];
 
215
  for (int i = 0; i < table_len; i++)
 
216
    if (pSym_count[i]) { syms0[num_used_syms].m_key = pSym_count[i]; syms0[num_used_syms++].m_sym_index = i + 1; }
 
217
  sym_freq* pSyms = radix_sort_syms(num_used_syms, syms0, syms1);
 
218
  calculate_minimum_redundancy(pSyms, num_used_syms);
 
219
 
 
220
  // Count the # of symbols of each code size.
 
221
  int num_codes[1 + MAX_HUFF_CODESIZE]; clear_obj(num_codes);
 
222
  for (int i = 0; i < num_used_syms; i++)
 
223
    num_codes[pSyms[i].m_key]++;
 
224
 
 
225
  const uint JPGE_CODE_SIZE_LIMIT = 16; // the maximum possible size of a JPEG Huffman code (valid range is [9,16] - 9 vs. 8 because of the dummy symbol)
 
226
  huffman_enforce_max_code_size(num_codes, num_used_syms, JPGE_CODE_SIZE_LIMIT);
 
227
 
 
228
  // Compute m_huff_bits array, which contains the # of symbols per code size.
 
229
  clear_obj(m_huff_bits[table_num]);
 
230
  for (int i = 1; i <= (int)JPGE_CODE_SIZE_LIMIT; i++)
 
231
    m_huff_bits[table_num][i] = static_cast<uint8>(num_codes[i]);
 
232
 
 
233
  // Remove the dummy symbol added above, which must be in largest bucket.
 
234
  for (int i = JPGE_CODE_SIZE_LIMIT; i >= 1; i--)
 
235
  {
 
236
    if (m_huff_bits[table_num][i]) { m_huff_bits[table_num][i]--; break; }
 
237
  }
 
238
 
 
239
  // Compute the m_huff_val array, which contains the symbol indices sorted by code size (smallest to largest).
 
240
  for (int i = num_used_syms - 1; i >= 1; i--)
 
241
    m_huff_val[table_num][num_used_syms - 1 - i] = static_cast<uint8>(pSyms[i].m_sym_index - 1);
 
242
}
 
243
 
 
244
// JPEG marker generation.
 
245
void jpeg_encoder::emit_byte(uint8 i)
 
246
{
 
247
  m_all_stream_writes_succeeded = m_all_stream_writes_succeeded && m_pStream->put_obj(i);
 
248
}
 
249
 
 
250
void jpeg_encoder::emit_word(uint i)
 
251
{
 
252
  emit_byte(uint8(i >> 8)); emit_byte(uint8(i & 0xFF));
 
253
}
 
254
 
 
255
void jpeg_encoder::emit_marker(int marker)
 
256
{
 
257
  emit_byte(uint8(0xFF)); emit_byte(uint8(marker));
 
258
}
 
259
 
 
260
// Emit JFIF marker
 
261
void jpeg_encoder::emit_jfif_app0()
 
262
{
 
263
  emit_marker(M_APP0);
 
264
  emit_word(2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1);
 
265
  emit_byte(0x4A); emit_byte(0x46); emit_byte(0x49); emit_byte(0x46); /* Identifier: ASCII "JFIF" */
 
266
  emit_byte(0);
 
267
  emit_byte(1);      /* Major version */
 
268
  emit_byte(1);      /* Minor version */
 
269
  emit_byte(0);      /* Density unit */
 
270
  emit_word(1);
 
271
  emit_word(1);
 
272
  emit_byte(0);      /* No thumbnail image */
 
273
  emit_byte(0);
 
274
}
 
275
 
 
276
// Emit quantization tables
 
277
void jpeg_encoder::emit_dqt()
 
278
{
 
279
  for (int i = 0; i < ((m_num_components == 3) ? 2 : 1); i++)
 
280
  {
 
281
    emit_marker(M_DQT);
 
282
    emit_word(64 + 1 + 2);
 
283
    emit_byte(static_cast<uint8>(i));
 
284
    for (int j = 0; j < 64; j++)
 
285
      emit_byte(static_cast<uint8>(m_quantization_tables[i][j]));
 
286
  }
 
287
}
 
288
 
 
289
// Emit start of frame marker
 
290
void jpeg_encoder::emit_sof()
 
291
{
 
292
  emit_marker(M_SOF0);                           /* baseline */
 
293
  emit_word(3 * m_num_components + 2 + 5 + 1);
 
294
  emit_byte(8);                                  /* precision */
 
295
  emit_word(m_image_y);
 
296
  emit_word(m_image_x);
 
297
  emit_byte(m_num_components);
 
298
  for (int i = 0; i < m_num_components; i++)
 
299
  {
 
300
    emit_byte(static_cast<uint8>(i + 1));                                   /* component ID     */
 
301
    emit_byte((m_comp_h_samp[i] << 4) + m_comp_v_samp[i]);  /* h and v sampling */
 
302
    emit_byte(i > 0);                                   /* quant. table num */
 
303
  }
 
304
}
 
305
 
 
306
// Emit Huffman table.
 
307
void jpeg_encoder::emit_dht(uint8 *bits, uint8 *val, int index, bool ac_flag)
 
308
{
 
309
  emit_marker(M_DHT);
 
310
 
 
311
  int length = 0;
 
312
  for (int i = 1; i <= 16; i++)
 
313
    length += bits[i];
 
314
 
 
315
  emit_word(length + 2 + 1 + 16);
 
316
  emit_byte(static_cast<uint8>(index + (ac_flag << 4)));
 
317
 
 
318
  for (int i = 1; i <= 16; i++)
 
319
    emit_byte(bits[i]);
 
320
 
 
321
  for (int i = 0; i < length; i++)
 
322
    emit_byte(val[i]);
 
323
}
 
324
 
 
325
// Emit all Huffman tables.
 
326
void jpeg_encoder::emit_dhts()
 
327
{
 
328
  emit_dht(m_huff_bits[0+0], m_huff_val[0+0], 0, false);
 
329
  emit_dht(m_huff_bits[2+0], m_huff_val[2+0], 0, true);
 
330
  if (m_num_components == 3)
 
331
  {
 
332
    emit_dht(m_huff_bits[0+1], m_huff_val[0+1], 1, false);
 
333
    emit_dht(m_huff_bits[2+1], m_huff_val[2+1], 1, true);
 
334
  }
 
335
}
 
336
 
 
337
// emit start of scan
 
338
void jpeg_encoder::emit_sos()
 
339
{
 
340
  emit_marker(M_SOS);
 
341
  emit_word(2 * m_num_components + 2 + 1 + 3);
 
342
  emit_byte(m_num_components);
 
343
  for (int i = 0; i < m_num_components; i++)
 
344
  {
 
345
    emit_byte(static_cast<uint8>(i + 1));
 
346
    if (i == 0)
 
347
      emit_byte((0 << 4) + 0);
 
348
    else
 
349
      emit_byte((1 << 4) + 1);
 
350
  }
 
351
  emit_byte(0);     /* spectral selection */
 
352
  emit_byte(63);
 
353
  emit_byte(0);
 
354
}
 
355
 
 
356
// Emit all markers at beginning of image file.
 
357
void jpeg_encoder::emit_markers()
 
358
{
 
359
  emit_marker(M_SOI);
 
360
  emit_jfif_app0();
 
361
  emit_dqt();
 
362
  emit_sof();
 
363
  emit_dhts();
 
364
  emit_sos();
 
365
}
 
366
 
 
367
// Compute the actual canonical Huffman codes/code sizes given the JPEG huff bits and val arrays.
 
368
void jpeg_encoder::compute_huffman_table(uint *codes, uint8 *code_sizes, uint8 *bits, uint8 *val)
 
369
{
 
370
  int i, l, last_p, si;
 
371
  uint8 huff_size[257];
 
372
  uint huff_code[257];
 
373
  uint code;
 
374
 
 
375
  int p = 0;
 
376
  for (l = 1; l <= 16; l++)
 
377
    for (i = 1; i <= bits[l]; i++)
 
378
      huff_size[p++] = (char)l;
 
379
 
 
380
  huff_size[p] = 0; last_p = p; // write sentinel
 
381
 
 
382
  code = 0; si = huff_size[0]; p = 0;
 
383
 
 
384
  while (huff_size[p])
 
385
  {
 
386
    while (huff_size[p] == si)
 
387
      huff_code[p++] = code++;
 
388
    code <<= 1;
 
389
    si++;
 
390
  }
 
391
 
 
392
  memset(codes, 0, sizeof(codes[0])*256);
 
393
  memset(code_sizes, 0, sizeof(code_sizes[0])*256);
 
394
  for (p = 0; p < last_p; p++)
 
395
  {
 
396
    codes[val[p]]      = huff_code[p];
 
397
    code_sizes[val[p]] = huff_size[p];
 
398
  }
 
399
}
 
400
 
 
401
// Quantization table generation.
 
402
void jpeg_encoder::compute_quant_table(int32 *pDst, int16 *pSrc)
 
403
{
 
404
  int32 q;
 
405
  if (m_params.m_quality < 50)
 
406
    q = 5000 / m_params.m_quality;
 
407
  else
 
408
    q = 200 - m_params.m_quality * 2;
 
409
  for (int i = 0; i < 64; i++)
 
410
  {
 
411
    int32 j = *pSrc++; j = (j * q + 50L) / 100L;
 
412
    *pDst++ = JPGE_MIN(JPGE_MAX(j, 1), 255);
 
413
  }
 
414
}
 
415
 
 
416
// Higher-level methods.
 
417
void jpeg_encoder::first_pass_init()
 
418
{
 
419
  m_bit_buffer = 0; m_bits_in = 0;
 
420
  memset(m_last_dc_val, 0, 3 * sizeof(m_last_dc_val[0]));
 
421
  m_mcu_y_ofs = 0;
 
422
  m_pass_num = 1;
 
423
}
 
424
 
 
425
bool jpeg_encoder::second_pass_init()
 
426
{
 
427
  compute_huffman_table(&m_huff_codes[0+0][0], &m_huff_code_sizes[0+0][0], m_huff_bits[0+0], m_huff_val[0+0]);
 
428
  compute_huffman_table(&m_huff_codes[2+0][0], &m_huff_code_sizes[2+0][0], m_huff_bits[2+0], m_huff_val[2+0]);
 
429
  if (m_num_components > 1)
 
430
  {
 
431
    compute_huffman_table(&m_huff_codes[0+1][0], &m_huff_code_sizes[0+1][0], m_huff_bits[0+1], m_huff_val[0+1]);
 
432
    compute_huffman_table(&m_huff_codes[2+1][0], &m_huff_code_sizes[2+1][0], m_huff_bits[2+1], m_huff_val[2+1]);
 
433
  }
 
434
  first_pass_init();
 
435
  emit_markers();
 
436
  m_pass_num = 2;
 
437
  return true;
 
438
}
 
439
 
 
440
bool jpeg_encoder::jpg_open(int p_x_res, int p_y_res, int src_channels)
 
441
{
 
442
  m_num_components = 3;
 
443
  switch (m_params.m_subsampling)
 
444
  {
 
445
    case Y_ONLY:
 
446
    {
 
447
      m_num_components = 1;
 
448
      m_comp_h_samp[0] = 1; m_comp_v_samp[0] = 1;
 
449
      m_mcu_x          = 8; m_mcu_y          = 8;
 
450
      break;
 
451
    }
 
452
    case H1V1:
 
453
    {
 
454
      m_comp_h_samp[0] = 1; m_comp_v_samp[0] = 1;
 
455
      m_comp_h_samp[1] = 1; m_comp_v_samp[1] = 1;
 
456
      m_comp_h_samp[2] = 1; m_comp_v_samp[2] = 1;
 
457
      m_mcu_x          = 8; m_mcu_y          = 8;
 
458
      break;
 
459
    }
 
460
    case H2V1:
 
461
    {
 
462
      m_comp_h_samp[0] = 2; m_comp_v_samp[0] = 1;
 
463
      m_comp_h_samp[1] = 1; m_comp_v_samp[1] = 1;
 
464
      m_comp_h_samp[2] = 1; m_comp_v_samp[2] = 1;
 
465
      m_mcu_x          = 16; m_mcu_y         = 8;
 
466
      break;
 
467
    }
 
468
    case H2V2:
 
469
    {
 
470
      m_comp_h_samp[0] = 2; m_comp_v_samp[0] = 2;
 
471
      m_comp_h_samp[1] = 1; m_comp_v_samp[1] = 1;
 
472
      m_comp_h_samp[2] = 1; m_comp_v_samp[2] = 1;
 
473
      m_mcu_x          = 16; m_mcu_y         = 16;
 
474
    }
 
475
  }
 
476
 
 
477
  m_image_x        = p_x_res; m_image_y = p_y_res;
 
478
  m_image_bpp      = src_channels;
 
479
  m_image_bpl      = m_image_x * src_channels;
 
480
  m_image_x_mcu    = (m_image_x + m_mcu_x - 1) & (~(m_mcu_x - 1));
 
481
  m_image_y_mcu    = (m_image_y + m_mcu_y - 1) & (~(m_mcu_y - 1));
 
482
  m_image_bpl_xlt  = m_image_x * m_num_components;
 
483
  m_image_bpl_mcu  = m_image_x_mcu * m_num_components;
 
484
  m_mcus_per_row   = m_image_x_mcu / m_mcu_x;
 
485
 
 
486
  if ((m_mcu_lines[0] = static_cast<uint8*>(jpge_malloc(m_image_bpl_mcu * m_mcu_y))) == NULL) return false;
 
487
  for (int i = 1; i < m_mcu_y; i++)
 
488
    m_mcu_lines[i] = m_mcu_lines[i-1] + m_image_bpl_mcu;
 
489
 
 
490
  compute_quant_table(m_quantization_tables[0], s_std_lum_quant);
 
491
  compute_quant_table(m_quantization_tables[1], m_params.m_no_chroma_discrim_flag ? s_std_lum_quant : s_std_croma_quant);
 
492
 
 
493
  m_out_buf_left = JPGE_OUT_BUF_SIZE;
 
494
  m_pOut_buf = m_out_buf;
 
495
 
 
496
  if (m_params.m_two_pass_flag)
 
497
  {
 
498
    clear_obj(m_huff_count);
 
499
    first_pass_init();
 
500
  }
 
501
  else
 
502
  {
 
503
    memcpy(m_huff_bits[0+0], s_dc_lum_bits, 17);    memcpy(m_huff_val [0+0], s_dc_lum_val, DC_LUM_CODES);
 
504
    memcpy(m_huff_bits[2+0], s_ac_lum_bits, 17);    memcpy(m_huff_val [2+0], s_ac_lum_val, AC_LUM_CODES);
 
505
    memcpy(m_huff_bits[0+1], s_dc_chroma_bits, 17); memcpy(m_huff_val [0+1], s_dc_chroma_val, DC_CHROMA_CODES);
 
506
    memcpy(m_huff_bits[2+1], s_ac_chroma_bits, 17); memcpy(m_huff_val [2+1], s_ac_chroma_val, AC_CHROMA_CODES);
 
507
    if (!second_pass_init()) return false;   // in effect, skip over the first pass
 
508
  }
 
509
  return m_all_stream_writes_succeeded;
 
510
}
 
511
 
 
512
void jpeg_encoder::load_block_8_8_grey(int x)
 
513
{
 
514
  uint8 *pSrc;
 
515
  sample_array_t *pDst = m_sample_array;
 
516
  x <<= 3;
 
517
  for (int i = 0; i < 8; i++, pDst += 8)
 
518
  {
 
519
    pSrc = m_mcu_lines[i] + x;
 
520
    pDst[0] = pSrc[0] - 128; pDst[1] = pSrc[1] - 128; pDst[2] = pSrc[2] - 128; pDst[3] = pSrc[3] - 128;
 
521
    pDst[4] = pSrc[4] - 128; pDst[5] = pSrc[5] - 128; pDst[6] = pSrc[6] - 128; pDst[7] = pSrc[7] - 128;
 
522
  }
 
523
}
 
524
 
 
525
void jpeg_encoder::load_block_8_8(int x, int y, int c)
 
526
{
 
527
  uint8 *pSrc;
 
528
  sample_array_t *pDst = m_sample_array;
 
529
  x = (x * (8 * 3)) + c;
 
530
  y <<= 3;
 
531
  for (int i = 0; i < 8; i++, pDst += 8)
 
532
  {
 
533
    pSrc = m_mcu_lines[y + i] + x;
 
534
    pDst[0] = pSrc[0 * 3] - 128; pDst[1] = pSrc[1 * 3] - 128; pDst[2] = pSrc[2 * 3] - 128; pDst[3] = pSrc[3 * 3] - 128;
 
535
    pDst[4] = pSrc[4 * 3] - 128; pDst[5] = pSrc[5 * 3] - 128; pDst[6] = pSrc[6 * 3] - 128; pDst[7] = pSrc[7 * 3] - 128;
 
536
  }
 
537
}
 
538
 
 
539
void jpeg_encoder::load_block_16_8(int x, int c)
 
540
{
 
541
  uint8 *pSrc1, *pSrc2;
 
542
  sample_array_t *pDst = m_sample_array;
 
543
  x = (x * (16 * 3)) + c;
 
544
  int a = 0, b = 2;
 
545
  for (int i = 0; i < 16; i += 2, pDst += 8)
 
546
  {
 
547
    pSrc1 = m_mcu_lines[i + 0] + x;
 
548
    pSrc2 = m_mcu_lines[i + 1] + x;
 
549
    pDst[0] = ((pSrc1[ 0 * 3] + pSrc1[ 1 * 3] + pSrc2[ 0 * 3] + pSrc2[ 1 * 3] + a) >> 2) - 128; pDst[1] = ((pSrc1[ 2 * 3] + pSrc1[ 3 * 3] + pSrc2[ 2 * 3] + pSrc2[ 3 * 3] + b) >> 2) - 128;
 
550
    pDst[2] = ((pSrc1[ 4 * 3] + pSrc1[ 5 * 3] + pSrc2[ 4 * 3] + pSrc2[ 5 * 3] + a) >> 2) - 128; pDst[3] = ((pSrc1[ 6 * 3] + pSrc1[ 7 * 3] + pSrc2[ 6 * 3] + pSrc2[ 7 * 3] + b) >> 2) - 128;
 
551
    pDst[4] = ((pSrc1[ 8 * 3] + pSrc1[ 9 * 3] + pSrc2[ 8 * 3] + pSrc2[ 9 * 3] + a) >> 2) - 128; pDst[5] = ((pSrc1[10 * 3] + pSrc1[11 * 3] + pSrc2[10 * 3] + pSrc2[11 * 3] + b) >> 2) - 128;
 
552
    pDst[6] = ((pSrc1[12 * 3] + pSrc1[13 * 3] + pSrc2[12 * 3] + pSrc2[13 * 3] + a) >> 2) - 128; pDst[7] = ((pSrc1[14 * 3] + pSrc1[15 * 3] + pSrc2[14 * 3] + pSrc2[15 * 3] + b) >> 2) - 128;
 
553
    int temp = a; a = b; b = temp;
 
554
  }
 
555
}
 
556
 
 
557
void jpeg_encoder::load_block_16_8_8(int x, int c)
 
558
{
 
559
  uint8 *pSrc1;
 
560
  sample_array_t *pDst = m_sample_array;
 
561
  x = (x * (16 * 3)) + c;
 
562
  for (int i = 0; i < 8; i++, pDst += 8)
 
563
  {
 
564
    pSrc1 = m_mcu_lines[i + 0] + x;
 
565
    pDst[0] = ((pSrc1[ 0 * 3] + pSrc1[ 1 * 3]) >> 1) - 128; pDst[1] = ((pSrc1[ 2 * 3] + pSrc1[ 3 * 3]) >> 1) - 128;
 
566
    pDst[2] = ((pSrc1[ 4 * 3] + pSrc1[ 5 * 3]) >> 1) - 128; pDst[3] = ((pSrc1[ 6 * 3] + pSrc1[ 7 * 3]) >> 1) - 128;
 
567
    pDst[4] = ((pSrc1[ 8 * 3] + pSrc1[ 9 * 3]) >> 1) - 128; pDst[5] = ((pSrc1[10 * 3] + pSrc1[11 * 3]) >> 1) - 128;
 
568
    pDst[6] = ((pSrc1[12 * 3] + pSrc1[13 * 3]) >> 1) - 128; pDst[7] = ((pSrc1[14 * 3] + pSrc1[15 * 3]) >> 1) - 128;
 
569
  }
 
570
}
 
571
 
 
572
void jpeg_encoder::load_quantized_coefficients(int component_num)
 
573
{
 
574
  int32 *q = m_quantization_tables[component_num > 0];
 
575
  int16 *pDst = m_coefficient_array;
 
576
  for (int i = 0; i < 64; i++)
 
577
  {
 
578
    sample_array_t j = m_sample_array[s_zag[i]];
 
579
    if (j < 0)
 
580
    {
 
581
      if ((j = -j + (*q >> 1)) < *q)
 
582
        *pDst++ = 0;
 
583
      else
 
584
        *pDst++ = static_cast<int16>(-(j / *q));
 
585
    }
 
586
    else
 
587
    {
 
588
      if ((j = j + (*q >> 1)) < *q)
 
589
        *pDst++ = 0;
 
590
      else
 
591
        *pDst++ = static_cast<int16>((j / *q));
 
592
    }
 
593
    q++;
 
594
  }
 
595
}
 
596
 
 
597
void jpeg_encoder::flush_output_buffer()
 
598
{
 
599
  if (m_out_buf_left != JPGE_OUT_BUF_SIZE)
 
600
    m_all_stream_writes_succeeded = m_all_stream_writes_succeeded && m_pStream->put_buf(m_out_buf, JPGE_OUT_BUF_SIZE - m_out_buf_left);
 
601
  m_pOut_buf = m_out_buf;
 
602
  m_out_buf_left = JPGE_OUT_BUF_SIZE;
 
603
}
 
604
 
 
605
void jpeg_encoder::put_bits(uint bits, uint len)
 
606
{
 
607
  m_bit_buffer |= ((uint32)bits << (24 - (m_bits_in += len)));
 
608
  while (m_bits_in >= 8)
 
609
  {
 
610
    uint8 c;
 
611
    #define JPGE_PUT_BYTE(c) { *m_pOut_buf++ = (c); if (--m_out_buf_left == 0) flush_output_buffer(); }
 
612
    JPGE_PUT_BYTE(c = (uint8)((m_bit_buffer >> 16) & 0xFF));
 
613
    if (c == 0xFF) JPGE_PUT_BYTE(0);
 
614
    m_bit_buffer <<= 8;
 
615
    m_bits_in -= 8;
 
616
  }
 
617
}
 
618
 
 
619
void jpeg_encoder::code_coefficients_pass_one(int component_num)
 
620
{
 
621
  if (component_num >= 3) return; // just to shut up static analysis
 
622
  int i, run_len, nbits, temp1;
 
623
  int16 *src = m_coefficient_array;
 
624
  uint32 *dc_count = component_num ? m_huff_count[0 + 1] : m_huff_count[0 + 0], *ac_count = component_num ? m_huff_count[2 + 1] : m_huff_count[2 + 0];
 
625
 
 
626
  temp1 = src[0] - m_last_dc_val[component_num];
 
627
  m_last_dc_val[component_num] = src[0];
 
628
  if (temp1 < 0) temp1 = -temp1;
 
629
 
 
630
  nbits = 0;
 
631
  while (temp1)
 
632
  {
 
633
    nbits++; temp1 >>= 1;
 
634
  }
 
635
 
 
636
  dc_count[nbits]++;
 
637
  for (run_len = 0, i = 1; i < 64; i++)
 
638
  {
 
639
    if ((temp1 = m_coefficient_array[i]) == 0)
 
640
      run_len++;
 
641
    else
 
642
    {
 
643
      while (run_len >= 16)
 
644
      {
 
645
        ac_count[0xF0]++;
 
646
        run_len -= 16;
 
647
      }
 
648
      if (temp1 < 0) temp1 = -temp1;
 
649
      nbits = 1;
 
650
      while (temp1 >>= 1) nbits++;
 
651
      ac_count[(run_len << 4) + nbits]++;
 
652
      run_len = 0;
 
653
    }
 
654
  }
 
655
  if (run_len) ac_count[0]++;
 
656
}
 
657
 
 
658
void jpeg_encoder::code_coefficients_pass_two(int component_num)
 
659
{
 
660
  int i, j, run_len, nbits, temp1, temp2;
 
661
  int16 *pSrc = m_coefficient_array;
 
662
  uint *codes[2];
 
663
  uint8 *code_sizes[2];
 
664
 
 
665
  if (component_num == 0)
 
666
  {
 
667
    codes[0] = m_huff_codes[0 + 0]; codes[1] = m_huff_codes[2 + 0];
 
668
    code_sizes[0] = m_huff_code_sizes[0 + 0]; code_sizes[1] = m_huff_code_sizes[2 + 0];
 
669
  }
 
670
  else
 
671
  {
 
672
    codes[0] = m_huff_codes[0 + 1]; codes[1] = m_huff_codes[2 + 1];
 
673
    code_sizes[0] = m_huff_code_sizes[0 + 1]; code_sizes[1] = m_huff_code_sizes[2 + 1];
 
674
  }
 
675
 
 
676
  temp1 = temp2 = pSrc[0] - m_last_dc_val[component_num];
 
677
  m_last_dc_val[component_num] = pSrc[0];
 
678
 
 
679
  if (temp1 < 0)
 
680
  {
 
681
    temp1 = -temp1; temp2--;
 
682
  }
 
683
 
 
684
  nbits = 0;
 
685
  while (temp1)
 
686
  {
 
687
    nbits++; temp1 >>= 1;
 
688
  }
 
689
 
 
690
  put_bits(codes[0][nbits], code_sizes[0][nbits]);
 
691
  if (nbits) put_bits(temp2 & ((1 << nbits) - 1), nbits);
 
692
 
 
693
  for (run_len = 0, i = 1; i < 64; i++)
 
694
  {
 
695
    if ((temp1 = m_coefficient_array[i]) == 0)
 
696
      run_len++;
 
697
    else
 
698
    {
 
699
      while (run_len >= 16)
 
700
      {
 
701
        put_bits(codes[1][0xF0], code_sizes[1][0xF0]);
 
702
        run_len -= 16;
 
703
      }
 
704
      if ((temp2 = temp1) < 0)
 
705
      {
 
706
        temp1 = -temp1;
 
707
        temp2--;
 
708
      }
 
709
      nbits = 1;
 
710
      while (temp1 >>= 1)
 
711
        nbits++;
 
712
      j = (run_len << 4) + nbits;
 
713
      put_bits(codes[1][j], code_sizes[1][j]);
 
714
      put_bits(temp2 & ((1 << nbits) - 1), nbits);
 
715
      run_len = 0;
 
716
    }
 
717
  }
 
718
  if (run_len)
 
719
    put_bits(codes[1][0], code_sizes[1][0]);
 
720
}
 
721
 
 
722
void jpeg_encoder::code_block(int component_num)
 
723
{
 
724
  DCT2D(m_sample_array);
 
725
  load_quantized_coefficients(component_num);
 
726
  if (m_pass_num == 1)
 
727
    code_coefficients_pass_one(component_num);
 
728
  else
 
729
    code_coefficients_pass_two(component_num);
 
730
}
 
731
 
 
732
void jpeg_encoder::process_mcu_row()
 
733
{
 
734
  if (m_num_components == 1)
 
735
  {
 
736
    for (int i = 0; i < m_mcus_per_row; i++)
 
737
    {
 
738
      load_block_8_8_grey(i); code_block(0);
 
739
    }
 
740
  }
 
741
  else if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 1))
 
742
  {
 
743
    for (int i = 0; i < m_mcus_per_row; i++)
 
744
    {
 
745
      load_block_8_8(i, 0, 0); code_block(0); load_block_8_8(i, 0, 1); code_block(1); load_block_8_8(i, 0, 2); code_block(2);
 
746
    }
 
747
  }
 
748
  else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 1))
 
749
  {
 
750
    for (int i = 0; i < m_mcus_per_row; i++)
 
751
    {
 
752
      load_block_8_8(i * 2 + 0, 0, 0); code_block(0); load_block_8_8(i * 2 + 1, 0, 0); code_block(0);
 
753
      load_block_16_8_8(i, 1); code_block(1); load_block_16_8_8(i, 2); code_block(2);
 
754
    }
 
755
  }
 
756
  else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 2))
 
757
  {
 
758
    for (int i = 0; i < m_mcus_per_row; i++)
 
759
    {
 
760
      load_block_8_8(i * 2 + 0, 0, 0); code_block(0); load_block_8_8(i * 2 + 1, 0, 0); code_block(0);
 
761
      load_block_8_8(i * 2 + 0, 1, 0); code_block(0); load_block_8_8(i * 2 + 1, 1, 0); code_block(0);
 
762
      load_block_16_8(i, 1); code_block(1); load_block_16_8(i, 2); code_block(2);
 
763
    }
 
764
  }
 
765
}
 
766
 
 
767
bool jpeg_encoder::terminate_pass_one()
 
768
{
 
769
  optimize_huffman_table(0+0, DC_LUM_CODES); optimize_huffman_table(2+0, AC_LUM_CODES);
 
770
  if (m_num_components > 1)
 
771
  {
 
772
    optimize_huffman_table(0+1, DC_CHROMA_CODES); optimize_huffman_table(2+1, AC_CHROMA_CODES);
 
773
  }
 
774
  return second_pass_init();
 
775
}
 
776
 
 
777
bool jpeg_encoder::terminate_pass_two()
 
778
{
 
779
  put_bits(0x7F, 7);
 
780
  flush_output_buffer();
 
781
  emit_marker(M_EOI);
 
782
  m_pass_num++; // purposely bump up m_pass_num, for debugging
 
783
  return true;
 
784
}
 
785
 
 
786
bool jpeg_encoder::process_end_of_image()
 
787
{
 
788
  if (m_mcu_y_ofs)
 
789
  {
 
790
    if (m_mcu_y_ofs < 16) // check here just to shut up static analysis
 
791
    {
 
792
      for (int i = m_mcu_y_ofs; i < m_mcu_y; i++)
 
793
        memcpy(m_mcu_lines[i], m_mcu_lines[m_mcu_y_ofs - 1], m_image_bpl_mcu);
 
794
    }
 
795
 
 
796
    process_mcu_row();
 
797
  }
 
798
 
 
799
  if (m_pass_num == 1)
 
800
    return terminate_pass_one();
 
801
  else
 
802
    return terminate_pass_two();
 
803
}
 
804
 
 
805
void jpeg_encoder::load_mcu(const void *pSrc)
 
806
{
 
807
  const uint8* Psrc = reinterpret_cast<const uint8*>(pSrc);
 
808
 
 
809
  uint8* pDst = m_mcu_lines[m_mcu_y_ofs]; // OK to write up to m_image_bpl_xlt bytes to pDst
 
810
 
 
811
  if (m_num_components == 1)
 
812
  {
 
813
    if (m_image_bpp == 4)
 
814
      RGBA_to_Y(pDst, Psrc, m_image_x);
 
815
    else if (m_image_bpp == 3)
 
816
      RGB_to_Y(pDst, Psrc, m_image_x);
 
817
    else
 
818
      memcpy(pDst, Psrc, m_image_x);
 
819
  }
 
820
  else
 
821
  {
 
822
    if (m_image_bpp == 4)
 
823
      RGBA_to_YCC(pDst, Psrc, m_image_x);
 
824
    else if (m_image_bpp == 3)
 
825
      RGB_to_YCC(pDst, Psrc, m_image_x);
 
826
    else
 
827
      Y_to_YCC(pDst, Psrc, m_image_x);
 
828
  }
 
829
 
 
830
  // Possibly duplicate pixels at end of scanline if not a multiple of 8 or 16
 
831
  if (m_num_components == 1)
 
832
    memset(m_mcu_lines[m_mcu_y_ofs] + m_image_bpl_xlt, pDst[m_image_bpl_xlt - 1], m_image_x_mcu - m_image_x);
 
833
  else
 
834
  {
 
835
    const uint8 y = pDst[m_image_bpl_xlt - 3 + 0], cb = pDst[m_image_bpl_xlt - 3 + 1], cr = pDst[m_image_bpl_xlt - 3 + 2];
 
836
    uint8 *q = m_mcu_lines[m_mcu_y_ofs] + m_image_bpl_xlt;
 
837
    for (int i = m_image_x; i < m_image_x_mcu; i++)
 
838
    {
 
839
      *q++ = y; *q++ = cb; *q++ = cr;
 
840
    }
 
841
  }
 
842
 
 
843
  if (++m_mcu_y_ofs == m_mcu_y)
 
844
  {
 
845
    process_mcu_row();
 
846
    m_mcu_y_ofs = 0;
 
847
  }
 
848
}
 
849
 
 
850
void jpeg_encoder::clear()
 
851
{
 
852
  m_mcu_lines[0] = NULL;
 
853
  m_pass_num = 0;
 
854
  m_all_stream_writes_succeeded = true;
 
855
}
 
856
 
 
857
jpeg_encoder::jpeg_encoder()
 
858
{
 
859
  clear();
 
860
}
 
861
 
 
862
jpeg_encoder::~jpeg_encoder()
 
863
{
 
864
  deinit();
 
865
}
 
866
 
 
867
bool jpeg_encoder::init(output_stream *pStream, int width, int height, int src_channels, const params &comp_params)
 
868
{
 
869
  deinit();
 
870
  if (((!pStream) || (width < 1) || (height < 1)) || ((src_channels != 1) && (src_channels != 3) && (src_channels != 4)) || (!comp_params.check())) return false;
 
871
  m_pStream = pStream;
 
872
  m_params = comp_params;
 
873
  return jpg_open(width, height, src_channels);
 
874
}
 
875
 
 
876
void jpeg_encoder::deinit()
 
877
{
 
878
  jpge_free(m_mcu_lines[0]);
 
879
  clear();
 
880
}
 
881
 
 
882
bool jpeg_encoder::process_scanline(const void* pScanline)
 
883
{
 
884
  if ((m_pass_num < 1) || (m_pass_num > 2)) return false;
 
885
  if (m_all_stream_writes_succeeded)
 
886
  {
 
887
    if (!pScanline)
 
888
    {
 
889
      if (!process_end_of_image()) return false;
 
890
    }
 
891
    else
 
892
    {
 
893
      load_mcu(pScanline);
 
894
    }
 
895
  }
 
896
  return m_all_stream_writes_succeeded;
 
897
}
 
898
 
 
899
class cfile_stream : public output_stream
 
900
{
 
901
   cfile_stream(const cfile_stream &);
 
902
   cfile_stream &operator= (const cfile_stream &);
 
903
 
 
904
   FILE* m_pFile;
 
905
   bool m_bStatus;
 
906
 
 
907
public:
 
908
   cfile_stream() : m_pFile(NULL), m_bStatus(false) { }
 
909
 
 
910
   virtual ~cfile_stream()
 
911
   {
 
912
      close();
 
913
   }
 
914
 
 
915
   bool open(const char *pFilename)
 
916
   {
 
917
      close();
 
918
      m_pFile = fopen(pFilename, "wb");
 
919
      m_bStatus = (m_pFile != NULL);
 
920
      return m_bStatus;
 
921
   }
 
922
 
 
923
   bool close()
 
924
   {
 
925
      if (m_pFile)
 
926
      {
 
927
         if (fclose(m_pFile) == EOF)
 
928
         {
 
929
            m_bStatus = false;
 
930
         }
 
931
         m_pFile = NULL;
 
932
      }
 
933
      return m_bStatus;
 
934
   }
 
935
 
 
936
   virtual bool put_buf(const void* pBuf, int len)
 
937
   {
 
938
      m_bStatus = m_bStatus && (fwrite(pBuf, len, 1, m_pFile) == 1);
 
939
      return m_bStatus;
 
940
   }
 
941
 
 
942
   uint get_size() const
 
943
   {
 
944
      return m_pFile ? ftell(m_pFile) : 0;
 
945
   }
 
946
};
 
947
 
 
948
// Writes JPEG image to file.
 
949
bool compress_image_to_jpeg_file(const char *pFilename, int width, int height, int num_channels, const uint8 *pImage_data, const params &comp_params)
 
950
{
 
951
  cfile_stream dst_stream;
 
952
  if (!dst_stream.open(pFilename))
 
953
    return false;
 
954
 
 
955
  jpge::jpeg_encoder dst_image;
 
956
  if (!dst_image.init(&dst_stream, width, height, num_channels, comp_params))
 
957
    return false;
 
958
 
 
959
  for (uint pass_index = 0; pass_index < dst_image.get_total_passes(); pass_index++)
 
960
  {
 
961
    for (int i = 0; i < height; i++)
 
962
    {
 
963
       const uint8* pBuf = pImage_data + i * width * num_channels;
 
964
       if (!dst_image.process_scanline(pBuf))
 
965
          return false;
 
966
    }
 
967
    if (!dst_image.process_scanline(NULL))
 
968
       return false;
 
969
  }
 
970
 
 
971
  dst_image.deinit();
 
972
 
 
973
  return dst_stream.close();
 
974
}
 
975
 
 
976
class memory_stream : public output_stream
 
977
{
 
978
   memory_stream(const memory_stream &);
 
979
   memory_stream &operator= (const memory_stream &);
 
980
 
 
981
   uint8 *m_pBuf;
 
982
   uint m_buf_size, m_buf_ofs;
 
983
 
 
984
public:
 
985
   memory_stream(void *pBuf, uint buf_size) : m_pBuf(static_cast<uint8*>(pBuf)), m_buf_size(buf_size), m_buf_ofs(0) { }
 
986
 
 
987
   virtual ~memory_stream() { }
 
988
 
 
989
   virtual bool put_buf(const void* pBuf, int len)
 
990
   {
 
991
      uint buf_remaining = m_buf_size - m_buf_ofs;
 
992
      if ((uint)len > buf_remaining)
 
993
         return false;
 
994
      memcpy(m_pBuf + m_buf_ofs, pBuf, len);
 
995
      m_buf_ofs += len;
 
996
      return true;
 
997
   }
 
998
 
 
999
   uint get_size() const
 
1000
   {
 
1001
      return m_buf_ofs;
 
1002
   }
 
1003
};
 
1004
 
 
1005
bool compress_image_to_jpeg_file_in_memory(void *pDstBuf, int &buf_size, int width, int height, int num_channels, const uint8 *pImage_data, const params &comp_params)
 
1006
{
 
1007
   if ((!pDstBuf) || (!buf_size))
 
1008
      return false;
 
1009
 
 
1010
   memory_stream dst_stream(pDstBuf, buf_size);
 
1011
 
 
1012
   buf_size = 0;
 
1013
 
 
1014
   jpge::jpeg_encoder dst_image;
 
1015
   if (!dst_image.init(&dst_stream, width, height, num_channels, comp_params))
 
1016
      return false;
 
1017
 
 
1018
   for (uint pass_index = 0; pass_index < dst_image.get_total_passes(); pass_index++)
 
1019
   {
 
1020
     for (int i = 0; i < height; i++)
 
1021
     {
 
1022
        const uint8* pScanline = pImage_data + i * width * num_channels;
 
1023
        if (!dst_image.process_scanline(pScanline))
 
1024
           return false;
 
1025
     }
 
1026
     if (!dst_image.process_scanline(NULL))
 
1027
        return false;
 
1028
   }
 
1029
 
 
1030
   dst_image.deinit();
 
1031
 
 
1032
   buf_size = dst_stream.get_size();
 
1033
   return true;
 
1034
}
 
1035
 
 
1036
} // namespace jpge