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