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