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))
100 // return false; // to go on compiling
102 fseek(fp,0L,SEEK_END);
103 long lgt = ftell(fp);
107 long beg = ftell(fp);
112 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
115 // --------------------------------------------------------------
116 // Special Patch to allow gdcm to read ACR-LibIDO formated images
118 // if recognition code tells us we deal with a LibIDO image
119 // we switch lineNumber and columnNumber
122 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
123 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
124 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
125 // with "little-endian strings"
127 filetype = gdcmACR_LIBIDO;
128 std::string rows = GetEntryByNumber(0x0028, 0x0010);
129 std::string columns = GetEntryByNumber(0x0028, 0x0011);
130 SetEntryByNumber(columns, 0x0028, 0x0010);
131 SetEntryByNumber(rows , 0x0028, 0x0011);
133 // ----------------- End of Special Patch ----------------
135 printLevel = 1; // 'Medium' print level by default
140 * @param exception_on_error
142 gdcmDocument::gdcmDocument(bool exception_on_error)
143 :gdcmElementSet(-1) {
144 (void)exception_on_error;
147 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
150 printLevel = 1; // 'Medium' print level by default
154 * \brief Canonical destructor.
156 gdcmDocument::~gdcmDocument (void) {
161 //-----------------------------------------------------------------------------
167 * \brief Prints The Dict Entries of THE public Dicom Dictionary
170 void gdcmDocument::PrintPubDict(std::ostream & os) {
171 RefPubDict->Print(os);
175 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
178 void gdcmDocument::PrintShaDict(std::ostream & os) {
179 RefShaDict->Print(os);
182 //-----------------------------------------------------------------------------
185 * \brief Get the public dictionary used
187 gdcmDict *gdcmDocument::GetPubDict(void) {
192 * \brief Get the shadow dictionary used
194 gdcmDict *gdcmDocument::GetShaDict(void) {
199 * \brief Set the shadow dictionary used
200 * \param dict dictionary to use in shadow
202 bool gdcmDocument::SetShaDict(gdcmDict *dict){
208 * \brief Set the shadow dictionary used
209 * \param dictName name of the dictionary to use in shadow
211 bool gdcmDocument::SetShaDict(DictKey dictName){
212 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
217 * \brief This predicate, based on hopefully reasonable heuristics,
218 * decides whether or not the current gdcmDocument was properly parsed
219 * and contains the mandatory information for being considered as
220 * a well formed and usable Dicom/Acr File.
221 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
224 bool gdcmDocument::IsReadable(void) {
225 if(filetype==gdcmUnknown) {
226 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
229 if(!tagHT.empty()<=0) {
230 std::cout << "gdcmDocument::IsReadable: wrong tagHT size : "
240 * \brief Internal function that checks whether the Transfer Syntax given
241 * as argument is the one present in the current document.
242 * @param SyntaxToCheck The transfert syntax we need to check against.
243 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
244 * the current document. False either when the document contains
245 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
247 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
249 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
253 // The entry might be present but not loaded (parsing and loading
254 // happen at differente stages): try loading and proceed with check...
255 LoadDocEntrySafe(Entry);
256 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
258 std::string Transfer = ValEntry->GetValue();
259 // The actual transfer (as read from disk) might be padded. We
260 // first need to remove the potential padding. We can make the
261 // weak assumption that padding was not executed with digits...
262 while ( ! isdigit(Transfer[Transfer.length()-1]) )
264 Transfer.erase(Transfer.length()-1, 1);
266 if ( Transfer == SyntaxToCheck )
273 * \brief Determines if the Transfer Syntax of the present document
274 * corresponds to a Implicit Value Representation of
276 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
277 * @return True when ImplicitVRLittleEndian found. False in all other cases.
279 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
281 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
285 * \brief Determines if the Transfer Syntax was already encountered
286 * and if it corresponds to a ExplicitVRLittleEndian one.
287 * @return True when ExplicitVRLittleEndian found. False in all other cases.
289 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
291 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
295 * \brief Determines if the Transfer Syntax was already encountered
296 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
297 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
299 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
301 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
305 * \brief Determines if the Transfer Syntax was already encountered
306 * and if it corresponds to a Explicit VR Big Endian one.
307 * @return True when big endian found. False in all other cases.
309 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
311 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
315 * \brief Determines if the Transfer Syntax was already encountered
316 * and if it corresponds to a JPEGBaseLineProcess1 one.
317 * @return True when JPEGBaseLineProcess1found. False in all other cases.
319 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
321 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
325 * \brief Determines if the Transfer Syntax was already encountered
326 * and if it corresponds to a JPEGExtendedProcess2-4 one.
327 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
329 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
331 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
335 * \brief Determines if the Transfer Syntax was already encountered
336 * and if it corresponds to a JPEGExtendeProcess3-5 one.
337 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
339 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
341 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
345 * \brief Determines if the Transfer Syntax was already encountered
346 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
347 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
350 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
352 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
356 * \brief Determines if the Transfer Syntax was already encountered
357 * and if it corresponds to a RLE Lossless one.
358 * @return True when RLE Lossless found. False in all
361 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
363 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
367 * \brief Determines if Transfer Syntax was already encountered
368 * and if it corresponds to a JPEG Lossless one.
369 * @return True when RLE Lossless found. False in all
372 bool gdcmDocument::IsJPEGLossless(void)
374 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
375 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
376 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90) );
380 * \brief Determines if the Transfer Syntax was already encountered
381 * and if it corresponds to a JPEG2000 one
382 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
385 bool gdcmDocument::IsJPEG2000(void)
387 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70)
388 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90) );
392 * \brief Predicate for dicom version 3 file.
393 * @return True when the file is a dicom version 3.
395 bool gdcmDocument::IsDicomV3(void) {
396 // Checking if Transfert Syntax exists is enough
397 // Anyway, it's to late check if the 'Preamble' was found ...
398 // And ... would it be a rich idea to check ?
399 // (some 'no Preamble' DICOM images exist !)
400 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
404 * \brief returns the File Type
405 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
406 * @return the FileType code
408 FileType gdcmDocument::GetFileType(void) {
413 * \brief opens the file
414 * @param exception_on_error
417 FILE *gdcmDocument::OpenFile(bool exception_on_error)
420 fp=fopen(filename.c_str(),"rb");
424 if(exception_on_error)
425 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
428 std::cout <<"gdcmDocument::OpenFile cannot open file: "
429 << filename.c_str() << std::endl;
430 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
439 fread(&zero, (size_t)2, (size_t)1, fp);
441 //ACR -- or DICOM with no Preamble --
442 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
446 fseek(fp, 126L, SEEK_CUR);
448 fread(dicm, (size_t)4, (size_t)1, fp);
449 if( memcmp(dicm, "DICM", 4) == 0 )
453 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", filename.c_str());
456 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", filename.c_str());
462 * \brief closes the file
463 * @return TRUE if the close was successfull
465 bool gdcmDocument::CloseFile(void) {
466 int closed = fclose(fp);
474 * \brief Writes in a file all the Header Entries (Dicom Elements)
475 * of the Chained List
476 * @param fp file pointer on an already open file
477 * @param type Type of the File to be written
478 * (ACR-NEMA, ExplicitVR, ImplicitVR)
479 * \return Always true.
481 bool gdcmDocument::Write(FILE *fp, FileType type) {
484 /// The stuff will have to be rewritten using the SeQuence based
485 /// tree-like stucture instead of the chained list .
486 /// (so we shall remove the Group*HT from the gdcmDocument)
490 /// \todo move the following lines (and a lot of others, to be written)
491 /// to a future function CheckAndCorrectHeader
495 /// Comment pourrait-on savoir si le DcmHeader vient d'un fichier
496 /// DicomV3 ou non (FileType est un champ de gdcmDocument ...)
497 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
499 /// a moins de se livrer a un tres complique ajout des champs manquants.
500 /// faire un CheckAndCorrectHeader (?)
502 if (type == gdcmImplicitVR)
504 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
505 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
507 /// \todo Refer to standards on page 21, chapter 6.2
508 /// "Value representation": values with a VR of UI shall be
509 /// padded with a single trailing null
510 /// Dans le cas suivant on doit pader manuellement avec un 0
512 SetEntryLengthByNumber(18, 0x0002, 0x0010);
515 if (type == gdcmExplicitVR)
517 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
518 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
520 /// \todo Refer to standards on page 21, chapter 6.2
521 /// "Value representation": values with a VR of UI shall be
522 /// padded with a single trailing null
523 /// Dans le cas suivant on doit pader manuellement avec un 0
525 SetEntryLengthByNumber(20, 0x0002, 0x0010);
529 * \todo rewrite later, if really usefull
531 * --> Warning : un-updated odd groups lengths can causes pb
532 * --> (xmedcon breaks)
533 * --> to be re- written with future org.
535 * if ( (type == ImplicitVR) || (type == ExplicitVR) )
536 * UpdateGroupLength(false,type);
538 * UpdateGroupLength(true,ACR);
541 WriteEntries(fp,type);
546 * \brief Modifies the value of a given Header Entry (Dicom Element)
547 * when it exists. Create it with the given value when unexistant.
548 * @param Value (string) Value to be set
549 * @param Group Group number of the Entry
550 * @param Elem Element number of the Entry
551 * \return pointer to the modified/created Header Entry (NULL when creation
555 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
561 a = GetDocEntryByNumber( Group, Elem);
563 a =NewDocEntryByNumber(Group, Elem);
566 b = new gdcmValEntry(a);
569 SetEntryByNumber(Value, Group, Elem);
571 return (gdcmValEntry*)b;
576 * \brief Modifies the value of a given Header Entry (Dicom Element)
577 * when it exists. Create it with the given value when unexistant.
578 * @param voidArea (binary) value to be set
579 * @param Group Group number of the Entry
580 * @param Elem Element number of the Entry
581 * \return pointer to the modified/created Header Entry (NULL when creation
586 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
593 a = GetDocEntryByNumber( Group, Elem);
595 a =NewBinEntryByNumber(Group, Elem);
598 b = new gdcmBinEntry(a);
601 SetEntryByNumber(voidArea, lgth, Group, Elem);
602 b->SetVoidArea(voidArea);
603 return (gdcmBinEntry*)b;
609 * \brief Set a new value if the invoked element exists
610 * Seems to be useless !!!
611 * @param Value new element value
612 * @param Group group number of the Entry
613 * @param Elem element number of the Entry
616 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
618 std::string v = Value;
619 SetEntryByNumber(v, Group, Elem);
623 //-----------------------------------------------------------------------------
627 * \brief Checks if a given Dicom Element exists within the H table
628 * @param group Group number of the searched Dicom Element
629 * @param element Element number of the searched Dicom Element
630 * @return number of occurences
632 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
633 std::string key = gdcmDictEntry::TranslateToKey(group, element );
634 return (tagHT.count(key));
638 * \brief Searches within Header Entries (Dicom Elements) parsed with
639 * the public and private dictionaries
640 * for the element value of a given tag.
641 * \warning Don't use any longer : use GetPubEntryByName
642 * @param tagName name of the searched element.
643 * @return Corresponding element value when it exists,
644 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
646 std::string gdcmDocument::GetEntryByName(std::string tagName) {
647 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
648 if( dictEntry == NULL)
651 return(GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
655 * \brief Searches within Header Entries (Dicom Elements) parsed with
656 * the public and private dictionaries
657 * for the element value representation of a given tag.
659 * Obtaining the VR (Value Representation) might be needed by caller
660 * to convert the string typed content to caller's native type
661 * (think of C++ vs Python). The VR is actually of a higher level
662 * of semantics than just the native C++ type.
663 * @param tagName name of the searched element.
664 * @return Corresponding element value representation when it exists,
665 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
667 std::string gdcmDocument::GetEntryVRByName(std::string tagName) {
668 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
669 if( dictEntry == NULL)
672 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
673 dictEntry->GetElement());
674 return elem->GetVR();
679 * \brief Searches within Header Entries (Dicom Elements) parsed with
680 * the public and private dictionaries
681 * for the element value representation of a given tag.
682 * @param group Group number of the searched tag.
683 * @param element Element number of the searched tag.
684 * @return Corresponding element value representation when it exists,
685 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
687 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
688 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
689 if ( ! tagHT.count(key))
691 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
695 * \brief Searches within Header Entries (Dicom Elements) parsed with
696 * the public and private dictionaries
697 * for the element value representation of a given tag..
699 * Obtaining the VR (Value Representation) might be needed by caller
700 * to convert the string typed content to caller's native type
701 * (think of C++ vs Python). The VR is actually of a higher level
702 * of semantics than just the native C++ type.
703 * @param group Group number of the searched tag.
704 * @param element Element number of the searched tag.
705 * @return Corresponding element value representation when it exists,
706 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
708 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
709 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
712 return elem->GetVR();
716 * \brief Searches within Header Entries (Dicom Elements) parsed with
717 * the public and private dictionaries
718 * for the value length of a given tag..
719 * @param group Group number of the searched tag.
720 * @param element Element number of the searched tag.
721 * @return Corresponding element length; -2 if not found
723 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
724 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
727 return elem->GetLength();
730 * \brief Sets the value (string) of the Header Entry (Dicom Element)
731 * @param content string value of the Dicom Element
732 * @param tagName name of the searched Dicom Element.
733 * @return true when found
735 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
736 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
737 if( dictEntry == NULL)
740 return(SetEntryByNumber(content,dictEntry->GetGroup(),
741 dictEntry->GetElement()));
745 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
746 * through it's (group, element) and modifies it's content with
748 * @param content new value (string) to substitute with
749 * @param group group number of the Dicom Element to modify
750 * @param element element number of the Dicom Element to modify
752 bool gdcmDocument::SetEntryByNumber(std::string content,
756 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
757 if ( ! tagHT.count(key))
759 int l = content.length();
760 if(l%2) // Non even length are padded with a space (020H).
763 content = content + '\0';
767 a = (gdcmValEntry *)tagHT[key];
769 a->SetValue(content);
771 VRKey vr = a->GetVR();
774 if( (vr == "US") || (vr == "SS") )
776 else if( (vr == "UL") || (vr == "SL") )
786 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
787 * through it's (group, element) and modifies it's content with
789 * @param content new value (void *) to substitute with
790 * @param group group number of the Dicom Element to modify
791 * @param element element number of the Dicom Element to modify
793 bool gdcmDocument::SetEntryByNumber(void *content,
798 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
799 if ( ! tagHT.count(key))
802 /* Hope Binray field length is never wrong
803 if(lgth%2) // Non even length are padded with a space (020H).
806 //content = content + '\0'; // fing a trick to enlarge a binary field?
810 a = (gdcmBinEntry *)tagHT[key];
811 a->SetVoidArea(content);
812 //a->SetLength(lgth); // ???
817 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
818 * in the PubDocEntrySet of this instance
819 * through it's (group, element) and modifies it's length with
821 * \warning Use with extreme caution.
822 * @param l new length to substitute with
823 * @param group group number of the Entry to modify
824 * @param element element number of the Entry to modify
825 * @return true on success, false otherwise.
827 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
831 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
832 if ( ! tagHT.count(key))
834 if (l%2) l++; // length must be even
835 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
841 * \brief Gets (from Header) the offset of a 'non string' element value
842 * (LoadElementValues has already be executed)
843 * @param Group group number of the Entry
844 * @param Elem element number of the Entry
845 * @return File Offset of the Element Value
847 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
849 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
852 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
853 "failed to Locate gdcmDocEntry");
856 return Entry->GetOffset();
860 * \brief Gets (from Header) 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 Pointer to the 'non string' area
866 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
868 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
871 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber",
872 "failed to Locate gdcmDocEntry");
875 return ((gdcmBinEntry *)Entry)->GetVoidArea();
879 * \brief Loads (from disk) the element content
880 * when a string is not suitable
881 * @param Group group number of the Entry
882 * @param Elem element number of the Entry
884 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
886 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
889 size_t o =(size_t)Element->GetOffset();
890 fseek(fp, o, SEEK_SET);
891 size_t l=Element->GetLength();
892 char* a = new char[l];
896 SetEntryVoidAreaByNumber(a, Group, Elem);
897 /// \todo check the result
898 size_t l2 = fread(a, 1, l ,fp);
909 * \brief Sets a 'non string' value to a given Dicom Element
911 * @param group Group number of the searched Dicom Element
912 * @param element Element number of the searched Dicom Element
915 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
919 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
920 if ( ! tagHT.count(key))
922 // This was for multimap ?
923 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
929 * \brief Update the entries with the shadow dictionary.
930 * Only non even entries are analyzed
932 void gdcmDocument::UpdateShaEntries(void) {
933 gdcmDictEntry *entry;
936 /// \todo TODO : still any use to explore recursively the whole structure?
938 for(ListTag::iterator it=listEntries.begin();
939 it!=listEntries.end();
942 // Odd group => from public dictionary
943 if((*it)->GetGroup()%2==0)
946 // Peer group => search the corresponding dict entry
948 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
952 if((*it)->IsImplicitVR())
957 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
959 // Set the new entry and the new value
960 (*it)->SetDictEntry(entry);
961 CheckDocEntryVR(*it,vr);
963 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
968 // Remove precedent value transformation
969 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
976 * \brief Searches within the Header Entries for a Dicom Element of
978 * @param tagName name of the searched Dicom Element.
979 * @return Corresponding Dicom Element when it exists, and NULL
982 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
983 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
984 if( dictEntry == NULL)
987 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
991 * \brief retrieves a Dicom Element (the first one) using (group, element)
992 * \warning (group, element) IS NOT an identifier inside the Dicom Header
993 * if you think it's NOT UNIQUE, check the count number
994 * and use iterators to retrieve ALL the Dicoms Elements within
995 * a given couple (group, element)
996 * @param group Group number of the searched Dicom Element
997 * @param element Element number of the searched Dicom Element
1000 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1002 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1003 if ( ! tagHT.count(key))
1005 return tagHT.find(key)->second;
1009 * \brief Loads the element while preserving the current
1010 * underlying file position indicator as opposed to
1011 * to LoadDocEntry that modifies it.
1012 * @param entry Header Entry whose value shall be loaded.
1015 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1016 long PositionOnEntry = ftell(fp);
1017 LoadDocEntry(entry);
1018 fseek(fp, PositionOnEntry, SEEK_SET);
1023 * \brief Writes in a file (according to the requested format)
1024 * the group, the element, the value representation and the length
1025 * of a single gdcmDocEntry passed as argument.
1026 * @param tag pointer on the gdcmDocEntry to be written
1027 * @param _fp already open file pointer
1028 * @param type type of the File to be written
1030 void gdcmDocument::WriteEntryTagVRLength(gdcmDocEntry *tag,
1034 guint16 group = tag->GetGroup();
1035 VRKey vr = tag->GetVR();
1036 guint16 el = tag->GetElement();
1037 guint32 lgr = tag->GetReadLength();
1039 if ( (group == 0xfffe) && (el == 0x0000) )
1040 // Fix in order to make some MR PHILIPS images e-film readable
1041 // see gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm:
1042 // we just *always* ignore spurious fffe|0000 tag !
1045 fwrite ( &group,(size_t)2 ,(size_t)1 ,_fp); //group
1046 fwrite ( &el,(size_t)2 ,(size_t)1 ,_fp); //element
1048 if ( type == gdcmExplicitVR ) {
1050 // Special case of delimiters:
1051 if (group == 0xfffe) {
1052 // Delimiters have NO Value Representation and have NO length.
1053 // Hence we skip writing the VR and length and we pad by writing
1057 fwrite (&ff,(size_t)4 ,(size_t)1 ,_fp);
1062 guint16 shortLgr = lgr;
1063 if (vr == "unkn") { // Unknown was 'written'
1064 // deal with Little Endian
1065 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1066 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1068 fwrite (vr.c_str(),(size_t)2 ,(size_t)1 ,_fp);
1069 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
1071 fwrite ( &z, (size_t)2 ,(size_t)1 ,_fp);
1072 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1074 fwrite ( &shortLgr,(size_t)2 ,(size_t)1 ,_fp);
1080 fwrite ( &lgr,(size_t)4 ,(size_t)1 ,_fp);
1085 * \brief Writes in a file (according to the requested format)
1086 * the value of a single gdcmDocEntry passed as argument.
1087 * @param tag Pointer on the gdcmDocEntry to be written
1088 * @param _fp Already open file pointer
1089 * @param type type of the File to be written
1092 // \todo TODO : to be re -written recursively !
1093 void gdcmDocument::WriteEntryValue(gdcmDocEntry *tag, FILE *_fp,FileType type)
1096 guint16 group = tag->GetGroup();
1097 VRKey vr = tag->GetVR();
1098 guint32 lgr = tag->GetReadLength();
1101 // SeQuences have no value:
1103 if (group == 0xfffe)
1104 // Delimiters have no associated value:
1107 //--------------------------------
1109 // FIXME :right now, both value and voidArea belong to gdcmValue
1111 // -------------------------------
1113 // if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) ) {
1115 gdcmBinEntry *BinEntry= (gdcmBinEntry *)tag;;
1116 voidArea = BinEntry->GetVoidArea();
1117 if (voidArea != NULL)
1118 { // there is a 'non string' LUT, overlay, etc
1119 fwrite ( voidArea,(size_t)lgr ,(size_t)1 ,_fp); // Elem value
1124 if (vr == "US" || vr == "SS")
1126 // some 'Short integer' fields may be mulivaluated
1127 // each single value is separated from the next one by '\'
1128 // we split the string and write each value as a short int
1129 std::vector<std::string> tokens;
1130 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1131 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1132 for (unsigned int i=0; i<tokens.size();i++)
1134 guint16 val_uint16 = atoi(tokens[i].c_str());
1135 void *ptr = &val_uint16;
1136 fwrite ( ptr,(size_t)2 ,(size_t)1 ,_fp);
1141 if (vr == "UL" || vr == "SL")
1143 // Some 'Integer' fields may be multivaluated (multiple instances
1144 // of integers). But each single integer value is separated from the
1145 // next one by '\' (backslash character). Hence we split the string
1146 // along the '\' and write each value as an int:
1147 std::vector<std::string> tokens;
1148 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1149 Tokenize (((gdcmValEntry *)tag)->GetValue(), tokens, "\\");
1150 for (unsigned int i=0; i<tokens.size();i++)
1152 guint32 val_uint32 = atoi(tokens[i].c_str());
1153 void *ptr = &val_uint32;
1154 fwrite ( ptr,(size_t)4 ,(size_t)1 ,_fp);
1159 fwrite (((gdcmValEntry *)tag)->GetValue().c_str(),
1160 (size_t)lgr ,(size_t)1, _fp); // Elem value
1164 * \brief Writes in a file (according to the requested format)
1165 * a single gdcmDocEntry passed as argument.
1166 * \sa WriteEntryValue, WriteEntryTagVRLength.
1167 * @param tag Pointer on the gdcmDocEntry to be written
1168 * @param _fp Already open file pointer
1169 * @param type type of the File to be written
1172 bool gdcmDocument::WriteEntry(gdcmDocEntry *tag, FILE *_fp,FileType type)
1174 guint32 length = tag->GetLength();
1176 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(tag) )
1178 // The value of a tag MUST (see the DICOM norm) be an odd number of
1179 // bytes. When this is not the case, pad with an additional byte:
1181 ValEntry->SetValue(ValEntry->GetValue()+"\0");
1182 ValEntry->SetLength(ValEntry->GetReadLength()+1);
1184 WriteEntryTagVRLength(ValEntry, _fp, type);
1185 WriteEntryValue(ValEntry, _fp, type);
1189 if (gdcmBinEntry* BinEntry = dynamic_cast< gdcmBinEntry* >(tag) )
1191 /// \todo FIXME : when voidArea belong to gdcmBinEntry only, fix
1194 // The value of a tag MUST (see the DICOM norm) be an odd number of
1195 // bytes. When this is not the case, pad with an additional byte:
1198 tag->SetValue(tag->GetValue()+"\0");
1199 tag->SetLength(tag->GetReadLength()+1);
1202 WriteEntryTagVRLength(tag, _fp, type);
1203 WriteEntryValue(tag, _fp, type);
1209 * \brief writes on disc according to the requested format
1210 * (ACR-NEMA, ExplicitVR, ImplicitVR) the image
1211 * using the Chained List
1212 * \warning does NOT add the missing elements in the header :
1213 * it's up to the user doing it !
1214 * (function CheckHeaderCoherence to be written)
1215 * \warning DON'T try, right now, to write a DICOM image
1216 * from an ACR Header (meta elements will be missing!)
1217 * @param type type of the File to be written
1218 * (ACR-NEMA, ExplicitVR, ImplicitVR)
1219 * @param _fp already open file pointer
1222 bool gdcmDocument::WriteEntries(FILE *_fp,FileType type)
1224 /// \todo FIXME : explore recursively the whole structure...
1225 /// \todo (?) check write failures (after *each* fwrite)
1227 dbg.Verbose(0, "gdcmDocument::WriteEntries: entering.");
1228 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
1230 gdcmDocEntry * entry = it->second;
1233 if ( type == gdcmACR ){
1234 if (entry->GetGroup() < 0x0008)
1235 // Ignore pure DICOM V3 groups
1237 if (entry->GetGroup() %2)
1238 // Ignore the "shadow" groups
1240 if (entry->GetVR() == "SQ" ) // ignore Sequences
1243 if (! WriteEntry(entry, _fp, type) ) {
1244 dbg.Verbose(0, "gdcmDocument::WriteEntries: write failure.");
1253 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1255 * @return The properly swaped 32 bits integer.
1257 guint32 gdcmDocument::SwapLong(guint32 a) {
1262 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1263 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1267 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1271 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1274 std::cout << "swapCode= " << sw << std::endl;
1275 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1282 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1284 * @return The properly unswaped 32 bits integer.
1286 guint32 gdcmDocument::UnswapLong(guint32 a) {
1287 return (SwapLong(a));
1291 * \brief Swaps the bytes so they agree with the processor order
1292 * @return The properly swaped 16 bits integer.
1294 guint16 gdcmDocument::SwapShort(guint16 a) {
1295 if ( (sw==4321) || (sw==2143) )
1296 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1301 * \brief Unswaps the bytes so they agree with the processor order
1302 * @return The properly unswaped 16 bits integer.
1304 guint16 gdcmDocument::UnswapShort(guint16 a) {
1305 return (SwapShort(a));
1308 //-----------------------------------------------------------------------------
1312 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1313 * @return false if file is not ACR-NEMA / PAPYRUS / DICOM
1316 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1318 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1326 depth = set->GetDepthLevel();
1329 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1332 NewDocEntry = ReadNextDocEntry( );
1336 vr = NewDocEntry->GetVR();
1339 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1342 vl= new gdcmValEntry(NewDocEntry->GetDictEntry());
1343 vl->Copy(NewDocEntry);
1344 vl->SetDepthLevel(depth);
1347 if (/*!delim_mode && */vl->isItemDelimitor())
1349 if ( !delim_mode && ftell(fp)-offset >= l_max)
1356 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1358 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1359 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1360 "nor BinEntry. Probably unknown VR.");
1363 ////// BinEntry or UNKOWN VR:
1364 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1365 bn->Copy(NewDocEntry);
1370 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1371 NewDocEntry->GetElement() == 0x0010 )
1373 if (NewDocEntry->GetLength()==0xffffffff)
1374 // Broken US.3405.1.dcm
1375 Parse7FE0(); // to skip the pixels
1376 // (multipart JPEG/RLE are trouble makers)
1380 // to be sure we are at the beginning
1381 SkipToNextDocEntry(NewDocEntry);
1382 l = NewDocEntry->GetFullLength();
1384 } else { // VR = "SQ"
1386 l=NewDocEntry->GetReadLength();
1387 if (l != 0) // don't mess the delim_mode for zero-length sequence
1388 if (l == 0xffffffff)
1392 // no other way to create it ...
1393 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1394 set->GetDepthLevel());
1395 sq->Copy(NewDocEntry);
1396 sq->SetDelimitorMode(delim_mode);
1397 sq->SetDepthLevel(depth);
1400 { // Don't try to parse zero-length sequences
1401 long lgt = ParseSQ( sq,
1402 NewDocEntry->GetOffset(),
1405 // FIXME : on en fait quoi, de lgt ?
1407 if ( !delim_mode && ftell(fp)-offset >= l_max)
1418 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1419 * @return parsed length for this level
1421 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1422 long offset, long l_max, bool delim_mode)
1424 int SQItemNumber = 0;
1426 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1430 int depth = set->GetDepthLevel();
1433 NewDocEntry = ReadNextDocEntry();
1435 if (NewDocEntry->isSequenceDelimitor()) {
1436 /// \todo add the Sequence Delimitor
1437 /// \todo find the trick to put it properly !
1438 set->SetSequenceDelimitationItem(NewDocEntry);
1442 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1446 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1447 itemSQ->AddEntry(NewDocEntry);
1448 /// \todo no value, no voidArea. Think of it while printing !
1449 l= NewDocEntry->GetReadLength();
1451 if (l == 0xffffffff)
1456 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1458 set->AddEntry(itemSQ,SQItemNumber);
1460 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1464 lgth = ftell(fp) - offset;
1469 * \brief Loads the element content if its length doesn't exceed
1470 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1471 * @param Entry Header Entry (Dicom Element) to be dealt with
1473 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry) {
1475 guint16 group = Entry->GetGroup();
1476 std::string vr= Entry->GetVR();
1477 guint32 length = Entry->GetLength();
1479 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1481 // A SeQuence "contains" a set of Elements.
1482 // (fffe e000) tells us an Element is beginning
1483 // (fffe e00d) tells us an Element just ended
1484 // (fffe e0dd) tells us the current SeQuence just ended
1485 if( group == 0xfffe ) {
1486 // NO more value field for SQ !
1487 //Entry->SetValue("gdcm::Skipped");
1488 // appel recursif de Load Value
1489 // (meme pb que pour le parsing)
1493 // When the length is zero things are easy:
1494 if ( length == 0 ) {
1495 ((gdcmValEntry *)Entry)->SetValue("");
1499 // The elements whose length is bigger than the specified upper bound
1500 // are not loaded. Instead we leave a short notice of the offset of
1501 // the element content and it's length.
1502 if (length > MaxSizeLoadEntry) {
1503 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1505 std::ostringstream s;
1506 s << "gdcm::NotLoaded.";
1507 s << " Address:" << (long)Entry->GetOffset();
1508 s << " Length:" << Entry->GetLength();
1509 s << " x(" << std::hex << Entry->GetLength() << ")";
1510 ValEntryPtr->SetValue(s.str());
1512 // to be sure we are at the end of the value ...
1513 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1518 // Any compacter code suggested (?)
1519 if ( IsDocEntryAnInteger(Entry) ) {
1521 std::ostringstream s;
1523 // When short integer(s) are expected, read and convert the following
1524 // n *two characters properly i.e. as short integers as opposed to strings.
1525 // Elements with Value Multiplicity > 1
1526 // contain a set of integers (not a single one)
1527 if (vr == "US" || vr == "SS") {
1529 NewInt = ReadInt16();
1532 for (int i=1; i < nbInt; i++) {
1534 NewInt = ReadInt16();
1539 // When integer(s) are expected, read and convert the following
1540 // n * four characters properly i.e. as integers as opposed to strings.
1541 // Elements with Value Multiplicity > 1
1542 // contain a set of integers (not a single one)
1543 else if (vr == "UL" || vr == "SL") {
1545 NewInt = ReadInt32();
1548 for (int i=1; i < nbInt; i++) {
1550 NewInt = ReadInt32();
1555 #ifdef GDCM_NO_ANSI_STRING_STREAM
1556 s << std::ends; // to avoid oddities on Solaris
1557 #endif //GDCM_NO_ANSI_STRING_STREAM
1559 ((gdcmValEntry *)Entry)->SetValue(s.str());
1563 // We need an additional byte for storing \0 that is not on disk
1564 std::string NewValue(length,0);
1565 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1566 if ( item_read != 1 ) {
1567 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1568 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1572 if( (vr == "UI") ) // Because of correspondance with the VR dic
1573 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1575 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1580 * \brief Find the value Length of the passed Header Entry
1581 * @param Entry Header Entry whose length of the value shall be loaded.
1583 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1584 guint16 element = Entry->GetElement();
1585 //guint16 group = Entry->GetGroup(); //FIXME
1586 std::string vr = Entry->GetVR();
1590 if ( (filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1592 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1594 // The following reserved two bytes (see PS 3.5-2001, section
1595 // 7.1.2 Data element structure with explicit vr p27) must be
1596 // skipped before proceeding on reading the length on 4 bytes.
1597 fseek(fp, 2L, SEEK_CUR);
1598 guint32 length32 = ReadInt32();
1600 if ( (vr == "OB") && (length32 == 0xffffffff) )
1602 Entry->SetLength(FindDocEntryLengthOB());
1605 FixDocEntryFoundLength(Entry, length32);
1609 // Length is encoded on 2 bytes.
1610 length16 = ReadInt16();
1612 // We can tell the current file is encoded in big endian (like
1613 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1614 // and it's value is the one of the encoding of a big endian file.
1615 // In order to deal with such big endian encoded files, we have
1616 // (at least) two strategies:
1617 // * when we load the "Transfer Syntax" tag with value of big endian
1618 // encoding, we raise the proper flags. Then we wait for the end
1619 // of the META group (0x0002) among which is "Transfer Syntax",
1620 // before switching the swap code to big endian. We have to postpone
1621 // the switching of the swap code since the META group is fully encoded
1622 // in little endian, and big endian coding only starts at the next
1623 // group. The corresponding code can be hard to analyse and adds
1624 // many additional unnecessary tests for regular tags.
1625 // * the second strategy consists in waiting for trouble, that shall
1626 // appear when we find the first group with big endian encoding. This
1627 // is easy to detect since the length of a "Group Length" tag (the
1628 // ones with zero as element number) has to be of 4 (0x0004). When we
1629 // encounter 1024 (0x0400) chances are the encoding changed and we
1630 // found a group with big endian encoding.
1631 // We shall use this second strategy. In order to make sure that we
1632 // can interpret the presence of an apparently big endian encoded
1633 // length of a "Group Length" without committing a big mistake, we
1634 // add an additional check: we look in the already parsed elements
1635 // for the presence of a "Transfer Syntax" whose value has to be "big
1636 // endian encoding". When this is the case, chances are we have got our
1637 // hands on a big endian encoded file: we switch the swap code to
1638 // big endian and proceed...
1639 if ( (element == 0x0000) && (length16 == 0x0400) )
1641 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1643 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1648 SwitchSwapToBigEndian();
1649 // Restore the unproperly loaded values i.e. the group, the element
1650 // and the dictionary entry depending on them.
1651 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1652 guint16 CorrectElem = SwapShort(Entry->GetElement());
1653 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1657 // This correct tag is not in the dictionary. Create a new one.
1658 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1660 // FIXME this can create a memory leaks on the old entry that be
1661 // left unreferenced.
1662 Entry->SetDictEntry(NewTag);
1665 // Heuristic: well some files are really ill-formed.
1666 if ( length16 == 0xffff)
1669 //dbg.Verbose(0, "gdcmDocument::FindLength",
1670 // "Erroneous element length fixed.");
1671 // Actually, length= 0xffff means that we deal with
1672 // Unknown Sequence Length
1674 FixDocEntryFoundLength(Entry, (guint32)length16);
1679 // Either implicit VR or a non DICOM conformal (see note below) explicit
1680 // VR that ommited the VR of (at least) this element. Farts happen.
1681 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1682 // on Data elements "Implicit and Explicit VR Data Elements shall
1683 // not coexist in a Data Set and Data Sets nested within it".]
1684 // Length is on 4 bytes.
1686 FixDocEntryFoundLength(Entry, ReadInt32());
1692 * \brief Find the Value Representation of the current Dicom Element.
1695 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1697 if (filetype != gdcmExplicitVR)
1702 long PositionOnEntry = ftell(fp);
1703 // Warning: we believe this is explicit VR (Value Representation) because
1704 // we used a heuristic that found "UL" in the first tag. Alas this
1705 // doesn't guarantee that all the tags will be in explicit VR. In some
1706 // cases (see e-film filtered files) one finds implicit VR tags mixed
1707 // within an explicit VR file. Hence we make sure the present tag
1708 // is in explicit VR and try to fix things if it happens not to be
1711 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1713 if(!CheckDocEntryVR(Entry,VR))
1715 fseek(fp, PositionOnEntry, SEEK_SET);
1716 // When this element is known in the dictionary we shall use, e.g. for
1717 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1718 // dictionary entry. Still we have to flag the element as implicit since
1719 // we know now our assumption on expliciteness is not furfilled.
1721 if ( Entry->IsVRUnknown() )
1722 Entry->SetVR("Implicit");
1723 Entry->SetImplicitVR();
1728 * \brief Check the correspondance between the VR of the header entry
1729 * and the taken VR. If they are different, the header entry is
1730 * updated with the new VR.
1731 * @param Entry Header Entry to check
1732 * @param vr Dicom Value Representation
1733 * @return false if the VR is incorrect of if the VR isn't referenced
1734 * otherwise, it returns true
1736 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1738 char msg[100]; // for sprintf
1739 bool RealExplicit = true;
1741 // Assume we are reading a falsely explicit VR file i.e. we reached
1742 // a tag where we expect reading a VR but are in fact we read the
1743 // first to bytes of the length. Then we will interogate (through find)
1744 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1745 // both GCC and VC++ implementations of the STL map. Hence when the
1746 // expected VR read happens to be non-ascii characters we consider
1747 // we hit falsely explicit VR tag.
1749 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1750 RealExplicit = false;
1752 // CLEANME searching the dicom_vr at each occurence is expensive.
1753 // PostPone this test in an optional integrity check at the end
1754 // of parsing or only in debug mode.
1755 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1756 RealExplicit= false;
1758 if ( !RealExplicit )
1760 // We thought this was explicit VR, but we end up with an
1761 // implicit VR tag. Let's backtrack.
1762 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1763 Entry->GetGroup(),Entry->GetElement());
1764 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1765 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1766 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1767 Entry->GetGroup(),Entry->GetElement(),
1768 "UL","FIXME","Group Length");
1769 Entry->SetDictEntry(NewEntry);
1774 if ( Entry->IsVRUnknown() )
1776 // When not a dictionary entry, we can safely overwrite the VR.
1777 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1783 else if ( Entry->GetVR() != vr )
1785 // The VR present in the file and the dictionary disagree. We assume
1786 // the file writer knew best and use the VR of the file. Since it would
1787 // be unwise to overwrite the VR of a dictionary (since it would
1788 // compromise it's next user), we need to clone the actual DictEntry
1789 // and change the VR for the read one.
1790 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1791 Entry->GetGroup(),Entry->GetElement(),
1792 vr,"FIXME",Entry->GetName());
1793 Entry->SetDictEntry(NewEntry);
1799 * \brief Get the transformed value of the header entry. The VR value
1800 * is used to define the transformation to operate on the value
1801 * \warning NOT end user intended method !
1803 * @return Transformed entry value
1805 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1807 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1809 std::string val=((gdcmValEntry *)Entry)->GetValue();
1810 std::string vr=Entry->GetVR();
1811 guint32 length = Entry->GetLength();
1812 std::ostringstream s;
1815 // When short integer(s) are expected, read and convert the following
1816 // n * 2 bytes properly i.e. as a multivaluated strings
1817 // (each single value is separated fromthe next one by '\'
1818 // as usual for standard multivaluated filels
1819 // Elements with Value Multiplicity > 1
1820 // contain a set of short integers (not a single one)
1822 if (vr == "US" || vr == "SS")
1827 for (int i=0; i < nbInt; i++)
1831 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1832 NewInt16 = SwapShort(NewInt16);
1837 // When integer(s) are expected, read and convert the following
1838 // n * 4 bytes properly i.e. as a multivaluated strings
1839 // (each single value is separated fromthe next one by '\'
1840 // as usual for standard multivaluated filels
1841 // Elements with Value Multiplicity > 1
1842 // contain a set of integers (not a single one)
1843 else if (vr == "UL" || vr == "SL")
1848 for (int i=0; i < nbInt; i++)
1852 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1853 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1854 NewInt32=SwapLong(NewInt32);
1858 #ifdef GDCM_NO_ANSI_STRING_STREAM
1859 s << std::ends; // to avoid oddities on Solaris
1860 #endif //GDCM_NO_ANSI_STRING_STREAM
1864 return(((gdcmValEntry *)Entry)->GetValue());
1868 * \brief Get the reverse transformed value of the header entry. The VR
1869 * value is used to define the reverse transformation to operate on
1871 * \warning NOT end user intended method !
1873 * @return Reverse transformed entry value
1875 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1877 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1879 std::string vr=Entry->GetVR();
1880 std::ostringstream s;
1881 std::vector<std::string> tokens;
1883 if (vr == "US" || vr == "SS")
1887 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1888 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1889 for (unsigned int i=0; i<tokens.size();i++)
1891 NewInt16 = atoi(tokens[i].c_str());
1892 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1896 if (vr == "UL" || vr == "SL")
1900 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1901 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1902 for (unsigned int i=0; i<tokens.size();i++)
1904 NewInt32 = atoi(tokens[i].c_str());
1905 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1906 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1911 #ifdef GDCM_NO_ANSI_STRING_STREAM
1912 s << std::ends; // to avoid oddities on Solaris
1913 #endif //GDCM_NO_ANSI_STRING_STREAM
1917 return(((gdcmValEntry *)Entry)->GetValue());
1921 * \brief Skip a given Header Entry
1922 * \warning NOT end user intended method !
1925 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1927 SkipBytes(entry->GetLength());
1931 * \brief Skips to the begining of the next Header Entry
1932 * \warning NOT end user intended method !
1935 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1937 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1938 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1942 * \brief Loads the value for a a given VLEntry
1943 * \warning NOT end user intended method !
1946 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
1948 //SkipBytes(entry->GetLength());
1949 LoadDocEntry(entry);
1952 * \brief When the length of an element value is obviously wrong (because
1953 * the parser went Jabberwocky) one can hope improving things by
1954 * applying some heuristics.
1956 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1957 guint32 FoundLength)
1959 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1960 if ( FoundLength == 0xffffffff) {
1964 guint16 gr =Entry->GetGroup();
1965 guint16 el =Entry->GetElement();
1967 if (FoundLength%2) {
1968 std::ostringstream s;
1969 s << "Warning : Tag with uneven length "
1971 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1972 dbg.Verbose(0, s.str().c_str());
1975 //////// Fix for some naughty General Electric images.
1976 // Allthough not recent many such GE corrupted images are still present
1977 // on Creatis hard disks. Hence this fix shall remain when such images
1978 // are no longer in user (we are talking a few years, here)...
1979 // Note: XMedCom probably uses such a trick since it is able to read
1980 // those pesky GE images ...
1981 if (FoundLength == 13) { // Only happens for this length !
1982 if ( (Entry->GetGroup() != 0x0008)
1983 || ( (Entry->GetElement() != 0x0070)
1984 && (Entry->GetElement() != 0x0080) ) )
1987 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1991 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1992 // Occurence of such images is quite low (unless one leaves close to a
1993 // 'Leonardo' source. Hence, one might consider commenting out the
1994 // following fix on efficiency reasons.
1996 if ( (Entry->GetGroup() == 0x0009)
1997 && ( (Entry->GetElement() == 0x1113)
1998 || (Entry->GetElement() == 0x1114) ) )
2001 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2004 //////// Deal with sequences, but only on users request:
2006 if ( ( Entry->GetVR() == "SQ") && enableSequences)
2008 FoundLength = 0; // ReadLength is unchanged
2011 //////// We encountered a 'delimiter' element i.e. a tag of the form
2012 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2013 // taken into account.
2015 if(Entry->GetGroup() == 0xfffe)
2017 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2018 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2019 // causes extra troubles...
2020 if( Entry->GetElement() != 0x0000 )
2026 Entry->SetUsableLength(FoundLength);
2030 * \brief Apply some heuristics to predict whether the considered
2031 * element value contains/represents an integer or not.
2032 * @param Entry The element value on which to apply the predicate.
2033 * @return The result of the heuristical predicate.
2035 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
2036 guint16 element = Entry->GetElement();
2037 guint16 group = Entry->GetGroup();
2038 std::string vr = Entry->GetVR();
2039 guint32 length = Entry->GetLength();
2041 // When we have some semantics on the element we just read, and if we
2042 // a priori know we are dealing with an integer, then we shall be
2043 // able to swap it's element value properly.
2044 if ( element == 0 ) // This is the group length of the group
2050 // Allthough this should never happen, still some images have a
2051 // corrupted group length [e.g. have a glance at offset x(8336) of
2052 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2053 // Since for dicom compliant and well behaved headers, the present
2054 // test is useless (and might even look a bit paranoid), when we
2055 // encounter such an ill-formed image, we simply display a warning
2056 // message and proceed on parsing (while crossing fingers).
2057 std::ostringstream s;
2058 int filePosition = ftell(fp);
2059 s << "Erroneous Group Length element length on : (" \
2060 << std::hex << group << " , " << element
2061 << ") -before- position x(" << filePosition << ")"
2062 << "lgt : " << length;
2063 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2067 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
2074 * \brief Find the Length till the next sequence delimiter
2075 * \warning NOT end user intended method !
2079 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
2080 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2083 long PositionOnEntry = ftell(fp);
2084 bool FoundSequenceDelimiter = false;
2085 guint32 TotalLength = 0;
2088 while ( ! FoundSequenceDelimiter)
2094 TotalLength += 4; // We even have to decount the group and element
2096 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
2098 char msg[100]; // for sprintf. Sorry
2099 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
2100 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2104 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
2105 FoundSequenceDelimiter = true;
2106 else if ( n != 0xe000 )
2108 char msg[100]; // for sprintf. Sorry
2109 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
2111 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
2115 ItemLength = ReadInt32();
2116 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
2117 // the ItemLength with ReadInt32
2118 SkipBytes(ItemLength);
2120 fseek(fp, PositionOnEntry, SEEK_SET);
2125 * \brief Reads a supposed to be 16 Bits integer
2126 * (swaps it depending on processor endianity)
2127 * @return read value
2129 guint16 gdcmDocument::ReadInt16(void) {
2132 item_read = fread (&g, (size_t)2,(size_t)1, fp);
2133 if ( item_read != 1 ) {
2135 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
2145 * \brief Reads a supposed to be 32 Bits integer
2146 * (swaps it depending on processor endianity)
2147 * @return read value
2149 guint32 gdcmDocument::ReadInt32(void) {
2152 item_read = fread (&g, (size_t)4,(size_t)1, fp);
2153 if ( item_read != 1 ) {
2155 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2165 * \brief skips bytes inside the source file
2166 * \warning NOT end user intended method !
2169 void gdcmDocument::SkipBytes(guint32 NBytes) {
2170 //FIXME don't dump the returned value
2171 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2175 * \brief Loads all the needed Dictionaries
2176 * \warning NOT end user intended method !
2178 void gdcmDocument::Initialise(void)
2180 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2181 RefShaDict = (gdcmDict*)0;
2185 * \brief Discover what the swap code is (among little endian, big endian,
2186 * bad little endian, bad big endian).
2188 * @return false when we are absolutely sure
2189 * it's neither ACR-NEMA nor DICOM
2190 * true when we hope ours assuptions are OK
2192 bool gdcmDocument::CheckSwap() {
2194 // The only guaranted way of finding the swap code is to find a
2195 // group tag since we know it's length has to be of four bytes i.e.
2196 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2197 // occurs when we can't find such group...
2199 guint32 x=4; // x : for ntohs
2200 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2206 char deb[HEADER_LENGTH_TO_READ];
2208 // First, compare HostByteOrder and NetworkByteOrder in order to
2209 // determine if we shall need to swap bytes (i.e. the Endian type).
2215 // The easiest case is the one of a DICOM header, since it possesses a
2216 // file preamble where it suffice to look for the string "DICM".
2217 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2220 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2221 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2223 // Next, determine the value representation (VR). Let's skip to the
2224 // first element (0002, 0000) and check there if we find "UL"
2225 // - or "OB" if the 1st one is (0002,0001) -,
2226 // in which case we (almost) know it is explicit VR.
2227 // WARNING: if it happens to be implicit VR then what we will read
2228 // is the length of the group. If this ascii representation of this
2229 // length happens to be "UL" then we shall believe it is explicit VR.
2230 // FIXME: in order to fix the above warning, we could read the next
2231 // element value (or a couple of elements values) in order to make
2232 // sure we are not commiting a big mistake.
2233 // We need to skip :
2234 // * the 128 bytes of File Preamble (often padded with zeroes),
2235 // * the 4 bytes of "DICM" string,
2236 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2237 // i.e. a total of 136 bytes.
2241 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2242 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2243 // *Implicit* VR. -and it is !-
2245 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2246 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2247 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2248 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2249 // when Write DCM *adds*
2251 // Use gdcmDocument::dicom_vr to test all the possibilities
2252 // instead of just checking for UL, OB and UI !? group 0000
2254 filetype = gdcmExplicitVR;
2255 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2256 "explicit Value Representation");
2260 filetype = gdcmImplicitVR;
2261 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2262 "not an explicit Value Representation");
2268 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2269 "HostByteOrder != NetworkByteOrder");
2274 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2275 "HostByteOrder = NetworkByteOrder");
2278 // Position the file position indicator at first tag (i.e.
2279 // after the file preamble and the "DICM" string).
2281 fseek (fp, 132L, SEEK_SET);
2285 // Alas, this is not a DicomV3 file and whatever happens there is no file
2286 // preamble. We can reset the file position indicator to where the data
2287 // is (i.e. the beginning of the file).
2288 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2291 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2292 // By clean we mean that the length of the first tag is written down.
2293 // If this is the case and since the length of the first group HAS to be
2294 // four (bytes), then determining the proper swap code is straightforward.
2297 // We assume the array of char we are considering contains the binary
2298 // representation of a 32 bits integer. Hence the following dirty
2300 s32 = *((guint32 *)(entCur));
2321 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2322 // It is time for despaired wild guesses.
2323 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2324 // i.e. the 'group length' element is not present :
2326 // check the supposed to be 'group number'
2327 // 0x0002 or 0x0004 or 0x0008
2328 // to determine ' sw' value .
2329 // Only 0 or 4321 will be possible
2330 // (no oportunity to check for the formerly well known
2331 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2332 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2333 // the file IS NOT ACR-NEMA nor DICOM V3
2334 // Find a trick to tell it the caller...
2336 s16 = *((guint16 *)(deb));
2352 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2353 "ACR/NEMA unfound swap info (Really hopeless !)");
2354 filetype = gdcmUnknown;
2358 // Then the only info we have is the net2host one.
2368 * \brief Restore the unproperly loaded values i.e. the group, the element
2369 * and the dictionary entry depending on them.
2371 void gdcmDocument::SwitchSwapToBigEndian(void)
2373 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2374 "Switching to BigEndian mode.");
2395 * \brief during parsing, Header Elements too long are not loaded in memory
2398 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2402 if ((guint32)NewSize >= (guint32)0xffffffff)
2404 MaxSizeLoadEntry = 0xffffffff;
2407 MaxSizeLoadEntry = NewSize;
2412 * \brief Header Elements too long will not be printed
2413 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2416 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2420 if ((guint32)NewSize >= (guint32)0xffffffff)
2422 MaxSizePrintEntry = 0xffffffff;
2425 MaxSizePrintEntry = NewSize;
2431 * \brief Read the next tag but WITHOUT loading it's value
2432 * (read the 'Group Number', the 'Element Number',
2433 * gets the Dict Entry
2434 * gets the VR, gets the length, gets the offset value)
2435 * @return On succes the newly created DocEntry, NULL on failure.
2437 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2439 gdcmDocEntry *NewEntry;
2444 // We reached the EOF (or an error occured) therefore
2445 // header parsing has to be considered as finished.
2446 return (gdcmDocEntry *)0;
2448 // Pb : how to propagate the element length (used in SkipDocEntry)
2449 // direct call to SkipBytes ?
2451 // if (ignoreShadow == 1 && g%2 ==1)
2452 // if user wants to skip shadow groups
2453 // and current element *is* a shadow element
2454 // we don't create anything
2455 // return (gdcmDocEntry *)1; // to tell caller it's NOT finished
2457 NewEntry = NewDocEntryByNumber(g, n);
2458 FindDocEntryVR(NewEntry);
2459 FindDocEntryLength(NewEntry);
2466 NewEntry->SetOffset(ftell(fp));
2471 * \brief Build a new Element Value from all the low level arguments.
2472 * Check for existence of dictionary entry, and build
2473 * a default one when absent.
2474 * @param Name Name of the underlying DictEntry
2476 gdcmDocEntry *gdcmDocument::NewDocEntryByName(std::string Name)
2478 gdcmDictEntry *NewTag = GetDictEntryByName(Name);
2480 NewTag = NewVirtualDictEntry(0xffff, 0xffff, "LO", "unkn", Name);
2482 gdcmDocEntry* NewEntry = new gdcmDocEntry(NewTag);
2485 dbg.Verbose(1, "gdcmDocument::ObtainDocEntryByName",
2486 "failed to allocate gdcmDocEntry");
2487 return (gdcmDocEntry *)0;
2493 * \brief Request a new virtual dict entry to the dict set
2494 * @param group group number of the underlying DictEntry
2495 * @param element element number of the underlying DictEntry
2496 * @param vr VR of the underlying DictEntry
2497 * @param fourth owner group
2498 * @param name english name
2500 gdcmDictEntry *gdcmDocument::NewVirtualDictEntry(guint16 group, guint16 element,
2505 return gdcmGlobal::GetDicts()->NewVirtualDictEntry(group,element,vr,fourth,name);
2509 * \brief Build a new Element Value from all the low level arguments.
2510 * Check for existence of dictionary entry, and build
2511 * a default one when absent.
2512 * @param Group group number of the underlying DictEntry
2513 * @param Elem element number of the underlying DictEntry
2515 gdcmDocEntry *gdcmDocument::NewDocEntryByNumber(guint16 Group, guint16 Elem)
2517 // Find out if the tag we encountered is in the dictionaries:
2518 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2520 DictEntry = NewVirtualDictEntry(Group, Elem);
2522 gdcmDocEntry *NewEntry = new gdcmDocEntry(DictEntry);
2525 dbg.Verbose(1, "gdcmDocument::NewDocEntryByNumber",
2526 "failed to allocate gdcmDocEntry");
2534 * \brief Build a new Element Value from all the low level arguments.
2535 * Check for existence of dictionary entry, and build
2536 * a default one when absent.
2537 * @param Group group number of the underlying DictEntry
2538 * @param Elem element number of the underlying DictEntry
2540 gdcmValEntry *gdcmDocument::NewValEntryByNumber(guint16 Group, guint16 Elem)
2542 // Find out if the tag we encountered is in the dictionaries:
2543 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2545 DictEntry = NewVirtualDictEntry(Group, Elem);
2547 gdcmValEntry *NewEntry = new gdcmValEntry(DictEntry);
2550 dbg.Verbose(1, "gdcmDocument::NewValEntryByNumber",
2551 "failed to allocate gdcmValEntry");
2559 * \brief Build a new Element Value from all the low level arguments.
2560 * Check for existence of dictionary entry, and build
2561 * a default one when absent.
2562 * @param Group group number of the underlying DictEntry
2563 * @param Elem element number of the underlying DictEntry
2565 gdcmBinEntry *gdcmDocument::NewBinEntryByNumber(guint16 Group, guint16 Elem)
2567 // Find out if the tag we encountered is in the dictionaries:
2568 gdcmDictEntry *DictEntry = GetDictEntryByNumber(Group, Elem);
2570 DictEntry = NewVirtualDictEntry(Group, Elem);
2572 gdcmBinEntry *NewEntry = new gdcmBinEntry(DictEntry);
2575 dbg.Verbose(1, "gdcmDocument::NewBinEntryByNumber",
2576 "failed to allocate gdcmBinEntry");
2583 * \brief Generate a free TagKey i.e. a TagKey that is not present
2584 * in the TagHt dictionary.
2585 * @param group The generated tag must belong to this group.
2586 * @return The element of tag with given group which is fee.
2588 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2590 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2592 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2593 if (tagHT.count(key) == 0)
2601 * \brief Searches both the public and the shadow dictionary (when they
2602 * exist) for the presence of the DictEntry with given name.
2603 * The public dictionary has precedence on the shadow one.
2604 * @param Name name of the searched DictEntry
2605 * @return Corresponding DictEntry when it exists, NULL otherwise.
2607 gdcmDictEntry *gdcmDocument::GetDictEntryByName(std::string Name)
2609 gdcmDictEntry *found = (gdcmDictEntry *)0;
2610 if (!RefPubDict && !RefShaDict)
2612 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2613 "we SHOULD have a default dictionary");
2617 found = RefPubDict->GetDictEntryByName(Name);
2623 found = RefShaDict->GetDictEntryByName(Name);
2631 * \brief Searches both the public and the shadow dictionary (when they
2632 * exist) for the presence of the DictEntry with given
2633 * group and element. The public dictionary has precedence on the
2635 * @param group group number of the searched DictEntry
2636 * @param element element number of the searched DictEntry
2637 * @return Corresponding DictEntry when it exists, NULL otherwise.
2639 gdcmDictEntry *gdcmDocument::GetDictEntryByNumber(guint16 group,guint16 element)
2641 gdcmDictEntry *found = (gdcmDictEntry *)0;
2642 if (!RefPubDict && !RefShaDict)
2644 dbg.Verbose(0, "gdcmDocument::GetDictEntry",
2645 "we SHOULD have a default dictionary");
2649 found = RefPubDict->GetDictEntryByNumber(group, element);
2655 found = RefShaDict->GetDictEntryByNumber(group, element);
2663 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2664 * is placed at the beginning of a tag (TestGroup, TestElement),
2665 * read the length associated to the Tag.
2666 * \warning On success the internal file pointer \ref gdcmDocument::fp
2667 * is modified to point after the tag and it's length.
2668 * On failure (i.e. when the tag wasn't the expected tag
2669 * (TestGroup, TestElement) the internal file pointer
2670 * \ref gdcmDocument::fp is restored to it's original position.
2671 * @param TestGroup The expected group of the tag.
2672 * @param TestElement The expected Element of the tag.
2673 * @return On success returns the length associated to the tag. On failure
2676 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2678 guint16 ItemTagGroup;
2679 guint16 ItemTagElement;
2680 long PositionOnEntry = ftell(fp);
2681 long CurrentPosition = ftell(fp); // On debugging purposes
2683 //// Read the Item Tag group and element, and make
2684 // sure they are respectively 0xfffe and 0xe000:
2685 ItemTagGroup = ReadInt16();
2686 ItemTagElement = ReadInt16();
2687 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2689 std::ostringstream s;
2690 s << " We should have found tag (";
2691 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2692 s << " but instead we encountered tag (";
2693 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2695 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2696 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2697 dbg.Verbose(0, s.str().c_str());
2698 fseek(fp, PositionOnEntry, SEEK_SET);
2702 //// Then read the associated Item Length
2703 CurrentPosition=ftell(fp);
2705 ItemLength = ReadInt32();
2707 std::ostringstream s;
2708 s << "Basic Item Length is: "
2709 << ItemLength << std::endl;
2710 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2711 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2717 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2718 * \sa \ref gdcmDocument::ReadTagLength
2719 * \warning See warning of \ref gdcmDocument::ReadTagLength
2720 * @return On success returns the length associated to the item tag.
2721 * On failure returns 0.
2723 guint32 gdcmDocument::ReadItemTagLength(void)
2725 return ReadTagLength(0xfffe, 0xe000);
2729 * \brief Read the length of an exptected Sequence Delimiter tag i.e.
2731 * \sa \ref gdcmDocument::ReadTagLength
2732 * \warning See warning of \ref gdcmDocument::ReadTagLength
2733 * @return On success returns the length associated to the Sequence
2734 * Delimiter tag. On failure returns 0.
2736 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2738 return ReadTagLength(0xfffe, 0xe0dd);
2743 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2744 * No other way so 'skip' the Data
2747 void gdcmDocument::Parse7FE0 (void)
2749 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2753 if ( IsImplicitVRLittleEndianTransferSyntax()
2754 || IsExplicitVRLittleEndianTransferSyntax()
2755 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2756 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2759 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2761 //// Read the Basic Offset Table Item Tag length...
2762 guint32 ItemLength = ReadItemTagLength();
2764 //// ... and then read length[s] itself[themselves]. We don't use
2765 // the values read (BTW what is the purpous of those lengths ?)
2766 if (ItemLength != 0) {
2767 // BTW, what is the purpous of those length anyhow !?
2768 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2769 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2770 for (int i=0; i < ItemLength; i += 4){
2771 guint32 IndividualLength;
2772 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2773 std::ostringstream s;
2774 s << " Read one length: ";
2775 s << std::hex << IndividualLength << std::endl;
2776 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2780 if ( ! IsRLELossLessTransferSyntax() )
2784 //// We then skip (not reading them) all the fragments of images:
2785 while ( ItemLength = ReadItemTagLength() )
2787 SkipBytes(ItemLength);
2795 long RleSegmentLength[15], fragmentLength;
2797 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2798 while ( fragmentLength = ReadSequenceDelimiterTagLength() )
2800 // Parse fragments of the current Fragment (Frame)
2801 //------------------ scanning (not reading) fragment pixels
2802 guint32 nbRleSegments = ReadInt32();
2803 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2805 //// Reading RLE Segments Offset Table
2806 guint32 RleSegmentOffsetTable[15];
2807 for(int k=1; k<=15; k++) {
2809 RleSegmentOffsetTable[k] = ReadInt32();
2810 printf(" at : %x Offset Segment %d : %d (%x)\n",
2811 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2812 RleSegmentOffsetTable[k]);
2815 // skipping (not reading) RLE Segments
2816 if (nbRleSegments>1) {
2817 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2818 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2819 - RleSegmentOffsetTable[k];
2821 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2822 k,(unsigned)RleSegmentLength[k],
2823 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2824 SkipBytes(RleSegmentLength[k]);
2828 RleSegmentLength[nbRleSegments]= fragmentLength
2829 - RleSegmentOffsetTable[nbRleSegments];
2831 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2832 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2833 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2834 SkipBytes(RleSegmentLength[nbRleSegments]);
2841 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2842 * \warning Does NOT work with ACR-NEMA files
2843 * \todo Find a trick to solve the pb (use RET fields ?)
2845 * @return true if 'smaller'
2847 bool gdcmDocument::operator<(gdcmDocument &document){
2851 s1=this->GetEntryByNumber(0x0010,0x0010);
2852 s2=document.GetEntryByNumber(0x0010,0x0010);
2860 s1=this->GetEntryByNumber(0x0010,0x0020);
2861 s2=document.GetEntryByNumber(0x0010,0x0020);
2868 // Study Instance UID
2869 s1=this->GetEntryByNumber(0x0020,0x000d);
2870 s2=document.GetEntryByNumber(0x0020,0x000d);
2877 // Serie Instance UID
2878 s1=this->GetEntryByNumber(0x0020,0x000e);
2879 s2=document.GetEntryByNumber(0x0020,0x000e);
2891 //-----------------------------------------------------------------------------