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