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