2 //-----------------------------------------------------------------------------
4 #include "gdcmDocument.h"
5 #include "gdcmValEntry.h"
6 #include "gdcmBinEntry.h"
7 #include "gdcmSeqEntry.h"
9 #include "gdcmGlobal.h"
11 #include "gdcmDebug.h"
20 #include <netinet/in.h>
25 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
26 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
27 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
28 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
29 #define UI1_1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
31 #define str2num(str, typeNum) *((typeNum *)(str))
33 //-----------------------------------------------------------------------------
34 // Refer to gdcmDocument::CheckSwap()
35 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
37 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
38 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
40 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
42 //-----------------------------------------------------------------------------
43 // Constructor / Destructor
47 * @param inFilename file to be opened for parsing
48 * @param exception_on_error whether we throw an exception or not
49 * @param enable_sequences = true to allow the header
50 * to be parsed *inside* the SeQuences,
51 * when they have an actual length
52 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
53 * @param ignore_shadow to allow skipping the shadow elements,
54 * to save memory space.
55 * \warning The TRUE value for this param has to be used
56 * with a FALSE value for the 'enable_sequence' param.
57 * ('public elements' may be embedded in 'shadow Sequences')
59 gdcmDocument::gdcmDocument(const char *inFilename,
60 bool exception_on_error,
61 bool enable_sequences,
63 : gdcmElementSet(-1) {
64 enableSequences=enable_sequences;
65 ignoreShadow =ignore_shadow;
67 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
68 filename = inFilename;
71 if ( !OpenFile(exception_on_error))
76 // return false; // to go on compiling
78 fseek(fp,0L,SEEK_END);
88 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
91 // --------------------------------------------------------------
92 // Special Patch to allow gdcm to read ACR-LibIDO formated images
94 // if recognition code tells us we deal with a LibIDO image
95 // we switch lineNumber and columnNumber
98 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
99 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
100 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
101 // with "little-endian strings"
103 filetype = gdcmACR_LIBIDO;
104 std::string rows = GetEntryByNumber(0x0028, 0x0010);
105 std::string columns = GetEntryByNumber(0x0028, 0x0011);
106 SetEntryByNumber(columns, 0x0028, 0x0010);
107 SetEntryByNumber(rows , 0x0028, 0x0011);
109 // ----------------- End of Special Patch ----------------
111 printLevel = 1; // 'Medium' print level by default
116 * @param exception_on_error
118 gdcmDocument::gdcmDocument(bool exception_on_error)
119 :gdcmElementSet(-1) {
120 (void)exception_on_error;
123 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
126 printLevel = 1; // 'Medium' print level by default
130 * \brief Canonical destructor.
132 gdcmDocument::~gdcmDocument (void) {
137 //-----------------------------------------------------------------------------
143 * \brief Prints The Dict Entries of THE public Dicom Dictionary
146 void gdcmDocument::PrintPubDict(std::ostream & os) {
147 RefPubDict->Print(os);
151 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
154 void gdcmDocument::PrintShaDict(std::ostream & os) {
155 RefShaDict->Print(os);
158 //-----------------------------------------------------------------------------
161 * \brief Get the public dictionary used
163 gdcmDict *gdcmDocument::GetPubDict(void) {
168 * \brief Get the shadow dictionary used
170 gdcmDict *gdcmDocument::GetShaDict(void) {
175 * \brief Set the shadow dictionary used
176 * \param dict dictionary to use in shadow
178 bool gdcmDocument::SetShaDict(gdcmDict *dict){
184 * \brief Set the shadow dictionary used
185 * \param dictName name of the dictionary to use in shadow
187 bool gdcmDocument::SetShaDict(DictKey dictName){
188 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
193 * \brief This predicate, based on hopefully reasonable heuristics,
194 * decides whether or not the current gdcmDocument was properly parsed
195 * and contains the mandatory information for being considered as
196 * a well formed and usable Dicom/Acr File.
197 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
200 bool gdcmDocument::IsReadable(void) {
201 if(filetype==gdcmUnknown) {
202 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
205 if(!tagHT.empty()<=0) {
206 std::cout << "gdcmDocument::IsReadable: wrong tagHT size : "
216 * \brief Determines if the Transfer Syntax was already encountered
217 * and if it corresponds to a ImplicitVRLittleEndian one.
218 * @return True when ImplicitVRLittleEndian found. False in all other cases.
220 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void) {
221 gdcmDocEntry *Element = GetDocEntryByNumber(0x0002, 0x0010);
224 LoadDocEntrySafe(Element);
226 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
227 if ( Transfer == UI1_2_840_10008_1_2 )
233 * \brief Determines if the Transfer Syntax was already encountered
234 * and if it corresponds to a ExplicitVRLittleEndian one.
235 * @return True when ExplicitVRLittleEndian found. False in all other cases.
237 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void) {
238 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
241 LoadDocEntrySafe(Element);
243 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
244 if ( Transfer == UI1_2_840_10008_1_2_1 )
250 * \brief Determines if the Transfer Syntax was already encountered
251 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
252 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
254 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
255 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
258 LoadDocEntrySafe(Element);
260 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
261 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
267 * \brief Determines if the Transfer Syntax was already encountered
268 * 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 gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void) {
272 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
275 LoadDocEntrySafe(Element);
277 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
278 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
284 * \brief Determines if the Transfer Syntax was already encountered
285 * and if it corresponds to a JPEGBaseLineProcess1 one.
286 * @return True when JPEGBaseLineProcess1found. False in all other cases.
288 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void) {
289 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
292 LoadDocEntrySafe(Element);
294 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
295 if ( Transfer == "1.2.840.10008.1.2.4.50" )
301 * \brief Determines if the Transfer Syntax was already encountered
302 * and if it corresponds to a JPEGExtendedProcess2-4 one.
303 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
305 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void) {
306 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
309 LoadDocEntrySafe(Element);
310 return ( ((gdcmValEntry *)Element)->GetValue() == "1.2.840.10008.1.2.4.51"
314 * \brief Determines if the Transfer Syntax was already encountered
315 * and if it corresponds to a JPEGExtendeProcess3-5 one.
316 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
318 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void) {
319 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
322 LoadDocEntrySafe(Element);
324 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
325 if ( Transfer == "1.2.840.10008.1.2.4.52" )
331 * \brief Determines if the Transfer Syntax was already encountered
332 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
333 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
336 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
337 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
340 LoadDocEntrySafe(Element);
342 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
343 if ( Transfer == "1.2.840.10008.1.2.4.53" )
349 * \brief Determines if the Transfer Syntax was already encountered
350 * and if it corresponds to a RLE Lossless one.
351 * @return True when RLE Lossless found. False in all
354 bool gdcmDocument::IsRLELossLessTransferSyntax(void) {
355 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
358 LoadDocEntrySafe(Element);
360 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
361 if ( Transfer == "1.2.840.10008.1.2.5" ) {
368 * \brief Determines if Transfer Syntax was already encountered
369 * and if it corresponds to a JPEG Lossless one.
370 * @return True when RLE Lossless found. False in all
373 bool gdcmDocument::IsJPEGLossless(void) {
374 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
375 // faire qq chose d'intelligent a la place de ça
378 LoadDocEntrySafe(Element);
380 const char * Transfert = ((gdcmValEntry *)Element)->GetValue().c_str();
382 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
383 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
385 if (((gdcmValEntry *)Element)->GetValue() == "1.2.840.10008.1.2.4.57")
392 * \brief Determines if the Transfer Syntax was already encountered
393 * and if it corresponds to a JPEG2000 one
394 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
397 bool gdcmDocument::IsJPEG2000(void) {
398 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
401 LoadDocEntrySafe(Element);
403 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
404 if ( (Transfer == "1.2.840.10008.1.2.4.90")
405 || (Transfer == "1.2.840.10008.1.2.4.91") )
411 * \brief Predicate for dicom version 3 file.
412 * @return True when the file is a dicom version 3.
414 bool gdcmDocument::IsDicomV3(void) {
415 // Checking if Transfert Syntax exists is enough
416 // Anyway, it's to late check if the 'Preamble' was found ...
417 // And ... would it be a rich idea to check ?
418 // (some 'no Preamble' DICOM images exist !)
419 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
423 * \brief returns the File Type
424 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
425 * @return the FileType code
427 FileType gdcmDocument::GetFileType(void) {
432 * \brief opens the file
433 * @param exception_on_error
436 FILE *gdcmDocument::OpenFile(bool exception_on_error)
439 fp=fopen(filename.c_str(),"rb");
443 if(exception_on_error)
444 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
447 std::cout <<"gdcmDocument::OpenFile cannot open file: "
448 << filename.c_str() << std::endl;
449 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
458 fread(&zero, (size_t)2, (size_t)1, fp);
460 //ACR -- or DICOM with no Preamble --
461 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
465 fseek(fp, 126L, SEEK_CUR);
467 fread(dicm, (size_t)4, (size_t)1, fp);
468 if( memcmp(dicm, "DICM", 4) == 0 )
472 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
475 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
481 * \brief closes the file
482 * @return TRUE if the close was successfull
484 bool gdcmDocument::CloseFile(void) {
485 int closed = fclose(fp);
493 * \brief Writes in a file all the Header Entries (Dicom Elements)
494 * of the Chained List
495 * @param fp file pointer on an already open file
496 * @param type Type of the File to be written
497 * (ACR-NEMA, ExplicitVR, ImplicitVR)
498 * \return Always true.
500 bool gdcmDocument::Write(FILE *fp, FileType type) {
503 /// The stuff will have to be rewritten using the SeQuence based
504 /// tree-like stucture instead of the chained list .
505 /// (so we shall remove the Group*HT from the gdcmDocument)
509 /// \todo move the following lines (and a lot of others, to be written)
510 /// to a future function CheckAndCorrectHeader
514 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
515 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
516 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
518 /// a moins de se livrer a un tres complique ajout des champs manquants.
519 /// faire un CheckAndCorrectHeader (?)
521 if (type == gdcmImplicitVR)
523 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
524 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
526 /// \todo Refer to standards on page 21, chapter 6.2
527 /// "Value representation": values with a VR of UI shall be
528 /// padded with a single trailing null
529 /// Dans le cas suivant on doit pader manuellement avec un 0
531 SetEntryLengthByNumber(18, 0x0002, 0x0010);
534 if (type == gdcmExplicitVR)
536 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
537 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
539 /// \todo Refer to standards on page 21, chapter 6.2
540 /// "Value representation": values with a VR of UI shall be
541 /// padded with a single trailing null
542 /// Dans le cas suivant on doit pader manuellement avec un 0
544 SetEntryLengthByNumber(20, 0x0002, 0x0010);
548 * \todo rewrite later, if really usefull
550 * --> Warning : un-updated odd groups lengths can causes pb
551 * --> (xmedcon breaks)
552 * --> to be re- written with future org.
554 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
555 * UpdateGroupLength(false,type);
557 * UpdateGroupLength(true,ACR);
560 WriteEntries(fp,type);
565 * \brief Modifies the value of a given Header Entry (Dicom Element)
566 * when it exists. Create it with the given value when unexistant.
567 * @param Value Value to be set
568 * @param Group Group number of the Entry
569 * @param Elem Element number of the Entry
570 * \return pointer to the modified/created Header Entry (NULL when creation
575 gdcmDocEntry * gdcmDocument::ReplaceOrCreateByNumber(
580 a = GetDocEntryByNumber( Group, Elem);
582 a =NewDocEntryByNumber(Group, Elem);
587 SetEntryByNumber(Value, Group, Elem);
588 //a->SetValue(Value);
593 * \brief Set a new value if the invoked element exists
594 * Seems to be useless !!!
595 * @param Value new element value
596 * @param Group group number of the Entry
597 * @param Elem element number of the Entry
600 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
602 std::string v = Value;
603 SetEntryByNumber(v, Group, Elem);
607 //-----------------------------------------------------------------------------
611 * \brief Checks if a given Dicom Element exists within the H table
612 * @param group Group number of the searched Dicom Element
613 * @param element Element number of the searched Dicom Element
614 * @return number of occurences
616 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
617 std::string key = gdcmDictEntry::TranslateToKey(group, element );
618 return (tagHT.count(key));
622 * \brief Searches within Header Entries (Dicom Elements) parsed with
623 * the public and private dictionaries
624 * for the element value of a given tag.
625 * \warning Don't use any longer : use GetPubEntryByName
626 * @param tagName name of the searched element.
627 * @return Corresponding element value when it exists,
628 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
630 std::string gdcmDocument::GetEntryByName(std::string tagName) {
631 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
632 if( dictEntry == NULL)
635 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
639 * \brief Searches within Header Entries (Dicom Elements) parsed with
640 * the public and private dictionaries
641 * for the element value representation of a given tag.
643 * Obtaining the VR (Value Representation) might be needed by caller
644 * to convert the string typed content to caller's native type
645 * (think of C++ vs Python). The VR is actually of a higher level
646 * of semantics than just the native C++ type.
647 * @param tagName name of the searched element.
648 * @return Corresponding element value representation when it exists,
649 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
651 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
652 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
653 if( dictEntry == NULL)
656 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
657 dictEntry->GetElement());
658 return elem->GetVR();
663 * \brief Searches within Header Entries (Dicom Elements) parsed with
664 * the public and private dictionaries
665 * for the element value representation of a given tag.
666 * @param group Group number of the searched tag.
667 * @param element Element number of the searched tag.
668 * @return Corresponding element value representation when it exists,
669 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
671 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
672 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
673 if ( ! tagHT.count(key))
675 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
679 * \brief Searches within Header Entries (Dicom Elements) parsed with
680 * the public and private dictionaries
681 * for the element value representation of a given tag..
683 * Obtaining the VR (Value Representation) might be needed by caller
684 * to convert the string typed content to caller's native type
685 * (think of C++ vs Python). The VR is actually of a higher level
686 * of semantics than just the native C++ type.
687 * @param group Group number of the searched tag.
688 * @param element Element number of the searched tag.
689 * @return Corresponding element value representation when it exists,
690 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
692 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
693 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
696 return elem->GetVR();
700 * \brief Searches within Header Entries (Dicom Elements) parsed with
701 * the public and private dictionaries
702 * for the value length of a given tag..
703 * @param group Group number of the searched tag.
704 * @param element Element number of the searched tag.
705 * @return Corresponding element length; -2 if not found
707 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
708 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
711 return elem->GetLength();
714 * \brief Sets the value (string) of the Header Entry (Dicom Element)
715 * @param content string value of the Dicom Element
716 * @param tagName name of the searched Dicom Element.
717 * @return true when found
719 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
720 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
721 if( dictEntry == NULL)
724 return(SetEntryByNumber(content,dictEntry->GetGroup(),
725 dictEntry->GetElement()));
729 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
730 * through it's (group, element) and modifies it's content with
732 * @param content new value to substitute with
733 * @param group group number of the Dicom Element to modify
734 * @param element element number of the Dicom Element to modify
736 bool gdcmDocument::SetEntryByNumber(std::string content,
740 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
741 if ( ! tagHT.count(key))
743 int l = content.length();
744 if(l%2) // Non even length are padded with a space (020H).
747 content = content + '\0';
753 ((gdcmValEntry*)a)->SetValue(content);
755 VRKey vr = a->GetVR();
758 if( (vr == "US") || (vr == "SS") )
760 else if( (vr == "UL") || (vr == "SL") )
770 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
771 * in the PubDocEntrySet of this instance
772 * through it's (group, element) and modifies it's length with
774 * \warning Use with extreme caution.
775 * @param l new length to substitute with
776 * @param group group number of the Entry to modify
777 * @param element element number of the Entry to modify
778 * @return true on success, false otherwise.
780 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
784 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
785 if ( ! tagHT.count(key))
787 if (l%2) l++; // length must be even
788 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
794 * \brief Gets (from Header) the offset of a 'non string' element value
795 * (LoadElementValues has already be executed)
796 * @param Group group number of the Entry
797 * @param Elem element number of the Entry
798 * @return File Offset of the Element Value
800 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
802 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
805 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
806 "failed to Locate gdcmDocEntry");
809 return Entry->GetOffset();
813 * \brief Gets (from Header) a 'non string' element value
814 * (LoadElementValues has already be executed)
815 * @param Group group number of the Entry
816 * @param Elem element number of the Entry
817 * @return Pointer to the 'non string' area
819 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
821 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
824 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
825 "failed to Locate gdcmDocEntry");
828 return ((gdcmBinEntry *)Entry)->GetVoidArea();
832 * \brief Loads (from disk) the element content
833 * when a string is not suitable
834 * @param Group group number of the Entry
835 * @param Elem element number of the Entry
837 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
839 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
842 size_t o =(size_t)Element->GetOffset();
843 fseek(fp, o, SEEK_SET);
844 size_t l=Element->GetLength();
845 char* a = new char[l];
849 SetEntryVoidAreaByNumber(a, Group, Elem);
850 /// \todo check the result
851 size_t l2 = fread(a, 1, l ,fp);
862 * \brief Sets a 'non string' value to a given Dicom Element
864 * @param group Group number of the searched Dicom Element
865 * @param element Element number of the searched Dicom Element
868 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
872 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
873 if ( ! tagHT.count(key))
875 // This was for multimap ?
876 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
882 * \brief Update the entries with the shadow dictionary.
883 * Only non even entries are analyzed
885 void gdcmDocument::UpdateShaEntries(void) {
886 gdcmDictEntry *entry;
889 // TODO : if still any use (?) explore recursively the whole structure
891 for(ListTag::iterator it=listEntries.begin();
892 it!=listEntries.end();
895 // Odd group => from public dictionary
896 if((*it)->GetGroup()%2==0)
899 // Peer group => search the corresponding dict entry
901 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
905 if((*it)->IsImplicitVR())
910 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
912 // Set the new entry and the new value
913 (*it)->SetDictEntry(entry);
914 CheckDocEntryVR(*it,vr);
916 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
921 // Remove precedent value transformation
922 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
929 * \brief Searches within the Header Entries for a Dicom Element of
931 * @param tagName name of the searched Dicom Element.
932 * @return Corresponding Dicom Element when it exists, and NULL
935 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
936 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
937 if( dictEntry == NULL)
940 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
944 * \brief retrieves a Dicom Element (the first one) using (group, element)
945 * \warning (group, element) IS NOT an identifier inside the Dicom Header
946 * if you think it's NOT UNIQUE, check the count number
947 * and use iterators to retrieve ALL the Dicoms Elements within
948 * a given couple (group, element)
949 * @param group Group number of the searched Dicom Element
950 * @param element Element number of the searched Dicom Element
953 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
955 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
956 if ( ! tagHT.count(key))
958 return tagHT.find(key)->second;
962 * \brief Loads the element while preserving the current
963 * underlying file position indicator as opposed to
964 * to LoadDocEntry that modifies it.
965 * @param entry Header Entry whose value shall be loaded.
968 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
969 long PositionOnEntry = ftell(fp);
971 fseek(fp, PositionOnEntry, SEEK_SET);
976 * \brief Writes in a file (according to the requested format)
977 * the group, the element, the value representation and the length
978 * of a single gdcmDocEntry passed as argument.
979 * @param tag pointer on the gdcmDocEntry to be written
980 * @param _fp already open file pointer
981 * @param type type of the File to be written
983 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
987 guint16 group = tag->GetGroup();
988 VRKey vr = tag->GetVR();
989 guint16 el = tag->GetElement();
990 guint32 lgr = tag->GetReadLength();
992 if ( (group == 0xfffe) && (el == 0x0000) )
993 // Fix in order to make some MR PHILIPS images e-film readable
994 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
995 // we just *always* ignore spurious fffe|0000 tag !
998 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
999 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1001 if ( type == gdcmExplicitVR ) {
1003 // Special case of delimiters:
1004 if (group == 0xfffe) {
1005 // Delimiters have NO Value Representation and have NO length.
1006 // Hence we skip writing the VR and length and we pad by writing
1010 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1015 guint16 shortLgr = lgr;
1016 if (vr == "unkn") { // Unknown was 'written'
1017 // deal with Little Endian
1018 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1019 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1021 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1022 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1024 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1025 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1027 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1033 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1038 * \brief Writes in a file (according to the requested format)
1039 * the value of a single gdcmDocEntry passed as argument.
1040 * @param tag Pointer on the gdcmDocEntry to be written
1041 * @param _fp Already open file pointer
1042 * @param type type of the File to be written
1045 // TODO : to be re -written recursively !
1047 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1050 guint16 group = tag->GetGroup();
1051 VRKey vr = tag->GetVR();
1052 guint32 lgr = tag->GetReadLength();
1055 // SeQuences have no value:
1057 if (group == 0xfffe)
1058 // Delimiters have no associated value:
1061 //--------------------------------
1063 // FIXME :right now, both value and voidArea belong to gdcmValue
1065 // -------------------------------
1067 // if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) ) {
1069 gdcmBinEntry *BinEntry= (gdcmBinEntry *)tag;;
1070 voidArea = BinEntry->GetVoidArea();
1071 if (voidArea != NULL)
1072 { // there is a 'non string' LUT, overlay, etc
1073 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1078 if (vr == "US" || vr == "SS")
1080 // some 'Short integer' fields may be mulivaluated
1081 // each single value is separated from the next one by '\'
1082 // we split the string and write each value as a short int
1083 std::vector<std::string> tokens;
1084 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1085 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1086 for (unsigned int i=0; i<tokens.size();i++)
1088 guint16 val_uint16 = atoi(tokens[i].c_str());
1089 void *ptr = &val_uint16;
1090 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1095 // some 'Integer' fields may be mulivaluated
1096 // each single value is separated from the next one by '\'
1097 // we split the string and write each value as an int
1098 if (vr == "UL" || vr == "SL")
1100 std::vector<std::string> tokens;
1101 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1102 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1103 for (unsigned int i=0; i<tokens.size();i++)
1105 guint32 val_uint32 = atoi(tokens[i].c_str());
1106 void *ptr = &val_uint32;
1107 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1112 fwrite (((gdcmValEntry *)tag)->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1116 * \brief Writes in a file (according to the requested format)
1117 * a single gdcmDocEntry passed as argument.
1118 * \sa WriteEntryValue, WriteEntryTagVRLength.
1119 * @param tag Pointer on the gdcmDocEntry to be written
1120 * @param _fp Already open file pointer
1121 * @param type type of the File to be written
1124 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1126 guint32 length = tag->GetLength();
1128 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(tag) ) {
1129 // The value of a tag MUST (see the DICOM norm) be an odd number of
1130 // bytes. When this is not the case, pad with an additional byte:
1132 ValEntry->SetValue(ValEntry->GetValue()+"\0");
1133 ValEntry->SetLength(ValEntry->GetReadLength()+1);
1136 WriteEntryTagVRLength(ValEntry, _fp, type);
1137 std::cout << "after WriteEntryTagVRLength " << std::endl;
1138 WriteEntryValue(ValEntry, _fp, type);
1139 std::cout << "after WriteEntryValue " << std::endl;
1143 if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) ) {
1145 // FIXME : when voidArea belong to gdcmBinEntry only, fix voidArea length
1147 // The value of a tag MUST (see the DICOM norm) be an odd number of
1148 // bytes. When this is not the case, pad with an additional byte:
1151 Vtag->SetValue(Vtag->GetValue()+"\0");
1152 Vtag->SetLength(Vtag->GetReadLength()+1);
1156 WriteEntryTagVRLength(tag, _fp, type);
1157 std::cout << "after WriteEntryTagVRLength " << std::endl;
1158 WriteEntryValue(tag, _fp, type);
1159 std::cout << "after WriteEntryValue " << std::endl;
1165 * \brief writes on disc according to the requested format
1166 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1167 * using the Chained List
1168 * \warning does NOT add the missing elements in the header :
1169 * it's up to the user doing it !
1170 * (function CheckHeaderCoherence to be written)
1171 * \warning DON'T try, right now, to write a DICOM image
1172 * from an ACR Header (meta elements will be missing!)
1173 * @param type type of the File to be written
1174 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1175 * @param _fp already open file pointer
1178 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1181 // FIXME : explore recursively the whole structure...
1183 /// \todo (?) check write failures (after *each* fwrite)
1185 std::cout << "--------------------- gdcmDocument::WriteEntries " << std::endl;
1186 for (TagDocEntryHT::iterator tag2=tagHT.begin();
1187 tag2 != tagHT.end();
1191 (*tag2).second->Print();
1193 if ( type == gdcmACR ){
1194 if ((*tag2).second->GetGroup() < 0x0008)
1195 // Ignore pure DICOM V3 groups
1197 if ((*tag2).second->GetGroup() %2)
1198 // Ignore the "shadow" groups
1200 if ((*tag2).second->GetVR() == "SQ" ) // ignore Sequences
1203 if (! WriteEntry((*tag2).second,_fp,type) ) {
1204 std::cout << "Write Failure " << std::endl;
1215 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1217 * @return The properly swaped 32 bits integer.
1219 guint32 gdcmDocument::SwapLong(guint32 a) {
1224 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1225 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1229 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1233 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1236 std::cout << "swapCode= " << sw << std::endl;
1237 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1244 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1246 * @return The properly unswaped 32 bits integer.
1248 guint32 gdcmDocument::UnswapLong(guint32 a) {
1249 return (SwapLong(a));
1253 * \brief Swaps the bytes so they agree with the processor order
1254 * @return The properly swaped 16 bits integer.
1256 guint16 gdcmDocument::SwapShort(guint16 a) {
1257 if ( (sw==4321) || (sw==2143) )
1258 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1263 * \brief Unswaps the bytes so they agree with the processor order
1264 * @return The properly unswaped 16 bits integer.
1266 guint16 gdcmDocument::UnswapShort(guint16 a) {
1267 return (SwapShort(a));
1270 //-----------------------------------------------------------------------------
1274 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1275 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1278 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1280 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1288 depth = set->GetDepthLevel();
1291 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1294 NewDocEntry = ReadNextDocEntry( );
1298 vr = NewDocEntry->GetVR();
1301 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1304 vl= new gdcmValEntry(NewDocEntry->GetDictEntry());
1305 vl->Copy(NewDocEntry);
1306 vl->SetDepthLevel(depth);
1309 if (/*!delim_mode && */vl->isItemDelimitor())
1311 if ( !delim_mode && ftell(fp)-offset >= l_max)
1318 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1320 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1321 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1322 "nor BinEntry. Probably unknown VR.");
1325 ////// BinEntry or UNKOWN VR:
1326 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1327 bn->Copy(NewDocEntry);
1332 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1333 NewDocEntry->GetElement() == 0x0010 )
1335 if (NewDocEntry->GetLength()==0xffffffff)
1336 // Broken US.3405.1.dcm
1337 Parse7FE0(); // to skip the pixels
1338 // (multipart JPEG/RLE are trouble makers)
1342 // to be sure we are at the beginning
1343 SkipToNextDocEntry(NewDocEntry);
1344 l = NewDocEntry->GetFullLength();
1346 } else { // VR = "SQ"
1348 l=NewDocEntry->GetReadLength();
1349 if (l != 0) // don't mess the delim_mode for zero-length sequence
1350 if (l == 0xffffffff)
1354 // no other way to create it ...
1355 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1356 set->GetDepthLevel());
1357 sq->Copy(NewDocEntry);
1358 sq->SetDelimitorMode(delim_mode);
1359 sq->SetDepthLevel(depth);
1362 { // Don't try to parse zero-length sequences
1363 long lgt = ParseSQ( sq,
1364 NewDocEntry->GetOffset(),
1367 // FIXME : on en fait quoi, de lgt ?
1369 if ( !delim_mode && ftell(fp)-offset >= l_max)
1380 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1381 * @return parsed length for this level
1383 long gdcmDocument::ParseSQ(gdcmSeqEntry *set, long offset, long l_max, bool delim_mode) {
1384 int SQItemNumber = 0;
1385 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1389 int depth = set->GetDepthLevel();
1392 NewDocEntry = ReadNextDocEntry();
1394 if (NewDocEntry->isSequenceDelimitor()) {
1395 //add the Sequence Delimitor // TODO : find the trick to put it properly !
1396 set->SetSequenceDelimitationItem(NewDocEntry);
1400 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1403 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1404 itemSQ->AddEntry(NewDocEntry); // no value, no voidArea. Think of it while printing !
1405 l= NewDocEntry->GetReadLength();
1412 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1414 set->AddEntry(itemSQ);
1415 SQItemNumber ++; // a voir
1416 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1420 lgth = ftell(fp) - offset;
1425 * \brief Loads the element content if its length doesn't exceed
1426 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1427 * @param Entry Header Entry (Dicom Element) to be dealt with
1429 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry) {
1431 guint16 group = Entry->GetGroup();
1432 std::string vr= Entry->GetVR();
1433 guint32 length = Entry->GetLength();
1435 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1437 // A SeQuence "contains" a set of Elements.
1438 // (fffe e000) tells us an Element is beginning
1439 // (fffe e00d) tells us an Element just ended
1440 // (fffe e0dd) tells us the current SeQuence just ended
1441 if( group == 0xfffe ) {
1442 // NO more value field for SQ !
1443 //Entry->SetValue("gdcm::Skipped");
1444 // appel recursif de Load Value
1445 // (meme pb que pour le parsing)
1449 // When the length is zero things are easy:
1450 if ( length == 0 ) {
1451 ((gdcmValEntry *)Entry)->SetValue("");
1455 // The elements whose length is bigger than the specified upper bound
1456 // are not loaded. Instead we leave a short notice of the offset of
1457 // the element content and it's length.
1458 if (length > MaxSizeLoadEntry) {
1459 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1461 std::ostringstream s;
1462 s << "gdcm::NotLoaded.";
1463 s << " Address:" << (long)Entry->GetOffset();
1464 s << " Length:" << Entry->GetLength();
1465 s << " x(" << std::hex << Entry->GetLength() << ")";
1466 ValEntryPtr->SetValue(s.str());
1468 // to be sure we are at the end of the value ...
1469 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1474 // Any compacter code suggested (?)
1475 if ( IsDocEntryAnInteger(Entry) ) {
1477 std::ostringstream s;
1479 // When short integer(s) are expected, read and convert the following
1480 // n *two characters properly i.e. as short integers as opposed to strings.
1481 // Elements with Value Multiplicity > 1
1482 // contain a set of integers (not a single one)
1483 if (vr == "US" || vr == "SS") {
1485 NewInt = ReadInt16();
1488 for (int i=1; i < nbInt; i++) {
1490 NewInt = ReadInt16();
1495 // When integer(s) are expected, read and convert the following
1496 // n * four characters properly i.e. as integers as opposed to strings.
1497 // Elements with Value Multiplicity > 1
1498 // contain a set of integers (not a single one)
1499 else if (vr == "UL" || vr == "SL") {
1501 NewInt = ReadInt32();
1504 for (int i=1; i < nbInt; i++) {
1506 NewInt = ReadInt32();
1511 #ifdef GDCM_NO_ANSI_STRING_STREAM
1512 s << std::ends; // to avoid oddities on Solaris
1513 #endif //GDCM_NO_ANSI_STRING_STREAM
1515 ((gdcmValEntry *)Entry)->SetValue(s.str());
1519 // We need an additional byte for storing \0 that is not on disk
1520 std::string NewValue(length,0);
1521 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1522 if ( item_read != 1 ) {
1523 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1524 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1528 if( (vr == "UI") ) // Because of correspondance with the VR dic
1529 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1531 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1536 * \brief Find the value Length of the passed Header Entry
1537 * @param Entry Header Entry whose length of the value shall be loaded.
1539 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1540 guint16 element = Entry->GetElement();
1541 //guint16 group = Entry->GetGroup(); //FIXME
1542 std::string vr = Entry->GetVR();
1546 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1548 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1550 // The following reserved two bytes (see PS 3.5-2001, section
1551 // 7.1.2 Data element structure with explicit vr p27) must be
1552 // skipped before proceeding on reading the length on 4 bytes.
1553 fseek(fp, 2L, SEEK_CUR);
1554 guint32 length32 = ReadInt32();
1556 if ( (vr == "OB") && (length32 == 0xffffffff) )
1558 Entry->SetLength(FindDocEntryLengthOB());
1561 FixDocEntryFoundLength(Entry, length32);
1565 // Length is encoded on 2 bytes.
1566 length16 = ReadInt16();
1568 // We can tell the current file is encoded in big endian (like
1569 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1570 // and it's value is the one of the encoding of a big endian file.
1571 // In order to deal with such big endian encoded files, we have
1572 // (at least) two strategies:
1573 // * when we load the "Transfer Syntax" tag with value of big endian
1574 // encoding, we raise the proper flags. Then we wait for the end
1575 // of the META group (0x0002) among which is "Transfer Syntax",
1576 // before switching the swap code to big endian. We have to postpone
1577 // the switching of the swap code since the META group is fully encoded
1578 // in little endian, and big endian coding only starts at the next
1579 // group. The corresponding code can be hard to analyse and adds
1580 // many additional unnecessary tests for regular tags.
1581 // * the second strategy consists in waiting for trouble, that shall
1582 // appear when we find the first group with big endian encoding. This
1583 // is easy to detect since the length of a "Group Length" tag (the
1584 // ones with zero as element number) has to be of 4 (0x0004). When we
1585 // encounter 1024 (0x0400) chances are the encoding changed and we
1586 // found a group with big endian encoding.
1587 // We shall use this second strategy. In order to make sure that we
1588 // can interpret the presence of an apparently big endian encoded
1589 // length of a "Group Length" without committing a big mistake, we
1590 // add an additional check: we look in the already parsed elements
1591 // for the presence of a "Transfer Syntax" whose value has to be "big
1592 // endian encoding". When this is the case, chances are we have got our
1593 // hands on a big endian encoded file: we switch the swap code to
1594 // big endian and proceed...
1595 if ( (element == 0x0000) && (length16 == 0x0400) )
1597 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1599 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1604 SwitchSwapToBigEndian();
1605 // Restore the unproperly loaded values i.e. the group, the element
1606 // and the dictionary entry depending on them.
1607 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1608 guint16 CorrectElem = SwapShort(Entry->GetElement());
1609 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1613 // This correct tag is not in the dictionary. Create a new one.
1614 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1616 // FIXME this can create a memory leaks on the old entry that be
1617 // left unreferenced.
1618 Entry->SetDictEntry(NewTag);
1621 // Heuristic: well some files are really ill-formed.
1622 if ( length16 == 0xffff)
1625 //dbg.Verbose(0, "gdcmDocument::FindLength",
1626 // "Erroneous element length fixed.");
1627 // Actually, length= 0xffff means that we deal with
1628 // Unknown Sequence Length
1630 FixDocEntryFoundLength(Entry, (guint32)length16);
1635 // Either implicit VR or a non DICOM conformal (see note below) explicit
1636 // VR that ommited the VR of (at least) this element. Farts happen.
1637 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1638 // on Data elements "Implicit and Explicit VR Data Elements shall
1639 // not coexist in a Data Set and Data Sets nested within it".]
1640 // Length is on 4 bytes.
1642 FixDocEntryFoundLength(Entry, ReadInt32());
1648 * \brief Find the Value Representation of the current Dicom Element.
1651 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1653 if (filetype != gdcmExplicitVR)
1658 long PositionOnEntry = ftell(fp);
1659 // Warning: we believe this is explicit VR (Value Representation) because
1660 // we used a heuristic that found "UL" in the first tag. Alas this
1661 // doesn't guarantee that all the tags will be in explicit VR. In some
1662 // cases (see e-film filtered files) one finds implicit VR tags mixed
1663 // within an explicit VR file. Hence we make sure the present tag
1664 // is in explicit VR and try to fix things if it happens not to be
1667 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1669 if(!CheckDocEntryVR(Entry,VR))
1671 fseek(fp, PositionOnEntry, SEEK_SET);
1672 // When this element is known in the dictionary we shall use, e.g. for
1673 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1674 // dictionary entry. Still we have to flag the element as implicit since
1675 // we know now our assumption on expliciteness is not furfilled.
1677 if ( Entry->IsVRUnknown() )
1678 Entry->SetVR("Implicit");
1679 Entry->SetImplicitVR();
1684 * \brief Check the correspondance between the VR of the header entry
1685 * and the taken VR. If they are different, the header entry is
1686 * updated with the new VR.
1687 * @param Entry Header Entry to check
1688 * @param vr Dicom Value Representation
1689 * @return false if the VR is incorrect of if the VR isn't referenced
1690 * otherwise, it returns true
1692 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1694 char msg[100]; // for sprintf
1695 bool RealExplicit = true;
1697 // Assume we are reading a falsely explicit VR file i.e. we reached
1698 // a tag where we expect reading a VR but are in fact we read the
1699 // first to bytes of the length. Then we will interogate (through find)
1700 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1701 // both GCC and VC++ implementations of the STL map. Hence when the
1702 // expected VR read happens to be non-ascii characters we consider
1703 // we hit falsely explicit VR tag.
1705 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1706 RealExplicit = false;
1708 // CLEANME searching the dicom_vr at each occurence is expensive.
1709 // PostPone this test in an optional integrity check at the end
1710 // of parsing or only in debug mode.
1711 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1712 RealExplicit= false;
1714 if ( !RealExplicit )
1716 // We thought this was explicit VR, but we end up with an
1717 // implicit VR tag. Let's backtrack.
1718 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1719 Entry->GetGroup(),Entry->GetElement());
1720 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1721 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1722 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1723 Entry->GetGroup(),Entry->GetElement(),
1724 "UL","FIXME","Group Length");
1725 Entry->SetDictEntry(NewEntry);
1730 if ( Entry->IsVRUnknown() )
1732 // When not a dictionary entry, we can safely overwrite the VR.
1733 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1739 else if ( Entry->GetVR() != vr )
1741 // The VR present in the file and the dictionary disagree. We assume
1742 // the file writer knew best and use the VR of the file. Since it would
1743 // be unwise to overwrite the VR of a dictionary (since it would
1744 // compromise it's next user), we need to clone the actual DictEntry
1745 // and change the VR for the read one.
1746 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1747 Entry->GetGroup(),Entry->GetElement(),
1748 vr,"FIXME",Entry->GetName());
1749 Entry->SetDictEntry(NewEntry);
1755 * \brief Get the transformed value of the header entry. The VR value
1756 * is used to define the transformation to operate on the value
1757 * \warning NOT end user intended method !
1759 * @return Transformed entry value
1761 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1763 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1765 std::string val=((gdcmValEntry *)Entry)->GetValue();
1766 std::string vr=Entry->GetVR();
1767 guint32 length = Entry->GetLength();
1768 std::ostringstream s;
1771 // When short integer(s) are expected, read and convert the following
1772 // n * 2 bytes properly i.e. as a multivaluated strings
1773 // (each single value is separated fromthe next one by '\'
1774 // as usual for standard multivaluated filels
1775 // Elements with Value Multiplicity > 1
1776 // contain a set of short integers (not a single one)
1778 if (vr == "US" || vr == "SS")
1783 for (int i=0; i < nbInt; i++)
1787 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1788 NewInt16 = SwapShort(NewInt16);
1793 // When integer(s) are expected, read and convert the following
1794 // n * 4 bytes properly i.e. as a multivaluated strings
1795 // (each single value is separated fromthe next one by '\'
1796 // as usual for standard multivaluated filels
1797 // Elements with Value Multiplicity > 1
1798 // contain a set of integers (not a single one)
1799 else if (vr == "UL" || vr == "SL")
1804 for (int i=0; i < nbInt; i++)
1808 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1809 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1810 NewInt32=SwapLong(NewInt32);
1814 #ifdef GDCM_NO_ANSI_STRING_STREAM
1815 s << std::ends; // to avoid oddities on Solaris
1816 #endif //GDCM_NO_ANSI_STRING_STREAM
1820 return(((gdcmValEntry *)Entry)->GetValue());
1824 * \brief Get the reverse transformed value of the header entry. The VR
1825 * value is used to define the reverse transformation to operate on
1827 * \warning NOT end user intended method !
1829 * @return Reverse transformed entry value
1831 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1833 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1835 std::string vr=Entry->GetVR();
1836 std::ostringstream s;
1837 std::vector<std::string> tokens;
1839 if (vr == "US" || vr == "SS")
1843 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1844 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1845 for (unsigned int i=0; i<tokens.size();i++)
1847 NewInt16 = atoi(tokens[i].c_str());
1848 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1852 if (vr == "UL" || vr == "SL")
1856 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1857 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1858 for (unsigned int i=0; i<tokens.size();i++)
1860 NewInt32 = atoi(tokens[i].c_str());
1861 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1862 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1867 #ifdef GDCM_NO_ANSI_STRING_STREAM
1868 s << std::ends; // to avoid oddities on Solaris
1869 #endif //GDCM_NO_ANSI_STRING_STREAM
1873 return(((gdcmValEntry *)Entry)->GetValue());
1877 * \brief Skip a given Header Entry
1878 * \warning NOT end user intended method !
1881 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1883 SkipBytes(entry->GetLength());
1887 * \brief Skips to the begining of the next Header Entry
1888 * \warning NOT end user intended method !
1891 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1893 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1894 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1898 * \brief Loads the value for a a given VLEntry
1899 * \warning NOT end user intended method !
1902 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
1904 //SkipBytes(entry->GetLength());
1905 LoadDocEntry(entry);
1908 * \brief When the length of an element value is obviously wrong (because
1909 * the parser went Jabberwocky) one can hope improving things by
1910 * applying this heuristic.
1912 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry, guint32 FoundLength)
1914 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1915 if ( FoundLength == 0xffffffff) {
1919 guint16 gr =Entry->GetGroup();
1920 guint16 el =Entry->GetElement();
1922 if (FoundLength%2) {
1923 std::ostringstream s;
1924 s << "Warning : Tag with uneven length " << FoundLength
1925 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1926 dbg.Verbose(0,s.str().c_str());
1929 // Sorry for the patch!
1930 // XMedCom did the trick to read some naughty GE images ...
1931 if (FoundLength == 13) {
1932 // The following 'if' will be removed when there is no more
1933 // images on Creatis HDs with a 13 length for Manufacturer...
1934 if ( (Entry->GetGroup() != 0x0008) ||
1935 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1936 // end of remove area
1938 Entry->SetReadLength(10); // a bug is to be fixed
1942 // to fix some garbage 'Leonardo' Siemens images
1943 // May be commented out to avoid overhead
1944 else if ( (Entry->GetGroup() == 0x0009) &&
1945 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
1947 Entry->SetReadLength(4); // a bug is to be fixed
1951 // to try to 'go inside' SeQuences (with length), and not to skip them
1952 else if ( Entry->GetVR() == "SQ")
1954 if (enableSequences) // only if the user does want to !
1955 FoundLength =0; // ReadLength is unchanged
1958 // we found a 'delimiter' element
1959 // fffe|xxxx is just a marker, we don't take its length into account
1960 else if(Entry->GetGroup() == 0xfffe)
1962 // *normally, fffe|0000 doesn't exist !
1963 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
1964 // causes extra troubles :-(
1968 Entry->SetUsableLength(FoundLength);
1972 * \brief Apply some heuristics to predict whether the considered
1973 * element value contains/represents an integer or not.
1974 * @param Entry The element value on which to apply the predicate.
1975 * @return The result of the heuristical predicate.
1977 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1978 guint16 element = Entry->GetElement();
1979 guint16 group = Entry->GetGroup();
1980 std::string vr = Entry->GetVR();
1981 guint32 length = Entry->GetLength();
1982 // When we have some semantics on the element we just read, and if we
1983 // a priori know we are dealing with an integer, then we shall be
1984 // able to swap it's element value properly.
1985 if ( element == 0 ) // This is the group length of the group
1991 std::ostringstream s;
1992 int filePosition = ftell(fp);
1993 s << "Erroneous Group Length element length on : (" \
1994 << std::hex << group << " , " << element
1995 << ") -before- position x(" << filePosition << ")"
1996 << "lgt : " << length;
1997 // These 2 lines commented out : a *very dirty* patch
1998 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1999 // have a glance at offset x(8336) ...
2000 // For *regular* headers, the test is useless..
2001 // lets's print a warning message and go on,
2002 // instead of giving up with an error message
2004 //std::cout << s.str().c_str() << std::endl;
2005 // dbg.Error("gdcmDocument::IsDocEntryAnInteger",
2006 // s.str().c_str());
2009 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2015 * \brief Find the Length till the next sequence delimiter
2016 * \warning NOT end user intended method !
2020 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2021 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2024 long PositionOnEntry = ftell(fp);
2025 bool FoundSequenceDelimiter = false;
2026 guint32 TotalLength = 0;
2029 while ( ! FoundSequenceDelimiter)
2035 TotalLength += 4; // We even have to decount the group and element
2037 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2039 char msg[100]; // for sprintf. Sorry
2040 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2041 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2045 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2046 FoundSequenceDelimiter = true;
2047 else if ( n != 0xe000 )
2049 char msg[100]; // for sprintf. Sorry
2050 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2052 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2056 ItemLength = ReadInt32();
2057 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2058 // the ItemLength with ReadInt32
2059 SkipBytes(ItemLength);
2061 fseek(fp, PositionOnEntry, SEEK_SET);
2066 * \brief Reads a supposed to be 16 Bits integer
2067 * (swaps it depending on processor endianity)
2068 * @return read value
2070 guint16 gdcmDocument::ReadInt16(void) {
2073 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2074 if ( item_read != 1 ) {
2076 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2086 * \brief Reads a supposed to be 32 Bits integer
2087 * (swaps it depending on processor endianity)
2088 * @return read value
2090 guint32 gdcmDocument::ReadInt32(void) {
2093 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2094 if ( item_read != 1 ) {
2096 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2106 * \brief skips bytes inside the source file
2107 * \warning NOT end user intended method !
2110 void gdcmDocument::SkipBytes(guint32 NBytes) {
2111 //FIXME don't dump the returned value
2112 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2116 * \brief Loads all the needed Dictionaries
2117 * \warning NOT end user intended method !
2119 void gdcmDocument::Initialise(void)
2121 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2122 RefShaDict = (gdcmDict*)0;
2126 * \brief Discover what the swap code is (among little endian, big endian,
2127 * bad little endian, bad big endian).
2129 * @return false when we are absolutely sure
2130 * it's neither ACR-NEMA nor DICOM
2131 * true when we hope ours assuptions are OK
2133 bool gdcmDocument::CheckSwap() {
2135 // The only guaranted way of finding the swap code is to find a
2136 // group tag since we know it's length has to be of four bytes i.e.
2137 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2138 // occurs when we can't find such group...
2140 guint32 x=4; // x : for ntohs
2141 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2147 char deb[HEADER_LENGTH_TO_READ];
2149 // First, compare HostByteOrder and NetworkByteOrder in order to
2150 // determine if we shall need to swap bytes (i.e. the Endian type).
2156 // The easiest case is the one of a DICOM header, since it possesses a
2157 // file preamble where it suffice to look for the string "DICM".
2158 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2161 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2162 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2164 // Next, determine the value representation (VR). Let's skip to the
2165 // first element (0002, 0000) and check there if we find "UL"
2166 // - or "OB" if the 1st one is (0002,0001) -,
2167 // in which case we (almost) know it is explicit VR.
2168 // WARNING: if it happens to be implicit VR then what we will read
2169 // is the length of the group. If this ascii representation of this
2170 // length happens to be "UL" then we shall believe it is explicit VR.
2171 // FIXME: in order to fix the above warning, we could read the next
2172 // element value (or a couple of elements values) in order to make
2173 // sure we are not commiting a big mistake.
2174 // We need to skip :
2175 // * the 128 bytes of File Preamble (often padded with zeroes),
2176 // * the 4 bytes of "DICM" string,
2177 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2178 // i.e. a total of 136 bytes.
2182 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2183 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2184 // *Implicit* VR. -and it is !-
2186 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2187 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2188 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2189 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2190 // when Write DCM *adds*
2192 // Use gdcmDocument::dicom_vr to test all the possibilities
2193 // instead of just checking for UL, OB and UI !? group 0000
2195 filetype = gdcmExplicitVR;
2196 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2197 "explicit Value Representation");
2201 filetype = gdcmImplicitVR;
2202 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2203 "not an explicit Value Representation");
2209 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2210 "HostByteOrder != NetworkByteOrder");
2215 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2216 "HostByteOrder = NetworkByteOrder");
2219 // Position the file position indicator at first tag (i.e.
2220 // after the file preamble and the "DICM" string).
2222 fseek (fp, 132L, SEEK_SET);
2226 // Alas, this is not a DicomV3 file and whatever happens there is no file
2227 // preamble. We can reset the file position indicator to where the data
2228 // is (i.e. the beginning of the file).
2229 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2232 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2233 // By clean we mean that the length of the first tag is written down.
2234 // If this is the case and since the length of the first group HAS to be
2235 // four (bytes), then determining the proper swap code is straightforward.
2238 // We assume the array of char we are considering contains the binary
2239 // representation of a 32 bits integer. Hence the following dirty
2241 s32 = *((guint32 *)(entCur));
2262 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2263 // It is time for despaired wild guesses.
2264 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2265 // i.e. the 'group length' element is not present :
2267 // check the supposed to be 'group number'
2268 // 0x0002 or 0x0004 or 0x0008
2269 // to determine ' sw' value .
2270 // Only 0 or 4321 will be possible
2271 // (no oportunity to check for the formerly well known
2272 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2273 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2274 // the file IS NOT ACR-NEMA nor DICOM V3
2275 // Find a trick to tell it the caller...
2277 s16 = *((guint16 *)(deb));
2293 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2294 "ACR/NEMA unfound swap info (Really hopeless !)");
2295 filetype = gdcmUnknown;
2299 // Then the only info we have is the net2host one.
2309 * \brief Restore the unproperly loaded values i.e. the group, the element
2310 * and the dictionary entry depending on them.
2312 void gdcmDocument::SwitchSwapToBigEndian(void)
2314 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2315 "Switching to BigEndian mode.");
2336 * \brief during parsing, Header Elements too long are not loaded in memory
2339 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2343 if ((guint32)NewSize >= (guint32)0xffffffff)
2345 MaxSizeLoadEntry = 0xffffffff;
2348 MaxSizeLoadEntry = NewSize;
2353 * \brief Header Elements too long will not be printed
2354 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2357 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2361 if ((guint32)NewSize >= (guint32)0xffffffff)
2363 MaxSizePrintEntry = 0xffffffff;
2366 MaxSizePrintEntry = NewSize;
2372 * \brief Read the next tag but WITHOUT loading it's value
2373 * (read the 'Group Number', the 'Element Number',
2374 * gets the Dict Entry
2375 * gets the VR, gets the length, gets the offset value)
2376 * @return On succes the newly created DocEntry, NULL on failure.
2378 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2380 gdcmDocEntry *NewEntry;
2385 // We reached the EOF (or an error occured) therefore
2386 // header parsing has to be considered as finished.
2387 return (gdcmDocEntry *)0;
2389 // Pb : how to propagate the element length (used in SkipDocEntry)
2390 // direct call to SkipBytes ?
2392 // if (ignoreShadow == 1 && g%2 ==1)
2393 // if user wants to skip shadow groups
2394 // and current element *is* a shadow element
2395 // we don't create anything
2396 // return (gdcmDocEntry *)1; // to tell caller it's NOT finished
2398 NewEntry = NewDocEntryByNumber(g, n);
2399 FindDocEntryVR(NewEntry);
2400 FindDocEntryLength(NewEntry);
2407 NewEntry->SetOffset(ftell(fp));
2412 * \brief Build a new Element Value from all the low level arguments.
2413 * Check for existence of dictionary entry, and build
2414 * a default one when absent.
2415 * @param Name Name of the underlying DictEntry
2417 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2419 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2421 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2423 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2426 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2427 "failed to allocate gdcmDocEntry");
2428 return (gdcmDocEntry *)0;
2434 * \brief Request a new virtual dict entry to the dict set
2435 * @param group group number of the underlying DictEntry
2436 * @param element element number of the underlying DictEntry
2437 * @param vr VR of the underlying DictEntry
2438 * @param fourth owner group
2439 * @param name english name
2441 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2446 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2450 * \brief Build a new Element Value from all the low level arguments.
2451 * Check for existence of dictionary entry, and build
2452 * a default one when absent.
2453 * @param Group group number of the underlying DictEntry
2454 * @param Elem element number of the underlying DictEntry
2456 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2458 // Find out if the tag we encountered is in the dictionaries:
2459 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2461 DictEntry = NewVirtualDictEntry(Group, Elem);
2463 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2466 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2467 "failed to allocate gdcmDocEntry");
2474 * \brief Generate a free TagKey i.e. a TagKey that is not present
2475 * in the TagHt dictionary.
2476 * @param group The generated tag must belong to this group.
2477 * @return The element of tag with given group which is fee.
2479 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2481 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2483 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2484 if (tagHT.count(key) == 0)
2492 * \brief Searches both the public and the shadow dictionary (when they
2493 * exist) for the presence of the DictEntry with given name.
2494 * The public dictionary has precedence on the shadow one.
2495 * @param Name name of the searched DictEntry
2496 * @return Corresponding DictEntry when it exists, NULL otherwise.
2498 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2500 gdcmDictEntry *found = (gdcmDictEntry *)0;
2501 if (!RefPubDict && !RefShaDict)
2503 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2504 "we SHOULD have a default dictionary");
2508 found = RefPubDict->GetDictEntryByName(Name);
2514 found = RefShaDict->GetDictEntryByName(Name);
2522 * \brief Searches both the public and the shadow dictionary (when they
2523 * exist) for the presence of the DictEntry with given
2524 * group and element. The public dictionary has precedence on the
2526 * @param group group of the searched DictEntry
2527 * @param element element of the searched DictEntry
2528 * @return Corresponding DictEntry when it exists, NULL otherwise.
2530 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2532 gdcmDictEntry *found = (gdcmDictEntry *)0;
2533 if (!RefPubDict && !RefShaDict)
2535 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2536 "we SHOULD have a default dictionary");
2540 found = RefPubDict->GetDictEntryByNumber(group, element);
2546 found = RefShaDict->GetDictEntryByNumber(group, element);
2555 * \ingroup gdcmDocument
2556 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2557 * \ No other way so 'skip' the Data
2560 void gdcmDocument::Parse7FE0 (void) {
2562 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2566 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
2567 if (Transfer == UI1_2_840_10008_1_2 )
2569 if ( Transfer == UI1_2_840_10008_1_2_1 )
2571 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
2573 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
2577 std::string str_nb=GetEntryByNumber(0x0028,0x0100);
2578 if (str_nb == GDCM_UNFOUND ) {
2581 nb = atoi(str_nb.c_str() );
2582 if (nb == 12) nb =16;
2585 guint16 ItemTagGr,ItemTagEl;
2589 // -------------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2591 if ( Transfer != UI1_1_2_840_10008_1_2_5 ) { // !RLELossLessTransferSyntax
2594 fread(&ItemTagGr,2,1,fp); //Reading (fffe):Basic Offset Table Item Tag Gr
2595 fread(&ItemTagEl,2,1,fp); //Reading (e000):Basic Offset Table Item Tag El
2597 ItemTagGr=SwapShort(ItemTagGr);
2598 ItemTagEl=SwapShort(ItemTagEl);
2600 printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
2601 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2605 ln=SwapLong(ln); // Basic Offset Table Item Length
2606 printf("at %x : Basic Offset Table Item Length (\?\?) %d x(%08x)\n",
2607 (unsigned)ftellRes,ln,ln);
2609 // What is it used for ??
2610 char * BasicOffsetTableItemValue= new char[ln+1];
2611 fread(BasicOffsetTableItemValue,ln,1,fp);
2613 for (int i=0;i<ln;i+=4){
2614 a=str2num(&BasicOffsetTableItemValue[i],guint32);
2615 printf(" x(%08x) %d\n",a,a);
2620 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2621 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2623 ItemTagGr=SwapShort(ItemTagGr);
2624 ItemTagEl=SwapShort(ItemTagEl);
2626 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2627 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2629 while ( ( ItemTagGr==0xfffe) && (ItemTagEl!=0xe0dd) ) { // Parse fragments
2634 ln=SwapLong(ln); // length
2635 printf(" at %x : fragment length %d x(%08x)\n",
2636 (unsigned)ftellRes, ln,ln);
2638 // ------------------------
2639 fseek(fp,ln,SEEK_CUR); // skipping (not reading) fragment pixels
2640 // ------------------------
2643 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2644 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2646 ItemTagGr=SwapShort(ItemTagGr);
2647 ItemTagEl=SwapShort(ItemTagEl);
2649 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2650 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2656 long RleSegmentLength[15],fragmentLength;
2657 guint32 nbRleSegments;
2658 guint32 RleSegmentOffsetTable[15];
2660 // Basic Offset Table with Item Value
2662 fread(&ItemTagGr,2,1,fp); //Reading (fffe):Basic Offset Table Item Tag Gr
2663 fread(&ItemTagEl,2,1,fp); //Reading (e000):Basic Offset Table Item Tag El
2665 ItemTagGr=SwapShort(ItemTagGr);
2666 ItemTagEl=SwapShort(ItemTagEl);
2668 printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
2669 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2674 ln=SwapLong(ln); // Basic Offset Table Item Length
2675 printf("at %x : Basic Offset Table Item Length (\?\?) %d x(%08x)\n",
2676 (unsigned)ftellRes,ln,ln);
2678 // What is it used for ??
2679 char * BasicOffsetTableItemValue= new char[ln+1];
2680 fread(BasicOffsetTableItemValue,ln,1,fp);
2682 for (int i=0;i<ln;i+=4){
2683 a=str2num(&BasicOffsetTableItemValue[i],guint32);
2684 printf(" x(%08x) %d\n",a,a);
2689 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2690 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2692 ItemTagGr=SwapShort(ItemTagGr);
2693 ItemTagEl=SwapShort(ItemTagEl);
2695 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2696 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2698 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2699 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
2700 // Parse fragments of the current Fragment (Frame)
2702 fread(&fragmentLength,4,1,fp);
2704 fragmentLength=SwapLong(fragmentLength); // length
2705 printf(" at %x : 'fragment' length %d x(%08x)\n",
2706 (unsigned)ftellRes, (unsigned)fragmentLength,(unsigned)fragmentLength);
2708 //------------------ scanning (not reading) fragment pixels
2710 fread(&nbRleSegments,4,1,fp); // Reading : Number of RLE Segments
2712 nbRleSegments=SwapLong(nbRleSegments);
2713 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2715 for(int k=1; k<=15; k++) { // Reading RLE Segments Offset Table
2717 fread(&RleSegmentOffsetTable[k],4,1,fp);
2719 RleSegmentOffsetTable[k]=SwapLong(RleSegmentOffsetTable[k]);
2720 printf(" at : %x Offset Segment %d : %d (%x)\n",
2721 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2722 RleSegmentOffsetTable[k]);
2725 if (nbRleSegments>1) { // skipping (not reading) RLE Segments
2726 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2727 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2728 - RleSegmentOffsetTable[k];
2730 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2731 k,(unsigned)RleSegmentLength[k],(unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2732 fseek(fp,RleSegmentLength[k],SEEK_CUR);
2735 RleSegmentLength[nbRleSegments]= fragmentLength
2736 - RleSegmentOffsetTable[nbRleSegments];
2738 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2739 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2740 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2742 fseek(fp,RleSegmentLength[nbRleSegments],SEEK_CUR);
2744 // ------------------ end of scanning fragment pixels
2747 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2748 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2750 ItemTagGr=SwapShort(ItemTagGr);
2751 ItemTagEl=SwapShort(ItemTagEl);
2753 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2754 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2761 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2762 * \warning Does NOT work with ACR-NEMA files
2763 * \todo Find a trick to solve the pb (use RET fields ?)
2765 * @return true if 'smaller'
2767 bool gdcmDocument::operator<(gdcmDocument &document){
2771 s1=this->GetEntryByNumber(0x0010,0x0010);
2772 s2=document.GetEntryByNumber(0x0010,0x0010);
2780 s1=this->GetEntryByNumber(0x0010,0x0020);
2781 s2=document.GetEntryByNumber(0x0010,0x0020);
2788 // Study Instance UID
2789 s1=this->GetEntryByNumber(0x0020,0x000d);
2790 s2=document.GetEntryByNumber(0x0020,0x000d);
2797 // Serie Instance UID
2798 s1=this->GetEntryByNumber(0x0020,0x000e);
2799 s2=document.GetEntryByNumber(0x0020,0x000e);
2811 //-----------------------------------------------------------------------------