]> Creatis software - gdcm.git/blob - src/gdcmPixelConvert.cxx
* src/gdcmDocument.cxx : fix bug... test if the fp is opened to use it
[gdcm.git] / src / gdcmPixelConvert.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmPixelConvert.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/11/25 10:24:34 $
7   Version:   $Revision: 1.33 $
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 is already made by 
591    // ::GrabInformationsFromHeader. So, the structure sizes are
592    // correct
593    Squeeze();
594
595    //////////////////////////////////////////////////
596    //// First stage: get our hands on the Pixel Data.
597    if ( !fp )
598    {
599       dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
600                       "unavailable file pointer." );
601       return false;
602    }
603
604    fp->seekg( PixelOffset, std::ios_base::beg );
605    if( fp->fail() || fp->eof()) //Fp->gcount() == 1
606    {
607       dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
608                       "unable to find PixelOffset in file." );
609       return false;
610    }
611
612    AllocateDecompressed();
613
614    //////////////////////////////////////////////////
615    //// Second stage: read from disk dans decompress.
616    if ( BitsAllocated == 12 )
617    {
618       ReadAndDecompress12BitsTo16Bits( fp);
619    }
620    else if ( IsDecompressed )
621    {
622       // This problem can be found when some obvious informations are found
623       // after the field containing the image datas. In this case, these
624       // bad datas are added to the size of the image (in the PixelDataLength
625       // variable). But DecompressedSize is the right size of the image !
626       if( PixelDataLength != DecompressedSize)
627       {
628          dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
629                       "Mismatch between PixelConvert and DecompressedSize." );
630       }
631       if( PixelDataLength > DecompressedSize)
632       {
633          fp->read( (char*)Decompressed, DecompressedSize);
634       }
635       else
636       {
637          fp->read( (char*)Decompressed, PixelDataLength);
638       }
639
640       if ( fp->fail() || fp->eof())//Fp->gcount() == 1
641       {
642          dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
643                          "reading of decompressed pixel data failed." );
644          return false;
645       }
646    } 
647    else if ( IsRLELossless )
648    {
649       if ( ! ReadAndDecompressRLEFile( fp ) )
650       {
651          dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
652                          "RLE decompressor failed." );
653          return false;
654       }
655    }
656    else
657    {
658       // Default case concerns JPEG family
659       if ( ! ReadAndDecompressJPEGFile( fp ) )
660       {
661          dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
662                          "JPEG decompressor failed." );
663          return false;
664       }
665    }
666
667    ////////////////////////////////////////////
668    //// Third stage: twigle the bytes and bits.
669    ConvertReorderEndianity();
670    ConvertReArrangeBits();
671    ConvertHandleColor();
672
673    return true;
674 }
675
676 void PixelConvert::ConvertHandleColor()
677 {
678    //////////////////////////////////
679    // Deal with the color decoding i.e. handle:
680    //   - R, G, B planes (as opposed to RGB pixels)
681    //   - YBR (various) encodings.
682    //   - LUT[s] (or "PALETTE COLOR").
683    //
684    // The classification in the color decoding schema is based on the blending
685    // of two Dicom tags values:
686    // * "Photometric Interpretation" for which we have the cases:
687    //  - [Photo A] MONOCHROME[1|2] pictures,
688    //  - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
689    //  - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
690    //  - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
691    // * "Planar Configuration" for which we have the cases:
692    //  - [Planar 0] 0 then Pixels are already RGB
693    //  - [Planar 1] 1 then we have 3 planes : R, G, B,
694    //  - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
695    //
696    // Now in theory, one could expect some coherence when blending the above
697    // cases. For example we should not encounter files belonging at the
698    // time to case [Planar 0] and case [Photo D].
699    // Alas, this was only theory ! Because in practice some odd (read ill
700    // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
701    //     - "Planar Configuration" = 0,
702    //     - "Photometric Interpretation" = "PALETTE COLOR".
703    // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
704    // towards Dicom-non-conformance files:
705    //   << whatever the "Planar Configuration" value might be, a
706    //      "Photometric Interpretation" set to "PALETTE COLOR" forces
707    //      a LUT intervention >>
708    //
709    // Now we are left with the following handling of the cases:
710    // - [Planar 0] OR  [Photo A] no color decoding (since respectively
711    //       Pixels are already RGB and monochrome pictures have no color :),
712    // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
713    // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
714    // - [Planar 2] OR  [Photo D] requires LUT intervention.
715
716    if ( ! IsDecompressedRGB() )
717    {
718       // [Planar 2] OR  [Photo D]: LUT intervention done outside
719       return;
720    }
721                                                                                 
722    if ( PlanarConfiguration == 1 )
723    {
724       if ( IsYBRFull )
725       {
726          // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
727          ConvertYcBcRPlanesToRGBPixels();
728       }
729       else
730       {
731          // [Planar 1] AND [Photo C]
732          ConvertRGBPlanesToRGBPixels();
733       }
734       return;
735    }
736                                                                                 
737    // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
738    // pixels need to be RGB-fied anyway
739    if (IsRLELossless)
740    {
741      ConvertRGBPlanesToRGBPixels();
742    }
743    // In *normal *case, when planarConf is 0, pixels are already in RGB
744 }
745
746 /**
747  * \brief Predicate to know wether the image[s] (once decompressed) is RGB.
748  * \note See comments of \ref ConvertHandleColor
749  */
750 bool PixelConvert::IsDecompressedRGB()
751 {
752    if (   IsMonochrome
753        || PlanarConfiguration == 2
754        || IsPaletteColor )
755    {
756       return false;
757    }
758    return true;
759 }
760
761 void PixelConvert::ComputeDecompressedAndRGBSizes()
762 {
763    int bitsAllocated = BitsAllocated;
764    // Number of "Bits Allocated" is fixed to 16 when it's 12, since
765    // in this case we will expand the image to 16 bits (see
766    //    \ref ReadAndDecompress12BitsTo16Bits() )
767    if (  BitsAllocated == 12 )
768    {
769       bitsAllocated = 16;
770    }
771                                                                                 
772    DecompressedSize =  XSize * YSize * ZSize
773                      * ( bitsAllocated / 8 )
774                      * SamplesPerPixel;
775    if ( HasLUT )
776    {
777       RGBSize = 3 * DecompressedSize;
778    }
779    else
780    {
781       RGBSize = DecompressedSize;
782    }
783 }
784
785 void PixelConvert::GrabInformationsFromHeader( Header* header )
786 {
787    // Just in case some access to a Header element requires disk access.
788    // Note: gdcmDocument::Fp is leaved open after OpenFile.
789    std::ifstream* fp = header->OpenFile();
790    // Number of Bits Allocated for storing a Pixel is defaulted to 16
791    // when absent from the header.
792    BitsAllocated = header->GetBitsAllocated();
793    if ( BitsAllocated == 0 )
794    {
795       BitsAllocated = 16;
796    }
797
798    // Number of "Bits Stored" defaulted to number of "Bits Allocated"
799    // when absent from the header.
800    BitsStored = header->GetBitsStored();
801    if ( BitsStored == 0 )
802    {
803       BitsStored = BitsAllocated;
804    }
805
806    // High Bit Position
807    HighBitPosition = header->GetHighBitPosition();
808    if ( HighBitPosition == 0 )
809    {
810       HighBitPosition = BitsAllocated - 1;
811    }
812
813    XSize = header->GetXSize();
814    YSize = header->GetYSize();
815    ZSize = header->GetZSize();
816    SamplesPerPixel = header->GetSamplesPerPixel();
817    PixelSize = header->GetPixelSize();
818    PixelSign = header->IsSignedPixelData();
819    SwapCode  = header->GetSwapCode();
820    TransferSyntaxType ts = header->GetTransferSyntax();
821    IsDecompressed =
822         ( ! header->IsDicomV3() )
823      || ts == ImplicitVRLittleEndian
824      || ts == ImplicitVRLittleEndianDLXGE
825      || ts == ExplicitVRLittleEndian
826      || ts == ExplicitVRBigEndian
827      || ts == DeflatedExplicitVRLittleEndian;
828    IsJPEG2000     = header->IsJPEG2000();
829    IsJPEGLossless = header->IsJPEGLossless();
830    IsRLELossless  =  ( ts == RLELossless );
831    PixelOffset     = header->GetPixelOffset();
832    PixelDataLength = header->GetPixelAreaLength();
833    RLEInfo  = header->GetRLEInfo();
834    JPEGInfo = header->GetJPEGInfo();
835                                                                              
836    PlanarConfiguration = header->GetPlanarConfiguration();
837    IsMonochrome = header->IsMonochrome();
838    IsPaletteColor = header->IsPaletteColor();
839    IsYBRFull = header->IsYBRFull();
840
841    /////////////////////////////////////////////////////////////////
842    // LUT section:
843    HasLUT = header->HasLUT();
844    if ( HasLUT )
845    {
846       LutRedDescriptor   = header->GetEntryByNumber( 0x0028, 0x1101 );
847       LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
848       LutBlueDescriptor  = header->GetEntryByNumber( 0x0028, 0x1103 );
849    
850       // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
851       // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
852       // Document::Document() ], the loading of the value (content) of a
853       // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
854       // loaded). Hence, we first try to obtain the LUTs data from the header
855       // and when this fails we read the LUTs data directely from disk.
856       /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
857       ///       We should NOT bypass the [Bin|Val]Entry class. Instead
858       ///       an access to an UNLOADED content of a [Bin|Val]Entry occurence
859       ///       (e.g. BinEntry::GetBinArea()) should force disk access from
860       ///       within the [Bin|Val]Entry class itself. The only problem
861       ///       is that the [Bin|Val]Entry is unaware of the FILE* is was
862       ///       parsed from. Fix that. FIXME.
863    
864       ////// Red round:
865       LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
866       if ( ! LutRedData )
867       {
868          // Read the Lut Data from disk
869          DocEntry* lutRedDataEntry = header->GetDocEntryByNumber( 0x0028,
870                                                                   0x1201 );
871          LutRedData = new uint8_t[ lutRedDataEntry->GetLength() ];
872          fp->seekg(  lutRedDataEntry->GetOffset() ,std::ios_base::beg );
873          fp->read( (char*)LutRedData, (size_t)lutRedDataEntry->GetLength());
874          if ( fp->fail() || fp->eof())//Fp->gcount() == 1
875          {
876             dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
877                             "unable to read red LUT data" );
878          }
879       }
880
881       ////// Green round:
882       LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
883       if ( ! LutGreenData)
884       {
885          // Read the Lut Data from disk
886          DocEntry* lutGreenDataEntry = header->GetDocEntryByNumber( 0x0028,
887                                                                     0x1202 );
888          LutGreenData = new uint8_t[ lutGreenDataEntry->GetLength() ];
889          fp->seekg( lutGreenDataEntry->GetOffset() , std::ios_base::beg );
890          fp->read( (char*)LutGreenData, (size_t)lutGreenDataEntry->GetLength() );
891          if ( fp->fail() || fp->eof())//Fp->gcount() == 1
892          {
893             dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
894                            "unable to read green LUT data" );
895          }
896       }
897
898       ////// Blue round:
899       LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
900       if ( ! LutBlueData )
901       {
902          // Read the Lut Data from disk
903          DocEntry* lutBlueDataEntry  = header->GetDocEntryByNumber( 0x0028,
904                                                                     0x1203 );
905          LutBlueData = new uint8_t[ lutBlueDataEntry->GetLength() ];
906          fp->seekg(  lutBlueDataEntry->GetOffset() , std::ios_base::beg );
907          fp->read( (char*)LutBlueData, (size_t)lutBlueDataEntry->GetLength() );
908          if ( fp->fail() || fp->eof())//Fp->gcount() == 1
909          {
910             dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
911                            "unable to read blue LUT data" );
912          }
913       }
914    }
915
916    ComputeDecompressedAndRGBSizes();
917
918    if(fp) 
919    {
920       header->CloseFile();
921    }
922 }
923
924 /**
925  * \brief Build Red/Green/Blue/Alpha LUT from Header
926  *         when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
927  *          and (0028,1101),(0028,1102),(0028,1102)
928  *            - xxx Palette Color Lookup Table Descriptor - are found
929  *          and (0028,1201),(0028,1202),(0028,1202)
930  *            - xxx Palette Color Lookup Table Data - are found
931  * \warning does NOT deal with :
932  *   0028 1100 Gray Lookup Table Descriptor (Retired)
933  *   0028 1221 Segmented Red Palette Color Lookup Table Data
934  *   0028 1222 Segmented Green Palette Color Lookup Table Data
935  *   0028 1223 Segmented Blue Palette Color Lookup Table Data
936  *   no known Dicom reader deals with them :-(
937  * @return a RGBA Lookup Table
938  */
939 void PixelConvert::BuildLUTRGBA()
940 {
941    if ( LutRGBA )
942    {
943       return;
944    }
945    // Not so easy : see
946    // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
947                                                                                 
948    if ( ! IsPaletteColor )
949    {
950       return;
951    }
952                                                                                 
953    if (   LutRedDescriptor   == GDCM_UNFOUND
954        || LutGreenDescriptor == GDCM_UNFOUND
955        || LutBlueDescriptor  == GDCM_UNFOUND )
956    {
957       return;
958    }
959
960    ////////////////////////////////////////////
961    // Extract the info from the LUT descriptors
962    int lengthR;   // Red LUT length in Bytes
963    int debR;      // Subscript of the first Lut Value
964    int nbitsR;    // Lut item size (in Bits)
965    int nbRead = sscanf( LutRedDescriptor.c_str(),
966                         "%d\\%d\\%d",
967                         &lengthR, &debR, &nbitsR );
968    if( nbRead != 3 )
969    {
970       dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong red LUT descriptor");
971    }
972                                                                                 
973    int lengthG;  // Green LUT length in Bytes
974    int debG;     // Subscript of the first Lut Value
975    int nbitsG;   // Lut item size (in Bits)
976    nbRead = sscanf( LutGreenDescriptor.c_str(),
977                     "%d\\%d\\%d",
978                     &lengthG, &debG, &nbitsG );
979    if( nbRead != 3 )
980    {
981       dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong green LUT descriptor");
982    }
983                                                                                 
984    int lengthB;  // Blue LUT length in Bytes
985    int debB;     // Subscript of the first Lut Value
986    int nbitsB;   // Lut item size (in Bits)
987    nbRead = sscanf( LutRedDescriptor.c_str(),
988                     "%d\\%d\\%d",
989                     &lengthB, &debB, &nbitsB );
990    if( nbRead != 3 )
991    {
992       dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong blue LUT descriptor");
993    }
994                                                                                 
995    ////////////////////////////////////////////////////////
996    if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
997    {
998       return;
999    }
1000
1001    ////////////////////////////////////////////////
1002    // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1003    LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1004    if ( !LutRGBA )
1005    {
1006       return;
1007    }
1008    memset( LutRGBA, 0, 1024 );
1009                                                                                 
1010    int mult;
1011    if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1012    {
1013       // when LUT item size is different than pixel size
1014       mult = 2; // high byte must be = low byte
1015    }
1016    else
1017    {
1018       // See PS 3.3-2003 C.11.1.1.2 p 619
1019       mult = 1;
1020    }
1021                                                                                 
1022    // if we get a black image, let's just remove the '+1'
1023    // from 'i*mult+1' and check again
1024    // if it works, we shall have to check the 3 Palettes
1025    // to see which byte is ==0 (first one, or second one)
1026    // and fix the code
1027    // We give up the checking to avoid some (useless ?)overhead
1028    // (optimistic asumption)
1029    int i;
1030    uint8_t* a = LutRGBA + 0;
1031    for( i=0; i < lengthR; ++i )
1032    {
1033       *a = LutRedData[i*mult+1];
1034       a += 4;
1035    }
1036                                                                                 
1037    a = LutRGBA + 1;
1038    for( i=0; i < lengthG; ++i)
1039    {
1040       *a = LutGreenData[i*mult+1];
1041       a += 4;
1042    }
1043                                                                                 
1044    a = LutRGBA + 2;
1045    for(i=0; i < lengthB; ++i)
1046    {
1047       *a = LutBlueData[i*mult+1];
1048       a += 4;
1049    }
1050                                                                                 
1051    a = LutRGBA + 3;
1052    for(i=0; i < 256; ++i)
1053    {
1054       *a = 1; // Alpha component
1055       a += 4;
1056    }
1057 }
1058
1059 /**
1060  * \brief Build the RGB image from the Decompressed imagage and the LUTs.
1061  */
1062 bool PixelConvert::BuildRGBImage()
1063 {
1064    if ( RGB )
1065    {
1066       // The job is already done.
1067       return true;
1068    }
1069
1070    if ( ! Decompressed )
1071    {
1072       // The job can't be done
1073       return false;
1074    }
1075
1076    BuildLUTRGBA();
1077    if ( ! LutRGBA )
1078    {
1079       // The job can't be done
1080       return false;
1081    }
1082                                                                                 
1083    // Build RGB Pixels
1084    AllocateRGB();
1085    uint8_t* localRGB = RGB;
1086    for (size_t i = 0; i < DecompressedSize; ++i )
1087    {
1088       int j  = Decompressed[i] * 4;
1089       *localRGB++ = LutRGBA[j];
1090       *localRGB++ = LutRGBA[j+1];
1091       *localRGB++ = LutRGBA[j+2];
1092    }
1093    return true;
1094 }
1095
1096 /**
1097  * \brief        Print self.
1098  * @param indent Indentation string to be prepended during printing.
1099  * @param os     Stream to print to.
1100  */
1101 void PixelConvert::Print( std::string indent, std::ostream &os )
1102 {
1103    os << indent
1104       << "--- Pixel information -------------------------"
1105       << std::endl;
1106    os << indent
1107       << "Pixel Data: offset " << PixelOffset
1108       << " x" << std::hex << PixelOffset << std::dec
1109       << "   length " << PixelDataLength
1110       << " x" << std::hex << PixelDataLength << std::dec
1111       << std::endl;
1112
1113    if ( IsRLELossless )
1114    {
1115       if ( RLEInfo )
1116       {
1117          RLEInfo->Print( indent, os );
1118       }
1119       else
1120       {
1121          dbg.Verbose(0, "PixelConvert::Print: set as RLE file "
1122                         "but NO RLEinfo present.");
1123       }
1124    }
1125
1126    if ( IsJPEG2000 || IsJPEGLossless )
1127    {
1128       if ( JPEGInfo )
1129       {
1130          JPEGInfo->Print( indent, os );
1131       }
1132       else
1133       {
1134          dbg.Verbose(0, "PixelConvert::Print: set as JPEG file "
1135                         "but NO JPEGinfo present.");
1136       }
1137    }
1138 }
1139
1140 } // end namespace gdcm
1141
1142 // NOTES on File internal calls
1143 // User
1144 // ---> GetImageData
1145 //     ---> GetImageDataIntoVector
1146 //        |---> GetImageDataIntoVectorRaw
1147 //        | lut intervention
1148 // User
1149 // ---> GetImageDataRaw
1150 //     ---> GetImageDataIntoVectorRaw