1 /*=========================================================================
4 Module: $RCSfile: gdcmDataEntry.cxx,v $
6 Date: $Date: 2008/02/13 15:41:26 $
7 Version: $Revision: 1.53 $
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 // Could be defined like MAX_SIZE_LOAD_ELEMENT_VALUE
35 #define GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA 8
37 namespace GDCM_NAME_SPACE
39 //-----------------------------------------------------------------------------
40 #define MAX_SIZE_PRINT_ELEMENT_VALUE 0x7fffffff
41 uint32_t DataEntry::MaxSizePrintEntry = MAX_SIZE_PRINT_ELEMENT_VALUE;
43 //-----------------------------------------------------------------------------
44 // Constructor / Destructor
46 * \brief Constructor for a given DataEntry
47 * @param group group number of the Data Entry to be created
48 * @param elem element number of the Data Entry to be created
49 * @param vr Value Representation of the Data Entry to be created
51 DataEntry::DataEntry(uint16_t group,uint16_t elem,
53 : DocEntry(group,elem,vr)
65 * \brief Constructor for a given DocEntry
66 * @param e Pointer to existing Doc entry
68 DataEntry::DataEntry(DocEntry *e)
69 //: DocEntry(e->GetDictEntry())
70 : DocEntry(e->GetGroup(),e->GetElement(), e->GetVR() )
81 * \brief Canonical destructor.
83 DataEntry::~DataEntry ()
89 //-----------------------------------------------------------------------------
92 * \brief Sets the value (non string) of the current DataEntry
94 * @param self self=true : The area : *belongs" to the DataEntry
95 * : will be delete with the DataEntry
96 * self=false The area *is not* deleted with the DataEntry
99 void DataEntry::SetBinArea( uint8_t *area, bool self )
106 State = STATE_LOADED;
109 * \brief Inserts the value (non string) into the current DataEntry
111 * @param length length
113 void DataEntry::CopyBinArea( uint8_t *area, uint32_t length )
117 uint32_t lgh = length + length%2;
120 if( area && length > 0 )
123 memcpy(BinArea,area,length);
125 BinArea[length]=0; // padd with zero
127 State = STATE_LOADED;
132 * \brief Inserts the elementary (non string) value into the current DataEntry
133 * @param id index of the elementary value to be set
134 * @param val value, passed as a double
136 void DataEntry::SetValue(const uint32_t &id, const double &val)
140 State = STATE_LOADED;
142 if( id > GetValueCount() )
144 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
148 const VRKey &vr = GetVR();
149 if( vr == "US" || vr == "SS" )
151 uint16_t *data = (uint16_t *)BinArea;
152 data[id] = (uint16_t)val;
154 else if( vr == "UL" || vr == "SL" )
156 uint32_t *data = (uint32_t *)BinArea;
157 data[id] = (uint32_t)val;
159 else if( vr == "FL" )
161 float *data = (float *)BinArea;
162 data[id] = (float)val;
164 else if( vr == "FD" )
166 double *data = (double *)BinArea;
167 data[id] = (double)val;
169 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
171 gdcmErrorMacro("SetValue on String representable not implemented yet");
175 BinArea[id] = (uint8_t)val;
179 * \brief returns, as a double one of the values
180 * (when entry is multivaluated), identified by its index.
181 * Returns 0.0 if index is wrong
184 double DataEntry::GetValue(const uint32_t &id) const
188 if (GetLength() != 0) // avoid stupid messages
189 /// \todo warn the user there was a problem !
190 gdcmErrorMacro("BinArea not set " << std::hex
191 << GetGroup() << " " << GetElement()
192 << " Can't get the value");
196 uint32_t count = GetValueCount();
199 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
203 // if user *knows* that entry contains a US,
204 // he just has to cast the double he receives
206 const VRKey &vr = GetVR();
208 if( vr == "US" || vr == "SS" )
209 return ((uint16_t *)BinArea)[id];
210 else if( vr == "UL" || vr == "SL" )
211 return ((uint32_t *)BinArea)[id];
212 else if( vr == "FL" )
213 return ((float *)BinArea)[id];
214 else if( vr == "FD" )
215 return ((double *)BinArea)[id];
216 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
218 // this is for VR = "DS", ...
221 // Don't use std::string to accelerate processing
223 char *tmp = new char[GetLength()+1];
224 memcpy(tmp,BinArea,GetLength());
235 for(uint32_t i=0;i<GetLength();i++)
265 * \brief Checks if the multiplicity of the value follows Dictionary VM
267 bool DataEntry::IsValueCountValid() /*const*/
270 const std::string &strVM = GetVM();
271 uint32_t vc = GetValueCount();
272 bool valid = vc == 0;
276 // FIXME : what shall we do with VM = "2-n", "3-n", etc
280 // make sure there is at least one ??? FIXME
285 std::istringstream os;
289 // vm respects the one from the dict
290 // vm is 0 (we need to check if this element is allowed to be empty) FIXME
294 // Entries whose type is 1 are mandatory, with a mandatory value.
295 // Entries whose type is 1c are mandatory-inside-a-Sequence,
296 // with a mandatory value.
297 // Entries whose type is 2 are mandatory, with an optional value.
298 // Entries whose type is 2c are mandatory-inside-a-Sequence,
299 // with an optional value.
300 // Entries whose type is 3 are optional.
302 // case vc == 0 is only applicable for 'type 2' entries.
303 // Problem : entry type may depend on the modality and/or the Sequence
304 // it's embedded in !
305 // (Get the information in the 'Conformance Statements' ...)
312 * \brief returns the number of elementary values
314 uint32_t DataEntry::GetValueCount( ) const
316 const VRKey &vr = GetVR();
317 if( vr == "US" || vr == "SS" )
318 return GetLength()/sizeof(uint16_t);
319 else if( vr == "UL" || vr == "SL" )
320 return GetLength()/sizeof(uint32_t);
321 else if( vr == "FL" || vr == "OF" )
322 return GetLength()/4 ; // FL has a *4* length! sizeof(float);
323 else if( vr == "FD" )
324 return GetLength()/8; // FD has a *8* length! sizeof(double);
325 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
327 // Some element in DICOM are allowed to be empty
330 // Don't use std::string to accelerate processing
332 for(uint32_t i=0;i<GetLength();i++)
334 if( BinArea[i] == '\\')
343 * \brief Gets a std::vector of 'double' holding the value(s) of a DS DataEntry
344 * @param valueVector std::vector double of value(s)
345 * \return false if VR not "DS" or DataEntry empty
347 bool DataEntry::GetDSValue(std::vector <double> &valueVector)
349 /// \todo rewrite the whole method, in order *not to use* std::string !
350 std::vector<std::string> tokens;
352 if (GetVR() != "DS") // never trust a user !
355 Util::Tokenize ( GetString().c_str(), tokens, "\\" );
357 int nbValues= tokens.size();
361 for (int loop=0; loop<nbValues; loop++)
362 valueVector.push_back(atof(tokens[loop].c_str()));
368 * \brief Sets the 'value' of a DataEntry, passed as a std::string
369 * @param value string representation of the value to be set
371 void DataEntry::SetString(std::string const &value)
374 const VRKey &vr = GetVR();
375 if ( vr == "US" || vr == "SS" )
377 std::vector<std::string> tokens;
378 Util::Tokenize (value, tokens, "\\");
379 SetLength(tokens.size()*sizeof(uint16_t));
382 uint16_t *data = (uint16_t *)BinArea;
383 for (unsigned int i=0; i<tokens.size();i++)
384 data[i] = atoi(tokens[i].c_str());
387 else if ( vr == "UL" || vr == "SL" )
389 std::vector<std::string> tokens;
390 Util::Tokenize (value, tokens, "\\");
391 SetLength(tokens.size()*sizeof(uint32_t));
394 uint32_t *data = (uint32_t *)BinArea;
395 for (unsigned int i=0; i<tokens.size();i++)
396 data[i] = atoi(tokens[i].c_str());
399 else if ( vr == "FL" )
401 std::vector<std::string> tokens;
402 Util::Tokenize (value, tokens, "\\");
403 SetLength(tokens.size()*sizeof(float));
406 float *data = (float *)BinArea;
407 for (unsigned int i=0; i<tokens.size();i++)
408 data[i] = (float)atof(tokens[i].c_str());
411 else if ( vr == "FD" )
413 std::vector<std::string> tokens;
414 Util::Tokenize (value, tokens, "\\");
415 SetLength(tokens.size()*sizeof(double));
418 double *data = (double *)BinArea;
419 for (unsigned int i=0; i<tokens.size();i++)
420 data[i] = atof(tokens[i].c_str());
425 size_t l = value.size();
428 memcpy(BinArea, value.c_str(), l);
429 if (l%2) // padded with blank except for UI
435 State = STATE_LOADED;
438 * \brief returns as a string (when possible) the value of the DataEntry
440 std::string const &DataEntry::GetString() const
442 static std::ostringstream s;
443 const VRKey &vr = GetVR();
447 StrArea = new std::string();
453 // When short integer(s) are stored, convert the following (n * 2) characters
454 // as a displayable string, the values being separated by a back-slash
457 uint16_t *data=(uint16_t *)BinArea;
458 for (unsigned int i=0; i < GetValueCount(); i++)
466 else if (vr == "SS" )
468 int16_t *data=(int16_t *)BinArea;
469 for (unsigned int i=0; i < GetValueCount(); i++)
476 } // See above comment on multiple short integers (mutatis mutandis).
477 else if( vr == "UL" )
479 uint32_t *data=(uint32_t *)BinArea;
480 for (unsigned int i=0; i < GetValueCount(); i++)
488 else if( vr == "SL" )
490 int32_t *data=(int32_t *)BinArea;
491 for (unsigned int i=0; i < GetValueCount(); i++)
498 } // See above comment on multiple short integers (mutatis mutandis).
499 else if( vr == "FL" )
501 float *data=(float *)BinArea;
502 for (unsigned int i=0; i < GetValueCount(); i++)
509 } // See above comment on multiple short integers (mutatis mutandis).
510 else if( vr == "FD" )
512 double *data=(double *)BinArea;
513 for (unsigned int i=0; i < GetValueCount(); i++)
523 StrArea->append((const char *)BinArea,GetLength());
524 // to avoid gdcm to propagate oddities in lengthes
526 StrArea->append(" ",1);
532 * \brief returns an hexadecimal representation of the DataEntry value
534 std::string const &DataEntry::GetHexaRepresentation() const
536 static std::ostringstream s2;
537 const VRKey &vr = GetVR();
541 StrHexaArea = new std::string();
546 // When short integer(s) are stored, convert the following (n * 2) characters
547 // 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++)
556 s2 << std::setw( 2 ) << std::setfill( '0' );
561 *StrHexaArea=s2.str();
563 else if (vr == "SS" )
565 int16_t *data=(int16_t *)BinArea;
566 for (unsigned int i=0; i < GetValueCount(); i++)
568 s2 << std::setw( 4 ) << std::setfill( '0' );
573 *StrHexaArea=s2.str();
574 } // See above comment on multiple short integers (mutatis mutandis).
575 else if( vr == "UL" )
577 uint32_t *data=(uint32_t *)BinArea;
578 for (unsigned int i=0; i < GetValueCount(); i++)
580 s2 << std::setw( 4 ) << std::setfill( '0' );
585 *StrHexaArea=s2.str();
587 else if( vr == "SL" )
589 int32_t *data=(int32_t *)BinArea;
590 for (unsigned int i=0; i < GetValueCount(); i++)
592 s2 << std::setw( 4 ) << std::setfill( '0' );
597 *StrHexaArea=s2.str();
599 else if( vr == "FL" )
601 unsigned char *toto=(unsigned char *)BinArea;
602 for (unsigned int i=0; i < GetValueCount(); i++)
608 for(int iif=0; iif<4; iif++)
614 *StrHexaArea=s2.str();
616 else if( vr == "FD" )
618 //double *data=(double *)BinArea;
619 unsigned char *toto=(unsigned char *)BinArea;
620 for (unsigned int i=0; i < GetValueCount(); i++)
628 for(int iid=0; iid<8; iid++)
635 *StrHexaArea=s2.str();
639 unsigned int l = (Length > GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA) ? GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA : Length;
640 uint8_t *data=(uint8_t *)BinArea;
641 for (unsigned int i=0; i < l; i++)
645 s2 << std::setw( 2 ) << (int)(data[i]);
649 *StrHexaArea=s2.str();
655 * \brief Copies all the attributes from an other DocEntry
656 * @param doc entry to copy from
657 * @remarks The content BinArea is copied too (StrArea is not)
659 void DataEntry::Copy(DocEntry *doc)
663 DataEntry *entry = dynamic_cast<DataEntry *>(doc);
666 State = entry->State;
668 CopyBinArea(entry->BinArea,entry->GetLength());
673 * \brief Writes the 'common part' + the 'value' area of a DataEntry
674 * @param fp already open ofstream pointer
675 * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
677 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype,
678 bool insideMetaElements, bool insideSequence)
680 // writes the 'common part'
681 DocEntry::WriteContent(fp, filetype, insideMetaElements, insideSequence);
683 if ( GetGroup() == 0xfffe )
685 return; //delimitors have NO value
688 // --> We only deal with Little Endian writting.
689 // --> forget Big Endian Transfer Syntax writting!
690 // Next DICOM version will give it up ...
692 // WARNING - For Implicit VR private element,
693 // we have *no choice* but considering them as
694 // something like 'OB' values.
695 // we rewrite them as we found them on disc.
696 // Some trouble will occur if element was
697 // *actually* OW, if image was produced
698 // on Big endian based processor, read and writen
699 // on Little endian based processor
700 // and, later on, somebody needs
701 // this 'OW' Implicit VR private element (?!?)
702 // (Same stuff, mutatis mutandis, for Little/Big)
704 // 8/16 bits Pixels problem should be solved automatiquely,
705 // since we ensure the VR (OB vs OW) is conform to Pixel size.
707 uint8_t *data = BinArea; //safe notation
708 size_t l = GetLength();
709 // gdcmDebugMacro("in DataEntry::WriteContent " << GetKey() << " AtomicLength: "
710 // << Global::GetVR()->GetAtomicElementLength(this->GetVR() ) // << " BinArea in :" << &BinArea
712 if (BinArea) // the binArea was *actually* loaded
714 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
715 unsigned short vrLgth =
716 Global::GetVR()->GetAtomicElementLength(this->GetVR());
722 binary_write (*fp, data, l );
727 uint16_t *data16 = (uint16_t *)data;
728 for(i=0;i<l/vrLgth;i++)
729 binary_write( *fp, data16[i]);
734 uint32_t *data32 = (uint32_t *)data;
735 for(i=0;i<l/vrLgth;i++)
736 binary_write( *fp, data32[i]);
741 double *data64 = (double *)data;
742 for(i=0;i<l/vrLgth;i++)
743 binary_write( *fp, data64[i]);
748 binary_write (*fp, data, l );
749 #endif //GDCM_WORDS_BIGENDIAN
754 // nothing was loaded, but we need to skip space on disc
757 // --> WARNING : nothing is written;
758 // --> the initial data (on the the source image) is lost
759 // --> user is *not* informed !
760 gdcmDebugMacro ("Nothing was loaded, but we need to skip space on disc. "
761 << "Length =" << l << " for " << GetKey() );
762 fp->seekp(l, std::ios::cur); // At Write time, for unloaded elems
765 // to avoid gdcm to propagate oddities
766 // (length was already modified)
768 fp->seekp(1, std::ios::cur); // At Write time, for non even length elems
772 * \brief Compute the full length of the elementary DataEntry (not only value
773 * length) depending on the VR.
775 uint32_t DataEntry::ComputeFullLength()
777 return GetFullLength();
780 //-----------------------------------------------------------------------------
783 /// \brief Creates a DataEntry owned BinArea
784 /// (remove previous one if any and relevant StrArea if any)
785 void DataEntry::NewBinArea( )
788 if( GetLength() > 0 )
789 BinArea = new uint8_t[GetLength()];
792 /// \brief Removes the BinArea, if owned by the DataEntry,
793 /// and the relevant StrArea if any
794 void DataEntry::DeleteBinArea(void)
796 if (BinArea && SelfArea)
813 //-----------------------------------------------------------------------------
816 //-----------------------------------------------------------------------------
819 * \brief Prints a DataEntry (Dicom entry)
820 * @param os ostream we want to print in
821 * @param indent Indentation string to be prepended during printing
823 void DataEntry::Print(std::ostream &os, std::string const & )
827 // First, Print the common part (vr [length offset] name).
830 uint16_t g = GetGroup();
831 if (g == 0xfffe) // delimiters have NO value
833 return; // just to avoid identing all the remaining code
836 std::ostringstream s;
842 const VRKey &vr = GetVR();
844 if( vr == "US" || vr == "SS" || vr == "UL" || vr == "SL"
845 || vr == "FL" || vr == "FD")
846 s << " [" << GetString() << "] =0x(" << GetHexaRepresentation() << ")";
849 if(Global::GetVR()->IsVROfStringRepresentable(vr))
851 // replace non printable characters by '.'
852 std::string cleanString = Util::CreateCleanString(v);
853 if ( cleanString.length() <= GetMaxSizePrintEntry()
856 // FIXME : when IsNotLoaded(), you create a Clean String ?!?
857 // FIXME : PrintLevel<2 *does* print the values
858 // (3 is only for extra offsets printing)
859 // What do you wanted to do ? JPR
861 s << " [" << cleanString << "]";
865 s << " [GDCM_NAME_SPACE::too long for print (" << cleanString.length() << ") ]";
870 // A lot of Private elements (with no VR) contain actually
871 // only printable characters;
872 // Let's deal with them as is they were VR std::string representable
874 if ( Util::IsCleanArea( GetBinArea(), GetLength() ) )
876 // FIXME : since the 'Area' *is* clean, just use
877 // a 'CreateString' method, to save CPU time.
878 std::string cleanString =
879 Util::CreateCleanString( BinArea,GetLength() );
880 s << " [" << cleanString << "]";
884 s << " [" << GDCM_BINLOADED << ";"
885 << "length = " << GetLength() << "] =0x(" << GetHexaRepresentation() << ")";
893 s << " [" << GDCM_NOTLOADED << "]";
894 else if( IsUnfound() )
895 s << " [" << GDCM_UNFOUND << "]";
896 else if( IsUnread() )
897 s << " [" << GDCM_UNREAD << "]";
898 else if ( GetLength() == 0 )
903 s << " (" << GDCM_PIXELDATA << ")";
905 // Display the UID value (instead of displaying only the rough code)
906 // First 'clean' trailing character (space or zero)
909 const uint16_t &gr = GetGroup();
910 const uint16_t &elt = GetElement();
911 TS *ts = Global::GetTS();
915 // Any more to be displayed ?
916 if ( elt == 0x0010 || elt == 0x0002 )
918 if ( v.length() != 0 ) // for brain damaged headers
920 if ( ! isdigit((unsigned char)v[v.length()-1]) )
922 v.erase(v.length()-1, 1);
925 s << " ==>\t[" << ts->GetValue(v) << "]";
928 else if (gr == 0x0008)
930 if ( elt == 0x0016 || elt == 0x1150 )
932 if ( v.length() != 0 ) // for brain damaged headers
934 if ( ! isdigit((unsigned char)v[v.length()-1]) )
936 v.erase(v.length()-1, 1);
939 s << " ==>\t[" << ts->GetValue(v) << "]";
942 else if (gr == 0x0004)
944 if ( elt == 0x1510 || elt == 0x1512 )
946 if ( v.length() != 0 ) // for brain damaged headers
948 if ( ! isdigit((unsigned char)v[v.length()-1]) )
950 v.erase(v.length()-1, 1);
953 s << " ==>\t[" << ts->GetValue(v) << "]";
961 //-----------------------------------------------------------------------------
962 } // end namespace gdcm