jpge.cpp 36 KB

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