]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
* CLEANUP_ROUND (8) for gdcmPixelConvert (end of RLE nigthmare)
[gdcm.git] / src / gdcmFile.cxx
1   /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFile.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/10/08 16:27:20 $
7   Version:   $Revision: 1.135 $
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 "gdcmFile.h"
20 #include "gdcmDebug.h"
21 #include "gdcmPixelConvert.h"
22 #include "jpeg/ljpg/jpegless.h"
23
24 typedef std::pair<TagDocEntryHT::iterator,TagDocEntryHT::iterator> IterHT;
25
26 //-------------------------------------------------------------------------
27 // Constructor / Destructor
28 /**
29  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
30  *        file (gdcmHeader only deals with the ... header)
31  *        Opens (in read only and when possible) an existing file and checks
32  *        for DICOM compliance. Returns NULL on failure.
33  *        It will be up to the user to load the pixels into memory
34  *        (see GetImageData, GetImageDataRaw)
35  * \note  the in-memory representation of all available tags found in
36  *        the DICOM header is post-poned to first header information access.
37  *        This avoid a double parsing of public part of the header when
38  *        user sets an a posteriori shadow dictionary (efficiency can be
39  *        seen as a side effect).   
40  * @param header already built gdcmHeader
41  */
42 gdcmFile::gdcmFile(gdcmHeader *header)
43 {
44    Header     = header;
45    SelfHeader = false;
46    Initialise();
47 }
48
49 /**
50  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
51  *        file (gdcmHeader only deals with the ... header)
52  *        Opens (in read only and when possible) an existing file and checks
53  *        for DICOM compliance. Returns NULL on failure.
54  *        It will be up to the user to load the pixels into memory
55  *        (see GetImageData, GetImageDataRaw)
56  * \note  the in-memory representation of all available tags found in
57  *        the DICOM header is post-poned to first header information access.
58  *        This avoid a double parsing of public part of the header when
59  *        one sets an a posteriori shadow dictionary (efficiency can be
60  *        seen as a side effect).   
61  * @param filename file to be opened for parsing
62  */
63 gdcmFile::gdcmFile(std::string const & filename )
64 {
65    Header = new gdcmHeader( filename );
66    SelfHeader = true;
67    Initialise();
68 }
69
70 /**
71  * \brief Factorization for various forms of constructors.
72  */
73 void gdcmFile::Initialise()
74 {
75    if ( Header->IsReadable() )
76    {
77       ImageDataSizeRaw = ComputeDecompressedPixelDataSizeFromHeader();
78       if ( Header->HasLUT() )
79       {
80          ImageDataSize = 3 * ImageDataSizeRaw;
81       }
82       else
83       {
84          ImageDataSize = ImageDataSizeRaw;
85       }
86    }
87    SaveInitialValues();
88 }
89
90 /**
91  * \brief canonical destructor
92  * \note  If the gdcmHeader was created by the gdcmFile constructor,
93  *        it is destroyed by the gdcmFile
94  */
95 gdcmFile::~gdcmFile()
96
97    if( SelfHeader )
98    {
99       delete Header;
100    }
101    Header = 0;
102
103    DeleteInitialValues();
104 }
105
106 /**
107  * \brief Sets some initial values for the Constructor
108  * \warning not end user intended
109  */
110 void gdcmFile::SaveInitialValues()
111
112
113    PixelRead  = -1; // no ImageData read yet.
114    LastAllocatedPixelDataLength = 0;
115    Pixel_Data = 0;
116
117    InitialSpp = "";     
118    InitialPhotInt = "";
119    InitialPlanConfig = "";
120    InitialBitsAllocated = "";
121    InitialHighBit = "";
122   
123    InitialRedLUTDescr   = 0;
124    InitialGreenLUTDescr = 0;
125    InitialBlueLUTDescr  = 0;
126    InitialRedLUTData    = 0;
127    InitialGreenLUTData  = 0;
128    InitialBlueLUTData   = 0; 
129                 
130    if ( Header->IsReadable() )
131    {
132       // the following values *may* be modified 
133       // by gdcmFile::GetImageDataIntoVectorRaw
134       // we save their initial value.
135       InitialSpp           = Header->GetEntryByNumber(0x0028,0x0002);
136       InitialPhotInt       = Header->GetEntryByNumber(0x0028,0x0004);
137       InitialPlanConfig    = Header->GetEntryByNumber(0x0028,0x0006);
138       
139       InitialBitsAllocated = Header->GetEntryByNumber(0x0028,0x0100);
140       InitialHighBit       = Header->GetEntryByNumber(0x0028,0x0102);
141
142       // the following entries *may* be removed from the H table
143       // (NOT deleted ...) by gdcmFile::GetImageDataIntoVectorRaw  
144       // we keep a pointer on them.
145       InitialRedLUTDescr   = Header->GetDocEntryByNumber(0x0028,0x1101);
146       InitialGreenLUTDescr = Header->GetDocEntryByNumber(0x0028,0x1102);
147       InitialBlueLUTDescr  = Header->GetDocEntryByNumber(0x0028,0x1103);
148
149       InitialRedLUTData    = Header->GetDocEntryByNumber(0x0028,0x1201);
150       InitialGreenLUTData  = Header->GetDocEntryByNumber(0x0028,0x1202);
151       InitialBlueLUTData   = Header->GetDocEntryByNumber(0x0028,0x1203); 
152    }
153 }
154
155 /**
156  * \brief restores some initial values
157  * \warning not end user intended
158  */
159 void gdcmFile::RestoreInitialValues()
160 {   
161    if ( Header->IsReadable() )
162    {      
163       // the following values *may* have been modified 
164       // by gdcmFile::GetImageDataIntoVectorRaw
165       // we restore their initial value.
166       if ( InitialSpp != "")
167          Header->SetEntryByNumber(InitialSpp,0x0028,0x0002);
168       if ( InitialPhotInt != "")
169          Header->SetEntryByNumber(InitialPhotInt,0x0028,0x0004);
170       if ( InitialPlanConfig != "")
171
172          Header->SetEntryByNumber(InitialPlanConfig,0x0028,0x0006);
173       if ( InitialBitsAllocated != "")
174           Header->SetEntryByNumber(InitialBitsAllocated,0x0028,0x0100);
175       if ( InitialHighBit != "")
176           Header->SetEntryByNumber(InitialHighBit,0x0028,0x0102);
177                
178       // the following entries *may* be have been removed from the H table
179       // (NOT deleted ...) by gdcmFile::GetImageDataIntoVectorRaw  
180       // we restore them.
181
182       if (InitialRedLUTDescr)
183          Header->AddEntry(InitialRedLUTDescr);
184       if (InitialGreenLUTDescr)
185          Header->AddEntry(InitialGreenLUTDescr);
186       if (InitialBlueLUTDescr)
187          Header->AddEntry(InitialBlueLUTDescr);
188
189       if (InitialRedLUTData)
190          Header->AddEntry(InitialBlueLUTDescr);
191       if (InitialGreenLUTData)
192          Header->AddEntry(InitialGreenLUTData);
193       if (InitialBlueLUTData)
194          Header->AddEntry(InitialBlueLUTData);
195    }
196 }
197
198 /**
199  * \brief delete initial values (il they were saved)
200  *        of InitialLutDescriptors and InitialLutData
201  */
202 void gdcmFile::DeleteInitialValues()
203
204
205 // InitialLutDescriptors and InitialLutData
206 // will have to be deleted if the don't belong any longer
207 // to the Header H table when the header is deleted...
208
209    if ( InitialRedLUTDescr )           
210       delete InitialRedLUTDescr;
211   
212    if ( InitialGreenLUTDescr )
213       delete InitialGreenLUTDescr;
214       
215    if ( InitialBlueLUTDescr )      
216       delete InitialBlueLUTDescr; 
217        
218    if ( InitialRedLUTData )      
219       delete InitialRedLUTData;
220    
221    if ( InitialGreenLUTData != NULL)
222       delete InitialGreenLUTData;
223       
224    if ( InitialBlueLUTData != NULL)      
225       delete InitialBlueLUTData;      
226 }
227
228 //-----------------------------------------------------------------------------
229 // Print
230
231 //-----------------------------------------------------------------------------
232 // Public
233
234 /**
235  * \brief     computes the length (in bytes) we must ALLOCATE to receive the
236  *            image(s) pixels (multiframes taken into account) 
237  * \warning : it is NOT the group 7FE0 length
238  *          (no interest for compressed images).
239  */
240 int gdcmFile::ComputeDecompressedPixelDataSizeFromHeader()
241 {
242    // see PS 3.3-2003 : C.7.6.3.2.1  
243    // 
244    //   MONOCHROME1
245    //   MONOCHROME2
246    //   PALETTE COLOR
247    //   RGB
248    //   HSV  (Retired)
249    //   ARGB (Retired)
250    //   CMYK (Retired)
251    //   YBR_FULL
252    //   YBR_FULL_422 (no LUT, no Palette)
253    //   YBR_PARTIAL_422
254    //   YBR_ICT
255    //   YBR_RCT
256
257    // LUT's
258    // ex : gdcm-US-ALOKA-16.dcm
259    // 0028|1221 [OW]   [Segmented Red Palette Color Lookup Table Data]
260    // 0028|1222 [OW]   [Segmented Green Palette Color Lookup Table Data]  
261    // 0028|1223 [OW]   [Segmented Blue Palette Color Lookup Table Data]
262
263    // ex  : OT-PAL-8-face.dcm
264    // 0028|1201 [US]   [Red Palette Color Lookup Table Data]
265    // 0028|1202 [US]   [Green Palette Color Lookup Table Data]
266    // 0028|1203 [US]   [Blue Palette Color Lookup Table Data]
267
268    // Number of "Bits Allocated"
269    int numberBitsAllocated = Header->GetBitsAllocated();
270    if ( ( numberBitsAllocated == 0 ) || ( numberBitsAllocated == 12 ) )
271    {
272       numberBitsAllocated = 16;
273    } 
274
275    int DecompressedSize = Header->GetXSize()
276                         * Header->GetYSize() 
277                         * Header->GetZSize()
278                         * ( numberBitsAllocated / 8 )
279                         * Header->GetSamplesPerPixel();
280    
281    return DecompressedSize;
282 }
283
284 /**
285  * \brief   - Allocates necessary memory, 
286  *          - Reads the pixels from disk (uncompress if necessary),
287  *          - Transforms YBR pixels, if any, into RGB pixels
288  *          - Transforms 3 planes R, G, B, if any, into a single RGB Plane
289  *          - Transforms single Grey plane + 3 Palettes into a RGB Plane
290  *          - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
291  * @return  Pointer to newly allocated pixel data.
292  *          NULL if alloc fails 
293  */
294 uint8_t* gdcmFile::GetImageData()
295 {
296    // FIXME (Mathieu)
297    // I need to deallocate Pixel_Data before doing any allocation:
298    
299    if ( Pixel_Data )
300      if ( LastAllocatedPixelDataLength != ImageDataSize ) 
301         free(Pixel_Data);
302    if ( !Pixel_Data )
303       Pixel_Data = new uint8_t[ImageDataSize];
304     
305    if ( Pixel_Data )
306    {
307       LastAllocatedPixelDataLength = ImageDataSize;
308
309       // we load the pixels (and transform grey level + LUT into RGB)
310       GetImageDataIntoVector(Pixel_Data, ImageDataSize);
311
312       // We say the value *is* loaded.
313       GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
314          GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
315
316       // Will be 7fe0, 0010 in standard case
317       GetHeader()->SetEntryBinAreaByNumber( Pixel_Data, 
318          GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel()); 
319    }      
320    PixelRead = 0; // no PixelRaw
321
322    return Pixel_Data;
323 }
324
325 /**
326  * \brief
327  *          Read the pixels from disk (uncompress if necessary),
328  *          Transforms YBR pixels, if any, into RGB pixels
329  *          Transforms 3 planes R, G, B, if any, into a single RGB Plane
330  *          Transforms single Grey plane + 3 Palettes into a RGB Plane   
331  *          Copies at most MaxSize bytes of pixel data to caller allocated
332  *          memory space.
333  * \warning This function allows people that want to build a volume
334  *          from an image stack *not to* have, first to get the image pixels, 
335  *          and then move them to the volume area.
336  *          It's absolutely useless for any VTK user since vtk chooses 
337  *          to invert the lines of an image, that is the last line comes first
338  *          (for some axis related reasons?). Hence he will have 
339  *          to load the image line by line, starting from the end.
340  *          VTK users have to call GetImageData
341  *     
342  * @param   destination Address (in caller's memory space) at which the
343  *          pixel data should be copied
344  * @param   maxSize Maximum number of bytes to be copied. When MaxSize
345  *          is not sufficient to hold the pixel data the copy is not
346  *          executed (i.e. no partial copy).
347  * @return  On success, the number of bytes actually copied. Zero on
348  *          failure e.g. MaxSize is lower than necessary.
349  */
350 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t maxSize)
351 {
352    GetImageDataIntoVectorRaw (destination, maxSize);
353    PixelRead = 0 ; // =0 : no ImageDataRaw 
354    if ( !Header->HasLUT() )
355    {
356       return ImageDataSize;
357    }
358                             
359    // from Lut R + Lut G + Lut B
360    uint8_t *newDest = new uint8_t[ImageDataSize];
361    uint8_t *a       = (uint8_t *)destination;
362    uint8_t *lutRGBA = Header->GetLUTRGBA();
363
364    if ( lutRGBA )
365    {
366       int j;
367       // move Gray pixels to temp area  
368       memmove(newDest, destination, ImageDataSizeRaw);
369       for (size_t i=0; i<ImageDataSizeRaw; ++i) 
370       {
371          // Build RGB Pixels
372          j    = newDest[i]*4;
373          *a++ = lutRGBA[j];
374          *a++ = lutRGBA[j+1];
375          *a++ = lutRGBA[j+2];
376       }
377       delete[] newDest;
378     
379    // now, it's an RGB image
380    // Lets's write it in the Header
381
382    // FIXME : Better use CreateOrReplaceIfExist ?
383
384    std::string spp = "3";        // Samples Per Pixel
385    Header->SetEntryByNumber(spp,0x0028,0x0002);
386    std::string rgb = "RGB ";     // Photometric Interpretation
387    Header->SetEntryByNumber(rgb,0x0028,0x0004);
388    std::string planConfig = "0"; // Planar Configuration
389    Header->SetEntryByNumber(planConfig,0x0028,0x0006);
390
391    }
392    else  // GetLUTRGBA() failed
393    { 
394       // (gdcm-US-ALOKA-16.dcm), contains Segmented xxx Palette Color 
395       // that are *more* than 65535 long ?!? 
396       // No idea how to manage such an image !
397       // Need to make RGB Pixels (?) from grey Pixels (?!) and Gray Lut  (!?!)
398       // It seems that *no Dicom Viewer* has any idea :-(
399         
400       std::string photomInterp = "MONOCHROME1 ";  // Photometric Interpretation
401       Header->SetEntryByNumber(photomInterp,0x0028,0x0004);
402    } 
403
404    /// \todo Drop Palette Color out of the Header?
405    return ImageDataSize; 
406 }
407
408 /**
409  * \brief   Allocates necessary memory, 
410  *          Transforms YBR pixels (if any) into RGB pixels
411  *          Transforms 3 planes R, G, B  (if any) into a single RGB Plane
412  *          Copies the pixel data (image[s]/volume[s]) to newly allocated zone. 
413  *          DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
414  * @return  Pointer to newly allocated pixel data.
415  * \        NULL if alloc fails 
416  */
417 uint8_t* gdcmFile::GetImageDataRaw ()
418 {
419    size_t imgDataSize;
420    if ( Header->HasLUT() )
421       /// \todo Let gdcmHeader user a chance to get the right value
422       imgDataSize = ImageDataSizeRaw;
423    else 
424       imgDataSize = ImageDataSize;
425     
426    // FIXME (Mathieu)
427    // I need to deallocate Pixel_Data before doing any allocation:
428    
429    if ( Pixel_Data )
430       if ( LastAllocatedPixelDataLength != imgDataSize )
431          free(Pixel_Data);
432    if ( !Pixel_Data ) 
433       Pixel_Data = new uint8_t[imgDataSize];
434
435    if ( Pixel_Data )
436    {
437       LastAllocatedPixelDataLength = imgDataSize;
438       
439       // we load the pixels ( grey level or RGB, but NO transformation)
440        GetImageDataIntoVectorRaw(Pixel_Data, imgDataSize);
441
442       // We say the value *is* loaded.
443       GetHeader()->SetEntryByNumber( GDCM_BINLOADED,
444          GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
445  
446       // will be 7fe0, 0010 in standard cases
447       GetHeader()->SetEntryBinAreaByNumber(Pixel_Data, 
448          GetHeader()->GetGrPixel(), GetHeader()->GetNumPixel());
449    } 
450    PixelRead = 1; // PixelRaw
451
452    return Pixel_Data;
453 }
454
455 /**
456  * \brief   Copies at most MaxSize bytes of pixel data to caller's
457  *          memory space.
458  * \warning This function was designed to avoid people that want to build
459  *          a volume from an image stack to need first to get the image pixels 
460  *          and then move them to the volume area.
461  *          It's absolutely useless for any VTK user since vtk chooses 
462  *          to invert the lines of an image, that is the last line comes first
463  *          (for some axis related reasons?). Hence he will have 
464  *          to load the image line by line, starting from the end.
465  *          VTK users hace to call GetImageData
466  * \warning DOES NOT transform the Grey Plane + Palette Color (if any) 
467  *                   into a single RGB Pixels Plane
468  *          the (VTK) user will manage the palettes
469  *     
470  * @param   destination Address (in caller's memory space) at which the
471  *          pixel data should be copied
472  * @param   maxSize Maximum number of bytes to be copied. When MaxSize
473  *          is not sufficient to hold the pixel data the copy is not
474  *          executed (i.e. no partial copy).
475  * @return  On success, the number of bytes actually copied. Zero on
476  *          failure e.g. MaxSize is lower than necessary.
477  */
478 size_t gdcmFile::GetImageDataIntoVectorRaw (void* destination, size_t maxSize)
479 {
480   // we save the initial values of the following
481   // in order to be able to restore the header in a disk-consistent state
482   // (if user asks twice to get the pixels from disk)
483
484    if ( PixelRead != -1 ) // File was "read" before
485    {  
486       RestoreInitialValues(); 
487    }
488    
489    PixelRead = 1 ; // PixelRaw
490     
491    if ( ImageDataSize > maxSize )
492    {
493       dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
494                      "than caller's expected MaxSize");
495       return (size_t)0;
496    }
497
498    ReadPixelData( destination );
499
500    // Number of Bits Allocated for storing a Pixel
501    int numberBitsAllocated = Header->GetBitsAllocated();
502    if ( numberBitsAllocated == 0 )
503    {
504       numberBitsAllocated = 16;
505    }
506
507    // Number of Bits actually used
508    int numberBitsStored = Header->GetBitsStored();
509    if ( numberBitsStored == 0 )
510    {
511       numberBitsStored = numberBitsAllocated;
512    }
513
514    // High Bit Position
515    int highBitPosition = Header->GetHighBitPosition();
516    if ( highBitPosition == 0 )
517    {
518       highBitPosition = numberBitsAllocated - 1;
519    }
520
521    bool signedPixel = Header->IsSignedPixelData();
522
523    ConvertReorderEndianity( (uint8_t*) destination,
524                             ImageDataSize,
525                             numberBitsStored,
526                             numberBitsAllocated,
527                             signedPixel );
528
529    ConvertReArrangeBits( (uint8_t*) destination,
530                          ImageDataSize,
531                          numberBitsStored,
532                          numberBitsAllocated,
533                          highBitPosition );
534
535 #ifdef GDCM_DEBUG
536    FILE*  DebugFile;
537    DebugFile = fopen( "SpuriousFile.RAW", "wb" );
538    fwrite( PixelConvertor.GetUncompressed(),
539            PixelConvertor.GetUncompressedsSize(),
540            1, DebugFile );
541    fclose( DebugFile );
542 #endif //GDCM_DEBUG
543
544 // SPLIT ME
545 //////////////////////////////////
546 // Deal with the color
547    
548    // Monochrome pictures don't require color intervention
549    if ( Header->IsMonochrome() )
550    {
551       return ImageDataSize; 
552    }
553       
554    // Planar configuration = 0 : Pixels are already RGB
555    // Planar configuration = 1 : 3 planes : R, G, B
556    // Planar configuration = 2 : 1 gray Plane + 3 LUT
557
558    // Well ... supposed to be !
559    // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
560    //                            PhotometricInterpretation=PALETTE COLOR
561    // and heuristic has to be found :-( 
562
563    int planConf = Header->GetPlanarConfiguration();
564
565    // Planar configuration = 2 ==> 1 gray Plane + 3 LUT
566    //   ...and...
567    // whatever the Planar Configuration might be, "PALETTE COLOR "
568    // implies that we deal with the palette. 
569    if ( ( planConf == 2 ) || Header->IsPaletteColor() )
570    {
571       return ImageDataSize;
572    }
573
574    // When planConf is 0, pixels are allready in RGB
575
576    if ( planConf == 1 )
577    {
578       uint8_t* newDest = new uint8_t[ImageDataSize];
579       // Warning : YBR_FULL_422 acts as RGB
580       if ( Header->IsYBRFull() )
581       {
582          ConvertYcBcRPlanesToRGBPixels((uint8_t*)destination, newDest);
583       }
584       else
585       {
586          ConvertRGBPlanesToRGBPixels((uint8_t*)destination, newDest);
587       }
588       memmove(destination, newDest, ImageDataSize);
589       delete[] newDest;
590    }
591
592 ///////////////////////////////////////////////////
593    // now, it's an RGB image
594    // Lets's write it in the Header
595  
596    // Droping Palette Color out of the Header
597    // has been moved to the Write process.
598
599    // TODO : move 'values' modification to the write process
600    //      : save also (in order to be able to restore)
601    //      : 'high bit' -when not equal to 'bits stored' + 1
602    //      : 'bits allocated', when it's equal to 12 ?!
603
604    std::string spp = "3";            // Samples Per Pixel
605    std::string photInt = "RGB ";     // Photometric Interpretation
606    std::string planConfig = "0";     // Planar Configuration
607      
608    Header->SetEntryByNumber(spp,0x0028,0x0002);
609    Header->SetEntryByNumber(photInt,0x0028,0x0004);
610    Header->SetEntryByNumber(planConfig,0x0028,0x0006);
611  
612    return ImageDataSize; 
613 }
614
615 /**
616  * \brief   Re-arrange the bits within the bytes.
617  */
618 void gdcmFile::ConvertReArrangeBits( uint8_t* pixelZone,
619                                      size_t imageDataSize,
620                                      int numberBitsStored,
621                                      int numberBitsAllocated,
622                                      int highBitPosition)
623      throw ( gdcmFormatError )
624 {
625    if ( numberBitsStored != numberBitsAllocated )
626    {
627       int l = (int)(imageDataSize / (numberBitsAllocated/8));
628       if ( numberBitsAllocated == 16 )
629       {
630          uint16_t mask = 0xffff;
631          mask = mask >> ( numberBitsAllocated - numberBitsStored );
632          uint16_t* deb = (uint16_t*)pixelZone;
633          for(int i = 0; i<l; i++)
634          {
635             *deb = (*deb >> (numberBitsStored - highBitPosition - 1)) & mask;
636             deb++;
637          }
638       }
639       else if ( numberBitsAllocated == 32 )
640       {
641          uint32_t mask = 0xffffffff;
642          mask = mask >> ( numberBitsAllocated - numberBitsStored );
643          uint32_t* deb = (uint32_t*)pixelZone;
644          for(int i = 0; i<l; i++)
645          {
646             *deb = (*deb >> (numberBitsStored - highBitPosition - 1)) & mask;
647             deb++;
648          }
649       }
650       else
651       {
652          dbg.Verbose(0, "gdcmFile::ConvertReArrangeBits: weird image");
653          throw gdcmFormatError( "gdcmFile::ConvertReArrangeBits()",
654                                 "weird image !?" );
655       }
656    }
657 }
658
659 /**
660  * \brief Deal with endianity i.e. re-arange bytes inside the integer
661  */
662 void gdcmFile::ConvertReorderEndianity( uint8_t* pixelZone,
663                                         size_t imageDataSize,
664                                         int numberBitsStored,
665                                         int numberBitsAllocated,
666                                         bool signedPixel)
667 {
668    if ( numberBitsAllocated != 8 )
669    {
670       SwapZone( pixelZone, Header->GetSwapCode(), ImageDataSize,
671                 numberBitsAllocated );
672    }
673      
674    // Special kludge in order to deal with xmedcon broken images:
675    if (  ( numberBitsAllocated == 16 )
676       && ( numberBitsStored < numberBitsAllocated )
677       && ( ! signedPixel ) )
678    {
679       int l = (int)(ImageDataSize / (numberBitsAllocated/8));
680       uint16_t *deb = (uint16_t *)pixelZone;
681       for(int i = 0; i<l; i++)
682       {
683          if( *deb == 0xffff )
684          {
685            *deb = 0;
686          }
687          deb++;   
688       }
689    }
690 }
691
692 /**
693  * \brief   Convert (Y plane, cB plane, cR plane) to RGB pixels
694  * \warning Works on all the frames at a time
695  */
696 void gdcmFile::ConvertYcBcRPlanesToRGBPixels(uint8_t* source,
697                                              uint8_t* destination)
698 {
699    // to see the tricks about YBR_FULL, YBR_FULL_422, 
700    // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
701    // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
702    // and be *very* affraid
703    //
704    int l        = Header->GetXSize() * Header->GetYSize();
705    int nbFrames = Header->GetZSize();
706
707    uint8_t* a = source;
708    uint8_t* b = source + l;
709    uint8_t* c = source + l + l;
710    double R, G, B;
711
712    /// \todo : Replace by the 'well known' integer computation
713    ///         counterpart. Refer to
714    ///            http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
715    ///         for code optimisation.
716  
717    for (int i = 0; i < nbFrames; i++)
718    {
719       for (int j = 0; j < l; j++)
720       {
721          R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
722          G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
723          B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
724
725          if (R < 0.0)   R = 0.0;
726          if (G < 0.0)   G = 0.0;
727          if (B < 0.0)   B = 0.0;
728          if (R > 255.0) R = 255.0;
729          if (G > 255.0) G = 255.0;
730          if (B > 255.0) B = 255.0;
731
732          *(destination++) = (uint8_t)R;
733          *(destination++) = (uint8_t)G;
734          *(destination++) = (uint8_t)B;
735          a++;
736          b++;
737          c++;  
738       }
739    }
740 }
741
742 /**
743  * \brief   Convert (Red plane, Green plane, Blue plane) to RGB pixels
744  * \warning Works on all the frames at a time
745  */
746 void gdcmFile::ConvertRGBPlanesToRGBPixels(uint8_t* source,
747                                            uint8_t* destination)
748 {
749    int l = Header->GetXSize() * Header->GetYSize() * Header->GetZSize();
750
751    uint8_t* a = source;
752    uint8_t* b = source + l;
753    uint8_t* c = source + l + l;
754
755    for (int j = 0; j < l; j++)
756    {
757       *(destination++) = *(a++);
758       *(destination++) = *(b++);
759       *(destination++) = *(c++);
760    }
761 }
762
763 /**
764  * \brief   Points the internal Pixel_Data pointer to the callers inData
765  *          image representation, BUT WITHOUT COPYING THE DATA.
766  *          'image' Pixels are presented as C-like 2D arrays : line per line.
767  *          'volume'Pixels are presented as C-like 3D arrays : plane per plane 
768  * \warning Since the pixels are not copied, it is the caller's responsability
769  *          not to deallocate it's data before gdcm uses them (e.g. with
770  *          the Write() method.
771  * @param inData user supplied pixel area
772  * @param expectedSize total image size, in Bytes
773  *
774  * @return boolean
775  */
776 bool gdcmFile::SetImageData(uint8_t* inData, size_t expectedSize)
777 {
778    Header->SetImageDataSize( expectedSize );
779 // FIXME : if already allocated, memory leak !
780    Pixel_Data     = inData;
781    ImageDataSize = ImageDataSizeRaw = expectedSize;
782    PixelRead     = 1;
783 // FIXME : 7fe0, 0010 IS NOT set ...
784    return true;
785 }
786
787 /**
788  * \brief Writes on disk A SINGLE Dicom file
789  *        NO test is performed on  processor "Endiannity".
790  *        It's up to the user to call his Reader properly
791  * @param fileName name of the file to be created
792  *                 (any already existing file is over written)
793  * @return false if write fails
794  */
795
796 bool gdcmFile::WriteRawData(std::string const & fileName)
797 {
798    FILE* fp1 = fopen(fileName.c_str(), "wb");
799    if (fp1 == NULL)
800    {
801       printf("Fail to open (write) file [%s] \n", fileName.c_str());
802       return false;
803    }
804    fwrite (Pixel_Data, ImageDataSize, 1, fp1);
805    fclose (fp1);
806
807    return true;
808 }
809
810 /**
811  * \brief Writes on disk A SINGLE Dicom file, 
812  *        using the Implicit Value Representation convention
813  *        NO test is performed on  processor "Endiannity".
814  * @param fileName name of the file to be created
815  *                 (any already existing file is overwritten)
816  * @return false if write fails
817  */
818
819 bool gdcmFile::WriteDcmImplVR (std::string const & fileName)
820 {
821    return WriteBase(fileName, gdcmImplicitVR);
822 }
823
824 /**
825 * \brief Writes on disk A SINGLE Dicom file, 
826  *        using the Explicit Value Representation convention
827  *        NO test is performed on  processor "Endiannity". * @param fileName name of the file to be created
828  *                 (any already existing file is overwritten)
829  * @return false if write fails
830  */
831
832 bool gdcmFile::WriteDcmExplVR (std::string const & fileName)
833 {
834    return WriteBase(fileName, gdcmExplicitVR);
835 }
836
837 /**
838  * \brief Writes on disk A SINGLE Dicom file, 
839  *        using the ACR-NEMA convention
840  *        NO test is performed on  processor "Endiannity".
841  *        (a l'attention des logiciels cliniques 
842  *        qui ne prennent en entrée QUE des images ACR ...
843  * \warning if a DICOM_V3 header is supplied,
844  *         groups < 0x0008 and shadow groups are ignored
845  * \warning NO TEST is performed on processor "Endiannity".
846  * @param fileName name of the file to be created
847  *                 (any already existing file is overwritten)
848  * @return false if write fails
849  */
850
851 bool gdcmFile::WriteAcr (std::string const & fileName)
852 {
853    return WriteBase(fileName, gdcmACR);
854 }
855
856 //-----------------------------------------------------------------------------
857 // Protected
858 /**
859  * \brief NOT a end user inteded function
860  *        (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
861  * @param fileName name of the file to be created
862  *                 (any already existing file is overwritten)
863  * @param  type file type (ExplicitVR, ImplicitVR, ...)
864  * @return false if write fails
865  */
866 bool gdcmFile::WriteBase (std::string const & fileName, FileType type)
867 {
868    if ( PixelRead == -1 && type != gdcmExplicitVR)
869    {
870       return false;
871    }
872
873    FILE* fp1 = fopen(fileName.c_str(), "wb");
874    if (fp1 == NULL)
875    {
876       printf("Failed to open (write) File [%s] \n", fileName.c_str());
877       return false;
878    }
879
880    if ( type == gdcmImplicitVR || type == gdcmExplicitVR )
881    {
882       // writing Dicom File Preamble
883       uint8_t* filePreamble = new uint8_t[128];
884       memset(filePreamble, 0, 128);
885       fwrite(filePreamble, 128, 1, fp1);
886       fwrite("DICM", 4, 1, fp1);
887
888       delete[] filePreamble;
889    }
890
891    // --------------------------------------------------------------
892    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
893    //
894    // if recognition code tells us we dealt with a LibIDO image
895    // we reproduce on disk the switch between lineNumber and columnNumber
896    // just before writting ...
897    
898    /// \todo the best trick would be *change* the recognition code
899    ///       but pb expected if user deals with, e.g. COMPLEX images
900
901    std::string rows, columns; 
902    if ( Header->GetFileType() == gdcmACR_LIBIDO)
903    {
904       rows    = Header->GetEntryByNumber(0x0028, 0x0010);
905       columns = Header->GetEntryByNumber(0x0028, 0x0011);
906
907       Header->SetEntryByNumber(columns,  0x0028, 0x0010);
908       Header->SetEntryByNumber(rows   ,  0x0028, 0x0011);
909    }
910    // ----------------- End of Special Patch ----------------
911       
912    uint16_t grPixel  = Header->GetGrPixel();
913    uint16_t numPixel = Header->GetNumPixel();;
914           
915    gdcmDocEntry* PixelElement = 
916       GetHeader()->GetDocEntryByNumber(grPixel, numPixel);  
917  
918    if ( PixelRead == 1 )
919    {
920       // we read pixel 'as is' (no tranformation LUT -> RGB)
921       PixelElement->SetLength( ImageDataSizeRaw );
922    }
923    else if ( PixelRead == 0 )
924    {
925       // we tranformed GrayLevel pixels + LUT into RGB Pixel
926       PixelElement->SetLength( ImageDataSize );
927    }
928  
929    Header->Write(fp1, type);
930
931    // --------------------------------------------------------------
932    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
933    // 
934    // ...and we restore the Header to be Dicom Compliant again 
935    // just after writting
936
937    if ( Header->GetFileType() == gdcmACR_LIBIDO )
938    {
939       Header->SetEntryByNumber(rows   , 0x0028, 0x0010);
940       Header->SetEntryByNumber(columns, 0x0028, 0x0011);
941    }
942    // ----------------- End of Special Patch ----------------
943    
944    // fwrite(Pixel_Data, ImageDataSize, 1, fp1);  // should be useless, now
945    fclose (fp1);
946
947    return true;
948 }
949
950 //-----------------------------------------------------------------------------
951 // Private
952 /**
953  * \brief   Swap the bytes, according to swap code.
954  * \warning not end user intended
955  * @param   im area to deal with
956  * @param   swap swap code
957  * @param   lgr Area Length
958  * @param   nb Pixels Bit number 
959  */
960 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb)
961 {
962    int i;
963
964    if( nb == 16 )
965    {
966       uint16_t* im16 = (uint16_t*)im;
967       switch( swap )
968       {
969          case 0:
970          case 12:
971          case 1234:
972             break;
973          case 21:
974          case 3412:
975          case 2143:
976          case 4321:
977             for(i=0; i < lgr/2; i++)
978             {
979                im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
980             }
981             break;
982          default:
983             std::cout << "SWAP value (16 bits) not allowed :i" << swap << 
984             std::endl;
985       }
986    }
987    else if( nb == 32 )
988    {
989       uint32_t s32;
990       uint16_t fort, faible;
991       uint32_t* im32 = (uint32_t*)im;
992       switch ( swap )
993       {
994          case 0:
995          case 1234:
996             break;
997          case 4321:
998             for(i = 0; i < lgr/4; i++)
999             {
1000                faible  = im32[i] & 0x0000ffff;  // 4321
1001                fort    = im32[i] >> 16;
1002                fort    = ( fort >> 8   ) | ( fort << 8 );
1003                faible  = ( faible >> 8 ) | ( faible << 8);
1004                s32     = faible;
1005                im32[i] = ( s32 << 16 ) | fort;
1006             }
1007             break;
1008          case 2143:
1009             for(i = 0; i < lgr/4; i++)
1010             {
1011                faible  = im32[i] & 0x0000ffff;   // 2143
1012                fort    = im32[i] >> 16;
1013                fort    = ( fort >> 8 ) | ( fort << 8 );
1014                faible  = ( faible >> 8) | ( faible << 8);
1015                s32     = fort; 
1016                im32[i] = ( s32 << 16 ) | faible;
1017             }
1018             break;
1019          case 3412:
1020             for(i = 0; i < lgr/4; i++)
1021             {
1022                faible  = im32[i] & 0x0000ffff; // 3412
1023                fort    = im32[i] >> 16;
1024                s32     = faible;
1025                im32[i] = ( s32 << 16 ) | fort;
1026             }
1027             break;
1028          default:
1029             std::cout << "SWAP value (32 bits) not allowed : " << swap << 
1030             std::endl;
1031       }
1032    }
1033 }
1034
1035 /**
1036  * \brief   Read pixel data from disk (optionaly decompressing) into the
1037  *          caller specified memory location.
1038  * @param   destination where the pixel data should be stored.
1039  *
1040  */
1041 bool gdcmFile::ReadPixelData(void* destination) 
1042 {
1043    FILE* fp = Header->OpenFile();
1044
1045    if ( !fp )
1046    {
1047       return false;
1048    }
1049    if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 )
1050    {
1051       Header->CloseFile();
1052       return false;
1053    }
1054
1055    if ( Header->GetBitsAllocated() == 12 )
1056    {
1057       ConvertDecompress12BitsTo16Bits( (uint8_t*)destination, 
1058                                        Header->GetXSize(),
1059                                        Header->GetYSize(),
1060                                        fp);
1061       Header->CloseFile();
1062       return true;
1063    }
1064
1065    // ----------------------  Uncompressed File
1066    if ( !Header->IsDicomV3()                             ||
1067         Header->IsImplicitVRLittleEndianTransferSyntax() ||
1068         Header->IsExplicitVRLittleEndianTransferSyntax() ||
1069         Header->IsExplicitVRBigEndianTransferSyntax()    ||
1070         Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() )
1071    {
1072       size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
1073       Header->CloseFile();
1074       if ( ItemRead != 1 )
1075       {
1076          return false;
1077       }
1078       else
1079       {
1080          return true;
1081       }
1082    }
1083
1084    // ---------------------- Run Length Encoding
1085    if ( Header->IsRLELossLessTransferSyntax() )
1086    {
1087       bool res = gdcmPixelConvert::gdcm_read_RLE_file ( destination,
1088                                       Header->GetXSize(),
1089                                       Header->GetYSize(),
1090                                       Header->GetZSize(),
1091                                       Header->GetBitsAllocated(),
1092                                       &(Header->RLEInfo),
1093                                       fp );
1094       Header->CloseFile();
1095       return res; 
1096    }  
1097     
1098    // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000 
1099    int numberBitsAllocated = Header->GetBitsAllocated();
1100    if ( ( numberBitsAllocated == 0 ) || ( numberBitsAllocated == 12 ) )
1101    {
1102       numberBitsAllocated = 16;
1103    }
1104
1105    int nBytes= numberBitsAllocated/8;
1106    int taille = Header->GetXSize() * Header->GetYSize()  
1107                 * Header->GetSamplesPerPixel();
1108    long fragmentBegining; // for ftell, fseek
1109
1110    bool jpg2000     = Header->IsJPEG2000();
1111    bool jpgLossless = Header->IsJPEGLossless();
1112
1113    bool res = true;
1114    uint16_t ItemTagGr, ItemTagEl;
1115    int ln;  
1116    
1117    //  Position on begining of Jpeg Pixels
1118    
1119    fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
1120    fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
1121    if(Header->GetSwapCode())
1122    {
1123       ItemTagGr = Header->SwapShort(ItemTagGr);
1124       ItemTagEl = Header->SwapShort(ItemTagEl);
1125    }
1126
1127    fread(&ln,4,1,fp);
1128    if( Header->GetSwapCode() )
1129    {
1130       ln = Header->SwapLong( ln );    // Basic Offset Table Item length
1131    }
1132
1133    if ( ln != 0 )
1134    {
1135       // What is it used for ?!?
1136       uint8_t* BasicOffsetTableItemValue = new uint8_t[ln+1];
1137       fread(BasicOffsetTableItemValue,ln,1,fp);
1138       //delete[] BasicOffsetTableItemValue;
1139    }
1140
1141    // first Fragment initialisation
1142    fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
1143    fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
1144    if( Header->GetSwapCode() )
1145    {
1146       ItemTagGr = Header->SwapShort( ItemTagGr );
1147       ItemTagEl = Header->SwapShort( ItemTagEl );
1148    }
1149
1150    // parsing fragments until Sequence Delim. Tag found
1151    while ( ItemTagGr == 0xfffe && ItemTagEl != 0xe0dd )
1152    {
1153       // --- for each Fragment
1154       fread(&ln,4,1,fp);
1155       if( Header->GetSwapCode() )
1156       {
1157          ln = Header->SwapLong(ln);    // Fragment Item length
1158       }
1159       fragmentBegining = ftell( fp );
1160
1161       if ( jpg2000 )
1162       {
1163       // JPEG 2000 :    call to ???
1164       res = gdcm_read_JPEG2000_file (fp,destination);  // Not Yet written 
1165       // ------------------------------------- endif (JPEG2000)
1166       }
1167       else if (jpgLossless)
1168       {
1169          // JPEG LossLess : call to xmedcom Lossless JPEG
1170          // Reading Fragment pixels
1171          JPEGLosslessDecodeImage (fp, (uint16_t*)destination,
1172                Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(), ln);
1173          res = 1; // in order not to break the loop
1174   
1175       } // ------------------------------------- endif (JPEGLossless)
1176       else
1177       {
1178          // JPEG Lossy : call to IJG 6b
1179          if ( Header->GetBitsStored() == 8)
1180          {
1181             // Reading Fragment pixels
1182             res = gdcm_read_JPEG_file (fp,destination);
1183          }
1184          else
1185          {
1186             // Reading Fragment pixels
1187             res = gdcm_read_JPEG_file12 (fp,destination);
1188          }
1189          // ------------------------------------- endif (JPEGLossy)
1190       }
1191
1192       if ( !res )
1193       {
1194          break;
1195       }
1196                
1197       // location in user's memory 
1198       // for next fragment (if any) 
1199       destination = (uint8_t*)destination + taille * nBytes;
1200
1201       fseek(fp,fragmentBegining, SEEK_SET); // To be sure we start 
1202       fseek(fp,ln,SEEK_CUR);                // at the begining of next fragment
1203       
1204       ItemTagGr = ItemTagEl = 0;
1205       fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
1206       fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
1207       if( Header->GetSwapCode() )
1208       {
1209          ItemTagGr = Header->SwapShort( ItemTagGr );
1210          ItemTagEl = Header->SwapShort( ItemTagEl );
1211       }
1212    }
1213    // endWhile parsing fragments until Sequence Delim. Tag found    
1214
1215    Header->CloseFile();
1216    return res;
1217 }
1218
1219 /**
1220  * \brief Read from file a 12 bits per pixel image and uncompress it
1221  *        into a 16 bits per pixel image.
1222  */
1223 void gdcmFile::ConvertDecompress12BitsTo16Bits(
1224                   uint8_t* pixelZone,
1225                   int sizeX,
1226                   int sizeY,
1227                   FILE* filePtr)
1228                throw ( gdcmFormatError )
1229 {
1230    int nbPixels = sizeX * sizeY;
1231    uint16_t* destination = (uint16_t*)pixelZone;    
1232
1233    for( int p = 0; p < nbPixels; p += 2 )
1234    {
1235       uint8_t b0, b1, b2;
1236       size_t ItemRead;
1237
1238       ItemRead = fread( &b0, 1, 1, filePtr);
1239       if ( ItemRead != 1 )
1240       {
1241          throw gdcmFormatError( "gdcmFile::ConvertDecompress12BitsTo16Bits()",
1242                                 "Unfound first block" );
1243       }
1244
1245       ItemRead = fread( &b1, 1, 1, filePtr);
1246       if ( ItemRead != 1 )
1247       {
1248          throw gdcmFormatError( "gdcmFile::ConvertDecompress12BitsTo16Bits()",
1249                                 "Unfound second block" );
1250       }
1251
1252       ItemRead = fread( &b2, 1, 1, filePtr);      
1253       if ( ItemRead != 1 )
1254       {
1255          throw gdcmFormatError( "gdcmFile::ConvertDecompress12BitsTo16Bits()",
1256                                 "Unfound second block" );
1257       }
1258
1259       // Two steps are necessary to please VC++
1260       //
1261       // 2 pixels 12bit =     [0xABCDEF]
1262       // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
1263       //                     A                     B                 D
1264       *destination++ =  ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
1265       //                     F                     C                 E
1266       *destination++ =  ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
1267   
1268       /// \todo JPR Troubles expected on Big-Endian processors ?
1269    }
1270 }
1271 //-----------------------------------------------------------------------------