]> Creatis software - gdcm.git/blob - src/gdcmDataEntry.cxx
Add verbosity when something wrong occurs
[gdcm.git] / src / gdcmDataEntry.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDataEntry.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/12/23 10:26:41 $
7   Version:   $Revision: 1.27 $
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() << " AtomicLength: "
520               << Global::GetVR()->GetAtomicElementLength(this->GetVR() ) // << " BinArea in :" << &BinArea
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             uint16_t *data16 = (uint16_t *)data;
538             for(i=0;i<l/vrLgth;i++)
539                binary_write( *fp, data16[i]);
540             break;
541          }
542          case 4:
543          {
544             uint32_t *data32 = (uint32_t *)data;
545             for(i=0;i<l/vrLgth;i++)
546                binary_write( *fp, data32[i]);
547             break;
548          }
549          case 8:
550          {
551             double *data64 = (double *)data;
552             for(i=0;i<l/vrLgth;i++)
553                binary_write( *fp, data64[i]);
554             break;
555          }
556       }
557 #else
558    binary_write (*fp, data, l );
559 #endif //GDCM_WORDS_BIGENDIAN
560
561    }
562    else
563    {
564       // nothing was loaded, but we need to skip space on disc     
565       if (l != 0)
566       {
567       //  --> WARNING : nothing is written; 
568       //  --> the initial data (on the the source image) is lost
569       //  --> user is *not* informed !      
570          gdcmDebugMacro ("Nothing was loaded, but we need to skip space on disc. "
571                       << "Length =" << l << " for " << GetKey() );   
572          fp->seekp(l, std::ios::cur);
573       }
574    }
575    // to avoid gdcm to propagate oddities
576    // (length was already modified)  
577    if (l%2)
578       fp->seekp(1, std::ios::cur);  
579 }
580
581 /**
582  * \brief   Compute the full length of the elementary DataEntry (not only value
583  *          length) depending on the VR.
584  */
585 uint32_t DataEntry::ComputeFullLength()
586 {
587    return GetFullLength();
588 }
589
590 //-----------------------------------------------------------------------------
591 // Protected
592 /// \brief Creates a DataEntry owned BinArea (remove previous one if any)
593 void DataEntry::NewBinArea( )
594 {
595    DeleteBinArea();
596    if( GetLength() > 0 )
597       BinArea = new uint8_t[GetLength()];
598    SelfArea = true;
599 }
600 /// \brief Removes the BinArea, if owned by the DataEntry
601 void DataEntry::DeleteBinArea(void)
602 {
603    if (BinArea && SelfArea)
604    {
605       delete[] BinArea;
606       BinArea = NULL;
607    }
608 }
609
610 //-----------------------------------------------------------------------------
611 // Private
612
613 //-----------------------------------------------------------------------------
614 // Print
615 /**
616  * \brief   Prints a DataEntry (Dicom entry)
617  * @param   os ostream we want to print in
618  * @param indent Indentation string to be prepended during printing
619  */
620 void DataEntry::Print(std::ostream &os, std::string const & )
621 {
622    os << "D ";
623    DocEntry::Print(os);
624
625    uint16_t g = GetGroup();
626    if (g == 0xfffe) // delimiters have NO value
627    {          
628       return; // just to avoid identing all the remaining code 
629    }
630
631    std::ostringstream s;
632    TSAtr v;
633
634    if( BinArea )
635    {
636       v = GetString();
637       const VRKey &vr = GetVR();
638
639       if( vr == "US" || vr == "SS" )
640          s << " [" << GetString() << "]";
641       else if( vr == "UL" || vr == "SL" )
642          s << " [" << GetString() << "]";
643       else if ( vr == "FL" )
644          s << " [" << GetString() << "]";
645       else if ( vr == "FD" )
646          s << " [" << GetString() << "]";
647       else
648       { 
649          if(Global::GetVR()->IsVROfStringRepresentable(vr))
650          {
651             // replace non printable characters by '.'
652             std::string cleanString = Util::CreateCleanString(v);
653             if ( cleanString.length() <= GetMaxSizePrintEntry()
654               || PrintLevel >= 3
655               || IsNotLoaded() )
656            // FIXME : when IsNotLoaded(), you create a Clean String ?!?
657            // FIXME : PrintLevel<2 *does* print the values 
658            //        (3 is only for extra offsets printing)
659            // What do you wanted to do ? JPR
660             {
661                s << " [" << cleanString << "]";
662             }
663             else
664             {
665                s << " [gdcm::too long for print (" << cleanString.length() << ") ]";
666             }
667          }
668          else
669          {
670             // A lot of Private elements (with no VR) contain actually 
671             // only printable characters;
672             // Let's deal with them as is they were VR std::string representable
673     
674             if ( Util::IsCleanArea( GetBinArea(), GetLength()  ) )
675             {
676                // FIXME : since the 'Area' *is* clean, just use
677                //         a 'CreateString' method, to save CPU time.
678                std::string cleanString = 
679                      Util::CreateCleanString( BinArea,GetLength()  );
680                s << " [" << cleanString << "]";
681             }
682             else
683             {
684                s << " [" << GDCM_BINLOADED << ";"
685                << "length = " << GetLength() << "]";
686             }
687          }
688       }
689    }
690    else
691    {
692       if( IsNotLoaded() )
693          s << " [" << GDCM_NOTLOADED << "]";
694       else if( IsUnfound() )
695          s << " [" << GDCM_UNFOUND << "]";
696       else if( IsUnread() )
697          s << " [" << GDCM_UNREAD << "]";
698       else if ( GetLength() == 0 )
699          s << " []";
700    }
701
702    if( IsPixelData() )
703       s << " (" << GDCM_PIXELDATA << ")";
704
705    // Display the UID value (instead of displaying only the rough code)
706    // First 'clean' trailing character (space or zero) 
707    if(BinArea)
708    {
709       const uint16_t &gr = GetGroup();
710       const uint16_t &elt = GetElement();
711       TS *ts = Global::GetTS();
712
713       if (gr == 0x0002)
714       {
715          // Any more to be displayed ?
716          if ( elt == 0x0010 || elt == 0x0002 )
717          {
718             if ( v.length() != 0 )  // for brain damaged headers
719             {
720                if ( ! isdigit((unsigned char)v[v.length()-1]) )
721                {
722                   v.erase(v.length()-1, 1);
723                }
724             }
725             s << "  ==>\t[" << ts->GetValue(v) << "]";
726          }
727       }
728       else if (gr == 0x0008)
729       {
730          if ( elt == 0x0016 || elt == 0x1150 )
731          {
732             if ( v.length() != 0 )  // for brain damaged headers
733             {
734                if ( ! isdigit((unsigned char)v[v.length()-1]) )
735                {
736                   v.erase(v.length()-1, 1);
737                }
738             }
739             s << "  ==>\t[" << ts->GetValue(v) << "]";
740          }
741       }
742       else if (gr == 0x0004)
743       {
744          if ( elt == 0x1510 || elt == 0x1512  )
745          {
746             if ( v.length() != 0 )  // for brain damaged headers  
747             {
748                if ( ! isdigit((unsigned char)v[v.length()-1]) )
749                {
750                   v.erase(v.length()-1, 1);  
751                }
752             }
753             s << "  ==>\t[" << ts->GetValue(v) << "]";
754          }
755       }
756    }
757
758    os << s.str();
759 }
760
761 //-----------------------------------------------------------------------------
762 } // end namespace gdcm
763