]> Creatis software - gdcm.git/blob - src/gdcmDataEntry.cxx
BUG: 1-n VM was not handle properly
[gdcm.git] / src / gdcmDataEntry.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDataEntry.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/10/21 15:16:52 $
7   Version:   $Revision: 1.7 $
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 "gdcmDataEntry.h"
20 #include "gdcmVR.h"
21 #include "gdcmTS.h"
22 #include "gdcmGlobal.h"
23 #include "gdcmUtil.h"
24 #include "gdcmDebug.h"
25
26 #include <fstream>
27
28 namespace gdcm 
29 {
30 //-----------------------------------------------------------------------------
31 #define MAX_SIZE_PRINT_ELEMENT_VALUE 0x7fffffff
32 uint32_t DataEntry::MaxSizePrintEntry = MAX_SIZE_PRINT_ELEMENT_VALUE;
33
34 //-----------------------------------------------------------------------------
35 // Constructor / Destructor
36 /**
37  * \brief   Constructor for a given DictEntry
38  * @param   e Pointer to existing dictionary entry
39  */
40 DataEntry::DataEntry(DictEntry *e) 
41             : DocEntry(e)
42 {
43    State = STATE_LOADED;
44    Flag = FLAG_NONE;
45
46    BinArea = 0;
47    SelfArea = true;
48 }
49
50 /**
51  * \brief   Constructor for a given DocEntry
52  * @param   e Pointer to existing Doc entry
53  */
54 DataEntry::DataEntry(DocEntry *e)
55             : DocEntry(e->GetDictEntry())
56 {
57    Flag = 0;
58    BinArea = 0;
59    SelfArea = true;
60
61    Copy(e);
62 }
63
64 /**
65  * \brief   Canonical destructor.
66  */
67 DataEntry::~DataEntry ()
68 {
69    DeleteBinArea();
70 }
71
72 //-----------------------------------------------------------------------------
73 // Print
74
75 //-----------------------------------------------------------------------------
76 // Public
77 /**
78  * \brief Sets the value (non string) of the current Dicom Header Entry
79  */
80 void DataEntry::SetBinArea( uint8_t *area, bool self )  
81
82    DeleteBinArea();
83
84    BinArea = area;
85    SelfArea = self;
86
87    State = STATE_LOADED;
88 }
89
90 void DataEntry::CopyBinArea( uint8_t *area, uint32_t length )
91 {
92    DeleteBinArea();
93
94    uint32_t lgh = length + length%2;
95    SetLength(lgh);
96
97    if( area && length > 0 )
98    {
99       NewBinArea();
100       memcpy(BinArea,area,length);
101       if( length!=lgh )
102          BinArea[length]=0;
103
104       State = STATE_LOADED;
105    }
106 }
107
108 void DataEntry::SetValue(const uint32_t &id,const double &val)
109 {
110    if( !BinArea )
111       NewBinArea();
112    State = STATE_LOADED;
113
114    if( id > GetValueCount() )
115    {
116       gdcmErrorMacro("Index (" << id << ")is greater than the data size");
117       return;
118    }
119
120    const VRKey &vr = GetVR();
121    if( vr == "US" || vr == "SS" )
122    {
123       uint16_t *data = (uint16_t *)BinArea;
124       data[id] = (uint16_t)val;
125    }
126    else if( vr == "UL" || vr == "SL" )
127    {
128       uint32_t *data = (uint32_t *)BinArea;
129       data[id] = (uint32_t)val;
130    }
131    else if( vr == "FL" )
132    {
133       float *data = (float *)BinArea;
134       data[id] = (float)val;
135    }
136    else if( vr == "FD" )
137    {
138       double *data = (double *)BinArea;
139       data[id] = (double)val;
140    }
141    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
142    {
143       gdcmErrorMacro("SetValue on String representable not implemented yet");
144    }
145    else
146    {
147       BinArea[id] = (uint8_t)val;
148    }
149 }
150
151 double DataEntry::GetValue(const uint32_t &id) const
152 {
153    if( !BinArea )
154    {
155       gdcmErrorMacro("BinArea not set. Can't get the value");
156       return 0;
157    }
158
159    uint32_t count = GetValueCount();
160    if( id > count )
161    {
162       gdcmErrorMacro("Index (" << id << ")is greater than the data size");
163       return 0;
164    }
165
166    const VRKey &vr = GetVR();
167    if( vr == "US" || vr == "SS" )
168       return ((uint16_t *)BinArea)[id];
169    else if( vr == "UL" || vr == "SL" )
170       return ((uint32_t *)BinArea)[id];
171    else if( vr == "FL" )
172       return ((float *)BinArea)[id];
173    else if( vr == "FD" )
174       return ((double *)BinArea)[id];
175    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
176    {
177       if( GetLength() )
178       {
179          // Don't use std::string to accelerate processing
180          double val = 0.0;
181          char *tmp = new char[GetLength()+1];
182          memcpy(tmp,BinArea,GetLength());
183          tmp[GetLength()]=0;
184
185          if( count == 0 )
186          {
187             val = atof(tmp);
188          }
189          else
190          {
191             count = id;
192             char *beg = tmp;
193             for(uint32_t i=0;i<GetLength();i++)
194             {
195                if( tmp[i] == '\\' )
196                {
197                   if( count == 0 )
198                   {
199                      tmp[i] = 0;
200                      break;
201                   }
202                   else
203                   {
204                      count--;
205                      beg = &(tmp[i+1]);
206                   }
207                }
208             }
209             val = atof(beg);
210          }
211
212          delete[] tmp;
213          return val;
214       }
215       else 
216          return 0.0;
217    }
218    else
219       return BinArea[id];
220 }
221
222 bool DataEntry::IsValueCountValid() const
223 {
224   bool valid = false;
225   uint32_t vm;
226   const std::string &strVM = GetVM();
227   if( strVM == "1-n" )
228     {
229     // make sure it is at least one ??? FIXME
230     valid = GetValueCount() >= 1;
231     }
232   else
233     {
234     std::istringstream os;
235     os.str( strVM );
236     os >> vm;
237     valid = vm == GetValueCount();
238     }
239   return valid;
240 }
241
242 uint32_t DataEntry::GetValueCount(void) const
243 {
244    const VRKey &vr = GetVR();
245    if( vr == "US" || vr == "SS" )
246       return GetLength()/sizeof(uint16_t);
247    else if( vr == "UL" || vr == "SL" )
248       return GetLength()/sizeof(uint32_t);
249    else if( vr == "FL" )
250       return GetLength()/sizeof(float);
251    else if( vr == "FD" )
252       return GetLength()/sizeof(double);
253    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
254    {
255       // Don't use std::string to accelerate processing
256       uint32_t count = 1;
257       for(uint32_t i=0;i<GetLength();i++)
258       {
259          if( BinArea[i] == '\\')
260             count++;
261       }
262       return count;
263    }
264
265    return GetLength();
266 }
267
268 void DataEntry::SetString(std::string const &value)
269 {
270    DeleteBinArea();
271
272    const VRKey &vr = GetVR();
273    if ( vr == "US" || vr == "SS" )
274    {
275       std::vector<std::string> tokens;
276       Util::Tokenize (value, tokens, "\\");
277       SetLength(tokens.size()*sizeof(uint16_t));
278       NewBinArea();
279
280       uint16_t *data = (uint16_t *)BinArea;
281       for (unsigned int i=0; i<tokens.size();i++)
282          data[i] = atoi(tokens[i].c_str());
283       tokens.clear();
284    }
285    else if ( vr == "UL" || vr == "SL" )
286    {
287       std::vector<std::string> tokens;
288       Util::Tokenize (value, tokens, "\\");
289       SetLength(tokens.size()*sizeof(uint32_t));
290       NewBinArea();
291
292       uint32_t *data = (uint32_t *)BinArea;
293       for (unsigned int i=0; i<tokens.size();i++)
294          data[i] = atoi(tokens[i].c_str());
295       tokens.clear();
296    }
297    else if ( vr == "FL" )
298    {
299       std::vector<std::string> tokens;
300       Util::Tokenize (value, tokens, "\\");
301       SetLength(tokens.size()*sizeof(float));
302       NewBinArea();
303
304       float *data = (float *)BinArea;
305       for (unsigned int i=0; i<tokens.size();i++)
306          data[i] = (float)atof(tokens[i].c_str());
307       tokens.clear();
308    }
309    else if ( vr == "FD" )
310    {
311       std::vector<std::string> tokens;
312       Util::Tokenize (value, tokens, "\\");
313       SetLength(tokens.size()*sizeof(double));
314       NewBinArea();
315
316       double *data = (double *)BinArea;
317       for (unsigned int i=0; i<tokens.size();i++)
318          data[i] = atof(tokens[i].c_str());
319       tokens.clear();
320    }
321    else
322    {
323       if( value.size() > 0 )
324       {
325          std::string finalVal = Util::DicomString( value.c_str() );
326          SetLength(finalVal.size());
327          NewBinArea();
328
329          memcpy(BinArea, &(finalVal[0]), finalVal.size());
330       }
331    }
332    State = STATE_LOADED;
333 }
334
335 std::string const &DataEntry::GetString() const
336 {
337    static std::ostringstream s;
338    const VRKey &vr = GetVR();
339
340    s.str("");
341    StrArea="";
342
343    if( !BinArea )
344       return StrArea;
345
346    if( vr == "US" || vr == "SS" )
347    {
348       uint16_t *data=(uint16_t *)BinArea;
349
350       for (unsigned int i=0; i < GetValueCount(); i++)
351       {
352          if( i!=0 )
353             s << '\\';
354          s << data[i];
355       }
356       StrArea=s.str();
357    }
358    // See above comment on multiple integers (mutatis mutandis).
359    else if( vr == "UL" || vr == "SL" )
360    {
361       uint32_t *data=(uint32_t *)BinArea;
362
363       for (unsigned int i=0; i < GetValueCount(); i++)
364       {
365          if( i!=0 )
366             s << '\\';
367          s << data[i];
368       }
369       StrArea=s.str();
370    }
371    else if( vr == "FL" )
372    {
373       float *data=(float *)BinArea;
374
375       for (unsigned int i=0; i < GetValueCount(); i++)
376       {
377          if( i!=0 )
378             s << '\\';
379          s << data[i];
380       }
381       StrArea=s.str();
382    }
383    else if( vr == "FD" )
384    {
385       double *data=(double *)BinArea;
386
387       for (unsigned int i=0; i < GetValueCount(); i++)
388       {
389          if( i!=0 )
390             s << '\\';
391          s << data[i];
392       }
393       StrArea=s.str();
394    }
395    else
396       StrArea.append((const char *)BinArea,GetLength());
397
398    return StrArea;
399 }
400
401 void DataEntry::Copy(DocEntry *doc)
402 {
403    DocEntry::Copy(doc);
404
405    DataEntry *entry = dynamic_cast<DataEntry *>(doc);
406    if ( entry )
407    {
408       State = entry->State;
409       Flag = entry->Flag;
410       CopyBinArea(entry->BinArea,entry->GetLength());
411    }
412 }
413
414 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype)
415
416    DocEntry::WriteContent(fp, filetype);
417
418    if ( GetGroup() == 0xfffe )
419    {
420       return; //delimitors have NO value
421    }
422
423    uint8_t *binArea8 = BinArea; //safe notation
424    size_t lgr = GetLength();
425    if (BinArea) // the binArea was *actually* loaded
426    {
427
428    //  The same operation should be done if we wanted 
429    //  to write image with Big Endian Transfer Syntax, 
430    //  while working on Little Endian Processor
431    // --> forget Big Endian Transfer Syntax writting!
432    //     Next DICOM version will give it up ...
433
434    // --> FIXME 
435    //    The stuff looks nice, but it's probably bugged,
436    //    since troubles occur on big endian processors (SunSparc, Motorola)
437    //    while reading the pixels of a 
438    //    gdcm-written Little-Endian 16 bits per pixel image
439
440 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
441
442       /// \todo FIXME : Right now, we only care of Pixels element
443       ///       we should deal with *all* the BinEntries
444       ///       Well, not really since we are not interpreting values read...
445
446       // 8 Bits Pixels *are* OB, 16 Bits Pixels *are* OW
447       // -value forced while Reading process-
448       
449       // -->  WARNING
450       // -->        the following lines *looked* very clever, 
451       // -->        but they don't work on big endian processors.
452       // -->        since I've no access for the moment to a big endian proc :-(
453       // -->        I comment them out, to see the result on the dash board 
454       // -->     
455       
456       // --> Revert to initial code : TestWriteSimple hangs on Darwin :-(     
457       if (GetGroup() == 0x7fe0 && GetVR() == "OW")
458       {  
459          uint16_t *binArea16 = (uint16_t*)binArea8;
460          binary_write (*fp, binArea16, lgr );
461       }
462       else
463       { 
464          // For any other VR, DataEntry is re-written as-is
465          binary_write (*fp, binArea8, lgr );
466       }
467
468       // -->  WARNING      
469       // -->         remove the following line, an uncomment the previous ones, 
470       // -->         if it doesn't work better
471       // -->     
472       /*binary_write ( *fp, binArea8, lgr ); // Elem value*/
473       
474 #else
475       binary_write ( *fp, binArea8, lgr ); // Elem value
476 #endif //GDCM_WORDS_BIGENDIAN
477    }
478    else
479    {
480       // nothing was loaded, but we need to skip space on disc
481       
482       //  --> WARNING : nothing is written; 
483       //  --> the initial data (on the the source image) is lost
484       //  --> user is *not* informed !
485       
486       fp->seekp(lgr, std::ios::cur);
487    }
488 }
489
490 //-----------------------------------------------------------------------------
491 // Protected
492 void DataEntry::NewBinArea(void)
493 {
494    DeleteBinArea();
495    if( GetLength() > 0 )
496       BinArea = new uint8_t[GetLength()];
497    SelfArea = true;
498 }
499
500 void DataEntry::DeleteBinArea(void)
501 {
502    if (BinArea && SelfArea)
503    {
504       delete[] BinArea;
505       BinArea = NULL;
506    }
507 }
508
509 //-----------------------------------------------------------------------------
510 // Private
511
512 //-----------------------------------------------------------------------------
513 // Print
514 /**
515  * \brief   Prints a DataEntry (Dicom entry)
516  * @param   os ostream we want to print in
517  * @param indent Indentation string to be prepended during printing
518  */
519 void DataEntry::Print(std::ostream &os, std::string const & )
520 {
521    os << "D ";
522    DocEntry::Print(os);
523
524    uint16_t g = GetGroup();
525    if (g == 0xfffe) // delimiters have NO value
526    {          
527       return; // just to avoid identing all the remaining code 
528    }
529
530    std::ostringstream s;
531    TSAtr v;
532
533    if( BinArea )
534    {
535       v = GetString();
536       const VRKey &vr = GetVR();
537
538       if( vr == "US" || vr == "SS" )
539          s << " [" << GetString() << "]";
540       else if( vr == "UL" || vr == "SL" )
541          s << " [" << GetString() << "]";
542       else if ( vr == "FL" )
543          s << " [" << GetString() << "]";
544       else if ( vr == "FD" )
545          s << " [" << GetString() << "]";
546       else
547       { 
548          if(Global::GetVR()->IsVROfStringRepresentable(vr))
549          {
550             std::string cleanString = Util::CreateCleanString(v);  // replace non printable characters by '.'
551             if ( cleanString.length() <= GetMaxSizePrintEntry()
552             || PrintLevel >= 3
553             || IsNotLoaded() )
554             {
555                s << " [" << cleanString << "]";
556             }
557             else
558             {
559                s << " [gdcm::too long for print (" << cleanString.length() << ") ]";
560             }
561          }
562          else
563          {
564             if ( Util::IsCleanArea( GetBinArea(),GetLength()  ) )
565             {
566                std::string cleanString = 
567                      Util::CreateCleanString( BinArea,GetLength()  );
568                s << " [" << cleanString << "]";
569             }
570             else
571             {
572                s << " [" << GDCM_BINLOADED << ";"
573                << "length = " << GetLength() << "]";
574             }
575          }
576       }
577    }
578    else
579    {
580       if( IsNotLoaded() )
581          s << " [" << GDCM_NOTLOADED << "]";
582       else if( IsUnfound() )
583          s << " [" << GDCM_UNFOUND << "]";
584       else if( IsUnread() )
585          s << " [" << GDCM_UNREAD << "]";
586       else if ( GetLength() == 0 )
587          s << " []";
588    }
589
590    if( IsPixelData() )
591       s << " (" << GDCM_PIXELDATA << ")";
592
593    // Display the UID value (instead of displaying only the rough code)
594    // First 'clean' trailing character (space or zero) 
595    if(BinArea)
596    {
597       const uint16_t &gr = GetGroup();
598       const uint16_t &elt = GetElement();
599       TS *ts = Global::GetTS();
600
601       if (gr == 0x0002)
602       {
603          // Any more to be displayed ?
604          if ( elt == 0x0010 || elt == 0x0002 )
605          {
606             if ( v.length() != 0 )  // for brain damaged headers
607             {
608                if ( ! isdigit((unsigned char)v[v.length()-1]) )
609                {
610                   v.erase(v.length()-1, 1);
611                }
612             }
613             s << "  ==>\t[" << ts->GetValue(v) << "]";
614          }
615       }
616       else if (gr == 0x0008)
617       {
618          if ( elt == 0x0016 || elt == 0x1150 )
619          {
620             if ( v.length() != 0 )  // for brain damaged headers
621             {
622                if ( ! isdigit((unsigned char)v[v.length()-1]) )
623                {
624                   v.erase(v.length()-1, 1);
625                }
626             }
627             s << "  ==>\t[" << ts->GetValue(v) << "]";
628          }
629       }
630       else if (gr == 0x0004)
631       {
632          if ( elt == 0x1510 || elt == 0x1512  )
633          {
634             if ( v.length() != 0 )  // for brain damaged headers  
635             {
636                if ( ! isdigit((unsigned char)v[v.length()-1]) )
637                {
638                   v.erase(v.length()-1, 1);  
639                }
640             }
641             s << "  ==>\t[" << ts->GetValue(v) << "]";
642          }
643       }
644    }
645
646    os << s.str();
647 }
648
649 //-----------------------------------------------------------------------------
650 } // end namespace gdcm
651