]> Creatis software - gdcm.git/blob - src/gdcmPixelReadConvert.cxx
* ENH - Comment out Mathieu's (dangerous) Super Hack
[gdcm.git] / src / gdcmPixelReadConvert.cxx
1 /*=========================================================================
2
3   Program:   gdcm
4   Module:    $RCSfile: gdcmPixelReadConvert.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/14 15:06:37 $
7   Version:   $Revision: 1.27 $
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
19 //////////////////   TEMPORARY NOTE
20 // look for "fixMem" and convert that to a member of this class
21 // Removing the prefix fixMem and dealing with allocations should do the trick
22 //
23 // grep PixelReadConvert everywhere and clean up !
24
25 #include "gdcmDebug.h"
26 #include "gdcmHeader.h"
27 #include "gdcmGlobal.h"
28 #include "gdcmTS.h"
29 #include "gdcmPixelReadConvert.h"
30 #include "gdcmDocEntry.h"
31 #include "gdcmRLEFramesInfo.h"
32 #include "gdcmJPEGFragmentsInfo.h"
33
34 #include <fstream>
35 #include <stdio.h> //for sscanf
36
37 namespace gdcm
38 {
39 #define str2num(str, typeNum) *((typeNum *)(str))
40
41 // For JPEG 2000, body in file gdcmJpeg2000.cxx
42 bool gdcm_read_JPEG2000_file (std::ifstream* fp, void* image_buffer);
43
44 #define JOCTET uint8_t
45 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
46 bool gdcm_read_JPEG_file8 (std::ifstream *fp, void *image_buffer);
47 bool gdcm_read_JPEG_memory8    (const JOCTET *buffer, const size_t buflen, 
48                                 void *image_buffer,
49                                 size_t *howManyRead, size_t *howManyWritten);
50 //
51 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
52 bool gdcm_read_JPEG_file12 (std::ifstream *fp, void *image_buffer);
53 bool gdcm_read_JPEG_memory12   (const JOCTET *buffer, const size_t buflen, 
54                                 void *image_buffer,
55                                 size_t *howManyRead, size_t *howManyWritten);
56
57 // For JPEG 16 Bits, body in file gdcmJpeg16.cxx
58 // Beware this is misleading there is no 16bits DCT algorithm, only
59 // jpeg lossless compression exist in 16bits.
60 bool gdcm_read_JPEG_file16 (std::ifstream *fp, void *image_buffer);
61 bool gdcm_read_JPEG_memory16   (const JOCTET *buffer, const size_t buflen, 
62                                 void* image_buffer,
63                                 size_t *howManyRead, size_t *howManyWritten);
64
65
66 //-----------------------------------------------------------------------------
67 // Constructor / Destructor
68 PixelReadConvert::PixelReadConvert() 
69 {
70    RGB = 0;
71    RGBSize = 0;
72    Raw = 0;
73    RawSize = 0;
74    LutRGBA = 0;
75    LutRedData = 0;
76    LutGreenData = 0;
77    LutBlueData =0;
78 }
79
80 void PixelReadConvert::Squeeze() 
81 {
82    if ( RGB )
83    {
84       delete [] RGB;
85    } 
86    RGB = 0;
87
88    if ( Raw )
89    {
90       delete [] Raw;
91    }
92    Raw = 0;
93
94    if ( LutRGBA )
95    {
96       delete [] LutRGBA;
97    }
98    LutRGBA = 0;
99 }
100
101 PixelReadConvert::~PixelReadConvert() 
102 {
103    Squeeze();
104 }
105
106 void PixelReadConvert::AllocateRGB()
107 {
108   if ( RGB ) {
109      delete [] RGB;
110   }
111   RGB = new uint8_t[ RGBSize ];
112 }
113
114 void PixelReadConvert::AllocateRaw()
115 {
116   if ( Raw ) {
117      delete [] Raw;
118   }
119   Raw = new uint8_t[ RawSize ];
120 }
121
122 /**
123  * \brief Read from file a 12 bits per pixel image and decompress it
124  *        into a 16 bits per pixel image.
125  */
126 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream *fp )
127                throw ( FormatError )
128 {
129    int nbPixels = XSize * YSize;
130    uint16_t* localDecompres = (uint16_t*)Raw;
131
132    for( int p = 0; p < nbPixels; p += 2 )
133    {
134       uint8_t b0, b1, b2;
135
136       fp->read( (char*)&b0, 1);
137       if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
138       {
139          throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
140                                 "Unfound first block" );
141       }
142
143       fp->read( (char*)&b1, 1 );
144       if ( fp->fail() || fp->eof())//Fp->gcount() == 1
145       {
146          throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
147                                 "Unfound second block" );
148       }
149
150       fp->read( (char*)&b2, 1 );
151       if ( fp->fail() || fp->eof())//Fp->gcount() == 1
152       {
153          throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
154                                 "Unfound second block" );
155       }
156
157       // Two steps are necessary to please VC++
158       //
159       // 2 pixels 12bit =     [0xABCDEF]
160       // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
161       //                        A                     B                 D
162       *localDecompres++ =  ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
163       //                        F                     C                 E
164       *localDecompres++ =  ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
165
166       /// \todo JPR Troubles expected on Big-Endian processors ?
167    }
168 }
169
170 /**
171  * \brief     Try to deal with RLE 16 Bits. 
172  *            We assume the RLE has already been parsed and loaded in
173  *            Raw (through \ref ReadAndDecompressJPEGFile ).
174  *            We here need to make 16 Bits Pixels from Low Byte and
175  *            High Byte 'Planes'...(for what it may mean)
176  * @return    Boolean
177  */
178 bool PixelReadConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
179 {
180    size_t pixelNumber = XSize * YSize;
181    size_t rawSize = XSize * YSize * NumberOfFrames;
182
183    // We assumed Raw contains the decoded RLE pixels but as
184    // 8 bits per pixel. In order to convert those pixels to 16 bits
185    // per pixel we cannot work in place within Raw and hence
186    // we copy it in a safe place, say copyRaw.
187
188    uint8_t* copyRaw = new uint8_t[ rawSize * 2 ];
189    memmove( copyRaw, Raw, rawSize * 2 );
190
191    uint8_t* x = Raw;
192    uint8_t* a = copyRaw;
193    uint8_t* b = a + pixelNumber;
194
195    for ( int i = 0; i < NumberOfFrames; i++ )
196    {
197       for ( unsigned int j = 0; j < pixelNumber; j++ )
198       {
199          *(x++) = *(b++);
200          *(x++) = *(a++);
201       }
202    }
203
204    delete[] copyRaw;
205       
206    /// \todo check that operator new []didn't fail, and sometimes return false
207    return true;
208 }
209
210 /**
211  * \brief Implementation of the RLE decoding algorithm for decompressing
212  *        a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
213  * @param subRaw Sub region of \ref Raw where the de
214  *        decoded fragment should be placed.
215  * @param fragmentSize The length of the binary fragment as found on the disk.
216  * @param RawSegmentSize The expected length of the fragment ONCE
217  *        Raw.
218  * @param fp File Pointer: on entry the position should be the one of
219  *        the fragment to be decoded.
220  */
221 bool PixelReadConvert::ReadAndDecompressRLEFragment( uint8_t *subRaw,
222                                                  long fragmentSize,
223                                                  long RawSegmentSize,
224                                                  std::ifstream *fp )
225 {
226    int8_t count;
227    long numberOfOutputBytes = 0;
228    long numberOfReadBytes = 0;
229
230    while( numberOfOutputBytes < RawSegmentSize )
231    {
232       fp->read( (char*)&count, 1 );
233       numberOfReadBytes += 1;
234       if ( count >= 0 )
235       // Note: count <= 127 comparison is always true due to limited range
236       //       of data type int8_t [since the maximum of an exact width
237       //       signed integer of width N is 2^(N-1) - 1, which for int8_t
238       //       is 127].
239       {
240          fp->read( (char*)subRaw, count + 1);
241          numberOfReadBytes   += count + 1;
242          subRaw     += count + 1;
243          numberOfOutputBytes += count + 1;
244       }
245       else
246       {
247          if ( ( count <= -1 ) && ( count >= -127 ) )
248          {
249             int8_t newByte;
250             fp->read( (char*)&newByte, 1);
251             numberOfReadBytes += 1;
252             for( int i = 0; i < -count + 1; i++ )
253             {
254                subRaw[i] = newByte;
255             }
256             subRaw     += -count + 1;
257             numberOfOutputBytes += -count + 1;
258          }
259       }
260       // if count = 128 output nothing
261                                                                                 
262       if ( numberOfReadBytes > fragmentSize )
263       {
264          gdcmVerboseMacro( "Read more bytes than the segment size.");
265          return false;
266       }
267    }
268    return true;
269 }
270
271 /**
272  * \brief     Reads from disk the Pixel Data of 'Run Length Encoded'
273  *            Dicom encapsulated file and decompress it.
274  * @param     fp already open File Pointer
275  *            at which the pixel data should be copied
276  * @return    Boolean
277  */
278 bool PixelReadConvert::ReadAndDecompressRLEFile( std::ifstream *fp )
279 {
280    uint8_t *subRaw = Raw;
281    long RawSegmentSize = XSize * YSize;
282
283    // Loop on the frame[s]
284    for( RLEFramesInfo::RLEFrameList::iterator
285         it  = RLEInfo->Frames.begin();
286         it != RLEInfo->Frames.end();
287       ++it )
288    {
289       // Loop on the fragments
290       for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
291       {
292          fp->seekg(  (*it)->Offset[k] , std::ios::beg );
293          (void)ReadAndDecompressRLEFragment( subRaw,
294                                              (*it)->Length[k],
295                                              RawSegmentSize, 
296                                              fp );
297          subRaw += RawSegmentSize;
298       }
299    }
300
301    if ( BitsAllocated == 16 )
302    {
303       // Try to deal with RLE 16 Bits
304       (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
305    }
306
307    return true;
308 }
309
310 /**
311  * \brief Swap the bytes, according to \ref SwapCode.
312  */
313 void PixelReadConvert::ConvertSwapZone()
314 {
315    unsigned int i;
316
317    if( BitsAllocated == 16 )
318    {
319       uint16_t *im16 = (uint16_t*)Raw;
320       switch( SwapCode )
321       {
322          case 1234:
323             break;
324          case 3412:
325          case 2143:
326          case 4321:
327             for( i = 0; i < RawSize / 2; i++ )
328             {
329                im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
330             }
331             break;
332          default:
333             gdcmVerboseMacro("SwapCode value (16 bits) not allowed.");
334       }
335    }
336    else if( BitsAllocated == 32 )
337    {
338       uint32_t s32;
339       uint16_t high;
340       uint16_t low;
341       uint32_t* im32 = (uint32_t*)Raw;
342       switch ( SwapCode )
343       {
344          case 1234:
345             break;
346          case 4321:
347             for( i = 0; i < RawSize / 4; i++ )
348             {
349                low     = im32[i] & 0x0000ffff;  // 4321
350                high    = im32[i] >> 16;
351                high    = ( high >> 8 ) | ( high << 8 );
352                low     = ( low  >> 8 ) | ( low  << 8 );
353                s32     = low;
354                im32[i] = ( s32 << 16 ) | high;
355             }
356             break;
357          case 2143:
358             for( i = 0; i < RawSize / 4; i++ )
359             {
360                low     = im32[i] & 0x0000ffff;   // 2143
361                high    = im32[i] >> 16;
362                high    = ( high >> 8 ) | ( high << 8 );
363                low     = ( low  >> 8 ) | ( low  << 8 );
364                s32     = high;
365                im32[i] = ( s32 << 16 ) | low;
366             }
367             break;
368          case 3412:
369             for( i = 0; i < RawSize / 4; i++ )
370             {
371                low     = im32[i] & 0x0000ffff; // 3412
372                high    = im32[i] >> 16;
373                s32     = low;
374                im32[i] = ( s32 << 16 ) | high;
375             }
376             break;
377          default:
378             gdcmVerboseMacro("SwapCode value (32 bits) not allowed." );
379       }
380    }
381 }
382
383 /**
384  * \brief Deal with endianity i.e. re-arange bytes inside the integer
385  */
386 void PixelReadConvert::ConvertReorderEndianity()
387 {
388    if ( BitsAllocated != 8 )
389    {
390       ConvertSwapZone();
391    }
392
393    // Special kludge in order to deal with xmedcon broken images:
394    if (  ( BitsAllocated == 16 )
395        && ( BitsStored < BitsAllocated )
396        && ( ! PixelSign ) )
397    {
398       int l = (int)( RawSize / ( BitsAllocated / 8 ) );
399       uint16_t *deb = (uint16_t *)Raw;
400       for(int i = 0; i<l; i++)
401       {
402          if( *deb == 0xffff )
403          {
404            *deb = 0;
405          }
406          deb++;
407       }
408    }
409 }
410
411
412 /**
413  * \brief     Reads from disk the Pixel Data of JPEG Dicom encapsulated
414  *            file and decompress it. This function assumes that each
415  *            jpeg fragment contains a whole frame (jpeg file).
416  * @param     fp File Pointer
417  * @return    Boolean
418  */
419 bool PixelReadConvert::ReadAndDecompressJPEGFramesFromFile( std::ifstream *fp )
420 {
421    uint8_t *localRaw = Raw;
422    // Loop on the fragment[s]
423    for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
424         it  = JPEGInfo->Fragments.begin();
425         it != JPEGInfo->Fragments.end();
426       ++it )
427    {
428       fp->seekg( (*it)->Offset, std::ios::beg);
429
430       if ( BitsStored == 8)
431       {
432          // JPEG Lossy : call to IJG 6b
433          if ( ! gdcm_read_JPEG_file8( fp, localRaw ) )
434          {
435             return false;
436          }
437       }
438       else if ( BitsStored <= 12)
439       {
440          // Reading Fragment pixels
441          if ( ! gdcm_read_JPEG_file12 ( fp, localRaw ) )
442          {
443             return false;
444          }
445       }
446       else if ( BitsStored <= 16)
447       {
448          // Reading Fragment pixels
449          if ( ! gdcm_read_JPEG_file16 ( fp, localRaw ) )
450          {
451             return false;
452          }
453          //gdcmAssertMacro( IsJPEGLossless );
454       }
455       else
456       {
457          // other JPEG lossy not supported
458          gdcmErrorMacro( "Unknown jpeg lossy compression ");
459          return false;
460       }
461
462       // Advance to next free location in Raw 
463       // for next fragment decompression (if any)
464       int length = XSize * YSize * SamplesPerPixel;
465       int numberBytes = BitsAllocated / 8;
466
467       localRaw += length * numberBytes;
468    }
469    return true;
470 }
471
472 /**
473  * \brief     Reads from disk the Pixel Data of JPEG Dicom encapsulated
474  *            file and decompress it. This function assumes that the dicom
475  *            image is a single frame split into several JPEG fragments.
476  *            Those fragments will be glued together into a memory buffer
477  *            before being read.
478  * @param     fp File Pointer
479  * @return    Boolean
480  */
481 bool PixelReadConvert::
482 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream *fp )
483 {
484    // Loop on the fragment[s] to get total length
485    size_t totalLength = 0;
486    JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
487    for( it  = JPEGInfo->Fragments.begin();
488         it != JPEGInfo->Fragments.end();
489         ++it )
490    {
491       totalLength += (*it)->Length;
492    }
493
494    // Concatenate the jpeg fragments into a local buffer
495    JOCTET *buffer = new JOCTET [totalLength];
496    JOCTET *p = buffer;
497
498    // Loop on the fragment[s]
499    for( it  = JPEGInfo->Fragments.begin();
500         it != JPEGInfo->Fragments.end();
501         ++it )
502    {
503       fp->seekg( (*it)->Offset, std::ios::beg);
504       size_t len = (*it)->Length;
505       fp->read((char *)p,len);
506       p += len;
507    }
508
509    size_t howManyRead = 0;
510    size_t howManyWritten = 0;
511    
512    if ( BitsStored == 8)
513    {
514       if ( ! gdcm_read_JPEG_memory8( buffer, totalLength, Raw,
515                                      &howManyRead, &howManyWritten ) ) 
516       {
517          gdcmErrorMacro( "Failed to read jpeg8 ");
518          delete [] buffer;
519          return false;
520       }
521    }
522    else if ( BitsStored <= 12)
523    {
524       if ( ! gdcm_read_JPEG_memory12( buffer, totalLength, Raw,
525                                       &howManyRead, &howManyWritten ) ) 
526       {
527          gdcmErrorMacro( "Failed to read jpeg12 ");
528             delete [] buffer;
529             return false;
530       }
531    }
532    else if ( BitsStored <= 16)
533    {
534       
535       if ( ! gdcm_read_JPEG_memory16( buffer, totalLength, Raw,
536                                       &howManyRead, &howManyWritten ) ) 
537       {
538          gdcmErrorMacro( "Failed to read jpeg16 ");
539          delete [] buffer;
540          return false;
541       }
542    }
543    else
544    {
545       // other JPEG lossy not supported
546       gdcmErrorMacro( "Unsupported jpeg lossy compression ");
547       delete [] buffer;
548       return false;
549    }      
550
551    // free local buffer
552    delete [] buffer;
553    
554    return true;      
555 }
556
557 /**
558  * \brief     Reads from disk the Pixel Data of JPEG Dicom encapsulated
559  *            file and decompress it. This function handles the generic 
560  *            and complex case where the DICOM contains several frames,
561  *            and some of the frames are possibly split into several JPEG
562  *            fragments. 
563  * @param     fp File Pointer
564  * @return    Boolean
565  */
566 bool PixelReadConvert::
567 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream *fp )
568 {
569    // Loop on the fragment[s] to get total length
570    size_t totalLength = 0;
571    JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
572    for( it  = JPEGInfo->Fragments.begin();
573         it != JPEGInfo->Fragments.end();
574         ++it )
575    {
576       totalLength += (*it)->Length;
577    }
578
579    // Concatenate the jpeg fragments into a local buffer
580    JOCTET *buffer = new JOCTET [totalLength];
581    JOCTET *p = buffer;
582
583    // Loop on the fragment[s]
584    for( it  = JPEGInfo->Fragments.begin();
585         it != JPEGInfo->Fragments.end();
586         ++it )
587    {
588       fp->seekg( (*it)->Offset, std::ios::beg);
589       size_t len = (*it)->Length;
590       fp->read((char *)p,len);
591       p+=len;
592    }
593
594    size_t howManyRead = 0;
595    size_t howManyWritten = 0;
596    size_t fragmentLength = 0;
597    
598    for( it  = JPEGInfo->Fragments.begin() ;
599         (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
600         ++it )
601    {
602       fragmentLength += (*it)->Length;
603       
604       if (howManyRead > fragmentLength) continue;
605
606       if ( BitsStored == 8)
607       {
608         if ( ! gdcm_read_JPEG_memory8( buffer+howManyRead, totalLength-howManyRead,
609                                      Raw+howManyWritten,
610                                      &howManyRead, &howManyWritten ) ) 
611           {
612             gdcmErrorMacro( "Failed to read jpeg8");
613             delete [] buffer;
614             return false;
615           }
616       }
617       else if ( BitsStored <= 12)
618       {
619       
620         if ( ! gdcm_read_JPEG_memory12( buffer+howManyRead, totalLength-howManyRead,
621                                       Raw+howManyWritten,
622                                       &howManyRead, &howManyWritten ) ) 
623           {
624             gdcmErrorMacro( "Failed to read jpeg12");
625             delete [] buffer;
626             return false;
627          }
628       }
629       else if ( BitsStored <= 16)
630       {
631       
632         if ( ! gdcm_read_JPEG_memory16( buffer+howManyRead, totalLength-howManyRead,
633                                       Raw+howManyWritten,
634                                       &howManyRead, &howManyWritten ) ) 
635           {
636             gdcmErrorMacro( "Failed to read jpeg16 ");
637             delete [] buffer;
638             return false;
639           }
640       }
641       else
642       {
643          // other JPEG lossy not supported
644          gdcmErrorMacro( "Unsupported jpeg lossy compression ");
645          delete [] buffer;
646          return false;
647       }
648       
649       if (howManyRead < fragmentLength)
650          howManyRead = fragmentLength;
651    }
652
653    // free local buffer
654    delete [] buffer;
655    
656    return true;
657 }
658
659 /**
660  * \brief     Reads from disk the Pixel Data of JPEG Dicom encapsulated
661  *            file and decompress it.
662  * @param     fp File Pointer
663  * @return    Boolean
664  */
665 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
666 {
667    if ( IsJPEG2000 )
668    {
669       fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
670       if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
671          return false;
672    }
673
674    if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
675    {
676       // we have one frame split into several fragments
677       // we will pack those fragments into a single buffer and 
678       // read from it
679       return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
680    }
681    else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
682    {
683       // suppose each fragment is a frame
684       return ReadAndDecompressJPEGFramesFromFile( fp );
685    }
686    else 
687    {
688       // The dicom image contains frames containing fragments of images
689       // a more complex algorithm :-)
690       return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
691    }   
692 }
693
694 /**
695  * \brief  Re-arrange the bits within the bytes.
696  * @return Boolean
697  */
698 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
699 {
700    if ( BitsStored != BitsAllocated )
701    {
702       int l = (int)( RawSize / ( BitsAllocated / 8 ) );
703       if ( BitsAllocated == 16 )
704       {
705          uint16_t mask = 0xffff;
706          mask = mask >> ( BitsAllocated - BitsStored );
707          uint16_t* deb = (uint16_t*)Raw;
708          for(int i = 0; i<l; i++)
709          {
710             *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
711             deb++;
712          }
713       }
714       else if ( BitsAllocated == 32 )
715       {
716          uint32_t mask = 0xffffffff;
717          mask = mask >> ( BitsAllocated - BitsStored );
718          uint32_t* deb = (uint32_t*)Raw;
719          for(int i = 0; i<l; i++)
720          {
721             *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
722             deb++;
723          }
724       }
725       else
726       {
727          gdcmVerboseMacro("Weird image");
728          throw FormatError( "Weird image !?" );
729       }
730    }
731    return true;
732 }
733
734 /**
735  * \brief   Convert (Y plane, cB plane, cR plane) to RGB pixels
736  * \warning Works on all the frames at a time
737  */
738 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
739 {
740    uint8_t *localRaw = Raw;
741    uint8_t *copyRaw = new uint8_t[ RawSize ];
742    memmove( copyRaw, localRaw, RawSize );
743
744    // to see the tricks about YBR_FULL, YBR_FULL_422,
745    // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
746    // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
747    // and be *very* affraid
748    //
749    int l        = XSize * YSize;
750    int nbFrames = ZSize;
751
752    uint8_t *a = copyRaw;
753    uint8_t *b = copyRaw + l;
754    uint8_t *c = copyRaw + l + l;
755    double R, G, B;
756
757    /// \todo : Replace by the 'well known' integer computation
758    ///         counterpart. Refer to
759    ///            http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
760    ///         for code optimisation.
761
762    for ( int i = 0; i < nbFrames; i++ )
763    {
764       for ( int j = 0; j < l; j++ )
765       {
766          R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
767          G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
768          B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
769
770          if (R < 0.0)   R = 0.0;
771          if (G < 0.0)   G = 0.0;
772          if (B < 0.0)   B = 0.0;
773          if (R > 255.0) R = 255.0;
774          if (G > 255.0) G = 255.0;
775          if (B > 255.0) B = 255.0;
776
777          *(localRaw++) = (uint8_t)R;
778          *(localRaw++) = (uint8_t)G;
779          *(localRaw++) = (uint8_t)B;
780          a++;
781          b++;
782          c++;
783       }
784    }
785    delete[] copyRaw;
786 }
787
788 /**
789  * \brief   Convert (Red plane, Green plane, Blue plane) to RGB pixels
790  * \warning Works on all the frames at a time
791  */
792 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
793 {
794    uint8_t *localRaw = Raw;
795    uint8_t *copyRaw = new uint8_t[ RawSize ];
796    memmove( copyRaw, localRaw, RawSize );
797
798    int l = XSize * YSize * ZSize;
799
800    uint8_t* a = copyRaw;
801    uint8_t* b = copyRaw + l;
802    uint8_t* c = copyRaw + l + l;
803
804    for (int j = 0; j < l; j++)
805    {
806       *(localRaw++) = *(a++);
807       *(localRaw++) = *(b++);
808       *(localRaw++) = *(c++);
809    }
810    delete[] copyRaw;
811 }
812
813 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
814 {
815    // ComputeRawAndRGBSizes is already made by 
816    // ::GrabInformationsFromHeader. So, the structure sizes are
817    // correct
818    Squeeze();
819
820    //////////////////////////////////////////////////
821    //// First stage: get our hands on the Pixel Data.
822    if ( !fp )
823    {
824       gdcmVerboseMacro( "Unavailable file pointer." );
825       return false;
826    }
827
828    fp->seekg( PixelOffset, std::ios::beg );
829    if( fp->fail() || fp->eof())
830    {
831       gdcmVerboseMacro( "Unable to find PixelOffset in file." );
832       return false;
833    }
834
835    AllocateRaw();
836
837    //////////////////////////////////////////////////
838    //// Second stage: read from disk dans decompress.
839    if ( BitsAllocated == 12 )
840    {
841       ReadAndDecompress12BitsTo16Bits( fp);
842    }
843    else if ( IsRaw )
844    {
845       // This problem can be found when some obvious informations are found
846       // after the field containing the image datas. In this case, these
847       // bad datas are added to the size of the image (in the PixelDataLength
848       // variable). But RawSize is the right size of the image !
849       if( PixelDataLength != RawSize)
850       {
851          gdcmVerboseMacro( "Mismatch between PixelReadConvert and RawSize." );
852       }
853       if( PixelDataLength > RawSize)
854       {
855          fp->read( (char*)Raw, RawSize);
856       }
857       else
858       {
859          fp->read( (char*)Raw, PixelDataLength);
860       }
861
862       if ( fp->fail() || fp->eof())
863       {
864          gdcmVerboseMacro( "Reading of Raw pixel data failed." );
865          return false;
866       }
867    } 
868    else if ( IsRLELossless )
869    {
870       if ( ! ReadAndDecompressRLEFile( fp ) )
871       {
872          gdcmVerboseMacro( "RLE decompressor failed." );
873          return false;
874       }
875    }
876    else
877    {
878       // Default case concerns JPEG family
879       if ( ! ReadAndDecompressJPEGFile( fp ) )
880       {
881          gdcmVerboseMacro( "JPEG decompressor failed." );
882          return false;
883       }
884    }
885
886    ////////////////////////////////////////////
887    //// Third stage: twigle the bytes and bits.
888    ConvertReorderEndianity();
889    ConvertReArrangeBits();
890    ConvertHandleColor();
891
892    return true;
893 }
894
895 void PixelReadConvert::ConvertHandleColor()
896 {
897    //////////////////////////////////
898    // Deal with the color decoding i.e. handle:
899    //   - R, G, B planes (as opposed to RGB pixels)
900    //   - YBR (various) encodings.
901    //   - LUT[s] (or "PALETTE COLOR").
902    //
903    // The classification in the color decoding schema is based on the blending
904    // of two Dicom tags values:
905    // * "Photometric Interpretation" for which we have the cases:
906    //  - [Photo A] MONOCHROME[1|2] pictures,
907    //  - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
908    //  - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
909    //  - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
910    // * "Planar Configuration" for which we have the cases:
911    //  - [Planar 0] 0 then Pixels are already RGB
912    //  - [Planar 1] 1 then we have 3 planes : R, G, B,
913    //  - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
914    //
915    // Now in theory, one could expect some coherence when blending the above
916    // cases. For example we should not encounter files belonging at the
917    // time to case [Planar 0] and case [Photo D].
918    // Alas, this was only theory ! Because in practice some odd (read ill
919    // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
920    //     - "Planar Configuration" = 0,
921    //     - "Photometric Interpretation" = "PALETTE COLOR".
922    // Hence gdcm will use the folowing "heuristic" in order to be tolerant
923    // towards Dicom-non-conformance files:
924    //   << whatever the "Planar Configuration" value might be, a
925    //      "Photometric Interpretation" set to "PALETTE COLOR" forces
926    //      a LUT intervention >>
927    //
928    // Now we are left with the following handling of the cases:
929    // - [Planar 0] OR  [Photo A] no color decoding (since respectively
930    //       Pixels are already RGB and monochrome pictures have no color :),
931    // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
932    // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
933    // - [Planar 2] OR  [Photo D] requires LUT intervention.
934
935    if ( ! IsRawRGB() )
936    {
937       // [Planar 2] OR  [Photo D]: LUT intervention done outside
938       return;
939    }
940                                                                                 
941    if ( PlanarConfiguration == 1 )
942    {
943       if ( IsYBRFull )
944       {
945          // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
946          ConvertYcBcRPlanesToRGBPixels();
947       }
948       else
949       {
950          // [Planar 1] AND [Photo C]
951          ConvertRGBPlanesToRGBPixels();
952       }
953       return;
954    }
955                                                                                 
956    // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
957    // pixels need to be RGB-fied anyway
958    if (IsRLELossless)
959    {
960      ConvertRGBPlanesToRGBPixels();
961    }
962    // In *normal *case, when planarConf is 0, pixels are already in RGB
963 }
964
965 /**
966  * \brief Predicate to know wether the image[s] (once Raw) is RGB.
967  * \note See comments of \ref ConvertHandleColor
968  */
969 bool PixelReadConvert::IsRawRGB()
970 {
971    if (   IsMonochrome
972        || PlanarConfiguration == 2
973        || IsPaletteColor )
974    {
975       return false;
976    }
977    return true;
978 }
979
980 void PixelReadConvert::ComputeRawAndRGBSizes()
981 {
982    int bitsAllocated = BitsAllocated;
983    // Number of "Bits Allocated" is fixed to 16 when it's 12, since
984    // in this case we will expand the image to 16 bits (see
985    //    \ref ReadAndDecompress12BitsTo16Bits() )
986    if (  BitsAllocated == 12 )
987    {
988       bitsAllocated = 16;
989    }
990                                                                                 
991    RawSize =  XSize * YSize * ZSize
992                      * ( bitsAllocated / 8 )
993                      * SamplesPerPixel;
994    if ( HasLUT )
995    {
996       RGBSize = 3 * RawSize;
997    }
998    else
999    {
1000       RGBSize = RawSize;
1001    }
1002 }
1003
1004 void PixelReadConvert::GrabInformationsFromHeader( Header *header )
1005 {
1006    // Number of Bits Allocated for storing a Pixel is defaulted to 16
1007    // when absent from the header.
1008    BitsAllocated = header->GetBitsAllocated();
1009    if ( BitsAllocated == 0 )
1010    {
1011       BitsAllocated = 16;
1012    }
1013
1014    // Number of "Bits Stored" defaulted to number of "Bits Allocated"
1015    // when absent from the header.
1016    BitsStored = header->GetBitsStored();
1017    if ( BitsStored == 0 )
1018    {
1019       BitsStored = BitsAllocated;
1020    }
1021
1022    // High Bit Position
1023    HighBitPosition = header->GetHighBitPosition();
1024    if ( HighBitPosition == 0 )
1025    {
1026       HighBitPosition = BitsAllocated - 1;
1027    }
1028
1029    XSize = header->GetXSize();
1030    YSize = header->GetYSize();
1031    ZSize = header->GetZSize();
1032    SamplesPerPixel = header->GetSamplesPerPixel();
1033    PixelSize = header->GetPixelSize();
1034    PixelSign = header->IsSignedPixelData();
1035    SwapCode  = header->GetSwapCode();
1036    std::string ts = header->GetTransferSyntax();
1037    IsRaw =
1038         ( ! header->IsDicomV3() )
1039      || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
1040      || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
1041      || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
1042      || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
1043      || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
1044    IsJPEG2000     = Global::GetTS()->IsJPEG2000(ts);
1045    IsJPEGLossless = Global::GetTS()->IsJPEGLossless(ts);
1046    IsRLELossless  =  Global::GetTS()->IsRLELossless(ts);
1047    PixelOffset     = header->GetPixelOffset();
1048    PixelDataLength = header->GetPixelAreaLength();
1049    RLEInfo  = header->GetRLEInfo();
1050    JPEGInfo = header->GetJPEGInfo();
1051                                                                              
1052    PlanarConfiguration = header->GetPlanarConfiguration();
1053    IsMonochrome = header->IsMonochrome();
1054    IsPaletteColor = header->IsPaletteColor();
1055    IsYBRFull = header->IsYBRFull();
1056
1057    /////////////////////////////////////////////////////////////////
1058    // LUT section:
1059    HasLUT = header->HasLUT();
1060    if ( HasLUT )
1061    {
1062       // Just in case some access to a Header element requires disk access.
1063       LutRedDescriptor   = header->GetEntry( 0x0028, 0x1101 );
1064       LutGreenDescriptor = header->GetEntry( 0x0028, 0x1102 );
1065       LutBlueDescriptor  = header->GetEntry( 0x0028, 0x1103 );
1066    
1067       // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
1068       // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
1069       // Document::Document() ], the loading of the value (content) of a
1070       // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
1071       // loaded). Hence, we first try to obtain the LUTs data from the header
1072       // and when this fails we read the LUTs data directely from disk.
1073       /// \TODO Reading a [Bin|Val]Entry directly from disk is a kludge.
1074       ///       We should NOT bypass the [Bin|Val]Entry class. Instead
1075       ///       an access to an UNLOADED content of a [Bin|Val]Entry occurence
1076       ///       (e.g. BinEntry::GetBinArea()) should force disk access from
1077       ///       within the [Bin|Val]Entry class itself. The only problem
1078       ///       is that the [Bin|Val]Entry is unaware of the FILE* is was
1079       ///       parsed from. Fix that. FIXME.
1080    
1081       ////// Red round
1082       header->LoadEntryBinArea(0x0028, 0x1201);
1083       LutRedData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1201 );
1084       if ( ! LutRedData )
1085       {
1086          gdcmVerboseMacro( "Unable to read Red LUT data" );
1087       }
1088
1089       ////// Green round:
1090       header->LoadEntryBinArea(0x0028, 0x1202);
1091       LutGreenData = (uint8_t*)header->GetEntryBinArea(0x0028, 0x1202 );
1092       if ( ! LutGreenData)
1093       {
1094          gdcmVerboseMacro( "Unable to read Green LUT data" );
1095       }
1096
1097       ////// Blue round:
1098       header->LoadEntryBinArea(0x0028, 0x1203);
1099       LutBlueData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1203 );
1100       if ( ! LutBlueData )
1101       {
1102          gdcmVerboseMacro( "Unable to read Blue LUT data" );
1103       }
1104    }
1105
1106    ComputeRawAndRGBSizes();
1107 }
1108
1109 /**
1110  * \brief Build Red/Green/Blue/Alpha LUT from Header
1111  *         when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1112  *          and (0028,1101),(0028,1102),(0028,1102)
1113  *            - xxx Palette Color Lookup Table Descriptor - are found
1114  *          and (0028,1201),(0028,1202),(0028,1202)
1115  *            - xxx Palette Color Lookup Table Data - are found
1116  * \warning does NOT deal with :
1117  *   0028 1100 Gray Lookup Table Descriptor (Retired)
1118  *   0028 1221 Segmented Red Palette Color Lookup Table Data
1119  *   0028 1222 Segmented Green Palette Color Lookup Table Data
1120  *   0028 1223 Segmented Blue Palette Color Lookup Table Data
1121  *   no known Dicom reader deals with them :-(
1122  * @return a RGBA Lookup Table
1123  */
1124 void PixelReadConvert::BuildLUTRGBA()
1125 {
1126    if ( LutRGBA )
1127    {
1128       return;
1129    }
1130    // Not so easy : see
1131    // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
1132                                                                                 
1133    if ( ! IsPaletteColor )
1134    {
1135       return;
1136    }
1137                                                                                 
1138    if (   LutRedDescriptor   == GDCM_UNFOUND
1139        || LutGreenDescriptor == GDCM_UNFOUND
1140        || LutBlueDescriptor  == GDCM_UNFOUND )
1141    {
1142       return;
1143    }
1144
1145    ////////////////////////////////////////////
1146    // Extract the info from the LUT descriptors
1147    int lengthR;   // Red LUT length in Bytes
1148    int debR;      // Subscript of the first Lut Value
1149    int nbitsR;    // Lut item size (in Bits)
1150    int nbRead = sscanf( LutRedDescriptor.c_str(),
1151                         "%d\\%d\\%d",
1152                         &lengthR, &debR, &nbitsR );
1153    if( nbRead != 3 )
1154    {
1155       gdcmVerboseMacro( "Wrong Red LUT descriptor" );
1156    }
1157                                                                                 
1158    int lengthG;  // Green LUT length in Bytes
1159    int debG;     // Subscript of the first Lut Value
1160    int nbitsG;   // Lut item size (in Bits)
1161    nbRead = sscanf( LutGreenDescriptor.c_str(),
1162                     "%d\\%d\\%d",
1163                     &lengthG, &debG, &nbitsG );
1164    if( nbRead != 3 )
1165    {
1166       gdcmVerboseMacro( "Wrong Green LUT descriptor" );
1167    }
1168                                                                                 
1169    int lengthB;  // Blue LUT length in Bytes
1170    int debB;     // Subscript of the first Lut Value
1171    int nbitsB;   // Lut item size (in Bits)
1172    nbRead = sscanf( LutRedDescriptor.c_str(),
1173                     "%d\\%d\\%d",
1174                     &lengthB, &debB, &nbitsB );
1175    if( nbRead != 3 )
1176    {
1177       gdcmVerboseMacro( "Wrong Blue LUT descriptor" );
1178    }
1179                                                                                 
1180    ////////////////////////////////////////////////////////
1181    if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1182    {
1183       return;
1184    }
1185
1186    ////////////////////////////////////////////////
1187    // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1188    LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1189    if ( !LutRGBA )
1190    {
1191       return;
1192    }
1193    memset( LutRGBA, 0, 1024 );
1194                                                                                 
1195    int mult;
1196    if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1197    {
1198       // when LUT item size is different than pixel size
1199       mult = 2; // high byte must be = low byte
1200    }
1201    else
1202    {
1203       // See PS 3.3-2003 C.11.1.1.2 p 619
1204       mult = 1;
1205    }
1206                                                                                 
1207    // if we get a black image, let's just remove the '+1'
1208    // from 'i*mult+1' and check again
1209    // if it works, we shall have to check the 3 Palettes
1210    // to see which byte is ==0 (first one, or second one)
1211    // and fix the code
1212    // We give up the checking to avoid some (useless ?) overhead
1213    // (optimistic asumption)
1214    int i;
1215    uint8_t* a = LutRGBA + 0;
1216    for( i=0; i < lengthR; ++i )
1217    {
1218       *a = LutRedData[i*mult+1];
1219       a += 4;
1220    }
1221                                                                                 
1222    a = LutRGBA + 1;
1223    for( i=0; i < lengthG; ++i)
1224    {
1225       *a = LutGreenData[i*mult+1];
1226       a += 4;
1227    }
1228                                                                                 
1229    a = LutRGBA + 2;
1230    for(i=0; i < lengthB; ++i)
1231    {
1232       *a = LutBlueData[i*mult+1];
1233       a += 4;
1234    }
1235                                                                                 
1236    a = LutRGBA + 3;
1237    for(i=0; i < 256; ++i)
1238    {
1239       *a = 1; // Alpha component
1240       a += 4;
1241    }
1242 }
1243
1244 /**
1245  * \brief Build the RGB image from the Raw imagage and the LUTs.
1246  */
1247 bool PixelReadConvert::BuildRGBImage()
1248 {
1249    if ( RGB )
1250    {
1251       // The job is already done.
1252       return true;
1253    }
1254
1255    if ( ! Raw )
1256    {
1257       // The job can't be done
1258       return false;
1259    }
1260
1261    BuildLUTRGBA();
1262    if ( ! LutRGBA )
1263    {
1264       // The job can't be done
1265       return false;
1266    }
1267                                                                                 
1268    // Build RGB Pixels
1269    AllocateRGB();
1270    uint8_t* localRGB = RGB;
1271    for (size_t i = 0; i < RawSize; ++i )
1272    {
1273       int j  = Raw[i] * 4;
1274       *localRGB++ = LutRGBA[j];
1275       *localRGB++ = LutRGBA[j+1];
1276       *localRGB++ = LutRGBA[j+2];
1277    }
1278    return true;
1279 }
1280
1281 /**
1282  * \brief        Print self.
1283  * @param os     Stream to print to.
1284  */
1285 void PixelReadConvert::Print( std::ostream &os )
1286 {
1287    Print("",os);
1288 }
1289
1290 /**
1291  * \brief        Print self.
1292  * @param indent Indentation string to be prepended during printing.
1293  * @param os     Stream to print to.
1294  */
1295 void PixelReadConvert::Print( std::string indent, std::ostream &os )
1296 {
1297    os << indent
1298       << "--- Pixel information -------------------------"
1299       << std::endl;
1300    os << indent
1301       << "Pixel Data: offset " << PixelOffset
1302       << " x(" << std::hex << PixelOffset << std::dec
1303       << ")   length " << PixelDataLength
1304       << " x(" << std::hex << PixelDataLength << std::dec
1305       << ")" << std::endl;
1306
1307    if ( IsRLELossless )
1308    {
1309       if ( RLEInfo )
1310       {
1311          RLEInfo->Print( indent, os );
1312       }
1313       else
1314       {
1315          gdcmVerboseMacro("Set as RLE file but NO RLEinfo present.");
1316       }
1317    }
1318
1319    if ( IsJPEG2000 || IsJPEGLossless )
1320    {
1321       if ( JPEGInfo )
1322       {
1323          JPEGInfo->Print( indent, os );
1324       }
1325       else
1326       {
1327          gdcmVerboseMacro("Set as JPEG file but NO JPEGinfo present.");
1328       }
1329    }
1330 }
1331
1332 } // end namespace gdcm
1333
1334 // NOTES on File internal calls
1335 // User
1336 // ---> GetImageData
1337 //     ---> GetImageDataIntoVector
1338 //        |---> GetImageDataIntoVectorRaw
1339 //        | lut intervention
1340 // User
1341 // ---> GetImageDataRaw
1342 //     ---> GetImageDataIntoVectorRaw
1343