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