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;
1445 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1449 int depth = set->GetDepthLevel();
1452 NewDocEntry = ReadNextDocEntry();
1454 if (NewDocEntry->isSequenceDelimitor()) {
1455 //add the Sequence Delimitor // TODO : find the trick to put it properly !
1456 set->SetSequenceDelimitationItem(NewDocEntry);
1460 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1463 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1464 itemSQ->AddEntry(NewDocEntry); // no value, no voidArea. Think of it while printing !
1465 l= NewDocEntry->GetReadLength();
1472 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1474 set->AddEntry(itemSQ,SQItemNumber);
1476 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1480 lgth = ftell(fp) - offset;
1485 * \brief Loads the element content if its length doesn't exceed
1486 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1487 * @param Entry Header Entry (Dicom Element) to be dealt with
1489 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry) {
1491 guint16 group = Entry->GetGroup();
1492 std::string vr= Entry->GetVR();
1493 guint32 length = Entry->GetLength();
1495 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1497 // A SeQuence "contains" a set of Elements.
1498 // (fffe e000) tells us an Element is beginning
1499 // (fffe e00d) tells us an Element just ended
1500 // (fffe e0dd) tells us the current SeQuence just ended
1501 if( group == 0xfffe ) {
1502 // NO more value field for SQ !
1503 //Entry->SetValue("gdcm::Skipped");
1504 // appel recursif de Load Value
1505 // (meme pb que pour le parsing)
1509 // When the length is zero things are easy:
1510 if ( length == 0 ) {
1511 ((gdcmValEntry *)Entry)->SetValue("");
1515 // The elements whose length is bigger than the specified upper bound
1516 // are not loaded. Instead we leave a short notice of the offset of
1517 // the element content and it's length.
1518 if (length > MaxSizeLoadEntry) {
1519 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1521 std::ostringstream s;
1522 s << "gdcm::NotLoaded.";
1523 s << " Address:" << (long)Entry->GetOffset();
1524 s << " Length:" << Entry->GetLength();
1525 s << " x(" << std::hex << Entry->GetLength() << ")";
1526 ValEntryPtr->SetValue(s.str());
1528 // to be sure we are at the end of the value ...
1529 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1534 // Any compacter code suggested (?)
1535 if ( IsDocEntryAnInteger(Entry) ) {
1537 std::ostringstream s;
1539 // When short integer(s) are expected, read and convert the following
1540 // n *two characters properly i.e. as short integers as opposed to strings.
1541 // Elements with Value Multiplicity > 1
1542 // contain a set of integers (not a single one)
1543 if (vr == "US" || vr == "SS") {
1545 NewInt = ReadInt16();
1548 for (int i=1; i < nbInt; i++) {
1550 NewInt = ReadInt16();
1555 // When integer(s) are expected, read and convert the following
1556 // n * four characters properly i.e. as integers as opposed to strings.
1557 // Elements with Value Multiplicity > 1
1558 // contain a set of integers (not a single one)
1559 else if (vr == "UL" || vr == "SL") {
1561 NewInt = ReadInt32();
1564 for (int i=1; i < nbInt; i++) {
1566 NewInt = ReadInt32();
1571 #ifdef GDCM_NO_ANSI_STRING_STREAM
1572 s << std::ends; // to avoid oddities on Solaris
1573 #endif //GDCM_NO_ANSI_STRING_STREAM
1575 ((gdcmValEntry *)Entry)->SetValue(s.str());
1579 // We need an additional byte for storing \0 that is not on disk
1580 std::string NewValue(length,0);
1581 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1582 if ( item_read != 1 ) {
1583 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1584 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1588 if( (vr == "UI") ) // Because of correspondance with the VR dic
1589 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1591 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1596 * \brief Find the value Length of the passed Header Entry
1597 * @param Entry Header Entry whose length of the value shall be loaded.
1599 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1600 guint16 element = Entry->GetElement();
1601 //guint16 group = Entry->GetGroup(); //FIXME
1602 std::string vr = Entry->GetVR();
1606 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1608 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1610 // The following reserved two bytes (see PS 3.5-2001, section
1611 // 7.1.2 Data element structure with explicit vr p27) must be
1612 // skipped before proceeding on reading the length on 4 bytes.
1613 fseek(fp, 2L, SEEK_CUR);
1614 guint32 length32 = ReadInt32();
1616 if ( (vr == "OB") && (length32 == 0xffffffff) )
1618 Entry->SetLength(FindDocEntryLengthOB());
1621 FixDocEntryFoundLength(Entry, length32);
1625 // Length is encoded on 2 bytes.
1626 length16 = ReadInt16();
1628 // We can tell the current file is encoded in big endian (like
1629 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1630 // and it's value is the one of the encoding of a big endian file.
1631 // In order to deal with such big endian encoded files, we have
1632 // (at least) two strategies:
1633 // * when we load the "Transfer Syntax" tag with value of big endian
1634 // encoding, we raise the proper flags. Then we wait for the end
1635 // of the META group (0x0002) among which is "Transfer Syntax",
1636 // before switching the swap code to big endian. We have to postpone
1637 // the switching of the swap code since the META group is fully encoded
1638 // in little endian, and big endian coding only starts at the next
1639 // group. The corresponding code can be hard to analyse and adds
1640 // many additional unnecessary tests for regular tags.
1641 // * the second strategy consists in waiting for trouble, that shall
1642 // appear when we find the first group with big endian encoding. This
1643 // is easy to detect since the length of a "Group Length" tag (the
1644 // ones with zero as element number) has to be of 4 (0x0004). When we
1645 // encounter 1024 (0x0400) chances are the encoding changed and we
1646 // found a group with big endian encoding.
1647 // We shall use this second strategy. In order to make sure that we
1648 // can interpret the presence of an apparently big endian encoded
1649 // length of a "Group Length" without committing a big mistake, we
1650 // add an additional check: we look in the already parsed elements
1651 // for the presence of a "Transfer Syntax" whose value has to be "big
1652 // endian encoding". When this is the case, chances are we have got our
1653 // hands on a big endian encoded file: we switch the swap code to
1654 // big endian and proceed...
1655 if ( (element == 0x0000) && (length16 == 0x0400) )
1657 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1659 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1664 SwitchSwapToBigEndian();
1665 // Restore the unproperly loaded values i.e. the group, the element
1666 // and the dictionary entry depending on them.
1667 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1668 guint16 CorrectElem = SwapShort(Entry->GetElement());
1669 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1673 // This correct tag is not in the dictionary. Create a new one.
1674 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1676 // FIXME this can create a memory leaks on the old entry that be
1677 // left unreferenced.
1678 Entry->SetDictEntry(NewTag);
1681 // Heuristic: well some files are really ill-formed.
1682 if ( length16 == 0xffff)
1685 //dbg.Verbose(0, "gdcmDocument::FindLength",
1686 // "Erroneous element length fixed.");
1687 // Actually, length= 0xffff means that we deal with
1688 // Unknown Sequence Length
1690 FixDocEntryFoundLength(Entry, (guint32)length16);
1695 // Either implicit VR or a non DICOM conformal (see note below) explicit
1696 // VR that ommited the VR of (at least) this element. Farts happen.
1697 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1698 // on Data elements "Implicit and Explicit VR Data Elements shall
1699 // not coexist in a Data Set and Data Sets nested within it".]
1700 // Length is on 4 bytes.
1702 FixDocEntryFoundLength(Entry, ReadInt32());
1708 * \brief Find the Value Representation of the current Dicom Element.
1711 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1713 if (filetype != gdcmExplicitVR)
1718 long PositionOnEntry = ftell(fp);
1719 // Warning: we believe this is explicit VR (Value Representation) because
1720 // we used a heuristic that found "UL" in the first tag. Alas this
1721 // doesn't guarantee that all the tags will be in explicit VR. In some
1722 // cases (see e-film filtered files) one finds implicit VR tags mixed
1723 // within an explicit VR file. Hence we make sure the present tag
1724 // is in explicit VR and try to fix things if it happens not to be
1727 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1729 if(!CheckDocEntryVR(Entry,VR))
1731 fseek(fp, PositionOnEntry, SEEK_SET);
1732 // When this element is known in the dictionary we shall use, e.g. for
1733 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1734 // dictionary entry. Still we have to flag the element as implicit since
1735 // we know now our assumption on expliciteness is not furfilled.
1737 if ( Entry->IsVRUnknown() )
1738 Entry->SetVR("Implicit");
1739 Entry->SetImplicitVR();
1744 * \brief Check the correspondance between the VR of the header entry
1745 * and the taken VR. If they are different, the header entry is
1746 * updated with the new VR.
1747 * @param Entry Header Entry to check
1748 * @param vr Dicom Value Representation
1749 * @return false if the VR is incorrect of if the VR isn't referenced
1750 * otherwise, it returns true
1752 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1754 char msg[100]; // for sprintf
1755 bool RealExplicit = true;
1757 // Assume we are reading a falsely explicit VR file i.e. we reached
1758 // a tag where we expect reading a VR but are in fact we read the
1759 // first to bytes of the length. Then we will interogate (through find)
1760 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1761 // both GCC and VC++ implementations of the STL map. Hence when the
1762 // expected VR read happens to be non-ascii characters we consider
1763 // we hit falsely explicit VR tag.
1765 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1766 RealExplicit = false;
1768 // CLEANME searching the dicom_vr at each occurence is expensive.
1769 // PostPone this test in an optional integrity check at the end
1770 // of parsing or only in debug mode.
1771 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1772 RealExplicit= false;
1774 if ( !RealExplicit )
1776 // We thought this was explicit VR, but we end up with an
1777 // implicit VR tag. Let's backtrack.
1778 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1779 Entry->GetGroup(),Entry->GetElement());
1780 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1781 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1782 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1783 Entry->GetGroup(),Entry->GetElement(),
1784 "UL","FIXME","Group Length");
1785 Entry->SetDictEntry(NewEntry);
1790 if ( Entry->IsVRUnknown() )
1792 // When not a dictionary entry, we can safely overwrite the VR.
1793 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1799 else if ( Entry->GetVR() != vr )
1801 // The VR present in the file and the dictionary disagree. We assume
1802 // the file writer knew best and use the VR of the file. Since it would
1803 // be unwise to overwrite the VR of a dictionary (since it would
1804 // compromise it's next user), we need to clone the actual DictEntry
1805 // and change the VR for the read one.
1806 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1807 Entry->GetGroup(),Entry->GetElement(),
1808 vr,"FIXME",Entry->GetName());
1809 Entry->SetDictEntry(NewEntry);
1815 * \brief Get the transformed value of the header entry. The VR value
1816 * is used to define the transformation to operate on the value
1817 * \warning NOT end user intended method !
1819 * @return Transformed entry value
1821 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1823 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1825 std::string val=((gdcmValEntry *)Entry)->GetValue();
1826 std::string vr=Entry->GetVR();
1827 guint32 length = Entry->GetLength();
1828 std::ostringstream s;
1831 // When short integer(s) are expected, read and convert the following
1832 // n * 2 bytes properly i.e. as a multivaluated strings
1833 // (each single value is separated fromthe next one by '\'
1834 // as usual for standard multivaluated filels
1835 // Elements with Value Multiplicity > 1
1836 // contain a set of short integers (not a single one)
1838 if (vr == "US" || vr == "SS")
1843 for (int i=0; i < nbInt; i++)
1847 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1848 NewInt16 = SwapShort(NewInt16);
1853 // When integer(s) are expected, read and convert the following
1854 // n * 4 bytes properly i.e. as a multivaluated strings
1855 // (each single value is separated fromthe next one by '\'
1856 // as usual for standard multivaluated filels
1857 // Elements with Value Multiplicity > 1
1858 // contain a set of integers (not a single one)
1859 else if (vr == "UL" || vr == "SL")
1864 for (int i=0; i < nbInt; i++)
1868 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1869 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1870 NewInt32=SwapLong(NewInt32);
1874 #ifdef GDCM_NO_ANSI_STRING_STREAM
1875 s << std::ends; // to avoid oddities on Solaris
1876 #endif //GDCM_NO_ANSI_STRING_STREAM
1880 return(((gdcmValEntry *)Entry)->GetValue());
1884 * \brief Get the reverse transformed value of the header entry. The VR
1885 * value is used to define the reverse transformation to operate on
1887 * \warning NOT end user intended method !
1889 * @return Reverse transformed entry value
1891 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1893 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1895 std::string vr=Entry->GetVR();
1896 std::ostringstream s;
1897 std::vector<std::string> tokens;
1899 if (vr == "US" || vr == "SS")
1903 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1904 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1905 for (unsigned int i=0; i<tokens.size();i++)
1907 NewInt16 = atoi(tokens[i].c_str());
1908 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1912 if (vr == "UL" || vr == "SL")
1916 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1917 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1918 for (unsigned int i=0; i<tokens.size();i++)
1920 NewInt32 = atoi(tokens[i].c_str());
1921 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1922 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1927 #ifdef GDCM_NO_ANSI_STRING_STREAM
1928 s << std::ends; // to avoid oddities on Solaris
1929 #endif //GDCM_NO_ANSI_STRING_STREAM
1933 return(((gdcmValEntry *)Entry)->GetValue());
1937 * \brief Skip a given Header Entry
1938 * \warning NOT end user intended method !
1941 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1943 SkipBytes(entry->GetLength());
1947 * \brief Skips to the begining of the next Header Entry
1948 * \warning NOT end user intended method !
1951 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1953 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1954 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1958 * \brief Loads the value for a a given VLEntry
1959 * \warning NOT end user intended method !
1962 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
1964 //SkipBytes(entry->GetLength());
1965 LoadDocEntry(entry);
1968 * \brief When the length of an element value is obviously wrong (because
1969 * the parser went Jabberwocky) one can hope improving things by
1970 * applying this heuristic.
1972 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry, guint32 FoundLength)
1974 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1975 if ( FoundLength == 0xffffffff) {
1979 guint16 gr =Entry->GetGroup();
1980 guint16 el =Entry->GetElement();
1982 if (FoundLength%2) {
1983 std::ostringstream s;
1984 s << "Warning : Tag with uneven length " << FoundLength
1985 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1986 dbg.Verbose(0,s.str().c_str());
1989 // Sorry for the patch!
1990 // XMedCom did the trick to read some naughty GE images ...
1991 if (FoundLength == 13) {
1992 // The following 'if' will be removed when there is no more
1993 // images on Creatis HDs with a 13 length for Manufacturer...
1994 if ( (Entry->GetGroup() != 0x0008) ||
1995 ( (Entry->GetElement() != 0x0070) && (Entry->GetElement() != 0x0080) ) ){
1996 // end of remove area
1998 Entry->SetReadLength(10); // a bug is to be fixed
2002 // to fix some garbage 'Leonardo' Siemens images
2003 // May be commented out to avoid overhead
2004 else if ( (Entry->GetGroup() == 0x0009) &&
2005 ( (Entry->GetElement() == 0x1113) || (Entry->GetElement() == 0x1114) ) ){
2007 Entry->SetReadLength(4); // a bug is to be fixed
2011 // to try to 'go inside' SeQuences (with length), and not to skip them
2012 else if ( Entry->GetVR() == "SQ")
2014 if (enableSequences) // only if the user does want to !
2015 FoundLength =0; // ReadLength is unchanged
2018 // we found a 'delimiter' element
2019 // fffe|xxxx is just a marker, we don't take its length into account
2020 else if(Entry->GetGroup() == 0xfffe)
2022 // *normally, fffe|0000 doesn't exist !
2023 if( Entry->GetElement() != 0x0000 ) // gdcm-MR-PHILIPS-16-Multi-Seq.dcm
2024 // causes extra troubles :-(
2028 Entry->SetUsableLength(FoundLength);
2032 * \brief Apply some heuristics to predict whether the considered
2033 * element value contains/represents an integer or not.
2034 * @param Entry The element value on which to apply the predicate.
2035 * @return The result of the heuristical predicate.
2037 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2038 guint16 element = Entry->GetElement();
2039 guint16 group = Entry->GetGroup();
2040 std::string vr = Entry->GetVR();
2041 guint32 length = Entry->GetLength();
2042 // When we have some semantics on the element we just read, and if we
2043 // a priori know we are dealing with an integer, then we shall be
2044 // able to swap it's element value properly.
2045 if ( element == 0 ) // This is the group length of the group
2051 std::ostringstream s;
2052 int filePosition = ftell(fp);
2053 s << "Erroneous Group Length element length on : (" \
2054 << std::hex << group << " , " << element
2055 << ") -before- position x(" << filePosition << ")"
2056 << "lgt : " << length;
2057 // These 2 lines commented out : a *very dirty* patch
2058 // to go on PrintHeader'ing gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
2059 // have a glance at offset x(8336) ...
2060 // For *regular* headers, the test is useless..
2061 // lets's print a warning message and go on,
2062 // instead of giving up with an error message
2064 //std::cout << s.str().c_str() << std::endl;
2065 // dbg.Error("gdcmDocument::IsDocEntryAnInteger",
2066 // s.str().c_str());
2069 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2075 * \brief Find the Length till the next sequence delimiter
2076 * \warning NOT end user intended method !
2080 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2081 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2084 long PositionOnEntry = ftell(fp);
2085 bool FoundSequenceDelimiter = false;
2086 guint32 TotalLength = 0;
2089 while ( ! FoundSequenceDelimiter)
2095 TotalLength += 4; // We even have to decount the group and element
2097 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2099 char msg[100]; // for sprintf. Sorry
2100 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2101 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2105 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2106 FoundSequenceDelimiter = true;
2107 else if ( n != 0xe000 )
2109 char msg[100]; // for sprintf. Sorry
2110 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2112 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2116 ItemLength = ReadInt32();
2117 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2118 // the ItemLength with ReadInt32
2119 SkipBytes(ItemLength);
2121 fseek(fp, PositionOnEntry, SEEK_SET);
2126 * \brief Reads a supposed to be 16 Bits integer
2127 * (swaps it depending on processor endianity)
2128 * @return read value
2130 guint16 gdcmDocument::ReadInt16(void) {
2133 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2134 if ( item_read != 1 ) {
2136 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2146 * \brief Reads a supposed to be 32 Bits integer
2147 * (swaps it depending on processor endianity)
2148 * @return read value
2150 guint32 gdcmDocument::ReadInt32(void) {
2153 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2154 if ( item_read != 1 ) {
2156 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2166 * \brief skips bytes inside the source file
2167 * \warning NOT end user intended method !
2170 void gdcmDocument::SkipBytes(guint32 NBytes) {
2171 //FIXME don't dump the returned value
2172 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2176 * \brief Loads all the needed Dictionaries
2177 * \warning NOT end user intended method !
2179 void gdcmDocument::Initialise(void)
2181 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2182 RefShaDict = (gdcmDict*)0;
2186 * \brief Discover what the swap code is (among little endian, big endian,
2187 * bad little endian, bad big endian).
2189 * @return false when we are absolutely sure
2190 * it's neither ACR-NEMA nor DICOM
2191 * true when we hope ours assuptions are OK
2193 bool gdcmDocument::CheckSwap() {
2195 // The only guaranted way of finding the swap code is to find a
2196 // group tag since we know it's length has to be of four bytes i.e.
2197 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2198 // occurs when we can't find such group...
2200 guint32 x=4; // x : for ntohs
2201 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2207 char deb[HEADER_LENGTH_TO_READ];
2209 // First, compare HostByteOrder and NetworkByteOrder in order to
2210 // determine if we shall need to swap bytes (i.e. the Endian type).
2216 // The easiest case is the one of a DICOM header, since it possesses a
2217 // file preamble where it suffice to look for the string "DICM".
2218 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2221 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2222 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2224 // Next, determine the value representation (VR). Let's skip to the
2225 // first element (0002, 0000) and check there if we find "UL"
2226 // - or "OB" if the 1st one is (0002,0001) -,
2227 // in which case we (almost) know it is explicit VR.
2228 // WARNING: if it happens to be implicit VR then what we will read
2229 // is the length of the group. If this ascii representation of this
2230 // length happens to be "UL" then we shall believe it is explicit VR.
2231 // FIXME: in order to fix the above warning, we could read the next
2232 // element value (or a couple of elements values) in order to make
2233 // sure we are not commiting a big mistake.
2234 // We need to skip :
2235 // * the 128 bytes of File Preamble (often padded with zeroes),
2236 // * the 4 bytes of "DICM" string,
2237 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2238 // i.e. a total of 136 bytes.
2242 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2243 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2244 // *Implicit* VR. -and it is !-
2246 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2247 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2248 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2249 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2250 // when Write DCM *adds*
2252 // Use gdcmDocument::dicom_vr to test all the possibilities
2253 // instead of just checking for UL, OB and UI !? group 0000
2255 filetype = gdcmExplicitVR;
2256 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2257 "explicit Value Representation");
2261 filetype = gdcmImplicitVR;
2262 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2263 "not an explicit Value Representation");
2269 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2270 "HostByteOrder != NetworkByteOrder");
2275 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2276 "HostByteOrder = NetworkByteOrder");
2279 // Position the file position indicator at first tag (i.e.
2280 // after the file preamble and the "DICM" string).
2282 fseek (fp, 132L, SEEK_SET);
2286 // Alas, this is not a DicomV3 file and whatever happens there is no file
2287 // preamble. We can reset the file position indicator to where the data
2288 // is (i.e. the beginning of the file).
2289 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2292 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2293 // By clean we mean that the length of the first tag is written down.
2294 // If this is the case and since the length of the first group HAS to be
2295 // four (bytes), then determining the proper swap code is straightforward.
2298 // We assume the array of char we are considering contains the binary
2299 // representation of a 32 bits integer. Hence the following dirty
2301 s32 = *((guint32 *)(entCur));
2322 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2323 // It is time for despaired wild guesses.
2324 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2325 // i.e. the 'group length' element is not present :
2327 // check the supposed to be 'group number'
2328 // 0x0002 or 0x0004 or 0x0008
2329 // to determine ' sw' value .
2330 // Only 0 or 4321 will be possible
2331 // (no oportunity to check for the formerly well known
2332 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2333 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2334 // the file IS NOT ACR-NEMA nor DICOM V3
2335 // Find a trick to tell it the caller...
2337 s16 = *((guint16 *)(deb));
2353 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2354 "ACR/NEMA unfound swap info (Really hopeless !)");
2355 filetype = gdcmUnknown;
2359 // Then the only info we have is the net2host one.
2369 * \brief Restore the unproperly loaded values i.e. the group, the element
2370 * and the dictionary entry depending on them.
2372 void gdcmDocument::SwitchSwapToBigEndian(void)
2374 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2375 "Switching to BigEndian mode.");
2396 * \brief during parsing, Header Elements too long are not loaded in memory
2399 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2403 if ((guint32)NewSize >= (guint32)0xffffffff)
2405 MaxSizeLoadEntry = 0xffffffff;
2408 MaxSizeLoadEntry = NewSize;
2413 * \brief Header Elements too long will not be printed
2414 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2417 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2421 if ((guint32)NewSize >= (guint32)0xffffffff)
2423 MaxSizePrintEntry = 0xffffffff;
2426 MaxSizePrintEntry = NewSize;
2432 * \brief Read the next tag but WITHOUT loading it's value
2433 * (read the 'Group Number', the 'Element Number',
2434 * gets the Dict Entry
2435 * gets the VR, gets the length, gets the offset value)
2436 * @return On succes the newly created DocEntry, NULL on failure.
2438 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2440 gdcmDocEntry *NewEntry;
2445 // We reached the EOF (or an error occured) therefore
2446 // header parsing has to be considered as finished.
2447 return (gdcmDocEntry *)0;
2449 // Pb : how to propagate the element length (used in SkipDocEntry)
2450 // direct call to SkipBytes ?
2452 // if (ignoreShadow == 1 && g%2 ==1)
2453 // if user wants to skip shadow groups
2454 // and current element *is* a shadow element
2455 // we don't create anything
2456 // return (gdcmDocEntry *)1; // to tell caller it's NOT finished
2458 NewEntry = NewDocEntryByNumber(g, n);
2459 FindDocEntryVR(NewEntry);
2460 FindDocEntryLength(NewEntry);
2467 NewEntry->SetOffset(ftell(fp));
2472 * \brief Build a new Element Value from all the low level arguments.
2473 * Check for existence of dictionary entry, and build
2474 * a default one when absent.
2475 * @param Name Name of the underlying DictEntry
2477 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2479 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2481 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2483 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2486 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2487 "failed to allocate gdcmDocEntry");
2488 return (gdcmDocEntry *)0;
2494 * \brief Request a new virtual dict entry to the dict set
2495 * @param group group number of the underlying DictEntry
2496 * @param element element number of the underlying DictEntry
2497 * @param vr VR of the underlying DictEntry
2498 * @param fourth owner group
2499 * @param name english name
2501 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2506 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2510 * \brief Build a new Element Value from all the low level arguments.
2511 * Check for existence of dictionary entry, and build
2512 * a default one when absent.
2513 * @param Group group number of the underlying DictEntry
2514 * @param Elem element number of the underlying DictEntry
2516 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2518 // Find out if the tag we encountered is in the dictionaries:
2519 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2521 DictEntry = NewVirtualDictEntry(Group, Elem);
2523 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2526 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2527 "failed to allocate gdcmDocEntry");
2535 * \brief Build a new Element Value from all the low level arguments.
2536 * Check for existence of dictionary entry, and build
2537 * a default one when absent.
2538 * @param Group group number of the underlying DictEntry
2539 * @param Elem element number of the underlying DictEntry
2541 gdcmValEntry *gdcmDocument::NewValEntryByNumber(guint16 Group, guint16 Elem)
2543 // Find out if the tag we encountered is in the dictionaries:
2544 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2546 DictEntry = NewVirtualDictEntry(Group, Elem);
2548 gdcmValEntry *NewEntry = new gdcmValEntry(DictEntry);
2551 dbg.Verbose(1, "gdcmDocument::NewValEntryByNumber",
2552 "failed to allocate gdcmValEntry");
2560 * \brief Build a new Element Value from all the low level arguments.
2561 * Check for existence of dictionary entry, and build
2562 * a default one when absent.
2563 * @param Group group number of the underlying DictEntry
2564 * @param Elem element number of the underlying DictEntry
2566 gdcmBinEntry *gdcmDocument::NewBinEntryByNumber(guint16 Group, guint16 Elem)
2568 // Find out if the tag we encountered is in the dictionaries:
2569 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2571 DictEntry = NewVirtualDictEntry(Group, Elem);
2573 gdcmBinEntry *NewEntry = new gdcmBinEntry(DictEntry);
2576 dbg.Verbose(1, "gdcmDocument::NewBinEntryByNumber",
2577 "failed to allocate gdcmBinEntry");
2584 * \brief Generate a free TagKey i.e. a TagKey that is not present
2585 * in the TagHt dictionary.
2586 * @param group The generated tag must belong to this group.
2587 * @return The element of tag with given group which is fee.
2589 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2591 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2593 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2594 if (tagHT.count(key) == 0)
2602 * \brief Searches both the public and the shadow dictionary (when they
2603 * exist) for the presence of the DictEntry with given name.
2604 * The public dictionary has precedence on the shadow one.
2605 * @param Name name of the searched DictEntry
2606 * @return Corresponding DictEntry when it exists, NULL otherwise.
2608 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2610 gdcmDictEntry *found = (gdcmDictEntry *)0;
2611 if (!RefPubDict && !RefShaDict)
2613 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2614 "we SHOULD have a default dictionary");
2618 found = RefPubDict->GetDictEntryByName(Name);
2624 found = RefShaDict->GetDictEntryByName(Name);
2632 * \brief Searches both the public and the shadow dictionary (when they
2633 * exist) for the presence of the DictEntry with given
2634 * group and element. The public dictionary has precedence on the
2636 * @param group group number of the searched DictEntry
2637 * @param element element number of the searched DictEntry
2638 * @return Corresponding DictEntry when it exists, NULL otherwise.
2640 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2642 gdcmDictEntry *found = (gdcmDictEntry *)0;
2643 if (!RefPubDict && !RefShaDict)
2645 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2646 "we SHOULD have a default dictionary");
2650 found = RefPubDict->GetDictEntryByNumber(group, element);
2656 found = RefShaDict->GetDictEntryByNumber(group, element);
2665 * \ingroup gdcmDocument
2666 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2667 * \ No other way so 'skip' the Data
2670 void gdcmDocument::Parse7FE0 (void) {
2672 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2676 std::string Transfer = ((gdcmValEntry *)Element)->GetValue();
2677 if (Transfer == UI1_2_840_10008_1_2 )
2679 if ( Transfer == UI1_2_840_10008_1_2_1 )
2681 if ( Transfer == UI1_2_840_10008_1_2_2 ) //1.2.2 ??? A verifier !
2683 if ( Transfer == UI1_2_840_10008_1_2_1_99 )
2687 std::string str_nb=GetEntryByNumber(0x0028,0x0100);
2688 if (str_nb == GDCM_UNFOUND ) {
2691 nb = atoi(str_nb.c_str() );
2692 if (nb == 12) nb =16;
2695 guint16 ItemTagGr,ItemTagEl;
2699 // -------------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2701 if ( Transfer != UI1_1_2_840_10008_1_2_5 ) { // !RLELossLessTransferSyntax
2704 fread(&ItemTagGr,2,1,fp); //Reading (fffe):Basic Offset Table Item Tag Gr
2705 fread(&ItemTagEl,2,1,fp); //Reading (e000):Basic Offset Table Item Tag El
2707 ItemTagGr=SwapShort(ItemTagGr);
2708 ItemTagEl=SwapShort(ItemTagEl);
2710 printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
2711 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2715 ln=SwapLong(ln); // Basic Offset Table Item Length
2716 printf("at %x : Basic Offset Table Item Length (\?\?) %d x(%08x)\n",
2717 (unsigned)ftellRes,ln,ln);
2719 // What is it used for ??
2720 char * BasicOffsetTableItemValue= new char[ln+1];
2721 fread(BasicOffsetTableItemValue,ln,1,fp);
2723 for (int i=0;i<ln;i+=4){
2724 a=str2num(&BasicOffsetTableItemValue[i],guint32);
2725 printf(" x(%08x) %d\n",a,a);
2730 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2731 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2733 ItemTagGr=SwapShort(ItemTagGr);
2734 ItemTagEl=SwapShort(ItemTagEl);
2736 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2737 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2739 while ( ( ItemTagGr==0xfffe) && (ItemTagEl!=0xe0dd) ) { // Parse fragments
2744 ln=SwapLong(ln); // length
2745 printf(" at %x : fragment length %d x(%08x)\n",
2746 (unsigned)ftellRes, ln,ln);
2748 // ------------------------
2749 fseek(fp,ln,SEEK_CUR); // skipping (not reading) fragment pixels
2750 // ------------------------
2753 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2754 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2756 ItemTagGr=SwapShort(ItemTagGr);
2757 ItemTagEl=SwapShort(ItemTagEl);
2759 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2760 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2766 long RleSegmentLength[15],fragmentLength;
2767 guint32 nbRleSegments;
2768 guint32 RleSegmentOffsetTable[15];
2770 // Basic Offset Table with Item Value
2772 fread(&ItemTagGr,2,1,fp); //Reading (fffe):Basic Offset Table Item Tag Gr
2773 fread(&ItemTagEl,2,1,fp); //Reading (e000):Basic Offset Table Item Tag El
2775 ItemTagGr=SwapShort(ItemTagGr);
2776 ItemTagEl=SwapShort(ItemTagEl);
2778 printf ("at %x : ItemTag (should be fffe,e000): %04x,%04x\n",
2779 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2784 ln=SwapLong(ln); // Basic Offset Table Item Length
2785 printf("at %x : Basic Offset Table Item Length (\?\?) %d x(%08x)\n",
2786 (unsigned)ftellRes,ln,ln);
2788 // What is it used for ??
2789 char * BasicOffsetTableItemValue= new char[ln+1];
2790 fread(BasicOffsetTableItemValue,ln,1,fp);
2792 for (int i=0;i<ln;i+=4){
2793 a=str2num(&BasicOffsetTableItemValue[i],guint32);
2794 printf(" x(%08x) %d\n",a,a);
2799 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2800 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2802 ItemTagGr=SwapShort(ItemTagGr);
2803 ItemTagEl=SwapShort(ItemTagEl);
2805 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2806 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2808 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2809 while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) {
2810 // Parse fragments of the current Fragment (Frame)
2812 fread(&fragmentLength,4,1,fp);
2814 fragmentLength=SwapLong(fragmentLength); // length
2815 printf(" at %x : 'fragment' length %d x(%08x)\n",
2816 (unsigned)ftellRes, (unsigned)fragmentLength,(unsigned)fragmentLength);
2818 //------------------ scanning (not reading) fragment pixels
2820 fread(&nbRleSegments,4,1,fp); // Reading : Number of RLE Segments
2822 nbRleSegments=SwapLong(nbRleSegments);
2823 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2825 for(int k=1; k<=15; k++) { // Reading RLE Segments Offset Table
2827 fread(&RleSegmentOffsetTable[k],4,1,fp);
2829 RleSegmentOffsetTable[k]=SwapLong(RleSegmentOffsetTable[k]);
2830 printf(" at : %x Offset Segment %d : %d (%x)\n",
2831 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2832 RleSegmentOffsetTable[k]);
2835 if (nbRleSegments>1) { // skipping (not reading) RLE Segments
2836 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2837 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2838 - RleSegmentOffsetTable[k];
2840 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2841 k,(unsigned)RleSegmentLength[k],(unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2842 fseek(fp,RleSegmentLength[k],SEEK_CUR);
2845 RleSegmentLength[nbRleSegments]= fragmentLength
2846 - RleSegmentOffsetTable[nbRleSegments];
2848 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2849 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2850 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2852 fseek(fp,RleSegmentLength[nbRleSegments],SEEK_CUR);
2854 // ------------------ end of scanning fragment pixels
2857 fread(&ItemTagGr,2,1,fp); // Reading (fffe) : Item Tag Gr
2858 fread(&ItemTagEl,2,1,fp); // Reading (e000) : Item Tag El
2860 ItemTagGr=SwapShort(ItemTagGr);
2861 ItemTagEl=SwapShort(ItemTagEl);
2863 printf ("at %x : ItemTag (should be fffe,e000 or e0dd): %04x,%04x\n",
2864 (unsigned)ftellRes,ItemTagGr,ItemTagEl );
2871 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2872 * \warning Does NOT work with ACR-NEMA files
2873 * \todo Find a trick to solve the pb (use RET fields ?)
2875 * @return true if 'smaller'
2877 bool gdcmDocument::operator<(gdcmDocument &document){
2881 s1=this->GetEntryByNumber(0x0010,0x0010);
2882 s2=document.GetEntryByNumber(0x0010,0x0010);
2890 s1=this->GetEntryByNumber(0x0010,0x0020);
2891 s2=document.GetEntryByNumber(0x0010,0x0020);
2898 // Study Instance UID
2899 s1=this->GetEntryByNumber(0x0020,0x000d);
2900 s2=document.GetEntryByNumber(0x0020,0x000d);
2907 // Serie Instance UID
2908 s1=this->GetEntryByNumber(0x0020,0x000e);
2909 s2=document.GetEntryByNumber(0x0020,0x000e);
2921 //-----------------------------------------------------------------------------