]> Creatis software - gdcm.git/blob - src/gdcmJpeg.cxx
In order to allow to use current version (1.3) of gdcm *and* ITK (that includes
[gdcm.git] / src / gdcmJpeg.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmJpeg.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/05/23 14:18:10 $
7   Version:   $Revision: 1.56 $
8                                                                                 
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.
12                                                                                 
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.
16                                                                                 
17 =========================================================================*/
18 #include "gdcmFileHelper.h"
19 #include "gdcmJPEGFragment.h"
20 #include "gdcmDebug.h"
21
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
26 //          function
27 //
28 //  #pragma unknown_control_flow (setjmp)
29 #  if   (_COMPILER_VERSION >= 730)
30 #  pragma set woff 3505
31 #  endif
32 #endif
33 #ifdef _MSC_VER
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 )
38 #endif
39
40 #include <setjmp.h>
41 #include <fstream>
42
43 #if defined(__BORLANDC__)
44    #include <mem.h> // for memset
45 #endif 
46
47 #include "jdatasrc.cxx"
48 #include "jdatadst.cxx"
49
50 namespace GDCM_NAME_SPACE 
51 {
52
53  /**
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
62  */
63  
64 bool gdcm_write_JPEG_file (std::ostream *fp, void *im_buf, 
65                            int image_width, int image_height, int quality)
66 {
67
68    JSAMPLE *image_buffer = (JSAMPLE*) im_buf;
69
70   /* This struct contains the JPEG compression parameters and pointers to
71    * working space (which is allocated as needed by the JPEG library).
72    * It is possible to have several such structures, representing multiple
73    * compression/decompression processes, in existence at once.  We refer
74    * to any one struct (and its associated working data) as a "JPEG object".
75    */
76   struct jpeg_compress_struct cinfo;
77   /* This struct represents a JPEG error handler.  It is declared separately
78    * because applications often want to supply a specialized error handler
79    * (see the second half of this file for an example).  But here we just
80    * take the easy way out and use the standard error handler, which will
81    * print a message on stderr and call exit() if compression fails.
82    * Note that this struct must live as long as the main JPEG parameter
83    * struct, to avoid dangling-pointer problems.
84    */
85   struct jpeg_error_mgr jerr;
86   /* More stuff */
87   //FILE*  outfile;    /* target FILE* /
88   JSAMPROW row_pointer[1];   /* pointer to JSAMPLE row[s] */
89   int row_stride;            /* physical row width in image buffer */
90
91   /* Step 1: allocate and initialize JPEG compression object */
92
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.
97    */
98   cinfo.err = jpeg_std_error(&jerr);
99   /* Now we can initialize the JPEG compression object. */
100   jpeg_create_compress(&cinfo);
101
102   /* Step 2: specify data destination (eg, a file) */
103   /* Note: steps 2 and 3 can be done in either order. */
104
105   /* Here we use the library-supplied code to send compressed data to a
106    * stdio stream.  You can also write your own code to do something else.
107    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
108    * requires it in order to write binary files.
109    */
110  // if ((outfile = fopen(filename, "wb")) == NULL) {
111  //   fprintf(stderr, "can't open %s\n", filename);
112  //   exit(1);
113  //
114  // }
115   assert( 0 );
116   (void)fp;
117   //jpeg_stdio_dest(&cinfo, fp, 0, 0, image_width, image_height, quality);
118
119   /* Step 3: set parameters for compression */
120
121   /* First we supply a description of the input image.
122    * Four fields of the cinfo struct must be filled in:
123    */
124   cinfo.image_width = image_width;/* image width and height, in pixels */
125   cinfo.image_height = image_height;
126   cinfo.input_components = 3;     /* # of color components per pixel */
127   cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
128   /* Now use the library's routine to set default compression parameters.
129    * (You must set at least cinfo.in_color_space before calling this,
130    * since the defaults depend on the source color space.)
131    */
132   jpeg_set_defaults(&cinfo);
133   /* Now you can set any non-default parameters you wish to.
134    * Here we just illustrate the use of quality (quantization table) scaling:
135    */
136   jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
137
138   /* Step 4: Start compressor */
139
140   /* TRUE ensures that we will write a complete interchange-JPEG file.
141    * Pass TRUE unless you are very sure of what you're doing.
142    */
143   jpeg_start_compress(&cinfo, TRUE);
144
145   /* Step 5: while (scan lines remain to be written) */
146   /*           jpeg_write_scanlines(...); */
147
148   /* Here we use the library's state variable cinfo.next_scanline as the
149    * loop counter, so that we don't have to keep track ourselves.
150    * To keep things simple, we pass one scanline per call; you can pass
151    * more if you wish, though.
152    */
153   row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
154
155   while (cinfo.next_scanline < cinfo.image_height) {
156     /* jpeg_write_scanlines expects an array of pointers to scanlines.
157      * Here the array is only one element long, but you could pass
158      * more than one scanline at a time if that's more convenient.
159      */
160     row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
161
162     (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
163   }
164
165   /* Step 6: Finish compression */
166
167   jpeg_finish_compress(&cinfo);
168   
169   /* After finish_compress, we can close the output file. */
170   
171  // fclose(fp); --> the caller will close (multiframe treatement)
172
173   /* Step 7: release JPEG compression object */
174
175   /* This is an important step since it will release a good deal of memory. */
176   jpeg_destroy_compress(&cinfo);
177
178   /* And we're done! */
179
180   return true;
181 }
182
183 //-----------------------------------------------------------------------------
184 struct my_error_mgr {
185    struct jpeg_error_mgr pub; /* "public" fields */
186    jmp_buf setjmp_buffer;     /* for return to caller */
187 };
188 typedef struct my_error_mgr* my_error_ptr;
189 //-----------------------------------------------------------------------------
190
191 /*
192  * Here's the routine that will replace the standard error_exit method:
193  */
194 extern "C" {
195 METHODDEF(void) my_error_exit (j_common_ptr cinfo) {
196    /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
197    my_error_ptr myerr = (my_error_ptr) cinfo->err;
198
199    /* Always display the message. */
200    /* We could postpone this until after returning, if we chose. */
201    (*cinfo->err->output_message) (cinfo);
202
203    /* Return control to the setjmp point */
204    longjmp(myerr->setjmp_buffer, 1);
205 }
206
207 //METHODDEF(void) my_output_message (j_common_ptr cinfo)
208 //{
209 //   char buffer[JMSG_LENGTH_MAX];
210 // 
211 //   /* Create the message */
212 //   (*cinfo->err->format_message) (cinfo, buffer);
213 //
214 //   // Custom display message, we could be more fancy and throw an exception:
215 //   gdcmStaticErrorMacro( buffer );
216 //}
217
218 }
219 //-----------------------------------------------------------------------------
220  
221 /**
222  * \brief   routine for JPEG decompression 
223  * @param fp pointer to an already open file descriptor 
224  *                      8 significant bits per pixel
225  * @param image_buffer to receive uncompressed pixels
226  * @param statesuspension Suspension State basically it should be 3 otherwise more complex to handle
227  * @return 1 on success, 0 on error
228  */
229 void *SampBuffer; 
230 bool JPEGFragment::ReadJPEGFile (std::ifstream *fp, void *image_buffer, int &statesuspension)
231 {
232    pImage = (uint8_t*)image_buffer;
233    // This struct contains the JPEG decompression parameters and pointers to
234    // working space (which is allocated as needed by the JPEG library).
235
236    static struct jpeg_decompress_struct cinfo;
237
238    // -------------- inside, we found :
239    // JDIMENSION image_width;       // input image width 
240    // JDIMENSION image_height;      // input image height 
241    // int input_components;         // nb of color components in input image 
242    // J_COLOR_SPACE in_color_space; // colorspace of input image 
243    // double input_gamma;           // image gamma of input image 
244
245    // We use our private extension JPEG error handler.
246    // Note that this struct must live as long as the main JPEG parameter
247    // struct, to avoid dangling-pointer problems.
248
249    struct my_error_mgr jerr;
250
251    JSAMPARRAY buffer;// Output row buffer
252   
253    // rappel :
254    // ------
255    // typedef unsigned char JSAMPLE;
256    // typedef JSAMPLE FAR *JSAMPROW;/* ptr to one image row of pixel samples. */
257    // typedef JSAMPROW *JSAMPARRAY;/* ptr to some rows (a 2-D sample array) */
258    // typedef JSAMPARRAY *JSAMPIMAGE;/* a 3-D sample array: top index is color */
259
260    int row_stride;// physical row width in output buffer
261   
262   // We set up the normal JPEG error routines, then override error_exit.
263   
264   cinfo.err = jpeg_std_error(&jerr.pub);
265   // for any jpeg error call my_error_exit
266   jerr.pub.error_exit = my_error_exit;
267   // for any output message call my_output_message
268   //jerr.pub.output_message = my_output_message;
269
270   // Establish the setjmp return context for my_error_exit to use.
271   if (setjmp(jerr.setjmp_buffer))
272   {
273     // If we get here, the JPEG code has signaled an error.
274     // We need to clean up the JPEG object, close the input file, and return.
275
276     gdcmErrorMacro( "Serious Problem !" );
277     jpeg_destroy_decompress(&cinfo);
278     return 0;
279   }
280   // Now we can initialize the JPEG decompression object.
281   if ( statesuspension == 0 )
282     {
283     jpeg_create_decompress(&cinfo);
284     jpeg_stdio_src(&cinfo, fp, this, 1);
285     }
286   else
287     {
288     jpeg_stdio_src(&cinfo, fp, this, 0);
289     }
290    // Step 3: read file parameters with jpeg_read_header()
291
292    if ( statesuspension < 2 )
293    {
294       if ( jpeg_read_header(&cinfo, TRUE) == JPEG_SUSPENDED )
295       {
296       // Suspension in jpeg_read_header
297       statesuspension = 2; 
298       }
299  
300       // Step 4: set parameters for decompression
301       // prevent the library from performing any color space conversion
302       if ( cinfo.process == JPROC_LOSSLESS )
303       {
304          cinfo.jpeg_color_space = JCS_UNKNOWN;
305          cinfo.out_color_space = JCS_UNKNOWN;
306       }
307    }
308
309    // Step 5: Start decompressor
310    if (statesuspension < 3 )
311    {
312       if ( jpeg_start_decompress(&cinfo) == FALSE )
313       {
314          // Suspension: jpeg_start_decompress
315          statesuspension = 3;
316       }
317
318       // JSAMPLEs per row in output buffer
319       row_stride = cinfo.output_width * cinfo.output_components*2;
320   
321       // Make a one-row-high sample array that will go away when done with image
322       buffer = (*cinfo.mem->alloc_sarray)
323             ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
324
325       // Step 6: while (scan lines remain to be read)
326
327       // Save the buffer in case of suspension to be able to reuse it later:
328       SampBuffer = buffer;
329    }
330    else
331    {
332       // Suspension: re-use the buffer:
333       buffer = (JSAMPARRAY)SampBuffer;
334    }
335    int bufsize = cinfo.output_width * cinfo.output_components;
336    size_t rowsize = bufsize * sizeof(JSAMPLE);
337
338    while (cinfo.output_scanline < cinfo.output_height)
339    {
340       if ( jpeg_read_scanlines(&cinfo, buffer, 1) == 0 )
341         {
342         // Suspension in jpeg_read_scanlines
343         statesuspension = 3;
344         return true;
345         }
346 // The ijg has no notion of big endian, therefore always swap the jpeg stream
347 #if (defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)) && (CMAKE_BITS_IN_JSAMPLE != 8)
348       uint16_t *buffer16 = (uint16_t*)*buffer;
349       uint16_t *pimage16 = (uint16_t*)pImage;
350       for(unsigned int i=0;i<rowsize/2;i++)
351         pimage16[i] = (buffer16[i] >> 8) | (buffer16[i] << 8 );
352 #else
353       memcpy( pImage, *buffer,rowsize);
354 #endif //GDCM_WORDS_BIGENDIAN
355       pImage+=rowsize;
356    }
357
358    // Step 7: Finish decompression
359    if ( jpeg_finish_decompress(&cinfo) == FALSE )
360      {
361      // Suspension: jpeg_finish_decompress
362      statesuspension = 4;
363      }
364    
365    // Step 8: Release JPEG decompression object
366    jpeg_destroy_decompress(&cinfo);
367
368    // At this point you may want to check to see whether any corrupt-data
369    // warnings occurred (test whether jerr.pub.num_warnings is nonzero).
370
371    return true;
372 }
373
374 #ifdef _MSC_VER
375 // Put the warning back
376 #pragma warning( default : 4611 )
377 #endif
378
379 } // end namespace gdcm