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)
360 // TODO The stuff has been rewritten using the chained list instead
362 // so we could remove the GroupHT from the gdcmParser
366 // TODO : move the following lines (and a lot of others, to be written)
367 // to a future function CheckAndCorrectHeader
370 // Comment pourrait-on savoir si le DcmHeader vient d'un fichier DicomV3 ou non
371 // (FileType est un champ de gdcmParser ...)
372 // WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
374 // a moins de se livrer a un tres complique ajout des champs manquants.
375 // faire un CheckAndCorrectHeader (?)
378 if (type == ImplicitVR)
380 std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
381 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
383 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
384 // values with a VR of UI shall be padded with a single trailing null
385 // Dans le cas suivant on doit pader manuellement avec un 0
387 SetEntryLengthByNumber(18, 0x0002, 0x0010);
390 if (type == ExplicitVR)
392 std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
393 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
395 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
396 // values with a VR of UI shall be padded with a single trailing null
397 // Dans le cas suivant on doit pader manuellement avec un 0
399 SetEntryLengthByNumber(20, 0x0002, 0x0010);
403 if ( (type == ImplicitVR) || (type == ExplicitVR) )
404 UpdateGroupLength(false,type);
406 UpdateGroupLength(true,ACR);
408 WriteEntries(type, fp);
413 * \ingroup gdcmParser
414 * \brief Modifies the value of a given Header Entry (Dicom Element)
415 * if it exists; Creates it with the given value if it doesn't
416 * @param Value passed as a std::string
421 bool gdcmParser::ReplaceOrCreateByNumber(std::string Value,
422 guint16 Group, guint16 Elem )
424 if (CheckIfEntryExistByNumber(Group, Elem) == 0) {
425 gdcmHeaderEntry *a =NewHeaderEntryByNumber(Group, Elem);
430 SetEntryByNumber(Value, Group, Elem);
435 * \ingroup gdcmParser
436 * \brief Modifies the value of a given Header Entry (Dicom Element)
437 * if it exists; Creates it with the given value if it doesn't
438 * @param Value passed as a char*
444 bool gdcmParser::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
445 gdcmHeaderEntry* nvHeaderEntry=NewHeaderEntryByNumber(Group, Elem);
450 AddHeaderEntry(nvHeaderEntry);
452 std::string v = Value;
453 SetEntryByNumber(v, Group, Elem);
458 * \ingroup gdcmParser
459 * \brief Set a new value if the invoked element exists
460 * Seems to be useless !!!
466 bool gdcmParser::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
467 std::string v = Value;
468 SetEntryByNumber(v, Group, Elem);
472 //-----------------------------------------------------------------------------
475 * \ingroup gdcmParser
476 * \brief Checks if a given Dicom Element exists
477 * \ within the H table
478 * @param group Group number of the searched Dicom Element
479 * @param element Element number of the searched Dicom Element
480 * @return number of occurences
482 int gdcmParser::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
483 std::string key = gdcmDictEntry::TranslateToKey(group, element );
484 return (tagHT.count(key));
488 * \ingroup gdcmParser
489 * \brief Searches within Header Entries (Dicom Elements) parsed with
490 * the public and private dictionaries
491 * for the element value of a given tag.
492 * @param tagName name of the searched element.
493 * @return Corresponding element value when it exists,
494 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
496 std::string gdcmParser::GetEntryByName(std::string tagName) {
497 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
498 if( dictEntry == NULL)
501 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
505 * \ingroup gdcmParser
506 * \brief Searches within Header Entries (Dicom Elements) parsed with
507 * the public and private dictionaries
508 * for the element value representation of a given tag.
510 * Obtaining the VR (Value Representation) might be needed by caller
511 * to convert the string typed content to caller's native type
512 * (think of C++ vs Python). The VR is actually of a higher level
513 * of semantics than just the native C++ type.
514 * @param tagName name of the searched element.
515 * @return Corresponding element value representation when it exists,
516 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
518 std::string gdcmParser::GetEntryVRByName(std::string tagName) {
519 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
520 if( dictEntry == NULL)
523 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
524 dictEntry->GetElement());
525 return elem->GetVR();
529 * \ingroup gdcmParser
530 * \brief Searches within Header Entries (Dicom Elements) parsed with
531 * the public and private dictionaries
532 * for the element value representation of a given tag.
533 * @param group Group of the searched tag.
534 * @param element Element of the searched tag.
535 * @return Corresponding element value representation when it exists,
536 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
538 std::string gdcmParser::GetEntryByNumber(guint16 group, guint16 element) {
539 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
540 if ( ! tagHT.count(key))
542 return tagHT.find(key)->second->GetValue();
546 * \ingroup gdcmParser
547 * \brief Searches within Header Entries (Dicom Elements) parsed with
548 * the public and private dictionaries
549 * for the element value representation of a given tag..
551 * Obtaining the VR (Value Representation) might be needed by caller
552 * to convert the string typed content to caller's native type
553 * (think of C++ vs Python). The VR is actually of a higher level
554 * of semantics than just the native C++ type.
555 * @param group Group of the searched tag.
556 * @param element Element of the searched tag.
557 * @return Corresponding element value representation when it exists,
558 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
560 std::string gdcmParser::GetEntryVRByNumber(guint16 group, guint16 element) {
561 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
564 return elem->GetVR();
568 * \ingroup gdcmParser
569 * \brief Sets the value (string) of the Header Entry (Dicom Element)
570 * @param content string value of the Dicom Element
571 * @param tagName name of the searched Dicom Element.
572 * @return true when found
574 bool gdcmParser::SetEntryByName(std::string content,std::string tagName) {
575 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
576 if( dictEntry == NULL)
579 return(SetEntryByNumber(content,dictEntry->GetGroup(),
580 dictEntry->GetElement()));
584 * \ingroup gdcmParser
585 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
586 * through it's (group, element) and modifies it's content with
588 * \warning Don't use any longer : use SetPubEntryByNumber
589 * @param content new value to substitute with
590 * @param group group of the Dicom Element to modify
591 * @param element element of the Dicom Element to modify
593 bool gdcmParser::SetEntryByNumber(std::string content,
596 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
597 if ( ! tagHT.count(key))
599 int l = content.length();
600 if(l%2) // Odd length are padded with a space (020H).
603 content = content + '\0';
606 //tagHT[key]->SetValue(content);
609 TagHeaderEntryHT::iterator p2;
610 // DO NOT remove the following lines : they explain the stuff
611 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
612 //p2=p.first; // iterator on the first synonym
613 //a=p2->second; // H Table target column (2-nd col)
616 a = ((tagHT.equal_range(key)).first)->second;
618 a-> SetValue(content);
620 //std::string vr = tagHT[key]->GetVR();
621 std::string vr = a->GetVR();
624 if( (vr == "US") || (vr == "SS") )
626 else if( (vr == "UL") || (vr == "SL") )
631 //tagHT[key]->SetLength(lgr);
637 * \ingroup gdcmParser
638 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
639 * in the PubHeaderEntrySet of this instance
640 * through it's (group, element) and modifies it's length with
642 * \warning Use with extreme caution.
643 * @param length new length to substitute with
644 * @param group group of the entry to modify
645 * @param element element of the Entry to modify
646 * @return 1 on success, 0 otherwise.
649 bool gdcmParser::SetEntryLengthByNumber(guint32 length,
650 guint16 group, guint16 element) {
651 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
652 if ( ! tagHT.count(key))
654 if (length%2) length++; // length must be even
655 //tagHT[key]->SetLength(length);
656 ( ((tagHT.equal_range(key)).first)->second )->SetLength(length);
662 * \ingroup gdcmParser
663 * \brief Gets (from Header) the offset of a 'non string' element value
664 * \ (LoadElementValues has already be executed)
667 * @return File Offset of the Element Value
669 size_t gdcmParser::GetEntryOffsetByNumber(guint16 Group, guint16 Elem) {
670 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
673 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
674 "failed to Locate gdcmHeaderEntry");
677 return Entry->GetOffset();
681 * \ingroup gdcmParser
682 * \brief Gets (from Header) a 'non string' element value
683 * \ (LoadElementValues has already be executed)
686 * @return Pointer to the 'non string' area
688 void * gdcmParser::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem) {
689 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
692 dbg.Verbose(1, "gdcmParser::GetHeaderEntryByNumber",
693 "failed to Locate gdcmHeaderEntry");
696 return Entry->GetVoidArea();
700 * \ingroup gdcmParser
701 * \brief Loads (from disk) the element content
702 * when a string is not suitable
704 void *gdcmParser::LoadEntryVoidArea(guint16 Group, guint16 Elem) {
705 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
708 size_t o =(size_t)Element->GetOffset();
709 fseek(fp, o, SEEK_SET);
710 int l=Element->GetLength();
711 void * a = malloc(l);
715 SetEntryVoidAreaByNumber(a, Group, Elem);
716 // TODO check the result
717 size_t l2 = fread(a, 1, l ,fp);
727 * \ingroup gdcmParser
728 * \brief Sets a 'non string' value to a given Dicom Element
730 * @param group Group number of the searched Dicom Element
731 * @param element Element number of the searched Dicom Element
734 bool gdcmParser::SetEntryVoidAreaByNumber(void * area,guint16 group, guint16 element)
736 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
737 if ( ! tagHT.count(key))
739 //tagHT[key]->SetVoidArea(area);
740 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
745 * \ingroup gdcmParser
746 * \brief Update the entries with the shadow dictionary. Only odd entries are
749 void gdcmParser::UpdateShaEntries(void)
751 gdcmDictEntry *entry;
754 for(ListTag::iterator it=listEntries.begin();
755 it!=listEntries.end();
758 // Odd group => from public dictionary
759 if((*it)->GetGroup()%2==0)
762 // Peer group => search the corresponding dict entry
764 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
768 if((*it)->IsImplicitVR())
773 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
776 // Set the new entry and the new value
777 (*it)->SetDictEntry(entry);
778 CheckHeaderEntryVR(*it,vr);
780 (*it)->SetValue(GetHeaderEntryValue(*it));
784 // Remove precedent value transformation
785 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
791 * \ingroup gdcmParser
792 * \brief Searches within the Header Entries for a Dicom Element of
794 * @param tagName name of the searched Dicom Element.
795 * @return Corresponding Dicom Element when it exists, and NULL
798 gdcmHeaderEntry *gdcmParser::GetHeaderEntryByName(std::string tagName)
800 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
801 if( dictEntry == NULL)
804 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
808 * \ingroup gdcmParser
809 * \brief retrieves a Dicom Element (the first one) using (group, element)
810 * \ warning (group, element) IS NOT an identifier inside the Dicom Header
811 * if you think it's NOT UNIQUE, check the count number
812 * and use iterators to retrieve ALL the Dicoms Elements within
813 * a given couple (group, element)
814 * @param group Group number of the searched Dicom Element
815 * @param element Element number of the searched Dicom Element
818 gdcmHeaderEntry* gdcmParser::GetHeaderEntryByNumber(guint16 group, guint16 element)
820 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
821 if ( ! tagHT.count(key))
823 return tagHT.find(key)->second;
827 * \ingroup gdcmParser
828 * \brief Loads the element while preserving the current
829 * underlying file position indicator as opposed to
830 * to LoadHeaderEntry that modifies it.
831 * @param entry Header Entry whose value shall be loaded.
834 void gdcmParser::LoadHeaderEntrySafe(gdcmHeaderEntry * entry)
836 long PositionOnEntry = ftell(fp);
837 LoadHeaderEntry(entry);
838 fseek(fp, PositionOnEntry, SEEK_SET);
842 * \ingroup gdcmParser
843 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
844 * \warning : to be re-written using the chained list instead of the H table.
845 * \warning : DO NOT use (doesn't work any longer because of the multimap)
846 * \todo : to be re-written using the chained list instead of the H table
847 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
848 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
850 void gdcmParser::UpdateGroupLength(bool SkipSequence, FileType type)
855 gdcmHeaderEntry *elem;
857 std::string str_trash;
860 GroupHT groupHt; // to hold the length of each group
863 // typedef std::map<GroupKey, int> GroupHT;
865 gdcmHeaderEntry *elemZ;
867 // for each Tag in the DCM Header
869 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
874 gr = elem->GetGroup();
875 el = elem->GetElement();
878 sprintf(trash, "%04x", gr);
879 key = trash; // generate 'group tag'
881 // if the caller decided not to take SEQUENCEs into account
882 // e.g : he wants to write an ACR-NEMA File
884 if (SkipSequence && vr == "SQ")
887 // Still unsolved problem :
888 // we cannot find the 'Sequence Delimitation Item'
889 // since it's at the end of the Hash Table
892 // pas SEQUENCE en ACR-NEMA
894 // --> la descente a l'interieur' des SQ
895 // devrait etre faite avec une liste chainee, pas avec une HTable...
897 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
899 if (el == 0x0000) // the first elem is 0x0000
901 groupHt[key] = 0; // initialize group length
905 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
908 else // any elem but the first
910 if (type == ExplicitVR)
912 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
914 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
917 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
921 unsigned short int gr_bid;
923 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
927 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
928 // warning: unsigned int format, different type arg
929 sscanf(g->first.c_str(),"%x",&gr_bid);
930 tk = g->first + "|0000"; // generate the element full tag
932 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
934 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
935 elemZ = new gdcmHeaderEntry(tagZ);
937 AddHeaderEntry(elemZ); // create it
941 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
943 sprintf(trash ,"%d",g->second);
945 elemZ->SetValue(str_trash);
950 * \ingroup gdcmParser
951 * \brief writes on disc according to the requested format
952 * \ (ACR-NEMA, ExplicitVR, ImplicitVR) the image
953 * \ warning does NOT add the missing elements in the header :
954 * \ it's up to the user doing it !
955 * \ (function CheckHeaderCoherence to be written)
956 * @param type type of the File to be written
957 * (ACR-NEMA, ExplicitVR, ImplicitVR)
958 * @param _fp already open file pointer
960 void gdcmParser::WriteEntries(FileType type, FILE * _fp)
969 std::vector<std::string> tokens;
971 // uses now listEntries to iterate, not TagHt!
973 // pb : gdcmParser.Add does NOT update listEntries
974 // TODO : find a trick (in STL?) to do it, at low cost !
978 // TODO (?) tester les echecs en ecriture (apres chaque fwrite)
980 for (ListTag::iterator tag2=listEntries.begin();
981 tag2 != listEntries.end();
984 gr = (*tag2)->GetGroup();
985 el = (*tag2)->GetElement();
986 lgr = (*tag2)->GetLength();
987 val = (*tag2)->GetValue().c_str();
988 vr = (*tag2)->GetVR();
992 if (gr < 0x0008) continue; // ignore pure DICOM V3 groups
993 if (gr %2) continue; // ignore shadow groups
994 if (vr == "SQ" ) continue; // ignore Sequences
995 // TODO : find a trick to *skip* the SeQuences !
996 // Not only ignore the SQ element
997 if (gr == 0xfffe ) continue; // ignore delimiters
1000 fwrite ( &gr,(size_t)2 ,(size_t)1 ,_fp); //group
1001 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1003 if ( (type == ExplicitVR) && (gr <= 0x0002) )
1006 guint16 z=0, shortLgr;
1007 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1009 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1011 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1012 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1018 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1023 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1026 if (vr == "US" || vr == "SS")
1028 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1029 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1030 for (unsigned int i=0; i<tokens.size();i++)
1032 val_uint16 = atoi(tokens[i].c_str());
1034 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1039 if (vr == "UL" || vr == "SL")
1041 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1042 Tokenize ((*tag2)->GetValue(), tokens, "\\");
1043 for (unsigned int i=0; i<tokens.size();i++)
1045 val_uint32 = atoi(tokens[i].c_str());
1047 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1052 // Pixels are never loaded in the element !
1053 if ((gr == 0x7fe0) && (el == 0x0010) )
1056 fwrite ( val,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1061 * \ingroup gdcmParser
1062 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1064 * @return The properly swaped 32 bits integer.
1066 guint32 gdcmParser::SwapLong(guint32 a)
1073 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1074 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1078 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1082 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1085 dbg.Error(" gdcmParser::SwapLong : unset swap code");
1092 * \ingroup gdcmParser
1093 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1095 * @return The properly unswaped 32 bits integer.
1097 guint32 gdcmParser::UnswapLong(guint32 a)
1099 return (SwapLong(a));
1103 * \ingroup gdcmParser
1104 * \brief Swaps the bytes so they agree with the processor order
1105 * @return The properly swaped 16 bits integer.
1107 guint16 gdcmParser::SwapShort(guint16 a)
1109 if ( (sw==4321) || (sw==2143) )
1110 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1115 * \ingroup gdcmParser
1116 * \brief Unswaps the bytes so they agree with the processor order
1117 * @return The properly unswaped 16 bits integer.
1119 guint16 gdcmParser::UnswapShort(guint16 a)
1121 return (SwapShort(a));
1124 //-----------------------------------------------------------------------------
1127 * \ingroup gdcmParser
1128 * \brief Parses the header of the file but WITHOUT loading element values.
1130 void gdcmParser::Parse(bool exception_on_error) throw(gdcmFormatError)
1132 gdcmHeaderEntry *newHeaderEntry = (gdcmHeaderEntry *)0;
1136 while ( (newHeaderEntry = ReadNextHeaderEntry()) )
1138 SkipHeaderEntry(newHeaderEntry);
1139 AddHeaderEntry(newHeaderEntry);
1144 * \ingroup gdcmParser
1145 * \brief Loads the element values of all the Header Entries pointed in the
1146 * public Chained List.
1148 void gdcmParser::LoadHeaderEntries(void)
1151 for (ListTag::iterator i = GetListEntry().begin();
1152 i != GetListEntry().end();
1155 LoadHeaderEntry(*i);
1160 // Load 'non string' values
1161 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
1162 if( PhotometricInterpretation == "PALETTE COLOR " )
1164 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
1165 LoadEntryVoidArea(0x0028,0x1201); // R LUT
1166 LoadEntryVoidArea(0x0028,0x1202); // G LUT
1167 LoadEntryVoidArea(0x0028,0x1203); // B LUT
1169 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1170 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1171 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1174 // --------------------------------------------------------------
1175 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1177 // if recognition code tells us we deal with a LibIDO image
1178 // we switch lineNumber and columnNumber
1180 std::string RecCode;
1181 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
1182 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1183 RecCode == "CANRME_AILIBOD1_1." )
1185 filetype = ACR_LIBIDO;
1186 std::string rows = GetEntryByNumber(0x0028, 0x0010);
1187 std::string columns = GetEntryByNumber(0x0028, 0x0011);
1188 SetEntryByNumber(columns, 0x0028, 0x0010);
1189 SetEntryByNumber(rows , 0x0028, 0x0011);
1191 // ----------------- End of Special Patch ----------------
1195 * \ingroup gdcmParser
1196 * \brief Loads the element content if it's length is not bigger
1197 * than the value specified with
1198 * gdcmParser::SetMaxSizeLoadEntry()
1199 * @param Entry Header Entry (Dicom Element) to be dealt with
1201 void gdcmParser::LoadHeaderEntry(gdcmHeaderEntry *Entry)
1204 guint16 group = Entry->GetGroup();
1205 std::string vr= Entry->GetVR();
1206 guint32 length = Entry->GetLength();
1207 bool SkipLoad = false;
1209 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1211 // the test was commented out to 'go inside' the SeQuences
1212 // we don't any longer skip them !
1214 // if( vr == "SQ" ) // (DO NOT remove this comment)
1217 // A SeQuence "contains" a set of Elements.
1218 // (fffe e000) tells us an Element is beginning
1219 // (fffe e00d) tells us an Element just ended
1220 // (fffe e0dd) tells us the current SeQuence just ended
1221 if( group == 0xfffe )
1226 Entry->SetLength(0);
1227 Entry->SetValue("gdcm::Skipped");
1231 // When the length is zero things are easy:
1234 Entry->SetValue("");
1238 // The elements whose length is bigger than the specified upper bound
1239 // are not loaded. Instead we leave a short notice of the offset of
1240 // the element content and it's length.
1241 if (length > MaxSizeLoadEntry)
1243 std::ostringstream s;
1244 s << "gdcm::NotLoaded.";
1245 s << " Address:" << (long)Entry->GetOffset();
1246 s << " Length:" << Entry->GetLength();
1247 s << " x(" << std::hex << Entry->GetLength() << ")";
1248 Entry->SetValue(s.str());
1252 // When integer(s) are expected, read and convert the following
1253 // n *(two or four bytes)
1254 // properly i.e. as integers as opposed to a strings.
1255 // Elements with Value Multiplicity > 1
1256 // contain a set of integers (not a single one)
1258 // Any compacter code suggested (?)
1259 if ( IsHeaderEntryAnInteger(Entry) )
1262 std::ostringstream s;
1264 if (vr == "US" || vr == "SS")
1267 NewInt = ReadInt16();
1271 for (int i=1; i < nbInt; i++)
1274 NewInt = ReadInt16();
1280 else if (vr == "UL" || vr == "SL")
1283 NewInt = ReadInt32();
1287 for (int i=1; i < nbInt; i++)
1290 NewInt = ReadInt32();
1295 #ifdef GDCM_NO_ANSI_STRING_STREAM
1296 s << std::ends; // to avoid oddities on Solaris
1297 #endif //GDCM_NO_ANSI_STRING_STREAM
1298 Entry->SetValue(s.str());
1302 // We need an additional byte for storing \0 that is not on disk
1303 std::string NewValue(length,0);
1304 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1305 if ( item_read != 1 )
1307 dbg.Verbose(1, "gdcmParser::LoadElementValue","unread element value");
1308 Entry->SetValue("gdcm::UnRead");
1311 Entry->SetValue(NewValue);
1315 * \ingroup gdcmParser
1316 * \brief add a new Dicom Element pointer to
1317 * the H Table and to the chained List
1318 * \warning push_bash in listEntries ONLY during ParseHeader
1319 * \todo something to allow further Elements addition,
1320 * \ when position to be taken care of
1321 * @param newHeaderEntry
1323 void gdcmParser::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry)
1325 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1326 listEntries.push_back(newHeaderEntry);
1331 * \ingroup gdcmParser
1333 * @param Entry Header Entry whose length of the value shall be loaded.
1337 void gdcmParser::FindHeaderEntryLength (gdcmHeaderEntry *Entry)
1339 guint16 element = Entry->GetElement();
1340 guint16 group = Entry->GetGroup();
1341 std::string vr = Entry->GetVR();
1343 if( (element == 0x0010) && (group == 0x7fe0) )
1346 dbg.Verbose(2, "gdcmParser::FindLength: ",
1347 "we reached 7fe0 0010");
1350 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1352 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1354 // The following reserved two bytes (see PS 3.5-2001, section
1355 // 7.1.2 Data element structure with explicit vr p27) must be
1356 // skipped before proceeding on reading the length on 4 bytes.
1357 fseek(fp, 2L, SEEK_CUR);
1358 guint32 length32 = ReadInt32();
1360 if ( (vr == "OB") && (length32 == 0xffffffff) )
1362 Entry->SetLength(FindHeaderEntryLengthOB());
1365 FixHeaderEntryFoundLength(Entry, length32);
1369 // Length is encoded on 2 bytes.
1370 length16 = ReadInt16();
1372 // We can tell the current file is encoded in big endian (like
1373 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1374 // and it's value is the one of the encoding of a big endian file.
1375 // In order to deal with such big endian encoded files, we have
1376 // (at least) two strategies:
1377 // * when we load the "Transfer Syntax" tag with value of big endian
1378 // encoding, we raise the proper flags. Then we wait for the end
1379 // of the META group (0x0002) among which is "Transfer Syntax",
1380 // before switching the swap code to big endian. We have to postpone
1381 // the switching of the swap code since the META group is fully encoded
1382 // in little endian, and big endian coding only starts at the next
1383 // group. The corresponding code can be hard to analyse and adds
1384 // many additional unnecessary tests for regular tags.
1385 // * the second strategy consists in waiting for trouble, that shall
1386 // appear when we find the first group with big endian encoding. This
1387 // is easy to detect since the length of a "Group Length" tag (the
1388 // ones with zero as element number) has to be of 4 (0x0004). When we
1389 // encounter 1024 (0x0400) chances are the encoding changed and we
1390 // found a group with big endian encoding.
1391 // We shall use this second strategy. In order to make sure that we
1392 // can interpret the presence of an apparently big endian encoded
1393 // length of a "Group Length" without committing a big mistake, we
1394 // add an additional check: we look in the already parsed elements
1395 // for the presence of a "Transfer Syntax" whose value has to be "big
1396 // endian encoding". When this is the case, chances are we have got our
1397 // hands on a big endian encoded file: we switch the swap code to
1398 // big endian and proceed...
1399 if ( (element == 0x0000) && (length16 == 0x0400) )
1401 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1403 dbg.Verbose(0, "gdcmParser::FindLength", "not explicit VR");
1408 SwitchSwapToBigEndian();
1409 // Restore the unproperly loaded values i.e. the group, the element
1410 // and the dictionary entry depending on them.
1411 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1412 guint16 CorrectElem = SwapShort(Entry->GetElement());
1413 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1417 // This correct tag is not in the dictionary. Create a new one.
1418 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1420 // FIXME this can create a memory leaks on the old entry that be
1421 // left unreferenced.
1422 Entry->SetDictEntry(NewTag);
1425 // Heuristic: well some files are really ill-formed.
1426 if ( length16 == 0xffff)
1429 //dbg.Verbose(0, "gdcmParser::FindLength",
1430 // "Erroneous element length fixed.");
1431 // Actually, length= 0xffff means that we deal with
1432 // Unknown Sequence Length
1435 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1440 // Either implicit VR or a non DICOM conformal (see not below) explicit
1441 // VR that ommited the VR of (at least) this element. Farts happen.
1442 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1443 // on Data elements "Implicit and Explicit VR Data Elements shall
1444 // not coexist in a Data Set and Data Sets nested within it".]
1445 // Length is on 4 bytes.
1446 FixHeaderEntryFoundLength(Entry, ReadInt32());
1452 * \ingroup gdcmParser
1453 * \brief Find the Value Representation of the current Dicom Element.
1456 void gdcmParser::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1458 if (filetype != ExplicitVR)
1464 long PositionOnEntry = ftell(fp);
1465 // Warning: we believe this is explicit VR (Value Representation) because
1466 // we used a heuristic that found "UL" in the first tag. Alas this
1467 // doesn't guarantee that all the tags will be in explicit VR. In some
1468 // cases (see e-film filtered files) one finds implicit VR tags mixed
1469 // within an explicit VR file. Hence we make sure the present tag
1470 // is in explicit VR and try to fix things if it happens not to be
1473 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
1475 if(!CheckHeaderEntryVR(Entry,VR))
1477 fseek(fp, PositionOnEntry, SEEK_SET);
1478 // When this element is known in the dictionary we shall use, e.g. for
1479 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1480 // dictionary entry. Still we have to flag the element as implicit since
1481 // we know now our assumption on expliciteness is not furfilled.
1483 if ( Entry->IsVRUnknown() )
1484 Entry->SetVR("Implicit");
1485 Entry->SetImplicitVR();
1490 * \ingroup gdcmParser
1491 * \brief Check the correspondance between the VR of the header entry
1492 * and the taken VR. If they are different, the header entry is
1493 * updated with the new VR.
1496 * @return false if the VR is incorrect of if the VR isn't referenced
1497 * otherwise, it returns true
1499 bool gdcmParser::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1501 char msg[100]; // for sprintf
1502 bool RealExplicit = true;
1504 // Assume we are reading a falsely explicit VR file i.e. we reached
1505 // a tag where we expect reading a VR but are in fact we read the
1506 // first to bytes of the length. Then we will interogate (through find)
1507 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1508 // both GCC and VC++ implementations of the STL map. Hence when the
1509 // expected VR read happens to be non-ascii characters we consider
1510 // we hit falsely explicit VR tag.
1512 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1513 RealExplicit = false;
1515 // CLEANME searching the dicom_vr at each occurence is expensive.
1516 // PostPone this test in an optional integrity check at the end
1517 // of parsing or only in debug mode.
1518 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1519 RealExplicit= false;
1521 if ( !RealExplicit )
1523 // We thought this was explicit VR, but we end up with an
1524 // implicit VR tag. Let's backtrack.
1525 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1526 Entry->GetGroup(),Entry->GetElement());
1527 dbg.Verbose(1, "gdcmParser::FindVR: ",msg);
1532 if ( Entry->IsVRUnknown() )
1534 // When not a dictionary entry, we can safely overwrite the VR.
1537 else if ( Entry->GetVR() != vr )
1539 // The VR present in the file and the dictionary disagree. We assume
1540 // the file writer knew best and use the VR of the file. Since it would
1541 // be unwise to overwrite the VR of a dictionary (since it would
1542 // compromise it's next user), we need to clone the actual DictEntry
1543 // and change the VR for the read one.
1544 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1545 Entry->GetGroup(),Entry->GetElement(),
1546 vr,"FIXME",Entry->GetName());
1547 Entry->SetDictEntry(NewEntry);
1553 * \ingroup gdcmParser
1554 * \brief Get the transformed value of the header entry. The VR value
1555 * is used to define the transformation to operate on the value
1556 * \warning NOT end user intended method !
1558 * @return Transformed entry value
1560 std::string gdcmParser::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1562 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1564 std::string val=Entry->GetValue();
1565 std::string vr=Entry->GetVR();
1566 guint32 length = Entry->GetLength();
1567 std::ostringstream s;
1570 if (vr == "US" || vr == "SS")
1575 for (int i=0; i < nbInt; i++)
1579 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1580 NewInt16 = SwapShort(NewInt16);
1585 else if (vr == "UL" || vr == "SL")
1590 for (int i=0; i < nbInt; i++)
1594 NewInt32=(val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1595 NewInt32=SwapLong(NewInt32);
1600 #ifdef GDCM_NO_ANSI_STRING_STREAM
1601 s << std::ends; // to avoid oddities on Solaris
1602 #endif //GDCM_NO_ANSI_STRING_STREAM
1606 return(Entry->GetValue());
1610 * \ingroup gdcmParser
1611 * \brief Get the reverse transformed value of the header entry. The VR
1612 * value is used to define the reverse transformation to operate on
1614 * \warning NOT end user intended method !
1616 * @return Reverse transformed entry value
1618 std::string gdcmParser::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1620 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1622 std::string vr=Entry->GetVR();
1623 std::ostringstream s;
1624 std::vector<std::string> tokens;
1627 if (vr == "US" || vr == "SS")
1631 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1632 Tokenize (Entry->GetValue(), tokens, "\\");
1633 for (unsigned int i=0; i<tokens.size();i++)
1635 NewInt16 = atoi(tokens[i].c_str());
1636 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1640 if (vr == "UL" || vr == "SL")
1644 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1645 Tokenize (Entry->GetValue(), tokens, "\\");
1646 for (unsigned int i=0; i<tokens.size();i++)
1648 NewInt32 = atoi(tokens[i].c_str());
1649 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1650 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1655 #ifdef GDCM_NO_ANSI_STRING_STREAM
1656 s << std::ends; // to avoid oddities on Solaris
1657 #endif //GDCM_NO_ANSI_STRING_STREAM
1661 return(Entry->GetValue());
1665 * \ingroup gdcmParser
1666 * \brief Skip a given Header Entry
1667 * \warning NOT end user intended method !
1670 void gdcmParser::SkipHeaderEntry(gdcmHeaderEntry *entry)
1672 SkipBytes(entry->GetLength());
1676 * \ingroup gdcmParser
1677 * \brief When the length of an element value is obviously wrong (because
1678 * the parser went Jabberwocky) one can hope improving things by
1679 * applying this heuristic.
1681 void gdcmParser::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1683 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1685 if ( FoundLength == 0xffffffff)
1690 // Sorry for the patch!
1691 // XMedCom did the trick to read some nasty GE images ...
1692 else if (FoundLength == 13)
1694 // The following 'if' will be removed when there is no more
1695 // images on Creatis HDs with a 13 length for Manufacturer...
1696 if ( (Entry->GetGroup() != 0x0008) ||
1697 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ) {
1698 // end of remove area
1700 Entry->SetReadLength(10); // a bug is to be fixed
1704 // to fix some garbage 'Leonardo' Siemens images
1705 // May be commented out to avoid overhead
1706 else if ( (Entry->GetGroup() == 0x0009) &&
1707 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) )
1710 Entry->SetReadLength(4); // a bug is to be fixed
1714 // to try to 'go inside' SeQuences (with length), and not to skip them
1715 else if ( Entry->GetVR() == "SQ")
1717 if (enableSequences) // only if the user does want to !
1721 // a SeQuence Element is beginning
1722 // Let's forget it's length
1723 // (we want to 'go inside')
1725 // Pb : *normaly* fffe|e000 is just a marker, its length *should be* zero
1726 // in gdcm-MR-PHILIPS-16-Multi-Seq.dcm we find lengthes as big as 28800
1727 // if we set the length to zero IsHeaderEntryAnInteger() breaks...
1728 // if we don't, we lost 28800 characters from the Header :-(
1730 else if(Entry->GetGroup() == 0xfffe)
1732 // sometimes, length seems to be wrong
1733 FoundLength =0; // some more clever checking to be done !
1735 // only gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1736 // causes troubles :-(
1739 Entry->SetUsableLength(FoundLength);
1743 * \ingroup gdcmParser
1744 * \brief Apply some heuristics to predict wether the considered
1745 * element value contains/represents an integer or not.
1746 * @param Entry The element value on which to apply the predicate.
1747 * @return The result of the heuristical predicate.
1749 bool gdcmParser::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry)
1751 guint16 element = Entry->GetElement();
1752 guint16 group = Entry->GetGroup();
1753 std::string vr = Entry->GetVR();
1754 guint32 length = Entry->GetLength();
1756 // When we have some semantics on the element we just read, and if we
1757 // a priori know we are dealing with an integer, then we shall be
1758 // able to swap it's element value properly.
1759 if ( element == 0 ) // This is the group length of the group
1765 std::ostringstream s;
1766 s << "Erroneous Group Length element length on :" \
1767 << std::hex << group << " , " << element;
1768 dbg.Error("gdcmParser::IsAnInteger",
1772 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1779 * \ingroup gdcmParser
1784 guint32 gdcmParser::FindHeaderEntryLengthOB(void)
1786 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1789 long PositionOnEntry = ftell(fp);
1790 bool FoundSequenceDelimiter = false;
1791 guint32 TotalLength = 0;
1794 while ( ! FoundSequenceDelimiter)
1800 TotalLength += 4; // We even have to decount the group and element
1802 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */
1804 char msg[100]; // for sprintf. Sorry
1805 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1806 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1810 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
1811 FoundSequenceDelimiter = true;
1812 else if ( n != 0xe000 )
1814 char msg[100]; // for sprintf. Sorry
1815 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1817 dbg.Verbose(1, "gdcmParser::FindLengthOB: ",msg);
1821 ItemLength = ReadInt32();
1822 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1823 // the ItemLength with ReadInt32
1824 SkipBytes(ItemLength);
1826 fseek(fp, PositionOnEntry, SEEK_SET);
1831 * \ingroup gdcmParser
1832 * \brief Reads a supposed to be 16 Bits integer
1833 * \ (swaps it depending on processor endianity)
1835 * @return integer acts as a boolean
1837 guint16 gdcmParser::ReadInt16(void)
1841 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1842 if ( item_read != 1 )
1845 dbg.Verbose(0, "gdcmParser::ReadInt16", " File Error");
1855 * \ingroup gdcmParser
1856 * \brief Reads a supposed to be 32 Bits integer
1857 * \ (swaps it depending on processor endianity)
1861 guint32 gdcmParser::ReadInt32(void)
1865 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1866 if ( item_read != 1 )
1869 dbg.Verbose(0, "gdcmParser::ReadInt32", " File Error");
1879 * \ingroup gdcmParser
1884 void gdcmParser::SkipBytes(guint32 NBytes)
1886 //FIXME don't dump the returned value
1887 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1891 * \ingroup gdcmParser
1894 void gdcmParser::Initialise(void)
1896 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1897 RefShaDict = (gdcmDict*)0;
1901 * \ingroup gdcmParser
1902 * \brief Discover what the swap code is (among little endian, big endian,
1903 * bad little endian, bad big endian).
1906 void gdcmParser::CheckSwap()
1908 // Fourth semantics:
1910 // ---> Warning : This fourth field is NOT part
1911 // of the 'official' Dicom Dictionnary
1912 // and should NOT be used.
1913 // (Not defined for all the groups
1914 // may be removed in a future release)
1917 // META Meta Information
1929 // NMI Nuclear Medicine
1931 // BFS Basic Film Session
1932 // BFB Basic Film Box
1933 // BIB Basic Image Box
1948 // The only guaranted way of finding the swap code is to find a
1949 // group tag since we know it's length has to be of four bytes i.e.
1950 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1951 // occurs when we can't find such group...
1953 guint32 x=4; // x : for ntohs
1954 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1958 char deb[HEADER_LENGTH_TO_READ];
1960 // First, compare HostByteOrder and NetworkByteOrder in order to
1961 // determine if we shall need to swap bytes (i.e. the Endian type).
1966 //cout << net2host << endl;
1968 // The easiest case is the one of a DICOM header, since it possesses a
1969 // file preamble where it suffice to look for the string "DICM".
1970 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1973 if(memcmp(entCur, "DICM", (size_t)4) == 0)
1975 dbg.Verbose(1, "gdcmParser::CheckSwap:", "looks like DICOM Version3");
1976 // Next, determine the value representation (VR). Let's skip to the
1977 // first element (0002, 0000) and check there if we find "UL"
1978 // - or "OB" if the 1st one is (0002,0001) -,
1979 // in which case we (almost) know it is explicit VR.
1980 // WARNING: if it happens to be implicit VR then what we will read
1981 // is the length of the group. If this ascii representation of this
1982 // length happens to be "UL" then we shall believe it is explicit VR.
1983 // FIXME: in order to fix the above warning, we could read the next
1984 // element value (or a couple of elements values) in order to make
1985 // sure we are not commiting a big mistake.
1986 // We need to skip :
1987 // * the 128 bytes of File Preamble (often padded with zeroes),
1988 // * the 4 bytes of "DICM" string,
1989 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1990 // i.e. a total of 136 bytes.
1993 // Use gdcmParser::dicom_vr to test all the possibilities
1994 // instead of just checking for UL, OB and UI !?
1995 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
1996 (memcmp(entCur, "OB", (size_t)2) == 0) ||
1997 (memcmp(entCur, "UI", (size_t)2) == 0) )
1999 filetype = ExplicitVR;
2000 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2001 "explicit Value Representation");
2005 filetype = ImplicitVR;
2006 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2007 "not an explicit Value Representation");
2012 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2013 "HostByteOrder != NetworkByteOrder");
2018 dbg.Verbose(1, "gdcmParser::CheckSwap:",
2019 "HostByteOrder = NetworkByteOrder");
2022 // Position the file position indicator at first tag (i.e.
2023 // after the file preamble and the "DICM" string).
2025 fseek (fp, 132L, SEEK_SET);
2029 // Alas, this is not a DicomV3 file and whatever happens there is no file
2030 // preamble. We can reset the file position indicator to where the data
2031 // is (i.e. the beginning of the file).
2032 dbg.Verbose(1, "gdcmParser::CheckSwap:", "not a DICOM Version3 file");
2035 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2036 // By clean we mean that the length of the first tag is written down.
2037 // If this is the case and since the length of the first group HAS to be
2038 // four (bytes), then determining the proper swap code is straightforward.
2041 // We assume the array of char we are considering contains the binary
2042 // representation of a 32 bits integer. Hence the following dirty
2044 s = *((guint32 *)(entCur));
2065 dbg.Verbose(0, "gdcmParser::CheckSwap:",
2066 "ACR/NEMA unfound swap info (time to raise bets)");
2069 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2070 // It is time for despaired wild guesses. So, let's assume this file
2071 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
2072 // not present. Then the only info we have is the net2host one.
2082 * \ingroup gdcmParser
2085 void gdcmParser::SwitchSwapToBigEndian(void)
2087 dbg.Verbose(1, "gdcmParser::SwitchSwapToBigEndian",
2088 "Switching to BigEndian mode.");
2109 * \ingroup gdcmParser
2114 void gdcmParser::SetMaxSizeLoadEntry(long NewSize)
2118 if ((guint32)NewSize >= (guint32)0xffffffff)
2120 MaxSizeLoadEntry = 0xffffffff;
2123 MaxSizeLoadEntry = NewSize;
2127 * \ingroup gdcmParser
2128 * \brief Searches both the public and the shadow dictionary (when they
2129 * exist) for the presence of the DictEntry with given name.
2130 * The public dictionary has precedence on the shadow one.
2131 * @param Name name of the searched DictEntry
2132 * @return Corresponding DictEntry when it exists, NULL otherwise.
2134 gdcmDictEntry *gdcmParser::GetDictEntryByName(std::string Name)
2136 gdcmDictEntry *found = (gdcmDictEntry *)0;
2137 if (!RefPubDict && !RefShaDict)
2139 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2140 "we SHOULD have a default dictionary");
2144 found = RefPubDict->GetDictEntryByName(Name);
2150 found = RefShaDict->GetDictEntryByName(Name);
2158 * \ingroup gdcmParser
2159 * \brief Searches both the public and the shadow dictionary (when they
2160 * exist) for the presence of the DictEntry with given
2161 * group and element. The public dictionary has precedence on the
2163 * @param group group of the searched DictEntry
2164 * @param element element of the searched DictEntry
2165 * @return Corresponding DictEntry when it exists, NULL otherwise.
2167 gdcmDictEntry *gdcmParser::GetDictEntryByNumber(guint16 group,guint16 element)
2169 gdcmDictEntry *found = (gdcmDictEntry *)0;
2170 if (!RefPubDict && !RefShaDict)
2172 dbg.Verbose(0, "gdcmParser::GetDictEntry",
2173 "we SHOULD have a default dictionary");
2177 found = RefPubDict->GetDictEntryByNumber(group, element);
2183 found = RefShaDict->GetDictEntryByNumber(group, element);
2191 * \ingroup gdcmParser
2192 * \brief Read the next tag but WITHOUT loading it's value
2193 * @return On succes the newly created HeaderEntry, NULL on failure.
2195 gdcmHeaderEntry *gdcmParser::ReadNextHeaderEntry(void)
2198 gdcmHeaderEntry *NewEntry;
2204 // We reached the EOF (or an error occured) and header parsing
2205 // has to be considered as finished.
2206 return (gdcmHeaderEntry *)0;
2208 NewEntry = NewHeaderEntryByNumber(g, n);
2209 FindHeaderEntryVR(NewEntry);
2210 FindHeaderEntryLength(NewEntry);
2217 NewEntry->SetOffset(ftell(fp));
2218 //if ( (g==0x7fe0) && (n==0x0010) )
2223 * \ingroup gdcmParser
2224 * \brief Build a new Element Value from all the low level arguments.
2225 * Check for existence of dictionary entry, and build
2226 * a default one when absent.
2227 * @param Name Name of the underlying DictEntry
2229 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByName(std::string Name)
2231 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2233 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
2235 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2238 dbg.Verbose(1, "gdcmParser::ObtainHeaderEntryByName",
2239 "failed to allocate gdcmHeaderEntry");
2240 return (gdcmHeaderEntry *)0;
2246 * \ingroup gdcmParser
2247 * \brief Request a new virtual dict entry to the dict set
2248 * @param group group of the underlying DictEntry
2249 * @param element element of the underlying DictEntry
2250 * @param vr VR of the underlying DictEntry
2251 * @param fourth owner group
2252 * @param name english name
2254 gdcmDictEntry *gdcmParser::NewVirtualDictEntry(guint16 group, guint16 element,
2259 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2263 * \ingroup gdcmParser
2264 * \brief Build a new Element Value from all the low level arguments.
2265 * Check for existence of dictionary entry, and build
2266 * a default one when absent.
2267 * @param Group group of the underlying DictEntry
2268 * @param Elem element of the underlying DictEntry
2270 gdcmHeaderEntry *gdcmParser::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2272 // Find out if the tag we encountered is in the dictionaries:
2273 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2275 DictEntry = NewVirtualDictEntry(Group, Elem);
2277 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2280 dbg.Verbose(1, "gdcmParser::NewHeaderEntryByNumber",
2281 "failed to allocate gdcmHeaderEntry");
2288 * \ingroup gdcmParser
2289 * \brief Small utility function that creates a new manually crafted
2290 * (as opposed as read from the file) gdcmHeaderEntry with user
2291 * specified name and adds it to the public tag hash table.
2292 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2293 * @param NewTagName The name to be given to this new tag.
2294 * @param VR The Value Representation to be given to this new tag.
2295 * @return The newly hand crafted Element Value.
2297 gdcmHeaderEntry *gdcmParser::NewManualHeaderEntryToPubDict(std::string NewTagName,
2300 gdcmHeaderEntry *NewEntry = NULL;
2301 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2302 guint32 FreeElem = 0;
2303 gdcmDictEntry *DictEntry = NULL;
2305 FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2306 if (FreeElem == UINT32_MAX)
2308 dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2309 "Group 0xffff in Public Dict is full");
2313 DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2314 VR, "GDCM", NewTagName);
2315 NewEntry = new gdcmHeaderEntry(DictEntry);
2316 AddHeaderEntry(NewEntry);
2321 * \ingroup gdcmParser
2322 * \brief Generate a free TagKey i.e. a TagKey that is not present
2323 * in the TagHt dictionary.
2324 * @param group The generated tag must belong to this group.
2325 * @return The element of tag with given group which is fee.
2327 guint32 gdcmParser::GenerateFreeTagKeyInGroup(guint16 group)
2329 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2331 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2332 if (tagHT.count(key) == 0)
2338 //-----------------------------------------------------------------------------