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