]> Creatis software - gdcm.git/blob - src/gdcmDataEntry.cxx
BUG: 1-n VM are also allowed to be empty
[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:52:13 $
7   Version:   $Revision: 1.9 $
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   uint32_t vc = GetValueCount();
228   if( strVM == "1-n" )
229     {
230     // make sure it is at least one ??? FIXME
231     valid = vc >= 1 || vc == 0;
232     }
233   else
234     {
235     std::istringstream os;
236     os.str( strVM );
237     os >> vm;
238     // Two cases:
239     // vm respect the one from the dict
240     // vm is 0 (we need to check is this element is allowed to be empty) FIXME
241     valid = vc == vm || vc == 0;
242     }
243   return valid;
244 }
245
246 uint32_t DataEntry::GetValueCount(void) const
247 {
248    const VRKey &vr = GetVR();
249    if( vr == "US" || vr == "SS" )
250       return GetLength()/sizeof(uint16_t);
251    else if( vr == "UL" || vr == "SL" )
252       return GetLength()/sizeof(uint32_t);
253    else if( vr == "FL" )
254       return GetLength()/sizeof(float);
255    else if( vr == "FD" )
256       return GetLength()/sizeof(double);
257    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
258    {
259       // Some element in DICOM are allowed to be empty
260       if( !GetLength() ) return 0;
261       // Don't use std::string to accelerate processing
262       uint32_t count = 1;
263       for(uint32_t i=0;i<GetLength();i++)
264       {
265          if( BinArea[i] == '\\')
266             count++;
267       }
268       return count;
269    }
270
271    return GetLength();
272 }
273
274 void DataEntry::SetString(std::string const &value)
275 {
276    DeleteBinArea();
277
278    const VRKey &vr = GetVR();
279    if ( vr == "US" || vr == "SS" )
280    {
281       std::vector<std::string> tokens;
282       Util::Tokenize (value, tokens, "\\");
283       SetLength(tokens.size()*sizeof(uint16_t));
284       NewBinArea();
285
286       uint16_t *data = (uint16_t *)BinArea;
287       for (unsigned int i=0; i<tokens.size();i++)
288          data[i] = atoi(tokens[i].c_str());
289       tokens.clear();
290    }
291    else if ( vr == "UL" || vr == "SL" )
292    {
293       std::vector<std::string> tokens;
294       Util::Tokenize (value, tokens, "\\");
295       SetLength(tokens.size()*sizeof(uint32_t));
296       NewBinArea();
297
298       uint32_t *data = (uint32_t *)BinArea;
299       for (unsigned int i=0; i<tokens.size();i++)
300          data[i] = atoi(tokens[i].c_str());
301       tokens.clear();
302    }
303    else if ( vr == "FL" )
304    {
305       std::vector<std::string> tokens;
306       Util::Tokenize (value, tokens, "\\");
307       SetLength(tokens.size()*sizeof(float));
308       NewBinArea();
309
310       float *data = (float *)BinArea;
311       for (unsigned int i=0; i<tokens.size();i++)
312          data[i] = (float)atof(tokens[i].c_str());
313       tokens.clear();
314    }
315    else if ( vr == "FD" )
316    {
317       std::vector<std::string> tokens;
318       Util::Tokenize (value, tokens, "\\");
319       SetLength(tokens.size()*sizeof(double));
320       NewBinArea();
321
322       double *data = (double *)BinArea;
323       for (unsigned int i=0; i<tokens.size();i++)
324          data[i] = atof(tokens[i].c_str());
325       tokens.clear();
326    }
327    else
328    {
329       if( value.size() > 0 )
330       {
331          std::string finalVal = Util::DicomString( value.c_str() );
332          SetLength(finalVal.size());
333          NewBinArea();
334
335          memcpy(BinArea, &(finalVal[0]), finalVal.size());
336       }
337    }
338    State = STATE_LOADED;
339 }
340
341 std::string const &DataEntry::GetString() const
342 {
343    static std::ostringstream s;
344    const VRKey &vr = GetVR();
345
346    s.str("");
347    StrArea="";
348
349    if( !BinArea )
350       return StrArea;
351
352    if( vr == "US" || vr == "SS" )
353    {
354       uint16_t *data=(uint16_t *)BinArea;
355
356       for (unsigned int i=0; i < GetValueCount(); i++)
357       {
358          if( i!=0 )
359             s << '\\';
360          s << data[i];
361       }
362       StrArea=s.str();
363    }
364    // See above comment on multiple integers (mutatis mutandis).
365    else if( vr == "UL" || vr == "SL" )
366    {
367       uint32_t *data=(uint32_t *)BinArea;
368
369       for (unsigned int i=0; i < GetValueCount(); i++)
370       {
371          if( i!=0 )
372             s << '\\';
373          s << data[i];
374       }
375       StrArea=s.str();
376    }
377    else if( vr == "FL" )
378    {
379       float *data=(float *)BinArea;
380
381       for (unsigned int i=0; i < GetValueCount(); i++)
382       {
383          if( i!=0 )
384             s << '\\';
385          s << data[i];
386       }
387       StrArea=s.str();
388    }
389    else if( vr == "FD" )
390    {
391       double *data=(double *)BinArea;
392
393       for (unsigned int i=0; i < GetValueCount(); i++)
394       {
395          if( i!=0 )
396             s << '\\';
397          s << data[i];
398       }
399       StrArea=s.str();
400    }
401    else
402       StrArea.append((const char *)BinArea,GetLength());
403
404    return StrArea;
405 }
406
407 void DataEntry::Copy(DocEntry *doc)
408 {
409    DocEntry::Copy(doc);
410
411    DataEntry *entry = dynamic_cast<DataEntry *>(doc);
412    if ( entry )
413    {
414       State = entry->State;
415       Flag = entry->Flag;
416       CopyBinArea(entry->BinArea,entry->GetLength());
417    }
418 }
419
420 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype)
421
422    DocEntry::WriteContent(fp, filetype);
423
424    if ( GetGroup() == 0xfffe )
425    {
426       return; //delimitors have NO value
427    }
428
429    uint8_t *binArea8 = BinArea; //safe notation
430    size_t lgr = GetLength();
431    if (BinArea) // the binArea was *actually* loaded
432    {
433
434    //  The same operation should be done if we wanted 
435    //  to write image with Big Endian Transfer Syntax, 
436    //  while working on Little Endian Processor
437    // --> forget Big Endian Transfer Syntax writting!
438    //     Next DICOM version will give it up ...
439
440    // --> FIXME 
441    //    The stuff looks nice, but it's probably bugged,
442    //    since troubles occur on big endian processors (SunSparc, Motorola)
443    //    while reading the pixels of a 
444    //    gdcm-written Little-Endian 16 bits per pixel image
445
446 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
447
448       /// \todo FIXME : Right now, we only care of Pixels element
449       ///       we should deal with *all* the BinEntries
450       ///       Well, not really since we are not interpreting values read...
451
452       // 8 Bits Pixels *are* OB, 16 Bits Pixels *are* OW
453       // -value forced while Reading process-
454       
455       // -->  WARNING
456       // -->        the following lines *looked* very clever, 
457       // -->        but they don't work on big endian processors.
458       // -->        since I've no access for the moment to a big endian proc :-(
459       // -->        I comment them out, to see the result on the dash board 
460       // -->     
461       
462       // --> Revert to initial code : TestWriteSimple hangs on Darwin :-(     
463       if (GetGroup() == 0x7fe0 && GetVR() == "OW")
464       {  
465          uint16_t *binArea16 = (uint16_t*)binArea8;
466          binary_write (*fp, binArea16, lgr );
467       }
468       else
469       { 
470          // For any other VR, DataEntry is re-written as-is
471          binary_write (*fp, binArea8, lgr );
472       }
473
474       // -->  WARNING      
475       // -->         remove the following line, an uncomment the previous ones, 
476       // -->         if it doesn't work better
477       // -->     
478       /*binary_write ( *fp, binArea8, lgr ); // Elem value*/
479       
480 #else
481       binary_write ( *fp, binArea8, lgr ); // Elem value
482 #endif //GDCM_WORDS_BIGENDIAN
483    }
484    else
485    {
486       // nothing was loaded, but we need to skip space on disc
487       
488       //  --> WARNING : nothing is written; 
489       //  --> the initial data (on the the source image) is lost
490       //  --> user is *not* informed !
491       
492       fp->seekp(lgr, std::ios::cur);
493    }
494 }
495
496 //-----------------------------------------------------------------------------
497 // Protected
498 void DataEntry::NewBinArea(void)
499 {
500    DeleteBinArea();
501    if( GetLength() > 0 )
502       BinArea = new uint8_t[GetLength()];
503    SelfArea = true;
504 }
505
506 void DataEntry::DeleteBinArea(void)
507 {
508    if (BinArea && SelfArea)
509    {
510       delete[] BinArea;
511       BinArea = NULL;
512    }
513 }
514
515 //-----------------------------------------------------------------------------
516 // Private
517
518 //-----------------------------------------------------------------------------
519 // Print
520 /**
521  * \brief   Prints a DataEntry (Dicom entry)
522  * @param   os ostream we want to print in
523  * @param indent Indentation string to be prepended during printing
524  */
525 void DataEntry::Print(std::ostream &os, std::string const & )
526 {
527    os << "D ";
528    DocEntry::Print(os);
529
530    uint16_t g = GetGroup();
531    if (g == 0xfffe) // delimiters have NO value
532    {          
533       return; // just to avoid identing all the remaining code 
534    }
535
536    std::ostringstream s;
537    TSAtr v;
538
539    if( BinArea )
540    {
541       v = GetString();
542       const VRKey &vr = GetVR();
543
544       if( vr == "US" || vr == "SS" )
545          s << " [" << GetString() << "]";
546       else if( vr == "UL" || vr == "SL" )
547          s << " [" << GetString() << "]";
548       else if ( vr == "FL" )
549          s << " [" << GetString() << "]";
550       else if ( vr == "FD" )
551          s << " [" << GetString() << "]";
552       else
553       { 
554          if(Global::GetVR()->IsVROfStringRepresentable(vr))
555          {
556             std::string cleanString = Util::CreateCleanString(v);  // replace non printable characters by '.'
557             if ( cleanString.length() <= GetMaxSizePrintEntry()
558             || PrintLevel >= 3
559             || IsNotLoaded() )
560             {
561                s << " [" << cleanString << "]";
562             }
563             else
564             {
565                s << " [gdcm::too long for print (" << cleanString.length() << ") ]";
566             }
567          }
568          else
569          {
570             if ( Util::IsCleanArea( GetBinArea(),GetLength()  ) )
571             {
572                std::string cleanString = 
573                      Util::CreateCleanString( BinArea,GetLength()  );
574                s << " [" << cleanString << "]";
575             }
576             else
577             {
578                s << " [" << GDCM_BINLOADED << ";"
579                << "length = " << GetLength() << "]";
580             }
581          }
582       }
583    }
584    else
585    {
586       if( IsNotLoaded() )
587          s << " [" << GDCM_NOTLOADED << "]";
588       else if( IsUnfound() )
589          s << " [" << GDCM_UNFOUND << "]";
590       else if( IsUnread() )
591          s << " [" << GDCM_UNREAD << "]";
592       else if ( GetLength() == 0 )
593          s << " []";
594    }
595
596    if( IsPixelData() )
597       s << " (" << GDCM_PIXELDATA << ")";
598
599    // Display the UID value (instead of displaying only the rough code)
600    // First 'clean' trailing character (space or zero) 
601    if(BinArea)
602    {
603       const uint16_t &gr = GetGroup();
604       const uint16_t &elt = GetElement();
605       TS *ts = Global::GetTS();
606
607       if (gr == 0x0002)
608       {
609          // Any more to be displayed ?
610          if ( elt == 0x0010 || elt == 0x0002 )
611          {
612             if ( v.length() != 0 )  // for brain damaged headers
613             {
614                if ( ! isdigit((unsigned char)v[v.length()-1]) )
615                {
616                   v.erase(v.length()-1, 1);
617                }
618             }
619             s << "  ==>\t[" << ts->GetValue(v) << "]";
620          }
621       }
622       else if (gr == 0x0008)
623       {
624          if ( elt == 0x0016 || elt == 0x1150 )
625          {
626             if ( v.length() != 0 )  // for brain damaged headers
627             {
628                if ( ! isdigit((unsigned char)v[v.length()-1]) )
629                {
630                   v.erase(v.length()-1, 1);
631                }
632             }
633             s << "  ==>\t[" << ts->GetValue(v) << "]";
634          }
635       }
636       else if (gr == 0x0004)
637       {
638          if ( elt == 0x1510 || elt == 0x1512  )
639          {
640             if ( v.length() != 0 )  // for brain damaged headers  
641             {
642                if ( ! isdigit((unsigned char)v[v.length()-1]) )
643                {
644                   v.erase(v.length()-1, 1);  
645                }
646             }
647             s << "  ==>\t[" << ts->GetValue(v) << "]";
648          }
649       }
650    }
651
652    os << s.str();
653 }
654
655 //-----------------------------------------------------------------------------
656 } // end namespace gdcm
657