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