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))
112 wasUpdated = 0; // will be set to 1 if user adds an entry
113 printLevel = 1; // 'Medium' print level by default
117 * \ingroup gdcmParser
119 * @param exception_on_error
121 gdcmParser::gdcmParser(bool exception_on_error) {
124 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
127 wasUpdated = 0; // will be set to 1 if user adds an entry
128 printLevel = 1; // 'Medium' print level by default
132 * \ingroup gdcmParser
133 * \brief Canonical destructor.
135 gdcmParser::~gdcmParser (void) {
140 //-----------------------------------------------------------------------------
143 * \ingroup gdcmParser
144 * \brief Prints the Header Entries (Dicom Elements)
145 * both from the H Table and the chained list
148 void gdcmParser::PrintEntry(std::ostream & os) {
149 std::ostringstream s;
151 for (ListTag::iterator i = listEntries.begin();
152 i != listEntries.end();
155 (*i)->SetPrintLevel(printLevel);
162 * \ingroup gdcmParser
163 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
166 void gdcmParser::PrintPubDict(std::ostream & os) {
167 RefPubDict->Print(os);
171 * \ingroup gdcmParser
172 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
175 void gdcmParser::PrintShaDict(std::ostream & os) {
176 RefShaDict->Print(os);
179 //-----------------------------------------------------------------------------
182 * \ingroup gdcmParser
183 * \brief Get the public dictionary used
185 gdcmDict *gdcmParser::GetPubDict(void) {
190 * \ingroup gdcmParser
191 * \brief Get the shadow dictionary used
193 gdcmDict *gdcmParser::GetShaDict(void) {
198 * \ingroup gdcmParser
199 * \brief Set the shadow dictionary used
200 * \param dict dictionary to use in shadow
202 bool gdcmParser::SetShaDict(gdcmDict *dict){
208 * \ingroup gdcmParser
209 * \brief Set the shadow dictionary used
210 * \param dictName name of the dictionary to use in shadow
212 bool gdcmParser::SetShaDict(DictKey dictName){
213 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
218 * \ingroup gdcmParser
219 * \brief This predicate, based on hopefully reasonable heuristics,
220 * decides whether or not the current gdcmParser was properly parsed
221 * and contains the mandatory information for being considered as
222 * a well formed and usable Dicom/Acr File.
223 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
226 bool gdcmParser::IsReadable(void) {
227 if(filetype==Unknown) {
230 if(listEntries.size()<=0) {
238 * \ingroup gdcmParser
239 * \brief Determines if the Transfer Syntax was already encountered
240 * and if it corresponds to a ImplicitVRLittleEndian one.
242 * @return True when ImplicitVRLittleEndian found. False in all other cases.
244 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
245 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
248 LoadHeaderEntrySafe(Element);
250 std::string Transfer = Element->GetValue();
251 if ( Transfer == UI1_2_840_10008_1_2 )
257 * \ingroup gdcmParser
258 * \brief Determines if the Transfer Syntax was already encountered
259 * and if it corresponds to a ExplicitVRLittleEndian one.
261 * @return True when ExplicitVRLittleEndian found. False in all other cases.
263 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void) {
264 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
267 LoadHeaderEntrySafe(Element);
269 std::string Transfer = Element->GetValue();
270 if ( Transfer == UI1_2_840_10008_1_2_1 )
276 * \ingroup gdcmParser
277 * \brief Determines if the Transfer Syntax was already encountered
278 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
280 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
282 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
283 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
286 LoadHeaderEntrySafe(Element);
288 std::string Transfer = Element->GetValue();
289 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
295 * \ingroup gdcmParser
296 * \brief Determines if the Transfer Syntax was already encountered
297 * and if it corresponds to a Explicit VR Big Endian one.
299 * @return True when big endian found. False in all other cases.
301 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void) {
302 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
305 LoadHeaderEntrySafe(Element);
307 std::string Transfer = Element->GetValue();
308 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
314 * \ingroup gdcmParser
315 * \brief returns the File Type
316 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
319 FileType gdcmParser::GetFileType(void) {
324 * \ingroup gdcmParser
325 * \brief opens the file
326 * @param exception_on_error
329 FILE *gdcmParser::OpenFile(bool exception_on_error)
332 fp=fopen(filename.c_str(),"rb");
333 if(exception_on_error)
336 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
342 fread(&zero, (size_t)2, (size_t)1, fp);
344 //ACR -- or DICOM with no Preamble --
345 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
349 fseek(fp, 126L, SEEK_CUR);
351 fread(dicm, (size_t)4, (size_t)1, fp);
352 if( memcmp(dicm, "DICM", 4) == 0 )
356 dbg.Verbose(0, "gdcmParser::OpenFile not DICOM/ACR", filename.c_str());
359 dbg.Verbose(0, "gdcmParser::OpenFile cannot open file", filename.c_str());
365 * \ingroup gdcmParser
366 * \brief closes the file
367 * @return TRUE if the close was successfull
369 bool gdcmParser::CloseFile(void) {
370 int closed = fclose(fp);
378 * \ingroup gdcmParser
380 * @param fp file pointer on an already open file
381 * @param type type of the File to be written
382 * (ACR-NEMA, ExplicitVR, ImplicitVR)
383 * @return always "True" ?!
385 bool gdcmParser::Write(FILE *fp, FileType type) {
387 // TODO The stuff was rewritten using the chained list instead
389 // so we could remove the GroupHT from the gdcmParser
393 // TODO : move the following lines (and a lot of others, to be written)
394 // to a future function CheckAndCorrectHeader
397 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
398 // (FileType est un champ de gdcmParser ...)
399 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
401 // a moins de se livrer a un tres complique ajout des champs manquants.
402 // faire un CheckAndCorrectHeader (?)
405 if (type == ImplicitVR)
407 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
408 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
410 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
411 // values with a VR of UI shall be padded with a single trailing null
412 // Dans le cas suivant on doit pader manuellement avec un 0
414 SetEntryLengthByNumber(18, 0x0002, 0x0010);
417 if (type == ExplicitVR)
419 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
420 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
422 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
423 // values with a VR of UI shall be padded with a single trailing null
424 // Dans le cas suivant on doit pader manuellement avec un 0
426 SetEntryLengthByNumber(20, 0x0002, 0x0010);
429 /* TODO : rewrite later
431 if ( (type == ImplicitVR) || (type == ExplicitVR) )
432 UpdateGroupLength(false,type);
434 UpdateGroupLength(true,ACR);
437 WriteEntries(fp,type);
442 * \ingroup gdcmParser
443 * \brief Modifies the value of a given Header Entry (Dicom Element)
444 * if it exists; Creates it with the given value if it doesn't
445 * @param Value passed as a std::string
450 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
453 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
454 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
459 SetEntryByNumber(Value, Group, Elem);
464 * \ingroup gdcmParser
465 * \brief Modifies the value of a given Header Entry (Dicom Element)
466 * if it exists; Creates it with the given value if it doesn't
467 * @param Value passed as a char*
473 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
474 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
479 AddHeaderEntry(nvHeaderEntry);
481 std::string v = Value;
482 SetEntryByNumber(v, Group, Elem);
487 * \ingroup gdcmParser
488 * \brief Set a new value if the invoked element exists
489 * Seems to be useless !!!
495 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
497 std::string v = Value;
498 SetEntryByNumber(v, Group, Elem);
502 //-----------------------------------------------------------------------------
505 * \ingroup gdcmParser
506 * \brief Checks if a given Dicom Element exists
507 * \ within the H table
508 * @param group Group number of the searched Dicom Element
509 * @param element Element number of the searched Dicom Element
510 * @return number of occurences
512 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
513 std::string key = gdcmDictEntry::TranslateToKey(group, element );
514 return (tagHT.count(key));
518 * \ingroup gdcmParser
519 * \brief Searches within Header Entries (Dicom Elements) parsed with
520 * the public and private dictionaries
521 * for the element value of a given tag.
522 * \warning Don't use any longer : use GetPubEntryByName
523 * @param tagName name of the searched element.
524 * @return Corresponding element value when it exists,
525 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
527 std::string gdcmParser::GetEntryByName(std::string tagName) {
528 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
529 if( dictEntry == NULL)
532 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
536 * \ingroup gdcmParser
537 * \brief Searches within Header Entries (Dicom Elements) parsed with
538 * the public and private dictionaries
539 * for the element value representation of a given tag.
541 * Obtaining the VR (Value Representation) might be needed by caller
542 * to convert the string typed content to caller's native type
543 * (think of C++ vs Python). The VR is actually of a higher level
544 * of semantics than just the native C++ type.
545 * @param tagName name of the searched element.
546 * @return Corresponding element value representation when it exists,
547 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
549 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
550 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
551 if( dictEntry == NULL)
554 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
555 dictEntry->GetElement());
556 return elem->GetVR();
560 * \ingroup gdcmParser
561 * \brief Searches within Header Entries (Dicom Elements) parsed with
562 * the public and private dictionaries
563 * for the element value representation of a given tag.
564 * @param group Group of the searched tag.
565 * @param element Element of the searched tag.
566 * @return Corresponding element value representation when it exists,
567 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
569 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element){
570 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
571 if ( ! tagHT.count(key))
573 return tagHT.find(key)->second->GetValue();
577 * \ingroup gdcmParser
578 * \brief Searches within Header Entries (Dicom Elements) parsed with
579 * the public and private dictionaries
580 * for the element value representation of a given tag..
582 * Obtaining the VR (Value Representation) might be needed by caller
583 * to convert the string typed content to caller's native type
584 * (think of C++ vs Python). The VR is actually of a higher level
585 * of semantics than just the native C++ type.
586 * @param group Group of the searched tag.
587 * @param element Element of the searched tag.
588 * @return Corresponding element value representation when it exists,
589 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
591 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
592 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
595 return elem->GetVR();
599 * \ingroup gdcmParser
600 * \brief Sets the value (string) of the Header Entry (Dicom Element)
601 * @param content string value of the Dicom Element
602 * @param tagName name of the searched Dicom Element.
603 * @return true when found
605 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
606 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
607 if( dictEntry == NULL)
610 return(SetEntryByNumber(content,dictEntry->GetGroup(),
611 dictEntry->GetElement()));
615 * \ingroup gdcmParser
616 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
617 * through it's (group, element) and modifies it's content with
619 * \warning Don't use any longer : use SetPubEntryByNumber
620 * @param content new value to substitute with
621 * @param group group of the Dicom Element to modify
622 * @param element element of the Dicom Element to modify
624 bool gdcmParser::SetEntryByNumber(std::string content,
628 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
629 if ( ! tagHT.count(key))
631 int l = content.length();
632 if(l%2) // Odd length are padded with a space (020H).
635 content = content + '\0';
640 TagHeaderEntryHT::iterator p2;
641 // DO NOT remove the following lines : they explain the stuff
642 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
643 //p2=p.first; // iterator on the first synonym
644 //a=p2->second; // H Table target column (2-nd col)
647 a = ((tagHT.equal_range(key)).first)->second;
649 a-> SetValue(content);
651 std::string vr = a->GetVR();
654 if( (vr == "US") || (vr == "SS") )
656 else if( (vr == "UL") || (vr == "SL") )
666 * \ingroup gdcmParser
667 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
668 * in the PubHeaderEntrySet of this instance
669 * through it's (group, element) and modifies it's length with
671 * \warning Use with extreme caution.
672 * @param length new length to substitute with
673 * @param group group of the entry to modify
674 * @param element element of the Entry to modify
675 * @return 1 on success, 0 otherwise.
677 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
681 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
682 if ( ! tagHT.count(key))
684 if (length%2) length++; // length must be even
685 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
691 * \ingroup gdcmParser
692 * \brief Gets (from Header) the offset of a 'non string' element value
693 * \ (LoadElementValues has already be executed)
696 * @return File Offset of the Element Value
698 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
700 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
703 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
704 "failed to Locate gdcmHeaderEntry");
707 return Entry->GetOffset();
711 * \ingroup gdcmParser
712 * \brief Gets (from Header) a 'non string' element value
713 * \ (LoadElementValues has already be executed)
716 * @return Pointer to the 'non string' area
718 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
720 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
723 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
724 "failed to Locate gdcmHeaderEntry");
727 return Entry->GetVoidArea();
731 * \ingroup gdcmParser
732 * \brief Loads (from disk) the element content
733 * when a string is not suitable
737 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
739 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
742 size_t o =(size_t)Element->GetOffset();
743 fseek(fp, o, SEEK_SET);
744 int l=Element->GetLength();
745 void * a = malloc(l);
749 SetEntryVoidAreaByNumber(a, Group, Elem);
750 // TODO check the result
751 size_t l2 = fread(a, 1, l ,fp);
762 * \ingroup gdcmParser
763 * \brief Sets a 'non string' value to a given Dicom Element
765 * @param group Group number of the searched Dicom Element
766 * @param element Element number of the searched Dicom Element
769 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,
773 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
774 if ( ! tagHT.count(key))
776 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
781 * \ingroup gdcmParser
782 * \brief Update the entries with the shadow dictionary. Only odd entries are
785 void gdcmParser::UpdateShaEntries(void) {
786 gdcmDictEntry *entry;
789 for(ListTag::iterator it=listEntries.begin();
790 it!=listEntries.end();
793 // Odd group => from public dictionary
794 if((*it)->GetGroup()%2==0)
797 // Peer group => search the corresponding dict entry
799 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
803 if((*it)->IsImplicitVR())
808 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
810 // Set the new entry and the new value
811 (*it)->SetDictEntry(entry);
812 CheckHeaderEntryVR(*it,vr);
814 (*it)->SetValue(GetHeaderEntryValue(*it));
818 // Remove precedent value transformation
819 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
825 * \ingroup gdcmParser
826 * \brief Searches within the Header Entries for a Dicom Element of
828 * @param tagName name of the searched Dicom Element.
829 * @return Corresponding Dicom Element when it exists, and NULL
832 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName) {
833 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
834 if( dictEntry == NULL)
837 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
841 * \ingroup gdcmParser
842 * \brief retrieves a Dicom Element (the first one) using (group, element)
843 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
844 * if you think it's NOT UNIQUE, check the count number
845 * and use iterators to retrieve ALL the Dicoms Elements within
846 * a given couple (group, element)
847 * @param group Group number of the searched Dicom Element
848 * @param element Element number of the searched Dicom Element
851 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
853 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
854 if ( ! tagHT.count(key))
856 return tagHT.find(key)->second;
860 * \ingroup gdcmParser
861 * \brief retrieves the Dicom Elements (all of them) using (group, element)
862 * @param group Group number of the searched Dicom Element.
863 * @param element Element number of the searched Dicom Element.
864 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
867 IterHT gdcmParser::GetHeaderEntrySameNumber(guint16 group, guint16 element){
868 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
869 return (tagHT.equal_range(key));
873 * \ingroup gdcmParser
874 * \brief Loads the element while preserving the current
875 * underlying file position indicator as opposed to
876 * to LoadHeaderEntry that modifies it.
877 * @param entry Header Entry whose value shall be loaded.
880 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
881 long PositionOnEntry = ftell(fp);
882 LoadHeaderEntry(entry);
883 fseek(fp, PositionOnEntry, SEEK_SET);
887 * \ingroup gdcmParser
888 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
889 * \warning : to be re-written using the chained list instead of the H table.
890 * \warning : DO NOT use (doesn't work any longer because of the multimap)
891 * \todo : to be re-written using the chained list instead of the H table
892 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
893 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
895 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type) {
899 gdcmHeaderEntry *elem;
901 std::string str_trash;
904 GroupHT groupHt; // to hold the length of each group
907 // typedef std::map<GroupKey, int> GroupHT;
909 gdcmHeaderEntry *elemZ;
911 // for each Tag in the DCM Header
913 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
918 gr = elem->GetGroup();
919 el = elem->GetElement();
922 sprintf(trash, "%04x", gr);
923 key = trash; // generate 'group tag'
925 // if the caller decided not to take SEQUENCEs into account
926 // e.g : he wants to write an ACR-NEMA File
928 if (SkipSequence && vr == "SQ")
931 // Still unsolved problem :
932 // we cannot find the 'Sequence Delimitation Item'
933 // since it's at the end of the Hash Table
936 // pas SEQUENCE en ACR-NEMA
938 // --> la descente a l'interieur' des SQ
939 // devrait etre faite avec une liste chainee, pas avec une HTable...
941 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
943 if (el == 0x0000) // the first elem is 0x0000
945 groupHt[key] = 0; // initialize group length
949 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
952 else // any elem but the first
954 if (type == ExplicitVR)
956 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
958 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
961 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
965 unsigned short int gr_bid;
967 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
971 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
972 // warning: unsigned int format, different type arg
973 sscanf(g->first.c_str(),"%x",&gr_bid);
974 tk = g->first + "|0000"; // generate the element full tag
976 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
978 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
979 elemZ = new gdcmHeaderEntry(tagZ);
981 AddHeaderEntry(elemZ); // create it
985 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
987 sprintf(trash ,"%d",g->second);
989 elemZ->SetValue(str_trash);
994 * \ingroup gdcmParser
995 * \brief writes on disc according to the requested format
996 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
997 * \ warning does NOT add the missing elements in the header :
998 * \ it's up to the user doing it !
999 * \ (function CheckHeaderCoherence to be written)
1000 * \ warning DON'T try, right now, to write a DICOM image
1001 * \ from an ACR Header (meta elements will be missing!)
1002 * @param type type of the File to be written
1003 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1004 * @param _fp already open file pointer
1006 void gdcmParser::WriteEntries(FILE *_fp,FileType type)
1016 std::vector<std::string> tokens;
1018 // TODO : function CheckHeaderCoherence to be written
1020 // uses now listEntries to iterate, not TagHt!
1022 // pb : gdcmParser.Add does NOT update listEntries
1023 // TODO : find a trick (in STL?) to do it, at low cost !
1027 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
1030 for (ListTag::iterator tag2=listEntries.begin();
1031 tag2 != listEntries.end();
1034 gr = (*tag2)->GetGroup();
1035 el = (*tag2)->GetElement();
1036 lgr = (*tag2)->GetReadLength();
1037 val = (*tag2)->GetValue().c_str();
1038 vr = (*tag2)->GetVR();
1039 voidArea = (*tag2)->GetVoidArea();
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 == "unkn") { // 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 == "unkn") // 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)
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 (voidArea != NULL) { // there is a 'non string' LUT, overlay, etc
1098 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1102 if (vr == "US" || vr == "SS")
1104 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1105 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1106 for (unsigned int i=0; i<tokens.size();i++)
1108 val_uint16 = atoi(tokens[i].c_str());
1110 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1115 if (vr == "UL" || vr == "SL")
1117 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1118 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1119 for (unsigned int i=0; i<tokens.size();i++)
1121 val_uint32 = atoi(tokens[i].c_str());
1123 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1129 // Pixels are never loaded in the element !
1130 // we stop writting when Pixel are processed
1131 // FIX : we loose trailing elements (RAB, right now)
1133 if ((gr == GrPixel) && (el == NumPixel) ) {
1135 if (compte == countGrPixel) // we passed *all* the GrPixel,NumPixel
1138 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1143 * \ingroup gdcmParser
1144 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1146 * @return The properly swaped 32 bits integer.
1148 guint32 gdcmParser::SwapLong(guint32 a) {
1153 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1154 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1158 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1162 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1165 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1172 * \ingroup gdcmParser
1173 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1175 * @return The properly unswaped 32 bits integer.
1177 guint32 gdcmParser::UnswapLong(guint32 a) {
1178 return (SwapLong(a));
1182 * \ingroup gdcmParser
1183 * \brief Swaps the bytes so they agree with the processor order
1184 * @return The properly swaped 16 bits integer.
1186 guint16 gdcmParser::SwapShort(guint16 a) {
1187 if ( (sw==4321) || (sw==2143) )
1188 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1193 * \ingroup gdcmParser
1194 * \brief Unswaps the bytes so they agree with the processor order
1195 * @return The properly unswaped 16 bits integer.
1197 guint16 gdcmParser::UnswapShort(guint16 a) {
1198 return (SwapShort(a));
1201 //-----------------------------------------------------------------------------
1204 * \ingroup gdcmParser
1205 * \brief Parses the header of the file but WITHOUT loading element values.
1206 * @return false if file is not ACR-NEMA / DICOM
1208 bool gdcmParser::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1214 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1215 while ( (newHeaderEntry = ReadNextHeaderEntry()) ) {
1216 SkipHeaderEntry(newHeaderEntry);
1217 if ( (ignoreShadow==0) || (newHeaderEntry->GetGroup()%2) == 0) {
1218 AddHeaderEntry(newHeaderEntry);
1225 * \ingroup gdcmParser
1226 * \brief Loads the element values of all the Header Entries pointed in the
1227 * public Chained List.
1229 void gdcmParser::LoadHeaderEntries(void) {
1231 for (ListTag::iterator i = GetListEntry().begin();
1232 i != GetListEntry().end();
1235 LoadHeaderEntry(*i);
1240 // Load 'non string' values
1241 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1242 if( PhotometricInterpretation == "PALETTE COLOR " ) {
1243 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1244 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1245 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1246 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1248 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1249 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1250 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1252 //FIXME : how to use it?
1253 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
1255 // --------------------------------------------------------------
1256 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1258 // if recognition code tells us we deal with a LibIDO image
1259 // we switch lineNumber and columnNumber
1261 std::string RecCode;
1262 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1263 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1264 RecCode == "CANRME_AILIBOD1_1." )
1266 filetype = ACR_LIBIDO;
1267 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1268 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1269 SetEntryByNumber(columns, 0x0028, 0x0010);
1270 SetEntryByNumber(rows , 0x0028, 0x0011);
1272 // ----------------- End of Special Patch ----------------
1276 * \ingroup gdcmParser
1277 * \brief Loads the element content if its length doesn't exceed
1278 * the value specified with gdcmParser::SetMaxSizeLoadEntry()
1279 * @param Entry Header Entry (Dicom Element) to be dealt with
1281 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1283 guint16 group = Entry->GetGroup();
1284 std::string vr= Entry->GetVR();
1285 guint32 length = Entry->GetLength();
1286 bool SkipLoad = false;
1288 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1290 // the test was commented out to 'go inside' the SeQuences
1291 // we don't any longer skip them !
1293 // if( vr == "SQ" ) // (DO NOT remove this comment)
1296 // A SeQuence "contains" a set of Elements.
1297 // (fffe e000) tells us an Element is beginning
1298 // (fffe e00d) tells us an Element just ended
1299 // (fffe e0dd) tells us the current SeQuence just ended
1300 if( group == 0xfffe )
1304 Entry->SetLength(0);
1305 Entry->SetValue("gdcm::Skipped");
1309 // When the length is zero things are easy:
1310 if ( length == 0 ) {
1311 Entry->SetValue("");
1315 // The elements whose length is bigger than the specified upper bound
1316 // are not loaded. Instead we leave a short notice of the offset of
1317 // the element content and it's length.
1318 if (length > MaxSizeLoadEntry) {
1319 std::ostringstream s;
1320 s << "gdcm::NotLoaded.";
1321 s << " Address:" << (long)Entry->GetOffset();
1322 s << " Length:" << Entry->GetLength();
1323 s << " x(" << std::hex << Entry->GetLength() << ")";
1324 Entry->SetValue(s.str());
1328 // When integer(s) are expected, read and convert the following
1329 // n *(two or four bytes)
1330 // properly i.e. as integers as opposed to strings.
1331 // Elements with Value Multiplicity > 1
1332 // contain a set of integers (not a single one)
1334 // Any compacter code suggested (?)
1335 if ( IsHeaderEntryAnInteger(Entry) ) {
1337 std::ostringstream s;
1339 if (vr == "US" || vr == "SS") {
1341 NewInt = ReadInt16();
1344 for (int i=1; i < nbInt; i++) {
1346 NewInt = ReadInt16();
1351 else if (vr == "UL" || vr == "SL") {
1353 NewInt = ReadInt32();
1356 for (int i=1; i < nbInt; i++) {
1358 NewInt = ReadInt32();
1363 #ifdef GDCM_NO_ANSI_STRING_STREAM
1364 s << std::ends; // to avoid oddities on Solaris
1365 #endif //GDCM_NO_ANSI_STRING_STREAM
1367 Entry->SetValue(s.str());
1371 // We need an additional byte for storing \0 that is not on disk
1372 std::string NewValue(length,0);
1373 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1374 if ( item_read != 1 ) {
1375 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1376 Entry->SetValue("gdcm::UnRead");
1380 if( (vr == "UI") ) // Because of correspondance with the VR dic
1381 Entry->SetValue(NewValue.c_str()); // ??? JPR ???
1383 Entry->SetValue(NewValue);
1387 * \ingroup gdcmParser
1388 * \brief add a new Dicom Element pointer to
1389 * the H Table and to the chained List
1390 * \warning push_bash in listEntries ONLY during ParseHeader
1391 * \TODO something to allow further Elements addition,
1392 * \ when position to be taken care of
1393 * @param newHeaderEntry
1395 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1396 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1397 listEntries.push_back(newHeaderEntry);
1402 * \ingroup gdcmParser
1404 * @param Entry Header Entry whose length of the value shall be loaded.
1408 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1409 guint16 element = Entry->GetElement();
1410 guint16 group = Entry->GetGroup();
1411 std::string vr = Entry->GetVR();
1413 if( (element == NumPixel) && (group == GrPixel) )
1416 dbg.Verbose(2, "gdcmParser::FindLength: ",
1417 "we reached (GrPixel,NumPixel)");
1420 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1422 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1424 // The following reserved two bytes (see PS 3.5-2001, section
1425 // 7.1.2 Data element structure with explicit vr p27) must be
1426 // skipped before proceeding on reading the length on 4 bytes.
1427 fseek(fp, 2L, SEEK_CUR);
1428 guint32 length32 = ReadInt32();
1430 if ( (vr == "OB") && (length32 == 0xffffffff) )
1432 Entry->SetLength(FindHeaderEntryLengthOB());
1435 FixHeaderEntryFoundLength(Entry, length32);
1439 // Length is encoded on 2 bytes.
1440 length16 = ReadInt16();
1442 // We can tell the current file is encoded in big endian (like
1443 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1444 // and it's value is the one of the encoding of a big endian file.
1445 // In order to deal with such big endian encoded files, we have
1446 // (at least) two strategies:
1447 // * when we load the "Transfer Syntax" tag with value of big endian
1448 // encoding, we raise the proper flags. Then we wait for the end
1449 // of the META group (0x0002) among which is "Transfer Syntax",
1450 // before switching the swap code to big endian. We have to postpone
1451 // the switching of the swap code since the META group is fully encoded
1452 // in little endian, and big endian coding only starts at the next
1453 // group. The corresponding code can be hard to analyse and adds
1454 // many additional unnecessary tests for regular tags.
1455 // * the second strategy consists in waiting for trouble, that shall
1456 // appear when we find the first group with big endian encoding. This
1457 // is easy to detect since the length of a "Group Length" tag (the
1458 // ones with zero as element number) has to be of 4 (0x0004). When we
1459 // encounter 1024 (0x0400) chances are the encoding changed and we
1460 // found a group with big endian encoding.
1461 // We shall use this second strategy. In order to make sure that we
1462 // can interpret the presence of an apparently big endian encoded
1463 // length of a "Group Length" without committing a big mistake, we
1464 // add an additional check: we look in the already parsed elements
1465 // for the presence of a "Transfer Syntax" whose value has to be "big
1466 // endian encoding". When this is the case, chances are we have got our
1467 // hands on a big endian encoded file: we switch the swap code to
1468 // big endian and proceed...
1469 if ( (element == 0x0000) && (length16 == 0x0400) )
1471 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1473 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1478 SwitchSwapToBigEndian();
1479 // Restore the unproperly loaded values i.e. the group, the element
1480 // and the dictionary entry depending on them.
1481 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1482 guint16 CorrectElem = SwapShort(Entry->GetElement());
1483 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1487 // This correct tag is not in the dictionary. Create a new one.
1488 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1490 // FIXME this can create a memory leaks on the old entry that be
1491 // left unreferenced.
1492 Entry->SetDictEntry(NewTag);
1495 // Heuristic: well some files are really ill-formed.
1496 if ( length16 == 0xffff)
1499 //dbg.Verbose(0, "gdcmParser::FindLength",
1500 // "Erroneous element length fixed.");
1501 // Actually, length= 0xffff means that we deal with
1502 // Unknown Sequence Length
1505 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1510 // Either implicit VR or a non DICOM conformal (see not below) explicit
1511 // VR that ommited the VR of (at least) this element. Farts happen.
1512 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1513 // on Data elements "Implicit and Explicit VR Data Elements shall
1514 // not coexist in a Data Set and Data Sets nested within it".]
1515 // Length is on 4 bytes.
1516 FixHeaderEntryFoundLength(Entry, ReadInt32());
1522 * \ingroup gdcmParser
1523 * \brief Find the Value Representation of the current Dicom Element.
1526 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1528 if (filetype != ExplicitVR)
1533 long PositionOnEntry = ftell(fp);
1534 // Warning: we believe this is explicit VR (Value Representation) because
1535 // we used a heuristic that found "UL" in the first tag. Alas this
1536 // doesn't guarantee that all the tags will be in explicit VR. In some
1537 // cases (see e-film filtered files) one finds implicit VR tags mixed
1538 // within an explicit VR file. Hence we make sure the present tag
1539 // is in explicit VR and try to fix things if it happens not to be
1542 int lgrLue=fread (&VR, (size_t)2,(size_t)1, fp); // lgrLue not used
1544 if(!CheckHeaderEntryVR(Entry,VR))
1546 fseek(fp, PositionOnEntry, SEEK_SET);
1547 // When this element is known in the dictionary we shall use, e.g. for
1548 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1549 // dictionary entry. Still we have to flag the element as implicit since
1550 // we know now our assumption on expliciteness is not furfilled.
1552 if ( Entry->IsVRUnknown() )
1553 Entry->SetVR("Implicit");
1554 Entry->SetImplicitVR();
1559 * \ingroup gdcmParser
1560 * \brief Check the correspondance between the VR of the header entry
1561 * and the taken VR. If they are different, the header entry is
1562 * updated with the new VR.
1565 * @return false if the VR is incorrect of if the VR isn't referenced
1566 * otherwise, it returns true
1568 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1570 char msg[100]; // for sprintf
1571 bool RealExplicit = true;
1573 // Assume we are reading a falsely explicit VR file i.e. we reached
1574 // a tag where we expect reading a VR but are in fact we read the
1575 // first to bytes of the length. Then we will interogate (through find)
1576 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1577 // both GCC and VC++ implementations of the STL map. Hence when the
1578 // expected VR read happens to be non-ascii characters we consider
1579 // we hit falsely explicit VR tag.
1581 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1582 RealExplicit = false;
1584 // CLEANME searching the dicom_vr at each occurence is expensive.
1585 // PostPone this test in an optional integrity check at the end
1586 // of parsing or only in debug mode.
1587 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1588 RealExplicit= false;
1590 if ( !RealExplicit )
1592 // We thought this was explicit VR, but we end up with an
1593 // implicit VR tag. Let's backtrack.
1594 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1595 Entry->GetGroup(),Entry->GetElement());
1596 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1597 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1598 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1599 Entry->GetGroup(),Entry->GetElement(),
1600 "UL","FIXME","Group Length");
1601 Entry->SetDictEntry(NewEntry);
1606 if ( Entry->IsVRUnknown() )
1608 // When not a dictionary entry, we can safely overwrite the VR.
1609 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1615 else if ( Entry->GetVR() != vr )
1617 // The VR present in the file and the dictionary disagree. We assume
1618 // the file writer knew best and use the VR of the file. Since it would
1619 // be unwise to overwrite the VR of a dictionary (since it would
1620 // compromise it's next user), we need to clone the actual DictEntry
1621 // and change the VR for the read one.
1622 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1623 Entry->GetGroup(),Entry->GetElement(),
1624 vr,"FIXME",Entry->GetName());
1625 Entry->SetDictEntry(NewEntry);
1631 * \ingroup gdcmParser
1632 * \brief Get the transformed value of the header entry. The VR value
1633 * is used to define the transformation to operate on the value
1634 * \warning NOT end user intended method !
1636 * @return Transformed entry value
1638 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1640 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1642 std::string val=Entry->GetValue();
1643 std::string vr=Entry->GetVR();
1644 guint32 length = Entry->GetLength();
1645 std::ostringstream s;
1648 if (vr == "US" || vr == "SS")
1653 for (int i=0; i < nbInt; i++)
1657 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1658 NewInt16 = SwapShort(NewInt16);
1663 else if (vr == "UL" || vr == "SL")
1668 for (int i=0; i < nbInt; i++)
1672 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1673 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1674 NewInt32=SwapLong(NewInt32);
1678 #ifdef GDCM_NO_ANSI_STRING_STREAM
1679 s << std::ends; // to avoid oddities on Solaris
1680 #endif //GDCM_NO_ANSI_STRING_STREAM
1684 return(Entry->GetValue());
1688 * \ingroup gdcmParser
1689 * \brief Get the reverse transformed value of the header entry. The VR
1690 * value is used to define the reverse transformation to operate on
1692 * \warning NOT end user intended method !
1694 * @return Reverse transformed entry value
1696 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1698 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1700 std::string vr=Entry->GetVR();
1701 std::ostringstream s;
1702 std::vector<std::string> tokens;
1704 if (vr == "US" || vr == "SS")
1708 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1709 Tokenize (Entry->GetValue(), tokens, "\\");
1710 for (unsigned int i=0; i<tokens.size();i++)
1712 NewInt16 = atoi(tokens[i].c_str());
1713 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1717 if (vr == "UL" || vr == "SL")
1721 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1722 Tokenize (Entry->GetValue(), tokens, "\\");
1723 for (unsigned int i=0; i<tokens.size();i++)
1725 NewInt32 = atoi(tokens[i].c_str());
1726 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1727 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1732 #ifdef GDCM_NO_ANSI_STRING_STREAM
1733 s << std::ends; // to avoid oddities on Solaris
1734 #endif //GDCM_NO_ANSI_STRING_STREAM
1738 return(Entry->GetValue());
1742 * \ingroup gdcmParser
1743 * \brief Skip a given Header Entry
1744 * \warning NOT end user intended method !
1747 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1749 SkipBytes(entry->GetLength());
1753 * \ingroup gdcmParser
1754 * \brief When the length of an element value is obviously wrong (because
1755 * the parser went Jabberwocky) one can hope improving things by
1756 * applying this heuristic.
1758 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1760 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1762 if ( FoundLength == 0xffffffff) {
1766 guint16 gr =Entry->GetGroup();
1767 guint16 el =Entry->GetElement();
1769 if (FoundLength%2) {
1770 std::cout << "Warning : Tag with uneven length " << FoundLength
1771 << " in x(" << std::hex << gr << "," << el <<")" << std::dec << std::endl;
1774 // Sorry for the patch!
1775 // XMedCom did the trick to read some nasty GE images ...
1776 if (FoundLength == 13) {
1777 // The following 'if' will be removed when there is no more
1778 // images on Creatis HDs with a 13 length for Manufacturer...
1779 if ( (Entry->GetGroup() != 0x0008) ||
1780 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1781 // end of remove area
1783 Entry->SetReadLength(10); // a bug is to be fixed
1787 // to fix some garbage 'Leonardo' Siemens images
1788 // May be commented out to avoid overhead
1789 else if ( (Entry->GetGroup() == 0x0009) &&
1790 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1792 Entry->SetReadLength(4); // a bug is to be fixed
1796 // to try to 'go inside' SeQuences (with length), and not to skip them
1797 else if ( Entry->GetVR() == "SQ")
1799 if (enableSequences) // only if the user does want to !
1800 FoundLength =0; // ReadLength is unchanged
1803 // a SeQuence Element is beginning
1804 // Let's forget it's length
1805 // (we want to 'go inside')
1807 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1808 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1809 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1810 // if we don't, we lost 28800 characters from the Header :-(
1812 else if(Entry->GetGroup() == 0xfffe)
1814 // sometimes, length seems to be wrong
1815 FoundLength =0; // some more clever checking to be done !
1817 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1818 // causes troubles :-(
1821 Entry->SetUsableLength(FoundLength);
1825 * \ingroup gdcmParser
1826 * \brief Apply some heuristics to predict wether the considered
1827 * element value contains/represents an integer or not.
1828 * @param Entry The element value on which to apply the predicate.
1829 * @return The result of the heuristical predicate.
1831 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1832 guint16 element = Entry->GetElement();
1833 guint16 group = Entry->GetGroup();
1834 std::string vr = Entry->GetVR();
1835 guint32 length = Entry->GetLength();
1836 // When we have some semantics on the element we just read, and if we
1837 // a priori know we are dealing with an integer, then we shall be
1838 // able to swap it's element value properly.
1839 if ( element == 0 ) // This is the group length of the group
1845 std::ostringstream s;
1846 int filePosition = ftell(fp);
1847 s << "Erroneous Group Length element length on : (" \
1848 << std::hex << group << " , " << element
1849 << ") -before- position x(" << filePosition << ")"
1850 << "lgt : " << length;
1851 // These 2 lines commented out : a *very dirty* patch
1852 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1853 // have a glance at offset x(8336) ...
1854 // For *regular* headers, the test is useless..
1855 // lets's print a warning message and go on,
1856 // instead of giving up with an error message
1858 //std::cout << s.str().c_str() << std::endl;
1860 // dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1861 // s.str().c_str());
1864 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1871 * \ingroup gdcmParser
1876 guint32 gdcmParser::FindHeaderEntryLengthOB(void) {
1877 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1880 long PositionOnEntry = ftell(fp);
1881 bool FoundSequenceDelimiter = false;
1882 guint32 TotalLength = 0;
1885 while ( ! FoundSequenceDelimiter)
1891 TotalLength += 4; // We even have to decount the group and element
1893 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1895 char msg[100]; // for sprintf. Sorry
1896 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1897 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1901 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1902 FoundSequenceDelimiter = true;
1903 else if ( n != 0xe000 )
1905 char msg[100]; // for sprintf. Sorry
1906 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1908 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1912 ItemLength = ReadInt32();
1913 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1914 // the ItemLength with ReadInt32
1915 SkipBytes(ItemLength);
1917 fseek(fp, PositionOnEntry, SEEK_SET);
1922 * \ingroup gdcmParser
1923 * \brief Reads a supposed to be 16 Bits integer
1924 * \ (swaps it depending on processor endianity)
1926 * @return read value
1928 guint16 gdcmParser::ReadInt16(void) {
1931 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1932 if ( item_read != 1 ) {
1934 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1944 * \ingroup gdcmParser
1945 * \brief Reads a supposed to be 32 Bits integer
1946 * \ (swaps it depending on processor endianity)
1948 * @return read value
1950 guint32 gdcmParser::ReadInt32(void) {
1953 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1954 if ( item_read != 1 ) {
1956 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1966 * \ingroup gdcmParser
1971 void gdcmParser::SkipBytes(guint32 NBytes) {
1972 //FIXME don't dump the returned value
1973 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1977 * \ingroup gdcmParser
1980 void gdcmParser::Initialise(void)
1982 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1983 RefShaDict = (gdcmDict*)0;
1987 * \ingroup gdcmParser
1988 * \brief Discover what the swap code is (among little endian, big endian,
1989 * bad little endian, bad big endian).
1991 * @return false when we are absolutely sure
1992 * it's neither ACR-NEMA nor DICOM
1993 * true when we hope ours assuptions are OK
1995 bool gdcmParser::CheckSwap() {
1997 // The only guaranted way of finding the swap code is to find a
1998 // group tag since we know it's length has to be of four bytes i.e.
1999 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2000 // occurs when we can't find such group...
2002 guint32 x=4; // x : for ntohs
2003 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2009 char deb[HEADER_LENGTH_TO_READ];
2011 // First, compare HostByteOrder and NetworkByteOrder in order to
2012 // determine if we shall need to swap bytes (i.e. the Endian type).
2018 // The easiest case is the one of a DICOM header, since it possesses a
2019 // file preamble where it suffice to look for the string "DICM".
2020 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2023 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2024 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
2026 // Next, determine the value representation (VR). Let's skip to the
2027 // first element (0002, 0000) and check there if we find "UL"
2028 // - or "OB" if the 1st one is (0002,0001) -,
2029 // in which case we (almost) know it is explicit VR.
2030 // WARNING: if it happens to be implicit VR then what we will read
2031 // is the length of the group. If this ascii representation of this
2032 // length happens to be "UL" then we shall believe it is explicit VR.
2033 // FIXME: in order to fix the above warning, we could read the next
2034 // element value (or a couple of elements values) in order to make
2035 // sure we are not commiting a big mistake.
2036 // We need to skip :
2037 // * the 128 bytes of File Preamble (often padded with zeroes),
2038 // * the 4 bytes of "DICM" string,
2039 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2040 // i.e. a total of 136 bytes.
2044 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2045 // but elem 0002,0010 (Transfert Syntax) tells us the file is *Implicit* VR.
2048 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2049 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2050 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2051 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2052 // when Write DCM *adds*
2054 // Use gdcmParser::dicom_vr to test all the possibilities
2055 // instead of just checking for UL, OB and UI !? // group 0000
2058 filetype = ExplicitVR;
2059 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2060 "explicit Value Representation");
2064 filetype = ImplicitVR;
2065 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2066 "not an explicit Value Representation");
2072 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2073 "HostByteOrder != NetworkByteOrder");
2078 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2079 "HostByteOrder = NetworkByteOrder");
2082 // Position the file position indicator at first tag (i.e.
2083 // after the file preamble and the "DICM" string).
2085 fseek (fp, 132L, SEEK_SET);
2089 // Alas, this is not a DicomV3 file and whatever happens there is no file
2090 // preamble. We can reset the file position indicator to where the data
2091 // is (i.e. the beginning of the file).
2092 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2095 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2096 // By clean we mean that the length of the first tag is written down.
2097 // If this is the case and since the length of the first group HAS to be
2098 // four (bytes), then determining the proper swap code is straightforward.
2101 // We assume the array of char we are considering contains the binary
2102 // representation of a 32 bits integer. Hence the following dirty
2104 s32 = *((guint32 *)(entCur));
2125 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2126 // It is time for despaired wild guesses.
2127 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2128 // i.e. the 'group length' element is not present :
2130 // check the supposed to be 'group number'
2131 // 0x0002 or 0x0004 or 0x0008
2132 // to determine ' sw' value .
2133 // Only 0 or 4321 will be possible
2134 // (no oportunity to check for the formerly well known
2135 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2136 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2137 // the file IS NOT ACR-NEMA nor DICOM V3
2138 // Find a trick to tell it the caller...
2140 s16 = *((guint16 *)(deb));
2156 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2157 "ACR/NEMA unfound swap info (Really hopeless !)");
2162 // Then the only info we have is the net2host one.
2172 * \ingroup gdcmParser
2175 void gdcmParser::SwitchSwapToBigEndian(void)
2177 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2178 "Switching to BigEndian mode.");
2199 * \ingroup gdcmParser
2203 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2207 if ((guint32)NewSize >= (guint32)0xffffffff)
2209 MaxSizeLoadEntry = 0xffffffff;
2212 MaxSizeLoadEntry = NewSize;
2217 * \ingroup gdcmParser
2219 * \warning TODO : not yet usable
2220 * (see MAX_SIZE_PRINT_ELEMENT_VALUE
2221 * in gdcmHeaderEntry gdcmLoadEntry)
2225 void gdcmParser::SetMaxSizePrintEntry(long NewSize)
2229 if ((guint32)NewSize >= (guint32)0xffffffff)
2231 MaxSizePrintEntry = 0xffffffff;
2234 MaxSizePrintEntry = NewSize;
2238 * \ingroup gdcmParser
2239 * \brief Searches both the public and the shadow dictionary (when they
2240 * exist) for the presence of the DictEntry with given name.
2241 * The public dictionary has precedence on the shadow one.
2242 * @param Name name of the searched DictEntry
2243 * @return Corresponding DictEntry when it exists, NULL otherwise.
2245 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2247 gdcmDictEntry *found = (gdcmDictEntry *)0;
2248 if (!RefPubDict && !RefShaDict)
2250 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2251 "we SHOULD have a default dictionary");
2255 found = RefPubDict->GetDictEntryByName(Name);
2261 found = RefShaDict->GetDictEntryByName(Name);
2269 * \ingroup gdcmParser
2270 * \brief Searches both the public and the shadow dictionary (when they
2271 * exist) for the presence of the DictEntry with given
2272 * group and element. The public dictionary has precedence on the
2274 * @param group group of the searched DictEntry
2275 * @param element element of the searched DictEntry
2276 * @return Corresponding DictEntry when it exists, NULL otherwise.
2278 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2280 gdcmDictEntry *found = (gdcmDictEntry *)0;
2281 if (!RefPubDict && !RefShaDict)
2283 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2284 "we SHOULD have a default dictionary");
2288 found = RefPubDict->GetDictEntryByNumber(group, element);
2294 found = RefShaDict->GetDictEntryByNumber(group, element);
2302 * \ingroup gdcmParser
2303 * \brief Read the next tag but WITHOUT loading it's value
2304 * @return On succes the newly created HeaderEntry, NULL on failure.
2306 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void) {
2308 gdcmHeaderEntry *NewEntry;
2313 // We reached the EOF (or an error occured) therefore
2314 // header parsing has to be considered as finished.
2315 return (gdcmHeaderEntry *)0;
2317 /* Pb : how to propagate the element length (used in SkipHeaderEntry)
2318 // direct call to SkipBytes ?
2320 if (ignoreShadow == 1 && g%2 ==1) //JPR
2321 // if user wants to skip shadow groups
2322 // and current element *is* a shadow element
2323 // we don't create anything
2324 return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2326 NewEntry = NewHeaderEntryByNumber(g, n);
2327 FindHeaderEntryVR(NewEntry);
2328 FindHeaderEntryLength(NewEntry);
2334 NewEntry->SetOffset(ftell(fp));
2339 * \ingroup gdcmParser
2340 * \brief Build a new Element Value from all the low level arguments.
2341 * Check for existence of dictionary entry, and build
2342 * a default one when absent.
2343 * @param Name Name of the underlying DictEntry
2345 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2347 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2349 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2351 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2354 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2355 "failed to allocate gdcmHeaderEntry");
2356 return (gdcmHeaderEntry *)0;
2362 * \ingroup gdcmParser
2363 * \brief Request a new virtual dict entry to the dict set
2364 * @param group group of the underlying DictEntry
2365 * @param elem element of the underlying DictEntry
2366 * @param vr VR of the underlying DictEntry
2367 * @param fourth owner group
2368 * @param name english name
2370 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2375 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2379 * \ingroup gdcmParser
2380 * \brief Build a new Element Value from all the low level arguments.
2381 * Check for existence of dictionary entry, and build
2382 * a default one when absent.
2383 * @param Group group of the underlying DictEntry
2384 * @param Elem element of the underlying DictEntry
2386 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2388 // Find out if the tag we encountered is in the dictionaries:
2389 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2391 DictEntry = NewVirtualDictEntry(Group, Elem);
2393 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2396 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2397 "failed to allocate gdcmHeaderEntry");
2403 // Never used; commented out, waiting for removal.
2405 * \ingroup gdcmParser
2406 * \brief Small utility function that creates a new manually crafted
2407 * (as opposed as read from the file) gdcmHeaderEntry with user
2408 * specified name and adds it to the public tag hash table.
2409 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2410 * @param NewTagName The name to be given to this new tag.
2411 * @param VR The Value Representation to be given to this new tag.
2412 * @return The newly hand crafted Element Value.
2414 //gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2417 // gdcmHeaderEntry *NewEntry = NULL;
2418 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2419 // guint32 FreeElem = 0;
2420 // gdcmDictEntry *DictEntry = NULL;
2422 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2423 // if (FreeElem == UINT32_MAX)
2425 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2426 // "Group 0xffff in Public Dict is full");
2430 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2431 // VR, "GDCM", NewTagName);
2432 // NewEntry = new gdcmHeaderEntry(DictEntry);
2433 // AddHeaderEntry(NewEntry);
2438 * \ingroup gdcmParser
2439 * \brief Generate a free TagKey i.e. a TagKey that is not present
2440 * in the TagHt dictionary.
2441 * @param group The generated tag must belong to this group.
2442 * @return The element of tag with given group which is fee.
2444 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2446 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2448 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2449 if (tagHT.count(key) == 0)
2455 //-----------------------------------------------------------------------------