2
0

JPEGData.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. #define XMD_H
  2. #include "JPEGData.h"
  3. #include "MemStream.h"
  4. #include "ImageUtils.h"
  5. #include <setjmp.h>
  6. extern "C"
  7. {
  8. #include "jpeg/jpeglib.h"
  9. #include "jpeg/jerror.h"
  10. #include "jpeg/jpegint.h"
  11. }
  12. USING_NS_BF;
  13. // -----------------------------------------------------------------------
  14. // JPEG error handling
  15. // Will "longjmp" on error_exit.
  16. // -----------------------------------------------------------------------
  17. struct ErrorHandler
  18. {
  19. /** "subclass" of jpeg_error_mgr */
  20. struct jpeg_error_mgr errorMgr;
  21. jmp_buf setjmpBuffer;
  22. ErrorHandler( j_decompress_ptr cinfo )
  23. {
  24. Init( (j_common_ptr)cinfo );
  25. }
  26. ErrorHandler( j_compress_ptr cinfo )
  27. {
  28. Init( (j_common_ptr)cinfo );
  29. }
  30. void Init( j_common_ptr cinfo )
  31. {
  32. // setup the standard error handling.
  33. cinfo->err = jpeg_std_error( &errorMgr );
  34. // then hook up our error_exit function.
  35. errorMgr.error_exit = &ErrorHandler::OnErrorExit;
  36. }
  37. static void OnErrorExit( j_common_ptr cinfo )
  38. {
  39. // recover the pointer to "derived class" instance
  40. ErrorHandler* errorHandler = (ErrorHandler*)cinfo->err;
  41. // use the default error message output.
  42. (*cinfo->err->output_message)( cinfo );
  43. // return control to the setjmp point.
  44. longjmp( errorHandler->setjmpBuffer, 1 );
  45. }
  46. };
  47. struct JpegMemSource
  48. {
  49. JpegMemSource(JPEGData* buffer, j_decompress_ptr cinfo )
  50. {
  51. struct jpeg_source_mgr * src;
  52. if ( cinfo->src == NULL )
  53. {
  54. // Have the jpeg library allocate the source manager object so
  55. // that it is automatically deallocated by the decompressor.
  56. cinfo->src = (struct jpeg_source_mgr *)(*cinfo->mem->alloc_small)( (j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(struct jpeg_source_mgr) );
  57. }
  58. src = cinfo->src;
  59. src->init_source = &JpegMemSource::InitSource;
  60. src->fill_input_buffer = &JpegMemSource::FillInputBuffer;
  61. src->skip_input_data = &JpegMemSource::SkipInputData;
  62. src->resync_to_restart = jpeg_resync_to_restart; /* use default method */
  63. src->term_source = &JpegMemSource::TermSource;
  64. src->bytes_in_buffer = (size_t) buffer->mSrcDataLen;
  65. src->next_input_byte = (JOCTET *) buffer->mSrcData;
  66. }
  67. ~JpegMemSource()
  68. {
  69. // The setjmp/longjmp action in ErrorHandler can actually
  70. // completely skip the destruction of this C++ data source wrapper,
  71. // but that is OK so long as there is no actual cleanup to do.
  72. }
  73. static void InitSource( j_decompress_ptr cinfo )
  74. {
  75. /* no work necessary here */
  76. }
  77. static boolean FillInputBuffer( j_decompress_ptr cinfo )
  78. {
  79. static JOCTET mybuffer[4];
  80. /* The whole JPEG data is expected to reside in the supplied memory
  81. * buffer, so any request for more data beyond the given buffer size
  82. * is treated as an error.
  83. */
  84. WARNMS(cinfo, JWRN_JPEG_EOF);
  85. /* Insert a fake EOI marker */
  86. mybuffer[0] = (JOCTET) 0xFF;
  87. mybuffer[1] = (JOCTET) JPEG_EOI;
  88. cinfo->src->next_input_byte = mybuffer;
  89. cinfo->src->bytes_in_buffer = 2;
  90. return TRUE;
  91. }
  92. static void SkipInputData( j_decompress_ptr cinfo, long num_bytes )
  93. {
  94. struct jpeg_source_mgr * src = cinfo->src;
  95. /* Just a dumb implementation for now. Could use fseek() except
  96. * it doesn't work on pipes. Not clear that being smart is worth
  97. * any trouble anyway --- large skips are infrequent.
  98. */
  99. if (num_bytes > 0) {
  100. while (num_bytes > (long) src->bytes_in_buffer) {
  101. num_bytes -= (long) src->bytes_in_buffer;
  102. (void) (*src->fill_input_buffer) (cinfo);
  103. /* note we assume that fill_input_buffer will never return FALSE,
  104. * so suspension need not be handled.
  105. */
  106. }
  107. src->next_input_byte += (size_t) num_bytes;
  108. src->bytes_in_buffer -= (size_t) num_bytes;
  109. }
  110. }
  111. static void TermSource( j_decompress_ptr cinfo )
  112. {
  113. /* no work necessary here */
  114. }
  115. };
  116. #define JPEGMEMDEST_BLOCK_SIZE 16384
  117. struct JpegMemDest : jpeg_destination_mgr
  118. {
  119. Array<uint8> mData;
  120. JpegMemDest(JPEGData* buffer, j_compress_ptr cinfo)
  121. {
  122. if (cinfo->dest == NULL)
  123. {
  124. cinfo->dest = this;
  125. }
  126. init_destination = &InitDestination;
  127. empty_output_buffer = &EmptyOutputBuffer;
  128. term_destination = &TermDestination;
  129. }
  130. ~JpegMemDest()
  131. {
  132. }
  133. static void InitDestination(j_compress_ptr cinfo)
  134. {
  135. auto self = (JpegMemDest*)cinfo->dest;
  136. self->mData.Resize(JPEGMEMDEST_BLOCK_SIZE);
  137. cinfo->dest->next_output_byte = &self->mData[0];
  138. cinfo->dest->free_in_buffer = self->mData.size();
  139. }
  140. static boolean EmptyOutputBuffer(j_compress_ptr cinfo)
  141. {
  142. auto self = (JpegMemDest*)cinfo->dest;
  143. size_t oldsize = self->mData.size();
  144. self->mData.Resize(oldsize + JPEGMEMDEST_BLOCK_SIZE);
  145. cinfo->dest->next_output_byte = &self->mData[oldsize];
  146. cinfo->dest->free_in_buffer = self->mData.size() - oldsize;
  147. return true;
  148. }
  149. static void TermDestination(j_compress_ptr cinfo)
  150. {
  151. auto self = (JpegMemDest*)cinfo->dest;
  152. self->mData.Resize(self->mData.size() - cinfo->dest->free_in_buffer);
  153. }
  154. };
  155. bool JPEGData::ReadData()
  156. {
  157. jpeg_decompress_struct cinfo;
  158. ErrorHandler err( &cinfo );
  159. if ( setjmp( err.setjmpBuffer ) )
  160. {
  161. // ErrorHandler::OnErrorExit will longjmp back to here from
  162. // within the ReadImage call below.
  163. jpeg_destroy_decompress( &cinfo );
  164. return false;
  165. }
  166. jpeg_create_decompress( &cinfo );
  167. JpegMemSource(this, &cinfo );
  168. jpeg_read_header( &cinfo, TRUE );
  169. jpeg_start_decompress( &cinfo );
  170. mWidth = cinfo.output_width;
  171. mHeight = cinfo.output_height;
  172. mBits = new uint32[ mWidth * mHeight ];
  173. uint32* destPtr = mBits;
  174. // Have the jpeg library allocate a scan-line buffer as a
  175. // per-image resource so that it will be automatically deallocated
  176. // by jpeg_finish_decompress.
  177. int row_stride = cinfo.output_width * cinfo.output_components;
  178. unsigned char** scanline = (*cinfo.mem->alloc_sarray)( (j_common_ptr)&cinfo, JPOOL_IMAGE, row_stride, 1 );
  179. if ( cinfo.output_components == 1 )
  180. {
  181. while ( cinfo.output_scanline < cinfo.output_height )
  182. {
  183. jpeg_read_scanlines( &cinfo, scanline, 1 );
  184. uint8* p = *scanline;
  185. for ( JDIMENSION i = 0; i < cinfo.output_width; ++i )
  186. {
  187. int r = *p++;
  188. *destPtr++ = 0xFF000000 | (r << 16) | (r << 8) | (r);
  189. }
  190. }
  191. }
  192. else
  193. {
  194. while ( cinfo.output_scanline < cinfo.output_height )
  195. {
  196. jpeg_read_scanlines(&cinfo, scanline, 1 );
  197. uint8* p = *scanline;
  198. for ( JDIMENSION i = 0; i < cinfo.output_width; ++i )
  199. {
  200. int b = *p++;
  201. int g = *p++;
  202. int r = *p++;
  203. *destPtr++ = 0xFF000000 | (r << 16) | (g << 8) | (b);
  204. }
  205. }
  206. }
  207. jpeg_finish_decompress( &cinfo );
  208. jpeg_destroy_decompress( &cinfo );
  209. return true;
  210. }
  211. void JPEGData::Compress(int quality)
  212. {
  213. jpeg_compress_struct cinfo;
  214. /* Now we can initialize the JPEG compression object. */
  215. jpeg_create_compress(&cinfo);
  216. ErrorHandler err(&cinfo);
  217. if (setjmp(err.setjmpBuffer))
  218. {
  219. // ErrorHandler::OnErrorExit will longjmp back to here from
  220. // within the ReadImage call below.
  221. jpeg_destroy_compress(&cinfo);
  222. return;
  223. }
  224. JSAMPROW row_pointer[1];
  225. JpegMemDest jpegMemDest(this, &cinfo);
  226. //jpeg_stdio_dest(&cinfo, outfile);
  227. /* Step 3: set parameters for compression */
  228. /* First we supply a description of the input image.
  229. * Four fields of the cinfo struct must be filled in:
  230. */
  231. cinfo.image_width = mWidth; /* image width and height, in pixels */
  232. cinfo.image_height = mHeight;
  233. cinfo.input_components = 3; /* # of color components per pixel */
  234. cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
  235. /* Now use the library's routine to set default compression parameters.
  236. * (You must set at least cinfo.in_color_space before calling this,
  237. * since the defaults depend on the source color space.)
  238. */
  239. jpeg_set_defaults(&cinfo);
  240. /* Now you can set any non-default parameters you wish to.
  241. * Here we just illustrate the use of quality (quantization table) scaling:
  242. */
  243. jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
  244. /* Step 4: Start compressor */
  245. /* TRUE ensures that we will write a complete interchange-JPEG file.
  246. * Pass TRUE unless you are very sure of what you're doing.
  247. */
  248. jpeg_start_compress(&cinfo, TRUE);
  249. /* Step 5: while (scan lines remain to be written) */
  250. /* jpeg_write_scanlines(...); */
  251. /* Here we use the library's state variable cinfo.next_scanline as the
  252. * loop counter, so that we don't have to keep track ourselves.
  253. * To keep things simple, we pass one scanline per call; you can pass
  254. * more if you wish, though.
  255. */
  256. int row_stride = mWidth * 3; /* JSAMPLEs per row in image_buffer */
  257. uint8* line = new uint8[mWidth * 3];
  258. row_pointer[0] = (JSAMPROW)line;
  259. while (cinfo.next_scanline < cinfo.image_height)
  260. {
  261. uint8* src = (uint8*)&mBits[cinfo.next_scanline * mWidth];
  262. uint8* dest = line;
  263. for (int x = 0; x < mWidth; x++)
  264. {
  265. *(dest++) = src[2];
  266. *(dest++) = src[1];
  267. *(dest++) = src[0];
  268. src += 4;
  269. }
  270. (void)jpeg_write_scanlines(&cinfo, row_pointer, 1);
  271. }
  272. delete line;
  273. /* Step 6: Finish compression */
  274. jpeg_finish_compress(&cinfo);
  275. /* After finish_compress, we can close the output file. */
  276. //fclose(outfile);
  277. /* Step 7: release JPEG compression object */
  278. /* This is an important step since it will release a good deal of memory. */
  279. jpeg_destroy_compress(&cinfo);
  280. mSrcDataLen = (int)jpegMemDest.mData.size();
  281. mSrcData = new uint8[mSrcDataLen];
  282. memcpy(mSrcData, &jpegMemDest.mData[0], mSrcDataLen);
  283. }