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