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; // 'Heavy' header print 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; // 'Heavy' header print 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 s << "------------ using listEntries ----------------" << std::endl;
107 for (ListTag::iterator i = listEntries.begin();
108 i != listEntries.end();
111 (*i)->SetPrintLevel(printLevel);
118 * \ingroup gdcmParser
119 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
122 void gdcmParser::PrintPubDict(std::ostream & os)
124 RefPubDict->Print(os);
128 * \ingroup gdcmParser
129 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
132 void gdcmParser::PrintShaDict(std::ostream & os)
134 RefShaDict->Print(os);
137 //-----------------------------------------------------------------------------
140 * \ingroup gdcmParser
141 * \brief Get the public dictionary used
143 gdcmDict *gdcmParser::GetPubDict(void)
149 * \ingroup gdcmParser
150 * \brief Get the shadow dictionary used
152 gdcmDict *gdcmParser::GetShaDict(void)
158 * \ingroup gdcmParser
159 * \brief Set the shadow dictionary used
160 * \param dict dictionary to use in shadow
162 bool gdcmParser::SetShaDict(gdcmDict *dict)
169 * \ingroup gdcmParser
170 * \brief Set the shadow dictionary used
171 * \param dictName name of the dictionary to use in shadow
173 bool gdcmParser::SetShaDict(DictKey dictName)
175 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
180 * \ingroup gdcmParser
181 * \brief This predicate, based on hopefully reasonable heuristics,
182 * decides whether or not the current gdcmParser was properly parsed
183 * and contains the mandatory information for being considered as
184 * a well formed and usable Dicom/Acr File.
185 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
188 bool gdcmParser::IsReadable(void)
190 if(filetype==Unknown)
193 if(listEntries.size()<=0)
200 * \ingroup gdcmParser
201 * \brief Determines if the Transfer Syntax was already encountered
202 * and if it corresponds to a ImplicitVRLittleEndian one.
204 * @return True when ImplicitVRLittleEndian found. False in all other cases.
206 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void)
208 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
211 LoadHeaderEntrySafe(Element);
213 std::string Transfer = Element->GetValue();
214 if ( Transfer == UI1_2_840_10008_1_2 )
220 * \ingroup gdcmParser
221 * \brief Determines if the Transfer Syntax was already encountered
222 * and if it corresponds to a ExplicitVRLittleEndian one.
224 * @return True when ExplicitVRLittleEndian found. False in all other cases.
226 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void)
228 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
231 LoadHeaderEntrySafe(Element);
233 std::string Transfer = Element->GetValue();
234 if ( Transfer == UI1_2_840_10008_1_2_1 )
240 * \ingroup gdcmParser
241 * \brief Determines if the Transfer Syntax was already encountered
242 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
244 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
246 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
248 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
251 LoadHeaderEntrySafe(Element);
253 std::string Transfer = Element->GetValue();
254 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
260 * \ingroup gdcmParser
261 * \brief Determines if the Transfer Syntax was already encountered
262 * and if it corresponds to a Explicit VR Big Endian one.
264 * @return True when big endian found. False in all other cases.
266 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void)
268 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
271 LoadHeaderEntrySafe(Element);
273 std::string Transfer = Element->GetValue();
274 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
280 * \ingroup gdcmParser
281 * \brief returns the File Type
282 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
285 FileType gdcmParser::GetFileType(void) {
290 * \ingroup gdcmParser
291 * \brief opens the file
292 * @param exception_on_error
295 FILE *gdcmParser::OpenFile(bool exception_on_error)
298 fp=fopen(filename.c_str(),"rb");
299 if(exception_on_error)
302 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
308 fread(&zero, (size_t)2, (size_t)1, fp);
310 //ACR -- or DICOM with no Preamble --
311 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
315 fseek(fp, 126L, SEEK_CUR);
317 fread(dicm, (size_t)4, (size_t)1, fp);
318 if( memcmp(dicm, "DICM", 4) == 0 )
322 dbg.Verbose(0, "gdcmParser::gdcmParser not DICOM/ACR", filename.c_str());
325 dbg.Verbose(0, "gdcmParser::gdcmParser cannot open file", filename.c_str());
331 * \ingroup gdcmParser
332 * \brief closes the file
333 * @return TRUE if the close was successfull
335 bool gdcmParser::CloseFile(void)
337 int closed = fclose(fp);
345 * \ingroup gdcmParser
347 * @param fp file pointer on an already open file
348 * @param type type of the File to be written
349 * (ACR-NEMA, ExplicitVR, ImplicitVR)
350 * @return always "True" ?!
352 bool gdcmParser::Write(FILE *fp, FileType type)
355 // TODO The stuff has been rewritten using the chained list instead
357 // so we could remove the GroupHT from the gdcmParser
361 // TODO : move the following lines (and a lot of others, to be written)
362 // to a future function CheckAndCorrectHeader
365 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
366 // (FileType est un champ de gdcmParser ...)
367 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
369 // a moins de se livrer a un tres complique ajout des champs manquants.
370 // faire un CheckAndCorrectHeader (?)
373 if (type == ImplicitVR)
375 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
376 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
378 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
379 // values with a VR of UI shall be padded with a single trailing null
380 // Dans le cas suivant on doit pader manuellement avec un 0
382 SetEntryLengthByNumber(18, 0x0002, 0x0010);
385 if (type == ExplicitVR)
387 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
388 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
390 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
391 // values with a VR of UI shall be padded with a single trailing null
392 // Dans le cas suivant on doit pader manuellement avec un 0
394 SetEntryLengthByNumber(20, 0x0002, 0x0010);
398 if ( (type == ImplicitVR) || (type == ExplicitVR) )
399 UpdateGroupLength(false,type);
401 UpdateGroupLength(true,ACR);
403 WriteEntries(type, fp);
408 * \ingroup gdcmParser
409 * \brief Modifies the value of a given Header Entry (Dicom Element)
410 * if it exists; Creates it with the given value if it doesn't
411 * @param Value passed as a std::string
416 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
417 guint16 Group, guint16 Elem )
419 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
420 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
425 SetEntryByNumber(Value, Group, Elem);
430 * \ingroup gdcmParser
431 * \brief Modifies the value of a given Header Entry (Dicom Element)
432 * if it exists; Creates it with the given value if it doesn't
433 * @param Value passed as a char*
439 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem )
441 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
446 AddHeaderEntry(nvHeaderEntry);
448 std::string v = Value;
449 SetEntryByNumber(v, Group, Elem);
454 * \ingroup gdcmParser
455 * \brief Set a new value if the invoked element exists
456 * Seems to be useless !!!
462 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
464 std::string v = Value;
465 SetEntryByNumber(v, Group, Elem);
469 //-----------------------------------------------------------------------------
472 * \ingroup gdcmParser
473 * \brief Checks if a given Dicom Element exists
474 * \ within the H table
475 * @param group Group number of the searched Dicom Element
476 * @param element Element number of the searched Dicom Element
477 * @return number of occurences
479 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element )
481 std::string key = gdcmDictEntry::TranslateToKey(group, element );
482 return (tagHT.count(key));
486 * \ingroup gdcmParser
487 * \brief Searches within Header Entries (Dicom Elements) parsed with
488 * the public and private dictionaries
489 * for the element value of a given tag.
490 * \warning Don't use any longer : use GetPubEntryByName
491 * @param tagName name of the searched element.
492 * @return Corresponding element value when it exists,
493 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
495 std::string gdcmParser::GetEntryByName(std::string tagName)
497 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
498 if( dictEntry == NULL)
501 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
505 * \ingroup gdcmParser
506 * \brief Searches within Header Entries (Dicom Elements) parsed with
507 * the public and private dictionaries
508 * for the element value representation of a given tag.
510 * Obtaining the VR (Value Representation) might be needed by caller
511 * to convert the string typed content to caller's native type
512 * (think of C++ vs Python). The VR is actually of a higher level
513 * of semantics than just the native C++ type.
514 * @param tagName name of the searched element.
515 * @return Corresponding element value representation when it exists,
516 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
518 std::string gdcmParser::GetEntryVRByName(std::string tagName)
520 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
521 if( dictEntry == NULL)
524 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
525 dictEntry->GetElement());
526 return elem->GetVR();
530 * \ingroup gdcmParser
531 * \brief Searches within Header Entries (Dicom Elements) parsed with
532 * the public and private dictionaries
533 * for the element value representation of a given tag.
534 * @param group Group of the searched tag.
535 * @param element Element of the searched tag.
536 * @return Corresponding element value representation when it exists,
537 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
539 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element)
541 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
542 if ( ! tagHT.count(key))
544 return tagHT.find(key)->second->GetValue();
548 * \ingroup gdcmParser
549 * \brief Searches within Header Entries (Dicom Elements) parsed with
550 * the public and private dictionaries
551 * for the element value representation of a given tag..
553 * Obtaining the VR (Value Representation) might be needed by caller
554 * to convert the string typed content to caller's native type
555 * (think of C++ vs Python). The VR is actually of a higher level
556 * of semantics than just the native C++ type.
557 * @param group Group of the searched tag.
558 * @param element Element of the searched tag.
559 * @return Corresponding element value representation when it exists,
560 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
562 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element)
564 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
567 return elem->GetVR();
571 * \ingroup gdcmParser
572 * \brief Sets the value (string) of the Header Entry (Dicom Element)
573 * @param content string value of the Dicom Element
574 * @param tagName name of the searched Dicom Element.
575 * @return true when found
577 bool gdcmParser::SetEntryByName(std::string content,std::string tagName)
579 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
580 if( dictEntry == NULL)
583 return(SetEntryByNumber(content,dictEntry->GetGroup(),
584 dictEntry->GetElement()));
588 * \ingroup gdcmParser
589 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
590 * through it's (group, element) and modifies it's content with
592 * \warning Don't use any longer : use SetPubEntryByNumber
593 * @param content new value to substitute with
594 * @param group group of the Dicom Element to modify
595 * @param element element of the Dicom Element to modify
597 bool gdcmParser::SetEntryByNumber(std::string content,
601 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
602 if ( ! tagHT.count(key))
604 int l = content.length();
605 if(l%2) // Odd length are padded with a space (020H).
608 content = content + '\0';
611 //tagHT[key]->SetValue(content);
614 TagHeaderEntryHT::iterator p2;
615 // DO NOT remove the following lines : they explain the stuff
616 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
617 //p2=p.first; // iterator on the first synonym
618 //a=p2->second; // H Table target column (2-nd col)
621 a = ((tagHT.equal_range(key)).first)->second;
623 a-> SetValue(content);
625 //std::string vr = tagHT[key]->GetVR();
626 std::string vr = a->GetVR();
629 if( (vr == "US") || (vr == "SS") )
631 else if( (vr == "UL") || (vr == "SL") )
636 //tagHT[key]->SetLength(lgr);
642 * \ingroup gdcmParser
643 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
644 * in the PubHeaderEntrySet of this instance
645 * through it's (group, element) and modifies it's length with
647 * \warning Use with extreme caution.
648 * @param length new length to substitute with
649 * @param group group of the entry to modify
650 * @param element element of the Entry to modify
651 * @return 1 on success, 0 otherwise.
654 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
655 guint16 group, guint16 element)
657 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
658 if ( ! tagHT.count(key))
660 if (length%2) length++; // length must be even
661 //tagHT[key]->SetLength(length);
662 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
668 * \ingroup gdcmParser
669 * \brief Gets (from Header) the offset of a 'non string' element value
670 * \ (LoadElementValues has already be executed)
673 * @return File Offset of the Element Value
675 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
677 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
680 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
681 "failed to Locate gdcmHeaderEntry");
684 return Entry->GetOffset();
688 * \ingroup gdcmParser
689 * \brief Gets (from Header) a 'non string' element value
690 * \ (LoadElementValues has already be executed)
693 * @return Pointer to the 'non string' area
695 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
697 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
700 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
701 "failed to Locate gdcmHeaderEntry");
704 return Entry->GetVoidArea();
708 * \ingroup gdcmParser
709 * \brief Loads (from disk) the element content
710 * when a string is not suitable
712 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
714 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
717 size_t o =(size_t)Element->GetOffset();
718 fseek(fp, o, SEEK_SET);
719 int l=Element->GetLength();
720 void * a = malloc(l);
724 SetEntryVoidAreaByNumber(a, Group, Elem);
725 // TODO check the result
726 size_t l2 = fread(a, 1, l ,fp);
736 * \ingroup gdcmParser
737 * \brief Sets a 'non string' value to a given Dicom Element
739 * @param group Group number of the searched Dicom Element
740 * @param element Element number of the searched Dicom Element
743 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,guint16 group, guint16 element)
745 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
746 if ( ! tagHT.count(key))
748 //tagHT[key]->SetVoidArea(area);
749 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
754 * \ingroup gdcmParser
755 * \brief Update the entries with the shadow dictionary. Only odd entries are
758 void gdcmParser::UpdateShaEntries(void)
760 gdcmDictEntry *entry;
763 for(ListTag::iterator it=listEntries.begin();
764 it!=listEntries.end();
767 // Odd group => from public dictionary
768 if((*it)->GetGroup()%2==0)
771 // Peer group => search the corresponding dict entry
773 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
777 if((*it)->IsImplicitVR())
782 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
785 // Set the new entry and the new value
786 (*it)->SetDictEntry(entry);
787 CheckHeaderEntryVR(*it,vr);
789 (*it)->SetValue(GetHeaderEntryValue(*it));
793 // Remove precedent value transformation
794 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
800 * \ingroup gdcmParser
801 * \brief Searches within the Header Entries for a Dicom Element of
803 * @param tagName name of the searched Dicom Element.
804 * @return Corresponding Dicom Element when it exists, and NULL
807 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName)
809 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
810 if( dictEntry == NULL)
813 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
817 * \ingroup gdcmParser
818 * \brief retrieves a Dicom Element (the first one) using (group, element)
819 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
820 * if you think it's NOT UNIQUE, check the count number
821 * and use iterators to retrieve ALL the Dicoms Elements within
822 * a given couple (group, element)
823 * @param group Group number of the searched Dicom Element
824 * @param element Element number of the searched Dicom Element
827 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
829 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
830 if ( ! tagHT.count(key))
832 return tagHT.find(key)->second;
836 * \ingroup gdcmParser
837 * \brief Loads the element while preserving the current
838 * underlying file position indicator as opposed to
839 * to LoadHeaderEntry that modifies it.
840 * @param entry Header Entry whose value shall be loaded.
843 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry)
845 long PositionOnEntry = ftell(fp);
846 LoadHeaderEntry(entry);
847 fseek(fp, PositionOnEntry, SEEK_SET);
851 * \ingroup gdcmParser
852 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
853 * \warning : to be re-written using the chained list instead of the H table.
854 * \warning : DO NOT use (doesn't work any longer because of the multimap)
855 * \todo : to be re-written using the chained list instead of the H table
856 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
857 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
859 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type)
864 gdcmHeaderEntry *elem;
866 std::string str_trash;
869 GroupHT groupHt; // to hold the length of each group
872 // typedef std::map<GroupKey, int> GroupHT;
874 gdcmHeaderEntry *elemZ;
876 // for each Tag in the DCM Header
878 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
883 gr = elem->GetGroup();
884 el = elem->GetElement();
887 sprintf(trash, "%04x", gr);
888 key = trash; // generate 'group tag'
890 // if the caller decided not to take SEQUENCEs into account
891 // e.g : he wants to write an ACR-NEMA File
893 if (SkipSequence && vr == "SQ")
896 // Still unsolved problem :
897 // we cannot find the 'Sequence Delimitation Item'
898 // since it's at the end of the Hash Table
901 // pas SEQUENCE en ACR-NEMA
903 // --> la descente a l'interieur' des SQ
904 // devrait etre faite avec une liste chainee, pas avec une HTable...
906 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
908 if (el == 0x0000) // the first elem is 0x0000
910 groupHt[key] = 0; // initialize group length
914 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
917 else // any elem but the first
919 if (type == ExplicitVR)
921 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
923 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
926 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
930 unsigned short int gr_bid;
932 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
936 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
937 // warning: unsigned int format, different type arg
938 sscanf(g->first.c_str(),"%x",&gr_bid);
939 tk = g->first + "|0000"; // generate the element full tag
941 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
943 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
944 elemZ = new gdcmHeaderEntry(tagZ);
946 AddHeaderEntry(elemZ); // create it
950 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
952 sprintf(trash ,"%d",g->second);
954 elemZ->SetValue(str_trash);
959 * \ingroup gdcmParser
960 * \brief writes on disc according to the requested format
961 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
962 * \ warning does NOT add the missing elements in the header :
963 * \ it's up to the user doing it !
964 * \ (function CheckHeaderCoherence to be written)
965 * @param type type of the File to be written
966 * (ACR-NEMA, ExplicitVR, ImplicitVR)
967 * @param _fp already open file pointer
969 void gdcmParser::WriteEntries(FileType type, FILE * _fp)
978 std::vector<std::string> tokens;
980 // uses now listEntries to iterate, not TagHt!
982 // pb : gdcmParser.Add does NOT update listEntries
983 // TODO : find a trick (in STL?) to do it, at low cost !
987 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
989 for (ListTag::iterator tag2=listEntries.begin();
990 tag2 != listEntries.end();
993 gr = (*tag2)->GetGroup();
994 el = (*tag2)->GetElement();
995 lgr = (*tag2)->GetLength();
996 val = (*tag2)->GetValue().c_str();
997 vr = (*tag2)->GetVR();
1001 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
1002 if (gr %2) continue; // ignore shadow groups
1003 if (vr == "SQ" ) continue; // ignore Sequences
1004 // TODO : find a trick to *skip* the SeQuences !
1005 // Not only ignore the SQ element
1006 if (gr == 0xfffe ) continue; // ignore delimiters
1009 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1010 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1012 if ( (type == ExplicitVR) && (gr <= 0x0002) )
1015 guint16 z=0, shortLgr;
1016 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1018 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1020 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1021 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1027 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1032 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1035 if (vr == "US" || vr == "SS")
1037 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1038 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1039 for (unsigned int i=0; i<tokens.size();i++)
1041 val_uint16 = atoi(tokens[i].c_str());
1043 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1048 if (vr == "UL" || vr == "SL")
1050 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1051 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1052 for (unsigned int i=0; i<tokens.size();i++)
1054 val_uint32 = atoi(tokens[i].c_str());
1056 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1061 // Pixels are never loaded in the element !
1062 if ((gr == 0x7fe0) && (el == 0x0010) )
1065 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1070 * \ingroup gdcmParser
1071 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1073 * @return The properly swaped 32 bits integer.
1075 guint32 gdcmParser::SwapLong(guint32 a)
1082 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1083 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1087 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1091 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1094 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1101 * \ingroup gdcmParser
1102 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1104 * @return The properly unswaped 32 bits integer.
1106 guint32 gdcmParser::UnswapLong(guint32 a)
1108 return (SwapLong(a));
1112 * \ingroup gdcmParser
1113 * \brief Swaps the bytes so they agree with the processor order
1114 * @return The properly swaped 16 bits integer.
1116 guint16 gdcmParser::SwapShort(guint16 a)
1118 if ( (sw==4321) || (sw==2143) )
1119 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1124 * \ingroup gdcmParser
1125 * \brief Unswaps the bytes so they agree with the processor order
1126 * @return The properly unswaped 16 bits integer.
1128 guint16 gdcmParser::UnswapShort(guint16 a)
1130 return (SwapShort(a));
1133 //-----------------------------------------------------------------------------
1136 * \ingroup gdcmParser
1137 * \brief Parses the header of the file but WITHOUT loading element values.
1139 void gdcmParser::Parse(bool exception_on_error) throw(gdcmFormatError)
1141 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1145 while ( (newHeaderEntry = ReadNextHeaderEntry()) )
1147 SkipHeaderEntry(newHeaderEntry);
1148 AddHeaderEntry(newHeaderEntry);
1153 * \ingroup gdcmParser
1154 * \brief Loads the element values of all the Header Entries pointed in the
1155 * public Chained List.
1157 void gdcmParser::LoadHeaderEntries(void)
1160 for (ListTag::iterator i = GetListEntry().begin();
1161 i != GetListEntry().end();
1164 LoadHeaderEntry(*i);
1169 // Load 'non string' values
1170 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1171 if( PhotometricInterpretation == "PALETTE COLOR " )
1173 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1174 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1175 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1176 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1178 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1179 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1180 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1183 // --------------------------------------------------------------
1184 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1186 // if recognition code tells us we deal with a LibIDO image
1187 // we switch lineNumber and columnNumber
1189 std::string RecCode;
1190 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1191 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1192 RecCode == "CANRME_AILIBOD1_1." )
1194 filetype = ACR_LIBIDO;
1195 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1196 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1197 SetEntryByNumber(columns, 0x0028, 0x0010);
1198 SetEntryByNumber(rows , 0x0028, 0x0011);
1200 // ----------------- End of Special Patch ----------------
1204 * \ingroup gdcmParser
1205 * \brief Loads the element content if it's length is not bigger
1206 * than the value specified with
1207 * gdcmParser::SetMaxSizeLoadEntry()
1208 * @param Entry Header Entry (Dicom Element) to be dealt with
1210 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry)
1213 guint16 group = Entry->GetGroup();
1214 std::string vr= Entry->GetVR();
1215 guint32 length = Entry->GetLength();
1216 bool SkipLoad = false;
1218 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1220 // the test was commented out to 'go inside' the SeQuences
1221 // we don't any longer skip them !
1223 // if( vr == "SQ" ) // (DO NOT remove this comment)
1226 // A SeQuence "contains" a set of Elements.
1227 // (fffe e000) tells us an Element is beginning
1228 // (fffe e00d) tells us an Element just ended
1229 // (fffe e0dd) tells us the current SeQuence just ended
1230 if( group == 0xfffe )
1235 Entry->SetLength(0);
1236 Entry->SetValue("gdcm::Skipped");
1240 // When the length is zero things are easy:
1243 Entry->SetValue("");
1247 // The elements whose length is bigger than the specified upper bound
1248 // are not loaded. Instead we leave a short notice of the offset of
1249 // the element content and it's length.
1250 if (length > MaxSizeLoadEntry)
1252 std::ostringstream s;
1253 s << "gdcm::NotLoaded.";
1254 s << " Address:" << (long)Entry->GetOffset();
1255 s << " Length:" << Entry->GetLength();
1256 s << " x(" << std::hex << Entry->GetLength() << ")";
1257 Entry->SetValue(s.str());
1261 // When integer(s) are expected, read and convert the following
1262 // n *(two or four bytes)
1263 // properly i.e. as integers as opposed to a strings.
1264 // Elements with Value Multiplicity > 1
1265 // contain a set of integers (not a single one)
1267 // Any compacter code suggested (?)
1268 if ( IsHeaderEntryAnInteger(Entry) )
1271 std::ostringstream s;
1273 if (vr == "US" || vr == "SS")
1276 NewInt = ReadInt16();
1280 for (int i=1; i < nbInt; i++)
1283 NewInt = ReadInt16();
1289 else if (vr == "UL" || vr == "SL")
1292 NewInt = ReadInt32();
1296 for (int i=1; i < nbInt; i++)
1299 NewInt = ReadInt32();
1304 #ifdef GDCM_NO_ANSI_STRING_STREAM
1305 s << std::ends; // to avoid oddities on Solaris
1306 #endif //GDCM_NO_ANSI_STRING_STREAM
1307 Entry->SetValue(s.str());
1311 // We need an additional byte for storing \0 that is not on disk
1312 std::string NewValue(length,0);
1313 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1314 if ( item_read != 1 )
1316 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1317 Entry->SetValue("gdcm::UnRead");
1321 if( (vr == "UI") ) // Because of correspondance with the VR dic
1322 Entry->SetValue(NewValue.c_str());
1324 Entry->SetValue(NewValue);
1328 * \ingroup gdcmParser
1329 * \brief add a new Dicom Element pointer to
1330 * the H Table and to the chained List
1331 * \warning push_bash in listEntries ONLY during ParseHeader
1332 * \todo something to allow further Elements addition,
1333 * \ when position to be taken care of
1334 * @param newHeaderEntry
1336 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry)
1338 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1339 listEntries.push_back(newHeaderEntry);
1344 * \ingroup gdcmParser
1346 * @param Entry Header Entry whose length of the value shall be loaded.
1350 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry)
1352 guint16 element = Entry->GetElement();
1353 guint16 group = Entry->GetGroup();
1354 std::string vr = Entry->GetVR();
1356 if( (element == 0x0010) && (group == 0x7fe0) )
1359 dbg.Verbose(2, "gdcmParser::FindLength: ",
1360 "we reached 7fe0 0010");
1363 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1365 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1367 // The following reserved two bytes (see PS 3.5-2001, section
1368 // 7.1.2 Data element structure with explicit vr p27) must be
1369 // skipped before proceeding on reading the length on 4 bytes.
1370 fseek(fp, 2L, SEEK_CUR);
1371 guint32 length32 = ReadInt32();
1373 if ( (vr == "OB") && (length32 == 0xffffffff) )
1375 Entry->SetLength(FindHeaderEntryLengthOB());
1378 FixHeaderEntryFoundLength(Entry, length32);
1382 // Length is encoded on 2 bytes.
1383 length16 = ReadInt16();
1385 // We can tell the current file is encoded in big endian (like
1386 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1387 // and it's value is the one of the encoding of a big endian file.
1388 // In order to deal with such big endian encoded files, we have
1389 // (at least) two strategies:
1390 // * when we load the "Transfer Syntax" tag with value of big endian
1391 // encoding, we raise the proper flags. Then we wait for the end
1392 // of the META group (0x0002) among which is "Transfer Syntax",
1393 // before switching the swap code to big endian. We have to postpone
1394 // the switching of the swap code since the META group is fully encoded
1395 // in little endian, and big endian coding only starts at the next
1396 // group. The corresponding code can be hard to analyse and adds
1397 // many additional unnecessary tests for regular tags.
1398 // * the second strategy consists in waiting for trouble, that shall
1399 // appear when we find the first group with big endian encoding. This
1400 // is easy to detect since the length of a "Group Length" tag (the
1401 // ones with zero as element number) has to be of 4 (0x0004). When we
1402 // encounter 1024 (0x0400) chances are the encoding changed and we
1403 // found a group with big endian encoding.
1404 // We shall use this second strategy. In order to make sure that we
1405 // can interpret the presence of an apparently big endian encoded
1406 // length of a "Group Length" without committing a big mistake, we
1407 // add an additional check: we look in the already parsed elements
1408 // for the presence of a "Transfer Syntax" whose value has to be "big
1409 // endian encoding". When this is the case, chances are we have got our
1410 // hands on a big endian encoded file: we switch the swap code to
1411 // big endian and proceed...
1412 if ( (element == 0x0000) && (length16 == 0x0400) )
1414 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1416 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1421 SwitchSwapToBigEndian();
1422 // Restore the unproperly loaded values i.e. the group, the element
1423 // and the dictionary entry depending on them.
1424 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1425 guint16 CorrectElem = SwapShort(Entry->GetElement());
1426 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1430 // This correct tag is not in the dictionary. Create a new one.
1431 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1433 // FIXME this can create a memory leaks on the old entry that be
1434 // left unreferenced.
1435 Entry->SetDictEntry(NewTag);
1438 // Heuristic: well some files are really ill-formed.
1439 if ( length16 == 0xffff)
1442 //dbg.Verbose(0, "gdcmParser::FindLength",
1443 // "Erroneous element length fixed.");
1444 // Actually, length= 0xffff means that we deal with
1445 // Unknown Sequence Length
1448 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1453 // Either implicit VR or a non DICOM conformal (see not below) explicit
1454 // VR that ommited the VR of (at least) this element. Farts happen.
1455 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1456 // on Data elements "Implicit and Explicit VR Data Elements shall
1457 // not coexist in a Data Set and Data Sets nested within it".]
1458 // Length is on 4 bytes.
1459 FixHeaderEntryFoundLength(Entry, ReadInt32());
1465 * \ingroup gdcmParser
1466 * \brief Find the Value Representation of the current Dicom Element.
1469 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1471 if (filetype != ExplicitVR)
1477 long PositionOnEntry = ftell(fp);
1478 // Warning: we believe this is explicit VR (Value Representation) because
1479 // we used a heuristic that found "UL" in the first tag. Alas this
1480 // doesn't guarantee that all the tags will be in explicit VR. In some
1481 // cases (see e-film filtered files) one finds implicit VR tags mixed
1482 // within an explicit VR file. Hence we make sure the present tag
1483 // is in explicit VR and try to fix things if it happens not to be
1486 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1488 if(!CheckHeaderEntryVR(Entry,VR))
1490 fseek(fp, PositionOnEntry, SEEK_SET);
1491 // When this element is known in the dictionary we shall use, e.g. for
1492 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1493 // dictionary entry. Still we have to flag the element as implicit since
1494 // we know now our assumption on expliciteness is not furfilled.
1496 if ( Entry->IsVRUnknown() )
1497 Entry->SetVR("Implicit");
1498 Entry->SetImplicitVR();
1503 * \ingroup gdcmParser
1504 * \brief Check the correspondance between the VR of the header entry
1505 * and the taken VR. If they are different, the header entry is
1506 * updated with the new VR.
1509 * @return false if the VR is incorrect of if the VR isn't referenced
1510 * otherwise, it returns true
1512 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1514 char msg[100]; // for sprintf
1515 bool RealExplicit = true;
1517 // Assume we are reading a falsely explicit VR file i.e. we reached
1518 // a tag where we expect reading a VR but are in fact we read the
1519 // first to bytes of the length. Then we will interogate (through find)
1520 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1521 // both GCC and VC++ implementations of the STL map. Hence when the
1522 // expected VR read happens to be non-ascii characters we consider
1523 // we hit falsely explicit VR tag.
1525 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1526 RealExplicit = false;
1528 // CLEANME searching the dicom_vr at each occurence is expensive.
1529 // PostPone this test in an optional integrity check at the end
1530 // of parsing or only in debug mode.
1531 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1532 RealExplicit= false;
1534 if ( !RealExplicit )
1536 // We thought this was explicit VR, but we end up with an
1537 // implicit VR tag. Let's backtrack.
1538 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1539 Entry->GetGroup(),Entry->GetElement());
1540 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1545 if ( Entry->IsVRUnknown() )
1547 // When not a dictionary entry, we can safely overwrite the VR.
1550 else if ( Entry->GetVR() != vr )
1552 // The VR present in the file and the dictionary disagree. We assume
1553 // the file writer knew best and use the VR of the file. Since it would
1554 // be unwise to overwrite the VR of a dictionary (since it would
1555 // compromise it's next user), we need to clone the actual DictEntry
1556 // and change the VR for the read one.
1557 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1558 Entry->GetGroup(),Entry->GetElement(),
1559 vr,"FIXME",Entry->GetName());
1560 Entry->SetDictEntry(NewEntry);
1566 * \ingroup gdcmParser
1567 * \brief Get the transformed value of the header entry. The VR value
1568 * is used to define the transformation to operate on the value
1569 * \warning NOT end user intended method !
1571 * @return Transformed entry value
1573 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1575 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1577 std::string val=Entry->GetValue();
1578 std::string vr=Entry->GetVR();
1579 guint32 length = Entry->GetLength();
1580 std::ostringstream s;
1583 if (vr == "US" || vr == "SS")
1588 for (int i=0; i < nbInt; i++)
1592 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1593 NewInt16 = SwapShort(NewInt16);
1598 else if (vr == "UL" || vr == "SL")
1603 for (int i=0; i < nbInt; i++)
1607 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1608 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1609 NewInt32=SwapLong(NewInt32);
1614 #ifdef GDCM_NO_ANSI_STRING_STREAM
1615 s << std::ends; // to avoid oddities on Solaris
1616 #endif //GDCM_NO_ANSI_STRING_STREAM
1620 return(Entry->GetValue());
1624 * \ingroup gdcmParser
1625 * \brief Get the reverse transformed value of the header entry. The VR
1626 * value is used to define the reverse transformation to operate on
1628 * \warning NOT end user intended method !
1630 * @return Reverse transformed entry value
1632 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1634 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1636 std::string vr=Entry->GetVR();
1637 std::ostringstream s;
1638 std::vector<std::string> tokens;
1640 if (vr == "US" || vr == "SS")
1644 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1645 Tokenize (Entry->GetValue(), tokens, "\\");
1646 for (unsigned int i=0; i<tokens.size();i++)
1648 NewInt16 = atoi(tokens[i].c_str());
1649 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1653 if (vr == "UL" || vr == "SL")
1657 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1658 Tokenize (Entry->GetValue(), tokens, "\\");
1659 for (unsigned int i=0; i<tokens.size();i++)
1661 NewInt32 = atoi(tokens[i].c_str());
1662 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1663 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1668 #ifdef GDCM_NO_ANSI_STRING_STREAM
1669 s << std::ends; // to avoid oddities on Solaris
1670 #endif //GDCM_NO_ANSI_STRING_STREAM
1674 return(Entry->GetValue());
1678 * \ingroup gdcmParser
1679 * \brief Skip a given Header Entry
1680 * \warning NOT end user intended method !
1683 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1685 SkipBytes(entry->GetLength());
1689 * \ingroup gdcmParser
1690 * \brief When the length of an element value is obviously wrong (because
1691 * the parser went Jabberwocky) one can hope improving things by
1692 * applying this heuristic.
1694 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1696 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1698 if ( FoundLength == 0xffffffff)
1703 // Sorry for the patch!
1704 // XMedCom did the trick to read some nasty GE images ...
1705 else if (FoundLength == 13)
1707 // The following 'if' will be removed when there is no more
1708 // images on Creatis HDs with a 13 length for Manufacturer...
1709 if ( (Entry->GetGroup() != 0x0008) ||
1710 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ) {
1711 // end of remove area
1713 Entry->SetReadLength(10); // a bug is to be fixed
1717 // to fix some garbage 'Leonardo' Siemens images
1718 // May be commented out to avoid overhead
1719 else if ( (Entry->GetGroup() == 0x0009) &&
1720 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) )
1723 Entry->SetReadLength(4); // a bug is to be fixed
1727 // to try to 'go inside' SeQuences (with length), and not to skip them
1728 else if ( Entry->GetVR() == "SQ")
1730 if (enableSequences) // only if the user does want to !
1734 // a SeQuence Element is beginning
1735 // Let's forget it's length
1736 // (we want to 'go inside')
1738 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1739 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1740 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1741 // if we don't, we lost 28800 characters from the Header :-(
1743 else if(Entry->GetGroup() == 0xfffe)
1745 // sometimes, length seems to be wrong
1746 FoundLength =0; // some more clever checking to be done !
1748 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1749 // causes troubles :-(
1752 Entry->SetUsableLength(FoundLength);
1756 * \ingroup gdcmParser
1757 * \brief Apply some heuristics to predict wether the considered
1758 * element value contains/represents an integer or not.
1759 * @param Entry The element value on which to apply the predicate.
1760 * @return The result of the heuristical predicate.
1762 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry)
1764 guint16 element = Entry->GetElement();
1765 guint16 group = Entry->GetGroup();
1766 std::string vr = Entry->GetVR();
1767 guint32 length = Entry->GetLength();
1769 // When we have some semantics on the element we just read, and if we
1770 // a priori know we are dealing with an integer, then we shall be
1771 // able to swap it's element value properly.
1772 if ( element == 0 ) // This is the group length of the group
1778 std::ostringstream s;
1779 s << "Erroneous Group Length element length on :" \
1780 << std::hex << group << " , " << element;
1781 dbg.Error("gdcmParser::IsAnInteger",
1785 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1792 * \ingroup gdcmParser
1797 guint32 gdcmParser::FindHeaderEntryLengthOB(void)
1799 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1802 long PositionOnEntry = ftell(fp);
1803 bool FoundSequenceDelimiter = false;
1804 guint32 TotalLength = 0;
1807 while ( ! FoundSequenceDelimiter)
1813 TotalLength += 4; // We even have to decount the group and element
1815 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1817 char msg[100]; // for sprintf. Sorry
1818 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1819 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1823 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1824 FoundSequenceDelimiter = true;
1825 else if ( n != 0xe000 )
1827 char msg[100]; // for sprintf. Sorry
1828 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1830 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1834 ItemLength = ReadInt32();
1835 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1836 // the ItemLength with ReadInt32
1837 SkipBytes(ItemLength);
1839 fseek(fp, PositionOnEntry, SEEK_SET);
1844 * \ingroup gdcmParser
1845 * \brief Reads a supposed to be 16 Bits integer
1846 * \ (swaps it depending on processor endianity)
1848 * @return integer acts as a boolean
1850 guint16 gdcmParser::ReadInt16(void)
1854 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1855 if ( item_read != 1 )
1858 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1868 * \ingroup gdcmParser
1869 * \brief Reads a supposed to be 32 Bits integer
1870 * \ (swaps it depending on processor endianity)
1874 guint32 gdcmParser::ReadInt32(void)
1878 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1879 if ( item_read != 1 )
1882 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1892 * \ingroup gdcmParser
1897 void gdcmParser::SkipBytes(guint32 NBytes)
1899 //FIXME don't dump the returned value
1900 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1904 * \ingroup gdcmParser
1907 void gdcmParser::Initialise(void)
1909 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1910 RefShaDict = (gdcmDict*)0;
1914 * \ingroup gdcmParser
1915 * \brief Discover what the swap code is (among little endian, big endian,
1916 * bad little endian, bad big endian).
1919 void gdcmParser::CheckSwap()
1921 // Fourth semantics:
1923 // ---> Warning : This fourth field is NOT part
1924 // of the 'official' Dicom Dictionnary
1925 // and should NOT be used.
1926 // (Not defined for all the groups
1927 // may be removed in a future release)
1930 // META Meta Information
1942 // NMI Nuclear Medicine
1944 // BFS Basic Film Session
1945 // BFB Basic Film Box
1946 // BIB Basic Image Box
1961 // The only guaranted way of finding the swap code is to find a
1962 // group tag since we know it's length has to be of four bytes i.e.
1963 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1964 // occurs when we can't find such group...
1966 guint32 x=4; // x : for ntohs
1967 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1971 char deb[HEADER_LENGTH_TO_READ];
1973 // First, compare HostByteOrder and NetworkByteOrder in order to
1974 // determine if we shall need to swap bytes (i.e. the Endian type).
1979 //cout << net2host << endl;
1981 // The easiest case is the one of a DICOM header, since it possesses a
1982 // file preamble where it suffice to look for the string "DICM".
1983 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1986 if(memcmp(entCur, "DICM", (size_t)4) == 0)
1988 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
1989 // Next, determine the value representation (VR). Let's skip to the
1990 // first element (0002, 0000) and check there if we find "UL"
1991 // - or "OB" if the 1st one is (0002,0001) -,
1992 // in which case we (almost) know it is explicit VR.
1993 // WARNING: if it happens to be implicit VR then what we will read
1994 // is the length of the group. If this ascii representation of this
1995 // length happens to be "UL" then we shall believe it is explicit VR.
1996 // FIXME: in order to fix the above warning, we could read the next
1997 // element value (or a couple of elements values) in order to make
1998 // sure we are not commiting a big mistake.
1999 // We need to skip :
2000 // * the 128 bytes of File Preamble (often padded with zeroes),
2001 // * the 4 bytes of "DICM" string,
2002 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2003 // i.e. a total of 136 bytes.
2006 // Use gdcmParser::dicom_vr to test all the possibilities
2007 // instead of just checking for UL, OB and UI !?
2008 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2009 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2010 (memcmp(entCur, "UI", (size_t)2) == 0) )
2012 filetype = ExplicitVR;
2013 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2014 "explicit Value Representation");
2018 filetype = ImplicitVR;
2019 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2020 "not an explicit Value Representation");
2025 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2026 "HostByteOrder != NetworkByteOrder");
2031 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2032 "HostByteOrder = NetworkByteOrder");
2035 // Position the file position indicator at first tag (i.e.
2036 // after the file preamble and the "DICM" string).
2038 fseek (fp, 132L, SEEK_SET);
2042 // Alas, this is not a DicomV3 file and whatever happens there is no file
2043 // preamble. We can reset the file position indicator to where the data
2044 // is (i.e. the beginning of the file).
2045 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2048 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2049 // By clean we mean that the length of the first tag is written down.
2050 // If this is the case and since the length of the first group HAS to be
2051 // four (bytes), then determining the proper swap code is straightforward.
2054 // We assume the array of char we are considering contains the binary
2055 // representation of a 32 bits integer. Hence the following dirty
2057 s = *((guint32 *)(entCur));
2078 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2079 "ACR/NEMA unfound swap info (time to raise bets)");
2082 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2083 // It is time for despaired wild guesses. So, let's assume this file
2084 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
2085 // not present. Then the only info we have is the net2host one.
2095 * \ingroup gdcmParser
2098 void gdcmParser::SwitchSwapToBigEndian(void)
2100 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2101 "Switching to BigEndian mode.");
2122 * \ingroup gdcmParser
2127 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2131 if ((guint32)NewSize >= (guint32)0xffffffff)
2133 MaxSizeLoadEntry = 0xffffffff;
2136 MaxSizeLoadEntry = NewSize;
2140 * \ingroup gdcmParser
2141 * \brief Searches both the public and the shadow dictionary (when they
2142 * exist) for the presence of the DictEntry with given name.
2143 * The public dictionary has precedence on the shadow one.
2144 * @param Name name of the searched DictEntry
2145 * @return Corresponding DictEntry when it exists, NULL otherwise.
2147 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2149 gdcmDictEntry *found = (gdcmDictEntry *)0;
2150 if (!RefPubDict && !RefShaDict)
2152 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2153 "we SHOULD have a default dictionary");
2157 found = RefPubDict->GetDictEntryByName(Name);
2163 found = RefShaDict->GetDictEntryByName(Name);
2171 * \ingroup gdcmParser
2172 * \brief Searches both the public and the shadow dictionary (when they
2173 * exist) for the presence of the DictEntry with given
2174 * group and element. The public dictionary has precedence on the
2176 * @param group group of the searched DictEntry
2177 * @param element element of the searched DictEntry
2178 * @return Corresponding DictEntry when it exists, NULL otherwise.
2180 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2182 gdcmDictEntry *found = (gdcmDictEntry *)0;
2183 if (!RefPubDict && !RefShaDict)
2185 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2186 "we SHOULD have a default dictionary");
2190 found = RefPubDict->GetDictEntryByNumber(group, element);
2196 found = RefShaDict->GetDictEntryByNumber(group, element);
2204 * \ingroup gdcmParser
2205 * \brief Read the next tag but WITHOUT loading it's value
2206 * @return On succes the newly created HeaderEntry, NULL on failure.
2208 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void)
2211 gdcmHeaderEntry *NewEntry;
2217 // We reached the EOF (or an error occured) and header parsing
2218 // has to be considered as finished.
2219 return (gdcmHeaderEntry *)0;
2221 NewEntry = NewHeaderEntryByNumber(g, n);
2222 FindHeaderEntryVR(NewEntry);
2223 FindHeaderEntryLength(NewEntry);
2230 NewEntry->SetOffset(ftell(fp));
2231 //if ( (g==0x7fe0) && (n==0x0010) )
2236 * \ingroup gdcmParser
2237 * \brief Build a new Element Value from all the low level arguments.
2238 * Check for existence of dictionary entry, and build
2239 * a default one when absent.
2240 * @param Name Name of the underlying DictEntry
2242 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2244 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2246 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2248 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2251 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2252 "failed to allocate gdcmHeaderEntry");
2253 return (gdcmHeaderEntry *)0;
2259 * \ingroup gdcmParser
2260 * \brief Request a new virtual dict entry to the dict set
2261 * @param group group of the underlying DictEntry
2262 * @param elem element of the underlying DictEntry
2263 * @param vr VR of the underlying DictEntry
2264 * @param fourth owner group
2265 * @param name english name
2267 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2272 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2276 * \ingroup gdcmParser
2277 * \brief Build a new Element Value from all the low level arguments.
2278 * Check for existence of dictionary entry, and build
2279 * a default one when absent.
2280 * @param Group group of the underlying DictEntry
2281 * @param Elem element of the underlying DictEntry
2283 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2285 // Find out if the tag we encountered is in the dictionaries:
2286 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2288 DictEntry = NewVirtualDictEntry(Group, Elem);
2290 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2293 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2294 "failed to allocate gdcmHeaderEntry");
2301 * \ingroup gdcmParser
2302 * \brief Small utility function that creates a new manually crafted
2303 * (as opposed as read from the file) gdcmHeaderEntry with user
2304 * specified name and adds it to the public tag hash table.
2305 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2306 * @param NewTagName The name to be given to this new tag.
2307 * @param VR The Value Representation to be given to this new tag.
2308 * @return The newly hand crafted Element Value.
2310 gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2313 gdcmHeaderEntry *NewEntry = NULL;
2314 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2315 guint32 FreeElem = 0;
2316 gdcmDictEntry *DictEntry = NULL;
2318 FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2319 if (FreeElem == UINT32_MAX)
2321 dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2322 "Group 0xffff in Public Dict is full");
2326 DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2327 VR, "GDCM", NewTagName);
2328 NewEntry = new gdcmHeaderEntry(DictEntry);
2329 AddHeaderEntry(NewEntry);
2334 * \ingroup gdcmParser
2335 * \brief Generate a free TagKey i.e. a TagKey that is not present
2336 * in the TagHt dictionary.
2337 * @param group The generated tag must belong to this group.
2338 * @return The element of tag with given group which is fee.
2340 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2342 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2344 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2345 if (tagHT.count(key) == 0)
2351 //-----------------------------------------------------------------------------