1 /*=========================================================================
4 Module: $RCSfile: gdcmDataEntry.cxx,v $
6 Date: $Date: 2007/09/14 08:22:19 $
7 Version: $Revision: 1.48 $
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.
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.
17 =========================================================================*/
19 #include "gdcmDataEntry.h"
22 #include "gdcmGlobal.h"
24 #include "gdcmDebug.h"
28 #if defined(__BORLANDC__)
29 #include <mem.h> // for memcpy
30 #include <stdlib.h> // for atof
31 #include <ctype.h> // for isdigit
34 namespace GDCM_NAME_SPACE
36 //-----------------------------------------------------------------------------
37 #define MAX_SIZE_PRINT_ELEMENT_VALUE 0x7fffffff
38 uint32_t DataEntry::MaxSizePrintEntry = MAX_SIZE_PRINT_ELEMENT_VALUE;
40 //-----------------------------------------------------------------------------
41 // Constructor / Destructor
43 * \brief Constructor for a given DataEntry
44 * @param group group number of the Data Entry to be created
45 * @param elem element number of the Data Entry to be created
46 * @param vr Value Representation of the Data Entry to be created
48 DataEntry::DataEntry(uint16_t group,uint16_t elem,
50 : DocEntry(group,elem,vr)
61 * \brief Constructor for a given DocEntry
62 * @param e Pointer to existing Doc entry
64 DataEntry::DataEntry(DocEntry *e)
65 //: DocEntry(e->GetDictEntry())
66 : DocEntry(e->GetGroup(),e->GetElement(), e->GetVR() )
77 * \brief Canonical destructor.
79 DataEntry::~DataEntry ()
85 //-----------------------------------------------------------------------------
88 * \brief Sets the value (non string) of the current DataEntry
90 * @param self self=true : The area : *belongs" to the DataEntry
91 * : will be delete with the DataEntry
92 * self=false The area *is not* deleted with the DataEntry
95 void DataEntry::SetBinArea( uint8_t *area, bool self )
102 State = STATE_LOADED;
105 * \brief Inserts the value (non string) into the current DataEntry
107 * @param length length
109 void DataEntry::CopyBinArea( uint8_t *area, uint32_t length )
113 uint32_t lgh = length + length%2;
116 if( area && length > 0 )
119 memcpy(BinArea,area,length);
121 BinArea[length]=0; // padd with zero
123 State = STATE_LOADED;
128 * \brief Inserts the elementary (non string) value into the current DataEntry
129 * @param id index of the elementary value to be set
130 * @param val value, passed as a double
132 void DataEntry::SetValue(const uint32_t &id, const double &val)
136 State = STATE_LOADED;
138 if( id > GetValueCount() )
140 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
144 const VRKey &vr = GetVR();
145 if( vr == "US" || vr == "SS" )
147 uint16_t *data = (uint16_t *)BinArea;
148 data[id] = (uint16_t)val;
150 else if( vr == "UL" || vr == "SL" )
152 uint32_t *data = (uint32_t *)BinArea;
153 data[id] = (uint32_t)val;
155 else if( vr == "FL" )
157 float *data = (float *)BinArea;
158 data[id] = (float)val;
160 else if( vr == "FD" )
162 double *data = (double *)BinArea;
163 data[id] = (double)val;
165 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
167 gdcmErrorMacro("SetValue on String representable not implemented yet");
171 BinArea[id] = (uint8_t)val;
175 * \brief returns, as a double one of the values
176 * (when entry is multivaluated), identified by its index.
177 * Returns 0.0 if index is wrong
180 double DataEntry::GetValue(const uint32_t &id) const
184 if (GetLength() != 0) // avoid stupid messages
185 /// \todo warn the user there was a problem !
186 gdcmErrorMacro("BinArea not set " << std::hex
187 << GetGroup() << " " << GetElement()
188 << " Can't get the value");
192 uint32_t count = GetValueCount();
195 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
199 // if user *knows* that entry contains a US,
200 // he just has to cast the double he receives
202 const VRKey &vr = GetVR();
204 if( vr == "US" || vr == "SS" )
205 return ((uint16_t *)BinArea)[id];
206 else if( vr == "UL" || vr == "SL" )
207 return ((uint32_t *)BinArea)[id];
208 else if( vr == "FL" )
209 return ((float *)BinArea)[id];
210 else if( vr == "FD" )
211 return ((double *)BinArea)[id];
212 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
214 // this is for VR = "DS", ...
217 // Don't use std::string to accelerate processing
219 char *tmp = new char[GetLength()+1];
220 memcpy(tmp,BinArea,GetLength());
231 for(uint32_t i=0;i<GetLength();i++)
261 * \brief Checks if the multiplicity of the value follows Dictionary VM
263 bool DataEntry::IsValueCountValid() /*const*/
266 const std::string &strVM = GetVM();
267 uint32_t vc = GetValueCount();
268 bool valid = vc == 0;
272 // FIXME : what shall we do with VM = "2-n", "3-n", etc
276 // make sure there is at least one ??? FIXME
281 std::istringstream os;
285 // vm respects the one from the dict
286 // vm is 0 (we need to check if this element is allowed to be empty) FIXME
290 // Entries whose type is 1 are mandatory, with a mandatory value.
291 // Entries whose type is 1c are mandatory-inside-a-Sequence,
292 // with a mandatory value.
293 // Entries whose type is 2 are mandatory, with an optional value.
294 // Entries whose type is 2c are mandatory-inside-a-Sequence,
295 // with an optional value.
296 // Entries whose type is 3 are optional.
298 // case vc == 0 is only applicable for 'type 2' entries.
299 // Problem : entry type may depend on the modality and/or the Sequence
300 // it's embedded in !
301 // (Get the information in the 'Conformance Statements' ...)
308 * \brief returns the number of elementary values
310 uint32_t DataEntry::GetValueCount( ) const
312 const VRKey &vr = GetVR();
313 if( vr == "US" || vr == "SS" )
314 return GetLength()/sizeof(uint16_t);
315 else if( vr == "UL" || vr == "SL" )
316 return GetLength()/sizeof(uint32_t);
317 else if( vr == "FL" || vr == "OF" )
318 return GetLength()/4 ; // FL has a *4* length! sizeof(float);
319 else if( vr == "FD" )
320 return GetLength()/8; // FD has a *8* length! sizeof(double);
321 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
323 // Some element in DICOM are allowed to be empty
326 // Don't use std::string to accelerate processing
328 for(uint32_t i=0;i<GetLength();i++)
330 if( BinArea[i] == '\\')
339 * \brief Gets a std::vector of 'double' holding the value(s) of a DS DataEntry
340 * @param valueVector std::vector double of value(s)
341 * \return false if VR not "DS" or DataEntry empty
343 bool DataEntry::GetDSValue(std::vector <double> &valueVector)
345 /// \todo rewrite the whole method, in order *not to use* std::string !
346 std::vector<std::string> tokens;
348 if (GetVR() != "DS") // never trust a user !
351 Util::Tokenize ( GetString().c_str(), tokens, "\\" );
353 int nbValues= tokens.size();
357 for (int loop=0; loop<nbValues; loop++)
358 valueVector.push_back(atof(tokens[loop].c_str()));
364 * \brief Sets the 'value' of a DataEntry, passed as a std::string
365 * @param value string representation of the value to be set
367 void DataEntry::SetString(std::string const &value)
370 const VRKey &vr = GetVR();
371 if ( vr == "US" || vr == "SS" )
373 std::vector<std::string> tokens;
374 Util::Tokenize (value, tokens, "\\");
375 SetLength(tokens.size()*sizeof(uint16_t));
378 uint16_t *data = (uint16_t *)BinArea;
379 for (unsigned int i=0; i<tokens.size();i++)
380 data[i] = atoi(tokens[i].c_str());
383 else if ( vr == "UL" || vr == "SL" )
385 std::vector<std::string> tokens;
386 Util::Tokenize (value, tokens, "\\");
387 SetLength(tokens.size()*sizeof(uint32_t));
390 uint32_t *data = (uint32_t *)BinArea;
391 for (unsigned int i=0; i<tokens.size();i++)
392 data[i] = atoi(tokens[i].c_str());
395 else if ( vr == "FL" )
397 std::vector<std::string> tokens;
398 Util::Tokenize (value, tokens, "\\");
399 SetLength(tokens.size()*sizeof(float));
402 float *data = (float *)BinArea;
403 for (unsigned int i=0; i<tokens.size();i++)
404 data[i] = (float)atof(tokens[i].c_str());
407 else if ( vr == "FD" )
409 std::vector<std::string> tokens;
410 Util::Tokenize (value, tokens, "\\");
411 SetLength(tokens.size()*sizeof(double));
414 double *data = (double *)BinArea;
415 for (unsigned int i=0; i<tokens.size();i++)
416 data[i] = atof(tokens[i].c_str());
421 size_t l = value.size();
424 memcpy(BinArea, value.c_str(), l);
425 if (l%2) // padded with blank except for UI
431 State = STATE_LOADED;
434 * \brief returns as a string (when possible) the value of the DataEntry
436 std::string const &DataEntry::GetString() const
438 static std::ostringstream s;
439 const VRKey &vr = GetVR();
443 StrArea = new std::string();
449 // When short integer(s) are stored, convert the following (n * 2) characters
450 // as a displayable string, the values being separated by a back-slash
453 uint16_t *data=(uint16_t *)BinArea;
454 for (unsigned int i=0; i < GetValueCount(); i++)
462 else if (vr == "SS" )
464 int16_t *data=(int16_t *)BinArea;
465 for (unsigned int i=0; i < GetValueCount(); i++)
472 } // See above comment on multiple short integers (mutatis mutandis).
473 else if( vr == "UL" )
475 uint32_t *data=(uint32_t *)BinArea;
476 for (unsigned int i=0; i < GetValueCount(); i++)
484 else if( vr == "SL" )
486 int32_t *data=(int32_t *)BinArea;
487 for (unsigned int i=0; i < GetValueCount(); i++)
494 } else if( vr == "FL" )
496 float *data=(float *)BinArea;
497 for (unsigned int i=0; i < GetValueCount(); i++)
505 else if( vr == "FD" )
507 double *data=(double *)BinArea;
508 for (unsigned int i=0; i < GetValueCount(); i++)
518 StrArea->append((const char *)BinArea,GetLength());
519 // to avoid gdcm to propagate oddities in lengthes
521 StrArea->append(" ",1); }
527 * \brief Copies all the attributes from an other DocEntry
528 * @param doc entry to copy from
529 * @remarks The content BinArea is copied too (StrArea is not)
531 void DataEntry::Copy(DocEntry *doc)
535 DataEntry *entry = dynamic_cast<DataEntry *>(doc);
538 State = entry->State;
540 CopyBinArea(entry->BinArea,entry->GetLength());
545 * \brief Writes the 'common part' + the 'value' area of a DataEntry
546 * @param fp already open ofstream pointer
547 * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
549 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype,
550 bool insideMetaElements, bool insideSequence)
552 // writes the 'common part'
553 DocEntry::WriteContent(fp, filetype, insideMetaElements, insideSequence);
555 if ( GetGroup() == 0xfffe )
557 return; //delimitors have NO value
560 // --> We only deal with Little Endian writting.
561 // --> forget Big Endian Transfer Syntax writting!
562 // Next DICOM version will give it up ...
564 // WARNING - For Implicit VR private element,
565 // we have *no choice* but considering them as
566 // something like 'OB' values.
567 // we rewrite them as we found them on disc.
568 // Some trouble will occur if element was
569 // *actually* OW, if image was produced
570 // on Big endian based processor, read and writen
571 // on Little endian based processor
572 // and, later on, somebody needs
573 // this 'OW' Implicit VR private element (?!?)
574 // (Same stuff, mutatis mutandis, for Little/Big)
576 // 8/16 bits Pixels problem should be solved automatiquely,
577 // since we ensure the VR (OB vs OW) is conform to Pixel size.
579 uint8_t *data = BinArea; //safe notation
580 size_t l = GetLength();
581 // gdcmDebugMacro("in DataEntry::WriteContent " << GetKey() << " AtomicLength: "
582 // << Global::GetVR()->GetAtomicElementLength(this->GetVR() ) // << " BinArea in :" << &BinArea
584 if (BinArea) // the binArea was *actually* loaded
586 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
587 unsigned short vrLgth =
588 Global::GetVR()->GetAtomicElementLength(this->GetVR());
594 binary_write (*fp, data, l );
599 uint16_t *data16 = (uint16_t *)data;
600 for(i=0;i<l/vrLgth;i++)
601 binary_write( *fp, data16[i]);
606 uint32_t *data32 = (uint32_t *)data;
607 for(i=0;i<l/vrLgth;i++)
608 binary_write( *fp, data32[i]);
613 double *data64 = (double *)data;
614 for(i=0;i<l/vrLgth;i++)
615 binary_write( *fp, data64[i]);
620 binary_write (*fp, data, l );
621 #endif //GDCM_WORDS_BIGENDIAN
626 // nothing was loaded, but we need to skip space on disc
629 // --> WARNING : nothing is written;
630 // --> the initial data (on the the source image) is lost
631 // --> user is *not* informed !
632 gdcmDebugMacro ("Nothing was loaded, but we need to skip space on disc. "
633 << "Length =" << l << " for " << GetKey() );
634 fp->seekp(l, std::ios::cur); // At Write time, for unloaded elems
637 // to avoid gdcm to propagate oddities
638 // (length was already modified)
640 fp->seekp(1, std::ios::cur); // At Write time, for non even length elems
644 * \brief Compute the full length of the elementary DataEntry (not only value
645 * length) depending on the VR.
647 uint32_t DataEntry::ComputeFullLength()
649 return GetFullLength();
652 //-----------------------------------------------------------------------------
655 /// \brief Creates a DataEntry owned BinArea
656 /// (remove previous one if any and relevant StrArea if any)
657 void DataEntry::NewBinArea( )
660 if( GetLength() > 0 )
661 BinArea = new uint8_t[GetLength()];
664 /// \brief Removes the BinArea, if owned by the DataEntry,
665 /// and the relevant StrArea if any
666 void DataEntry::DeleteBinArea(void)
668 if (BinArea && SelfArea)
680 //-----------------------------------------------------------------------------
683 //-----------------------------------------------------------------------------
686 * \brief Prints a DataEntry (Dicom entry)
687 * @param os ostream we want to print in
688 * @param indent Indentation string to be prepended during printing
690 void DataEntry::Print(std::ostream &os, std::string const & )
694 // First, Print the common part (vr [length offset] name).
697 uint16_t g = GetGroup();
698 if (g == 0xfffe) // delimiters have NO value
700 return; // just to avoid identing all the remaining code
703 std::ostringstream s;
709 const VRKey &vr = GetVR();
711 if( vr == "US" || vr == "SS" || vr == "UL" || vr == "SL"
712 || vr == "FL" || vr == "FD")
713 s << " [" << GetString() << "]";
716 if(Global::GetVR()->IsVROfStringRepresentable(vr))
718 // replace non printable characters by '.'
719 std::string cleanString = Util::CreateCleanString(v);
720 if ( cleanString.length() <= GetMaxSizePrintEntry()
723 // FIXME : when IsNotLoaded(), you create a Clean String ?!?
724 // FIXME : PrintLevel<2 *does* print the values
725 // (3 is only for extra offsets printing)
726 // What do you wanted to do ? JPR
728 s << " [" << cleanString << "]";
732 s << " [GDCM_NAME_SPACE::too long for print (" << cleanString.length() << ") ]";
737 // A lot of Private elements (with no VR) contain actually
738 // only printable characters;
739 // Let's deal with them as is they were VR std::string representable
741 if ( Util::IsCleanArea( GetBinArea(), GetLength() ) )
743 // FIXME : since the 'Area' *is* clean, just use
744 // a 'CreateString' method, to save CPU time.
745 std::string cleanString =
746 Util::CreateCleanString( BinArea,GetLength() );
747 s << " [" << cleanString << "]";
751 s << " [" << GDCM_BINLOADED << ";"
752 << "length = " << GetLength() << "]";
760 s << " [" << GDCM_NOTLOADED << "]";
761 else if( IsUnfound() )
762 s << " [" << GDCM_UNFOUND << "]";
763 else if( IsUnread() )
764 s << " [" << GDCM_UNREAD << "]";
765 else if ( GetLength() == 0 )
770 s << " (" << GDCM_PIXELDATA << ")";
772 // Display the UID value (instead of displaying only the rough code)
773 // First 'clean' trailing character (space or zero)
776 const uint16_t &gr = GetGroup();
777 const uint16_t &elt = GetElement();
778 TS *ts = Global::GetTS();
782 // Any more to be displayed ?
783 if ( elt == 0x0010 || elt == 0x0002 )
785 if ( v.length() != 0 ) // for brain damaged headers
787 if ( ! isdigit((unsigned char)v[v.length()-1]) )
789 v.erase(v.length()-1, 1);
792 s << " ==>\t[" << ts->GetValue(v) << "]";
795 else if (gr == 0x0008)
797 if ( elt == 0x0016 || elt == 0x1150 )
799 if ( v.length() != 0 ) // for brain damaged headers
801 if ( ! isdigit((unsigned char)v[v.length()-1]) )
803 v.erase(v.length()-1, 1);
806 s << " ==>\t[" << ts->GetValue(v) << "]";
809 else if (gr == 0x0004)
811 if ( elt == 0x1510 || elt == 0x1512 )
813 if ( v.length() != 0 ) // for brain damaged headers
815 if ( ! isdigit((unsigned char)v[v.length()-1]) )
817 v.erase(v.length()-1, 1);
820 s << " ==>\t[" << ts->GetValue(v) << "]";
828 //-----------------------------------------------------------------------------
829 } // end namespace gdcm