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