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