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"
27 //-----------------------------------------------------------------------------
28 // Refer to gdcmParser::CheckSwap()
29 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
31 // Refer to gdcmParser::SetMaxSizeLoadElementValue()
32 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
34 //-----------------------------------------------------------------------------
35 // Constructor / Destructor
40 * @param exception_on_error
41 * @param enable_sequences = true to allow the header
42 * to be parsed *inside* the SeQuences,
43 * when they have an actual length
44 *\TODO may be we need one more bool,
45 * to allow skipping the private elements while parsing the header
46 * in order to save space
48 gdcmParser::gdcmParser(const char *InFilename,
49 bool exception_on_error,
50 bool enable_sequences )
52 enableSequences=enable_sequences;
54 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
55 filename = InFilename;
58 if ( !OpenFile(exception_on_error))
64 wasUpdated = 0; // will be set to 1 if user adds an entry
65 printLevel = 1; // 'Medium' print level by default
71 * @param exception_on_error
73 gdcmParser::gdcmParser(bool exception_on_error)
77 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
80 wasUpdated = 0; // will be set to 1 if user adds an entry
81 printLevel = 1; // 'Medium' print level by default
86 * \brief Canonical destructor.
88 gdcmParser::~gdcmParser (void)
94 //-----------------------------------------------------------------------------
98 * \brief Prints the Header Entries (Dicom Elements)
99 * both from the H Table and the chained list
102 void gdcmParser::PrintEntry(std::ostream & os)
104 std::ostringstream s;
106 for (ListTag::iterator i = listEntries.begin();
107 i != listEntries.end();
110 (*i)->SetPrintLevel(printLevel);
117 * \ingroup gdcmParser
118 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
121 void gdcmParser::PrintPubDict(std::ostream & os) {
122 RefPubDict->Print(os);
126 * \ingroup gdcmParser
127 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
130 void gdcmParser::PrintShaDict(std::ostream & os) {
131 RefShaDict->Print(os);
134 //-----------------------------------------------------------------------------
137 * \ingroup gdcmParser
138 * \brief Get the public dictionary used
140 gdcmDict *gdcmParser::GetPubDict(void)
146 * \ingroup gdcmParser
147 * \brief Get the shadow dictionary used
149 gdcmDict *gdcmParser::GetShaDict(void)
155 * \ingroup gdcmParser
156 * \brief Set the shadow dictionary used
157 * \param dict dictionary to use in shadow
159 bool gdcmParser::SetShaDict(gdcmDict *dict)
166 * \ingroup gdcmParser
167 * \brief Set the shadow dictionary used
168 * \param dictName name of the dictionary to use in shadow
170 bool gdcmParser::SetShaDict(DictKey dictName)
172 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
177 * \ingroup gdcmParser
178 * \brief This predicate, based on hopefully reasonable heuristics,
179 * decides whether or not the current gdcmParser was properly parsed
180 * and contains the mandatory information for being considered as
181 * a well formed and usable Dicom/Acr File.
182 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
185 bool gdcmParser::IsReadable(void)
187 if(filetype==Unknown)
190 if(listEntries.size()<=0)
197 * \ingroup gdcmParser
198 * \brief Determines if the Transfer Syntax was already encountered
199 * and if it corresponds to a ImplicitVRLittleEndian one.
201 * @return True when ImplicitVRLittleEndian found. False in all other cases.
203 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void)
205 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
208 LoadHeaderEntrySafe(Element);
210 std::string Transfer = Element->GetValue();
211 if ( Transfer == UI1_2_840_10008_1_2 )
217 * \ingroup gdcmParser
218 * \brief Determines if the Transfer Syntax was already encountered
219 * and if it corresponds to a ExplicitVRLittleEndian one.
221 * @return True when ExplicitVRLittleEndian found. False in all other cases.
223 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void)
225 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
228 LoadHeaderEntrySafe(Element);
230 std::string Transfer = Element->GetValue();
231 if ( Transfer == UI1_2_840_10008_1_2_1 )
237 * \ingroup gdcmParser
238 * \brief Determines if the Transfer Syntax was already encountered
239 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
241 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
243 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(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_1_99 )
257 * \ingroup gdcmParser
258 * \brief Determines if the Transfer Syntax was already encountered
259 * and if it corresponds to a Explicit VR Big Endian one.
261 * @return True when big endian found. False in all other cases.
263 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void)
265 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
268 LoadHeaderEntrySafe(Element);
270 std::string Transfer = Element->GetValue();
271 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
277 * \ingroup gdcmParser
278 * \brief returns the File Type
279 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
282 FileType gdcmParser::GetFileType(void) {
287 * \ingroup gdcmParser
288 * \brief opens the file
289 * @param exception_on_error
292 FILE *gdcmParser::OpenFile(bool exception_on_error)
295 fp=fopen(filename.c_str(),"rb");
296 if(exception_on_error)
299 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
305 fread(&zero, (size_t)2, (size_t)1, fp);
307 //ACR -- or DICOM with no Preamble --
308 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
312 fseek(fp, 126L, SEEK_CUR);
314 fread(dicm, (size_t)4, (size_t)1, fp);
315 if( memcmp(dicm, "DICM", 4) == 0 )
319 dbg.Verbose(0, "gdcmParser::gdcmParser not DICOM/ACR", filename.c_str());
322 dbg.Verbose(0, "gdcmParser::gdcmParser cannot open file", filename.c_str());
328 * \ingroup gdcmParser
329 * \brief closes the file
330 * @return TRUE if the close was successfull
332 bool gdcmParser::CloseFile(void)
334 int closed = fclose(fp);
342 * \ingroup gdcmParser
344 * @param fp file pointer on an already open file
345 * @param type type of the File to be written
346 * (ACR-NEMA, ExplicitVR, ImplicitVR)
347 * @return always "True" ?!
349 bool gdcmParser::Write(FILE *fp, FileType type)
352 // TODO The stuff has been rewritten using the chained list instead
354 // so we could remove the GroupHT from the gdcmParser
358 // TODO : move the following lines (and a lot of others, to be written)
359 // to a future function CheckAndCorrectHeader
362 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
363 // (FileType est un champ de gdcmParser ...)
364 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
366 // a moins de se livrer a un tres complique ajout des champs manquants.
367 // faire un CheckAndCorrectHeader (?)
370 if (type == ImplicitVR)
372 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
373 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
375 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
376 // values with a VR of UI shall be padded with a single trailing null
377 // Dans le cas suivant on doit pader manuellement avec un 0
379 SetEntryLengthByNumber(18, 0x0002, 0x0010);
382 if (type == ExplicitVR)
384 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
385 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
387 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
388 // values with a VR of UI shall be padded with a single trailing null
389 // Dans le cas suivant on doit pader manuellement avec un 0
391 SetEntryLengthByNumber(20, 0x0002, 0x0010);
395 if ( (type == ImplicitVR) || (type == ExplicitVR) )
396 UpdateGroupLength(false,type);
398 UpdateGroupLength(true,ACR);
400 WriteEntries(type, fp);
405 * \ingroup gdcmParser
406 * \brief Modifies the value of a given Header Entry (Dicom Element)
407 * if it exists; Creates it with the given value if it doesn't
408 * @param Value passed as a std::string
413 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
414 guint16 Group, guint16 Elem )
416 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
417 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
422 SetEntryByNumber(Value, Group, Elem);
427 * \ingroup gdcmParser
428 * \brief Modifies the value of a given Header Entry (Dicom Element)
429 * if it exists; Creates it with the given value if it doesn't
430 * @param Value passed as a char*
436 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem )
438 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
443 AddHeaderEntry(nvHeaderEntry);
445 std::string v = Value;
446 SetEntryByNumber(v, Group, Elem);
451 * \ingroup gdcmParser
452 * \brief Set a new value if the invoked element exists
453 * Seems to be useless !!!
459 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
461 std::string v = Value;
462 SetEntryByNumber(v, Group, Elem);
466 //-----------------------------------------------------------------------------
469 * \ingroup gdcmParser
470 * \brief Checks if a given Dicom Element exists
471 * \ within the H table
472 * @param group Group number of the searched Dicom Element
473 * @param element Element number of the searched Dicom Element
474 * @return number of occurences
476 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element )
478 std::string key = gdcmDictEntry::TranslateToKey(group, element );
479 return (tagHT.count(key));
483 * \ingroup gdcmParser
484 * \brief Searches within Header Entries (Dicom Elements) parsed with
485 * the public and private dictionaries
486 * for the element value of a given tag.
487 * \warning Don't use any longer : use GetPubEntryByName
488 * @param tagName name of the searched element.
489 * @return Corresponding element value when it exists,
490 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
492 std::string gdcmParser::GetEntryByName(std::string tagName)
494 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
495 if( dictEntry == NULL)
498 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
502 * \ingroup gdcmParser
503 * \brief Searches within Header Entries (Dicom Elements) parsed with
504 * the public and private dictionaries
505 * for the element value representation of a given tag.
507 * Obtaining the VR (Value Representation) might be needed by caller
508 * to convert the string typed content to caller's native type
509 * (think of C++ vs Python). The VR is actually of a higher level
510 * of semantics than just the native C++ type.
511 * @param tagName name of the searched element.
512 * @return Corresponding element value representation when it exists,
513 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
515 std::string gdcmParser::GetEntryVRByName(std::string tagName)
517 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
518 if( dictEntry == NULL)
521 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
522 dictEntry->GetElement());
523 return elem->GetVR();
527 * \ingroup gdcmParser
528 * \brief Searches within Header Entries (Dicom Elements) parsed with
529 * the public and private dictionaries
530 * for the element value representation of a given tag.
531 * @param group Group of the searched tag.
532 * @param element Element of the searched tag.
533 * @return Corresponding element value representation when it exists,
534 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
536 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element)
538 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
539 if ( ! tagHT.count(key))
541 return tagHT.find(key)->second->GetValue();
545 * \ingroup gdcmParser
546 * \brief Searches within Header Entries (Dicom Elements) parsed with
547 * the public and private dictionaries
548 * for the element value representation of a given tag..
550 * Obtaining the VR (Value Representation) might be needed by caller
551 * to convert the string typed content to caller's native type
552 * (think of C++ vs Python). The VR is actually of a higher level
553 * of semantics than just the native C++ type.
554 * @param group Group of the searched tag.
555 * @param element Element of the searched tag.
556 * @return Corresponding element value representation when it exists,
557 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
559 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element)
561 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
564 return elem->GetVR();
568 * \ingroup gdcmParser
569 * \brief Sets the value (string) of the Header Entry (Dicom Element)
570 * @param content string value of the Dicom Element
571 * @param tagName name of the searched Dicom Element.
572 * @return true when found
574 bool gdcmParser::SetEntryByName(std::string content,std::string tagName)
576 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
577 if( dictEntry == NULL)
580 return(SetEntryByNumber(content,dictEntry->GetGroup(),
581 dictEntry->GetElement()));
585 * \ingroup gdcmParser
586 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
587 * through it's (group, element) and modifies it's content with
589 * \warning Don't use any longer : use SetPubEntryByNumber
590 * @param content new value to substitute with
591 * @param group group of the Dicom Element to modify
592 * @param element element of the Dicom Element to modify
594 bool gdcmParser::SetEntryByNumber(std::string content,
598 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
599 if ( ! tagHT.count(key))
601 int l = content.length();
602 if(l%2) // Odd length are padded with a space (020H).
605 content = content + '\0';
608 //tagHT[key]->SetValue(content);
611 TagHeaderEntryHT::iterator p2;
612 // DO NOT remove the following lines : they explain the stuff
613 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
614 //p2=p.first; // iterator on the first synonym
615 //a=p2->second; // H Table target column (2-nd col)
618 a = ((tagHT.equal_range(key)).first)->second;
620 a-> SetValue(content);
622 //std::string vr = tagHT[key]->GetVR();
623 std::string vr = a->GetVR();
626 if( (vr == "US") || (vr == "SS") )
628 else if( (vr == "UL") || (vr == "SL") )
633 //tagHT[key]->SetLength(lgr);
639 * \ingroup gdcmParser
640 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
641 * in the PubHeaderEntrySet of this instance
642 * through it's (group, element) and modifies it's length with
644 * \warning Use with extreme caution.
645 * @param length new length to substitute with
646 * @param group group of the entry to modify
647 * @param element element of the Entry to modify
648 * @return 1 on success, 0 otherwise.
651 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
652 guint16 group, guint16 element)
654 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
655 if ( ! tagHT.count(key))
657 if (length%2) length++; // length must be even
658 //tagHT[key]->SetLength(length);
659 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
665 * \ingroup gdcmParser
666 * \brief Gets (from Header) the offset of a 'non string' element value
667 * \ (LoadElementValues has already be executed)
670 * @return File Offset of the Element Value
672 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
674 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
677 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
678 "failed to Locate gdcmHeaderEntry");
681 return Entry->GetOffset();
685 * \ingroup gdcmParser
686 * \brief Gets (from Header) a 'non string' element value
687 * \ (LoadElementValues has already be executed)
690 * @return Pointer to the 'non string' area
692 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
694 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
697 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
698 "failed to Locate gdcmHeaderEntry");
701 return Entry->GetVoidArea();
705 * \ingroup gdcmParser
706 * \brief Loads (from disk) the element content
707 * when a string is not suitable
709 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
711 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
714 size_t o =(size_t)Element->GetOffset();
715 fseek(fp, o, SEEK_SET);
716 int l=Element->GetLength();
717 void * a = malloc(l);
721 SetEntryVoidAreaByNumber(a, Group, Elem);
722 // TODO check the result
723 size_t l2 = fread(a, 1, l ,fp);
733 * \ingroup gdcmParser
734 * \brief Sets a 'non string' value to a given Dicom Element
736 * @param group Group number of the searched Dicom Element
737 * @param element Element number of the searched Dicom Element
740 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,guint16 group, guint16 element)
742 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
743 if ( ! tagHT.count(key))
745 //tagHT[key]->SetVoidArea(area);
746 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
751 * \ingroup gdcmParser
752 * \brief Update the entries with the shadow dictionary. Only odd entries are
755 void gdcmParser::UpdateShaEntries(void)
757 gdcmDictEntry *entry;
760 for(ListTag::iterator it=listEntries.begin();
761 it!=listEntries.end();
764 // Odd group => from public dictionary
765 if((*it)->GetGroup()%2==0)
768 // Peer group => search the corresponding dict entry
770 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
774 if((*it)->IsImplicitVR())
779 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
782 // Set the new entry and the new value
783 (*it)->SetDictEntry(entry);
784 CheckHeaderEntryVR(*it,vr);
786 (*it)->SetValue(GetHeaderEntryValue(*it));
790 // Remove precedent value transformation
791 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
797 * \ingroup gdcmParser
798 * \brief Searches within the Header Entries for a Dicom Element of
800 * @param tagName name of the searched Dicom Element.
801 * @return Corresponding Dicom Element when it exists, and NULL
804 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName)
806 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
807 if( dictEntry == NULL)
810 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
814 * \ingroup gdcmParser
815 * \brief retrieves a Dicom Element (the first one) using (group, element)
816 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
817 * if you think it's NOT UNIQUE, check the count number
818 * and use iterators to retrieve ALL the Dicoms Elements within
819 * a given couple (group, element)
820 * @param group Group number of the searched Dicom Element
821 * @param element Element number of the searched Dicom Element
824 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
826 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
827 if ( ! tagHT.count(key))
829 return tagHT.find(key)->second;
833 * \ingroup gdcmParser
834 * \brief Loads the element while preserving the current
835 * underlying file position indicator as opposed to
836 * to LoadHeaderEntry that modifies it.
837 * @param entry Header Entry whose value shall be loaded.
840 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry)
842 long PositionOnEntry = ftell(fp);
843 LoadHeaderEntry(entry);
844 fseek(fp, PositionOnEntry, SEEK_SET);
848 * \ingroup gdcmParser
849 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
850 * \warning : to be re-written using the chained list instead of the H table.
851 * \warning : DO NOT use (doesn't work any longer because of the multimap)
852 * \todo : to be re-written using the chained list instead of the H table
853 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
854 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
856 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type)
861 gdcmHeaderEntry *elem;
863 std::string str_trash;
866 GroupHT groupHt; // to hold the length of each group
869 // typedef std::map<GroupKey, int> GroupHT;
871 gdcmHeaderEntry *elemZ;
873 // for each Tag in the DCM Header
875 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
880 gr = elem->GetGroup();
881 el = elem->GetElement();
884 sprintf(trash, "%04x", gr);
885 key = trash; // generate 'group tag'
887 // if the caller decided not to take SEQUENCEs into account
888 // e.g : he wants to write an ACR-NEMA File
890 if (SkipSequence && vr == "SQ")
893 // Still unsolved problem :
894 // we cannot find the 'Sequence Delimitation Item'
895 // since it's at the end of the Hash Table
898 // pas SEQUENCE en ACR-NEMA
900 // --> la descente a l'interieur' des SQ
901 // devrait etre faite avec une liste chainee, pas avec une HTable...
903 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
905 if (el == 0x0000) // the first elem is 0x0000
907 groupHt[key] = 0; // initialize group length
911 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
914 else // any elem but the first
916 if (type == ExplicitVR)
918 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
920 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
923 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
927 unsigned short int gr_bid;
929 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
933 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
934 // warning: unsigned int format, different type arg
935 sscanf(g->first.c_str(),"%x",&gr_bid);
936 tk = g->first + "|0000"; // generate the element full tag
938 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
940 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
941 elemZ = new gdcmHeaderEntry(tagZ);
943 AddHeaderEntry(elemZ); // create it
947 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
949 sprintf(trash ,"%d",g->second);
951 elemZ->SetValue(str_trash);
956 * \ingroup gdcmParser
957 * \brief writes on disc according to the requested format
958 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
959 * \ warning does NOT add the missing elements in the header :
960 * \ it's up to the user doing it !
961 * \ (function CheckHeaderCoherence to be written)
962 * @param type type of the File to be written
963 * (ACR-NEMA, ExplicitVR, ImplicitVR)
964 * @param _fp already open file pointer
966 void gdcmParser::WriteEntries(FileType type, FILE * _fp)
975 std::vector<std::string> tokens;
977 // uses now listEntries to iterate, not TagHt!
979 // pb : gdcmParser.Add does NOT update listEntries
980 // TODO : find a trick (in STL?) to do it, at low cost !
984 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
986 for (ListTag::iterator tag2=listEntries.begin();
987 tag2 != listEntries.end();
990 gr = (*tag2)->GetGroup();
991 el = (*tag2)->GetElement();
992 lgr = (*tag2)->GetLength();
993 val = (*tag2)->GetValue().c_str();
994 vr = (*tag2)->GetVR();
998 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
999 if (gr %2) continue; // ignore shadow groups
1000 if (vr == "SQ" ) continue; // ignore Sequences
1001 // TODO : find a trick to *skip* the SeQuences !
1002 // Not only ignore the SQ element
1003 if (gr == 0xfffe ) continue; // ignore delimiters
1006 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1007 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1009 if ( (type == ExplicitVR) && (gr <= 0x0002) )
1012 guint16 z=0, shortLgr;
1013 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1015 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1017 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1018 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1024 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1029 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1032 if (vr == "US" || vr == "SS")
1034 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1035 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1036 for (unsigned int i=0; i<tokens.size();i++)
1038 val_uint16 = atoi(tokens[i].c_str());
1040 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1045 if (vr == "UL" || vr == "SL")
1047 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1048 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1049 for (unsigned int i=0; i<tokens.size();i++)
1051 val_uint32 = atoi(tokens[i].c_str());
1053 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1058 // Pixels are never loaded in the element !
1059 if ((gr == 0x7fe0) && (el == 0x0010) )
1062 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1067 * \ingroup gdcmParser
1068 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1070 * @return The properly swaped 32 bits integer.
1072 guint32 gdcmParser::SwapLong(guint32 a)
1079 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1080 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1084 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1088 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1091 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1098 * \ingroup gdcmParser
1099 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1101 * @return The properly unswaped 32 bits integer.
1103 guint32 gdcmParser::UnswapLong(guint32 a)
1105 return (SwapLong(a));
1109 * \ingroup gdcmParser
1110 * \brief Swaps the bytes so they agree with the processor order
1111 * @return The properly swaped 16 bits integer.
1113 guint16 gdcmParser::SwapShort(guint16 a)
1115 if ( (sw==4321) || (sw==2143) )
1116 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1121 * \ingroup gdcmParser
1122 * \brief Unswaps the bytes so they agree with the processor order
1123 * @return The properly unswaped 16 bits integer.
1125 guint16 gdcmParser::UnswapShort(guint16 a)
1127 return (SwapShort(a));
1130 //-----------------------------------------------------------------------------
1133 * \ingroup gdcmParser
1134 * \brief Parses the header of the file but WITHOUT loading element values.
1136 void gdcmParser::Parse(bool exception_on_error) throw(gdcmFormatError)
1138 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1142 while ( (newHeaderEntry = ReadNextHeaderEntry()) )
1144 SkipHeaderEntry(newHeaderEntry);
1145 AddHeaderEntry(newHeaderEntry);
1150 * \ingroup gdcmParser
1151 * \brief Loads the element values of all the Header Entries pointed in the
1152 * public Chained List.
1154 void gdcmParser::LoadHeaderEntries(void)
1157 for (ListTag::iterator i = GetListEntry().begin();
1158 i != GetListEntry().end();
1161 LoadHeaderEntry(*i);
1166 // Load 'non string' values
1167 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1168 if( PhotometricInterpretation == "PALETTE COLOR " )
1170 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1171 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1172 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1173 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1175 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1176 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1177 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1180 // --------------------------------------------------------------
1181 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1183 // if recognition code tells us we deal with a LibIDO image
1184 // we switch lineNumber and columnNumber
1186 std::string RecCode;
1187 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1188 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1189 RecCode == "CANRME_AILIBOD1_1." )
1191 filetype = ACR_LIBIDO;
1192 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1193 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1194 SetEntryByNumber(columns, 0x0028, 0x0010);
1195 SetEntryByNumber(rows , 0x0028, 0x0011);
1197 // ----------------- End of Special Patch ----------------
1201 * \ingroup gdcmParser
1202 * \brief Loads the element content if it's length is not bigger
1203 * than the value specified with
1204 * gdcmParser::SetMaxSizeLoadEntry()
1205 * @param Entry Header Entry (Dicom Element) to be dealt with
1207 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry)
1210 guint16 group = Entry->GetGroup();
1211 std::string vr= Entry->GetVR();
1212 guint32 length = Entry->GetLength();
1213 bool SkipLoad = false;
1215 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1217 // the test was commented out to 'go inside' the SeQuences
1218 // we don't any longer skip them !
1220 // if( vr == "SQ" ) // (DO NOT remove this comment)
1223 // A SeQuence "contains" a set of Elements.
1224 // (fffe e000) tells us an Element is beginning
1225 // (fffe e00d) tells us an Element just ended
1226 // (fffe e0dd) tells us the current SeQuence just ended
1227 if( group == 0xfffe )
1232 Entry->SetLength(0);
1233 Entry->SetValue("gdcm::Skipped");
1237 // When the length is zero things are easy:
1240 Entry->SetValue("");
1244 // The elements whose length is bigger than the specified upper bound
1245 // are not loaded. Instead we leave a short notice of the offset of
1246 // the element content and it's length.
1247 if (length > MaxSizeLoadEntry)
1249 std::ostringstream s;
1250 s << "gdcm::NotLoaded.";
1251 s << " Address:" << (long)Entry->GetOffset();
1252 s << " Length:" << Entry->GetLength();
1253 s << " x(" << std::hex << Entry->GetLength() << ")";
1254 Entry->SetValue(s.str());
1258 // When integer(s) are expected, read and convert the following
1259 // n *(two or four bytes)
1260 // properly i.e. as integers as opposed to a strings.
1261 // Elements with Value Multiplicity > 1
1262 // contain a set of integers (not a single one)
1264 // Any compacter code suggested (?)
1265 if ( IsHeaderEntryAnInteger(Entry) )
1268 std::ostringstream s;
1270 if (vr == "US" || vr == "SS")
1273 NewInt = ReadInt16();
1277 for (int i=1; i < nbInt; i++)
1280 NewInt = ReadInt16();
1286 else if (vr == "UL" || vr == "SL")
1289 NewInt = ReadInt32();
1293 for (int i=1; i < nbInt; i++)
1296 NewInt = ReadInt32();
1301 #ifdef GDCM_NO_ANSI_STRING_STREAM
1302 s << std::ends; // to avoid oddities on Solaris
1303 #endif //GDCM_NO_ANSI_STRING_STREAM
1304 Entry->SetValue(s.str());
1308 // We need an additional byte for storing \0 that is not on disk
1309 std::string NewValue(length,0);
1310 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1311 if ( item_read != 1 )
1313 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1314 Entry->SetValue("gdcm::UnRead");
1318 if( (vr == "UI") ) // Because of correspondance with the VR dic
1319 Entry->SetValue(NewValue.c_str());
1321 Entry->SetValue(NewValue);
1325 * \ingroup gdcmParser
1326 * \brief add a new Dicom Element pointer to
1327 * the H Table and to the chained List
1328 * \warning push_bash in listEntries ONLY during ParseHeader
1329 * \todo something to allow further Elements addition,
1330 * \ when position to be taken care of
1331 * @param newHeaderEntry
1333 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry)
1335 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1336 listEntries.push_back(newHeaderEntry);
1341 * \ingroup gdcmParser
1343 * @param Entry Header Entry whose length of the value shall be loaded.
1347 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry)
1349 guint16 element = Entry->GetElement();
1350 guint16 group = Entry->GetGroup();
1351 std::string vr = Entry->GetVR();
1353 if( (element == 0x0010) && (group == 0x7fe0) )
1356 dbg.Verbose(2, "gdcmParser::FindLength: ",
1357 "we reached 7fe0 0010");
1360 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1362 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1364 // The following reserved two bytes (see PS 3.5-2001, section
1365 // 7.1.2 Data element structure with explicit vr p27) must be
1366 // skipped before proceeding on reading the length on 4 bytes.
1367 fseek(fp, 2L, SEEK_CUR);
1368 guint32 length32 = ReadInt32();
1370 if ( (vr == "OB") && (length32 == 0xffffffff) )
1372 Entry->SetLength(FindHeaderEntryLengthOB());
1375 FixHeaderEntryFoundLength(Entry, length32);
1379 // Length is encoded on 2 bytes.
1380 length16 = ReadInt16();
1382 // We can tell the current file is encoded in big endian (like
1383 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1384 // and it's value is the one of the encoding of a big endian file.
1385 // In order to deal with such big endian encoded files, we have
1386 // (at least) two strategies:
1387 // * when we load the "Transfer Syntax" tag with value of big endian
1388 // encoding, we raise the proper flags. Then we wait for the end
1389 // of the META group (0x0002) among which is "Transfer Syntax",
1390 // before switching the swap code to big endian. We have to postpone
1391 // the switching of the swap code since the META group is fully encoded
1392 // in little endian, and big endian coding only starts at the next
1393 // group. The corresponding code can be hard to analyse and adds
1394 // many additional unnecessary tests for regular tags.
1395 // * the second strategy consists in waiting for trouble, that shall
1396 // appear when we find the first group with big endian encoding. This
1397 // is easy to detect since the length of a "Group Length" tag (the
1398 // ones with zero as element number) has to be of 4 (0x0004). When we
1399 // encounter 1024 (0x0400) chances are the encoding changed and we
1400 // found a group with big endian encoding.
1401 // We shall use this second strategy. In order to make sure that we
1402 // can interpret the presence of an apparently big endian encoded
1403 // length of a "Group Length" without committing a big mistake, we
1404 // add an additional check: we look in the already parsed elements
1405 // for the presence of a "Transfer Syntax" whose value has to be "big
1406 // endian encoding". When this is the case, chances are we have got our
1407 // hands on a big endian encoded file: we switch the swap code to
1408 // big endian and proceed...
1409 if ( (element == 0x0000) && (length16 == 0x0400) )
1411 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1413 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1418 SwitchSwapToBigEndian();
1419 // Restore the unproperly loaded values i.e. the group, the element
1420 // and the dictionary entry depending on them.
1421 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1422 guint16 CorrectElem = SwapShort(Entry->GetElement());
1423 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1427 // This correct tag is not in the dictionary. Create a new one.
1428 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1430 // FIXME this can create a memory leaks on the old entry that be
1431 // left unreferenced.
1432 Entry->SetDictEntry(NewTag);
1435 // Heuristic: well some files are really ill-formed.
1436 if ( length16 == 0xffff)
1439 //dbg.Verbose(0, "gdcmParser::FindLength",
1440 // "Erroneous element length fixed.");
1441 // Actually, length= 0xffff means that we deal with
1442 // Unknown Sequence Length
1445 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1450 // Either implicit VR or a non DICOM conformal (see not below) explicit
1451 // VR that ommited the VR of (at least) this element. Farts happen.
1452 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1453 // on Data elements "Implicit and Explicit VR Data Elements shall
1454 // not coexist in a Data Set and Data Sets nested within it".]
1455 // Length is on 4 bytes.
1456 FixHeaderEntryFoundLength(Entry, ReadInt32());
1462 * \ingroup gdcmParser
1463 * \brief Find the Value Representation of the current Dicom Element.
1466 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1468 if (filetype != ExplicitVR)
1474 long PositionOnEntry = ftell(fp);
1475 // Warning: we believe this is explicit VR (Value Representation) because
1476 // we used a heuristic that found "UL" in the first tag. Alas this
1477 // doesn't guarantee that all the tags will be in explicit VR. In some
1478 // cases (see e-film filtered files) one finds implicit VR tags mixed
1479 // within an explicit VR file. Hence we make sure the present tag
1480 // is in explicit VR and try to fix things if it happens not to be
1483 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1485 if(!CheckHeaderEntryVR(Entry,VR))
1487 fseek(fp, PositionOnEntry, SEEK_SET);
1488 // When this element is known in the dictionary we shall use, e.g. for
1489 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1490 // dictionary entry. Still we have to flag the element as implicit since
1491 // we know now our assumption on expliciteness is not furfilled.
1493 if ( Entry->IsVRUnknown() )
1494 Entry->SetVR("Implicit");
1495 Entry->SetImplicitVR();
1500 * \ingroup gdcmParser
1501 * \brief Check the correspondance between the VR of the header entry
1502 * and the taken VR. If they are different, the header entry is
1503 * updated with the new VR.
1506 * @return false if the VR is incorrect of if the VR isn't referenced
1507 * otherwise, it returns true
1509 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1511 char msg[100]; // for sprintf
1512 bool RealExplicit = true;
1514 // Assume we are reading a falsely explicit VR file i.e. we reached
1515 // a tag where we expect reading a VR but are in fact we read the
1516 // first to bytes of the length. Then we will interogate (through find)
1517 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1518 // both GCC and VC++ implementations of the STL map. Hence when the
1519 // expected VR read happens to be non-ascii characters we consider
1520 // we hit falsely explicit VR tag.
1522 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1523 RealExplicit = false;
1525 // CLEANME searching the dicom_vr at each occurence is expensive.
1526 // PostPone this test in an optional integrity check at the end
1527 // of parsing or only in debug mode.
1528 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1529 RealExplicit= false;
1531 if ( !RealExplicit )
1533 // We thought this was explicit VR, but we end up with an
1534 // implicit VR tag. Let's backtrack.
1535 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1536 Entry->GetGroup(),Entry->GetElement());
1537 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1542 if ( Entry->IsVRUnknown() )
1544 // When not a dictionary entry, we can safely overwrite the VR.
1547 else if ( Entry->GetVR() != vr )
1549 // The VR present in the file and the dictionary disagree. We assume
1550 // the file writer knew best and use the VR of the file. Since it would
1551 // be unwise to overwrite the VR of a dictionary (since it would
1552 // compromise it's next user), we need to clone the actual DictEntry
1553 // and change the VR for the read one.
1554 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1555 Entry->GetGroup(),Entry->GetElement(),
1556 vr,"FIXME",Entry->GetName());
1557 Entry->SetDictEntry(NewEntry);
1563 * \ingroup gdcmParser
1564 * \brief Get the transformed value of the header entry. The VR value
1565 * is used to define the transformation to operate on the value
1566 * \warning NOT end user intended method !
1568 * @return Transformed entry value
1570 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1572 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1574 std::string val=Entry->GetValue();
1575 std::string vr=Entry->GetVR();
1576 guint32 length = Entry->GetLength();
1577 std::ostringstream s;
1580 if (vr == "US" || vr == "SS")
1585 for (int i=0; i < nbInt; i++)
1589 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1590 NewInt16 = SwapShort(NewInt16);
1595 else if (vr == "UL" || vr == "SL")
1600 for (int i=0; i < nbInt; i++)
1604 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1605 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1606 NewInt32=SwapLong(NewInt32);
1611 #ifdef GDCM_NO_ANSI_STRING_STREAM
1612 s << std::ends; // to avoid oddities on Solaris
1613 #endif //GDCM_NO_ANSI_STRING_STREAM
1617 return(Entry->GetValue());
1621 * \ingroup gdcmParser
1622 * \brief Get the reverse transformed value of the header entry. The VR
1623 * value is used to define the reverse transformation to operate on
1625 * \warning NOT end user intended method !
1627 * @return Reverse transformed entry value
1629 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1631 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1633 std::string vr=Entry->GetVR();
1634 std::ostringstream s;
1635 std::vector<std::string> tokens;
1637 if (vr == "US" || vr == "SS")
1641 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1642 Tokenize (Entry->GetValue(), tokens, "\\");
1643 for (unsigned int i=0; i<tokens.size();i++)
1645 NewInt16 = atoi(tokens[i].c_str());
1646 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1650 if (vr == "UL" || vr == "SL")
1654 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1655 Tokenize (Entry->GetValue(), tokens, "\\");
1656 for (unsigned int i=0; i<tokens.size();i++)
1658 NewInt32 = atoi(tokens[i].c_str());
1659 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1660 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1665 #ifdef GDCM_NO_ANSI_STRING_STREAM
1666 s << std::ends; // to avoid oddities on Solaris
1667 #endif //GDCM_NO_ANSI_STRING_STREAM
1671 return(Entry->GetValue());
1675 * \ingroup gdcmParser
1676 * \brief Skip a given Header Entry
1677 * \warning NOT end user intended method !
1680 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1682 SkipBytes(entry->GetLength());
1686 * \ingroup gdcmParser
1687 * \brief When the length of an element value is obviously wrong (because
1688 * the parser went Jabberwocky) one can hope improving things by
1689 * applying this heuristic.
1691 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1693 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1695 if ( FoundLength == 0xffffffff)
1700 // Sorry for the patch!
1701 // XMedCom did the trick to read some nasty GE images ...
1702 else if (FoundLength == 13)
1704 // The following 'if' will be removed when there is no more
1705 // images on Creatis HDs with a 13 length for Manufacturer...
1706 if ( (Entry->GetGroup() != 0x0008) ||
1707 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ) {
1708 // end of remove area
1710 Entry->SetReadLength(10); // a bug is to be fixed
1714 // to fix some garbage 'Leonardo' Siemens images
1715 // May be commented out to avoid overhead
1716 else if ( (Entry->GetGroup() == 0x0009) &&
1717 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) )
1720 Entry->SetReadLength(4); // a bug is to be fixed
1724 // to try to 'go inside' SeQuences (with length), and not to skip them
1725 else if ( Entry->GetVR() == "SQ")
1727 if (enableSequences) // only if the user does want to !
1731 // a SeQuence Element is beginning
1732 // Let's forget it's length
1733 // (we want to 'go inside')
1735 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1736 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1737 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1738 // if we don't, we lost 28800 characters from the Header :-(
1740 else if(Entry->GetGroup() == 0xfffe)
1742 // sometimes, length seems to be wrong
1743 FoundLength =0; // some more clever checking to be done !
1745 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1746 // causes troubles :-(
1749 Entry->SetUsableLength(FoundLength);
1753 * \ingroup gdcmParser
1754 * \brief Apply some heuristics to predict wether the considered
1755 * element value contains/represents an integer or not.
1756 * @param Entry The element value on which to apply the predicate.
1757 * @return The result of the heuristical predicate.
1759 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry)
1761 guint16 element = Entry->GetElement();
1762 guint16 group = Entry->GetGroup();
1763 std::string vr = Entry->GetVR();
1764 guint32 length = Entry->GetLength();
1766 // When we have some semantics on the element we just read, and if we
1767 // a priori know we are dealing with an integer, then we shall be
1768 // able to swap it's element value properly.
1769 if ( element == 0 ) // This is the group length of the group
1775 std::ostringstream s;
1776 s << "Erroneous Group Length element length on :" \
1777 << std::hex << group << " , " << element;
1778 dbg.Error("gdcmParser::IsHeaderEntryAnInteger",
1782 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1789 * \ingroup gdcmParser
1794 guint32 gdcmParser::FindHeaderEntryLengthOB(void)
1796 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1799 long PositionOnEntry = ftell(fp);
1800 bool FoundSequenceDelimiter = false;
1801 guint32 TotalLength = 0;
1804 while ( ! FoundSequenceDelimiter)
1810 TotalLength += 4; // We even have to decount the group and element
1812 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1814 char msg[100]; // for sprintf. Sorry
1815 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1816 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1820 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1821 FoundSequenceDelimiter = true;
1822 else if ( n != 0xe000 )
1824 char msg[100]; // for sprintf. Sorry
1825 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1827 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1831 ItemLength = ReadInt32();
1832 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1833 // the ItemLength with ReadInt32
1834 SkipBytes(ItemLength);
1836 fseek(fp, PositionOnEntry, SEEK_SET);
1841 * \ingroup gdcmParser
1842 * \brief Reads a supposed to be 16 Bits integer
1843 * \ (swaps it depending on processor endianity)
1845 * @return integer acts as a boolean
1847 guint16 gdcmParser::ReadInt16(void)
1851 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1852 if ( item_read != 1 )
1855 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1865 * \ingroup gdcmParser
1866 * \brief Reads a supposed to be 32 Bits integer
1867 * \ (swaps it depending on processor endianity)
1871 guint32 gdcmParser::ReadInt32(void)
1875 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1876 if ( item_read != 1 )
1879 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1889 * \ingroup gdcmParser
1894 void gdcmParser::SkipBytes(guint32 NBytes)
1896 //FIXME don't dump the returned value
1897 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1901 * \ingroup gdcmParser
1904 void gdcmParser::Initialise(void)
1906 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1907 RefShaDict = (gdcmDict*)0;
1911 * \ingroup gdcmParser
1912 * \brief Discover what the swap code is (among little endian, big endian,
1913 * bad little endian, bad big endian).
1916 void gdcmParser::CheckSwap()
1918 // Fourth semantics:
1920 // ---> Warning : This fourth field is NOT part
1921 // of the 'official' Dicom Dictionnary
1922 // and should NOT be used.
1923 // (Not defined for all the groups
1924 // may be removed in a future release)
1927 // META Meta Information
1939 // NMI Nuclear Medicine
1941 // BFS Basic Film Session
1942 // BFB Basic Film Box
1943 // BIB Basic Image Box
1958 // The only guaranted way of finding the swap code is to find a
1959 // group tag since we know it's length has to be of four bytes i.e.
1960 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1961 // occurs when we can't find such group...
1963 guint32 x=4; // x : for ntohs
1964 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1968 char deb[HEADER_LENGTH_TO_READ];
1970 // First, compare HostByteOrder and NetworkByteOrder in order to
1971 // determine if we shall need to swap bytes (i.e. the Endian type).
1976 //cout << net2host << endl;
1978 // The easiest case is the one of a DICOM header, since it possesses a
1979 // file preamble where it suffice to look for the string "DICM".
1980 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1983 if(memcmp(entCur, "DICM", (size_t)4) == 0)
1985 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
1986 // Next, determine the value representation (VR). Let's skip to the
1987 // first element (0002, 0000) and check there if we find "UL"
1988 // - or "OB" if the 1st one is (0002,0001) -,
1989 // in which case we (almost) know it is explicit VR.
1990 // WARNING: if it happens to be implicit VR then what we will read
1991 // is the length of the group. If this ascii representation of this
1992 // length happens to be "UL" then we shall believe it is explicit VR.
1993 // FIXME: in order to fix the above warning, we could read the next
1994 // element value (or a couple of elements values) in order to make
1995 // sure we are not commiting a big mistake.
1996 // We need to skip :
1997 // * the 128 bytes of File Preamble (often padded with zeroes),
1998 // * the 4 bytes of "DICM" string,
1999 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2000 // i.e. a total of 136 bytes.
2003 // Use gdcmParser::dicom_vr to test all the possibilities
2004 // instead of just checking for UL, OB and UI !?
2005 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2006 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2007 (memcmp(entCur, "UI", (size_t)2) == 0) )
2009 filetype = ExplicitVR;
2010 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2011 "explicit Value Representation");
2015 filetype = ImplicitVR;
2016 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2017 "not an explicit Value Representation");
2022 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2023 "HostByteOrder != NetworkByteOrder");
2028 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2029 "HostByteOrder = NetworkByteOrder");
2032 // Position the file position indicator at first tag (i.e.
2033 // after the file preamble and the "DICM" string).
2035 fseek (fp, 132L, SEEK_SET);
2039 // Alas, this is not a DicomV3 file and whatever happens there is no file
2040 // preamble. We can reset the file position indicator to where the data
2041 // is (i.e. the beginning of the file).
2042 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2045 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2046 // By clean we mean that the length of the first tag is written down.
2047 // If this is the case and since the length of the first group HAS to be
2048 // four (bytes), then determining the proper swap code is straightforward.
2051 // We assume the array of char we are considering contains the binary
2052 // representation of a 32 bits integer. Hence the following dirty
2054 s = *((guint32 *)(entCur));
2075 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2076 "ACR/NEMA unfound swap info (time to raise bets)");
2079 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2080 // It is time for despaired wild guesses. So, let's assume this file
2081 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
2082 // not present. Then the only info we have is the net2host one.
2092 * \ingroup gdcmParser
2095 void gdcmParser::SwitchSwapToBigEndian(void)
2097 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2098 "Switching to BigEndian mode.");
2119 * \ingroup gdcmParser
2124 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2128 if ((guint32)NewSize >= (guint32)0xffffffff)
2130 MaxSizeLoadEntry = 0xffffffff;
2133 MaxSizeLoadEntry = NewSize;
2137 * \ingroup gdcmParser
2138 * \brief Searches both the public and the shadow dictionary (when they
2139 * exist) for the presence of the DictEntry with given name.
2140 * The public dictionary has precedence on the shadow one.
2141 * @param Name name of the searched DictEntry
2142 * @return Corresponding DictEntry when it exists, NULL otherwise.
2144 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2146 gdcmDictEntry *found = (gdcmDictEntry *)0;
2147 if (!RefPubDict && !RefShaDict)
2149 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2150 "we SHOULD have a default dictionary");
2154 found = RefPubDict->GetDictEntryByName(Name);
2160 found = RefShaDict->GetDictEntryByName(Name);
2168 * \ingroup gdcmParser
2169 * \brief Searches both the public and the shadow dictionary (when they
2170 * exist) for the presence of the DictEntry with given
2171 * group and element. The public dictionary has precedence on the
2173 * @param group group of the searched DictEntry
2174 * @param element element of the searched DictEntry
2175 * @return Corresponding DictEntry when it exists, NULL otherwise.
2177 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2179 gdcmDictEntry *found = (gdcmDictEntry *)0;
2180 if (!RefPubDict && !RefShaDict)
2182 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2183 "we SHOULD have a default dictionary");
2187 found = RefPubDict->GetDictEntryByNumber(group, element);
2193 found = RefShaDict->GetDictEntryByNumber(group, element);
2201 * \ingroup gdcmParser
2202 * \brief Read the next tag but WITHOUT loading it's value
2203 * @return On succes the newly created HeaderEntry, NULL on failure.
2205 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void)
2208 gdcmHeaderEntry *NewEntry;
2214 // We reached the EOF (or an error occured) and header parsing
2215 // has to be considered as finished.
2216 return (gdcmHeaderEntry *)0;
2218 NewEntry = NewHeaderEntryByNumber(g, n);
2219 FindHeaderEntryVR(NewEntry);
2220 FindHeaderEntryLength(NewEntry);
2227 NewEntry->SetOffset(ftell(fp));
2228 //if ( (g==0x7fe0) && (n==0x0010) )
2233 * \ingroup gdcmParser
2234 * \brief Build a new Element Value from all the low level arguments.
2235 * Check for existence of dictionary entry, and build
2236 * a default one when absent.
2237 * @param Name Name of the underlying DictEntry
2239 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2241 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2243 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2245 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2248 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2249 "failed to allocate gdcmHeaderEntry");
2250 return (gdcmHeaderEntry *)0;
2256 * \ingroup gdcmParser
2257 * \brief Request a new virtual dict entry to the dict set
2258 * @param group group of the underlying DictEntry
2259 * @param elem element of the underlying DictEntry
2260 * @param vr VR of the underlying DictEntry
2261 * @param fourth owner group
2262 * @param name english name
2264 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2269 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2273 * \ingroup gdcmParser
2274 * \brief Build a new Element Value from all the low level arguments.
2275 * Check for existence of dictionary entry, and build
2276 * a default one when absent.
2277 * @param Group group of the underlying DictEntry
2278 * @param Elem element of the underlying DictEntry
2280 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2282 // Find out if the tag we encountered is in the dictionaries:
2283 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2285 DictEntry = NewVirtualDictEntry(Group, Elem);
2287 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2290 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2291 "failed to allocate gdcmHeaderEntry");
2298 * \ingroup gdcmParser
2299 * \brief Small utility function that creates a new manually crafted
2300 * (as opposed as read from the file) gdcmHeaderEntry with user
2301 * specified name and adds it to the public tag hash table.
2302 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2303 * @param NewTagName The name to be given to this new tag.
2304 * @param VR The Value Representation to be given to this new tag.
2305 * @return The newly hand crafted Element Value.
2307 gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2310 gdcmHeaderEntry *NewEntry = NULL;
2311 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2312 guint32 FreeElem = 0;
2313 gdcmDictEntry *DictEntry = NULL;
2315 FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2316 if (FreeElem == UINT32_MAX)
2318 dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2319 "Group 0xffff in Public Dict is full");
2323 DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2324 VR, "GDCM", NewTagName);
2325 NewEntry = new gdcmHeaderEntry(DictEntry);
2326 AddHeaderEntry(NewEntry);
2331 * \ingroup gdcmParser
2332 * \brief Generate a free TagKey i.e. a TagKey that is not present
2333 * in the TagHt dictionary.
2334 * @param group The generated tag must belong to this group.
2335 * @return The element of tag with given group which is fee.
2337 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2339 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2341 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2342 if (tagHT.count(key) == 0)
2348 //-----------------------------------------------------------------------------