2 //-----------------------------------------------------------------------------
3 #include "gdcmParser.h"
11 #include <netinet/in.h>
14 #ifdef GDCM_NO_ANSI_STRING_STREAM
16 # define ostringstream ostrstream
21 //-----------------------------------------------------------------------------
22 // Refer to gdcmParser::CheckSwap()
23 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
25 // Refer to gdcmParser::SetMaxSizeLoadElementValue()
26 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
28 //-----------------------------------------------------------------------------
29 // Constructor / Destructor
34 * @param exception_on_error
35 * @param enable_sequences = true to allow the header
36 * to be parsed *inside* the SeQuences,
37 * when they have an actual length
38 *\TODO may be we need one more bool,
39 * to allow skipping the private elements while parsing the header
40 * in order to save space
42 gdcmParser::gdcmParser(const char *InFilename,
43 bool exception_on_error,
44 bool enable_sequences )
46 enableSequences=enable_sequences;
48 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
49 filename = InFilename;
52 if ( !OpenFile(exception_on_error))
58 wasUpdated = 0; // will be set to 1 if user adds an entry
59 printLevel = 1; // 'Heavy' header print by default
65 * @param exception_on_error
67 gdcmParser::gdcmParser(bool exception_on_error)
71 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
74 wasUpdated = 0; // will be set to 1 if user adds an entry
75 printLevel = 1; // 'Heavy' header print by default
80 * \brief Canonical destructor.
82 gdcmParser::~gdcmParser (void)
88 //-----------------------------------------------------------------------------
92 * \brief Prints the Header Entries (Dicom Elements)
93 * both from the H Table and the chained list
96 void gdcmParser::PrintPubEntry(std::ostream & os)
100 s << "------------ using listEntries ----------------" << std::endl;
101 for (ListTag::iterator i = listEntries.begin();
102 i != listEntries.end();
105 (*i)->SetPrintLevel(printLevel);
112 * \ingroup gdcmParser
113 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
116 void gdcmParser::PrintPubDict(std::ostream & os)
118 RefPubDict->Print(os);
122 * \ingroup gdcmParser
123 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
126 void gdcmParser::PrintShaDict(std::ostream & os)
128 RefShaDict->Print(os);
131 //-----------------------------------------------------------------------------
134 * \ingroup gdcmParser
135 * \brief Get the public dictionary used
137 gdcmDict *gdcmParser::GetPubDict(void)
143 * \ingroup gdcmParser
144 * \brief Get the shadow dictionary used
146 gdcmDict *gdcmParser::GetShaDict(void)
152 * \ingroup gdcmParser
153 * \brief Set the shadow dictionary used
154 * \param dict dictionary to use in shadow
156 bool gdcmParser::SetShaDict(gdcmDict *dict)
163 * \ingroup gdcmParser
164 * \brief Set the shadow dictionary used
165 * \param dictName name of the dictionary to use in shadow
167 bool gdcmParser::SetShaDict(DictKey dictName)
169 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
174 * \ingroup gdcmParser
175 * \brief This predicate, based on hopefully reasonable heuristics,
176 * decides whether or not the current gdcmParser was properly parsed
177 * and contains the mandatory information for being considered as
178 * a well formed and usable Dicom/Acr File.
179 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
182 bool gdcmParser::IsReadable(void)
184 std::string res = GetEntryByNumber(0x0028, 0x0005);
185 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
187 return false; // Image Dimensions
190 if ( !GetHeaderEntryByNumber(0x0028, 0x0100) )
191 return false; // "Bits Allocated"
192 if ( !GetHeaderEntryByNumber(0x0028, 0x0101) )
193 return false; // "Bits Stored"
194 if ( !GetHeaderEntryByNumber(0x0028, 0x0102) )
195 return false; // "High Bit"
196 if ( !GetHeaderEntryByNumber(0x0028, 0x0103) )
197 return false; // "Pixel Representation"
202 * \ingroup gdcmParser
203 * \brief Determines if the Transfer Syntax was already encountered
204 * and if it corresponds to a ImplicitVRLittleEndian one.
206 * @return True when ImplicitVRLittleEndian found. False in all other cases.
208 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void)
210 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
213 LoadHeaderEntrySafe(Element);
215 std::string Transfer = Element->GetValue();
216 if ( Transfer == "1.2.840.10008.1.2" )
222 * \ingroup gdcmParser
223 * \brief Determines if the Transfer Syntax was already encountered
224 * and if it corresponds to a ExplicitVRLittleEndian one.
226 * @return True when ExplicitVRLittleEndian found. False in all other cases.
228 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void)
230 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
233 LoadHeaderEntrySafe(Element);
235 std::string Transfer = Element->GetValue();
236 if ( Transfer == "1.2.840.10008.1.2.1" )
242 * \ingroup gdcmParser
243 * \brief Determines if the Transfer Syntax was already encountered
244 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
246 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
248 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
250 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
253 LoadHeaderEntrySafe(Element);
255 std::string Transfer = Element->GetValue();
256 if ( Transfer == "1.2.840.10008.1.2.1.99" )
262 * \ingroup gdcmParser
263 * \brief Determines if the Transfer Syntax was already encountered
264 * and if it corresponds to a Explicit VR Big Endian one.
266 * @return True when big endian found. False in all other cases.
268 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void)
270 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
273 LoadHeaderEntrySafe(Element);
275 std::string Transfer = Element->GetValue();
276 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
282 * \ingroup gdcmParser
283 * \brief returns the File Type
284 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
287 FileType gdcmParser::GetFileType(void) {
292 * \ingroup gdcmParser
293 * \brief opens the file
294 * @param exception_on_error
297 FILE *gdcmParser::OpenFile(bool exception_on_error)
300 fp=fopen(filename.c_str(),"rb");
301 if(exception_on_error)
304 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
310 fread(&zero, (size_t)2, (size_t)1, fp);
312 //ACR -- or DICOM with no Preamble --
313 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
317 fseek(fp, 126L, SEEK_CUR);
319 fread(dicm, (size_t)4, (size_t)1, fp);
320 if( memcmp(dicm, "DICM", 4) == 0 )
324 dbg.Verbose(0, "gdcmParser::gdcmParser not DICOM/ACR", filename.c_str());
327 std::cerr<<filename.c_str()<<std::endl;
328 dbg.Verbose(0, "gdcmParser::gdcmParser cannot open file", filename.c_str());
334 * \ingroup gdcmParser
335 * \brief closes the file
336 * @return TRUE if the close was successfull
338 bool gdcmParser::CloseFile(void)
340 int closed = fclose(fp);
348 * \ingroup gdcmParser
350 * @param fp file pointer on an already open file
351 * @param type type of the File to be written
352 * (ACR-NEMA, ExplicitVR, ImplicitVR)
353 * @return always "True" ?!
355 bool gdcmParser::Write(FILE *fp, FileType type)
358 // TODO The stuff has been rewritten using the chained list instead
360 // so we could remove the GroupHT from the gdcmParser
364 // TODO : move the following lines (and a lot of others, to be written)
365 // to a future function CheckAndCorrectHeader
368 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
369 // (FileType est un champ de gdcmParser ...)
370 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
372 // a moins de se livrer a un tres complique ajout des champs manquants.
373 // faire un CheckAndCorrectHeader (?)
376 if (type == ImplicitVR)
378 std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
379 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
381 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
382 // values with a VR of UI shall be padded with a single trailing null
383 // Dans le cas suivant on doit pader manuellement avec un 0
385 SetEntryLengthByNumber(18, 0x0002, 0x0010);
388 if (type == ExplicitVR)
390 std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
391 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
393 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
394 // values with a VR of UI shall be padded with a single trailing null
395 // Dans le cas suivant on doit pader manuellement avec un 0
397 SetEntryLengthByNumber(20, 0x0002, 0x0010);
401 if ( (type == ImplicitVR) || (type == ExplicitVR) )
402 UpdateGroupLength(false,type);
404 UpdateGroupLength(true,ACR);
406 WriteEntries(type, fp);
411 * \ingroup gdcmParser
412 * \brief Modifies the value of a given Header Entry (Dicom Element)
413 * if it exists; Creates it with the given value if it doesn't
414 * @param Value passed as a std::string
419 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
420 guint16 Group, guint16 Elem )
422 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
423 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
428 SetEntryByNumber(Value, Group, Elem);
433 * \ingroup gdcmParser
434 * \brief Modifies the value of a given Header Entry (Dicom Element)
435 * if it exists; Creates it with the given value if it doesn't
436 * @param Value passed as a char*
442 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem )
444 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
449 AddHeaderEntry(nvHeaderEntry);
451 std::string v = Value;
452 SetEntryByNumber(v, Group, Elem);
457 * \ingroup gdcmParser
458 * \brief Set a new value if the invoked element exists
459 * Seems to be useless !!!
465 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
467 std::string v = Value;
468 SetEntryByNumber(v, Group, Elem);
472 //-----------------------------------------------------------------------------
475 * \ingroup gdcmParser
476 * \brief Checks if a given Dicom Element exists
477 * \ within the H table
478 * @param group Group number of the searched Dicom Element
479 * @param element Element number of the searched Dicom Element
480 * @return number of occurences
482 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element )
484 std::string key = gdcmDictEntry::TranslateToKey(group, element );
485 return (tagHT.count(key));
489 * \ingroup gdcmParser
490 * \brief Searches within Header Entries (Dicom Elements) parsed with
491 * the public and private dictionaries
492 * for the element value of a given tag.
493 * \warning Don't use any longer : use GetPubEntryByName
494 * @param tagName name of the searched element.
495 * @return Corresponding element value when it exists,
496 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
498 std::string gdcmParser::GetEntryByName(std::string tagName)
500 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
501 if( dictEntry == NULL)
504 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
508 * \ingroup gdcmParser
509 * \brief Searches within Header Entries (Dicom Elements) parsed with
510 * the public and private dictionaries
511 * for the element value representation of a given tag.
513 * Obtaining the VR (Value Representation) might be needed by caller
514 * to convert the string typed content to caller's native type
515 * (think of C++ vs Python). The VR is actually of a higher level
516 * of semantics than just the native C++ type.
517 * @param tagName name of the searched element.
518 * @return Corresponding element value representation when it exists,
519 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
521 std::string gdcmParser::GetEntryVRByName(std::string tagName)
523 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
524 if( dictEntry == NULL)
527 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
528 dictEntry->GetElement());
529 return elem->GetVR();
533 * \ingroup gdcmParser
534 * \brief Searches within Header Entries (Dicom Elements) parsed with
535 * the public and private dictionaries
536 * for the element value representation of a given tag.
537 * @param group Group of the searched tag.
538 * @param element Element of the searched tag.
539 * @return Corresponding element value representation when it exists,
540 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
542 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element)
544 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
545 if ( ! tagHT.count(key))
547 return tagHT.find(key)->second->GetValue();
551 * \ingroup gdcmParser
552 * \brief Searches within Header Entries (Dicom Elements) parsed with
553 * the public and private dictionaries
554 * for the element value representation of a given tag..
556 * Obtaining the VR (Value Representation) might be needed by caller
557 * to convert the string typed content to caller's native type
558 * (think of C++ vs Python). The VR is actually of a higher level
559 * of semantics than just the native C++ type.
560 * @param group Group of the searched tag.
561 * @param element Element of the searched tag.
562 * @return Corresponding element value representation when it exists,
563 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
565 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element)
567 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
570 return elem->GetVR();
574 * \ingroup gdcmParser
575 * \brief Sets the value (string) of the Header Entry (Dicom Element)
576 * @param content string value of the Dicom Element
577 * @param tagName name of the searched Dicom Element.
578 * @return true when found
580 bool gdcmParser::SetEntryByName(std::string content,std::string tagName)
582 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
583 if( dictEntry == NULL)
586 return(SetEntryByNumber(content,dictEntry->GetGroup(),
587 dictEntry->GetElement()));
591 * \ingroup gdcmParser
592 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
593 * through it's (group, element) and modifies it's content with
595 * \warning Don't use any longer : use SetPubEntryByNumber
596 * @param content new value to substitute with
597 * @param group group of the Dicom Element to modify
598 * @param element element of the Dicom Element to modify
600 bool gdcmParser::SetEntryByNumber(std::string content,
604 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
605 if ( ! tagHT.count(key))
607 int l = content.length();
608 if(l%2) // Odd length are padded with a space (020H).
611 content = content + '\0';
614 //tagHT[key]->SetValue(content);
617 TagHeaderEntryHT::iterator p2;
618 // DO NOT remove the following lines : they explain the stuff
619 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
620 //p2=p.first; // iterator on the first synonym
621 //a=p2->second; // H Table target column (2-nd col)
624 a = ((tagHT.equal_range(key)).first)->second;
626 a-> SetValue(content);
628 //std::string vr = tagHT[key]->GetVR();
629 std::string vr = a->GetVR();
632 if( (vr == "US") || (vr == "SS") )
634 else if( (vr == "UL") || (vr == "SL") )
639 //tagHT[key]->SetLength(lgr);
645 * \ingroup gdcmParser
646 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
647 * in the PubHeaderEntrySet of this instance
648 * through it's (group, element) and modifies it's length with
650 * \warning Use with extreme caution.
651 * @param length new length to substitute with
652 * @param group group of the entry to modify
653 * @param element element of the Entry to modify
654 * @return 1 on success, 0 otherwise.
657 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
658 guint16 group, guint16 element)
660 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
661 if ( ! tagHT.count(key))
663 if (length%2) length++; // length must be even
664 //tagHT[key]->SetLength(length);
665 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
671 * \ingroup gdcmParser
672 * \brief Gets (from Header) the offset of a 'non string' element value
673 * \ (LoadElementValues has already be executed)
676 * @return File Offset of the Element Value
678 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
680 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
683 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
684 "failed to Locate gdcmHeaderEntry");
687 return Entry->GetOffset();
691 * \ingroup gdcmParser
692 * \brief Gets (from Header) a 'non string' element value
693 * \ (LoadElementValues has already be executed)
696 * @return Pointer to the 'non string' area
698 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
700 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
703 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
704 "failed to Locate gdcmHeaderEntry");
707 return Entry->GetVoidArea();
711 * \ingroup gdcmParser
712 * \brief Loads (from disk) the element content
713 * when a string is not suitable
715 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
717 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
720 size_t o =(size_t)Element->GetOffset();
721 fseek(fp, o, SEEK_SET);
722 int l=Element->GetLength();
723 void * a = malloc(l);
727 SetEntryVoidAreaByNumber(a, Group, Elem);
728 // TODO check the result
729 size_t l2 = fread(a, 1, l ,fp);
739 * \ingroup gdcmParser
740 * \brief Sets a 'non string' value to a given Dicom Element
742 * @param group Group number of the searched Dicom Element
743 * @param element Element number of the searched Dicom Element
746 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,guint16 group, guint16 element)
748 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
749 if ( ! tagHT.count(key))
751 //tagHT[key]->SetVoidArea(area);
752 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
757 * \ingroup gdcmParser
758 * \brief Update the entries with the shadow dictionary. Only odd entries are
761 void gdcmParser::UpdateShaEntries(void)
766 gdcmDictEntry *entry;
769 for(ListTag::iterator it=listEntries.begin();
770 it!=listEntries.end();
773 // Odd group => from public dictionary
774 if((*it)->GetGroup()%1==0)
777 // Peer group => search the corresponding dict entry
778 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
781 (*it)->SetDictEntry(entry);
783 CheckHeaderEntryVR(*it,vr);
789 * \ingroup gdcmParser
790 * \brief Searches within the Header Entries for a Dicom Element of
792 * @param tagName name of the searched Dicom Element.
793 * @return Corresponding Dicom Element when it exists, and NULL
796 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName)
798 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
799 if( dictEntry == NULL)
802 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
806 * \ingroup gdcmParser
807 * \brief retrieves a Dicom Element (the first one) using (group, element)
808 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
809 * if you think it's NOT UNIQUE, check the count number
810 * and use iterators to retrieve ALL the Dicoms Elements within
811 * a given couple (group, element)
812 * @param group Group number of the searched Dicom Element
813 * @param element Element number of the searched Dicom Element
816 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
818 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
819 if ( ! tagHT.count(key))
821 return tagHT.find(key)->second;
825 * \ingroup gdcmParser
826 * \brief Loads the element while preserving the current
827 * underlying file position indicator as opposed to
828 * to LoadHeaderEntry that modifies it.
829 * @param entry Header Entry whose value shall be loaded.
832 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry)
834 long PositionOnEntry = ftell(fp);
835 LoadHeaderEntry(entry);
836 fseek(fp, PositionOnEntry, SEEK_SET);
840 * \ingroup gdcmParser
841 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
842 * \warning : to be re-written using the chained list instead of the H table.
843 * \warning : DO NOT use (doesn't work any longer because of the multimap)
844 * \todo : to be re-written using the chained list instead of the H table
845 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
846 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
848 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type)
853 gdcmHeaderEntry *elem;
855 std::string str_trash;
858 GroupHT groupHt; // to hold the length of each group
861 // typedef std::map<GroupKey, int> GroupHT;
863 gdcmHeaderEntry *elemZ;
865 // for each Tag in the DCM Header
867 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
872 gr = elem->GetGroup();
873 el = elem->GetElement();
876 sprintf(trash, "%04x", gr);
877 key = trash; // generate 'group tag'
879 // if the caller decided not to take SEQUENCEs into account
880 // e.g : he wants to write an ACR-NEMA File
882 if (SkipSequence && vr == "SQ")
885 // Still unsolved problem :
886 // we cannot find the 'Sequence Delimitation Item'
887 // since it's at the end of the Hash Table
890 // pas SEQUENCE en ACR-NEMA
892 // --> la descente a l'interieur' des SQ
893 // devrait etre faite avec une liste chainee, pas avec une HTable...
895 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
897 if (el == 0x0000) // the first elem is 0x0000
899 groupHt[key] = 0; // initialize group length
903 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
906 else // any elem but the first
908 if (type == ExplicitVR)
910 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
912 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
915 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
919 unsigned short int gr_bid;
921 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
925 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
926 // warning: unsigned int format, different type arg
927 sscanf(g->first.c_str(),"%x",&gr_bid);
928 tk = g->first + "|0000"; // generate the element full tag
930 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
932 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
933 elemZ = new gdcmHeaderEntry(tagZ);
935 AddHeaderEntry(elemZ); // create it
939 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
941 sprintf(trash ,"%d",g->second);
943 elemZ->SetValue(str_trash);
948 * \ingroup gdcmParser
949 * \brief writes on disc according to the requested format
950 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
951 * \ warning does NOT add the missing elements in the header :
952 * \ it's up to the user doing it !
953 * \ (function CheckHeaderCoherence to be written)
954 * @param type type of the File to be written
955 * (ACR-NEMA, ExplicitVR, ImplicitVR)
956 * @param _fp already open file pointer
958 void gdcmParser::WriteEntries(FileType type, FILE * _fp)
967 std::vector<std::string> tokens;
969 // uses now listEntries to iterate, not TagHt!
971 // pb : gdcmParser.Add does NOT update listEntries
972 // TODO : find a trick (in STL?) to do it, at low cost !
976 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
978 for (ListTag::iterator tag2=listEntries.begin();
979 tag2 != listEntries.end();
982 gr = (*tag2)->GetGroup();
983 el = (*tag2)->GetElement();
984 lgr = (*tag2)->GetLength();
985 val = (*tag2)->GetValue().c_str();
986 vr = (*tag2)->GetVR();
990 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
991 if (gr %2) continue; // ignore shadow groups
992 if (vr == "SQ" ) continue; // ignore Sequences
993 // TODO : find a trick to *skip* the SeQuences !
994 // Not only ignore the SQ element
995 if (gr == 0xfffe ) continue; // ignore delimiters
998 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
999 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1001 if ( (type == ExplicitVR) && (gr <= 0x0002) )
1004 guint16 z=0, shortLgr;
1005 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1007 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1009 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1010 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1016 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1021 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1024 if (vr == "US" || vr == "SS")
1026 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1027 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1028 for (unsigned int i=0; i<tokens.size();i++)
1030 val_uint16 = atoi(tokens[i].c_str());
1032 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1037 if (vr == "UL" || vr == "SL")
1039 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1040 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1041 for (unsigned int i=0; i<tokens.size();i++)
1043 val_uint32 = atoi(tokens[i].c_str());
1045 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1050 // Pixels are never loaded in the element !
1051 if ((gr == 0x7fe0) && (el == 0x0010) )
1054 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1059 * \ingroup gdcmParser
1060 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1062 * @return The properly swaped 32 bits integer.
1064 guint32 gdcmParser::SwapLong(guint32 a)
1071 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1072 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1076 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1080 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1083 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1090 * \ingroup gdcmParser
1091 * \brief Swaps the bytes so they agree with the processor order
1092 * @return The properly swaped 16 bits integer.
1094 guint16 gdcmParser::SwapShort(guint16 a)
1096 if ( (sw==4321) || (sw==2143) )
1097 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1101 //-----------------------------------------------------------------------------
1104 * \ingroup gdcmParser
1105 * \brief Parses the header of the file but WITHOUT loading element values.
1107 void gdcmParser::Parse(bool exception_on_error) throw(gdcmFormatError)
1109 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1113 while ( (newHeaderEntry = ReadNextHeaderEntry()) )
1115 SkipHeaderEntry(newHeaderEntry);
1116 AddHeaderEntry(newHeaderEntry);
1121 * \ingroup gdcmParser
1122 * \brief Loads the element values of all the Header Entries pointed in the
1123 * public Chained List.
1125 void gdcmParser::LoadHeaderEntries(void)
1128 for (ListTag::iterator i = GetListEntry().begin();
1129 i != GetListEntry().end();
1132 LoadHeaderEntry(*i);
1137 // Load 'non string' values
1138 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1139 if( PhotometricInterpretation == "PALETTE COLOR " )
1141 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1142 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1143 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1144 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1146 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1147 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1148 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1151 // --------------------------------------------------------------
1152 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1154 // if recognition code tells us we deal with a LibIDO image
1155 // we switch lineNumber and columnNumber
1157 std::string RecCode;
1158 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1159 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1160 RecCode == "CANRME_AILIBOD1_1." )
1162 filetype = ACR_LIBIDO;
1163 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1164 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1165 SetEntryByNumber(columns, 0x0028, 0x0010);
1166 SetEntryByNumber(rows , 0x0028, 0x0011);
1168 // ----------------- End of Special Patch ----------------
1172 * \ingroup gdcmParser
1173 * \brief Loads the element content if it's length is not bigger
1174 * than the value specified with
1175 * gdcmParser::SetMaxSizeLoadEntry()
1176 * @param Entry Header Entry (Dicom Element) to be dealt with
1178 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry)
1181 guint16 group = Entry->GetGroup();
1182 std::string vr= Entry->GetVR();
1183 guint32 length = Entry->GetLength();
1184 bool SkipLoad = false;
1186 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1188 // the test was commented out to 'go inside' the SeQuences
1189 // we don't any longer skip them !
1191 // if( vr == "SQ" ) // (DO NOT remove this comment)
1194 // A SeQuence "contains" a set of Elements.
1195 // (fffe e000) tells us an Element is beginning
1196 // (fffe e00d) tells us an Element just ended
1197 // (fffe e0dd) tells us the current SeQuence just ended
1198 if( group == 0xfffe )
1203 Entry->SetLength(0);
1204 Entry->SetValue("gdcm::Skipped");
1208 // When the length is zero things are easy:
1211 Entry->SetValue("");
1215 // The elements whose length is bigger than the specified upper bound
1216 // are not loaded. Instead we leave a short notice of the offset of
1217 // the element content and it's length.
1218 if (length > MaxSizeLoadEntry)
1220 std::ostringstream s;
1221 s << "gdcm::NotLoaded.";
1222 s << " Address:" << (long)Entry->GetOffset();
1223 s << " Length:" << Entry->GetLength();
1224 s << " x(" << std::hex << Entry->GetLength() << ")";
1225 Entry->SetValue(s.str());
1229 // When integer(s) are expected, read and convert the following
1230 // n *(two or four bytes)
1231 // properly i.e. as integers as opposed to a strings.
1232 // Elements with Value Multiplicity > 1
1233 // contain a set of integers (not a single one)
1235 // Any compacter code suggested (?)
1236 if ( IsHeaderEntryAnInteger(Entry) )
1239 std::ostringstream s;
1241 if (vr == "US" || vr == "SS")
1244 NewInt = ReadInt16();
1248 for (int i=1; i < nbInt; i++)
1251 NewInt = ReadInt16();
1257 else if (vr == "UL" || vr == "SL")
1260 NewInt = ReadInt32();
1264 for (int i=1; i < nbInt; i++)
1267 NewInt = ReadInt32();
1272 #ifdef GDCM_NO_ANSI_STRING_STREAM
1273 s << std::ends; // to avoid oddities on Solaris
1274 #endif //GDCM_NO_ANSI_STRING_STREAM
1275 Entry->SetValue(s.str());
1279 // We need an additional byte for storing \0 that is not on disk
1280 char* NewValue = (char*)malloc(length+1);
1283 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
1286 NewValue[length]= 0;
1288 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
1289 if ( item_read != 1 )
1292 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1293 Entry->SetValue("gdcm::UnRead");
1296 Entry->SetValue(NewValue);
1301 * \ingroup gdcmParser
1302 * \brief add a new Dicom Element pointer to
1303 * the H Table and to the chained List
1304 * \warning push_bash in listEntries ONLY during ParseHeader
1305 * \todo something to allow further Elements addition,
1306 * \ when position to be taken care of
1307 * @param newHeaderEntry
1309 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry * newHeaderEntry)
1311 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1312 listEntries.push_back(newHeaderEntry);
1317 * \ingroup gdcmParser
1319 * @param Entry Header Entry whose length of the value shall be loaded.
1323 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry * Entry)
1325 guint16 element = Entry->GetElement();
1326 guint16 group = Entry->GetGroup();
1327 std::string vr = Entry->GetVR();
1329 if( (element == 0x0010) && (group == 0x7fe0) )
1332 dbg.Verbose(2, "gdcmParser::FindLength: ",
1333 "we reached 7fe0 0010");
1336 if ( (filetype == ExplicitVR) && ! Entry->IsImplicitVr() )
1338 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1340 // The following reserved two bytes (see PS 3.5-2001, section
1341 // 7.1.2 Data element structure with explicit vr p27) must be
1342 // skipped before proceeding on reading the length on 4 bytes.
1343 fseek(fp, 2L, SEEK_CUR);
1344 guint32 length32 = ReadInt32();
1346 if ( (vr == "OB") && (length32 == 0xffffffff) )
1348 Entry->SetLength(FindHeaderEntryLengthOB());
1351 FixHeaderEntryFoundLength(Entry, length32);
1355 // Length is encoded on 2 bytes.
1356 length16 = ReadInt16();
1358 // We can tell the current file is encoded in big endian (like
1359 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1360 // and it's value is the one of the encoding of a big endian file.
1361 // In order to deal with such big endian encoded files, we have
1362 // (at least) two strategies:
1363 // * when we load the "Transfer Syntax" tag with value of big endian
1364 // encoding, we raise the proper flags. Then we wait for the end
1365 // of the META group (0x0002) among which is "Transfer Syntax",
1366 // before switching the swap code to big endian. We have to postpone
1367 // the switching of the swap code since the META group is fully encoded
1368 // in little endian, and big endian coding only starts at the next
1369 // group. The corresponding code can be hard to analyse and adds
1370 // many additional unnecessary tests for regular tags.
1371 // * the second strategy consists in waiting for trouble, that shall
1372 // appear when we find the first group with big endian encoding. This
1373 // is easy to detect since the length of a "Group Length" tag (the
1374 // ones with zero as element number) has to be of 4 (0x0004). When we
1375 // encounter 1024 (0x0400) chances are the encoding changed and we
1376 // found a group with big endian encoding.
1377 // We shall use this second strategy. In order to make sure that we
1378 // can interpret the presence of an apparently big endian encoded
1379 // length of a "Group Length" without committing a big mistake, we
1380 // add an additional check: we look in the already parsed elements
1381 // for the presence of a "Transfer Syntax" whose value has to be "big
1382 // endian encoding". When this is the case, chances are we have got our
1383 // hands on a big endian encoded file: we switch the swap code to
1384 // big endian and proceed...
1385 if ( (element == 0x0000) && (length16 == 0x0400) )
1387 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1389 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1394 SwitchSwapToBigEndian();
1395 // Restore the unproperly loaded values i.e. the group, the element
1396 // and the dictionary entry depending on them.
1397 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1398 guint16 CorrectElem = SwapShort(Entry->GetElement());
1399 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1403 // This correct tag is not in the dictionary. Create a new one.
1404 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1406 // FIXME this can create a memory leaks on the old entry that be
1407 // left unreferenced.
1408 Entry->SetDictEntry(NewTag);
1411 // Heuristic: well some files are really ill-formed.
1412 if ( length16 == 0xffff)
1415 //dbg.Verbose(0, "gdcmParser::FindLength",
1416 // "Erroneous element length fixed.");
1417 // Actually, length= 0xffff means that we deal with
1418 // Unknown Sequence Length
1421 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1425 // Either implicit VR or a non DICOM conformal (see not below) explicit
1426 // VR that ommited the VR of (at least) this element. Farts happen.
1427 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1428 // on Data elements "Implicit and Explicit VR Data Elements shall
1429 // not coexist in a Data Set and Data Sets nested within it".]
1430 // Length is on 4 bytes.
1431 FixHeaderEntryFoundLength(Entry, ReadInt32());
1436 * \ingroup gdcmParser
1437 * \brief Find the Value Representation of the current Dicom Element.
1440 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1442 if (filetype != ExplicitVR)
1448 long PositionOnEntry = ftell(fp);
1449 // Warning: we believe this is explicit VR (Value Representation) because
1450 // we used a heuristic that found "UL" in the first tag. Alas this
1451 // doesn't guarantee that all the tags will be in explicit VR. In some
1452 // cases (see e-film filtered files) one finds implicit VR tags mixed
1453 // within an explicit VR file. Hence we make sure the present tag
1454 // is in explicit VR and try to fix things if it happens not to be
1457 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1459 if(!CheckHeaderEntryVR(Entry,VR))
1461 fseek(fp, PositionOnEntry, SEEK_SET);
1462 // When this element is known in the dictionary we shall use, e.g. for
1463 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1464 // dictionary entry. Still we have to flag the element as implicit since
1465 // we know now our assumption on expliciteness is not furfilled.
1467 if ( Entry->IsVRUnknown() )
1468 Entry->SetVR("Implicit");
1469 Entry->SetImplicitVr();
1474 * \ingroup gdcmParser
1475 * \brief Check the correspondance between the VR of the header entry
1476 * and the taken VR. If they are different, the header entry is
1477 * updated with the new VR.
1480 * @return false if the VR is incorrect of if the VR isn't referenced
1481 * otherwise, it returns true
1483 bool gdcmParser::CheckHeaderEntryVR (gdcmHeaderEntry *Entry, VRKey vr)
1485 char msg[100]; // for sprintf
1486 bool RealExplicit = true;
1488 // Assume we are reading a falsely explicit VR file i.e. we reached
1489 // a tag where we expect reading a VR but are in fact we read the
1490 // first to bytes of the length. Then we will interogate (through find)
1491 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1492 // both GCC and VC++ implementations of the STL map. Hence when the
1493 // expected VR read happens to be non-ascii characters we consider
1494 // we hit falsely explicit VR tag.
1496 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1497 RealExplicit = false;
1499 // CLEANME searching the dicom_vr at each occurence is expensive.
1500 // PostPone this test in an optional integrity check at the end
1501 // of parsing or only in debug mode.
1502 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1503 RealExplicit= false;
1505 if ( !RealExplicit )
1507 // We thought this was explicit VR, but we end up with an
1508 // implicit VR tag. Let's backtrack.
1509 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1510 Entry->GetGroup(),Entry->GetElement());
1511 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1516 if ( Entry->IsVRUnknown() )
1518 // When not a dictionary entry, we can safely overwrite the VR.
1521 else if ( Entry->GetVR() != vr )
1523 // The VR present in the file and the dictionary disagree. We assume
1524 // the file writer knew best and use the VR of the file. Since it would
1525 // be unwise to overwrite the VR of a dictionary (since it would
1526 // compromise it's next user), we need to clone the actual DictEntry
1527 // and change the VR for the read one.
1528 gdcmDictEntry* NewTag = NewVirtualDictEntry(Entry->GetGroup(),
1529 Entry->GetElement(),
1533 Entry->SetDictEntry(NewTag);
1539 * \ingroup gdcmParser
1540 * \brief Skip a given Header Entry
1541 * \warning NOT end user intended method !
1545 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1547 SkipBytes(entry->GetLength());
1551 * \ingroup gdcmParser
1552 * \brief When the length of an element value is obviously wrong (because
1553 * the parser went Jabberwocky) one can hope improving things by
1554 * applying this heuristic.
1556 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1558 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1560 if ( FoundLength == 0xffffffff)
1565 // Sorry for the patch!
1566 // XMedCom did the trick to read some nasty GE images ...
1567 else if (FoundLength == 13)
1569 // The following 'if' will be removed when there is no more
1570 // images on Creatis HDs with a 13 length for Manufacturer...
1571 if ( (Entry->GetGroup() != 0x0008) ||
1572 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ) {
1573 // end of remove area
1575 Entry->SetReadLength(10); // a bug is to be fixed
1579 // to fix some garbage 'Leonardo' Siemens images
1580 // May be commented out to avoid overhead
1581 else if ( (Entry->GetGroup() == 0x0009) &&
1582 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) )
1585 Entry->SetReadLength(4); // a bug is to be fixed
1589 // to try to 'go inside' SeQuences (with length), and not to skip them
1590 else if ( Entry->GetVR() == "SQ")
1592 if (enableSequences) // only if the user does want to !
1596 // a SeQuence Element is beginning
1597 // Let's forget it's length
1598 // (we want to 'go inside')
1600 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1601 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1602 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1603 // if we don't, we lost 28800 characters from the Header :-(
1605 else if(Entry->GetGroup() == 0xfffe)
1607 // sometimes, length seems to be wrong
1608 FoundLength =0; // some more clever checking to be done !
1610 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1611 // causes troubles :-(
1614 Entry->SetUsableLength(FoundLength);
1618 * \ingroup gdcmParser
1619 * \brief Apply some heuristics to predict wether the considered
1620 * element value contains/represents an integer or not.
1621 * @param Entry The element value on which to apply the predicate.
1622 * @return The result of the heuristical predicate.
1624 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry)
1626 guint16 element = Entry->GetElement();
1627 guint16 group = Entry->GetGroup();
1628 std::string vr = Entry->GetVR();
1629 guint32 length = Entry->GetLength();
1631 // When we have some semantics on the element we just read, and if we
1632 // a priori know we are dealing with an integer, then we shall be
1633 // able to swap it's element value properly.
1634 if ( element == 0 ) // This is the group length of the group
1640 std::ostringstream s;
1641 s << "Erroneous Group Length element length on :" \
1642 << std::hex << group << " , " << element;
1643 dbg.Error("gdcmParser::IsAnInteger",
1647 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1654 * \ingroup gdcmParser
1659 guint32 gdcmParser::FindHeaderEntryLengthOB(void)
1661 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1664 long PositionOnEntry = ftell(fp);
1665 bool FoundSequenceDelimiter = false;
1666 guint32 TotalLength = 0;
1669 while ( ! FoundSequenceDelimiter)
1675 TotalLength += 4; // We even have to decount the group and element
1677 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1679 char msg[100]; // for sprintf. Sorry
1680 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1681 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1685 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1686 FoundSequenceDelimiter = true;
1687 else if ( n != 0xe000 )
1689 char msg[100]; // for sprintf. Sorry
1690 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1692 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1696 ItemLength = ReadInt32();
1697 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1698 // the ItemLength with ReadInt32
1699 SkipBytes(ItemLength);
1701 fseek(fp, PositionOnEntry, SEEK_SET);
1706 * \ingroup gdcmParser
1707 * \brief Reads a supposed to be 16 Bits integer
1708 * \ (swaps it depending on processor endianity)
1710 * @return integer acts as a boolean
1712 guint16 gdcmParser::ReadInt16(void)
1716 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1717 if ( item_read != 1 )
1720 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1730 * \ingroup gdcmParser
1731 * \brief Reads a supposed to be 32 Bits integer
1732 * \ (swaps it depending on processor endianity)
1736 guint32 gdcmParser::ReadInt32(void)
1740 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1741 if ( item_read != 1 )
1744 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1754 * \ingroup gdcmParser
1759 void gdcmParser::SkipBytes(guint32 NBytes)
1761 //FIXME don't dump the returned value
1762 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1766 * \ingroup gdcmParser
1769 void gdcmParser::Initialise(void)
1771 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1772 RefShaDict = (gdcmDict*)0;
1776 * \ingroup gdcmParser
1777 * \brief Discover what the swap code is (among little endian, big endian,
1778 * bad little endian, bad big endian).
1781 void gdcmParser::CheckSwap()
1783 // Fourth semantics:
1785 // ---> Warning : This fourth field is NOT part
1786 // of the 'official' Dicom Dictionnary
1787 // and should NOT be used.
1788 // (Not defined for all the groups
1789 // may be removed in a future release)
1792 // META Meta Information
1804 // NMI Nuclear Medicine
1806 // BFS Basic Film Session
1807 // BFB Basic Film Box
1808 // BIB Basic Image Box
1823 // The only guaranted way of finding the swap code is to find a
1824 // group tag since we know it's length has to be of four bytes i.e.
1825 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1826 // occurs when we can't find such group...
1828 guint32 x=4; // x : for ntohs
1829 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1833 char deb[HEADER_LENGTH_TO_READ];
1835 // First, compare HostByteOrder and NetworkByteOrder in order to
1836 // determine if we shall need to swap bytes (i.e. the Endian type).
1841 //cout << net2host << endl;
1843 // The easiest case is the one of a DICOM header, since it possesses a
1844 // file preamble where it suffice to look for the string "DICM".
1845 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1848 if(memcmp(entCur, "DICM", (size_t)4) == 0)
1850 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
1851 // Next, determine the value representation (VR). Let's skip to the
1852 // first element (0002, 0000) and check there if we find "UL"
1853 // - or "OB" if the 1st one is (0002,0001) -,
1854 // in which case we (almost) know it is explicit VR.
1855 // WARNING: if it happens to be implicit VR then what we will read
1856 // is the length of the group. If this ascii representation of this
1857 // length happens to be "UL" then we shall believe it is explicit VR.
1858 // FIXME: in order to fix the above warning, we could read the next
1859 // element value (or a couple of elements values) in order to make
1860 // sure we are not commiting a big mistake.
1861 // We need to skip :
1862 // * the 128 bytes of File Preamble (often padded with zeroes),
1863 // * the 4 bytes of "DICM" string,
1864 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1865 // i.e. a total of 136 bytes.
1868 // Use gdcmParser::dicom_vr to test all the possibilities
1869 // instead of just checking for UL, OB and UI !?
1870 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
1871 (memcmp(entCur, "OB", (size_t)2) == 0) ||
1872 (memcmp(entCur, "UI", (size_t)2) == 0) )
1874 filetype = ExplicitVR;
1875 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1876 "explicit Value Representation");
1880 filetype = ImplicitVR;
1881 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1882 "not an explicit Value Representation");
1887 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1888 "HostByteOrder != NetworkByteOrder");
1893 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1894 "HostByteOrder = NetworkByteOrder");
1897 // Position the file position indicator at first tag (i.e.
1898 // after the file preamble and the "DICM" string).
1900 fseek (fp, 132L, SEEK_SET);
1904 // Alas, this is not a DicomV3 file and whatever happens there is no file
1905 // preamble. We can reset the file position indicator to where the data
1906 // is (i.e. the beginning of the file).
1907 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
1910 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1911 // By clean we mean that the length of the first tag is written down.
1912 // If this is the case and since the length of the first group HAS to be
1913 // four (bytes), then determining the proper swap code is straightforward.
1916 // We assume the array of char we are considering contains the binary
1917 // representation of a 32 bits integer. Hence the following dirty
1919 s = *((guint32 *)(entCur));
1940 dbg.Verbose(0, "gdcmParser::CheckSwap:",
1941 "ACR/NEMA unfound swap info (time to raise bets)");
1944 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1945 // It is time for despaired wild guesses. So, let's assume this file
1946 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
1947 // not present. Then the only info we have is the net2host one.
1957 * \ingroup gdcmParser
1960 void gdcmParser::SwitchSwapToBigEndian(void)
1962 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
1963 "Switching to BigEndian mode.");
1984 * \ingroup gdcmParser
1989 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
1993 if ((guint32)NewSize >= (guint32)0xffffffff)
1995 MaxSizeLoadEntry = 0xffffffff;
1998 MaxSizeLoadEntry = NewSize;
2002 * \ingroup gdcmParser
2003 * \brief Searches both the public and the shadow dictionary (when they
2004 * exist) for the presence of the DictEntry with given name.
2005 * The public dictionary has precedence on the shadow one.
2006 * @param Name name of the searched DictEntry
2007 * @return Corresponding DictEntry when it exists, NULL otherwise.
2009 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2011 gdcmDictEntry *found = (gdcmDictEntry *)0;
2012 if (!RefPubDict && !RefShaDict)
2014 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2015 "we SHOULD have a default dictionary");
2019 found = RefPubDict->GetDictEntryByName(Name);
2025 found = RefShaDict->GetDictEntryByName(Name);
2033 * \ingroup gdcmParser
2034 * \brief Searches both the public and the shadow dictionary (when they
2035 * exist) for the presence of the DictEntry with given
2036 * group and element. The public dictionary has precedence on the
2038 * @param group group of the searched DictEntry
2039 * @param element element of the searched DictEntry
2040 * @return Corresponding DictEntry when it exists, NULL otherwise.
2042 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2044 gdcmDictEntry *found = (gdcmDictEntry *)0;
2045 if (!RefPubDict && !RefShaDict)
2047 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2048 "we SHOULD have a default dictionary");
2052 found = RefPubDict->GetDictEntryByNumber(group, element);
2058 found = RefShaDict->GetDictEntryByNumber(group, element);
2066 * \ingroup gdcmParser
2067 * \brief Read the next tag but WITHOUT loading it's value
2068 * @return On succes the newly created HeaderEntry, NULL on failure.
2070 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void)
2073 gdcmHeaderEntry *NewEntry;
2079 // We reached the EOF (or an error occured) and header parsing
2080 // has to be considered as finished.
2081 return (gdcmHeaderEntry *)0;
2083 NewEntry = NewHeaderEntryByNumber(g, n);
2084 FindHeaderEntryVR(NewEntry);
2085 FindHeaderEntryLength(NewEntry);
2092 NewEntry->SetOffset(ftell(fp));
2093 //if ( (g==0x7fe0) && (n==0x0010) )
2098 * \ingroup gdcmParser
2099 * \brief Build a new Element Value from all the low level arguments.
2100 * Check for existence of dictionary entry, and build
2101 * a default one when absent.
2102 * @param Name Name of the underlying DictEntry
2104 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2106 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2108 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2110 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2113 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2114 "failed to allocate gdcmHeaderEntry");
2115 return (gdcmHeaderEntry *)0;
2121 * \ingroup gdcmParser
2122 * \brief Request a new virtual dict entry to the dict set
2123 * @param group group of the underlying DictEntry
2124 * @param elem element of the underlying DictEntry
2125 * @param vr VR of the underlying DictEntry
2126 * @param fourth owner group
2127 * @param name english name
2129 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2134 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2138 * \ingroup gdcmParser
2139 * \brief Build a new Element Value from all the low level arguments.
2140 * Check for existence of dictionary entry, and build
2141 * a default one when absent.
2142 * @param Group group of the underlying DictEntry
2143 * @param Elem element of the underlying DictEntry
2145 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2147 // Find out if the tag we encountered is in the dictionaries:
2148 gdcmDictEntry *NewTag = GetDictEntryByNumber(Group, Elem);
2150 NewTag = NewVirtualDictEntry(Group, Elem);
2152 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2155 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2156 "failed to allocate gdcmHeaderEntry");
2163 * \ingroup gdcmParser
2164 * \brief Small utility function that creates a new manually crafted
2165 * (as opposed as read from the file) gdcmHeaderEntry with user
2166 * specified name and adds it to the public tag hash table.
2167 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2168 * @param NewTagName The name to be given to this new tag.
2169 * @param VR The Value Representation to be given to this new tag.
2170 * @return The newly hand crafted Element Value.
2172 gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2175 gdcmHeaderEntry *NewEntry = NULL;
2176 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2177 guint32 FreeElem = 0;
2178 gdcmDictEntry *DictEntry = NULL;
2180 FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2181 if (FreeElem == UINT32_MAX)
2183 dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2184 "Group 0xffff in Public Dict is full");
2188 DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2189 VR, "GDCM", NewTagName);
2190 NewEntry = new gdcmHeaderEntry(DictEntry);
2191 AddHeaderEntry(NewEntry);
2196 * \ingroup gdcmParser
2197 * \brief Generate a free TagKey i.e. a TagKey that is not present
2198 * in the TagHt dictionary.
2199 * @param group The generated tag must belong to this group.
2200 * @return The element of tag with given group which is fee.
2202 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2204 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2206 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2207 if (tagHT.count(key) == 0)
2213 //-----------------------------------------------------------------------------