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