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