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 (string) 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
574 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
580 a = GetDocEntryByNumber( Group, Elem);
582 a =NewDocEntryByNumber(Group, Elem);
585 b = new gdcmValEntry(a);
588 SetEntryByNumber(Value, Group, Elem);
590 return (gdcmValEntry*)b;
595 * \brief Modifies the value of a given Header Entry (Dicom Element)
596 * when it exists. Create it with the given value when unexistant.
597 * @param voidArea (binary) value to be set
598 * @param Group Group number of the Entry
599 * @param Elem Element number of the Entry
600 * \return pointer to the modified/created Header Entry (NULL when creation
605 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
612 a = GetDocEntryByNumber( Group, Elem);
614 a =NewBinEntryByNumber(Group, Elem);
617 b = new gdcmBinEntry(a);
620 SetEntryByNumber(voidArea, lgth, Group, Elem);
621 b->SetVoidArea(voidArea);
622 return (gdcmBinEntry*)b;
628 * \brief Set a new value if the invoked element exists
629 * Seems to be useless !!!
630 * @param Value new element value
631 * @param Group group number of the Entry
632 * @param Elem element number of the Entry
635 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
637 std::string v = Value;
638 SetEntryByNumber(v, Group, Elem);
642 //-----------------------------------------------------------------------------
646 * \brief Checks if a given Dicom Element exists within the H table
647 * @param group Group number of the searched Dicom Element
648 * @param element Element number of the searched Dicom Element
649 * @return number of occurences
651 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
652 std::string key = gdcmDictEntry::TranslateToKey(group, element );
653 return (tagHT.count(key));
657 * \brief Searches within Header Entries (Dicom Elements) parsed with
658 * the public and private dictionaries
659 * for the element value of a given tag.
660 * \warning Don't use any longer : use GetPubEntryByName
661 * @param tagName name of the searched element.
662 * @return Corresponding element value when it exists,
663 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
665 std::string gdcmDocument::GetEntryByName(std::string tagName) {
666 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
667 if( dictEntry == NULL)
670 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
674 * \brief Searches within Header Entries (Dicom Elements) parsed with
675 * the public and private dictionaries
676 * for the element value representation of a given tag.
678 * Obtaining the VR (Value Representation) might be needed by caller
679 * to convert the string typed content to caller's native type
680 * (think of C++ vs Python). The VR is actually of a higher level
681 * of semantics than just the native C++ type.
682 * @param tagName name of the searched element.
683 * @return Corresponding element value representation when it exists,
684 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
686 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
687 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
688 if( dictEntry == NULL)
691 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
692 dictEntry->GetElement());
693 return elem->GetVR();
698 * \brief Searches within Header Entries (Dicom Elements) parsed with
699 * the public and private dictionaries
700 * for the element value representation of a given tag.
701 * @param group Group number of the searched tag.
702 * @param element Element number of the searched tag.
703 * @return Corresponding element value representation when it exists,
704 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
706 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
707 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
708 if ( ! tagHT.count(key))
710 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
714 * \brief Searches within Header Entries (Dicom Elements) parsed with
715 * the public and private dictionaries
716 * for the element value representation of a given tag..
718 * Obtaining the VR (Value Representation) might be needed by caller
719 * to convert the string typed content to caller's native type
720 * (think of C++ vs Python). The VR is actually of a higher level
721 * of semantics than just the native C++ type.
722 * @param group Group number of the searched tag.
723 * @param element Element number of the searched tag.
724 * @return Corresponding element value representation when it exists,
725 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
727 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
728 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
731 return elem->GetVR();
735 * \brief Searches within Header Entries (Dicom Elements) parsed with
736 * the public and private dictionaries
737 * for the value length of a given tag..
738 * @param group Group number of the searched tag.
739 * @param element Element number of the searched tag.
740 * @return Corresponding element length; -2 if not found
742 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
743 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
746 return elem->GetLength();
749 * \brief Sets the value (string) of the Header Entry (Dicom Element)
750 * @param content string value of the Dicom Element
751 * @param tagName name of the searched Dicom Element.
752 * @return true when found
754 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
755 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
756 if( dictEntry == NULL)
759 return(SetEntryByNumber(content,dictEntry->GetGroup(),
760 dictEntry->GetElement()));
764 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
765 * through it's (group, element) and modifies it's content with
767 * @param content new value (string) to substitute with
768 * @param group group number of the Dicom Element to modify
769 * @param element element number of the Dicom Element to modify
771 bool gdcmDocument::SetEntryByNumber(std::string content,
775 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
776 if ( ! tagHT.count(key))
778 int l = content.length();
779 if(l%2) // Non even length are padded with a space (020H).
782 content = content + '\0';
786 a = (gdcmValEntry *)tagHT[key];
788 a->SetValue(content);
790 VRKey vr = a->GetVR();
793 if( (vr == "US") || (vr == "SS") )
795 else if( (vr == "UL") || (vr == "SL") )
805 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
806 * through it's (group, element) and modifies it's content with
808 * @param content new value (void *) to substitute with
809 * @param group group number of the Dicom Element to modify
810 * @param element element number of the Dicom Element to modify
812 bool gdcmDocument::SetEntryByNumber(void *content,
817 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
818 if ( ! tagHT.count(key))
821 /* Hope Binray field length is never wrong
822 if(lgth%2) // Non even length are padded with a space (020H).
825 //content = content + '\0'; // fing a trick to enlarge a binary field?
829 a = (gdcmBinEntry *)tagHT[key];
830 a->SetVoidArea(content);
831 //a->SetLength(lgth); // ???
836 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
837 * in the PubDocEntrySet of this instance
838 * through it's (group, element) and modifies it's length with
840 * \warning Use with extreme caution.
841 * @param l new length to substitute with
842 * @param group group number of the Entry to modify
843 * @param element element number of the Entry to modify
844 * @return true on success, false otherwise.
846 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
850 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
851 if ( ! tagHT.count(key))
853 if (l%2) l++; // length must be even
854 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
860 * \brief Gets (from Header) the offset of a 'non string' element value
861 * (LoadElementValues has already be executed)
862 * @param Group group number of the Entry
863 * @param Elem element number of the Entry
864 * @return File Offset of the Element Value
866 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
868 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
871 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
872 "failed to Locate gdcmDocEntry");
875 return Entry->GetOffset();
879 * \brief Gets (from Header) a 'non string' element value
880 * (LoadElementValues has already be executed)
881 * @param Group group number of the Entry
882 * @param Elem element number of the Entry
883 * @return Pointer to the 'non string' area
885 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
887 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
890 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
891 "failed to Locate gdcmDocEntry");
894 return ((gdcmBinEntry *)Entry)->GetVoidArea();
898 * \brief Loads (from disk) the element content
899 * when a string is not suitable
900 * @param Group group number of the Entry
901 * @param Elem element number of the Entry
903 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
905 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
908 size_t o =(size_t)Element->GetOffset();
909 fseek(fp, o, SEEK_SET);
910 size_t l=Element->GetLength();
911 char* a = new char[l];
915 SetEntryVoidAreaByNumber(a, Group, Elem);
916 /// \todo check the result
917 size_t l2 = fread(a, 1, l ,fp);
928 * \brief Sets a 'non string' value to a given Dicom Element
930 * @param group Group number of the searched Dicom Element
931 * @param element Element number of the searched Dicom Element
934 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
938 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
939 if ( ! tagHT.count(key))
941 // This was for multimap ?
942 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
948 * \brief Update the entries with the shadow dictionary.
949 * Only non even entries are analyzed
951 void gdcmDocument::UpdateShaEntries(void) {
952 gdcmDictEntry *entry;
955 // TODO : if still any use (?) explore recursively the whole structure
957 for(ListTag::iterator it=listEntries.begin();
958 it!=listEntries.end();
961 // Odd group => from public dictionary
962 if((*it)->GetGroup()%2==0)
965 // Peer group => search the corresponding dict entry
967 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
971 if((*it)->IsImplicitVR())
976 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
978 // Set the new entry and the new value
979 (*it)->SetDictEntry(entry);
980 CheckDocEntryVR(*it,vr);
982 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
987 // Remove precedent value transformation
988 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
995 * \brief Searches within the Header Entries for a Dicom Element of
997 * @param tagName name of the searched Dicom Element.
998 * @return Corresponding Dicom Element when it exists, and NULL
1001 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1002 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1003 if( dictEntry == NULL)
1006 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1010 * \brief retrieves a Dicom Element (the first one) using (group, element)
1011 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1012 * if you think it's NOT UNIQUE, check the count number
1013 * and use iterators to retrieve ALL the Dicoms Elements within
1014 * a given couple (group, element)
1015 * @param group Group number of the searched Dicom Element
1016 * @param element Element number of the searched Dicom Element
1019 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1021 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1022 if ( ! tagHT.count(key))
1024 return tagHT.find(key)->second;
1028 * \brief Loads the element while preserving the current
1029 * underlying file position indicator as opposed to
1030 * to LoadDocEntry that modifies it.
1031 * @param entry Header Entry whose value shall be loaded.
1034 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1035 long PositionOnEntry = ftell(fp);
1036 LoadDocEntry(entry);
1037 fseek(fp, PositionOnEntry, SEEK_SET);
1042 * \brief Writes in a file (according to the requested format)
1043 * the group, the element, the value representation and the length
1044 * of a single gdcmDocEntry passed as argument.
1045 * @param tag pointer on the gdcmDocEntry to be written
1046 * @param _fp already open file pointer
1047 * @param type type of the File to be written
1049 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
1053 guint16 group = tag->GetGroup();
1054 VRKey vr = tag->GetVR();
1055 guint16 el = tag->GetElement();
1056 guint32 lgr = tag->GetReadLength();
1058 if ( (group == 0xfffe) && (el == 0x0000) )
1059 // Fix in order to make some MR PHILIPS images e-film readable
1060 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1061 // we just *always* ignore spurious fffe|0000 tag !
1064 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1065 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1067 if ( type == gdcmExplicitVR ) {
1069 // Special case of delimiters:
1070 if (group == 0xfffe) {
1071 // Delimiters have NO Value Representation and have NO length.
1072 // Hence we skip writing the VR and length and we pad by writing
1076 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1081 guint16 shortLgr = lgr;
1082 if (vr == "unkn") { // Unknown was 'written'
1083 // deal with Little Endian
1084 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1085 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1087 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1088 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1090 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1091 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1093 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1099 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1104 * \brief Writes in a file (according to the requested format)
1105 * the value of a single gdcmDocEntry passed as argument.
1106 * @param tag Pointer on the gdcmDocEntry to be written
1107 * @param _fp Already open file pointer
1108 * @param type type of the File to be written
1111 // TODO : to be re -written recursively !
1113 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1116 guint16 group = tag->GetGroup();
1117 VRKey vr = tag->GetVR();
1118 guint32 lgr = tag->GetReadLength();
1121 // SeQuences have no value:
1123 if (group == 0xfffe)
1124 // Delimiters have no associated value:
1127 //--------------------------------
1129 // FIXME :right now, both value and voidArea belong to gdcmValue
1131 // -------------------------------
1133 // if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) ) {
1135 gdcmBinEntry *BinEntry= (gdcmBinEntry *)tag;;
1136 voidArea = BinEntry->GetVoidArea();
1137 if (voidArea != NULL)
1138 { // there is a 'non string' LUT, overlay, etc
1139 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1144 if (vr == "US" || vr == "SS")
1146 // some 'Short integer' fields may be mulivaluated
1147 // each single value is separated from the next one by '\'
1148 // we split the string and write each value as a short int
1149 std::vector<std::string> tokens;
1150 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1151 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1152 for (unsigned int i=0; i<tokens.size();i++)
1154 guint16 val_uint16 = atoi(tokens[i].c_str());
1155 void *ptr = &val_uint16;
1156 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1161 // some 'Integer' fields may be mulivaluated
1162 // each single value is separated from the next one by '\'
1163 // we split the string and write each value as an int
1164 if (vr == "UL" || vr == "SL")
1166 std::vector<std::string> tokens;
1167 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1168 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1169 for (unsigned int i=0; i<tokens.size();i++)
1171 guint32 val_uint32 = atoi(tokens[i].c_str());
1172 void *ptr = &val_uint32;
1173 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1178 fwrite (((gdcmValEntry *)tag)->GetValue().c_str(), (size_t)lgr ,(size_t)1, _fp); // Elem value
1182 * \brief Writes in a file (according to the requested format)
1183 * a single gdcmDocEntry passed as argument.
1184 * \sa WriteEntryValue, WriteEntryTagVRLength.
1185 * @param tag Pointer on the gdcmDocEntry to be written
1186 * @param _fp Already open file pointer
1187 * @param type type of the File to be written
1190 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1192 guint32 length = tag->GetLength();
1194 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(tag) ) {
1195 // The value of a tag MUST (see the DICOM norm) be an odd number of
1196 // bytes. When this is not the case, pad with an additional byte:
1198 ValEntry->SetValue(ValEntry->GetValue()+"\0");
1199 ValEntry->SetLength(ValEntry->GetReadLength()+1);
1201 WriteEntryTagVRLength(ValEntry, _fp, type);
1202 WriteEntryValue(ValEntry, _fp, type);
1206 if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) ) {
1208 // FIXME : when voidArea belong to gdcmBinEntry only, fix voidArea length
1210 // The value of a tag MUST (see the DICOM norm) be an odd number of
1211 // bytes. When this is not the case, pad with an additional byte:
1214 tag->SetValue(tag->GetValue()+"\0");
1215 tag->SetLength(tag->GetReadLength()+1);
1218 WriteEntryTagVRLength(tag, _fp, type);
1219 WriteEntryValue(tag, _fp, type);
1225 * \brief writes on disc according to the requested format
1226 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1227 * using the Chained List
1228 * \warning does NOT add the missing elements in the header :
1229 * it's up to the user doing it !
1230 * (function CheckHeaderCoherence to be written)
1231 * \warning DON'T try, right now, to write a DICOM image
1232 * from an ACR Header (meta elements will be missing!)
1233 * @param type type of the File to be written
1234 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1235 * @param _fp already open file pointer
1238 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1241 // FIXME : explore recursively the whole structure...
1243 /// \todo (?) check write failures (after *each* fwrite)
1245 std::cout << "--------------------- gdcmDocument::WriteEntries " << std::endl;
1246 for (TagDocEntryHT::iterator tag2=tagHT.begin();
1247 tag2 != tagHT.end();
1251 (*tag2).second->Print();
1253 if ( type == gdcmACR ){
1254 if ((*tag2).second->GetGroup() < 0x0008)
1255 // Ignore pure DICOM V3 groups
1257 if ((*tag2).second->GetGroup() %2)
1258 // Ignore the "shadow" groups
1260 if ((*tag2).second->GetVR() == "SQ" ) // ignore Sequences
1263 if (! WriteEntry((*tag2).second,_fp,type) ) {
1264 std::cout << "Write Failure " << std::endl;
1275 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1277 * @return The properly swaped 32 bits integer.
1279 guint32 gdcmDocument::SwapLong(guint32 a) {
1284 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1285 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1289 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1293 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1296 std::cout << "swapCode= " << sw << std::endl;
1297 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1304 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1306 * @return The properly unswaped 32 bits integer.
1308 guint32 gdcmDocument::UnswapLong(guint32 a) {
1309 return (SwapLong(a));
1313 * \brief Swaps the bytes so they agree with the processor order
1314 * @return The properly swaped 16 bits integer.
1316 guint16 gdcmDocument::SwapShort(guint16 a) {
1317 if ( (sw==4321) || (sw==2143) )
1318 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1323 * \brief Unswaps the bytes so they agree with the processor order
1324 * @return The properly unswaped 16 bits integer.
1326 guint16 gdcmDocument::UnswapShort(guint16 a) {
1327 return (SwapShort(a));
1330 //-----------------------------------------------------------------------------
1334 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1335 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1338 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1340 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1348 depth = set->GetDepthLevel();
1351 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1354 NewDocEntry = ReadNextDocEntry( );
1358 vr = NewDocEntry->GetVR();
1361 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1364 vl= new gdcmValEntry(NewDocEntry->GetDictEntry());
1365 vl->Copy(NewDocEntry);
1366 vl->SetDepthLevel(depth);
1369 if (/*!delim_mode && */vl->isItemDelimitor())
1371 if ( !delim_mode && ftell(fp)-offset >= l_max)
1378 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1380 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1381 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1382 "nor BinEntry. Probably unknown VR.");
1385 ////// BinEntry or UNKOWN VR:
1386 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1387 bn->Copy(NewDocEntry);
1392 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1393 NewDocEntry->GetElement() == 0x0010 )
1395 if (NewDocEntry->GetLength()==0xffffffff)
1396 // Broken US.3405.1.dcm
1397 Parse7FE0(); // to skip the pixels
1398 // (multipart JPEG/RLE are trouble makers)
1402 // to be sure we are at the beginning
1403 SkipToNextDocEntry(NewDocEntry);
1404 l = NewDocEntry->GetFullLength();
1406 } else { // VR = "SQ"
1408 l=NewDocEntry->GetReadLength();
1409 if (l != 0) // don't mess the delim_mode for zero-length sequence
1410 if (l == 0xffffffff)
1414 // no other way to create it ...
1415 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1416 set->GetDepthLevel());
1417 sq->Copy(NewDocEntry);
1418 sq->SetDelimitorMode(delim_mode);
1419 sq->SetDepthLevel(depth);
1422 { // Don't try to parse zero-length sequences
1423 long lgt = ParseSQ( sq,
1424 NewDocEntry->GetOffset(),
1427 // FIXME : on en fait quoi, de lgt ?
1429 if ( !delim_mode && ftell(fp)-offset >= l_max)
1440 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1441 * @return parsed length for this level
1443 long gdcmDocument::ParseSQ(gdcmSeqEntry *set, long offset, long l_max, bool delim_mode) {
1444 int SQItemNumber = 0;
1446 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1450 int depth = set->GetDepthLevel();
1453 NewDocEntry = ReadNextDocEntry();
1455 if (NewDocEntry->isSequenceDelimitor()) {
1456 //add the Sequence Delimitor // TODO : find the trick to put it properly !
1457 set->SetSequenceDelimitationItem(NewDocEntry);
1461 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1464 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1465 itemSQ->AddEntry(NewDocEntry); // no value, no voidArea. Think of it while printing !
1466 l= NewDocEntry->GetReadLength();
1473 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1475 set->AddEntry(itemSQ,SQItemNumber);
1477 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1481 lgth = ftell(fp) - offset;
1486 * \brief Loads the element content if its length doesn't exceed
1487 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1488 * @param Entry Header Entry (Dicom Element) to be dealt with
1490 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry) {
1492 guint16 group = Entry->GetGroup();
1493 std::string vr= Entry->GetVR();
1494 guint32 length = Entry->GetLength();
1496 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1498 // A SeQuence "contains" a set of Elements.
1499 // (fffe e000) tells us an Element is beginning
1500 // (fffe e00d) tells us an Element just ended
1501 // (fffe e0dd) tells us the current SeQuence just ended
1502 if( group == 0xfffe ) {
1503 // NO more value field for SQ !
1504 //Entry->SetValue("gdcm::Skipped");
1505 // appel recursif de Load Value
1506 // (meme pb que pour le parsing)
1510 // When the length is zero things are easy:
1511 if ( length == 0 ) {
1512 ((gdcmValEntry *)Entry)->SetValue("");
1516 // The elements whose length is bigger than the specified upper bound
1517 // are not loaded. Instead we leave a short notice of the offset of
1518 // the element content and it's length.
1519 if (length > MaxSizeLoadEntry) {
1520 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1522 std::ostringstream s;
1523 s << "gdcm::NotLoaded.";
1524 s << " Address:" << (long)Entry->GetOffset();
1525 s << " Length:" << Entry->GetLength();
1526 s << " x(" << std::hex << Entry->GetLength() << ")";
1527 ValEntryPtr->SetValue(s.str());
1529 // to be sure we are at the end of the value ...
1530 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1535 // Any compacter code suggested (?)
1536 if ( IsDocEntryAnInteger(Entry) ) {
1538 std::ostringstream s;
1540 // When short integer(s) are expected, read and convert the following
1541 // n *two characters properly i.e. as short integers as opposed to strings.
1542 // Elements with Value Multiplicity > 1
1543 // contain a set of integers (not a single one)
1544 if (vr == "US" || vr == "SS") {
1546 NewInt = ReadInt16();
1549 for (int i=1; i < nbInt; i++) {
1551 NewInt = ReadInt16();
1556 // When integer(s) are expected, read and convert the following
1557 // n * four characters properly i.e. as integers as opposed to strings.
1558 // Elements with Value Multiplicity > 1
1559 // contain a set of integers (not a single one)
1560 else if (vr == "UL" || vr == "SL") {
1562 NewInt = ReadInt32();
1565 for (int i=1; i < nbInt; i++) {
1567 NewInt = ReadInt32();
1572 #ifdef GDCM_NO_ANSI_STRING_STREAM
1573 s << std::ends; // to avoid oddities on Solaris
1574 #endif //GDCM_NO_ANSI_STRING_STREAM
1576 ((gdcmValEntry *)Entry)->SetValue(s.str());
1580 // We need an additional byte for storing \0 that is not on disk
1581 std::string NewValue(length,0);
1582 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1583 if ( item_read != 1 ) {
1584 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1585 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1589 if( (vr == "UI") ) // Because of correspondance with the VR dic
1590 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1592 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1597 * \brief Find the value Length of the passed Header Entry
1598 * @param Entry Header Entry whose length of the value shall be loaded.
1600 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1601 guint16 element = Entry->GetElement();
1602 //guint16 group = Entry->GetGroup(); //FIXME
1603 std::string vr = Entry->GetVR();
1607 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1609 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1611 // The following reserved two bytes (see PS 3.5-2001, section
1612 // 7.1.2 Data element structure with explicit vr p27) must be
1613 // skipped before proceeding on reading the length on 4 bytes.
1614 fseek(fp, 2L, SEEK_CUR);
1615 guint32 length32 = ReadInt32();
1617 if ( (vr == "OB") && (length32 == 0xffffffff) )
1619 Entry->SetLength(FindDocEntryLengthOB());
1622 FixDocEntryFoundLength(Entry, length32);
1626 // Length is encoded on 2 bytes.
1627 length16 = ReadInt16();
1629 // We can tell the current file is encoded in big endian (like
1630 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1631 // and it's value is the one of the encoding of a big endian file.
1632 // In order to deal with such big endian encoded files, we have
1633 // (at least) two strategies:
1634 // * when we load the "Transfer Syntax" tag with value of big endian
1635 // encoding, we raise the proper flags. Then we wait for the end
1636 // of the META group (0x0002) among which is "Transfer Syntax",
1637 // before switching the swap code to big endian. We have to postpone
1638 // the switching of the swap code since the META group is fully encoded
1639 // in little endian, and big endian coding only starts at the next
1640 // group. The corresponding code can be hard to analyse and adds
1641 // many additional unnecessary tests for regular tags.
1642 // * the second strategy consists in waiting for trouble, that shall
1643 // appear when we find the first group with big endian encoding. This
1644 // is easy to detect since the length of a "Group Length" tag (the
1645 // ones with zero as element number) has to be of 4 (0x0004). When we
1646 // encounter 1024 (0x0400) chances are the encoding changed and we
1647 // found a group with big endian encoding.
1648 // We shall use this second strategy. In order to make sure that we
1649 // can interpret the presence of an apparently big endian encoded
1650 // length of a "Group Length" without committing a big mistake, we
1651 // add an additional check: we look in the already parsed elements
1652 // for the presence of a "Transfer Syntax" whose value has to be "big
1653 // endian encoding". When this is the case, chances are we have got our
1654 // hands on a big endian encoded file: we switch the swap code to
1655 // big endian and proceed...
1656 if ( (element == 0x0000) && (length16 == 0x0400) )
1658 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1660 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1665 SwitchSwapToBigEndian();
1666 // Restore the unproperly loaded values i.e. the group, the element
1667 // and the dictionary entry depending on them.
1668 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1669 guint16 CorrectElem = SwapShort(Entry->GetElement());
1670 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1674 // This correct tag is not in the dictionary. Create a new one.
1675 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1677 // FIXME this can create a memory leaks on the old entry that be
1678 // left unreferenced.
1679 Entry->SetDictEntry(NewTag);
1682 // Heuristic: well some files are really ill-formed.
1683 if ( length16 == 0xffff)
1686 //dbg.Verbose(0, "gdcmDocument::FindLength",
1687 // "Erroneous element length fixed.");
1688 // Actually, length= 0xffff means that we deal with
1689 // Unknown Sequence Length
1691 FixDocEntryFoundLength(Entry, (guint32)length16);
1696 // Either implicit VR or a non DICOM conformal (see note below) explicit
1697 // VR that ommited the VR of (at least) this element. Farts happen.
1698 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1699 // on Data elements "Implicit and Explicit VR Data Elements shall
1700 // not coexist in a Data Set and Data Sets nested within it".]
1701 // Length is on 4 bytes.
1703 FixDocEntryFoundLength(Entry, ReadInt32());
1709 * \brief Find the Value Representation of the current Dicom Element.
1712 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1714 if (filetype != gdcmExplicitVR)
1719 long PositionOnEntry = ftell(fp);
1720 // Warning: we believe this is explicit VR (Value Representation) because
1721 // we used a heuristic that found "UL" in the first tag. Alas this
1722 // doesn't guarantee that all the tags will be in explicit VR. In some
1723 // cases (see e-film filtered files) one finds implicit VR tags mixed
1724 // within an explicit VR file. Hence we make sure the present tag
1725 // is in explicit VR and try to fix things if it happens not to be
1728 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1730 if(!CheckDocEntryVR(Entry,VR))
1732 fseek(fp, PositionOnEntry, SEEK_SET);
1733 // When this element is known in the dictionary we shall use, e.g. for
1734 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1735 // dictionary entry. Still we have to flag the element as implicit since
1736 // we know now our assumption on expliciteness is not furfilled.
1738 if ( Entry->IsVRUnknown() )
1739 Entry->SetVR("Implicit");
1740 Entry->SetImplicitVR();
1745 * \brief Check the correspondance between the VR of the header entry
1746 * and the taken VR. If they are different, the header entry is
1747 * updated with the new VR.
1748 * @param Entry Header Entry to check
1749 * @param vr Dicom Value Representation
1750 * @return false if the VR is incorrect of if the VR isn't referenced
1751 * otherwise, it returns true
1753 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1755 char msg[100]; // for sprintf
1756 bool RealExplicit = true;
1758 // Assume we are reading a falsely explicit VR file i.e. we reached
1759 // a tag where we expect reading a VR but are in fact we read the
1760 // first to bytes of the length. Then we will interogate (through find)
1761 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1762 // both GCC and VC++ implementations of the STL map. Hence when the
1763 // expected VR read happens to be non-ascii characters we consider
1764 // we hit falsely explicit VR tag.
1766 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1767 RealExplicit = false;
1769 // CLEANME searching the dicom_vr at each occurence is expensive.
1770 // PostPone this test in an optional integrity check at the end
1771 // of parsing or only in debug mode.
1772 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1773 RealExplicit= false;
1775 if ( !RealExplicit )
1777 // We thought this was explicit VR, but we end up with an
1778 // implicit VR tag. Let's backtrack.
1779 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1780 Entry->GetGroup(),Entry->GetElement());
1781 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1782 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1783 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1784 Entry->GetGroup(),Entry->GetElement(),
1785 "UL","FIXME","Group Length");
1786 Entry->SetDictEntry(NewEntry);
1791 if ( Entry->IsVRUnknown() )
1793 // When not a dictionary entry, we can safely overwrite the VR.
1794 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1800 else if ( Entry->GetVR() != vr )
1802 // The VR present in the file and the dictionary disagree. We assume
1803 // the file writer knew best and use the VR of the file. Since it would
1804 // be unwise to overwrite the VR of a dictionary (since it would
1805 // compromise it's next user), we need to clone the actual DictEntry
1806 // and change the VR for the read one.
1807 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1808 Entry->GetGroup(),Entry->GetElement(),
1809 vr,"FIXME",Entry->GetName());
1810 Entry->SetDictEntry(NewEntry);
1816 * \brief Get the transformed value of the header entry. The VR value
1817 * is used to define the transformation to operate on the value
1818 * \warning NOT end user intended method !
1820 * @return Transformed entry value
1822 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1824 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1826 std::string val=((gdcmValEntry *)Entry)->GetValue();
1827 std::string vr=Entry->GetVR();
1828 guint32 length = Entry->GetLength();
1829 std::ostringstream s;
1832 // When short integer(s) are expected, read and convert the following
1833 // n * 2 bytes properly i.e. as a multivaluated strings
1834 // (each single value is separated fromthe next one by '\'
1835 // as usual for standard multivaluated filels
1836 // Elements with Value Multiplicity > 1
1837 // contain a set of short integers (not a single one)
1839 if (vr == "US" || vr == "SS")
1844 for (int i=0; i < nbInt; i++)
1848 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1849 NewInt16 = SwapShort(NewInt16);
1854 // When integer(s) are expected, read and convert the following
1855 // n * 4 bytes properly i.e. as a multivaluated strings
1856 // (each single value is separated fromthe next one by '\'
1857 // as usual for standard multivaluated filels
1858 // Elements with Value Multiplicity > 1
1859 // contain a set of integers (not a single one)
1860 else if (vr == "UL" || vr == "SL")
1865 for (int i=0; i < nbInt; i++)
1869 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1870 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1871 NewInt32=SwapLong(NewInt32);
1875 #ifdef GDCM_NO_ANSI_STRING_STREAM
1876 s << std::ends; // to avoid oddities on Solaris
1877 #endif //GDCM_NO_ANSI_STRING_STREAM
1881 return(((gdcmValEntry *)Entry)->GetValue());
1885 * \brief Get the reverse transformed value of the header entry. The VR
1886 * value is used to define the reverse transformation to operate on
1888 * \warning NOT end user intended method !
1890 * @return Reverse transformed entry value
1892 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1894 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1896 std::string vr=Entry->GetVR();
1897 std::ostringstream s;
1898 std::vector<std::string> tokens;
1900 if (vr == "US" || vr == "SS")
1904 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1905 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1906 for (unsigned int i=0; i<tokens.size();i++)
1908 NewInt16 = atoi(tokens[i].c_str());
1909 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1913 if (vr == "UL" || vr == "SL")
1917 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1918 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1919 for (unsigned int i=0; i<tokens.size();i++)
1921 NewInt32 = atoi(tokens[i].c_str());
1922 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1923 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1928 #ifdef GDCM_NO_ANSI_STRING_STREAM
1929 s << std::ends; // to avoid oddities on Solaris
1930 #endif //GDCM_NO_ANSI_STRING_STREAM
1934 return(((gdcmValEntry *)Entry)->GetValue());
1938 * \brief Skip a given Header Entry
1939 * \warning NOT end user intended method !
1942 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1944 SkipBytes(entry->GetLength());
1948 * \brief Skips to the begining of the next Header Entry
1949 * \warning NOT end user intended method !
1952 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1954 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1955 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1959 * \brief Loads the value for a a given VLEntry
1960 * \warning NOT end user intended method !
1963 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
1965 //SkipBytes(entry->GetLength());
1966 LoadDocEntry(entry);
1969 * \brief When the length of an element value is obviously wrong (because
1970 * the parser went Jabberwocky) one can hope improving things by
1971 * applying this heuristic.
1973 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry, guint32 FoundLength)
1975 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1976 if ( FoundLength == 0xffffffff) {
1980 guint16 gr =Entry->GetGroup();
1981 guint16 el =Entry->GetElement();
1983 if (FoundLength%2) {
1984 std::ostringstream s;
1985 s << "Warning : Tag with uneven length " << FoundLength
1986 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1987 dbg.Verbose(0,s.str().c_str());
1990 // Sorry for the patch!
1991 // XMedCom did the trick to read some naughty GE images ...
1992 if (FoundLength == 13) {
1993 // The following 'if' will be removed when there is no more
1994 // images on Creatis HDs with a 13 length for Manufacturer...
1995 if ( (Entry->GetGroup() != 0x0008) ||
1996 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1997 // end of remove area
1999 Entry->SetReadLength(10); // a bug is to be fixed
2003 // to fix some garbage 'Leonardo' Siemens images
2004 // May be commented out to avoid overhead
2005 else if ( (Entry->GetGroup() == 0x0009) &&
2006 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
2008 Entry->SetReadLength(4); // a bug is to be fixed
2012 // to try to 'go inside' SeQuences (with length), and not to skip them
2013 else if ( Entry->GetVR() == "SQ")
2015 if (enableSequences) // only if the user does want to !
2016 FoundLength =0; // ReadLength is unchanged
2019 // we found a 'delimiter' element
2020 // fffe|xxxx is just a marker, we don't take its length into account
2021 else if(Entry->GetGroup() == 0xfffe)
2023 // *normally, fffe|0000 doesn't exist !
2024 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
2025 // causes extra troubles :-(
2029 Entry->SetUsableLength(FoundLength);
2033 * \brief Apply some heuristics to predict whether the considered
2034 * element value contains/represents an integer or not.
2035 * @param Entry The element value on which to apply the predicate.
2036 * @return The result of the heuristical predicate.
2038 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2039 guint16 element = Entry->GetElement();
2040 guint16 group = Entry->GetGroup();
2041 std::string vr = Entry->GetVR();
2042 guint32 length = Entry->GetLength();
2043 // When we have some semantics on the element we just read, and if we
2044 // a priori know we are dealing with an integer, then we shall be
2045 // able to swap it's element value properly.
2046 if ( element == 0 ) // This is the group length of the group
2052 std::ostringstream s;
2053 int filePosition = ftell(fp);
2054 s << "Erroneous Group Length element length on : (" \
2055 << std::hex << group << " , " << element
2056 << ") -before- position x(" << filePosition << ")"
2057 << "lgt : " << length;
2058 // These 2 lines commented out : a *very dirty* patch
2059 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
2060 // have a glance at offset x(8336) ...
2061 // For *regular* headers, the test is useless..
2062 // lets's print a warning message and go on,
2063 // instead of giving up with an error message
2065 //std::cout << s.str().c_str() << std::endl;
2066 // dbg.Error("gdcmDocument::IsDocEntryAnInteger",
2067 // s.str().c_str());
2070 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2076 * \brief Find the Length till the next sequence delimiter
2077 * \warning NOT end user intended method !
2081 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2082 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2085 long PositionOnEntry = ftell(fp);
2086 bool FoundSequenceDelimiter = false;
2087 guint32 TotalLength = 0;
2090 while ( ! FoundSequenceDelimiter)
2096 TotalLength += 4; // We even have to decount the group and element
2098 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2100 char msg[100]; // for sprintf. Sorry
2101 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2102 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2106 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2107 FoundSequenceDelimiter = true;
2108 else if ( n != 0xe000 )
2110 char msg[100]; // for sprintf. Sorry
2111 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2113 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2117 ItemLength = ReadInt32();
2118 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2119 // the ItemLength with ReadInt32
2120 SkipBytes(ItemLength);
2122 fseek(fp, PositionOnEntry, SEEK_SET);
2127 * \brief Reads a supposed to be 16 Bits integer
2128 * (swaps it depending on processor endianity)
2129 * @return read value
2131 guint16 gdcmDocument::ReadInt16(void) {
2134 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2135 if ( item_read != 1 ) {
2137 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2147 * \brief Reads a supposed to be 32 Bits integer
2148 * (swaps it depending on processor endianity)
2149 * @return read value
2151 guint32 gdcmDocument::ReadInt32(void) {
2154 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2155 if ( item_read != 1 ) {
2157 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2167 * \brief skips bytes inside the source file
2168 * \warning NOT end user intended method !
2171 void gdcmDocument::SkipBytes(guint32 NBytes) {
2172 //FIXME don't dump the returned value
2173 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2177 * \brief Loads all the needed Dictionaries
2178 * \warning NOT end user intended method !
2180 void gdcmDocument::Initialise(void)
2182 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2183 RefShaDict = (gdcmDict*)0;
2187 * \brief Discover what the swap code is (among little endian, big endian,
2188 * bad little endian, bad big endian).
2190 * @return false when we are absolutely sure
2191 * it's neither ACR-NEMA nor DICOM
2192 * true when we hope ours assuptions are OK
2194 bool gdcmDocument::CheckSwap() {
2196 // The only guaranted way of finding the swap code is to find a
2197 // group tag since we know it's length has to be of four bytes i.e.
2198 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2199 // occurs when we can't find such group...
2201 guint32 x=4; // x : for ntohs
2202 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2208 char deb[HEADER_LENGTH_TO_READ];
2210 // First, compare HostByteOrder and NetworkByteOrder in order to
2211 // determine if we shall need to swap bytes (i.e. the Endian type).
2217 // The easiest case is the one of a DICOM header, since it possesses a
2218 // file preamble where it suffice to look for the string "DICM".
2219 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2222 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2223 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2225 // Next, determine the value representation (VR). Let's skip to the
2226 // first element (0002, 0000) and check there if we find "UL"
2227 // - or "OB" if the 1st one is (0002,0001) -,
2228 // in which case we (almost) know it is explicit VR.
2229 // WARNING: if it happens to be implicit VR then what we will read
2230 // is the length of the group. If this ascii representation of this
2231 // length happens to be "UL" then we shall believe it is explicit VR.
2232 // FIXME: in order to fix the above warning, we could read the next
2233 // element value (or a couple of elements values) in order to make
2234 // sure we are not commiting a big mistake.
2235 // We need to skip :
2236 // * the 128 bytes of File Preamble (often padded with zeroes),
2237 // * the 4 bytes of "DICM" string,
2238 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2239 // i.e. a total of 136 bytes.
2243 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2244 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2245 // *Implicit* VR. -and it is !-
2247 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2248 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2249 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2250 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2251 // when Write DCM *adds*
2253 // Use gdcmDocument::dicom_vr to test all the possibilities
2254 // instead of just checking for UL, OB and UI !? group 0000
2256 filetype = gdcmExplicitVR;
2257 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2258 "explicit Value Representation");
2262 filetype = gdcmImplicitVR;
2263 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2264 "not an explicit Value Representation");
2270 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2271 "HostByteOrder != NetworkByteOrder");
2276 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2277 "HostByteOrder = NetworkByteOrder");
2280 // Position the file position indicator at first tag (i.e.
2281 // after the file preamble and the "DICM" string).
2283 fseek (fp, 132L, SEEK_SET);
2287 // Alas, this is not a DicomV3 file and whatever happens there is no file
2288 // preamble. We can reset the file position indicator to where the data
2289 // is (i.e. the beginning of the file).
2290 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2293 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2294 // By clean we mean that the length of the first tag is written down.
2295 // If this is the case and since the length of the first group HAS to be
2296 // four (bytes), then determining the proper swap code is straightforward.
2299 // We assume the array of char we are considering contains the binary
2300 // representation of a 32 bits integer. Hence the following dirty
2302 s32 = *((guint32 *)(entCur));
2323 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2324 // It is time for despaired wild guesses.
2325 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2326 // i.e. the 'group length' element is not present :
2328 // check the supposed to be 'group number'
2329 // 0x0002 or 0x0004 or 0x0008
2330 // to determine ' sw' value .
2331 // Only 0 or 4321 will be possible
2332 // (no oportunity to check for the formerly well known
2333 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2334 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2335 // the file IS NOT ACR-NEMA nor DICOM V3
2336 // Find a trick to tell it the caller...
2338 s16 = *((guint16 *)(deb));
2354 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2355 "ACR/NEMA unfound swap info (Really hopeless !)");
2356 filetype = gdcmUnknown;
2360 // Then the only info we have is the net2host one.
2370 * \brief Restore the unproperly loaded values i.e. the group, the element
2371 * and the dictionary entry depending on them.
2373 void gdcmDocument::SwitchSwapToBigEndian(void)
2375 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2376 "Switching to BigEndian mode.");
2397 * \brief during parsing, Header Elements too long are not loaded in memory
2400 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2404 if ((guint32)NewSize >= (guint32)0xffffffff)
2406 MaxSizeLoadEntry = 0xffffffff;
2409 MaxSizeLoadEntry = NewSize;
2414 * \brief Header Elements too long will not be printed
2415 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2418 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2422 if ((guint32)NewSize >= (guint32)0xffffffff)
2424 MaxSizePrintEntry = 0xffffffff;
2427 MaxSizePrintEntry = NewSize;
2433 * \brief Read the next tag but WITHOUT loading it's value
2434 * (read the 'Group Number', the 'Element Number',
2435 * gets the Dict Entry
2436 * gets the VR, gets the length, gets the offset value)
2437 * @return On succes the newly created DocEntry, NULL on failure.
2439 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2441 gdcmDocEntry *NewEntry;
2446 // We reached the EOF (or an error occured) therefore
2447 // header parsing has to be considered as finished.
2448 return (gdcmDocEntry *)0;
2450 // Pb : how to propagate the element length (used in SkipDocEntry)
2451 // direct call to SkipBytes ?
2453 // if (ignoreShadow == 1 && g%2 ==1)
2454 // if user wants to skip shadow groups
2455 // and current element *is* a shadow element
2456 // we don't create anything
2457 // return (gdcmDocEntry *)1; // to tell caller it's NOT finished
2459 NewEntry = NewDocEntryByNumber(g, n);
2460 FindDocEntryVR(NewEntry);
2461 FindDocEntryLength(NewEntry);
2468 NewEntry->SetOffset(ftell(fp));
2473 * \brief Build a new Element Value from all the low level arguments.
2474 * Check for existence of dictionary entry, and build
2475 * a default one when absent.
2476 * @param Name Name of the underlying DictEntry
2478 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2480 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2482 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2484 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2487 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2488 "failed to allocate gdcmDocEntry");
2489 return (gdcmDocEntry *)0;
2495 * \brief Request a new virtual dict entry to the dict set
2496 * @param group group number of the underlying DictEntry
2497 * @param element element number of the underlying DictEntry
2498 * @param vr VR of the underlying DictEntry
2499 * @param fourth owner group
2500 * @param name english name
2502 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2507 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2511 * \brief Build a new Element Value from all the low level arguments.
2512 * Check for existence of dictionary entry, and build
2513 * a default one when absent.
2514 * @param Group group number of the underlying DictEntry
2515 * @param Elem element number of the underlying DictEntry
2517 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2519 // Find out if the tag we encountered is in the dictionaries:
2520 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2522 DictEntry = NewVirtualDictEntry(Group, Elem);
2524 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2527 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2528 "failed to allocate gdcmDocEntry");
2536 * \brief Build a new Element Value from all the low level arguments.
2537 * Check for existence of dictionary entry, and build
2538 * a default one when absent.
2539 * @param Group group number of the underlying DictEntry
2540 * @param Elem element number of the underlying DictEntry
2542 gdcmValEntry *gdcmDocument::NewValEntryByNumber(guint16 Group, guint16 Elem)
2544 // Find out if the tag we encountered is in the dictionaries:
2545 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2547 DictEntry = NewVirtualDictEntry(Group, Elem);
2549 gdcmValEntry *NewEntry = new gdcmValEntry(DictEntry);
2552 dbg.Verbose(1, "gdcmDocument::NewValEntryByNumber",
2553 "failed to allocate gdcmValEntry");
2561 * \brief Build a new Element Value from all the low level arguments.
2562 * Check for existence of dictionary entry, and build
2563 * a default one when absent.
2564 * @param Group group number of the underlying DictEntry
2565 * @param Elem element number of the underlying DictEntry
2567 gdcmBinEntry *gdcmDocument::NewBinEntryByNumber(guint16 Group, guint16 Elem)
2569 // Find out if the tag we encountered is in the dictionaries:
2570 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2572 DictEntry = NewVirtualDictEntry(Group, Elem);
2574 gdcmBinEntry *NewEntry = new gdcmBinEntry(DictEntry);
2577 dbg.Verbose(1, "gdcmDocument::NewBinEntryByNumber",
2578 "failed to allocate gdcmBinEntry");
2585 * \brief Generate a free TagKey i.e. a TagKey that is not present
2586 * in the TagHt dictionary.
2587 * @param group The generated tag must belong to this group.
2588 * @return The element of tag with given group which is fee.
2590 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2592 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2594 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2595 if (tagHT.count(key) == 0)
2603 * \brief Searches both the public and the shadow dictionary (when they
2604 * exist) for the presence of the DictEntry with given name.
2605 * The public dictionary has precedence on the shadow one.
2606 * @param Name name of the searched DictEntry
2607 * @return Corresponding DictEntry when it exists, NULL otherwise.
2609 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2611 gdcmDictEntry *found = (gdcmDictEntry *)0;
2612 if (!RefPubDict && !RefShaDict)
2614 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2615 "we SHOULD have a default dictionary");
2619 found = RefPubDict->GetDictEntryByName(Name);
2625 found = RefShaDict->GetDictEntryByName(Name);
2633 * \brief Searches both the public and the shadow dictionary (when they
2634 * exist) for the presence of the DictEntry with given
2635 * group and element. The public dictionary has precedence on the
2637 * @param group group number of the searched DictEntry
2638 * @param element element number of the searched DictEntry
2639 * @return Corresponding DictEntry when it exists, NULL otherwise.
2641 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2643 gdcmDictEntry *found = (gdcmDictEntry *)0;
2644 if (!RefPubDict && !RefShaDict)
2646 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2647 "we SHOULD have a default dictionary");
2651 found = RefPubDict->GetDictEntryByNumber(group, element);
2657 found = RefShaDict->GetDictEntryByNumber(group, element);
2666 * \ingroup gdcmDocument
2667 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2668 * \ No other way so 'skip' the Data
2671 void gdcmDocument::Parse7FE0 (void) {
2673 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2677 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
2678 if (Transfer == UI1_2_840_10008_1_2 )
2680 if ( Transfer == UI1_2_840_10008_1_2_1 )
2682 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
2684 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
2688 std::string str_nb=GetEntryByNumber(0x0028,0x0100);
2689 if (str_nb == GDCM_UNFOUND ) {
2692 nb = atoi(str_nb.c_str() );
2693 if (nb == 12) nb =16;
2696 guint16 ItemTagGr,ItemTagEl;
2700 // -------------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2702 if ( Transfer != UI1_1_2_840_10008_1_2_5 ) { // !RLELossLessTransferSyntax
2705 fread(&ItemTagGr,2,1,fp); //Reading (fffe):Basic Offset Table Item Tag Gr
2706 fread(&ItemTagEl,2,1,fp); //Reading (e000):Basic Offset Table Item Tag El
2708 ItemTagGr=SwapShort(ItemTagGr);
2709 ItemTagEl=SwapShort(ItemTagEl);
2711 printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
2712 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2716 ln=SwapLong(ln); // Basic Offset Table Item Length
2717 printf("at %x : Basic Offset Table Item Length (\?\?) %d x(%08x)\n",
2718 (unsigned)ftellRes,ln,ln);
2720 // What is it used for ??
2721 char * BasicOffsetTableItemValue= new char[ln+1];
2722 fread(BasicOffsetTableItemValue,ln,1,fp);
2724 for (int i=0;i<ln;i+=4){
2725 a=str2num(&BasicOffsetTableItemValue[i],guint32);
2726 printf(" x(%08x) %d\n",a,a);
2731 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2732 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2734 ItemTagGr=SwapShort(ItemTagGr);
2735 ItemTagEl=SwapShort(ItemTagEl);
2737 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2738 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2740 while ( ( ItemTagGr==0xfffe) && (ItemTagEl!=0xe0dd) ) { // Parse fragments
2745 ln=SwapLong(ln); // length
2746 printf(" at %x : fragment length %d x(%08x)\n",
2747 (unsigned)ftellRes, ln,ln);
2749 // ------------------------
2750 fseek(fp,ln,SEEK_CUR); // skipping (not reading) fragment pixels
2751 // ------------------------
2754 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2755 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2757 ItemTagGr=SwapShort(ItemTagGr);
2758 ItemTagEl=SwapShort(ItemTagEl);
2760 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2761 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2767 long RleSegmentLength[15],fragmentLength;
2768 guint32 nbRleSegments;
2769 guint32 RleSegmentOffsetTable[15];
2771 // Basic Offset Table with Item Value
2773 fread(&ItemTagGr,2,1,fp); //Reading (fffe):Basic Offset Table Item Tag Gr
2774 fread(&ItemTagEl,2,1,fp); //Reading (e000):Basic Offset Table Item Tag El
2776 ItemTagGr=SwapShort(ItemTagGr);
2777 ItemTagEl=SwapShort(ItemTagEl);
2779 printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
2780 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2785 ln=SwapLong(ln); // Basic Offset Table Item Length
2786 printf("at %x : Basic Offset Table Item Length (\?\?) %d x(%08x)\n",
2787 (unsigned)ftellRes,ln,ln);
2789 // What is it used for ??
2790 char * BasicOffsetTableItemValue= new char[ln+1];
2791 fread(BasicOffsetTableItemValue,ln,1,fp);
2793 for (int i=0;i<ln;i+=4){
2794 a=str2num(&BasicOffsetTableItemValue[i],guint32);
2795 printf(" x(%08x) %d\n",a,a);
2800 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2801 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2803 ItemTagGr=SwapShort(ItemTagGr);
2804 ItemTagEl=SwapShort(ItemTagEl);
2806 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2807 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2809 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2810 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
2811 // Parse fragments of the current Fragment (Frame)
2813 fread(&fragmentLength,4,1,fp);
2815 fragmentLength=SwapLong(fragmentLength); // length
2816 printf(" at %x : 'fragment' length %d x(%08x)\n",
2817 (unsigned)ftellRes, (unsigned)fragmentLength,(unsigned)fragmentLength);
2819 //------------------ scanning (not reading) fragment pixels
2821 fread(&nbRleSegments,4,1,fp); // Reading : Number of RLE Segments
2823 nbRleSegments=SwapLong(nbRleSegments);
2824 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2826 for(int k=1; k<=15; k++) { // Reading RLE Segments Offset Table
2828 fread(&RleSegmentOffsetTable[k],4,1,fp);
2830 RleSegmentOffsetTable[k]=SwapLong(RleSegmentOffsetTable[k]);
2831 printf(" at : %x Offset Segment %d : %d (%x)\n",
2832 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2833 RleSegmentOffsetTable[k]);
2836 if (nbRleSegments>1) { // skipping (not reading) RLE Segments
2837 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2838 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2839 - RleSegmentOffsetTable[k];
2841 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2842 k,(unsigned)RleSegmentLength[k],(unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2843 fseek(fp,RleSegmentLength[k],SEEK_CUR);
2846 RleSegmentLength[nbRleSegments]= fragmentLength
2847 - RleSegmentOffsetTable[nbRleSegments];
2849 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2850 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2851 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2853 fseek(fp,RleSegmentLength[nbRleSegments],SEEK_CUR);
2855 // ------------------ end of scanning fragment pixels
2858 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2859 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2861 ItemTagGr=SwapShort(ItemTagGr);
2862 ItemTagEl=SwapShort(ItemTagEl);
2864 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2865 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2872 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2873 * \warning Does NOT work with ACR-NEMA files
2874 * \todo Find a trick to solve the pb (use RET fields ?)
2876 * @return true if 'smaller'
2878 bool gdcmDocument::operator<(gdcmDocument &document){
2882 s1=this->GetEntryByNumber(0x0010,0x0010);
2883 s2=document.GetEntryByNumber(0x0010,0x0010);
2891 s1=this->GetEntryByNumber(0x0010,0x0020);
2892 s2=document.GetEntryByNumber(0x0010,0x0020);
2899 // Study Instance UID
2900 s1=this->GetEntryByNumber(0x0020,0x000d);
2901 s2=document.GetEntryByNumber(0x0020,0x000d);
2908 // Serie Instance UID
2909 s1=this->GetEntryByNumber(0x0020,0x000e);
2910 s2=document.GetEntryByNumber(0x0020,0x000e);
2922 //-----------------------------------------------------------------------------