2 //-----------------------------------------------------------------------------
3 #include "gdcmParser.h"
11 #include <netinet/in.h>
14 #ifdef GDCM_NO_ANSI_STRING_STREAM
16 # define ostringstream ostrstream
22 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
23 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
24 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
25 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
29 // ---> Warning : This fourth field is NOT part
30 // of the 'official' Dicom Dictionnary
31 // and should NOT be used.
32 // (Not defined for all the groups
33 // may be removed in a future release)
36 // META Meta Information
48 // NMI Nuclear Medicine
50 // BFS Basic Film Session
52 // BIB Basic Image Box
67 //-----------------------------------------------------------------------------
68 // Refer to gdcmParser::CheckSwap()
69 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
71 // Refer to gdcmParser::SetMaxSizeLoadElementValue()
72 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
74 //-----------------------------------------------------------------------------
75 // Constructor / Destructor
80 * @param exception_on_error
81 * @param enable_sequences = true to allow the header
82 * to be parsed *inside* the SeQuences,
83 * when they have an actual length
84 * @param ignore_shadow to allow skipping the shadow elements,
85 * to save memory space.
86 * \warning The TRUE value for this param has to be used
87 * with a FALSE value for the 'enable_sequence' param.
88 * ('public elements' may be embedded in 'shadow Sequences')
90 gdcmParser::gdcmParser(const char *InFilename,
91 bool exception_on_error,
92 bool enable_sequences,
94 enableSequences=enable_sequences;
95 ignoreShadow =ignore_shadow;
97 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
98 filename = InFilename;
101 if ( !OpenFile(exception_on_error))
107 wasUpdated = 0; // will be set to 1 if user adds an entry
108 printLevel = 1; // 'Medium' print level by default
112 * \ingroup gdcmParser
114 * @param exception_on_error
116 gdcmParser::gdcmParser(bool exception_on_error) {
119 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
122 wasUpdated = 0; // will be set to 1 if user adds an entry
123 printLevel = 1; // 'Medium' print level by default
127 * \ingroup gdcmParser
128 * \brief Canonical destructor.
130 gdcmParser::~gdcmParser (void) {
135 //-----------------------------------------------------------------------------
138 * \ingroup gdcmParser
139 * \brief Prints the Header Entries (Dicom Elements)
140 * both from the H Table and the chained list
143 void gdcmParser::PrintEntry(std::ostream & os) {
144 std::ostringstream s;
146 for (ListTag::iterator i = listEntries.begin();
147 i != listEntries.end();
150 (*i)->SetPrintLevel(printLevel);
157 * \ingroup gdcmParser
158 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
161 void gdcmParser::PrintPubDict(std::ostream & os) {
162 RefPubDict->Print(os);
166 * \ingroup gdcmParser
167 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
170 void gdcmParser::PrintShaDict(std::ostream & os) {
171 RefShaDict->Print(os);
174 //-----------------------------------------------------------------------------
177 * \ingroup gdcmParser
178 * \brief Get the public dictionary used
180 gdcmDict *gdcmParser::GetPubDict(void) {
185 * \ingroup gdcmParser
186 * \brief Get the shadow dictionary used
188 gdcmDict *gdcmParser::GetShaDict(void) {
193 * \ingroup gdcmParser
194 * \brief Set the shadow dictionary used
195 * \param dict dictionary to use in shadow
197 bool gdcmParser::SetShaDict(gdcmDict *dict){
203 * \ingroup gdcmParser
204 * \brief Set the shadow dictionary used
205 * \param dictName name of the dictionary to use in shadow
207 bool gdcmParser::SetShaDict(DictKey dictName){
208 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
213 * \ingroup gdcmParser
214 * \brief This predicate, based on hopefully reasonable heuristics,
215 * decides whether or not the current gdcmParser was properly parsed
216 * and contains the mandatory information for being considered as
217 * a well formed and usable Dicom/Acr File.
218 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
221 bool gdcmParser::IsReadable(void) {
222 if(filetype==Unknown)
225 if(listEntries.size()<=0)
232 * \ingroup gdcmParser
233 * \brief Determines if the Transfer Syntax was already encountered
234 * and if it corresponds to a ImplicitVRLittleEndian one.
236 * @return True when ImplicitVRLittleEndian found. False in all other cases.
238 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
239 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
242 LoadHeaderEntrySafe(Element);
244 std::string Transfer = Element->GetValue();
245 if ( Transfer == UI1_2_840_10008_1_2 )
251 * \ingroup gdcmParser
252 * \brief Determines if the Transfer Syntax was already encountered
253 * and if it corresponds to a ExplicitVRLittleEndian one.
255 * @return True when ExplicitVRLittleEndian found. False in all other cases.
257 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
258 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
261 LoadHeaderEntrySafe(Element);
263 std::string Transfer = Element->GetValue();
264 if ( Transfer == UI1_2_840_10008_1_2_1 )
270 * \ingroup gdcmParser
271 * \brief Determines if the Transfer Syntax was already encountered
272 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
274 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
276 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
277 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
280 LoadHeaderEntrySafe(Element);
282 std::string Transfer = Element->GetValue();
283 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
289 * \ingroup gdcmParser
290 * \brief Determines if the Transfer Syntax was already encountered
291 * and if it corresponds to a Explicit VR Big Endian one.
293 * @return True when big endian found. False in all other cases.
295 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
296 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
299 LoadHeaderEntrySafe(Element);
301 std::string Transfer = Element->GetValue();
302 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
308 * \ingroup gdcmParser
309 * \brief returns the File Type
310 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
313 FileType gdcmParser::GetFileType(void) {
318 * \ingroup gdcmParser
319 * \brief opens the file
320 * @param exception_on_error
323 FILE *gdcmParser::OpenFile(bool exception_on_error)
326 fp=fopen(filename.c_str(),"rb");
327 if(exception_on_error)
330 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
336 fread(&zero, (size_t)2, (size_t)1, fp);
338 //ACR -- or DICOM with no Preamble --
339 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
343 fseek(fp, 126L, SEEK_CUR);
345 fread(dicm, (size_t)4, (size_t)1, fp);
346 if( memcmp(dicm, "DICM", 4) == 0 )
350 dbg.Verbose(0, "gdcmParser::gdcmParser not DICOM/ACR", filename.c_str());
353 dbg.Verbose(0, "gdcmParser::gdcmParser cannot open file", filename.c_str());
359 * \ingroup gdcmParser
360 * \brief closes the file
361 * @return TRUE if the close was successfull
363 bool gdcmParser::CloseFile(void) {
364 int closed = fclose(fp);
372 * \ingroup gdcmParser
374 * @param fp file pointer on an already open file
375 * @param type type of the File to be written
376 * (ACR-NEMA, ExplicitVR, ImplicitVR)
377 * @return always "True" ?!
379 bool gdcmParser::Write(FILE *fp, FileType type) {
381 // TODO The stuff has been rewritten using the chained list instead
383 // so we could remove the GroupHT from the gdcmParser
387 // TODO : move the following lines (and a lot of others, to be written)
388 // to a future function CheckAndCorrectHeader
391 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
392 // (FileType est un champ de gdcmParser ...)
393 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
395 // a moins de se livrer a un tres complique ajout des champs manquants.
396 // faire un CheckAndCorrectHeader (?)
399 if (type == ImplicitVR)
401 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
402 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
404 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
405 // values with a VR of UI shall be padded with a single trailing null
406 // Dans le cas suivant on doit pader manuellement avec un 0
408 SetEntryLengthByNumber(18, 0x0002, 0x0010);
411 if (type == ExplicitVR)
413 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
414 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
416 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
417 // values with a VR of UI shall be padded with a single trailing null
418 // Dans le cas suivant on doit pader manuellement avec un 0
420 SetEntryLengthByNumber(20, 0x0002, 0x0010);
424 if ( (type == ImplicitVR) || (type == ExplicitVR) )
425 UpdateGroupLength(false,type);
427 UpdateGroupLength(true,ACR);
429 WriteEntries(type, fp);
434 * \ingroup gdcmParser
435 * \brief Modifies the value of a given Header Entry (Dicom Element)
436 * if it exists; Creates it with the given value if it doesn't
437 * @param Value passed as a std::string
442 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
445 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
446 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
451 SetEntryByNumber(Value, Group, Elem);
456 * \ingroup gdcmParser
457 * \brief Modifies the value of a given Header Entry (Dicom Element)
458 * if it exists; Creates it with the given value if it doesn't
459 * @param Value passed as a char*
465 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
466 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
471 AddHeaderEntry(nvHeaderEntry);
473 std::string v = Value;
474 SetEntryByNumber(v, Group, Elem);
479 * \ingroup gdcmParser
480 * \brief Set a new value if the invoked element exists
481 * Seems to be useless !!!
487 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
489 std::string v = Value;
490 SetEntryByNumber(v, Group, Elem);
494 //-----------------------------------------------------------------------------
497 * \ingroup gdcmParser
498 * \brief Checks if a given Dicom Element exists
499 * \ within the H table
500 * @param group Group number of the searched Dicom Element
501 * @param element Element number of the searched Dicom Element
502 * @return number of occurences
504 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
505 std::string key = gdcmDictEntry::TranslateToKey(group, element );
506 return (tagHT.count(key));
510 * \ingroup gdcmParser
511 * \brief Searches within Header Entries (Dicom Elements) parsed with
512 * the public and private dictionaries
513 * for the element value of a given tag.
514 * \warning Don't use any longer : use GetPubEntryByName
515 * @param tagName name of the searched element.
516 * @return Corresponding element value when it exists,
517 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
519 std::string gdcmParser::GetEntryByName(std::string tagName) {
520 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
521 if( dictEntry == NULL)
524 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
528 * \ingroup gdcmParser
529 * \brief Searches within Header Entries (Dicom Elements) parsed with
530 * the public and private dictionaries
531 * for the element value representation of a given tag.
533 * Obtaining the VR (Value Representation) might be needed by caller
534 * to convert the string typed content to caller's native type
535 * (think of C++ vs Python). The VR is actually of a higher level
536 * of semantics than just the native C++ type.
537 * @param tagName name of the searched element.
538 * @return Corresponding element value representation when it exists,
539 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
541 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
542 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
543 if( dictEntry == NULL)
546 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
547 dictEntry->GetElement());
548 return elem->GetVR();
552 * \ingroup gdcmParser
553 * \brief Searches within Header Entries (Dicom Elements) parsed with
554 * the public and private dictionaries
555 * for the element value representation of a given tag.
556 * @param group Group of the searched tag.
557 * @param element Element of the searched tag.
558 * @return Corresponding element value representation when it exists,
559 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
561 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
562 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
563 if ( ! tagHT.count(key))
565 return tagHT.find(key)->second->GetValue();
569 * \ingroup gdcmParser
570 * \brief Searches within Header Entries (Dicom Elements) parsed with
571 * the public and private dictionaries
572 * for the element value representation of a given tag..
574 * Obtaining the VR (Value Representation) might be needed by caller
575 * to convert the string typed content to caller's native type
576 * (think of C++ vs Python). The VR is actually of a higher level
577 * of semantics than just the native C++ type.
578 * @param group Group of the searched tag.
579 * @param element Element of the searched tag.
580 * @return Corresponding element value representation when it exists,
581 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
583 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
584 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
587 return elem->GetVR();
591 * \ingroup gdcmParser
592 * \brief Sets the value (string) of the Header Entry (Dicom Element)
593 * @param content string value of the Dicom Element
594 * @param tagName name of the searched Dicom Element.
595 * @return true when found
597 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
598 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
599 if( dictEntry == NULL)
602 return(SetEntryByNumber(content,dictEntry->GetGroup(),
603 dictEntry->GetElement()));
607 * \ingroup gdcmParser
608 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
609 * through it's (group, element) and modifies it's content with
611 * \warning Don't use any longer : use SetPubEntryByNumber
612 * @param content new value to substitute with
613 * @param group group of the Dicom Element to modify
614 * @param element element of the Dicom Element to modify
616 bool gdcmParser::SetEntryByNumber(std::string content,
620 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
621 if ( ! tagHT.count(key))
623 int l = content.length();
624 if(l%2) // Odd length are padded with a space (020H).
627 content = content + '\0';
632 TagHeaderEntryHT::iterator p2;
633 // DO NOT remove the following lines : they explain the stuff
634 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
635 //p2=p.first; // iterator on the first synonym
636 //a=p2->second; // H Table target column (2-nd col)
639 a = ((tagHT.equal_range(key)).first)->second;
641 a-> SetValue(content);
643 std::string vr = a->GetVR();
646 if( (vr == "US") || (vr == "SS") )
648 else if( (vr == "UL") || (vr == "SL") )
658 * \ingroup gdcmParser
659 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
660 * in the PubHeaderEntrySet of this instance
661 * through it's (group, element) and modifies it's length with
663 * \warning Use with extreme caution.
664 * @param length new length to substitute with
665 * @param group group of the entry to modify
666 * @param element element of the Entry to modify
667 * @return 1 on success, 0 otherwise.
670 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
674 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
675 if ( ! tagHT.count(key))
677 if (length%2) length++; // length must be even
678 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
684 * \ingroup gdcmParser
685 * \brief Gets (from Header) the offset of a 'non string' element value
686 * \ (LoadElementValues has already be executed)
689 * @return File Offset of the Element Value
691 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
693 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
696 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
697 "failed to Locate gdcmHeaderEntry");
700 return Entry->GetOffset();
704 * \ingroup gdcmParser
705 * \brief Gets (from Header) a 'non string' element value
706 * \ (LoadElementValues has already be executed)
709 * @return Pointer to the 'non string' area
711 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
713 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
716 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
717 "failed to Locate gdcmHeaderEntry");
720 return Entry->GetVoidArea();
724 * \ingroup gdcmParser
725 * \brief Loads (from disk) the element content
726 * when a string is not suitable
730 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
732 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
735 size_t o =(size_t)Element->GetOffset();
736 fseek(fp, o, SEEK_SET);
737 int l=Element->GetLength();
738 void * a = malloc(l);
742 SetEntryVoidAreaByNumber(a, Group, Elem);
743 // TODO check the result
744 size_t l2 = fread(a, 1, l ,fp);
754 * \ingroup gdcmParser
755 * \brief Sets a 'non string' value to a given Dicom Element
757 * @param group Group number of the searched Dicom Element
758 * @param element Element number of the searched Dicom Element
761 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
765 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
766 if ( ! tagHT.count(key))
768 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
773 * \ingroup gdcmParser
774 * \brief Update the entries with the shadow dictionary. Only odd entries are
777 void gdcmParser::UpdateShaEntries(void) {
778 gdcmDictEntry *entry;
781 for(ListTag::iterator it=listEntries.begin();
782 it!=listEntries.end();
785 // Odd group => from public dictionary
786 if((*it)->GetGroup()%2==0)
789 // Peer group => search the corresponding dict entry
791 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
795 if((*it)->IsImplicitVR())
800 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
802 // Set the new entry and the new value
803 (*it)->SetDictEntry(entry);
804 CheckHeaderEntryVR(*it,vr);
806 (*it)->SetValue(GetHeaderEntryValue(*it));
810 // Remove precedent value transformation
811 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
817 * \ingroup gdcmParser
818 * \brief Searches within the Header Entries for a Dicom Element of
820 * @param tagName name of the searched Dicom Element.
821 * @return Corresponding Dicom Element when it exists, and NULL
824 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
825 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
826 if( dictEntry == NULL)
829 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
833 * \ingroup gdcmParser
834 * \brief retrieves a Dicom Element (the first one) using (group, element)
835 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
836 * if you think it's NOT UNIQUE, check the count number
837 * and use iterators to retrieve ALL the Dicoms Elements within
838 * a given couple (group, element)
839 * @param group Group number of the searched Dicom Element
840 * @param element Element number of the searched Dicom Element
843 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
845 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
846 if ( ! tagHT.count(key))
848 return tagHT.find(key)->second;
852 * \ingroup gdcmParser
853 * \brief retrieves the Dicom Elements (all of them) using (group, element)
854 * @param group Group number of the searched Dicom Element.
855 * @param element Element number of the searched Dicom Element.
856 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
859 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
860 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
861 return (tagHT.equal_range(key));
865 * \ingroup gdcmParser
866 * \brief Loads the element while preserving the current
867 * underlying file position indicator as opposed to
868 * to LoadHeaderEntry that modifies it.
869 * @param entry Header Entry whose value shall be loaded.
872 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
873 long PositionOnEntry = ftell(fp);
874 LoadHeaderEntry(entry);
875 fseek(fp, PositionOnEntry, SEEK_SET);
879 * \ingroup gdcmParser
880 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
881 * \warning : to be re-written using the chained list instead of the H table.
882 * \warning : DO NOT use (doesn't work any longer because of the multimap)
883 * \todo : to be re-written using the chained list instead of the H table
884 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
885 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
887 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
891 gdcmHeaderEntry *elem;
893 std::string str_trash;
896 GroupHT groupHt; // to hold the length of each group
899 // typedef std::map<GroupKey, int> GroupHT;
901 gdcmHeaderEntry *elemZ;
903 // for each Tag in the DCM Header
905 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
910 gr = elem->GetGroup();
911 el = elem->GetElement();
914 sprintf(trash, "%04x", gr);
915 key = trash; // generate 'group tag'
917 // if the caller decided not to take SEQUENCEs into account
918 // e.g : he wants to write an ACR-NEMA File
920 if (SkipSequence && vr == "SQ")
923 // Still unsolved problem :
924 // we cannot find the 'Sequence Delimitation Item'
925 // since it's at the end of the Hash Table
928 // pas SEQUENCE en ACR-NEMA
930 // --> la descente a l'interieur' des SQ
931 // devrait etre faite avec une liste chainee, pas avec une HTable...
933 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
935 if (el == 0x0000) // the first elem is 0x0000
937 groupHt[key] = 0; // initialize group length
941 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
944 else // any elem but the first
946 if (type == ExplicitVR)
948 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
950 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
953 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
957 unsigned short int gr_bid;
959 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
963 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
964 // warning: unsigned int format, different type arg
965 sscanf(g->first.c_str(),"%x",&gr_bid);
966 tk = g->first + "|0000"; // generate the element full tag
968 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
970 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
971 elemZ = new gdcmHeaderEntry(tagZ);
973 AddHeaderEntry(elemZ); // create it
977 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
979 sprintf(trash ,"%d",g->second);
981 elemZ->SetValue(str_trash);
986 * \ingroup gdcmParser
987 * \brief writes on disc according to the requested format
988 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
989 * \ warning does NOT add the missing elements in the header :
990 * \ it's up to the user doing it !
991 * \ (function CheckHeaderCoherence to be written)
992 * @param type type of the File to be written
993 * (ACR-NEMA, ExplicitVR, ImplicitVR)
994 * @param _fp already open file pointer
996 void gdcmParser::WriteEntries(FileType type, FILE * _fp)
1005 std::vector<std::string> tokens;
1007 // uses now listEntries to iterate, not TagHt!
1009 // pb : gdcmParser.Add does NOT update listEntries
1010 // TODO : find a trick (in STL?) to do it, at low cost !
1014 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1016 for (ListTag::iterator tag2=listEntries.begin();
1017 tag2 != listEntries.end();
1020 gr = (*tag2)->GetGroup();
1021 el = (*tag2)->GetElement();
1022 lgr = (*tag2)->GetLength();
1023 val = (*tag2)->GetValue().c_str();
1024 vr = (*tag2)->GetVR();
1028 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
1029 if (gr %2) continue; // ignore shadow groups
1030 if (vr == "SQ" ) continue; // ignore Sequences
1031 // TODO : find a trick to *skip* the SeQuences !
1032 // Not only ignore the SQ element
1033 if (gr == 0xfffe ) continue; // ignore delimiters
1036 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1037 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1039 if ( (type == ExplicitVR) && (gr <= 0x0002) )
1042 guint16 z=0, shortLgr;
1043 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1045 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1047 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1048 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1054 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1059 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1062 if (vr == "US" || vr == "SS")
1064 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1065 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1066 for (unsigned int i=0; i<tokens.size();i++)
1068 val_uint16 = atoi(tokens[i].c_str());
1070 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1075 if (vr == "UL" || vr == "SL")
1077 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1078 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1079 for (unsigned int i=0; i<tokens.size();i++)
1081 val_uint32 = atoi(tokens[i].c_str());
1083 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1088 // Pixels are never loaded in the element !
1089 if ((gr == 0x7fe0) && (el == 0x0010) )
1092 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1097 * \ingroup gdcmParser
1098 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1100 * @return The properly swaped 32 bits integer.
1102 guint32 gdcmParser::SwapLong(guint32 a) {
1107 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1108 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1112 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1116 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1119 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1126 * \ingroup gdcmParser
1127 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1129 * @return The properly unswaped 32 bits integer.
1131 guint32 gdcmParser::UnswapLong(guint32 a) {
1132 return (SwapLong(a));
1136 * \ingroup gdcmParser
1137 * \brief Swaps the bytes so they agree with the processor order
1138 * @return The properly swaped 16 bits integer.
1140 guint16 gdcmParser::SwapShort(guint16 a) {
1141 if ( (sw==4321) || (sw==2143) )
1142 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1147 * \ingroup gdcmParser
1148 * \brief Unswaps the bytes so they agree with the processor order
1149 * @return The properly unswaped 16 bits integer.
1151 guint16 gdcmParser::UnswapShort(guint16 a) {
1152 return (SwapShort(a));
1155 //-----------------------------------------------------------------------------
1158 * \ingroup gdcmParser
1159 * \brief Parses the header of the file but WITHOUT loading element values.
1161 void gdcmParser::Parse(bool exception_on_error) throw(gdcmFormatError) {
1162 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1166 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1167 SkipHeaderEntry(newHeaderEntry);
1168 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) { //JPR
1169 AddHeaderEntry(newHeaderEntry);
1175 * \ingroup gdcmParser
1176 * \brief Loads the element values of all the Header Entries pointed in the
1177 * public Chained List.
1179 void gdcmParser::LoadHeaderEntries(void) {
1181 for (ListTag::iterator i = GetListEntry().begin();
1182 i != GetListEntry().end();
1185 LoadHeaderEntry(*i);
1190 // Load 'non string' values
1191 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1192 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1193 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1194 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1195 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1196 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1198 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1199 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1200 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1203 // --------------------------------------------------------------
1204 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1206 // if recognition code tells us we deal with a LibIDO image
1207 // we switch lineNumber and columnNumber
1209 std::string RecCode;
1210 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1211 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1212 RecCode == "CANRME_AILIBOD1_1." )
1214 filetype = ACR_LIBIDO;
1215 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1216 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1217 SetEntryByNumber(columns, 0x0028, 0x0010);
1218 SetEntryByNumber(rows , 0x0028, 0x0011);
1220 // ----------------- End of Special Patch ----------------
1224 * \ingroup gdcmParser
1225 * \brief Loads the element content if it's length is not bigger
1226 * than the value specified with
1227 * gdcmParser::SetMaxSizeLoadEntry()
1228 * @param Entry Header Entry (Dicom Element) to be dealt with
1230 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1232 guint16 group = Entry->GetGroup();
1233 std::string vr= Entry->GetVR();
1234 guint32 length = Entry->GetLength();
1235 bool SkipLoad = false;
1237 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1239 // the test was commented out to 'go inside' the SeQuences
1240 // we don't any longer skip them !
1242 // if( vr == "SQ" ) // (DO NOT remove this comment)
1245 // A SeQuence "contains" a set of Elements.
1246 // (fffe e000) tells us an Element is beginning
1247 // (fffe e00d) tells us an Element just ended
1248 // (fffe e0dd) tells us the current SeQuence just ended
1249 if( group == 0xfffe )
1253 Entry->SetLength(0);
1254 Entry->SetValue("gdcm::Skipped");
1258 // When the length is zero things are easy:
1259 if ( length == 0 ) {
1260 Entry->SetValue("");
1264 // The elements whose length is bigger than the specified upper bound
1265 // are not loaded. Instead we leave a short notice of the offset of
1266 // the element content and it's length.
1267 if (length > MaxSizeLoadEntry) {
1268 std::ostringstream s;
1269 s << "gdcm::NotLoaded.";
1270 s << " Address:" << (long)Entry->GetOffset();
1271 s << " Length:" << Entry->GetLength();
1272 s << " x(" << std::hex << Entry->GetLength() << ")";
1273 Entry->SetValue(s.str());
1277 // When integer(s) are expected, read and convert the following
1278 // n *(two or four bytes)
1279 // properly i.e. as integers as opposed to a strings.
1280 // Elements with Value Multiplicity > 1
1281 // contain a set of integers (not a single one)
1283 // Any compacter code suggested (?)
1284 if ( IsHeaderEntryAnInteger(Entry) ) {
1286 std::ostringstream s;
1288 if (vr == "US" || vr == "SS") {
1290 NewInt = ReadInt16();
1293 for (int i=1; i < nbInt; i++) {
1295 NewInt = ReadInt16();
1300 else if (vr == "UL" || vr == "SL") {
1302 NewInt = ReadInt32();
1305 for (int i=1; i < nbInt; i++) {
1307 NewInt = ReadInt32();
1312 #ifdef GDCM_NO_ANSI_STRING_STREAM
1313 s << std::ends; // to avoid oddities on Solaris
1314 #endif //GDCM_NO_ANSI_STRING_STREAM
1316 Entry->SetValue(s.str());
1320 // We need an additional byte for storing \0 that is not on disk
1321 std::string NewValue(length,0);
1322 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1323 if ( item_read != 1 ) {
1324 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1325 Entry->SetValue("gdcm::UnRead");
1329 if( (vr == "UI") ) // Because of correspondance with the VR dic
1330 Entry->SetValue(NewValue.c_str());
1332 Entry->SetValue(NewValue);
1336 * \ingroup gdcmParser
1337 * \brief add a new Dicom Element pointer to
1338 * the H Table and to the chained List
1339 * \warning push_bash in listEntries ONLY during ParseHeader
1340 * \todo something to allow further Elements addition,
1341 * \ when position to be taken care of
1342 * @param newHeaderEntry
1344 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1345 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1346 listEntries.push_back(newHeaderEntry);
1351 * \ingroup gdcmParser
1353 * @param Entry Header Entry whose length of the value shall be loaded.
1357 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1358 guint16 element = Entry->GetElement();
1359 guint16 group = Entry->GetGroup();
1360 std::string vr = Entry->GetVR();
1362 if( (element == 0x0010) && (group == 0x7fe0) )
1365 dbg.Verbose(2, "gdcmParser::FindLength: ",
1366 "we reached 7fe0 0010");
1369 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1371 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1373 // The following reserved two bytes (see PS 3.5-2001, section
1374 // 7.1.2 Data element structure with explicit vr p27) must be
1375 // skipped before proceeding on reading the length on 4 bytes.
1376 fseek(fp, 2L, SEEK_CUR);
1377 guint32 length32 = ReadInt32();
1379 if ( (vr == "OB") && (length32 == 0xffffffff) )
1381 Entry->SetLength(FindHeaderEntryLengthOB());
1384 FixHeaderEntryFoundLength(Entry, length32);
1388 // Length is encoded on 2 bytes.
1389 length16 = ReadInt16();
1391 // We can tell the current file is encoded in big endian (like
1392 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1393 // and it's value is the one of the encoding of a big endian file.
1394 // In order to deal with such big endian encoded files, we have
1395 // (at least) two strategies:
1396 // * when we load the "Transfer Syntax" tag with value of big endian
1397 // encoding, we raise the proper flags. Then we wait for the end
1398 // of the META group (0x0002) among which is "Transfer Syntax",
1399 // before switching the swap code to big endian. We have to postpone
1400 // the switching of the swap code since the META group is fully encoded
1401 // in little endian, and big endian coding only starts at the next
1402 // group. The corresponding code can be hard to analyse and adds
1403 // many additional unnecessary tests for regular tags.
1404 // * the second strategy consists in waiting for trouble, that shall
1405 // appear when we find the first group with big endian encoding. This
1406 // is easy to detect since the length of a "Group Length" tag (the
1407 // ones with zero as element number) has to be of 4 (0x0004). When we
1408 // encounter 1024 (0x0400) chances are the encoding changed and we
1409 // found a group with big endian encoding.
1410 // We shall use this second strategy. In order to make sure that we
1411 // can interpret the presence of an apparently big endian encoded
1412 // length of a "Group Length" without committing a big mistake, we
1413 // add an additional check: we look in the already parsed elements
1414 // for the presence of a "Transfer Syntax" whose value has to be "big
1415 // endian encoding". When this is the case, chances are we have got our
1416 // hands on a big endian encoded file: we switch the swap code to
1417 // big endian and proceed...
1418 if ( (element == 0x0000) && (length16 == 0x0400) )
1420 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1422 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1427 SwitchSwapToBigEndian();
1428 // Restore the unproperly loaded values i.e. the group, the element
1429 // and the dictionary entry depending on them.
1430 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1431 guint16 CorrectElem = SwapShort(Entry->GetElement());
1432 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1436 // This correct tag is not in the dictionary. Create a new one.
1437 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1439 // FIXME this can create a memory leaks on the old entry that be
1440 // left unreferenced.
1441 Entry->SetDictEntry(NewTag);
1444 // Heuristic: well some files are really ill-formed.
1445 if ( length16 == 0xffff)
1448 //dbg.Verbose(0, "gdcmParser::FindLength",
1449 // "Erroneous element length fixed.");
1450 // Actually, length= 0xffff means that we deal with
1451 // Unknown Sequence Length
1454 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1459 // Either implicit VR or a non DICOM conformal (see not below) explicit
1460 // VR that ommited the VR of (at least) this element. Farts happen.
1461 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1462 // on Data elements "Implicit and Explicit VR Data Elements shall
1463 // not coexist in a Data Set and Data Sets nested within it".]
1464 // Length is on 4 bytes.
1465 FixHeaderEntryFoundLength(Entry, ReadInt32());
1471 * \ingroup gdcmParser
1472 * \brief Find the Value Representation of the current Dicom Element.
1475 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1477 if (filetype != ExplicitVR)
1483 long PositionOnEntry = ftell(fp);
1484 // Warning: we believe this is explicit VR (Value Representation) because
1485 // we used a heuristic that found "UL" in the first tag. Alas this
1486 // doesn't guarantee that all the tags will be in explicit VR. In some
1487 // cases (see e-film filtered files) one finds implicit VR tags mixed
1488 // within an explicit VR file. Hence we make sure the present tag
1489 // is in explicit VR and try to fix things if it happens not to be
1492 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1494 if(!CheckHeaderEntryVR(Entry,VR))
1496 fseek(fp, PositionOnEntry, SEEK_SET);
1497 // When this element is known in the dictionary we shall use, e.g. for
1498 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1499 // dictionary entry. Still we have to flag the element as implicit since
1500 // we know now our assumption on expliciteness is not furfilled.
1502 if ( Entry->IsVRUnknown() )
1503 Entry->SetVR("Implicit");
1504 Entry->SetImplicitVR();
1509 * \ingroup gdcmParser
1510 * \brief Check the correspondance between the VR of the header entry
1511 * and the taken VR. If they are different, the header entry is
1512 * updated with the new VR.
1515 * @return false if the VR is incorrect of if the VR isn't referenced
1516 * otherwise, it returns true
1518 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1520 char msg[100]; // for sprintf
1521 bool RealExplicit = true;
1523 // Assume we are reading a falsely explicit VR file i.e. we reached
1524 // a tag where we expect reading a VR but are in fact we read the
1525 // first to bytes of the length. Then we will interogate (through find)
1526 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1527 // both GCC and VC++ implementations of the STL map. Hence when the
1528 // expected VR read happens to be non-ascii characters we consider
1529 // we hit falsely explicit VR tag.
1531 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1532 RealExplicit = false;
1534 // CLEANME searching the dicom_vr at each occurence is expensive.
1535 // PostPone this test in an optional integrity check at the end
1536 // of parsing or only in debug mode.
1537 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1538 RealExplicit= false;
1540 if ( !RealExplicit )
1542 // We thought this was explicit VR, but we end up with an
1543 // implicit VR tag. Let's backtrack.
1544 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1545 Entry->GetGroup(),Entry->GetElement());
1546 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1551 if ( Entry->IsVRUnknown() )
1553 // When not a dictionary entry, we can safely overwrite the VR.
1556 else if ( Entry->GetVR() != vr )
1558 // The VR present in the file and the dictionary disagree. We assume
1559 // the file writer knew best and use the VR of the file. Since it would
1560 // be unwise to overwrite the VR of a dictionary (since it would
1561 // compromise it's next user), we need to clone the actual DictEntry
1562 // and change the VR for the read one.
1563 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1564 Entry->GetGroup(),Entry->GetElement(),
1565 vr,"FIXME",Entry->GetName());
1566 Entry->SetDictEntry(NewEntry);
1572 * \ingroup gdcmParser
1573 * \brief Get the transformed value of the header entry. The VR value
1574 * is used to define the transformation to operate on the value
1575 * \warning NOT end user intended method !
1577 * @return Transformed entry value
1579 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1581 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1583 std::string val=Entry->GetValue();
1584 std::string vr=Entry->GetVR();
1585 guint32 length = Entry->GetLength();
1586 std::ostringstream s;
1589 if (vr == "US" || vr == "SS")
1594 for (int i=0; i < nbInt; i++)
1598 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1599 NewInt16 = SwapShort(NewInt16);
1604 else if (vr == "UL" || vr == "SL")
1609 for (int i=0; i < nbInt; i++)
1613 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1614 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1615 NewInt32=SwapLong(NewInt32);
1620 #ifdef GDCM_NO_ANSI_STRING_STREAM
1621 s << std::ends; // to avoid oddities on Solaris
1622 #endif //GDCM_NO_ANSI_STRING_STREAM
1626 return(Entry->GetValue());
1630 * \ingroup gdcmParser
1631 * \brief Get the reverse transformed value of the header entry. The VR
1632 * value is used to define the reverse transformation to operate on
1634 * \warning NOT end user intended method !
1636 * @return Reverse transformed entry value
1638 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1640 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1642 std::string vr=Entry->GetVR();
1643 std::ostringstream s;
1644 std::vector<std::string> tokens;
1646 if (vr == "US" || vr == "SS")
1650 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1651 Tokenize (Entry->GetValue(), tokens, "\\");
1652 for (unsigned int i=0; i<tokens.size();i++)
1654 NewInt16 = atoi(tokens[i].c_str());
1655 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1659 if (vr == "UL" || vr == "SL")
1663 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1664 Tokenize (Entry->GetValue(), tokens, "\\");
1665 for (unsigned int i=0; i<tokens.size();i++)
1667 NewInt32 = atoi(tokens[i].c_str());
1668 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1669 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1674 #ifdef GDCM_NO_ANSI_STRING_STREAM
1675 s << std::ends; // to avoid oddities on Solaris
1676 #endif //GDCM_NO_ANSI_STRING_STREAM
1680 return(Entry->GetValue());
1684 * \ingroup gdcmParser
1685 * \brief Skip a given Header Entry
1686 * \warning NOT end user intended method !
1689 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1691 SkipBytes(entry->GetLength());
1695 * \ingroup gdcmParser
1696 * \brief When the length of an element value is obviously wrong (because
1697 * the parser went Jabberwocky) one can hope improving things by
1698 * applying this heuristic.
1700 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1702 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1704 if ( FoundLength == 0xffffffff)
1709 // Sorry for the patch!
1710 // XMedCom did the trick to read some nasty GE images ...
1711 else if (FoundLength == 13)
1713 // The following 'if' will be removed when there is no more
1714 // images on Creatis HDs with a 13 length for Manufacturer...
1715 if ( (Entry->GetGroup() != 0x0008) ||
1716 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ) {
1717 // end of remove area
1719 Entry->SetReadLength(10); // a bug is to be fixed
1723 // to fix some garbage 'Leonardo' Siemens images
1724 // May be commented out to avoid overhead
1725 else if ( (Entry->GetGroup() == 0x0009) &&
1726 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) )
1729 Entry->SetReadLength(4); // a bug is to be fixed
1733 // to try to 'go inside' SeQuences (with length), and not to skip them
1734 else if ( Entry->GetVR() == "SQ")
1736 if (enableSequences) // only if the user does want to !
1737 FoundLength =0; // ReadLength is unchanged
1740 // a SeQuence Element is beginning
1741 // Let's forget it's length
1742 // (we want to 'go inside')
1744 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1745 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1746 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1747 // if we don't, we lost 28800 characters from the Header :-(
1749 else if(Entry->GetGroup() == 0xfffe)
1751 // sometimes, length seems to be wrong
1752 FoundLength =0; // some more clever checking to be done !
1754 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1755 // causes troubles :-(
1758 Entry->SetUsableLength(FoundLength);
1762 * \ingroup gdcmParser
1763 * \brief Apply some heuristics to predict wether the considered
1764 * element value contains/represents an integer or not.
1765 * @param Entry The element value on which to apply the predicate.
1766 * @return The result of the heuristical predicate.
1768 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1769 guint16 element = Entry->GetElement();
1770 guint16 group = Entry->GetGroup();
1771 std::string vr = Entry->GetVR();
1772 guint32 length = Entry->GetLength();
1773 // When we have some semantics on the element we just read, and if we
1774 // a priori know we are dealing with an integer, then we shall be
1775 // able to swap it's element value properly.
1776 if ( element == 0 ) // This is the group length of the group
1782 std::ostringstream s;
1783 int filePosition = ftell(fp);
1784 s << "Erroneous Group Length element length on : (" \
1785 << std::hex << group << " , " << element
1786 << ") -before- position x(" << filePosition << ")"
1787 << "lgt : " << length;
1788 // These 2 lines commented out : a *very dirty* patch
1789 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1790 // have a glance at offset x(8336) ...
1791 // For *regular* headers, the test is useless..
1792 // lets's print a warning message and go on,
1793 // instead of giving up with an error message
1794 std::cout << s.str().c_str() << std::endl;
1795 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1796 // s.str().c_str());
1799 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1806 * \ingroup gdcmParser
1811 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1812 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1815 long PositionOnEntry = ftell(fp);
1816 bool FoundSequenceDelimiter = false;
1817 guint32 TotalLength = 0;
1820 while ( ! FoundSequenceDelimiter)
1826 TotalLength += 4; // We even have to decount the group and element
1828 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1830 char msg[100]; // for sprintf. Sorry
1831 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1832 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1836 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1837 FoundSequenceDelimiter = true;
1838 else if ( n != 0xe000 )
1840 char msg[100]; // for sprintf. Sorry
1841 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1843 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1847 ItemLength = ReadInt32();
1848 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1849 // the ItemLength with ReadInt32
1850 SkipBytes(ItemLength);
1852 fseek(fp, PositionOnEntry, SEEK_SET);
1857 * \ingroup gdcmParser
1858 * \brief Reads a supposed to be 16 Bits integer
1859 * \ (swaps it depending on processor endianity)
1861 * @return read value
1863 guint16 gdcmParser::ReadInt16(void) {
1866 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1867 if ( item_read != 1 ) {
1869 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1879 * \ingroup gdcmParser
1880 * \brief Reads a supposed to be 32 Bits integer
1881 * \ (swaps it depending on processor endianity)
1883 * @return read value
1885 guint32 gdcmParser::ReadInt32(void) {
1888 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1889 if ( item_read != 1 ) {
1891 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1901 * \ingroup gdcmParser
1906 void gdcmParser::SkipBytes(guint32 NBytes) {
1907 //FIXME don't dump the returned value
1908 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1912 * \ingroup gdcmParser
1915 void gdcmParser::Initialise(void)
1917 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1918 RefShaDict = (gdcmDict*)0;
1922 * \ingroup gdcmParser
1923 * \brief Discover what the swap code is (among little endian, big endian,
1924 * bad little endian, bad big endian).
1927 void gdcmParser::CheckSwap() {
1929 // The only guaranted way of finding the swap code is to find a
1930 // group tag since we know it's length has to be of four bytes i.e.
1931 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1932 // occurs when we can't find such group...
1935 guint32 x=4; // x : for ntohs
1936 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1940 char deb[HEADER_LENGTH_TO_READ];
1942 // First, compare HostByteOrder and NetworkByteOrder in order to
1943 // determine if we shall need to swap bytes (i.e. the Endian type).
1949 // The easiest case is the one of a DICOM header, since it possesses a
1950 // file preamble where it suffice to look for the string "DICM".
1951 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1954 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
1955 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
1957 // Next, determine the value representation (VR). Let's skip to the
1958 // first element (0002, 0000) and check there if we find "UL"
1959 // - or "OB" if the 1st one is (0002,0001) -,
1960 // in which case we (almost) know it is explicit VR.
1961 // WARNING: if it happens to be implicit VR then what we will read
1962 // is the length of the group. If this ascii representation of this
1963 // length happens to be "UL" then we shall believe it is explicit VR.
1964 // FIXME: in order to fix the above warning, we could read the next
1965 // element value (or a couple of elements values) in order to make
1966 // sure we are not commiting a big mistake.
1967 // We need to skip :
1968 // * the 128 bytes of File Preamble (often padded with zeroes),
1969 // * the 4 bytes of "DICM" string,
1970 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1971 // i.e. a total of 136 bytes.
1974 // Use gdcmParser::dicom_vr to test all the possibilities
1975 // instead of just checking for UL, OB and UI !?
1976 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
1977 (memcmp(entCur, "OB", (size_t)2) == 0) ||
1978 (memcmp(entCur, "UI", (size_t)2) == 0) )
1980 filetype = ExplicitVR;
1981 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1982 "explicit Value Representation");
1986 filetype = ImplicitVR;
1987 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1988 "not an explicit Value Representation");
1993 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1994 "HostByteOrder != NetworkByteOrder");
1999 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2000 "HostByteOrder = NetworkByteOrder");
2003 // Position the file position indicator at first tag (i.e.
2004 // after the file preamble and the "DICM" string).
2006 fseek (fp, 132L, SEEK_SET);
2010 // Alas, this is not a DicomV3 file and whatever happens there is no file
2011 // preamble. We can reset the file position indicator to where the data
2012 // is (i.e. the beginning of the file).
2013 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2016 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2017 // By clean we mean that the length of the first tag is written down.
2018 // If this is the case and since the length of the first group HAS to be
2019 // four (bytes), then determining the proper swap code is straightforward.
2022 // We assume the array of char we are considering contains the binary
2023 // representation of a 32 bits integer. Hence the following dirty
2025 s = *((guint32 *)(entCur));
2045 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2046 "ACR/NEMA unfound swap info (time to raise bets)");
2049 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2050 // It is time for despaired wild guesses. So, let's assume this file
2051 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
2052 // not present. Then the only info we have is the net2host one.
2062 * \ingroup gdcmParser
2065 void gdcmParser::SwitchSwapToBigEndian(void)
2067 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2068 "Switching to BigEndian mode.");
2089 * \ingroup gdcmParser
2094 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2098 if ((guint32)NewSize >= (guint32)0xffffffff)
2100 MaxSizeLoadEntry = 0xffffffff;
2103 MaxSizeLoadEntry = NewSize;
2107 * \ingroup gdcmParser
2108 * \brief Searches both the public and the shadow dictionary (when they
2109 * exist) for the presence of the DictEntry with given name.
2110 * The public dictionary has precedence on the shadow one.
2111 * @param Name name of the searched DictEntry
2112 * @return Corresponding DictEntry when it exists, NULL otherwise.
2114 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2116 gdcmDictEntry *found = (gdcmDictEntry *)0;
2117 if (!RefPubDict && !RefShaDict)
2119 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2120 "we SHOULD have a default dictionary");
2124 found = RefPubDict->GetDictEntryByName(Name);
2130 found = RefShaDict->GetDictEntryByName(Name);
2138 * \ingroup gdcmParser
2139 * \brief Searches both the public and the shadow dictionary (when they
2140 * exist) for the presence of the DictEntry with given
2141 * group and element. The public dictionary has precedence on the
2143 * @param group group of the searched DictEntry
2144 * @param element element of the searched DictEntry
2145 * @return Corresponding DictEntry when it exists, NULL otherwise.
2147 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2149 gdcmDictEntry *found = (gdcmDictEntry *)0;
2150 if (!RefPubDict && !RefShaDict)
2152 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2153 "we SHOULD have a default dictionary");
2157 found = RefPubDict->GetDictEntryByNumber(group, element);
2163 found = RefShaDict->GetDictEntryByNumber(group, element);
2171 * \ingroup gdcmParser
2172 * \brief Read the next tag but WITHOUT loading it's value
2173 * @return On succes the newly created HeaderEntry, NULL on failure.
2175 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2177 gdcmHeaderEntry *NewEntry;
2183 // We reached the EOF (or an error occured) therefore
2184 // header parsing has to be considered as finished.
2185 return (gdcmHeaderEntry *)0;
2187 /* Pb : how to propagate the element length (used in SkipHeaderEntry)
2188 // direct call to SkipBytes ?
2190 if (ignoreShadow == 1 && g%2 ==1) //JPR
2191 // if user wants to skip shadow groups
2192 // and current element *is* a shadow element
2193 // we don't create anything
2194 return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2196 NewEntry = NewHeaderEntryByNumber(g, n);
2197 FindHeaderEntryVR(NewEntry);
2198 FindHeaderEntryLength(NewEntry);
2204 NewEntry->SetOffset(ftell(fp));
2205 //if ( (g==0x7fe0) && (n==0x0010) )
2210 * \ingroup gdcmParser
2211 * \brief Build a new Element Value from all the low level arguments.
2212 * Check for existence of dictionary entry, and build
2213 * a default one when absent.
2214 * @param Name Name of the underlying DictEntry
2216 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2218 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2220 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2222 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2225 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2226 "failed to allocate gdcmHeaderEntry");
2227 return (gdcmHeaderEntry *)0;
2233 * \ingroup gdcmParser
2234 * \brief Request a new virtual dict entry to the dict set
2235 * @param group group of the underlying DictEntry
2236 * @param elem element of the underlying DictEntry
2237 * @param vr VR of the underlying DictEntry
2238 * @param fourth owner group
2239 * @param name english name
2241 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2246 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2250 * \ingroup gdcmParser
2251 * \brief Build a new Element Value from all the low level arguments.
2252 * Check for existence of dictionary entry, and build
2253 * a default one when absent.
2254 * @param Group group of the underlying DictEntry
2255 * @param Elem element of the underlying DictEntry
2257 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2259 // Find out if the tag we encountered is in the dictionaries:
2260 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2262 DictEntry = NewVirtualDictEntry(Group, Elem);
2264 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2267 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2268 "failed to allocate gdcmHeaderEntry");
2275 * \ingroup gdcmParser
2276 * \brief Small utility function that creates a new manually crafted
2277 * (as opposed as read from the file) gdcmHeaderEntry with user
2278 * specified name and adds it to the public tag hash table.
2279 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2280 * @param NewTagName The name to be given to this new tag.
2281 * @param VR The Value Representation to be given to this new tag.
2282 * @return The newly hand crafted Element Value.
2284 gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2287 gdcmHeaderEntry *NewEntry = NULL;
2288 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2289 guint32 FreeElem = 0;
2290 gdcmDictEntry *DictEntry = NULL;
2292 FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2293 if (FreeElem == UINT32_MAX)
2295 dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2296 "Group 0xffff in Public Dict is full");
2300 DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2301 VR, "GDCM", NewTagName);
2302 NewEntry = new gdcmHeaderEntry(DictEntry);
2303 AddHeaderEntry(NewEntry);
2308 * \ingroup gdcmParser
2309 * \brief Generate a free TagKey i.e. a TagKey that is not present
2310 * in the TagHt dictionary.
2311 * @param group The generated tag must belong to this group.
2312 * @return The element of tag with given group which is fee.
2314 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2316 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2318 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2319 if (tagHT.count(key) == 0)
2325 //-----------------------------------------------------------------------------