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