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