1 /*=========================================================================
4 Module: $RCSfile: gdcmDataEntry.cxx,v $
6 Date: $Date: 2008/04/10 12:15:35 $
7 Version: $Revision: 1.54 $
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
33 #include <string.h> // memcpy
34 #include <stdlib.h> // atof
36 // Could be defined like MAX_SIZE_LOAD_ELEMENT_VALUE
37 #define GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA 8
39 namespace GDCM_NAME_SPACE
41 //-----------------------------------------------------------------------------
42 #define MAX_SIZE_PRINT_ELEMENT_VALUE 0x7fffffff
43 uint32_t DataEntry::MaxSizePrintEntry = MAX_SIZE_PRINT_ELEMENT_VALUE;
45 //-----------------------------------------------------------------------------
46 // Constructor / Destructor
48 * \brief Constructor for a given DataEntry
49 * @param group group number of the Data Entry to be created
50 * @param elem element number of the Data Entry to be created
51 * @param vr Value Representation of the Data Entry to be created
53 DataEntry::DataEntry(uint16_t group,uint16_t elem,
55 : DocEntry(group,elem,vr)
67 * \brief Constructor for a given DocEntry
68 * @param e Pointer to existing Doc entry
70 DataEntry::DataEntry(DocEntry *e)
71 //: DocEntry(e->GetDictEntry())
72 : DocEntry(e->GetGroup(),e->GetElement(), e->GetVR() )
83 * \brief Canonical destructor.
85 DataEntry::~DataEntry ()
91 //-----------------------------------------------------------------------------
94 * \brief Sets the value (non string) of the current DataEntry
96 * @param self self=true : The area : *belongs" to the DataEntry
97 * : will be delete with the DataEntry
98 * self=false The area *is not* deleted with the DataEntry
101 void DataEntry::SetBinArea( uint8_t *area, bool self )
108 State = STATE_LOADED;
111 * \brief Inserts the value (non string) into the current DataEntry
113 * @param length length
115 void DataEntry::CopyBinArea( uint8_t *area, uint32_t length )
119 uint32_t lgh = length + length%2;
122 if( area && length > 0 )
125 memcpy(BinArea,area,length);
127 BinArea[length]=0; // padd with zero
129 State = STATE_LOADED;
134 * \brief Inserts the elementary (non string) value into the current DataEntry
135 * @param id index of the elementary value to be set
136 * @param val value, passed as a double
138 void DataEntry::SetValue(const uint32_t &id, const double &val)
142 State = STATE_LOADED;
144 if( id > GetValueCount() )
146 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
150 const VRKey &vr = GetVR();
151 if( vr == "US" || vr == "SS" )
153 uint16_t *data = (uint16_t *)BinArea;
154 data[id] = (uint16_t)val;
156 else if( vr == "UL" || vr == "SL" )
158 uint32_t *data = (uint32_t *)BinArea;
159 data[id] = (uint32_t)val;
161 else if( vr == "FL" )
163 float *data = (float *)BinArea;
164 data[id] = (float)val;
166 else if( vr == "FD" )
168 double *data = (double *)BinArea;
169 data[id] = (double)val;
171 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
173 gdcmErrorMacro("SetValue on String representable not implemented yet");
177 BinArea[id] = (uint8_t)val;
181 * \brief returns, as a double one of the values
182 * (when entry is multivaluated), identified by its index.
183 * Returns 0.0 if index is wrong
186 double DataEntry::GetValue(const uint32_t &id) const
190 if (GetLength() != 0) // avoid stupid messages
191 /// \todo warn the user there was a problem !
192 gdcmErrorMacro("BinArea not set " << std::hex
193 << GetGroup() << " " << GetElement()
194 << " Can't get the value");
198 uint32_t count = GetValueCount();
201 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
205 // if user *knows* that entry contains a US,
206 // he just has to cast the double he receives
208 const VRKey &vr = GetVR();
210 if( vr == "US" || vr == "SS" )
211 return ((uint16_t *)BinArea)[id];
212 else if( vr == "UL" || vr == "SL" )
213 return ((uint32_t *)BinArea)[id];
214 else if( vr == "FL" )
215 return ((float *)BinArea)[id];
216 else if( vr == "FD" )
217 return ((double *)BinArea)[id];
218 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
220 // this is for VR = "DS", ...
223 // Don't use std::string to accelerate processing
225 char *tmp = new char[GetLength()+1];
226 memcpy(tmp,BinArea,GetLength());
237 for(uint32_t i=0;i<GetLength();i++)
267 * \brief Checks if the multiplicity of the value follows Dictionary VM
269 bool DataEntry::IsValueCountValid() /*const*/
272 const std::string &strVM = GetVM();
273 uint32_t vc = GetValueCount();
274 bool valid = vc == 0;
278 // FIXME : what shall we do with VM = "2-n", "3-n", etc
282 // make sure there is at least one ??? FIXME
287 std::istringstream os;
291 // vm respects the one from the dict
292 // vm is 0 (we need to check if this element is allowed to be empty) FIXME
296 // Entries whose type is 1 are mandatory, with a mandatory value.
297 // Entries whose type is 1c are mandatory-inside-a-Sequence,
298 // with a mandatory value.
299 // Entries whose type is 2 are mandatory, with an optional value.
300 // Entries whose type is 2c are mandatory-inside-a-Sequence,
301 // with an optional value.
302 // Entries whose type is 3 are optional.
304 // case vc == 0 is only applicable for 'type 2' entries.
305 // Problem : entry type may depend on the modality and/or the Sequence
306 // it's embedded in !
307 // (Get the information in the 'Conformance Statements' ...)
314 * \brief returns the number of elementary values
316 uint32_t DataEntry::GetValueCount( ) const
318 const VRKey &vr = GetVR();
319 if( vr == "US" || vr == "SS" )
320 return GetLength()/sizeof(uint16_t);
321 else if( vr == "UL" || vr == "SL" )
322 return GetLength()/sizeof(uint32_t);
323 else if( vr == "FL" || vr == "OF" )
324 return GetLength()/4 ; // FL has a *4* length! sizeof(float);
325 else if( vr == "FD" )
326 return GetLength()/8; // FD has a *8* length! sizeof(double);
327 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
329 // Some element in DICOM are allowed to be empty
332 // Don't use std::string to accelerate processing
334 for(uint32_t i=0;i<GetLength();i++)
336 if( BinArea[i] == '\\')
345 * \brief Gets a std::vector of 'double' holding the value(s) of a DS DataEntry
346 * @param valueVector std::vector double of value(s)
347 * \return false if VR not "DS" or DataEntry empty
349 bool DataEntry::GetDSValue(std::vector <double> &valueVector)
351 /// \todo rewrite the whole method, in order *not to use* std::string !
352 std::vector<std::string> tokens;
354 if (GetVR() != "DS") // never trust a user !
357 Util::Tokenize ( GetString().c_str(), tokens, "\\" );
359 int nbValues= tokens.size();
363 for (int loop=0; loop<nbValues; loop++)
364 valueVector.push_back(atof(tokens[loop].c_str()));
370 * \brief Sets the 'value' of a DataEntry, passed as a std::string
371 * @param value string representation of the value to be set
373 void DataEntry::SetString(std::string const &value)
376 const VRKey &vr = GetVR();
377 if ( vr == "US" || vr == "SS" )
379 std::vector<std::string> tokens;
380 Util::Tokenize (value, tokens, "\\");
381 SetLength(tokens.size()*sizeof(uint16_t));
384 uint16_t *data = (uint16_t *)BinArea;
385 for (unsigned int i=0; i<tokens.size();i++)
386 data[i] = atoi(tokens[i].c_str());
389 else if ( vr == "UL" || vr == "SL" )
391 std::vector<std::string> tokens;
392 Util::Tokenize (value, tokens, "\\");
393 SetLength(tokens.size()*sizeof(uint32_t));
396 uint32_t *data = (uint32_t *)BinArea;
397 for (unsigned int i=0; i<tokens.size();i++)
398 data[i] = atoi(tokens[i].c_str());
401 else if ( vr == "FL" )
403 std::vector<std::string> tokens;
404 Util::Tokenize (value, tokens, "\\");
405 SetLength(tokens.size()*sizeof(float));
408 float *data = (float *)BinArea;
409 for (unsigned int i=0; i<tokens.size();i++)
410 data[i] = (float)atof(tokens[i].c_str());
413 else if ( vr == "FD" )
415 std::vector<std::string> tokens;
416 Util::Tokenize (value, tokens, "\\");
417 SetLength(tokens.size()*sizeof(double));
420 double *data = (double *)BinArea;
421 for (unsigned int i=0; i<tokens.size();i++)
422 data[i] = atof(tokens[i].c_str());
427 size_t l = value.size();
430 memcpy(BinArea, value.c_str(), l);
431 if (l%2) // padded with blank except for UI
439 State = STATE_LOADED;
442 * \brief returns as a string (when possible) the value of the DataEntry
444 std::string const &DataEntry::GetString() const
446 static std::ostringstream s;
447 const VRKey &vr = GetVR();
451 StrArea = new std::string();
457 // When short integer(s) are stored, convert the following (n * 2) characters
458 // as a displayable string, the values being separated by a back-slash
461 uint16_t *data=(uint16_t *)BinArea;
462 for (unsigned int i=0; i < GetValueCount(); i++)
470 else if (vr == "SS" )
472 int16_t *data=(int16_t *)BinArea;
473 for (unsigned int i=0; i < GetValueCount(); i++)
480 } // See above comment on multiple short integers (mutatis mutandis).
481 else if( vr == "UL" )
483 uint32_t *data=(uint32_t *)BinArea;
484 for (unsigned int i=0; i < GetValueCount(); i++)
492 else if( vr == "SL" )
494 int32_t *data=(int32_t *)BinArea;
495 for (unsigned int i=0; i < GetValueCount(); i++)
502 } // See above comment on multiple short integers (mutatis mutandis).
503 else if( vr == "FL" )
505 float *data=(float *)BinArea;
506 for (unsigned int i=0; i < GetValueCount(); i++)
513 } // See above comment on multiple short integers (mutatis mutandis).
514 else if( vr == "FD" )
516 double *data=(double *)BinArea;
517 for (unsigned int i=0; i < GetValueCount(); i++)
527 StrArea->append((const char *)BinArea,GetLength());
528 // to avoid gdcm to propagate oddities in lengthes
530 StrArea->append(" ",1);
536 * \brief returns an hexadecimal representation of the DataEntry value
538 std::string const &DataEntry::GetHexaRepresentation() const
540 static std::ostringstream s2;
541 const VRKey &vr = GetVR();
545 StrHexaArea = new std::string();
550 // When short integer(s) are stored, convert the following (n * 2) characters
551 // as a displayable string, the values being separated by a back-slash
557 uint16_t *data=(uint16_t *)BinArea;
558 for (unsigned int i=0; i < GetValueCount(); i++)
560 s2 << std::setw( 2 ) << std::setfill( '0' );
565 *StrHexaArea=s2.str();
567 else if (vr == "SS" )
569 int16_t *data=(int16_t *)BinArea;
570 for (unsigned int i=0; i < GetValueCount(); i++)
572 s2 << std::setw( 4 ) << std::setfill( '0' );
577 *StrHexaArea=s2.str();
578 } // See above comment on multiple short integers (mutatis mutandis).
579 else if( vr == "UL" )
581 uint32_t *data=(uint32_t *)BinArea;
582 for (unsigned int i=0; i < GetValueCount(); i++)
584 s2 << std::setw( 4 ) << std::setfill( '0' );
589 *StrHexaArea=s2.str();
591 else if( vr == "SL" )
593 int32_t *data=(int32_t *)BinArea;
594 for (unsigned int i=0; i < GetValueCount(); i++)
596 s2 << std::setw( 4 ) << std::setfill( '0' );
601 *StrHexaArea=s2.str();
603 else if( vr == "FL" )
605 unsigned char *toto=(unsigned char *)BinArea;
606 for (unsigned int i=0; i < GetValueCount(); i++)
612 for(int iif=0; iif<4; iif++)
618 *StrHexaArea=s2.str();
620 else if( vr == "FD" )
622 //double *data=(double *)BinArea;
623 unsigned char *toto=(unsigned char *)BinArea;
624 for (unsigned int i=0; i < GetValueCount(); i++)
632 for(int iid=0; iid<8; iid++)
639 *StrHexaArea=s2.str();
643 unsigned int l = (Length > GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA) ? GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA : Length;
644 uint8_t *data=(uint8_t *)BinArea;
645 for (unsigned int i=0; i < l; i++)
649 s2 << std::setw( 2 ) << (int)(data[i]);
653 *StrHexaArea=s2.str();
659 * \brief Copies all the attributes from an other DocEntry
660 * @param doc entry to copy from
661 * @remarks The content BinArea is copied too (StrArea is not)
663 void DataEntry::Copy(DocEntry *doc)
667 DataEntry *entry = dynamic_cast<DataEntry *>(doc);
670 State = entry->State;
672 CopyBinArea(entry->BinArea,entry->GetLength());
677 * \brief Writes the 'common part' + the 'value' area of a DataEntry
678 * @param fp already open ofstream pointer
679 * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
681 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype,
682 bool insideMetaElements, bool insideSequence)
684 // writes the 'common part'
685 DocEntry::WriteContent(fp, filetype, insideMetaElements, insideSequence);
687 if ( GetGroup() == 0xfffe )
689 return; //delimitors have NO value
692 // --> We only deal with Little Endian writting.
693 // --> forget Big Endian Transfer Syntax writting!
694 // Next DICOM version will give it up ...
696 // WARNING - For Implicit VR private element,
697 // we have *no choice* but considering them as
698 // something like 'OB' values.
699 // we rewrite them as we found them on disc.
700 // Some trouble will occur if element was
701 // *actually* OW, if image was produced
702 // on Big endian based processor, read and writen
703 // on Little endian based processor
704 // and, later on, somebody needs
705 // this 'OW' Implicit VR private element (?!?)
706 // (Same stuff, mutatis mutandis, for Little/Big)
708 // 8/16 bits Pixels problem should be solved automatiquely,
709 // since we ensure the VR (OB vs OW) is conform to Pixel size.
711 uint8_t *data = BinArea; //safe notation
712 size_t l = GetLength();
713 // gdcmDebugMacro("in DataEntry::WriteContent " << GetKey() << " AtomicLength: "
714 // << Global::GetVR()->GetAtomicElementLength(this->GetVR() ) // << " BinArea in :" << &BinArea
716 if (BinArea) // the binArea was *actually* loaded
718 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
719 unsigned short vrLgth =
720 Global::GetVR()->GetAtomicElementLength(this->GetVR());
726 binary_write (*fp, data, l );
731 uint16_t *data16 = (uint16_t *)data;
732 for(i=0;i<l/vrLgth;i++)
733 binary_write( *fp, data16[i]);
738 uint32_t *data32 = (uint32_t *)data;
739 for(i=0;i<l/vrLgth;i++)
740 binary_write( *fp, data32[i]);
745 double *data64 = (double *)data;
746 for(i=0;i<l/vrLgth;i++)
747 binary_write( *fp, data64[i]);
752 binary_write (*fp, data, l );
753 #endif //GDCM_WORDS_BIGENDIAN
758 // nothing was loaded, but we need to skip space on disc
761 // --> WARNING : nothing is written;
762 // --> the initial data (on the the source image) is lost
763 // --> user is *not* informed !
764 gdcmDebugMacro ("Nothing was loaded, but we need to skip space on disc. "
765 << "Length =" << l << " for " << GetKey() );
766 fp->seekp(l, std::ios::cur); // At Write time, for unloaded elems
769 // to avoid gdcm to propagate oddities
770 // (length was already modified)
772 fp->seekp(1, std::ios::cur); // At Write time, for non even length elems
776 * \brief Compute the full length of the elementary DataEntry (not only value
777 * length) depending on the VR.
779 uint32_t DataEntry::ComputeFullLength()
781 return GetFullLength();
784 //-----------------------------------------------------------------------------
787 /// \brief Creates a DataEntry owned BinArea
788 /// (remove previous one if any and relevant StrArea if any)
789 void DataEntry::NewBinArea( )
792 if( GetLength() > 0 )
793 BinArea = new uint8_t[GetLength()];
796 /// \brief Removes the BinArea, if owned by the DataEntry,
797 /// and the relevant StrArea if any
798 void DataEntry::DeleteBinArea(void)
800 if (BinArea && SelfArea)
817 //-----------------------------------------------------------------------------
820 //-----------------------------------------------------------------------------
823 * \brief Prints a DataEntry (Dicom entry)
824 * @param os ostream we want to print in
825 * @param indent Indentation string to be prepended during printing
827 void DataEntry::Print(std::ostream &os, std::string const & )
831 // First, Print the common part (vr [length offset] name).
834 uint16_t g = GetGroup();
835 if (g == 0xfffe) // delimiters have NO value
837 return; // just to avoid identing all the remaining code
840 std::ostringstream s;
846 const VRKey &vr = GetVR();
848 if( vr == "US" || vr == "SS" || vr == "UL" || vr == "SL"
849 || vr == "FL" || vr == "FD")
850 s << " [" << GetString() << "] =0x(" << GetHexaRepresentation() << ")";
853 if(Global::GetVR()->IsVROfStringRepresentable(vr))
855 // replace non printable characters by '.'
856 std::string cleanString = Util::CreateCleanString(v);
857 if ( cleanString.length() <= GetMaxSizePrintEntry()
860 // FIXME : when IsNotLoaded(), you create a Clean String ?!?
861 // FIXME : PrintLevel<2 *does* print the values
862 // (3 is only for extra offsets printing)
863 // What do you wanted to do ? JPR
865 s << " [" << cleanString << "]";
869 s << " [GDCM_NAME_SPACE::too long for print (" << cleanString.length() << ") ]";
874 // A lot of Private elements (with no VR) contain actually
875 // only printable characters;
876 // Let's deal with them as is they were VR std::string representable
878 if ( Util::IsCleanArea( GetBinArea(), GetLength() ) )
880 // FIXME : since the 'Area' *is* clean, just use
881 // a 'CreateString' method, to save CPU time.
882 std::string cleanString =
883 Util::CreateCleanString( BinArea,GetLength() );
884 s << " [" << cleanString << "]";
888 s << " [" << GDCM_BINLOADED << ";"
889 << "length = " << GetLength() << "] =0x(" << GetHexaRepresentation() << ")";
897 s << " [" << GDCM_NOTLOADED << "]";
898 else if( IsUnfound() )
899 s << " [" << GDCM_UNFOUND << "]";
900 else if( IsUnread() )
901 s << " [" << GDCM_UNREAD << "]";
902 else if ( GetLength() == 0 )
907 s << " (" << GDCM_PIXELDATA << ")";
909 // Display the UID value (instead of displaying only the rough code)
910 // First 'clean' trailing character (space or zero)
913 const uint16_t &gr = GetGroup();
914 const uint16_t &elt = GetElement();
915 TS *ts = Global::GetTS();
919 // Any more to be displayed ?
920 if ( elt == 0x0010 || elt == 0x0002 )
922 if ( v.length() != 0 ) // for brain damaged headers
924 if ( ! isdigit((unsigned char)v[v.length()-1]) )
926 v.erase(v.length()-1, 1);
929 s << " ==>\t[" << ts->GetValue(v) << "]";
932 else if (gr == 0x0008)
934 if ( elt == 0x0016 || elt == 0x1150 )
936 if ( v.length() != 0 ) // for brain damaged headers
938 if ( ! isdigit((unsigned char)v[v.length()-1]) )
940 v.erase(v.length()-1, 1);
943 s << " ==>\t[" << ts->GetValue(v) << "]";
946 else if (gr == 0x0004)
948 if ( elt == 0x1510 || elt == 0x1512 )
950 if ( v.length() != 0 ) // for brain damaged headers
952 if ( ! isdigit((unsigned char)v[v.length()-1]) )
954 v.erase(v.length()-1, 1);
957 s << " ==>\t[" << ts->GetValue(v) << "]";
965 //-----------------------------------------------------------------------------
966 } // end namespace gdcm