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