]> Creatis software - gdcm.git/blob - src/gdcmJpeg.cxx
Fix mistypings
[gdcm.git] / src / gdcmJpeg.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmJpeg.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/08/30 17:37:16 $
7   Version:   $Revision: 1.59 $
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, char *inputdata, size_t inputlength,
65                            int image_width, int image_height, int numZ,
66                            int sample_pixel, int bitsallocated, int quality)
67 {
68   (void)bitsallocated;
69   struct jpeg_compress_struct cinfo;
70   int row_stride;            /* physical row width in image buffer */
71
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".
77    */
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.
86    */
87   struct jpeg_error_mgr jerr;
88   /* More stuff */
89
90   /* Step 1: allocate and initialize JPEG compression object */
91
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.
96    */
97   cinfo.err = jpeg_std_error(&jerr);
98   /* Now we can initialize the JPEG compression object. */
99   jpeg_create_compress(&cinfo);
100
101   /* Step 2: specify data destination (eg, a file) */
102   /* Note: steps 2 and 3 can be done in either order. */
103
104   int fragment_size = static_cast< int >( inputlength );
105   jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
106
107   /* Step 3: set parameters for compression */
108
109   /* First we supply a description of the input image.
110    * Four fields of the cinfo struct must be filled in:
111    */
112   cinfo.image_width = image_width;/* image width and height, in pixels */
113   cinfo.image_height = image_height;
114   if ( sample_pixel == 3 )
115     {
116     cinfo.input_components = 3;     /* # of color components per pixel */
117     cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
118     }
119   else
120     {
121     cinfo.input_components = 1;     /* # of color components per pixel */
122     cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
123     }
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.)
127    */
128   jpeg_set_defaults(&cinfo);
129   /*
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
136    * 
137    *    quality=predictor*100 + point_transform
138    * 
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,
141    * which is lossless.
142    */
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:
146    */
147   jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
148
149   /* Step 4: Start compressor */
150
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.
153    */
154   jpeg_start_compress(&cinfo, TRUE);
155
156   /* Step 5: while (scan lines remain to be written) */
157   /*           jpeg_write_scanlines(...); */
158
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.
163    */
164   if (sample_pixel == 3)
165     {
166     row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
167     }
168   else
169     {
170     assert( sample_pixel == 1 );
171     row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
172     }
173
174   (void)numZ;
175
176   uint8_t* input_buffer = (uint8_t*)inputdata;
177   //uint8_t *pbuffer = input_buffer;
178   //int i;
179   //for(i=0; i<numZ; ++i)
180 //    {
181   JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
182   JSAMPROW row_pointer[1];   /* pointer to JSAMPLE row[s] */
183   row_pointer[0] = image_buffer;
184
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.
189      */
190     //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
191
192     if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
193       {
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
197       return false;
198       }
199     row_pointer[0] += row_stride;
200   }
201 //    pbuffer+=fragment_size; //shift to next image
202
203     //Upodate frag size
204 //    size_t end = fp->tellp();
205 //    std::cerr << "DIFF: " << end-beg << std::endl;
206
207 //    JpegPair &jp = v[i];
208 //    jp.second = end-beg;
209     //beg = end; //
210  //   }
211
212   /* Step 6: Finish compression */
213
214   jpeg_finish_compress(&cinfo);
215
216   /* Step 7: release JPEG compression object */
217
218   /* This is an important step since it will release a good deal of memory. */
219   jpeg_destroy_compress(&cinfo);
220
221   /* And we're done! */
222
223   return true;
224 }
225
226 //-----------------------------------------------------------------------------
227 struct my_error_mgr {
228    struct jpeg_error_mgr pub; /* "public" fields */
229    jmp_buf setjmp_buffer;     /* for return to caller */
230 };
231 typedef struct my_error_mgr* my_error_ptr;
232 //-----------------------------------------------------------------------------
233
234 /*
235  * Here's the routine that will replace the standard error_exit method:
236  */
237 extern "C" {
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;
241
242    /* Always display the message. */
243    /* We could postpone this until after returning, if we chose. */
244    (*cinfo->err->output_message) (cinfo);
245
246    /* Return control to the setjmp point */
247    longjmp(myerr->setjmp_buffer, 1);
248 }
249
250 //METHODDEF(void) my_output_message (j_common_ptr cinfo)
251 //{
252 //   char buffer[JMSG_LENGTH_MAX];
253 // 
254 //   /* Create the message */
255 //   (*cinfo->err->format_message) (cinfo, buffer);
256 //
257 //   // Custom display message, we could be more fancy and throw an exception:
258 //   gdcmStaticErrorMacro( buffer );
259 //}
260
261 }
262 //-----------------------------------------------------------------------------
263  
264 /**
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
271  */
272 void *SampBuffer; 
273 bool JPEGFragment::ReadJPEGFile (std::ifstream *fp, void *image_buffer, int &statesuspension)
274 {
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).
278
279    static struct jpeg_decompress_struct cinfo;
280
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 
287
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.
291
292    struct my_error_mgr jerr;
293
294    JSAMPARRAY buffer;// Output row buffer
295   
296    // rappel :
297    // ------
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 */
302
303    int row_stride;// physical row width in output buffer
304   
305   // We set up the normal JPEG error routines, then override error_exit.
306   
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;
312
313   // Establish the setjmp return context for my_error_exit to use.
314   if (setjmp(jerr.setjmp_buffer))
315   {
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.
318
319     gdcmErrorMacro( "Serious Problem !" );
320     jpeg_destroy_decompress(&cinfo);
321     return 0;
322   }
323   // Now we can initialize the JPEG decompression object.
324   if ( statesuspension == 0 )
325     {
326     jpeg_create_decompress(&cinfo);
327     jpeg_stdio_src(&cinfo, fp, this, 1);
328     }
329   else
330     {
331     jpeg_stdio_src(&cinfo, fp, this, 0);
332     }
333    // Step 3: read file parameters with jpeg_read_header()
334
335    if ( statesuspension < 2 )
336    {
337       if ( jpeg_read_header(&cinfo, TRUE) == JPEG_SUSPENDED )
338       {
339       // Suspension in jpeg_read_header
340       statesuspension = 2; 
341       }
342  
343       // Step 4: set parameters for decompression
344       // prevent the library from performing any color space conversion
345       if ( cinfo.process == JPROC_LOSSLESS )
346       {
347          cinfo.jpeg_color_space = JCS_UNKNOWN;
348          cinfo.out_color_space = JCS_UNKNOWN;
349       }
350    }
351
352    // Step 5: Start decompressor
353    if (statesuspension < 3 )
354    {
355       if ( jpeg_start_decompress(&cinfo) == FALSE )
356       {
357          // Suspension: jpeg_start_decompress
358          statesuspension = 3;
359       }
360
361       // JSAMPLEs per row in output buffer
362       row_stride = cinfo.output_width * cinfo.output_components*2;
363   
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);
367
368       // Step 6: while (scan lines remain to be read)
369
370       // Save the buffer in case of suspension to be able to reuse it later:
371       SampBuffer = buffer;
372    }
373    else
374    {
375       // Suspension: re-use the buffer:
376       buffer = (JSAMPARRAY)SampBuffer;
377    }
378    int bufsize = cinfo.output_width * cinfo.output_components;
379    size_t rowsize = bufsize * sizeof(JSAMPLE);
380
381    while (cinfo.output_scanline < cinfo.output_height)
382    {
383       if ( jpeg_read_scanlines(&cinfo, buffer, 1) == 0 )
384         {
385         // Suspension in jpeg_read_scanlines
386         statesuspension = 3;
387         return true;
388         }
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 );
395 #else
396       memcpy( pImage, *buffer,rowsize);
397 #endif //GDCM_WORDS_BIGENDIAN
398       pImage+=rowsize;
399    }
400
401    // Step 7: Finish decompression
402    if ( jpeg_finish_decompress(&cinfo) == FALSE )
403      {
404      // Suspension: jpeg_finish_decompress
405      statesuspension = 4;
406      }
407    
408    // Step 8: Release JPEG decompression object
409    jpeg_destroy_decompress(&cinfo);
410
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).
413
414    return true;
415 }
416
417 #ifdef _MSC_VER
418 // Put the warning back
419 #pragma warning( default : 4611 )
420 #endif
421
422 } // end namespace gdcm