2 //-----------------------------------------------------------------------------
3 #include "gdcmParser.h"
11 #include <netinet/in.h>
14 #ifdef GDCM_NO_ANSI_STRING_STREAM
16 # define ostringstream ostrstream
22 //-----------------------------------------------------------------------------
23 // Refer to gdcmParser::CheckSwap()
24 const unsigned int gdcmParser::HEADER_LENGTH_TO_READ = 256;
26 // Refer to gdcmParser::SetMaxSizeLoadElementValue()
27 const unsigned int gdcmParser::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
29 //-----------------------------------------------------------------------------
30 // Constructor / Destructor
35 * @param exception_on_error
36 * @param enable_sequences = true to allow the header
37 * to be parsed *inside* the SeQuences,
38 * when they have an actual length
39 *\TODO may be we need one more bool,
40 * to allow skipping the private elements while parsing the header
41 * in order to save space
43 gdcmParser::gdcmParser(const char *InFilename,
44 bool exception_on_error,
45 bool enable_sequences )
47 enableSequences=enable_sequences;
49 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
50 filename = InFilename;
53 if ( !OpenFile(exception_on_error))
61 wasUpdated = 0; // will be set to 1 if user adds an entry
62 printLevel = 1; // 'Medium' header print by default
68 * @param exception_on_error
70 gdcmParser::gdcmParser(bool exception_on_error)
74 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
77 wasUpdated = 0; // will be set to 1 if user adds an entry
78 printLevel = 1; // 'Heavy' header print by default
83 * \brief Canonical destructor.
85 gdcmParser::~gdcmParser (void)
91 //-----------------------------------------------------------------------------
95 * \brief Prints the Header Entries (Dicom Elements)
96 * both from the H Table and the chained list
99 void gdcmParser::PrintEntry(std::ostream & os)
101 std::ostringstream s;
103 s << "------------ gdcmParser::Print, using listEntries ----------------" << std::endl;
104 for (ListTag::iterator i = listEntries.begin();
105 i != listEntries.end();
108 (*i)->SetPrintLevel(printLevel);
115 * \ingroup gdcmParser
116 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
119 void gdcmParser::PrintPubDict(std::ostream & os)
121 RefPubDict->Print(os);
125 * \ingroup gdcmParser
126 * \brief Prints The Dict Entries of the current shadow Dicom Dictionnry
129 void gdcmParser::PrintShaDict(std::ostream & os)
131 RefShaDict->Print(os);
134 //-----------------------------------------------------------------------------
137 * \ingroup gdcmParser
138 * \brief Get THE public dictionary used
140 gdcmDict *gdcmParser::GetPubDict(void)
146 * \ingroup gdcmParser
147 * \brief Get the current shadow dictionary
149 gdcmDict *gdcmParser::GetShaDict(void)
155 * \ingroup gdcmParser
156 * \brief Set the shadow dictionary used
157 * \param dict dictionary to use in shadow
159 bool gdcmParser::SetShaDict(gdcmDict *dict)
166 * \ingroup gdcmParser
167 * \brief Set the shadow dictionary used
168 * \param dictName name of the dictionary to use in shadow
170 bool gdcmParser::SetShaDict(DictKey dictName) {
171 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
176 * \ingroup gdcmParser
177 * \brief This predicate, based on hopefully reasonable heuristics,
178 * decides whether or not the current gdcmParser was properly parsed
179 * and contains the mandatory information for being considered as
180 * a well formed and usable Dicom/Acr File.
181 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
184 bool gdcmParser::IsReadable(void)
186 std::string res = GetEntryByNumber(0x0028, 0x0005);
187 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 ) {
188 //std::cout << "error on : 28 5" << std::endl;
189 return false; // Image Dimensions
192 if ( !GetHeaderEntryByNumber(0x0028, 0x0100) ) {
193 //std::cout << "error on : 28 100" << std::endl;
194 return false; // "Bits Allocated"
196 if ( !GetHeaderEntryByNumber(0x0028, 0x0101) ){
197 // std::cout << "error on : 28 101" << std::endl;
198 return false; // "Bits Stored"
200 if ( !GetHeaderEntryByNumber(0x0028, 0x0102) ) {
201 //std::cout << "error on : 28 102" << std::endl;
202 return false; // "High Bit"
204 if ( !GetHeaderEntryByNumber(0x0028, 0x0103) ) {
205 //std::cout << "error on : 28 103" << std::endl;
206 return false; // "Pixel Representation"
212 * \ingroup gdcmParser
213 * \brief Determines if the Transfer Syntax was already encountered
214 * and if it corresponds to a ImplicitVRLittleEndian one.
216 * @return True when ImplicitVRLittleEndian found. False in all other cases.
218 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
219 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
222 LoadHeaderEntrySafe(Element);
224 std::string Transfer = Element->GetValue();
225 if ( Transfer == "1.2.840.10008.1.2" )
231 * \ingroup gdcmParser
232 * \brief Determines if the Transfer Syntax was already encountered
233 * and if it corresponds to a ExplicitVRLittleEndian one.
235 * @return True when ExplicitVRLittleEndian found. False in all other cases.
237 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void)
239 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
242 LoadHeaderEntrySafe(Element);
244 std::string Transfer = Element->GetValue();
245 if ( Transfer == "1.2.840.10008.1.2.1" )
251 * \ingroup gdcmParser
252 * \brief Determines if the Transfer Syntax was already encountered
253 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
255 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
257 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
259 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
262 LoadHeaderEntrySafe(Element);
264 std::string Transfer = Element->GetValue();
265 if ( Transfer == "1.2.840.10008.1.2.1.99" )
271 * \ingroup gdcmParser
272 * \brief Determines if the Transfer Syntax was already encountered
273 * and if it corresponds to a Explicit VR Big Endian one.
275 * @return True when big endian found. False in all other cases.
277 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void)
279 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
282 LoadHeaderEntrySafe(Element);
284 std::string Transfer = Element->GetValue();
285 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
291 * \ingroup gdcmParser
292 * \brief returns the File Type
293 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
296 FileType gdcmParser::GetFileType(void) {
301 * \ingroup gdcmParser
302 * \brief opens the file
303 * @param exception_on_error
306 FILE *gdcmParser::OpenFile(bool exception_on_error)
309 fp=fopen(filename.c_str(),"rb");
310 if(exception_on_error)
313 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
319 fread(&zero, (size_t)2, (size_t)1, fp);
321 //ACR -- or DICOM with no Preamble --
322 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
326 fseek(fp, 126L, SEEK_CUR);
328 fread(dicm, (size_t)4, (size_t)1, fp);
329 if( memcmp(dicm, "DICM", 4) == 0 )
333 dbg.Verbose(0, "gdcmParser::gdcmParser not DICOM/ACR", filename.c_str());
336 dbg.Verbose(0, "gdcmParser::gdcmParser cannot open file", filename.c_str());
342 * \ingroup gdcmParser
343 * \brief closes the file
344 * @return TRUE if the close was successfull
346 bool gdcmParser::CloseFile(void)
348 int closed = fclose(fp);
356 * \ingroup gdcmParser
358 * @param fp file pointer on an already open file
359 * @param type type of the File to be written
360 * (ACR-NEMA, ExplicitVR, ImplicitVR)
361 * @return always "True" ?!
363 bool gdcmParser::Write(FILE *fp, FileType type)
366 // TODO The stuff has been rewritten using the chained list instead
368 // so we could remove the GroupHT from the gdcmParser
372 // TODO : move the following lines (and a lot of others, to be written)
373 // to a future function CheckAndCorrectHeader
376 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
377 // (FileType est un champ de gdcmParser ...)
378 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
380 // a moins de se livrer a un tres complique ajout des champs manquants.
381 // faire un CheckAndCorrectHeader (?)
384 if (type == ImplicitVR)
386 std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
387 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
389 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
390 // values with a VR of UI shall be padded with a single trailing null
391 // Dans le cas suivant on doit pader manuellement avec un 0
393 SetEntryLengthByNumber(18, 0x0002, 0x0010);
396 if (type == ExplicitVR)
398 std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
399 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
401 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
402 // values with a VR of UI shall be padded with a single trailing null
403 // Dans le cas suivant on doit pader manuellement avec un 0
405 SetEntryLengthByNumber(20, 0x0002, 0x0010);
409 if ( (type == ImplicitVR) || (type == ExplicitVR) )
410 UpdateGroupLength(false,type);
412 UpdateGroupLength(true,ACR);
414 WriteEntries(type, fp);
419 * \ingroup gdcmParser
420 * \brief Modifies the value of a given Header Entry (Dicom Element)
421 * if it exists; Creates it with the given value if it doesn't
422 * @param Value passed as a std::string
427 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
428 guint16 Group, guint16 Elem )
430 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
431 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
436 SetEntryByNumber(Value, Group, Elem);
441 * \ingroup gdcmParser
442 * \brief Modifies the value of a given Header Entry (Dicom Element)
443 * if it exists; Creates it with the given value if it doesn't
444 * @param Value passed as a char*
450 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem )
452 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
457 AddHeaderEntry(nvHeaderEntry);
459 std::string v = Value;
460 SetEntryByNumber(v, Group, Elem);
465 * \ingroup gdcmParser
466 * \brief Set a new value if the invoked element exists
467 * Seems to be useless !!!
473 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
475 std::string v = Value;
476 SetEntryByNumber(v, Group, Elem);
480 //-----------------------------------------------------------------------------
483 * \ingroup gdcmParser
484 * \brief Checks if a given Dicom Element exists
485 * \ within the H table
486 * @param group Group number of the searched Dicom Element
487 * @param element Element number of the searched Dicom Element
488 * @return number of occurences
490 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element )
492 std::string key = gdcmDictEntry::TranslateToKey(group, element );
493 return (tagHT.count(key));
497 * \ingroup gdcmParser
498 * \brief Searches within Header Entries (Dicom Elements) parsed with
499 * the public and private dictionaries
500 * for the element value of a given tag.
501 * @param tagName name of the searched element.
502 * @return Corresponding element value when it exists,
503 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
505 std::string gdcmParser::GetEntryByName(std::string tagName)
507 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
508 if( dictEntry == NULL)
511 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
515 * \ingroup gdcmParser
516 * \brief Searches within Header Entries (Dicom Elements) parsed with
517 * the public and private dictionaries
518 * for the element value representation of a given tag.
520 * Obtaining the VR (Value Representation) might be needed by caller
521 * to convert the string typed content to caller's native type
522 * (think of C++ vs Python). The VR is actually of a higher level
523 * of semantics than just the native C++ type.
524 * @param tagName name of the searched element.
525 * @return Corresponding element value representation when it exists,
526 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
528 std::string gdcmParser::GetEntryVRByName(std::string tagName)
530 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
531 if( dictEntry == NULL)
534 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
535 dictEntry->GetElement());
536 return elem->GetVR();
540 * \ingroup gdcmParser
541 * \brief Searches within Header Entries (Dicom Elements) parsed with
542 * the public and private dictionaries
543 * for the element value representation of a given tag.
544 * @param group Group of the searched tag.
545 * @param element Element of the searched tag.
546 * @return Corresponding element value representation when it exists,
547 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
549 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element)
551 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
552 if ( ! tagHT.count(key))
554 return tagHT.find(key)->second->GetValue();
558 * \ingroup gdcmParser
559 * \brief Searches within Header Entries (Dicom Elements) parsed with
560 * the public and private dictionaries
561 * for the element value representation of a given tag..
563 * Obtaining the VR (Value Representation) might be needed by caller
564 * to convert the string typed content to caller's native type
565 * (think of C++ vs Python). The VR is actually of a higher level
566 * of semantics than just the native C++ type.
567 * @param group Group of the searched tag.
568 * @param element Element of the searched tag.
569 * @return Corresponding element value representation when it exists,
570 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
572 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element)
574 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
577 return elem->GetVR();
581 * \ingroup gdcmParser
582 * \brief Sets the value (string) of the Header Entry (Dicom Element)
583 * @param content string value of the Dicom Element
584 * @param tagName name of the searched Dicom Element.
585 * @return true when found
587 bool gdcmParser::SetEntryByName(std::string content,std::string tagName)
589 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
590 if( dictEntry == NULL)
593 return(SetEntryByNumber(content,dictEntry->GetGroup(),
594 dictEntry->GetElement()));
598 * \ingroup gdcmParser
599 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
600 * through it's (group, element) and modifies it's content with
602 * \warning Don't use any longer : use SetPubEntryByNumber
603 * @param content new value to substitute with
604 * @param group group of the Dicom Element to modify
605 * @param element element of the Dicom Element to modify
607 bool gdcmParser::SetEntryByNumber(std::string content,
611 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
612 if ( ! tagHT.count(key))
614 int l = content.length();
615 if(l%2) // Odd length are padded with a space (020H).
618 content = content + '\0';
621 //tagHT[key]->SetValue(content);
624 TagHeaderEntryHT::iterator p2;
625 // DO NOT remove the following lines : they explain the stuff
626 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
627 //p2=p.first; // iterator on the first synonym
628 //a=p2->second; // H Table target column (2-nd col)
631 a = ((tagHT.equal_range(key)).first)->second;
633 a-> SetValue(content);
635 //std::string vr = tagHT[key]->GetVR();
636 std::string vr = a->GetVR();
639 if( (vr == "US") || (vr == "SS") )
641 else if( (vr == "UL") || (vr == "SL") )
646 //tagHT[key]->SetLength(lgr);
652 * \ingroup gdcmParser
653 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
654 * in the PubHeaderEntrySet of this instance
655 * through it's (group, element) and modifies it's length with
657 * \warning Use with extreme caution.
658 * @param length new length to substitute with
659 * @param group group of the entry to modify
660 * @param element element of the Entry to modify
661 * @return 1 on success, 0 otherwise.
664 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
665 guint16 group, guint16 element)
667 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
668 if ( ! tagHT.count(key))
670 if (length%2) length++; // length must be even
671 //tagHT[key]->SetLength(length);
672 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
678 * \ingroup gdcmParser
679 * \brief Gets (from Header) the offset of a 'non string' element value
680 * \ (LoadElementValues has already be executed)
683 * @return File Offset of the Element Value
685 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
687 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
690 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
691 "failed to Locate gdcmHeaderEntry");
694 return Entry->GetOffset();
698 * \ingroup gdcmParser
699 * \brief Gets (from Header) a 'non string' element value
700 * \ (LoadElementValues has already be executed)
703 * @return Pointer to the 'non string' area
705 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
707 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
710 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
711 "failed to Locate gdcmHeaderEntry");
714 return Entry->GetVoidArea();
718 * \ingroup gdcmParser
719 * \brief Loads (from disk) the element content
720 * when a string is not suitable
722 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
724 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
727 size_t o =(size_t)Element->GetOffset();
728 fseek(fp, o, SEEK_SET);
729 int l=Element->GetLength();
730 void * a = malloc(l);
734 SetEntryVoidAreaByNumber(a, Group, Elem);
735 // TODO check the result
736 size_t l2 = fread(a, 1, l ,fp);
746 * \ingroup gdcmParser
747 * \brief Sets a 'non string' value to a given Dicom Element
749 * @param group Group number of the searched Dicom Element
750 * @param element Element number of the searched Dicom Element
753 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,guint16 group, guint16 element)
755 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
756 if ( ! tagHT.count(key))
758 //tagHT[key]->SetVoidArea(area);
759 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
764 * \ingroup gdcmParser
765 * \brief Update the entries with the shadow dictionary. Only odd entries are
768 void gdcmParser::UpdateShaEntries(void)
770 gdcmDictEntry *entry;
773 for(ListTag::iterator it=listEntries.begin();
774 it!=listEntries.end();
777 // Odd group => from public dictionary
778 if((*it)->GetGroup()%2==0)
781 // Peer group => search the corresponding dict entry
783 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
787 if((*it)->IsImplicitVR())
792 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
795 // Set the new entry and the new value
796 (*it)->SetDictEntry(entry);
797 CheckHeaderEntryVR(*it,vr);
799 (*it)->SetValue(GetHeaderEntryValue(*it));
803 // Remove precedent value transformation
804 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
810 * \ingroup gdcmParser
811 * \brief Searches within the Header Entries for a Dicom Element of
813 * @param tagName name of the searched Dicom Element.
814 * @return Corresponding Dicom Element when it exists, and NULL
817 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName)
819 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
820 if( dictEntry == NULL)
823 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
827 * \ingroup gdcmParser
828 * \brief retrieves a Dicom Element (the first one) using (group, element)
829 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
830 * if you think it's NOT UNIQUE, check the count number
831 * and use iterators to retrieve ALL the Dicoms Elements within
832 * a given couple (group, element)
833 * @param group Group number of the searched Dicom Element
834 * @param element Element number of the searched Dicom Element
837 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
839 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
840 if ( ! tagHT.count(key))
842 return tagHT.find(key)->second;
846 * \ingroup gdcmParser
847 * \brief Loads the element while preserving the current
848 * underlying file position indicator as opposed to
849 * to LoadHeaderEntry that modifies it.
850 * @param entry Header Entry whose value shall be loaded.
853 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry)
855 long PositionOnEntry = ftell(fp);
856 LoadHeaderEntry(entry);
857 fseek(fp, PositionOnEntry, SEEK_SET);
861 * \ingroup gdcmParser
862 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
863 * \warning : to be re-written using the chained list instead of the H table.
864 * \warning : DO NOT use (doesn't work any longer because of the multimap)
865 * \todo : to be re-written using the chained list instead of the H table
866 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
867 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
869 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type)
874 gdcmHeaderEntry *elem;
876 std::string str_trash;
879 GroupHT groupHt; // to hold the length of each group
882 // typedef std::map<GroupKey, int> GroupHT;
884 gdcmHeaderEntry *elemZ;
886 // for each Tag in the DCM Header
888 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
893 gr = elem->GetGroup();
894 el = elem->GetElement();
897 sprintf(trash, "%04x", gr);
898 key = trash; // generate 'group tag'
900 // if the caller decided not to take SEQUENCEs into account
901 // e.g : he wants to write an ACR-NEMA File
903 if (SkipSequence && vr == "SQ")
906 // Still unsolved problem :
907 // we cannot find the 'Sequence Delimitation Item'
908 // since it's at the end of the Hash Table
911 // pas SEQUENCE en ACR-NEMA
913 // --> la descente a l'interieur' des SQ
914 // devrait etre faite avec une liste chainee, pas avec une HTable...
916 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
918 if (el == 0x0000) // the first elem is 0x0000
920 groupHt[key] = 0; // initialize group length
924 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
927 else // any elem but the first
929 if (type == ExplicitVR)
931 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
933 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
936 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
940 unsigned short int gr_bid;
942 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
946 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
947 // warning: unsigned int format, different type arg
948 sscanf(g->first.c_str(),"%x",&gr_bid);
949 tk = g->first + "|0000"; // generate the element full tag
951 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
953 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
954 elemZ = new gdcmHeaderEntry(tagZ);
956 AddHeaderEntry(elemZ); // create it
960 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
962 sprintf(trash ,"%d",g->second);
964 elemZ->SetValue(str_trash);
969 * \ingroup gdcmParser
970 * \brief writes on disc according to the requested format
971 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
972 * \ warning does NOT add the missing elements in the header :
973 * \ it's up to the user doing it !
974 * \ (function CheckHeaderCoherence to be written)
975 * @param type type of the File to be written
976 * (ACR-NEMA, ExplicitVR, ImplicitVR)
977 * @param _fp already open file pointer
979 void gdcmParser::WriteEntries(FileType type, FILE * _fp)
988 std::vector<std::string> tokens;
990 // uses now listEntries to iterate, not TagHt!
992 // pb : gdcmParser.Add does NOT update listEntries
993 // TODO : find a trick (in STL?) to do it, at low cost !
997 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
999 for (ListTag::iterator tag2=listEntries.begin();
1000 tag2 != listEntries.end();
1003 gr = (*tag2)->GetGroup();
1004 el = (*tag2)->GetElement();
1005 lgr = (*tag2)->GetLength();
1006 val = (*tag2)->GetValue().c_str();
1007 vr = (*tag2)->GetVR();
1011 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
1012 if (gr %2) continue; // ignore shadow groups
1013 if (vr == "SQ" ) continue; // ignore Sequences
1014 // TODO : find a trick to *skip* the SeQuences !
1015 // Not only ignore the SQ element
1016 if (gr == 0xfffe ) continue; // ignore delimiters
1019 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1020 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1022 if ( (type == ExplicitVR) && (gr <= 0x0002) )
1025 guint16 z=0, shortLgr;
1026 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1028 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1030 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1031 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1037 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1042 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1045 if (vr == "US" || vr == "SS")
1047 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1048 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1049 for (unsigned int i=0; i<tokens.size();i++)
1051 val_uint16 = atoi(tokens[i].c_str());
1053 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1058 if (vr == "UL" || vr == "SL")
1060 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1061 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1062 for (unsigned int i=0; i<tokens.size();i++)
1064 val_uint32 = atoi(tokens[i].c_str());
1066 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1071 // Pixels are never loaded in the element !
1072 if ((gr == 0x7fe0) && (el == 0x0010) )
1075 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1080 * \ingroup gdcmParser
1081 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1083 * @return The properly swaped 32 bits integer.
1085 guint32 gdcmParser::SwapLong(guint32 a)
1092 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1093 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1097 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1101 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1104 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1111 * \ingroup gdcmParser
1112 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1114 * @return The properly unswaped 32 bits integer.
1116 guint32 gdcmParser::UnswapLong(guint32 a)
1118 return (SwapLong(a));
1122 * \ingroup gdcmParser
1123 * \brief Swaps the bytes so they agree with the processor order
1124 * @return The properly swaped 16 bits integer.
1126 guint16 gdcmParser::SwapShort(guint16 a)
1128 if ( (sw==4321) || (sw==2143) )
1129 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1134 * \ingroup gdcmParser
1135 * \brief Unswaps the bytes so they agree with the processor order
1136 * @return The properly unswaped 16 bits integer.
1138 guint16 gdcmParser::UnswapShort(guint16 a)
1140 return (SwapShort(a));
1143 //-----------------------------------------------------------------------------
1146 * \ingroup gdcmParser
1147 * \brief Parses the header of the file but WITHOUT loading element values.
1149 void gdcmParser::Parse(bool exception_on_error) throw(gdcmFormatError)
1151 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1155 while ( (newHeaderEntry = ReadNextHeaderEntry()) )
1157 SkipHeaderEntry(newHeaderEntry);
1158 AddHeaderEntry(newHeaderEntry);
1163 * \ingroup gdcmParser
1164 * \brief Loads the element values of all the Header Entries pointed in the
1165 * public Chained List.
1167 void gdcmParser::LoadHeaderEntries(void)
1170 for (ListTag::iterator i = GetListEntry().begin();
1171 i != GetListEntry().end();
1174 LoadHeaderEntry(*i);
1179 // Load 'non string' values
1180 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1181 if( PhotometricInterpretation == "PALETTE COLOR " )
1183 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1184 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1185 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1186 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1188 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1189 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1190 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1193 // --------------------------------------------------------------
1194 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1196 // if recognition code tells us we deal with a LibIDO image
1197 // we switch lineNumber and columnNumber
1199 std::string RecCode;
1200 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1201 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1202 RecCode == "CANRME_AILIBOD1_1." )
1204 filetype = ACR_LIBIDO;
1205 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1206 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1207 SetEntryByNumber(columns, 0x0028, 0x0010);
1208 SetEntryByNumber(rows , 0x0028, 0x0011);
1210 // ----------------- End of Special Patch ----------------
1214 * \ingroup gdcmParser
1215 * \brief Loads the element content if it's length is not bigger
1216 * than the value specified with
1217 * gdcmParser::SetMaxSizeLoadEntry()
1218 * @param Entry Header Entry (Dicom Element) to be dealt with
1220 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry)
1223 guint16 group = Entry->GetGroup();
1224 std::string vr= Entry->GetVR();
1225 guint32 length = Entry->GetLength();
1226 bool SkipLoad = false;
1228 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1230 // the test was commented out to 'go inside' the SeQuences
1231 // we don't any longer skip them !
1233 // if( vr == "SQ" ) // (DO NOT remove this comment)
1236 // A SeQuence "contains" a set of Elements.
1237 // (fffe e000) tells us an Element is beginning
1238 // (fffe e00d) tells us an Element just ended
1239 // (fffe e0dd) tells us the current SeQuence just ended
1240 if( group == 0xfffe )
1245 Entry->SetLength(0);
1246 Entry->SetValue("gdcm::Skipped");
1250 // When the length is zero things are easy:
1253 Entry->SetValue("");
1257 // The elements whose length is bigger than the specified upper bound
1258 // are not loaded. Instead we leave a short notice of the offset of
1259 // the element content and it's length.
1260 if (length > MaxSizeLoadEntry)
1262 std::ostringstream s;
1263 s << "gdcm::NotLoaded.";
1264 s << " Address:" << (long)Entry->GetOffset();
1265 s << " Length:" << Entry->GetLength();
1266 s << " x(" << std::hex << Entry->GetLength() << ")";
1267 Entry->SetValue(s.str());
1271 // When integer(s) are expected, read and convert the following
1272 // n *(two or four bytes)
1273 // properly i.e. as integers as opposed to a strings.
1274 // Elements with Value Multiplicity > 1
1275 // contain a set of integers (not a single one)
1277 // Any compacter code suggested (?)
1278 if ( IsHeaderEntryAnInteger(Entry) )
1281 std::ostringstream s;
1283 if (vr == "US" || vr == "SS")
1286 NewInt = ReadInt16();
1290 for (int i=1; i < nbInt; i++)
1293 NewInt = ReadInt16();
1299 else if (vr == "UL" || vr == "SL")
1302 NewInt = ReadInt32();
1306 for (int i=1; i < nbInt; i++)
1309 NewInt = ReadInt32();
1314 #ifdef GDCM_NO_ANSI_STRING_STREAM
1315 s << std::ends; // to avoid oddities on Solaris
1316 #endif //GDCM_NO_ANSI_STRING_STREAM
1317 Entry->SetValue(s.str());
1321 // We need an additional byte for storing \0 that is not on disk
1322 std::string NewValue(length,0);
1323 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1324 if ( item_read != 1 )
1326 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1327 Entry->SetValue("gdcm::UnRead");
1330 Entry->SetValue(NewValue);
1334 * \ingroup gdcmParser
1335 * \brief add a new Dicom Element pointer to
1336 * the H Table and to the chained List
1337 * \warning push_bash in listEntries ONLY during ParseHeader
1338 * \todo something to allow further Elements addition,
1339 * \ when position to be taken care of
1340 * @param newHeaderEntry
1342 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry)
1344 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1345 listEntries.push_back(newHeaderEntry);
1350 * \ingroup gdcmParser
1352 * @param Entry Header Entry whose length of the value shall be loaded.
1356 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry)
1358 guint16 element = Entry->GetElement();
1359 guint16 group = Entry->GetGroup();
1360 std::string vr = Entry->GetVR();
1362 if( (element == 0x0010) && (group == 0x7fe0) )
1365 dbg.Verbose(2, "gdcmParser::FindLength: ",
1366 "we reached 7fe0 0010");
1369 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1371 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1373 // The following reserved two bytes (see PS 3.5-2001, section
1374 // 7.1.2 Data element structure with explicit vr p27) must be
1375 // skipped before proceeding on reading the length on 4 bytes.
1376 fseek(fp, 2L, SEEK_CUR);
1377 guint32 length32 = ReadInt32();
1379 if ( (vr == "OB") && (length32 == 0xffffffff) )
1381 Entry->SetLength(FindHeaderEntryLengthOB());
1384 FixHeaderEntryFoundLength(Entry, length32);
1388 // Length is encoded on 2 bytes.
1389 length16 = ReadInt16();
1391 // We can tell the current file is encoded in big endian (like
1392 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1393 // and it's value is the one of the encoding of a big endian file.
1394 // In order to deal with such big endian encoded files, we have
1395 // (at least) two strategies:
1396 // * when we load the "Transfer Syntax" tag with value of big endian
1397 // encoding, we raise the proper flags. Then we wait for the end
1398 // of the META group (0x0002) among which is "Transfer Syntax",
1399 // before switching the swap code to big endian. We have to postpone
1400 // the switching of the swap code since the META group is fully encoded
1401 // in little endian, and big endian coding only starts at the next
1402 // group. The corresponding code can be hard to analyse and adds
1403 // many additional unnecessary tests for regular tags.
1404 // * the second strategy consists in waiting for trouble, that shall
1405 // appear when we find the first group with big endian encoding. This
1406 // is easy to detect since the length of a "Group Length" tag (the
1407 // ones with zero as element number) has to be of 4 (0x0004). When we
1408 // encounter 1024 (0x0400) chances are the encoding changed and we
1409 // found a group with big endian encoding.
1410 // We shall use this second strategy. In order to make sure that we
1411 // can interpret the presence of an apparently big endian encoded
1412 // length of a "Group Length" without committing a big mistake, we
1413 // add an additional check: we look in the already parsed elements
1414 // for the presence of a "Transfer Syntax" whose value has to be "big
1415 // endian encoding". When this is the case, chances are we have got our
1416 // hands on a big endian encoded file: we switch the swap code to
1417 // big endian and proceed...
1418 if ( (element == 0x0000) && (length16 == 0x0400) )
1420 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1422 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1427 SwitchSwapToBigEndian();
1428 // Restore the unproperly loaded values i.e. the group, the element
1429 // and the dictionary entry depending on them.
1430 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1431 guint16 CorrectElem = SwapShort(Entry->GetElement());
1432 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1436 // This correct tag is not in the dictionary. Create a new one.
1437 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1439 // FIXME this can create a memory leaks on the old entry that be
1440 // left unreferenced.
1441 Entry->SetDictEntry(NewTag);
1444 // Heuristic: well some files are really ill-formed.
1445 if ( length16 == 0xffff)
1448 //dbg.Verbose(0, "gdcmParser::FindLength",
1449 // "Erroneous element length fixed.");
1450 // Actually, length= 0xffff means that we deal with
1451 // Unknown Sequence Length
1454 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1459 // Either implicit VR or a non DICOM conformal (see not below) explicit
1460 // VR that ommited the VR of (at least) this element. Farts happen.
1461 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1462 // on Data elements "Implicit and Explicit VR Data Elements shall
1463 // not coexist in a Data Set and Data Sets nested within it".]
1464 // Length is on 4 bytes.
1465 FixHeaderEntryFoundLength(Entry, ReadInt32());
1471 * \ingroup gdcmParser
1472 * \brief Find the Value Representation of the current Dicom Element.
1475 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1477 if (filetype != ExplicitVR)
1483 long PositionOnEntry = ftell(fp);
1484 // Warning: we believe this is explicit VR (Value Representation) because
1485 // we used a heuristic that found "UL" in the first tag. Alas this
1486 // doesn't guarantee that all the tags will be in explicit VR. In some
1487 // cases (see e-film filtered files) one finds implicit VR tags mixed
1488 // within an explicit VR file. Hence we make sure the present tag
1489 // is in explicit VR and try to fix things if it happens not to be
1492 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1494 if(!CheckHeaderEntryVR(Entry,VR))
1496 fseek(fp, PositionOnEntry, SEEK_SET);
1497 // When this element is known in the dictionary we shall use, e.g. for
1498 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1499 // dictionary entry. Still we have to flag the element as implicit since
1500 // we know now our assumption on expliciteness is not furfilled.
1502 if ( Entry->IsVRUnknown() )
1503 Entry->SetVR("Implicit");
1504 Entry->SetImplicitVR();
1509 * \ingroup gdcmParser
1510 * \brief Check the correspondance between the VR of the header entry
1511 * and the taken VR. If they are different, the header entry is
1512 * updated with the new VR.
1515 * @return false if the VR is incorrect of if the VR isn't referenced
1516 * otherwise, it returns true
1518 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1520 char msg[100]; // for sprintf
1521 bool RealExplicit = true;
1523 // Assume we are reading a falsely explicit VR file i.e. we reached
1524 // a tag where we expect reading a VR but are in fact we read the
1525 // first to bytes of the length. Then we will interogate (through find)
1526 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1527 // both GCC and VC++ implementations of the STL map. Hence when the
1528 // expected VR read happens to be non-ascii characters we consider
1529 // we hit falsely explicit VR tag.
1531 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1532 RealExplicit = false;
1534 // CLEANME searching the dicom_vr at each occurence is expensive.
1535 // PostPone this test in an optional integrity check at the end
1536 // of parsing or only in debug mode.
1537 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1538 RealExplicit= false;
1540 if ( !RealExplicit )
1542 // We thought this was explicit VR, but we end up with an
1543 // implicit VR tag. Let's backtrack.
1544 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1545 Entry->GetGroup(),Entry->GetElement());
1546 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1551 if ( Entry->IsVRUnknown() )
1553 // When not a dictionary entry, we can safely overwrite the VR.
1556 else if ( Entry->GetVR() != vr )
1558 // The VR present in the file and the dictionary disagree. We assume
1559 // the file writer knew best and use the VR of the file. Since it would
1560 // be unwise to overwrite the VR of a dictionary (since it would
1561 // compromise it's next user), we need to clone the actual DictEntry
1562 // and change the VR for the read one.
1563 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1564 Entry->GetGroup(),Entry->GetElement(),
1565 vr,"FIXME",Entry->GetName());
1566 Entry->SetDictEntry(NewEntry);
1572 * \ingroup gdcmParser
1573 * \brief Get the transformed value of the header entry. The VR value
1574 * is used to define the transformation to operate on the value
1575 * \warning NOT end user intended method !
1577 * @return Transformed entry value
1579 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1581 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1583 std::string val=Entry->GetValue();
1584 std::string vr=Entry->GetVR();
1585 guint32 length = Entry->GetLength();
1586 std::ostringstream s;
1589 if (vr == "US" || vr == "SS")
1594 for (int i=0; i < nbInt; i++)
1598 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1599 NewInt16 = SwapShort(NewInt16);
1604 else if (vr == "UL" || vr == "SL")
1609 for (int i=0; i < nbInt; i++)
1613 NewInt32=(val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1614 NewInt32=SwapLong(NewInt32);
1619 #ifdef GDCM_NO_ANSI_STRING_STREAM
1620 s << std::ends; // to avoid oddities on Solaris
1621 #endif //GDCM_NO_ANSI_STRING_STREAM
1625 return(Entry->GetValue());
1629 * \ingroup gdcmParser
1630 * \brief Get the reverse transformed value of the header entry. The VR
1631 * value is used to define the reverse transformation to operate on
1633 * \warning NOT end user intended method !
1635 * @return Reverse transformed entry value
1637 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1639 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1641 std::string vr=Entry->GetVR();
1642 std::ostringstream s;
1643 std::vector<std::string> tokens;
1646 if (vr == "US" || vr == "SS")
1650 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1651 Tokenize (Entry->GetValue(), tokens, "\\");
1652 for (unsigned int i=0; i<tokens.size();i++)
1654 NewInt16 = atoi(tokens[i].c_str());
1655 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1659 if (vr == "UL" || vr == "SL")
1663 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1664 Tokenize (Entry->GetValue(), tokens, "\\");
1665 for (unsigned int i=0; i<tokens.size();i++)
1667 NewInt32 = atoi(tokens[i].c_str());
1668 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1669 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1674 #ifdef GDCM_NO_ANSI_STRING_STREAM
1675 s << std::ends; // to avoid oddities on Solaris
1676 #endif //GDCM_NO_ANSI_STRING_STREAM
1680 return(Entry->GetValue());
1684 * \ingroup gdcmParser
1685 * \brief Skip a given Header Entry
1686 * \warning NOT end user intended method !
1689 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1691 SkipBytes(entry->GetLength());
1695 * \ingroup gdcmParser
1696 * \brief When the length of an element value is obviously wrong (because
1697 * the parser went Jabberwocky) one can hope improving things by
1698 * applying this heuristic.
1700 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1702 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1704 if ( FoundLength == 0xffffffff)
1709 // Sorry for the patch!
1710 // XMedCom did the trick to read some nasty GE images ...
1711 else if (FoundLength == 13)
1713 // The following 'if' will be removed when there is no more
1714 // images on Creatis HDs with a 13 length for Manufacturer...
1715 if ( (Entry->GetGroup() != 0x0008) ||
1716 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ) {
1717 // end of remove area
1719 Entry->SetReadLength(10); // a bug is to be fixed
1723 // to fix some garbage 'Leonardo' Siemens images
1724 // May be commented out to avoid overhead
1725 else if ( (Entry->GetGroup() == 0x0009) &&
1726 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) )
1729 Entry->SetReadLength(4); // a bug is to be fixed
1733 // to try to 'go inside' SeQuences (with length), and not to skip them
1734 else if ( Entry->GetVR() == "SQ")
1736 if (enableSequences) // only if the user does want to !
1740 // a SeQuence Element is beginning
1741 // Let's forget it's length
1742 // (we want to 'go inside')
1744 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1745 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1746 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1747 // if we don't, we lost 28800 characters from the Header :-(
1749 else if(Entry->GetGroup() == 0xfffe)
1751 // sometimes, length seems to be wrong
1752 FoundLength =0; // some more clever checking to be done !
1754 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1755 // causes troubles :-(
1758 Entry->SetUsableLength(FoundLength);
1762 * \ingroup gdcmParser
1763 * \brief Apply some heuristics to predict wether the considered
1764 * element value contains/represents an integer or not.
1765 * @param Entry The element value on which to apply the predicate.
1766 * @return The result of the heuristical predicate.
1768 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry)
1770 guint16 element = Entry->GetElement();
1771 guint16 group = Entry->GetGroup();
1772 std::string vr = Entry->GetVR();
1773 guint32 length = Entry->GetLength();
1775 // When we have some semantics on the element we just read, and if we
1776 // a priori know we are dealing with an integer, then we shall be
1777 // able to swap it's element value properly.
1778 if ( element == 0 ) // This is the group length of the group
1784 std::ostringstream s;
1785 s << "Erroneous Group Length element length on :" \
1786 << std::hex << group << " , " << element;
1787 dbg.Error("gdcmParser::IsAnInteger",
1791 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1798 * \ingroup gdcmParser
1803 guint32 gdcmParser::FindHeaderEntryLengthOB(void)
1805 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1808 long PositionOnEntry = ftell(fp);
1809 bool FoundSequenceDelimiter = false;
1810 guint32 TotalLength = 0;
1813 while ( ! FoundSequenceDelimiter)
1819 TotalLength += 4; // We even have to decount the group and element
1821 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1823 char msg[100]; // for sprintf. Sorry
1824 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1825 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1829 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1830 FoundSequenceDelimiter = true;
1831 else if ( n != 0xe000 )
1833 char msg[100]; // for sprintf. Sorry
1834 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1836 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1840 ItemLength = ReadInt32();
1841 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1842 // the ItemLength with ReadInt32
1843 SkipBytes(ItemLength);
1845 fseek(fp, PositionOnEntry, SEEK_SET);
1850 * \ingroup gdcmParser
1851 * \brief Reads a supposed to be 16 Bits integer
1852 * \ (swaps it depending on processor endianity)
1854 * @return integer acts as a boolean
1856 guint16 gdcmParser::ReadInt16(void)
1860 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1861 if ( item_read != 1 )
1864 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1874 * \ingroup gdcmParser
1875 * \brief Reads a supposed to be 32 Bits integer
1876 * \ (swaps it depending on processor endianity)
1880 guint32 gdcmParser::ReadInt32(void)
1884 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1885 if ( item_read != 1 )
1888 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1898 * \ingroup gdcmParser
1903 void gdcmParser::SkipBytes(guint32 NBytes)
1905 //FIXME don't dump the returned value
1906 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1910 * \ingroup gdcmParser
1913 void gdcmParser::Initialise(void)
1915 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1916 RefShaDict = (gdcmDict*)0;
1920 * \ingroup gdcmParser
1921 * \brief Discover what the swap code is (among little endian, big endian,
1922 * bad little endian, bad big endian).
1925 void gdcmParser::CheckSwap()
1927 // Fourth semantics:
1929 // ---> Warning : This fourth field is NOT part
1930 // of the 'official' Dicom Dictionnary
1931 // and should NOT be used.
1932 // (Not defined for all the groups
1933 // may be removed in a future release)
1936 // META Meta Information
1948 // NMI Nuclear Medicine
1950 // BFS Basic Film Session
1951 // BFB Basic Film Box
1952 // BIB Basic Image Box
1967 // The only guaranted way of finding the swap code is to find a
1968 // group tag since we know it's length has to be of four bytes i.e.
1969 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1970 // occurs when we can't find such group...
1972 guint32 x=4; // x : for ntohs
1973 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1977 char deb[HEADER_LENGTH_TO_READ];
1979 // First, compare HostByteOrder and NetworkByteOrder in order to
1980 // determine if we shall need to swap bytes (i.e. the Endian type).
1985 //cout << net2host << endl;
1987 // The easiest case is the one of a DICOM header, since it possesses a
1988 // file preamble where it suffice to look for the string "DICM".
1989 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1992 if(memcmp(entCur, "DICM", (size_t)4) == 0)
1994 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
1995 // Next, determine the value representation (VR). Let's skip to the
1996 // first element (0002, 0000) and check there if we find "UL"
1997 // - or "OB" if the 1st one is (0002,0001) -,
1998 // in which case we (almost) know it is explicit VR.
1999 // WARNING: if it happens to be implicit VR then what we will read
2000 // is the length of the group. If this ascii representation of this
2001 // length happens to be "UL" then we shall believe it is explicit VR.
2002 // FIXME: in order to fix the above warning, we could read the next
2003 // element value (or a couple of elements values) in order to make
2004 // sure we are not commiting a big mistake.
2005 // We need to skip :
2006 // * the 128 bytes of File Preamble (often padded with zeroes),
2007 // * the 4 bytes of "DICM" string,
2008 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2009 // i.e. a total of 136 bytes.
2012 // Use gdcmParser::dicom_vr to test all the possibilities
2013 // instead of just checking for UL, OB and UI !?
2014 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2015 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2016 (memcmp(entCur, "UI", (size_t)2) == 0) )
2018 filetype = ExplicitVR;
2019 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2020 "explicit Value Representation");
2024 filetype = ImplicitVR;
2025 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2026 "not an explicit Value Representation");
2031 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2032 "HostByteOrder != NetworkByteOrder");
2037 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2038 "HostByteOrder = NetworkByteOrder");
2041 // Position the file position indicator at first tag (i.e.
2042 // after the file preamble and the "DICM" string).
2044 fseek (fp, 132L, SEEK_SET);
2048 // Alas, this is not a DicomV3 file and whatever happens there is no file
2049 // preamble. We can reset the file position indicator to where the data
2050 // is (i.e. the beginning of the file).
2051 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2054 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2055 // By clean we mean that the length of the first tag is written down.
2056 // If this is the case and since the length of the first group HAS to be
2057 // four (bytes), then determining the proper swap code is straightforward.
2060 // We assume the array of char we are considering contains the binary
2061 // representation of a 32 bits integer. Hence the following dirty
2063 s = *((guint32 *)(entCur));
2084 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2085 "ACR/NEMA unfound swap info (time to raise bets)");
2088 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2089 // It is time for despaired wild guesses. So, let's assume this file
2090 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
2091 // not present. Then the only info we have is the net2host one.
2101 * \ingroup gdcmParser
2104 void gdcmParser::SwitchSwapToBigEndian(void)
2106 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2107 "Switching to BigEndian mode.");
2128 * \ingroup gdcmParser
2133 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2137 if ((guint32)NewSize >= (guint32)0xffffffff)
2139 MaxSizeLoadEntry = 0xffffffff;
2142 MaxSizeLoadEntry = NewSize;
2146 * \ingroup gdcmParser
2147 * \brief Searches both the public and the shadow dictionary (when they
2148 * exist) for the presence of the DictEntry with given name.
2149 * The public dictionary has precedence on the shadow one.
2150 * @param Name name of the searched DictEntry
2151 * @return Corresponding DictEntry when it exists, NULL otherwise.
2153 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2155 gdcmDictEntry *found = (gdcmDictEntry *)0;
2156 if (!RefPubDict && !RefShaDict)
2158 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2159 "we SHOULD have a default dictionary");
2163 found = RefPubDict->GetDictEntryByName(Name);
2169 found = RefShaDict->GetDictEntryByName(Name);
2177 * \ingroup gdcmParser
2178 * \brief Searches both the public and the shadow dictionary (when they
2179 * exist) for the presence of the DictEntry with given
2180 * group and element. The public dictionary has precedence on the
2182 * @param group group of the searched DictEntry
2183 * @param element element of the searched DictEntry
2184 * @return Corresponding DictEntry when it exists, NULL otherwise.
2186 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2188 gdcmDictEntry *found = (gdcmDictEntry *)0;
2189 if (!RefPubDict && !RefShaDict)
2191 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2192 "we SHOULD have a default dictionary");
2196 found = RefPubDict->GetDictEntryByNumber(group, element);
2202 found = RefShaDict->GetDictEntryByNumber(group, element);
2210 * \ingroup gdcmParser
2211 * \brief Read the next tag but WITHOUT loading it's value
2212 * @return On succes the newly created HeaderEntry, NULL on failure.
2214 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void)
2217 gdcmHeaderEntry *NewEntry;
2223 // We reached the EOF (or an error occured) and header parsing
2224 // has to be considered as finished.
2225 return (gdcmHeaderEntry *)0;
2227 NewEntry = NewHeaderEntryByNumber(g, n);
2228 FindHeaderEntryVR(NewEntry);
2229 FindHeaderEntryLength(NewEntry);
2236 NewEntry->SetOffset(ftell(fp));
2237 //if ( (g==0x7fe0) && (n==0x0010) )
2242 * \ingroup gdcmParser
2243 * \brief Build a new Element Value from all the low level arguments.
2244 * Check for existence of dictionary entry, and build
2245 * a default one when absent.
2246 * @param Name Name of the underlying DictEntry
2248 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2250 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2252 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2254 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2257 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2258 "failed to allocate gdcmHeaderEntry");
2259 return (gdcmHeaderEntry *)0;
2265 * \ingroup gdcmParser
2266 * \brief Request a new virtual dict entry to the dict set
2267 * @param group group of the underlying DictEntry
2268 * @param element element of the underlying DictEntry
2269 * @param vr VR of the underlying DictEntry
2270 * @param fourth owner group
2271 * @param name english name
2273 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2278 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2282 * \ingroup gdcmParser
2283 * \brief Build a new Element Value from all the low level arguments.
2284 * Check for existence of dictionary entry, and build
2285 * a default one when absent.
2286 * @param Group group of the underlying DictEntry
2287 * @param Elem element of the underlying DictEntry
2289 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2291 // Find out if the tag we encountered is in the dictionaries:
2292 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2294 DictEntry = NewVirtualDictEntry(Group, Elem);
2296 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2299 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2300 "failed to allocate gdcmHeaderEntry");
2307 * \ingroup gdcmParser
2308 * \brief Small utility function that creates a new manually crafted
2309 * (as opposed as read from the file) gdcmHeaderEntry with user
2310 * specified name and adds it to the public tag hash table.
2311 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2312 * @param NewTagName The name to be given to this new tag.
2313 * @param VR The Value Representation to be given to this new tag.
2314 * @return The newly hand crafted Element Value.
2316 gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2319 gdcmHeaderEntry *NewEntry = NULL;
2320 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2321 guint32 FreeElem = 0;
2322 gdcmDictEntry *DictEntry = NULL;
2324 FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2325 if (FreeElem == UINT32_MAX)
2327 dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2328 "Group 0xffff in Public Dict is full");
2332 DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2333 VR, "GDCM", NewTagName);
2334 NewEntry = new gdcmHeaderEntry(DictEntry);
2335 AddHeaderEntry(NewEntry);
2340 * \ingroup gdcmParser
2341 * \brief Generate a free TagKey i.e. a TagKey that is not present
2342 * in the TagHt dictionary.
2343 * @param group The generated tag must belong to this group.
2344 * @return The element of tag with given group which is fee.
2346 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2348 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2350 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2351 if (tagHT.count(key) == 0)
2357 //-----------------------------------------------------------------------------