]> Creatis software - gdcm.git/blob - src/gdcmJpeg.cxx
COMP: Fix warning on Big endian plateform
[gdcm.git] / src / gdcmJpeg.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmJpeg.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/18 16:44:46 $
7   Version:   $Revision: 1.33 $
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 #include "gdcmFile.h"
19
20 /*
21 DICOM provides a mechanism for supporting the use of JPEG Image Compression 
22 through the Encapsulated Format (see PS 3.3 of the DICOM Standard). 
23 Annex A defines a number of Transfer Syntaxes which reference 
24 the JPEG Standard and provide a number of lossless (bit preserving) 
25 and lossy compression schemes.
26 In order to facilitate interoperability of implementations conforming 
27 to the DICOM Standard which elect to use one or more 
28 of the Transfer Syntaxes for JPEG Image Compression, the following policy is specified:
29
30   Any implementation which conforms to the DICOM Standard and has elected 
31   to support any one of the Transfer Syntaxes for lossless JPEG Image Compression, 
32   shall support the following lossless compression: 
33   The subset (first-order horizontal prediction [Selection Value 1) of JPEG Process 14 
34   (DPCM, non-hierarchical with Huffman coding) (see Annex F of the DICOM Standard).
35
36    Any implementation which conforms to the DICOM Standard and has elected 
37    to support any one of the Transfer Syntaxes for 8-bit lossy JPEG Image Compression, 
38    shall support the JPEG Baseline Compression (coding Process 1).
39
40    Any implementation which conforms to the DICOM Standard and has elected 
41    to support any one of the Transfer Syntaxes for 12-bit lossy JPEG Image Compression, 
42    shall support the JPEG Compression Process 4.
43
44 Note: The DICOM conformance statement shall differentiate between implementations 
45 that can simply receive JPEG encoded images and those that can receive and process 
46 JPEG encoded images (see PS 3.2 of the DICOM Standard).
47
48 The use of the DICOM Encapsulated Format to support JPEG Compressed Pixel Data 
49 implies that the Data Elements which are related to the Native Format Pixel Data encoding
50 (e.g. Bits Allocated, Bits Stored, High Bit, Pixel Representation, Rows, Columns, etc.) 
51 shall contain values which are consistent with the characteristics 
52 of the uncompressed pixel data from which the compressed Data Stream was derived. 
53 The Pixel Data characteristics included in the JPEG Interchange Format 
54 shall be used to decode the compressed data stream.
55
56 Run Length Encoding Compression
57
58 DICOM provides a mechanism for supporting the use of Run Length Encoding (RLE) 
59 Compression which is a byte oriented lossless compression scheme through 
60 the encapsulated Format (see PS 3.3 of this Standard). 
61 Annex G of the DICOM Standard defines RLE Compression and its Transfer Syntax.
62
63 Note: The RLE Compression algorithm described in Annex G 
64 of the DICOM Standard is the compression used in 
65 the TIFF 6.0 specification known as the "PackBits" scheme.
66
67 The use of the DICOM Encapsulated Format to support RLE Compressed Pixel Data 
68 implies that the Data Elements which are related to the Native Format Pixel Data encoding (
69 e.g. Bits Allocated, Bits Stored, High Bit, Pixel Representation, Rows, Columns, etc.) 
70 shall contain values which are consistent with the characteristics 
71 of the uncompressed pixel data from which the compressed data is derived
72 */
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 #include <setjmp.h>
88 #include <fstream>
89 #include "jdatasrc.cxx"
90 #include "jdatadst.cxx"
91
92 namespace gdcm 
93 {
94 /******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/
95
96 /* This half of the example shows how to feed data into the JPEG compressor.
97  * We present a minimal version that does not worry about refinements such
98  * as error recovery (the JPEG code will just exit() if it gets an error).
99  */
100
101 /*
102  * IMAGE DATA FORMATS:
103  *
104  * The standard input image format is a rectangular array of pixels, with
105  * each pixel having the same number of "component" values (color channels).
106  * Each pixel row is an array of JSAMPLEs (which typically are unsigned chars).
107  * If you are working with color data, then the color values for each pixel
108  * must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit
109  * RGB color.
110  *
111  * For this example, we'll assume that this data structure matches the way
112  * our application has stored the image in memory, so we can just pass a
113  * pointer to our image buffer.  In particular, let's say that the image is
114  * RGB color and is described by:
115  */
116
117
118 //extern JSAMPLE * image_buffer; /* Points to large array of R,G,B-order data */
119 //extern int image_height;       /* Number of rows in image */
120 //extern int image_width;        /* Number of columns in image */
121
122
123
124 /*
125  * Sample routine for JPEG compression.  We assume that the target file name
126  * and a compression quality factor are passed in.
127  */
128
129  /**
130  * \brief   routine for JPEG decompression 
131  * @param fp pointer to an already open file descriptor 
132  *                      8 significant bits per pixel
133  * @param im_buf Points to array (of R,G,B-order) data to compress
134  * @param quality compression quality
135  * @param image_height Number of rows in image 
136  * @param image_width Number of columns in image
137  * @return 1 on success, 0 on error
138  */
139  
140 bool gdcm_write_JPEG_file (std::ofstream* fp, void*  im_buf, 
141                            int image_width, int image_height, int quality)
142 {
143
144    JSAMPLE* image_buffer = (JSAMPLE*) im_buf;
145
146   /* This struct contains the JPEG compression parameters and pointers to
147    * working space (which is allocated as needed by the JPEG library).
148    * It is possible to have several such structures, representing multiple
149    * compression/decompression processes, in existence at once.  We refer
150    * to any one struct (and its associated working data) as a "JPEG object".
151    */
152   struct jpeg_compress_struct cinfo;
153   /* This struct represents a JPEG error handler.  It is declared separately
154    * because applications often want to supply a specialized error handler
155    * (see the second half of this file for an example).  But here we just
156    * take the easy way out and use the standard error handler, which will
157    * print a message on stderr and call exit() if compression fails.
158    * Note that this struct must live as long as the main JPEG parameter
159    * struct, to avoid dangling-pointer problems.
160    */
161   struct jpeg_error_mgr jerr;
162   /* More stuff */
163   //FILE*  outfile;    /* target FILE* /
164   JSAMPROW row_pointer[1];   /* pointer to JSAMPLE row[s] */
165   int row_stride;            /* physical row width in image buffer */
166
167   /* Step 1: allocate and initialize JPEG compression object */
168
169   /* We have to set up the error handler first, in case the initialization
170    * step fails.  (Unlikely, but it could happen if you are out of memory.)
171    * This routine fills in the contents of struct jerr, and returns jerr's
172    * address which we place into the link field in cinfo.
173    */
174   cinfo.err = jpeg_std_error(&jerr);
175   /* Now we can initialize the JPEG compression object. */
176   jpeg_create_compress(&cinfo);
177
178   /* Step 2: specify data destination (eg, a file) */
179   /* Note: steps 2 and 3 can be done in either order. */
180
181   /* Here we use the library-supplied code to send compressed data to a
182    * stdio stream.  You can also write your own code to do something else.
183    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
184    * requires it in order to write binary files.
185    */
186  // if ((outfile = fopen(filename, "wb")) == NULL) {
187  //   fprintf(stderr, "can't open %s\n", filename);
188  //   exit(1);
189  //
190  // }
191   jpeg_stdio_dest(&cinfo, fp);
192
193   /* Step 3: set parameters for compression */
194
195   /* First we supply a description of the input image.
196    * Four fields of the cinfo struct must be filled in:
197    */
198   cinfo.image_width = image_width;/* image width and height, in pixels */
199   cinfo.image_height = image_height;
200   cinfo.input_components = 3;     /* # of color components per pixel */
201   cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
202   /* Now use the library's routine to set default compression parameters.
203    * (You must set at least cinfo.in_color_space before calling this,
204    * since the defaults depend on the source color space.)
205    */
206   jpeg_set_defaults(&cinfo);
207   /* Now you can set any non-default parameters you wish to.
208    * Here we just illustrate the use of quality (quantization table) scaling:
209    */
210   jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
211
212   /* Step 4: Start compressor */
213
214   /* TRUE ensures that we will write a complete interchange-JPEG file.
215    * Pass TRUE unless you are very sure of what you're doing.
216    */
217   jpeg_start_compress(&cinfo, TRUE);
218
219   /* Step 5: while (scan lines remain to be written) */
220   /*           jpeg_write_scanlines(...); */
221
222   /* Here we use the library's state variable cinfo.next_scanline as the
223    * loop counter, so that we don't have to keep track ourselves.
224    * To keep things simple, we pass one scanline per call; you can pass
225    * more if you wish, though.
226    */
227   row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
228
229   while (cinfo.next_scanline < cinfo.image_height) {
230     /* jpeg_write_scanlines expects an array of pointers to scanlines.
231      * Here the array is only one element long, but you could pass
232      * more than one scanline at a time if that's more convenient.
233      */
234     row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
235
236     (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
237   }
238
239   /* Step 6: Finish compression */
240
241   jpeg_finish_compress(&cinfo);
242   
243   /* After finish_compress, we can close the output file. */
244   
245  // fclose(fp); --> the caller will close (multiframe treatement)
246
247   /* Step 7: release JPEG compression object */
248
249   /* This is an important step since it will release a good deal of memory. */
250   jpeg_destroy_compress(&cinfo);
251
252   /* And we're done! */
253
254   return true; //???
255 }
256
257
258
259 /*
260  * SOME FINE POINTS:
261  *
262  * In the above loop, we ignored the return value of jpeg_write_scanlines,
263  * which is the number of scanlines actually written.  We could get away
264  * with this because we were only relying on the value of cinfo.next_scanline,
265  * which will be incremented correctly.  If you maintain additional loop
266  * variables then you should be careful to increment them properly.
267  * Actually, for output to a stdio stream you needn't worry, because
268  * then jpeg_write_scanlines will write all the lines passed (or else exit
269  * with a fatal error).  Partial writes can only occur if you use a data
270  * destination module that can demand suspension of the compressor.
271  * (If you don't know what that's for, you don't need it.)
272  *
273  * If the compressor requires full-image buffers (for entropy-coding
274  * optimization or a multi-scan JPEG file), it will create temporary
275  * files for anything that doesn't fit within the maximum-memory setting.
276  * (Note that temp files are NOT needed if you use the default parameters.)
277  * On some systems you may need to set up a signal handler to ensure that
278  * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
279  *
280  * Scanlines MUST be supplied in top-to-bottom order if you want your JPEG
281  * files to be compatible with everyone else's.  If you cannot readily read
282  * your data in that order, you'll need an intermediate array to hold the
283  * image.  See rdtarga.c or rdbmp.c for examples of handling bottom-to-top
284  * source data using the JPEG code's internal virtual-array mechanisms.
285  */
286
287
288
289 /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
290
291 /* This half of the example shows how to read data from the JPEG decompressor.
292  * It's a bit more refined than the above, in that we show:
293  *   (a) how to modify the JPEG library's standard error-reporting behavior;
294  *   (b) how to allocate workspace using the library's memory manager.
295  *
296  * Just to make this example a little different from the first one, we'll
297  * assume that we do not intend to put the whole image into an in-memory
298  * buffer, but to send it line-by-line someplace else.  We need a one-
299  * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG
300  * memory manager allocate it for us.  This approach is actually quite useful
301  * because we don't need to remember to deallocate the buffer separately: it
302  * will go away automatically when the JPEG object is cleaned up.
303  */
304
305 /*
306  * ERROR HANDLING:
307  *
308  * The JPEG library's standard error handler (jerror.c) is divided into
309  * several "methods" which you can override individually.  This lets you
310  * adjust the behavior without duplicating a lot of code, which you might
311  * have to update with each future release.
312  *
313  * Our example here shows how to override the "error_exit" method so that
314  * control is returned to the library's caller when a fatal error occurs,
315  * rather than calling exit() as the standard error_exit method does.
316  *
317  * We use C's setjmp/longjmp facility to return control.  This means that the
318  * routine which calls the JPEG library must first execute a setjmp() call to
319  * establish the return point.  We want the replacement error_exit to do a
320  * longjmp().  But we need to make the setjmp buffer accessible to the
321  * error_exit routine.  To do this, we make a private extension of the
322  * standard JPEG error handler object.  (If we were using C++, we'd say we
323  * were making a subclass of the regular error handler.)
324  *
325  * Here's the extended error handler struct:
326  */
327
328 //-----------------------------------------------------------------------------
329 struct my_error_mgr {
330    struct jpeg_error_mgr pub; /* "public" fields */
331    jmp_buf setjmp_buffer;     /* for return to caller */
332 };
333
334 //-----------------------------------------------------------------------------
335 typedef struct my_error_mgr* my_error_ptr;
336
337 /*
338  * Here's the routine that will replace the standard error_exit method:
339  */
340 METHODDEF(void) my_error_exit (j_common_ptr cinfo) {
341    /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
342    my_error_ptr myerr = (my_error_ptr) cinfo->err;
343
344    /* Always display the message. */
345    /* We could postpone this until after returning, if we chose. */
346    (*cinfo->err->output_message) (cinfo);
347
348    /* Return control to the setjmp point */
349    longjmp(myerr->setjmp_buffer, 1);
350 }
351
352 //-----------------------------------------------------------------------------
353 /*
354  * Sample routine for JPEG decompression.  We assume that the source file name
355  * is passed in.  We want to return 1 on success, 0 on error.
356  */
357  
358  /**
359  * \brief   routine for JPEG decompression 
360  * @param fp pointer to an already open file descriptor 
361  *                      8 significant bits per pixel
362  * @param image_buffer to receive uncompressed pixels
363  * @return 1 on success, 0 on error
364  */
365  
366 bool gdcm_read_JPEG_file ( std::ifstream* fp, void* image_buffer )
367 {
368    char* pimage;
369
370    /* This struct contains the JPEG decompression parameters and pointers to
371     * working space (which is allocated as needed by the JPEG library).
372     */
373    struct jpeg_decompress_struct cinfo;
374
375    /* -------------- inside, we found :
376     * JDIMENSION image_width;       // input image width 
377     * JDIMENSION image_height;      // input image height 
378     * int input_components;         // nb of color components in input image 
379     * J_COLOR_SPACE in_color_space; // colorspace of input image 
380     * double input_gamma;           // image gamma of input image 
381     * -------------- */
382
383    /* We use our private extension JPEG error handler.
384     * Note that this struct must live as long as the main JPEG parameter
385     * struct, to avoid dangling-pointer problems.
386     */
387    struct my_error_mgr jerr;
388    /* More stuff */
389
390    JSAMPARRAY buffer;/* Output row buffer */
391   
392    // rappel :
393    // ------
394    // typedef unsigned char JSAMPLE;
395    // typedef JSAMPLE FAR *JSAMPROW;/* ptr to one image row of pixel samples. */
396    // typedef JSAMPROW *JSAMPARRAY;/* ptr to some rows (a 2-D sample array) */
397    // typedef JSAMPARRAY *JSAMPIMAGE;/* a 3-D sample array: top index is color */
398
399    int row_stride;/* physical row width in output buffer */
400   
401 #ifdef GDCM_JPG_DEBUG
402    printf("entree dans File::gdcm_read_JPEG_file (i.e. 8), depuis gdcmJpeg\n");
403 #endif //GDCM_JPG_DEBUG
404
405    /* In this example we want to open the input file before doing anything else,
406     * so that the setjmp() error recovery below can assume the file is open.
407     * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
408     * requires it in order to read binary files.
409     */
410     
411   /* Step 1: allocate and initialize JPEG decompression object */  
412 #ifdef GDCM_JPG_DEBUG
413   printf("Entree Step 1\n");
414 #endif //GDCM_JPG_DEBUG
415   
416   /* We set up the normal JPEG error routines, then override error_exit. */
417   
418   cinfo.err = jpeg_std_error(&jerr.pub);
419   jerr.pub.error_exit = my_error_exit;
420   
421   /* Establish the setjmp return context for my_error_exit to use. */  
422   if (setjmp(jerr.setjmp_buffer))
423   {
424     /* If we get here, the JPEG code has signaled an error.
425      * We need to clean up the JPEG object, close the input file, and return.
426      */
427     jpeg_destroy_decompress(&cinfo);
428     return 0;
429   }
430   /* Now we can initialize the JPEG decompression object. */
431   jpeg_create_decompress(&cinfo);
432
433    /* Step 2: specify data source (eg, a file) */
434 #ifdef GDCM_JPG_DEBUG
435   printf("Entree Step 2\n");
436 #endif //GDCM_JPG_DEBUG
437
438    jpeg_stdio_src(&cinfo, fp);
439
440    /* Step 3: read file parameters with jpeg_read_header() */
441 #ifdef GDCM_JPG_DEBUG
442   printf("Entree Step 3\n");
443 #endif //GDCM_JPG_DEBUG
444
445    (void) jpeg_read_header(&cinfo, TRUE);
446    
447    /* We can ignore the return value from jpeg_read_header since
448     *   (a) suspension is not possible with the stdio data source, and
449     *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
450     * See libjpeg.doc for more info.
451     */
452
453     // prevent the library from performing any color space conversion
454    if( cinfo.process == JPROC_LOSSLESS )
455    {
456       cinfo.jpeg_color_space = JCS_UNKNOWN;
457       cinfo.out_color_space = JCS_UNKNOWN;
458    }
459
460
461 #ifdef GDCM_JPG_DEBUG
462       printf("--------------Header contents :----------------\n");
463       printf("image_width %d image_height %d\n", 
464               cinfo.image_width , cinfo.image_height);
465       printf("bits of precision in image data  %d \n", 
466               cinfo.output_components);
467       printf("nb of color components returned  %d \n", 
468               cinfo.data_precision);
469 #endif //GDCM_JPG_DEBUG
470
471
472    /*
473     * JDIMENSION image_width;       // input image width 
474     * JDIMENSION image_height;      // input image height 
475     * int output_components;        // # of color components returned 
476     * J_COLOR_SPACE in_color_space; // colorspace of input image 
477     * double input_gamma;           // image gamma of input image
478     * int data_precision;           // bits of precision in image data 
479     */
480
481    /* Step 4: set parameters for decompression */
482 #ifdef GDCM_JPG_DEBUG
483   printf("Entree Step 4\n");
484 #endif //GDCM_JPG_DEBUG
485    /* In this example, we don't need to change any of the defaults set by
486     * jpeg_read_header(), so we do nothing here.
487     */
488
489    /* Step 5: Start decompressor */
490 #ifdef GDCM_JPG_DEBUG
491    printf("Entree Step 5\n");
492 #endif //GDCM_JPG_DEBUG
493
494    (void) jpeg_start_decompress(&cinfo);
495    /* We can ignore the return value since suspension is not possible
496     * with the stdio data source.
497     */
498
499    /* We may need to do some setup of our own at this point before reading
500     * the data.  After jpeg_start_decompress() we have the correct scaled
501     * output image dimensions available, as well as the output colormap
502     * if we asked for color quantization.
503     * In this example, we need to make an output work buffer of the right size.
504     */ 
505
506    /* JSAMPLEs per row in output buffer */
507    row_stride = cinfo.output_width * cinfo.output_components*2;
508   
509 #ifdef GDCM_JPG_DEBUG
510   printf ("cinfo.output_width %d cinfo.output_components %d  row_stride %d\n",
511                       cinfo.output_width, cinfo.output_components,row_stride);
512 #endif //GDCM_JPG_DEBUG
513
514    /* Make a one-row-high sample array that will go away when done with image */
515    buffer = (*cinfo.mem->alloc_sarray)
516             ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
517
518    /* Step 6: while (scan lines remain to be read) */
519 #ifdef GDCM_JPG_DEBUG
520     printf("Entree Step 6\n"); 
521 #endif //GDCM_JPG_DEBUG
522    /*           jpeg_read_scanlines(...); */
523
524    /* Here we use the library's state variable cinfo.output_scanline as the
525     * loop counter, so that we don't have to keep track ourselves.
526     */
527 #ifdef GDCM_JPG_DEBUG
528       printf ("cinfo.output_height %d  cinfo.output_width %d\n",
529                cinfo.output_height,cinfo.output_width);
530 #endif //GDCM_JPG_DEBUG
531    pimage=(char *)image_buffer;
532   
533    int bufsize = cinfo.output_width * cinfo.output_components;
534    size_t rowsize = bufsize * sizeof(JSAMPLE);
535
536    while (cinfo.output_scanline < cinfo.output_height) {
537       /* jpeg_read_scanlines expects an array of pointers to scanlines.
538        * Here the array is only one element long, but you could ask for
539        * more than one scanline at a time if that's more convenient.
540        */
541
542      //printf( "scanlines: %d\n",cinfo.output_scanline);
543       (void) jpeg_read_scanlines(&cinfo, buffer, 1);
544 // The ijg has no notion of big endian, therefore always swap the jpeg stream
545 #if defined(GDCM_WORDS_BIGENDIAN) && (CMAKE_BITS_IN_JSAMPLE != 8)
546       uint16_t *buffer16 = (uint16_t*)*buffer;
547       uint16_t *pimage16 = (uint16_t*)pimage;
548       for(unsigned int i=0;i<rowsize/2;i++)
549         pimage16[i] = (buffer16[i] >> 8) | (buffer16[i] << 8 );
550 #else
551       memcpy( pimage, *buffer,rowsize);
552 #endif //GDCM_WORDS_BIGENDIAN
553       pimage+=rowsize;
554    }
555
556   /* Step 7: Finish decompression */
557 #ifdef GDCM_JPG_DEBUG
558    printf("Entree Step 7\n");
559 #endif //GDCM_JPG_DEBUG
560
561    (void) jpeg_finish_decompress(&cinfo);
562    
563    /* We can ignore the return value since suspension is not possible
564     * with the stdio data source.
565     */
566
567    /* Step 8: Release JPEG decompression object */
568
569 #ifdef GDCM_JPG_DEBUG
570   printf("Entree Step 8\n");
571 #endif //GDCM_JPG_DEBUG
572
573    /* This is an important step since it will release a good deal of memory. */
574
575    jpeg_destroy_decompress(&cinfo);
576
577    /* After finish_decompress, we can close the input file.
578     * Here we postpone it until after no more JPEG errors are possible,
579     * so as to simplify the setjmp error logic above.  (Actually, I don't
580     * think that jpeg_destroy can do an error exit, but why assume anything...)
581     */
582
583    /* At this point you may want to check to see whether any corrupt-data
584     * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
585     */
586
587    /* And we're done! */
588
589    return true;
590 }
591
592
593 /*
594  * SOME FINE POINTS:
595  *
596  * In the above code, we ignored the return value of jpeg_read_scanlines,
597  * which is the number of scanlines actually read.  We could get away with
598  * this because we asked for only one line at a time and we weren't using
599  * a suspending data source.  See libjpeg.doc for more info.
600  *
601  * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
602  * we should have done it beforehand to ensure that the space would be
603  * counted against the JPEG max_memory setting.  In some systems the above
604  * code would risk an out-of-memory error.  However, in general we don't
605  * know the output image dimensions before jpeg_start_decompress(), unless we
606  * call jpeg_calc_output_dimensions().  See libjpeg.doc for more about this.
607  *
608  * Scanlines are returned in the same order as they appear in the JPEG file,
609  * which is standardly top-to-bottom.  If you must emit data bottom-to-top,
610  * you can use one of the virtual arrays provided by the JPEG memory manager
611  * to invert the data.  See wrbmp.c for an example.
612  *
613  * As with compression, some operating modes may require temporary files.
614  * On some systems you may need to set up a signal handler to ensure that
615  * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
616  */
617  
618 //----------------------------------------------------------------------------
619
620
621 /**
622  * \brief   routine for JPEG decompression from a memory buffer.
623  * routine for JPEG decompression from a memory buffer. This routine
624  * only reads one JPEG image at a time, but returns information about
625  * how many bytes have been consumed from the \c input_buffer, and 
626  * how many bytes have been written into the output \c image_buffer.
627  *
628  * @param input_buffer pointer to a memory buffer containing the jpeg
629  *                     compressed data.
630  * @param buflen length of the memory buffer.
631  * @param image_buffer pointer to the location where the decompressed
632  *                     image will be filled.
633  * @param howManyRead returns how many bytes have been consumed from the
634  *                    input_buffer.
635  * @param howManyWritten returns how many bytes have been written into
636  *                       the output image_buffer.
637  * @return 1 on success, 0 on error
638  */
639  
640 bool gdcm_read_JPEG_memory ( const JOCTET* input_buffer, const size_t buflen, 
641                              void* image_buffer,
642                              size_t *howManyRead, size_t *howManyWritten)
643 {
644    char* pimage=(char *)image_buffer;
645    JOCTET* input = (JOCTET*) input_buffer;
646
647    /* This struct contains the JPEG decompression parameters and pointers to
648     * working space (which is allocated as needed by the JPEG library).
649     */
650    struct jpeg_decompress_struct cinfo;
651
652    /* -------------- inside, we found :
653     * JDIMENSION image_width;       // input image width 
654     * JDIMENSION image_height;      // input image height 
655     * int input_components;         // nb of color components in input image 
656     * J_COLOR_SPACE in_color_space; // colorspace of input image 
657     * double input_gamma;           // image gamma of input image 
658     * -------------- */
659
660    /* We use our private extension JPEG error handler.
661     * Note that this struct must live as long as the main JPEG parameter
662     * struct, to avoid dangling-pointer problems.
663     */
664    struct my_error_mgr jerr;
665    /* More stuff */
666
667    JSAMPARRAY buffer;/* Output row buffer */
668   
669    // rappel :
670    // ------
671    // typedef unsigned char JSAMPLE;
672    // typedef JSAMPLE FAR *JSAMPROW;/* ptr to one image row of pixel samples. */
673    // typedef JSAMPROW *JSAMPARRAY;/* ptr to some rows (a 2-D sample array) */
674    // typedef JSAMPARRAY *JSAMPIMAGE;/* a 3-D sample array: top index is color */
675
676    int row_stride;/* physical row width in output buffer */
677   
678 #ifdef GDCM_JPG_DEBUG
679    printf("entree dans File::gdcm_read_JPEG_file (i.e. 8), depuis gdcmJpeg\n");
680 #endif //GDCM_JPG_DEBUG
681
682    /* In this example we want to open the input file before doing anything else,
683     * so that the setjmp() error recovery below can assume the file is open.
684     * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
685     * requires it in order to read binary files.
686     */
687     
688   /* Step 1: allocate and initialize JPEG decompression object */  
689 #ifdef GDCM_JPG_DEBUG
690   printf("Entree Step 1\n");
691 #endif //GDCM_JPG_DEBUG
692   
693   /* We set up the normal JPEG error routines, then override error_exit. */
694   
695   cinfo.err = jpeg_std_error(&jerr.pub);
696   jerr.pub.error_exit = my_error_exit;
697   
698   /* Establish the setjmp return context for my_error_exit to use. */  
699   if (setjmp(jerr.setjmp_buffer))
700   {
701     /* If we get here, the JPEG code has signaled an error.
702      * We need to clean up the JPEG object, close the input file, and return.
703      */
704     jpeg_destroy_decompress(&cinfo);
705     
706     *howManyRead    += input - input_buffer;
707     *howManyWritten += pimage - (char *)image_buffer;
708     return 0;
709   }
710
711   /* Now we can initialize the JPEG decompression object. */
712   jpeg_create_decompress(&cinfo);
713
714   /* Step 2: specify data source (eg, a file) */
715 #ifdef GDCM_JPG_DEBUG
716   printf("Entree Step 2\n");
717 #endif //GDCM_JPG_DEBUG
718   
719   jpeg_memory_src(&cinfo, input, buflen);
720   
721   /* Step 3: read file parameters with jpeg_read_header() */
722 #ifdef GDCM_JPG_DEBUG
723   printf("Entree Step 3\n");
724 #endif //GDCM_JPG_DEBUG
725   
726   (void) jpeg_read_header(&cinfo, TRUE);
727   
728   /* We can ignore the return value from jpeg_read_header since
729    *   (a) suspension is not possible with the stdio data source, and
730    *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
731    * See libjpeg.doc for more info.
732    */
733   
734   // prevent the library from performing any color space conversion
735   if( cinfo.process == JPROC_LOSSLESS )
736   {
737      cinfo.jpeg_color_space = JCS_UNKNOWN;
738      cinfo.out_color_space = JCS_UNKNOWN;
739   }
740
741 #ifdef GDCM_JPG_DEBUG
742   printf("--------------Header contents :----------------\n");
743   printf("image_width %d image_height %d\n", 
744          cinfo.image_width , cinfo.image_height);
745   printf("bits of precision in image data  %d \n", 
746          cinfo.output_components);
747   printf("nb of color components returned  %d \n", 
748          cinfo.data_precision);
749 #endif //GDCM_JPG_DEBUG
750
751
752   /*
753    * JDIMENSION image_width;       // input image width 
754    * JDIMENSION image_height;      // input image height 
755    * int output_components;        // # of color components returned 
756    * J_COLOR_SPACE in_color_space; // colorspace of input image 
757    * double input_gamma;           // image gamma of input image
758    * int data_precision;           // bits of precision in image data 
759    */
760
761   /* Step 4: set parameters for decompression */
762 #ifdef GDCM_JPG_DEBUG
763   printf("Entree Step 4\n");
764 #endif //GDCM_JPG_DEBUG
765   /* In this example, we don't need to change any of the defaults set by
766    * jpeg_read_header(), so we do nothing here.
767    */
768
769   /* Step 5: Start decompressor */
770 #ifdef GDCM_JPG_DEBUG
771   printf("Entree Step 5\n");
772 #endif //GDCM_JPG_DEBUG
773
774   (void) jpeg_start_decompress(&cinfo);
775   /* We can ignore the return value since suspension is not possible
776    * with the stdio data source.
777    */
778
779   /* We may need to do some setup of our own at this point before reading
780    * the data.  After jpeg_start_decompress() we have the correct scaled
781    * output image dimensions available, as well as the output colormap
782    * if we asked for color quantization.
783    * In this example, we need to make an output work buffer of the right size.
784    */ 
785
786   /* JSAMPLEs per row in output buffer */
787   row_stride = cinfo.output_width * cinfo.output_components*2;
788   
789 #ifdef GDCM_JPG_DEBUG
790   printf ("cinfo.output_width %d cinfo.output_components %d  row_stride %d\n",
791           cinfo.output_width, cinfo.output_components,row_stride);
792 #endif //GDCM_JPG_DEBUG
793
794   /* Make a one-row-high sample array that will go away when done with image */
795   buffer = (*cinfo.mem->alloc_sarray)
796      ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
797     
798
799   /* Step 6: while (scan lines remain to be read) */
800 #ifdef GDCM_JPG_DEBUG
801   printf("Entree Step 6\n"); 
802 #endif //GDCM_JPG_DEBUG
803   /*           jpeg_read_scanlines(...); */
804
805   /* Here we use the library's state variable cinfo.output_scanline as the
806    * loop counter, so that we don't have to keep track ourselves.
807    */
808 #ifdef GDCM_JPG_DEBUG
809   printf ("cinfo.output_height %d  cinfo.output_width %d\n",
810           cinfo.output_height,cinfo.output_width);
811 #endif //GDCM_JPG_DEBUG
812   
813   int bufsize = cinfo.output_width * cinfo.output_components;
814   size_t rowsize = bufsize * sizeof(JSAMPLE);
815
816   while (cinfo.output_scanline < cinfo.output_height) {
817      /* jpeg_read_scanlines expects an array of pointers to scanlines.
818       * Here the array is only one element long, but you could ask for
819       * more than one scanline at a time if that's more convenient.
820       */
821
822      //printf( "scanlines: %d\n",cinfo.output_scanline);
823      (void) jpeg_read_scanlines(&cinfo, buffer, 1);
824 #if defined(GDCM_WORDS_BIGENDIAN) && (CMAKE_BITS_IN_JSAMPLE != 8)
825       uint16_t *buffer16 = (uint16_t*)*buffer;
826       uint16_t *pimage16 = (uint16_t*)pimage;
827       for(unsigned int i=0;i<rowsize/2;i++)
828         pimage16[i] = (buffer16[i] >> 8) | (buffer16[i] << 8 );
829 #else
830       memcpy( pimage, *buffer,rowsize);
831 #endif //GDCM_WORDS_BIGENDIAN
832      pimage+=rowsize;
833   }
834    
835   /* Step 7: Finish decompression */
836 #ifdef GDCM_JPG_DEBUG
837   printf("Entree Step 7\n");
838 #endif //GDCM_JPG_DEBUG
839
840   input = (JOCTET *)cinfo.src->next_input_byte;
841
842   (void) jpeg_finish_decompress(&cinfo);
843
844   /* We can ignore the return value since suspension is not possible
845    * with the stdio data source.
846    */
847    
848   /* Step 8: Release JPEG decompression object */
849
850 #ifdef GDCM_JPG_DEBUG
851   printf("Entree Step 8\n");
852 #endif //GDCM_JPG_DEBUG
853   
854   /* This is an important step since it will release a good deal of memory. */
855   
856   jpeg_destroy_decompress(&cinfo);
857   
858    
859   /* After finish_decompress, we can close the input file.
860    * Here we postpone it until after no more JPEG errors are possible,
861    * so as to simplify the setjmp error logic above.  (Actually, I don't
862    * think that jpeg_destroy can do an error exit, but why assume anything...)
863    */
864   
865   /* At this point you may want to check to see whether any corrupt-data
866    * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
867    */
868
869   /* And we're done! */
870   *howManyRead    += input - input_buffer;
871   *howManyWritten += pimage - (char *)image_buffer;
872
873   return true;
874 }
875
876 } // end namespace gdcm