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