]> Creatis software - gdcm.git/blob - src/gdcmDataEntry.cxx
Minor typo fixes
[gdcm.git] / src / gdcmDataEntry.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDataEntry.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/12/09 12:23:38 $
7   Version:   $Revision: 1.25 $
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 = FLAG_NONE;
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  * @param area area
80  * @param self self
81  */
82 void DataEntry::SetBinArea( uint8_t *area, bool self )  
83
84    DeleteBinArea();
85
86    BinArea = area;
87    SelfArea = self;
88
89    State = STATE_LOADED;
90 }
91 /**
92  * \brief Inserts the value (non string) into the current Dicom Header Entry
93  * @param area area
94  * @param length length 
95  */
96 void DataEntry::CopyBinArea( uint8_t *area, uint32_t length )
97 {
98    DeleteBinArea();
99
100    uint32_t lgh = length + length%2;
101    SetLength(lgh);
102
103    if( area && length > 0 )
104    {
105       NewBinArea();
106       memcpy(BinArea,area,length);
107       if( length!=lgh )
108          BinArea[length]=0;
109
110       State = STATE_LOADED;
111    }
112 }
113
114 /**
115  * \brief Inserts the value (non string) into the current Dicom Header Entry
116  * @param id id
117  * @param val val 
118  */
119 void DataEntry::SetValue(const uint32_t &id, const double &val)
120 {
121    if( !BinArea )
122       NewBinArea();
123    State = STATE_LOADED;
124
125    if( id > GetValueCount() )
126    {
127       gdcmErrorMacro("Index (" << id << ")is greater than the data size");
128       return;
129    }
130
131    const VRKey &vr = GetVR();
132    if( vr == "US" || vr == "SS" )
133    {
134       uint16_t *data = (uint16_t *)BinArea;
135       data[id] = (uint16_t)val;
136    }
137    else if( vr == "UL" || vr == "SL" )
138    {
139       uint32_t *data = (uint32_t *)BinArea;
140       data[id] = (uint32_t)val;
141    }
142    else if( vr == "FL" )
143    {
144       float *data = (float *)BinArea;
145       data[id] = (float)val;
146    }
147    else if( vr == "FD" )
148    {
149       double *data = (double *)BinArea;
150       data[id] = (double)val;
151    }
152    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
153    {
154       gdcmErrorMacro("SetValue on String representable not implemented yet");
155    }
156    else
157    {
158       BinArea[id] = (uint8_t)val;
159    }
160 }
161 /**
162  * \brief returns, as a double (?!?) one of the values 
163  *      (when entry is multivaluated), identified by its index.
164  *      Returns 0.0 if index is wrong
165  *     FIXME : warn the user there was a problem ! 
166  * @param id id
167  */
168 double DataEntry::GetValue(const uint32_t &id) const
169 {
170    if( !BinArea )
171    {
172       gdcmErrorMacro("BinArea not set. Can't get the value");
173       return 0.0;
174    }
175
176    uint32_t count = GetValueCount();
177    if( id > count )
178    {
179       gdcmErrorMacro("Index (" << id << ")is greater than the data size");
180       return 0.0;
181    }
182
183    // FIX the API : user *knows* that entry contains a US
184    //               and he receives a double ?!?
185    
186    const VRKey &vr = GetVR();
187    if( vr == "US" || vr == "SS" )
188       return ((uint16_t *)BinArea)[id];
189    else if( vr == "UL" || vr == "SL" )
190       return ((uint32_t *)BinArea)[id];
191    else if( vr == "FL" )
192       return ((float *)BinArea)[id];
193    else if( vr == "FD" )
194       return ((double *)BinArea)[id];
195    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
196    {
197       if( GetLength() )
198       {
199          // Don't use std::string to accelerate processing
200          double val;
201          char *tmp = new char[GetLength()+1];
202          memcpy(tmp,BinArea,GetLength());
203          tmp[GetLength()]=0;
204
205          if( count == 0 )
206          {
207             val = atof(tmp);
208          }
209          else
210          {
211             count = id;
212             char *beg = tmp;
213             for(uint32_t i=0;i<GetLength();i++)
214             {
215                if( tmp[i] == '\\' )
216                {
217                   if( count == 0 )
218                   {
219                      tmp[i] = 0;
220                      break;
221                   }
222                   else
223                   {
224                      count--;
225                      beg = &(tmp[i+1]);
226                   }
227                }
228             }
229             val = atof(beg);
230          }
231
232          delete[] tmp;
233          return val;
234       }
235       else 
236          return 0.0;
237    }
238    else
239       return BinArea[id];
240 }
241
242 /**
243  * \brief Checks if the multiplicity of the value follows Dictionary VM
244  */
245 bool DataEntry::IsValueCountValid() const
246 {
247   uint32_t vm;
248   const std::string &strVM = GetVM();
249   uint32_t vc = GetValueCount();
250   bool valid = vc == 0;
251   if( valid )
252     return true;
253   
254   // FIXME : what shall we do with VM = "2-n", "3-n", etc
255   
256   if( strVM == "1-n" )
257   {
258     // make sure there is at least one ??? FIXME
259     valid = vc >= 1;
260   }
261   else
262   {
263     std::istringstream os;
264     os.str( strVM );
265     os >> vm;
266     // Two cases:
267     // vm respects the one from the dict
268     // vm is 0 (we need to check if this element is allowed to be empty) FIXME
269
270     // note  (JPR)
271     // ----    
272     // Entries whose type is 1 are mandatory, with a mandatory value.
273     // Entries whose type is 1c are mandatory-inside-a-Sequence,
274     //                          with a mandatory value.
275     // Entries whose type is 2 are mandatory, with an optional value.
276     // Entries whose type is 2c are mandatory-inside-a-Sequence,
277     //                          with an optional value.
278     // Entries whose type is 3 are optional.
279
280     // case vc == 0 is only applicable for 'type 2' entries.
281     // Problem : entry type may depend on the modality and/or the Sequence
282     //           it's embedded in !
283     //          (Get the information in the 'Conformance Statements' ...)  
284     valid = vc == vm;
285   }
286   return valid;
287 }
288
289 /**
290  * \brief returns the number of elementary values
291  */ 
292 uint32_t DataEntry::GetValueCount( ) const
293 {
294    const VRKey &vr = GetVR();
295    if( vr == "US" || vr == "SS" )
296       return GetLength()/sizeof(uint16_t);
297    else if( vr == "UL" || vr == "SL" )
298       return GetLength()/sizeof(uint32_t);
299    else if( vr == "FL" || vr == "OF" )
300       return GetLength()/4 ; // FL has a *4* length! sizeof(float);
301    else if( vr == "FD" )
302       return GetLength()/8;  // FD has a *8* length! sizeof(double);
303    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
304    {
305       // Some element in DICOM are allowed to be empty
306       if( !GetLength() ) 
307          return 0;
308       // Don't use std::string to accelerate processing
309       uint32_t count = 1;
310       for(uint32_t i=0;i<GetLength();i++)
311       {
312          if( BinArea[i] == '\\')
313             count++;
314       }
315       return count;
316    }
317    return GetLength();
318 }
319 /**
320  * \brief Sets the 'value' of an Entry, passed as a std::string
321  * @param value string representation of the value to be set
322  */ 
323 void DataEntry::SetString(std::string const &value)
324 {
325    DeleteBinArea();
326
327    const VRKey &vr = GetVR();
328    if ( vr == "US" || vr == "SS" )
329    {
330       std::vector<std::string> tokens;
331       Util::Tokenize (value, tokens, "\\");
332       SetLength(tokens.size()*sizeof(uint16_t));
333       NewBinArea();
334
335       uint16_t *data = (uint16_t *)BinArea;
336       for (unsigned int i=0; i<tokens.size();i++)
337          data[i] = atoi(tokens[i].c_str());
338       tokens.clear();
339    }
340    else if ( vr == "UL" || vr == "SL" )
341    {
342       std::vector<std::string> tokens;
343       Util::Tokenize (value, tokens, "\\");
344       SetLength(tokens.size()*sizeof(uint32_t));
345       NewBinArea();
346
347       uint32_t *data = (uint32_t *)BinArea;
348       for (unsigned int i=0; i<tokens.size();i++)
349          data[i] = atoi(tokens[i].c_str());
350       tokens.clear();
351    }
352    else if ( vr == "FL" )
353    {
354       std::vector<std::string> tokens;
355       Util::Tokenize (value, tokens, "\\");
356       SetLength(tokens.size()*sizeof(float));
357       NewBinArea();
358
359       float *data = (float *)BinArea;
360       for (unsigned int i=0; i<tokens.size();i++)
361          data[i] = (float)atof(tokens[i].c_str());
362       tokens.clear();
363    }
364    else if ( vr == "FD" )
365    {
366       std::vector<std::string> tokens;
367       Util::Tokenize (value, tokens, "\\");
368       SetLength(tokens.size()*sizeof(double));
369       NewBinArea();
370
371       double *data = (double *)BinArea;
372       for (unsigned int i=0; i<tokens.size();i++)
373          data[i] = atof(tokens[i].c_str());
374       tokens.clear();
375    }
376    else
377    {
378       if( value.size() > 0 )
379       {
380          size_t l =  value.size();    
381          SetLength(l + l%2);
382          NewBinArea();
383          memcpy(BinArea, value.c_str(), l);
384          if (l%2)
385             BinArea[l] = '\0';
386       }
387    }
388    State = STATE_LOADED;
389 }
390 /**
391  * \brief   returns as a string (when possible) the value of the DataEntry
392  */
393 std::string const &DataEntry::GetString() const
394 {
395    static std::ostringstream s;
396    const VRKey &vr = GetVR();
397
398    s.str("");
399    StrArea="";
400
401    if( !BinArea )
402       return StrArea;
403       
404    // When short integer(s) are stored, convert the following (n * 2) characters 
405    // as a displayable string, the values being separated by a back-slash
406
407    if( vr == "US" || vr == "SS" )
408    {
409       uint16_t *data=(uint16_t *)BinArea;
410
411       for (unsigned int i=0; i < GetValueCount(); i++)
412       {
413          if( i!=0 )
414             s << '\\';
415          s << data[i];
416       }
417       StrArea=s.str();
418    }
419    // See above comment on multiple short integers (mutatis mutandis).
420    else if( vr == "UL" || vr == "SL" )
421    {
422       uint32_t *data=(uint32_t *)BinArea;
423
424       for (unsigned int i=0; i < GetValueCount(); i++)
425       {
426          if( i!=0 )
427             s << '\\';
428          s << data[i];
429       }
430       StrArea=s.str();
431    }
432    else if( vr == "FL" )
433    {
434       float *data=(float *)BinArea;
435
436       for (unsigned int i=0; i < GetValueCount(); i++)
437       {
438          if( i!=0 )
439             s << '\\';
440          s << data[i];
441       }
442       StrArea=s.str();
443    }
444    else if( vr == "FD" )
445    {
446       double *data=(double *)BinArea;
447
448       for (unsigned int i=0; i < GetValueCount(); i++)
449       {
450          if( i!=0 )
451             s << '\\';
452          s << data[i];
453       }
454       StrArea=s.str();
455    }
456    else
457    {
458       StrArea.append((const char *)BinArea,GetLength());
459       // to avoid gdcm propagate oddities in lengthes
460       if ( GetLength()%2)
461          StrArea.append(" ",1);  
462    }
463    return StrArea;
464 }
465
466 /**
467  * \brief Copies all the attributes from an other DocEntry 
468  * @param doc entry to copy from
469  * @remarks The content BinArea is copied too
470  */
471 void DataEntry::Copy(DocEntry *doc)
472 {
473    DocEntry::Copy(doc);
474
475    DataEntry *entry = dynamic_cast<DataEntry *>(doc);
476    if ( entry )
477    {
478       State = entry->State;
479       Flag = entry->Flag;
480       CopyBinArea(entry->BinArea,entry->GetLength());
481    }
482 }
483
484 /**
485  * \brief   Writes the 'value' area of a DataEntry
486  * @param fp already open ofstream pointer
487  * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
488  */
489 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype)
490
491    DocEntry::WriteContent(fp, filetype);
492
493    if ( GetGroup() == 0xfffe )
494    {
495       return; //delimitors have NO value
496    }
497    
498    // --> We only deal with Little Endian writting
499    // --> forget Big Endian Transfer Syntax writting!
500    //     Next DICOM version will give it up ...
501  
502    // WARNING - For Implicit VR private element,
503    //           we have *no choice* but considering them as
504    //           something like 'OB' values.
505    //           we rewrite them as we found them on disc.
506    //           Some trouble will occur if element was 
507    //           *actually* OW, if image was produced 
508    //           on Big endian based processor, read and writen 
509    //           on Little endian based processor
510    //           and, later on, somebody needs
511    //           this 'OW' Implicit VR private element (?!?)
512    //           (Same stuff, mutatis mutandis, for Little/Big)
513  
514    // 8/16 bits Pixels problem should be solved automatiquely,
515    // since we ensure the VR (OB vs OW) is conform to Pixel size.
516         
517    uint8_t *data = BinArea; //safe notation
518    size_t l = GetLength(); 
519    gdcmDebugMacro ("in DataEntry::WriteContent " << GetKey() 
520              << " : " << Global::GetVR()->GetAtomicElementLength(this->GetVR())
521              );
522    if (BinArea) // the binArea was *actually* loaded
523    {
524 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
525       unsigned short vrLgth = 
526                         Global::GetVR()->GetAtomicElementLength(this->GetVR());
527       unsigned int i;
528       switch(vrLgth)
529       {
530          case 1:
531          {
532             binary_write (*fp, data, l );           
533             break;
534          }     
535          case 2:
536          {
537 gdcmDebugMacro ("AtomicLength = 2 found; lgt =" << l); 
538             uint16_t *data16 = (uint16_t *)data;
539             for(i=0;i<l/vrLgth;i++)
540                binary_write( *fp, data16[i]);
541             break;
542          }
543          case 4:
544          {
545             uint32_t *data32 = (uint32_t *)data;
546             for(i=0;i<l/vrLgth;i++)
547                binary_write( *fp, data32[i]);
548             break;
549          }
550          case 8:
551          {
552             double *data64 = (double *)data;
553             for(i=0;i<l/vrLgth;i++)
554                binary_write( *fp, data64[i]);
555             break;
556          }
557       }
558 #else
559    binary_write (*fp, data, l );
560 #endif //GDCM_WORDS_BIGENDIAN
561
562    }
563    else
564    {
565       // nothing was loaded, but we need to skip space on disc
566       
567       //  --> WARNING : nothing is written; 
568       //  --> the initial data (on the the source image) is lost
569       //  --> user is *not* informed !
570       
571       fp->seekp(l, std::ios::cur);
572    }
573    // to avoid gdcm to propagate oddities
574    // (length was already modified)  
575    if (l%2)
576       fp->seekp(1, std::ios::cur);  
577 }
578
579 /**
580  * \brief   Compute the full length of the elementary DataEntry (not only value
581  *          length) depending on the VR.
582  */
583 uint32_t DataEntry::ComputeFullLength()
584 {
585    return GetFullLength();
586 }
587
588 //-----------------------------------------------------------------------------
589 // Protected
590 /// \brief Creates a DataEntry owned BinArea (remove previous one if any)
591 void DataEntry::NewBinArea( )
592 {
593    DeleteBinArea();
594    if( GetLength() > 0 )
595       BinArea = new uint8_t[GetLength()];
596    SelfArea = true;
597 }
598 /// \brief Removes the BinArea, if owned by the DataEntry
599 void DataEntry::DeleteBinArea(void)
600 {
601    if (BinArea && SelfArea)
602    {
603       delete[] BinArea;
604       BinArea = NULL;
605    }
606 }
607
608 //-----------------------------------------------------------------------------
609 // Private
610
611 //-----------------------------------------------------------------------------
612 // Print
613 /**
614  * \brief   Prints a DataEntry (Dicom entry)
615  * @param   os ostream we want to print in
616  * @param indent Indentation string to be prepended during printing
617  */
618 void DataEntry::Print(std::ostream &os, std::string const & )
619 {
620    os << "D ";
621    DocEntry::Print(os);
622
623    uint16_t g = GetGroup();
624    if (g == 0xfffe) // delimiters have NO value
625    {          
626       return; // just to avoid identing all the remaining code 
627    }
628
629    std::ostringstream s;
630    TSAtr v;
631
632    if( BinArea )
633    {
634       v = GetString();
635       const VRKey &vr = GetVR();
636
637       if( vr == "US" || vr == "SS" )
638          s << " [" << GetString() << "]";
639       else if( vr == "UL" || vr == "SL" )
640          s << " [" << GetString() << "]";
641       else if ( vr == "FL" )
642          s << " [" << GetString() << "]";
643       else if ( vr == "FD" )
644          s << " [" << GetString() << "]";
645       else
646       { 
647          if(Global::GetVR()->IsVROfStringRepresentable(vr))
648          {
649             // replace non printable characters by '.'
650             std::string cleanString = Util::CreateCleanString(v);
651             if ( cleanString.length() <= GetMaxSizePrintEntry()
652               || PrintLevel >= 3
653               || IsNotLoaded() )
654            // FIXME : when IsNotLoaded(), you create a Clean String ?!?
655            // FIXME : PrintLevel<2 *does* print the values 
656            //        (3 is only for extra offsets printing)
657            // What do you wanted to do ? JPR
658             {
659                s << " [" << cleanString << "]";
660             }
661             else
662             {
663                s << " [gdcm::too long for print (" << cleanString.length() << ") ]";
664             }
665          }
666          else
667          {
668             // A lot of Private elements (with no VR) contain actually 
669             // only printable characters;
670             // Let's deal with them as is they were VR std::string representable
671     
672             if ( Util::IsCleanArea( GetBinArea(), GetLength()  ) )
673             {
674                // FIXME : since the 'Area' *is* clean, just use
675                //         a 'CreateString' method, to save CPU time.
676                std::string cleanString = 
677                      Util::CreateCleanString( BinArea,GetLength()  );
678                s << " [" << cleanString << "]";
679             }
680             else
681             {
682                s << " [" << GDCM_BINLOADED << ";"
683                << "length = " << GetLength() << "]";
684             }
685          }
686       }
687    }
688    else
689    {
690       if( IsNotLoaded() )
691          s << " [" << GDCM_NOTLOADED << "]";
692       else if( IsUnfound() )
693          s << " [" << GDCM_UNFOUND << "]";
694       else if( IsUnread() )
695          s << " [" << GDCM_UNREAD << "]";
696       else if ( GetLength() == 0 )
697          s << " []";
698    }
699
700    if( IsPixelData() )
701       s << " (" << GDCM_PIXELDATA << ")";
702
703    // Display the UID value (instead of displaying only the rough code)
704    // First 'clean' trailing character (space or zero) 
705    if(BinArea)
706    {
707       const uint16_t &gr = GetGroup();
708       const uint16_t &elt = GetElement();
709       TS *ts = Global::GetTS();
710
711       if (gr == 0x0002)
712       {
713          // Any more to be displayed ?
714          if ( elt == 0x0010 || elt == 0x0002 )
715          {
716             if ( v.length() != 0 )  // for brain damaged headers
717             {
718                if ( ! isdigit((unsigned char)v[v.length()-1]) )
719                {
720                   v.erase(v.length()-1, 1);
721                }
722             }
723             s << "  ==>\t[" << ts->GetValue(v) << "]";
724          }
725       }
726       else if (gr == 0x0008)
727       {
728          if ( elt == 0x0016 || elt == 0x1150 )
729          {
730             if ( v.length() != 0 )  // for brain damaged headers
731             {
732                if ( ! isdigit((unsigned char)v[v.length()-1]) )
733                {
734                   v.erase(v.length()-1, 1);
735                }
736             }
737             s << "  ==>\t[" << ts->GetValue(v) << "]";
738          }
739       }
740       else if (gr == 0x0004)
741       {
742          if ( elt == 0x1510 || elt == 0x1512  )
743          {
744             if ( v.length() != 0 )  // for brain damaged headers  
745             {
746                if ( ! isdigit((unsigned char)v[v.length()-1]) )
747                {
748                   v.erase(v.length()-1, 1);  
749                }
750             }
751             s << "  ==>\t[" << ts->GetValue(v) << "]";
752          }
753       }
754    }
755
756    os << s.str();
757 }
758
759 //-----------------------------------------------------------------------------
760 } // end namespace gdcm
761