1 /*=========================================================================
4 Module: $RCSfile: gdcmJpeg.cxx,v $
6 Date: $Date: 2007/08/30 17:37:16 $
7 Version: $Revision: 1.59 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
18 #include "gdcmFileHelper.h"
19 #include "gdcmJPEGFragment.h"
20 #include "gdcmDebug.h"
22 #if defined(__sgi) && !defined(__GNUC__)
23 // Try to get rid of the warning:
24 //cc-3505 CC: WARNING File = /usr/include/internal/setjmp_core.h, Line = 74
25 // setjmp not marked as unknown_control_flow because it is not declared as a
28 // #pragma unknown_control_flow (setjmp)
29 # if (_COMPILER_VERSION >= 730)
30 # pragma set woff 3505
34 // Let us get rid of this funny warning on /W4:
35 // warning C4611: interaction between '_setjmp' and C++ object
36 // destruction is non-portable
37 #pragma warning( disable : 4611 )
43 #if defined(__BORLANDC__)
44 #include <mem.h> // for memset
47 #include "jdatasrc.cxx"
48 #include "jdatadst.cxx"
50 namespace GDCM_NAME_SPACE
54 * \brief routine for JPEG decompression
55 * @param fp pointer to an already open file descriptor
56 * 8 significant bits per pixel
57 * @param im_buf Points to array (of R,G,B-order) data to compress
58 * @param quality compression quality
59 * @param image_height Number of rows in image
60 * @param image_width Number of columns in image
61 * @return 1 on success, 0 on error
64 bool gdcm_write_JPEG_file (std::ostream *fp, char *inputdata, size_t inputlength,
65 int image_width, int image_height, int numZ,
66 int sample_pixel, int bitsallocated, int quality)
69 struct jpeg_compress_struct cinfo;
70 int row_stride; /* physical row width in image buffer */
72 /* This struct contains the JPEG compression parameters and pointers to
73 * working space (which is allocated as needed by the JPEG library).
74 * It is possible to have several such structures, representing multiple
75 * compression/decompression processes, in existence at once. We refer
76 * to any one struct (and its associated working data) as a "JPEG object".
78 //struct jpeg_compress_struct cinfo;
79 /* This struct represents a JPEG error handler. It is declared separately
80 * because applications often want to supply a specialized error handler
81 * (see the second half of this file for an example). But here we just
82 * take the easy way out and use the standard error handler, which will
83 * print a message on stderr and call exit() if compression fails.
84 * Note that this struct must live as long as the main JPEG parameter
85 * struct, to avoid dangling-pointer problems.
87 struct jpeg_error_mgr jerr;
90 /* Step 1: allocate and initialize JPEG compression object */
92 /* We have to set up the error handler first, in case the initialization
93 * step fails. (Unlikely, but it could happen if you are out of memory.)
94 * This routine fills in the contents of struct jerr, and returns jerr's
95 * address which we place into the link field in cinfo.
97 cinfo.err = jpeg_std_error(&jerr);
98 /* Now we can initialize the JPEG compression object. */
99 jpeg_create_compress(&cinfo);
101 /* Step 2: specify data destination (eg, a file) */
102 /* Note: steps 2 and 3 can be done in either order. */
104 int fragment_size = static_cast< int >( inputlength );
105 jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
107 /* Step 3: set parameters for compression */
109 /* First we supply a description of the input image.
110 * Four fields of the cinfo struct must be filled in:
112 cinfo.image_width = image_width;/* image width and height, in pixels */
113 cinfo.image_height = image_height;
114 if ( sample_pixel == 3 )
116 cinfo.input_components = 3; /* # of color components per pixel */
117 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
121 cinfo.input_components = 1; /* # of color components per pixel */
122 cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
124 /* Now use the library's routine to set default compression parameters.
125 * (You must set at least cinfo.in_color_space before calling this,
126 * since the defaults depend on the source color space.)
128 jpeg_set_defaults(&cinfo);
130 * http://www.koders.com/c/fid80DBBF1D49D004EF71CE7C493C34610C4F17D3D3.aspx
131 * http://studio.imagemagick.org/pipermail/magick-users/2002-September/004685.html
132 * You need to set -quality 101 or greater. If quality is 100 or less you
133 * get regular JPEG output. This is not explained in the documentation, only
134 * in the comments in coder/jpeg.c. When you have configured libjpeg with
135 * lossless support, then
137 * quality=predictor*100 + point_transform
139 * If you don't know what these values should be, just use 101.
140 * They only affect the compression ratio, not the image appearance,
143 jpeg_simple_lossless (&cinfo, 1, 0);
144 /* Now you can set any non-default parameters you wish to.
145 * Here we just illustrate the use of quality (quantization table) scaling:
147 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
149 /* Step 4: Start compressor */
151 /* TRUE ensures that we will write a complete interchange-JPEG file.
152 * Pass TRUE unless you are very sure of what you're doing.
154 jpeg_start_compress(&cinfo, TRUE);
156 /* Step 5: while (scan lines remain to be written) */
157 /* jpeg_write_scanlines(...); */
159 /* Here we use the library's state variable cinfo.next_scanline as the
160 * loop counter, so that we don't have to keep track ourselves.
161 * To keep things simple, we pass one scanline per call; you can pass
162 * more if you wish, though.
164 if (sample_pixel == 3)
166 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
170 assert( sample_pixel == 1 );
171 row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
176 uint8_t* input_buffer = (uint8_t*)inputdata;
177 //uint8_t *pbuffer = input_buffer;
179 //for(i=0; i<numZ; ++i)
181 JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
182 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
183 row_pointer[0] = image_buffer;
185 while (cinfo.next_scanline < cinfo.image_height) {
186 /* jpeg_write_scanlines expects an array of pointers to scanlines.
187 * Here the array is only one element long, but you could pass
188 * more than one scanline at a time if that's more convenient.
190 //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
192 if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
194 //entering suspension mode, basically we wrote the whole jpeg fragment
195 // technically we could enforce that by checkig the value of row_pointer to
196 // actually be at the end of the image...TODO
199 row_pointer[0] += row_stride;
201 // pbuffer+=fragment_size; //shift to next image
204 // size_t end = fp->tellp();
205 // std::cerr << "DIFF: " << end-beg << std::endl;
207 // JpegPair &jp = v[i];
208 // jp.second = end-beg;
212 /* Step 6: Finish compression */
214 jpeg_finish_compress(&cinfo);
216 /* Step 7: release JPEG compression object */
218 /* This is an important step since it will release a good deal of memory. */
219 jpeg_destroy_compress(&cinfo);
221 /* And we're done! */
226 //-----------------------------------------------------------------------------
227 struct my_error_mgr {
228 struct jpeg_error_mgr pub; /* "public" fields */
229 jmp_buf setjmp_buffer; /* for return to caller */
231 typedef struct my_error_mgr* my_error_ptr;
232 //-----------------------------------------------------------------------------
235 * Here's the routine that will replace the standard error_exit method:
238 METHODDEF(void) my_error_exit (j_common_ptr cinfo) {
239 /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
240 my_error_ptr myerr = (my_error_ptr) cinfo->err;
242 /* Always display the message. */
243 /* We could postpone this until after returning, if we chose. */
244 (*cinfo->err->output_message) (cinfo);
246 /* Return control to the setjmp point */
247 longjmp(myerr->setjmp_buffer, 1);
250 //METHODDEF(void) my_output_message (j_common_ptr cinfo)
252 // char buffer[JMSG_LENGTH_MAX];
254 // /* Create the message */
255 // (*cinfo->err->format_message) (cinfo, buffer);
257 // // Custom display message, we could be more fancy and throw an exception:
258 // gdcmStaticErrorMacro( buffer );
262 //-----------------------------------------------------------------------------
265 * \brief routine for JPEG decompression
266 * @param fp pointer to an already open file descriptor
267 * 8 significant bits per pixel
268 * @param image_buffer to receive uncompressed pixels
269 * @param statesuspension Suspension State basically it should be 3 otherwise more complex to handle
270 * @return 1 on success, 0 on error
273 bool JPEGFragment::ReadJPEGFile (std::ifstream *fp, void *image_buffer, int &statesuspension)
275 pImage = (uint8_t*)image_buffer;
276 // This struct contains the JPEG decompression parameters and pointers to
277 // working space (which is allocated as needed by the JPEG library).
279 static struct jpeg_decompress_struct cinfo;
281 // -------------- inside, we found :
282 // JDIMENSION image_width; // input image width
283 // JDIMENSION image_height; // input image height
284 // int input_components; // nb of color components in input image
285 // J_COLOR_SPACE in_color_space; // colorspace of input image
286 // double input_gamma; // image gamma of input image
288 // We use our private extension JPEG error handler.
289 // Note that this struct must live as long as the main JPEG parameter
290 // struct, to avoid dangling-pointer problems.
292 struct my_error_mgr jerr;
294 JSAMPARRAY buffer;// Output row buffer
298 // typedef unsigned char JSAMPLE;
299 // typedef JSAMPLE FAR *JSAMPROW;/* ptr to one image row of pixel samples. */
300 // typedef JSAMPROW *JSAMPARRAY;/* ptr to some rows (a 2-D sample array) */
301 // typedef JSAMPARRAY *JSAMPIMAGE;/* a 3-D sample array: top index is color */
303 int row_stride;// physical row width in output buffer
305 // We set up the normal JPEG error routines, then override error_exit.
307 cinfo.err = jpeg_std_error(&jerr.pub);
308 // for any jpeg error call my_error_exit
309 jerr.pub.error_exit = my_error_exit;
310 // for any output message call my_output_message
311 //jerr.pub.output_message = my_output_message;
313 // Establish the setjmp return context for my_error_exit to use.
314 if (setjmp(jerr.setjmp_buffer))
316 // If we get here, the JPEG code has signaled an error.
317 // We need to clean up the JPEG object, close the input file, and return.
319 gdcmErrorMacro( "Serious Problem !" );
320 jpeg_destroy_decompress(&cinfo);
323 // Now we can initialize the JPEG decompression object.
324 if ( statesuspension == 0 )
326 jpeg_create_decompress(&cinfo);
327 jpeg_stdio_src(&cinfo, fp, this, 1);
331 jpeg_stdio_src(&cinfo, fp, this, 0);
333 // Step 3: read file parameters with jpeg_read_header()
335 if ( statesuspension < 2 )
337 if ( jpeg_read_header(&cinfo, TRUE) == JPEG_SUSPENDED )
339 // Suspension in jpeg_read_header
343 // Step 4: set parameters for decompression
344 // prevent the library from performing any color space conversion
345 if ( cinfo.process == JPROC_LOSSLESS )
347 cinfo.jpeg_color_space = JCS_UNKNOWN;
348 cinfo.out_color_space = JCS_UNKNOWN;
352 // Step 5: Start decompressor
353 if (statesuspension < 3 )
355 if ( jpeg_start_decompress(&cinfo) == FALSE )
357 // Suspension: jpeg_start_decompress
361 // JSAMPLEs per row in output buffer
362 row_stride = cinfo.output_width * cinfo.output_components*2;
364 // Make a one-row-high sample array that will go away when done with image
365 buffer = (*cinfo.mem->alloc_sarray)
366 ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
368 // Step 6: while (scan lines remain to be read)
370 // Save the buffer in case of suspension to be able to reuse it later:
375 // Suspension: re-use the buffer:
376 buffer = (JSAMPARRAY)SampBuffer;
378 int bufsize = cinfo.output_width * cinfo.output_components;
379 size_t rowsize = bufsize * sizeof(JSAMPLE);
381 while (cinfo.output_scanline < cinfo.output_height)
383 if ( jpeg_read_scanlines(&cinfo, buffer, 1) == 0 )
385 // Suspension in jpeg_read_scanlines
389 // The ijg has no notion of big endian, therefore always swap the jpeg stream
390 #if (defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)) && (CMAKE_BITS_IN_JSAMPLE != 8)
391 uint16_t *buffer16 = (uint16_t*)*buffer;
392 uint16_t *pimage16 = (uint16_t*)pImage;
393 for(unsigned int i=0;i<rowsize/2;i++)
394 pimage16[i] = (buffer16[i] >> 8) | (buffer16[i] << 8 );
396 memcpy( pImage, *buffer,rowsize);
397 #endif //GDCM_WORDS_BIGENDIAN
401 // Step 7: Finish decompression
402 if ( jpeg_finish_decompress(&cinfo) == FALSE )
404 // Suspension: jpeg_finish_decompress
408 // Step 8: Release JPEG decompression object
409 jpeg_destroy_decompress(&cinfo);
411 // At this point you may want to check to see whether any corrupt-data
412 // warnings occurred (test whether jerr.pub.num_warnings is nonzero).
418 // Put the warning back
419 #pragma warning( default : 4611 )
422 } // end namespace gdcm