1 /*=========================================================================
4 Module: $RCSfile: gdcmDataEntry.cxx,v $
6 Date: $Date: 2007/08/29 15:30:48 $
7 Version: $Revision: 1.47 $
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 namespace GDCM_NAME_SPACE
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
93 * @param self self=true : The area : *belongs" to the DataEntry
94 * : will be delete with the DataEntry
95 * self=false The area *is not* deleted with the DataEntry
98 void DataEntry::SetBinArea( uint8_t *area, bool self )
105 State = STATE_LOADED;
108 * \brief Inserts the value (non string) into the current DataEntry
110 * @param length length
112 void DataEntry::CopyBinArea( uint8_t *area, uint32_t length )
116 uint32_t lgh = length + length%2;
119 if( area && length > 0 )
122 memcpy(BinArea,area,length);
124 BinArea[length]=0; // padd with zero
126 State = STATE_LOADED;
131 * \brief Inserts the elementary (non string) value into the current DataEntry
132 * @param id index of the elementary value to be set
133 * @param val value, passed as a double
135 void DataEntry::SetValue(const uint32_t &id, const double &val)
139 State = STATE_LOADED;
141 if( id > GetValueCount() )
143 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
147 const VRKey &vr = GetVR();
148 if( vr == "US" || vr == "SS" )
150 uint16_t *data = (uint16_t *)BinArea;
151 data[id] = (uint16_t)val;
153 else if( vr == "UL" || vr == "SL" )
155 uint32_t *data = (uint32_t *)BinArea;
156 data[id] = (uint32_t)val;
158 else if( vr == "FL" )
160 float *data = (float *)BinArea;
161 data[id] = (float)val;
163 else if( vr == "FD" )
165 double *data = (double *)BinArea;
166 data[id] = (double)val;
168 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
170 gdcmErrorMacro("SetValue on String representable not implemented yet");
174 BinArea[id] = (uint8_t)val;
178 * \brief returns, as a double one of the values
179 * (when entry is multivaluated), identified by its index.
180 * Returns 0.0 if index is wrong
183 double DataEntry::GetValue(const uint32_t &id) const
187 if (GetLength() != 0) // avoid stupid messages
188 /// \todo warn the user there was a problem !
189 gdcmErrorMacro("BinArea not set " << std::hex
190 << GetGroup() << " " << GetElement()
191 << " Can't get the value");
195 uint32_t count = GetValueCount();
198 gdcmErrorMacro("Index (" << id << ") is greater than the data size");
202 // if user *knows* that entry contains a US,
203 // he just has to cast the double he receives
205 const VRKey &vr = GetVR();
207 if( vr == "US" || vr == "SS" )
208 return ((uint16_t *)BinArea)[id];
209 else if( vr == "UL" || vr == "SL" )
210 return ((uint32_t *)BinArea)[id];
211 else if( vr == "FL" )
212 return ((float *)BinArea)[id];
213 else if( vr == "FD" )
214 return ((double *)BinArea)[id];
215 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
217 // this is for VR = "DS", ...
220 // Don't use std::string to accelerate processing
222 char *tmp = new char[GetLength()+1];
223 memcpy(tmp,BinArea,GetLength());
234 for(uint32_t i=0;i<GetLength();i++)
264 * \brief Checks if the multiplicity of the value follows Dictionary VM
266 bool DataEntry::IsValueCountValid() /*const*/
269 const std::string &strVM = GetVM();
270 uint32_t vc = GetValueCount();
271 bool valid = vc == 0;
275 // FIXME : what shall we do with VM = "2-n", "3-n", etc
279 // make sure there is at least one ??? FIXME
284 std::istringstream os;
288 // vm respects the one from the dict
289 // vm is 0 (we need to check if this element is allowed to be empty) FIXME
293 // Entries whose type is 1 are mandatory, with a mandatory value.
294 // Entries whose type is 1c are mandatory-inside-a-Sequence,
295 // with a mandatory value.
296 // Entries whose type is 2 are mandatory, with an optional value.
297 // Entries whose type is 2c are mandatory-inside-a-Sequence,
298 // with an optional value.
299 // Entries whose type is 3 are optional.
301 // case vc == 0 is only applicable for 'type 2' entries.
302 // Problem : entry type may depend on the modality and/or the Sequence
303 // it's embedded in !
304 // (Get the information in the 'Conformance Statements' ...)
311 * \brief returns the number of elementary values
313 uint32_t DataEntry::GetValueCount( ) const
315 const VRKey &vr = GetVR();
316 if( vr == "US" || vr == "SS" )
317 return GetLength()/sizeof(uint16_t);
318 else if( vr == "UL" || vr == "SL" )
319 return GetLength()/sizeof(uint32_t);
320 else if( vr == "FL" || vr == "OF" )
321 return GetLength()/4 ; // FL has a *4* length! sizeof(float);
322 else if( vr == "FD" )
323 return GetLength()/8; // FD has a *8* length! sizeof(double);
324 else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
326 // Some element in DICOM are allowed to be empty
329 // Don't use std::string to accelerate processing
331 for(uint32_t i=0;i<GetLength();i++)
333 if( BinArea[i] == '\\')
342 * \brief Gets a std::vector of 'double' holding the value(s) of a DS DataEntry
343 * @param valueVector std::vector double of value(s)
344 * \return false if VR not "DS" or DataEntry empty
346 bool DataEntry::GetDSValue(std::vector <double> &valueVector)
348 /// \todo rewrite the whole method, in order *not to use* std::string !
349 std::vector<std::string> tokens;
351 if (GetVR() != "DS") // never trust a user !
354 Util::Tokenize ( GetString().c_str(), tokens, "\\" );
356 int nbValues= tokens.size();
360 for (int loop=0; loop<nbValues; loop++)
361 valueVector.push_back(atof(tokens[loop].c_str()));
367 * \brief Sets the 'value' of a DataEntry, passed as a std::string
368 * @param value string representation of the value to be set
370 void DataEntry::SetString(std::string const &value)
373 const VRKey &vr = GetVR();
374 if ( vr == "US" || vr == "SS" )
376 std::vector<std::string> tokens;
377 Util::Tokenize (value, tokens, "\\");
378 SetLength(tokens.size()*sizeof(uint16_t));
381 uint16_t *data = (uint16_t *)BinArea;
382 for (unsigned int i=0; i<tokens.size();i++)
383 data[i] = atoi(tokens[i].c_str());
386 else if ( vr == "UL" || vr == "SL" )
388 std::vector<std::string> tokens;
389 Util::Tokenize (value, tokens, "\\");
390 SetLength(tokens.size()*sizeof(uint32_t));
393 uint32_t *data = (uint32_t *)BinArea;
394 for (unsigned int i=0; i<tokens.size();i++)
395 data[i] = atoi(tokens[i].c_str());
398 else if ( vr == "FL" )
400 std::vector<std::string> tokens;
401 Util::Tokenize (value, tokens, "\\");
402 SetLength(tokens.size()*sizeof(float));
405 float *data = (float *)BinArea;
406 for (unsigned int i=0; i<tokens.size();i++)
407 data[i] = (float)atof(tokens[i].c_str());
410 else if ( vr == "FD" )
412 std::vector<std::string> tokens;
413 Util::Tokenize (value, tokens, "\\");
414 SetLength(tokens.size()*sizeof(double));
417 double *data = (double *)BinArea;
418 for (unsigned int i=0; i<tokens.size();i++)
419 data[i] = atof(tokens[i].c_str());
424 size_t l = value.size();
427 memcpy(BinArea, value.c_str(), l);
428 if (l%2) // padded with blank except for UI
434 State = STATE_LOADED;
437 * \brief returns as a string (when possible) the value of the DataEntry
439 std::string const &DataEntry::GetString() const
441 static std::ostringstream s;
442 const VRKey &vr = GetVR();
446 StrArea = new std::string();
452 // When short integer(s) are stored, convert the following (n * 2) characters
453 // as a displayable string, the values being separated by a back-slash
456 uint16_t *data=(uint16_t *)BinArea;
457 for (unsigned int i=0; i < GetValueCount(); i++)
465 else if (vr == "SS" )
467 int16_t *data=(int16_t *)BinArea;
468 for (unsigned int i=0; i < GetValueCount(); i++)
475 } // See above comment on multiple short integers (mutatis mutandis).
476 else if( vr == "UL" )
478 uint32_t *data=(uint32_t *)BinArea;
479 for (unsigned int i=0; i < GetValueCount(); i++)
487 else if( vr == "SL" )
489 int32_t *data=(int32_t *)BinArea;
490 for (unsigned int i=0; i < GetValueCount(); i++)
497 } else if( vr == "FL" )
499 float *data=(float *)BinArea;
500 for (unsigned int i=0; i < GetValueCount(); i++)
508 else if( vr == "FD" )
510 double *data=(double *)BinArea;
511 for (unsigned int i=0; i < GetValueCount(); i++)
521 StrArea->append((const char *)BinArea,GetLength());
522 // to avoid gdcm to propagate oddities in lengthes
524 StrArea->append(" ",1); }
530 * \brief Copies all the attributes from an other DocEntry
531 * @param doc entry to copy from
532 * @remarks The content BinArea is copied too (StrArea is not)
534 void DataEntry::Copy(DocEntry *doc)
538 DataEntry *entry = dynamic_cast<DataEntry *>(doc);
541 State = entry->State;
543 CopyBinArea(entry->BinArea,entry->GetLength());
548 * \brief Writes the 'common part' + the 'value' area of a DataEntry
549 * @param fp already open ofstream pointer
550 * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
552 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype,
553 bool insideMetaElements, bool insideSequence)
555 // writes the 'common part'
556 DocEntry::WriteContent(fp, filetype, insideMetaElements, insideSequence);
558 if ( GetGroup() == 0xfffe )
560 return; //delimitors have NO value
563 // --> We only deal with Little Endian writting.
564 // --> forget Big Endian Transfer Syntax writting!
565 // Next DICOM version will give it up ...
567 // WARNING - For Implicit VR private element,
568 // we have *no choice* but considering them as
569 // something like 'OB' values.
570 // we rewrite them as we found them on disc.
571 // Some trouble will occur if element was
572 // *actually* OW, if image was produced
573 // on Big endian based processor, read and writen
574 // on Little endian based processor
575 // and, later on, somebody needs
576 // this 'OW' Implicit VR private element (?!?)
577 // (Same stuff, mutatis mutandis, for Little/Big)
579 // 8/16 bits Pixels problem should be solved automatiquely,
580 // since we ensure the VR (OB vs OW) is conform to Pixel size.
582 uint8_t *data = BinArea; //safe notation
583 size_t l = GetLength();
584 // gdcmDebugMacro("in DataEntry::WriteContent " << GetKey() << " AtomicLength: "
585 // << Global::GetVR()->GetAtomicElementLength(this->GetVR() ) // << " BinArea in :" << &BinArea
587 if (BinArea) // the binArea was *actually* loaded
589 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
590 unsigned short vrLgth =
591 Global::GetVR()->GetAtomicElementLength(this->GetVR());
597 binary_write (*fp, data, l );
602 uint16_t *data16 = (uint16_t *)data;
603 for(i=0;i<l/vrLgth;i++)
604 binary_write( *fp, data16[i]);
609 uint32_t *data32 = (uint32_t *)data;
610 for(i=0;i<l/vrLgth;i++)
611 binary_write( *fp, data32[i]);
616 double *data64 = (double *)data;
617 for(i=0;i<l/vrLgth;i++)
618 binary_write( *fp, data64[i]);
623 binary_write (*fp, data, l );
624 #endif //GDCM_WORDS_BIGENDIAN
629 // nothing was loaded, but we need to skip space on disc
632 // --> WARNING : nothing is written;
633 // --> the initial data (on the the source image) is lost
634 // --> user is *not* informed !
635 gdcmDebugMacro ("Nothing was loaded, but we need to skip space on disc. "
636 << "Length =" << l << " for " << GetKey() );
637 fp->seekp(l, std::ios::cur); // At Write time, for unloaded elems
640 // to avoid gdcm to propagate oddities
641 // (length was already modified)
643 fp->seekp(1, std::ios::cur); // At Write time, for non even length elems
647 * \brief Compute the full length of the elementary DataEntry (not only value
648 * length) depending on the VR.
650 uint32_t DataEntry::ComputeFullLength()
652 return GetFullLength();
655 //-----------------------------------------------------------------------------
657 /// \brief Creates a DataEntry owned BinArea
658 /// (remove previous one if any and relevant StrArea if any)
659 void DataEntry::NewBinArea( )
662 if( GetLength() > 0 )
663 BinArea = new uint8_t[GetLength()];
666 /// \brief Removes the BinArea, if owned by the DataEntry,
667 /// and the relevant StrArea if any
668 void DataEntry::DeleteBinArea(void)
670 if (BinArea && SelfArea)
682 //-----------------------------------------------------------------------------
685 //-----------------------------------------------------------------------------
688 * \brief Prints a DataEntry (Dicom entry)
689 * @param os ostream we want to print in
690 * @param indent Indentation string to be prepended during printing
692 void DataEntry::Print(std::ostream &os, std::string const & )
697 uint16_t g = GetGroup();
698 if (g == 0xfffe) // delimiters have NO value
700 return; // just to avoid identing all the remaining code
703 std::ostringstream s;
709 const VRKey &vr = GetVR();
711 if( vr == "US" || vr == "SS" || vr == "UL" || vr == "SL"
712 || vr == "FL" || vr == "FD")
713 s << " [" << GetString() << "]";
716 if(Global::GetVR()->IsVROfStringRepresentable(vr))
718 // replace non printable characters by '.'
719 std::string cleanString = Util::CreateCleanString(v);
720 if ( cleanString.length() <= GetMaxSizePrintEntry()
723 // FIXME : when IsNotLoaded(), you create a Clean String ?!?
724 // FIXME : PrintLevel<2 *does* print the values
725 // (3 is only for extra offsets printing)
726 // What do you wanted to do ? JPR
728 s << " [" << cleanString << "]";
732 s << " [GDCM_NAME_SPACE::too long for print (" << cleanString.length() << ") ]";
737 // A lot of Private elements (with no VR) contain actually
738 // only printable characters;
739 // Let's deal with them as is they were VR std::string representable
741 if ( Util::IsCleanArea( GetBinArea(), GetLength() ) )
743 // FIXME : since the 'Area' *is* clean, just use
744 // a 'CreateString' method, to save CPU time.
745 std::string cleanString =
746 Util::CreateCleanString( BinArea,GetLength() );
747 s << " [" << cleanString << "]";
751 s << " [" << GDCM_BINLOADED << ";"
752 << "length = " << GetLength() << "]";
760 s << " [" << GDCM_NOTLOADED << "]";
761 else if( IsUnfound() )
762 s << " [" << GDCM_UNFOUND << "]";
763 else if( IsUnread() )
764 s << " [" << GDCM_UNREAD << "]";
765 else if ( GetLength() == 0 )
770 s << " (" << GDCM_PIXELDATA << ")";
772 // Display the UID value (instead of displaying only the rough code)
773 // First 'clean' trailing character (space or zero)
776 const uint16_t &gr = GetGroup();
777 const uint16_t &elt = GetElement();
778 TS *ts = Global::GetTS();
782 // Any more to be displayed ?
783 if ( elt == 0x0010 || elt == 0x0002 )
785 if ( v.length() != 0 ) // for brain damaged headers
787 if ( ! isdigit((unsigned char)v[v.length()-1]) )
789 v.erase(v.length()-1, 1);
792 s << " ==>\t[" << ts->GetValue(v) << "]";
795 else if (gr == 0x0008)
797 if ( elt == 0x0016 || elt == 0x1150 )
799 if ( v.length() != 0 ) // for brain damaged headers
801 if ( ! isdigit((unsigned char)v[v.length()-1]) )
803 v.erase(v.length()-1, 1);
806 s << " ==>\t[" << ts->GetValue(v) << "]";
809 else if (gr == 0x0004)
811 if ( elt == 0x1510 || elt == 0x1512 )
813 if ( v.length() != 0 ) // for brain damaged headers
815 if ( ! isdigit((unsigned char)v[v.length()-1]) )
817 v.erase(v.length()-1, 1);
820 s << " ==>\t[" << ts->GetValue(v) << "]";
828 //-----------------------------------------------------------------------------
829 } // end namespace gdcm