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