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 ) {
46 enableSequences=enable_sequences;
48 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
49 filename = InFilename;
52 if ( !OpenFile(exception_on_error))
60 wasUpdated = 0; // will be set to 1 if user adds an entry
61 printLevel = 1; // 'Medium' header print by default
67 * @param exception_on_error
69 gdcmParser::gdcmParser(bool exception_on_error) {
72 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
75 wasUpdated = 0; // will be set to 1 if user adds an entry
76 printLevel = 1; // 'Heavy' header print by default
81 * \brief Canonical destructor.
83 gdcmParser::~gdcmParser (void) {
88 //-----------------------------------------------------------------------------
92 * \brief Prints the Header Entries (Dicom Elements)
93 * both from the H Table and the chained list
96 void gdcmParser::PrintEntry(std::ostream & os) {
99 s << "------------ gdcmParser::Print, using listEntries ----------------" << std::endl;
100 for (ListTag::iterator i = listEntries.begin();
101 i != listEntries.end();
104 (*i)->SetPrintLevel(printLevel);
111 * \ingroup gdcmParser
112 * \brief Prints The Dict Entries of THE public Dicom Dictionnry
115 void gdcmParser::PrintPubDict(std::ostream & os) {
116 RefPubDict->Print(os);
120 * \ingroup gdcmParser
121 * \brief Prints The Dict Entries of the current shadow Dicom Dictionnry
124 void gdcmParser::PrintShaDict(std::ostream & os) {
125 RefShaDict->Print(os);
128 //-----------------------------------------------------------------------------
131 * \ingroup gdcmParser
132 * \brief Get THE public dictionary used
134 gdcmDict *gdcmParser::GetPubDict(void)
140 * \ingroup gdcmParser
141 * \brief Get the current shadow dictionary
143 gdcmDict *gdcmParser::GetShaDict(void)
149 * \ingroup gdcmParser
150 * \brief Set the shadow dictionary used
151 * \param dict dictionary to use in shadow
153 bool gdcmParser::SetShaDict(gdcmDict *dict)
160 * \ingroup gdcmParser
161 * \brief Set the shadow dictionary used
162 * \param dictName name of the dictionary to use in shadow
164 bool gdcmParser::SetShaDict(DictKey dictName) {
165 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
170 * \ingroup gdcmParser
171 * \brief This predicate, based on hopefully reasonable heuristics,
172 * decides whether or not the current gdcmParser was properly parsed
173 * and contains the mandatory information for being considered as
174 * a well formed and usable Dicom/Acr File.
175 * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
178 bool gdcmParser::IsReadable(void)
180 std::string res = GetEntryByNumber(0x0028, 0x0005);
181 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 ) {
182 //std::cout << "error on : 28 5" << std::endl;
183 return false; // Image Dimensions
186 if ( !GetHeaderEntryByNumber(0x0028, 0x0100) ) {
187 //std::cout << "error on : 28 100" << std::endl;
188 return false; // "Bits Allocated"
190 if ( !GetHeaderEntryByNumber(0x0028, 0x0101) ){
191 // std::cout << "error on : 28 101" << std::endl;
192 return false; // "Bits Stored"
194 if ( !GetHeaderEntryByNumber(0x0028, 0x0102) ) {
195 //std::cout << "error on : 28 102" << std::endl;
196 return false; // "High Bit"
198 if ( !GetHeaderEntryByNumber(0x0028, 0x0103) ) {
199 //std::cout << "error on : 28 103" << std::endl;
200 return false; // "Pixel Representation"
206 * \ingroup gdcmParser
207 * \brief Determines if the Transfer Syntax was already encountered
208 * and if it corresponds to a ImplicitVRLittleEndian one.
210 * @return True when ImplicitVRLittleEndian found. False in all other cases.
212 bool gdcmParser::IsImplicitVRLittleEndianTransferSyntax(void) {
213 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
216 LoadHeaderEntrySafe(Element);
218 std::string Transfer = Element->GetValue();
219 if ( Transfer == "1.2.840.10008.1.2" )
225 * \ingroup gdcmParser
226 * \brief Determines if the Transfer Syntax was already encountered
227 * and if it corresponds to a ExplicitVRLittleEndian one.
229 * @return True when ExplicitVRLittleEndian found. False in all other cases.
231 bool gdcmParser::IsExplicitVRLittleEndianTransferSyntax(void)
233 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
236 LoadHeaderEntrySafe(Element);
238 std::string Transfer = Element->GetValue();
239 if ( Transfer == "1.2.840.10008.1.2.1" )
245 * \ingroup gdcmParser
246 * \brief Determines if the Transfer Syntax was already encountered
247 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
249 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
251 bool gdcmParser::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
253 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
256 LoadHeaderEntrySafe(Element);
258 std::string Transfer = Element->GetValue();
259 if ( Transfer == "1.2.840.10008.1.2.1.99" )
265 * \ingroup gdcmParser
266 * \brief Determines if the Transfer Syntax was already encountered
267 * and if it corresponds to a Explicit VR Big Endian one.
269 * @return True when big endian found. False in all other cases.
271 bool gdcmParser::IsExplicitVRBigEndianTransferSyntax(void)
273 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
276 LoadHeaderEntrySafe(Element);
278 std::string Transfer = Element->GetValue();
279 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
285 * \ingroup gdcmParser
286 * \brief returns the File Type
287 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
290 FileType gdcmParser::GetFileType(void) {
295 * \ingroup gdcmParser
296 * \brief opens the file
297 * @param exception_on_error
300 FILE *gdcmParser::OpenFile(bool exception_on_error)
303 fp=fopen(filename.c_str(),"rb");
304 if(exception_on_error)
307 throw gdcmFileError("gdcmParser::gdcmParser(const char *, bool)");
313 fread(&zero, (size_t)2, (size_t)1, fp);
315 //ACR -- or DICOM with no Preamble --
316 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
320 fseek(fp, 126L, SEEK_CUR);
322 fread(dicm, (size_t)4, (size_t)1, fp);
323 if( memcmp(dicm, "DICM", 4) == 0 )
327 dbg.Verbose(0, "gdcmParser::gdcmParser not DICOM/ACR", filename.c_str());
330 dbg.Verbose(0, "gdcmParser::gdcmParser cannot open file", filename.c_str());
336 * \ingroup gdcmParser
337 * \brief closes the file
338 * @return TRUE if the close was successfull
340 bool gdcmParser::CloseFile(void)
342 int closed = fclose(fp);
350 * \ingroup gdcmParser
352 * @param fp file pointer on an already open file
353 * @param type type of the File to be written
354 * (ACR-NEMA, ExplicitVR, ImplicitVR)
355 * @return always "True" ?!
357 bool gdcmParser::Write(FILE *fp, FileType type) {
359 // TODO The stuff has been rewritten using the chained list instead
361 // so we could remove the GroupHT from the gdcmParser
365 // TODO : move the following lines (and a lot of others, to be written)
366 // to a future function CheckAndCorrectHeader
369 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
370 // (FileType est un champ de gdcmParser ...)
371 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
373 // a moins de se livrer a un tres complique ajout des champs manquants.
374 // faire un CheckAndCorrectHeader (?)
377 if (type == ImplicitVR)
379 std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
380 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
382 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
383 // values with a VR of UI shall be padded with a single trailing null
384 // Dans le cas suivant on doit pader manuellement avec un 0
386 SetEntryLengthByNumber(18, 0x0002, 0x0010);
389 if (type == ExplicitVR)
391 std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
392 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
394 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
395 // values with a VR of UI shall be padded with a single trailing null
396 // Dans le cas suivant on doit pader manuellement avec un 0
398 SetEntryLengthByNumber(20, 0x0002, 0x0010);
402 if ( (type == ImplicitVR) || (type == ExplicitVR) )
403 UpdateGroupLength(false,type);
405 UpdateGroupLength(true,ACR);
407 WriteEntries(type, fp);
412 * \ingroup gdcmParser
413 * \brief Modifies the value of a given Header Entry (Dicom Element)
414 * if it exists; Creates it with the given value if it doesn't
415 * @param Value passed as a std::string
420 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
421 guint16 Group, guint16 Elem )
423 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
424 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
429 SetEntryByNumber(Value, Group, Elem);
434 * \ingroup gdcmParser
435 * \brief Modifies the value of a given Header Entry (Dicom Element)
436 * if it exists; Creates it with the given value if it doesn't
437 * @param Value passed as a char*
443 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
444 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
449 AddHeaderEntry(nvHeaderEntry);
451 std::string v = Value;
452 SetEntryByNumber(v, Group, Elem);
457 * \ingroup gdcmParser
458 * \brief Set a new value if the invoked element exists
459 * Seems to be useless !!!
465 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
466 std::string v = Value;
467 SetEntryByNumber(v, Group, Elem);
471 //-----------------------------------------------------------------------------
474 * \ingroup gdcmParser
475 * \brief Checks if a given Dicom Element exists
476 * \ within the H table
477 * @param group Group number of the searched Dicom Element
478 * @param element Element number of the searched Dicom Element
479 * @return number of occurences
481 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
482 std::string key = gdcmDictEntry::TranslateToKey(group, element );
483 return (tagHT.count(key));
487 * \ingroup gdcmParser
488 * \brief Searches within Header Entries (Dicom Elements) parsed with
489 * the public and private dictionaries
490 * for the element value of a given tag.
491 * @param tagName name of the searched element.
492 * @return Corresponding element value when it exists,
493 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
495 std::string gdcmParser::GetEntryByName(std::string tagName) {
496 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
497 if( dictEntry == NULL)
500 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
504 * \ingroup gdcmParser
505 * \brief Searches within Header Entries (Dicom Elements) parsed with
506 * the public and private dictionaries
507 * for the element value representation of a given tag.
509 * Obtaining the VR (Value Representation) might be needed by caller
510 * to convert the string typed content to caller's native type
511 * (think of C++ vs Python). The VR is actually of a higher level
512 * of semantics than just the native C++ type.
513 * @param tagName name of the searched element.
514 * @return Corresponding element value representation when it exists,
515 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
517 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
518 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
519 if( dictEntry == NULL)
522 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
523 dictEntry->GetElement());
524 return elem->GetVR();
528 * \ingroup gdcmParser
529 * \brief Searches within Header Entries (Dicom Elements) parsed with
530 * the public and private dictionaries
531 * for the element value representation of a given tag.
532 * @param group Group of the searched tag.
533 * @param element Element of the searched tag.
534 * @return Corresponding element value representation when it exists,
535 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
537 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element) {
538 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
539 if ( ! tagHT.count(key))
541 return tagHT.find(key)->second->GetValue();
545 * \ingroup gdcmParser
546 * \brief Searches within Header Entries (Dicom Elements) parsed with
547 * the public and private dictionaries
548 * for the element value representation of a given tag..
550 * Obtaining the VR (Value Representation) might be needed by caller
551 * to convert the string typed content to caller's native type
552 * (think of C++ vs Python). The VR is actually of a higher level
553 * of semantics than just the native C++ type.
554 * @param group Group of the searched tag.
555 * @param element Element of the searched tag.
556 * @return Corresponding element value representation when it exists,
557 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
559 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
560 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
563 return elem->GetVR();
567 * \ingroup gdcmParser
568 * \brief Sets the value (string) of the Header Entry (Dicom Element)
569 * @param content string value of the Dicom Element
570 * @param tagName name of the searched Dicom Element.
571 * @return true when found
573 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
574 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
575 if( dictEntry == NULL)
578 return(SetEntryByNumber(content,dictEntry->GetGroup(),
579 dictEntry->GetElement()));
583 * \ingroup gdcmParser
584 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
585 * through it's (group, element) and modifies it's content with
587 * \warning Don't use any longer : use SetPubEntryByNumber
588 * @param content new value to substitute with
589 * @param group group of the Dicom Element to modify
590 * @param element element of the Dicom Element to modify
592 bool gdcmParser::SetEntryByNumber(std::string content,
595 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
596 if ( ! tagHT.count(key))
598 int l = content.length();
599 if(l%2) // Odd length are padded with a space (020H).
602 content = content + '\0';
607 TagHeaderEntryHT::iterator p2;
608 // DO NOT remove the following lines : they explain the stuff
609 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
610 //p2=p.first; // iterator on the first synonym
611 //a=p2->second; // H Table target column (2-nd col)
614 a = ((tagHT.equal_range(key)).first)->second;
616 a-> SetValue(content);
618 std::string vr = a->GetVR();
621 if( (vr == "US") || (vr == "SS") )
623 else if( (vr == "UL") || (vr == "SL") )
633 * \ingroup gdcmParser
634 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
635 * in the PubHeaderEntrySet of this instance
636 * through it's (group, element) and modifies it's length with
638 * \warning Use with extreme caution.
639 * @param length new length to substitute with
640 * @param group group of the entry to modify
641 * @param element element of the Entry to modify
642 * @return 1 on success, 0 otherwise.
645 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
648 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
649 if ( ! tagHT.count(key))
651 if (length%2) length++; // length must be even
652 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
658 * \ingroup gdcmParser
659 * \brief Gets (from Header) the offset of a 'non string' element value
660 * \ (LoadElementValues has already be executed)
663 * @return File Offset of the Element Value
665 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem) {
666 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
669 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
670 "failed to Locate gdcmHeaderEntry");
673 return Entry->GetOffset();
677 * \ingroup gdcmParser
678 * \brief Gets (from Header) a 'non string' element value
679 * \ (LoadElementValues has already be executed)
682 * @return Pointer to the 'non string' area
684 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem) {
685 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
688 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
689 "failed to Locate gdcmHeaderEntry");
692 return Entry->GetVoidArea();
696 * \ingroup gdcmParser
697 * \brief Loads (from disk) the element content
698 * when a string is not suitable
700 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem) {
701 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
704 size_t o =(size_t)Element->GetOffset();
705 fseek(fp, o, SEEK_SET);
706 int l=Element->GetLength();
707 void * a = malloc(l);
711 SetEntryVoidAreaByNumber(a, Group, Elem);
712 // TODO check the result
713 size_t l2 = fread(a, 1, l ,fp);
723 * \ingroup gdcmParser
724 * \brief Sets a 'non string' value to a given Dicom Element
726 * @param group Group number of the searched Dicom Element
727 * @param element Element number of the searched Dicom Element
730 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,guint16 group, guint16 element)
732 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
733 if ( ! tagHT.count(key))
735 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
740 * \ingroup gdcmParser
741 * \brief Update the entries with the shadow dictionary. Only odd entries are
744 void gdcmParser::UpdateShaEntries(void)
746 gdcmDictEntry *entry;
749 for(ListTag::iterator it=listEntries.begin();
750 it!=listEntries.end();
753 // Odd group => from public dictionary
754 if((*it)->GetGroup()%2==0)
757 // Peer group => search the corresponding dict entry
759 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),
760 (*it)->GetElement());
764 if((*it)->IsImplicitVR())
769 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
772 // Set the new entry and the new value
773 (*it)->SetDictEntry(entry);
774 CheckHeaderEntryVR(*it,vr);
776 (*it)->SetValue(GetHeaderEntryValue(*it));
780 // Remove precedent value transformation
781 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
787 * \ingroup gdcmParser
788 * \brief Searches within the Header Entries for a Dicom Element of
790 * @param tagName name of the searched Dicom Element.
791 * @return Corresponding Dicom Element when it exists, and NULL
794 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName)
796 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
797 if( dictEntry == NULL)
800 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
804 * \ingroup gdcmParser
805 * \brief retrieves a Dicom Element (the first one) using (group, element)
806 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
807 * if you think it's NOT UNIQUE, check the count number
808 * and use iterators to retrieve ALL the Dicoms Elements within
809 * a given couple (group, element)
810 * @param group Group number of the searched Dicom Element
811 * @param element Element number of the searched Dicom Element
814 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
816 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
817 if ( ! tagHT.count(key))
819 return tagHT.find(key)->second;
823 * \ingroup gdcmParser
824 * \brief Loads the element while preserving the current
825 * underlying file position indicator as opposed to
826 * to LoadHeaderEntry that modifies it.
827 * @param entry Header Entry whose value shall be loaded.
830 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry)
832 long PositionOnEntry = ftell(fp);
833 LoadHeaderEntry(entry);
834 fseek(fp, PositionOnEntry, SEEK_SET);
838 * \ingroup gdcmParser
839 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
840 * \warning : to be re-written using the chained list instead of the H table.
841 * \warning : DO NOT use (doesn't work any longer because of the multimap)
842 * \todo : to be re-written using the chained list instead of the H table
843 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
844 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
846 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type)
851 gdcmHeaderEntry *elem;
853 std::string str_trash;
856 GroupHT groupHt; // to hold the length of each group
859 // typedef std::map<GroupKey, int> GroupHT;
861 gdcmHeaderEntry *elemZ;
863 // for each Tag in the DCM Header
865 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
870 gr = elem->GetGroup();
871 el = elem->GetElement();
874 sprintf(trash, "%04x", gr);
875 key = trash; // generate 'group tag'
877 // if the caller decided not to take SEQUENCEs into account
878 // e.g : he wants to write an ACR-NEMA File
880 if (SkipSequence && vr == "SQ")
883 // Still unsolved problem :
884 // we cannot find the 'Sequence Delimitation Item'
885 // since it's at the end of the Hash Table
888 // pas SEQUENCE en ACR-NEMA
890 // --> la descente a l'interieur' des SQ
891 // devrait etre faite avec une liste chainee, pas avec une HTable...
893 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
895 if (el == 0x0000) // the first elem is 0x0000
897 groupHt[key] = 0; // initialize group length
901 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
904 else // any elem but the first
906 if (type == ExplicitVR)
908 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
910 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
913 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
917 unsigned short int gr_bid;
919 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
923 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
924 // warning: unsigned int format, different type arg
925 sscanf(g->first.c_str(),"%x",&gr_bid);
926 tk = g->first + "|0000"; // generate the element full tag
928 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
930 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
931 elemZ = new gdcmHeaderEntry(tagZ);
933 AddHeaderEntry(elemZ); // create it
937 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
939 sprintf(trash ,"%d",g->second);
941 elemZ->SetValue(str_trash);
946 * \ingroup gdcmParser
947 * \brief writes on disc according to the requested format
948 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
949 * \ warning does NOT add the missing elements in the header :
950 * \ it's up to the user doing it !
951 * \ (function CheckHeaderCoherence to be written)
952 * @param type type of the File to be written
953 * (ACR-NEMA, ExplicitVR, ImplicitVR)
954 * @param _fp already open file pointer
956 void gdcmParser::WriteEntries(FileType type, FILE * _fp)
965 std::vector<std::string> tokens;
967 // uses now listEntries to iterate, not TagHt!
969 // pb : gdcmParser.Add does NOT update listEntries
970 // TODO : find a trick (in STL?) to do it, at low cost !
974 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
976 for (ListTag::iterator tag2=listEntries.begin();
977 tag2 != listEntries.end();
980 gr = (*tag2)->GetGroup();
981 el = (*tag2)->GetElement();
982 lgr = (*tag2)->GetLength();
983 val = (*tag2)->GetValue().c_str();
984 vr = (*tag2)->GetVR();
988 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
989 if (gr %2) continue; // ignore shadow groups
990 if (vr == "SQ" ) continue; // ignore Sequences
991 // TODO : find a trick to *skip* the SeQuences !
992 // Not only ignore the SQ element
993 if (gr == 0xfffe ) continue; // ignore delimiters
996 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
997 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
999 if ( (type == ExplicitVR) && (gr <= 0x0002) )
1002 guint16 z=0, shortLgr;
1003 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1005 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1007 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1008 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1014 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1019 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1022 if (vr == "US" || vr == "SS")
1024 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1025 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1026 for (unsigned int i=0; i<tokens.size();i++)
1028 val_uint16 = atoi(tokens[i].c_str());
1030 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1035 if (vr == "UL" || vr == "SL")
1037 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1038 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1039 for (unsigned int i=0; i<tokens.size();i++)
1041 val_uint32 = atoi(tokens[i].c_str());
1043 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1048 // Pixels are never loaded in the element !
1049 if ((gr == 0x7fe0) && (el == 0x0010) )
1052 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1057 * \ingroup gdcmParser
1058 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1060 * @return The properly swaped 32 bits integer.
1062 guint32 gdcmParser::SwapLong(guint32 a)
1069 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1070 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1074 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1078 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1081 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1088 * \ingroup gdcmParser
1089 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1091 * @return The properly unswaped 32 bits integer.
1093 guint32 gdcmParser::UnswapLong(guint32 a)
1095 return (SwapLong(a));
1099 * \ingroup gdcmParser
1100 * \brief Swaps the bytes so they agree with the processor order
1101 * @return The properly swaped 16 bits integer.
1103 guint16 gdcmParser::SwapShort(guint16 a)
1105 if ( (sw==4321) || (sw==2143) )
1106 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1111 * \ingroup gdcmParser
1112 * \brief Unswaps the bytes so they agree with the processor order
1113 * @return The properly unswaped 16 bits integer.
1115 guint16 gdcmParser::UnswapShort(guint16 a)
1117 return (SwapShort(a));
1120 //-----------------------------------------------------------------------------
1123 * \ingroup gdcmParser
1124 * \brief Parses the header of the file but WITHOUT loading element values.
1126 void gdcmParser::Parse(bool exception_on_error) throw(gdcmFormatError)
1128 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1132 while ( (newHeaderEntry = ReadNextHeaderEntry()) )
1134 SkipHeaderEntry(newHeaderEntry);
1135 AddHeaderEntry(newHeaderEntry);
1140 * \ingroup gdcmParser
1141 * \brief Loads the element values of all the Header Entries pointed in the
1142 * public Chained List.
1144 void gdcmParser::LoadHeaderEntries(void)
1147 for (ListTag::iterator i = GetListEntry().begin();
1148 i != GetListEntry().end();
1151 LoadHeaderEntry(*i);
1156 // Load 'non string' values
1157 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1158 if( PhotometricInterpretation == "PALETTE COLOR " )
1160 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1161 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1162 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1163 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1165 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1166 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1167 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1170 // --------------------------------------------------------------
1171 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1173 // if recognition code tells us we deal with a LibIDO image
1174 // we switch lineNumber and columnNumber
1176 std::string RecCode;
1177 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1178 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1179 RecCode == "CANRME_AILIBOD1_1." )
1181 filetype = ACR_LIBIDO;
1182 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1183 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1184 SetEntryByNumber(columns, 0x0028, 0x0010);
1185 SetEntryByNumber(rows , 0x0028, 0x0011);
1187 // ----------------- End of Special Patch ----------------
1191 * \ingroup gdcmParser
1192 * \brief Loads the element content if it's length is not bigger
1193 * than the value specified with
1194 * gdcmParser::SetMaxSizeLoadEntry()
1195 * @param Entry Header Entry (Dicom Element) to be dealt with
1197 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry)
1200 guint16 group = Entry->GetGroup();
1201 std::string vr= Entry->GetVR();
1202 guint32 length = Entry->GetLength();
1203 bool SkipLoad = false;
1205 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1207 // the test was commented out to 'go inside' the SeQuences
1208 // we don't any longer skip them !
1210 // if( vr == "SQ" ) // (DO NOT remove this comment)
1213 // A SeQuence "contains" a set of Elements.
1214 // (fffe e000) tells us an Element is beginning
1215 // (fffe e00d) tells us an Element just ended
1216 // (fffe e0dd) tells us the current SeQuence just ended
1217 if( group == 0xfffe )
1221 Entry->SetUsableLength(0);
1222 Entry->SetValue("gdcm::Skipped");
1226 // When the length is zero things are easy:
1229 Entry->SetValue("");
1233 // The elements whose length is bigger than the specified upper bound
1234 // are not loaded. Instead we leave a short notice of the offset of
1235 // the element content and it's length.
1236 if (length > MaxSizeLoadEntry)
1238 std::ostringstream s;
1239 s << "gdcm::NotLoaded.";
1240 s << " Address:" << (long)Entry->GetOffset();
1241 s << " Length:" << Entry->GetLength();
1242 s << " x(" << std::hex << Entry->GetLength() << ")";
1243 Entry->SetValue(s.str());
1247 // When integer(s) are expected, read and convert the following
1248 // n *(two or four bytes)
1249 // properly i.e. as integers as opposed to a strings.
1250 // Elements with Value Multiplicity > 1
1251 // contain a set of integers (not a single one)
1253 // Any compacter code suggested (?)
1254 if ( IsHeaderEntryAnInteger(Entry) )
1257 std::ostringstream s;
1259 if (vr == "US" || vr == "SS")
1262 NewInt = ReadInt16();
1266 for (int i=1; i < nbInt; i++)
1269 NewInt = ReadInt16();
1275 else if (vr == "UL" || vr == "SL")
1278 NewInt = ReadInt32();
1282 for (int i=1; i < nbInt; i++)
1285 NewInt = ReadInt32();
1290 #ifdef GDCM_NO_ANSI_STRING_STREAM
1291 s << std::ends; // to avoid oddities on Solaris
1292 #endif //GDCM_NO_ANSI_STRING_STREAM
1293 Entry->SetValue(s.str());
1297 // We need an additional byte for storing \0 that is not on disk
1298 std::string NewValue(length,0);
1299 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1300 if ( item_read != 1 )
1302 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1303 Entry->SetValue("gdcm::UnRead");
1306 Entry->SetValue(NewValue);
1310 * \ingroup gdcmParser
1311 * \brief add a new Dicom Element pointer to
1312 * the H Table and to the chained List
1313 * \warning push_bash in listEntries ONLY during ParseHeader
1314 * \todo something to allow further Elements addition,
1315 * \ when position to be taken care of
1316 * @param newHeaderEntry
1318 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry)
1320 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1321 listEntries.push_back(newHeaderEntry);
1326 * \ingroup gdcmParser
1328 * @param Entry Header Entry whose length of the value shall be loaded.
1332 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry)
1334 guint16 element = Entry->GetElement();
1335 guint16 group = Entry->GetGroup();
1336 std::string vr = Entry->GetVR();
1338 if( (element == 0x0010) && (group == 0x7fe0) )
1341 dbg.Verbose(2, "gdcmParser::FindLength: ",
1342 "we reached 7fe0 0010");
1345 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1347 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1349 // The following reserved two bytes (see PS 3.5-2001, section
1350 // 7.1.2 Data element structure with explicit vr p27) must be
1351 // skipped before proceeding on reading the length on 4 bytes.
1352 fseek(fp, 2L, SEEK_CUR);
1353 guint32 length32 = ReadInt32();
1355 if ( (vr == "OB") && (length32 == 0xffffffff) )
1357 Entry->SetLength(FindHeaderEntryLengthOB());
1360 FixHeaderEntryFoundLength(Entry, length32);
1364 // Length is encoded on 2 bytes.
1365 length16 = ReadInt16();
1367 // We can tell the current file is encoded in big endian (like
1368 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1369 // and it's value is the one of the encoding of a big endian file.
1370 // In order to deal with such big endian encoded files, we have
1371 // (at least) two strategies:
1372 // * when we load the "Transfer Syntax" tag with value of big endian
1373 // encoding, we raise the proper flags. Then we wait for the end
1374 // of the META group (0x0002) among which is "Transfer Syntax",
1375 // before switching the swap code to big endian. We have to postpone
1376 // the switching of the swap code since the META group is fully encoded
1377 // in little endian, and big endian coding only starts at the next
1378 // group. The corresponding code can be hard to analyse and adds
1379 // many additional unnecessary tests for regular tags.
1380 // * the second strategy consists in waiting for trouble, that shall
1381 // appear when we find the first group with big endian encoding. This
1382 // is easy to detect since the length of a "Group Length" tag (the
1383 // ones with zero as element number) has to be of 4 (0x0004). When we
1384 // encounter 1024 (0x0400) chances are the encoding changed and we
1385 // found a group with big endian encoding.
1386 // We shall use this second strategy. In order to make sure that we
1387 // can interpret the presence of an apparently big endian encoded
1388 // length of a "Group Length" without committing a big mistake, we
1389 // add an additional check: we look in the already parsed elements
1390 // for the presence of a "Transfer Syntax" whose value has to be "big
1391 // endian encoding". When this is the case, chances are we have got our
1392 // hands on a big endian encoded file: we switch the swap code to
1393 // big endian and proceed...
1394 if ( (element == 0x0000) && (length16 == 0x0400) )
1396 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1398 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1403 SwitchSwapToBigEndian();
1404 // Restore the unproperly loaded values i.e. the group, the element
1405 // and the dictionary entry depending on them.
1406 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1407 guint16 CorrectElem = SwapShort(Entry->GetElement());
1408 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1412 // This correct tag is not in the dictionary. Create a new one.
1413 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1415 // FIXME this can create a memory leaks on the old entry that be
1416 // left unreferenced.
1417 Entry->SetDictEntry(NewTag);
1420 // Heuristic: well some files are really ill-formed.
1421 if ( length16 == 0xffff)
1424 //dbg.Verbose(0, "gdcmParser::FindLength",
1425 // "Erroneous element length fixed.");
1426 // Actually, length= 0xffff means that we deal with
1427 // Unknown Sequence Length
1430 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1435 // Either implicit VR or a non DICOM conformal (see not below) explicit
1436 // VR that ommited the VR of (at least) this element. Farts happen.
1437 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1438 // on Data elements "Implicit and Explicit VR Data Elements shall
1439 // not coexist in a Data Set and Data Sets nested within it".]
1440 // Length is on 4 bytes.
1441 FixHeaderEntryFoundLength(Entry, ReadInt32());
1447 * \ingroup gdcmParser
1448 * \brief Find the Value Representation of the current Dicom Element.
1451 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1453 if (filetype != ExplicitVR)
1459 long PositionOnEntry = ftell(fp);
1460 // Warning: we believe this is explicit VR (Value Representation) because
1461 // we used a heuristic that found "UL" in the first tag. Alas this
1462 // doesn't guarantee that all the tags will be in explicit VR. In some
1463 // cases (see e-film filtered files) one finds implicit VR tags mixed
1464 // within an explicit VR file. Hence we make sure the present tag
1465 // is in explicit VR and try to fix things if it happens not to be
1468 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1470 if(!CheckHeaderEntryVR(Entry,VR))
1472 fseek(fp, PositionOnEntry, SEEK_SET);
1473 // When this element is known in the dictionary we shall use, e.g. for
1474 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1475 // dictionary entry. Still we have to flag the element as implicit since
1476 // we know now our assumption on expliciteness is not furfilled.
1478 if ( Entry->IsVRUnknown() )
1479 Entry->SetVR("Implicit");
1480 Entry->SetImplicitVR();
1485 * \ingroup gdcmParser
1486 * \brief Check the correspondance between the VR of the header entry
1487 * and the taken VR. If they are different, the header entry is
1488 * updated with the new VR.
1491 * @return false if the VR is incorrect of if the VR isn't referenced
1492 * otherwise, it returns true
1494 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1496 char msg[100]; // for sprintf
1497 bool RealExplicit = true;
1499 // Assume we are reading a falsely explicit VR file i.e. we reached
1500 // a tag where we expect reading a VR but are in fact we read the
1501 // first to bytes of the length. Then we will interogate (through find)
1502 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1503 // both GCC and VC++ implementations of the STL map. Hence when the
1504 // expected VR read happens to be non-ascii characters we consider
1505 // we hit falsely explicit VR tag.
1507 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1508 RealExplicit = false;
1510 // CLEANME searching the dicom_vr at each occurence is expensive.
1511 // PostPone this test in an optional integrity check at the end
1512 // of parsing or only in debug mode.
1513 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1514 RealExplicit= false;
1516 if ( !RealExplicit )
1518 // We thought this was explicit VR, but we end up with an
1519 // implicit VR tag. Let's backtrack.
1520 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1521 Entry->GetGroup(),Entry->GetElement());
1522 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1527 if ( Entry->IsVRUnknown() )
1529 // When not a dictionary entry, we can safely overwrite the VR.
1532 else if ( Entry->GetVR() != vr )
1534 // The VR present in the file and the dictionary disagree. We assume
1535 // the file writer knew best and use the VR of the file. Since it would
1536 // be unwise to overwrite the VR of a dictionary (since it would
1537 // compromise it's next user), we need to clone the actual DictEntry
1538 // and change the VR for the read one.
1539 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1540 Entry->GetGroup(),Entry->GetElement(),
1541 vr,"FIXME",Entry->GetName());
1542 Entry->SetDictEntry(NewEntry);
1548 * \ingroup gdcmParser
1549 * \brief Get the transformed value of the header entry. The VR value
1550 * is used to define the transformation to operate on the value
1551 * \warning NOT end user intended method !
1553 * @return Transformed entry value
1555 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1557 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1559 std::string val=Entry->GetValue();
1560 std::string vr=Entry->GetVR();
1561 guint32 length = Entry->GetLength();
1562 std::ostringstream s;
1565 if (vr == "US" || vr == "SS")
1570 for (int i=0; i < nbInt; i++)
1574 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1575 NewInt16 = SwapShort(NewInt16);
1580 else if (vr == "UL" || vr == "SL")
1585 for (int i=0; i < nbInt; i++)
1589 NewInt32=(val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1590 NewInt32=SwapLong(NewInt32);
1595 #ifdef GDCM_NO_ANSI_STRING_STREAM
1596 s << std::ends; // to avoid oddities on Solaris
1597 #endif //GDCM_NO_ANSI_STRING_STREAM
1601 return(Entry->GetValue());
1605 * \ingroup gdcmParser
1606 * \brief Get the reverse transformed value of the header entry. The VR
1607 * value is used to define the reverse transformation to operate on
1609 * \warning NOT end user intended method !
1611 * @return Reverse transformed entry value
1613 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1615 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1617 std::string vr=Entry->GetVR();
1618 std::ostringstream s;
1619 std::vector<std::string> tokens;
1622 if (vr == "US" || vr == "SS")
1626 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1627 Tokenize (Entry->GetValue(), tokens, "\\");
1628 for (unsigned int i=0; i<tokens.size();i++)
1630 NewInt16 = atoi(tokens[i].c_str());
1631 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1635 if (vr == "UL" || vr == "SL")
1639 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1640 Tokenize (Entry->GetValue(), tokens, "\\");
1641 for (unsigned int i=0; i<tokens.size();i++)
1643 NewInt32 = atoi(tokens[i].c_str());
1644 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1645 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1650 #ifdef GDCM_NO_ANSI_STRING_STREAM
1651 s << std::ends; // to avoid oddities on Solaris
1652 #endif //GDCM_NO_ANSI_STRING_STREAM
1656 return(Entry->GetValue());
1660 * \ingroup gdcmParser
1661 * \brief Skip a given Header Entry
1662 * \warning NOT end user intended method !
1665 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1667 SkipBytes(entry->GetLength());
1671 * \ingroup gdcmParser
1672 * \brief When the length of an element value is obviously wrong (because
1673 * the parser went Jabberwocky) one can hope improving things by
1674 * applying this heuristic.
1676 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1678 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1680 if ( FoundLength == 0xffffffff) {
1684 // Sorry for the patch!
1685 // XMedCom did the trick to read some nasty GE images ...
1686 else if (FoundLength == 13)
1688 // The following 'if' will be removed when there is no more
1689 // images on Creatis HDs with a 13 length for Manufacturer...
1690 if ( (Entry->GetGroup() != 0x0008) ||
1691 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ) {
1692 // end of remove area
1694 Entry->SetReadLength(10); // a bug is to be fixed
1698 // to fix some garbage 'Leonardo' Siemens images
1699 // May be commented out to avoid overhead
1700 else if ( (Entry->GetGroup() == 0x0009) &&
1701 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) )
1704 Entry->SetReadLength(4); // a bug is to be fixed
1708 // to try to 'go inside' SeQuences (with length), and not to skip them
1709 else if ( Entry->GetVR() == "SQ")
1711 if (enableSequences) // only if the user does want to !
1715 // a SeQuence Element is beginning
1716 // Let's forget it's length
1717 // (we want to 'go inside')
1719 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1720 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1721 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1722 // if we don't, we lost 28800 characters from the Header :-(
1724 else if(Entry->GetGroup() == 0xfffe)
1726 // sometimes, length seems to be wrong
1727 FoundLength =0; // some more clever checking to be done !
1729 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1730 // causes troubles :-(
1733 Entry->SetUsableLength(FoundLength);
1737 * \ingroup gdcmParser
1738 * \brief Apply some heuristics to predict wether the considered
1739 * element value contains/represents an integer or not.
1740 * @param Entry The element value on which to apply the predicate.
1741 * @return The result of the heuristical predicate.
1743 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry)
1745 guint16 element = Entry->GetElement();
1746 guint16 group = Entry->GetGroup();
1747 std::string vr = Entry->GetVR();
1748 guint32 length = Entry->GetLength();
1750 // When we have some semantics on the element we just read, and if we
1751 // a priori know we are dealing with an integer, then we shall be
1752 // able to swap it's element value properly.
1753 if ( element == 0 ) // This is the group length of the group
1759 std::ostringstream s;
1760 s << "Erroneous Group Length element length on :" \
1761 << std::hex << group << " , " << element;
1762 dbg.Error("gdcmParser::IsAnInteger",
1766 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1773 * \ingroup gdcmParser
1778 guint32 gdcmParser::FindHeaderEntryLengthOB(void)
1780 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1783 long PositionOnEntry = ftell(fp);
1784 bool FoundSequenceDelimiter = false;
1785 guint32 TotalLength = 0;
1788 while ( ! FoundSequenceDelimiter)
1794 TotalLength += 4; // We even have to decount the group and element
1796 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1798 char msg[100]; // for sprintf. Sorry
1799 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1800 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1804 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1805 FoundSequenceDelimiter = true;
1806 else if ( n != 0xe000 )
1808 char msg[100]; // for sprintf. Sorry
1809 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1811 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1815 ItemLength = ReadInt32();
1816 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1817 // the ItemLength with ReadInt32
1818 SkipBytes(ItemLength);
1820 fseek(fp, PositionOnEntry, SEEK_SET);
1825 * \ingroup gdcmParser
1826 * \brief Reads a supposed to be 16 Bits integer
1827 * \ (swaps it depending on processor endianity)
1829 * @return integer acts as a boolean
1831 guint16 gdcmParser::ReadInt16(void)
1835 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1836 if ( item_read != 1 )
1839 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1849 * \ingroup gdcmParser
1850 * \brief Reads a supposed to be 32 Bits integer
1851 * \ (swaps it depending on processor endianity)
1855 guint32 gdcmParser::ReadInt32(void)
1859 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1860 if ( item_read != 1 )
1863 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1873 * \ingroup gdcmParser
1878 void gdcmParser::SkipBytes(guint32 NBytes)
1880 //FIXME don't dump the returned value
1881 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1885 * \ingroup gdcmParser
1888 void gdcmParser::Initialise(void)
1890 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1891 RefShaDict = (gdcmDict*)0;
1895 * \ingroup gdcmParser
1896 * \brief Discover what the swap code is (among little endian, big endian,
1897 * bad little endian, bad big endian).
1900 void gdcmParser::CheckSwap()
1902 // Fourth semantics:
1904 // ---> Warning : This fourth field is NOT part
1905 // of the 'official' Dicom Dictionnary
1906 // and should NOT be used.
1907 // (Not defined for all the groups
1908 // may be removed in a future release)
1911 // META Meta Information
1923 // NMI Nuclear Medicine
1925 // BFS Basic Film Session
1926 // BFB Basic Film Box
1927 // BIB Basic Image Box
1942 // The only guaranted way of finding the swap code is to find a
1943 // group tag since we know it's length has to be of four bytes i.e.
1944 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1945 // occurs when we can't find such group...
1947 guint32 x=4; // x : for ntohs
1948 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1952 char deb[HEADER_LENGTH_TO_READ];
1954 // First, compare HostByteOrder and NetworkByteOrder in order to
1955 // determine if we shall need to swap bytes (i.e. the Endian type).
1960 //cout << net2host << endl;
1962 // The easiest case is the one of a DICOM header, since it possesses a
1963 // file preamble where it suffice to look for the string "DICM".
1964 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1967 if(memcmp(entCur, "DICM", (size_t)4) == 0)
1969 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
1970 // Next, determine the value representation (VR). Let's skip to the
1971 // first element (0002, 0000) and check there if we find "UL"
1972 // - or "OB" if the 1st one is (0002,0001) -,
1973 // in which case we (almost) know it is explicit VR.
1974 // WARNING: if it happens to be implicit VR then what we will read
1975 // is the length of the group. If this ascii representation of this
1976 // length happens to be "UL" then we shall believe it is explicit VR.
1977 // FIXME: in order to fix the above warning, we could read the next
1978 // element value (or a couple of elements values) in order to make
1979 // sure we are not commiting a big mistake.
1980 // We need to skip :
1981 // * the 128 bytes of File Preamble (often padded with zeroes),
1982 // * the 4 bytes of "DICM" string,
1983 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1984 // i.e. a total of 136 bytes.
1987 // Use gdcmParser::dicom_vr to test all the possibilities
1988 // instead of just checking for UL, OB and UI !?
1989 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
1990 (memcmp(entCur, "OB", (size_t)2) == 0) ||
1991 (memcmp(entCur, "UI", (size_t)2) == 0) )
1993 filetype = ExplicitVR;
1994 dbg.Verbose(1, "gdcmParser::CheckSwap:",
1995 "explicit Value Representation");
1999 filetype = ImplicitVR;
2000 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2001 "not an explicit Value Representation");
2006 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2007 "HostByteOrder != NetworkByteOrder");
2012 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2013 "HostByteOrder = NetworkByteOrder");
2016 // Position the file position indicator at first tag (i.e.
2017 // after the file preamble and the "DICM" string).
2019 fseek (fp, 132L, SEEK_SET);
2023 // Alas, this is not a DicomV3 file and whatever happens there is no file
2024 // preamble. We can reset the file position indicator to where the data
2025 // is (i.e. the beginning of the file).
2026 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2029 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2030 // By clean we mean that the length of the first tag is written down.
2031 // If this is the case and since the length of the first group HAS to be
2032 // four (bytes), then determining the proper swap code is straightforward.
2035 // We assume the array of char we are considering contains the binary
2036 // representation of a 32 bits integer. Hence the following dirty
2038 s = *((guint32 *)(entCur));
2059 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2060 "ACR/NEMA unfound swap info (time to raise bets)");
2063 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2064 // It is time for despaired wild guesses. So, let's assume this file
2065 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
2066 // not present. Then the only info we have is the net2host one.
2076 * \ingroup gdcmParser
2079 void gdcmParser::SwitchSwapToBigEndian(void)
2081 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2082 "Switching to BigEndian mode.");
2103 * \ingroup gdcmParser
2108 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2112 if ((guint32)NewSize >= (guint32)0xffffffff)
2114 MaxSizeLoadEntry = 0xffffffff;
2117 MaxSizeLoadEntry = NewSize;
2121 * \ingroup gdcmParser
2122 * \brief Searches both the public and the shadow dictionary (when they
2123 * exist) for the presence of the DictEntry with given name.
2124 * The public dictionary has precedence on the shadow one.
2125 * @param Name name of the searched DictEntry
2126 * @return Corresponding DictEntry when it exists, NULL otherwise.
2128 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2130 gdcmDictEntry *found = (gdcmDictEntry *)0;
2131 if (!RefPubDict && !RefShaDict)
2133 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2134 "we SHOULD have a default dictionary");
2138 found = RefPubDict->GetDictEntryByName(Name);
2144 found = RefShaDict->GetDictEntryByName(Name);
2152 * \ingroup gdcmParser
2153 * \brief Searches both the public and the shadow dictionary (when they
2154 * exist) for the presence of the DictEntry with given
2155 * group and element. The public dictionary has precedence on the
2157 * @param group group of the searched DictEntry
2158 * @param element element of the searched DictEntry
2159 * @return Corresponding DictEntry when it exists, NULL otherwise.
2161 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2163 gdcmDictEntry *found = (gdcmDictEntry *)0;
2164 if (!RefPubDict && !RefShaDict)
2166 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2167 "we SHOULD have a default dictionary");
2171 found = RefPubDict->GetDictEntryByNumber(group, element);
2177 found = RefShaDict->GetDictEntryByNumber(group, element);
2185 * \ingroup gdcmParser
2186 * \brief Read the next tag but WITHOUT loading it's value
2187 * @return On succes the newly created HeaderEntry, NULL on failure.
2189 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void)
2192 gdcmHeaderEntry *NewEntry;
2198 // We reached the EOF (or an error occured) and header parsing
2199 // has to be considered as finished.
2200 return (gdcmHeaderEntry *)0;
2202 NewEntry = NewHeaderEntryByNumber(g, n);
2203 FindHeaderEntryVR(NewEntry);
2204 FindHeaderEntryLength(NewEntry);
2211 NewEntry->SetOffset(ftell(fp));
2212 //if ( (g==0x7fe0) && (n==0x0010) )
2217 * \ingroup gdcmParser
2218 * \brief Build a new Element Value from all the low level arguments.
2219 * Check for existence of dictionary entry, and build
2220 * a default one when absent.
2221 * @param Name Name of the underlying DictEntry
2223 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2225 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2227 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2229 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2232 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2233 "failed to allocate gdcmHeaderEntry");
2234 return (gdcmHeaderEntry *)0;
2240 * \ingroup gdcmParser
2241 * \brief Request a new virtual dict entry to the dict set
2242 * @param group group of the underlying DictEntry
2243 * @param element element of the underlying DictEntry
2244 * @param vr VR of the underlying DictEntry
2245 * @param fourth owner group
2246 * @param name english name
2248 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2253 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2257 * \ingroup gdcmParser
2258 * \brief Build a new Element Value from all the low level arguments.
2259 * Check for existence of dictionary entry, and build
2260 * a default one when absent.
2261 * @param Group group of the underlying DictEntry
2262 * @param Elem element of the underlying DictEntry
2264 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2266 // Find out if the tag we encountered is in the dictionaries:
2267 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2269 DictEntry = NewVirtualDictEntry(Group, Elem);
2271 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2274 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2275 "failed to allocate gdcmHeaderEntry");
2282 * \ingroup gdcmParser
2283 * \brief Small utility function that creates a new manually crafted
2284 * (as opposed as read from the file) gdcmHeaderEntry with user
2285 * specified name and adds it to the public tag hash table.
2286 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2287 * @param NewTagName The name to be given to this new tag.
2288 * @param VR The Value Representation to be given to this new tag.
2289 * @return The newly hand crafted Element Value.
2291 gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2294 gdcmHeaderEntry *NewEntry = NULL;
2295 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2296 guint32 FreeElem = 0;
2297 gdcmDictEntry *DictEntry = NULL;
2299 FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2300 if (FreeElem == UINT32_MAX)
2302 dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2303 "Group 0xffff in Public Dict is full");
2307 DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2308 VR, "GDCM", NewTagName);
2309 NewEntry = new gdcmHeaderEntry(DictEntry);
2310 AddHeaderEntry(NewEntry);
2315 * \ingroup gdcmParser
2316 * \brief Generate a free TagKey i.e. a TagKey that is not present
2317 * in the TagHt dictionary.
2318 * @param group The generated tag must belong to this group.
2319 * @return The element of tag with given group which is fee.
2321 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2323 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2325 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2326 if (tagHT.count(key) == 0)
2332 //-----------------------------------------------------------------------------