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