1 /*=========================================================================
4 Module: $RCSfile: gdcmJpeg.cxx,v $
6 Date: $Date: 2005/10/18 18:39:49 $
7 Version: $Revision: 1.50 $
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 )
42 #include "jdatasrc.cxx"
43 #include "jdatadst.cxx"
49 * \brief routine for JPEG decompression
50 * @param fp pointer to an already open file descriptor
51 * 8 significant bits per pixel
52 * @param im_buf Points to array (of R,G,B-order) data to compress
53 * @param quality compression quality
54 * @param image_height Number of rows in image
55 * @param image_width Number of columns in image
56 * @return 1 on success, 0 on error
59 bool gdcm_write_JPEG_file (std::ostream *fp, void *im_buf,
60 int image_width, int image_height, int quality)
63 JSAMPLE *image_buffer = (JSAMPLE*) im_buf;
65 /* This struct contains the JPEG compression parameters and pointers to
66 * working space (which is allocated as needed by the JPEG library).
67 * It is possible to have several such structures, representing multiple
68 * compression/decompression processes, in existence at once. We refer
69 * to any one struct (and its associated working data) as a "JPEG object".
71 struct jpeg_compress_struct cinfo;
72 /* This struct represents a JPEG error handler. It is declared separately
73 * because applications often want to supply a specialized error handler
74 * (see the second half of this file for an example). But here we just
75 * take the easy way out and use the standard error handler, which will
76 * print a message on stderr and call exit() if compression fails.
77 * Note that this struct must live as long as the main JPEG parameter
78 * struct, to avoid dangling-pointer problems.
80 struct jpeg_error_mgr jerr;
82 //FILE* outfile; /* target FILE* /
83 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
84 int row_stride; /* physical row width in image buffer */
86 /* Step 1: allocate and initialize JPEG compression object */
88 /* We have to set up the error handler first, in case the initialization
89 * step fails. (Unlikely, but it could happen if you are out of memory.)
90 * This routine fills in the contents of struct jerr, and returns jerr's
91 * address which we place into the link field in cinfo.
93 cinfo.err = jpeg_std_error(&jerr);
94 /* Now we can initialize the JPEG compression object. */
95 jpeg_create_compress(&cinfo);
97 /* Step 2: specify data destination (eg, a file) */
98 /* Note: steps 2 and 3 can be done in either order. */
100 /* Here we use the library-supplied code to send compressed data to a
101 * stdio stream. You can also write your own code to do something else.
102 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
103 * requires it in order to write binary files.
105 // if ((outfile = fopen(filename, "wb")) == NULL) {
106 // fprintf(stderr, "can't open %s\n", filename);
111 //jpeg_stdio_dest(&cinfo, fp, 0, 0, image_width, image_height, quality);
113 /* Step 3: set parameters for compression */
115 /* First we supply a description of the input image.
116 * Four fields of the cinfo struct must be filled in:
118 cinfo.image_width = image_width;/* image width and height, in pixels */
119 cinfo.image_height = image_height;
120 cinfo.input_components = 3; /* # of color components per pixel */
121 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
122 /* Now use the library's routine to set default compression parameters.
123 * (You must set at least cinfo.in_color_space before calling this,
124 * since the defaults depend on the source color space.)
126 jpeg_set_defaults(&cinfo);
127 /* Now you can set any non-default parameters you wish to.
128 * Here we just illustrate the use of quality (quantization table) scaling:
130 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
132 /* Step 4: Start compressor */
134 /* TRUE ensures that we will write a complete interchange-JPEG file.
135 * Pass TRUE unless you are very sure of what you're doing.
137 jpeg_start_compress(&cinfo, TRUE);
139 /* Step 5: while (scan lines remain to be written) */
140 /* jpeg_write_scanlines(...); */
142 /* Here we use the library's state variable cinfo.next_scanline as the
143 * loop counter, so that we don't have to keep track ourselves.
144 * To keep things simple, we pass one scanline per call; you can pass
145 * more if you wish, though.
147 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
149 while (cinfo.next_scanline < cinfo.image_height) {
150 /* jpeg_write_scanlines expects an array of pointers to scanlines.
151 * Here the array is only one element long, but you could pass
152 * more than one scanline at a time if that's more convenient.
154 row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
156 (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
159 /* Step 6: Finish compression */
161 jpeg_finish_compress(&cinfo);
163 /* After finish_compress, we can close the output file. */
165 // fclose(fp); --> the caller will close (multiframe treatement)
167 /* Step 7: release JPEG compression object */
169 /* This is an important step since it will release a good deal of memory. */
170 jpeg_destroy_compress(&cinfo);
172 /* And we're done! */
177 //-----------------------------------------------------------------------------
178 struct my_error_mgr {
179 struct jpeg_error_mgr pub; /* "public" fields */
180 jmp_buf setjmp_buffer; /* for return to caller */
182 typedef struct my_error_mgr* my_error_ptr;
183 //-----------------------------------------------------------------------------
186 * Here's the routine that will replace the standard error_exit method:
189 METHODDEF(void) my_error_exit (j_common_ptr cinfo) {
190 /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
191 my_error_ptr myerr = (my_error_ptr) cinfo->err;
193 /* Always display the message. */
194 /* We could postpone this until after returning, if we chose. */
195 (*cinfo->err->output_message) (cinfo);
197 /* Return control to the setjmp point */
198 longjmp(myerr->setjmp_buffer, 1);
201 //METHODDEF(void) my_output_message (j_common_ptr cinfo)
203 // char buffer[JMSG_LENGTH_MAX];
205 // /* Create the message */
206 // (*cinfo->err->format_message) (cinfo, buffer);
208 // // Custom display message, we could be more fancy and throw an exception:
209 // gdcmErrorMacro( buffer );
213 //-----------------------------------------------------------------------------
216 * \brief routine for JPEG decompression
217 * @param fp pointer to an already open file descriptor
218 * 8 significant bits per pixel
219 * @param image_buffer to receive uncompressed pixels
220 * @param statesuspension Suspension State basically it should be 3 otherwise more complex to handle
221 * @return 1 on success, 0 on error
224 bool JPEGFragment::ReadJPEGFile (std::ifstream *fp, void *image_buffer, int &statesuspension)
226 pImage = (uint8_t*)image_buffer;
227 // This struct contains the JPEG decompression parameters and pointers to
228 // working space (which is allocated as needed by the JPEG library).
230 static struct jpeg_decompress_struct cinfo;
232 // -------------- inside, we found :
233 // JDIMENSION image_width; // input image width
234 // JDIMENSION image_height; // input image height
235 // int input_components; // nb of color components in input image
236 // J_COLOR_SPACE in_color_space; // colorspace of input image
237 // double input_gamma; // image gamma of input image
239 // We use our private extension JPEG error handler.
240 // Note that this struct must live as long as the main JPEG parameter
241 // struct, to avoid dangling-pointer problems.
243 struct my_error_mgr jerr;
245 JSAMPARRAY buffer;// Output row buffer
249 // typedef unsigned char JSAMPLE;
250 // typedef JSAMPLE FAR *JSAMPROW;/* ptr to one image row of pixel samples. */
251 // typedef JSAMPROW *JSAMPARRAY;/* ptr to some rows (a 2-D sample array) */
252 // typedef JSAMPARRAY *JSAMPIMAGE;/* a 3-D sample array: top index is color */
254 int row_stride;// physical row width in output buffer
256 // We set up the normal JPEG error routines, then override error_exit.
258 cinfo.err = jpeg_std_error(&jerr.pub);
259 // for any jpeg error call my_error_exit
260 jerr.pub.error_exit = my_error_exit;
261 // for any output message call my_output_message
262 //jerr.pub.output_message = my_output_message;
264 // Establish the setjmp return context for my_error_exit to use.
265 if (setjmp(jerr.setjmp_buffer))
267 // If we get here, the JPEG code has signaled an error.
268 // We need to clean up the JPEG object, close the input file, and return.
270 gdcmErrorMacro( "Serious Problem !" );
271 jpeg_destroy_decompress(&cinfo);
274 // Now we can initialize the JPEG decompression object.
275 if ( statesuspension == 0 )
277 jpeg_create_decompress(&cinfo);
278 jpeg_stdio_src(&cinfo, fp, this, 1);
282 jpeg_stdio_src(&cinfo, fp, this, 0);
284 // Step 3: read file parameters with jpeg_read_header()
286 if ( statesuspension < 2 )
288 if ( jpeg_read_header(&cinfo, TRUE) == JPEG_SUSPENDED )
290 // Suspension in jpeg_read_header
294 // Step 4: set parameters for decompression
295 // prevent the library from performing any color space conversion
296 if ( cinfo.process == JPROC_LOSSLESS )
298 cinfo.jpeg_color_space = JCS_UNKNOWN;
299 cinfo.out_color_space = JCS_UNKNOWN;
303 // Step 5: Start decompressor
304 if (statesuspension < 3 )
306 if ( jpeg_start_decompress(&cinfo) == FALSE )
308 // Suspension: jpeg_start_decompress
312 // JSAMPLEs per row in output buffer
313 row_stride = cinfo.output_width * cinfo.output_components*2;
315 // Make a one-row-high sample array that will go away when done with image
316 buffer = (*cinfo.mem->alloc_sarray)
317 ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
319 // Step 6: while (scan lines remain to be read)
321 // Save the buffer in case of suspension to be able to reuse it later:
326 // Suspension: re-use the buffer:
327 buffer = (JSAMPARRAY)SampBuffer;
329 int bufsize = cinfo.output_width * cinfo.output_components;
330 size_t rowsize = bufsize * sizeof(JSAMPLE);
332 while (cinfo.output_scanline < cinfo.output_height)
334 if ( jpeg_read_scanlines(&cinfo, buffer, 1) == 0 )
336 // Suspension in jpeg_read_scanlines
340 // The ijg has no notion of big endian, therefore always swap the jpeg stream
341 #if (defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)) && (CMAKE_BITS_IN_JSAMPLE != 8)
342 uint16_t *buffer16 = (uint16_t*)*buffer;
343 uint16_t *pimage16 = (uint16_t*)pImage;
344 for(unsigned int i=0;i<rowsize/2;i++)
345 pimage16[i] = (buffer16[i] >> 8) | (buffer16[i] << 8 );
347 memcpy( pImage, *buffer,rowsize);
348 #endif //GDCM_WORDS_BIGENDIAN
352 // Step 7: Finish decompression
353 if ( jpeg_finish_decompress(&cinfo) == FALSE )
355 // Suspension: jpeg_finish_decompress
359 // Step 8: Release JPEG decompression object
360 jpeg_destroy_decompress(&cinfo);
362 // At this point you may want to check to see whether any corrupt-data
363 // warnings occurred (test whether jerr.pub.num_warnings is nonzero).
369 // Put the warning back
370 #pragma warning( default : 4611 )
373 } // end namespace gdcm