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