]> Creatis software - gdcm.git/blob - src/gdcmPixelReadConvert.cxx
2d6e0545343db63c889fafd913593a574c68624c
[gdcm.git] / src / gdcmPixelReadConvert.cxx
1 /*=========================================================================
2
3   Program:   gdcm
4   Module:    $RCSfile: gdcmPixelReadConvert.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/12/16 11:37:03 $
7   Version:   $Revision: 1.12 $
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    // Loop on the fragment[s]
505    for( it  = JPEGInfo->Fragments.begin();
506         it != JPEGInfo->Fragments.end();
507         ++it )
508    {
509       fp->seekg( (*it)->Offset, std::ios::beg);
510       size_t len = (*it)->Length;
511       fp->read((char *)p,len);
512       p += len;
513    }
514
515    size_t howManyRead = 0;
516    size_t howManyWritten = 0;
517    
518    if ( BitsStored == 8)
519    {
520       if ( ! gdcm_read_JPEG_memory8( buffer, totalLength, Raw,
521                                      &howManyRead, &howManyWritten ) ) 
522       {
523          dbg.Error(
524             "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg8 "
525             );
526          delete [] buffer;
527          return false;
528       }
529    }
530    else if ( BitsStored <= 12)
531    {
532       if ( ! gdcm_read_JPEG_memory12( buffer, totalLength, Raw,
533                                       &howManyRead, &howManyWritten ) ) 
534       {
535          dbg.Error(
536             "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg12 "
537             );
538             delete [] buffer;
539             return false;
540       }
541    }
542    else if ( BitsStored <= 16)
543    {
544       
545       if ( ! gdcm_read_JPEG_memory16( buffer, totalLength, Raw,
546                                       &howManyRead, &howManyWritten ) ) 
547       {
548          dbg.Error(
549             "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg16 "
550             );
551          delete [] buffer;
552          return false;
553       }
554    }
555    else
556    {
557       // other JPEG lossy not supported
558       dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
559                 "jpeg lossy compression ");
560       delete [] buffer;
561       return false;
562    }      
563
564    // free local buffer
565    delete [] buffer;
566    
567    return true;      
568 }
569
570 /**
571  * \brief     Reads from disk the Pixel Data of JPEG Dicom encapsulated
572  *            file and decompress it. This function handles the generic 
573  *            and complex case where the DICOM contains several frames,
574  *            and some of the frames are possibly split into several JPEG
575  *            fragments. 
576  * @param     fp File Pointer
577  * @return    Boolean
578  */
579 bool PixelReadConvert::
580 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream* fp )
581 {
582    // Loop on the fragment[s] to get total length
583    size_t totalLength = 0;
584    JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
585    for( it  = JPEGInfo->Fragments.begin();
586         it != JPEGInfo->Fragments.end();
587         ++it )
588    {
589       totalLength += (*it)->Length;
590    }
591
592    // Concatenate the jpeg fragments into a local buffer
593    JOCTET *buffer = new JOCTET [totalLength];
594    JOCTET *p = buffer;
595
596    // Loop on the fragment[s]
597    for( it  = JPEGInfo->Fragments.begin();
598         it != JPEGInfo->Fragments.end();
599         ++it )
600    {
601       fp->seekg( (*it)->Offset, std::ios::beg);
602       size_t len = (*it)->Length;
603       fp->read((char *)p,len);
604       p+=len;
605    }
606
607    size_t howManyRead = 0;
608    size_t howManyWritten = 0;
609    size_t fragmentLength = 0;
610    
611    for( it  = JPEGInfo->Fragments.begin() ;
612         (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
613         ++it )
614    {
615       fragmentLength += (*it)->Length;
616       
617       if (howManyRead > fragmentLength) continue;
618
619       if ( BitsStored == 8)
620       {
621         if ( ! gdcm_read_JPEG_memory8( buffer+howManyRead, totalLength-howManyRead,
622                                      Raw+howManyWritten,
623                                      &howManyRead, &howManyWritten ) ) 
624           {
625             dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg8 ");
626             delete [] buffer;
627             return false;
628           }
629       }
630       else if ( BitsStored <= 12)
631       {
632       
633         if ( ! gdcm_read_JPEG_memory12( buffer+howManyRead, totalLength-howManyRead,
634                                       Raw+howManyWritten,
635                                       &howManyRead, &howManyWritten ) ) 
636           {
637             dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg12 ");
638             delete [] buffer;
639             return false;
640          }
641       }
642       else if ( BitsStored <= 16)
643       {
644       
645         if ( ! gdcm_read_JPEG_memory16( buffer+howManyRead, totalLength-howManyRead,
646                                       Raw+howManyWritten,
647                                       &howManyRead, &howManyWritten ) ) 
648           {
649             dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg16 ");
650             delete [] buffer;
651             return false;
652           }
653       }
654       else
655       {
656          // other JPEG lossy not supported
657          dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
658                    "jpeg lossy compression ");
659          delete [] buffer;
660          return false;
661       }
662       
663       if (howManyRead < fragmentLength)
664          howManyRead = fragmentLength;
665    }
666
667    // free local buffer
668    delete [] buffer;
669    
670    return true;
671 }
672
673 /**
674  * \brief     Reads from disk the Pixel Data of JPEG Dicom encapsulated
675  *            file and decompress it.
676  * @param     fp File Pointer
677  * @return    Boolean
678  */
679 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream* fp )
680 {
681    if ( IsJPEG2000 )
682    {
683       fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
684       if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
685          return false;
686    }
687
688    if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
689    {
690       // we have one frame split into several fragments
691       // we will pack those fragments into a single buffer and 
692       // read from it
693       return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
694    }
695    else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
696    {
697       // suppose each fragment is a frame
698       return ReadAndDecompressJPEGFramesFromFile( fp );
699    }
700    else 
701    {
702       // The dicom image contains frames containing fragments of images
703       // a more complex algorithm :-)
704       return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
705    }   
706 }
707
708 /**
709  * \brief  Re-arrange the bits within the bytes.
710  * @return Boolean
711  */
712 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
713 {
714    if ( BitsStored != BitsAllocated )
715    {
716       int l = (int)( RawSize / ( BitsAllocated / 8 ) );
717       if ( BitsAllocated == 16 )
718       {
719          uint16_t mask = 0xffff;
720          mask = mask >> ( BitsAllocated - BitsStored );
721          uint16_t* deb = (uint16_t*)Raw;
722          for(int i = 0; i<l; i++)
723          {
724             *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
725             deb++;
726          }
727       }
728       else if ( BitsAllocated == 32 )
729       {
730          uint32_t mask = 0xffffffff;
731          mask = mask >> ( BitsAllocated - BitsStored );
732          uint32_t* deb = (uint32_t*)Raw;
733          for(int i = 0; i<l; i++)
734          {
735             *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
736             deb++;
737          }
738       }
739       else
740       {
741          dbg.Verbose(0, "PixelReadConvert::ConvertReArrangeBits: weird image");
742          throw FormatError( "PixelReadConvert::ConvertReArrangeBits()",
743                                 "weird image !?" );
744       }
745    }
746    return true;
747 }
748
749 /**
750  * \brief   Convert (Y plane, cB plane, cR plane) to RGB pixels
751  * \warning Works on all the frames at a time
752  */
753 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
754 {
755    uint8_t* localRaw = Raw;
756    uint8_t* copyRaw = new uint8_t[ RawSize ];
757    memmove( copyRaw, localRaw, RawSize );
758
759    // to see the tricks about YBR_FULL, YBR_FULL_422,
760    // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
761    // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
762    // and be *very* affraid
763    //
764    int l        = XSize * YSize;
765    int nbFrames = ZSize;
766
767    uint8_t* a = copyRaw;
768    uint8_t* b = copyRaw + l;
769    uint8_t* c = copyRaw + l + l;
770    double R, G, B;
771
772    /// \todo : Replace by the 'well known' integer computation
773    ///         counterpart. Refer to
774    ///            http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
775    ///         for code optimisation.
776
777    for ( int i = 0; i < nbFrames; i++ )
778    {
779       for ( int j = 0; j < l; j++ )
780       {
781          R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
782          G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
783          B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
784
785          if (R < 0.0)   R = 0.0;
786          if (G < 0.0)   G = 0.0;
787          if (B < 0.0)   B = 0.0;
788          if (R > 255.0) R = 255.0;
789          if (G > 255.0) G = 255.0;
790          if (B > 255.0) B = 255.0;
791
792          *(localRaw++) = (uint8_t)R;
793          *(localRaw++) = (uint8_t)G;
794          *(localRaw++) = (uint8_t)B;
795          a++;
796          b++;
797          c++;
798       }
799    }
800    delete[] copyRaw;
801 }
802
803 /**
804  * \brief   Convert (Red plane, Green plane, Blue plane) to RGB pixels
805  * \warning Works on all the frames at a time
806  */
807 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
808 {
809    uint8_t* localRaw = Raw;
810    uint8_t* copyRaw = new uint8_t[ RawSize ];
811    memmove( copyRaw, localRaw, RawSize );
812
813    int l = XSize * YSize * ZSize;
814
815    uint8_t* a = copyRaw;
816    uint8_t* b = copyRaw + l;
817    uint8_t* c = copyRaw + l + l;
818
819    for (int j = 0; j < l; j++)
820    {
821       *(localRaw++) = *(a++);
822       *(localRaw++) = *(b++);
823       *(localRaw++) = *(c++);
824    }
825    delete[] copyRaw;
826 }
827
828 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream* fp )
829 {
830    // ComputeRawAndRGBSizes is already made by 
831    // ::GrabInformationsFromHeader. So, the structure sizes are
832    // correct
833    Squeeze();
834
835    //////////////////////////////////////////////////
836    //// First stage: get our hands on the Pixel Data.
837    if ( !fp )
838    {
839       dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
840                       "unavailable file pointer." );
841       return false;
842    }
843
844    fp->seekg( PixelOffset, std::ios::beg );
845    if( fp->fail() || fp->eof()) //Fp->gcount() == 1
846    {
847       dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
848                       "unable to find PixelOffset in file." );
849       return false;
850    }
851
852    AllocateRaw();
853
854    //////////////////////////////////////////////////
855    //// Second stage: read from disk dans decompress.
856    if ( BitsAllocated == 12 )
857    {
858       ReadAndDecompress12BitsTo16Bits( fp);
859    }
860    else if ( IsRaw )
861    {
862       // This problem can be found when some obvious informations are found
863       // after the field containing the image datas. In this case, these
864       // bad datas are added to the size of the image (in the PixelDataLength
865       // variable). But RawSize is the right size of the image !
866       if( PixelDataLength != RawSize)
867       {
868          dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
869                       "Mismatch between PixelReadConvert and RawSize." );
870       }
871       if( PixelDataLength > RawSize)
872       {
873          fp->read( (char*)Raw, RawSize);
874       }
875       else
876       {
877          fp->read( (char*)Raw, PixelDataLength);
878       }
879
880       if ( fp->fail() || fp->eof())//Fp->gcount() == 1
881       {
882          dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
883                          "reading of Raw pixel data failed." );
884          return false;
885       }
886    } 
887    else if ( IsRLELossless )
888    {
889       if ( ! ReadAndDecompressRLEFile( fp ) )
890       {
891          dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
892                          "RLE decompressor failed." );
893          return false;
894       }
895    }
896    else
897    {
898       // Default case concerns JPEG family
899       if ( ! ReadAndDecompressJPEGFile( fp ) )
900       {
901          dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
902                          "JPEG decompressor failed." );
903          return false;
904       }
905    }
906
907    ////////////////////////////////////////////
908    //// Third stage: twigle the bytes and bits.
909    ConvertReorderEndianity();
910    ConvertReArrangeBits();
911    ConvertHandleColor();
912
913    return true;
914 }
915
916 void PixelReadConvert::ConvertHandleColor()
917 {
918    //////////////////////////////////
919    // Deal with the color decoding i.e. handle:
920    //   - R, G, B planes (as opposed to RGB pixels)
921    //   - YBR (various) encodings.
922    //   - LUT[s] (or "PALETTE COLOR").
923    //
924    // The classification in the color decoding schema is based on the blending
925    // of two Dicom tags values:
926    // * "Photometric Interpretation" for which we have the cases:
927    //  - [Photo A] MONOCHROME[1|2] pictures,
928    //  - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
929    //  - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
930    //  - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
931    // * "Planar Configuration" for which we have the cases:
932    //  - [Planar 0] 0 then Pixels are already RGB
933    //  - [Planar 1] 1 then we have 3 planes : R, G, B,
934    //  - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
935    //
936    // Now in theory, one could expect some coherence when blending the above
937    // cases. For example we should not encounter files belonging at the
938    // time to case [Planar 0] and case [Photo D].
939    // Alas, this was only theory ! Because in practice some odd (read ill
940    // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
941    //     - "Planar Configuration" = 0,
942    //     - "Photometric Interpretation" = "PALETTE COLOR".
943    // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
944    // towards Dicom-non-conformance files:
945    //   << whatever the "Planar Configuration" value might be, a
946    //      "Photometric Interpretation" set to "PALETTE COLOR" forces
947    //      a LUT intervention >>
948    //
949    // Now we are left with the following handling of the cases:
950    // - [Planar 0] OR  [Photo A] no color decoding (since respectively
951    //       Pixels are already RGB and monochrome pictures have no color :),
952    // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
953    // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
954    // - [Planar 2] OR  [Photo D] requires LUT intervention.
955
956    if ( ! IsRawRGB() )
957    {
958       // [Planar 2] OR  [Photo D]: LUT intervention done outside
959       return;
960    }
961                                                                                 
962    if ( PlanarConfiguration == 1 )
963    {
964       if ( IsYBRFull )
965       {
966          // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
967          ConvertYcBcRPlanesToRGBPixels();
968       }
969       else
970       {
971          // [Planar 1] AND [Photo C]
972          ConvertRGBPlanesToRGBPixels();
973       }
974       return;
975    }
976                                                                                 
977    // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
978    // pixels need to be RGB-fied anyway
979    if (IsRLELossless)
980    {
981      ConvertRGBPlanesToRGBPixels();
982    }
983    // In *normal *case, when planarConf is 0, pixels are already in RGB
984 }
985
986 /**
987  * \brief Predicate to know wether the image[s] (once Raw) is RGB.
988  * \note See comments of \ref ConvertHandleColor
989  */
990 bool PixelReadConvert::IsRawRGB()
991 {
992    if (   IsMonochrome
993        || PlanarConfiguration == 2
994        || IsPaletteColor )
995    {
996       return false;
997    }
998    return true;
999 }
1000
1001 void PixelReadConvert::ComputeRawAndRGBSizes()
1002 {
1003    int bitsAllocated = BitsAllocated;
1004    // Number of "Bits Allocated" is fixed to 16 when it's 12, since
1005    // in this case we will expand the image to 16 bits (see
1006    //    \ref ReadAndDecompress12BitsTo16Bits() )
1007    if (  BitsAllocated == 12 )
1008    {
1009       bitsAllocated = 16;
1010    }
1011                                                                                 
1012    RawSize =  XSize * YSize * ZSize
1013                      * ( bitsAllocated / 8 )
1014                      * SamplesPerPixel;
1015    if ( HasLUT )
1016    {
1017       RGBSize = 3 * RawSize;
1018    }
1019    else
1020    {
1021       RGBSize = RawSize;
1022    }
1023 }
1024
1025 void PixelReadConvert::GrabInformationsFromHeader( Header* header )
1026 {
1027    // Number of Bits Allocated for storing a Pixel is defaulted to 16
1028    // when absent from the header.
1029    BitsAllocated = header->GetBitsAllocated();
1030    if ( BitsAllocated == 0 )
1031    {
1032       BitsAllocated = 16;
1033    }
1034
1035    // Number of "Bits Stored" defaulted to number of "Bits Allocated"
1036    // when absent from the header.
1037    BitsStored = header->GetBitsStored();
1038    if ( BitsStored == 0 )
1039    {
1040       BitsStored = BitsAllocated;
1041    }
1042
1043    // High Bit Position
1044    HighBitPosition = header->GetHighBitPosition();
1045    if ( HighBitPosition == 0 )
1046    {
1047       HighBitPosition = BitsAllocated - 1;
1048    }
1049
1050    XSize = header->GetXSize();
1051    YSize = header->GetYSize();
1052    ZSize = header->GetZSize();
1053    SamplesPerPixel = header->GetSamplesPerPixel();
1054    PixelSize = header->GetPixelSize();
1055    PixelSign = header->IsSignedPixelData();
1056    SwapCode  = header->GetSwapCode();
1057    TransferSyntaxType ts = header->GetTransferSyntax();
1058    IsRaw =
1059         ( ! header->IsDicomV3() )
1060      || ts == ImplicitVRLittleEndian
1061      || ts == ImplicitVRLittleEndianDLXGE
1062      || ts == ExplicitVRLittleEndian
1063      || ts == ExplicitVRBigEndian
1064      || ts == DeflatedExplicitVRLittleEndian;
1065    IsJPEG2000     = header->IsJPEG2000();
1066    IsJPEGLossless = header->IsJPEGLossless();
1067    IsRLELossless  =  ( ts == RLELossless );
1068    PixelOffset     = header->GetPixelOffset();
1069    PixelDataLength = header->GetPixelAreaLength();
1070    RLEInfo  = header->GetRLEInfo();
1071    JPEGInfo = header->GetJPEGInfo();
1072                                                                              
1073    PlanarConfiguration = header->GetPlanarConfiguration();
1074    IsMonochrome = header->IsMonochrome();
1075    IsPaletteColor = header->IsPaletteColor();
1076    IsYBRFull = header->IsYBRFull();
1077
1078    /////////////////////////////////////////////////////////////////
1079    // LUT section:
1080    HasLUT = header->HasLUT();
1081    if ( HasLUT )
1082    {
1083       // Just in case some access to a Header element requires disk access.
1084       // Note: gdcmDocument::Fp is leaved open after OpenFile.
1085       LutRedDescriptor   = header->GetEntryByNumber( 0x0028, 0x1101 );
1086       LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
1087       LutBlueDescriptor  = header->GetEntryByNumber( 0x0028, 0x1103 );
1088    
1089       // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
1090       // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
1091       // Document::Document() ], the loading of the value (content) of a
1092       // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
1093       // loaded). Hence, we first try to obtain the LUTs data from the header
1094       // and when this fails we read the LUTs data directely from disk.
1095       /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
1096       ///       We should NOT bypass the [Bin|Val]Entry class. Instead
1097       ///       an access to an UNLOADED content of a [Bin|Val]Entry occurence
1098       ///       (e.g. BinEntry::GetBinArea()) should force disk access from
1099       ///       within the [Bin|Val]Entry class itself. The only problem
1100       ///       is that the [Bin|Val]Entry is unaware of the FILE* is was
1101       ///       parsed from. Fix that. FIXME.
1102    
1103       ////// Red round
1104       header->LoadEntryBinArea(0x0028, 0x1201);
1105       LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
1106       if ( ! LutRedData )
1107       {
1108          dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
1109                          "unable to read red LUT data" );
1110       }
1111
1112       ////// Green round:
1113       header->LoadEntryBinArea(0x0028, 0x1202);
1114       LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
1115       if ( ! LutGreenData)
1116       {
1117          dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
1118                         "unable to read green LUT data" );
1119       }
1120
1121       ////// Blue round:
1122       header->LoadEntryBinArea(0x0028, 0x1203);
1123       LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
1124       if ( ! LutBlueData )
1125       {
1126          dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
1127                         "unable to read blue LUT data" );
1128       }
1129    }
1130
1131    ComputeRawAndRGBSizes();
1132 }
1133
1134 /**
1135  * \brief Build Red/Green/Blue/Alpha LUT from Header
1136  *         when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1137  *          and (0028,1101),(0028,1102),(0028,1102)
1138  *            - xxx Palette Color Lookup Table Descriptor - are found
1139  *          and (0028,1201),(0028,1202),(0028,1202)
1140  *            - xxx Palette Color Lookup Table Data - are found
1141  * \warning does NOT deal with :
1142  *   0028 1100 Gray Lookup Table Descriptor (Retired)
1143  *   0028 1221 Segmented Red Palette Color Lookup Table Data
1144  *   0028 1222 Segmented Green Palette Color Lookup Table Data
1145  *   0028 1223 Segmented Blue Palette Color Lookup Table Data
1146  *   no known Dicom reader deals with them :-(
1147  * @return a RGBA Lookup Table
1148  */
1149 void PixelReadConvert::BuildLUTRGBA()
1150 {
1151    if ( LutRGBA )
1152    {
1153       return;
1154    }
1155    // Not so easy : see
1156    // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
1157                                                                                 
1158    if ( ! IsPaletteColor )
1159    {
1160       return;
1161    }
1162                                                                                 
1163    if (   LutRedDescriptor   == GDCM_UNFOUND
1164        || LutGreenDescriptor == GDCM_UNFOUND
1165        || LutBlueDescriptor  == GDCM_UNFOUND )
1166    {
1167       return;
1168    }
1169
1170    ////////////////////////////////////////////
1171    // Extract the info from the LUT descriptors
1172    int lengthR;   // Red LUT length in Bytes
1173    int debR;      // Subscript of the first Lut Value
1174    int nbitsR;    // Lut item size (in Bits)
1175    int nbRead = sscanf( LutRedDescriptor.c_str(),
1176                         "%d\\%d\\%d",
1177                         &lengthR, &debR, &nbitsR );
1178    if( nbRead != 3 )
1179    {
1180       dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong red LUT descriptor");
1181    }
1182                                                                                 
1183    int lengthG;  // Green LUT length in Bytes
1184    int debG;     // Subscript of the first Lut Value
1185    int nbitsG;   // Lut item size (in Bits)
1186    nbRead = sscanf( LutGreenDescriptor.c_str(),
1187                     "%d\\%d\\%d",
1188                     &lengthG, &debG, &nbitsG );
1189    if( nbRead != 3 )
1190    {
1191       dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong green LUT descriptor");
1192    }
1193                                                                                 
1194    int lengthB;  // Blue LUT length in Bytes
1195    int debB;     // Subscript of the first Lut Value
1196    int nbitsB;   // Lut item size (in Bits)
1197    nbRead = sscanf( LutRedDescriptor.c_str(),
1198                     "%d\\%d\\%d",
1199                     &lengthB, &debB, &nbitsB );
1200    if( nbRead != 3 )
1201    {
1202       dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong blue LUT descriptor");
1203    }
1204                                                                                 
1205    ////////////////////////////////////////////////////////
1206    if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1207    {
1208       return;
1209    }
1210
1211    ////////////////////////////////////////////////
1212    // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1213    LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1214    if ( !LutRGBA )
1215    {
1216       return;
1217    }
1218    memset( LutRGBA, 0, 1024 );
1219                                                                                 
1220    int mult;
1221    if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1222    {
1223       // when LUT item size is different than pixel size
1224       mult = 2; // high byte must be = low byte
1225    }
1226    else
1227    {
1228       // See PS 3.3-2003 C.11.1.1.2 p 619
1229       mult = 1;
1230    }
1231                                                                                 
1232    // if we get a black image, let's just remove the '+1'
1233    // from 'i*mult+1' and check again
1234    // if it works, we shall have to check the 3 Palettes
1235    // to see which byte is ==0 (first one, or second one)
1236    // and fix the code
1237    // We give up the checking to avoid some (useless ?)overhead
1238    // (optimistic asumption)
1239    int i;
1240    uint8_t* a = LutRGBA + 0;
1241    for( i=0; i < lengthR; ++i )
1242    {
1243       *a = LutRedData[i*mult+1];
1244       a += 4;
1245    }
1246                                                                                 
1247    a = LutRGBA + 1;
1248    for( i=0; i < lengthG; ++i)
1249    {
1250       *a = LutGreenData[i*mult+1];
1251       a += 4;
1252    }
1253                                                                                 
1254    a = LutRGBA + 2;
1255    for(i=0; i < lengthB; ++i)
1256    {
1257       *a = LutBlueData[i*mult+1];
1258       a += 4;
1259    }
1260                                                                                 
1261    a = LutRGBA + 3;
1262    for(i=0; i < 256; ++i)
1263    {
1264       *a = 1; // Alpha component
1265       a += 4;
1266    }
1267 }
1268
1269 /**
1270  * \brief Build the RGB image from the Raw imagage and the LUTs.
1271  */
1272 bool PixelReadConvert::BuildRGBImage()
1273 {
1274    if ( RGB )
1275    {
1276       // The job is already done.
1277       return true;
1278    }
1279
1280    if ( ! Raw )
1281    {
1282       // The job can't be done
1283       return false;
1284    }
1285
1286    BuildLUTRGBA();
1287    if ( ! LutRGBA )
1288    {
1289       // The job can't be done
1290       return false;
1291    }
1292                                                                                 
1293    // Build RGB Pixels
1294    AllocateRGB();
1295    uint8_t* localRGB = RGB;
1296    for (size_t i = 0; i < RawSize; ++i )
1297    {
1298       int j  = Raw[i] * 4;
1299       *localRGB++ = LutRGBA[j];
1300       *localRGB++ = LutRGBA[j+1];
1301       *localRGB++ = LutRGBA[j+2];
1302    }
1303    return true;
1304 }
1305
1306 /**
1307  * \brief        Print self.
1308  * @param os     Stream to print to.
1309  */
1310 void PixelReadConvert::Print( std::ostream &os )
1311 {
1312    Print("",os);
1313 }
1314
1315 /**
1316  * \brief        Print self.
1317  * @param indent Indentation string to be prepended during printing.
1318  * @param os     Stream to print to.
1319  */
1320 void PixelReadConvert::Print( std::string indent, std::ostream &os )
1321 {
1322    os << indent
1323       << "--- Pixel information -------------------------"
1324       << std::endl;
1325    os << indent
1326       << "Pixel Data: offset " << PixelOffset
1327       << " x(" << std::hex << PixelOffset << std::dec
1328       << ")   length " << PixelDataLength
1329       << " x(" << std::hex << PixelDataLength << std::dec
1330       << ")" << std::endl;
1331
1332    if ( IsRLELossless )
1333    {
1334       if ( RLEInfo )
1335       {
1336          RLEInfo->Print( indent, os );
1337       }
1338       else
1339       {
1340          dbg.Verbose(0, "PixelReadConvert::Print: set as RLE file "
1341                         "but NO RLEinfo present.");
1342       }
1343    }
1344
1345    if ( IsJPEG2000 || IsJPEGLossless )
1346    {
1347       if ( JPEGInfo )
1348       {
1349          JPEGInfo->Print( indent, os );
1350       }
1351       else
1352       {
1353          dbg.Verbose(0, "PixelReadConvert::Print: set as JPEG file "
1354                         "but NO JPEGinfo present.");
1355       }
1356    }
1357 }
1358
1359 } // end namespace gdcm
1360
1361 // NOTES on File internal calls
1362 // User
1363 // ---> GetImageData
1364 //     ---> GetImageDataIntoVector
1365 //        |---> GetImageDataIntoVectorRaw
1366 //        | lut intervention
1367 // User
1368 // ---> GetImageDataRaw
1369 //     ---> GetImageDataIntoVectorRaw
1370