2 //-----------------------------------------------------------------------------
3 #include "gdcmParser.h"
11 #include <netinet/in.h>
14 #ifdef GDCM_NO_ANSI_STRING_STREAM
16 # define ostringstream ostrstream
22 //-----------------------------------------------------------------------------
23 // Refer to gdcmParser::CheckSwap()
24 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
26 // Refer to gdcmParser::SetMaxSizeLoadElementValue()
27 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
29 //-----------------------------------------------------------------------------
30 // Constructor / Destructor
35 * @param exception_on_error
36 * @param enable_sequences = true to allow the header
37 * to be parsed *inside* the SeQuences,
38 * when they have an actual length
39 *\TODO may be we need one more bool,
40 * to allow skipping the private elements while parsing the header
41 * in order to save space
43 gdcmParser::gdcmParser(const char *InFilename,
44 bool exception_on_error,
45 bool enable_sequences )
47 enableSequences=enable_sequences;
49 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
50 filename = InFilename;
53 if ( !OpenFile(exception_on_error))
59 wasUpdated = 0; // will be set to 1 if user adds an entry
60 printLevel = 1; // 'Heavy' header print by default
66 * @param exception_on_error
68 gdcmParser::gdcmParser(bool exception_on_error)
72 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
75 wasUpdated = 0; // will be set to 1 if user adds an entry
76 printLevel = 1; // 'Heavy' header print by default
81 * \brief Canonical destructor.
83 gdcmParser::~gdcmParser (void)
89 //-----------------------------------------------------------------------------
93 * \brief Prints the Header Entries (Dicom Elements)
94 * both from the H Table and the chained list
97 void gdcmParser::PrintEntry(std::ostream & os)
101 s << "------------ using listEntries ----------------" << std::endl;
102 for (ListTag::iterator i = listEntries.begin();
103 i != listEntries.end();
106 (*i)->SetPrintLevel(printLevel);
113 * \ingroup gdcmParser
114 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
117 void gdcmParser::PrintPubDict(std::ostream & os)
119 RefPubDict->Print(os);
123 * \ingroup gdcmParser
124 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
127 void gdcmParser::PrintShaDict(std::ostream & os)
129 RefShaDict->Print(os);
132 //-----------------------------------------------------------------------------
135 * \ingroup gdcmParser
136 * \brief Get the public dictionary used
138 gdcmDict *gdcmParser::GetPubDict(void)
144 * \ingroup gdcmParser
145 * \brief Get the shadow dictionary used
147 gdcmDict *gdcmParser::GetShaDict(void)
153 * \ingroup gdcmParser
154 * \brief Set the shadow dictionary used
155 * \param dict dictionary to use in shadow
157 bool gdcmParser::SetShaDict(gdcmDict *dict)
164 * \ingroup gdcmParser
165 * \brief Set the shadow dictionary used
166 * \param dictName name of the dictionary to use in shadow
168 bool gdcmParser::SetShaDict(DictKey dictName)
170 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
175 * \ingroup gdcmParser
176 * \brief This predicate, based on hopefully reasonable heuristics,
177 * decides whether or not the current gdcmParser was properly parsed
178 * and contains the mandatory information for being considered as
179 * a well formed and usable Dicom/Acr File.
180 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
183 bool gdcmParser::IsReadable(void)
185 std::string res = GetEntryByNumber(0x0028, 0x0005);
186 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
188 return false; // Image Dimensions
191 if ( !GetHeaderEntryByNumber(0x0028, 0x0100) )
192 return false; // "Bits Allocated"
193 if ( !GetHeaderEntryByNumber(0x0028, 0x0101) )
194 return false; // "Bits Stored"
195 if ( !GetHeaderEntryByNumber(0x0028, 0x0102) )
196 return false; // "High Bit"
197 if ( !GetHeaderEntryByNumber(0x0028, 0x0103) )
198 return false; // "Pixel Representation"
203 * \ingroup gdcmParser
204 * \brief Determines if the Transfer Syntax was already encountered
205 * and if it corresponds to a ImplicitVRLittleEndian one.
207 * @return True when ImplicitVRLittleEndian found. False in all other cases.
209 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void)
211 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
214 LoadHeaderEntrySafe(Element);
216 std::string Transfer = Element->GetValue();
217 if ( Transfer == "1.2.840.10008.1.2" )
223 * \ingroup gdcmParser
224 * \brief Determines if the Transfer Syntax was already encountered
225 * and if it corresponds to a ExplicitVRLittleEndian one.
227 * @return True when ExplicitVRLittleEndian found. False in all other cases.
229 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void)
231 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
234 LoadHeaderEntrySafe(Element);
236 std::string Transfer = Element->GetValue();
237 if ( Transfer == "1.2.840.10008.1.2.1" )
243 * \ingroup gdcmParser
244 * \brief Determines if the Transfer Syntax was already encountered
245 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
247 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
249 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
251 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
254 LoadHeaderEntrySafe(Element);
256 std::string Transfer = Element->GetValue();
257 if ( Transfer == "1.2.840.10008.1.2.1.99" )
263 * \ingroup gdcmParser
264 * \brief Determines if the Transfer Syntax was already encountered
265 * and if it corresponds to a Explicit VR Big Endian one.
267 * @return True when big endian found. False in all other cases.
269 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void)
271 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
274 LoadHeaderEntrySafe(Element);
276 std::string Transfer = Element->GetValue();
277 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
283 * \ingroup gdcmParser
284 * \brief returns the File Type
285 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
288 FileType gdcmParser::GetFileType(void) {
293 * \ingroup gdcmParser
294 * \brief opens the file
295 * @param exception_on_error
298 FILE *gdcmParser::OpenFile(bool exception_on_error)
301 fp=fopen(filename.c_str(),"rb");
302 if(exception_on_error)
305 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
311 fread(&zero, (size_t)2, (size_t)1, fp);
313 //ACR -- or DICOM with no Preamble --
314 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
318 fseek(fp, 126L, SEEK_CUR);
320 fread(dicm, (size_t)4, (size_t)1, fp);
321 if( memcmp(dicm, "DICM", 4) == 0 )
325 dbg.Verbose(0, "gdcmParser::gdcmParser not DICOM/ACR", filename.c_str());
328 dbg.Verbose(0, "gdcmParser::gdcmParser cannot open file", filename.c_str());
334 * \ingroup gdcmParser
335 * \brief closes the file
336 * @return TRUE if the close was successfull
338 bool gdcmParser::CloseFile(void)
340 int closed = fclose(fp);
348 * \ingroup gdcmParser
350 * @param fp file pointer on an already open file
351 * @param type type of the File to be written
352 * (ACR-NEMA, ExplicitVR, ImplicitVR)
353 * @return always "True" ?!
355 bool gdcmParser::Write(FILE *fp, FileType type)
358 // TODO The stuff has been rewritten using the chained list instead
360 // so we could remove the GroupHT from the gdcmParser
364 // TODO : move the following lines (and a lot of others, to be written)
365 // to a future function CheckAndCorrectHeader
368 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
369 // (FileType est un champ de gdcmParser ...)
370 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
372 // a moins de se livrer a un tres complique ajout des champs manquants.
373 // faire un CheckAndCorrectHeader (?)
376 if (type == ImplicitVR)
378 std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
379 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
381 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
382 // values with a VR of UI shall be padded with a single trailing null
383 // Dans le cas suivant on doit pader manuellement avec un 0
385 SetEntryLengthByNumber(18, 0x0002, 0x0010);
388 if (type == ExplicitVR)
390 std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
391 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
393 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
394 // values with a VR of UI shall be padded with a single trailing null
395 // Dans le cas suivant on doit pader manuellement avec un 0
397 SetEntryLengthByNumber(20, 0x0002, 0x0010);
401 if ( (type == ImplicitVR) || (type == ExplicitVR) )
402 UpdateGroupLength(false,type);
404 UpdateGroupLength(true,ACR);
406 WriteEntries(type, fp);
411 * \ingroup gdcmParser
412 * \brief Modifies the value of a given Header Entry (Dicom Element)
413 * if it exists; Creates it with the given value if it doesn't
414 * @param Value passed as a std::string
419 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
420 guint16 Group, guint16 Elem )
422 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
423 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
428 SetEntryByNumber(Value, Group, Elem);
433 * \ingroup gdcmParser
434 * \brief Modifies the value of a given Header Entry (Dicom Element)
435 * if it exists; Creates it with the given value if it doesn't
436 * @param Value passed as a char*
442 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem )
444 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
449 AddHeaderEntry(nvHeaderEntry);
451 std::string v = Value;
452 SetEntryByNumber(v, Group, Elem);
457 * \ingroup gdcmParser
458 * \brief Set a new value if the invoked element exists
459 * Seems to be useless !!!
465 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
467 std::string v = Value;
468 SetEntryByNumber(v, Group, Elem);
472 //-----------------------------------------------------------------------------
475 * \ingroup gdcmParser
476 * \brief Checks if a given Dicom Element exists
477 * \ within the H table
478 * @param group Group number of the searched Dicom Element
479 * @param element Element number of the searched Dicom Element
480 * @return number of occurences
482 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element )
484 std::string key = gdcmDictEntry::TranslateToKey(group, element );
485 return (tagHT.count(key));
489 * \ingroup gdcmParser
490 * \brief Searches within Header Entries (Dicom Elements) parsed with
491 * the public and private dictionaries
492 * for the element value of a given tag.
493 * \warning Don't use any longer : use GetPubEntryByName
494 * @param tagName name of the searched element.
495 * @return Corresponding element value when it exists,
496 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
498 std::string gdcmParser::GetEntryByName(std::string tagName)
500 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
501 if( dictEntry == NULL)
504 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
508 * \ingroup gdcmParser
509 * \brief Searches within Header Entries (Dicom Elements) parsed with
510 * the public and private dictionaries
511 * for the element value representation of a given tag.
513 * Obtaining the VR (Value Representation) might be needed by caller
514 * to convert the string typed content to caller's native type
515 * (think of C++ vs Python). The VR is actually of a higher level
516 * of semantics than just the native C++ type.
517 * @param tagName name of the searched element.
518 * @return Corresponding element value representation when it exists,
519 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
521 std::string gdcmParser::GetEntryVRByName(std::string tagName)
523 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
524 if( dictEntry == NULL)
527 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
528 dictEntry->GetElement());
529 return elem->GetVR();
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.
537 * @param group Group of the searched tag.
538 * @param element Element of the searched tag.
539 * @return Corresponding element value representation when it exists,
540 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
542 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element)
544 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
545 if ( ! tagHT.count(key))
547 return tagHT.find(key)->second->GetValue();
551 * \ingroup gdcmParser
552 * \brief Searches within Header Entries (Dicom Elements) parsed with
553 * the public and private dictionaries
554 * for the element value representation of a given tag..
556 * Obtaining the VR (Value Representation) might be needed by caller
557 * to convert the string typed content to caller's native type
558 * (think of C++ vs Python). The VR is actually of a higher level
559 * of semantics than just the native C++ type.
560 * @param group Group of the searched tag.
561 * @param element Element of the searched tag.
562 * @return Corresponding element value representation when it exists,
563 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
565 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element)
567 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
570 return elem->GetVR();
574 * \ingroup gdcmParser
575 * \brief Sets the value (string) of the Header Entry (Dicom Element)
576 * @param content string value of the Dicom Element
577 * @param tagName name of the searched Dicom Element.
578 * @return true when found
580 bool gdcmParser::SetEntryByName(std::string content,std::string tagName)
582 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
583 if( dictEntry == NULL)
586 return(SetEntryByNumber(content,dictEntry->GetGroup(),
587 dictEntry->GetElement()));
591 * \ingroup gdcmParser
592 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
593 * through it's (group, element) and modifies it's content with
595 * \warning Don't use any longer : use SetPubEntryByNumber
596 * @param content new value to substitute with
597 * @param group group of the Dicom Element to modify
598 * @param element element of the Dicom Element to modify
600 bool gdcmParser::SetEntryByNumber(std::string content,
604 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
605 if ( ! tagHT.count(key))
607 int l = content.length();
608 if(l%2) // Odd length are padded with a space (020H).
611 content = content + '\0';
614 //tagHT[key]->SetValue(content);
617 TagHeaderEntryHT::iterator p2;
618 // DO NOT remove the following lines : they explain the stuff
619 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
620 //p2=p.first; // iterator on the first synonym
621 //a=p2->second; // H Table target column (2-nd col)
624 a = ((tagHT.equal_range(key)).first)->second;
626 a-> SetValue(content);
628 //std::string vr = tagHT[key]->GetVR();
629 std::string vr = a->GetVR();
632 if( (vr == "US") || (vr == "SS") )
634 else if( (vr == "UL") || (vr == "SL") )
639 //tagHT[key]->SetLength(lgr);
645 * \ingroup gdcmParser
646 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
647 * in the PubHeaderEntrySet of this instance
648 * through it's (group, element) and modifies it's length with
650 * \warning Use with extreme caution.
651 * @param length new length to substitute with
652 * @param group group of the entry to modify
653 * @param element element of the Entry to modify
654 * @return 1 on success, 0 otherwise.
657 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
658 guint16 group, guint16 element)
660 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
661 if ( ! tagHT.count(key))
663 if (length%2) length++; // length must be even
664 //tagHT[key]->SetLength(length);
665 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
671 * \ingroup gdcmParser
672 * \brief Gets (from Header) the offset of a 'non string' element value
673 * \ (LoadElementValues has already be executed)
676 * @return File Offset of the Element Value
678 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
680 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
683 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
684 "failed to Locate gdcmHeaderEntry");
687 return Entry->GetOffset();
691 * \ingroup gdcmParser
692 * \brief Gets (from Header) a 'non string' element value
693 * \ (LoadElementValues has already be executed)
696 * @return Pointer to the 'non string' area
698 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
700 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
703 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
704 "failed to Locate gdcmHeaderEntry");
707 return Entry->GetVoidArea();
711 * \ingroup gdcmParser
712 * \brief Loads (from disk) the element content
713 * when a string is not suitable
715 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
717 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
720 size_t o =(size_t)Element->GetOffset();
721 fseek(fp, o, SEEK_SET);
722 int l=Element->GetLength();
723 void * a = malloc(l);
727 SetEntryVoidAreaByNumber(a, Group, Elem);
728 // TODO check the result
729 size_t l2 = fread(a, 1, l ,fp);
739 * \ingroup gdcmParser
740 * \brief Sets a 'non string' value to a given Dicom Element
742 * @param group Group number of the searched Dicom Element
743 * @param element Element number of the searched Dicom Element
746 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,guint16 group, guint16 element)
748 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
749 if ( ! tagHT.count(key))
751 //tagHT[key]->SetVoidArea(area);
752 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
757 * \ingroup gdcmParser
758 * \brief Update the entries with the shadow dictionary. Only odd entries are
761 void gdcmParser::UpdateShaEntries(void)
763 gdcmDictEntry *entry;
766 for(ListTag::iterator it=listEntries.begin();
767 it!=listEntries.end();
770 // Odd group => from public dictionary
771 if((*it)->GetGroup()%2==0)
774 // Peer group => search the corresponding dict entry
776 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
780 if((*it)->IsImplicitVR())
785 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
788 // Set the new entry and the new value
789 (*it)->SetDictEntry(entry);
790 CheckHeaderEntryVR(*it,vr);
792 (*it)->SetValue(GetHeaderEntryValue(*it));
796 // Remove precedent value transformation
797 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
803 * \ingroup gdcmParser
804 * \brief Searches within the Header Entries for a Dicom Element of
806 * @param tagName name of the searched Dicom Element.
807 * @return Corresponding Dicom Element when it exists, and NULL
810 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName)
812 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
813 if( dictEntry == NULL)
816 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
820 * \ingroup gdcmParser
821 * \brief retrieves a Dicom Element (the first one) using (group, element)
822 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
823 * if you think it's NOT UNIQUE, check the count number
824 * and use iterators to retrieve ALL the Dicoms Elements within
825 * a given couple (group, element)
826 * @param group Group number of the searched Dicom Element
827 * @param element Element number of the searched Dicom Element
830 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
832 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
833 if ( ! tagHT.count(key))
835 return tagHT.find(key)->second;
839 * \ingroup gdcmParser
840 * \brief Loads the element while preserving the current
841 * underlying file position indicator as opposed to
842 * to LoadHeaderEntry that modifies it.
843 * @param entry Header Entry whose value shall be loaded.
846 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry)
848 long PositionOnEntry = ftell(fp);
849 LoadHeaderEntry(entry);
850 fseek(fp, PositionOnEntry, SEEK_SET);
854 * \ingroup gdcmParser
855 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
856 * \warning : to be re-written using the chained list instead of the H table.
857 * \warning : DO NOT use (doesn't work any longer because of the multimap)
858 * \todo : to be re-written using the chained list instead of the H table
859 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
860 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
862 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type)
867 gdcmHeaderEntry *elem;
869 std::string str_trash;
872 GroupHT groupHt; // to hold the length of each group
875 // typedef std::map<GroupKey, int> GroupHT;
877 gdcmHeaderEntry *elemZ;
879 // for each Tag in the DCM Header
881 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
886 gr = elem->GetGroup();
887 el = elem->GetElement();
890 sprintf(trash, "%04x", gr);
891 key = trash; // generate 'group tag'
893 // if the caller decided not to take SEQUENCEs into account
894 // e.g : he wants to write an ACR-NEMA File
896 if (SkipSequence && vr == "SQ")
899 // Still unsolved problem :
900 // we cannot find the 'Sequence Delimitation Item'
901 // since it's at the end of the Hash Table
904 // pas SEQUENCE en ACR-NEMA
906 // --> la descente a l'interieur' des SQ
907 // devrait etre faite avec une liste chainee, pas avec une HTable...
909 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
911 if (el == 0x0000) // the first elem is 0x0000
913 groupHt[key] = 0; // initialize group length
917 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
920 else // any elem but the first
922 if (type == ExplicitVR)
924 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
926 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
929 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
933 unsigned short int gr_bid;
935 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
939 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
940 // warning: unsigned int format, different type arg
941 sscanf(g->first.c_str(),"%x",&gr_bid);
942 tk = g->first + "|0000"; // generate the element full tag
944 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
946 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
947 elemZ = new gdcmHeaderEntry(tagZ);
949 AddHeaderEntry(elemZ); // create it
953 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
955 sprintf(trash ,"%d",g->second);
957 elemZ->SetValue(str_trash);
962 * \ingroup gdcmParser
963 * \brief writes on disc according to the requested format
964 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
965 * \ warning does NOT add the missing elements in the header :
966 * \ it's up to the user doing it !
967 * \ (function CheckHeaderCoherence to be written)
968 * @param type type of the File to be written
969 * (ACR-NEMA, ExplicitVR, ImplicitVR)
970 * @param _fp already open file pointer
972 void gdcmParser::WriteEntries(FileType type, FILE * _fp)
981 std::vector<std::string> tokens;
983 // uses now listEntries to iterate, not TagHt!
985 // pb : gdcmParser.Add does NOT update listEntries
986 // TODO : find a trick (in STL?) to do it, at low cost !
990 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
992 for (ListTag::iterator tag2=listEntries.begin();
993 tag2 != listEntries.end();
996 gr = (*tag2)->GetGroup();
997 el = (*tag2)->GetElement();
998 lgr = (*tag2)->GetLength();
999 val = (*tag2)->GetValue().c_str();
1000 vr = (*tag2)->GetVR();
1004 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
1005 if (gr %2) continue; // ignore shadow groups
1006 if (vr == "SQ" ) continue; // ignore Sequences
1007 // TODO : find a trick to *skip* the SeQuences !
1008 // Not only ignore the SQ element
1009 if (gr == 0xfffe ) continue; // ignore delimiters
1012 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1013 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1015 if ( (type == ExplicitVR) && (gr <= 0x0002) )
1018 guint16 z=0, shortLgr;
1019 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1021 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1023 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1024 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1030 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1035 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1038 if (vr == "US" || vr == "SS")
1040 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1041 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1042 for (unsigned int i=0; i<tokens.size();i++)
1044 val_uint16 = atoi(tokens[i].c_str());
1046 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1051 if (vr == "UL" || vr == "SL")
1053 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1054 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1055 for (unsigned int i=0; i<tokens.size();i++)
1057 val_uint32 = atoi(tokens[i].c_str());
1059 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1064 // Pixels are never loaded in the element !
1065 if ((gr == 0x7fe0) && (el == 0x0010) )
1068 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1073 * \ingroup gdcmParser
1074 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1076 * @return The properly swaped 32 bits integer.
1078 guint32 gdcmParser::SwapLong(guint32 a)
1085 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1086 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1090 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1094 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1097 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1104 * \ingroup gdcmParser
1105 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1107 * @return The properly unswaped 32 bits integer.
1109 guint32 gdcmParser::UnswapLong(guint32 a)
1111 return (SwapLong(a));
1115 * \ingroup gdcmParser
1116 * \brief Swaps the bytes so they agree with the processor order
1117 * @return The properly swaped 16 bits integer.
1119 guint16 gdcmParser::SwapShort(guint16 a)
1121 if ( (sw==4321) || (sw==2143) )
1122 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1127 * \ingroup gdcmParser
1128 * \brief Unswaps the bytes so they agree with the processor order
1129 * @return The properly unswaped 16 bits integer.
1131 guint16 gdcmParser::UnswapShort(guint16 a)
1133 return (SwapShort(a));
1136 //-----------------------------------------------------------------------------
1139 * \ingroup gdcmParser
1140 * \brief Parses the header of the file but WITHOUT loading element values.
1142 void gdcmParser::Parse(bool exception_on_error) throw(gdcmFormatError)
1144 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1148 while ( (newHeaderEntry = ReadNextHeaderEntry()) )
1150 SkipHeaderEntry(newHeaderEntry);
1151 AddHeaderEntry(newHeaderEntry);
1156 * \ingroup gdcmParser
1157 * \brief Loads the element values of all the Header Entries pointed in the
1158 * public Chained List.
1160 void gdcmParser::LoadHeaderEntries(void)
1163 for (ListTag::iterator i = GetListEntry().begin();
1164 i != GetListEntry().end();
1167 LoadHeaderEntry(*i);
1172 // Load 'non string' values
1173 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1174 if( PhotometricInterpretation == "PALETTE COLOR " )
1176 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1177 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1178 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1179 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1181 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1182 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1183 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1186 // --------------------------------------------------------------
1187 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1189 // if recognition code tells us we deal with a LibIDO image
1190 // we switch lineNumber and columnNumber
1192 std::string RecCode;
1193 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1194 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1195 RecCode == "CANRME_AILIBOD1_1." )
1197 filetype = ACR_LIBIDO;
1198 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1199 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1200 SetEntryByNumber(columns, 0x0028, 0x0010);
1201 SetEntryByNumber(rows , 0x0028, 0x0011);
1203 // ----------------- End of Special Patch ----------------
1207 * \ingroup gdcmParser
1208 * \brief Loads the element content if it's length is not bigger
1209 * than the value specified with
1210 * gdcmParser::SetMaxSizeLoadEntry()
1211 * @param Entry Header Entry (Dicom Element) to be dealt with
1213 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry)
1216 guint16 group = Entry->GetGroup();
1217 std::string vr= Entry->GetVR();
1218 guint32 length = Entry->GetLength();
1219 bool SkipLoad = false;
1221 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1223 // the test was commented out to 'go inside' the SeQuences
1224 // we don't any longer skip them !
1226 // if( vr == "SQ" ) // (DO NOT remove this comment)
1229 // A SeQuence "contains" a set of Elements.
1230 // (fffe e000) tells us an Element is beginning
1231 // (fffe e00d) tells us an Element just ended
1232 // (fffe e0dd) tells us the current SeQuence just ended
1233 if( group == 0xfffe )
1238 Entry->SetLength(0);
1239 Entry->SetValue("gdcm::Skipped");
1243 // When the length is zero things are easy:
1246 Entry->SetValue("");
1250 // The elements whose length is bigger than the specified upper bound
1251 // are not loaded. Instead we leave a short notice of the offset of
1252 // the element content and it's length.
1253 if (length > MaxSizeLoadEntry)
1255 std::ostringstream s;
1256 s << "gdcm::NotLoaded.";
1257 s << " Address:" << (long)Entry->GetOffset();
1258 s << " Length:" << Entry->GetLength();
1259 s << " x(" << std::hex << Entry->GetLength() << ")";
1260 Entry->SetValue(s.str());
1264 // When integer(s) are expected, read and convert the following
1265 // n *(two or four bytes)
1266 // properly i.e. as integers as opposed to a strings.
1267 // Elements with Value Multiplicity > 1
1268 // contain a set of integers (not a single one)
1270 // Any compacter code suggested (?)
1271 if ( IsHeaderEntryAnInteger(Entry) )
1274 std::ostringstream s;
1276 if (vr == "US" || vr == "SS")
1279 NewInt = ReadInt16();
1283 for (int i=1; i < nbInt; i++)
1286 NewInt = ReadInt16();
1292 else if (vr == "UL" || vr == "SL")
1295 NewInt = ReadInt32();
1299 for (int i=1; i < nbInt; i++)
1302 NewInt = ReadInt32();
1307 #ifdef GDCM_NO_ANSI_STRING_STREAM
1308 s << std::ends; // to avoid oddities on Solaris
1309 #endif //GDCM_NO_ANSI_STRING_STREAM
1310 Entry->SetValue(s.str());
1314 // We need an additional byte for storing \0 that is not on disk
1315 std::string NewValue(length,0);
1316 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1317 if ( item_read != 1 )
1319 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1320 Entry->SetValue("gdcm::UnRead");
1323 Entry->SetValue(NewValue);
1327 * \ingroup gdcmParser
1328 * \brief add a new Dicom Element pointer to
1329 * the H Table and to the chained List
1330 * \warning push_bash in listEntries ONLY during ParseHeader
1331 * \todo something to allow further Elements addition,
1332 * \ when position to be taken care of
1333 * @param newHeaderEntry
1335 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry)
1337 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1338 listEntries.push_back(newHeaderEntry);
1343 * \ingroup gdcmParser
1345 * @param Entry Header Entry whose length of the value shall be loaded.
1349 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry)
1351 guint16 element = Entry->GetElement();
1352 guint16 group = Entry->GetGroup();
1353 std::string vr = Entry->GetVR();
1355 if( (element == 0x0010) && (group == 0x7fe0) )
1358 dbg.Verbose(2, "gdcmParser::FindLength: ",
1359 "we reached 7fe0 0010");
1362 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1364 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1366 // The following reserved two bytes (see PS 3.5-2001, section
1367 // 7.1.2 Data element structure with explicit vr p27) must be
1368 // skipped before proceeding on reading the length on 4 bytes.
1369 fseek(fp, 2L, SEEK_CUR);
1370 guint32 length32 = ReadInt32();
1372 if ( (vr == "OB") && (length32 == 0xffffffff) )
1374 Entry->SetLength(FindHeaderEntryLengthOB());
1377 FixHeaderEntryFoundLength(Entry, length32);
1381 // Length is encoded on 2 bytes.
1382 length16 = ReadInt16();
1384 // We can tell the current file is encoded in big endian (like
1385 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1386 // and it's value is the one of the encoding of a big endian file.
1387 // In order to deal with such big endian encoded files, we have
1388 // (at least) two strategies:
1389 // * when we load the "Transfer Syntax" tag with value of big endian
1390 // encoding, we raise the proper flags. Then we wait for the end
1391 // of the META group (0x0002) among which is "Transfer Syntax",
1392 // before switching the swap code to big endian. We have to postpone
1393 // the switching of the swap code since the META group is fully encoded
1394 // in little endian, and big endian coding only starts at the next
1395 // group. The corresponding code can be hard to analyse and adds
1396 // many additional unnecessary tests for regular tags.
1397 // * the second strategy consists in waiting for trouble, that shall
1398 // appear when we find the first group with big endian encoding. This
1399 // is easy to detect since the length of a "Group Length" tag (the
1400 // ones with zero as element number) has to be of 4 (0x0004). When we
1401 // encounter 1024 (0x0400) chances are the encoding changed and we
1402 // found a group with big endian encoding.
1403 // We shall use this second strategy. In order to make sure that we
1404 // can interpret the presence of an apparently big endian encoded
1405 // length of a "Group Length" without committing a big mistake, we
1406 // add an additional check: we look in the already parsed elements
1407 // for the presence of a "Transfer Syntax" whose value has to be "big
1408 // endian encoding". When this is the case, chances are we have got our
1409 // hands on a big endian encoded file: we switch the swap code to
1410 // big endian and proceed...
1411 if ( (element == 0x0000) && (length16 == 0x0400) )
1413 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1415 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1420 SwitchSwapToBigEndian();
1421 // Restore the unproperly loaded values i.e. the group, the element
1422 // and the dictionary entry depending on them.
1423 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1424 guint16 CorrectElem = SwapShort(Entry->GetElement());
1425 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1429 // This correct tag is not in the dictionary. Create a new one.
1430 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1432 // FIXME this can create a memory leaks on the old entry that be
1433 // left unreferenced.
1434 Entry->SetDictEntry(NewTag);
1437 // Heuristic: well some files are really ill-formed.
1438 if ( length16 == 0xffff)
1441 //dbg.Verbose(0, "gdcmParser::FindLength",
1442 // "Erroneous element length fixed.");
1443 // Actually, length= 0xffff means that we deal with
1444 // Unknown Sequence Length
1447 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1452 // Either implicit VR or a non DICOM conformal (see not below) explicit
1453 // VR that ommited the VR of (at least) this element. Farts happen.
1454 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1455 // on Data elements "Implicit and Explicit VR Data Elements shall
1456 // not coexist in a Data Set and Data Sets nested within it".]
1457 // Length is on 4 bytes.
1458 FixHeaderEntryFoundLength(Entry, ReadInt32());
1464 * \ingroup gdcmParser
1465 * \brief Find the Value Representation of the current Dicom Element.
1468 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1470 if (filetype != ExplicitVR)
1476 long PositionOnEntry = ftell(fp);
1477 // Warning: we believe this is explicit VR (Value Representation) because
1478 // we used a heuristic that found "UL" in the first tag. Alas this
1479 // doesn't guarantee that all the tags will be in explicit VR. In some
1480 // cases (see e-film filtered files) one finds implicit VR tags mixed
1481 // within an explicit VR file. Hence we make sure the present tag
1482 // is in explicit VR and try to fix things if it happens not to be
1485 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1487 if(!CheckHeaderEntryVR(Entry,VR))
1489 fseek(fp, PositionOnEntry, SEEK_SET);
1490 // When this element is known in the dictionary we shall use, e.g. for
1491 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1492 // dictionary entry. Still we have to flag the element as implicit since
1493 // we know now our assumption on expliciteness is not furfilled.
1495 if ( Entry->IsVRUnknown() )
1496 Entry->SetVR("Implicit");
1497 Entry->SetImplicitVR();
1502 * \ingroup gdcmParser
1503 * \brief Check the correspondance between the VR of the header entry
1504 * and the taken VR. If they are different, the header entry is
1505 * updated with the new VR.
1508 * @return false if the VR is incorrect of if the VR isn't referenced
1509 * otherwise, it returns true
1511 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1513 char msg[100]; // for sprintf
1514 bool RealExplicit = true;
1516 // Assume we are reading a falsely explicit VR file i.e. we reached
1517 // a tag where we expect reading a VR but are in fact we read the
1518 // first to bytes of the length. Then we will interogate (through find)
1519 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1520 // both GCC and VC++ implementations of the STL map. Hence when the
1521 // expected VR read happens to be non-ascii characters we consider
1522 // we hit falsely explicit VR tag.
1524 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1525 RealExplicit = false;
1527 // CLEANME searching the dicom_vr at each occurence is expensive.
1528 // PostPone this test in an optional integrity check at the end
1529 // of parsing or only in debug mode.
1530 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1531 RealExplicit= false;
1533 if ( !RealExplicit )
1535 // We thought this was explicit VR, but we end up with an
1536 // implicit VR tag. Let's backtrack.
1537 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1538 Entry->GetGroup(),Entry->GetElement());
1539 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1544 if ( Entry->IsVRUnknown() )
1546 // When not a dictionary entry, we can safely overwrite the VR.
1549 else if ( Entry->GetVR() != vr )
1551 // The VR present in the file and the dictionary disagree. We assume
1552 // the file writer knew best and use the VR of the file. Since it would
1553 // be unwise to overwrite the VR of a dictionary (since it would
1554 // compromise it's next user), we need to clone the actual DictEntry
1555 // and change the VR for the read one.
1556 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1557 Entry->GetGroup(),Entry->GetElement(),
1558 vr,"FIXME",Entry->GetName());
1559 Entry->SetDictEntry(NewEntry);
1565 * \ingroup gdcmParser
1566 * \brief Get the transformed value of the header entry. The VR value
1567 * is used to define the transformation to operate on the value
1568 * \warning NOT end user intended method !
1570 * @return Transformed entry value
1572 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1574 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1576 std::string val=Entry->GetValue();
1577 std::string vr=Entry->GetVR();
1578 guint32 length = Entry->GetLength();
1579 std::ostringstream s;
1582 if (vr == "US" || vr == "SS")
1587 for (int i=0; i < nbInt; i++)
1591 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1592 NewInt16 = SwapShort(NewInt16);
1597 else if (vr == "UL" || vr == "SL")
1602 for (int i=0; i < nbInt; i++)
1606 NewInt32=(val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1607 NewInt32=SwapLong(NewInt32);
1612 #ifdef GDCM_NO_ANSI_STRING_STREAM
1613 s << std::ends; // to avoid oddities on Solaris
1614 #endif //GDCM_NO_ANSI_STRING_STREAM
1618 return(Entry->GetValue());
1622 * \ingroup gdcmParser
1623 * \brief Get the reverse transformed value of the header entry. The VR
1624 * value is used to define the reverse transformation to operate on
1626 * \warning NOT end user intended method !
1628 * @return Reverse transformed entry value
1630 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1632 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1634 std::string vr=Entry->GetVR();
1635 std::ostringstream s;
1636 std::vector<std::string> tokens;
1639 if (vr == "US" || vr == "SS")
1643 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1644 Tokenize (Entry->GetValue(), tokens, "\\");
1645 for (unsigned int i=0; i<tokens.size();i++)
1647 NewInt16 = atoi(tokens[i].c_str());
1648 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1652 if (vr == "UL" || vr == "SL")
1656 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1657 Tokenize (Entry->GetValue(), tokens, "\\");
1658 for (unsigned int i=0; i<tokens.size();i++)
1660 NewInt32 = atoi(tokens[i].c_str());
1661 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1662 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1667 #ifdef GDCM_NO_ANSI_STRING_STREAM
1668 s << std::ends; // to avoid oddities on Solaris
1669 #endif //GDCM_NO_ANSI_STRING_STREAM
1673 return(Entry->GetValue());
1677 * \ingroup gdcmParser
1678 * \brief Skip a given Header Entry
1679 * \warning NOT end user intended method !
1682 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1684 SkipBytes(entry->GetLength());
1688 * \ingroup gdcmParser
1689 * \brief When the length of an element value is obviously wrong (because
1690 * the parser went Jabberwocky) one can hope improving things by
1691 * applying this heuristic.
1693 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1695 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1697 if ( FoundLength == 0xffffffff)
1702 // Sorry for the patch!
1703 // XMedCom did the trick to read some nasty GE images ...
1704 else if (FoundLength == 13)
1706 // The following 'if' will be removed when there is no more
1707 // images on Creatis HDs with a 13 length for Manufacturer...
1708 if ( (Entry->GetGroup() != 0x0008) ||
1709 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ) {
1710 // end of remove area
1712 Entry->SetReadLength(10); // a bug is to be fixed
1716 // to fix some garbage 'Leonardo' Siemens images
1717 // May be commented out to avoid overhead
1718 else if ( (Entry->GetGroup() == 0x0009) &&
1719 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) )
1722 Entry->SetReadLength(4); // a bug is to be fixed
1726 // to try to 'go inside' SeQuences (with length), and not to skip them
1727 else if ( Entry->GetVR() == "SQ")
1729 if (enableSequences) // only if the user does want to !
1733 // a SeQuence Element is beginning
1734 // Let's forget it's length
1735 // (we want to 'go inside')
1737 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1738 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1739 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1740 // if we don't, we lost 28800 characters from the Header :-(
1742 else if(Entry->GetGroup() == 0xfffe)
1744 // sometimes, length seems to be wrong
1745 FoundLength =0; // some more clever checking to be done !
1747 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1748 // causes troubles :-(
1751 Entry->SetUsableLength(FoundLength);
1755 * \ingroup gdcmParser
1756 * \brief Apply some heuristics to predict wether the considered
1757 * element value contains/represents an integer or not.
1758 * @param Entry The element value on which to apply the predicate.
1759 * @return The result of the heuristical predicate.
1761 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry)
1763 guint16 element = Entry->GetElement();
1764 guint16 group = Entry->GetGroup();
1765 std::string vr = Entry->GetVR();
1766 guint32 length = Entry->GetLength();
1768 // When we have some semantics on the element we just read, and if we
1769 // a priori know we are dealing with an integer, then we shall be
1770 // able to swap it's element value properly.
1771 if ( element == 0 ) // This is the group length of the group
1777 std::ostringstream s;
1778 s << "Erroneous Group Length element length on :" \
1779 << std::hex << group << " , " << element;
1780 dbg.Error("gdcmParser::IsAnInteger",
1784 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1791 * \ingroup gdcmParser
1796 guint32 gdcmParser::FindHeaderEntryLengthOB(void)
1798 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1801 long PositionOnEntry = ftell(fp);
1802 bool FoundSequenceDelimiter = false;
1803 guint32 TotalLength = 0;
1806 while ( ! FoundSequenceDelimiter)
1812 TotalLength += 4; // We even have to decount the group and element
1814 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1816 char msg[100]; // for sprintf. Sorry
1817 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1818 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1822 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1823 FoundSequenceDelimiter = true;
1824 else if ( n != 0xe000 )
1826 char msg[100]; // for sprintf. Sorry
1827 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1829 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1833 ItemLength = ReadInt32();
1834 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1835 // the ItemLength with ReadInt32
1836 SkipBytes(ItemLength);
1838 fseek(fp, PositionOnEntry, SEEK_SET);
1843 * \ingroup gdcmParser
1844 * \brief Reads a supposed to be 16 Bits integer
1845 * \ (swaps it depending on processor endianity)
1847 * @return integer acts as a boolean
1849 guint16 gdcmParser::ReadInt16(void)
1853 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1854 if ( item_read != 1 )
1857 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1867 * \ingroup gdcmParser
1868 * \brief Reads a supposed to be 32 Bits integer
1869 * \ (swaps it depending on processor endianity)
1873 guint32 gdcmParser::ReadInt32(void)
1877 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1878 if ( item_read != 1 )
1881 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1891 * \ingroup gdcmParser
1896 void gdcmParser::SkipBytes(guint32 NBytes)
1898 //FIXME don't dump the returned value
1899 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1903 * \ingroup gdcmParser
1906 void gdcmParser::Initialise(void)
1908 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1909 RefShaDict = (gdcmDict*)0;
1913 * \ingroup gdcmParser
1914 * \brief Discover what the swap code is (among little endian, big endian,
1915 * bad little endian, bad big endian).
1918 void gdcmParser::CheckSwap()
1920 // Fourth semantics:
1922 // ---> Warning : This fourth field is NOT part
1923 // of the 'official' Dicom Dictionnary
1924 // and should NOT be used.
1925 // (Not defined for all the groups
1926 // may be removed in a future release)
1929 // META Meta Information
1941 // NMI Nuclear Medicine
1943 // BFS Basic Film Session
1944 // BFB Basic Film Box
1945 // BIB Basic Image Box
1960 // The only guaranted way of finding the swap code is to find a
1961 // group tag since we know it's length has to be of four bytes i.e.
1962 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1963 // occurs when we can't find such group...
1965 guint32 x=4; // x : for ntohs
1966 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1970 char deb[HEADER_LENGTH_TO_READ];
1972 // First, compare HostByteOrder and NetworkByteOrder in order to
1973 // determine if we shall need to swap bytes (i.e. the Endian type).
1978 //cout << net2host << endl;
1980 // The easiest case is the one of a DICOM header, since it possesses a
1981 // file preamble where it suffice to look for the string "DICM".
1982 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1985 if(memcmp(entCur, "DICM", (size_t)4) == 0)
1987 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
1988 // Next, determine the value representation (VR). Let's skip to the
1989 // first element (0002, 0000) and check there if we find "UL"
1990 // - or "OB" if the 1st one is (0002,0001) -,
1991 // in which case we (almost) know it is explicit VR.
1992 // WARNING: if it happens to be implicit VR then what we will read
1993 // is the length of the group. If this ascii representation of this
1994 // length happens to be "UL" then we shall believe it is explicit VR.
1995 // FIXME: in order to fix the above warning, we could read the next
1996 // element value (or a couple of elements values) in order to make
1997 // sure we are not commiting a big mistake.
1998 // We need to skip :
1999 // * the 128 bytes of File Preamble (often padded with zeroes),
2000 // * the 4 bytes of "DICM" string,
2001 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2002 // i.e. a total of 136 bytes.
2005 // Use gdcmParser::dicom_vr to test all the possibilities
2006 // instead of just checking for UL, OB and UI !?
2007 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2008 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2009 (memcmp(entCur, "UI", (size_t)2) == 0) )
2011 filetype = ExplicitVR;
2012 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2013 "explicit Value Representation");
2017 filetype = ImplicitVR;
2018 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2019 "not an explicit Value Representation");
2024 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2025 "HostByteOrder != NetworkByteOrder");
2030 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2031 "HostByteOrder = NetworkByteOrder");
2034 // Position the file position indicator at first tag (i.e.
2035 // after the file preamble and the "DICM" string).
2037 fseek (fp, 132L, SEEK_SET);
2041 // Alas, this is not a DicomV3 file and whatever happens there is no file
2042 // preamble. We can reset the file position indicator to where the data
2043 // is (i.e. the beginning of the file).
2044 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2047 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2048 // By clean we mean that the length of the first tag is written down.
2049 // If this is the case and since the length of the first group HAS to be
2050 // four (bytes), then determining the proper swap code is straightforward.
2053 // We assume the array of char we are considering contains the binary
2054 // representation of a 32 bits integer. Hence the following dirty
2056 s = *((guint32 *)(entCur));
2077 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2078 "ACR/NEMA unfound swap info (time to raise bets)");
2081 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2082 // It is time for despaired wild guesses. So, let's assume this file
2083 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
2084 // not present. Then the only info we have is the net2host one.
2094 * \ingroup gdcmParser
2097 void gdcmParser::SwitchSwapToBigEndian(void)
2099 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2100 "Switching to BigEndian mode.");
2121 * \ingroup gdcmParser
2126 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2130 if ((guint32)NewSize >= (guint32)0xffffffff)
2132 MaxSizeLoadEntry = 0xffffffff;
2135 MaxSizeLoadEntry = NewSize;
2139 * \ingroup gdcmParser
2140 * \brief Searches both the public and the shadow dictionary (when they
2141 * exist) for the presence of the DictEntry with given name.
2142 * The public dictionary has precedence on the shadow one.
2143 * @param Name name of the searched DictEntry
2144 * @return Corresponding DictEntry when it exists, NULL otherwise.
2146 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2148 gdcmDictEntry *found = (gdcmDictEntry *)0;
2149 if (!RefPubDict && !RefShaDict)
2151 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2152 "we SHOULD have a default dictionary");
2156 found = RefPubDict->GetDictEntryByName(Name);
2162 found = RefShaDict->GetDictEntryByName(Name);
2170 * \ingroup gdcmParser
2171 * \brief Searches both the public and the shadow dictionary (when they
2172 * exist) for the presence of the DictEntry with given
2173 * group and element. The public dictionary has precedence on the
2175 * @param group group of the searched DictEntry
2176 * @param element element of the searched DictEntry
2177 * @return Corresponding DictEntry when it exists, NULL otherwise.
2179 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2181 gdcmDictEntry *found = (gdcmDictEntry *)0;
2182 if (!RefPubDict && !RefShaDict)
2184 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2185 "we SHOULD have a default dictionary");
2189 found = RefPubDict->GetDictEntryByNumber(group, element);
2195 found = RefShaDict->GetDictEntryByNumber(group, element);
2203 * \ingroup gdcmParser
2204 * \brief Read the next tag but WITHOUT loading it's value
2205 * @return On succes the newly created HeaderEntry, NULL on failure.
2207 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void)
2210 gdcmHeaderEntry *NewEntry;
2216 // We reached the EOF (or an error occured) and header parsing
2217 // has to be considered as finished.
2218 return (gdcmHeaderEntry *)0;
2220 NewEntry = NewHeaderEntryByNumber(g, n);
2221 FindHeaderEntryVR(NewEntry);
2222 FindHeaderEntryLength(NewEntry);
2229 NewEntry->SetOffset(ftell(fp));
2230 //if ( (g==0x7fe0) && (n==0x0010) )
2235 * \ingroup gdcmParser
2236 * \brief Build a new Element Value from all the low level arguments.
2237 * Check for existence of dictionary entry, and build
2238 * a default one when absent.
2239 * @param Name Name of the underlying DictEntry
2241 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2243 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2245 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2247 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2250 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2251 "failed to allocate gdcmHeaderEntry");
2252 return (gdcmHeaderEntry *)0;
2258 * \ingroup gdcmParser
2259 * \brief Request a new virtual dict entry to the dict set
2260 * @param group group of the underlying DictEntry
2261 * @param elem element of the underlying DictEntry
2262 * @param vr VR of the underlying DictEntry
2263 * @param fourth owner group
2264 * @param name english name
2266 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2271 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2275 * \ingroup gdcmParser
2276 * \brief Build a new Element Value from all the low level arguments.
2277 * Check for existence of dictionary entry, and build
2278 * a default one when absent.
2279 * @param Group group of the underlying DictEntry
2280 * @param Elem element of the underlying DictEntry
2282 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2284 // Find out if the tag we encountered is in the dictionaries:
2285 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2287 DictEntry = NewVirtualDictEntry(Group, Elem);
2289 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2292 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2293 "failed to allocate gdcmHeaderEntry");
2300 * \ingroup gdcmParser
2301 * \brief Small utility function that creates a new manually crafted
2302 * (as opposed as read from the file) gdcmHeaderEntry with user
2303 * specified name and adds it to the public tag hash table.
2304 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2305 * @param NewTagName The name to be given to this new tag.
2306 * @param VR The Value Representation to be given to this new tag.
2307 * @return The newly hand crafted Element Value.
2309 gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2312 gdcmHeaderEntry *NewEntry = NULL;
2313 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2314 guint32 FreeElem = 0;
2315 gdcmDictEntry *DictEntry = NULL;
2317 FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2318 if (FreeElem == UINT32_MAX)
2320 dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2321 "Group 0xffff in Public Dict is full");
2325 DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2326 VR, "GDCM", NewTagName);
2327 NewEntry = new gdcmHeaderEntry(DictEntry);
2328 AddHeaderEntry(NewEntry);
2333 * \ingroup gdcmParser
2334 * \brief Generate a free TagKey i.e. a TagKey that is not present
2335 * in the TagHt dictionary.
2336 * @param group The generated tag must belong to this group.
2337 * @return The element of tag with given group which is fee.
2339 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2341 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2343 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2344 if (tagHT.count(key) == 0)
2350 //-----------------------------------------------------------------------------