1 /*=========================================================================
4 Module: $RCSfile: gdcmDataEntry.cxx,v $
6 Date: $Date: 2006/07/10 08:27:27 $
7 Version: $Revision: 1.41 $
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
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 //-----------------------------------------------------------------------------
91 * \brief Sets the value (non string) of the current 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);
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 /// \todo FIX the API : user *knows* that entry contains a US
200 /// and he receives a double ?!?
202 const VRKey &vr = GetVR();
203 /// \todo FIX the API : user *knows* that entry contains a US,
204 /// the method is supposed to return a double
205 /// but sends a US ?!?
206 if( vr == "US" || vr == "SS" )
207 return ((uint16_t *)BinArea)[id];
208 else if( vr == "UL" || vr == "SL" )
209 return ((uint32_t *)BinArea)[id];
210 else if( vr == "FL" )
211 return ((float *)BinArea)[id];
212 else if( vr == "FD" )
213 return ((double *)BinArea)[id];
214 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
216 // this is for VR = "DS", ...
219 // Don't use std::string to accelerate processing
221 char *tmp = new char[GetLength()+1];
222 memcpy(tmp,BinArea,GetLength());
233 for(uint32_t i=0;i<GetLength();i++)
263 * \brief Checks if the multiplicity of the value follows Dictionary VM
265 bool DataEntry::IsValueCountValid() /*const*/
268 const std::string &strVM = GetVM();
269 uint32_t vc = GetValueCount();
270 bool valid = vc == 0;
274 // FIXME : what shall we do with VM = "2-n", "3-n", etc
278 // make sure there is at least one ??? FIXME
283 std::istringstream os;
287 // vm respects the one from the dict
288 // vm is 0 (we need to check if this element is allowed to be empty) FIXME
292 // Entries whose type is 1 are mandatory, with a mandatory value.
293 // Entries whose type is 1c are mandatory-inside-a-Sequence,
294 // with a mandatory value.
295 // Entries whose type is 2 are mandatory, with an optional value.
296 // Entries whose type is 2c are mandatory-inside-a-Sequence,
297 // with an optional value.
298 // Entries whose type is 3 are optional.
300 // case vc == 0 is only applicable for 'type 2' entries.
301 // Problem : entry type may depend on the modality and/or the Sequence
302 // it's embedded in !
303 // (Get the information in the 'Conformance Statements' ...)
310 * \brief returns the number of elementary values
312 uint32_t DataEntry::GetValueCount( ) const
314 const VRKey &vr = GetVR();
315 if( vr == "US" || vr == "SS" )
316 return GetLength()/sizeof(uint16_t);
317 else if( vr == "UL" || vr == "SL" )
318 return GetLength()/sizeof(uint32_t);
319 else if( vr == "FL" || vr == "OF" )
320 return GetLength()/4 ; // FL has a *4* length! sizeof(float);
321 else if( vr == "FD" )
322 return GetLength()/8; // FD has a *8* length! sizeof(double);
323 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
325 // Some element in DICOM are allowed to be empty
328 // Don't use std::string to accelerate processing
330 for(uint32_t i=0;i<GetLength();i++)
332 if( BinArea[i] == '\\')
341 * \brief Gets a std::vector <double> holding the value(s) of a DS DataEntry
342 * @param valueVector std::vector double of value(s)
343 * \return false if VR not "DS" or DataEntry empty
345 bool DataEntry::GetDSValue(std::vector <double> &valueVector)
347 /// \todo rewrite the whole method, in order *not to use* std::string !
348 std::vector<std::string> tokens;
350 if (GetVR() != "DS") // never trust a user !
353 Util::Tokenize ( GetString().c_str(), tokens, "\\" );
355 int nbValues= tokens.size();
359 for (int loop=0; loop<nbValues; loop++)
360 valueVector.push_back(atof(tokens[loop].c_str()));
366 * \brief Sets the 'value' of a DataEntry, passed as a std::string
367 * @param value string representation of the value to be set
369 void DataEntry::SetString(std::string const &value)
372 const VRKey &vr = GetVR();
373 if ( vr == "US" || vr == "SS" )
375 std::vector<std::string> tokens;
376 Util::Tokenize (value, tokens, "\\");
377 SetLength(tokens.size()*sizeof(uint16_t));
380 uint16_t *data = (uint16_t *)BinArea;
381 for (unsigned int i=0; i<tokens.size();i++)
382 data[i] = atoi(tokens[i].c_str());
385 else if ( vr == "UL" || vr == "SL" )
387 std::vector<std::string> tokens;
388 Util::Tokenize (value, tokens, "\\");
389 SetLength(tokens.size()*sizeof(uint32_t));
392 uint32_t *data = (uint32_t *)BinArea;
393 for (unsigned int i=0; i<tokens.size();i++)
394 data[i] = atoi(tokens[i].c_str());
397 else if ( vr == "FL" )
399 std::vector<std::string> tokens;
400 Util::Tokenize (value, tokens, "\\");
401 SetLength(tokens.size()*sizeof(float));
404 float *data = (float *)BinArea;
405 for (unsigned int i=0; i<tokens.size();i++)
406 data[i] = (float)atof(tokens[i].c_str());
409 else if ( vr == "FD" )
411 std::vector<std::string> tokens;
412 Util::Tokenize (value, tokens, "\\");
413 SetLength(tokens.size()*sizeof(double));
416 double *data = (double *)BinArea;
417 for (unsigned int i=0; i<tokens.size();i++)
418 data[i] = atof(tokens[i].c_str());
423 size_t l = value.size();
426 memcpy(BinArea, value.c_str(), l);
427 if (l%2) // padded with blank except for UI
433 State = STATE_LOADED;
436 * \brief returns as a string (when possible) the value of the DataEntry
438 std::string const &DataEntry::GetString() const
440 static std::ostringstream s;
441 const VRKey &vr = GetVR();
445 StrArea = new std::string();
451 // When short integer(s) are stored, convert the following (n * 2) characters
452 // as a displayable string, the values being separated by a back-slash
455 uint16_t *data=(uint16_t *)BinArea;
456 for (unsigned int i=0; i < GetValueCount(); i++)
464 else if (vr == "SS" )
466 int16_t *data=(int16_t *)BinArea;
467 for (unsigned int i=0; i < GetValueCount(); i++)
474 } // See above comment on multiple short integers (mutatis mutandis).
475 else if( vr == "UL" )
477 uint32_t *data=(uint32_t *)BinArea;
478 for (unsigned int i=0; i < GetValueCount(); i++)
486 else if( vr == "SL" )
488 int32_t *data=(int32_t *)BinArea;
489 for (unsigned int i=0; i < GetValueCount(); i++)
496 } else if( vr == "FL" )
498 float *data=(float *)BinArea;
499 for (unsigned int i=0; i < GetValueCount(); i++)
507 else if( vr == "FD" )
509 double *data=(double *)BinArea;
510 for (unsigned int i=0; i < GetValueCount(); i++)
520 StrArea->append((const char *)BinArea,GetLength());
521 // to avoid gdcm to propagate oddities in lengthes
523 StrArea->append(" ",1); }
529 * \brief Copies all the attributes from an other DocEntry
530 * @param doc entry to copy from
531 * @remarks The content BinArea is copied too (StrArea is not)
533 void DataEntry::Copy(DocEntry *doc)
537 DataEntry *entry = dynamic_cast<DataEntry *>(doc);
540 State = entry->State;
542 CopyBinArea(entry->BinArea,entry->GetLength());
547 * \brief Writes the 'value' area of a DataEntry
548 * @param fp already open ofstream pointer
549 * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
551 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype)
553 DocEntry::WriteContent(fp, filetype);
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 //-----------------------------------------------------------------------------
654 /// \brief Creates a DataEntry owned BinArea
655 /// (remove previous one if any and relevant StrArea if any)
656 void DataEntry::NewBinArea( )
659 if( GetLength() > 0 )
660 BinArea = new uint8_t[GetLength()];
663 /// \brief Removes the BinArea, if owned by the DataEntry,
664 /// and the relevant StrArea if any
665 void DataEntry::DeleteBinArea(void)
667 if (BinArea && SelfArea)
679 //-----------------------------------------------------------------------------
682 //-----------------------------------------------------------------------------
685 * \brief Prints a DataEntry (Dicom entry)
686 * @param os ostream we want to print in
687 * @param indent Indentation string to be prepended during printing
689 void DataEntry::Print(std::ostream &os, std::string const & )
694 uint16_t g = GetGroup();
695 if (g == 0xfffe) // delimiters have NO value
697 return; // just to avoid identing all the remaining code
700 std::ostringstream s;
706 const VRKey &vr = GetVR();
708 if( vr == "US" || vr == "SS" || vr == "UL" || vr == "SL"
709 || vr == "FL" || vr == "FD")
710 s << " [" << GetString() << "]";
713 if(Global::GetVR()->IsVROfStringRepresentable(vr))
715 // replace non printable characters by '.'
716 std::string cleanString = Util::CreateCleanString(v);
717 if ( cleanString.length() <= GetMaxSizePrintEntry()
720 // FIXME : when IsNotLoaded(), you create a Clean String ?!?
721 // FIXME : PrintLevel<2 *does* print the values
722 // (3 is only for extra offsets printing)
723 // What do you wanted to do ? JPR
725 s << " [" << cleanString << "]";
729 s << " [gdcm::too long for print (" << cleanString.length() << ") ]";
734 // A lot of Private elements (with no VR) contain actually
735 // only printable characters;
736 // Let's deal with them as is they were VR std::string representable
738 if ( Util::IsCleanArea( GetBinArea(), GetLength() ) )
740 // FIXME : since the 'Area' *is* clean, just use
741 // a 'CreateString' method, to save CPU time.
742 std::string cleanString =
743 Util::CreateCleanString( BinArea,GetLength() );
744 s << " [" << cleanString << "]";
748 s << " [" << GDCM_BINLOADED << ";"
749 << "length = " << GetLength() << "]";
757 s << " [" << GDCM_NOTLOADED << "]";
758 else if( IsUnfound() )
759 s << " [" << GDCM_UNFOUND << "]";
760 else if( IsUnread() )
761 s << " [" << GDCM_UNREAD << "]";
762 else if ( GetLength() == 0 )
767 s << " (" << GDCM_PIXELDATA << ")";
769 // Display the UID value (instead of displaying only the rough code)
770 // First 'clean' trailing character (space or zero)
773 const uint16_t &gr = GetGroup();
774 const uint16_t &elt = GetElement();
775 TS *ts = Global::GetTS();
779 // Any more to be displayed ?
780 if ( elt == 0x0010 || elt == 0x0002 )
782 if ( v.length() != 0 ) // for brain damaged headers
784 if ( ! isdigit((unsigned char)v[v.length()-1]) )
786 v.erase(v.length()-1, 1);
789 s << " ==>\t[" << ts->GetValue(v) << "]";
792 else if (gr == 0x0008)
794 if ( elt == 0x0016 || elt == 0x1150 )
796 if ( v.length() != 0 ) // for brain damaged headers
798 if ( ! isdigit((unsigned char)v[v.length()-1]) )
800 v.erase(v.length()-1, 1);
803 s << " ==>\t[" << ts->GetValue(v) << "]";
806 else if (gr == 0x0004)
808 if ( elt == 0x1510 || elt == 0x1512 )
810 if ( v.length() != 0 ) // for brain damaged headers
812 if ( ! isdigit((unsigned char)v[v.length()-1]) )
814 v.erase(v.length()-1, 1);
817 s << " ==>\t[" << ts->GetValue(v) << "]";
825 //-----------------------------------------------------------------------------
826 } // end namespace gdcm