1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/11/16 10:37:54 $
7 Version: $Revision: 1.126 $
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"
299 * \brief Accessor to the Transfer Syntax (when present) of the
300 * current document (it internally handles reading the
301 * value from disk when only parsing occured).
302 * @return The encountered Transfer Syntax of the current document.
304 TransferSyntaxType Document::GetTransferSyntax()
306 DocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
312 // The entry might be present but not loaded (parsing and loading
313 // happen at different stages): try loading and proceed with check...
314 LoadDocEntrySafe(entry);
315 if (ValEntry* valEntry = dynamic_cast< ValEntry* >(entry) )
317 std::string transfer = valEntry->GetValue();
318 // The actual transfer (as read from disk) might be padded. We
319 // first need to remove the potential padding. We can make the
320 // weak assumption that padding was not executed with digits...
321 if ( transfer.length() == 0 )
323 // for brain damaged headers
326 while ( !isdigit(transfer[transfer.length()-1]) )
328 transfer.erase(transfer.length()-1, 1);
330 for (int i = 0; TransferSyntaxStrings[i] != NULL; i++)
332 if ( TransferSyntaxStrings[i] == transfer )
334 return TransferSyntaxType(i);
341 bool Document::IsJPEGLossless()
343 TransferSyntaxType r = GetTransferSyntax();
344 return r == JPEGFullProgressionProcess10_12
345 || r == JPEGLosslessProcess14
346 || r == JPEGLosslessProcess14_1;
350 * \brief Determines if the Transfer Syntax was already encountered
351 * and if it corresponds to a JPEG2000 one
352 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
355 bool Document::IsJPEG2000()
357 TransferSyntaxType r = GetTransferSyntax();
358 return r == JPEG2000Lossless || r == JPEG2000;
362 * \brief Determines if the Transfer Syntax corresponds to any form
363 * of Jpeg encoded Pixel data.
364 * @return True when any form of JPEG found. False otherwise.
366 bool Document::IsJPEG()
368 TransferSyntaxType r = GetTransferSyntax();
369 return r == JPEGBaselineProcess1
370 || r == JPEGExtendedProcess2_4
371 || r == JPEGExtendedProcess3_5
372 || r == JPEGSpectralSelectionProcess6_8
378 * \brief Determines if the Transfer Syntax corresponds to encapsulated
379 * of encoded Pixel Data (as opposed to native).
380 * @return True when encapsulated. False when native.
382 bool Document::IsEncapsulate()
384 TransferSyntaxType r = GetTransferSyntax();
385 return IsJPEG() || r == RLELossless;
389 * \brief Predicate for dicom version 3 file.
390 * @return True when the file is a dicom version 3.
392 bool Document::IsDicomV3()
394 // Checking if Transfert Syntax exists is enough
395 // Anyway, it's to late check if the 'Preamble' was found ...
396 // And ... would it be a rich idea to check ?
397 // (some 'no Preamble' DICOM images exist !)
398 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
402 * \brief returns the File Type
403 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
404 * @return the FileType code
406 FileType Document::GetFileType()
412 * \brief Tries to open the file \ref Document::Filename and
413 * checks the preamble when existing.
414 * @return The FILE pointer on success.
416 std::ifstream* Document::OpenFile()
418 if (Filename.length() == 0) return 0;
422 "Document::OpenFile is already opened when opening: ",
426 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
431 "Document::OpenFile cannot open file: ",
437 Fp->read((char*)&zero, (size_t)2 );
439 //ACR -- or DICOM with no Preamble --
440 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
446 Fp->seekg(126L, std::ios_base::cur);
448 Fp->read(dicm, (size_t)4);
449 if( memcmp(dicm, "DICM", 4) == 0 )
456 "Document::OpenFile not DICOM/ACR (missing preamble)",
463 * \brief closes the file
464 * @return TRUE if the close was successfull
466 bool Document::CloseFile()
475 return true; //FIXME how do we detect a non-close ifstream ?
479 * \brief Writes in a file all the Header Entries (Dicom Elements)
480 * @param fp file pointer on an already open file
481 * @param filetype Type of the File to be written
482 * (ACR-NEMA, ExplicitVR, ImplicitVR)
483 * \return Always true.
485 void Document::Write(std::ofstream* fp, FileType filetype)
487 /// \todo move the following lines (and a lot of others, to be written)
488 /// to a future function CheckAndCorrectHeader
489 /// (necessary if user wants to write a DICOM V3 file
490 /// starting from an ACR-NEMA (V2) Header
492 if (filetype == ImplicitVR)
495 Util::DicomString( TransferSyntaxStrings[ImplicitVRLittleEndian] );
496 ReplaceOrCreateByNumber(ts, 0x0002, 0x0010);
498 /// \todo Refer to standards on page 21, chapter 6.2
499 /// "Value representation": values with a VR of UI shall be
500 /// padded with a single trailing null
501 /// in the following case we have to padd manually with a 0
503 SetEntryLengthByNumber(18, 0x0002, 0x0010);
506 if (filetype == ExplicitVR)
509 Util::DicomString( TransferSyntaxStrings[ExplicitVRLittleEndian] );
510 ReplaceOrCreateByNumber(ts, 0x0002, 0x0010); //LEAK
512 /// \todo Refer to standards on page 21, chapter 6.2
513 /// "Value representation": values with a VR of UI shall be
514 /// padded with a single trailing null
515 /// Dans le cas suivant on doit pader manuellement avec un 0
517 SetEntryLengthByNumber(20, 0x0002, 0x0010);
521 * \todo rewrite later, if really usefull
522 * - 'Group Length' element is optional in DICOM
523 * - but un-updated odd groups lengthes can causes pb
526 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
527 * UpdateGroupLength(false,filetype);
528 * if ( filetype == ACR)
529 * UpdateGroupLength(true,ACR);
532 ElementSet::Write(fp, filetype); // This one is recursive
537 * \brief Modifies the value of a given Header Entry (Dicom Element)
538 * when it exists. Create it with the given value when unexistant.
539 * @param value (string) Value to be set
540 * @param group Group number of the Entry
541 * @param elem Element number of the Entry
542 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
543 * \return pointer to the modified/created Header Entry (NULL when creation
546 ValEntry* Document::ReplaceOrCreateByNumber(
547 std::string const & value,
552 ValEntry* valEntry = 0;
553 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
557 // check if (group,element) DictEntry exists
558 // if it doesn't, create an entry in DictSet::VirtualEntry
561 // Find out if the tag we received is in the dictionaries:
562 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
563 DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
566 currentEntry = NewDocEntryByNumber(group, elem, vr);
570 currentEntry = NewDocEntryByNumber(group, elem);
575 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
576 " NewDocEntryByNumber failed.");
580 valEntry = new ValEntry(currentEntry);
583 if ( !AddEntry(valEntry))
586 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
587 " failed allthough this is a creation.");
593 valEntry = dynamic_cast< ValEntry* >(currentEntry);
594 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
595 // then we change it to a ValEntry ?
596 // Shouldn't it be considered as an error ?
598 // We need to promote the DocEntry to a ValEntry:
599 valEntry = new ValEntry(currentEntry);
600 if (!RemoveEntry(currentEntry))
603 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
604 " of previous DocEntry failed.");
607 if ( !AddEntry(valEntry))
610 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
611 " promoted ValEntry failed.");
617 SetEntryByNumber(value, group, elem);
623 * \brief Modifies the value of a given Header Entry (Dicom Element)
624 * when it exists. Create it with the given value when unexistant.
625 * @param binArea (binary) value to be set
626 * @param Group Group number of the Entry
627 * @param Elem Element number of the Entry
628 * \return pointer to the modified/created Header Entry (NULL when creation
631 BinEntry* Document::ReplaceOrCreateByNumber(
638 BinEntry* binEntry = 0;
639 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
643 // check if (group,element) DictEntry exists
644 // if it doesn't, create an entry in DictSet::VirtualEntry
647 // Find out if the tag we received is in the dictionaries:
648 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
649 DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
653 currentEntry = NewDocEntryByNumber(group, elem, vr);
657 currentEntry = NewDocEntryByNumber(group, elem);
661 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
662 " NewDocEntryByNumber failed.");
665 binEntry = new BinEntry(currentEntry);
666 if ( !AddEntry(binEntry))
668 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
669 " failed allthough this is a creation.");
674 binEntry = dynamic_cast< BinEntry* >(currentEntry);
675 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
676 // then we change it to a BinEntry ?
677 // Shouldn't it be considered as an error ?
679 // We need to promote the DocEntry to a BinEntry:
680 binEntry = new BinEntry(currentEntry);
681 if (!RemoveEntry(currentEntry))
683 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
684 " of previous DocEntry failed.");
687 if ( !AddEntry(binEntry))
689 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
690 " promoted BinEntry failed.");
696 SetEntryByNumber(binArea, lgth, group, elem);
703 * \brief Modifies the value of a given Header Entry (Dicom Element)
704 * when it exists. Create it when unexistant.
705 * @param Group Group number of the Entry
706 * @param Elem Element number of the Entry
707 * \return pointer to the modified/created SeqEntry (NULL when creation
710 SeqEntry* Document::ReplaceOrCreateByNumber( uint16_t group, uint16_t elem)
713 DocEntry* a = GetDocEntryByNumber( group, elem);
716 a = NewSeqEntryByNumber(group, elem);
722 b = new SeqEntry(a, 1); // FIXME : 1 (Depth)
729 * \brief Set a new value if the invoked element exists
730 * Seems to be useless !!!
731 * @param value new element value
732 * @param group group number of the Entry
733 * @param elem element number of the Entry
736 bool Document::ReplaceIfExistByNumber(std::string const & value,
737 uint16_t group, uint16_t elem )
739 SetEntryByNumber(value, group, elem);
744 //-----------------------------------------------------------------------------
748 * \brief Checks if a given Dicom Element exists within the H table
749 * @param group Group number of the searched Dicom Element
750 * @param element Element number of the searched Dicom Element
751 * @return true is found
753 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
755 const std::string &key = DictEntry::TranslateToKey(group, element );
756 return TagHT.count(key) != 0;
760 * \brief Searches within Header Entries (Dicom Elements) parsed with
761 * the public and private dictionaries
762 * for the element value of a given tag.
763 * \warning Don't use any longer : use GetPubEntryByName
764 * @param tagName name of the searched element.
765 * @return Corresponding element value when it exists,
766 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
768 std::string Document::GetEntryByName(TagName const & tagName)
770 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
776 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
780 * \brief Searches within Header Entries (Dicom Elements) parsed with
781 * the public and private dictionaries
782 * for the element value representation of a given tag.
784 * Obtaining the VR (Value Representation) might be needed by caller
785 * to convert the string typed content to caller's native type
786 * (think of C++ vs Python). The VR is actually of a higher level
787 * of semantics than just the native C++ type.
788 * @param tagName name of the searched element.
789 * @return Corresponding element value representation when it exists,
790 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
792 std::string Document::GetEntryVRByName(TagName const& tagName)
794 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
795 if( dictEntry == NULL)
800 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
801 dictEntry->GetElement());
802 return elem->GetVR();
806 * \brief Searches within Header Entries (Dicom Elements) parsed with
807 * the public and private dictionaries
808 * for the element value representation of a given tag.
809 * @param group Group number of the searched tag.
810 * @param element Element number of the searched tag.
811 * @return Corresponding element value representation when it exists,
812 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
814 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
816 TagKey key = DictEntry::TranslateToKey(group, element);
817 /// \todo use map methods, instead of multimap JPR
818 if ( !TagHT.count(key))
823 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
827 * \brief Searches within Header Entries (Dicom Elements) parsed with
828 * the public and private dictionaries
829 * for the element value representation of a given tag..
831 * Obtaining the VR (Value Representation) might be needed by caller
832 * to convert the string typed content to caller's native type
833 * (think of C++ vs Python). The VR is actually of a higher level
834 * of semantics than just the native C++ type.
835 * @param group Group number of the searched tag.
836 * @param element Element number of the searched tag.
837 * @return Corresponding element value representation when it exists,
838 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
840 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
842 DocEntry* elem = GetDocEntryByNumber(group, element);
847 return elem->GetVR();
851 * \brief Searches within Header Entries (Dicom Elements) parsed with
852 * the public and private dictionaries
853 * for the value length of a given tag..
854 * @param group Group number of the searched tag.
855 * @param element Element number of the searched tag.
856 * @return Corresponding element length; -2 if not found
858 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
860 DocEntry* elem = GetDocEntryByNumber(group, element);
863 return -2; //magic number
865 return elem->GetLength();
868 * \brief Sets the value (string) of the Header Entry (Dicom Element)
869 * @param content string value of the Dicom Element
870 * @param tagName name of the searched Dicom Element.
871 * @return true when found
873 bool Document::SetEntryByName( std::string const & content,
874 TagName const & tagName)
876 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
882 return SetEntryByNumber(content,dictEntry->GetGroup(),
883 dictEntry->GetElement());
887 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
888 * through it's (group, element) and modifies it's content with
890 * @param content new value (string) to substitute with
891 * @param group group number of the Dicom Element to modify
892 * @param element element number of the Dicom Element to modify
894 bool Document::SetEntryByNumber(std::string const& content,
895 uint16_t group, uint16_t element)
900 ValEntry* valEntry = GetValEntryByNumber(group, element);
903 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
904 " ValEntry (try promotion first).");
907 // Non even content must be padded with a space (020H)...
908 std::string finalContent = Util::DicomString( content.c_str() );
909 assert( !(finalContent.size() % 2) );
910 valEntry->SetValue(finalContent);
912 // Integers have a special treatement for their length:
914 l = finalContent.length();
915 if ( l != 0) // To avoid to be cheated by 'zero length' integers
917 VRKey vr = valEntry->GetVR();
918 if( vr == "US" || vr == "SS" )
920 // for multivaluated items
921 c = Util::CountSubstring(content, "\\") + 1;
924 else if( vr == "UL" || vr == "SL" )
926 // for multivaluated items
927 c = Util::CountSubstring(content, "\\") + 1;
931 valEntry->SetLength(l);
936 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
937 * through it's (group, element) and modifies it's content with
939 * @param content new value (void* -> uint8_t*) to substitute with
940 * @param lgth new value length
941 * @param group group number of the Dicom Element to modify
942 * @param element element number of the Dicom Element to modify
944 bool Document::SetEntryByNumber(uint8_t*content, int lgth,
945 uint16_t group, uint16_t element)
947 (void)lgth; //not used
948 TagKey key = DictEntry::TranslateToKey(group, element);
949 if ( !TagHT.count(key))
954 /* Hope Binary field length is *never* wrong
955 if(lgth%2) // Non even length are padded with a space (020H).
958 //content = content + '\0'; // fing a trick to enlarge a binary field?
961 BinEntry* a = (BinEntry *)TagHT[key];
962 a->SetBinArea(content);
964 a->SetValue(GDCM_BINLOADED);
970 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
971 * in the PubDocEntrySet of this instance
972 * through it's (group, element) and modifies it's length with
974 * \warning Use with extreme caution.
975 * @param l new length to substitute with
976 * @param group group number of the Entry to modify
977 * @param element element number of the Entry to modify
978 * @return true on success, false otherwise.
980 bool Document::SetEntryLengthByNumber(uint32_t l,
981 uint16_t group, uint16_t element)
983 /// \todo use map methods, instead of multimap JPR
984 TagKey key = DictEntry::TranslateToKey(group, element);
985 if ( !TagHT.count(key) )
991 l++; // length must be even
993 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
999 * \brief Gets (from Header) the offset of a 'non string' element value
1000 * (LoadElementValues has already be executed)
1001 * @param group group number of the Entry
1002 * @param elem element number of the Entry
1003 * @return File Offset of the Element Value
1005 size_t Document::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1007 DocEntry* entry = GetDocEntryByNumber(group, elem);
1010 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry present.");
1013 return entry->GetOffset();
1017 * \brief Gets (from Header) a 'non string' element value
1018 * (LoadElementValues has already be executed)
1019 * @param group group number of the Entry
1020 * @param elem element number of the Entry
1021 * @return Pointer to the 'non string' area
1023 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1025 DocEntry* entry = GetDocEntryByNumber(group, elem);
1028 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
1031 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
1033 return binEntry->GetBinArea();
1040 * \brief Loads (from disk) the element content
1041 * when a string is not suitable
1042 * @param group group number of the Entry
1043 * @param elem element number of the Entry
1045 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1047 // Search the corresponding DocEntry
1048 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1052 size_t o =(size_t)docElement->GetOffset();
1053 Fp->seekg( o, std::ios_base::beg);
1054 size_t l = docElement->GetLength();
1055 uint8_t* a = new uint8_t[l];
1058 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1063 Fp->read((char*)a, l);
1064 if( Fp->fail() || Fp->eof() )//Fp->gcount() == 1
1070 // Set the value to the DocEntry
1071 if( !SetEntryBinAreaByNumber( a, group, elem ) )
1074 dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1078 * \brief Loads (from disk) the element content
1079 * when a string is not suitable
1080 * @param element Entry whose binArea is going to be loaded
1082 void Document::LoadEntryBinArea(BinEntry* element)
1084 size_t o =(size_t)element->GetOffset();
1085 Fp->seekg(o, std::ios_base::beg);
1086 size_t l = element->GetLength();
1087 uint8_t* a = new uint8_t[l];
1090 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1094 /// \todo check the result
1095 Fp->read((char*)a, l);
1096 if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1102 element->SetBinArea((uint8_t*)a);
1106 * \brief Sets a 'non string' value to a given Dicom Element
1107 * @param area area containing the 'non string' value
1108 * @param group Group number of the searched Dicom Element
1109 * @param element Element number of the searched Dicom Element
1112 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1113 uint16_t group, uint16_t element)
1115 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1116 if ( !currentEntry )
1121 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1123 binEntry->SetBinArea( area );
1131 * \brief Update the entries with the shadow dictionary.
1132 * Only non even entries are analyzed
1134 void Document::UpdateShaEntries()
1139 /// \todo TODO : still any use to explore recursively the whole structure?
1141 for(ListTag::iterator it=listEntries.begin();
1142 it!=listEntries.end();
1145 // Odd group => from public dictionary
1146 if((*it)->GetGroup()%2==0)
1149 // Peer group => search the corresponding dict entry
1151 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1155 if((*it)->IsImplicitVR())
1160 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1162 // Set the new entry and the new value
1163 (*it)->SetDictEntry(entry);
1164 CheckDocEntryVR(*it,vr);
1166 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1171 // Remove precedent value transformation
1172 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1179 * \brief Searches within the Header Entries for a Dicom Element of
1181 * @param tagName name of the searched Dicom Element.
1182 * @return Corresponding Dicom Element when it exists, and NULL
1185 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1187 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1193 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1197 * \brief retrieves a Dicom Element (the first one) using (group, element)
1198 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1199 * if you think it's NOT UNIQUE, check the count number
1200 * and use iterators to retrieve ALL the Dicoms Elements within
1201 * a given couple (group, element)
1202 * @param group Group number of the searched Dicom Element
1203 * @param element Element number of the searched Dicom Element
1206 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element)
1208 TagKey key = DictEntry::TranslateToKey(group, element);
1209 if ( !TagHT.count(key))
1213 return TagHT.find(key)->second;
1217 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1218 * returns a result when the corresponding entry is of type
1220 * @return When present, the corresponding ValEntry.
1222 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1224 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1225 if ( !currentEntry )
1229 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1233 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1239 * \brief Loads the element while preserving the current
1240 * underlying file position indicator as opposed to
1241 * to LoadDocEntry that modifies it.
1242 * @param entry Header Entry whose value shall be loaded.
1245 void Document::LoadDocEntrySafe(DocEntry * entry)
1247 long PositionOnEntry = Fp->tellg();
1248 LoadDocEntry(entry);
1249 Fp->seekg(PositionOnEntry, std::ios_base::beg);
1253 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1255 * @return The properly swaped 32 bits integer.
1257 uint32_t Document::SwapLong(uint32_t a)
1264 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1265 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1269 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1273 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1276 //std::cout << "swapCode= " << SwapCode << std::endl;
1277 dbg.Error(" Document::SwapLong : unset swap code");
1284 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1286 * @return The properly unswaped 32 bits integer.
1288 uint32_t Document::UnswapLong(uint32_t a)
1294 * \brief Swaps the bytes so they agree with the processor order
1295 * @return The properly swaped 16 bits integer.
1297 uint16_t Document::SwapShort(uint16_t a)
1299 if ( SwapCode == 4321 || SwapCode == 2143 )
1301 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1307 * \brief Unswaps the bytes so they agree with the processor order
1308 * @return The properly unswaped 16 bits integer.
1310 uint16_t Document::UnswapShort(uint16_t a)
1312 return SwapShort(a);
1315 //-----------------------------------------------------------------------------
1319 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1320 * @return length of the parsed set.
1322 void Document::ParseDES(DocEntrySet *set, long offset,
1323 long l_max, bool delim_mode)
1325 DocEntry *newDocEntry = 0;
1329 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1333 newDocEntry = ReadNextDocEntry( );
1339 VRKey vr = newDocEntry->GetVR();
1343 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1345 /////////////////////// ValEntry
1346 ValEntry* newValEntry =
1347 new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1348 newValEntry->Copy( newDocEntry );
1350 // When "set" is a Document, then we are at the top of the
1351 // hierarchy and the Key is simply of the form ( group, elem )...
1352 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1355 newValEntry->SetKey( newValEntry->GetKey() );
1357 // ...but when "set" is a SQItem, we are inserting this new
1358 // valEntry in a sequence item. Hence the key has the
1359 // generalized form (refer to \ref BaseTagKey):
1360 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1362 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1363 + newValEntry->GetKey() );
1366 LoadDocEntry( newValEntry );
1367 bool delimitor=newValEntry->IsItemDelimitor();
1368 if( !set->AddEntry( newValEntry ) )
1370 // If here expect big troubles
1371 delete newValEntry; //otherwise mem leak
1378 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1385 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1387 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1388 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1389 "nor BinEntry. Probably unknown VR.");
1392 //////////////////// BinEntry or UNKOWN VR:
1393 /* BinEntry* newBinEntry =
1394 new BinEntry( newDocEntry->GetDictEntry() ); //LEAK
1395 newBinEntry->Copy( newDocEntry );*/
1396 BinEntry* newBinEntry = new BinEntry( newDocEntry ); //LEAK
1398 // When "this" is a Document the Key is simply of the
1399 // form ( group, elem )...
1400 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1403 newBinEntry->SetKey( newBinEntry->GetKey() );
1405 // but when "this" is a SQItem, we are inserting this new
1406 // valEntry in a sequence item, and the kay has the
1407 // generalized form (refer to \ref BaseTagKey):
1408 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1410 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1411 + newBinEntry->GetKey() );
1414 LoadDocEntry( newBinEntry );
1415 if( !set->AddEntry( newBinEntry ) )
1417 //Expect big troubles if here
1422 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1423 && ( newDocEntry->GetElement() == 0x0010 ) )
1425 TransferSyntaxType ts = GetTransferSyntax();
1426 if ( ts == RLELossless )
1428 long PositionOnEntry = Fp->tellg();
1429 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1431 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1433 else if ( IsJPEG() )
1435 long PositionOnEntry = Fp->tellg();
1436 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1437 ComputeJPEGFragmentInfo();
1438 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1442 // Just to make sure we are at the beginning of next entry.
1443 SkipToNextDocEntry(newDocEntry);
1448 unsigned long l = newDocEntry->GetReadLength();
1449 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1451 if ( l == 0xffffffff )
1460 // no other way to create it ...
1461 SeqEntry* newSeqEntry =
1462 new SeqEntry( newDocEntry->GetDictEntry() );
1463 newSeqEntry->Copy( newDocEntry );
1464 newSeqEntry->SetDelimitorMode( delim_mode );
1466 // At the top of the hierarchy, stands a Document. When "set"
1467 // is a Document, then we are building the first depth level.
1468 // Hence the SeqEntry we are building simply has a depth
1470 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1473 newSeqEntry->SetDepthLevel( 1 );
1474 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1476 // But when "set" is allready a SQItem, we are building a nested
1477 // sequence, and hence the depth level of the new SeqEntry
1478 // we are building, is one level deeper:
1479 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1481 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1482 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1483 + newSeqEntry->GetKey() );
1487 { // Don't try to parse zero-length sequences
1488 ParseSQ( newSeqEntry,
1489 newDocEntry->GetOffset(),
1492 set->AddEntry( newSeqEntry );
1493 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1503 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1504 * @return parsed length for this level
1506 void Document::ParseSQ( SeqEntry* seqEntry,
1507 long offset, long l_max, bool delim_mode)
1509 int SQItemNumber = 0;
1514 DocEntry* newDocEntry = ReadNextDocEntry();
1517 // FIXME Should warn user
1522 if ( newDocEntry->IsSequenceDelimitor() )
1524 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1528 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1533 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1534 std::ostringstream newBase;
1535 newBase << seqEntry->GetKey()
1539 itemSQ->SetBaseTagKey( newBase.str() );
1540 unsigned int l = newDocEntry->GetReadLength();
1542 if ( l == 0xffffffff )
1551 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1553 seqEntry->AddEntry( itemSQ, SQItemNumber );
1555 if ( !delim_mode && ( Fp->tellg() - offset ) >= l_max )
1563 * \brief Loads the element content if its length doesn't exceed
1564 * the value specified with Document::SetMaxSizeLoadEntry()
1565 * @param entry Header Entry (Dicom Element) to be dealt with
1567 void Document::LoadDocEntry(DocEntry* entry)
1569 uint16_t group = entry->GetGroup();
1570 std::string vr = entry->GetVR();
1571 uint32_t length = entry->GetLength();
1573 Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1575 // A SeQuence "contains" a set of Elements.
1576 // (fffe e000) tells us an Element is beginning
1577 // (fffe e00d) tells us an Element just ended
1578 // (fffe e0dd) tells us the current SeQuence just ended
1579 if( group == 0xfffe )
1581 // NO more value field for SQ !
1585 // When the length is zero things are easy:
1588 ((ValEntry *)entry)->SetValue("");
1592 // The elements whose length is bigger than the specified upper bound
1593 // are not loaded. Instead we leave a short notice of the offset of
1594 // the element content and it's length.
1596 std::ostringstream s;
1597 if (length > MaxSizeLoadEntry)
1599 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1601 //s << "gdcm::NotLoaded (BinEntry)";
1602 s << GDCM_NOTLOADED;
1603 s << " Address:" << (long)entry->GetOffset();
1604 s << " Length:" << entry->GetLength();
1605 s << " x(" << std::hex << entry->GetLength() << ")";
1606 binEntryPtr->SetValue(s.str());
1608 // Be carefull : a BinEntry IS_A ValEntry ...
1609 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1611 // s << "gdcm::NotLoaded. (ValEntry)";
1612 s << GDCM_NOTLOADED;
1613 s << " Address:" << (long)entry->GetOffset();
1614 s << " Length:" << entry->GetLength();
1615 s << " x(" << std::hex << entry->GetLength() << ")";
1616 valEntryPtr->SetValue(s.str());
1621 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1622 << "nor a ValEntry ?! Should never print that !" << std::endl;
1625 // to be sure we are at the end of the value ...
1626 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1627 std::ios_base::beg);
1631 // When we find a BinEntry not very much can be done :
1632 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1634 s << GDCM_BINLOADED;
1635 binEntryPtr->SetValue(s.str());
1636 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1640 /// \todo Any compacter code suggested (?)
1641 if ( IsDocEntryAnInteger(entry) )
1645 // When short integer(s) are expected, read and convert the following
1646 // n *two characters properly i.e. consider them as short integers as
1647 // opposed to strings.
1648 // Elements with Value Multiplicity > 1
1649 // contain a set of integers (not a single one)
1650 if (vr == "US" || vr == "SS")
1653 NewInt = ReadInt16();
1657 for (int i=1; i < nbInt; i++)
1660 NewInt = ReadInt16();
1665 // See above comment on multiple integers (mutatis mutandis).
1666 else if (vr == "UL" || vr == "SL")
1669 NewInt = ReadInt32();
1673 for (int i=1; i < nbInt; i++)
1676 NewInt = ReadInt32();
1681 #ifdef GDCM_NO_ANSI_STRING_STREAM
1682 s << std::ends; // to avoid oddities on Solaris
1683 #endif //GDCM_NO_ANSI_STRING_STREAM
1685 ((ValEntry *)entry)->SetValue(s.str());
1689 // FIXME: We need an additional byte for storing \0 that is not on disk
1690 char *str = new char[length+1];
1691 Fp->read(str, (size_t)length);
1692 str[length] = '\0'; //this is only useful when length is odd
1693 // Special DicomString call to properly handle \0 and even length
1694 std::string newValue;
1697 newValue = Util::DicomString(str, length+1);
1698 //dbg.Verbose(0, "Warning: bad length: ", length );
1699 dbg.Verbose(0, "For string :", newValue.c_str());
1700 // Since we change the length of string update it length
1701 entry->SetReadLength(length+1);
1705 newValue = Util::DicomString(str, length);
1709 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1711 if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1713 dbg.Verbose(1, "Document::LoadDocEntry",
1714 "unread element value");
1715 valEntry->SetValue(GDCM_UNREAD);
1721 // Because of correspondance with the VR dic
1722 valEntry->SetValue(newValue);
1726 valEntry->SetValue(newValue);
1731 dbg.Error(true, "Document::LoadDocEntry"
1732 "Should have a ValEntry, here !");
1738 * \brief Find the value Length of the passed Header Entry
1739 * @param entry Header Entry whose length of the value shall be loaded.
1741 void Document::FindDocEntryLength( DocEntry *entry )
1742 throw ( FormatError )
1744 uint16_t element = entry->GetElement();
1745 std::string vr = entry->GetVR();
1748 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1750 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1752 // The following reserved two bytes (see PS 3.5-2003, section
1753 // "7.1.2 Data element structure with explicit vr", p 27) must be
1754 // skipped before proceeding on reading the length on 4 bytes.
1755 Fp->seekg( 2L, std::ios_base::cur);
1756 uint32_t length32 = ReadInt32();
1758 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1763 /// \todo rename that to FindDocEntryLengthOBOrOW since
1764 /// the above test is on both OB and OW...
1765 lengthOB = FindDocEntryLengthOB();
1767 catch ( FormatUnexpected )
1769 // Computing the length failed (this happens with broken
1770 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1771 // chance to get the pixels by deciding the element goes
1772 // until the end of the file. Hence we artificially fix the
1773 // the length and proceed.
1774 long currentPosition = Fp->tellg();
1775 Fp->seekg(0L,std::ios_base::end);
1776 long lengthUntilEOF = Fp->tellg() - currentPosition;
1777 Fp->seekg(currentPosition, std::ios_base::beg);
1778 entry->SetLength(lengthUntilEOF);
1781 entry->SetLength(lengthOB);
1784 FixDocEntryFoundLength(entry, length32);
1788 // Length is encoded on 2 bytes.
1789 length16 = ReadInt16();
1791 // We can tell the current file is encoded in big endian (like
1792 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1793 // and it's value is the one of the encoding of a big endian file.
1794 // In order to deal with such big endian encoded files, we have
1795 // (at least) two strategies:
1796 // * when we load the "Transfer Syntax" tag with value of big endian
1797 // encoding, we raise the proper flags. Then we wait for the end
1798 // of the META group (0x0002) among which is "Transfer Syntax",
1799 // before switching the swap code to big endian. We have to postpone
1800 // the switching of the swap code since the META group is fully encoded
1801 // in little endian, and big endian coding only starts at the next
1802 // group. The corresponding code can be hard to analyse and adds
1803 // many additional unnecessary tests for regular tags.
1804 // * the second strategy consists in waiting for trouble, that shall
1805 // appear when we find the first group with big endian encoding. This
1806 // is easy to detect since the length of a "Group Length" tag (the
1807 // ones with zero as element number) has to be of 4 (0x0004). When we
1808 // encounter 1024 (0x0400) chances are the encoding changed and we
1809 // found a group with big endian encoding.
1810 // We shall use this second strategy. In order to make sure that we
1811 // can interpret the presence of an apparently big endian encoded
1812 // length of a "Group Length" without committing a big mistake, we
1813 // add an additional check: we look in the already parsed elements
1814 // for the presence of a "Transfer Syntax" whose value has to be "big
1815 // endian encoding". When this is the case, chances are we have got our
1816 // hands on a big endian encoded file: we switch the swap code to
1817 // big endian and proceed...
1818 if ( element == 0x0000 && length16 == 0x0400 )
1820 TransferSyntaxType ts = GetTransferSyntax();
1821 if ( ts != ExplicitVRBigEndian )
1823 throw FormatError( "Document::FindDocEntryLength()",
1824 " not explicit VR." );
1828 SwitchSwapToBigEndian();
1829 // Restore the unproperly loaded values i.e. the group, the element
1830 // and the dictionary entry depending on them.
1831 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1832 uint16_t correctElem = SwapShort( entry->GetElement() );
1833 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1837 // This correct tag is not in the dictionary. Create a new one.
1838 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1840 // FIXME this can create a memory leaks on the old entry that be
1841 // left unreferenced.
1842 entry->SetDictEntry( newTag );
1845 // Heuristic: well, some files are really ill-formed.
1846 if ( length16 == 0xffff)
1848 // 0xffff means that we deal with 'Unknown Length' Sequence
1851 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1856 // Either implicit VR or a non DICOM conformal (see note below) explicit
1857 // VR that ommited the VR of (at least) this element. Farts happen.
1858 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1859 // on Data elements "Implicit and Explicit VR Data Elements shall
1860 // not coexist in a Data Set and Data Sets nested within it".]
1861 // Length is on 4 bytes.
1863 FixDocEntryFoundLength( entry, ReadInt32() );
1869 * \brief Find the Value Representation of the current Dicom Element.
1872 void Document::FindDocEntryVR( DocEntry *entry )
1874 if ( Filetype != ExplicitVR )
1881 long positionOnEntry = Fp->tellg();
1882 // Warning: we believe this is explicit VR (Value Representation) because
1883 // we used a heuristic that found "UL" in the first tag. Alas this
1884 // doesn't guarantee that all the tags will be in explicit VR. In some
1885 // cases (see e-film filtered files) one finds implicit VR tags mixed
1886 // within an explicit VR file. Hence we make sure the present tag
1887 // is in explicit VR and try to fix things if it happens not to be
1890 Fp->read (vr, (size_t)2);
1893 if( !CheckDocEntryVR(entry, vr) )
1895 Fp->seekg(positionOnEntry, std::ios_base::beg);
1896 // When this element is known in the dictionary we shall use, e.g. for
1897 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1898 // dictionary entry. Still we have to flag the element as implicit since
1899 // we know now our assumption on expliciteness is not furfilled.
1901 if ( entry->IsVRUnknown() )
1903 entry->SetVR("Implicit");
1905 entry->SetImplicitVR();
1910 * \brief Check the correspondance between the VR of the header entry
1911 * and the taken VR. If they are different, the header entry is
1912 * updated with the new VR.
1913 * @param entry Header Entry to check
1914 * @param vr Dicom Value Representation
1915 * @return false if the VR is incorrect of if the VR isn't referenced
1916 * otherwise, it returns true
1918 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1921 bool realExplicit = true;
1923 // Assume we are reading a falsely explicit VR file i.e. we reached
1924 // a tag where we expect reading a VR but are in fact we read the
1925 // first to bytes of the length. Then we will interogate (through find)
1926 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1927 // both GCC and VC++ implementations of the STL map. Hence when the
1928 // expected VR read happens to be non-ascii characters we consider
1929 // we hit falsely explicit VR tag.
1931 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1933 realExplicit = false;
1936 // CLEANME searching the dicom_vr at each occurence is expensive.
1937 // PostPone this test in an optional integrity check at the end
1938 // of parsing or only in debug mode.
1939 if ( realExplicit && !Global::GetVR()->Count(vr) )
1941 realExplicit = false;
1944 if ( !realExplicit )
1946 // We thought this was explicit VR, but we end up with an
1947 // implicit VR tag. Let's backtrack.
1948 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
1949 entry->GetGroup(), entry->GetElement());
1950 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1952 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1954 // Group length is UL !
1955 DictEntry* newEntry = NewVirtualDictEntry(
1956 entry->GetGroup(), entry->GetElement(),
1957 "UL", "FIXME", "Group Length");
1958 entry->SetDictEntry( newEntry );
1963 if ( entry->IsVRUnknown() )
1965 // When not a dictionary entry, we can safely overwrite the VR.
1966 if( entry->GetElement() == 0x0000 )
1968 // Group length is UL !
1976 else if ( entry->GetVR() != vr )
1978 // The VR present in the file and the dictionary disagree. We assume
1979 // the file writer knew best and use the VR of the file. Since it would
1980 // be unwise to overwrite the VR of a dictionary (since it would
1981 // compromise it's next user), we need to clone the actual DictEntry
1982 // and change the VR for the read one.
1983 DictEntry* newEntry = NewVirtualDictEntry(
1984 entry->GetGroup(), entry->GetElement(),
1985 vr, "FIXME", entry->GetName());
1986 entry->SetDictEntry(newEntry);
1993 * \brief Get the transformed value of the header entry. The VR value
1994 * is used to define the transformation to operate on the value
1995 * \warning NOT end user intended method !
1996 * @param entry entry to tranform
1997 * @return Transformed entry value
1999 std::string Document::GetDocEntryValue(DocEntry *entry)
2001 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2003 std::string val = ((ValEntry *)entry)->GetValue();
2004 std::string vr = entry->GetVR();
2005 uint32_t length = entry->GetLength();
2006 std::ostringstream s;
2009 // When short integer(s) are expected, read and convert the following
2010 // n * 2 bytes properly i.e. as a multivaluated strings
2011 // (each single value is separated fromthe next one by '\'
2012 // as usual for standard multivaluated filels
2013 // Elements with Value Multiplicity > 1
2014 // contain a set of short integers (not a single one)
2016 if( vr == "US" || vr == "SS" )
2021 for (int i=0; i < nbInt; i++)
2027 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2028 newInt16 = SwapShort( newInt16 );
2033 // When integer(s) are expected, read and convert the following
2034 // n * 4 bytes properly i.e. as a multivaluated strings
2035 // (each single value is separated fromthe next one by '\'
2036 // as usual for standard multivaluated filels
2037 // Elements with Value Multiplicity > 1
2038 // contain a set of integers (not a single one)
2039 else if( vr == "UL" || vr == "SL" )
2044 for (int i=0; i < nbInt; i++)
2050 newInt32 = ( val[4*i+0] & 0xFF )
2051 + (( val[4*i+1] & 0xFF ) << 8 )
2052 + (( val[4*i+2] & 0xFF ) << 16 )
2053 + (( val[4*i+3] & 0xFF ) << 24 );
2054 newInt32 = SwapLong( newInt32 );
2058 #ifdef GDCM_NO_ANSI_STRING_STREAM
2059 s << std::ends; // to avoid oddities on Solaris
2060 #endif //GDCM_NO_ANSI_STRING_STREAM
2064 return ((ValEntry *)entry)->GetValue();
2068 * \brief Get the reverse transformed value of the header entry. The VR
2069 * value is used to define the reverse transformation to operate on
2071 * \warning NOT end user intended method !
2072 * @param entry Entry to reverse transform
2073 * @return Reverse transformed entry value
2075 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2077 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2079 std::string vr = entry->GetVR();
2080 std::vector<std::string> tokens;
2081 std::ostringstream s;
2083 if ( vr == "US" || vr == "SS" )
2087 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2088 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2089 for (unsigned int i=0; i<tokens.size(); i++)
2091 newInt16 = atoi(tokens[i].c_str());
2092 s << ( newInt16 & 0xFF )
2093 << (( newInt16 >> 8 ) & 0xFF );
2097 if ( vr == "UL" || vr == "SL")
2101 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2102 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2103 for (unsigned int i=0; i<tokens.size();i++)
2105 newInt32 = atoi(tokens[i].c_str());
2106 s << (char)( newInt32 & 0xFF )
2107 << (char)(( newInt32 >> 8 ) & 0xFF )
2108 << (char)(( newInt32 >> 16 ) & 0xFF )
2109 << (char)(( newInt32 >> 24 ) & 0xFF );
2114 #ifdef GDCM_NO_ANSI_STRING_STREAM
2115 s << std::ends; // to avoid oddities on Solaris
2116 #endif //GDCM_NO_ANSI_STRING_STREAM
2120 return ((ValEntry *)entry)->GetValue();
2124 * \brief Skip a given Header Entry
2125 * \warning NOT end user intended method !
2126 * @param entry entry to skip
2128 void Document::SkipDocEntry(DocEntry *entry)
2130 SkipBytes(entry->GetLength());
2134 * \brief Skips to the begining of the next Header Entry
2135 * \warning NOT end user intended method !
2136 * @param entry entry to skip
2138 void Document::SkipToNextDocEntry(DocEntry *entry)
2140 Fp->seekg((long)(entry->GetOffset()), std::ios_base::beg);
2141 Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2145 * \brief When the length of an element value is obviously wrong (because
2146 * the parser went Jabberwocky) one can hope improving things by
2147 * applying some heuristics.
2148 * @param entry entry to check
2149 * @param foundLength fist assumption about length
2151 void Document::FixDocEntryFoundLength(DocEntry *entry,
2152 uint32_t foundLength)
2154 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2155 if ( foundLength == 0xffffffff)
2160 uint16_t gr = entry->GetGroup();
2161 uint16_t el = entry->GetElement();
2163 if ( foundLength % 2)
2165 std::ostringstream s;
2166 s << "Warning : Tag with uneven length "
2168 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2169 dbg.Verbose(0, s.str().c_str());
2172 //////// Fix for some naughty General Electric images.
2173 // Allthough not recent many such GE corrupted images are still present
2174 // on Creatis hard disks. Hence this fix shall remain when such images
2175 // are no longer in user (we are talking a few years, here)...
2176 // Note: XMedCom probably uses such a trick since it is able to read
2177 // those pesky GE images ...
2178 if ( foundLength == 13)
2180 // Only happens for this length !
2181 if ( entry->GetGroup() != 0x0008
2182 || ( entry->GetElement() != 0x0070
2183 && entry->GetElement() != 0x0080 ) )
2186 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2190 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2191 // Occurence of such images is quite low (unless one leaves close to a
2192 // 'Leonardo' source. Hence, one might consider commenting out the
2193 // following fix on efficiency reasons.
2194 else if ( entry->GetGroup() == 0x0009
2195 && ( entry->GetElement() == 0x1113
2196 || entry->GetElement() == 0x1114 ) )
2199 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2202 else if ( entry->GetVR() == "SQ" )
2204 foundLength = 0; // ReadLength is unchanged
2207 //////// We encountered a 'delimiter' element i.e. a tag of the form
2208 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2209 // taken into account.
2210 else if( entry->GetGroup() == 0xfffe )
2212 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2213 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2214 // causes extra troubles...
2215 if( entry->GetElement() != 0x0000 )
2221 entry->SetUsableLength(foundLength);
2225 * \brief Apply some heuristics to predict whether the considered
2226 * element value contains/represents an integer or not.
2227 * @param entry The element value on which to apply the predicate.
2228 * @return The result of the heuristical predicate.
2230 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2232 uint16_t element = entry->GetElement();
2233 uint16_t group = entry->GetGroup();
2234 const std::string & vr = entry->GetVR();
2235 uint32_t length = entry->GetLength();
2237 // When we have some semantics on the element we just read, and if we
2238 // a priori know we are dealing with an integer, then we shall be
2239 // able to swap it's element value properly.
2240 if ( element == 0 ) // This is the group length of the group
2248 // Allthough this should never happen, still some images have a
2249 // corrupted group length [e.g. have a glance at offset x(8336) of
2250 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2251 // Since for dicom compliant and well behaved headers, the present
2252 // test is useless (and might even look a bit paranoid), when we
2253 // encounter such an ill-formed image, we simply display a warning
2254 // message and proceed on parsing (while crossing fingers).
2255 std::ostringstream s;
2256 long filePosition = Fp->tellg();
2257 s << "Erroneous Group Length element length on : (" \
2258 << std::hex << group << " , " << element
2259 << ") -before- position x(" << filePosition << ")"
2260 << "lgt : " << length;
2261 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2265 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2274 * \brief Find the Length till the next sequence delimiter
2275 * \warning NOT end user intended method !
2279 uint32_t Document::FindDocEntryLengthOB()
2280 throw( FormatUnexpected )
2282 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2283 long positionOnEntry = Fp->tellg();
2284 bool foundSequenceDelimiter = false;
2285 uint32_t totalLength = 0;
2287 while ( !foundSequenceDelimiter )
2293 group = ReadInt16();
2296 catch ( FormatError )
2298 throw FormatError("Document::FindDocEntryLengthOB()",
2299 " group or element not present.");
2302 // We have to decount the group and element we just read
2305 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2307 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2308 "tag nor a Sequence delimiter tag.");
2309 Fp->seekg(positionOnEntry, std::ios_base::beg);
2310 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2311 "Neither an Item tag nor a Sequence "
2315 if ( elem == 0xe0dd )
2317 foundSequenceDelimiter = true;
2320 uint32_t itemLength = ReadInt32();
2321 // We add 4 bytes since we just read the ItemLength with ReadInt32
2322 totalLength += itemLength + 4;
2323 SkipBytes(itemLength);
2325 if ( foundSequenceDelimiter )
2330 Fp->seekg( positionOnEntry, std::ios_base::beg);
2335 * \brief Reads a supposed to be 16 Bits integer
2336 * (swaps it depending on processor endianity)
2337 * @return read value
2339 uint16_t Document::ReadInt16()
2340 throw( FormatError )
2343 Fp->read ((char*)&g, (size_t)2);
2346 throw FormatError( "Document::ReadInt16()", " file error." );
2350 throw FormatError( "Document::ReadInt16()", "EOF." );
2357 * \brief Reads a supposed to be 32 Bits integer
2358 * (swaps it depending on processor endianity)
2359 * @return read value
2361 uint32_t Document::ReadInt32()
2362 throw( FormatError )
2365 Fp->read ((char*)&g, (size_t)4);
2368 throw FormatError( "Document::ReadInt32()", " file error." );
2372 throw FormatError( "Document::ReadInt32()", "EOF." );
2379 * \brief skips bytes inside the source file
2380 * \warning NOT end user intended method !
2383 void Document::SkipBytes(uint32_t nBytes)
2385 //FIXME don't dump the returned value
2386 Fp->seekg((long)nBytes, std::ios_base::cur);
2390 * \brief Loads all the needed Dictionaries
2391 * \warning NOT end user intended method !
2393 void Document::Initialise()
2395 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2397 RLEInfo = new RLEFramesInfo;
2398 JPEGInfo = new JPEGFragmentsInfo;
2402 * \brief Discover what the swap code is (among little endian, big endian,
2403 * bad little endian, bad big endian).
2405 * @return false when we are absolutely sure
2406 * it's neither ACR-NEMA nor DICOM
2407 * true when we hope ours assuptions are OK
2409 bool Document::CheckSwap()
2411 // The only guaranted way of finding the swap code is to find a
2412 // group tag since we know it's length has to be of four bytes i.e.
2413 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2414 // occurs when we can't find such group...
2416 uint32_t x = 4; // x : for ntohs
2417 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2421 char deb[256]; //HEADER_LENGTH_TO_READ];
2423 // First, compare HostByteOrder and NetworkByteOrder in order to
2424 // determine if we shall need to swap bytes (i.e. the Endian type).
2425 if ( x == ntohs(x) )
2434 // The easiest case is the one of a DICOM header, since it possesses a
2435 // file preamble where it suffice to look for the string "DICM".
2436 Fp->read(deb, HEADER_LENGTH_TO_READ);
2438 char *entCur = deb + 128;
2439 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2441 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2443 // Next, determine the value representation (VR). Let's skip to the
2444 // first element (0002, 0000) and check there if we find "UL"
2445 // - or "OB" if the 1st one is (0002,0001) -,
2446 // in which case we (almost) know it is explicit VR.
2447 // WARNING: if it happens to be implicit VR then what we will read
2448 // is the length of the group. If this ascii representation of this
2449 // length happens to be "UL" then we shall believe it is explicit VR.
2450 // FIXME: in order to fix the above warning, we could read the next
2451 // element value (or a couple of elements values) in order to make
2452 // sure we are not commiting a big mistake.
2453 // We need to skip :
2454 // * the 128 bytes of File Preamble (often padded with zeroes),
2455 // * the 4 bytes of "DICM" string,
2456 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2457 // i.e. a total of 136 bytes.
2461 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2462 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2463 // *Implicit* VR. -and it is !-
2465 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2466 memcmp(entCur, "OB", (size_t)2) == 0 ||
2467 memcmp(entCur, "UI", (size_t)2) == 0 ||
2468 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2469 // when Write DCM *adds*
2471 // Use Document::dicom_vr to test all the possibilities
2472 // instead of just checking for UL, OB and UI !? group 0000
2474 Filetype = ExplicitVR;
2475 dbg.Verbose(1, "Document::CheckSwap:",
2476 "explicit Value Representation");
2480 Filetype = ImplicitVR;
2481 dbg.Verbose(1, "Document::CheckSwap:",
2482 "not an explicit Value Representation");
2488 dbg.Verbose(1, "Document::CheckSwap:",
2489 "HostByteOrder != NetworkByteOrder");
2494 dbg.Verbose(1, "Document::CheckSwap:",
2495 "HostByteOrder = NetworkByteOrder");
2498 // Position the file position indicator at first tag (i.e.
2499 // after the file preamble and the "DICM" string).
2500 Fp->seekg(0, std::ios_base::beg);
2501 Fp->seekg ( 132L, std::ios_base::beg);
2505 // Alas, this is not a DicomV3 file and whatever happens there is no file
2506 // preamble. We can reset the file position indicator to where the data
2507 // is (i.e. the beginning of the file).
2508 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2509 Fp->seekg(0, std::ios_base::beg);
2511 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2512 // By clean we mean that the length of the first tag is written down.
2513 // If this is the case and since the length of the first group HAS to be
2514 // four (bytes), then determining the proper swap code is straightforward.
2517 // We assume the array of char we are considering contains the binary
2518 // representation of a 32 bits integer. Hence the following dirty
2520 s32 = *((uint32_t *)(entCur));
2541 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2542 // It is time for despaired wild guesses.
2543 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2544 // i.e. the 'group length' element is not present :
2546 // check the supposed to be 'group number'
2547 // 0x0002 or 0x0004 or 0x0008
2548 // to determine ' SwapCode' value .
2549 // Only 0 or 4321 will be possible
2550 // (no oportunity to check for the formerly well known
2551 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2552 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2553 // the file IS NOT ACR-NEMA nor DICOM V3
2554 // Find a trick to tell it the caller...
2556 s16 = *((uint16_t *)(deb));
2573 dbg.Verbose(0, "Document::CheckSwap:",
2574 "ACR/NEMA unfound swap info (Really hopeless !)");
2578 // Then the only info we have is the net2host one.
2588 * \brief Restore the unproperly loaded values i.e. the group, the element
2589 * and the dictionary entry depending on them.
2591 void Document::SwitchSwapToBigEndian()
2593 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2594 "Switching to BigEndian mode.");
2595 if ( SwapCode == 0 )
2599 else if ( SwapCode == 4321 )
2603 else if ( SwapCode == 3412 )
2607 else if ( SwapCode == 2143 )
2614 * \brief during parsing, Header Elements too long are not loaded in memory
2617 void Document::SetMaxSizeLoadEntry(long newSize)
2623 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2625 MaxSizeLoadEntry = 0xffffffff;
2628 MaxSizeLoadEntry = newSize;
2633 * \brief Header Elements too long will not be printed
2634 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2637 void Document::SetMaxSizePrintEntry(long newSize)
2639 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2644 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2646 MaxSizePrintEntry = 0xffffffff;
2649 MaxSizePrintEntry = newSize;
2655 * \brief Handle broken private tag from Philips NTSCAN
2656 * where the endianess is being switch to BigEndian for no
2660 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2662 // Endian reversion. Some files contain groups of tags with reversed endianess.
2663 static int reversedEndian = 0;
2664 // try to fix endian switching in the middle of headers
2665 if ((group == 0xfeff) && (elem == 0x00e0))
2667 // start endian swap mark for group found
2669 SwitchSwapToBigEndian();
2674 else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian)
2676 // end of reversed endian group
2678 SwitchSwapToBigEndian();
2684 * \brief Read the next tag but WITHOUT loading it's value
2685 * (read the 'Group Number', the 'Element Number',
2686 * gets the Dict Entry
2687 * gets the VR, gets the length, gets the offset value)
2688 * @return On succes the newly created DocEntry, NULL on failure.
2690 DocEntry* Document::ReadNextDocEntry()
2697 group = ReadInt16();
2700 catch ( FormatError e )
2702 // We reached the EOF (or an error occured) therefore
2703 // header parsing has to be considered as finished.
2708 HandleBrokenEndian(group, elem);
2709 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2710 FindDocEntryVR(newEntry);
2714 FindDocEntryLength(newEntry);
2716 catch ( FormatError e )
2724 newEntry->SetOffset(Fp->tellg());
2731 * \brief Generate a free TagKey i.e. a TagKey that is not present
2732 * in the TagHt dictionary.
2733 * @param group The generated tag must belong to this group.
2734 * @return The element of tag with given group which is fee.
2736 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2738 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2740 TagKey key = DictEntry::TranslateToKey(group, elem);
2741 if (TagHT.count(key) == 0)
2750 * \brief Assuming the internal file pointer \ref Document::Fp
2751 * is placed at the beginning of a tag check whether this
2752 * tag is (TestGroup, TestElement).
2753 * \warning On success the internal file pointer \ref Document::Fp
2754 * is modified to point after the tag.
2755 * On failure (i.e. when the tag wasn't the expected tag
2756 * (TestGroup, TestElement) the internal file pointer
2757 * \ref Document::Fp is restored to it's original position.
2758 * @param testGroup The expected group of the tag.
2759 * @param testElement The expected Element of the tag.
2760 * @return True on success, false otherwise.
2762 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2764 long positionOnEntry = Fp->tellg();
2765 long currentPosition = Fp->tellg(); // On debugging purposes
2767 //// Read the Item Tag group and element, and make
2768 // sure they are what we expected:
2769 uint16_t itemTagGroup;
2770 uint16_t itemTagElement;
2773 itemTagGroup = ReadInt16();
2774 itemTagElement = ReadInt16();
2776 catch ( FormatError e )
2778 //std::cerr << e << std::endl;
2781 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2783 std::ostringstream s;
2784 s << " We should have found tag (";
2785 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2786 s << " but instead we encountered tag (";
2787 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2789 s << " at address: " << (unsigned)currentPosition << std::endl;
2790 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2791 dbg.Verbose(0, s.str().c_str());
2792 Fp->seekg(positionOnEntry, std::ios_base::beg);
2800 * \brief Assuming the internal file pointer \ref Document::Fp
2801 * is placed at the beginning of a tag (TestGroup, TestElement),
2802 * read the length associated to the Tag.
2803 * \warning On success the internal file pointer \ref Document::Fp
2804 * is modified to point after the tag and it's length.
2805 * On failure (i.e. when the tag wasn't the expected tag
2806 * (TestGroup, TestElement) the internal file pointer
2807 * \ref Document::Fp is restored to it's original position.
2808 * @param testGroup The expected group of the tag.
2809 * @param testElement The expected Element of the tag.
2810 * @return On success returns the length associated to the tag. On failure
2813 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2815 long positionOnEntry = Fp->tellg();
2816 (void)positionOnEntry;
2818 if ( !ReadTag(testGroup, testElement) )
2823 //// Then read the associated Item Length
2824 long currentPosition = Fp->tellg();
2825 uint32_t itemLength = ReadInt32();
2827 std::ostringstream s;
2828 s << "Basic Item Length is: "
2829 << itemLength << std::endl;
2830 s << " at address: " << (unsigned)currentPosition << std::endl;
2831 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2837 * \brief When parsing the Pixel Data of an encapsulated file, read
2838 * the basic offset table (when present, and BTW dump it).
2840 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2842 //// Read the Basic Offset Table Item Tag length...
2843 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2845 // When present, read the basic offset table itself.
2846 // Notes: - since the presence of this basic offset table is optional
2847 // we can't rely on it for the implementation, and we will simply
2848 // trash it's content (when present).
2849 // - still, when present, we could add some further checks on the
2850 // lengths, but we won't bother with such fuses for the time being.
2851 if ( itemLength != 0 )
2853 char* basicOffsetTableItemValue = new char[itemLength + 1];
2854 Fp->read(basicOffsetTableItemValue, itemLength);
2857 for (unsigned int i=0; i < itemLength; i += 4 )
2859 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2861 std::ostringstream s;
2862 s << " Read one length: ";
2863 s << std::hex << individualLength << std::endl;
2865 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2870 delete[] basicOffsetTableItemValue;
2875 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2876 * Compute the RLE extra information and store it in \ref RLEInfo
2877 * for later pixel retrieval usage.
2879 void Document::ComputeRLEInfo()
2881 TransferSyntaxType ts = GetTransferSyntax();
2882 if ( ts != RLELossless )
2887 // Encoded pixel data: for the time being we are only concerned with
2888 // Jpeg or RLE Pixel data encodings.
2889 // As stated in PS 3.5-2003, section 8.2 p44:
2890 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2891 // value representation OB is used".
2892 // Hence we expect an OB value representation. Concerning OB VR,
2893 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2894 // "For the Value Representations OB and OW, the encoding shall meet the
2895 // following specifications depending on the Data element tag:"
2897 // - the first item in the sequence of items before the encoded pixel
2898 // data stream shall be basic offset table item. The basic offset table
2899 // item value, however, is not required to be present"
2901 ReadAndSkipEncapsulatedBasicOffsetTable();
2903 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2904 // Loop on the individual frame[s] and store the information
2905 // on the RLE fragments in a RLEFramesInfo.
2906 // Note: - when only a single frame is present, this is a
2908 // - when more than one frame are present, then we are in
2909 // the case of a multi-frame image.
2911 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2913 // Parse the RLE Header and store the corresponding RLE Segment
2914 // Offset Table information on fragments of this current Frame.
2915 // Note that the fragment pixels themselves are not loaded
2916 // (but just skipped).
2917 long frameOffset = Fp->tellg();
2919 uint32_t nbRleSegments = ReadInt32();
2920 if ( nbRleSegments > 16 )
2922 // There should be at most 15 segments (refer to RLEFrame class)
2923 dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2926 uint32_t rleSegmentOffsetTable[15];
2927 for( int k = 1; k <= 15; k++ )
2929 rleSegmentOffsetTable[k] = ReadInt32();
2932 // Deduce from both the RLE Header and the frameLength the
2933 // fragment length, and again store this info in a
2935 long rleSegmentLength[15];
2936 // skipping (not reading) RLE Segments
2937 if ( nbRleSegments > 1)
2939 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2941 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2942 - rleSegmentOffsetTable[k];
2943 SkipBytes(rleSegmentLength[k]);
2947 rleSegmentLength[nbRleSegments] = frameLength
2948 - rleSegmentOffsetTable[nbRleSegments];
2949 SkipBytes(rleSegmentLength[nbRleSegments]);
2951 // Store the collected info
2952 RLEFrame* newFrameInfo = new RLEFrame;
2953 newFrameInfo->NumberFragments = nbRleSegments;
2954 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2956 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2957 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2959 RLEInfo->Frames.push_back( newFrameInfo );
2962 // Make sure that at the end of the item we encounter a 'Sequence
2964 if ( !ReadTag(0xfffe, 0xe0dd) )
2966 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2967 dbg.Verbose(0, " item at end of RLE item sequence");
2972 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2973 * Compute the jpeg extra information (fragment[s] offset[s] and
2974 * length) and store it[them] in \ref JPEGInfo for later pixel
2977 void Document::ComputeJPEGFragmentInfo()
2979 // If you need to, look for comments of ComputeRLEInfo().
2985 ReadAndSkipEncapsulatedBasicOffsetTable();
2987 // Loop on the fragments[s] and store the parsed information in a
2989 long fragmentLength;
2990 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2992 long fragmentOffset = Fp->tellg();
2994 // Store the collected info
2995 JPEGFragment* newFragment = new JPEGFragment;
2996 newFragment->Offset = fragmentOffset;
2997 newFragment->Length = fragmentLength;
2998 JPEGInfo->Fragments.push_back( newFragment );
3000 SkipBytes( fragmentLength );
3003 // Make sure that at the end of the item we encounter a 'Sequence
3005 if ( !ReadTag(0xfffe, 0xe0dd) )
3007 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3008 dbg.Verbose(0, " item at end of JPEG item sequence");
3013 * \brief Walk recursively the given \ref DocEntrySet, and feed
3014 * the given hash table (\ref TagDocEntryHT) with all the
3015 * \ref DocEntry (Dicom entries) encountered.
3016 * This method does the job for \ref BuildFlatHashTable.
3017 * @param builtHT Where to collect all the \ref DocEntry encountered
3018 * when recursively walking the given set.
3019 * @param set The structure to be traversed (recursively).
3021 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3024 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3026 TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3027 for( TagDocEntryHT::const_iterator i = currentHT.begin();
3028 i != currentHT.end();
3031 DocEntry* entry = i->second;
3032 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3034 const ListSQItem& items = seqEntry->GetSQItems();
3035 for( ListSQItem::const_iterator item = items.begin();
3036 item != items.end();
3039 BuildFlatHashTableRecurse( builtHT, *item );
3043 builtHT[entry->GetKey()] = entry;
3048 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3050 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3051 for (ListDocEntry::const_iterator i = currentList.begin();
3052 i != currentList.end();
3055 DocEntry* entry = *i;
3056 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3058 const ListSQItem& items = seqEntry->GetSQItems();
3059 for( ListSQItem::const_iterator item = items.begin();
3060 item != items.end();
3063 BuildFlatHashTableRecurse( builtHT, *item );
3067 builtHT[entry->GetKey()] = entry;
3074 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3077 * The structure used by a Document (through \ref ElementSet),
3078 * in order to old the parsed entries of a Dicom header, is a recursive
3079 * one. This is due to the fact that the sequences (when present)
3080 * can be nested. Additionaly, the sequence items (represented in
3081 * gdcm as \ref SQItem) add an extra complexity to the data
3082 * structure. Hence, a gdcm user whishing to visit all the entries of
3083 * a Dicom header will need to dig in the gdcm internals (which
3084 * implies exposing all the internal data structures to the API).
3085 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3086 * recursively builds a temporary hash table, which holds all the
3087 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3089 * \warning Of course there is NO integrity constrain between the
3090 * returned \ref TagDocEntryHT and the \ref ElementSet used
3091 * to build it. Hence if the underlying \ref ElementSet is
3092 * altered, then it is the caller responsability to invoke
3093 * \ref BuildFlatHashTable again...
3094 * @return The flat std::map<> we juste build.
3096 TagDocEntryHT* Document::BuildFlatHashTable()
3098 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3099 BuildFlatHashTableRecurse( *FlatHT, this );
3106 * \brief Compares two documents, according to \ref DicomDir rules
3107 * \warning Does NOT work with ACR-NEMA files
3108 * \todo Find a trick to solve the pb (use RET fields ?)
3110 * @return true if 'smaller'
3112 bool Document::operator<(Document &document)
3115 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3116 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3128 s1 = GetEntryByNumber(0x0010,0x0020);
3129 s2 = document.GetEntryByNumber(0x0010,0x0020);
3140 // Study Instance UID
3141 s1 = GetEntryByNumber(0x0020,0x000d);
3142 s2 = document.GetEntryByNumber(0x0020,0x000d);
3153 // Serie Instance UID
3154 s1 = GetEntryByNumber(0x0020,0x000e);
3155 s2 = document.GetEntryByNumber(0x0020,0x000e);
3170 } // end namespace gdcm
3172 //-----------------------------------------------------------------------------