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)
84 dicom_vr = (gdcmVR*)0;
85 Dicts = (gdcmDictSet*)0;
86 RefPubDict = (gdcmDict*)0;
87 RefShaDict = (gdcmDict*)0;
90 //-----------------------------------------------------------------------------
94 * \brief Prints the Header Entries (Dicom Elements)
95 * both from the H Table and the chained list
98 void gdcmParser::PrintPubEntry(std::ostream & os)
100 std::ostringstream s;
103 // char greltag[10]; //group element tag
105 s << "------------ using listEntries ----------------" << std::endl;
108 for (ListTag::iterator i = listEntries.begin();
109 i != listEntries.end();
112 (*i)->SetPrintLevel(printLevel);
119 * \ingroup gdcmParser
120 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
123 void gdcmParser::PrintPubDict(std::ostream & os)
125 RefPubDict->Print(os);
129 * \ingroup gdcmParser
130 * \brief Prints The Dict Entries of THE shadow Dicom Dictionnry
133 void gdcmParser::PrintShaDict(std::ostream & os)
135 RefShaDict->Print(os);
138 //-----------------------------------------------------------------------------
141 * \ingroup gdcmParser
142 * \brief This predicate, based on hopefully reasonable heuristics,
143 * decides whether or not the current gdcmParser was properly parsed
144 * and contains the mandatory information for being considered as
145 * a well formed and usable Dicom/Acr File.
146 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
149 bool gdcmParser::IsReadable(void)
151 std::string res = GetEntryByNumber(0x0028, 0x0005);
152 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
154 return false; // Image Dimensions
157 if ( !GetHeaderEntryByNumber(0x0028, 0x0100) )
158 return false; // "Bits Allocated"
159 if ( !GetHeaderEntryByNumber(0x0028, 0x0101) )
160 return false; // "Bits Stored"
161 if ( !GetHeaderEntryByNumber(0x0028, 0x0102) )
162 return false; // "High Bit"
163 if ( !GetHeaderEntryByNumber(0x0028, 0x0103) )
164 return false; // "Pixel Representation"
169 * \ingroup gdcmParser
170 * \brief Determines if the Transfer Syntax was already encountered
171 * and if it corresponds to a ImplicitVRLittleEndian one.
173 * @return True when ImplicitVRLittleEndian found. False in all other cases.
175 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void)
177 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
180 LoadHeaderEntrySafe(Element);
182 std::string Transfer = Element->GetValue();
183 if ( Transfer == "1.2.840.10008.1.2" )
189 * \ingroup gdcmParser
190 * \brief Determines if the Transfer Syntax was already encountered
191 * and if it corresponds to a ExplicitVRLittleEndian one.
193 * @return True when ExplicitVRLittleEndian found. False in all other cases.
195 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void)
197 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
200 LoadHeaderEntrySafe(Element);
202 std::string Transfer = Element->GetValue();
203 if ( Transfer == "1.2.840.10008.1.2.1" )
209 * \ingroup gdcmParser
210 * \brief Determines if the Transfer Syntax was already encountered
211 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
213 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
215 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
217 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
220 LoadHeaderEntrySafe(Element);
222 std::string Transfer = Element->GetValue();
223 if ( Transfer == "1.2.840.10008.1.2.1.99" )
229 * \ingroup gdcmParser
230 * \brief Determines if the Transfer Syntax was already encountered
231 * and if it corresponds to a Explicit VR Big Endian one.
233 * @return True when big endian found. False in all other cases.
235 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void)
237 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
240 LoadHeaderEntrySafe(Element);
242 std::string Transfer = Element->GetValue();
243 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
249 * \ingroup gdcmParser
250 * \brief returns the File Type
251 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
254 FileType gdcmParser::GetFileType(void) {
259 * \ingroup gdcmParser
260 * \brief opens the file
261 * @param exception_on_error
264 FILE *gdcmParser::OpenFile(bool exception_on_error)
267 fp=fopen(filename.c_str(),"rb");
268 if(exception_on_error)
271 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
277 fread(&zero, (size_t)2, (size_t)1, fp);
279 //ACR -- or DICOM with no Preamble --
280 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
284 fseek(fp, 126L, SEEK_CUR);
286 fread(dicm, (size_t)4, (size_t)1, fp);
287 if( memcmp(dicm, "DICM", 4) == 0 )
291 dbg.Verbose(0, "gdcmParser::gdcmParser not DICOM/ACR", filename.c_str());
294 std::cerr<<filename.c_str()<<std::endl;
295 dbg.Verbose(0, "gdcmParser::gdcmParser cannot open file", filename.c_str());
301 * \ingroup gdcmParser
302 * \brief closes the file
303 * @return TRUE if the close was successfull
305 bool gdcmParser::CloseFile(void)
307 int closed = fclose(fp);
315 * \ingroup gdcmParser
316 * \brief Parses the header of the file but WITHOUT loading element values.
318 void gdcmParser::Parse(bool exception_on_error) throw(gdcmFormatError)
320 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
324 while ( (newHeaderEntry = ReadNextHeaderEntry()) )
326 SkipHeaderEntry(newHeaderEntry);
327 AddHeaderEntry(newHeaderEntry);
332 * \ingroup gdcmParser
334 * @param fp file pointer on an already open file
335 * @param type type of the File to be written
336 * (ACR-NEMA, ExplicitVR, ImplicitVR)
337 * @return always "True" ?!
339 bool gdcmParser::Write(FILE *fp, FileType type)
342 // TODO The stuff has been rewritten using the chained list instead
344 // so we could remove the GroupHT from the gdcmParser
348 // TODO : move the following lines (and a lot of others, to be written)
349 // to a future function CheckAndCorrectHeader
352 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
353 // (FileType est un champ de gdcmParser ...)
354 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
356 // a moins de se livrer a un tres complique ajout des champs manquants.
357 // faire un CheckAndCorrectHeader (?)
360 if (type == ImplicitVR)
362 std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
363 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
365 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
366 // values with a VR of UI shall be padded with a single trailing null
367 // Dans le cas suivant on doit pader manuellement avec un 0
369 SetEntryLengthByNumber(18, 0x0002, 0x0010);
372 if (type == ExplicitVR)
374 std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
375 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
377 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
378 // values with a VR of UI shall be padded with a single trailing null
379 // Dans le cas suivant on doit pader manuellement avec un 0
381 SetEntryLengthByNumber(20, 0x0002, 0x0010);
385 if ( (type == ImplicitVR) || (type == ExplicitVR) )
386 UpdateGroupLength(false,type);
388 UpdateGroupLength(true,ACR);
390 WriteEntries(type, fp);
395 * \ingroup gdcmParser
396 * \brief Modifies the value of a given Header Entry (Dicom Element)
397 * if it exists; Creates it with the given value if it doesn't
398 * @param Value passed as a std::string
403 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
404 guint16 Group, guint16 Elem )
406 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
407 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
412 SetEntryByNumber(Value, Group, Elem);
417 * \ingroup gdcmParser
418 * \brief Modifies the value of a given Header Entry (Dicom Element)
419 * if it exists; Creates it with the given value if it doesn't
420 * @param Value passed as a char*
426 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem )
428 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
433 AddHeaderEntry(nvHeaderEntry);
435 std::string v = Value;
436 SetEntryByNumber(v, Group, Elem);
441 * \ingroup gdcmParser
442 * \brief Set a new value if the invoked element exists
443 * Seems to be useless !!!
449 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
451 std::string v = Value;
452 SetEntryByNumber(v, Group, Elem);
456 //-----------------------------------------------------------------------------
459 * \ingroup gdcmParser
460 * \brief Checks if a given Dicom Element exists
461 * \ within the H table
462 * @param group Group number of the searched Dicom Element
463 * @param element Element number of the searched Dicom Element
464 * @return number of occurences
466 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element )
468 std::string key = gdcmDictEntry::TranslateToKey(group, element );
469 return (tagHT.count(key));
473 * \ingroup gdcmParser
474 * \brief Searches within Header Entries (Dicom Elements) parsed with
475 * the public and private dictionaries
476 * for the element value of a given tag.
477 * \warning Don't use any longer : use GetPubEntryByName
478 * @param tagName name of the searched element.
479 * @return Corresponding element value when it exists,
480 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
482 std::string gdcmParser::GetEntryByName(std::string tagName)
484 gdcmDictEntry *dictEntry = RefPubDict->GetTagByName(tagName);
485 if( dictEntry == NULL)
488 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
492 * \ingroup gdcmParser
493 * \brief Searches within Header Entries (Dicom Elements) parsed with
494 * the public and private dictionaries
495 * for the element value representation of a given tag.
497 * Obtaining the VR (Value Representation) might be needed by caller
498 * to convert the string typed content to caller's native type
499 * (think of C++ vs Python). The VR is actually of a higher level
500 * of semantics than just the native C++ type.
501 * @param tagName name of the searched element.
502 * @return Corresponding element value representation when it exists,
503 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
505 std::string gdcmParser::GetEntryVRByName(std::string tagName)
507 gdcmDictEntry *dictEntry = RefPubDict->GetTagByName(tagName);
508 if( dictEntry == NULL)
511 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
512 dictEntry->GetElement());
513 return elem->GetVR();
517 * \ingroup gdcmParser
518 * \brief Searches within Header Entries (Dicom Elements) parsed with
519 * the public and private dictionaries
520 * for the element value representation of a given tag.
521 * @param group Group of the searched tag.
522 * @param element Element of the searched tag.
523 * @return Corresponding element value representation when it exists,
524 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
526 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element)
528 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
529 if ( ! tagHT.count(key))
531 return tagHT.find(key)->second->GetValue();
535 * \ingroup gdcmParser
536 * \brief Searches within Header Entries (Dicom Elements) parsed with
537 * the public and private dictionaries
538 * for the element value representation of a given tag..
540 * Obtaining the VR (Value Representation) might be needed by caller
541 * to convert the string typed content to caller's native type
542 * (think of C++ vs Python). The VR is actually of a higher level
543 * of semantics than just the native C++ type.
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::GetEntryVRByNumber(guint16 group, guint16 element)
551 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
554 return elem->GetVR();
558 * \ingroup gdcmParser
559 * \brief Sets the value (string) of the Header Entry (Dicom Element)
560 * @param content string value of the Dicom Element
561 * @param tagName name of the searched Dicom Element.
562 * @return true when found
564 bool gdcmParser::SetEntryByName(std::string content,std::string tagName)
566 gdcmDictEntry *dictEntry = RefPubDict->GetTagByName(tagName);
567 if( dictEntry == NULL)
570 return(SetEntryByNumber(content,dictEntry->GetGroup(),
571 dictEntry->GetElement()));
572 /* TagKey key = gdcmDictEntry::TranslateToKey(dictEntry->GetGroup(),
573 dictEntry->GetElement());
574 if ( GetPubEntry().count(key) == 0 )
577 int l = content.length();
578 if(l%2) // Odd length are padded with a space (020H).
581 content = content + '\0';
584 //tagHt[key]->SetValue(content);
587 TagHeaderEntryHT::iterator p2;
588 // DO NOT remove the following lines : they explain how the stuff works
589 //p= tagHt.equal_range(key); // get a pair of iterators first-last synonym
590 //p2=p.first; // iterator on the first synonym
591 //a=p2->second; // H Table target column (2-nd col)
593 a = ((GetPubEntry().equal_range(key)).first)->second;
594 a-> SetValue(content);
595 std::string vr = a->GetVR();
598 if( (vr == "US") || (vr == "SS") )
600 else if( (vr == "UL") || (vr == "SL") )
609 * \ingroup gdcmParser
610 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
611 * through it's (group, element) and modifies it's content with
613 * \warning Don't use any longer : use SetPubEntryByNumber
614 * @param content new value to substitute with
615 * @param group group of the Dicom Element to modify
616 * @param element element of the Dicom Element to modify
618 bool gdcmParser::SetEntryByNumber(std::string content,
622 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
623 if ( ! tagHT.count(key))
625 int l = content.length();
626 if(l%2) // Odd length are padded with a space (020H).
629 content = content + '\0';
632 //tagHT[key]->SetValue(content);
635 TagHeaderEntryHT::iterator p2;
636 // DO NOT remove the following lines : they explain the stuff
637 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
638 //p2=p.first; // iterator on the first synonym
639 //a=p2->second; // H Table target column (2-nd col)
642 a = ((tagHT.equal_range(key)).first)->second;
644 a-> SetValue(content);
646 //std::string vr = tagHT[key]->GetVR();
647 std::string vr = a->GetVR();
650 if( (vr == "US") || (vr == "SS") )
652 else if( (vr == "UL") || (vr == "SL") )
657 //tagHT[key]->SetLength(lgr);
663 * \ingroup gdcmParser
664 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
665 * in the PubHeaderEntrySet of this instance
666 * through it's (group, element) and modifies it's length with
668 * \warning Use with extreme caution.
669 * @param length new length to substitute with
670 * @param group group of the ElVal to modify
671 * @param element element of the ElVal to modify
672 * @return 1 on success, 0 otherwise.
675 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
676 guint16 group, guint16 element)
678 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
679 if ( ! tagHT.count(key))
681 if (length%2) length++; // length must be even
682 //tagHT[key]->SetLength(length);
683 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
689 * \ingroup gdcmParser
690 * \brief Gets (from Header) the offset of a 'non string' element value
691 * \ (LoadElementValues has already be executed)
694 * @return File Offset of the Element Value
696 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
698 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
701 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
702 "failed to Locate gdcmHeaderEntry");
705 return Entry->GetOffset();
709 * \ingroup gdcmParser
710 * \brief Gets (from Header) a 'non string' element value
711 * \ (LoadElementValues has already be executed)
714 * @return Pointer to the 'non string' area
716 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
718 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
721 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
722 "failed to Locate gdcmHeaderEntry");
725 return Entry->GetVoidArea();
729 * \ingroup gdcmParser
730 * \brief Loads (from disk) the element content
731 * when a string is not suitable
733 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem)
735 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
738 size_t o =(size_t)Element->GetOffset();
739 fseek(fp, o, SEEK_SET);
740 int l=Element->GetLength();
741 void * a = malloc(l);
745 SetEntryVoidAreaByNumber(a, Group, Elem);
746 // TODO check the result
747 size_t l2 = fread(a, 1, l ,fp);
757 * \ingroup gdcmParser
758 * \brief Sets a 'non string' value to a given Dicom Element
760 * @param group Group number of the searched Dicom Element
761 * @param element Element number of the searched Dicom Element
764 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,guint16 group, guint16 element)
766 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
767 if ( ! tagHT.count(key))
769 //tagHT[key]->SetVoidArea(area);
770 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
775 * \ingroup gdcmParser
776 * \brief Searches within the Header Entries for a Dicom Element of
778 * @param tagName name of the searched Dicom Element.
779 * @return Corresponding Dicom Element when it exists, and NULL
782 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName)
784 gdcmDictEntry *dictEntry = RefPubDict->GetTagByName(tagName);
785 if( dictEntry == NULL)
788 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
792 * \ingroup gdcmParser
793 * \brief retrieves a Dicom Element (the first one) using (group, element)
794 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
795 * if you think it's NOT UNIQUE, check the count number
796 * and use iterators to retrieve ALL the Dicoms Elements within
797 * a given couple (group, element)
798 * @param group Group number of the searched Dicom Element
799 * @param element Element number of the searched Dicom Element
802 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
804 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
805 if ( ! tagHT.count(key))
807 return tagHT.find(key)->second;
811 * \ingroup gdcmParser
812 * \brief Loads the element while preserving the current
813 * underlying file position indicator as opposed to
814 * to LoadHeaderEntry that modifies it.
815 * @param entry Header Entry whose value shall be loaded.
818 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry)
820 long PositionOnEntry = ftell(fp);
821 LoadHeaderEntry(entry);
822 fseek(fp, PositionOnEntry, SEEK_SET);
826 * \ingroup gdcmParser
827 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
828 * \warning : to be re-written using the chained list instead of the H table.
829 * \warning : DO NOT use (doesn't work any longer because of the multimap)
830 * \todo : to be re-written using the chained list instead of the H table
831 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
832 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
834 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type)
839 gdcmHeaderEntry *elem;
841 std::string str_trash;
844 GroupHT groupHt; // to hold the length of each group
847 // typedef std::map<GroupKey, int> GroupHT;
849 gdcmHeaderEntry *elemZ;
851 // for each Tag in the DCM Header
853 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
858 gr = elem->GetGroup();
859 el = elem->GetElement();
862 sprintf(trash, "%04x", gr);
863 key = trash; // generate 'group tag'
865 // if the caller decided not to take SEQUENCEs into account
866 // e.g : he wants to write an ACR-NEMA File
868 if (SkipSequence && vr == "SQ")
871 // Still unsolved problem :
872 // we cannot find the 'Sequence Delimitation Item'
873 // since it's at the end of the Hash Table
876 // pas SEQUENCE en ACR-NEMA
878 // --> la descente a l'interieur' des SQ
879 // devrait etre faite avec une liste chainee, pas avec une HTable...
881 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
883 if (el == 0x0000) // the first elem is 0x0000
885 groupHt[key] = 0; // initialize group length
889 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
892 else // any elem but the first
894 if (type == ExplicitVR)
896 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
898 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
901 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
905 unsigned short int gr_bid;
907 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
911 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
912 // warning: unsigned int format, different type arg
913 sscanf(g->first.c_str(),"%x",&gr_bid);
914 tk = g->first + "|0000"; // generate the element full tag
916 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
918 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
919 elemZ = new gdcmHeaderEntry(tagZ);
921 AddHeaderEntry(elemZ); // create it
925 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
927 sprintf(trash ,"%d",g->second);
929 elemZ->SetValue(str_trash);
934 * \ingroup gdcmParser
935 * \brief writes on disc according to the requested format
936 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
937 * \ warning does NOT add the missing elements in the header :
938 * \ it's up to the user doing it !
939 * \ (function CheckHeaderCoherence to be written)
940 * @param type type of the File to be written
941 * (ACR-NEMA, ExplicitVR, ImplicitVR)
942 * @param _fp already open file pointer
944 void gdcmParser::WriteEntries(FileType type, FILE * _fp)
953 std::vector<std::string> tokens;
955 // uses now listEntries to iterate, not TagHt!
957 // pb : gdcmParser.Add does NOT update listEntries
958 // TODO : find a trick (in STL?) to do it, at low cost !
962 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
964 for (ListTag::iterator tag2=listEntries.begin();
965 tag2 != listEntries.end();
968 gr = (*tag2)->GetGroup();
969 el = (*tag2)->GetElement();
970 lgr = (*tag2)->GetLength();
971 val = (*tag2)->GetValue().c_str();
972 vr = (*tag2)->GetVR();
976 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
977 if (gr %2) continue; // ignore shadow groups
978 if (vr == "SQ" ) continue; // ignore Sequences
979 // TODO : find a trick to *skip* the SeQuences !
980 // Not only ignore the SQ element
981 if (gr == 0xfffe ) continue; // ignore delimiters
984 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
985 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
987 if ( (type == ExplicitVR) && (gr <= 0x0002) )
990 guint16 z=0, shortLgr;
991 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
993 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
995 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
996 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1002 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1007 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1010 if (vr == "US" || vr == "SS")
1012 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1013 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1014 for (unsigned int i=0; i<tokens.size();i++)
1016 val_uint16 = atoi(tokens[i].c_str());
1018 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1023 if (vr == "UL" || vr == "SL")
1025 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1026 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1027 for (unsigned int i=0; i<tokens.size();i++)
1029 val_uint32 = atoi(tokens[i].c_str());
1031 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1036 // Pixels are never loaded in the element !
1037 if ((gr == 0x7fe0) && (el == 0x0010) )
1040 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1045 * \ingroup gdcmParser
1046 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1048 * @return The properly swaped 32 bits integer.
1050 guint32 gdcmParser::SwapLong(guint32 a)
1057 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1058 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1062 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1066 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1069 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1076 * \ingroup gdcmParser
1077 * \brief Swaps the bytes so they agree with the processor order
1078 * @return The properly swaped 16 bits integer.
1080 guint16 gdcmParser::SwapShort(guint16 a)
1082 if ( (sw==4321) || (sw==2143) )
1083 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1087 //-----------------------------------------------------------------------------
1090 * \ingroup gdcmParser
1091 * \brief Loads the element values of all the Header Entries pointed in the
1092 * public Chained List.
1094 void gdcmParser::LoadHeaderEntries(void)
1097 for (ListTag::iterator i = GetPubListEntry().begin();
1098 i != GetPubListEntry().end();
1101 LoadHeaderEntry(*i);
1106 // Load 'non string' values
1107 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1108 if( PhotometricInterpretation == "PALETTE COLOR " )
1110 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1111 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1112 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1113 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1115 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1116 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1117 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1120 // --------------------------------------------------------------
1121 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1123 // if recognition code tells us we deal with a LibIDO image
1124 // we switch lineNumber and columnNumber
1126 std::string RecCode;
1127 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1128 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1129 RecCode == "CANRME_AILIBOD1_1." )
1131 filetype = ACR_LIBIDO;
1132 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1133 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1134 SetEntryByNumber(columns, 0x0028, 0x0010);
1135 SetEntryByNumber(rows , 0x0028, 0x0011);
1137 // ----------------- End of Special Patch ----------------
1141 * \ingroup gdcmParser
1142 * \brief Loads the element content if it's length is not bigger
1143 * than the value specified with
1144 * gdcmParser::SetMaxSizeLoadEntry()
1145 * @param ElVal Header Entry (Dicom Element) to be dealt with
1147 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry * ElVal)
1150 guint16 group = ElVal->GetGroup();
1151 std::string vr= ElVal->GetVR();
1152 guint32 length = ElVal->GetLength();
1153 bool SkipLoad = false;
1155 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
1157 // the test was commented out to 'go inside' the SeQuences
1158 // we don't any longer skip them !
1160 // if( vr == "SQ" ) // (DO NOT remove this comment)
1163 // A SeQuence "contains" a set of Elements.
1164 // (fffe e000) tells us an Element is beginning
1165 // (fffe e00d) tells us an Element just ended
1166 // (fffe e0dd) tells us the current SeQuence just ended
1167 if( group == 0xfffe )
1172 ElVal->SetLength(0);
1173 ElVal->SetValue("gdcm::Skipped");
1177 // When the length is zero things are easy:
1180 ElVal->SetValue("");
1184 // The elements whose length is bigger than the specified upper bound
1185 // are not loaded. Instead we leave a short notice of the offset of
1186 // the element content and it's length.
1187 if (length > MaxSizeLoadEntry)
1189 std::ostringstream s;
1190 s << "gdcm::NotLoaded.";
1191 s << " Address:" << (long)ElVal->GetOffset();
1192 s << " Length:" << ElVal->GetLength();
1193 s << " x(" << std::hex << ElVal->GetLength() << ")";
1194 ElVal->SetValue(s.str());
1198 // When integer(s) are expected, read and convert the following
1199 // n *(two or four bytes)
1200 // properly i.e. as integers as opposed to a strings.
1201 // Elements with Value Multiplicity > 1
1202 // contain a set of integers (not a single one)
1204 // Any compacter code suggested (?)
1205 if ( IsHeaderEntryAnInteger(ElVal) )
1208 std::ostringstream s;
1210 if (vr == "US" || vr == "SS")
1213 NewInt = ReadInt16();
1217 for (int i=1; i < nbInt; i++)
1220 NewInt = ReadInt16();
1226 else if (vr == "UL" || vr == "SL")
1229 NewInt = ReadInt32();
1233 for (int i=1; i < nbInt; i++)
1236 NewInt = ReadInt32();
1241 #ifdef GDCM_NO_ANSI_STRING_STREAM
1242 s << std::ends; // to avoid oddities on Solaris
1243 #endif //GDCM_NO_ANSI_STRING_STREAM
1244 ElVal->SetValue(s.str());
1248 // We need an additional byte for storing \0 that is not on disk
1249 char* NewValue = (char*)malloc(length+1);
1252 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
1255 NewValue[length]= 0;
1257 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
1258 if ( item_read != 1 )
1261 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1262 ElVal->SetValue("gdcm::UnRead");
1265 ElVal->SetValue(NewValue);
1270 * \ingroup gdcmParser
1271 * \brief add a new Dicom Element pointer to
1272 * the H Table and to the chained List
1273 * \warning push_bash in listEntries ONLY during ParseHeader
1274 * \todo something to allow further Elements addition,
1275 * \ when position to be taken care of
1276 * @param newHeaderEntry
1278 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry * newHeaderEntry)
1280 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1281 listEntries.push_back(newHeaderEntry);
1286 * \ingroup gdcmParser
1288 * @param ElVal : Header Entry whose length of the value shall be loaded.
1292 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry * ElVal)
1294 guint16 element = ElVal->GetElement();
1295 guint16 group = ElVal->GetGroup();
1296 std::string vr = ElVal->GetVR();
1298 if( (element == 0x0010) && (group == 0x7fe0) )
1301 dbg.Verbose(2, "gdcmParser::FindLength: ",
1302 "we reached 7fe0 0010");
1305 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() )
1307 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1309 // The following reserved two bytes (see PS 3.5-2001, section
1310 // 7.1.2 Data element structure with explicit vr p27) must be
1311 // skipped before proceeding on reading the length on 4 bytes.
1312 fseek(fp, 2L, SEEK_CUR);
1313 guint32 length32 = ReadInt32();
1315 if ( (vr == "OB") && (length32 == 0xffffffff) )
1317 ElVal->SetLength(FindHeaderEntryLengthOB());
1320 FixHeaderEntryFoundLength(ElVal, length32);
1324 // Length is encoded on 2 bytes.
1325 length16 = ReadInt16();
1327 // We can tell the current file is encoded in big endian (like
1328 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1329 // and it's value is the one of the encoding of a big endian file.
1330 // In order to deal with such big endian encoded files, we have
1331 // (at least) two strategies:
1332 // * when we load the "Transfer Syntax" tag with value of big endian
1333 // encoding, we raise the proper flags. Then we wait for the end
1334 // of the META group (0x0002) among which is "Transfer Syntax",
1335 // before switching the swap code to big endian. We have to postpone
1336 // the switching of the swap code since the META group is fully encoded
1337 // in little endian, and big endian coding only starts at the next
1338 // group. The corresponding code can be hard to analyse and adds
1339 // many additional unnecessary tests for regular tags.
1340 // * the second strategy consists in waiting for trouble, that shall
1341 // appear when we find the first group with big endian encoding. This
1342 // is easy to detect since the length of a "Group Length" tag (the
1343 // ones with zero as element number) has to be of 4 (0x0004). When we
1344 // encounter 1024 (0x0400) chances are the encoding changed and we
1345 // found a group with big endian encoding.
1346 // We shall use this second strategy. In order to make sure that we
1347 // can interpret the presence of an apparently big endian encoded
1348 // length of a "Group Length" without committing a big mistake, we
1349 // add an additional check: we look in the already parsed elements
1350 // for the presence of a "Transfer Syntax" whose value has to be "big
1351 // endian encoding". When this is the case, chances are we have got our
1352 // hands on a big endian encoded file: we switch the swap code to
1353 // big endian and proceed...
1354 if ( (element == 0x0000) && (length16 == 0x0400) )
1356 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1358 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1363 SwitchSwapToBigEndian();
1364 // Restore the unproperly loaded values i.e. the group, the element
1365 // and the dictionary entry depending on them.
1366 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
1367 guint16 CorrectElem = SwapShort(ElVal->GetElement());
1368 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1372 // This correct tag is not in the dictionary. Create a new one.
1373 NewTag = Dicts->NewVirtualDictEntry(CorrectGroup, CorrectElem);
1375 // FIXME this can create a memory leaks on the old entry that be
1376 // left unreferenced.
1377 ElVal->SetDictEntry(NewTag);
1380 // Heuristic: well some files are really ill-formed.
1381 if ( length16 == 0xffff)
1384 //dbg.Verbose(0, "gdcmParser::FindLength",
1385 // "Erroneous element length fixed.");
1386 // Actually, length= 0xffff means that we deal with
1387 // Unknown Sequence Length
1390 FixHeaderEntryFoundLength(ElVal, (guint32)length16);
1394 // Either implicit VR or a non DICOM conformal (see not below) explicit
1395 // VR that ommited the VR of (at least) this element. Farts happen.
1396 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1397 // on Data elements "Implicit and Explicit VR Data Elements shall
1398 // not coexist in a Data Set and Data Sets nested within it".]
1399 // Length is on 4 bytes.
1400 FixHeaderEntryFoundLength(ElVal, ReadInt32());
1405 * \ingroup gdcmParser
1406 * \brief Find the Value Representation of the current Dicom Element.
1409 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *ElVal)
1411 if (filetype != ExplicitVR)
1417 char msg[100]; // for sprintf. Sorry
1419 long PositionOnEntry = ftell(fp);
1420 // Warning: we believe this is explicit VR (Value Representation) because
1421 // we used a heuristic that found "UL" in the first tag. Alas this
1422 // doesn't guarantee that all the tags will be in explicit VR. In some
1423 // cases (see e-film filtered files) one finds implicit VR tags mixed
1424 // within an explicit VR file. Hence we make sure the present tag
1425 // is in explicit VR and try to fix things if it happens not to be
1427 bool RealExplicit = true;
1429 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1431 vr = std::string(VR);
1433 // Assume we are reading a falsely explicit VR file i.e. we reached
1434 // a tag where we expect reading a VR but are in fact we read the
1435 // first to bytes of the length. Then we will interogate (through find)
1436 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1437 // both GCC and VC++ implementations of the STL map. Hence when the
1438 // expected VR read happens to be non-ascii characters we consider
1439 // we hit falsely explicit VR tag.
1441 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
1442 RealExplicit = false;
1444 // CLEANME searching the dicom_vr at each occurence is expensive.
1445 // PostPone this test in an optional integrity check at the end
1446 // of parsing or only in debug mode.
1447 if ( RealExplicit && !dicom_vr->Count(vr) )
1448 RealExplicit= false;
1452 if ( ElVal->IsVRUnknown() )
1454 // When not a dictionary entry, we can safely overwrite the VR.
1458 if ( ElVal->GetVR() == vr )
1460 // The VR we just read and the dictionary agree. Nothing to do.
1463 // The VR present in the file and the dictionary disagree. We assume
1464 // the file writer knew best and use the VR of the file. Since it would
1465 // be unwise to overwrite the VR of a dictionary (since it would
1466 // compromise it's next user), we need to clone the actual DictEntry
1467 // and change the VR for the read one.
1468 gdcmDictEntry* NewTag = Dicts->NewVirtualDictEntry(ElVal->GetGroup(),
1469 ElVal->GetElement(),
1473 ElVal->SetDictEntry(NewTag);
1477 // We thought this was explicit VR, but we end up with an
1478 // implicit VR tag. Let's backtrack.
1480 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1481 ElVal->GetGroup(),ElVal->GetElement());
1482 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1484 fseek(fp, PositionOnEntry, SEEK_SET);
1485 // When this element is known in the dictionary we shall use, e.g. for
1486 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1487 // dictionary entry. Still we have to flag the element as implicit since
1488 // we know now our assumption on expliciteness is not furfilled.
1490 if ( ElVal->IsVRUnknown() )
1491 ElVal->SetVR("Implicit");
1492 ElVal->SetImplicitVr();
1496 * \ingroup gdcmParser
1497 * \brief Skip a given Header Entry
1498 * \warning NOT end user intended method !
1502 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry * entry)
1504 SkipBytes(entry->GetLength());
1508 * \ingroup gdcmParser
1509 * \brief When the length of an element value is obviously wrong (because
1510 * the parser went Jabberwocky) one can hope improving things by
1511 * applying this heuristic.
1513 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry * ElVal, guint32 FoundLength)
1515 ElVal->SetReadLength(FoundLength); // will be updated only if a bug is found
1517 if ( FoundLength == 0xffffffff)
1522 // Sorry for the patch!
1523 // XMedCom did the trick to read some nasty GE images ...
1524 else if (FoundLength == 13)
1526 // The following 'if' will be removed when there is no more
1527 // images on Creatis HDs with a 13 length for Manufacturer...
1528 if ( (ElVal->GetGroup() != 0x0008) ||
1529 ( (ElVal->GetElement() != 0x0070) && (ElVal->GetElement() != 0x0080) ) ) {
1530 // end of remove area
1532 ElVal->SetReadLength(10); // a bug is to be fixed
1536 // to fix some garbage 'Leonardo' Siemens images
1537 // May be commented out to avoid overhead
1538 else if ( (ElVal->GetGroup() == 0x0009) &&
1539 ( (ElVal->GetElement() == 0x1113) || (ElVal->GetElement() == 0x1114) ) )
1542 ElVal->SetReadLength(4); // a bug is to be fixed
1546 // to try to 'go inside' SeQuences (with length), and not to skip them
1547 else if ( ElVal->GetVR() == "SQ")
1549 if (enableSequences) // only if the user does want to !
1553 // a SeQuence Element is beginning
1554 // Let's forget it's length
1555 // (we want to 'go inside')
1557 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1558 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1559 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1560 // if we don't, we lost 28800 characters from the Header :-(
1562 else if(ElVal->GetGroup() == 0xfffe)
1564 // sometimes, length seems to be wrong
1565 FoundLength =0; // some more clever checking to be done !
1567 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1568 // causes troubles :-(
1571 ElVal->SetUsableLength(FoundLength);
1575 * \ingroup gdcmParser
1576 * \brief Apply some heuristics to predict wether the considered
1577 * element value contains/represents an integer or not.
1578 * @param ElVal The element value on which to apply the predicate.
1579 * @return The result of the heuristical predicate.
1581 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry * ElVal)
1583 guint16 element = ElVal->GetElement();
1584 guint16 group = ElVal->GetGroup();
1585 std::string vr = ElVal->GetVR();
1586 guint32 length = ElVal->GetLength();
1588 // When we have some semantics on the element we just read, and if we
1589 // a priori know we are dealing with an integer, then we shall be
1590 // able to swap it's element value properly.
1591 if ( element == 0 ) // This is the group length of the group
1597 std::ostringstream s;
1598 s << "Erroneous Group Length element length on :" \
1599 << std::hex << group << " , " << element;
1600 dbg.Error("gdcmParser::IsAnInteger",
1604 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1611 * \ingroup gdcmParser
1616 guint32 gdcmParser::FindHeaderEntryLengthOB(void)
1618 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1621 long PositionOnEntry = ftell(fp);
1622 bool FoundSequenceDelimiter = false;
1623 guint32 TotalLength = 0;
1626 while ( ! FoundSequenceDelimiter)
1632 TotalLength += 4; // We even have to decount the group and element
1634 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1636 char msg[100]; // for sprintf. Sorry
1637 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1638 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1642 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1643 FoundSequenceDelimiter = true;
1644 else if ( n != 0xe000 )
1646 char msg[100]; // for sprintf. Sorry
1647 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1649 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1653 ItemLength = ReadInt32();
1654 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1655 // the ItemLength with ReadInt32
1656 SkipBytes(ItemLength);
1658 fseek(fp, PositionOnEntry, SEEK_SET);
1663 * \ingroup gdcmParser
1664 * \brief Reads a supposed to be 16 Bits integer
1665 * \ (swaps it depending on processor endianity)
1667 * @return integer acts as a boolean
1669 guint16 gdcmParser::ReadInt16(void)
1673 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1674 if ( item_read != 1 )
1677 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1687 * \ingroup gdcmParser
1688 * \brief Reads a supposed to be 32 Bits integer
1689 * \ (swaps it depending on processor endianity)
1693 guint32 gdcmParser::ReadInt32(void)
1697 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1698 if ( item_read != 1 )
1701 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1711 * \ingroup gdcmParser
1716 void gdcmParser::SkipBytes(guint32 NBytes)
1718 //FIXME don't dump the returned value
1719 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1723 * \ingroup gdcmParser
1726 void gdcmParser::Initialise(void)
1728 dicom_vr = gdcmGlobal::GetVR();
1729 dicom_ts = gdcmGlobal::GetTS();
1730 Dicts = gdcmGlobal::GetDicts();
1731 RefPubDict = Dicts->GetDefaultPubDict();
1732 RefShaDict = (gdcmDict*)0;
1736 * \ingroup gdcmParser
1737 * \brief Discover what the swap code is (among little endian, big endian,
1738 * bad little endian, bad big endian).
1741 void gdcmParser::CheckSwap()
1743 // Fourth semantics:
1745 // ---> Warning : This fourth field is NOT part
1746 // of the 'official' Dicom Dictionnary
1747 // and should NOT be used.
1748 // (Not defined for all the groups
1749 // may be removed in a future release)
1752 // META Meta Information
1764 // NMI Nuclear Medicine
1766 // BFS Basic Film Session
1767 // BFB Basic Film Box
1768 // BIB Basic Image Box
1783 // The only guaranted way of finding the swap code is to find a
1784 // group tag since we know it's length has to be of four bytes i.e.
1785 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1786 // occurs when we can't find such group...
1788 guint32 x=4; // x : for ntohs
1789 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1793 char deb[HEADER_LENGTH_TO_READ];
1795 // First, compare HostByteOrder and NetworkByteOrder in order to
1796 // determine if we shall need to swap bytes (i.e. the Endian type).
1801 //cout << net2host << endl;
1803 // The easiest case is the one of a DICOM header, since it possesses a
1804 // file preamble where it suffice to look for the string "DICM".
1805 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1808 if(memcmp(entCur, "DICM", (size_t)4) == 0)
1810 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
1811 // Next, determine the value representation (VR). Let's skip to the
1812 // first element (0002, 0000) and check there if we find "UL"
1813 // - or "OB" if the 1st one is (0002,0001) -,
1814 // in which case we (almost) know it is explicit VR.
1815 // WARNING: if it happens to be implicit VR then what we will read
1816 // is the length of the group. If this ascii representation of this
1817 // length happens to be "UL" then we shall believe it is explicit VR.
1818 // FIXME: in order to fix the above warning, we could read the next
1819 // element value (or a couple of elements values) in order to make
1820 // sure we are not commiting a big mistake.
1821 // We need to skip :
1822 // * the 128 bytes of File Preamble (often padded with zeroes),
1823 // * the 4 bytes of "DICM" string,
1824 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1825 // i.e. a total of 136 bytes.
1828 // Use gdcmParser::dicom_vr to test all the possibilities
1829 // instead of just checking for UL, OB and UI !?
1830 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
1831 (memcmp(entCur, "OB", (size_t)2) == 0) ||
1832 (memcmp(entCur, "UI", (size_t)2) == 0) )
1834 filetype = ExplicitVR;
1835 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1836 "explicit Value Representation");
1840 filetype = ImplicitVR;
1841 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1842 "not an explicit Value Representation");
1847 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1848 "HostByteOrder != NetworkByteOrder");
1853 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1854 "HostByteOrder = NetworkByteOrder");
1857 // Position the file position indicator at first tag (i.e.
1858 // after the file preamble and the "DICM" string).
1860 fseek (fp, 132L, SEEK_SET);
1864 // Alas, this is not a DicomV3 file and whatever happens there is no file
1865 // preamble. We can reset the file position indicator to where the data
1866 // is (i.e. the beginning of the file).
1867 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
1870 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1871 // By clean we mean that the length of the first tag is written down.
1872 // If this is the case and since the length of the first group HAS to be
1873 // four (bytes), then determining the proper swap code is straightforward.
1876 // We assume the array of char we are considering contains the binary
1877 // representation of a 32 bits integer. Hence the following dirty
1879 s = *((guint32 *)(entCur));
1900 dbg.Verbose(0, "gdcmParser::CheckSwap:",
1901 "ACR/NEMA unfound swap info (time to raise bets)");
1904 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1905 // It is time for despaired wild guesses. So, let's assume this file
1906 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
1907 // not present. Then the only info we have is the net2host one.
1917 * \ingroup gdcmParser
1920 void gdcmParser::SwitchSwapToBigEndian(void)
1922 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
1923 "Switching to BigEndian mode.");
1944 * \ingroup gdcmParser
1949 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
1953 if ((guint32)NewSize >= (guint32)0xffffffff)
1955 MaxSizeLoadEntry = 0xffffffff;
1958 MaxSizeLoadEntry = NewSize;
1962 * \ingroup gdcmParser
1963 * \brief Searches both the public and the shadow dictionary (when they
1964 * exist) for the presence of the DictEntry with given name.
1965 * The public dictionary has precedence on the shadow one.
1966 * @param Name name of the searched DictEntry
1967 * @return Corresponding DictEntry when it exists, NULL otherwise.
1969 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
1971 gdcmDictEntry *found = (gdcmDictEntry *)0;
1972 if (!RefPubDict && !RefShaDict)
1974 dbg.Verbose(0, "gdcmParser::GetDictEntry",
1975 "we SHOULD have a default dictionary");
1979 found = RefPubDict->GetTagByName(Name);
1985 found = RefShaDict->GetTagByName(Name);
1993 * \ingroup gdcmParser
1994 * \brief Searches both the public and the shadow dictionary (when they
1995 * exist) for the presence of the DictEntry with given
1996 * group and element. The public dictionary has precedence on the
1998 * @param group group of the searched DictEntry
1999 * @param element element of the searched DictEntry
2000 * @return Corresponding DictEntry when it exists, NULL otherwise.
2002 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2004 gdcmDictEntry *found = (gdcmDictEntry *)0;
2005 if (!RefPubDict && !RefShaDict)
2007 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2008 "we SHOULD have a default dictionary");
2012 found = RefPubDict->GetTagByNumber(group, element);
2018 found = RefShaDict->GetTagByNumber(group, element);
2026 * \ingroup gdcmParser
2027 * \brief Read the next tag but WITHOUT loading it's value
2028 * @return On succes the newly created HeaderEntry, NULL on failure.
2030 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void)
2033 gdcmHeaderEntry *NewElVal;
2039 // We reached the EOF (or an error occured) and header parsing
2040 // has to be considered as finished.
2041 return (gdcmHeaderEntry *)0;
2043 NewElVal = NewHeaderEntryByNumber(g, n);
2044 FindHeaderEntryVR(NewElVal);
2045 FindHeaderEntryLength(NewElVal);
2052 NewElVal->SetOffset(ftell(fp));
2053 //if ( (g==0x7fe0) && (n==0x0010) )
2058 * \ingroup gdcmParser
2059 * \brief Build a new Element Value from all the low level arguments.
2060 * Check for existence of dictionary entry, and build
2061 * a default one when absent.
2062 * @param Name Name of the underlying DictEntry
2064 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2066 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2068 NewTag = Dicts->NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2070 gdcmHeaderEntry* NewElVal = new gdcmHeaderEntry(NewTag);
2073 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2074 "failed to allocate gdcmHeaderEntry");
2075 return (gdcmHeaderEntry *)0;
2081 * \ingroup gdcmParser
2082 * \brief Build a new Element Value from all the low level arguments.
2083 * Check for existence of dictionary entry, and build
2084 * a default one when absent.
2085 * @param Group group of the underlying DictEntry
2086 * @param Elem element of the underlying DictEntry
2088 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2090 // Find out if the tag we encountered is in the dictionaries:
2091 gdcmDictEntry *NewTag = GetDictEntryByNumber(Group, Elem);
2093 NewTag = Dicts->NewVirtualDictEntry(Group, Elem);
2095 gdcmHeaderEntry* NewElVal = new gdcmHeaderEntry(NewTag);
2098 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2099 "failed to allocate gdcmHeaderEntry");
2106 * \ingroup gdcmParser
2107 * \brief Small utility function that creates a new manually crafted
2108 * (as opposed as read from the file) gdcmHeaderEntry with user
2109 * specified name and adds it to the public tag hash table.
2110 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2111 * @param NewTagName The name to be given to this new tag.
2112 * @param VR The Value Representation to be given to this new tag.
2113 * @return The newly hand crafted Element Value.
2115 gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2118 gdcmHeaderEntry *NewElVal = (gdcmHeaderEntry *)0;
2119 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2120 guint32 FreeElem = 0;
2121 gdcmDictEntry *NewEntry = (gdcmDictEntry *)0;
2123 FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2124 if (FreeElem == UINT32_MAX)
2126 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
2127 "Group 0xffff in Public Dict is full");
2131 NewEntry = Dicts->NewVirtualDictEntry(StuffGroup, FreeElem,
2132 VR, "GDCM", NewTagName);
2133 NewElVal = new gdcmHeaderEntry(NewEntry);
2134 AddHeaderEntry(NewElVal);
2139 * \ingroup gdcmParser
2140 * \brief Generate a free TagKey i.e. a TagKey that is not present
2141 * in the TagHt dictionary.
2142 * @param group The generated tag must belong to this group.
2143 * @return The element of tag with given group which is fee.
2145 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2147 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2149 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2150 if (tagHT.count(key) == 0)
2156 //-----------------------------------------------------------------------------