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