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