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