1 /*=========================================================================
4 Module: $RCSfile: gdcmDataEntry.cxx,v $
6 Date: $Date: 2007/10/30 09:14:41 $
7 Version: $Revision: 1.51 $
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 float *data=(float *)BinArea;
602 for (unsigned int i=0; i < GetValueCount(); i++)
604 s2 << std::setw( 4 ) << std::setfill( '0' );
609 *StrHexaArea=s2.str();
611 else if( vr == "FD" )
613 double *data=(double *)BinArea;
614 for (unsigned int i=0; i < GetValueCount(); i++)
616 s2 << std::setw( 8 ) << std::setfill( '0' );
621 *StrHexaArea=s2.str();
625 unsigned int l = (Length > GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA) ? GDCM_MAX_LENGTH_TO_CONVERT_TO_HEXA : Length;
626 uint8_t *data=(uint8_t *)BinArea;
627 for (unsigned int i=0; i < l; i++)
631 s2 << std::setw( 2 ) << (int)(data[i]);
635 *StrHexaArea=s2.str();
641 * \brief Copies all the attributes from an other DocEntry
642 * @param doc entry to copy from
643 * @remarks The content BinArea is copied too (StrArea is not)
645 void DataEntry::Copy(DocEntry *doc)
649 DataEntry *entry = dynamic_cast<DataEntry *>(doc);
652 State = entry->State;
654 CopyBinArea(entry->BinArea,entry->GetLength());
659 * \brief Writes the 'common part' + the 'value' area of a DataEntry
660 * @param fp already open ofstream pointer
661 * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
663 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype,
664 bool insideMetaElements, bool insideSequence)
666 // writes the 'common part'
667 DocEntry::WriteContent(fp, filetype, insideMetaElements, insideSequence);
669 if ( GetGroup() == 0xfffe )
671 return; //delimitors have NO value
674 // --> We only deal with Little Endian writting.
675 // --> forget Big Endian Transfer Syntax writting!
676 // Next DICOM version will give it up ...
678 // WARNING - For Implicit VR private element,
679 // we have *no choice* but considering them as
680 // something like 'OB' values.
681 // we rewrite them as we found them on disc.
682 // Some trouble will occur if element was
683 // *actually* OW, if image was produced
684 // on Big endian based processor, read and writen
685 // on Little endian based processor
686 // and, later on, somebody needs
687 // this 'OW' Implicit VR private element (?!?)
688 // (Same stuff, mutatis mutandis, for Little/Big)
690 // 8/16 bits Pixels problem should be solved automatiquely,
691 // since we ensure the VR (OB vs OW) is conform to Pixel size.
693 uint8_t *data = BinArea; //safe notation
694 size_t l = GetLength();
695 // gdcmDebugMacro("in DataEntry::WriteContent " << GetKey() << " AtomicLength: "
696 // << Global::GetVR()->GetAtomicElementLength(this->GetVR() ) // << " BinArea in :" << &BinArea
698 if (BinArea) // the binArea was *actually* loaded
700 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
701 unsigned short vrLgth =
702 Global::GetVR()->GetAtomicElementLength(this->GetVR());
708 binary_write (*fp, data, l );
713 uint16_t *data16 = (uint16_t *)data;
714 for(i=0;i<l/vrLgth;i++)
715 binary_write( *fp, data16[i]);
720 uint32_t *data32 = (uint32_t *)data;
721 for(i=0;i<l/vrLgth;i++)
722 binary_write( *fp, data32[i]);
727 double *data64 = (double *)data;
728 for(i=0;i<l/vrLgth;i++)
729 binary_write( *fp, data64[i]);
734 binary_write (*fp, data, l );
735 #endif //GDCM_WORDS_BIGENDIAN
740 // nothing was loaded, but we need to skip space on disc
743 // --> WARNING : nothing is written;
744 // --> the initial data (on the the source image) is lost
745 // --> user is *not* informed !
746 gdcmDebugMacro ("Nothing was loaded, but we need to skip space on disc. "
747 << "Length =" << l << " for " << GetKey() );
748 fp->seekp(l, std::ios::cur); // At Write time, for unloaded elems
751 // to avoid gdcm to propagate oddities
752 // (length was already modified)
754 fp->seekp(1, std::ios::cur); // At Write time, for non even length elems
758 * \brief Compute the full length of the elementary DataEntry (not only value
759 * length) depending on the VR.
761 uint32_t DataEntry::ComputeFullLength()
763 return GetFullLength();
766 //-----------------------------------------------------------------------------
769 /// \brief Creates a DataEntry owned BinArea
770 /// (remove previous one if any and relevant StrArea if any)
771 void DataEntry::NewBinArea( )
774 if( GetLength() > 0 )
775 BinArea = new uint8_t[GetLength()];
778 /// \brief Removes the BinArea, if owned by the DataEntry,
779 /// and the relevant StrArea if any
780 void DataEntry::DeleteBinArea(void)
782 if (BinArea && SelfArea)
799 //-----------------------------------------------------------------------------
802 //-----------------------------------------------------------------------------
805 * \brief Prints a DataEntry (Dicom entry)
806 * @param os ostream we want to print in
807 * @param indent Indentation string to be prepended during printing
809 void DataEntry::Print(std::ostream &os, std::string const & )
813 // First, Print the common part (vr [length offset] name).
816 uint16_t g = GetGroup();
817 if (g == 0xfffe) // delimiters have NO value
819 return; // just to avoid identing all the remaining code
822 std::ostringstream s;
828 const VRKey &vr = GetVR();
830 if( vr == "US" || vr == "SS" || vr == "UL" || vr == "SL"
831 || vr == "FL" || vr == "FD")
832 s << " [" << GetString() << "] =0x(" << GetHexaRepresentation() << ")";
835 if(Global::GetVR()->IsVROfStringRepresentable(vr))
837 // replace non printable characters by '.'
838 std::string cleanString = Util::CreateCleanString(v);
839 if ( cleanString.length() <= GetMaxSizePrintEntry()
842 // FIXME : when IsNotLoaded(), you create a Clean String ?!?
843 // FIXME : PrintLevel<2 *does* print the values
844 // (3 is only for extra offsets printing)
845 // What do you wanted to do ? JPR
847 s << " [" << cleanString << "]";
851 s << " [GDCM_NAME_SPACE::too long for print (" << cleanString.length() << ") ]";
856 // A lot of Private elements (with no VR) contain actually
857 // only printable characters;
858 // Let's deal with them as is they were VR std::string representable
860 if ( Util::IsCleanArea( GetBinArea(), GetLength() ) )
862 // FIXME : since the 'Area' *is* clean, just use
863 // a 'CreateString' method, to save CPU time.
864 std::string cleanString =
865 Util::CreateCleanString( BinArea,GetLength() );
866 s << " [" << cleanString << "]";
870 s << " [" << GDCM_BINLOADED << ";"
871 << "length = " << GetLength() << "] =0x(" << GetHexaRepresentation() << ")";
879 s << " [" << GDCM_NOTLOADED << "]";
880 else if( IsUnfound() )
881 s << " [" << GDCM_UNFOUND << "]";
882 else if( IsUnread() )
883 s << " [" << GDCM_UNREAD << "]";
884 else if ( GetLength() == 0 )
889 s << " (" << GDCM_PIXELDATA << ")";
891 // Display the UID value (instead of displaying only the rough code)
892 // First 'clean' trailing character (space or zero)
895 const uint16_t &gr = GetGroup();
896 const uint16_t &elt = GetElement();
897 TS *ts = Global::GetTS();
901 // Any more to be displayed ?
902 if ( elt == 0x0010 || elt == 0x0002 )
904 if ( v.length() != 0 ) // for brain damaged headers
906 if ( ! isdigit((unsigned char)v[v.length()-1]) )
908 v.erase(v.length()-1, 1);
911 s << " ==>\t[" << ts->GetValue(v) << "]";
914 else if (gr == 0x0008)
916 if ( elt == 0x0016 || elt == 0x1150 )
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 == 0x0004)
930 if ( elt == 0x1510 || elt == 0x1512 )
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) << "]";
947 //-----------------------------------------------------------------------------
948 } // end namespace gdcm