2 //-----------------------------------------------------------------------------
4 #include "gdcmDocument.h"
5 #include "gdcmGlobal.h"
16 #include <netinet/in.h>
21 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
22 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
23 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
24 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
27 guint32 totalSQlength;
28 guint32 alreadyParsedlength;
31 //-----------------------------------------------------------------------------
32 // Refer to gdcmDocument::CheckSwap()
33 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
35 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
36 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
38 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
40 //-----------------------------------------------------------------------------
41 // Constructor / Destructor
45 * @param inFilename file to be opened for parsing
46 * @param exception_on_error whether we throw an exception or not
47 * @param enable_sequences = true to allow the header
48 * to be parsed *inside* the SeQuences,
49 * when they have an actual length
50 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
51 * @param ignore_shadow to allow skipping the shadow elements,
52 * to save memory space.
53 * \warning The TRUE value for this param has to be used
54 * with a FALSE value for the 'enable_sequence' param.
55 * ('public elements' may be embedded in 'shadow Sequences')
57 gdcmDocument::gdcmDocument(const char *inFilename,
58 bool exception_on_error,
59 bool enable_sequences,
61 enableSequences=enable_sequences;
62 ignoreShadow =ignore_shadow;
64 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
65 filename = inFilename;
68 if ( !OpenFile(exception_on_error))
73 return NULL; // Du menage à faire avant de sortir ?
77 wasUpdated = 0; // will be set to 1 if user adds an entry
78 printLevel = 1; // 'Medium' print level by default
83 * @param exception_on_error
85 gdcmDocument::gdcmDocument(bool exception_on_error) {
86 (void)exception_on_error;
89 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
92 wasUpdated = 0; // will be set to 1 if user adds an entry
93 printLevel = 1; // 'Medium' print level by default
97 * \brief Canonical destructor.
99 gdcmDocument::~gdcmDocument (void) {
104 //-----------------------------------------------------------------------------
107 * \brief Prints the Doc Entries (Dicom Elements)
108 * from the chained list
111 void gdcmDocument::PrintEntry(std::ostream & os) {
113 for (ListTag::iterator i = listEntries.begin();
114 i != listEntries.end();
117 (*i)->SetPrintLevel(printLevel);
124 * \brief Prints The Dict Entries of THE public Dicom Dictionary
127 void gdcmDocument::PrintPubDict(std::ostream & os) {
128 RefPubDict->Print(os);
132 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
135 void gdcmDocument::PrintShaDict(std::ostream & os) {
136 RefShaDict->Print(os);
139 //-----------------------------------------------------------------------------
142 * \brief Get the public dictionary used
144 gdcmDict *gdcmDocument::GetPubDict(void) {
149 * \brief Get the shadow dictionary used
151 gdcmDict *gdcmDocument::GetShaDict(void) {
156 * \brief Set the shadow dictionary used
157 * \param dict dictionary to use in shadow
159 bool gdcmDocument::SetShaDict(gdcmDict *dict){
165 * \brief Set the shadow dictionary used
166 * \param dictName name of the dictionary to use in shadow
168 bool gdcmDocument::SetShaDict(DictKey dictName){
169 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
174 * \brief This predicate, based on hopefully reasonable heuristics,
175 * decides whether or not the current gdcmDocument was properly parsed
176 * and contains the mandatory information for being considered as
177 * a well formed and usable Dicom/Acr File.
178 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
181 bool gdcmDocument::IsReadable(void) {
182 if(filetype==Unknown) {
185 if(listEntries.size()<=0) {
193 * \brief Determines if the Transfer Syntax was already encountered
194 * and if it corresponds to a ImplicitVRLittleEndian one.
195 * @return True when ImplicitVRLittleEndian found. False in all other cases.
197 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void) {
198 gdcmHeaderEntry *Element = GetHeaderEntryByNumber(0x0002, 0x0010);
201 LoadHeaderEntrySafe(Element);
203 std::string Transfer = Element->GetValue();
204 if ( Transfer == UI1_2_840_10008_1_2 )
210 * \brief Determines if the Transfer Syntax was already encountered
211 * and if it corresponds to a ExplicitVRLittleEndian one.
212 * @return True when ExplicitVRLittleEndian found. False in all other cases.
214 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void) {
215 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
218 LoadHeaderEntrySafe(Element);
220 std::string Transfer = Element->GetValue();
221 if ( Transfer == UI1_2_840_10008_1_2_1 )
227 * \brief Determines if the Transfer Syntax was already encountered
228 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
229 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
231 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
232 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
235 LoadHeaderEntrySafe(Element);
237 std::string Transfer = Element->GetValue();
238 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
244 * \brief Determines if the Transfer Syntax was already encountered
245 * and if it corresponds to a Explicit VR Big Endian one.
246 * @return True when big endian found. False in all other cases.
248 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void) {
249 gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
252 LoadHeaderEntrySafe(Element);
254 std::string Transfer = Element->GetValue();
255 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
261 * \brief returns the File Type
262 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
263 * @return the FileType code
265 FileType gdcmDocument::GetFileType(void) {
270 * \brief opens the file
271 * @param exception_on_error
274 FILE *gdcmDocument::OpenFile(bool exception_on_error)
277 fp=fopen(filename.c_str(),"rb");
278 if(exception_on_error)
281 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
287 fread(&zero, (size_t)2, (size_t)1, fp);
289 //ACR -- or DICOM with no Preamble --
290 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
294 fseek(fp, 126L, SEEK_CUR);
296 fread(dicm, (size_t)4, (size_t)1, fp);
297 if( memcmp(dicm, "DICM", 4) == 0 )
301 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
304 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
310 * \brief closes the file
311 * @return TRUE if the close was successfull
313 bool gdcmDocument::CloseFile(void) {
314 int closed = fclose(fp);
322 * \brief Writes in a file all the Doc Entries (Dicom Elements)
323 * of the Chained List
324 * @param fp file pointer on an already open file
325 * @param type Type of the File to be written
326 * (ACR-NEMA, ExplicitVR, ImplicitVR)
327 * \return Always true.
329 bool gdcmDocument::Write(FILE *fp, FileType type) {
332 /// The stuff will have to be rewritten using the SeQuence based
333 /// tree-like stucture instead of the chained list .
334 /// (so we shall remove the GroupHT from the gdcmDocument)
338 /// \todo move the following lines (and a lot of others, to be written)
339 /// to a future function CheckAndCorrectHeader
343 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
344 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
345 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
347 /// a moins de se livrer a un tres complique ajout des champs manquants.
348 /// faire un CheckAndCorrectHeader (?)
350 if (type == ImplicitVR)
352 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
353 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
355 /// \todo Refer to standards on page 21, chapter 6.2
356 /// "Value representation": values with a VR of UI shall be
357 /// padded with a single trailing null
358 /// Dans le cas suivant on doit pader manuellement avec un 0
360 SetEntryLengthByNumber(18, 0x0002, 0x0010);
363 if (type == ExplicitVR)
365 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
366 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
368 /// \todo Refer to standards on page 21, chapter 6.2
369 /// "Value representation": values with a VR of UI shall be
370 /// padded with a single trailing null
371 /// Dans le cas suivant on doit pader manuellement avec un 0
373 SetEntryLengthByNumber(20, 0x0002, 0x0010);
377 * \todo rewrite later, if really usefull
379 * --> Warning : un-updated odd groups lengths can causes pb
380 * --> (xmedcon breaks)
381 * --> to be re- written with future org.
383 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
384 * UpdateGroupLength(false,type);
386 * UpdateGroupLength(true,ACR);
389 WriteEntries(fp,type);
394 * \brief Modifies the value of a given Header Entry (Dicom Element)
395 * when it exists. Create it with the given value when unexistant.
396 * \warning Adds the Header Entry to the HTable, NOT to the chained List
397 * @param Value Value to be set
398 * @param Group Group of the Entry
399 * @param Elem Element of the Entry
400 * \return pointer to the modified/created Header Entry (NULL when creation
403 gdcmHeaderEntry * gdcmDocument::ReplaceOrCreateByNumber(
408 a = GetHeaderEntryByNumber( Group, Elem);
410 a =NewHeaderEntryByNumber(Group, Elem);
415 //CLEANME SetEntryByNumber(Value, Group, Elem);
421 * \brief Set a new value if the invoked element exists
422 * Seems to be useless !!!
423 * @param Value new element value
424 * @param Group group of the Entry
425 * @param Elem element of the Entry
428 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
430 std::string v = Value;
431 SetEntryByNumber(v, Group, Elem);
435 //-----------------------------------------------------------------------------
439 * \brief Checks if a given Dicom Element exists
441 * @param group Group number of the searched Dicom Element
442 * @param element Element number of the searched Dicom Element
443 * @return number of occurences
445 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
446 std::string key = gdcmDictEntry::TranslateToKey(group, element );
447 return (tagHT.count(key));
451 * \brief Searches within Doc Entries (Dicom Elements) parsed with
452 * the public and private dictionaries
453 * for the element value of a given tag.
454 * \warning Don't use any longer : use GetPubEntryByName
455 * @param tagName name of the searched element.
456 * @return Corresponding element value when it exists,
457 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
459 std::string gdcmDocument::GetEntryByName(std::string tagName) {
460 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
461 if( dictEntry == NULL)
464 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
468 * \brief Searches within Doc Entries (Dicom Elements) parsed with
469 * the public and private dictionaries
470 * for the element value representation of a given tag.
472 * Obtaining the VR (Value Representation) might be needed by caller
473 * to convert the string typed content to caller's native type
474 * (think of C++ vs Python). The VR is actually of a higher level
475 * of semantics than just the native C++ type.
476 * @param tagName name of the searched element.
477 * @return Corresponding element value representation when it exists,
478 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
480 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
481 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
482 if( dictEntry == NULL)
485 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(dictEntry->GetGroup(),
486 dictEntry->GetElement());
487 return elem->GetVR();
492 * \brief Searches within Doc Entries (Dicom Elements) parsed with
493 * the public and private dictionaries
494 * for the element value representation of a given tag.
495 * @param group Group of the searched tag.
496 * @param element Element of the searched tag.
497 * @return Corresponding element value representation when it exists,
498 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
500 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
501 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
502 if ( ! tagHT.count(key))
504 return tagHT.find(key)->second->GetValue();
508 * \brief Searches within Doc Entries (Dicom Elements) parsed with
509 * the public and private dictionaries
510 * for the element value representation of a given tag..
512 * Obtaining the VR (Value Representation) might be needed by caller
513 * to convert the string typed content to caller's native type
514 * (think of C++ vs Python). The VR is actually of a higher level
515 * of semantics than just the native C++ type.
516 * @param group Group of the searched tag.
517 * @param element Element of the searched tag.
518 * @return Corresponding element value representation when it exists,
519 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
521 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
522 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
525 return elem->GetVR();
529 * \brief Searches within Doc Entries (Dicom Elements) parsed with
530 * the public and private dictionaries
531 * for the value length of a given tag..
532 * @param group Group of the searched tag.
533 * @param element Element of the searched tag.
534 * @return Corresponding element length; -2 if not found
536 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
537 gdcmHeaderEntry* elem = GetHeaderEntryByNumber(group, element);
540 return elem->GetLength();
543 * \brief Sets the value (string) of the Header Entry (Dicom Element)
544 * @param content string value of the Dicom Element
545 * @param tagName name of the searched Dicom Element.
546 * @return true when found
548 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
549 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
550 if( dictEntry == NULL)
553 return(SetEntryByNumber(content,dictEntry->GetGroup(),
554 dictEntry->GetElement()));
558 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
559 * through it's (group, element) and modifies it's content with
561 * \warning Don't use any longer : use SetPubEntryByNumber
562 * @param content new value to substitute with
563 * @param group group of the Dicom Element to modify
564 * @param element element of the Dicom Element to modify
566 bool gdcmDocument::SetEntryByNumber(std::string content,
570 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
571 if ( ! tagHT.count(key))
573 int l = content.length();
574 if(l%2) // Non even length are padded with a space (020H).
577 content = content + '\0';
582 TagHeaderEntryHT::iterator p2;
583 // DO NOT remove the following lines : they explain the stuff
584 //p= tagHT.equal_range(key); // get a pair of iterators first-last synonym
585 //p2=p.first; // iterator on the first synonym
586 //a=p2->second; // H Table target column (2-nd col)
589 a = ((tagHT.equal_range(key)).first)->second;
591 a-> SetValue(content);
593 std::string vr = a->GetVR();
596 if( (vr == "US") || (vr == "SS") )
598 else if( (vr == "UL") || (vr == "SL") )
608 * \brief Accesses an existing gdcmHeaderEntry (i.e. a Dicom Element)
609 * in the PubHeaderEntrySet of this instance
610 * through it's (group, element) and modifies it's length with
612 * \warning Use with extreme caution.
613 * @param l new length to substitute with
614 * @param group group of the Entry to modify
615 * @param element element of the Entry to modify
616 * @return true on success, false otherwise.
618 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
622 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
623 if ( ! tagHT.count(key))
625 if (l%2) l++; // length must be even
626 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
632 * \brief Gets (from Header) the offset of a 'non string' element value
633 * (LoadElementValues has already be executed)
634 * @param Group group of the Entry
635 * @param Elem element of the Entry
636 * @return File Offset of the Element Value
638 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
640 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
643 dbg.Verbose(1, "gdcmDocument::GetHeaderEntryByNumber",
644 "failed to Locate gdcmHeaderEntry");
647 return Entry->GetOffset();
651 * \brief Gets (from Header) a 'non string' element value
652 * (LoadElementValues has already be executed)
653 * @param Group group of the Entry
654 * @param Elem element of the Entry
655 * @return Pointer to the 'non string' area
657 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
659 gdcmHeaderEntry* Entry = GetHeaderEntryByNumber(Group, Elem);
662 dbg.Verbose(1, "gdcmDocument::GetHeaderEntryByNumber",
663 "failed to Locate gdcmHeaderEntry");
666 return Entry->GetVoidArea();
670 * \brief Loads (from disk) the element content
671 * when a string is not suitable
672 * @param Group group of the Entry
673 * @param Elem element of the Entry
675 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
677 gdcmHeaderEntry * Element= GetHeaderEntryByNumber(Group, Elem);
680 size_t o =(size_t)Element->GetOffset();
681 fseek(fp, o, SEEK_SET);
682 size_t l=Element->GetLength();
683 char* a = new char[l];
687 SetEntryVoidAreaByNumber(a, Group, Elem);
688 /// \todo check the result
689 size_t l2 = fread(a, 1, l ,fp);
700 * \brief Sets a 'non string' value to a given Dicom Element
702 * @param group Group number of the searched Dicom Element
703 * @param element Element number of the searched Dicom Element
706 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
710 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
711 if ( ! tagHT.count(key))
713 ( ((tagHT.equal_range(key)).first)->second )->SetVoidArea(area);
718 * \brief Update the entries with the shadow dictionary.
719 * Only non even entries are analyzed
721 void gdcmDocument::UpdateShaEntries(void) {
722 gdcmDictEntry *entry;
725 for(ListTag::iterator it=listEntries.begin();
726 it!=listEntries.end();
729 // Odd group => from public dictionary
730 if((*it)->GetGroup()%2==0)
733 // Peer group => search the corresponding dict entry
735 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
739 if((*it)->IsImplicitVR())
744 (*it)->SetValue(GetHeaderEntryUnvalue(*it));
746 // Set the new entry and the new value
747 (*it)->SetDictEntry(entry);
748 CheckHeaderEntryVR(*it,vr);
750 (*it)->SetValue(GetHeaderEntryValue(*it));
754 // Remove precedent value transformation
755 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
761 * \brief Searches within the Doc Entries for a Dicom Element of
763 * @param tagName name of the searched Dicom Element.
764 * @return Corresponding Dicom Element when it exists, and NULL
767 gdcmHeaderEntry *gdcmDocument::GetHeaderEntryByName(std::string tagName) {
768 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
769 if( dictEntry == NULL)
772 return(GetHeaderEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
776 * \brief retrieves a Dicom Element (the first one) using (group, element)
777 * \warning (group, element) IS NOT an identifier inside the Dicom Header
778 * if you think it's NOT UNIQUE, check the count number
779 * and use iterators to retrieve ALL the Dicoms Elements within
780 * a given couple (group, element)
781 * @param group Group number of the searched Dicom Element
782 * @param element Element number of the searched Dicom Element
785 gdcmHeaderEntry* gdcmDocument::GetHeaderEntryByNumber(guint16 group, guint16 element)
787 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
788 if ( ! tagHT.count(key))
790 return tagHT.find(key)->second;
794 * \brief retrieves the Dicom Elements (all of them) using (group, element)
795 * @param group Group number of the searched Dicom Element.
796 * @param element Element number of the searched Dicom Element.
797 * @return a range (i.e.pair<,>) containing all elements whose key is group|element)
800 IterHT gdcmDocument::GetHeaderEntrySameNumber(guint16 group, guint16 element){
801 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
802 return (tagHT.equal_range(key));
806 * \brief Loads the element while preserving the current
807 * underlying file position indicator as opposed to
808 * to LoadHeaderEntry that modifies it.
809 * @param entry Header Entry whose value shall be loaded.
812 void gdcmDocument::LoadHeaderEntrySafe(gdcmHeaderEntry * entry) {
813 long PositionOnEntry = ftell(fp);
814 LoadHeaderEntry(entry);
815 fseek(fp, PositionOnEntry, SEEK_SET);
819 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
820 * \warning : to be re-written using the chained list instead of the H table.
821 * \warning : DO NOT use (doesn't work any longer because of the multimap)
822 * \todo : to be re-written using the chained list instead of the H table
823 * @param SkipSequence TRUE if we don't want to write Sequences (ACR-NEMA Files)
824 * @param type Type of the File (ExplicitVR,ImplicitVR, ACR, ...)
826 void gdcmDocument::UpdateGroupLength(bool SkipSequence, FileType type) {
830 gdcmHeaderEntry *elem;
832 std::string str_trash;
835 GroupHT groupHt; // to hold the length of each group
838 // typedef std::map<GroupKey, int> GroupHT;
840 gdcmHeaderEntry *elemZ;
842 // for each Tag in the DCM Header
844 for (TagHeaderEntryHT::iterator tag2 = tagHT.begin();
849 gr = elem->GetGroup();
850 el = elem->GetElement();
853 sprintf(trash, "%04x", gr);
854 key = trash; // generate 'group tag'
856 // if the caller decided not to take SEQUENCEs into account
857 // e.g : he wants to write an ACR-NEMA File
859 if (SkipSequence && vr == "SQ")
862 // Still unsolved problem :
863 // we cannot find the 'Sequence Delimitation Item'
864 // since it's at the end of the Hash Table
867 // there is SEQUENCE in ACR-NEMA
869 // --> la descente a l'interieur' des SQ
870 // devrait etre faite avec une liste chainee, pas avec une HTable...
872 if ( groupHt.count(key) == 0) // we just read the first elem of a given group
874 if (el == 0x0000) // the first elem is 0x0000
876 groupHt[key] = 0; // initialize group length
880 groupHt[key] = 2 + 2 + 4 + elem->GetLength(); // non 0x0000 first group elem
883 else // any elem but the first
885 if (type == ExplicitVR)
887 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
889 groupHt[key] += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
892 groupHt[key] += 2 + 2 + 4 + elem->GetLength();
896 unsigned short int gr_bid;
898 for (GroupHT::iterator g = groupHt.begin(); // for each group we found
902 // FIXME: g++ -Wall -Wstrict-prototypes reports on following line:
903 // warning: unsigned int format, different type arg
904 sscanf(g->first.c_str(),"%x",&gr_bid); //FIXME
905 tk = g->first + "|0000"; // generate the element full tag
907 if ( tagHT.count(tk) == 0) // if element 0x0000 not found
909 gdcmDictEntry * tagZ = new gdcmDictEntry(gr_bid, 0x0000, "UL");
910 elemZ = new gdcmHeaderEntry(tagZ);
912 AddHeaderEntry(elemZ); // create it
916 elemZ=GetHeaderEntryByNumber(gr_bid, 0x0000);
918 sprintf(trash ,"%d",g->second);
920 elemZ->SetValue(str_trash);
925 * \brief Writes in a file (according to the requested format)
926 * the group, the element, the value representation and the length
927 * of a single gdcmHeaderEntry passed as argument.
928 * @param tag pointer on the gdcmHeaderEntry to be written
929 * @param _fp already open file pointer
930 * @param type type of the File to be written
932 void gdcmDocument::WriteEntryTagVRLength(gdcmHeaderEntry *tag,
936 guint16 group = tag->GetGroup();
937 std::string vr = tag->GetVR();
938 guint16 el = tag->GetElement();
939 guint32 lgr = tag->GetReadLength();
941 if ( (group == 0xfffe) && (el == 0x0000) )
942 // Fix in order to make some MR PHILIPS images e-film readable
943 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
944 // we just *always* ignore spurious fffe|0000 tag !
947 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
948 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
950 if ( type == ExplicitVR ) {
952 // Special case of delimiters:
953 if (group == 0xfffe) {
954 // Delimiters have NO Value Representation and have NO length.
955 // Hence we skip writing the VR and length and we pad by writing
959 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
964 guint16 shortLgr = lgr;
965 if (vr == "unkn") { // Unknown was 'written'
966 // deal with Little Endian
967 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
968 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
970 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
971 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
973 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
974 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
976 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
982 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
987 * \brief Writes in a file (according to the requested format)
988 * the value of a single gdcmHeaderEntry passed as argument.
989 * @param tag Pointer on the gdcmHeaderEntry to be written
990 * @param _fp Already open file pointer
991 * @param type type of the File to be written
993 void gdcmDocument::WriteEntryValue(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
996 guint16 group = tag->GetGroup();
997 std::string vr = tag->GetVR();
998 guint32 lgr = tag->GetReadLength();
1001 // SeQuences have no value:
1003 if (group == 0xfffe)
1004 // Delimiters have no associated value:
1008 voidArea = tag->GetVoidArea();
1009 if (voidArea != NULL)
1010 { // there is a 'non string' LUT, overlay, etc
1011 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1015 if (vr == "US" || vr == "SS")
1017 // some 'Short integer' fields may be mulivaluated
1018 // each single value is separated from the next one by '\'
1019 // we split the string and write each value as a short int
1020 std::vector<std::string> tokens;
1021 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1022 Tokenize (tag->GetValue(), tokens, "\\");
1023 for (unsigned int i=0; i<tokens.size();i++)
1025 guint16 val_uint16 = atoi(tokens[i].c_str());
1026 void *ptr = &val_uint16;
1027 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1032 // some 'Integer' fields may be mulivaluated
1033 // each single value is separated from the next one by '\'
1034 // we split the string and write each value as an int
1035 if (vr == "UL" || vr == "SL")
1037 std::vector<std::string> tokens;
1038 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1039 Tokenize (tag->GetValue(), tokens, "\\");
1040 for (unsigned int i=0; i<tokens.size();i++)
1042 guint32 val_uint32 = atoi(tokens[i].c_str());
1043 void *ptr = &val_uint32;
1044 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1049 fwrite (tag->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1053 * \brief Writes in a file (according to the requested format)
1054 * a single gdcmHeaderEntry passed as argument.
1055 * \sa WriteEntryValue, WriteEntryTagVRLength.
1056 * @param tag Pointer on the gdcmHeaderEntry to be written
1057 * @param _fp Already open file pointer
1058 * @param type type of the File to be written
1061 bool gdcmDocument::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
1063 guint32 length = tag->GetLength();
1065 // The value of a tag MUST (see the DICOM norm) be an odd number of
1066 // bytes. When this is not the case, pad with an additional byte:
1069 tag->SetValue(tag->GetValue()+"\0");
1070 tag->SetLength(tag->GetReadLength()+1);
1073 WriteEntryTagVRLength(tag, _fp, type);
1074 WriteEntryValue(tag, _fp, type);
1079 * \brief writes on disc according to the requested format
1080 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1081 * using the Chained List
1082 * \warning does NOT add the missing elements in the header :
1083 * it's up to the user doing it !
1084 * (function CheckHeaderCoherence to be written)
1085 * \warning DON'T try, right now, to write a DICOM image
1086 * from an ACR Header (meta elements will be missing!)
1087 * \sa WriteEntriesDeprecated (Special temporary method for Theralys)
1088 * @param type type of the File to be written
1089 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1090 * @param _fp already open file pointer
1093 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1095 /// \todo (?) check write failures (after *each* fwrite)
1097 for (ListTag::iterator tag2=listEntries.begin();
1098 tag2 != listEntries.end();
1102 if ((*tag2)->GetGroup() < 0x0008)
1103 // Ignore pure DICOM V3 groups
1105 if ((*tag2)->GetElement() %2)
1106 // Ignore the "shadow" groups
1108 if ((*tag2)->GetVR() == "SQ" ) // ignore Sequences
1110 if ((*tag2)->GetSQDepthLevel() != 0) // Not only ignore the SQ element
1113 if (! WriteEntry(*tag2,_fp,type) )
1120 * \brief writes on disc according to the requested format
1121 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image,
1122 * using only the last synonym of each mutimap H Table post.
1123 * \warning Uses the H Table, instead of the Chained List
1124 * in order to be compliant with the old way to proceed
1125 * (added elements taken in to account)
1126 * Only THERALYS, during a transitory phase is supposed
1127 * to use this method !!!
1128 * \warning DON'T try, right now, to write a DICOM image
1129 * from an ACR Header (meta elements will be missing!)
1131 * @param _fp already open file pointer
1132 * @param type type of the File to be written
1133 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1135 void gdcmDocument::WriteEntriesDeprecated(FILE *_fp,FileType type) {
1137 // restent a tester les echecs en ecriture (apres chaque fwrite)
1139 for (TagHeaderEntryHT::iterator tag2=tagHT.begin();
1140 tag2 != tagHT.end();
1143 if ((*tag2->second).GetGroup() < 0x0008) continue; // ignore pure DICOM V3 groups
1144 if ((*tag2->second).GetElement() %2) continue; // ignore shadow groups
1145 if ((*tag2->second).GetVR() == "SQ" ) continue; // ignore Sequences
1146 if ((*tag2->second).GetSQDepthLevel() != 0) continue; // Not only ignore the SQ element
1148 if ( ! WriteEntry(tag2->second,_fp,type))
1154 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1156 * @return The properly swaped 32 bits integer.
1158 guint32 gdcmDocument::SwapLong(guint32 a) {
1163 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1164 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1168 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1172 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1175 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1182 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1184 * @return The properly unswaped 32 bits integer.
1186 guint32 gdcmDocument::UnswapLong(guint32 a) {
1187 return (SwapLong(a));
1191 * \brief Swaps the bytes so they agree with the processor order
1192 * @return The properly swaped 16 bits integer.
1194 guint16 gdcmDocument::SwapShort(guint16 a) {
1195 if ( (sw==4321) || (sw==2143) )
1196 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1201 * \brief Unswaps the bytes so they agree with the processor order
1202 * @return The properly unswaped 16 bits integer.
1204 guint16 gdcmDocument::UnswapShort(guint16 a) {
1205 return (SwapShort(a));
1208 //-----------------------------------------------------------------------------
1212 * \brief Loads the element content if its length doesn't exceed
1213 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1214 * @param Entry Header Entry (Dicom Element) to be dealt with
1216 void gdcmDocument::LoadHeaderEntry(gdcmHeaderEntry *Entry) {
1218 guint16 group = Entry->GetGroup();
1219 std::string vr= Entry->GetVR();
1220 guint32 length = Entry->GetLength();
1222 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1224 // A SeQuence "contains" a set of Elements.
1225 // (fffe e000) tells us an Element is beginning
1226 // (fffe e00d) tells us an Element just ended
1227 // (fffe e0dd) tells us the current SeQuence just ended
1228 if( group == 0xfffe ) {
1229 Entry->SetValue("gdcm::Skipped");
1233 // When the length is zero things are easy:
1234 if ( length == 0 ) {
1235 Entry->SetValue("");
1239 // The elements whose length is bigger than the specified upper bound
1240 // are not loaded. Instead we leave a short notice of the offset of
1241 // the element content and it's length.
1242 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 // Any compacter code suggested (?)
1253 if ( IsHeaderEntryAnInteger(Entry) ) {
1255 std::ostringstream s;
1257 // When short integer(s) are expected, read and convert the following
1258 // n *two characters properly i.e. as short integers as opposed to strings.
1259 // Elements with Value Multiplicity > 1
1260 // contain a set of integers (not a single one)
1261 if (vr == "US" || vr == "SS") {
1263 NewInt = ReadInt16();
1266 for (int i=1; i < nbInt; i++) {
1268 NewInt = ReadInt16();
1273 // When integer(s) are expected, read and convert the following
1274 // n * four characters properly i.e. as integers as opposed to strings.
1275 // Elements with Value Multiplicity > 1
1276 // contain a set of integers (not a single one)
1277 else if (vr == "UL" || vr == "SL") {
1279 NewInt = ReadInt32();
1282 for (int i=1; i < nbInt; i++) {
1284 NewInt = ReadInt32();
1289 #ifdef GDCM_NO_ANSI_STRING_STREAM
1290 s << std::ends; // to avoid oddities on Solaris
1291 #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 ) {
1301 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1302 Entry->SetValue("gdcm::UnRead");
1306 if( (vr == "UI") ) // Because of correspondance with the VR dic
1307 Entry->SetValue(NewValue.c_str());
1309 Entry->SetValue(NewValue);
1313 * \brief add a new Dicom Element pointer to
1314 * the H Table and at the end of the chained List
1315 * \warning push_bash in listEntries ONLY during ParseHeader
1316 * \todo something to allow further Elements addition,
1317 * (at their right place in the chained list)
1318 * when position to be taken care of
1319 * @param newHeaderEntry
1321 void gdcmDocument::AddHeaderEntry(gdcmHeaderEntry *newHeaderEntry) {
1322 tagHT.insert( PairHT( newHeaderEntry->GetKey(),newHeaderEntry) );
1323 listEntries.push_back(newHeaderEntry);
1328 * \brief Find the value Length of the passed Header Entry
1329 * @param Entry Header Entry whose length of the value shall be loaded.
1331 void gdcmDocument::FindHeaderEntryLength (gdcmHeaderEntry *Entry) {
1332 guint16 element = Entry->GetElement();
1333 //guint16 group = Entry->GetGroup(); //FIXME
1334 std::string vr = Entry->GetVR();
1338 if ( (filetype == ExplicitVR) && (! Entry->IsImplicitVR()) )
1340 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1342 // The following reserved two bytes (see PS 3.5-2001, section
1343 // 7.1.2 Data element structure with explicit vr p27) must be
1344 // skipped before proceeding on reading the length on 4 bytes.
1345 fseek(fp, 2L, SEEK_CUR);
1346 guint32 length32 = ReadInt32();
1348 if ( (vr == "OB") && (length32 == 0xffffffff) )
1350 Entry->SetLength(FindHeaderEntryLengthOB());
1353 FixHeaderEntryFoundLength(Entry, length32);
1357 // Length is encoded on 2 bytes.
1358 length16 = ReadInt16();
1360 // We can tell the current file is encoded in big endian (like
1361 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1362 // and it's value is the one of the encoding of a big endian file.
1363 // In order to deal with such big endian encoded files, we have
1364 // (at least) two strategies:
1365 // * when we load the "Transfer Syntax" tag with value of big endian
1366 // encoding, we raise the proper flags. Then we wait for the end
1367 // of the META group (0x0002) among which is "Transfer Syntax",
1368 // before switching the swap code to big endian. We have to postpone
1369 // the switching of the swap code since the META group is fully encoded
1370 // in little endian, and big endian coding only starts at the next
1371 // group. The corresponding code can be hard to analyse and adds
1372 // many additional unnecessary tests for regular tags.
1373 // * the second strategy consists in waiting for trouble, that shall
1374 // appear when we find the first group with big endian encoding. This
1375 // is easy to detect since the length of a "Group Length" tag (the
1376 // ones with zero as element number) has to be of 4 (0x0004). When we
1377 // encounter 1024 (0x0400) chances are the encoding changed and we
1378 // found a group with big endian encoding.
1379 // We shall use this second strategy. In order to make sure that we
1380 // can interpret the presence of an apparently big endian encoded
1381 // length of a "Group Length" without committing a big mistake, we
1382 // add an additional check: we look in the already parsed elements
1383 // for the presence of a "Transfer Syntax" whose value has to be "big
1384 // endian encoding". When this is the case, chances are we have got our
1385 // hands on a big endian encoded file: we switch the swap code to
1386 // big endian and proceed...
1387 if ( (element == 0x0000) && (length16 == 0x0400) )
1389 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1391 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1396 SwitchSwapToBigEndian();
1397 // Restore the unproperly loaded values i.e. the group, the element
1398 // and the dictionary entry depending on them.
1399 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1400 guint16 CorrectElem = SwapShort(Entry->GetElement());
1401 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1405 // This correct tag is not in the dictionary. Create a new one.
1406 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1408 // FIXME this can create a memory leaks on the old entry that be
1409 // left unreferenced.
1410 Entry->SetDictEntry(NewTag);
1413 // Heuristic: well some files are really ill-formed.
1414 if ( length16 == 0xffff)
1417 //dbg.Verbose(0, "gdcmDocument::FindLength",
1418 // "Erroneous element length fixed.");
1419 // Actually, length= 0xffff means that we deal with
1420 // Unknown Sequence Length
1422 FixHeaderEntryFoundLength(Entry, (guint32)length16);
1427 // Either implicit VR or a non DICOM conformal (see note below) explicit
1428 // VR that ommited the VR of (at least) this element. Farts happen.
1429 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1430 // on Data elements "Implicit and Explicit VR Data Elements shall
1431 // not coexist in a Data Set and Data Sets nested within it".]
1432 // Length is on 4 bytes.
1434 FixHeaderEntryFoundLength(Entry, ReadInt32());
1440 * \brief Find the Value Representation of the current Dicom Element.
1443 void gdcmDocument::FindHeaderEntryVR( gdcmHeaderEntry *Entry)
1445 if (filetype != ExplicitVR)
1450 long PositionOnEntry = ftell(fp);
1451 // Warning: we believe this is explicit VR (Value Representation) because
1452 // we used a heuristic that found "UL" in the first tag. Alas this
1453 // doesn't guarantee that all the tags will be in explicit VR. In some
1454 // cases (see e-film filtered files) one finds implicit VR tags mixed
1455 // within an explicit VR file. Hence we make sure the present tag
1456 // is in explicit VR and try to fix things if it happens not to be
1459 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1461 if(!CheckHeaderEntryVR(Entry,VR))
1463 fseek(fp, PositionOnEntry, SEEK_SET);
1464 // When this element is known in the dictionary we shall use, e.g. for
1465 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1466 // dictionary entry. Still we have to flag the element as implicit since
1467 // we know now our assumption on expliciteness is not furfilled.
1469 if ( Entry->IsVRUnknown() )
1470 Entry->SetVR("Implicit");
1471 Entry->SetImplicitVR();
1476 * \brief Check the correspondance between the VR of the header entry
1477 * and the taken VR. If they are different, the header entry is
1478 * updated with the new VR.
1479 * @param Entry Header Entry to check
1480 * @param vr Dicom Value Representation
1481 * @return false if the VR is incorrect of if the VR isn't referenced
1482 * otherwise, it returns true
1484 bool gdcmDocument::CheckHeaderEntryVR(gdcmHeaderEntry *Entry, VRKey vr)
1486 char msg[100]; // for sprintf
1487 bool RealExplicit = true;
1489 // Assume we are reading a falsely explicit VR file i.e. we reached
1490 // a tag where we expect reading a VR but are in fact we read the
1491 // first to bytes of the length. Then we will interogate (through find)
1492 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1493 // both GCC and VC++ implementations of the STL map. Hence when the
1494 // expected VR read happens to be non-ascii characters we consider
1495 // we hit falsely explicit VR tag.
1497 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1498 RealExplicit = false;
1500 // CLEANME searching the dicom_vr at each occurence is expensive.
1501 // PostPone this test in an optional integrity check at the end
1502 // of parsing or only in debug mode.
1503 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1504 RealExplicit= false;
1506 if ( !RealExplicit )
1508 // We thought this was explicit VR, but we end up with an
1509 // implicit VR tag. Let's backtrack.
1510 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1511 Entry->GetGroup(),Entry->GetElement());
1512 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1513 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1514 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1515 Entry->GetGroup(),Entry->GetElement(),
1516 "UL","FIXME","Group Length");
1517 Entry->SetDictEntry(NewEntry);
1522 if ( Entry->IsVRUnknown() )
1524 // When not a dictionary entry, we can safely overwrite the VR.
1525 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1531 else if ( Entry->GetVR() != vr )
1533 // The VR present in the file and the dictionary disagree. We assume
1534 // the file writer knew best and use the VR of the file. Since it would
1535 // be unwise to overwrite the VR of a dictionary (since it would
1536 // compromise it's next user), we need to clone the actual DictEntry
1537 // and change the VR for the read one.
1538 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1539 Entry->GetGroup(),Entry->GetElement(),
1540 vr,"FIXME",Entry->GetName());
1541 Entry->SetDictEntry(NewEntry);
1547 * \brief Get the transformed value of the header entry. The VR value
1548 * is used to define the transformation to operate on the value
1549 * \warning NOT end user intended method !
1551 * @return Transformed entry value
1553 std::string gdcmDocument::GetHeaderEntryValue(gdcmHeaderEntry *Entry)
1555 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1557 std::string val=Entry->GetValue();
1558 std::string vr=Entry->GetVR();
1559 guint32 length = Entry->GetLength();
1560 std::ostringstream s;
1563 // When short integer(s) are expected, read and convert the following
1564 // n * 2 bytes properly i.e. as a multivaluated strings
1565 // (each single value is separated fromthe next one by '\'
1566 // as usual for standard multivaluated filels
1567 // Elements with Value Multiplicity > 1
1568 // contain a set of short integers (not a single one)
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 // When integer(s) are expected, read and convert the following
1586 // n * 4 bytes properly i.e. as a multivaluated strings
1587 // (each single value is separated fromthe next one by '\'
1588 // as usual for standard multivaluated filels
1589 // Elements with Value Multiplicity > 1
1590 // contain a set of integers (not a single one)
1591 else if (vr == "UL" || vr == "SL")
1596 for (int i=0; i < nbInt; i++)
1600 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1601 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1602 NewInt32=SwapLong(NewInt32);
1606 #ifdef GDCM_NO_ANSI_STRING_STREAM
1607 s << std::ends; // to avoid oddities on Solaris
1608 #endif //GDCM_NO_ANSI_STRING_STREAM
1612 return(Entry->GetValue());
1616 * \brief Get the reverse transformed value of the header entry. The VR
1617 * value is used to define the reverse transformation to operate on
1619 * \warning NOT end user intended method !
1621 * @return Reverse transformed entry value
1623 std::string gdcmDocument::GetHeaderEntryUnvalue(gdcmHeaderEntry *Entry)
1625 if ( (IsHeaderEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1627 std::string vr=Entry->GetVR();
1628 std::ostringstream s;
1629 std::vector<std::string> tokens;
1631 if (vr == "US" || vr == "SS")
1635 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1636 Tokenize (Entry->GetValue(), tokens, "\\");
1637 for (unsigned int i=0; i<tokens.size();i++)
1639 NewInt16 = atoi(tokens[i].c_str());
1640 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1644 if (vr == "UL" || vr == "SL")
1648 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1649 Tokenize (Entry->GetValue(), tokens, "\\");
1650 for (unsigned int i=0; i<tokens.size();i++)
1652 NewInt32 = atoi(tokens[i].c_str());
1653 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1654 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1659 #ifdef GDCM_NO_ANSI_STRING_STREAM
1660 s << std::ends; // to avoid oddities on Solaris
1661 #endif //GDCM_NO_ANSI_STRING_STREAM
1665 return(Entry->GetValue());
1669 * \brief Skip a given Header Entry
1670 * \warning NOT end user intended method !
1673 void gdcmDocument::SkipHeaderEntry(gdcmHeaderEntry *entry)
1675 SkipBytes(entry->GetLength());
1679 * \brief When the length of an element value is obviously wrong (because
1680 * the parser went Jabberwocky) one can hope improving things by
1681 * applying this heuristic.
1683 void gdcmDocument::FixHeaderEntryFoundLength(gdcmHeaderEntry *Entry, guint32 FoundLength)
1685 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1686 if ( FoundLength == 0xffffffff) {
1690 guint16 gr =Entry->GetGroup();
1691 guint16 el =Entry->GetElement();
1693 if (FoundLength%2) {
1694 std::ostringstream s;
1695 s << "Warning : Tag with uneven length " << FoundLength
1696 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1697 dbg.Verbose(0,s.str().c_str());
1700 // Sorry for the patch!
1701 // XMedCom did the trick to read some naughty GE images ...
1702 if (FoundLength == 13) {
1703 // The following 'if' will be removed when there is no more
1704 // images on Creatis HDs with a 13 length for Manufacturer...
1705 if ( (Entry->GetGroup() != 0x0008) ||
1706 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1707 // end of remove area
1709 Entry->SetReadLength(10); // a bug is to be fixed
1713 // to fix some garbage 'Leonardo' Siemens images
1714 // May be commented out to avoid overhead
1715 else if ( (Entry->GetGroup() == 0x0009) &&
1716 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1718 Entry->SetReadLength(4); // a bug is to be fixed
1722 // to try to 'go inside' SeQuences (with length), and not to skip them
1723 else if ( Entry->GetVR() == "SQ")
1725 if (enableSequences) // only if the user does want to !
1726 FoundLength =0; // ReadLength is unchanged
1729 // we found a 'delimiter' element
1730 // fffe|xxxx is just a marker, we don't take its length into account
1731 else if(Entry->GetGroup() == 0xfffe)
1733 // *normally, fffe|0000 doesn't exist !
1734 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1735 // causes extra troubles :-(
1739 Entry->SetUsableLength(FoundLength);
1743 * \brief Apply some heuristics to predict whether the considered
1744 * element value contains/represents an integer or not.
1745 * @param Entry The element value on which to apply the predicate.
1746 * @return The result of the heuristical predicate.
1748 bool gdcmDocument::IsHeaderEntryAnInteger(gdcmHeaderEntry *Entry) {
1749 guint16 element = Entry->GetElement();
1750 guint16 group = Entry->GetGroup();
1751 std::string vr = Entry->GetVR();
1752 guint32 length = Entry->GetLength();
1753 // When we have some semantics on the element we just read, and if we
1754 // a priori know we are dealing with an integer, then we shall be
1755 // able to swap it's element value properly.
1756 if ( element == 0 ) // This is the group length of the group
1762 std::ostringstream s;
1763 int filePosition = ftell(fp);
1764 s << "Erroneous Group Length element length on : (" \
1765 << std::hex << group << " , " << element
1766 << ") -before- position x(" << filePosition << ")"
1767 << "lgt : " << length;
1768 // These 2 lines commented out : a *very dirty* patch
1769 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1770 // have a glance at offset x(8336) ...
1771 // For *regular* headers, the test is useless..
1772 // lets's print a warning message and go on,
1773 // instead of giving up with an error message
1775 //std::cout << s.str().c_str() << std::endl;
1776 // dbg.Error("gdcmDocument::IsHeaderEntryAnInteger",
1777 // s.str().c_str());
1780 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1786 * \brief Find the Length till the next sequence delimiter
1787 * \warning NOT end user intended method !
1791 guint32 gdcmDocument::FindHeaderEntryLengthOB(void) {
1792 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1795 long PositionOnEntry = ftell(fp);
1796 bool FoundSequenceDelimiter = false;
1797 guint32 TotalLength = 0;
1800 while ( ! FoundSequenceDelimiter)
1806 TotalLength += 4; // We even have to decount the group and element
1808 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1810 char msg[100]; // for sprintf. Sorry
1811 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1812 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1816 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1817 FoundSequenceDelimiter = true;
1818 else if ( n != 0xe000 )
1820 char msg[100]; // for sprintf. Sorry
1821 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1823 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1827 ItemLength = ReadInt32();
1828 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1829 // the ItemLength with ReadInt32
1830 SkipBytes(ItemLength);
1832 fseek(fp, PositionOnEntry, SEEK_SET);
1837 * \brief Reads a supposed to be 16 Bits integer
1838 * (swaps it depending on processor endianity)
1839 * @return read value
1841 guint16 gdcmDocument::ReadInt16(void) {
1844 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1845 if ( item_read != 1 ) {
1847 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
1857 * \brief Reads a supposed to be 32 Bits integer
1858 * (swaps it depending on processor endianity)
1859 * @return read value
1861 guint32 gdcmDocument::ReadInt32(void) {
1864 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1865 if ( item_read != 1 ) {
1867 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
1877 * \brief skips bytes inside the source file
1878 * \warning NOT end user intended method !
1881 void gdcmDocument::SkipBytes(guint32 NBytes) {
1882 //FIXME don't dump the returned value
1883 (void)fseek(fp, (long)NBytes, SEEK_CUR);
1887 * \brief Loads all the needed Dictionaries
1888 * \warning NOT end user intended method !
1890 void gdcmDocument::Initialise(void)
1892 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
1893 RefShaDict = (gdcmDict*)0;
1897 * \brief Discover what the swap code is (among little endian, big endian,
1898 * bad little endian, bad big endian).
1900 * @return false when we are absolutely sure
1901 * it's neither ACR-NEMA nor DICOM
1902 * true when we hope ours assuptions are OK
1904 bool gdcmDocument::CheckSwap() {
1906 // The only guaranted way of finding the swap code is to find a
1907 // group tag since we know it's length has to be of four bytes i.e.
1908 // 0x00000004. Finding the swap code in then straigthforward. Trouble
1909 // occurs when we can't find such group...
1911 guint32 x=4; // x : for ntohs
1912 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
1918 char deb[HEADER_LENGTH_TO_READ];
1920 // First, compare HostByteOrder and NetworkByteOrder in order to
1921 // determine if we shall need to swap bytes (i.e. the Endian type).
1927 // The easiest case is the one of a DICOM header, since it possesses a
1928 // file preamble where it suffice to look for the string "DICM".
1929 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
1932 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
1933 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
1935 // Next, determine the value representation (VR). Let's skip to the
1936 // first element (0002, 0000) and check there if we find "UL"
1937 // - or "OB" if the 1st one is (0002,0001) -,
1938 // in which case we (almost) know it is explicit VR.
1939 // WARNING: if it happens to be implicit VR then what we will read
1940 // is the length of the group. If this ascii representation of this
1941 // length happens to be "UL" then we shall believe it is explicit VR.
1942 // FIXME: in order to fix the above warning, we could read the next
1943 // element value (or a couple of elements values) in order to make
1944 // sure we are not commiting a big mistake.
1945 // We need to skip :
1946 // * the 128 bytes of File Preamble (often padded with zeroes),
1947 // * the 4 bytes of "DICM" string,
1948 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1949 // i.e. a total of 136 bytes.
1953 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
1954 // but elem 0002,0010 (Transfert Syntax) tells us the file is
1955 // *Implicit* VR. -and it is !-
1957 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
1958 (memcmp(entCur, "OB", (size_t)2) == 0) ||
1959 (memcmp(entCur, "UI", (size_t)2) == 0) ||
1960 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
1961 // when Write DCM *adds*
1963 // Use gdcmDocument::dicom_vr to test all the possibilities
1964 // instead of just checking for UL, OB and UI !? group 0000
1966 filetype = ExplicitVR;
1967 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
1968 "explicit Value Representation");
1972 filetype = ImplicitVR;
1973 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
1974 "not an explicit Value Representation");
1980 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
1981 "HostByteOrder != NetworkByteOrder");
1986 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
1987 "HostByteOrder = NetworkByteOrder");
1990 // Position the file position indicator at first tag (i.e.
1991 // after the file preamble and the "DICM" string).
1993 fseek (fp, 132L, SEEK_SET);
1997 // Alas, this is not a DicomV3 file and whatever happens there is no file
1998 // preamble. We can reset the file position indicator to where the data
1999 // is (i.e. the beginning of the file).
2000 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2003 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2004 // By clean we mean that the length of the first tag is written down.
2005 // If this is the case and since the length of the first group HAS to be
2006 // four (bytes), then determining the proper swap code is straightforward.
2009 // We assume the array of char we are considering contains the binary
2010 // representation of a 32 bits integer. Hence the following dirty
2012 s32 = *((guint32 *)(entCur));
2033 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2034 // It is time for despaired wild guesses.
2035 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2036 // i.e. the 'group length' element is not present :
2038 // check the supposed to be 'group number'
2039 // 0x0002 or 0x0004 or 0x0008
2040 // to determine ' sw' value .
2041 // Only 0 or 4321 will be possible
2042 // (no oportunity to check for the formerly well known
2043 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2044 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2045 // the file IS NOT ACR-NEMA nor DICOM V3
2046 // Find a trick to tell it the caller...
2048 s16 = *((guint16 *)(deb));
2064 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2065 "ACR/NEMA unfound swap info (Really hopeless !)");
2070 // Then the only info we have is the net2host one.
2080 * \brief Restore the unproperly loaded values i.e. the group, the element
2081 * and the dictionary entry depending on them.
2083 void gdcmDocument::SwitchSwapToBigEndian(void)
2085 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2086 "Switching to BigEndian mode.");
2107 * \brief during parsing, Header Elements too long are not loaded in memory
2110 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2114 if ((guint32)NewSize >= (guint32)0xffffffff)
2116 MaxSizeLoadEntry = 0xffffffff;
2119 MaxSizeLoadEntry = NewSize;
2124 * \brief Header Elements too long will not be printed
2125 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2128 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2132 if ((guint32)NewSize >= (guint32)0xffffffff)
2134 MaxSizePrintEntry = 0xffffffff;
2137 MaxSizePrintEntry = NewSize;
2141 * \brief Searches both the public and the shadow dictionary (when they
2142 * exist) for the presence of the DictEntry with given name.
2143 * The public dictionary has precedence on the shadow one.
2144 * @param Name name of the searched DictEntry
2145 * @return Corresponding DictEntry when it exists, NULL otherwise.
2147 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2149 gdcmDictEntry *found = (gdcmDictEntry *)0;
2150 if (!RefPubDict && !RefShaDict)
2152 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2153 "we SHOULD have a default dictionary");
2157 found = RefPubDict->GetDictEntryByName(Name);
2163 found = RefShaDict->GetDictEntryByName(Name);
2171 * \brief Searches both the public and the shadow dictionary (when they
2172 * exist) for the presence of the DictEntry with given
2173 * group and element. The public dictionary has precedence on the
2175 * @param group group of the searched DictEntry
2176 * @param element element of the searched DictEntry
2177 * @return Corresponding DictEntry when it exists, NULL otherwise.
2179 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2181 gdcmDictEntry *found = (gdcmDictEntry *)0;
2182 if (!RefPubDict && !RefShaDict)
2184 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2185 "we SHOULD have a default dictionary");
2189 found = RefPubDict->GetDictEntryByNumber(group, element);
2195 found = RefShaDict->GetDictEntryByNumber(group, element);
2203 * \brief Read the next tag but WITHOUT loading it's value
2204 * @return On succes the newly created HeaderEntry, NULL on failure.
2206 gdcmHeaderEntry *gdcmDocument::ReadNextHeaderEntry(void) {
2208 gdcmHeaderEntry *NewEntry;
2213 // We reached the EOF (or an error occured) therefore
2214 // header parsing has to be considered as finished.
2215 return (gdcmHeaderEntry *)0;
2217 // Pb : how to propagate the element length (used in SkipHeaderEntry)
2218 // direct call to SkipBytes ?
2220 // if (ignoreShadow == 1 && g%2 ==1)
2221 // if user wants to skip shadow groups
2222 // and current element *is* a shadow element
2223 // we don't create anything
2224 // return (gdcmHeaderEntry *)1; // to tell caller it's NOT finished
2226 NewEntry = NewHeaderEntryByNumber(g, n);
2227 FindHeaderEntryVR(NewEntry);
2228 FindHeaderEntryLength(NewEntry);
2234 NewEntry->SetOffset(ftell(fp));
2239 * \brief Build a new Element Value from all the low level arguments.
2240 * Check for existence of dictionary entry, and build
2241 * a default one when absent.
2242 * @param Name Name of the underlying DictEntry
2244 gdcmHeaderEntry *gdcmDocument::NewHeaderEntryByName(std::string Name)
2246 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2248 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2250 gdcmHeaderEntry* NewEntry = new gdcmHeaderEntry(NewTag);
2253 dbg.Verbose(1, "gdcmDocument::ObtainHeaderEntryByName",
2254 "failed to allocate gdcmHeaderEntry");
2255 return (gdcmHeaderEntry *)0;
2261 * \brief Request a new virtual dict entry to the dict set
2262 * @param group group of the underlying DictEntry
2263 * @param element element of the underlying DictEntry
2264 * @param vr VR of the underlying DictEntry
2265 * @param fourth owner group
2266 * @param name english name
2268 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2273 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2277 * \brief Build a new Element Value from all the low level arguments.
2278 * Check for existence of dictionary entry, and build
2279 * a default one when absent.
2280 * @param Group group of the underlying DictEntry
2281 * @param Elem element of the underlying DictEntry
2283 gdcmHeaderEntry *gdcmDocument::NewHeaderEntryByNumber(guint16 Group, guint16 Elem)
2285 // Find out if the tag we encountered is in the dictionaries:
2286 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2288 DictEntry = NewVirtualDictEntry(Group, Elem);
2290 gdcmHeaderEntry *NewEntry = new gdcmHeaderEntry(DictEntry);
2293 dbg.Verbose(1, "gdcmDocument::NewHeaderEntryByNumber",
2294 "failed to allocate gdcmHeaderEntry");
2300 /// \todo Never used; commented out, waiting for removal.
2302 * \brief Small utility function that creates a new manually crafted
2303 * (as opposed as read from the file) gdcmHeaderEntry with user
2304 * specified name and adds it to the public tag hash table.
2305 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
2306 * @param NewTagName The name to be given to this new tag.
2307 * @param VR The Value Representation to be given to this new tag.
2308 * @return The newly hand crafted Element Value.
2310 //gdcmHeaderEntry *gdcmDocument::NewManualHeaderEntryToPubDict(std::string NewTagName,
2313 // gdcmHeaderEntry *NewEntry = NULL;
2314 // guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
2315 // guint32 FreeElem = 0;
2316 // gdcmDictEntry *DictEntry = NULL;
2318 // FreeElem = GenerateFreeTagKeyInGroup(StuffGroup);
2319 // if (FreeElem == UINT32_MAX)
2321 // dbg.Verbose(1, "gdcmHeader::NewManualHeaderEntryToPubDict",
2322 // "Group 0xffff in Public Dict is full");
2326 // DictEntry = NewVirtualDictEntry(StuffGroup, FreeElem,
2327 // VR, "GDCM", NewTagName);
2328 // NewEntry = new gdcmHeaderEntry(DictEntry);
2329 // AddHeaderEntry(NewEntry);
2334 * \brief Generate a free TagKey i.e. a TagKey that is not present
2335 * in the TagHt dictionary.
2336 * @param group The generated tag must belong to this group.
2337 * @return The element of tag with given group which is fee.
2339 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2341 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2343 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2344 if (tagHT.count(key) == 0)
2350 //-----------------------------------------------------------------------------