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 // Other usefull abreviations :
68 //Radiographic view associated with Patient Position (0018,5100).
71 // AP = Anterior/Posterior
72 // PA = Posterior/Anterior
75 // RLD = Right Lateral Decubitus
76 // LLD = Left Lateral Decubitus
77 // RLO = Right Lateral Oblique
78 // LLO = Left Lateral Oblique
80 //-----------------------------------------------------------------------------
81 // Refer to gdcmParser::CheckSwap()
82 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
84 // Refer to gdcmParser::SetMaxSizeLoadEntry()
85 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
87 // Refer to gdcmParser::SetMaxSizePrintEntry()
88 // TODO : Right now, better see "define, in gdcmHederEntry.cxx
89 const unsigned int gdcmParser::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
91 //-----------------------------------------------------------------------------
92 // Constructor / Destructor
97 * @param exception_on_error
98 * @param enable_sequences = true to allow the header
99 * to be parsed *inside* the SeQuences,
100 * when they have an actual length
101 * @param ignore_shadow to allow skipping the shadow elements,
102 * to save memory space.
103 * \warning The TRUE value for this param has to be used
104 * with a FALSE value for the 'enable_sequence' param.
105 * ('public elements' may be embedded in 'shadow Sequences')
107 gdcmParser::gdcmParser(const char *InFilename,
108 bool exception_on_error,
109 bool enable_sequences,
110 bool ignore_shadow) {
111 enableSequences=enable_sequences;
112 ignoreShadow =ignore_shadow;
114 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
115 filename = InFilename;
118 if ( !OpenFile(exception_on_error))
125 wasUpdated = 0; // will be set to 1 if user adds an entry
126 printLevel = 1; // 'Medium' print level by default
130 * \ingroup gdcmParser
132 * @param exception_on_error
134 gdcmParser::gdcmParser(bool exception_on_error) {
137 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
140 wasUpdated = 0; // will be set to 1 if user adds an entry
141 printLevel = 1; // 'Medium' print level by default
145 * \ingroup gdcmParser
146 * \brief Canonical destructor.
148 gdcmParser::~gdcmParser (void) {
153 //-----------------------------------------------------------------------------
156 * \ingroup gdcmParser
157 * \brief Prints the Header Entries (Dicom Elements)
158 * both from the H Table and the chained list
161 void gdcmParser::PrintEntry(std::ostream & os) {
162 std::ostringstream s;
164 for (ListTag::iterator i = listEntries.begin();
165 i != listEntries.end();
168 (*i)->SetPrintLevel(printLevel);
175 * \ingroup gdcmParser
176 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
179 void gdcmParser::PrintPubDict(std::ostream & os) {
180 RefPubDict->Print(os);
184 * \ingroup gdcmParser
185 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
188 void gdcmParser::PrintShaDict(std::ostream & os) {
189 RefShaDict->Print(os);
192 //-----------------------------------------------------------------------------
195 * \ingroup gdcmParser
196 * \brief Get the public dictionary used
198 gdcmDict *gdcmParser::GetPubDict(void) {
203 * \ingroup gdcmParser
204 * \brief Get the shadow dictionary used
206 gdcmDict *gdcmParser::GetShaDict(void) {
211 * \ingroup gdcmParser
212 * \brief Set the shadow dictionary used
213 * \param dict dictionary to use in shadow
215 bool gdcmParser::SetShaDict(gdcmDict *dict){
221 * \ingroup gdcmParser
222 * \brief Set the shadow dictionary used
223 * \param dictName name of the dictionary to use in shadow
225 bool gdcmParser::SetShaDict(DictKey dictName){
226 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
231 * \ingroup gdcmParser
232 * \brief This predicate, based on hopefully reasonable heuristics,
233 * decides whether or not the current gdcmParser was properly parsed
234 * and contains the mandatory information for being considered as
235 * a well formed and usable Dicom/Acr File.
236 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
239 bool gdcmParser::IsReadable(void) {
240 if(filetype==Unknown) {
243 if(listEntries.size()<=0) {
251 * \ingroup gdcmParser
252 * \brief Determines if the Transfer Syntax was already encountered
253 * and if it corresponds to a ImplicitVRLittleEndian one.
254 * @return True when ImplicitVRLittleEndian found. False in all other cases.
256 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
257 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
260 LoadHeaderEntrySafe(Element);
262 std::string Transfer = Element->GetValue();
263 if ( Transfer == UI1_2_840_10008_1_2 )
269 * \ingroup gdcmParser
270 * \brief Determines if the Transfer Syntax was already encountered
271 * and if it corresponds to a ExplicitVRLittleEndian one.
272 * @return True when ExplicitVRLittleEndian found. False in all other cases.
274 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
275 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
278 LoadHeaderEntrySafe(Element);
280 std::string Transfer = Element->GetValue();
281 if ( Transfer == UI1_2_840_10008_1_2_1 )
287 * \ingroup gdcmParser
288 * \brief Determines if the Transfer Syntax was already encountered
289 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
290 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
292 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
293 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
296 LoadHeaderEntrySafe(Element);
298 std::string Transfer = Element->GetValue();
299 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
305 * \ingroup gdcmParser
306 * \brief Determines if the Transfer Syntax was already encountered
307 * and if it corresponds to a Explicit VR Big Endian one.
308 * @return True when big endian found. False in all other cases.
310 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
311 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
314 LoadHeaderEntrySafe(Element);
316 std::string Transfer = Element->GetValue();
317 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
323 * \ingroup gdcmParser
324 * \brief returns the File Type
325 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
326 * @return the FileType code
328 FileType gdcmParser::GetFileType(void) {
333 * \ingroup gdcmParser
334 * \brief opens the file
335 * @param exception_on_error
338 FILE *gdcmParser::OpenFile(bool exception_on_error)
341 fp=fopen(filename.c_str(),"rb");
342 if(exception_on_error)
345 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
351 fread(&zero, (size_t)2, (size_t)1, fp);
353 //ACR -- or DICOM with no Preamble --
354 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
358 fseek(fp, 126L, SEEK_CUR);
360 fread(dicm, (size_t)4, (size_t)1, fp);
361 if( memcmp(dicm, "DICM", 4) == 0 )
365 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
368 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
374 * \ingroup gdcmParser
375 * \brief closes the file
376 * @return TRUE if the close was successfull
378 bool gdcmParser::CloseFile(void) {
379 int closed = fclose(fp);
387 * \ingroup gdcmParser
389 * @param fp file pointer on an already open file
390 * @param type type of the File to be written
391 * (ACR-NEMA, ExplicitVR, ImplicitVR)
392 * @return always "True" ?!
394 bool gdcmParser::Write(FILE *fp, FileType type) {
396 // TODO The stuff was rewritten using the chained list instead
398 // so we could remove the GroupHT from the gdcmParser
402 // TODO : move the following lines (and a lot of others, to be written)
403 // to a future function CheckAndCorrectHeader
406 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
407 // (FileType est un champ de gdcmParser ...)
408 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
410 // a moins de se livrer a un tres complique ajout des champs manquants.
411 // faire un CheckAndCorrectHeader (?)
414 if (type == ImplicitVR)
416 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
417 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
419 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
420 // values with a VR of UI shall be padded with a single trailing null
421 // Dans le cas suivant on doit pader manuellement avec un 0
423 SetEntryLengthByNumber(18, 0x0002, 0x0010);
426 if (type == ExplicitVR)
428 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
429 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
431 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
432 // values with a VR of UI shall be padded with a single trailing null
433 // Dans le cas suivant on doit pader manuellement avec un 0
435 SetEntryLengthByNumber(20, 0x0002, 0x0010);
438 /* TODO : rewrite later
440 if ( (type == ImplicitVR) || (type == ExplicitVR) )
441 UpdateGroupLength(false,type);
443 UpdateGroupLength(true,ACR);
446 WriteEntries(fp,type);
451 * \ingroup gdcmParser
452 * \brief Modifies the value of a given Header Entry (Dicom Element)
453 * if it exists; Creates it with the given value if it doesn't
454 * @param Value passed as a std::string
457 * \return false only if new element creation fails
459 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
462 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
463 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
468 SetEntryByNumber(Value, Group, Elem);
473 * \ingroup gdcmParser
474 * \brief Modifies the value of a given Header Entry (Dicom Element)
475 * if it exists; Creates it with the given value if it doesn't
476 * @param Value passed as a char*
477 * @param Group group of the Entry
478 * @param Elem element of the Entry
482 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
483 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
488 AddHeaderEntry(nvHeaderEntry);
490 std::string v = Value;
491 SetEntryByNumber(v, Group, Elem);
496 * \ingroup gdcmParser
497 * \brief Set a new value if the invoked element exists
498 * Seems to be useless !!!
499 * @param Value new element value
500 * @param Group group of the Entry
501 * @param Elem element of the Entry
504 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
506 std::string v = Value;
507 SetEntryByNumber(v, Group, Elem);
511 //-----------------------------------------------------------------------------
515 * \ingroup gdcmParser
516 * \brief Checks if a given Dicom Element exists
518 * @param group Group number of the searched Dicom Element
519 * @param element Element number of the searched Dicom Element
520 * @return number of occurences
522 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
523 std::string key = gdcmDictEntry::TranslateToKey(group, element );
524 return (tagHT.count(key));
528 * \ingroup gdcmParser
529 * \brief Searches within Header Entries (Dicom Elements) parsed with
530 * the public and private dictionaries
531 * for the element value of a given tag.
532 * \warning Don't use any longer : use GetPubEntryByName
533 * @param tagName name of the searched element.
534 * @return Corresponding element value when it exists,
535 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
537 std::string gdcmParser::GetEntryByName(std::string tagName) {
538 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
539 if( dictEntry == NULL)
542 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
546 * \ingroup gdcmParser
547 * \brief Searches within Header Entries (Dicom Elements) parsed with
548 * the public and private dictionaries
549 * for the element value representation of a given tag.
551 * Obtaining the VR (Value Representation) might be needed by caller
552 * to convert the string typed content to caller's native type
553 * (think of C++ vs Python). The VR is actually of a higher level
554 * of semantics than just the native C++ type.
555 * @param tagName name of the searched element.
556 * @return Corresponding element value representation when it exists,
557 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
559 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
560 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
561 if( dictEntry == NULL)
564 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
565 dictEntry->GetElement());
566 return elem->GetVR();
570 * \ingroup gdcmParser
571 * \brief Searches within Header Entries (Dicom Elements) parsed with
572 * the public and private dictionaries
573 * for the element value representation of a given tag.
574 * @param group Group of the searched tag.
575 * @param element Element of the searched tag.
576 * @return Corresponding element value representation when it exists,
577 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
579 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
580 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
581 if ( ! tagHT.count(key))
583 return tagHT.find(key)->second->GetValue();
587 * \ingroup gdcmParser
588 * \brief Searches within Header Entries (Dicom Elements) parsed with
589 * the public and private dictionaries
590 * for the element value representation of a given tag..
592 * Obtaining the VR (Value Representation) might be needed by caller
593 * to convert the string typed content to caller's native type
594 * (think of C++ vs Python). The VR is actually of a higher level
595 * of semantics than just the native C++ type.
596 * @param group Group of the searched tag.
597 * @param element Element of the searched tag.
598 * @return Corresponding element value representation when it exists,
599 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
601 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
602 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
605 return elem->GetVR();
609 * \ingroup gdcmParser
610 * \brief Sets the value (string) of the Header Entry (Dicom Element)
611 * @param content string value of the Dicom Element
612 * @param tagName name of the searched Dicom Element.
613 * @return true when found
615 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
616 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
617 if( dictEntry == NULL)
620 return(SetEntryByNumber(content,dictEntry->GetGroup(),
621 dictEntry->GetElement()));
625 * \ingroup gdcmParser
626 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
627 * through it's (group, element) and modifies it's content with
629 * \warning Don't use any longer : use SetPubEntryByNumber
630 * @param content new value to substitute with
631 * @param group group of the Dicom Element to modify
632 * @param element element of the Dicom Element to modify
634 bool gdcmParser::SetEntryByNumber(std::string content,
638 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
639 if ( ! tagHT.count(key))
641 int l = content.length();
642 if(l%2) // Non even length are padded with a space (020H).
645 content = content + '\0';
650 TagHeaderEntryHT::iterator p2;
651 // DO NOT remove the following lines : they explain the stuff
652 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
653 //p2=p.first; // iterator on the first synonym
654 //a=p2->second; // H Table target column (2-nd col)
657 a = ((tagHT.equal_range(key)).first)->second;
659 a-> SetValue(content);
661 std::string vr = a->GetVR();
664 if( (vr == "US") || (vr == "SS") )
666 else if( (vr == "UL") || (vr == "SL") )
676 * \ingroup gdcmParser
677 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
678 * in the PubHeaderEntrySet of this instance
679 * through it's (group, element) and modifies it's length with
681 * \warning Use with extreme caution.
682 * @param l new length to substitute with
683 * @param group group of the Entry to modify
684 * @param element element of the Entry to modify
685 * @return 1 on success, 0 otherwise.
687 bool gdcmParser::SetEntryLengthByNumber(guint32 l,
691 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
692 if ( ! tagHT.count(key))
694 if (l%2) l++; // length must be even
695 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
701 * \ingroup gdcmParser
702 * \brief Gets (from Header) the offset of a 'non string' element value
703 * (LoadElementValues has already be executed)
704 * @param Group group of the Entry
705 * @param Elem element of the Entry
706 * @return File Offset of the Element Value
708 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
710 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
713 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
714 "failed to Locate gdcmHeaderEntry");
717 return Entry->GetOffset();
721 * \ingroup gdcmParser
722 * \brief Gets (from Header) a 'non string' element value
723 * (LoadElementValues has already be executed)
724 * @param Group group of the Entry
725 * @param Elem element of the Entry
726 * @return Pointer to the 'non string' area
728 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
730 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
733 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
734 "failed to Locate gdcmHeaderEntry");
737 return Entry->GetVoidArea();
741 * \ingroup gdcmParser
742 * \brief Loads (from disk) the element content
743 * when a string is not suitable
744 * @param Group group of the Entry
745 * @param Elem element of the Entry
747 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
749 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
752 size_t o =(size_t)Element->GetOffset();
753 fseek(fp, o, SEEK_SET);
754 int l=Element->GetLength();
755 void * a = malloc(l);
759 SetEntryVoidAreaByNumber(a, Group, Elem);
760 // TODO check the result
761 size_t l2 = fread(a, 1, l ,fp);
772 * \ingroup gdcmParser
773 * \brief Sets a 'non string' value to a given Dicom Element
775 * @param group Group number of the searched Dicom Element
776 * @param element Element number of the searched Dicom Element
779 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
783 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
784 if ( ! tagHT.count(key))
786 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
791 * \ingroup gdcmParser
792 * \brief Update the entries with the shadow dictionary.
793 * Only non even entries are analyzed
795 void gdcmParser::UpdateShaEntries(void) {
796 gdcmDictEntry *entry;
799 for(ListTag::iterator it=listEntries.begin();
800 it!=listEntries.end();
803 // Odd group => from public dictionary
804 if((*it)->GetGroup()%2==0)
807 // Peer group => search the corresponding dict entry
809 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
813 if((*it)->IsImplicitVR())
818 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
820 // Set the new entry and the new value
821 (*it)->SetDictEntry(entry);
822 CheckHeaderEntryVR(*it,vr);
824 (*it)->SetValue(GetHeaderEntryValue(*it));
828 // Remove precedent value transformation
829 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
835 * \ingroup gdcmParser
836 * \brief Searches within the Header Entries for a Dicom Element of
838 * @param tagName name of the searched Dicom Element.
839 * @return Corresponding Dicom Element when it exists, and NULL
842 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
843 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
844 if( dictEntry == NULL)
847 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
851 * \ingroup gdcmParser
852 * \brief retrieves a Dicom Element (the first one) using (group, element)
853 * \warning (group, element) IS NOT an identifier inside the Dicom Header
854 * if you think it's NOT UNIQUE, check the count number
855 * and use iterators to retrieve ALL the Dicoms Elements within
856 * a given couple (group, element)
857 * @param group Group number of the searched Dicom Element
858 * @param element Element number of the searched Dicom Element
861 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
863 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
864 if ( ! tagHT.count(key))
866 return tagHT.find(key)->second;
870 * \ingroup gdcmParser
871 * \brief retrieves the Dicom Elements (all of them) using (group, element)
872 * @param group Group number of the searched Dicom Element.
873 * @param element Element number of the searched Dicom Element.
874 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
877 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
878 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
879 return (tagHT.equal_range(key));
883 * \ingroup gdcmParser
884 * \brief Loads the element while preserving the current
885 * underlying file position indicator as opposed to
886 * to LoadHeaderEntry that modifies it.
887 * @param entry Header Entry whose value shall be loaded.
890 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
891 long PositionOnEntry = ftell(fp);
892 LoadHeaderEntry(entry);
893 fseek(fp, PositionOnEntry, SEEK_SET);
897 * \ingroup gdcmParser
898 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
899 * \warning : to be re-written using the chained list instead of the H table.
900 * \warning : DO NOT use (doesn't work any longer because of the multimap)
901 * \todo : to be re-written using the chained list instead of the H table
902 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
903 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
905 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
909 gdcmHeaderEntry *elem;
911 std::string str_trash;
914 GroupHT groupHt; // to hold the length of each group
917 // typedef std::map<GroupKey, int> GroupHT;
919 gdcmHeaderEntry *elemZ;
921 // for each Tag in the DCM Header
923 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
928 gr = elem->GetGroup();
929 el = elem->GetElement();
932 sprintf(trash, "%04x", gr);
933 key = trash; // generate 'group tag'
935 // if the caller decided not to take SEQUENCEs into account
936 // e.g : he wants to write an ACR-NEMA File
938 if (SkipSequence && vr == "SQ")
941 // Still unsolved problem :
942 // we cannot find the 'Sequence Delimitation Item'
943 // since it's at the end of the Hash Table
946 // pas SEQUENCE en ACR-NEMA
948 // --> la descente a l'interieur' des SQ
949 // devrait etre faite avec une liste chainee, pas avec une HTable...
951 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
953 if (el == 0x0000) // the first elem is 0x0000
955 groupHt[key] = 0; // initialize group length
959 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
962 else // any elem but the first
964 if (type == ExplicitVR)
966 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
968 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
971 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
975 unsigned short int gr_bid;
977 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
981 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
982 // warning: unsigned int format, different type arg
983 sscanf(g->first.c_str(),"%x",&gr_bid);
984 tk = g->first + "|0000"; // generate the element full tag
986 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
988 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
989 elemZ = new gdcmHeaderEntry(tagZ);
991 AddHeaderEntry(elemZ); // create it
995 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
997 sprintf(trash ,"%d",g->second);
999 elemZ->SetValue(str_trash);
1004 * \ingroup gdcmParser
1005 * \brief writes on disc according to the requested format
1006 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1007 * \warning does NOT add the missing elements in the header :
1008 * it's up to the user doing it !
1009 * (function CheckHeaderCoherence to be written)
1010 * \warning DON'T try, right now, to write a DICOM image
1011 * from an ACR Header (meta elements will be missing!)
1012 * @param type type of the File to be written
1013 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1014 * @param _fp already open file pointer
1016 void gdcmParser::WriteEntries(FILE *_fp,FileType type)
1027 std::vector<std::string> tokens;
1029 // TODO : function CheckHeaderCoherence to be written
1031 // uses now listEntries to iterate, not TagHt!
1033 // pb : gdcmParser.Add does NOT update listEntries
1034 // TODO : find a trick (in STL?) to do it, at low cost !
1038 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1041 for (ListTag::iterator tag2=listEntries.begin();
1042 tag2 != listEntries.end();
1045 // === Deal with the length
1046 // --------------------
1047 if(((*tag2)->GetLength())%2==1)
1049 (*tag2)->SetValue((*tag2)->GetValue()+"\0");
1050 (*tag2)->SetLength((*tag2)->GetLength()+1);
1053 gr = (*tag2)->GetGroup();
1054 el = (*tag2)->GetElement();
1055 lgr = (*tag2)->GetReadLength();
1056 val = (*tag2)->GetValue().c_str();
1057 vr = (*tag2)->GetVR();
1058 voidArea = (*tag2)->GetVoidArea();
1062 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
1063 if (gr %2) continue; // ignore shadow groups
1064 if (vr == "SQ" ) continue; // ignore Sequences
1065 // TODO : find a trick to *skip* the SeQuences !
1066 // Not only ignore the SQ element
1067 if (gr == 0xfffe ) continue; // ignore delimiters
1070 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1071 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1073 // if ( (type == ExplicitVR) && (gr <= 0x0002) ) // ?!? < 2
1074 if ( (type == ExplicitVR) || (type == DICOMDIR) )
1077 guint16 z=0, shortLgr;
1079 { // Unknown was 'written'
1081 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1082 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1087 { // NO value for 'delimiters'
1088 if (vr == "unkn") // Unknown was 'written'
1089 fwrite(&z,(size_t)2 ,(size_t)1 ,_fp);
1091 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1094 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") || gr == 0xfffe)
1097 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1098 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1103 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1109 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1112 // === Deal with the value
1113 // -------------------
1114 if (vr == "SQ") continue; // no "value" to write for the SEQuences
1115 if (gr == 0xfffe)continue;
1117 if (voidArea != NULL)
1118 { // there is a 'non string' LUT, overlay, etc
1119 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1123 if (vr == "US" || vr == "SS")
1125 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1126 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1127 for (unsigned int i=0; i<tokens.size();i++)
1129 val_uint16 = atoi(tokens[i].c_str());
1131 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1136 if (vr == "UL" || vr == "SL")
1138 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1139 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1140 for (unsigned int i=0; i<tokens.size();i++)
1142 val_uint32 = atoi(tokens[i].c_str());
1144 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1150 // Pixels are never loaded in the element !
1151 // we stop writting when Pixel are processed
1152 // FIX : we loose trailing elements (RAB, right now)
1154 if ((gr == GrPixel) && (el == NumPixel) ) {
1156 if (compte == countGrPixel) // we passed *all* the GrPixel,NumPixel
1159 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1164 * \ingroup gdcmParser
1165 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1167 * @return The properly swaped 32 bits integer.
1169 guint32 gdcmParser::SwapLong(guint32 a) {
1174 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1175 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1179 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1183 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1186 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1193 * \ingroup gdcmParser
1194 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1196 * @return The properly unswaped 32 bits integer.
1198 guint32 gdcmParser::UnswapLong(guint32 a) {
1199 return (SwapLong(a));
1203 * \ingroup gdcmParser
1204 * \brief Swaps the bytes so they agree with the processor order
1205 * @return The properly swaped 16 bits integer.
1207 guint16 gdcmParser::SwapShort(guint16 a) {
1208 if ( (sw==4321) || (sw==2143) )
1209 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1214 * \ingroup gdcmParser
1215 * \brief Unswaps the bytes so they agree with the processor order
1216 * @return The properly unswaped 16 bits integer.
1218 guint16 gdcmParser::UnswapShort(guint16 a) {
1219 return (SwapShort(a));
1222 //-----------------------------------------------------------------------------
1225 * \ingroup gdcmParser
1226 * \brief Parses the header of the file but WITHOUT loading element values.
1227 * @return false if file is not ACR-NEMA / DICOM
1229 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1235 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1236 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1237 SkipHeaderEntry(newHeaderEntry);
1238 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1239 AddHeaderEntry(newHeaderEntry);
1246 * \ingroup gdcmParser
1247 * \brief Loads the element values of all the Header Entries pointed in the
1248 * public Chained List.
1250 void gdcmParser::LoadHeaderEntries(void) {
1252 for (ListTag::iterator i = GetListEntry().begin();
1253 i != GetListEntry().end();
1256 LoadHeaderEntry(*i);
1261 // Load 'non string' values
1262 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1263 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1264 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1265 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1266 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1267 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1269 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1270 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1271 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1273 //FIXME : how to use it?
1274 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1276 // --------------------------------------------------------------
1277 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1279 // if recognition code tells us we deal with a LibIDO image
1280 // we switch lineNumber and columnNumber
1282 std::string RecCode;
1283 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1284 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1285 RecCode == "CANRME_AILIBOD1_1." )
1287 filetype = ACR_LIBIDO;
1288 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1289 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1290 SetEntryByNumber(columns, 0x0028, 0x0010);
1291 SetEntryByNumber(rows , 0x0028, 0x0011);
1293 // ----------------- End of Special Patch ----------------
1297 * \ingroup gdcmParser
1298 * \brief Loads the element content if its length doesn't exceed
1299 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1300 * @param Entry Header Entry (Dicom Element) to be dealt with
1302 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1304 guint16 group = Entry->GetGroup();
1305 std::string vr= Entry->GetVR();
1306 guint32 length = Entry->GetLength();
1307 bool SkipLoad = false;
1309 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1311 // the test was commented out to 'go inside' the SeQuences
1312 // we don't any longer skip them !
1314 // if( vr == "SQ" ) // (DO NOT remove this comment)
1317 // A SeQuence "contains" a set of Elements.
1318 // (fffe e000) tells us an Element is beginning
1319 // (fffe e00d) tells us an Element just ended
1320 // (fffe e0dd) tells us the current SeQuence just ended
1321 if( group == 0xfffe )
1325 Entry->SetLength(0);
1326 Entry->SetValue("gdcm::Skipped");
1330 // When the length is zero things are easy:
1331 if ( length == 0 ) {
1332 Entry->SetValue("");
1336 // The elements whose length is bigger than the specified upper bound
1337 // are not loaded. Instead we leave a short notice of the offset of
1338 // the element content and it's length.
1339 if (length > MaxSizeLoadEntry) {
1340 std::ostringstream s;
1341 s << "gdcm::NotLoaded.";
1342 s << " Address:" << (long)Entry->GetOffset();
1343 s << " Length:" << Entry->GetLength();
1344 s << " x(" << std::hex << Entry->GetLength() << ")";
1345 Entry->SetValue(s.str());
1349 // When integer(s) are expected, read and convert the following
1350 // n *(two or four bytes)
1351 // properly i.e. as integers as opposed to strings.
1352 // Elements with Value Multiplicity > 1
1353 // contain a set of integers (not a single one)
1355 // Any compacter code suggested (?)
1356 if ( IsHeaderEntryAnInteger(Entry) ) {
1358 std::ostringstream s;
1360 if (vr == "US" || vr == "SS") {
1362 NewInt = ReadInt16();
1365 for (int i=1; i < nbInt; i++) {
1367 NewInt = ReadInt16();
1372 else if (vr == "UL" || vr == "SL") {
1374 NewInt = ReadInt32();
1377 for (int i=1; i < nbInt; i++) {
1379 NewInt = ReadInt32();
1384 #ifdef GDCM_NO_ANSI_STRING_STREAM
1385 s << std::ends; // to avoid oddities on Solaris
1386 #endif //GDCM_NO_ANSI_STRING_STREAM
1388 Entry->SetValue(s.str());
1392 // We need an additional byte for storing \0 that is not on disk
1393 std::string NewValue(length,0);
1394 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1395 if ( item_read != 1 ) {
1396 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1397 Entry->SetValue("gdcm::UnRead");
1401 if( (vr == "UI") ) // Because of correspondance with the VR dic
1402 Entry->SetValue(NewValue.c_str()); // ??? JPR ???
1404 Entry->SetValue(NewValue);
1408 * \ingroup gdcmParser
1409 * \brief add a new Dicom Element pointer to
1410 * the H Table and to the chained List
1411 * \warning push_bash in listEntries ONLY during ParseHeader
1412 * \todo something to allow further Elements addition,
1413 * (at their right place in the chained list)
1414 * when position to be taken care of
1415 * @param newHeaderEntry
1417 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1418 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1419 listEntries.push_back(newHeaderEntry);
1424 * \ingroup gdcmParser
1426 * @param Entry Header Entry whose length of the value shall be loaded.
1429 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1430 guint16 element = Entry->GetElement();
1431 guint16 group = Entry->GetGroup();
1432 std::string vr = Entry->GetVR();
1434 if( (element == NumPixel) && (group == GrPixel) )
1436 dbg.SetDebug(GDCM_DEBUG);
1437 dbg.Verbose(2, "gdcmParser::FindLength: ",
1438 "we reached (GrPixel,NumPixel)");
1441 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1443 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1445 // The following reserved two bytes (see PS 3.5-2001, section
1446 // 7.1.2 Data element structure with explicit vr p27) must be
1447 // skipped before proceeding on reading the length on 4 bytes.
1448 fseek(fp, 2L, SEEK_CUR);
1449 guint32 length32 = ReadInt32();
1451 if ( (vr == "OB") && (length32 == 0xffffffff) )
1453 Entry->SetLength(FindHeaderEntryLengthOB());
1456 FixHeaderEntryFoundLength(Entry, length32);
1460 // Length is encoded on 2 bytes.
1461 length16 = ReadInt16();
1463 // We can tell the current file is encoded in big endian (like
1464 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1465 // and it's value is the one of the encoding of a big endian file.
1466 // In order to deal with such big endian encoded files, we have
1467 // (at least) two strategies:
1468 // * when we load the "Transfer Syntax" tag with value of big endian
1469 // encoding, we raise the proper flags. Then we wait for the end
1470 // of the META group (0x0002) among which is "Transfer Syntax",
1471 // before switching the swap code to big endian. We have to postpone
1472 // the switching of the swap code since the META group is fully encoded
1473 // in little endian, and big endian coding only starts at the next
1474 // group. The corresponding code can be hard to analyse and adds
1475 // many additional unnecessary tests for regular tags.
1476 // * the second strategy consists in waiting for trouble, that shall
1477 // appear when we find the first group with big endian encoding. This
1478 // is easy to detect since the length of a "Group Length" tag (the
1479 // ones with zero as element number) has to be of 4 (0x0004). When we
1480 // encounter 1024 (0x0400) chances are the encoding changed and we
1481 // found a group with big endian encoding.
1482 // We shall use this second strategy. In order to make sure that we
1483 // can interpret the presence of an apparently big endian encoded
1484 // length of a "Group Length" without committing a big mistake, we
1485 // add an additional check: we look in the already parsed elements
1486 // for the presence of a "Transfer Syntax" whose value has to be "big
1487 // endian encoding". When this is the case, chances are we have got our
1488 // hands on a big endian encoded file: we switch the swap code to
1489 // big endian and proceed...
1490 if ( (element == 0x0000) && (length16 == 0x0400) )
1492 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1494 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1499 SwitchSwapToBigEndian();
1500 // Restore the unproperly loaded values i.e. the group, the element
1501 // and the dictionary entry depending on them.
1502 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1503 guint16 CorrectElem = SwapShort(Entry->GetElement());
1504 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1508 // This correct tag is not in the dictionary. Create a new one.
1509 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1511 // FIXME this can create a memory leaks on the old entry that be
1512 // left unreferenced.
1513 Entry->SetDictEntry(NewTag);
1516 // Heuristic: well some files are really ill-formed.
1517 if ( length16 == 0xffff)
1520 //dbg.Verbose(0, "gdcmParser::FindLength",
1521 // "Erroneous element length fixed.");
1522 // Actually, length= 0xffff means that we deal with
1523 // Unknown Sequence Length
1526 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1531 // Either implicit VR or a non DICOM conformal (see not below) explicit
1532 // VR that ommited the VR of (at least) this element. Farts happen.
1533 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1534 // on Data elements "Implicit and Explicit VR Data Elements shall
1535 // not coexist in a Data Set and Data Sets nested within it".]
1536 // Length is on 4 bytes.
1537 FixHeaderEntryFoundLength(Entry, ReadInt32());
1543 * \ingroup gdcmParser
1544 * \brief Find the Value Representation of the current Dicom Element.
1547 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1549 if (filetype != ExplicitVR)
1554 long PositionOnEntry = ftell(fp);
1555 // Warning: we believe this is explicit VR (Value Representation) because
1556 // we used a heuristic that found "UL" in the first tag. Alas this
1557 // doesn't guarantee that all the tags will be in explicit VR. In some
1558 // cases (see e-film filtered files) one finds implicit VR tags mixed
1559 // within an explicit VR file. Hence we make sure the present tag
1560 // is in explicit VR and try to fix things if it happens not to be
1563 int lgrLue=fread (&VR, (size_t)2,(size_t)1, fp); // lgrLue not used
1565 if(!CheckHeaderEntryVR(Entry,VR))
1567 fseek(fp, PositionOnEntry, SEEK_SET);
1568 // When this element is known in the dictionary we shall use, e.g. for
1569 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1570 // dictionary entry. Still we have to flag the element as implicit since
1571 // we know now our assumption on expliciteness is not furfilled.
1573 if ( Entry->IsVRUnknown() )
1574 Entry->SetVR("Implicit");
1575 Entry->SetImplicitVR();
1580 * \ingroup gdcmParser
1581 * \brief Check the correspondance between the VR of the header entry
1582 * and the taken VR. If they are different, the header entry is
1583 * updated with the new VR.
1584 * @param Entry Header Entry to check
1585 * @param vr Dicom Value Representation
1586 * @return false if the VR is incorrect of if the VR isn't referenced
1587 * otherwise, it returns true
1589 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1591 char msg[100]; // for sprintf
1592 bool RealExplicit = true;
1594 // Assume we are reading a falsely explicit VR file i.e. we reached
1595 // a tag where we expect reading a VR but are in fact we read the
1596 // first to bytes of the length. Then we will interogate (through find)
1597 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1598 // both GCC and VC++ implementations of the STL map. Hence when the
1599 // expected VR read happens to be non-ascii characters we consider
1600 // we hit falsely explicit VR tag.
1602 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1603 RealExplicit = false;
1605 // CLEANME searching the dicom_vr at each occurence is expensive.
1606 // PostPone this test in an optional integrity check at the end
1607 // of parsing or only in debug mode.
1608 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1609 RealExplicit= false;
1611 if ( !RealExplicit )
1613 // We thought this was explicit VR, but we end up with an
1614 // implicit VR tag. Let's backtrack.
1615 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1616 Entry->GetGroup(),Entry->GetElement());
1617 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1618 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1619 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1620 Entry->GetGroup(),Entry->GetElement(),
1621 "UL","FIXME","Group Length");
1622 Entry->SetDictEntry(NewEntry);
1627 if ( Entry->IsVRUnknown() )
1629 // When not a dictionary entry, we can safely overwrite the VR.
1630 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1636 else if ( Entry->GetVR() != vr )
1638 // The VR present in the file and the dictionary disagree. We assume
1639 // the file writer knew best and use the VR of the file. Since it would
1640 // be unwise to overwrite the VR of a dictionary (since it would
1641 // compromise it's next user), we need to clone the actual DictEntry
1642 // and change the VR for the read one.
1643 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1644 Entry->GetGroup(),Entry->GetElement(),
1645 vr,"FIXME",Entry->GetName());
1646 Entry->SetDictEntry(NewEntry);
1652 * \ingroup gdcmParser
1653 * \brief Get the transformed value of the header entry. The VR value
1654 * is used to define the transformation to operate on the value
1655 * \warning NOT end user intended method !
1657 * @return Transformed entry value
1659 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1661 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1663 std::string val=Entry->GetValue();
1664 std::string vr=Entry->GetVR();
1665 guint32 length = Entry->GetLength();
1666 std::ostringstream s;
1669 if (vr == "US" || vr == "SS")
1674 for (int i=0; i < nbInt; i++)
1678 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1679 NewInt16 = SwapShort(NewInt16);
1684 else if (vr == "UL" || vr == "SL")
1689 for (int i=0; i < nbInt; i++)
1693 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1694 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1695 NewInt32=SwapLong(NewInt32);
1699 #ifdef GDCM_NO_ANSI_STRING_STREAM
1700 s << std::ends; // to avoid oddities on Solaris
1701 #endif //GDCM_NO_ANSI_STRING_STREAM
1705 return(Entry->GetValue());
1709 * \ingroup gdcmParser
1710 * \brief Get the reverse transformed value of the header entry. The VR
1711 * value is used to define the reverse transformation to operate on
1713 * \warning NOT end user intended method !
1715 * @return Reverse transformed entry value
1717 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1719 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1721 std::string vr=Entry->GetVR();
1722 std::ostringstream s;
1723 std::vector<std::string> tokens;
1725 if (vr == "US" || vr == "SS")
1729 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1730 Tokenize (Entry->GetValue(), tokens, "\\");
1731 for (unsigned int i=0; i<tokens.size();i++)
1733 NewInt16 = atoi(tokens[i].c_str());
1734 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1738 if (vr == "UL" || vr == "SL")
1742 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1743 Tokenize (Entry->GetValue(), tokens, "\\");
1744 for (unsigned int i=0; i<tokens.size();i++)
1746 NewInt32 = atoi(tokens[i].c_str());
1747 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1748 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1753 #ifdef GDCM_NO_ANSI_STRING_STREAM
1754 s << std::ends; // to avoid oddities on Solaris
1755 #endif //GDCM_NO_ANSI_STRING_STREAM
1759 return(Entry->GetValue());
1763 * \ingroup gdcmParser
1764 * \brief Skip a given Header Entry
1765 * \warning NOT end user intended method !
1768 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1770 SkipBytes(entry->GetLength());
1774 * \ingroup gdcmParser
1775 * \brief When the length of an element value is obviously wrong (because
1776 * the parser went Jabberwocky) one can hope improving things by
1777 * applying this heuristic.
1779 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1781 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1783 if ( FoundLength == 0xffffffff) {
1787 guint16 gr =Entry->GetGroup();
1788 guint16 el =Entry->GetElement();
1790 if (FoundLength%2) {
1791 std::ostringstream s;
1792 s << "Warning : Tag with uneven length " << FoundLength
1793 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1794 dbg.Verbose(0,s.str().c_str());
1797 // Sorry for the patch!
1798 // XMedCom did the trick to read some nasty GE images ...
1799 if (FoundLength == 13) {
1800 // The following 'if' will be removed when there is no more
1801 // images on Creatis HDs with a 13 length for Manufacturer...
1802 if ( (Entry->GetGroup() != 0x0008) ||
1803 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1804 // end of remove area
1806 Entry->SetReadLength(10); // a bug is to be fixed
1810 // to fix some garbage 'Leonardo' Siemens images
1811 // May be commented out to avoid overhead
1812 else if ( (Entry->GetGroup() == 0x0009) &&
1813 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1815 Entry->SetReadLength(4); // a bug is to be fixed
1819 // to try to 'go inside' SeQuences (with length), and not to skip them
1820 else if ( Entry->GetVR() == "SQ")
1822 if (enableSequences) // only if the user does want to !
1823 FoundLength =0; // ReadLength is unchanged
1826 // a SeQuence Element is beginning
1827 // Let's forget it's length
1828 // (we want to 'go inside')
1830 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1831 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1832 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1833 // if we don't, we lost 28800 characters from the Header :-(
1835 else if(Entry->GetGroup() == 0xfffe)
1837 // sometimes, length seems to be wrong
1838 FoundLength =0; // some more clever checking to be done !
1840 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1841 // causes troubles :-(
1844 Entry->SetUsableLength(FoundLength);
1848 * \ingroup gdcmParser
1849 * \brief Apply some heuristics to predict wether the considered
1850 * element value contains/represents an integer or not.
1851 * @param Entry The element value on which to apply the predicate.
1852 * @return The result of the heuristical predicate.
1854 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1855 guint16 element = Entry->GetElement();
1856 guint16 group = Entry->GetGroup();
1857 std::string vr = Entry->GetVR();
1858 guint32 length = Entry->GetLength();
1859 // When we have some semantics on the element we just read, and if we
1860 // a priori know we are dealing with an integer, then we shall be
1861 // able to swap it's element value properly.
1862 if ( element == 0 ) // This is the group length of the group
1868 std::ostringstream s;
1869 int filePosition = ftell(fp);
1870 s << "Erroneous Group Length element length on : (" \
1871 << std::hex << group << " , " << element
1872 << ") -before- position x(" << filePosition << ")"
1873 << "lgt : " << length;
1874 // These 2 lines commented out : a *very dirty* patch
1875 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1876 // have a glance at offset x(8336) ...
1877 // For *regular* headers, the test is useless..
1878 // lets's print a warning message and go on,
1879 // instead of giving up with an error message
1881 //std::cout << s.str().c_str() << std::endl;
1883 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1884 // s.str().c_str());
1887 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1894 * \ingroup gdcmParser
1896 * \warning NOT end user intended method !
1899 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1900 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1903 long PositionOnEntry = ftell(fp);
1904 bool FoundSequenceDelimiter = false;
1905 guint32 TotalLength = 0;
1908 while ( ! FoundSequenceDelimiter)
1914 TotalLength += 4; // We even have to decount the group and element
1916 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1918 char msg[100]; // for sprintf. Sorry
1919 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1920 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1924 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1925 FoundSequenceDelimiter = true;
1926 else if ( n != 0xe000 )
1928 char msg[100]; // for sprintf. Sorry
1929 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1931 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1935 ItemLength = ReadInt32();
1936 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1937 // the ItemLength with ReadInt32
1938 SkipBytes(ItemLength);
1940 fseek(fp, PositionOnEntry, SEEK_SET);
1945 * \ingroup gdcmParser
1946 * \brief Reads a supposed to be 16 Bits integer
1947 * (swaps it depending on processor endianity)
1948 * @return read value
1950 guint16 gdcmParser::ReadInt16(void) {
1953 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1954 if ( item_read != 1 ) {
1956 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1966 * \ingroup gdcmParser
1967 * \brief Reads a supposed to be 32 Bits integer
1968 * (swaps it depending on processor endianity)
1969 * @return read value
1971 guint32 gdcmParser::ReadInt32(void) {
1974 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1975 if ( item_read != 1 ) {
1977 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1987 * \ingroup gdcmParser
1989 * \warning NOT end user intended method !
1992 void gdcmParser::SkipBytes(guint32 NBytes) {
1993 //FIXME don't dump the returned value
1994 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1998 * \ingroup gdcmParser
2001 void gdcmParser::Initialise(void)
2003 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2004 RefShaDict = (gdcmDict*)0;
2008 * \ingroup gdcmParser
2009 * \brief Discover what the swap code is (among little endian, big endian,
2010 * bad little endian, bad big endian).
2012 * @return false when we are absolutely sure
2013 * it's neither ACR-NEMA nor DICOM
2014 * true when we hope ours assuptions are OK
2016 bool gdcmParser::CheckSwap() {
2018 // The only guaranted way of finding the swap code is to find a
2019 // group tag since we know it's length has to be of four bytes i.e.
2020 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2021 // occurs when we can't find such group...
2023 guint32 x=4; // x : for ntohs
2024 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2030 char deb[HEADER_LENGTH_TO_READ];
2032 // First, compare HostByteOrder and NetworkByteOrder in order to
2033 // determine if we shall need to swap bytes (i.e. the Endian type).
2039 // The easiest case is the one of a DICOM header, since it possesses a
2040 // file preamble where it suffice to look for the string "DICM".
2041 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2044 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2045 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2047 // Next, determine the value representation (VR). Let's skip to the
2048 // first element (0002, 0000) and check there if we find "UL"
2049 // - or "OB" if the 1st one is (0002,0001) -,
2050 // in which case we (almost) know it is explicit VR.
2051 // WARNING: if it happens to be implicit VR then what we will read
2052 // is the length of the group. If this ascii representation of this
2053 // length happens to be "UL" then we shall believe it is explicit VR.
2054 // FIXME: in order to fix the above warning, we could read the next
2055 // element value (or a couple of elements values) in order to make
2056 // sure we are not commiting a big mistake.
2057 // We need to skip :
2058 // * the 128 bytes of File Preamble (often padded with zeroes),
2059 // * the 4 bytes of "DICM" string,
2060 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2061 // i.e. a total of 136 bytes.
2065 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2066 // but elem 0002,0010 (Transfert Syntax) tells us the file is *Implicit* VR.
2069 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2070 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2071 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2072 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2073 // when Write DCM *adds*
2075 // Use gdcmParser::dicom_vr to test all the possibilities
2076 // instead of just checking for UL, OB and UI !? // group 0000
2079 filetype = ExplicitVR;
2080 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2081 "explicit Value Representation");
2085 filetype = ImplicitVR;
2086 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2087 "not an explicit Value Representation");
2093 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2094 "HostByteOrder != NetworkByteOrder");
2099 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2100 "HostByteOrder = NetworkByteOrder");
2103 // Position the file position indicator at first tag (i.e.
2104 // after the file preamble and the "DICM" string).
2106 fseek (fp, 132L, SEEK_SET);
2110 // Alas, this is not a DicomV3 file and whatever happens there is no file
2111 // preamble. We can reset the file position indicator to where the data
2112 // is (i.e. the beginning of the file).
2113 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2116 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2117 // By clean we mean that the length of the first tag is written down.
2118 // If this is the case and since the length of the first group HAS to be
2119 // four (bytes), then determining the proper swap code is straightforward.
2122 // We assume the array of char we are considering contains the binary
2123 // representation of a 32 bits integer. Hence the following dirty
2125 s32 = *((guint32 *)(entCur));
2146 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2147 // It is time for despaired wild guesses.
2148 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2149 // i.e. the 'group length' element is not present :
2151 // check the supposed to be 'group number'
2152 // 0x0002 or 0x0004 or 0x0008
2153 // to determine ' sw' value .
2154 // Only 0 or 4321 will be possible
2155 // (no oportunity to check for the formerly well known
2156 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2157 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2158 // the file IS NOT ACR-NEMA nor DICOM V3
2159 // Find a trick to tell it the caller...
2161 s16 = *((guint16 *)(deb));
2177 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2178 "ACR/NEMA unfound swap info (Really hopeless !)");
2183 // Then the only info we have is the net2host one.
2193 * \ingroup gdcmParser
2196 void gdcmParser::SwitchSwapToBigEndian(void)
2198 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2199 "Switching to BigEndian mode.");
2220 * \ingroup gdcmParser
2221 * \brief during parsing, Header Elements too long are not loaded in memory
2224 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2228 if ((guint32)NewSize >= (guint32)0xffffffff)
2230 MaxSizeLoadEntry = 0xffffffff;
2233 MaxSizeLoadEntry = NewSize;
2238 * \ingroup gdcmParser
2239 * \brief Header Elements too long will not be printed
2241 * \todo : not yet usable
2242 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2243 * in gdcmHeaderEntry gdcmLoadEntry)
2247 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2251 if ((guint32)NewSize >= (guint32)0xffffffff)
2253 MaxSizePrintEntry = 0xffffffff;
2256 MaxSizePrintEntry = NewSize;
2260 * \ingroup gdcmParser
2261 * \brief Searches both the public and the shadow dictionary (when they
2262 * exist) for the presence of the DictEntry with given name.
2263 * The public dictionary has precedence on the shadow one.
2264 * @param Name name of the searched DictEntry
2265 * @return Corresponding DictEntry when it exists, NULL otherwise.
2267 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2269 gdcmDictEntry *found = (gdcmDictEntry *)0;
2270 if (!RefPubDict && !RefShaDict)
2272 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2273 "we SHOULD have a default dictionary");
2277 found = RefPubDict->GetDictEntryByName(Name);
2283 found = RefShaDict->GetDictEntryByName(Name);
2291 * \ingroup gdcmParser
2292 * \brief Searches both the public and the shadow dictionary (when they
2293 * exist) for the presence of the DictEntry with given
2294 * group and element. The public dictionary has precedence on the
2296 * @param group group of the searched DictEntry
2297 * @param element element of the searched DictEntry
2298 * @return Corresponding DictEntry when it exists, NULL otherwise.
2300 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2302 gdcmDictEntry *found = (gdcmDictEntry *)0;
2303 if (!RefPubDict && !RefShaDict)
2305 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2306 "we SHOULD have a default dictionary");
2310 found = RefPubDict->GetDictEntryByNumber(group, element);
2316 found = RefShaDict->GetDictEntryByNumber(group, element);
2324 * \ingroup gdcmParser
2325 * \brief Read the next tag but WITHOUT loading it's value
2326 * @return On succes the newly created HeaderEntry, NULL on failure.
2328 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2330 gdcmHeaderEntry *NewEntry;
2335 // We reached the EOF (or an error occured) therefore
2336 // header parsing has to be considered as finished.
2337 return (gdcmHeaderEntry *)0;
2339 /* Pb : how to propagate the element length (used in SkipHeaderEntry)
2340 // direct call to SkipBytes ?
2342 if (ignoreShadow == 1 && g%2 ==1) //JPR
2343 // if user wants to skip shadow groups
2344 // and current element *is* a shadow element
2345 // we don't create anything
2346 return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2348 NewEntry = NewHeaderEntryByNumber(g, n);
2349 FindHeaderEntryVR(NewEntry);
2350 FindHeaderEntryLength(NewEntry);
2356 NewEntry->SetOffset(ftell(fp));
2361 * \ingroup gdcmParser
2362 * \brief Build a new Element Value from all the low level arguments.
2363 * Check for existence of dictionary entry, and build
2364 * a default one when absent.
2365 * @param Name Name of the underlying DictEntry
2367 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2369 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2371 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2373 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2376 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2377 "failed to allocate gdcmHeaderEntry");
2378 return (gdcmHeaderEntry *)0;
2384 * \ingroup gdcmParser
2385 * \brief Request a new virtual dict entry to the dict set
2386 * @param group group of the underlying DictEntry
2387 * @param element element of the underlying DictEntry
2388 * @param vr VR of the underlying DictEntry
2389 * @param fourth owner group
2390 * @param name english name
2392 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2397 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2401 * \ingroup gdcmParser
2402 * \brief Build a new Element Value from all the low level arguments.
2403 * Check for existence of dictionary entry, and build
2404 * a default one when absent.
2405 * @param Group group of the underlying DictEntry
2406 * @param Elem element of the underlying DictEntry
2408 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2410 // Find out if the tag we encountered is in the dictionaries:
2411 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2413 DictEntry = NewVirtualDictEntry(Group, Elem);
2415 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2418 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2419 "failed to allocate gdcmHeaderEntry");
2425 // Never used; commented out, waiting for removal.
2427 * \ingroup gdcmParser
2428 * \brief Small utility function that creates a new manually crafted
2429 * (as opposed as read from the file) gdcmHeaderEntry with user
2430 * specified name and adds it to the public tag hash table.
2431 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2432 * @param NewTagName The name to be given to this new tag.
2433 * @param VR The Value Representation to be given to this new tag.
2434 * @return The newly hand crafted Element Value.
2436 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2439 // gdcmHeaderEntry *NewEntry = NULL;
2440 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2441 // guint32 FreeElem = 0;
2442 // gdcmDictEntry *DictEntry = NULL;
2444 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2445 // if (FreeElem == UINT32_MAX)
2447 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2448 // "Group 0xffff in Public Dict is full");
2452 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2453 // VR, "GDCM", NewTagName);
2454 // NewEntry = new gdcmHeaderEntry(DictEntry);
2455 // AddHeaderEntry(NewEntry);
2460 * \ingroup gdcmParser
2461 * \brief Generate a free TagKey i.e. a TagKey that is not present
2462 * in the TagHt dictionary.
2463 * @param group The generated tag must belong to this group.
2464 * @return The element of tag with given group which is fee.
2466 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2468 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2470 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2471 if (tagHT.count(key) == 0)
2477 //-----------------------------------------------------------------------------