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;
101 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
102 filename = InFilename;
105 if ( !OpenFile(exception_on_error))
111 wasUpdated = 0; // will be set to 1 if user adds an entry
112 printLevel = 1; // 'Medium' print level by default
116 * \ingroup gdcmParser
118 * @param exception_on_error
120 gdcmParser::gdcmParser(bool exception_on_error) {
123 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
126 wasUpdated = 0; // will be set to 1 if user adds an entry
127 printLevel = 1; // 'Medium' print level by default
131 * \ingroup gdcmParser
132 * \brief Canonical destructor.
134 gdcmParser::~gdcmParser (void) {
139 //-----------------------------------------------------------------------------
142 * \ingroup gdcmParser
143 * \brief Prints the Header Entries (Dicom Elements)
144 * both from the H Table and the chained list
147 void gdcmParser::PrintEntry(std::ostream & os) {
148 std::ostringstream s;
150 for (ListTag::iterator i = listEntries.begin();
151 i != listEntries.end();
154 (*i)->SetPrintLevel(printLevel);
161 * \ingroup gdcmParser
162 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
165 void gdcmParser::PrintPubDict(std::ostream & os) {
166 RefPubDict->Print(os);
170 * \ingroup gdcmParser
171 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
174 void gdcmParser::PrintShaDict(std::ostream & os) {
175 RefShaDict->Print(os);
178 //-----------------------------------------------------------------------------
181 * \ingroup gdcmParser
182 * \brief Get the public dictionary used
184 gdcmDict *gdcmParser::GetPubDict(void) {
189 * \ingroup gdcmParser
190 * \brief Get the shadow dictionary used
192 gdcmDict *gdcmParser::GetShaDict(void) {
197 * \ingroup gdcmParser
198 * \brief Set the shadow dictionary used
199 * \param dict dictionary to use in shadow
201 bool gdcmParser::SetShaDict(gdcmDict *dict){
207 * \ingroup gdcmParser
208 * \brief Set the shadow dictionary used
209 * \param dictName name of the dictionary to use in shadow
211 bool gdcmParser::SetShaDict(DictKey dictName){
212 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
217 * \ingroup gdcmParser
218 * \brief This predicate, based on hopefully reasonable heuristics,
219 * decides whether or not the current gdcmParser was properly parsed
220 * and contains the mandatory information for being considered as
221 * a well formed and usable Dicom/Acr File.
222 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
225 bool gdcmParser::IsReadable(void) {
226 if(filetype==Unknown)
228 if(listEntries.size()<=0)
235 * \ingroup gdcmParser
236 * \brief Determines if the Transfer Syntax was already encountered
237 * and if it corresponds to a ImplicitVRLittleEndian one.
239 * @return True when ImplicitVRLittleEndian found. False in all other cases.
241 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
242 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
245 LoadHeaderEntrySafe(Element);
247 std::string Transfer = Element->GetValue();
248 if ( Transfer == UI1_2_840_10008_1_2 )
254 * \ingroup gdcmParser
255 * \brief Determines if the Transfer Syntax was already encountered
256 * and if it corresponds to a ExplicitVRLittleEndian one.
258 * @return True when ExplicitVRLittleEndian found. False in all other cases.
260 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
261 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
264 LoadHeaderEntrySafe(Element);
266 std::string Transfer = Element->GetValue();
267 if ( Transfer == UI1_2_840_10008_1_2_1 )
273 * \ingroup gdcmParser
274 * \brief Determines if the Transfer Syntax was already encountered
275 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
277 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
279 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
280 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
283 LoadHeaderEntrySafe(Element);
285 std::string Transfer = Element->GetValue();
286 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
292 * \ingroup gdcmParser
293 * \brief Determines if the Transfer Syntax was already encountered
294 * and if it corresponds to a Explicit VR Big Endian one.
296 * @return True when big endian found. False in all other cases.
298 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
299 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
302 LoadHeaderEntrySafe(Element);
304 std::string Transfer = Element->GetValue();
305 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
311 * \ingroup gdcmParser
312 * \brief returns the File Type
313 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
316 FileType gdcmParser::GetFileType(void) {
321 * \ingroup gdcmParser
322 * \brief opens the file
323 * @param exception_on_error
326 FILE *gdcmParser::OpenFile(bool exception_on_error)
329 fp=fopen(filename.c_str(),"rb");
330 if(exception_on_error)
333 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
339 fread(&zero, (size_t)2, (size_t)1, fp);
341 //ACR -- or DICOM with no Preamble --
342 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
346 fseek(fp, 126L, SEEK_CUR);
348 fread(dicm, (size_t)4, (size_t)1, fp);
349 if( memcmp(dicm, "DICM", 4) == 0 )
353 dbg.Verbose(0, "gdcmParser::gdcmParser not DICOM/ACR", filename.c_str());
356 dbg.Verbose(0, "gdcmParser::gdcmParser cannot open file", filename.c_str());
362 * \ingroup gdcmParser
363 * \brief closes the file
364 * @return TRUE if the close was successfull
366 bool gdcmParser::CloseFile(void) {
367 int closed = fclose(fp);
375 * \ingroup gdcmParser
377 * @param fp file pointer on an already open file
378 * @param type type of the File to be written
379 * (ACR-NEMA, ExplicitVR, ImplicitVR)
380 * @return always "True" ?!
382 bool gdcmParser::Write(FILE *fp, FileType type) {
384 // TODO The stuff has been rewritten using the chained list instead
386 // so we could remove the GroupHT from the gdcmParser
390 // TODO : move the following lines (and a lot of others, to be written)
391 // to a future function CheckAndCorrectHeader
394 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
395 // (FileType est un champ de gdcmParser ...)
396 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
398 // a moins de se livrer a un tres complique ajout des champs manquants.
399 // faire un CheckAndCorrectHeader (?)
402 if (type == ImplicitVR)
404 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
405 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
407 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
408 // values with a VR of UI shall be padded with a single trailing null
409 // Dans le cas suivant on doit pader manuellement avec un 0
411 SetEntryLengthByNumber(18, 0x0002, 0x0010);
414 if (type == ExplicitVR)
416 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
417 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,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(20, 0x0002, 0x0010);
426 /* TODO : rewrite later
428 if ( (type == ImplicitVR) || (type == ExplicitVR) )
429 UpdateGroupLength(false,type);
431 UpdateGroupLength(true,ACR);
434 WriteEntries(type, fp);
439 * \ingroup gdcmParser
440 * \brief Modifies the value of a given Header Entry (Dicom Element)
441 * if it exists; Creates it with the given value if it doesn't
442 * @param Value passed as a std::string
447 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
450 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
451 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
456 SetEntryByNumber(Value, Group, Elem);
461 * \ingroup gdcmParser
462 * \brief Modifies the value of a given Header Entry (Dicom Element)
463 * if it exists; Creates it with the given value if it doesn't
464 * @param Value passed as a char*
470 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
471 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
476 AddHeaderEntry(nvHeaderEntry);
478 std::string v = Value;
479 SetEntryByNumber(v, Group, Elem);
484 * \ingroup gdcmParser
485 * \brief Set a new value if the invoked element exists
486 * Seems to be useless !!!
492 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
494 std::string v = Value;
495 SetEntryByNumber(v, Group, Elem);
499 //-----------------------------------------------------------------------------
502 * \ingroup gdcmParser
503 * \brief Checks if a given Dicom Element exists
504 * \ within the H table
505 * @param group Group number of the searched Dicom Element
506 * @param element Element number of the searched Dicom Element
507 * @return number of occurences
509 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
510 std::string key = gdcmDictEntry::TranslateToKey(group, element );
511 return (tagHT.count(key));
515 * \ingroup gdcmParser
516 * \brief Searches within Header Entries (Dicom Elements) parsed with
517 * the public and private dictionaries
518 * for the element value of a given tag.
519 * \warning Don't use any longer : use GetPubEntryByName
520 * @param tagName name of the searched element.
521 * @return Corresponding element value when it exists,
522 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
524 std::string gdcmParser::GetEntryByName(std::string tagName) {
525 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
526 if( dictEntry == NULL)
529 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
533 * \ingroup gdcmParser
534 * \brief Searches within Header Entries (Dicom Elements) parsed with
535 * the public and private dictionaries
536 * for the element value representation of a given tag.
538 * Obtaining the VR (Value Representation) might be needed by caller
539 * to convert the string typed content to caller's native type
540 * (think of C++ vs Python). The VR is actually of a higher level
541 * of semantics than just the native C++ type.
542 * @param tagName name of the searched element.
543 * @return Corresponding element value representation when it exists,
544 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
546 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
547 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
548 if( dictEntry == NULL)
551 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
552 dictEntry->GetElement());
553 return elem->GetVR();
557 * \ingroup gdcmParser
558 * \brief Searches within Header Entries (Dicom Elements) parsed with
559 * the public and private dictionaries
560 * for the element value representation of a given tag.
561 * @param group Group of the searched tag.
562 * @param element Element of the searched tag.
563 * @return Corresponding element value representation when it exists,
564 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
566 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
567 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
568 if ( ! tagHT.count(key))
570 return tagHT.find(key)->second->GetValue();
574 * \ingroup gdcmParser
575 * \brief Searches within Header Entries (Dicom Elements) parsed with
576 * the public and private dictionaries
577 * for the element value representation of a given tag..
579 * Obtaining the VR (Value Representation) might be needed by caller
580 * to convert the string typed content to caller's native type
581 * (think of C++ vs Python). The VR is actually of a higher level
582 * of semantics than just the native C++ type.
583 * @param group Group of the searched tag.
584 * @param element Element of the searched tag.
585 * @return Corresponding element value representation when it exists,
586 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
588 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
589 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
592 return elem->GetVR();
596 * \ingroup gdcmParser
597 * \brief Sets the value (string) of the Header Entry (Dicom Element)
598 * @param content string value of the Dicom Element
599 * @param tagName name of the searched Dicom Element.
600 * @return true when found
602 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
603 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
604 if( dictEntry == NULL)
607 return(SetEntryByNumber(content,dictEntry->GetGroup(),
608 dictEntry->GetElement()));
612 * \ingroup gdcmParser
613 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
614 * through it's (group, element) and modifies it's content with
616 * \warning Don't use any longer : use SetPubEntryByNumber
617 * @param content new value to substitute with
618 * @param group group of the Dicom Element to modify
619 * @param element element of the Dicom Element to modify
621 bool gdcmParser::SetEntryByNumber(std::string content,
625 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
626 if ( ! tagHT.count(key))
628 int l = content.length();
629 if(l%2) // Odd length are padded with a space (020H).
632 content = content + '\0';
637 TagHeaderEntryHT::iterator p2;
638 // DO NOT remove the following lines : they explain the stuff
639 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
640 //p2=p.first; // iterator on the first synonym
641 //a=p2->second; // H Table target column (2-nd col)
644 a = ((tagHT.equal_range(key)).first)->second;
646 a-> SetValue(content);
648 std::string vr = a->GetVR();
651 if( (vr == "US") || (vr == "SS") )
653 else if( (vr == "UL") || (vr == "SL") )
663 * \ingroup gdcmParser
664 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
665 * in the PubHeaderEntrySet of this instance
666 * through it's (group, element) and modifies it's length with
668 * \warning Use with extreme caution.
669 * @param length new length to substitute with
670 * @param group group of the entry to modify
671 * @param element element of the Entry to modify
672 * @return 1 on success, 0 otherwise.
675 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
679 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
680 if ( ! tagHT.count(key))
682 if (length%2) length++; // length must be even
683 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
689 * \ingroup gdcmParser
690 * \brief Gets (from Header) the offset of a 'non string' element value
691 * \ (LoadElementValues has already be executed)
694 * @return File Offset of the Element Value
696 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
698 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
701 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
702 "failed to Locate gdcmHeaderEntry");
705 return Entry->GetOffset();
709 * \ingroup gdcmParser
710 * \brief Gets (from Header) a 'non string' element value
711 * \ (LoadElementValues has already be executed)
714 * @return Pointer to the 'non string' area
716 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
718 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
721 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
722 "failed to Locate gdcmHeaderEntry");
725 return Entry->GetVoidArea();
729 * \ingroup gdcmParser
730 * \brief Loads (from disk) the element content
731 * when a string is not suitable
735 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
737 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
740 size_t o =(size_t)Element->GetOffset();
741 fseek(fp, o, SEEK_SET);
742 int l=Element->GetLength();
743 void * a = malloc(l);
747 SetEntryVoidAreaByNumber(a, Group, Elem);
748 // TODO check the result
749 size_t l2 = fread(a, 1, l ,fp);
759 * \ingroup gdcmParser
760 * \brief Sets a 'non string' value to a given Dicom Element
762 * @param group Group number of the searched Dicom Element
763 * @param element Element number of the searched Dicom Element
766 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
770 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
771 if ( ! tagHT.count(key))
773 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
778 * \ingroup gdcmParser
779 * \brief Update the entries with the shadow dictionary. Only odd entries are
782 void gdcmParser::UpdateShaEntries(void) {
783 gdcmDictEntry *entry;
786 for(ListTag::iterator it=listEntries.begin();
787 it!=listEntries.end();
790 // Odd group => from public dictionary
791 if((*it)->GetGroup()%2==0)
794 // Peer group => search the corresponding dict entry
796 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
800 if((*it)->IsImplicitVR())
805 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
807 // Set the new entry and the new value
808 (*it)->SetDictEntry(entry);
809 CheckHeaderEntryVR(*it,vr);
811 (*it)->SetValue(GetHeaderEntryValue(*it));
815 // Remove precedent value transformation
816 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
822 * \ingroup gdcmParser
823 * \brief Searches within the Header Entries for a Dicom Element of
825 * @param tagName name of the searched Dicom Element.
826 * @return Corresponding Dicom Element when it exists, and NULL
829 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
830 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
831 if( dictEntry == NULL)
834 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
838 * \ingroup gdcmParser
839 * \brief retrieves a Dicom Element (the first one) using (group, element)
840 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
841 * if you think it's NOT UNIQUE, check the count number
842 * and use iterators to retrieve ALL the Dicoms Elements within
843 * a given couple (group, element)
844 * @param group Group number of the searched Dicom Element
845 * @param element Element number of the searched Dicom Element
848 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
850 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
851 if ( ! tagHT.count(key))
853 return tagHT.find(key)->second;
857 * \ingroup gdcmParser
858 * \brief retrieves the Dicom Elements (all of them) using (group, element)
859 * @param group Group number of the searched Dicom Element.
860 * @param element Element number of the searched Dicom Element.
861 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
864 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
865 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
866 return (tagHT.equal_range(key));
870 * \ingroup gdcmParser
871 * \brief Loads the element while preserving the current
872 * underlying file position indicator as opposed to
873 * to LoadHeaderEntry that modifies it.
874 * @param entry Header Entry whose value shall be loaded.
877 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
878 long PositionOnEntry = ftell(fp);
879 LoadHeaderEntry(entry);
880 fseek(fp, PositionOnEntry, SEEK_SET);
884 * \ingroup gdcmParser
885 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
886 * \warning : to be re-written using the chained list instead of the H table.
887 * \warning : DO NOT use (doesn't work any longer because of the multimap)
888 * \todo : to be re-written using the chained list instead of the H table
889 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
890 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
892 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
896 gdcmHeaderEntry *elem;
898 std::string str_trash;
901 GroupHT groupHt; // to hold the length of each group
904 // typedef std::map<GroupKey, int> GroupHT;
906 gdcmHeaderEntry *elemZ;
908 // for each Tag in the DCM Header
910 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
915 gr = elem->GetGroup();
916 el = elem->GetElement();
919 sprintf(trash, "%04x", gr);
920 key = trash; // generate 'group tag'
922 // if the caller decided not to take SEQUENCEs into account
923 // e.g : he wants to write an ACR-NEMA File
925 if (SkipSequence && vr == "SQ")
928 // Still unsolved problem :
929 // we cannot find the 'Sequence Delimitation Item'
930 // since it's at the end of the Hash Table
933 // pas SEQUENCE en ACR-NEMA
935 // --> la descente a l'interieur' des SQ
936 // devrait etre faite avec une liste chainee, pas avec une HTable...
938 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
940 if (el == 0x0000) // the first elem is 0x0000
942 groupHt[key] = 0; // initialize group length
946 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
949 else // any elem but the first
951 if (type == ExplicitVR)
953 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
955 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
958 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
962 unsigned short int gr_bid;
964 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
968 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
969 // warning: unsigned int format, different type arg
970 sscanf(g->first.c_str(),"%x",&gr_bid);
971 tk = g->first + "|0000"; // generate the element full tag
973 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
975 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
976 elemZ = new gdcmHeaderEntry(tagZ);
978 AddHeaderEntry(elemZ); // create it
982 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
984 sprintf(trash ,"%d",g->second);
986 elemZ->SetValue(str_trash);
991 * \ingroup gdcmParser
992 * \brief writes on disc according to the requested format
993 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
994 * \ warning does NOT add the missing elements in the header :
995 * \ it's up to the user doing it !
996 * \ (function CheckHeaderCoherence to be written)
997 * \ warning DON'T try, right now, to write a DICOM image
998 * \ from an ACR Header (meta elements will be missing!)
999 * @param type type of the File to be written
1000 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1001 * @param _fp already open file pointer
1003 void gdcmParser::WriteEntries(FileType type, FILE * _fp)
1012 std::vector<std::string> tokens;
1014 // TODO : function CheckHeaderCoherence to be written
1016 // uses now listEntries to iterate, not TagHt!
1018 // pb : gdcmParser.Add does NOT update listEntries
1019 // TODO : find a trick (in STL?) to do it, at low cost !
1023 // TODO : get grPixel and numPixel
1024 guint16 grPixel =0x7fe0;
1025 guint16 numPixel=0x0010;
1026 //IterHT it = GetHeaderEntrySameNumber(grPixel,numPixel);
1029 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1031 for (ListTag::iterator tag2=listEntries.begin();
1032 tag2 != listEntries.end();
1035 gr = (*tag2)->GetGroup();
1036 el = (*tag2)->GetElement();
1037 lgr = (*tag2)->GetReadLength();
1038 val = (*tag2)->GetValue().c_str();
1039 vr = (*tag2)->GetVR();
1040 cout << hex << gr << " " << el << " " << vr <<" lgr " << lgr << endl;
1043 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
1044 if (gr %2) continue; // ignore shadow groups
1045 if (vr == "SQ" ) continue; // ignore Sequences
1046 // TODO : find a trick to *skip* the SeQuences !
1047 // Not only ignore the SQ element
1048 if (gr == 0xfffe ) continue; // ignore delimiters
1051 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1052 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1054 // === Deal with the length
1055 // --------------------
1057 // if ( (type == ExplicitVR) && (gr <= 0x0002) ) // ?!? < 2
1058 if ( (type == ExplicitVR) || (type == DICOMDIR) )
1061 guint16 z=0, shortLgr;
1062 if (vr == "Unknown") { // Unknown was 'written'
1064 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1065 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1067 if (gr != 0xfffe) { // NO value for 'delimiters'
1068 if (vr == "Unknown") // Unknown was 'written'
1069 fwrite(&z,(size_t)2 ,(size_t)1 ,_fp);
1071 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1074 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") || gr == 0xfffe) // JPR
1077 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1078 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1083 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1089 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1092 // === Deal with the value
1093 // -------------------
1094 if (vr == "SQ") continue; // no "value" to write for the SEQuences
1095 if (gr == 0xfffe)continue;
1097 if (vr == "US" || vr == "SS")
1099 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1100 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1101 for (unsigned int i=0; i<tokens.size();i++)
1103 val_uint16 = atoi(tokens[i].c_str());
1105 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1110 if (vr == "UL" || vr == "SL")
1112 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1113 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1114 for (unsigned int i=0; i<tokens.size();i++)
1116 val_uint32 = atoi(tokens[i].c_str());
1118 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1123 // Pixels are never loaded in the element !
1125 // TODO : FIX --> doesn't work when ICONE is found !!!
1127 if ((gr == grPixel) && (el == numPixel) )
1130 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1135 * \ingroup gdcmParser
1136 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1138 * @return The properly swaped 32 bits integer.
1140 guint32 gdcmParser::SwapLong(guint32 a) {
1145 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1146 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1150 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1154 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1157 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1164 * \ingroup gdcmParser
1165 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1167 * @return The properly unswaped 32 bits integer.
1169 guint32 gdcmParser::UnswapLong(guint32 a) {
1170 return (SwapLong(a));
1174 * \ingroup gdcmParser
1175 * \brief Swaps the bytes so they agree with the processor order
1176 * @return The properly swaped 16 bits integer.
1178 guint16 gdcmParser::SwapShort(guint16 a) {
1179 if ( (sw==4321) || (sw==2143) )
1180 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1185 * \ingroup gdcmParser
1186 * \brief Unswaps the bytes so they agree with the processor order
1187 * @return The properly unswaped 16 bits integer.
1189 guint16 gdcmParser::UnswapShort(guint16 a) {
1190 return (SwapShort(a));
1193 //-----------------------------------------------------------------------------
1196 * \ingroup gdcmParser
1197 * \brief Parses the header of the file but WITHOUT loading element values.
1198 * @return false if file is not ACR-NEMA / DICOM
1200 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1206 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1207 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1208 SkipHeaderEntry(newHeaderEntry);
1209 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1210 AddHeaderEntry(newHeaderEntry);
1217 * \ingroup gdcmParser
1218 * \brief Loads the element values of all the Header Entries pointed in the
1219 * public Chained List.
1221 void gdcmParser::LoadHeaderEntries(void) {
1223 for (ListTag::iterator i = GetListEntry().begin();
1224 i != GetListEntry().end();
1227 LoadHeaderEntry(*i);
1232 // Load 'non string' values
1233 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1234 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1235 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1236 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1237 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1238 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1240 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1241 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1242 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1245 // --------------------------------------------------------------
1246 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1248 // if recognition code tells us we deal with a LibIDO image
1249 // we switch lineNumber and columnNumber
1251 std::string RecCode;
1252 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1253 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1254 RecCode == "CANRME_AILIBOD1_1." )
1256 filetype = ACR_LIBIDO;
1257 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1258 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1259 SetEntryByNumber(columns, 0x0028, 0x0010);
1260 SetEntryByNumber(rows , 0x0028, 0x0011);
1262 // ----------------- End of Special Patch ----------------
1266 * \ingroup gdcmParser
1267 * \brief Loads the element content if its length doesn't exceed
1268 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1269 * @param Entry Header Entry (Dicom Element) to be dealt with
1271 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1273 guint16 group = Entry->GetGroup();
1274 std::string vr= Entry->GetVR();
1275 guint32 length = Entry->GetLength();
1276 bool SkipLoad = false;
1278 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1280 // the test was commented out to 'go inside' the SeQuences
1281 // we don't any longer skip them !
1283 // if( vr == "SQ" ) // (DO NOT remove this comment)
1286 // A SeQuence "contains" a set of Elements.
1287 // (fffe e000) tells us an Element is beginning
1288 // (fffe e00d) tells us an Element just ended
1289 // (fffe e0dd) tells us the current SeQuence just ended
1290 if( group == 0xfffe )
1294 Entry->SetLength(0);
1295 Entry->SetValue("gdcm::Skipped");
1299 // When the length is zero things are easy:
1300 if ( length == 0 ) {
1301 Entry->SetValue("");
1305 // The elements whose length is bigger than the specified upper bound
1306 // are not loaded. Instead we leave a short notice of the offset of
1307 // the element content and it's length.
1308 if (length > MaxSizeLoadEntry) {
1309 std::ostringstream s;
1310 s << "gdcm::NotLoaded.";
1311 s << " Address:" << (long)Entry->GetOffset();
1312 s << " Length:" << Entry->GetLength();
1313 s << " x(" << std::hex << Entry->GetLength() << ")";
1314 Entry->SetValue(s.str());
1318 // When integer(s) are expected, read and convert the following
1319 // n *(two or four bytes)
1320 // properly i.e. as integers as opposed to strings.
1321 // Elements with Value Multiplicity > 1
1322 // contain a set of integers (not a single one)
1324 // Any compacter code suggested (?)
1325 if ( IsHeaderEntryAnInteger(Entry) ) {
1327 std::ostringstream s;
1329 if (vr == "US" || vr == "SS") {
1331 NewInt = ReadInt16();
1334 for (int i=1; i < nbInt; i++) {
1336 NewInt = ReadInt16();
1341 else if (vr == "UL" || vr == "SL") {
1343 NewInt = ReadInt32();
1346 for (int i=1; i < nbInt; i++) {
1348 NewInt = ReadInt32();
1353 #ifdef GDCM_NO_ANSI_STRING_STREAM
1354 s << std::ends; // to avoid oddities on Solaris
1355 #endif //GDCM_NO_ANSI_STRING_STREAM
1357 Entry->SetValue(s.str());
1361 // We need an additional byte for storing \0 that is not on disk
1362 std::string NewValue(length,0);
1363 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1364 if ( item_read != 1 ) {
1365 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1366 Entry->SetValue("gdcm::UnRead");
1370 if( (vr == "UI") ) // Because of correspondance with the VR dic
1371 Entry->SetValue(NewValue.c_str()); // ??? JPR ???
1373 Entry->SetValue(NewValue);
1377 * \ingroup gdcmParser
1378 * \brief add a new Dicom Element pointer to
1379 * the H Table and to the chained List
1380 * \warning push_bash in listEntries ONLY during ParseHeader
1381 * \TODO something to allow further Elements addition,
1382 * \ when position to be taken care of
1383 * @param newHeaderEntry
1385 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1386 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1387 listEntries.push_back(newHeaderEntry);
1392 * \ingroup gdcmParser
1394 * @param Entry Header Entry whose length of the value shall be loaded.
1398 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1399 guint16 element = Entry->GetElement();
1400 guint16 group = Entry->GetGroup();
1401 std::string vr = Entry->GetVR();
1403 if( (element == 0x0010) && (group == 0x7fe0) )
1406 dbg.Verbose(2, "gdcmParser::FindLength: ",
1407 "we reached 7fe0 0010");
1410 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1412 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1414 // The following reserved two bytes (see PS 3.5-2001, section
1415 // 7.1.2 Data element structure with explicit vr p27) must be
1416 // skipped before proceeding on reading the length on 4 bytes.
1417 fseek(fp, 2L, SEEK_CUR);
1418 guint32 length32 = ReadInt32();
1420 if ( (vr == "OB") && (length32 == 0xffffffff) )
1422 Entry->SetLength(FindHeaderEntryLengthOB());
1425 FixHeaderEntryFoundLength(Entry, length32);
1429 // Length is encoded on 2 bytes.
1430 length16 = ReadInt16();
1432 // We can tell the current file is encoded in big endian (like
1433 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1434 // and it's value is the one of the encoding of a big endian file.
1435 // In order to deal with such big endian encoded files, we have
1436 // (at least) two strategies:
1437 // * when we load the "Transfer Syntax" tag with value of big endian
1438 // encoding, we raise the proper flags. Then we wait for the end
1439 // of the META group (0x0002) among which is "Transfer Syntax",
1440 // before switching the swap code to big endian. We have to postpone
1441 // the switching of the swap code since the META group is fully encoded
1442 // in little endian, and big endian coding only starts at the next
1443 // group. The corresponding code can be hard to analyse and adds
1444 // many additional unnecessary tests for regular tags.
1445 // * the second strategy consists in waiting for trouble, that shall
1446 // appear when we find the first group with big endian encoding. This
1447 // is easy to detect since the length of a "Group Length" tag (the
1448 // ones with zero as element number) has to be of 4 (0x0004). When we
1449 // encounter 1024 (0x0400) chances are the encoding changed and we
1450 // found a group with big endian encoding.
1451 // We shall use this second strategy. In order to make sure that we
1452 // can interpret the presence of an apparently big endian encoded
1453 // length of a "Group Length" without committing a big mistake, we
1454 // add an additional check: we look in the already parsed elements
1455 // for the presence of a "Transfer Syntax" whose value has to be "big
1456 // endian encoding". When this is the case, chances are we have got our
1457 // hands on a big endian encoded file: we switch the swap code to
1458 // big endian and proceed...
1459 if ( (element == 0x0000) && (length16 == 0x0400) )
1461 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1463 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1468 SwitchSwapToBigEndian();
1469 // Restore the unproperly loaded values i.e. the group, the element
1470 // and the dictionary entry depending on them.
1471 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1472 guint16 CorrectElem = SwapShort(Entry->GetElement());
1473 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1477 // This correct tag is not in the dictionary. Create a new one.
1478 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1480 // FIXME this can create a memory leaks on the old entry that be
1481 // left unreferenced.
1482 Entry->SetDictEntry(NewTag);
1485 // Heuristic: well some files are really ill-formed.
1486 if ( length16 == 0xffff)
1489 //dbg.Verbose(0, "gdcmParser::FindLength",
1490 // "Erroneous element length fixed.");
1491 // Actually, length= 0xffff means that we deal with
1492 // Unknown Sequence Length
1495 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1500 // Either implicit VR or a non DICOM conformal (see not below) explicit
1501 // VR that ommited the VR of (at least) this element. Farts happen.
1502 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1503 // on Data elements "Implicit and Explicit VR Data Elements shall
1504 // not coexist in a Data Set and Data Sets nested within it".]
1505 // Length is on 4 bytes.
1506 FixHeaderEntryFoundLength(Entry, ReadInt32());
1512 * \ingroup gdcmParser
1513 * \brief Find the Value Representation of the current Dicom Element.
1516 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1518 if (filetype != ExplicitVR)
1524 long PositionOnEntry = ftell(fp);
1525 // Warning: we believe this is explicit VR (Value Representation) because
1526 // we used a heuristic that found "UL" in the first tag. Alas this
1527 // doesn't guarantee that all the tags will be in explicit VR. In some
1528 // cases (see e-film filtered files) one finds implicit VR tags mixed
1529 // within an explicit VR file. Hence we make sure the present tag
1530 // is in explicit VR and try to fix things if it happens not to be
1533 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1535 if(!CheckHeaderEntryVR(Entry,VR))
1537 fseek(fp, PositionOnEntry, SEEK_SET);
1538 // When this element is known in the dictionary we shall use, e.g. for
1539 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1540 // dictionary entry. Still we have to flag the element as implicit since
1541 // we know now our assumption on expliciteness is not furfilled.
1543 if ( Entry->IsVRUnknown() )
1544 Entry->SetVR("Implicit");
1545 Entry->SetImplicitVR();
1550 * \ingroup gdcmParser
1551 * \brief Check the correspondance between the VR of the header entry
1552 * and the taken VR. If they are different, the header entry is
1553 * updated with the new VR.
1556 * @return false if the VR is incorrect of if the VR isn't referenced
1557 * otherwise, it returns true
1559 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1561 char msg[100]; // for sprintf
1562 bool RealExplicit = true;
1564 // Assume we are reading a falsely explicit VR file i.e. we reached
1565 // a tag where we expect reading a VR but are in fact we read the
1566 // first to bytes of the length. Then we will interogate (through find)
1567 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1568 // both GCC and VC++ implementations of the STL map. Hence when the
1569 // expected VR read happens to be non-ascii characters we consider
1570 // we hit falsely explicit VR tag.
1572 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1573 RealExplicit = false;
1575 // CLEANME searching the dicom_vr at each occurence is expensive.
1576 // PostPone this test in an optional integrity check at the end
1577 // of parsing or only in debug mode.
1578 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1579 RealExplicit= false;
1581 if ( !RealExplicit )
1583 // We thought this was explicit VR, but we end up with an
1584 // implicit VR tag. Let's backtrack.
1585 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1586 Entry->GetGroup(),Entry->GetElement());
1587 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1592 if ( Entry->IsVRUnknown() )
1594 // When not a dictionary entry, we can safely overwrite the VR.
1597 else if ( Entry->GetVR() != vr )
1599 // The VR present in the file and the dictionary disagree. We assume
1600 // the file writer knew best and use the VR of the file. Since it would
1601 // be unwise to overwrite the VR of a dictionary (since it would
1602 // compromise it's next user), we need to clone the actual DictEntry
1603 // and change the VR for the read one.
1604 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1605 Entry->GetGroup(),Entry->GetElement(),
1606 vr,"FIXME",Entry->GetName());
1607 Entry->SetDictEntry(NewEntry);
1613 * \ingroup gdcmParser
1614 * \brief Get the transformed value of the header entry. The VR value
1615 * is used to define the transformation to operate on the value
1616 * \warning NOT end user intended method !
1618 * @return Transformed entry value
1620 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1622 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1624 std::string val=Entry->GetValue();
1625 std::string vr=Entry->GetVR();
1626 guint32 length = Entry->GetLength();
1627 std::ostringstream s;
1630 if (vr == "US" || vr == "SS")
1635 for (int i=0; i < nbInt; i++)
1639 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1640 NewInt16 = SwapShort(NewInt16);
1645 else if (vr == "UL" || vr == "SL")
1650 for (int i=0; i < nbInt; i++)
1654 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1655 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1656 NewInt32=SwapLong(NewInt32);
1661 #ifdef GDCM_NO_ANSI_STRING_STREAM
1662 s << std::ends; // to avoid oddities on Solaris
1663 #endif //GDCM_NO_ANSI_STRING_STREAM
1667 return(Entry->GetValue());
1671 * \ingroup gdcmParser
1672 * \brief Get the reverse transformed value of the header entry. The VR
1673 * value is used to define the reverse transformation to operate on
1675 * \warning NOT end user intended method !
1677 * @return Reverse transformed entry value
1679 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1681 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1683 std::string vr=Entry->GetVR();
1684 std::ostringstream s;
1685 std::vector<std::string> tokens;
1687 if (vr == "US" || vr == "SS")
1691 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1692 Tokenize (Entry->GetValue(), tokens, "\\");
1693 for (unsigned int i=0; i<tokens.size();i++)
1695 NewInt16 = atoi(tokens[i].c_str());
1696 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1700 if (vr == "UL" || vr == "SL")
1704 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1705 Tokenize (Entry->GetValue(), tokens, "\\");
1706 for (unsigned int i=0; i<tokens.size();i++)
1708 NewInt32 = atoi(tokens[i].c_str());
1709 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1710 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1715 #ifdef GDCM_NO_ANSI_STRING_STREAM
1716 s << std::ends; // to avoid oddities on Solaris
1717 #endif //GDCM_NO_ANSI_STRING_STREAM
1721 return(Entry->GetValue());
1725 * \ingroup gdcmParser
1726 * \brief Skip a given Header Entry
1727 * \warning NOT end user intended method !
1730 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1732 SkipBytes(entry->GetLength());
1736 * \ingroup gdcmParser
1737 * \brief When the length of an element value is obviously wrong (because
1738 * the parser went Jabberwocky) one can hope improving things by
1739 * applying this heuristic.
1741 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1743 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1745 if ( FoundLength == 0xffffffff)
1750 // Sorry for the patch!
1751 // XMedCom did the trick to read some nasty GE images ...
1752 else if (FoundLength == 13)
1754 // The following 'if' will be removed when there is no more
1755 // images on Creatis HDs with a 13 length for Manufacturer...
1756 if ( (Entry->GetGroup() != 0x0008) ||
1757 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ) {
1758 // end of remove area
1760 Entry->SetReadLength(10); // a bug is to be fixed
1764 // to fix some garbage 'Leonardo' Siemens images
1765 // May be commented out to avoid overhead
1766 else if ( (Entry->GetGroup() == 0x0009) &&
1767 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) )
1770 Entry->SetReadLength(4); // a bug is to be fixed
1774 // to try to 'go inside' SeQuences (with length), and not to skip them
1775 else if ( Entry->GetVR() == "SQ")
1777 if (enableSequences) // only if the user does want to !
1778 FoundLength =0; // ReadLength is unchanged
1781 // a SeQuence Element is beginning
1782 // Let's forget it's length
1783 // (we want to 'go inside')
1785 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1786 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1787 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1788 // if we don't, we lost 28800 characters from the Header :-(
1790 else if(Entry->GetGroup() == 0xfffe)
1792 // sometimes, length seems to be wrong
1793 FoundLength =0; // some more clever checking to be done !
1795 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1796 // causes troubles :-(
1799 Entry->SetUsableLength(FoundLength);
1803 * \ingroup gdcmParser
1804 * \brief Apply some heuristics to predict wether the considered
1805 * element value contains/represents an integer or not.
1806 * @param Entry The element value on which to apply the predicate.
1807 * @return The result of the heuristical predicate.
1809 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1810 guint16 element = Entry->GetElement();
1811 guint16 group = Entry->GetGroup();
1812 std::string vr = Entry->GetVR();
1813 guint32 length = Entry->GetLength();
1814 // When we have some semantics on the element we just read, and if we
1815 // a priori know we are dealing with an integer, then we shall be
1816 // able to swap it's element value properly.
1817 if ( element == 0 ) // This is the group length of the group
1823 std::ostringstream s;
1824 int filePosition = ftell(fp);
1825 s << "Erroneous Group Length element length on : (" \
1826 << std::hex << group << " , " << element
1827 << ") -before- position x(" << filePosition << ")"
1828 << "lgt : " << length;
1829 // These 2 lines commented out : a *very dirty* patch
1830 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1831 // have a glance at offset x(8336) ...
1832 // For *regular* headers, the test is useless..
1833 // lets's print a warning message and go on,
1834 // instead of giving up with an error message
1835 std::cout << s.str().c_str() << std::endl;
1836 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1837 // s.str().c_str());
1840 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1847 * \ingroup gdcmParser
1852 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1853 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1856 long PositionOnEntry = ftell(fp);
1857 bool FoundSequenceDelimiter = false;
1858 guint32 TotalLength = 0;
1861 while ( ! FoundSequenceDelimiter)
1867 TotalLength += 4; // We even have to decount the group and element
1869 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1871 char msg[100]; // for sprintf. Sorry
1872 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1873 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1877 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1878 FoundSequenceDelimiter = true;
1879 else if ( n != 0xe000 )
1881 char msg[100]; // for sprintf. Sorry
1882 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1884 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1888 ItemLength = ReadInt32();
1889 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1890 // the ItemLength with ReadInt32
1891 SkipBytes(ItemLength);
1893 fseek(fp, PositionOnEntry, SEEK_SET);
1898 * \ingroup gdcmParser
1899 * \brief Reads a supposed to be 16 Bits integer
1900 * \ (swaps it depending on processor endianity)
1902 * @return read value
1904 guint16 gdcmParser::ReadInt16(void) {
1907 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1908 if ( item_read != 1 ) {
1910 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1920 * \ingroup gdcmParser
1921 * \brief Reads a supposed to be 32 Bits integer
1922 * \ (swaps it depending on processor endianity)
1924 * @return read value
1926 guint32 gdcmParser::ReadInt32(void) {
1929 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1930 if ( item_read != 1 ) {
1932 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1942 * \ingroup gdcmParser
1947 void gdcmParser::SkipBytes(guint32 NBytes) {
1948 //FIXME don't dump the returned value
1949 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1953 * \ingroup gdcmParser
1956 void gdcmParser::Initialise(void)
1958 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1959 RefShaDict = (gdcmDict*)0;
1963 * \ingroup gdcmParser
1964 * \brief Discover what the swap code is (among little endian, big endian,
1965 * bad little endian, bad big endian).
1967 * @return false when we are absolutely sure
1968 * it's neither ACR-NEMA nor DICOM
1969 * true when we hope ours assuptions are OK
1971 bool gdcmParser::CheckSwap() {
1973 // The only guaranted way of finding the swap code is to find a
1974 // group tag since we know it's length has to be of four bytes i.e.
1975 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1976 // occurs when we can't find such group...
1978 guint32 x=4; // x : for ntohs
1979 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1985 char deb[HEADER_LENGTH_TO_READ];
1987 // First, compare HostByteOrder and NetworkByteOrder in order to
1988 // determine if we shall need to swap bytes (i.e. the Endian type).
1994 // The easiest case is the one of a DICOM header, since it possesses a
1995 // file preamble where it suffice to look for the string "DICM".
1996 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1999 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2000 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2002 // Next, determine the value representation (VR). Let's skip to the
2003 // first element (0002, 0000) and check there if we find "UL"
2004 // - or "OB" if the 1st one is (0002,0001) -,
2005 // in which case we (almost) know it is explicit VR.
2006 // WARNING: if it happens to be implicit VR then what we will read
2007 // is the length of the group. If this ascii representation of this
2008 // length happens to be "UL" then we shall believe it is explicit VR.
2009 // FIXME: in order to fix the above warning, we could read the next
2010 // element value (or a couple of elements values) in order to make
2011 // sure we are not commiting a big mistake.
2012 // We need to skip :
2013 // * the 128 bytes of File Preamble (often padded with zeroes),
2014 // * the 4 bytes of "DICM" string,
2015 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2016 // i.e. a total of 136 bytes.
2019 // Use gdcmParser::dicom_vr to test all the possibilities
2020 // instead of just checking for UL, OB and UI !?
2021 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2022 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2023 (memcmp(entCur, "UI", (size_t)2) == 0) )
2025 filetype = ExplicitVR;
2026 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2027 "explicit Value Representation");
2031 filetype = ImplicitVR;
2032 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2033 "not an explicit Value Representation");
2038 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2039 "HostByteOrder != NetworkByteOrder");
2044 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2045 "HostByteOrder = NetworkByteOrder");
2048 // Position the file position indicator at first tag (i.e.
2049 // after the file preamble and the "DICM" string).
2051 fseek (fp, 132L, SEEK_SET);
2055 // Alas, this is not a DicomV3 file and whatever happens there is no file
2056 // preamble. We can reset the file position indicator to where the data
2057 // is (i.e. the beginning of the file).
2058 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2061 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2062 // By clean we mean that the length of the first tag is written down.
2063 // If this is the case and since the length of the first group HAS to be
2064 // four (bytes), then determining the proper swap code is straightforward.
2067 // We assume the array of char we are considering contains the binary
2068 // representation of a 32 bits integer. Hence the following dirty
2070 s32 = *((guint32 *)(entCur));
2091 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2092 // It is time for despaired wild guesses.
2093 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2094 // i.e. the 'group length' element is not present :
2096 // check the supposed to be 'group number'
2097 // 0x0002 or 0x0004 or 0x0008
2098 // to determine ' sw' value .
2099 // Only 0 or 4321 will be possible
2100 // (no oportunity to check for the formerly well known
2101 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2102 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2103 // the file IS NOT ACR-NEMA nor DICOM V3
2104 // Find a trick to tell it the caller...
2106 s16 = *((guint16 *)(deb));
2122 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2123 "ACR/NEMA unfound swap info (Really hopeless !)");
2128 // Then the only info we have is the net2host one.
2138 * \ingroup gdcmParser
2141 void gdcmParser::SwitchSwapToBigEndian(void)
2143 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2144 "Switching to BigEndian mode.");
2165 * \ingroup gdcmParser
2169 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2173 if ((guint32)NewSize >= (guint32)0xffffffff)
2175 MaxSizeLoadEntry = 0xffffffff;
2178 MaxSizeLoadEntry = NewSize;
2183 * \ingroup gdcmParser
2185 * \warning TODO : not yet usable
2186 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2187 * in gdcmHeaderEntry gdcmLoadEntry)
2191 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2195 if ((guint32)NewSize >= (guint32)0xffffffff)
2197 MaxSizePrintEntry = 0xffffffff;
2200 MaxSizePrintEntry = NewSize;
2204 * \ingroup gdcmParser
2205 * \brief Searches both the public and the shadow dictionary (when they
2206 * exist) for the presence of the DictEntry with given name.
2207 * The public dictionary has precedence on the shadow one.
2208 * @param Name name of the searched DictEntry
2209 * @return Corresponding DictEntry when it exists, NULL otherwise.
2211 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2213 gdcmDictEntry *found = (gdcmDictEntry *)0;
2214 if (!RefPubDict && !RefShaDict)
2216 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2217 "we SHOULD have a default dictionary");
2221 found = RefPubDict->GetDictEntryByName(Name);
2227 found = RefShaDict->GetDictEntryByName(Name);
2235 * \ingroup gdcmParser
2236 * \brief Searches both the public and the shadow dictionary (when they
2237 * exist) for the presence of the DictEntry with given
2238 * group and element. The public dictionary has precedence on the
2240 * @param group group of the searched DictEntry
2241 * @param element element of the searched DictEntry
2242 * @return Corresponding DictEntry when it exists, NULL otherwise.
2244 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2246 gdcmDictEntry *found = (gdcmDictEntry *)0;
2247 if (!RefPubDict && !RefShaDict)
2249 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2250 "we SHOULD have a default dictionary");
2254 found = RefPubDict->GetDictEntryByNumber(group, element);
2260 found = RefShaDict->GetDictEntryByNumber(group, element);
2268 * \ingroup gdcmParser
2269 * \brief Read the next tag but WITHOUT loading it's value
2270 * @return On succes the newly created HeaderEntry, NULL on failure.
2272 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2274 gdcmHeaderEntry *NewEntry;
2280 // We reached the EOF (or an error occured) therefore
2281 // header parsing has to be considered as finished.
2282 return (gdcmHeaderEntry *)0;
2284 /* Pb : how to propagate the element length (used in SkipHeaderEntry)
2285 // direct call to SkipBytes ?
2287 if (ignoreShadow == 1 && g%2 ==1) //JPR
2288 // if user wants to skip shadow groups
2289 // and current element *is* a shadow element
2290 // we don't create anything
2291 return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2293 NewEntry = NewHeaderEntryByNumber(g, n);
2294 FindHeaderEntryVR(NewEntry);
2295 FindHeaderEntryLength(NewEntry);
2301 NewEntry->SetOffset(ftell(fp));
2302 //if ( (g==0x7fe0) && (n==0x0010) )
2307 * \ingroup gdcmParser
2308 * \brief Build a new Element Value from all the low level arguments.
2309 * Check for existence of dictionary entry, and build
2310 * a default one when absent.
2311 * @param Name Name of the underlying DictEntry
2313 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2315 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2317 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2319 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2322 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2323 "failed to allocate gdcmHeaderEntry");
2324 return (gdcmHeaderEntry *)0;
2330 * \ingroup gdcmParser
2331 * \brief Request a new virtual dict entry to the dict set
2332 * @param group group of the underlying DictEntry
2333 * @param elem element of the underlying DictEntry
2334 * @param vr VR of the underlying DictEntry
2335 * @param fourth owner group
2336 * @param name english name
2338 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2343 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2347 * \ingroup gdcmParser
2348 * \brief Build a new Element Value from all the low level arguments.
2349 * Check for existence of dictionary entry, and build
2350 * a default one when absent.
2351 * @param Group group of the underlying DictEntry
2352 * @param Elem element of the underlying DictEntry
2354 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2356 // Find out if the tag we encountered is in the dictionaries:
2357 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2359 DictEntry = NewVirtualDictEntry(Group, Elem);
2361 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2364 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2365 "failed to allocate gdcmHeaderEntry");
2371 // Never used; commented out, waiting for removal.
2373 * \ingroup gdcmParser
2374 * \brief Small utility function that creates a new manually crafted
2375 * (as opposed as read from the file) gdcmHeaderEntry with user
2376 * specified name and adds it to the public tag hash table.
2377 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2378 * @param NewTagName The name to be given to this new tag.
2379 * @param VR The Value Representation to be given to this new tag.
2380 * @return The newly hand crafted Element Value.
2382 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2385 // gdcmHeaderEntry *NewEntry = NULL;
2386 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2387 // guint32 FreeElem = 0;
2388 // gdcmDictEntry *DictEntry = NULL;
2390 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2391 // if (FreeElem == UINT32_MAX)
2393 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2394 // "Group 0xffff in Public Dict is full");
2398 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2399 // VR, "GDCM", NewTagName);
2400 // NewEntry = new gdcmHeaderEntry(DictEntry);
2401 // AddHeaderEntry(NewEntry);
2406 * \ingroup gdcmParser
2407 * \brief Generate a free TagKey i.e. a TagKey that is not present
2408 * in the TagHt dictionary.
2409 * @param group The generated tag must belong to this group.
2410 * @return The element of tag with given group which is fee.
2412 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2414 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2416 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2417 if (tagHT.count(key) == 0)
2423 //-----------------------------------------------------------------------------