]> Creatis software - gdcm.git/blob - src/gdcmJpeg.cxx
* src/*.cxx : added pragma disable 4786/4251 to get rid of ~4300 warning
[gdcm.git] / src / gdcmJpeg.cxx
1 //This is needed when compiling in debug mode
2 #ifdef _MSC_VER
3 // 'identifier' : class 'type' needs to have dll-interface to be used by
4 // clients of class 'type2'
5 #pragma warning ( disable : 4251 )
6 // 'identifier' : identifier was truncated to 'number' characters in the
7 // debug information
8 #pragma warning ( disable : 4786 )
9 #endif //_MSC_VER
10
11 #include <stdio.h>
12 #include "gdcmFile.h"
13
14 // for jpeglib defined BITS_IN_JSAMPLE
15 #include "jpeg/libijg8/jBitsInJsample.h"
16 // FIXME : find something else when both 
17 // libJpeg8 and libJpeg12 will be active
18
19 #define DEBUG 0
20
21 /*
22 DICOM provides a mechanism for supporting the use of JPEG Image Compression 
23 through the Encapsulated Format (see PS 3.3 of the DICOM Standard). 
24 Annex A defines a number of Transfer Syntaxes which reference 
25 the JPEG Standard and provide a number of lossless (bit preserving) 
26 and lossy compression schemes.
27 In order to facilitate interoperability of implementations conforming 
28 to the DICOM Standard which elect to use one or more 
29 of the Transfer Syntaxes for JPEG Image Compression, the following policy is specified:
30
31   Any implementation which conforms to the DICOM Standard and has elected 
32   to support any one of the Transfer Syntaxes for lossless JPEG Image Compression, 
33   shall support the following lossless compression: 
34   The subset (first-order horizontal prediction [Selection Value 1) of JPEG Process 14 
35   (DPCM, non-hierarchical with Huffman coding) (see Annex F of the DICOM Standard).
36
37    Any implementation which conforms to the DICOM Standard and has elected 
38    to support any one of the Transfer Syntaxes for 8-bit lossy JPEG Image Compression, 
39    shall support the JPEG Baseline Compression (coding Process 1).
40
41    Any implementation which conforms to the DICOM Standard and has elected 
42    to support any one of the Transfer Syntaxes for 12-bit lossy JPEG Image Compression, 
43    shall support the JPEG Compression Process 4.
44
45 Note: The DICOM conformance statement shall differentiate between implementations 
46 that can simply receive JPEG encoded images and those that can receive and process 
47 JPEG encoded images (see PS 3.2 of the DICOM Standard).
48
49 The use of the DICOM Encapsulated Format to support JPEG Compressed Pixel Data 
50 implies that the Data Elements which are related to the Native Format Pixel Data encoding
51 (e.g. Bits Allocated, Bits Stored, High Bit, Pixel Representation, Rows, Columns, etc.) 
52 shall contain values which are consistent with the characteristics 
53 of the uncompressed pixel data from which the compressed Data Stream was derived. 
54 The Pixel Data characteristics included in the JPEG Interchange Format 
55 shall be used to decode the compressed data stream.
56
57 Run Length Encoding Compression
58
59 DICOM provides a mechanism for supporting the use of Run Length Encoding (RLE) 
60 Compression which is a byte oriented lossless compression scheme through 
61 the encapsulated Format (see PS 3.3 of this Standard). 
62 Annex G of the DICOM Standard defines RLE Compression and its Transfer Syntax.
63
64 Note: The RLE Compression algorithm described in Annex G 
65 of the DICOM Standard is the compression used in 
66 the TIFF 6.0 specification known as the "PackBits" scheme.
67
68 The use of the DICOM Encapsulated Format to support RLE Compressed Pixel Data 
69 implies that the Data Elements which are related to the Native Format Pixel Data encoding (
70 e.g. Bits Allocated, Bits Stored, High Bit, Pixel Representation, Rows, Columns, etc.) 
71 shall contain values which are consistent with the characteristics 
72 of the uncompressed pixel data from which the compressed data is derived
73 */
74
75 /*
76  * <setjmp.h> is used for the optional error recovery mechanism shown in
77  * the second part of the example.
78  */
79
80 /*
81  * Include file for users of JPEG library.
82  * You will need to have included system headers that define at least
83  * the typedefs FILE and size_t before you can include jpeglib.h.
84  * (stdio.h is sufficient on ANSI-conforming systems.)
85  * You may also wish to include "jerror.h".
86  */
87
88 extern "C" {
89 #include "jpeglib.h"
90 #include <setjmp.h>
91 }
92
93 /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
94
95 /* This half of the example shows how to read data from the JPEG decompressor.
96  * It's a bit more refined than the above, in that we show:
97  *   (a) how to modify the JPEG library's standard error-reporting behavior;
98  *   (b) how to allocate workspace using the library's memory manager.
99  *
100  * Just to make this example a little different from the first one, we'll
101  * assume that we do not intend to put the whole image into an in-memory
102  * buffer, but to send it line-by-line someplace else.  We need a one-
103  * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG
104  * memory manager allocate it for us.  This approach is actually quite useful
105  * because we don't need to remember to deallocate the buffer separately: it
106  * will go away automatically when the JPEG object is cleaned up.
107  */
108
109 /*
110  * ERROR HANDLING:
111  *
112  * The JPEG library's standard error handler (jerror.c) is divided into
113  * several "methods" which you can override individually.  This lets you
114  * adjust the behavior without duplicating a lot of code, which you might
115  * have to update with each future release.
116  *
117  * Our example here shows how to override the "error_exit" method so that
118  * control is returned to the library's caller when a fatal error occurs,
119  * rather than calling exit() as the standard error_exit method does.
120  *
121  * We use C's setjmp/longjmp facility to return control.  This means that the
122  * routine which calls the JPEG library must first execute a setjmp() call to
123  * establish the return point.  We want the replacement error_exit to do a
124  * longjmp().  But we need to make the setjmp buffer accessible to the
125  * error_exit routine.  To do this, we make a private extension of the
126  * standard JPEG error handler object.  (If we were using C++, we'd say we
127  * were making a subclass of the regular error handler.)
128  *
129  * Here's the extended error handler struct:
130  */
131
132 struct my_error_mgr {
133   struct jpeg_error_mgr pub;    /* "public" fields */
134   jmp_buf setjmp_buffer;        /* for return to caller */
135 };
136
137 typedef struct my_error_mgr * my_error_ptr;
138
139 /*
140  * Here's the routine that will replace the standard error_exit method:
141  */
142
143 METHODDEF(void)
144 my_error_exit (j_common_ptr cinfo) {
145   /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
146   my_error_ptr myerr = (my_error_ptr) cinfo->err;
147
148   /* Always display the message. */
149   /* We could postpone this until after returning, if we chose. */
150   (*cinfo->err->output_message) (cinfo);
151
152   /* Return control to the setjmp point */
153   longjmp(myerr->setjmp_buffer, 1);
154 }
155
156
157 /*
158  * Sample routine for JPEG decompression.  We assume that the source file name
159  * is passed in.  We want to return 1 on success, 0 on error.
160  */
161
162
163 //GLOBAL(int)
164 int
165 gdcmFile::gdcm_read_JPEG_file (void * image_buffer) {
166
167 char *pimage;
168
169   /* This struct contains the JPEG decompression parameters and pointers to
170    * working space (which is allocated as needed by the JPEG library).
171    */
172    
173   struct jpeg_decompress_struct cinfo;
174   
175   /* -------------- inside, we found :
176   JDIMENSION image_width;       // input image width 
177   JDIMENSION image_height;      // input image height 
178   int input_components;         // nb of color components in input image 
179   J_COLOR_SPACE in_color_space; // colorspace of input image 
180   double input_gamma;           // image gamma of input image 
181      -------------- */
182   
183   /* We use our private extension JPEG error handler.
184    * Note that this struct must live as long as the main JPEG parameter
185    * struct, to avoid dangling-pointer problems.
186    */
187   struct my_error_mgr jerr;
188   /* More stuff */
189  
190   JSAMPARRAY buffer;            /* Output row buffer */
191   
192   // rappel :
193   // ------
194   // typedef unsigned char JSAMPLE;
195   // typedef JSAMPLE FAR *JSAMPROW;     /* ptr to one image row of pixel samples. */
196   // typedef JSAMPROW *JSAMPARRAY;      /* ptr to some rows (a 2-D sample array) */
197   // typedef JSAMPARRAY *JSAMPIMAGE;    /* a 3-D sample array: top index is color */
198   
199  
200   int row_stride;               /* physical row width in output buffer */
201   
202  if (DEBUG) printf("entree dans gdcmFile::gdcm_read_JPEG_file, depuis gdcmJpeg\n");
203
204
205   /* In this example we want to open the input file before doing anything else,
206    * so that the setjmp() error recovery below can assume the file is open.
207    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
208    * requires it in order to read binary files.
209    */
210
211   /* Step 1: allocate and initialize JPEG decompression object */
212   
213   if (DEBUG)printf("Entree Step 1\n");
214
215   /* We set up the normal JPEG error routines, then override error_exit. */
216   
217   cinfo.err = jpeg_std_error(&jerr.pub);
218   jerr.pub.error_exit = my_error_exit;
219   
220   /* Establish the setjmp return context for my_error_exit to use. */
221   
222   if (setjmp(jerr.setjmp_buffer)) {
223     /* If we get here, the JPEG code has signaled an error.
224      * We need to clean up the JPEG object, close the input file, and return.
225      */
226     jpeg_destroy_decompress(&cinfo);
227     return 0;
228   }
229   /* Now we can initialize the JPEG decompression object. */
230   jpeg_create_decompress(&cinfo);
231
232   /* Step 2: specify data source (eg, a file) */
233   
234 if (DEBUG) printf("Entree Step 2\n");
235
236   jpeg_stdio_src(&cinfo, fp);
237
238   /* Step 3: read file parameters with jpeg_read_header() */
239
240  if (DEBUG) printf("Entree Step 3\n");
241
242   (void) jpeg_read_header(&cinfo, TRUE);
243    
244   /* We can ignore the return value from jpeg_read_header since
245    *   (a) suspension is not possible with the stdio data source, and
246    *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
247    * See libjpeg.doc for more info.
248    */
249
250 if (DEBUG) {   
251         printf("--------------Header contents :----------------\n");
252         printf("image_width %d image_height %d\n", 
253                                 cinfo.image_width , cinfo.image_height);
254         printf("bits of precision in image data  %d \n", 
255                                 cinfo.output_components);
256         printf("nb of color components returned  %d \n", 
257                                 cinfo.data_precision);
258 }
259
260
261 /*
262   JDIMENSION image_width;       // input image width 
263   JDIMENSION image_height;      // input image height 
264   int output_components;        // # of color components returned 
265   J_COLOR_SPACE in_color_space; // colorspace of input image 
266   double input_gamma;           // image gamma of input image
267   int data_precision;           // bits of precision in image data 
268  
269 */
270
271   /* Step 4: set parameters for decompression */
272   
273  if (DEBUG) printf("Entree Step 4\n");
274
275   /* In this example, we don't need to change any of the defaults set by
276    * jpeg_read_header(), so we do nothing here.
277    */
278
279   /* Step 5: Start decompressor */
280   
281  if (DEBUG) printf("Entree Step 5\n");
282
283   (void) jpeg_start_decompress(&cinfo);
284   /* We can ignore the return value since suspension is not possible
285    * with the stdio data source.
286    */
287    
288   /* We may need to do some setup of our own at this point before reading
289    * the data.  After jpeg_start_decompress() we have the correct scaled
290    * output image dimensions available, as well as the output colormap
291    * if we asked for color quantization.
292    * In this example, we need to make an output work buffer of the right size.
293    */ 
294    
295   /* JSAMPLEs per row in output buffer */
296   row_stride = cinfo.output_width * cinfo.output_components;
297   
298  if (DEBUG) printf ("cinfo.output_width %d cinfo.output_components %d  row_stride %d\n",
299         cinfo.output_width, cinfo.output_components,row_stride);
300         
301   /* Make a one-row-high sample array that will go away when done with image */
302   buffer = (*cinfo.mem->alloc_sarray)
303                 ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
304
305   /* Step 6: while (scan lines remain to be read) */
306   
307  if (DEBUG)  printf("Entree Step 6\n"); 
308
309   /*           jpeg_read_scanlines(...); */
310
311   /* Here we use the library's state variable cinfo.output_scanline as the
312    * loop counter, so that we don't have to keep track ourselves.
313    */
314    
315  if (DEBUG)  printf ("cinfo.output_height %d  cinfo.output_width %d\n",
316                         cinfo.output_height,cinfo.output_width);
317  
318   pimage=(char *)image_buffer;
319   
320   
321   while (cinfo.output_scanline < cinfo.output_height) {
322     /* jpeg_read_scanlines expects an array of pointers to scanlines.
323      * Here the array is only one element long, but you could ask for
324      * more than one scanline at a time if that's more convenient.
325      */
326      
327      // l'image est deja allouée (et passée en param)
328      // on ecrit directement les pixels
329      // (on DEVRAIT pouvoir)
330     
331     //(void) jpeg_read_scanlines(&cinfo, pimage, 1);
332     
333      (void) jpeg_read_scanlines(&cinfo, buffer, 1);
334       
335      if ( BITS_IN_JSAMPLE == 8) {
336          memcpy( pimage, buffer[0],row_stride); 
337          pimage+=row_stride;
338      } else {
339          memcpy( pimage, buffer[0],row_stride*2 ); // FIXME : *2  car 16 bits?!?
340          pimage+=row_stride*2;                     // FIXME : *2 car 16 bits?!?     
341      }
342   }
343  
344   /* Step 7: Finish decompression */
345   
346 if (DEBUG)  printf("Entree Step 7\n");
347
348   (void) jpeg_finish_decompress(&cinfo);
349   /* We can ignore the return value since suspension is not possible
350    * with the stdio data source.
351    */
352
353   /* Step 8: Release JPEG decompression object */
354   
355 if (DEBUG) printf("Entree Step 8\n");
356
357   /* This is an important step since it will release a good deal of memory. */
358   
359   jpeg_destroy_decompress(&cinfo);
360
361   /* After finish_decompress, we can close the input file.
362    * Here we postpone it until after no more JPEG errors are possible,
363    * so as to simplify the setjmp error logic above.  (Actually, I don't
364    * think that jpeg_destroy can do an error exit, but why assume anything...)
365    */
366
367   /* At this point you may want to check to see whether any corrupt-data
368    * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
369    */
370
371   /* And we're done! */
372   
373   return 1;
374 }
375
376 /*
377  * SOME FINE POINTS:
378  *
379  * In the above code, we ignored the return value of jpeg_read_scanlines,
380  * which is the number of scanlines actually read.  We could get away with
381  * this because we asked for only one line at a time and we weren't using
382  * a suspending data source.  See libjpeg.doc for more info.
383  *
384  * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
385  * we should have done it beforehand to ensure that the space would be
386  * counted against the JPEG max_memory setting.  In some systems the above
387  * code would risk an out-of-memory error.  However, in general we don't
388  * know the output image dimensions before jpeg_start_decompress(), unless we
389  * call jpeg_calc_output_dimensions().  See libjpeg.doc for more about this.
390  *
391  * Scanlines are returned in the same order as they appear in the JPEG file,
392  * which is standardly top-to-bottom.  If you must emit data bottom-to-top,
393  * you can use one of the virtual arrays provided by the JPEG memory manager
394  * to invert the data.  See wrbmp.c for an example.
395  *
396  * As with compression, some operating modes may require temporary files.
397  * On some systems you may need to set up a signal handler to ensure that
398  * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
399  */
400  
401
402
403
404
405  
406