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