1 /*=========================================================================
4 Module: $RCSfile: gdcmDataEntry.cxx,v $
6 Date: $Date: 2011/03/29 07:36:00 $
7 Version: $Revision: 1.57 $
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 ()
90 //-----------------------------------------------------------------------------
93 * \brief Sets the value (non string) of the current DataEntry
95 * @param self self=true : The area : *belongs" to the DataEntry
96 * : will be delete with the DataEntry
97 * self=false The area *is not* deleted with the DataEntry
100 void DataEntry::SetBinArea( uint8_t *area, bool self )
107 State = STATE_LOADED;
110 * \brief Inserts the value (non string) into the current DataEntry
112 * @param length length
114 void DataEntry::CopyBinArea( uint8_t *area, uint32_t length )
118 uint32_t lgh = length + length%2;
121 if( area && length > 0 )
124 memcpy(BinArea,area,length);
126 BinArea[length]=0; // padd with zero
128 State = STATE_LOADED;
133 * \brief Checks wether the current DataEntry contains number(s)
136 bool DataEntry::IsNumerical()
138 const VRKey &vr = GetVR();
154 * \brief Gets a std::vector of 'double' holding the value(s) of any 'numerical' DataEntry
155 * @param valueVector std::vector double of value(s)
156 * \return false if VR not "a 'numerical" one
158 bool DataEntry::GetNumerical(std::vector <double> &valueVector)
162 if (!IsNumerical()) // never trust a user !
165 const VRKey &vr = GetVR();
167 if (vr == "IS" || vr == "DS")
169 /// \todo rewrite the whole method, in order *not to use* std::string !
170 std::vector<std::string> tokens;
172 Util::Tokenize ( GetString().c_str(), tokens, "\\" );
174 int nbValues= tokens.size();
179 for (loop=0; loop<nbValues; loop++)
180 valueVector.push_back(atof(tokens[loop].c_str()));
182 for (loop=0; loop<nbValues; loop++)
183 valueVector.push_back(atoi(tokens[loop].c_str()));
188 uint32_t nbValues = GetValueCount();
193 for (loop=0; loop<nbValues; loop++)
194 valueVector.push_back(((uint16_t *)BinArea)[loop]);
198 for (loop=0; loop<nbValues; loop++)
199 valueVector.push_back(((int16_t *)BinArea)[loop]);
203 for (loop=0; loop<nbValues; loop++)
204 valueVector.push_back(((uint32_t *)BinArea)[loop]);
208 for (loop=0; loop<nbValues; loop++)
209 valueVector.push_back(((int32_t *)BinArea)[loop]);
213 for (loop=0; loop<nbValues; loop++)
214 valueVector.push_back(((float *)BinArea)[loop]);
218 for (loop=0; loop<nbValues; loop++)
219 valueVector.push_back(((double *)BinArea)[loop]);
226 * \brief Inserts the elementary (non string) value into the current DataEntry
227 * @param id index of the elementary value to be set
228 * @param val value, passed as a double
230 void DataEntry::SetValue(const uint32_t &id, const double &val)
234 State = STATE_LOADED;
236 if( id > GetValueCount() )
238 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
242 const VRKey &vr = GetVR();
243 if( vr == "US" || vr == "SS" )
245 uint16_t *data = (uint16_t *)BinArea;
246 data[id] = (uint16_t)val;
248 else if( vr == "UL" || vr == "SL" )
250 uint32_t *data = (uint32_t *)BinArea;
251 data[id] = (uint32_t)val;
253 else if( vr == "FL" )
255 float *data = (float *)BinArea;
256 data[id] = (float)val;
258 else if( vr == "FD" )
260 double *data = (double *)BinArea;
261 data[id] = (double)val;
263 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
265 gdcmErrorMacro("SetValue on String representable not implemented yet");
269 BinArea[id] = (uint8_t)val;
273 * \brief returns, as a double one of the values
274 * (when entry is multivaluated), identified by its index.
275 * Returns 0.0 if index is wrong
278 double DataEntry::GetValue(const uint32_t &id) const
282 if (GetLength() != 0) // avoid stupid messages
283 /// \todo warn the user there was a problem !
284 gdcmErrorMacro("BinArea not set " << std::hex
285 << GetGroup() << " " << GetElement()
286 << " Can't get the value");
290 uint32_t count = GetValueCount();
293 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
297 // if user *knows* that entry contains a US,
298 // he just has to cast the double he receives
300 const VRKey &vr = GetVR();
302 if( vr == "US" || vr == "SS" )
303 return ((uint16_t *)BinArea)[id];
304 else if( vr == "UL" || vr == "SL" )
305 return ((uint32_t *)BinArea)[id];
306 else if( vr == "FL" )
307 return ((float *)BinArea)[id];
308 else if( vr == "FD" )
309 return ((double *)BinArea)[id];
310 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
312 // this is for VR = "DS", ...
315 // Don't use std::string to accelerate processing
317 char *tmp = new char[GetLength()+1];
318 memcpy(tmp,BinArea,GetLength());
329 for(uint32_t i=0;i<GetLength();i++)
359 * \brief Checks if the multiplicity of the value follows Dictionary VM
361 bool DataEntry::IsValueCountValid() /*const*/
364 const std::string &strVM = GetVM();
365 uint32_t vc = GetValueCount();
366 bool valid = vc == 0;
370 // FIXME : what shall we do with VM = "2-n", "3-n", etc
374 // make sure there is at least one ??? FIXME
379 std::istringstream os;
383 // vm respects the one from the dict
384 // vm is 0 (we need to check if this element is allowed to be empty) FIXME
388 // Entries whose type is 1 are mandatory, with a mandatory value.
389 // Entries whose type is 1c are mandatory-inside-a-Sequence,
390 // with a mandatory value.
391 // Entries whose type is 2 are mandatory, with an optional value.
392 // Entries whose type is 2c are mandatory-inside-a-Sequence,
393 // with an optional value.
394 // Entries whose type is 3 are optional.
396 // case vc == 0 is only applicable for 'type 2' entries.
397 // Problem : entry type may depend on the modality and/or the Sequence
398 // it's embedded in !
399 // (Get the information in the 'Conformance Statements' ...)
406 * \brief returns the number of elementary values
408 uint32_t DataEntry::GetValueCount( ) const
410 const VRKey &vr = GetVR();
411 if( vr == "US" || vr == "SS" )
412 return GetLength()/sizeof(uint16_t);
413 else if( vr == "UL" || vr == "SL" )
414 return GetLength()/sizeof(uint32_t);
415 else if( vr == "FL" || vr == "OF" )
416 return GetLength()/4 ; // FL has a *4* length! sizeof(float);
417 else if( vr == "FD" )
418 return GetLength()/8; // FD has a *8* length! sizeof(double);
419 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
421 // Some element in DICOM are allowed to be empty
424 // Don't use std::string to accelerate processing
426 for(uint32_t i=0;i<GetLength();i++)
428 if( BinArea[i] == '\\')
437 * \brief Gets a std::vector of 'double' holding the value(s) of a DS DataEntry
438 * @param valueVector std::vector double of value(s)
439 * \return false if VR not "DS" or DataEntry empty
441 bool DataEntry::GetDSValue(std::vector <double> &valueVector)
443 /// \todo rewrite the whole method, in order *not to use* std::string !
444 std::vector<std::string> tokens;
446 if (GetVR() != "DS") // never trust a user !
449 Util::Tokenize ( GetString().c_str(), tokens, "\\" );
451 int nbValues= tokens.size();
455 for (int loop=0; loop<nbValues; loop++)
456 valueVector.push_back(atof(tokens[loop].c_str()));
462 * \brief Sets the 'value' of a DataEntry, passed as a std::string
463 * @param value string representation of the value to be set
465 void DataEntry::SetString(std::string const &value)
468 const VRKey &vr = GetVR();
469 if ( vr == "US" || vr == "SS" )
471 std::vector<std::string> tokens;
472 Util::Tokenize (value, tokens, "\\");
473 SetLength(tokens.size()*sizeof(uint16_t));
476 uint16_t *data = (uint16_t *)BinArea;
477 for (unsigned int i=0; i<tokens.size();i++)
478 data[i] = atoi(tokens[i].c_str());
481 else if ( vr == "UL" || vr == "SL" )
483 std::vector<std::string> tokens;
484 Util::Tokenize (value, tokens, "\\");
485 SetLength(tokens.size()*sizeof(uint32_t));
488 uint32_t *data = (uint32_t *)BinArea;
489 for (unsigned int i=0; i<tokens.size();i++)
490 data[i] = atoi(tokens[i].c_str());
493 else if ( vr == "FL" )
495 std::vector<std::string> tokens;
496 Util::Tokenize (value, tokens, "\\");
497 SetLength(tokens.size()*sizeof(float));
500 float *data = (float *)BinArea;
501 for (unsigned int i=0; i<tokens.size();i++)
502 data[i] = (float)atof(tokens[i].c_str());
505 else if ( vr == "FD" )
507 std::vector<std::string> tokens;
508 Util::Tokenize (value, tokens, "\\");
509 SetLength(tokens.size()*sizeof(double));
512 double *data = (double *)BinArea;
513 for (unsigned int i=0; i<tokens.size();i++)
514 data[i] = atof(tokens[i].c_str());
519 size_t l = value.size();
522 memcpy(BinArea, value.c_str(), l);
523 if (l%2) // padded with blank except for UI
531 State = STATE_LOADED;
534 * \brief returns as a string (when possible) the value of the DataEntry
536 std::string const &DataEntry::GetString() const
538 static std::ostringstream s;
539 const VRKey &vr = GetVR();
543 StrArea = new std::string();
549 // When short integer(s) are stored, convert the following (n * 2) characters
550 // as a displayable string, the values being separated by a back-slash
553 uint16_t *data=(uint16_t *)BinArea;
554 for (unsigned int i=0; i < GetValueCount(); i++)
562 else if (vr == "SS" )
564 int16_t *data=(int16_t *)BinArea;
565 for (unsigned int i=0; i < GetValueCount(); i++)
572 } // See above comment on multiple short integers (mutatis mutandis).
573 else if( vr == "UL" )
575 uint32_t *data=(uint32_t *)BinArea;
576 for (unsigned int i=0; i < GetValueCount(); i++)
584 else if( vr == "SL" )
586 int32_t *data=(int32_t *)BinArea;
587 for (unsigned int i=0; i < GetValueCount(); i++)
594 } // See above comment on multiple short integers (mutatis mutandis).
595 else if( vr == "FL" )
597 float *data=(float *)BinArea;
598 for (unsigned int i=0; i < GetValueCount(); i++)
605 } // See above comment on multiple short integers (mutatis mutandis).
606 else if( vr == "FD" )
608 double *data=(double *)BinArea;
609 for (unsigned int i=0; i < GetValueCount(); i++)
619 StrArea->append((const char *)BinArea,GetLength());
620 // to avoid gdcm to propagate oddities in lengthes
622 StrArea->append(" ",1);
628 * \brief returns an hexadecimal representation of the DataEntry value
630 std::string const &DataEntry::GetHexaRepresentation() const
632 static std::ostringstream s2;
633 const VRKey &vr = GetVR();
637 StrHexaArea = new std::string();
642 // When short integer(s) are stored, convert the following (n * 2) characters
643 // as a displayable string, the values being separated by a back-slash
649 uint16_t *data=(uint16_t *)BinArea;
650 for (unsigned int i=0; i < GetValueCount(); i++)
652 s2 << std::setw( 2 ) << std::setfill( '0' );
657 *StrHexaArea=s2.str();
659 else if (vr == "SS" )
661 int16_t *data=(int16_t *)BinArea;
662 for (unsigned int i=0; i < GetValueCount(); i++)
664 s2 << std::setw( 4 ) << std::setfill( '0' );
669 *StrHexaArea=s2.str();
670 } // See above comment on multiple short integers (mutatis mutandis).
671 else if( vr == "UL" )
673 uint32_t *data=(uint32_t *)BinArea;
674 for (unsigned int i=0; i < GetValueCount(); i++)
676 s2 << std::setw( 4 ) << std::setfill( '0' );
681 *StrHexaArea=s2.str();
683 else if( vr == "SL" )
685 int32_t *data=(int32_t *)BinArea;
686 for (unsigned int i=0; i < GetValueCount(); i++)
688 s2 << std::setw( 4 ) << std::setfill( '0' );
693 *StrHexaArea=s2.str();
695 else if( vr == "FL" )
697 unsigned char *toto=(unsigned char *)BinArea;
698 for (unsigned int i=0; i < GetValueCount(); i++)
704 for(int iif=0; iif<4; iif++)
710 *StrHexaArea=s2.str();
712 else if( vr == "FD" )
714 //double *data=(double *)BinArea;
715 unsigned char *toto=(unsigned char *)BinArea;
716 for (unsigned int i=0; i < GetValueCount(); i++)
724 for(int iid=0; iid<8; iid++)
731 *StrHexaArea=s2.str();
735 unsigned int l = (Length > GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA) ? GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA : Length;
736 uint8_t *data=(uint8_t *)BinArea;
737 for (unsigned int i=0; i < l; i++)
741 s2 << std::setw( 2 ) << (int)(data[i]);
745 *StrHexaArea=s2.str();
751 * \brief Copies all the attributes from an other DocEntry
752 * @param doc entry to copy from
753 * @remarks The content BinArea is copied too (StrArea is not)
755 void DataEntry::Copy(DocEntry *doc)
759 DataEntry *entry = dynamic_cast<DataEntry *>(doc);
762 State = entry->State;
764 CopyBinArea(entry->BinArea,entry->GetLength());
769 * \brief Writes the 'common part' + the 'value' area of a DataEntry
770 * @param fp already open ofstream pointer
771 * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
773 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype,
774 bool insideMetaElements, bool insideSequence)
776 // writes the 'common part'
777 DocEntry::WriteContent(fp, filetype, insideMetaElements, insideSequence);
779 if ( GetGroup() == 0xfffe )
781 return; //delimitors have NO value
784 // --> We only deal with Little Endian writting.
785 // --> forget Big Endian Transfer Syntax writting!
786 // Next DICOM version will give it up ...
788 // WARNING - For Implicit VR private element,
789 // we have *no choice* but considering them as
790 // something like 'OB' values.
791 // we rewrite them as we found them on disc.
792 // Some trouble will occur if element was
793 // *actually* OW, if image was produced
794 // on Big endian based processor, read and writen
795 // on Little endian based processor
796 // and, later on, somebody needs
797 // this 'OW' Implicit VR private element (?!?)
798 // (Same stuff, mutatis mutandis, for Little/Big)
800 // 8/16 bits Pixels problem should be solved automatiquely,
801 // since we ensure the VR (OB vs OW) is conform to Pixel size.
803 uint8_t *data = BinArea; //safe notation
804 size_t l = GetLength();
805 // gdcmDebugMacro("in DataEntry::WriteContent " << GetKey() << " AtomicLength: "
806 // << Global::GetVR()->GetAtomicElementLength(this->GetVR() ) // << " BinArea in :" << &BinArea
808 if (BinArea) // the binArea was *actually* loaded
810 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
811 unsigned short vrLgth =
812 Global::GetVR()->GetAtomicElementLength(this->GetVR());
818 binary_write (*fp, data, l );
823 uint16_t *data16 = (uint16_t *)data;
824 for(i=0;i<l/vrLgth;i++)
825 binary_write( *fp, data16[i]);
830 uint32_t *data32 = (uint32_t *)data;
831 for(i=0;i<l/vrLgth;i++)
832 binary_write( *fp, data32[i]);
837 double *data64 = (double *)data;
838 for(i=0;i<l/vrLgth;i++)
839 binary_write( *fp, data64[i]);
844 binary_write (*fp, data, l );
845 #endif //GDCM_WORDS_BIGENDIAN
850 // nothing was loaded, but we need to skip space on disc
853 // --> WARNING : nothing is written;
854 // --> the initial data (on the the source image) is lost
855 // --> user is *not* informed !
856 gdcmDebugMacro ("Nothing was loaded, but we need to skip space on disc. "
857 << "Length =" << l << " for " << GetKey() );
858 fp->seekp(l, std::ios::cur); // At Write time, for unloaded elems
861 // to avoid gdcm to propagate oddities
862 // (length was already modified)
864 fp->seekp(1, std::ios::cur); // At Write time, for non even length elems
868 * \brief Compute the full length of the elementary DataEntry (not only value
869 * length) depending on the VR.
871 uint32_t DataEntry::ComputeFullLength()
873 return GetFullLength();
876 //-----------------------------------------------------------------------------
879 /// \brief Creates a DataEntry owned BinArea
880 /// (remove previous one if any and relevant StrArea if any)
881 void DataEntry::NewBinArea( )
884 if( GetLength() > 0 )
885 BinArea = new uint8_t[GetLength()];
888 /// \brief Removes the BinArea, if owned by the DataEntry,
889 /// and the relevant StrArea if any
890 void DataEntry::DeleteBinArea(void)
892 if (BinArea && SelfArea)
909 //-----------------------------------------------------------------------------
912 //-----------------------------------------------------------------------------
915 * \brief Prints a DataEntry (Dicom entry)
916 * @param os ostream we want to print in
917 * @param indent Indentation string to be prepended during printing
919 void DataEntry::Print(std::ostream &os, std::string const & )
923 // First, Print the common part (vr [length offset] name).
926 uint16_t g = GetGroup();
927 if (g == 0xfffe) // delimiters have NO value
929 return; // just to avoid identing all the remaining code
932 std::ostringstream s;
938 const VRKey &vr = GetVR();
940 if( vr == "US" || vr == "SS" || vr == "UL" || vr == "SL"
941 || vr == "FL" || vr == "FD")
942 s << " [" << GetString() << "] =0x(" << GetHexaRepresentation() << ")";
945 if(Global::GetVR()->IsVROfStringRepresentable(vr))
947 // replace non printable characters by '.'
948 std::string cleanString = Util::CreateCleanString(v);
949 if ( cleanString.length() <= GetMaxSizePrintEntry()
952 // FIXME : when IsNotLoaded(), you create a Clean String ?!?
953 // FIXME : PrintLevel<2 *does* print the values
954 // (3 is only for extra offsets printing)
955 // What do you wanted to do ? JPR
957 s << " [" << cleanString << "]";
961 s << " [GDCM_NAME_SPACE::too long for print (" << cleanString.length() << ") ]";
966 // A lot of Private elements (with no VR) contain actually
967 // only printable characters;
968 // Let's deal with them as is they were VR std::string representable
970 if ( Util::IsCleanArea( GetBinArea(), GetLength() ) )
972 // FIXME : since the 'Area' *is* clean, just use
973 // a 'CreateString' method, to save CPU time.
974 std::string cleanString =
975 Util::CreateCleanString( BinArea,GetLength() );
976 s << " [" << cleanString << "]";
980 s << " [" << GDCM_BINLOADED << ";"
981 << "length = " << GetLength() << "] =0x(" << GetHexaRepresentation() << ")";
989 s << " [" << GDCM_NOTLOADED << "]";
990 else if( IsUnfound() )
991 s << " [" << GDCM_UNFOUND << "]";
992 else if( IsUnread() )
993 s << " [" << GDCM_UNREAD << "]";
994 else if ( GetLength() == 0 )
999 s << " (" << GDCM_PIXELDATA << ")";
1001 // Display the UID value (instead of displaying only the rough code)
1002 // First 'clean' trailing character (space or zero)
1005 const uint16_t &gr = GetGroup();
1006 const uint16_t &elt = GetElement();
1007 TS *ts = Global::GetTS();
1011 // Any more to be displayed ?
1012 if ( elt == 0x0010 || elt == 0x0002 )
1014 if ( v.length() != 0 ) // for brain damaged headers
1016 if ( ! isdigit((unsigned char)v[v.length()-1]) )
1018 v.erase(v.length()-1, 1);
1021 s << " ==>\t[" << ts->GetValue(v) << "]";
1024 else if (gr == 0x0008)
1026 if ( elt == 0x0016 || elt == 0x1150 )
1028 if ( v.length() != 0 ) // for brain damaged headers
1030 if ( ! isdigit((unsigned char)v[v.length()-1]) )
1032 v.erase(v.length()-1, 1);
1035 s << " ==>\t[" << ts->GetValue(v) << "]";
1038 else if (gr == 0x0004)
1040 if ( elt == 0x1510 || elt == 0x1512 )
1042 if ( v.length() != 0 ) // for brain damaged headers
1044 if ( ! isdigit((unsigned char)v[v.length()-1]) )
1046 v.erase(v.length()-1, 1);
1049 s << " ==>\t[" << ts->GetValue(v) << "]";
1057 //-----------------------------------------------------------------------------
1058 } // end namespace gdcm