1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/11/15 16:12:30 $
7 Version: $Revision: 1.123 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
23 #include "gdcmGlobal.h"
25 #include "gdcmDebug.h"
31 #if defined(_MSC_VER) || defined(__BORLANDC__)
34 #include <netinet/in.h>
39 static const char *TransferSyntaxStrings[] = {
40 // Implicit VR Little Endian
42 // Explicit VR Little Endian
43 "1.2.840.10008.1.2.1",
44 // Deflated Explicit VR Little Endian
45 "1.2.840.10008.1.2.1.99",
46 // Explicit VR Big Endian
47 "1.2.840.10008.1.2.2",
48 // JPEG Baseline (Process 1)
49 "1.2.840.10008.1.2.4.50",
50 // JPEG Extended (Process 2 & 4)
51 "1.2.840.10008.1.2.4.51",
52 // JPEG Extended (Process 3 & 5)
53 "1.2.840.10008.1.2.4.52",
54 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
55 "1.2.840.10008.1.2.4.53",
56 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
57 "1.2.840.10008.1.2.4.55",
58 // JPEG Lossless, Non-Hierarchical (Process 14)
59 "1.2.840.10008.1.2.4.57",
60 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14, [Selection Value 1])
61 "1.2.840.10008.1.2.4.70",
63 "1.2.840.10008.1.2.4.90",
65 "1.2.840.10008.1.2.4.91",
67 "1.2.840.10008.1.2.5",
69 "Unknown Transfer Syntax"
72 //-----------------------------------------------------------------------------
73 // Refer to Document::CheckSwap()
74 const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
76 // Refer to Document::SetMaxSizeLoadEntry()
77 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
78 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
80 //-----------------------------------------------------------------------------
81 // Constructor / Destructor
85 * @param filename file to be opened for parsing
87 Document::Document( std::string const & filename ) : ElementSet(-1)
89 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
99 dbg.Verbose(0, "Document::Document: starting parsing of file: ",
101 Fp->seekg( 0, std::ios_base::beg);
103 Fp->seekg(0, std::ios_base::end);
104 long lgt = Fp->tellg();
106 Fp->seekg( 0, std::ios_base::beg);
108 long beg = Fp->tellg();
111 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
113 Fp->seekg( 0, std::ios_base::beg);
115 // Load 'non string' values
117 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
118 if( PhotometricInterpretation == "PALETTE COLOR " )
120 LoadEntryBinArea(0x0028,0x1200); // gray LUT
121 /// FIXME FIXME FIXME
122 /// The tags refered by the three following lines used to be CORRECTLY
123 /// defined as having an US Value Representation in the public
124 /// dictionnary. BUT the semantics implied by the three following
125 /// lines state that the corresponding tag contents are in fact
126 /// the ones of a BinEntry.
127 /// In order to fix things "Quick and Dirty" the dictionnary was
128 /// altered on PURPOUS but now contains a WRONG value.
129 /// In order to fix things and restore the dictionary to its
130 /// correct value, one needs to decided of the semantics by deciding
131 /// wether the following tags are either:
132 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
133 /// also used as BinEntry, which requires the proper conversion,
134 /// - OW, and hence loaded as BinEntry, but afterwards also used
135 /// as ValEntry, which requires the proper conversion.
136 LoadEntryBinArea(0x0028,0x1201); // R LUT
137 LoadEntryBinArea(0x0028,0x1202); // G LUT
138 LoadEntryBinArea(0x0028,0x1203); // B LUT
140 // Segmented Red Palette Color LUT Data
141 LoadEntryBinArea(0x0028,0x1221);
142 // Segmented Green Palette Color LUT Data
143 LoadEntryBinArea(0x0028,0x1222);
144 // Segmented Blue Palette Color LUT Data
145 LoadEntryBinArea(0x0028,0x1223);
147 //FIXME later : how to use it?
148 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
152 // --------------------------------------------------------------
153 // Specific code to allow gdcm to read ACR-LibIDO formated images
154 // Note: ACR-LibIDO is an extension of the ACR standard that was
155 // used at CREATIS. For the time being (say a couple years)
156 // we keep this kludge to allow a smooth move to gdcm for
157 // CREATIS developpers (sorry folks).
159 // if recognition code tells us we deal with a LibIDO image
160 // we switch lineNumber and columnNumber
163 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
164 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
165 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
166 // with "little-endian strings"
168 Filetype = ACR_LIBIDO;
169 std::string rows = GetEntryByNumber(0x0028, 0x0010);
170 std::string columns = GetEntryByNumber(0x0028, 0x0011);
171 SetEntryByNumber(columns, 0x0028, 0x0010);
172 SetEntryByNumber(rows , 0x0028, 0x0011);
174 // ----------------- End of ACR-LibIDO kludge ------------------
176 PrintLevel = 1; // 'Medium' print level by default
180 * \brief This default constructor doesn't parse the file. You should
181 * then invoke \ref Document::SetFileName and then the parsing.
183 Document::Document() : ElementSet(-1)
187 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
190 Filetype = ExplicitVR;
191 PrintLevel = 1; // 'Medium' print level by default
195 * \brief Canonical destructor.
197 Document::~Document ()
202 // Recursive clean up of sequences
203 for (TagDocEntryHT::const_iterator it = TagHT.begin();
204 it != TagHT.end(); ++it )
206 //delete it->second; //temp remove
213 //-----------------------------------------------------------------------------
217 * \brief Prints The Dict Entries of THE public Dicom Dictionary
220 void Document::PrintPubDict(std::ostream & os)
222 RefPubDict->Print(os);
226 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
229 void Document::PrintShaDict(std::ostream & os)
231 RefShaDict->Print(os);
234 //-----------------------------------------------------------------------------
237 * \brief Get the public dictionary used
239 Dict* Document::GetPubDict()
245 * \brief Get the shadow dictionary used
247 Dict* Document::GetShaDict()
253 * \brief Set the shadow dictionary used
254 * \param dict dictionary to use in shadow
256 bool Document::SetShaDict(Dict *dict)
263 * \brief Set the shadow dictionary used
264 * \param dictName name of the dictionary to use in shadow
266 bool Document::SetShaDict(DictKey const & dictName)
268 RefShaDict = Global::GetDicts()->GetDict(dictName);
273 * \brief This predicate, based on hopefully reasonable heuristics,
274 * decides whether or not the current Document was properly parsed
275 * and contains the mandatory information for being considered as
276 * a well formed and usable Dicom/Acr File.
277 * @return true when Document is the one of a reasonable Dicom/Acr file,
280 bool Document::IsReadable()
282 if( Filetype == Unknown)
284 dbg.Verbose(0, "Document::IsReadable: wrong filetype");
290 dbg.Verbose(0, "Document::IsReadable: no tags in internal"
300 * \brief Internal function that checks whether the Transfer Syntax given
301 * as argument is the one present in the current document.
302 * @param syntaxToCheck The transfert syntax we need to check against.
303 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
304 * the current document. False either when the document contains
305 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
307 TransferSyntaxType Document::GetTransferSyntax()
309 DocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
315 // The entry might be present but not loaded (parsing and loading
316 // happen at different stages): try loading and proceed with check...
317 LoadDocEntrySafe(entry);
318 if (ValEntry* valEntry = dynamic_cast< ValEntry* >(entry) )
320 std::string transfer = valEntry->GetValue();
321 // The actual transfer (as read from disk) might be padded. We
322 // first need to remove the potential padding. We can make the
323 // weak assumption that padding was not executed with digits...
324 if ( transfer.length() == 0 )
326 // for brain damaged headers
329 while ( !isdigit(transfer[transfer.length()-1]) )
331 transfer.erase(transfer.length()-1, 1);
333 for (int i = 0; TransferSyntaxStrings[i] != NULL; i++)
335 if ( TransferSyntaxStrings[i] == transfer )
337 return TransferSyntaxType(i);
344 bool Document::IsJPEGLossless()
346 TransferSyntaxType r = GetTransferSyntax();
347 return r == JPEGFullProgressionProcess10_12
348 || r == JPEGLosslessProcess14
349 || r == JPEGLosslessProcess14_1;
353 * \brief Determines if the Transfer Syntax was already encountered
354 * and if it corresponds to a JPEG2000 one
355 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
358 bool Document::IsJPEG2000()
360 TransferSyntaxType r = GetTransferSyntax();
361 return r == JPEG2000Lossless || r == JPEG2000;
365 * \brief Determines if the Transfer Syntax corresponds to any form
366 * of Jpeg encoded Pixel data.
367 * @return True when any form of JPEG found. False otherwise.
369 bool Document::IsJPEG()
371 TransferSyntaxType r = GetTransferSyntax();
372 return r == JPEGBaselineProcess1
373 || r == JPEGExtendedProcess2_4
374 || r == JPEGExtendedProcess3_5
375 || r == JPEGSpectralSelectionProcess6_8
381 * \brief Determines if the Transfer Syntax corresponds to encapsulated
382 * of encoded Pixel Data (as opposed to native).
383 * @return True when encapsulated. False when native.
385 bool Document::IsEncapsulate()
387 TransferSyntaxType r = GetTransferSyntax();
388 return IsJPEG() || r == RLELossless;
392 * \brief Predicate for dicom version 3 file.
393 * @return True when the file is a dicom version 3.
395 bool Document::IsDicomV3()
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 Document::GetFileType()
415 * \brief Tries to open the file \ref Document::Filename and
416 * checks the preamble when existing.
417 * @return The FILE pointer on success.
419 std::ifstream* Document::OpenFile()
421 if (Filename.length() == 0) return 0;
425 "Document::OpenFile is already opened when opening: ",
429 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
434 "Document::OpenFile cannot open file: ",
440 Fp->read((char*)&zero, (size_t)2 );
442 //ACR -- or DICOM with no Preamble --
443 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
449 Fp->seekg(126L, std::ios_base::cur);
451 Fp->read(dicm, (size_t)4);
452 if( memcmp(dicm, "DICM", 4) == 0 )
459 "Document::OpenFile not DICOM/ACR (missing preamble)",
466 * \brief closes the file
467 * @return TRUE if the close was successfull
469 bool Document::CloseFile()
478 return true; //FIXME how do we detect a non-close ifstream ?
482 * \brief Writes in a file all the Header Entries (Dicom Elements)
483 * @param fp file pointer on an already open file
484 * @param filetype Type of the File to be written
485 * (ACR-NEMA, ExplicitVR, ImplicitVR)
486 * \return Always true.
488 void Document::Write(std::ofstream* fp, FileType filetype)
490 /// \todo move the following lines (and a lot of others, to be written)
491 /// to a future function CheckAndCorrectHeader
492 /// (necessary if user wants to write a DICOM V3 file
493 /// starting from an ACR-NEMA (V2) Header
495 if (filetype == ImplicitVR)
498 Util::DicomString( TransferSyntaxStrings[ImplicitVRLittleEndian] );
499 ReplaceOrCreateByNumber(ts, 0x0002, 0x0010);
501 /// \todo Refer to standards on page 21, chapter 6.2
502 /// "Value representation": values with a VR of UI shall be
503 /// padded with a single trailing null
504 /// in the following case we have to padd manually with a 0
506 SetEntryLengthByNumber(18, 0x0002, 0x0010);
509 if (filetype == ExplicitVR)
512 Util::DicomString( TransferSyntaxStrings[ExplicitVRLittleEndian] );
513 ReplaceOrCreateByNumber(ts, 0x0002, 0x0010); //LEAK
515 /// \todo Refer to standards on page 21, chapter 6.2
516 /// "Value representation": values with a VR of UI shall be
517 /// padded with a single trailing null
518 /// Dans le cas suivant on doit pader manuellement avec un 0
520 SetEntryLengthByNumber(20, 0x0002, 0x0010);
524 * \todo rewrite later, if really usefull
525 * - 'Group Length' element is optional in DICOM
526 * - but un-updated odd groups lengthes can causes pb
529 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
530 * UpdateGroupLength(false,filetype);
531 * if ( filetype == ACR)
532 * UpdateGroupLength(true,ACR);
535 ElementSet::Write(fp, filetype); // This one is recursive
540 * \brief Modifies the value of a given Header Entry (Dicom Element)
541 * when it exists. Create it with the given value when unexistant.
542 * @param value (string) Value to be set
543 * @param group Group number of the Entry
544 * @param elem Element number of the Entry
545 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
546 * \return pointer to the modified/created Header Entry (NULL when creation
549 ValEntry* Document::ReplaceOrCreateByNumber(
550 std::string const & value,
555 ValEntry* valEntry = 0;
556 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
560 // check if (group,element) DictEntry exists
561 // if it doesn't, create an entry in DictSet::VirtualEntry
564 // Find out if the tag we received is in the dictionaries:
565 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
566 DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
569 currentEntry = NewDocEntryByNumber(group, elem, vr);
573 currentEntry = NewDocEntryByNumber(group, elem);
578 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
579 " NewDocEntryByNumber failed.");
582 valEntry = new ValEntry(currentEntry);
583 if ( !AddEntry(valEntry))
586 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
587 " failed allthough this is a creation.");
589 // This is the reason why NewDocEntryByNumber are a real
590 // bad habit !!! FIXME
595 valEntry = dynamic_cast< ValEntry* >(currentEntry);
596 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
597 // then we change it to a ValEntry ?
598 // Shouldn't it be considered as an error ?
600 // We need to promote the DocEntry to a ValEntry:
601 valEntry = new ValEntry(currentEntry);
602 if (!RemoveEntry(currentEntry))
605 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
606 " of previous DocEntry failed.");
609 if ( !AddEntry(valEntry))
612 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
613 " promoted ValEntry failed.");
619 SetEntryByNumber(value, group, elem);
625 * \brief Modifies the value of a given Header Entry (Dicom Element)
626 * when it exists. Create it with the given value when unexistant.
627 * @param binArea (binary) value to be set
628 * @param Group Group number of the Entry
629 * @param Elem Element number of the Entry
630 * \return pointer to the modified/created Header Entry (NULL when creation
633 BinEntry* Document::ReplaceOrCreateByNumber(
640 BinEntry* binEntry = 0;
641 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
645 // check if (group,element) DictEntry exists
646 // if it doesn't, create an entry in DictSet::VirtualEntry
649 // Find out if the tag we received is in the dictionaries:
650 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
651 DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
655 currentEntry = NewDocEntryByNumber(group, elem, vr);
659 currentEntry = NewDocEntryByNumber(group, elem);
663 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
664 " NewDocEntryByNumber failed.");
667 binEntry = new BinEntry(currentEntry);
668 if ( !AddEntry(binEntry))
670 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
671 " failed allthough this is a creation.");
676 binEntry = dynamic_cast< BinEntry* >(currentEntry);
677 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
678 // then we change it to a BinEntry ?
679 // Shouldn't it be considered as an error ?
681 // We need to promote the DocEntry to a BinEntry:
682 binEntry = new BinEntry(currentEntry);
683 if (!RemoveEntry(currentEntry))
685 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
686 " of previous DocEntry failed.");
689 if ( !AddEntry(binEntry))
691 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
692 " promoted BinEntry failed.");
698 SetEntryByNumber(binArea, lgth, group, elem);
705 * \brief Modifies the value of a given Header Entry (Dicom Element)
706 * when it exists. Create it when unexistant.
707 * @param Group Group number of the Entry
708 * @param Elem Element number of the Entry
709 * \return pointer to the modified/created SeqEntry (NULL when creation
712 SeqEntry* Document::ReplaceOrCreateByNumber( uint16_t group, uint16_t elem)
715 DocEntry* a = GetDocEntryByNumber( group, elem);
718 a = NewSeqEntryByNumber(group, elem);
724 b = new SeqEntry(a, 1); // FIXME : 1 (Depth)
731 * \brief Set a new value if the invoked element exists
732 * Seems to be useless !!!
733 * @param value new element value
734 * @param group group number of the Entry
735 * @param elem element number of the Entry
738 bool Document::ReplaceIfExistByNumber(std::string const & value,
739 uint16_t group, uint16_t elem )
741 SetEntryByNumber(value, group, elem);
746 //-----------------------------------------------------------------------------
750 * \brief Checks if a given Dicom Element exists within the H table
751 * @param group Group number of the searched Dicom Element
752 * @param element Element number of the searched Dicom Element
753 * @return true is found
755 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
757 const std::string &key = DictEntry::TranslateToKey(group, element );
758 return TagHT.count(key) != 0;
762 * \brief Searches within Header Entries (Dicom Elements) parsed with
763 * the public and private dictionaries
764 * for the element value of a given tag.
765 * \warning Don't use any longer : use GetPubEntryByName
766 * @param tagName name of the searched element.
767 * @return Corresponding element value when it exists,
768 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
770 std::string Document::GetEntryByName(TagName const & tagName)
772 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
778 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
782 * \brief Searches within Header Entries (Dicom Elements) parsed with
783 * the public and private dictionaries
784 * for the element value representation of a given tag.
786 * Obtaining the VR (Value Representation) might be needed by caller
787 * to convert the string typed content to caller's native type
788 * (think of C++ vs Python). The VR is actually of a higher level
789 * of semantics than just the native C++ type.
790 * @param tagName name of the searched element.
791 * @return Corresponding element value representation when it exists,
792 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
794 std::string Document::GetEntryVRByName(TagName const& tagName)
796 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
797 if( dictEntry == NULL)
802 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
803 dictEntry->GetElement());
804 return elem->GetVR();
808 * \brief Searches within Header Entries (Dicom Elements) parsed with
809 * the public and private dictionaries
810 * for the element value representation of a given tag.
811 * @param group Group number of the searched tag.
812 * @param element Element number of the searched tag.
813 * @return Corresponding element value representation when it exists,
814 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
816 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
818 TagKey key = DictEntry::TranslateToKey(group, element);
819 /// \todo use map methods, instead of multimap JPR
820 if ( !TagHT.count(key))
825 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
829 * \brief Searches within Header Entries (Dicom Elements) parsed with
830 * the public and private dictionaries
831 * for the element value representation of a given tag..
833 * Obtaining the VR (Value Representation) might be needed by caller
834 * to convert the string typed content to caller's native type
835 * (think of C++ vs Python). The VR is actually of a higher level
836 * of semantics than just the native C++ type.
837 * @param group Group number of the searched tag.
838 * @param element Element number of the searched tag.
839 * @return Corresponding element value representation when it exists,
840 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
842 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
844 DocEntry* elem = GetDocEntryByNumber(group, element);
849 return elem->GetVR();
853 * \brief Searches within Header Entries (Dicom Elements) parsed with
854 * the public and private dictionaries
855 * for the value length of a given tag..
856 * @param group Group number of the searched tag.
857 * @param element Element number of the searched tag.
858 * @return Corresponding element length; -2 if not found
860 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
862 DocEntry* elem = GetDocEntryByNumber(group, element);
865 return -2; //magic number
867 return elem->GetLength();
870 * \brief Sets the value (string) of the Header Entry (Dicom Element)
871 * @param content string value of the Dicom Element
872 * @param tagName name of the searched Dicom Element.
873 * @return true when found
875 bool Document::SetEntryByName(std::string const & content,
876 TagName const & tagName)
878 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
884 return SetEntryByNumber(content,dictEntry->GetGroup(),
885 dictEntry->GetElement());
889 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
890 * through it's (group, element) and modifies it's content with
892 * @param content new value (string) to substitute with
893 * @param group group number of the Dicom Element to modify
894 * @param element element number of the Dicom Element to modify
896 bool Document::SetEntryByNumber(std::string const& content,
897 uint16_t group, uint16_t element)
902 ValEntry* valEntry = GetValEntryByNumber(group, element);
905 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
906 " ValEntry (try promotion first).");
909 // Non even content must be padded with a space (020H)...
910 std::string finalContent = Util::DicomString( content.c_str() );
911 assert( !(finalContent.size() % 2) );
912 valEntry->SetValue(finalContent);
914 // Integers have a special treatement for their length:
916 l = finalContent.length();
917 if ( l != 0) // To avoid to be cheated by 'zero length' integers
919 VRKey vr = valEntry->GetVR();
920 if( vr == "US" || vr == "SS" )
922 // for multivaluated items
923 c = Util::CountSubstring(content, "\\") + 1;
926 else if( vr == "UL" || vr == "SL" )
928 // for multivaluated items
929 c = Util::CountSubstring(content, "\\") + 1;
933 valEntry->SetLength(l);
938 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
939 * through it's (group, element) and modifies it's content with
941 * @param content new value (void* -> uint8_t*) to substitute with
942 * @param lgth new value length
943 * @param group group number of the Dicom Element to modify
944 * @param element element number of the Dicom Element to modify
946 bool Document::SetEntryByNumber(uint8_t*content, int lgth,
947 uint16_t group, uint16_t element)
949 (void)lgth; //not used
950 TagKey key = DictEntry::TranslateToKey(group, element);
951 if ( !TagHT.count(key))
956 /* Hope Binary field length is *never* wrong
957 if(lgth%2) // Non even length are padded with a space (020H).
960 //content = content + '\0'; // fing a trick to enlarge a binary field?
963 BinEntry* a = (BinEntry *)TagHT[key];
964 a->SetBinArea(content);
966 a->SetValue(GDCM_BINLOADED);
972 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
973 * in the PubDocEntrySet of this instance
974 * through it's (group, element) and modifies it's length with
976 * \warning Use with extreme caution.
977 * @param l new length to substitute with
978 * @param group group number of the Entry to modify
979 * @param element element number of the Entry to modify
980 * @return true on success, false otherwise.
982 bool Document::SetEntryLengthByNumber(uint32_t l,
983 uint16_t group, uint16_t element)
985 /// \todo use map methods, instead of multimap JPR
986 TagKey key = DictEntry::TranslateToKey(group, element);
987 if ( !TagHT.count(key) )
993 l++; // length must be even
995 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1001 * \brief Gets (from Header) the offset of a 'non string' element value
1002 * (LoadElementValues has already be executed)
1003 * @param group group number of the Entry
1004 * @param elem element number of the Entry
1005 * @return File Offset of the Element Value
1007 size_t Document::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1009 DocEntry* entry = GetDocEntryByNumber(group, elem);
1012 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry present.");
1015 return entry->GetOffset();
1019 * \brief Gets (from Header) a 'non string' element value
1020 * (LoadElementValues has already be executed)
1021 * @param group group number of the Entry
1022 * @param elem element number of the Entry
1023 * @return Pointer to the 'non string' area
1025 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1027 DocEntry* entry = GetDocEntryByNumber(group, elem);
1030 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
1033 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
1035 return binEntry->GetBinArea();
1042 * \brief Loads (from disk) the element content
1043 * when a string is not suitable
1044 * @param group group number of the Entry
1045 * @param elem element number of the Entry
1047 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1049 // Search the corresponding DocEntry
1050 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1054 size_t o =(size_t)docElement->GetOffset();
1055 Fp->seekg( o, std::ios_base::beg);
1056 size_t l = docElement->GetLength();
1057 uint8_t* a = new uint8_t[l];
1060 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1065 Fp->read((char*)a, l);
1066 if( Fp->fail() || Fp->eof() )//Fp->gcount() == 1
1072 // Set the value to the DocEntry
1073 if( !SetEntryBinAreaByNumber( a, group, elem ) )
1076 dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1080 * \brief Loads (from disk) the element content
1081 * when a string is not suitable
1082 * @param element Entry whose binArea is going to be loaded
1084 void Document::LoadEntryBinArea(BinEntry* element)
1086 size_t o =(size_t)element->GetOffset();
1087 Fp->seekg(o, std::ios_base::beg);
1088 size_t l = element->GetLength();
1089 uint8_t* a = new uint8_t[l];
1092 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1096 /// \todo check the result
1097 Fp->read((char*)a, l);
1098 if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1104 element->SetBinArea((uint8_t*)a);
1108 * \brief Sets a 'non string' value to a given Dicom Element
1109 * @param area area containing the 'non string' value
1110 * @param group Group number of the searched Dicom Element
1111 * @param element Element number of the searched Dicom Element
1114 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1115 uint16_t group, uint16_t element)
1117 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1118 if ( !currentEntry )
1123 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1125 binEntry->SetBinArea( area );
1133 * \brief Update the entries with the shadow dictionary.
1134 * Only non even entries are analyzed
1136 void Document::UpdateShaEntries()
1141 /// \todo TODO : still any use to explore recursively the whole structure?
1143 for(ListTag::iterator it=listEntries.begin();
1144 it!=listEntries.end();
1147 // Odd group => from public dictionary
1148 if((*it)->GetGroup()%2==0)
1151 // Peer group => search the corresponding dict entry
1153 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1157 if((*it)->IsImplicitVR())
1162 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1164 // Set the new entry and the new value
1165 (*it)->SetDictEntry(entry);
1166 CheckDocEntryVR(*it,vr);
1168 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1173 // Remove precedent value transformation
1174 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1181 * \brief Searches within the Header Entries for a Dicom Element of
1183 * @param tagName name of the searched Dicom Element.
1184 * @return Corresponding Dicom Element when it exists, and NULL
1187 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1189 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1195 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1199 * \brief retrieves a Dicom Element (the first one) using (group, element)
1200 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1201 * if you think it's NOT UNIQUE, check the count number
1202 * and use iterators to retrieve ALL the Dicoms Elements within
1203 * a given couple (group, element)
1204 * @param group Group number of the searched Dicom Element
1205 * @param element Element number of the searched Dicom Element
1208 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element)
1210 TagKey key = DictEntry::TranslateToKey(group, element);
1211 if ( !TagHT.count(key))
1215 return TagHT.find(key)->second;
1219 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1220 * returns a result when the corresponding entry is of type
1222 * @return When present, the corresponding ValEntry.
1224 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1226 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1227 if ( !currentEntry )
1231 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1235 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1241 * \brief Loads the element while preserving the current
1242 * underlying file position indicator as opposed to
1243 * to LoadDocEntry that modifies it.
1244 * @param entry Header Entry whose value shall be loaded.
1247 void Document::LoadDocEntrySafe(DocEntry * entry)
1249 long PositionOnEntry = Fp->tellg();
1250 LoadDocEntry(entry);
1251 Fp->seekg(PositionOnEntry, std::ios_base::beg);
1255 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1257 * @return The properly swaped 32 bits integer.
1259 uint32_t Document::SwapLong(uint32_t a)
1266 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1267 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1271 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1275 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1278 //std::cout << "swapCode= " << SwapCode << std::endl;
1279 dbg.Error(" Document::SwapLong : unset swap code");
1286 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1288 * @return The properly unswaped 32 bits integer.
1290 uint32_t Document::UnswapLong(uint32_t a)
1296 * \brief Swaps the bytes so they agree with the processor order
1297 * @return The properly swaped 16 bits integer.
1299 uint16_t Document::SwapShort(uint16_t a)
1301 if ( SwapCode == 4321 || SwapCode == 2143 )
1303 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1309 * \brief Unswaps the bytes so they agree with the processor order
1310 * @return The properly unswaped 16 bits integer.
1312 uint16_t Document::UnswapShort(uint16_t a)
1314 return SwapShort(a);
1317 //-----------------------------------------------------------------------------
1321 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1322 * @return length of the parsed set.
1324 void Document::ParseDES(DocEntrySet *set, long offset,
1325 long l_max, bool delim_mode)
1327 DocEntry *newDocEntry = 0;
1331 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1335 newDocEntry = ReadNextDocEntry( );
1341 VRKey vr = newDocEntry->GetVR();
1345 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1347 /////////////////////// ValEntry
1348 ValEntry* newValEntry =
1349 new ValEntry( newDocEntry->GetDictEntry() );
1350 newValEntry->Copy( newDocEntry );
1352 // When "set" is a Document, then we are at the top of the
1353 // hierarchy and the Key is simply of the form ( group, elem )...
1354 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1357 newValEntry->SetKey( newValEntry->GetKey() );
1359 // ...but when "set" is a SQItem, we are inserting this new
1360 // valEntry in a sequence item. Hence the key has the
1361 // generalized form (refer to \ref BaseTagKey):
1362 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1364 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1365 + newValEntry->GetKey() );
1368 set->AddEntry( newValEntry );
1369 LoadDocEntry( newValEntry );
1370 if (newValEntry->IsItemDelimitor())
1374 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1381 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1383 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1384 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1385 "nor BinEntry. Probably unknown VR.");
1388 //////////////////// BinEntry or UNKOWN VR:
1389 BinEntry* newBinEntry =
1390 new BinEntry( newDocEntry->GetDictEntry() ); //LEAK
1391 newBinEntry->Copy( newDocEntry );
1393 // When "this" is a Document the Key is simply of the
1394 // form ( group, elem )...
1395 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1398 newBinEntry->SetKey( newBinEntry->GetKey() );
1400 // but when "this" is a SQItem, we are inserting this new
1401 // valEntry in a sequence item, and the kay has the
1402 // generalized form (refer to \ref BaseTagKey):
1403 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1405 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1406 + newBinEntry->GetKey() );
1409 set->AddEntry( newBinEntry );
1410 LoadDocEntry( newBinEntry );
1413 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1414 && ( newDocEntry->GetElement() == 0x0010 ) )
1416 TransferSyntaxType ts = GetTransferSyntax();
1417 if ( ts == RLELossless )
1419 long PositionOnEntry = Fp->tellg();
1420 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1422 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1424 else if ( IsJPEG() )
1426 long PositionOnEntry = Fp->tellg();
1427 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1428 ComputeJPEGFragmentInfo();
1429 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1433 // Just to make sure we are at the beginning of next entry.
1434 SkipToNextDocEntry(newDocEntry);
1439 unsigned long l = newDocEntry->GetReadLength();
1440 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1442 if ( l == 0xffffffff )
1451 // no other way to create it ...
1452 SeqEntry* newSeqEntry =
1453 new SeqEntry( newDocEntry->GetDictEntry() );
1454 newSeqEntry->Copy( newDocEntry );
1455 newSeqEntry->SetDelimitorMode( delim_mode );
1457 // At the top of the hierarchy, stands a Document. When "set"
1458 // is a Document, then we are building the first depth level.
1459 // Hence the SeqEntry we are building simply has a depth
1461 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1464 newSeqEntry->SetDepthLevel( 1 );
1465 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1467 // But when "set" is allready a SQItem, we are building a nested
1468 // sequence, and hence the depth level of the new SeqEntry
1469 // we are building, is one level deeper:
1470 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1472 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1473 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1474 + newSeqEntry->GetKey() );
1478 { // Don't try to parse zero-length sequences
1479 ParseSQ( newSeqEntry,
1480 newDocEntry->GetOffset(),
1483 set->AddEntry( newSeqEntry );
1484 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1494 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1495 * @return parsed length for this level
1497 void Document::ParseSQ( SeqEntry* seqEntry,
1498 long offset, long l_max, bool delim_mode)
1500 int SQItemNumber = 0;
1505 DocEntry* newDocEntry = ReadNextDocEntry();
1508 // FIXME Should warn user
1513 if ( newDocEntry->IsSequenceDelimitor() )
1515 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1519 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1524 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1525 std::ostringstream newBase;
1526 newBase << seqEntry->GetKey()
1530 itemSQ->SetBaseTagKey( newBase.str() );
1531 unsigned int l = newDocEntry->GetReadLength();
1533 if ( l == 0xffffffff )
1542 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1544 seqEntry->AddEntry( itemSQ, SQItemNumber );
1546 if ( !delim_mode && ( Fp->tellg() - offset ) >= l_max )
1554 * \brief Loads the element content if its length doesn't exceed
1555 * the value specified with Document::SetMaxSizeLoadEntry()
1556 * @param entry Header Entry (Dicom Element) to be dealt with
1558 void Document::LoadDocEntry(DocEntry* entry)
1560 uint16_t group = entry->GetGroup();
1561 std::string vr = entry->GetVR();
1562 uint32_t length = entry->GetLength();
1564 Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1566 // A SeQuence "contains" a set of Elements.
1567 // (fffe e000) tells us an Element is beginning
1568 // (fffe e00d) tells us an Element just ended
1569 // (fffe e0dd) tells us the current SeQuence just ended
1570 if( group == 0xfffe )
1572 // NO more value field for SQ !
1576 // When the length is zero things are easy:
1579 ((ValEntry *)entry)->SetValue("");
1583 // The elements whose length is bigger than the specified upper bound
1584 // are not loaded. Instead we leave a short notice of the offset of
1585 // the element content and it's length.
1587 std::ostringstream s;
1588 if (length > MaxSizeLoadEntry)
1590 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1592 //s << "gdcm::NotLoaded (BinEntry)";
1593 s << GDCM_NOTLOADED;
1594 s << " Address:" << (long)entry->GetOffset();
1595 s << " Length:" << entry->GetLength();
1596 s << " x(" << std::hex << entry->GetLength() << ")";
1597 binEntryPtr->SetValue(s.str());
1599 // Be carefull : a BinEntry IS_A ValEntry ...
1600 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1602 // s << "gdcm::NotLoaded. (ValEntry)";
1603 s << GDCM_NOTLOADED;
1604 s << " Address:" << (long)entry->GetOffset();
1605 s << " Length:" << entry->GetLength();
1606 s << " x(" << std::hex << entry->GetLength() << ")";
1607 valEntryPtr->SetValue(s.str());
1612 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1613 << "nor a ValEntry ?! Should never print that !" << std::endl;
1616 // to be sure we are at the end of the value ...
1617 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1618 std::ios_base::beg);
1622 // When we find a BinEntry not very much can be done :
1623 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1625 s << GDCM_BINLOADED;
1626 binEntryPtr->SetValue(s.str());
1627 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1631 /// \todo Any compacter code suggested (?)
1632 if ( IsDocEntryAnInteger(entry) )
1636 // When short integer(s) are expected, read and convert the following
1637 // n *two characters properly i.e. consider them as short integers as
1638 // opposed to strings.
1639 // Elements with Value Multiplicity > 1
1640 // contain a set of integers (not a single one)
1641 if (vr == "US" || vr == "SS")
1644 NewInt = ReadInt16();
1648 for (int i=1; i < nbInt; i++)
1651 NewInt = ReadInt16();
1656 // See above comment on multiple integers (mutatis mutandis).
1657 else if (vr == "UL" || vr == "SL")
1660 NewInt = ReadInt32();
1664 for (int i=1; i < nbInt; i++)
1667 NewInt = ReadInt32();
1672 #ifdef GDCM_NO_ANSI_STRING_STREAM
1673 s << std::ends; // to avoid oddities on Solaris
1674 #endif //GDCM_NO_ANSI_STRING_STREAM
1676 ((ValEntry *)entry)->SetValue(s.str());
1680 // FIXME: We need an additional byte for storing \0 that is not on disk
1681 char *str = new char[length+1];
1682 Fp->read(str, (size_t)length);
1683 str[length] = '\0'; //this is only useful when length is odd
1684 // Special DicomString call to properly handle \0 and even length
1685 std::string newValue;
1688 newValue = Util::DicomString(str, length+1);
1689 //dbg.Verbose(0, "Warning: bad length: ", length );
1690 dbg.Verbose(0, "For string :", newValue.c_str());
1691 // Since we change the length of string update it length
1692 entry->SetReadLength(length+1);
1696 newValue = Util::DicomString(str, length);
1700 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1702 if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1704 dbg.Verbose(1, "Document::LoadDocEntry",
1705 "unread element value");
1706 valEntry->SetValue(GDCM_UNREAD);
1712 // Because of correspondance with the VR dic
1713 valEntry->SetValue(newValue);
1717 valEntry->SetValue(newValue);
1722 dbg.Error(true, "Document::LoadDocEntry"
1723 "Should have a ValEntry, here !");
1729 * \brief Find the value Length of the passed Header Entry
1730 * @param entry Header Entry whose length of the value shall be loaded.
1732 void Document::FindDocEntryLength( DocEntry *entry )
1733 throw ( FormatError )
1735 uint16_t element = entry->GetElement();
1736 std::string vr = entry->GetVR();
1739 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1741 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1743 // The following reserved two bytes (see PS 3.5-2003, section
1744 // "7.1.2 Data element structure with explicit vr", p 27) must be
1745 // skipped before proceeding on reading the length on 4 bytes.
1746 Fp->seekg( 2L, std::ios_base::cur);
1747 uint32_t length32 = ReadInt32();
1749 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1754 /// \todo rename that to FindDocEntryLengthOBOrOW since
1755 /// the above test is on both OB and OW...
1756 lengthOB = FindDocEntryLengthOB();
1758 catch ( FormatUnexpected )
1760 // Computing the length failed (this happens with broken
1761 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1762 // chance to get the pixels by deciding the element goes
1763 // until the end of the file. Hence we artificially fix the
1764 // the length and proceed.
1765 long currentPosition = Fp->tellg();
1766 Fp->seekg(0L,std::ios_base::end);
1767 long lengthUntilEOF = Fp->tellg() - currentPosition;
1768 Fp->seekg(currentPosition, std::ios_base::beg);
1769 entry->SetLength(lengthUntilEOF);
1772 entry->SetLength(lengthOB);
1775 FixDocEntryFoundLength(entry, length32);
1779 // Length is encoded on 2 bytes.
1780 length16 = ReadInt16();
1782 // We can tell the current file is encoded in big endian (like
1783 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1784 // and it's value is the one of the encoding of a big endian file.
1785 // In order to deal with such big endian encoded files, we have
1786 // (at least) two strategies:
1787 // * when we load the "Transfer Syntax" tag with value of big endian
1788 // encoding, we raise the proper flags. Then we wait for the end
1789 // of the META group (0x0002) among which is "Transfer Syntax",
1790 // before switching the swap code to big endian. We have to postpone
1791 // the switching of the swap code since the META group is fully encoded
1792 // in little endian, and big endian coding only starts at the next
1793 // group. The corresponding code can be hard to analyse and adds
1794 // many additional unnecessary tests for regular tags.
1795 // * the second strategy consists in waiting for trouble, that shall
1796 // appear when we find the first group with big endian encoding. This
1797 // is easy to detect since the length of a "Group Length" tag (the
1798 // ones with zero as element number) has to be of 4 (0x0004). When we
1799 // encounter 1024 (0x0400) chances are the encoding changed and we
1800 // found a group with big endian encoding.
1801 // We shall use this second strategy. In order to make sure that we
1802 // can interpret the presence of an apparently big endian encoded
1803 // length of a "Group Length" without committing a big mistake, we
1804 // add an additional check: we look in the already parsed elements
1805 // for the presence of a "Transfer Syntax" whose value has to be "big
1806 // endian encoding". When this is the case, chances are we have got our
1807 // hands on a big endian encoded file: we switch the swap code to
1808 // big endian and proceed...
1809 if ( element == 0x0000 && length16 == 0x0400 )
1811 TransferSyntaxType ts = GetTransferSyntax();
1812 if ( ts != ExplicitVRBigEndian )
1814 throw FormatError( "Document::FindDocEntryLength()",
1815 " not explicit VR." );
1819 SwitchSwapToBigEndian();
1820 // Restore the unproperly loaded values i.e. the group, the element
1821 // and the dictionary entry depending on them.
1822 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1823 uint16_t correctElem = SwapShort( entry->GetElement() );
1824 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1828 // This correct tag is not in the dictionary. Create a new one.
1829 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1831 // FIXME this can create a memory leaks on the old entry that be
1832 // left unreferenced.
1833 entry->SetDictEntry( newTag );
1836 // Heuristic: well, some files are really ill-formed.
1837 if ( length16 == 0xffff)
1839 // 0xffff means that we deal with 'Unknown Length' Sequence
1842 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1847 // Either implicit VR or a non DICOM conformal (see note below) explicit
1848 // VR that ommited the VR of (at least) this element. Farts happen.
1849 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1850 // on Data elements "Implicit and Explicit VR Data Elements shall
1851 // not coexist in a Data Set and Data Sets nested within it".]
1852 // Length is on 4 bytes.
1854 FixDocEntryFoundLength( entry, ReadInt32() );
1860 * \brief Find the Value Representation of the current Dicom Element.
1863 void Document::FindDocEntryVR( DocEntry *entry )
1865 if ( Filetype != ExplicitVR )
1872 long positionOnEntry = Fp->tellg();
1873 // Warning: we believe this is explicit VR (Value Representation) because
1874 // we used a heuristic that found "UL" in the first tag. Alas this
1875 // doesn't guarantee that all the tags will be in explicit VR. In some
1876 // cases (see e-film filtered files) one finds implicit VR tags mixed
1877 // within an explicit VR file. Hence we make sure the present tag
1878 // is in explicit VR and try to fix things if it happens not to be
1881 Fp->read (vr, (size_t)2);
1884 if( !CheckDocEntryVR(entry, vr) )
1886 Fp->seekg(positionOnEntry, std::ios_base::beg);
1887 // When this element is known in the dictionary we shall use, e.g. for
1888 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1889 // dictionary entry. Still we have to flag the element as implicit since
1890 // we know now our assumption on expliciteness is not furfilled.
1892 if ( entry->IsVRUnknown() )
1894 entry->SetVR("Implicit");
1896 entry->SetImplicitVR();
1901 * \brief Check the correspondance between the VR of the header entry
1902 * and the taken VR. If they are different, the header entry is
1903 * updated with the new VR.
1904 * @param entry Header Entry to check
1905 * @param vr Dicom Value Representation
1906 * @return false if the VR is incorrect of if the VR isn't referenced
1907 * otherwise, it returns true
1909 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1912 bool realExplicit = true;
1914 // Assume we are reading a falsely explicit VR file i.e. we reached
1915 // a tag where we expect reading a VR but are in fact we read the
1916 // first to bytes of the length. Then we will interogate (through find)
1917 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1918 // both GCC and VC++ implementations of the STL map. Hence when the
1919 // expected VR read happens to be non-ascii characters we consider
1920 // we hit falsely explicit VR tag.
1922 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1924 realExplicit = false;
1927 // CLEANME searching the dicom_vr at each occurence is expensive.
1928 // PostPone this test in an optional integrity check at the end
1929 // of parsing or only in debug mode.
1930 if ( realExplicit && !Global::GetVR()->Count(vr) )
1932 realExplicit = false;
1935 if ( !realExplicit )
1937 // We thought this was explicit VR, but we end up with an
1938 // implicit VR tag. Let's backtrack.
1939 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
1940 entry->GetGroup(), entry->GetElement());
1941 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1943 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1945 // Group length is UL !
1946 DictEntry* newEntry = NewVirtualDictEntry(
1947 entry->GetGroup(), entry->GetElement(),
1948 "UL", "FIXME", "Group Length");
1949 entry->SetDictEntry( newEntry );
1954 if ( entry->IsVRUnknown() )
1956 // When not a dictionary entry, we can safely overwrite the VR.
1957 if( entry->GetElement() == 0x0000 )
1959 // Group length is UL !
1967 else if ( entry->GetVR() != vr )
1969 // The VR present in the file and the dictionary disagree. We assume
1970 // the file writer knew best and use the VR of the file. Since it would
1971 // be unwise to overwrite the VR of a dictionary (since it would
1972 // compromise it's next user), we need to clone the actual DictEntry
1973 // and change the VR for the read one.
1974 DictEntry* newEntry = NewVirtualDictEntry(
1975 entry->GetGroup(), entry->GetElement(),
1976 vr, "FIXME", entry->GetName());
1977 entry->SetDictEntry(newEntry);
1984 * \brief Get the transformed value of the header entry. The VR value
1985 * is used to define the transformation to operate on the value
1986 * \warning NOT end user intended method !
1987 * @param entry entry to tranform
1988 * @return Transformed entry value
1990 std::string Document::GetDocEntryValue(DocEntry *entry)
1992 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1994 std::string val = ((ValEntry *)entry)->GetValue();
1995 std::string vr = entry->GetVR();
1996 uint32_t length = entry->GetLength();
1997 std::ostringstream s;
2000 // When short integer(s) are expected, read and convert the following
2001 // n * 2 bytes properly i.e. as a multivaluated strings
2002 // (each single value is separated fromthe next one by '\'
2003 // as usual for standard multivaluated filels
2004 // Elements with Value Multiplicity > 1
2005 // contain a set of short integers (not a single one)
2007 if( vr == "US" || vr == "SS" )
2012 for (int i=0; i < nbInt; i++)
2018 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2019 newInt16 = SwapShort( newInt16 );
2024 // When integer(s) are expected, read and convert the following
2025 // n * 4 bytes properly i.e. as a multivaluated strings
2026 // (each single value is separated fromthe next one by '\'
2027 // as usual for standard multivaluated filels
2028 // Elements with Value Multiplicity > 1
2029 // contain a set of integers (not a single one)
2030 else if( vr == "UL" || vr == "SL" )
2035 for (int i=0; i < nbInt; i++)
2041 newInt32 = ( val[4*i+0] & 0xFF )
2042 + (( val[4*i+1] & 0xFF ) << 8 )
2043 + (( val[4*i+2] & 0xFF ) << 16 )
2044 + (( val[4*i+3] & 0xFF ) << 24 );
2045 newInt32 = SwapLong( newInt32 );
2049 #ifdef GDCM_NO_ANSI_STRING_STREAM
2050 s << std::ends; // to avoid oddities on Solaris
2051 #endif //GDCM_NO_ANSI_STRING_STREAM
2055 return ((ValEntry *)entry)->GetValue();
2059 * \brief Get the reverse transformed value of the header entry. The VR
2060 * value is used to define the reverse transformation to operate on
2062 * \warning NOT end user intended method !
2063 * @param entry Entry to reverse transform
2064 * @return Reverse transformed entry value
2066 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2068 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2070 std::string vr = entry->GetVR();
2071 std::vector<std::string> tokens;
2072 std::ostringstream s;
2074 if ( vr == "US" || vr == "SS" )
2078 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2079 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2080 for (unsigned int i=0; i<tokens.size(); i++)
2082 newInt16 = atoi(tokens[i].c_str());
2083 s << ( newInt16 & 0xFF )
2084 << (( newInt16 >> 8 ) & 0xFF );
2088 if ( vr == "UL" || vr == "SL")
2092 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2093 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2094 for (unsigned int i=0; i<tokens.size();i++)
2096 newInt32 = atoi(tokens[i].c_str());
2097 s << (char)( newInt32 & 0xFF )
2098 << (char)(( newInt32 >> 8 ) & 0xFF )
2099 << (char)(( newInt32 >> 16 ) & 0xFF )
2100 << (char)(( newInt32 >> 24 ) & 0xFF );
2105 #ifdef GDCM_NO_ANSI_STRING_STREAM
2106 s << std::ends; // to avoid oddities on Solaris
2107 #endif //GDCM_NO_ANSI_STRING_STREAM
2111 return ((ValEntry *)entry)->GetValue();
2115 * \brief Skip a given Header Entry
2116 * \warning NOT end user intended method !
2117 * @param entry entry to skip
2119 void Document::SkipDocEntry(DocEntry *entry)
2121 SkipBytes(entry->GetLength());
2125 * \brief Skips to the begining of the next Header Entry
2126 * \warning NOT end user intended method !
2127 * @param entry entry to skip
2129 void Document::SkipToNextDocEntry(DocEntry *entry)
2131 Fp->seekg((long)(entry->GetOffset()), std::ios_base::beg);
2132 Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2136 * \brief When the length of an element value is obviously wrong (because
2137 * the parser went Jabberwocky) one can hope improving things by
2138 * applying some heuristics.
2139 * @param entry entry to check
2140 * @param foundLength fist assumption about length
2142 void Document::FixDocEntryFoundLength(DocEntry *entry,
2143 uint32_t foundLength)
2145 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2146 if ( foundLength == 0xffffffff)
2151 uint16_t gr = entry->GetGroup();
2152 uint16_t el = entry->GetElement();
2154 if ( foundLength % 2)
2156 std::ostringstream s;
2157 s << "Warning : Tag with uneven length "
2159 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2160 dbg.Verbose(0, s.str().c_str());
2163 //////// Fix for some naughty General Electric images.
2164 // Allthough not recent many such GE corrupted images are still present
2165 // on Creatis hard disks. Hence this fix shall remain when such images
2166 // are no longer in user (we are talking a few years, here)...
2167 // Note: XMedCom probably uses such a trick since it is able to read
2168 // those pesky GE images ...
2169 if ( foundLength == 13)
2171 // Only happens for this length !
2172 if ( entry->GetGroup() != 0x0008
2173 || ( entry->GetElement() != 0x0070
2174 && entry->GetElement() != 0x0080 ) )
2177 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2181 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2182 // Occurence of such images is quite low (unless one leaves close to a
2183 // 'Leonardo' source. Hence, one might consider commenting out the
2184 // following fix on efficiency reasons.
2185 else if ( entry->GetGroup() == 0x0009
2186 && ( entry->GetElement() == 0x1113
2187 || entry->GetElement() == 0x1114 ) )
2190 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2193 else if ( entry->GetVR() == "SQ" )
2195 foundLength = 0; // ReadLength is unchanged
2198 //////// We encountered a 'delimiter' element i.e. a tag of the form
2199 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2200 // taken into account.
2201 else if( entry->GetGroup() == 0xfffe )
2203 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2204 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2205 // causes extra troubles...
2206 if( entry->GetElement() != 0x0000 )
2212 entry->SetUsableLength(foundLength);
2216 * \brief Apply some heuristics to predict whether the considered
2217 * element value contains/represents an integer or not.
2218 * @param entry The element value on which to apply the predicate.
2219 * @return The result of the heuristical predicate.
2221 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2223 uint16_t element = entry->GetElement();
2224 uint16_t group = entry->GetGroup();
2225 const std::string & vr = entry->GetVR();
2226 uint32_t length = entry->GetLength();
2228 // When we have some semantics on the element we just read, and if we
2229 // a priori know we are dealing with an integer, then we shall be
2230 // able to swap it's element value properly.
2231 if ( element == 0 ) // This is the group length of the group
2239 // Allthough this should never happen, still some images have a
2240 // corrupted group length [e.g. have a glance at offset x(8336) of
2241 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2242 // Since for dicom compliant and well behaved headers, the present
2243 // test is useless (and might even look a bit paranoid), when we
2244 // encounter such an ill-formed image, we simply display a warning
2245 // message and proceed on parsing (while crossing fingers).
2246 std::ostringstream s;
2247 long filePosition = Fp->tellg();
2248 s << "Erroneous Group Length element length on : (" \
2249 << std::hex << group << " , " << element
2250 << ") -before- position x(" << filePosition << ")"
2251 << "lgt : " << length;
2252 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2256 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2265 * \brief Find the Length till the next sequence delimiter
2266 * \warning NOT end user intended method !
2270 uint32_t Document::FindDocEntryLengthOB()
2271 throw( FormatUnexpected )
2273 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2274 long positionOnEntry = Fp->tellg();
2275 bool foundSequenceDelimiter = false;
2276 uint32_t totalLength = 0;
2278 while ( !foundSequenceDelimiter )
2284 group = ReadInt16();
2287 catch ( FormatError )
2289 throw FormatError("Document::FindDocEntryLengthOB()",
2290 " group or element not present.");
2293 // We have to decount the group and element we just read
2296 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2298 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2299 "tag nor a Sequence delimiter tag.");
2300 Fp->seekg(positionOnEntry, std::ios_base::beg);
2301 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2302 "Neither an Item tag nor a Sequence "
2306 if ( elem == 0xe0dd )
2308 foundSequenceDelimiter = true;
2311 uint32_t itemLength = ReadInt32();
2312 // We add 4 bytes since we just read the ItemLength with ReadInt32
2313 totalLength += itemLength + 4;
2314 SkipBytes(itemLength);
2316 if ( foundSequenceDelimiter )
2321 Fp->seekg( positionOnEntry, std::ios_base::beg);
2326 * \brief Reads a supposed to be 16 Bits integer
2327 * (swaps it depending on processor endianity)
2328 * @return read value
2330 uint16_t Document::ReadInt16()
2331 throw( FormatError )
2334 Fp->read ((char*)&g, (size_t)2);
2337 throw FormatError( "Document::ReadInt16()", " file error." );
2341 throw FormatError( "Document::ReadInt16()", "EOF." );
2348 * \brief Reads a supposed to be 32 Bits integer
2349 * (swaps it depending on processor endianity)
2350 * @return read value
2352 uint32_t Document::ReadInt32()
2353 throw( FormatError )
2356 Fp->read ((char*)&g, (size_t)4);
2359 throw FormatError( "Document::ReadInt32()", " file error." );
2363 throw FormatError( "Document::ReadInt32()", "EOF." );
2370 * \brief skips bytes inside the source file
2371 * \warning NOT end user intended method !
2374 void Document::SkipBytes(uint32_t nBytes)
2376 //FIXME don't dump the returned value
2377 Fp->seekg((long)nBytes, std::ios_base::cur);
2381 * \brief Loads all the needed Dictionaries
2382 * \warning NOT end user intended method !
2384 void Document::Initialise()
2386 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2388 RLEInfo = new RLEFramesInfo;
2389 JPEGInfo = new JPEGFragmentsInfo;
2393 * \brief Discover what the swap code is (among little endian, big endian,
2394 * bad little endian, bad big endian).
2396 * @return false when we are absolutely sure
2397 * it's neither ACR-NEMA nor DICOM
2398 * true when we hope ours assuptions are OK
2400 bool Document::CheckSwap()
2402 // The only guaranted way of finding the swap code is to find a
2403 // group tag since we know it's length has to be of four bytes i.e.
2404 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2405 // occurs when we can't find such group...
2407 uint32_t x = 4; // x : for ntohs
2408 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2412 char deb[256]; //HEADER_LENGTH_TO_READ];
2414 // First, compare HostByteOrder and NetworkByteOrder in order to
2415 // determine if we shall need to swap bytes (i.e. the Endian type).
2416 if ( x == ntohs(x) )
2425 // The easiest case is the one of a DICOM header, since it possesses a
2426 // file preamble where it suffice to look for the string "DICM".
2427 Fp->read(deb, HEADER_LENGTH_TO_READ);
2429 char *entCur = deb + 128;
2430 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2432 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2434 // Next, determine the value representation (VR). Let's skip to the
2435 // first element (0002, 0000) and check there if we find "UL"
2436 // - or "OB" if the 1st one is (0002,0001) -,
2437 // in which case we (almost) know it is explicit VR.
2438 // WARNING: if it happens to be implicit VR then what we will read
2439 // is the length of the group. If this ascii representation of this
2440 // length happens to be "UL" then we shall believe it is explicit VR.
2441 // FIXME: in order to fix the above warning, we could read the next
2442 // element value (or a couple of elements values) in order to make
2443 // sure we are not commiting a big mistake.
2444 // We need to skip :
2445 // * the 128 bytes of File Preamble (often padded with zeroes),
2446 // * the 4 bytes of "DICM" string,
2447 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2448 // i.e. a total of 136 bytes.
2452 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2453 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2454 // *Implicit* VR. -and it is !-
2456 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2457 memcmp(entCur, "OB", (size_t)2) == 0 ||
2458 memcmp(entCur, "UI", (size_t)2) == 0 ||
2459 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2460 // when Write DCM *adds*
2462 // Use Document::dicom_vr to test all the possibilities
2463 // instead of just checking for UL, OB and UI !? group 0000
2465 Filetype = ExplicitVR;
2466 dbg.Verbose(1, "Document::CheckSwap:",
2467 "explicit Value Representation");
2471 Filetype = ImplicitVR;
2472 dbg.Verbose(1, "Document::CheckSwap:",
2473 "not an explicit Value Representation");
2479 dbg.Verbose(1, "Document::CheckSwap:",
2480 "HostByteOrder != NetworkByteOrder");
2485 dbg.Verbose(1, "Document::CheckSwap:",
2486 "HostByteOrder = NetworkByteOrder");
2489 // Position the file position indicator at first tag (i.e.
2490 // after the file preamble and the "DICM" string).
2491 Fp->seekg(0, std::ios_base::beg);
2492 Fp->seekg ( 132L, std::ios_base::beg);
2496 // Alas, this is not a DicomV3 file and whatever happens there is no file
2497 // preamble. We can reset the file position indicator to where the data
2498 // is (i.e. the beginning of the file).
2499 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2500 Fp->seekg(0, std::ios_base::beg);
2502 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2503 // By clean we mean that the length of the first tag is written down.
2504 // If this is the case and since the length of the first group HAS to be
2505 // four (bytes), then determining the proper swap code is straightforward.
2508 // We assume the array of char we are considering contains the binary
2509 // representation of a 32 bits integer. Hence the following dirty
2511 s32 = *((uint32_t *)(entCur));
2532 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2533 // It is time for despaired wild guesses.
2534 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2535 // i.e. the 'group length' element is not present :
2537 // check the supposed to be 'group number'
2538 // 0x0002 or 0x0004 or 0x0008
2539 // to determine ' SwapCode' value .
2540 // Only 0 or 4321 will be possible
2541 // (no oportunity to check for the formerly well known
2542 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2543 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2544 // the file IS NOT ACR-NEMA nor DICOM V3
2545 // Find a trick to tell it the caller...
2547 s16 = *((uint16_t *)(deb));
2564 dbg.Verbose(0, "Document::CheckSwap:",
2565 "ACR/NEMA unfound swap info (Really hopeless !)");
2569 // Then the only info we have is the net2host one.
2579 * \brief Restore the unproperly loaded values i.e. the group, the element
2580 * and the dictionary entry depending on them.
2582 void Document::SwitchSwapToBigEndian()
2584 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2585 "Switching to BigEndian mode.");
2586 if ( SwapCode == 0 )
2590 else if ( SwapCode == 4321 )
2594 else if ( SwapCode == 3412 )
2598 else if ( SwapCode == 2143 )
2605 * \brief during parsing, Header Elements too long are not loaded in memory
2608 void Document::SetMaxSizeLoadEntry(long newSize)
2614 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2616 MaxSizeLoadEntry = 0xffffffff;
2619 MaxSizeLoadEntry = newSize;
2624 * \brief Header Elements too long will not be printed
2625 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2628 void Document::SetMaxSizePrintEntry(long newSize)
2630 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2635 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2637 MaxSizePrintEntry = 0xffffffff;
2640 MaxSizePrintEntry = newSize;
2646 * \brief Handle broken private tag from Philips NTSCAN
2647 * where the endianess is being switch to BigEndian for no
2651 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2653 // Endian reversion. Some files contain groups of tags with reversed endianess.
2654 static int reversedEndian = 0;
2655 // try to fix endian switching in the middle of headers
2656 if ((group == 0xfeff) && (elem == 0x00e0))
2658 // start endian swap mark for group found
2660 SwitchSwapToBigEndian();
2665 else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian)
2667 // end of reversed endian group
2669 SwitchSwapToBigEndian();
2675 * \brief Read the next tag but WITHOUT loading it's value
2676 * (read the 'Group Number', the 'Element Number',
2677 * gets the Dict Entry
2678 * gets the VR, gets the length, gets the offset value)
2679 * @return On succes the newly created DocEntry, NULL on failure.
2681 DocEntry* Document::ReadNextDocEntry()
2688 group = ReadInt16();
2691 catch ( FormatError e )
2693 // We reached the EOF (or an error occured) therefore
2694 // header parsing has to be considered as finished.
2699 HandleBrokenEndian(group, elem);
2700 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2701 FindDocEntryVR(newEntry);
2705 FindDocEntryLength(newEntry);
2707 catch ( FormatError e )
2715 newEntry->SetOffset(Fp->tellg());
2722 * \brief Generate a free TagKey i.e. a TagKey that is not present
2723 * in the TagHt dictionary.
2724 * @param group The generated tag must belong to this group.
2725 * @return The element of tag with given group which is fee.
2727 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2729 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2731 TagKey key = DictEntry::TranslateToKey(group, elem);
2732 if (TagHT.count(key) == 0)
2741 * \brief Assuming the internal file pointer \ref Document::Fp
2742 * is placed at the beginning of a tag check whether this
2743 * tag is (TestGroup, TestElement).
2744 * \warning On success the internal file pointer \ref Document::Fp
2745 * is modified to point after the tag.
2746 * On failure (i.e. when the tag wasn't the expected tag
2747 * (TestGroup, TestElement) the internal file pointer
2748 * \ref Document::Fp is restored to it's original position.
2749 * @param testGroup The expected group of the tag.
2750 * @param testElement The expected Element of the tag.
2751 * @return True on success, false otherwise.
2753 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2755 long positionOnEntry = Fp->tellg();
2756 long currentPosition = Fp->tellg(); // On debugging purposes
2758 //// Read the Item Tag group and element, and make
2759 // sure they are what we expected:
2760 uint16_t itemTagGroup;
2761 uint16_t itemTagElement;
2764 itemTagGroup = ReadInt16();
2765 itemTagElement = ReadInt16();
2767 catch ( FormatError e )
2769 //std::cerr << e << std::endl;
2772 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2774 std::ostringstream s;
2775 s << " We should have found tag (";
2776 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2777 s << " but instead we encountered tag (";
2778 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2780 s << " at address: " << (unsigned)currentPosition << std::endl;
2781 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2782 dbg.Verbose(0, s.str().c_str());
2783 Fp->seekg(positionOnEntry, std::ios_base::beg);
2791 * \brief Assuming the internal file pointer \ref Document::Fp
2792 * is placed at the beginning of a tag (TestGroup, TestElement),
2793 * read the length associated to the Tag.
2794 * \warning On success the internal file pointer \ref Document::Fp
2795 * is modified to point after the tag and it's length.
2796 * On failure (i.e. when the tag wasn't the expected tag
2797 * (TestGroup, TestElement) the internal file pointer
2798 * \ref Document::Fp is restored to it's original position.
2799 * @param testGroup The expected group of the tag.
2800 * @param testElement The expected Element of the tag.
2801 * @return On success returns the length associated to the tag. On failure
2804 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2806 long positionOnEntry = Fp->tellg();
2807 (void)positionOnEntry;
2809 if ( !ReadTag(testGroup, testElement) )
2814 //// Then read the associated Item Length
2815 long currentPosition = Fp->tellg();
2816 uint32_t itemLength = ReadInt32();
2818 std::ostringstream s;
2819 s << "Basic Item Length is: "
2820 << itemLength << std::endl;
2821 s << " at address: " << (unsigned)currentPosition << std::endl;
2822 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2828 * \brief When parsing the Pixel Data of an encapsulated file, read
2829 * the basic offset table (when present, and BTW dump it).
2831 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2833 //// Read the Basic Offset Table Item Tag length...
2834 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2836 // When present, read the basic offset table itself.
2837 // Notes: - since the presence of this basic offset table is optional
2838 // we can't rely on it for the implementation, and we will simply
2839 // trash it's content (when present).
2840 // - still, when present, we could add some further checks on the
2841 // lengths, but we won't bother with such fuses for the time being.
2842 if ( itemLength != 0 )
2844 char* basicOffsetTableItemValue = new char[itemLength + 1];
2845 Fp->read(basicOffsetTableItemValue, itemLength);
2848 for (unsigned int i=0; i < itemLength; i += 4 )
2850 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2852 std::ostringstream s;
2853 s << " Read one length: ";
2854 s << std::hex << individualLength << std::endl;
2856 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2861 delete[] basicOffsetTableItemValue;
2866 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2867 * Compute the RLE extra information and store it in \ref RLEInfo
2868 * for later pixel retrieval usage.
2870 void Document::ComputeRLEInfo()
2872 TransferSyntaxType ts = GetTransferSyntax();
2873 if ( ts != RLELossless )
2878 // Encoded pixel data: for the time being we are only concerned with
2879 // Jpeg or RLE Pixel data encodings.
2880 // As stated in PS 3.5-2003, section 8.2 p44:
2881 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2882 // value representation OB is used".
2883 // Hence we expect an OB value representation. Concerning OB VR,
2884 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2885 // "For the Value Representations OB and OW, the encoding shall meet the
2886 // following specifications depending on the Data element tag:"
2888 // - the first item in the sequence of items before the encoded pixel
2889 // data stream shall be basic offset table item. The basic offset table
2890 // item value, however, is not required to be present"
2892 ReadAndSkipEncapsulatedBasicOffsetTable();
2894 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2895 // Loop on the individual frame[s] and store the information
2896 // on the RLE fragments in a RLEFramesInfo.
2897 // Note: - when only a single frame is present, this is a
2899 // - when more than one frame are present, then we are in
2900 // the case of a multi-frame image.
2902 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2904 // Parse the RLE Header and store the corresponding RLE Segment
2905 // Offset Table information on fragments of this current Frame.
2906 // Note that the fragment pixels themselves are not loaded
2907 // (but just skipped).
2908 long frameOffset = Fp->tellg();
2910 uint32_t nbRleSegments = ReadInt32();
2911 if ( nbRleSegments > 16 )
2913 // There should be at most 15 segments (refer to RLEFrame class)
2914 dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2917 uint32_t rleSegmentOffsetTable[15];
2918 for( int k = 1; k <= 15; k++ )
2920 rleSegmentOffsetTable[k] = ReadInt32();
2923 // Deduce from both the RLE Header and the frameLength the
2924 // fragment length, and again store this info in a
2926 long rleSegmentLength[15];
2927 // skipping (not reading) RLE Segments
2928 if ( nbRleSegments > 1)
2930 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2932 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2933 - rleSegmentOffsetTable[k];
2934 SkipBytes(rleSegmentLength[k]);
2938 rleSegmentLength[nbRleSegments] = frameLength
2939 - rleSegmentOffsetTable[nbRleSegments];
2940 SkipBytes(rleSegmentLength[nbRleSegments]);
2942 // Store the collected info
2943 RLEFrame* newFrameInfo = new RLEFrame;
2944 newFrameInfo->NumberFragments = nbRleSegments;
2945 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2947 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2948 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2950 RLEInfo->Frames.push_back( newFrameInfo );
2953 // Make sure that at the end of the item we encounter a 'Sequence
2955 if ( !ReadTag(0xfffe, 0xe0dd) )
2957 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2958 dbg.Verbose(0, " item at end of RLE item sequence");
2963 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2964 * Compute the jpeg extra information (fragment[s] offset[s] and
2965 * length) and store it[them] in \ref JPEGInfo for later pixel
2968 void Document::ComputeJPEGFragmentInfo()
2970 // If you need to, look for comments of ComputeRLEInfo().
2976 ReadAndSkipEncapsulatedBasicOffsetTable();
2978 // Loop on the fragments[s] and store the parsed information in a
2980 long fragmentLength;
2981 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2983 long fragmentOffset = Fp->tellg();
2985 // Store the collected info
2986 JPEGFragment* newFragment = new JPEGFragment;
2987 newFragment->Offset = fragmentOffset;
2988 newFragment->Length = fragmentLength;
2989 JPEGInfo->Fragments.push_back( newFragment );
2991 SkipBytes( fragmentLength );
2994 // Make sure that at the end of the item we encounter a 'Sequence
2996 if ( !ReadTag(0xfffe, 0xe0dd) )
2998 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2999 dbg.Verbose(0, " item at end of JPEG item sequence");
3004 * \brief Walk recursively the given \ref DocEntrySet, and feed
3005 * the given hash table (\ref TagDocEntryHT) with all the
3006 * \ref DocEntry (Dicom entries) encountered.
3007 * This method does the job for \ref BuildFlatHashTable.
3008 * @param builtHT Where to collect all the \ref DocEntry encountered
3009 * when recursively walking the given set.
3010 * @param set The structure to be traversed (recursively).
3012 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3015 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3017 TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3018 for( TagDocEntryHT::const_iterator i = currentHT.begin();
3019 i != currentHT.end();
3022 DocEntry* entry = i->second;
3023 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3025 const ListSQItem& items = seqEntry->GetSQItems();
3026 for( ListSQItem::const_iterator item = items.begin();
3027 item != items.end();
3030 BuildFlatHashTableRecurse( builtHT, *item );
3034 builtHT[entry->GetKey()] = entry;
3039 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3041 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3042 for (ListDocEntry::const_iterator i = currentList.begin();
3043 i != currentList.end();
3046 DocEntry* entry = *i;
3047 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3049 const ListSQItem& items = seqEntry->GetSQItems();
3050 for( ListSQItem::const_iterator item = items.begin();
3051 item != items.end();
3054 BuildFlatHashTableRecurse( builtHT, *item );
3058 builtHT[entry->GetKey()] = entry;
3065 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3068 * The structure used by a Document (through \ref ElementSet),
3069 * in order to old the parsed entries of a Dicom header, is a recursive
3070 * one. This is due to the fact that the sequences (when present)
3071 * can be nested. Additionaly, the sequence items (represented in
3072 * gdcm as \ref SQItem) add an extra complexity to the data
3073 * structure. Hence, a gdcm user whishing to visit all the entries of
3074 * a Dicom header will need to dig in the gdcm internals (which
3075 * implies exposing all the internal data structures to the API).
3076 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3077 * recursively builds a temporary hash table, which holds all the
3078 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3080 * \warning Of course there is NO integrity constrain between the
3081 * returned \ref TagDocEntryHT and the \ref ElementSet used
3082 * to build it. Hence if the underlying \ref ElementSet is
3083 * altered, then it is the caller responsability to invoke
3084 * \ref BuildFlatHashTable again...
3085 * @return The flat std::map<> we juste build.
3087 TagDocEntryHT* Document::BuildFlatHashTable()
3089 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3090 BuildFlatHashTableRecurse( *FlatHT, this );
3097 * \brief Compares two documents, according to \ref DicomDir rules
3098 * \warning Does NOT work with ACR-NEMA files
3099 * \todo Find a trick to solve the pb (use RET fields ?)
3101 * @return true if 'smaller'
3103 bool Document::operator<(Document &document)
3106 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3107 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3119 s1 = GetEntryByNumber(0x0010,0x0020);
3120 s2 = document.GetEntryByNumber(0x0010,0x0020);
3131 // Study Instance UID
3132 s1 = GetEntryByNumber(0x0020,0x000d);
3133 s2 = document.GetEntryByNumber(0x0020,0x000d);
3144 // Serie Instance UID
3145 s1 = GetEntryByNumber(0x0020,0x000e);
3146 s2 = document.GetEntryByNumber(0x0020,0x000e);
3161 } // end namespace gdcm
3163 //-----------------------------------------------------------------------------