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::SetMaxSizeLoadEntry()
72 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
74 // Refer to gdcmParser::SetMaxSizePrintEntry()
75 // TODO : Right now, better see "define, in gdcmHederEntry.cxx
76 const unsigned int gdcmParser::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
78 //-----------------------------------------------------------------------------
79 // Constructor / Destructor
84 * @param exception_on_error
85 * @param enable_sequences = true to allow the header
86 * to be parsed *inside* the SeQuences,
87 * when they have an actual length
88 * @param ignore_shadow to allow skipping the shadow elements,
89 * to save memory space.
90 * \warning The TRUE value for this param has to be used
91 * with a FALSE value for the 'enable_sequence' param.
92 * ('public elements' may be embedded in 'shadow Sequences')
94 gdcmParser::gdcmParser(const char *InFilename,
95 bool exception_on_error,
96 bool enable_sequences,
98 enableSequences=enable_sequences;
99 ignoreShadow =ignore_shadow;
100 cout << "chou" << endl;
102 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
103 filename = InFilename;
106 if ( !OpenFile(exception_on_error))
113 wasUpdated = 0; // will be set to 1 if user adds an entry
114 printLevel = 1; // 'Medium' print level by default
118 * \ingroup gdcmParser
120 * @param exception_on_error
122 gdcmParser::gdcmParser(bool exception_on_error) {
124 cout << "chou" << endl;
126 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
129 wasUpdated = 0; // will be set to 1 if user adds an entry
130 printLevel = 1; // 'Medium' print level by default
134 * \ingroup gdcmParser
135 * \brief Canonical destructor.
137 gdcmParser::~gdcmParser (void) {
142 //-----------------------------------------------------------------------------
145 * \ingroup gdcmParser
146 * \brief Prints the Header Entries (Dicom Elements)
147 * both from the H Table and the chained list
150 void gdcmParser::PrintEntry(std::ostream & os) {
151 std::ostringstream s;
153 for (ListTag::iterator i = listEntries.begin();
154 i != listEntries.end();
157 (*i)->SetPrintLevel(printLevel);
164 * \ingroup gdcmParser
165 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
168 void gdcmParser::PrintPubDict(std::ostream & os) {
169 RefPubDict->Print(os);
173 * \ingroup gdcmParser
174 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
177 void gdcmParser::PrintShaDict(std::ostream & os) {
178 RefShaDict->Print(os);
181 //-----------------------------------------------------------------------------
184 * \ingroup gdcmParser
185 * \brief Get the public dictionary used
187 gdcmDict *gdcmParser::GetPubDict(void) {
192 * \ingroup gdcmParser
193 * \brief Get the shadow dictionary used
195 gdcmDict *gdcmParser::GetShaDict(void) {
200 * \ingroup gdcmParser
201 * \brief Set the shadow dictionary used
202 * \param dict dictionary to use in shadow
204 bool gdcmParser::SetShaDict(gdcmDict *dict){
210 * \ingroup gdcmParser
211 * \brief Set the shadow dictionary used
212 * \param dictName name of the dictionary to use in shadow
214 bool gdcmParser::SetShaDict(DictKey dictName){
215 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
220 * \ingroup gdcmParser
221 * \brief This predicate, based on hopefully reasonable heuristics,
222 * decides whether or not the current gdcmParser was properly parsed
223 * and contains the mandatory information for being considered as
224 * a well formed and usable Dicom/Acr File.
225 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
228 bool gdcmParser::IsReadable(void) {
229 if(filetype==Unknown) {
232 if(listEntries.size()<=0) {
240 * \ingroup gdcmParser
241 * \brief Determines if the Transfer Syntax was already encountered
242 * and if it corresponds to a ImplicitVRLittleEndian one.
244 * @return True when ImplicitVRLittleEndian found. False in all other cases.
246 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
247 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
250 LoadHeaderEntrySafe(Element);
252 std::string Transfer = Element->GetValue();
253 if ( Transfer == UI1_2_840_10008_1_2 )
259 * \ingroup gdcmParser
260 * \brief Determines if the Transfer Syntax was already encountered
261 * and if it corresponds to a ExplicitVRLittleEndian one.
263 * @return True when ExplicitVRLittleEndian found. False in all other cases.
265 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
266 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
269 LoadHeaderEntrySafe(Element);
271 std::string Transfer = Element->GetValue();
272 if ( Transfer == UI1_2_840_10008_1_2_1 )
278 * \ingroup gdcmParser
279 * \brief Determines if the Transfer Syntax was already encountered
280 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
282 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
284 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
285 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
288 LoadHeaderEntrySafe(Element);
290 std::string Transfer = Element->GetValue();
291 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
297 * \ingroup gdcmParser
298 * \brief Determines if the Transfer Syntax was already encountered
299 * and if it corresponds to a Explicit VR Big Endian one.
301 * @return True when big endian found. False in all other cases.
303 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
304 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
307 LoadHeaderEntrySafe(Element);
309 std::string Transfer = Element->GetValue();
310 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
316 * \ingroup gdcmParser
317 * \brief returns the File Type
318 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
321 FileType gdcmParser::GetFileType(void) {
326 * \ingroup gdcmParser
327 * \brief opens the file
328 * @param exception_on_error
331 FILE *gdcmParser::OpenFile(bool exception_on_error)
334 fp=fopen(filename.c_str(),"rb");
335 if(exception_on_error)
338 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
344 fread(&zero, (size_t)2, (size_t)1, fp);
346 //ACR -- or DICOM with no Preamble --
347 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
351 fseek(fp, 126L, SEEK_CUR);
353 fread(dicm, (size_t)4, (size_t)1, fp);
354 if( memcmp(dicm, "DICM", 4) == 0 )
358 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
361 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
367 * \ingroup gdcmParser
368 * \brief closes the file
369 * @return TRUE if the close was successfull
371 bool gdcmParser::CloseFile(void) {
372 int closed = fclose(fp);
380 * \ingroup gdcmParser
382 * @param fp file pointer on an already open file
383 * @param type type of the File to be written
384 * (ACR-NEMA, ExplicitVR, ImplicitVR)
385 * @return always "True" ?!
387 bool gdcmParser::Write(FILE *fp, FileType type) {
389 // TODO The stuff was rewritten using the chained list instead
391 // so we could remove the GroupHT from the gdcmParser
395 // TODO : move the following lines (and a lot of others, to be written)
396 // to a future function CheckAndCorrectHeader
399 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
400 // (FileType est un champ de gdcmParser ...)
401 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
403 // a moins de se livrer a un tres complique ajout des champs manquants.
404 // faire un CheckAndCorrectHeader (?)
407 if (type == ImplicitVR)
409 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
410 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
412 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
413 // values with a VR of UI shall be padded with a single trailing null
414 // Dans le cas suivant on doit pader manuellement avec un 0
416 SetEntryLengthByNumber(18, 0x0002, 0x0010);
419 if (type == ExplicitVR)
421 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
422 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
424 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
425 // values with a VR of UI shall be padded with a single trailing null
426 // Dans le cas suivant on doit pader manuellement avec un 0
428 SetEntryLengthByNumber(20, 0x0002, 0x0010);
431 /* TODO : rewrite later
433 if ( (type == ImplicitVR) || (type == ExplicitVR) )
434 UpdateGroupLength(false,type);
436 UpdateGroupLength(true,ACR);
439 WriteEntries(fp,type);
444 * \ingroup gdcmParser
445 * \brief Modifies the value of a given Header Entry (Dicom Element)
446 * if it exists; Creates it with the given value if it doesn't
447 * @param Value passed as a std::string
452 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
455 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
456 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
461 SetEntryByNumber(Value, Group, Elem);
466 * \ingroup gdcmParser
467 * \brief Modifies the value of a given Header Entry (Dicom Element)
468 * if it exists; Creates it with the given value if it doesn't
469 * @param Value passed as a char*
475 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
476 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
481 AddHeaderEntry(nvHeaderEntry);
483 std::string v = Value;
484 SetEntryByNumber(v, Group, Elem);
489 * \ingroup gdcmParser
490 * \brief Set a new value if the invoked element exists
491 * Seems to be useless !!!
497 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
499 std::string v = Value;
500 SetEntryByNumber(v, Group, Elem);
504 //-----------------------------------------------------------------------------
507 * \ingroup gdcmParser
508 * \brief Checks if a given Dicom Element exists
509 * \ within the H table
510 * @param group Group number of the searched Dicom Element
511 * @param element Element number of the searched Dicom Element
512 * @return number of occurences
514 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
515 std::string key = gdcmDictEntry::TranslateToKey(group, element );
516 return (tagHT.count(key));
520 * \ingroup gdcmParser
521 * \brief Searches within Header Entries (Dicom Elements) parsed with
522 * the public and private dictionaries
523 * for the element value of a given tag.
524 * \warning Don't use any longer : use GetPubEntryByName
525 * @param tagName name of the searched element.
526 * @return Corresponding element value when it exists,
527 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
529 std::string gdcmParser::GetEntryByName(std::string tagName) {
530 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
531 if( dictEntry == NULL)
534 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
538 * \ingroup gdcmParser
539 * \brief Searches within Header Entries (Dicom Elements) parsed with
540 * the public and private dictionaries
541 * for the element value representation of a given tag.
543 * Obtaining the VR (Value Representation) might be needed by caller
544 * to convert the string typed content to caller's native type
545 * (think of C++ vs Python). The VR is actually of a higher level
546 * of semantics than just the native C++ type.
547 * @param tagName name of the searched element.
548 * @return Corresponding element value representation when it exists,
549 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
551 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
552 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
553 if( dictEntry == NULL)
556 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
557 dictEntry->GetElement());
558 return elem->GetVR();
562 * \ingroup gdcmParser
563 * \brief Searches within Header Entries (Dicom Elements) parsed with
564 * the public and private dictionaries
565 * for the element value representation of a given tag.
566 * @param group Group of the searched tag.
567 * @param element Element of the searched tag.
568 * @return Corresponding element value representation when it exists,
569 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
571 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
572 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
573 if ( ! tagHT.count(key))
575 return tagHT.find(key)->second->GetValue();
579 * \ingroup gdcmParser
580 * \brief Searches within Header Entries (Dicom Elements) parsed with
581 * the public and private dictionaries
582 * for the element value representation of a given tag..
584 * Obtaining the VR (Value Representation) might be needed by caller
585 * to convert the string typed content to caller's native type
586 * (think of C++ vs Python). The VR is actually of a higher level
587 * of semantics than just the native C++ type.
588 * @param group Group of the searched tag.
589 * @param element Element of the searched tag.
590 * @return Corresponding element value representation when it exists,
591 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
593 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
594 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
597 return elem->GetVR();
601 * \ingroup gdcmParser
602 * \brief Sets the value (string) of the Header Entry (Dicom Element)
603 * @param content string value of the Dicom Element
604 * @param tagName name of the searched Dicom Element.
605 * @return true when found
607 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
608 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
609 if( dictEntry == NULL)
612 return(SetEntryByNumber(content,dictEntry->GetGroup(),
613 dictEntry->GetElement()));
617 * \ingroup gdcmParser
618 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
619 * through it's (group, element) and modifies it's content with
621 * \warning Don't use any longer : use SetPubEntryByNumber
622 * @param content new value to substitute with
623 * @param group group of the Dicom Element to modify
624 * @param element element of the Dicom Element to modify
626 bool gdcmParser::SetEntryByNumber(std::string content,
630 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
631 if ( ! tagHT.count(key))
633 int l = content.length();
634 if(l%2) // Odd length are padded with a space (020H).
637 content = content + '\0';
642 TagHeaderEntryHT::iterator p2;
643 // DO NOT remove the following lines : they explain the stuff
644 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
645 //p2=p.first; // iterator on the first synonym
646 //a=p2->second; // H Table target column (2-nd col)
649 a = ((tagHT.equal_range(key)).first)->second;
651 a-> SetValue(content);
653 std::string vr = a->GetVR();
656 if( (vr == "US") || (vr == "SS") )
658 else if( (vr == "UL") || (vr == "SL") )
668 * \ingroup gdcmParser
669 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
670 * in the PubHeaderEntrySet of this instance
671 * through it's (group, element) and modifies it's length with
673 * \warning Use with extreme caution.
674 * @param length new length to substitute with
675 * @param group group of the entry to modify
676 * @param element element of the Entry to modify
677 * @return 1 on success, 0 otherwise.
679 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
683 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
684 if ( ! tagHT.count(key))
686 if (length%2) length++; // length must be even
687 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
693 * \ingroup gdcmParser
694 * \brief Gets (from Header) the offset of a 'non string' element value
695 * \ (LoadElementValues has already be executed)
698 * @return File Offset of the Element Value
700 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
702 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
705 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
706 "failed to Locate gdcmHeaderEntry");
709 return Entry->GetOffset();
713 * \ingroup gdcmParser
714 * \brief Gets (from Header) a 'non string' element value
715 * \ (LoadElementValues has already be executed)
718 * @return Pointer to the 'non string' area
720 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
722 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
725 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
726 "failed to Locate gdcmHeaderEntry");
729 return Entry->GetVoidArea();
733 * \ingroup gdcmParser
734 * \brief Loads (from disk) the element content
735 * when a string is not suitable
739 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
741 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
744 size_t o =(size_t)Element->GetOffset();
745 fseek(fp, o, SEEK_SET);
746 int l=Element->GetLength();
747 void * a = malloc(l);
751 SetEntryVoidAreaByNumber(a, Group, Elem);
752 // TODO check the result
753 size_t l2 = fread(a, 1, l ,fp);
764 * \ingroup gdcmParser
765 * \brief Sets a 'non string' value to a given Dicom Element
767 * @param group Group number of the searched Dicom Element
768 * @param element Element number of the searched Dicom Element
771 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
775 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
776 if ( ! tagHT.count(key))
778 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
783 * \ingroup gdcmParser
784 * \brief Update the entries with the shadow dictionary. Only odd entries are
787 void gdcmParser::UpdateShaEntries(void) {
788 gdcmDictEntry *entry;
791 for(ListTag::iterator it=listEntries.begin();
792 it!=listEntries.end();
795 // Odd group => from public dictionary
796 if((*it)->GetGroup()%2==0)
799 // Peer group => search the corresponding dict entry
801 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
805 if((*it)->IsImplicitVR())
810 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
812 // Set the new entry and the new value
813 (*it)->SetDictEntry(entry);
814 CheckHeaderEntryVR(*it,vr);
816 (*it)->SetValue(GetHeaderEntryValue(*it));
820 // Remove precedent value transformation
821 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
827 * \ingroup gdcmParser
828 * \brief Searches within the Header Entries for a Dicom Element of
830 * @param tagName name of the searched Dicom Element.
831 * @return Corresponding Dicom Element when it exists, and NULL
834 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
835 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
836 if( dictEntry == NULL)
839 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
843 * \ingroup gdcmParser
844 * \brief retrieves a Dicom Element (the first one) using (group, element)
845 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
846 * if you think it's NOT UNIQUE, check the count number
847 * and use iterators to retrieve ALL the Dicoms Elements within
848 * a given couple (group, element)
849 * @param group Group number of the searched Dicom Element
850 * @param element Element number of the searched Dicom Element
853 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
855 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
856 if ( ! tagHT.count(key))
858 return tagHT.find(key)->second;
862 * \ingroup gdcmParser
863 * \brief retrieves the Dicom Elements (all of them) using (group, element)
864 * @param group Group number of the searched Dicom Element.
865 * @param element Element number of the searched Dicom Element.
866 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
869 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
870 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
871 return (tagHT.equal_range(key));
875 * \ingroup gdcmParser
876 * \brief Loads the element while preserving the current
877 * underlying file position indicator as opposed to
878 * to LoadHeaderEntry that modifies it.
879 * @param entry Header Entry whose value shall be loaded.
882 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
883 long PositionOnEntry = ftell(fp);
884 LoadHeaderEntry(entry);
885 fseek(fp, PositionOnEntry, SEEK_SET);
889 * \ingroup gdcmParser
890 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
891 * \warning : to be re-written using the chained list instead of the H table.
892 * \warning : DO NOT use (doesn't work any longer because of the multimap)
893 * \todo : to be re-written using the chained list instead of the H table
894 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
895 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
897 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
901 gdcmHeaderEntry *elem;
903 std::string str_trash;
906 GroupHT groupHt; // to hold the length of each group
909 // typedef std::map<GroupKey, int> GroupHT;
911 gdcmHeaderEntry *elemZ;
913 // for each Tag in the DCM Header
915 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
920 gr = elem->GetGroup();
921 el = elem->GetElement();
924 sprintf(trash, "%04x", gr);
925 key = trash; // generate 'group tag'
927 // if the caller decided not to take SEQUENCEs into account
928 // e.g : he wants to write an ACR-NEMA File
930 if (SkipSequence && vr == "SQ")
933 // Still unsolved problem :
934 // we cannot find the 'Sequence Delimitation Item'
935 // since it's at the end of the Hash Table
938 // pas SEQUENCE en ACR-NEMA
940 // --> la descente a l'interieur' des SQ
941 // devrait etre faite avec une liste chainee, pas avec une HTable...
943 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
945 if (el == 0x0000) // the first elem is 0x0000
947 groupHt[key] = 0; // initialize group length
951 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
954 else // any elem but the first
956 if (type == ExplicitVR)
958 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
960 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
963 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
967 unsigned short int gr_bid;
969 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
973 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
974 // warning: unsigned int format, different type arg
975 sscanf(g->first.c_str(),"%x",&gr_bid);
976 tk = g->first + "|0000"; // generate the element full tag
978 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
980 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
981 elemZ = new gdcmHeaderEntry(tagZ);
983 AddHeaderEntry(elemZ); // create it
987 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
989 sprintf(trash ,"%d",g->second);
991 elemZ->SetValue(str_trash);
996 * \ingroup gdcmParser
997 * \brief writes on disc according to the requested format
998 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
999 * \ warning does NOT add the missing elements in the header :
1000 * \ it's up to the user doing it !
1001 * \ (function CheckHeaderCoherence to be written)
1002 * \ warning DON'T try, right now, to write a DICOM image
1003 * \ from an ACR Header (meta elements will be missing!)
1004 * @param type type of the File to be written
1005 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1006 * @param _fp already open file pointer
1008 void gdcmParser::WriteEntries(FILE *_fp,FileType type)
1018 std::vector<std::string> tokens;
1020 // TODO : function CheckHeaderCoherence to be written
1022 // uses now listEntries to iterate, not TagHt!
1024 // pb : gdcmParser.Add does NOT update listEntries
1025 // TODO : find a trick (in STL?) to do it, at low cost !
1029 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1032 for (ListTag::iterator tag2=listEntries.begin();
1033 tag2 != listEntries.end();
1036 gr = (*tag2)->GetGroup();
1037 el = (*tag2)->GetElement();
1038 lgr = (*tag2)->GetReadLength();
1039 val = (*tag2)->GetValue().c_str();
1040 vr = (*tag2)->GetVR();
1041 voidArea = (*tag2)->GetVoidArea();
1045 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
1046 if (gr %2) continue; // ignore shadow groups
1047 if (vr == "SQ" ) continue; // ignore Sequences
1048 // TODO : find a trick to *skip* the SeQuences !
1049 // Not only ignore the SQ element
1050 if (gr == 0xfffe ) continue; // ignore delimiters
1053 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1054 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1056 // === Deal with the length
1057 // --------------------
1059 // if ( (type == ExplicitVR) && (gr <= 0x0002) ) // ?!? < 2
1060 if ( (type == ExplicitVR) || (type == DICOMDIR) )
1063 guint16 z=0, shortLgr;
1064 if (vr == "unkn") { // Unknown was 'written'
1066 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1067 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1069 if (gr != 0xfffe) { // NO value for 'delimiters'
1070 if (vr == "unkn") // Unknown was 'written'
1071 fwrite(&z,(size_t)2 ,(size_t)1 ,_fp);
1073 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1076 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") || gr == 0xfffe)
1079 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1080 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1085 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1091 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1094 // === Deal with the value
1095 // -------------------
1096 if (vr == "SQ") continue; // no "value" to write for the SEQuences
1097 if (gr == 0xfffe)continue;
1099 if (voidArea != NULL) { // there is a 'non string' LUT, overlay, etc
1100 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1104 if (vr == "US" || vr == "SS")
1106 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1107 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1108 for (unsigned int i=0; i<tokens.size();i++)
1110 val_uint16 = atoi(tokens[i].c_str());
1112 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1117 if (vr == "UL" || vr == "SL")
1119 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1120 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1121 for (unsigned int i=0; i<tokens.size();i++)
1123 val_uint32 = atoi(tokens[i].c_str());
1125 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1131 // Pixels are never loaded in the element !
1132 // we stop writting when Pixel are processed
1133 // FIX : we loose trailing elements (RAB, right now)
1135 if ((gr == GrPixel) && (el == NumPixel) ) {
1137 if (compte == countGrPixel) // we passed *all* the GrPixel,NumPixel
1140 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1145 * \ingroup gdcmParser
1146 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1148 * @return The properly swaped 32 bits integer.
1150 guint32 gdcmParser::SwapLong(guint32 a) {
1155 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1156 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1160 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1164 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1167 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1174 * \ingroup gdcmParser
1175 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1177 * @return The properly unswaped 32 bits integer.
1179 guint32 gdcmParser::UnswapLong(guint32 a) {
1180 return (SwapLong(a));
1184 * \ingroup gdcmParser
1185 * \brief Swaps the bytes so they agree with the processor order
1186 * @return The properly swaped 16 bits integer.
1188 guint16 gdcmParser::SwapShort(guint16 a) {
1189 if ( (sw==4321) || (sw==2143) )
1190 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1195 * \ingroup gdcmParser
1196 * \brief Unswaps the bytes so they agree with the processor order
1197 * @return The properly unswaped 16 bits integer.
1199 guint16 gdcmParser::UnswapShort(guint16 a) {
1200 return (SwapShort(a));
1203 //-----------------------------------------------------------------------------
1206 * \ingroup gdcmParser
1207 * \brief Parses the header of the file but WITHOUT loading element values.
1208 * @return false if file is not ACR-NEMA / DICOM
1210 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1216 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1217 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1218 SkipHeaderEntry(newHeaderEntry);
1219 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1220 AddHeaderEntry(newHeaderEntry);
1227 * \ingroup gdcmParser
1228 * \brief Loads the element values of all the Header Entries pointed in the
1229 * public Chained List.
1231 void gdcmParser::LoadHeaderEntries(void) {
1233 for (ListTag::iterator i = GetListEntry().begin();
1234 i != GetListEntry().end();
1237 LoadHeaderEntry(*i);
1242 // Load 'non string' values
1243 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1244 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1245 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1246 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1247 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1248 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1250 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1251 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1252 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1254 //FIXME : how to use it?
1255 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1257 // --------------------------------------------------------------
1258 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1260 // if recognition code tells us we deal with a LibIDO image
1261 // we switch lineNumber and columnNumber
1263 std::string RecCode;
1264 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1265 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1266 RecCode == "CANRME_AILIBOD1_1." )
1268 filetype = ACR_LIBIDO;
1269 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1270 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1271 SetEntryByNumber(columns, 0x0028, 0x0010);
1272 SetEntryByNumber(rows , 0x0028, 0x0011);
1274 // ----------------- End of Special Patch ----------------
1278 * \ingroup gdcmParser
1279 * \brief Loads the element content if its length doesn't exceed
1280 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1281 * @param Entry Header Entry (Dicom Element) to be dealt with
1283 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1285 guint16 group = Entry->GetGroup();
1286 std::string vr= Entry->GetVR();
1287 guint32 length = Entry->GetLength();
1288 bool SkipLoad = false;
1290 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1292 // the test was commented out to 'go inside' the SeQuences
1293 // we don't any longer skip them !
1295 // if( vr == "SQ" ) // (DO NOT remove this comment)
1298 // A SeQuence "contains" a set of Elements.
1299 // (fffe e000) tells us an Element is beginning
1300 // (fffe e00d) tells us an Element just ended
1301 // (fffe e0dd) tells us the current SeQuence just ended
1302 if( group == 0xfffe )
1306 Entry->SetLength(0);
1307 Entry->SetValue("gdcm::Skipped");
1311 // When the length is zero things are easy:
1312 if ( length == 0 ) {
1313 Entry->SetValue("");
1317 // The elements whose length is bigger than the specified upper bound
1318 // are not loaded. Instead we leave a short notice of the offset of
1319 // the element content and it's length.
1320 if (length > MaxSizeLoadEntry) {
1321 std::ostringstream s;
1322 s << "gdcm::NotLoaded.";
1323 s << " Address:" << (long)Entry->GetOffset();
1324 s << " Length:" << Entry->GetLength();
1325 s << " x(" << std::hex << Entry->GetLength() << ")";
1326 Entry->SetValue(s.str());
1330 // When integer(s) are expected, read and convert the following
1331 // n *(two or four bytes)
1332 // properly i.e. as integers as opposed to strings.
1333 // Elements with Value Multiplicity > 1
1334 // contain a set of integers (not a single one)
1336 // Any compacter code suggested (?)
1337 if ( IsHeaderEntryAnInteger(Entry) ) {
1339 std::ostringstream s;
1341 if (vr == "US" || vr == "SS") {
1343 NewInt = ReadInt16();
1346 for (int i=1; i < nbInt; i++) {
1348 NewInt = ReadInt16();
1353 else if (vr == "UL" || vr == "SL") {
1355 NewInt = ReadInt32();
1358 for (int i=1; i < nbInt; i++) {
1360 NewInt = ReadInt32();
1365 #ifdef GDCM_NO_ANSI_STRING_STREAM
1366 s << std::ends; // to avoid oddities on Solaris
1367 #endif //GDCM_NO_ANSI_STRING_STREAM
1369 Entry->SetValue(s.str());
1373 // We need an additional byte for storing \0 that is not on disk
1374 std::string NewValue(length,0);
1375 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1376 if ( item_read != 1 ) {
1377 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1378 Entry->SetValue("gdcm::UnRead");
1382 if( (vr == "UI") ) // Because of correspondance with the VR dic
1383 Entry->SetValue(NewValue.c_str()); // ??? JPR ???
1385 Entry->SetValue(NewValue);
1389 * \ingroup gdcmParser
1390 * \brief add a new Dicom Element pointer to
1391 * the H Table and to the chained List
1392 * \warning push_bash in listEntries ONLY during ParseHeader
1393 * \TODO something to allow further Elements addition,
1394 * \ when position to be taken care of
1395 * @param newHeaderEntry
1397 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1398 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1399 listEntries.push_back(newHeaderEntry);
1404 * \ingroup gdcmParser
1406 * @param Entry Header Entry whose length of the value shall be loaded.
1410 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1411 guint16 element = Entry->GetElement();
1412 guint16 group = Entry->GetGroup();
1413 std::string vr = Entry->GetVR();
1415 if( (element == NumPixel) && (group == GrPixel) )
1418 dbg.Verbose(2, "gdcmParser::FindLength: ",
1419 "we reached (GrPixel,NumPixel)");
1422 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1424 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1426 // The following reserved two bytes (see PS 3.5-2001, section
1427 // 7.1.2 Data element structure with explicit vr p27) must be
1428 // skipped before proceeding on reading the length on 4 bytes.
1429 fseek(fp, 2L, SEEK_CUR);
1430 guint32 length32 = ReadInt32();
1432 if ( (vr == "OB") && (length32 == 0xffffffff) )
1434 Entry->SetLength(FindHeaderEntryLengthOB());
1437 FixHeaderEntryFoundLength(Entry, length32);
1441 // Length is encoded on 2 bytes.
1442 length16 = ReadInt16();
1444 // We can tell the current file is encoded in big endian (like
1445 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1446 // and it's value is the one of the encoding of a big endian file.
1447 // In order to deal with such big endian encoded files, we have
1448 // (at least) two strategies:
1449 // * when we load the "Transfer Syntax" tag with value of big endian
1450 // encoding, we raise the proper flags. Then we wait for the end
1451 // of the META group (0x0002) among which is "Transfer Syntax",
1452 // before switching the swap code to big endian. We have to postpone
1453 // the switching of the swap code since the META group is fully encoded
1454 // in little endian, and big endian coding only starts at the next
1455 // group. The corresponding code can be hard to analyse and adds
1456 // many additional unnecessary tests for regular tags.
1457 // * the second strategy consists in waiting for trouble, that shall
1458 // appear when we find the first group with big endian encoding. This
1459 // is easy to detect since the length of a "Group Length" tag (the
1460 // ones with zero as element number) has to be of 4 (0x0004). When we
1461 // encounter 1024 (0x0400) chances are the encoding changed and we
1462 // found a group with big endian encoding.
1463 // We shall use this second strategy. In order to make sure that we
1464 // can interpret the presence of an apparently big endian encoded
1465 // length of a "Group Length" without committing a big mistake, we
1466 // add an additional check: we look in the already parsed elements
1467 // for the presence of a "Transfer Syntax" whose value has to be "big
1468 // endian encoding". When this is the case, chances are we have got our
1469 // hands on a big endian encoded file: we switch the swap code to
1470 // big endian and proceed...
1471 if ( (element == 0x0000) && (length16 == 0x0400) )
1473 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1475 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1480 SwitchSwapToBigEndian();
1481 // Restore the unproperly loaded values i.e. the group, the element
1482 // and the dictionary entry depending on them.
1483 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1484 guint16 CorrectElem = SwapShort(Entry->GetElement());
1485 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1489 // This correct tag is not in the dictionary. Create a new one.
1490 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1492 // FIXME this can create a memory leaks on the old entry that be
1493 // left unreferenced.
1494 Entry->SetDictEntry(NewTag);
1497 // Heuristic: well some files are really ill-formed.
1498 if ( length16 == 0xffff)
1501 //dbg.Verbose(0, "gdcmParser::FindLength",
1502 // "Erroneous element length fixed.");
1503 // Actually, length= 0xffff means that we deal with
1504 // Unknown Sequence Length
1507 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1512 // Either implicit VR or a non DICOM conformal (see not below) explicit
1513 // VR that ommited the VR of (at least) this element. Farts happen.
1514 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1515 // on Data elements "Implicit and Explicit VR Data Elements shall
1516 // not coexist in a Data Set and Data Sets nested within it".]
1517 // Length is on 4 bytes.
1518 FixHeaderEntryFoundLength(Entry, ReadInt32());
1524 * \ingroup gdcmParser
1525 * \brief Find the Value Representation of the current Dicom Element.
1528 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1530 if (filetype != ExplicitVR)
1535 long PositionOnEntry = ftell(fp);
1536 // Warning: we believe this is explicit VR (Value Representation) because
1537 // we used a heuristic that found "UL" in the first tag. Alas this
1538 // doesn't guarantee that all the tags will be in explicit VR. In some
1539 // cases (see e-film filtered files) one finds implicit VR tags mixed
1540 // within an explicit VR file. Hence we make sure the present tag
1541 // is in explicit VR and try to fix things if it happens not to be
1544 int lgrLue=fread (&VR, (size_t)2,(size_t)1, fp); // lgrLue not used
1546 if(!CheckHeaderEntryVR(Entry,VR))
1548 fseek(fp, PositionOnEntry, SEEK_SET);
1549 // When this element is known in the dictionary we shall use, e.g. for
1550 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1551 // dictionary entry. Still we have to flag the element as implicit since
1552 // we know now our assumption on expliciteness is not furfilled.
1554 if ( Entry->IsVRUnknown() )
1555 Entry->SetVR("Implicit");
1556 Entry->SetImplicitVR();
1561 * \ingroup gdcmParser
1562 * \brief Check the correspondance between the VR of the header entry
1563 * and the taken VR. If they are different, the header entry is
1564 * updated with the new VR.
1567 * @return false if the VR is incorrect of if the VR isn't referenced
1568 * otherwise, it returns true
1570 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1572 char msg[100]; // for sprintf
1573 bool RealExplicit = true;
1575 // Assume we are reading a falsely explicit VR file i.e. we reached
1576 // a tag where we expect reading a VR but are in fact we read the
1577 // first to bytes of the length. Then we will interogate (through find)
1578 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1579 // both GCC and VC++ implementations of the STL map. Hence when the
1580 // expected VR read happens to be non-ascii characters we consider
1581 // we hit falsely explicit VR tag.
1583 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1584 RealExplicit = false;
1586 // CLEANME searching the dicom_vr at each occurence is expensive.
1587 // PostPone this test in an optional integrity check at the end
1588 // of parsing or only in debug mode.
1589 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1590 RealExplicit= false;
1592 if ( !RealExplicit )
1594 // We thought this was explicit VR, but we end up with an
1595 // implicit VR tag. Let's backtrack.
1596 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1597 Entry->GetGroup(),Entry->GetElement());
1598 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1599 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1600 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1601 Entry->GetGroup(),Entry->GetElement(),
1602 "UL","FIXME","Group Length");
1603 Entry->SetDictEntry(NewEntry);
1608 if ( Entry->IsVRUnknown() )
1610 // When not a dictionary entry, we can safely overwrite the VR.
1611 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1617 else if ( Entry->GetVR() != vr )
1619 // The VR present in the file and the dictionary disagree. We assume
1620 // the file writer knew best and use the VR of the file. Since it would
1621 // be unwise to overwrite the VR of a dictionary (since it would
1622 // compromise it's next user), we need to clone the actual DictEntry
1623 // and change the VR for the read one.
1624 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1625 Entry->GetGroup(),Entry->GetElement(),
1626 vr,"FIXME",Entry->GetName());
1627 Entry->SetDictEntry(NewEntry);
1633 * \ingroup gdcmParser
1634 * \brief Get the transformed value of the header entry. The VR value
1635 * is used to define the transformation to operate on the value
1636 * \warning NOT end user intended method !
1638 * @return Transformed entry value
1640 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1642 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1644 std::string val=Entry->GetValue();
1645 std::string vr=Entry->GetVR();
1646 guint32 length = Entry->GetLength();
1647 std::ostringstream s;
1650 if (vr == "US" || vr == "SS")
1655 for (int i=0; i < nbInt; i++)
1659 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1660 NewInt16 = SwapShort(NewInt16);
1665 else if (vr == "UL" || vr == "SL")
1670 for (int i=0; i < nbInt; i++)
1674 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1675 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1676 NewInt32=SwapLong(NewInt32);
1680 #ifdef GDCM_NO_ANSI_STRING_STREAM
1681 s << std::ends; // to avoid oddities on Solaris
1682 #endif //GDCM_NO_ANSI_STRING_STREAM
1686 return(Entry->GetValue());
1690 * \ingroup gdcmParser
1691 * \brief Get the reverse transformed value of the header entry. The VR
1692 * value is used to define the reverse transformation to operate on
1694 * \warning NOT end user intended method !
1696 * @return Reverse transformed entry value
1698 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1700 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1702 std::string vr=Entry->GetVR();
1703 std::ostringstream s;
1704 std::vector<std::string> tokens;
1706 if (vr == "US" || vr == "SS")
1710 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1711 Tokenize (Entry->GetValue(), tokens, "\\");
1712 for (unsigned int i=0; i<tokens.size();i++)
1714 NewInt16 = atoi(tokens[i].c_str());
1715 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1719 if (vr == "UL" || vr == "SL")
1723 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1724 Tokenize (Entry->GetValue(), tokens, "\\");
1725 for (unsigned int i=0; i<tokens.size();i++)
1727 NewInt32 = atoi(tokens[i].c_str());
1728 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1729 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1734 #ifdef GDCM_NO_ANSI_STRING_STREAM
1735 s << std::ends; // to avoid oddities on Solaris
1736 #endif //GDCM_NO_ANSI_STRING_STREAM
1740 return(Entry->GetValue());
1744 * \ingroup gdcmParser
1745 * \brief Skip a given Header Entry
1746 * \warning NOT end user intended method !
1749 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1751 SkipBytes(entry->GetLength());
1755 * \ingroup gdcmParser
1756 * \brief When the length of an element value is obviously wrong (because
1757 * the parser went Jabberwocky) one can hope improving things by
1758 * applying this heuristic.
1760 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1762 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1764 if ( FoundLength == 0xffffffff) {
1768 guint16 gr =Entry->GetGroup();
1769 guint16 el =Entry->GetElement();
1771 if (FoundLength%2) {
1772 std::cout << "Warning : Tag with uneven length " << FoundLength
1773 << " in x(" << std::hex << gr << "," << el <<")" << std::dec << std::endl;
1776 // Sorry for the patch!
1777 // XMedCom did the trick to read some nasty GE images ...
1778 if (FoundLength == 13) {
1779 // The following 'if' will be removed when there is no more
1780 // images on Creatis HDs with a 13 length for Manufacturer...
1781 if ( (Entry->GetGroup() != 0x0008) ||
1782 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1783 // end of remove area
1785 Entry->SetReadLength(10); // a bug is to be fixed
1789 // to fix some garbage 'Leonardo' Siemens images
1790 // May be commented out to avoid overhead
1791 else if ( (Entry->GetGroup() == 0x0009) &&
1792 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1794 Entry->SetReadLength(4); // a bug is to be fixed
1798 // to try to 'go inside' SeQuences (with length), and not to skip them
1799 else if ( Entry->GetVR() == "SQ")
1801 if (enableSequences) // only if the user does want to !
1802 FoundLength =0; // ReadLength is unchanged
1805 // a SeQuence Element is beginning
1806 // Let's forget it's length
1807 // (we want to 'go inside')
1809 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1810 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1811 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1812 // if we don't, we lost 28800 characters from the Header :-(
1814 else if(Entry->GetGroup() == 0xfffe)
1816 // sometimes, length seems to be wrong
1817 FoundLength =0; // some more clever checking to be done !
1819 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1820 // causes troubles :-(
1823 Entry->SetUsableLength(FoundLength);
1827 * \ingroup gdcmParser
1828 * \brief Apply some heuristics to predict wether the considered
1829 * element value contains/represents an integer or not.
1830 * @param Entry The element value on which to apply the predicate.
1831 * @return The result of the heuristical predicate.
1833 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1834 guint16 element = Entry->GetElement();
1835 guint16 group = Entry->GetGroup();
1836 std::string vr = Entry->GetVR();
1837 guint32 length = Entry->GetLength();
1838 // When we have some semantics on the element we just read, and if we
1839 // a priori know we are dealing with an integer, then we shall be
1840 // able to swap it's element value properly.
1841 if ( element == 0 ) // This is the group length of the group
1847 std::ostringstream s;
1848 int filePosition = ftell(fp);
1849 s << "Erroneous Group Length element length on : (" \
1850 << std::hex << group << " , " << element
1851 << ") -before- position x(" << filePosition << ")"
1852 << "lgt : " << length;
1853 // These 2 lines commented out : a *very dirty* patch
1854 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1855 // have a glance at offset x(8336) ...
1856 // For *regular* headers, the test is useless..
1857 // lets's print a warning message and go on,
1858 // instead of giving up with an error message
1860 //std::cout << s.str().c_str() << std::endl;
1862 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1863 // s.str().c_str());
1866 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1873 * \ingroup gdcmParser
1878 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1879 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1882 long PositionOnEntry = ftell(fp);
1883 bool FoundSequenceDelimiter = false;
1884 guint32 TotalLength = 0;
1887 while ( ! FoundSequenceDelimiter)
1893 TotalLength += 4; // We even have to decount the group and element
1895 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1897 char msg[100]; // for sprintf. Sorry
1898 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1899 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1903 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1904 FoundSequenceDelimiter = true;
1905 else if ( n != 0xe000 )
1907 char msg[100]; // for sprintf. Sorry
1908 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1910 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1914 ItemLength = ReadInt32();
1915 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1916 // the ItemLength with ReadInt32
1917 SkipBytes(ItemLength);
1919 fseek(fp, PositionOnEntry, SEEK_SET);
1924 * \ingroup gdcmParser
1925 * \brief Reads a supposed to be 16 Bits integer
1926 * \ (swaps it depending on processor endianity)
1928 * @return read value
1930 guint16 gdcmParser::ReadInt16(void) {
1933 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1934 if ( item_read != 1 ) {
1936 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1946 * \ingroup gdcmParser
1947 * \brief Reads a supposed to be 32 Bits integer
1948 * \ (swaps it depending on processor endianity)
1950 * @return read value
1952 guint32 gdcmParser::ReadInt32(void) {
1955 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1956 if ( item_read != 1 ) {
1958 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1968 * \ingroup gdcmParser
1973 void gdcmParser::SkipBytes(guint32 NBytes) {
1974 //FIXME don't dump the returned value
1975 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1979 * \ingroup gdcmParser
1982 void gdcmParser::Initialise(void)
1984 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1985 RefShaDict = (gdcmDict*)0;
1989 * \ingroup gdcmParser
1990 * \brief Discover what the swap code is (among little endian, big endian,
1991 * bad little endian, bad big endian).
1993 * @return false when we are absolutely sure
1994 * it's neither ACR-NEMA nor DICOM
1995 * true when we hope ours assuptions are OK
1997 bool gdcmParser::CheckSwap() {
1999 // The only guaranted way of finding the swap code is to find a
2000 // group tag since we know it's length has to be of four bytes i.e.
2001 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2002 // occurs when we can't find such group...
2004 guint32 x=4; // x : for ntohs
2005 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2011 char deb[HEADER_LENGTH_TO_READ];
2013 // First, compare HostByteOrder and NetworkByteOrder in order to
2014 // determine if we shall need to swap bytes (i.e. the Endian type).
2020 // The easiest case is the one of a DICOM header, since it possesses a
2021 // file preamble where it suffice to look for the string "DICM".
2022 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2025 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2026 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2028 // Next, determine the value representation (VR). Let's skip to the
2029 // first element (0002, 0000) and check there if we find "UL"
2030 // - or "OB" if the 1st one is (0002,0001) -,
2031 // in which case we (almost) know it is explicit VR.
2032 // WARNING: if it happens to be implicit VR then what we will read
2033 // is the length of the group. If this ascii representation of this
2034 // length happens to be "UL" then we shall believe it is explicit VR.
2035 // FIXME: in order to fix the above warning, we could read the next
2036 // element value (or a couple of elements values) in order to make
2037 // sure we are not commiting a big mistake.
2038 // We need to skip :
2039 // * the 128 bytes of File Preamble (often padded with zeroes),
2040 // * the 4 bytes of "DICM" string,
2041 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2042 // i.e. a total of 136 bytes.
2046 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2047 // but elem 0002,0010 (Transfert Syntax) tells us the file is *Implicit* VR.
2050 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2051 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2052 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2053 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2054 // when Write DCM *adds*
2056 // Use gdcmParser::dicom_vr to test all the possibilities
2057 // instead of just checking for UL, OB and UI !? // group 0000
2060 filetype = ExplicitVR;
2061 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2062 "explicit Value Representation");
2066 filetype = ImplicitVR;
2067 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2068 "not an explicit Value Representation");
2074 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2075 "HostByteOrder != NetworkByteOrder");
2080 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2081 "HostByteOrder = NetworkByteOrder");
2084 // Position the file position indicator at first tag (i.e.
2085 // after the file preamble and the "DICM" string).
2087 fseek (fp, 132L, SEEK_SET);
2091 // Alas, this is not a DicomV3 file and whatever happens there is no file
2092 // preamble. We can reset the file position indicator to where the data
2093 // is (i.e. the beginning of the file).
2094 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2097 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2098 // By clean we mean that the length of the first tag is written down.
2099 // If this is the case and since the length of the first group HAS to be
2100 // four (bytes), then determining the proper swap code is straightforward.
2103 // We assume the array of char we are considering contains the binary
2104 // representation of a 32 bits integer. Hence the following dirty
2106 s32 = *((guint32 *)(entCur));
2127 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2128 // It is time for despaired wild guesses.
2129 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2130 // i.e. the 'group length' element is not present :
2132 // check the supposed to be 'group number'
2133 // 0x0002 or 0x0004 or 0x0008
2134 // to determine ' sw' value .
2135 // Only 0 or 4321 will be possible
2136 // (no oportunity to check for the formerly well known
2137 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2138 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2139 // the file IS NOT ACR-NEMA nor DICOM V3
2140 // Find a trick to tell it the caller...
2142 s16 = *((guint16 *)(deb));
2158 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2159 "ACR/NEMA unfound swap info (Really hopeless !)");
2164 // Then the only info we have is the net2host one.
2174 * \ingroup gdcmParser
2177 void gdcmParser::SwitchSwapToBigEndian(void)
2179 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2180 "Switching to BigEndian mode.");
2201 * \ingroup gdcmParser
2205 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2209 if ((guint32)NewSize >= (guint32)0xffffffff)
2211 MaxSizeLoadEntry = 0xffffffff;
2214 MaxSizeLoadEntry = NewSize;
2219 * \ingroup gdcmParser
2221 * \warning TODO : not yet usable
2222 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2223 * in gdcmHeaderEntry gdcmLoadEntry)
2227 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2231 if ((guint32)NewSize >= (guint32)0xffffffff)
2233 MaxSizePrintEntry = 0xffffffff;
2236 MaxSizePrintEntry = NewSize;
2240 * \ingroup gdcmParser
2241 * \brief Searches both the public and the shadow dictionary (when they
2242 * exist) for the presence of the DictEntry with given name.
2243 * The public dictionary has precedence on the shadow one.
2244 * @param Name name of the searched DictEntry
2245 * @return Corresponding DictEntry when it exists, NULL otherwise.
2247 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2249 gdcmDictEntry *found = (gdcmDictEntry *)0;
2250 if (!RefPubDict && !RefShaDict)
2252 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2253 "we SHOULD have a default dictionary");
2257 found = RefPubDict->GetDictEntryByName(Name);
2263 found = RefShaDict->GetDictEntryByName(Name);
2271 * \ingroup gdcmParser
2272 * \brief Searches both the public and the shadow dictionary (when they
2273 * exist) for the presence of the DictEntry with given
2274 * group and element. The public dictionary has precedence on the
2276 * @param group group of the searched DictEntry
2277 * @param element element of the searched DictEntry
2278 * @return Corresponding DictEntry when it exists, NULL otherwise.
2280 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2282 gdcmDictEntry *found = (gdcmDictEntry *)0;
2283 if (!RefPubDict && !RefShaDict)
2285 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2286 "we SHOULD have a default dictionary");
2290 found = RefPubDict->GetDictEntryByNumber(group, element);
2296 found = RefShaDict->GetDictEntryByNumber(group, element);
2304 * \ingroup gdcmParser
2305 * \brief Read the next tag but WITHOUT loading it's value
2306 * @return On succes the newly created HeaderEntry, NULL on failure.
2308 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2310 gdcmHeaderEntry *NewEntry;
2315 // We reached the EOF (or an error occured) therefore
2316 // header parsing has to be considered as finished.
2317 return (gdcmHeaderEntry *)0;
2319 /* Pb : how to propagate the element length (used in SkipHeaderEntry)
2320 // direct call to SkipBytes ?
2322 if (ignoreShadow == 1 && g%2 ==1) //JPR
2323 // if user wants to skip shadow groups
2324 // and current element *is* a shadow element
2325 // we don't create anything
2326 return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2328 NewEntry = NewHeaderEntryByNumber(g, n);
2329 FindHeaderEntryVR(NewEntry);
2330 FindHeaderEntryLength(NewEntry);
2336 NewEntry->SetOffset(ftell(fp));
2341 * \ingroup gdcmParser
2342 * \brief Build a new Element Value from all the low level arguments.
2343 * Check for existence of dictionary entry, and build
2344 * a default one when absent.
2345 * @param Name Name of the underlying DictEntry
2347 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2349 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2351 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2353 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2356 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2357 "failed to allocate gdcmHeaderEntry");
2358 return (gdcmHeaderEntry *)0;
2364 * \ingroup gdcmParser
2365 * \brief Request a new virtual dict entry to the dict set
2366 * @param group group of the underlying DictEntry
2367 * @param elem element of the underlying DictEntry
2368 * @param vr VR of the underlying DictEntry
2369 * @param fourth owner group
2370 * @param name english name
2372 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2377 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2381 * \ingroup gdcmParser
2382 * \brief Build a new Element Value from all the low level arguments.
2383 * Check for existence of dictionary entry, and build
2384 * a default one when absent.
2385 * @param Group group of the underlying DictEntry
2386 * @param Elem element of the underlying DictEntry
2388 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2390 // Find out if the tag we encountered is in the dictionaries:
2391 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2393 DictEntry = NewVirtualDictEntry(Group, Elem);
2395 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2398 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2399 "failed to allocate gdcmHeaderEntry");
2405 // Never used; commented out, waiting for removal.
2407 * \ingroup gdcmParser
2408 * \brief Small utility function that creates a new manually crafted
2409 * (as opposed as read from the file) gdcmHeaderEntry with user
2410 * specified name and adds it to the public tag hash table.
2411 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2412 * @param NewTagName The name to be given to this new tag.
2413 * @param VR The Value Representation to be given to this new tag.
2414 * @return The newly hand crafted Element Value.
2416 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2419 // gdcmHeaderEntry *NewEntry = NULL;
2420 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2421 // guint32 FreeElem = 0;
2422 // gdcmDictEntry *DictEntry = NULL;
2424 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2425 // if (FreeElem == UINT32_MAX)
2427 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2428 // "Group 0xffff in Public Dict is full");
2432 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2433 // VR, "GDCM", NewTagName);
2434 // NewEntry = new gdcmHeaderEntry(DictEntry);
2435 // AddHeaderEntry(NewEntry);
2440 * \ingroup gdcmParser
2441 * \brief Generate a free TagKey i.e. a TagKey that is not present
2442 * in the TagHt dictionary.
2443 * @param group The generated tag must belong to this group.
2444 * @return The element of tag with given group which is fee.
2446 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2448 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2450 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2451 if (tagHT.count(key) == 0)
2457 //-----------------------------------------------------------------------------