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