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