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 // Implicit VR Little Endian
26 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
27 // Explicit VR Little Endian
28 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
29 // Deflated Explicit VR Little Endian
30 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
31 // Explicit VR Big Endian
32 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
33 // JPEG Baseline (Process 1)
34 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
35 // JPEG Extended (Process 2 & 4)
36 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
37 // JPEG Extended (Process 3 & 5)
38 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
39 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
40 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
41 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
42 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
43 // JPEG Lossless, Non-Hierarchical (Process 14)
44 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
45 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
46 // [Selection Value 1])
47 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
49 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
51 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
53 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
55 #define str2num(str, typeNum) *((typeNum *)(str))
57 //-----------------------------------------------------------------------------
58 // Refer to gdcmDocument::CheckSwap()
59 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
61 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
62 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
64 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
66 //-----------------------------------------------------------------------------
67 // Constructor / Destructor
71 * @param inFilename file to be opened for parsing
72 * @param exception_on_error whether we throw an exception or not
73 * @param enable_sequences = true to allow the header
74 * to be parsed *inside* the SeQuences,
75 * when they have an actual length
76 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
77 * @param ignore_shadow to allow skipping the shadow elements,
78 * to save memory space.
79 * \warning The TRUE value for this param has to be used
80 * with a FALSE value for the 'enable_sequence' param.
81 * ('public elements' may be embedded in 'shadow Sequences')
83 gdcmDocument::gdcmDocument(const char *inFilename,
84 bool exception_on_error,
85 bool enable_sequences,
87 : gdcmElementSet(-1) {
88 enableSequences=enable_sequences;
89 ignoreShadow =ignore_shadow;
91 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
92 filename = inFilename;
95 if ( !OpenFile(exception_on_error))
98 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
102 // return false; // to go on compiling
104 fseek(fp,0L,SEEK_END);
105 long lgt = ftell(fp);
109 long beg = ftell(fp);
114 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
117 // --------------------------------------------------------------
118 // Special Patch to allow gdcm to read ACR-LibIDO formated images
120 // if recognition code tells us we deal with a LibIDO image
121 // we switch lineNumber and columnNumber
124 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
125 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
126 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
127 // with "little-endian strings"
129 filetype = gdcmACR_LIBIDO;
130 std::string rows = GetEntryByNumber(0x0028, 0x0010);
131 std::string columns = GetEntryByNumber(0x0028, 0x0011);
132 SetEntryByNumber(columns, 0x0028, 0x0010);
133 SetEntryByNumber(rows , 0x0028, 0x0011);
135 // ----------------- End of Special Patch ----------------
137 printLevel = 1; // 'Medium' print level by default
142 * @param exception_on_error
144 gdcmDocument::gdcmDocument(bool exception_on_error)
145 :gdcmElementSet(-1) {
146 (void)exception_on_error;
149 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
152 printLevel = 1; // 'Medium' print level by default
156 * \brief Canonical destructor.
158 gdcmDocument::~gdcmDocument (void) {
163 //-----------------------------------------------------------------------------
169 * \brief Prints The Dict Entries of THE public Dicom Dictionary
172 void gdcmDocument::PrintPubDict(std::ostream & os) {
173 RefPubDict->Print(os);
177 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
180 void gdcmDocument::PrintShaDict(std::ostream & os) {
181 RefShaDict->Print(os);
184 //-----------------------------------------------------------------------------
187 * \brief Get the public dictionary used
189 gdcmDict *gdcmDocument::GetPubDict(void) {
194 * \brief Get the shadow dictionary used
196 gdcmDict *gdcmDocument::GetShaDict(void) {
201 * \brief Set the shadow dictionary used
202 * \param dict dictionary to use in shadow
204 bool gdcmDocument::SetShaDict(gdcmDict *dict){
210 * \brief Set the shadow dictionary used
211 * \param dictName name of the dictionary to use in shadow
213 bool gdcmDocument::SetShaDict(DictKey dictName){
214 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
219 * \brief This predicate, based on hopefully reasonable heuristics,
220 * decides whether or not the current gdcmDocument was properly parsed
221 * and contains the mandatory information for being considered as
222 * a well formed and usable Dicom/Acr File.
223 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
226 bool gdcmDocument::IsReadable(void) {
227 if(filetype==gdcmUnknown) {
228 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
231 if(!tagHT.empty()<=0) {
232 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
241 * \brief Internal function that checks whether the Transfer Syntax given
242 * as argument is the one present in the current document.
243 * @param SyntaxToCheck The transfert syntax we need to check against.
244 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
245 * the current document. False either when the document contains
246 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
248 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
250 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
254 // The entry might be present but not loaded (parsing and loading
255 // happen at differente stages): try loading and proceed with check...
256 LoadDocEntrySafe(Entry);
257 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
259 std::string Transfer = ValEntry->GetValue();
260 // The actual transfer (as read from disk) might be padded. We
261 // first need to remove the potential padding. We can make the
262 // weak assumption that padding was not executed with digits...
263 while ( ! isdigit(Transfer[Transfer.length()-1]) )
265 Transfer.erase(Transfer.length()-1, 1);
267 if ( Transfer == SyntaxToCheck )
274 * \brief Determines if the Transfer Syntax of the present document
275 * corresponds to a Implicit Value Representation of
277 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
278 * @return True when ImplicitVRLittleEndian found. False in all other cases.
280 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
282 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
286 * \brief Determines if the Transfer Syntax was already encountered
287 * and if it corresponds to a ExplicitVRLittleEndian one.
288 * @return True when ExplicitVRLittleEndian found. False in all other cases.
290 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
292 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
296 * \brief Determines if the Transfer Syntax was already encountered
297 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
298 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
300 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
302 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
306 * \brief Determines if the Transfer Syntax was already encountered
307 * and if it corresponds to a Explicit VR Big Endian one.
308 * @return True when big endian found. False in all other cases.
310 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
312 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
316 * \brief Determines if the Transfer Syntax was already encountered
317 * and if it corresponds to a JPEGBaseLineProcess1 one.
318 * @return True when JPEGBaseLineProcess1found. False in all other cases.
320 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
322 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
326 * \brief Determines if the Transfer Syntax was already encountered
327 * and if it corresponds to a JPEGExtendedProcess2-4 one.
328 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
330 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
332 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
336 * \brief Determines if the Transfer Syntax was already encountered
337 * and if it corresponds to a JPEGExtendeProcess3-5 one.
338 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
340 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
342 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
346 * \brief Determines if the Transfer Syntax was already encountered
347 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
348 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
351 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
353 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
357 * \brief Determines if the Transfer Syntax was already encountered
358 * and if it corresponds to a RLE Lossless one.
359 * @return True when RLE Lossless found. False in all
362 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
364 return IsGivenTransferSyntax(UI1_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)
375 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
376 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
377 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90) );
381 * \brief Determines if the Transfer Syntax was already encountered
382 * and if it corresponds to a JPEG2000 one
383 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
386 bool gdcmDocument::IsJPEG2000(void)
388 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70)
389 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90) );
393 * \brief Predicate for dicom version 3 file.
394 * @return True when the file is a dicom version 3.
396 bool gdcmDocument::IsDicomV3(void) {
397 // Checking if Transfert Syntax exists is enough
398 // Anyway, it's to late check if the 'Preamble' was found ...
399 // And ... would it be a rich idea to check ?
400 // (some 'no Preamble' DICOM images exist !)
401 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
405 * \brief returns the File Type
406 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
407 * @return the FileType code
409 FileType gdcmDocument::GetFileType(void) {
414 * \brief opens the file
415 * @param exception_on_error
418 FILE *gdcmDocument::OpenFile(bool exception_on_error)
421 fp=fopen(filename.c_str(),"rb");
425 if(exception_on_error)
426 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
429 std::cout <<"gdcmDocument::OpenFile cannot open file: "
430 << filename.c_str() << std::endl;
431 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
440 fread(&zero, (size_t)2, (size_t)1, fp);
442 //ACR -- or DICOM with no Preamble --
443 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
447 fseek(fp, 126L, SEEK_CUR);
449 fread(dicm, (size_t)4, (size_t)1, fp);
450 if( memcmp(dicm, "DICM", 4) == 0 )
454 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
457 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
463 * \brief closes the file
464 * @return TRUE if the close was successfull
466 bool gdcmDocument::CloseFile(void) {
467 int closed = fclose(fp);
475 * \brief Writes in a file all the Header Entries (Dicom Elements)
476 * of the Chained List
477 * @param fp file pointer on an already open file
478 * @param type Type of the File to be written
479 * (ACR-NEMA, ExplicitVR, ImplicitVR)
480 * \return Always true.
482 bool gdcmDocument::Write(FILE *fp, FileType type) {
485 /// The stuff will have to be rewritten using the SeQuence based
486 /// tree-like stucture instead of the chained list .
487 /// (so we shall remove the Group*HT from the gdcmDocument)
491 /// \todo move the following lines (and a lot of others, to be written)
492 /// to a future function CheckAndCorrectHeader
496 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
497 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
498 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
500 /// a moins de se livrer a un tres complique ajout des champs manquants.
501 /// faire un CheckAndCorrectHeader (?)
503 if (type == gdcmImplicitVR)
505 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
506 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
508 /// \todo Refer to standards on page 21, chapter 6.2
509 /// "Value representation": values with a VR of UI shall be
510 /// padded with a single trailing null
511 /// Dans le cas suivant on doit pader manuellement avec un 0
513 SetEntryLengthByNumber(18, 0x0002, 0x0010);
516 if (type == gdcmExplicitVR)
518 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
519 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
521 /// \todo Refer to standards on page 21, chapter 6.2
522 /// "Value representation": values with a VR of UI shall be
523 /// padded with a single trailing null
524 /// Dans le cas suivant on doit pader manuellement avec un 0
526 SetEntryLengthByNumber(20, 0x0002, 0x0010);
530 * \todo rewrite later, if really usefull
532 * --> Warning : un-updated odd groups lengths can causes pb
533 * --> (xmedcon breaks)
534 * --> to be re- written with future org.
536 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
537 * UpdateGroupLength(false,type);
539 * UpdateGroupLength(true,ACR);
542 WriteEntries(fp,type);
547 * \brief Modifies the value of a given Header Entry (Dicom Element)
548 * when it exists. Create it with the given value when unexistant.
549 * @param Value (string) Value to be set
550 * @param Group Group number of the Entry
551 * @param Elem Element number of the Entry
552 * \return pointer to the modified/created Header Entry (NULL when creation
556 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
562 a = GetDocEntryByNumber( Group, Elem);
564 a =NewDocEntryByNumber(Group, Elem);
567 b = new gdcmValEntry(a);
570 SetEntryByNumber(Value, Group, Elem);
572 return (gdcmValEntry*)b;
577 * \brief Modifies the value of a given Header Entry (Dicom Element)
578 * when it exists. Create it with the given value when unexistant.
579 * @param voidArea (binary) value to be set
580 * @param Group Group number of the Entry
581 * @param Elem Element number of the Entry
582 * \return pointer to the modified/created Header Entry (NULL when creation
587 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
594 a = GetDocEntryByNumber( Group, Elem);
596 a =NewBinEntryByNumber(Group, Elem);
599 b = new gdcmBinEntry(a);
602 SetEntryByNumber(voidArea, lgth, Group, Elem);
603 b->SetVoidArea(voidArea);
604 return (gdcmBinEntry*)b;
610 * \brief Set a new value if the invoked element exists
611 * Seems to be useless !!!
612 * @param Value new element value
613 * @param Group group number of the Entry
614 * @param Elem element number of the Entry
617 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
619 std::string v = Value;
620 SetEntryByNumber(v, Group, Elem);
624 //-----------------------------------------------------------------------------
628 * \brief Checks if a given Dicom Element exists within the H table
629 * @param group Group number of the searched Dicom Element
630 * @param element Element number of the searched Dicom Element
631 * @return number of occurences
633 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
634 std::string key = gdcmDictEntry::TranslateToKey(group, element );
635 return (tagHT.count(key));
639 * \brief Searches within Header Entries (Dicom Elements) parsed with
640 * the public and private dictionaries
641 * for the element value of a given tag.
642 * \warning Don't use any longer : use GetPubEntryByName
643 * @param tagName name of the searched element.
644 * @return Corresponding element value when it exists,
645 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
647 std::string gdcmDocument::GetEntryByName(std::string tagName) {
648 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
649 if( dictEntry == NULL)
652 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
656 * \brief Searches within Header Entries (Dicom Elements) parsed with
657 * the public and private dictionaries
658 * for the element value representation of a given tag.
660 * Obtaining the VR (Value Representation) might be needed by caller
661 * to convert the string typed content to caller's native type
662 * (think of C++ vs Python). The VR is actually of a higher level
663 * of semantics than just the native C++ type.
664 * @param tagName name of the searched element.
665 * @return Corresponding element value representation when it exists,
666 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
668 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
669 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
670 if( dictEntry == NULL)
673 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
674 dictEntry->GetElement());
675 return elem->GetVR();
680 * \brief Searches within Header Entries (Dicom Elements) parsed with
681 * the public and private dictionaries
682 * for the element value representation of a given tag.
683 * @param group Group number of the searched tag.
684 * @param element Element number of the searched tag.
685 * @return Corresponding element value representation when it exists,
686 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
688 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
689 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
690 if ( ! tagHT.count(key))
692 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
696 * \brief Searches within Header Entries (Dicom Elements) parsed with
697 * the public and private dictionaries
698 * for the element value representation of a given tag..
700 * Obtaining the VR (Value Representation) might be needed by caller
701 * to convert the string typed content to caller's native type
702 * (think of C++ vs Python). The VR is actually of a higher level
703 * of semantics than just the native C++ type.
704 * @param group Group number of the searched tag.
705 * @param element Element number of the searched tag.
706 * @return Corresponding element value representation when it exists,
707 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
709 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
710 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
713 return elem->GetVR();
717 * \brief Searches within Header Entries (Dicom Elements) parsed with
718 * the public and private dictionaries
719 * for the value length of a given tag..
720 * @param group Group number of the searched tag.
721 * @param element Element number of the searched tag.
722 * @return Corresponding element length; -2 if not found
724 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
725 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
728 return elem->GetLength();
731 * \brief Sets the value (string) of the Header Entry (Dicom Element)
732 * @param content string value of the Dicom Element
733 * @param tagName name of the searched Dicom Element.
734 * @return true when found
736 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
737 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
738 if( dictEntry == NULL)
741 return(SetEntryByNumber(content,dictEntry->GetGroup(),
742 dictEntry->GetElement()));
746 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
747 * through it's (group, element) and modifies it's content with
749 * @param content new value (string) to substitute with
750 * @param group group number of the Dicom Element to modify
751 * @param element element number of the Dicom Element to modify
753 bool gdcmDocument::SetEntryByNumber(std::string content,
757 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
758 if ( ! tagHT.count(key))
760 int l = content.length();
761 if(l%2) // Non even length are padded with a space (020H).
764 content = content + '\0';
768 a = (gdcmValEntry *)tagHT[key];
770 a->SetValue(content);
772 VRKey vr = a->GetVR();
775 if( (vr == "US") || (vr == "SS") )
777 else if( (vr == "UL") || (vr == "SL") )
787 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
788 * through it's (group, element) and modifies it's content with
790 * @param content new value (void *) to substitute with
791 * @param group group number of the Dicom Element to modify
792 * @param element element number of the Dicom Element to modify
794 bool gdcmDocument::SetEntryByNumber(void *content,
799 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
800 if ( ! tagHT.count(key))
803 /* Hope Binray field length is never wrong
804 if(lgth%2) // Non even length are padded with a space (020H).
807 //content = content + '\0'; // fing a trick to enlarge a binary field?
811 a = (gdcmBinEntry *)tagHT[key];
812 a->SetVoidArea(content);
813 //a->SetLength(lgth); // ???
818 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
819 * in the PubDocEntrySet of this instance
820 * through it's (group, element) and modifies it's length with
822 * \warning Use with extreme caution.
823 * @param l new length to substitute with
824 * @param group group number of the Entry to modify
825 * @param element element number of the Entry to modify
826 * @return true on success, false otherwise.
828 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
832 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
833 if ( ! tagHT.count(key))
835 if (l%2) l++; // length must be even
836 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
842 * \brief Gets (from Header) the offset of a 'non string' element value
843 * (LoadElementValues has already be executed)
844 * @param Group group number of the Entry
845 * @param Elem element number of the Entry
846 * @return File Offset of the Element Value
848 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
850 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
853 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
854 "failed to Locate gdcmDocEntry");
857 return Entry->GetOffset();
861 * \brief Gets (from Header) a 'non string' element value
862 * (LoadElementValues has already be executed)
863 * @param Group group number of the Entry
864 * @param Elem element number of the Entry
865 * @return Pointer to the 'non string' area
867 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
869 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
872 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
873 "failed to Locate gdcmDocEntry");
876 return ((gdcmBinEntry *)Entry)->GetVoidArea();
880 * \brief Loads (from disk) the element content
881 * when a string is not suitable
882 * @param Group group number of the Entry
883 * @param Elem element number of the Entry
885 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
887 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
890 size_t o =(size_t)Element->GetOffset();
891 fseek(fp, o, SEEK_SET);
892 size_t l=Element->GetLength();
893 char* a = new char[l];
897 SetEntryVoidAreaByNumber(a, Group, Elem);
898 /// \todo check the result
899 size_t l2 = fread(a, 1, l ,fp);
910 * \brief Sets a 'non string' value to a given Dicom Element
912 * @param group Group number of the searched Dicom Element
913 * @param element Element number of the searched Dicom Element
916 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
920 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
921 if ( ! tagHT.count(key))
923 // This was for multimap ?
924 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
930 * \brief Update the entries with the shadow dictionary.
931 * Only non even entries are analyzed
933 void gdcmDocument::UpdateShaEntries(void) {
934 gdcmDictEntry *entry;
937 /// \todo TODO : still any use to explore recursively the whole structure?
939 for(ListTag::iterator it=listEntries.begin();
940 it!=listEntries.end();
943 // Odd group => from public dictionary
944 if((*it)->GetGroup()%2==0)
947 // Peer group => search the corresponding dict entry
949 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
953 if((*it)->IsImplicitVR())
958 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
960 // Set the new entry and the new value
961 (*it)->SetDictEntry(entry);
962 CheckDocEntryVR(*it,vr);
964 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
969 // Remove precedent value transformation
970 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
977 * \brief Searches within the Header Entries for a Dicom Element of
979 * @param tagName name of the searched Dicom Element.
980 * @return Corresponding Dicom Element when it exists, and NULL
983 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
984 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
985 if( dictEntry == NULL)
988 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
992 * \brief retrieves a Dicom Element (the first one) using (group, element)
993 * \warning (group, element) IS NOT an identifier inside the Dicom Header
994 * if you think it's NOT UNIQUE, check the count number
995 * and use iterators to retrieve ALL the Dicoms Elements within
996 * a given couple (group, element)
997 * @param group Group number of the searched Dicom Element
998 * @param element Element number of the searched Dicom Element
1001 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1003 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1004 if ( ! tagHT.count(key))
1006 return tagHT.find(key)->second;
1010 * \brief Loads the element while preserving the current
1011 * underlying file position indicator as opposed to
1012 * to LoadDocEntry that modifies it.
1013 * @param entry Header Entry whose value shall be loaded.
1016 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1017 long PositionOnEntry = ftell(fp);
1018 LoadDocEntry(entry);
1019 fseek(fp, PositionOnEntry, SEEK_SET);
1024 * \brief Writes in a file (according to the requested format)
1025 * the group, the element, the value representation and the length
1026 * of a single gdcmDocEntry passed as argument.
1027 * @param tag pointer on the gdcmDocEntry to be written
1028 * @param _fp already open file pointer
1029 * @param type type of the File to be written
1031 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
1035 guint16 group = tag->GetGroup();
1036 VRKey vr = tag->GetVR();
1037 guint16 el = tag->GetElement();
1038 guint32 lgr = tag->GetReadLength();
1040 if ( (group == 0xfffe) && (el == 0x0000) )
1041 // Fix in order to make some MR PHILIPS images e-film readable
1042 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1043 // we just *always* ignore spurious fffe|0000 tag !
1046 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1047 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1049 if ( type == gdcmExplicitVR ) {
1051 // Special case of delimiters:
1052 if (group == 0xfffe) {
1053 // Delimiters have NO Value Representation and have NO length.
1054 // Hence we skip writing the VR and length and we pad by writing
1058 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1063 guint16 shortLgr = lgr;
1064 if (vr == "unkn") { // Unknown was 'written'
1065 // deal with Little Endian
1066 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1067 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1069 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1070 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1072 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1073 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1075 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1081 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1086 * \brief Writes in a file (according to the requested format)
1087 * the value of a single gdcmDocEntry passed as argument.
1088 * @param tag Pointer on the gdcmDocEntry to be written
1089 * @param _fp Already open file pointer
1090 * @param type type of the File to be written
1093 // \todo TODO : to be re -written recursively !
1094 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1097 guint16 group = tag->GetGroup();
1098 VRKey vr = tag->GetVR();
1099 guint32 lgr = tag->GetReadLength();
1102 // SeQuences have no value:
1104 if (group == 0xfffe)
1105 // Delimiters have no associated value:
1108 //--------------------------------
1110 // FIXME :right now, both value and voidArea belong to gdcmValue
1112 // -------------------------------
1114 // if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) ) {
1116 gdcmBinEntry *BinEntry= (gdcmBinEntry *)tag;;
1117 voidArea = BinEntry->GetVoidArea();
1118 if (voidArea != NULL)
1119 { // there is a 'non string' LUT, overlay, etc
1120 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1125 if (vr == "US" || vr == "SS")
1127 // some 'Short integer' fields may be mulivaluated
1128 // each single value is separated from the next one by '\'
1129 // we split the string and write each value as a short int
1130 std::vector<std::string> tokens;
1131 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1132 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1133 for (unsigned int i=0; i<tokens.size();i++)
1135 guint16 val_uint16 = atoi(tokens[i].c_str());
1136 void *ptr = &val_uint16;
1137 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1142 if (vr == "UL" || vr == "SL")
1144 // Some 'Integer' fields may be multivaluated (multiple instances
1145 // of integers). But each single integer value is separated from the
1146 // next one by '\' (backslash character). Hence we split the string
1147 // along the '\' and write each value as an int:
1148 std::vector<std::string> tokens;
1149 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1150 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1151 for (unsigned int i=0; i<tokens.size();i++)
1153 guint32 val_uint32 = atoi(tokens[i].c_str());
1154 void *ptr = &val_uint32;
1155 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1160 fwrite (((gdcmValEntry *)tag)->GetValue().c_str(),
1161 (size_t)lgr ,(size_t)1, _fp); // Elem value
1165 * \brief Writes in a file (according to the requested format)
1166 * a single gdcmDocEntry passed as argument.
1167 * \sa WriteEntryValue, WriteEntryTagVRLength.
1168 * @param tag Pointer on the gdcmDocEntry to be written
1169 * @param _fp Already open file pointer
1170 * @param type type of the File to be written
1173 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1175 guint32 length = tag->GetLength();
1177 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(tag) )
1179 // The value of a tag MUST (see the DICOM norm) be an odd number of
1180 // bytes. When this is not the case, pad with an additional byte:
1182 ValEntry->SetValue(ValEntry->GetValue()+"\0");
1183 ValEntry->SetLength(ValEntry->GetReadLength()+1);
1185 WriteEntryTagVRLength(ValEntry, _fp, type);
1186 WriteEntryValue(ValEntry, _fp, type);
1190 if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) )
1192 /// \todo FIXME : when voidArea belong to gdcmBinEntry only, fix
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:
1199 tag->SetValue(tag->GetValue()+"\0");
1200 tag->SetLength(tag->GetReadLength()+1);
1203 WriteEntryTagVRLength(tag, _fp, type);
1204 WriteEntryValue(tag, _fp, type);
1210 * \brief writes on disc according to the requested format
1211 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1212 * using the Chained List
1213 * \warning does NOT add the missing elements in the header :
1214 * it's up to the user doing it !
1215 * (function CheckHeaderCoherence to be written)
1216 * \warning DON'T try, right now, to write a DICOM image
1217 * from an ACR Header (meta elements will be missing!)
1218 * @param type type of the File to be written
1219 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1220 * @param _fp already open file pointer
1223 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1225 /// \todo FIXME : explore recursively the whole structure...
1226 /// \todo (?) check write failures (after *each* fwrite)
1228 dbg.Verbose(0, "gdcmDocument::WriteEntries: entering.");
1229 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
1231 gdcmDocEntry * entry = it->second;
1234 if ( type == gdcmACR ){
1235 if (entry->GetGroup() < 0x0008)
1236 // Ignore pure DICOM V3 groups
1238 if (entry->GetGroup() %2)
1239 // Ignore the "shadow" groups
1241 if (entry->GetVR() == "SQ" ) // ignore Sequences
1244 if (! WriteEntry(entry, _fp, type) ) {
1245 dbg.Verbose(0, "gdcmDocument::WriteEntries: write failure.");
1254 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1256 * @return The properly swaped 32 bits integer.
1258 guint32 gdcmDocument::SwapLong(guint32 a) {
1263 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1264 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1268 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1272 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1275 std::cout << "swapCode= " << sw << std::endl;
1276 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1283 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1285 * @return The properly unswaped 32 bits integer.
1287 guint32 gdcmDocument::UnswapLong(guint32 a) {
1288 return (SwapLong(a));
1292 * \brief Swaps the bytes so they agree with the processor order
1293 * @return The properly swaped 16 bits integer.
1295 guint16 gdcmDocument::SwapShort(guint16 a) {
1296 if ( (sw==4321) || (sw==2143) )
1297 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1302 * \brief Unswaps the bytes so they agree with the processor order
1303 * @return The properly unswaped 16 bits integer.
1305 guint16 gdcmDocument::UnswapShort(guint16 a) {
1306 return (SwapShort(a));
1309 //-----------------------------------------------------------------------------
1313 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1314 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1317 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1319 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1327 depth = set->GetDepthLevel();
1330 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1333 NewDocEntry = ReadNextDocEntry( );
1337 vr = NewDocEntry->GetVR();
1340 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1343 vl= new gdcmValEntry(NewDocEntry->GetDictEntry());
1344 vl->Copy(NewDocEntry);
1345 vl->SetDepthLevel(depth);
1348 if (/*!delim_mode && */vl->isItemDelimitor())
1350 if ( !delim_mode && ftell(fp)-offset >= l_max)
1357 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1359 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1360 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1361 "nor BinEntry. Probably unknown VR.");
1364 ////// BinEntry or UNKOWN VR:
1365 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1366 bn->Copy(NewDocEntry);
1371 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1372 NewDocEntry->GetElement() == 0x0010 )
1374 if (NewDocEntry->GetLength()==0xffffffff)
1375 // Broken US.3405.1.dcm
1376 Parse7FE0(); // to skip the pixels
1377 // (multipart JPEG/RLE are trouble makers)
1381 // to be sure we are at the beginning
1382 SkipToNextDocEntry(NewDocEntry);
1383 l = NewDocEntry->GetFullLength();
1385 } else { // VR = "SQ"
1387 l=NewDocEntry->GetReadLength();
1388 if (l != 0) // don't mess the delim_mode for zero-length sequence
1389 if (l == 0xffffffff)
1393 // no other way to create it ...
1394 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1395 set->GetDepthLevel());
1396 sq->Copy(NewDocEntry);
1397 sq->SetDelimitorMode(delim_mode);
1398 sq->SetDepthLevel(depth);
1401 { // Don't try to parse zero-length sequences
1402 long lgt = ParseSQ( sq,
1403 NewDocEntry->GetOffset(),
1406 // FIXME : on en fait quoi, de lgt ?
1408 if ( !delim_mode && ftell(fp)-offset >= l_max)
1419 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1420 * @return parsed length for this level
1422 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1423 long offset, long l_max, bool delim_mode)
1425 int SQItemNumber = 0;
1427 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1431 int depth = set->GetDepthLevel();
1434 NewDocEntry = ReadNextDocEntry();
1436 if (NewDocEntry->isSequenceDelimitor()) {
1437 /// \todo add the Sequence Delimitor
1438 /// \todo find the trick to put it properly !
1439 set->SetSequenceDelimitationItem(NewDocEntry);
1443 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1447 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1448 itemSQ->AddEntry(NewDocEntry);
1449 /// \todo no value, no voidArea. Think of it while printing !
1450 l= NewDocEntry->GetReadLength();
1452 if (l == 0xffffffff)
1457 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1459 set->AddEntry(itemSQ,SQItemNumber);
1461 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1465 lgth = ftell(fp) - offset;
1470 * \brief Loads the element content if its length doesn't exceed
1471 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1472 * @param Entry Header Entry (Dicom Element) to be dealt with
1474 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry) {
1476 guint16 group = Entry->GetGroup();
1477 std::string vr= Entry->GetVR();
1478 guint32 length = Entry->GetLength();
1480 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1482 // A SeQuence "contains" a set of Elements.
1483 // (fffe e000) tells us an Element is beginning
1484 // (fffe e00d) tells us an Element just ended
1485 // (fffe e0dd) tells us the current SeQuence just ended
1486 if( group == 0xfffe ) {
1487 // NO more value field for SQ !
1488 //Entry->SetValue("gdcm::Skipped");
1489 // appel recursif de Load Value
1490 // (meme pb que pour le parsing)
1494 // When the length is zero things are easy:
1495 if ( length == 0 ) {
1496 ((gdcmValEntry *)Entry)->SetValue("");
1500 // The elements whose length is bigger than the specified upper bound
1501 // are not loaded. Instead we leave a short notice of the offset of
1502 // the element content and it's length.
1503 if (length > MaxSizeLoadEntry) {
1504 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1506 std::ostringstream s;
1507 s << "gdcm::NotLoaded.";
1508 s << " Address:" << (long)Entry->GetOffset();
1509 s << " Length:" << Entry->GetLength();
1510 s << " x(" << std::hex << Entry->GetLength() << ")";
1511 ValEntryPtr->SetValue(s.str());
1513 // to be sure we are at the end of the value ...
1514 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1519 // Any compacter code suggested (?)
1520 if ( IsDocEntryAnInteger(Entry) ) {
1522 std::ostringstream s;
1524 // When short integer(s) are expected, read and convert the following
1525 // n *two characters properly i.e. as short integers as opposed to strings.
1526 // Elements with Value Multiplicity > 1
1527 // contain a set of integers (not a single one)
1528 if (vr == "US" || vr == "SS") {
1530 NewInt = ReadInt16();
1533 for (int i=1; i < nbInt; i++) {
1535 NewInt = ReadInt16();
1540 // When integer(s) are expected, read and convert the following
1541 // n * four characters properly i.e. as integers as opposed to strings.
1542 // Elements with Value Multiplicity > 1
1543 // contain a set of integers (not a single one)
1544 else if (vr == "UL" || vr == "SL") {
1546 NewInt = ReadInt32();
1549 for (int i=1; i < nbInt; i++) {
1551 NewInt = ReadInt32();
1556 #ifdef GDCM_NO_ANSI_STRING_STREAM
1557 s << std::ends; // to avoid oddities on Solaris
1558 #endif //GDCM_NO_ANSI_STRING_STREAM
1560 ((gdcmValEntry *)Entry)->SetValue(s.str());
1564 // We need an additional byte for storing \0 that is not on disk
1565 std::string NewValue(length,0);
1566 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1567 if ( item_read != 1 ) {
1568 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1569 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1573 if( (vr == "UI") ) // Because of correspondance with the VR dic
1574 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1576 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1581 * \brief Find the value Length of the passed Header Entry
1582 * @param Entry Header Entry whose length of the value shall be loaded.
1584 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1585 guint16 element = Entry->GetElement();
1586 //guint16 group = Entry->GetGroup(); //FIXME
1587 std::string vr = Entry->GetVR();
1591 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1593 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1595 // The following reserved two bytes (see PS 3.5-2001, section
1596 // 7.1.2 Data element structure with explicit vr p27) must be
1597 // skipped before proceeding on reading the length on 4 bytes.
1598 fseek(fp, 2L, SEEK_CUR);
1599 guint32 length32 = ReadInt32();
1601 if ( (vr == "OB") && (length32 == 0xffffffff) )
1603 Entry->SetLength(FindDocEntryLengthOB());
1606 FixDocEntryFoundLength(Entry, length32);
1610 // Length is encoded on 2 bytes.
1611 length16 = ReadInt16();
1613 // We can tell the current file is encoded in big endian (like
1614 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1615 // and it's value is the one of the encoding of a big endian file.
1616 // In order to deal with such big endian encoded files, we have
1617 // (at least) two strategies:
1618 // * when we load the "Transfer Syntax" tag with value of big endian
1619 // encoding, we raise the proper flags. Then we wait for the end
1620 // of the META group (0x0002) among which is "Transfer Syntax",
1621 // before switching the swap code to big endian. We have to postpone
1622 // the switching of the swap code since the META group is fully encoded
1623 // in little endian, and big endian coding only starts at the next
1624 // group. The corresponding code can be hard to analyse and adds
1625 // many additional unnecessary tests for regular tags.
1626 // * the second strategy consists in waiting for trouble, that shall
1627 // appear when we find the first group with big endian encoding. This
1628 // is easy to detect since the length of a "Group Length" tag (the
1629 // ones with zero as element number) has to be of 4 (0x0004). When we
1630 // encounter 1024 (0x0400) chances are the encoding changed and we
1631 // found a group with big endian encoding.
1632 // We shall use this second strategy. In order to make sure that we
1633 // can interpret the presence of an apparently big endian encoded
1634 // length of a "Group Length" without committing a big mistake, we
1635 // add an additional check: we look in the already parsed elements
1636 // for the presence of a "Transfer Syntax" whose value has to be "big
1637 // endian encoding". When this is the case, chances are we have got our
1638 // hands on a big endian encoded file: we switch the swap code to
1639 // big endian and proceed...
1640 if ( (element == 0x0000) && (length16 == 0x0400) )
1642 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1644 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1649 SwitchSwapToBigEndian();
1650 // Restore the unproperly loaded values i.e. the group, the element
1651 // and the dictionary entry depending on them.
1652 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1653 guint16 CorrectElem = SwapShort(Entry->GetElement());
1654 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1658 // This correct tag is not in the dictionary. Create a new one.
1659 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1661 // FIXME this can create a memory leaks on the old entry that be
1662 // left unreferenced.
1663 Entry->SetDictEntry(NewTag);
1666 // Heuristic: well some files are really ill-formed.
1667 if ( length16 == 0xffff)
1670 //dbg.Verbose(0, "gdcmDocument::FindLength",
1671 // "Erroneous element length fixed.");
1672 // Actually, length= 0xffff means that we deal with
1673 // Unknown Sequence Length
1675 FixDocEntryFoundLength(Entry, (guint32)length16);
1680 // Either implicit VR or a non DICOM conformal (see note below) explicit
1681 // VR that ommited the VR of (at least) this element. Farts happen.
1682 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1683 // on Data elements "Implicit and Explicit VR Data Elements shall
1684 // not coexist in a Data Set and Data Sets nested within it".]
1685 // Length is on 4 bytes.
1687 FixDocEntryFoundLength(Entry, ReadInt32());
1693 * \brief Find the Value Representation of the current Dicom Element.
1696 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1698 if (filetype != gdcmExplicitVR)
1703 long PositionOnEntry = ftell(fp);
1704 // Warning: we believe this is explicit VR (Value Representation) because
1705 // we used a heuristic that found "UL" in the first tag. Alas this
1706 // doesn't guarantee that all the tags will be in explicit VR. In some
1707 // cases (see e-film filtered files) one finds implicit VR tags mixed
1708 // within an explicit VR file. Hence we make sure the present tag
1709 // is in explicit VR and try to fix things if it happens not to be
1712 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1714 if(!CheckDocEntryVR(Entry,VR))
1716 fseek(fp, PositionOnEntry, SEEK_SET);
1717 // When this element is known in the dictionary we shall use, e.g. for
1718 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1719 // dictionary entry. Still we have to flag the element as implicit since
1720 // we know now our assumption on expliciteness is not furfilled.
1722 if ( Entry->IsVRUnknown() )
1723 Entry->SetVR("Implicit");
1724 Entry->SetImplicitVR();
1729 * \brief Check the correspondance between the VR of the header entry
1730 * and the taken VR. If they are different, the header entry is
1731 * updated with the new VR.
1732 * @param Entry Header Entry to check
1733 * @param vr Dicom Value Representation
1734 * @return false if the VR is incorrect of if the VR isn't referenced
1735 * otherwise, it returns true
1737 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1739 char msg[100]; // for sprintf
1740 bool RealExplicit = true;
1742 // Assume we are reading a falsely explicit VR file i.e. we reached
1743 // a tag where we expect reading a VR but are in fact we read the
1744 // first to bytes of the length. Then we will interogate (through find)
1745 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1746 // both GCC and VC++ implementations of the STL map. Hence when the
1747 // expected VR read happens to be non-ascii characters we consider
1748 // we hit falsely explicit VR tag.
1750 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1751 RealExplicit = false;
1753 // CLEANME searching the dicom_vr at each occurence is expensive.
1754 // PostPone this test in an optional integrity check at the end
1755 // of parsing or only in debug mode.
1756 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1757 RealExplicit= false;
1759 if ( !RealExplicit )
1761 // We thought this was explicit VR, but we end up with an
1762 // implicit VR tag. Let's backtrack.
1763 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1764 Entry->GetGroup(),Entry->GetElement());
1765 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1766 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1767 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1768 Entry->GetGroup(),Entry->GetElement(),
1769 "UL","FIXME","Group Length");
1770 Entry->SetDictEntry(NewEntry);
1775 if ( Entry->IsVRUnknown() )
1777 // When not a dictionary entry, we can safely overwrite the VR.
1778 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1784 else if ( Entry->GetVR() != vr )
1786 // The VR present in the file and the dictionary disagree. We assume
1787 // the file writer knew best and use the VR of the file. Since it would
1788 // be unwise to overwrite the VR of a dictionary (since it would
1789 // compromise it's next user), we need to clone the actual DictEntry
1790 // and change the VR for the read one.
1791 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1792 Entry->GetGroup(),Entry->GetElement(),
1793 vr,"FIXME",Entry->GetName());
1794 Entry->SetDictEntry(NewEntry);
1800 * \brief Get the transformed value of the header entry. The VR value
1801 * is used to define the transformation to operate on the value
1802 * \warning NOT end user intended method !
1804 * @return Transformed entry value
1806 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1808 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1810 std::string val=((gdcmValEntry *)Entry)->GetValue();
1811 std::string vr=Entry->GetVR();
1812 guint32 length = Entry->GetLength();
1813 std::ostringstream s;
1816 // When short integer(s) are expected, read and convert the following
1817 // n * 2 bytes properly i.e. as a multivaluated strings
1818 // (each single value is separated fromthe next one by '\'
1819 // as usual for standard multivaluated filels
1820 // Elements with Value Multiplicity > 1
1821 // contain a set of short integers (not a single one)
1823 if (vr == "US" || vr == "SS")
1828 for (int i=0; i < nbInt; i++)
1832 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1833 NewInt16 = SwapShort(NewInt16);
1838 // When integer(s) are expected, read and convert the following
1839 // n * 4 bytes properly i.e. as a multivaluated strings
1840 // (each single value is separated fromthe next one by '\'
1841 // as usual for standard multivaluated filels
1842 // Elements with Value Multiplicity > 1
1843 // contain a set of integers (not a single one)
1844 else if (vr == "UL" || vr == "SL")
1849 for (int i=0; i < nbInt; i++)
1853 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1854 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1855 NewInt32=SwapLong(NewInt32);
1859 #ifdef GDCM_NO_ANSI_STRING_STREAM
1860 s << std::ends; // to avoid oddities on Solaris
1861 #endif //GDCM_NO_ANSI_STRING_STREAM
1865 return(((gdcmValEntry *)Entry)->GetValue());
1869 * \brief Get the reverse transformed value of the header entry. The VR
1870 * value is used to define the reverse transformation to operate on
1872 * \warning NOT end user intended method !
1874 * @return Reverse transformed entry value
1876 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1878 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1880 std::string vr=Entry->GetVR();
1881 std::ostringstream s;
1882 std::vector<std::string> tokens;
1884 if (vr == "US" || vr == "SS")
1888 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1889 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1890 for (unsigned int i=0; i<tokens.size();i++)
1892 NewInt16 = atoi(tokens[i].c_str());
1893 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1897 if (vr == "UL" || vr == "SL")
1901 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1902 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1903 for (unsigned int i=0; i<tokens.size();i++)
1905 NewInt32 = atoi(tokens[i].c_str());
1906 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1907 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1912 #ifdef GDCM_NO_ANSI_STRING_STREAM
1913 s << std::ends; // to avoid oddities on Solaris
1914 #endif //GDCM_NO_ANSI_STRING_STREAM
1918 return(((gdcmValEntry *)Entry)->GetValue());
1922 * \brief Skip a given Header Entry
1923 * \warning NOT end user intended method !
1926 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1928 SkipBytes(entry->GetLength());
1932 * \brief Skips to the begining of the next Header Entry
1933 * \warning NOT end user intended method !
1936 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1938 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1939 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1943 * \brief Loads the value for a a given VLEntry
1944 * \warning NOT end user intended method !
1947 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
1949 //SkipBytes(entry->GetLength());
1950 LoadDocEntry(entry);
1953 * \brief When the length of an element value is obviously wrong (because
1954 * the parser went Jabberwocky) one can hope improving things by
1955 * applying some heuristics.
1957 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1958 guint32 FoundLength)
1960 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1961 if ( FoundLength == 0xffffffff) {
1965 guint16 gr =Entry->GetGroup();
1966 guint16 el =Entry->GetElement();
1968 if (FoundLength%2) {
1969 std::ostringstream s;
1970 s << "Warning : Tag with uneven length "
1972 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1973 dbg.Verbose(0, s.str().c_str());
1976 //////// Fix for some naughty General Electric images.
1977 // Allthough not recent many such GE corrupted images are still present
1978 // on Creatis hard disks. Hence this fix shall remain when such images
1979 // are no longer in user (we are talking a few years, here)...
1980 // Note: XMedCom probably uses such a trick since it is able to read
1981 // those pesky GE images ...
1982 if (FoundLength == 13) { // Only happens for this length !
1983 if ( (Entry->GetGroup() != 0x0008)
1984 || ( (Entry->GetElement() != 0x0070)
1985 && (Entry->GetElement() != 0x0080) ) )
1988 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1992 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1993 // Occurence of such images is quite low (unless one leaves close to a
1994 // 'Leonardo' source. Hence, one might consider commenting out the
1995 // following fix on efficiency reasons.
1997 if ( (Entry->GetGroup() == 0x0009)
1998 && ( (Entry->GetElement() == 0x1113)
1999 || (Entry->GetElement() == 0x1114) ) )
2002 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2005 //////// Deal with sequences, but only on users request:
2007 if ( ( Entry->GetVR() == "SQ") && enableSequences)
2009 FoundLength = 0; // ReadLength is unchanged
2012 //////// We encountered a 'delimiter' element i.e. a tag of the form
2013 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2014 // taken into account.
2016 if(Entry->GetGroup() == 0xfffe)
2018 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2019 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2020 // causes extra troubles...
2021 if( Entry->GetElement() != 0x0000 )
2027 Entry->SetUsableLength(FoundLength);
2031 * \brief Apply some heuristics to predict whether the considered
2032 * element value contains/represents an integer or not.
2033 * @param Entry The element value on which to apply the predicate.
2034 * @return The result of the heuristical predicate.
2036 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2037 guint16 element = Entry->GetElement();
2038 guint16 group = Entry->GetGroup();
2039 std::string vr = Entry->GetVR();
2040 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 // Allthough this should never happen, still some images have a
2052 // corrupted group length [e.g. have a glance at offset x(8336) of
2053 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2054 // Since for dicom compliant and well behaved headers, the present
2055 // test is useless (and might even look a bit paranoid), when we
2056 // encounter such an ill-formed image, we simply display a warning
2057 // message and proceed on parsing (while crossing fingers).
2058 std::ostringstream s;
2059 int filePosition = ftell(fp);
2060 s << "Erroneous Group Length element length on : (" \
2061 << std::hex << group << " , " << element
2062 << ") -before- position x(" << filePosition << ")"
2063 << "lgt : " << length;
2064 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2068 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);
2664 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2665 * is placed at the beginning of a tag (TestGroup, TestElement),
2666 * read the length associated to the Tag.
2667 * \warning On success the internal file pointer \ref gdcmDocument::fp
2668 * is modified to point after the tag and it's length.
2669 * On failure (i.e. when the tag wasn't the expected tag
2670 * (TestGroup, TestElement) the internal file pointer
2671 * \ref gdcmDocument::fp is restored to it's original position.
2672 * @param TestGroup The expected group of the tag.
2673 * @param TestElement The expected Element of the tag.
2674 * @return On success returns the length associated to the tag. On failure
2677 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2679 guint16 ItemTagGroup;
2680 guint16 ItemTagElement;
2681 long PositionOnEntry = ftell(fp);
2682 long CurrentPosition = ftell(fp); // On debugging purposes
2684 //// Read the Item Tag group and element, and make
2685 // sure they are respectively 0xfffe and 0xe000:
2686 ItemTagGroup = ReadInt16();
2687 ItemTagElement = ReadInt16();
2688 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2690 std::ostringstream s;
2691 s << " We should have found tag (";
2692 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2693 s << " but instead we encountered tag (";
2694 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2696 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2697 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2698 dbg.Verbose(0, s.str().c_str());
2699 fseek(fp, PositionOnEntry, SEEK_SET);
2703 //// Then read the associated Item Length
2704 CurrentPosition=ftell(fp);
2706 ItemLength = ReadInt32();
2708 std::ostringstream s;
2709 s << "Basic Item Length is: "
2710 << ItemLength << std::endl;
2711 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2712 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2718 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2719 * \sa \ref gdcmDocument::ReadTagLength
2720 * \warning See warning of \ref gdcmDocument::ReadTagLength
2721 * @return On success returns the length associated to the item tag.
2722 * On failure returns 0.
2724 guint32 gdcmDocument::ReadItemTagLength(void)
2726 return ReadTagLength(0xfffe, 0xe000);
2730 * \brief Read the length of an exptected Sequence Delimiter tag i.e.
2732 * \sa \ref gdcmDocument::ReadTagLength
2733 * \warning See warning of \ref gdcmDocument::ReadTagLength
2734 * @return On success returns the length associated to the Sequence
2735 * Delimiter tag. On failure returns 0.
2737 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2739 return ReadTagLength(0xfffe, 0xe0dd);
2744 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2745 * No other way so 'skip' the Data
2748 void gdcmDocument::Parse7FE0 (void)
2750 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2754 if ( IsImplicitVRLittleEndianTransferSyntax()
2755 || IsExplicitVRLittleEndianTransferSyntax()
2756 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2757 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2760 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2762 //// Read the Basic Offset Table Item Tag length...
2763 guint32 ItemLength = ReadItemTagLength();
2765 //// ... and then read length[s] itself[themselves]. We don't use
2766 // the values read (BTW what is the purpous of those lengths ?)
2767 if (ItemLength != 0) {
2768 // BTW, what is the purpous of those length anyhow !?
2769 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2770 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2771 for (int i=0; i < ItemLength; i += 4){
2772 guint32 IndividualLength;
2773 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2774 std::ostringstream s;
2775 s << " Read one length: ";
2776 s << std::hex << IndividualLength << std::endl;
2777 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2781 if ( ! IsRLELossLessTransferSyntax() )
2785 //// We then skip (not reading them) all the fragments of images:
2786 while ( ItemLength = ReadItemTagLength() )
2788 SkipBytes(ItemLength);
2796 long RleSegmentLength[15], fragmentLength;
2798 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2799 while ( fragmentLength = ReadSequenceDelimiterTagLength() )
2801 // Parse fragments of the current Fragment (Frame)
2802 //------------------ scanning (not reading) fragment pixels
2803 guint32 nbRleSegments = ReadInt32();
2804 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2806 //// Reading RLE Segments Offset Table
2807 guint32 RleSegmentOffsetTable[15];
2808 for(int k=1; k<=15; k++) {
2810 RleSegmentOffsetTable[k] = ReadInt32();
2811 printf(" at : %x Offset Segment %d : %d (%x)\n",
2812 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2813 RleSegmentOffsetTable[k]);
2816 // skipping (not reading) RLE Segments
2817 if (nbRleSegments>1) {
2818 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2819 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2820 - RleSegmentOffsetTable[k];
2822 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2823 k,(unsigned)RleSegmentLength[k],
2824 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2825 SkipBytes(RleSegmentLength[k]);
2829 RleSegmentLength[nbRleSegments]= fragmentLength
2830 - RleSegmentOffsetTable[nbRleSegments];
2832 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2833 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2834 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2835 SkipBytes(RleSegmentLength[nbRleSegments]);
2842 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2843 * \warning Does NOT work with ACR-NEMA files
2844 * \todo Find a trick to solve the pb (use RET fields ?)
2846 * @return true if 'smaller'
2848 bool gdcmDocument::operator<(gdcmDocument &document){
2852 s1=this->GetEntryByNumber(0x0010,0x0010);
2853 s2=document.GetEntryByNumber(0x0010,0x0010);
2861 s1=this->GetEntryByNumber(0x0010,0x0020);
2862 s2=document.GetEntryByNumber(0x0010,0x0020);
2869 // Study Instance UID
2870 s1=this->GetEntryByNumber(0x0020,0x000d);
2871 s2=document.GetEntryByNumber(0x0020,0x000d);
2878 // Serie Instance UID
2879 s1=this->GetEntryByNumber(0x0020,0x000e);
2880 s2=document.GetEntryByNumber(0x0020,0x000e);
2892 //-----------------------------------------------------------------------------