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