1 /*=========================================================================
4 Module: $RCSfile: gdcmJpeg.cxx,v $
6 Date: $Date: 2007/07/13 08:17:21 $
7 Version: $Revision: 1.57 $
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)
70 struct jpeg_compress_struct cinfo;
71 int row_stride; /* physical row width in image buffer */
73 /* This struct contains the JPEG compression parameters and pointers to
74 * working space (which is allocated as needed by the JPEG library).
75 * It is possible to have several such structures, representing multiple
76 * compression/decompression processes, in existence at once. We refer
77 * to any one struct (and its associated working data) as a "JPEG object".
79 //struct jpeg_compress_struct cinfo;
80 /* This struct represents a JPEG error handler. It is declared separately
81 * because applications often want to supply a specialized error handler
82 * (see the second half of this file for an example). But here we just
83 * take the easy way out and use the standard error handler, which will
84 * print a message on stderr and call exit() if compression fails.
85 * Note that this struct must live as long as the main JPEG parameter
86 * struct, to avoid dangling-pointer problems.
88 struct jpeg_error_mgr jerr;
91 /* Step 1: allocate and initialize JPEG compression object */
93 /* We have to set up the error handler first, in case the initialization
94 * step fails. (Unlikely, but it could happen if you are out of memory.)
95 * This routine fills in the contents of struct jerr, and returns jerr's
96 * address which we place into the link field in cinfo.
98 cinfo.err = jpeg_std_error(&jerr);
99 /* Now we can initialize the JPEG compression object. */
100 jpeg_create_compress(&cinfo);
102 /* Step 2: specify data destination (eg, a file) */
103 /* Note: steps 2 and 3 can be done in either order. */
105 int fragment_size = inputlength;
106 jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
108 /* Step 3: set parameters for compression */
110 /* First we supply a description of the input image.
111 * Four fields of the cinfo struct must be filled in:
113 cinfo.image_width = image_width;/* image width and height, in pixels */
114 cinfo.image_height = image_height;
115 if ( sample_pixel == 3 )
117 cinfo.input_components = 3; /* # of color components per pixel */
118 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
122 cinfo.input_components = 1; /* # of color components per pixel */
123 cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
125 /* Now use the library's routine to set default compression parameters.
126 * (You must set at least cinfo.in_color_space before calling this,
127 * since the defaults depend on the source color space.)
129 jpeg_set_defaults(&cinfo);
131 * http://www.koders.com/c/fid80DBBF1D49D004EF71CE7C493C34610C4F17D3D3.aspx
132 * http://studio.imagemagick.org/pipermail/magick-users/2002-September/004685.html
133 * You need to set -quality 101 or greater. If quality is 100 or less you
134 * get regular JPEG output. This is not explained in the documentation, only
135 * in the comments in coder/jpeg.c. When you have configured libjpeg with
136 * lossless support, then
138 * quality=predictor*100 + point_transform
140 * If you don't know what these values should be, just use 101.
141 * They only affect the compression ratio, not the image appearance,
144 jpeg_simple_lossless (&cinfo, 1, 1);
145 /* Now you can set any non-default parameters you wish to.
146 * Here we just illustrate the use of quality (quantization table) scaling:
148 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
150 /* Step 4: Start compressor */
152 /* TRUE ensures that we will write a complete interchange-JPEG file.
153 * Pass TRUE unless you are very sure of what you're doing.
155 jpeg_start_compress(&cinfo, TRUE);
157 /* Step 5: while (scan lines remain to be written) */
158 /* jpeg_write_scanlines(...); */
160 /* Here we use the library's state variable cinfo.next_scanline as the
161 * loop counter, so that we don't have to keep track ourselves.
162 * To keep things simple, we pass one scanline per call; you can pass
163 * more if you wish, though.
165 if (sample_pixel == 3)
167 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
171 assert( sample_pixel == 1 );
172 row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
177 uint8_t* input_buffer = (uint8_t*)inputdata;
178 //uint8_t *pbuffer = input_buffer;
180 //for(i=0; i<numZ; ++i)
182 JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
183 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
184 row_pointer[0] = image_buffer;
186 while (cinfo.next_scanline < cinfo.image_height) {
187 /* jpeg_write_scanlines expects an array of pointers to scanlines.
188 * Here the array is only one element long, but you could pass
189 * more than one scanline at a time if that's more convenient.
191 //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
193 if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
195 //entering suspension mode, basically we wrote the whole jpeg fragment
196 // technically we could enforce that by checkig the value of row_pointer to
197 // actually be at the end of the image...TODO
200 row_pointer[0] += row_stride;
202 // pbuffer+=fragment_size; //shift to next image
205 // size_t end = fp->tellp();
206 // std::cerr << "DIFF: " << end-beg << std::endl;
208 // JpegPair &jp = v[i];
209 // jp.second = end-beg;
213 /* Step 6: Finish compression */
215 jpeg_finish_compress(&cinfo);
217 /* Step 7: release JPEG compression object */
219 /* This is an important step since it will release a good deal of memory. */
220 jpeg_destroy_compress(&cinfo);
222 /* And we're done! */
227 //-----------------------------------------------------------------------------
228 struct my_error_mgr {
229 struct jpeg_error_mgr pub; /* "public" fields */
230 jmp_buf setjmp_buffer; /* for return to caller */
232 typedef struct my_error_mgr* my_error_ptr;
233 //-----------------------------------------------------------------------------
236 * Here's the routine that will replace the standard error_exit method:
239 METHODDEF(void) my_error_exit (j_common_ptr cinfo) {
240 /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
241 my_error_ptr myerr = (my_error_ptr) cinfo->err;
243 /* Always display the message. */
244 /* We could postpone this until after returning, if we chose. */
245 (*cinfo->err->output_message) (cinfo);
247 /* Return control to the setjmp point */
248 longjmp(myerr->setjmp_buffer, 1);
251 //METHODDEF(void) my_output_message (j_common_ptr cinfo)
253 // char buffer[JMSG_LENGTH_MAX];
255 // /* Create the message */
256 // (*cinfo->err->format_message) (cinfo, buffer);
258 // // Custom display message, we could be more fancy and throw an exception:
259 // gdcmStaticErrorMacro( buffer );
263 //-----------------------------------------------------------------------------
266 * \brief routine for JPEG decompression
267 * @param fp pointer to an already open file descriptor
268 * 8 significant bits per pixel
269 * @param image_buffer to receive uncompressed pixels
270 * @param statesuspension Suspension State basically it should be 3 otherwise more complex to handle
271 * @return 1 on success, 0 on error
274 bool JPEGFragment::ReadJPEGFile (std::ifstream *fp, void *image_buffer, int &statesuspension)
276 pImage = (uint8_t*)image_buffer;
277 // This struct contains the JPEG decompression parameters and pointers to
278 // working space (which is allocated as needed by the JPEG library).
280 static struct jpeg_decompress_struct cinfo;
282 // -------------- inside, we found :
283 // JDIMENSION image_width; // input image width
284 // JDIMENSION image_height; // input image height
285 // int input_components; // nb of color components in input image
286 // J_COLOR_SPACE in_color_space; // colorspace of input image
287 // double input_gamma; // image gamma of input image
289 // We use our private extension JPEG error handler.
290 // Note that this struct must live as long as the main JPEG parameter
291 // struct, to avoid dangling-pointer problems.
293 struct my_error_mgr jerr;
295 JSAMPARRAY buffer;// Output row buffer
299 // typedef unsigned char JSAMPLE;
300 // typedef JSAMPLE FAR *JSAMPROW;/* ptr to one image row of pixel samples. */
301 // typedef JSAMPROW *JSAMPARRAY;/* ptr to some rows (a 2-D sample array) */
302 // typedef JSAMPARRAY *JSAMPIMAGE;/* a 3-D sample array: top index is color */
304 int row_stride;// physical row width in output buffer
306 // We set up the normal JPEG error routines, then override error_exit.
308 cinfo.err = jpeg_std_error(&jerr.pub);
309 // for any jpeg error call my_error_exit
310 jerr.pub.error_exit = my_error_exit;
311 // for any output message call my_output_message
312 //jerr.pub.output_message = my_output_message;
314 // Establish the setjmp return context for my_error_exit to use.
315 if (setjmp(jerr.setjmp_buffer))
317 // If we get here, the JPEG code has signaled an error.
318 // We need to clean up the JPEG object, close the input file, and return.
320 gdcmErrorMacro( "Serious Problem !" );
321 jpeg_destroy_decompress(&cinfo);
324 // Now we can initialize the JPEG decompression object.
325 if ( statesuspension == 0 )
327 jpeg_create_decompress(&cinfo);
328 jpeg_stdio_src(&cinfo, fp, this, 1);
332 jpeg_stdio_src(&cinfo, fp, this, 0);
334 // Step 3: read file parameters with jpeg_read_header()
336 if ( statesuspension < 2 )
338 if ( jpeg_read_header(&cinfo, TRUE) == JPEG_SUSPENDED )
340 // Suspension in jpeg_read_header
344 // Step 4: set parameters for decompression
345 // prevent the library from performing any color space conversion
346 if ( cinfo.process == JPROC_LOSSLESS )
348 cinfo.jpeg_color_space = JCS_UNKNOWN;
349 cinfo.out_color_space = JCS_UNKNOWN;
353 // Step 5: Start decompressor
354 if (statesuspension < 3 )
356 if ( jpeg_start_decompress(&cinfo) == FALSE )
358 // Suspension: jpeg_start_decompress
362 // JSAMPLEs per row in output buffer
363 row_stride = cinfo.output_width * cinfo.output_components*2;
365 // Make a one-row-high sample array that will go away when done with image
366 buffer = (*cinfo.mem->alloc_sarray)
367 ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
369 // Step 6: while (scan lines remain to be read)
371 // Save the buffer in case of suspension to be able to reuse it later:
376 // Suspension: re-use the buffer:
377 buffer = (JSAMPARRAY)SampBuffer;
379 int bufsize = cinfo.output_width * cinfo.output_components;
380 size_t rowsize = bufsize * sizeof(JSAMPLE);
382 while (cinfo.output_scanline < cinfo.output_height)
384 if ( jpeg_read_scanlines(&cinfo, buffer, 1) == 0 )
386 // Suspension in jpeg_read_scanlines
390 // The ijg has no notion of big endian, therefore always swap the jpeg stream
391 #if (defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)) && (CMAKE_BITS_IN_JSAMPLE != 8)
392 uint16_t *buffer16 = (uint16_t*)*buffer;
393 uint16_t *pimage16 = (uint16_t*)pImage;
394 for(unsigned int i=0;i<rowsize/2;i++)
395 pimage16[i] = (buffer16[i] >> 8) | (buffer16[i] << 8 );
397 memcpy( pImage, *buffer,rowsize);
398 #endif //GDCM_WORDS_BIGENDIAN
402 // Step 7: Finish decompression
403 if ( jpeg_finish_decompress(&cinfo) == FALSE )
405 // Suspension: jpeg_finish_decompress
409 // Step 8: Release JPEG decompression object
410 jpeg_destroy_decompress(&cinfo);
412 // At this point you may want to check to see whether any corrupt-data
413 // warnings occurred (test whether jerr.pub.num_warnings is nonzero).
419 // Put the warning back
420 #pragma warning( default : 4611 )
423 } // end namespace gdcm